-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathads-bit.js
More file actions
2041 lines (1741 loc) · 79.8 KB
/
Copy pathads-bit.js
File metadata and controls
2041 lines (1741 loc) · 79.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ADS-Bit - Retro Side View
class ADSBit {
constructor() {
this.canvas = document.getElementById('pixel-canvas');
this.ctx = this.canvas.getContext('2d');
// Set up responsive canvas sizing
this.setupResponsiveCanvas();
this.width = this.canvas.width;
this.height = this.canvas.height;
// Receiver location (will be fetched from config API)
this.receiverLat = 0;
this.receiverLon = 0;
this.locationName = 'Loading...';
this.receivers = [];
// Flight data
this.flights = new Map();
this.aircraftTypes = new Map(); // Cache ICAO -> aircraft type
// WebSocket
this.ws = null;
this.reconnectDelay = 1000;
// Colors (retro pixel art theme)
this.colors = {
skyTop: '#6ca4dc',
skyBottom: '#b4d4ec',
cloud: '#ffffff',
sun: '#fcd444',
ground: '#d4a868',
groundDark: '#b8884c',
dirt: '#a87840',
antenna: '#c0c0c0', // Silver/gray antenna
antennaDark: '#808080', // Dark gray for shading
antennaBase: '#4c4c4c', // Dark base
antennaRing: '#ffffff', // White rings
plane: '#fcfcfc',
planeTowards: '#54fc54',
planeAway: '#fc9c54',
text: '#fcfcfc',
textShadow: '#000000',
grid: 'rgba(255, 255, 255, 0.1)',
cactus: '#54a844',
cactusDark: '#3c7c30',
mountain: '#8c7c68',
mountainSnow: '#fcfcfc',
rain: 'rgba(120, 160, 200, 0.5)',
snow: '#fcfcfc'
};
// Weather state
this.weather = {
condition: 'clear', // clear, cloudy, rain, snow
description: 'Clear',
temp: 0,
sunrise: null,
sunset: null,
lastUpdate: 0
};
// View direction state (0=North, 90=East, 180=South, 270=West)
this.viewDirection = 0;
this.viewDirectionNames = { 0: 'N', 90: 'E', 180: 'S', 270: 'W' };
this.fieldOfView = 90; // 90 degree field of view
// Theme for background images (loaded from config)
this.theme = 'desert';
// Display preferences (loaded from config)
this.displayConfig = {
temperature_unit: 'F',
show_weather: true,
show_sidebar: true,
default_view_direction: 0
};
this.siteConfig = {
title: 'ADS-Bit',
subtitle: 'Retro Flight Tracker'
};
// Hover and selection tracking
this.mouseX = -1;
this.mouseY = -1;
this.hoveredAircraft = null;
this.selectedAircraftIcao = null; // Selected from sidebar click
this.visibleAircraftList = []; // For sidebar display
this.lastSidebarUpdate = 0; // Throttle sidebar updates
this.lastStatsUpdate = 0; // Throttle stats updates
this.cachedCountText = '';
this.cachedRangeText = '';
// Load aircraft sprite images
this.aircraftImages = {
smallProp: new Image(),
regionalJet: new Image(),
narrowBody: new Image(),
wideBody: new Image(),
heavy: new Image(),
helicopter: new Image(),
balloon: new Image(),
glider: new Image(),
uav: new Image()
};
// Track which images have loaded
this.aircraftImagesLoaded = {
smallProp: false,
regionalJet: false,
narrowBody: false,
wideBody: false,
heavy: false,
helicopter: false,
balloon: false,
glider: false,
uav: false
};
// Load all aircraft images
Object.keys(this.aircraftImages).forEach(type => {
this.aircraftImages[type].onload = () => {
this.aircraftImagesLoaded[type] = true;
console.log(`${type} sprite loaded`);
};
this.aircraftImages[type].onerror = () => {
console.warn(`Failed to load ${type} sprite`);
};
this.aircraftImages[type].src = `images/${type}.png?v=24`;
});
// Load environment images (directional backgrounds, base, sun, clouds)
// Directional background images (loaded after fetching config)
this.backgroundImages = {
0: new Image(), // North
90: new Image(), // East
180: new Image(), // South
270: new Image() // West
};
this.backgroundImagesLoaded = { 0: false, 90: false, 180: false, 270: false };
this.sunImage = new Image();
this.sunImage.onload = () => {
this.sunImageLoaded = true;
console.log('sun.png loaded');
};
this.sunImage.onerror = () => {
console.warn('Failed to load sun.png');
};
this.sunImage.src = 'images/sun.png?v=24';
this.happyCloudImage = new Image();
this.happyCloudImage.onload = () => {
this.happyCloudImageLoaded = true;
console.log('happycloud.png loaded');
};
this.happyCloudImage.onerror = () => {
console.warn('Failed to load happycloud.png');
};
this.happyCloudImage.src = 'images/happycloud.png?v=24';
this.rainCloudImage = new Image();
this.rainCloudImage.onload = () => {
this.rainCloudImageLoaded = true;
console.log('raincloud.png loaded');
};
this.rainCloudImage.onerror = () => {
console.warn('Failed to load raincloud.png');
};
this.rainCloudImage.src = 'images/raincloud.png?v=24';
this.moonSprite = new Image();
this.moonSprite.onload = () => {
this.moonSpriteLoaded = true;
console.log('moon_6_phases.png loaded');
};
this.moonSprite.onerror = () => {
console.warn('Failed to load moon_6_phases.png');
};
this.moonSprite.src = 'images/moon_6_phases.png?v=32';
// Track which environment images have loaded
this.sunImageLoaded = false;
this.happyCloudImageLoaded = false;
this.rainCloudImageLoaded = false;
this.moonSpriteLoaded = false;
// Pixel art sprites (kept as fallback and for other elements)
this.sprites = this.createSprites();
this.init();
}
createSprites() {
// Define pixel art sprites as 2D arrays (1 = mast, 2 = white ring, 3 = base)
return {
// ADS-B Antenna
antenna: [
[0,0,1,0,0], // Top tip
[0,1,2,1,0], // Top ring (white)
[0,0,1,0,0], // Mast
[0,0,1,0,0], // Mast
[0,1,2,1,0], // Ring
[0,0,1,0,0], // Mast
[0,0,1,0,0], // Mast
[1,1,2,1,1], // Large ring
[0,0,1,0,0], // Mast
[0,0,1,0,0], // Mast
[0,3,3,3,0], // Base
[3,3,3,3,3] // Base platform
],
// Cactus (saguaro style)
cactus: [
[0,1,0,0,0,1,0],
[0,1,0,0,0,1,0],
[1,1,1,1,1,1,1],
[0,0,1,1,1,0,0],
[0,0,1,1,1,0,0],
[0,0,1,1,1,0,0],
[0,0,1,1,1,0,0],
[0,0,1,1,1,0,0]
],
// Mountain (simple peak)
mountain: [
[0,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,1,1,1,0,0,0,0],
[0,0,0,1,1,2,1,1,0,0,0],
[0,0,1,1,1,2,1,1,1,0,0],
[0,1,1,1,1,1,1,1,1,1,0],
[1,1,1,1,1,1,1,1,1,1,1]
],
// Aircraft sprites (side view, facing right)
// Colors: 1=fuselage, 2=windows, 3=wings, 4=tail, 5=engine
// Small prop plane (Cessna, small GA)
smallProp: [
[0,0,0,0,4,4,0,0], // Tail
[0,0,0,4,4,1,4,0], // Tail fin
[0,0,0,1,1,1,1,0], // Rear fuselage
[0,0,1,2,1,1,1,1], // Fuselage with windows
[3,3,3,3,3,1,1,1], // Wings + nose
[0,0,1,2,1,1,5,1], // Fuselage with prop
[0,0,0,1,1,1,1,0], // Belly
[0,0,0,0,0,3,0,0] // Bottom wing
],
// Regional jet (CRJ, ERJ)
regionalJet: [
[0,0,0,0,0,4,4,0,0], // Tail
[0,0,0,0,4,4,1,4,0], // Tail fin
[0,0,0,0,1,1,1,1,0], // Rear fuselage
[0,0,0,1,2,2,1,1,1], // Fuselage with windows
[0,3,3,3,3,3,3,1,1], // Wings
[0,0,0,1,2,2,1,5,1], // Fuselage + engine
[0,0,0,0,1,1,1,5,1], // Belly + engine
[0,0,0,0,0,0,3,0,0] // Wing tip
],
// Narrow body (737, A320)
narrowBody: [
[0,0,0,0,0,4,4,4,0,0], // Tall tail
[0,0,0,0,4,4,1,1,4,0], // Tail fin
[0,0,0,0,1,1,1,1,1,0], // Rear fuselage
[0,0,0,1,2,2,2,1,1,1], // Windows
[0,0,3,3,3,3,3,3,1,1], // Wings
[0,0,0,1,2,2,2,1,5,5], // Lower fuselage + engines
[0,0,0,0,1,1,1,1,5,5], // Belly + engines
[0,0,0,0,0,0,3,3,0,0] // Wing tip
],
// Wide body (777, 787, A350)
wideBody: [
[0,0,0,0,0,0,4,4,4,0,0], // Tall tail
[0,0,0,0,0,4,4,1,1,4,0], // Tail fin
[0,0,0,0,0,1,1,1,1,1,0], // Rear fuselage
[0,0,0,0,1,2,2,2,1,1,1], // Upper windows
[0,0,0,3,3,3,3,3,3,1,1], // Large wings
[0,0,0,3,3,3,3,3,3,1,1], // Wing body
[0,0,0,0,1,2,2,2,5,5,5], // Lower fuselage + big engines
[0,0,0,0,0,1,1,1,5,5,5], // Belly + engines
[0,0,0,0,0,0,0,3,3,0,0] // Wing tip
],
// Heavy/jumbo (747, A380)
heavy: [
[0,0,0,0,0,0,4,4,4,4,0,0], // Very tall tail
[0,0,0,0,0,4,4,1,1,1,4,0], // Tail fin
[0,0,0,0,2,2,1,1,1,1,1,0], // Upper deck with windows!
[0,0,0,0,1,1,1,1,1,1,1,0], // Upper fuselage
[0,0,0,1,2,2,2,2,1,1,1,1], // Main deck windows
[0,0,3,3,3,3,3,3,3,1,1,1], // Massive wings
[0,0,3,3,3,3,3,3,3,1,1,1], // Wing body
[0,0,0,1,2,2,2,2,5,5,5,5], // Lower deck + huge engines
[0,0,0,0,1,1,1,1,5,5,5,5], // Belly + engines
[0,0,0,0,0,0,0,3,3,3,0,0] // Wing tips
]
};
}
processPlaneImage() {
// Create an off-screen canvas to process the image
const tempCanvas = document.createElement('canvas');
tempCanvas.width = this.planeImage.width;
tempCanvas.height = this.planeImage.height;
const tempCtx = tempCanvas.getContext('2d');
// Draw the original image
tempCtx.drawImage(this.planeImage, 0, 0);
// Get image data
const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height);
const data = imageData.data;
const width = tempCanvas.width;
const height = tempCanvas.height;
// Flood fill from corners to mark background pixels
const isBackground = new Uint8Array(width * height);
const isWhiteish = (r, g, b) => r > 240 && g > 240 && b > 240;
const floodFill = (startX, startY) => {
const stack = [[startX, startY]];
while (stack.length > 0) {
const [x, y] = stack.pop();
if (x < 0 || x >= width || y < 0 || y >= height) continue;
const idx = y * width + x;
if (isBackground[idx]) continue;
const pixelIdx = idx * 4;
const r = data[pixelIdx];
const g = data[pixelIdx + 1];
const b = data[pixelIdx + 2];
if (!isWhiteish(r, g, b)) continue;
isBackground[idx] = 1;
// Add neighbors
stack.push([x + 1, y]);
stack.push([x - 1, y]);
stack.push([x, y + 1]);
stack.push([x, y - 1]);
}
};
// Flood fill from all four corners
floodFill(0, 0);
floodFill(width - 1, 0);
floodFill(0, height - 1);
floodFill(width - 1, height - 1);
// Make background pixels transparent
for (let i = 0; i < isBackground.length; i++) {
if (isBackground[i]) {
data[i * 4 + 3] = 0; // Set alpha to 0
}
}
// Put the modified data back
tempCtx.putImageData(imageData, 0, 0);
// Create a new image from the processed canvas
this.processedPlaneImage = new Image();
this.processedPlaneImage.src = tempCanvas.toDataURL();
this.processedPlaneImage.onload = () => {
this.planeImageLoaded = true;
console.log('Plane image processed and loaded');
};
}
setupResponsiveCanvas() {
const resizeCanvas = () => {
const container = this.canvas.parentElement;
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
// Maintain 4:3 aspect ratio (800x600)
const aspectRatio = 4 / 3;
let newWidth, newHeight;
if (containerWidth / containerHeight > aspectRatio) {
// Container is wider - fit to height
newHeight = containerHeight;
newWidth = newHeight * aspectRatio;
} else {
// Container is taller - fit to width
newWidth = containerWidth;
newHeight = newWidth / aspectRatio;
}
// Set canvas internal resolution (1200x900 for larger display)
this.canvas.width = 1200;
this.canvas.height = 900;
// Update stored dimensions
this.width = 1200;
this.height = 900;
// CSS will handle the visual scaling via CSS in HTML
};
// Initial resize
resizeCanvas();
// Handle window resize and orientation change
window.addEventListener('resize', resizeCanvas);
window.addEventListener('orientationchange', () => {
setTimeout(resizeCanvas, 100);
});
}
async init() {
// Fetch config (includes theme and location)
await this.fetchConfig();
// Load background images based on theme
this.loadBackgroundImages();
// Fetch weather
await this.fetchWeather();
// Update weather every 10 minutes
setInterval(() => this.fetchWeather(), 600000);
// Update date/time display every second
setInterval(() => this.updateWeatherDisplay(), 1000);
// Setup view direction controls
this.setupViewControls();
// Start rendering loop
this.render();
setInterval(() => this.render(), 100); // 10 FPS for retro feel
// Connect to WebSocket
this.connectWebSocket();
}
setupViewControls() {
// Keyboard controls
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowLeft' || e.key === 'a' || e.key === 'A') {
this.rotateView(-90);
} else if (e.key === 'ArrowRight' || e.key === 'd' || e.key === 'D') {
this.rotateView(90);
}
});
// Click handlers for arrow buttons
const leftArrow = document.getElementById('view-left');
const rightArrow = document.getElementById('view-right');
if (leftArrow) {
leftArrow.addEventListener('click', () => this.rotateView(-90));
}
if (rightArrow) {
rightArrow.addEventListener('click', () => this.rotateView(90));
}
// Mouse tracking for hover labels
this.canvas.addEventListener('mousemove', (e) => {
const rect = this.canvas.getBoundingClientRect();
// Convert mouse position to canvas coordinates
const scaleX = this.canvas.width / rect.width;
const scaleY = this.canvas.height / rect.height;
this.mouseX = (e.clientX - rect.left) * scaleX;
this.mouseY = (e.clientY - rect.top) * scaleY;
});
this.canvas.addEventListener('mouseleave', () => {
this.mouseX = -1;
this.mouseY = -1;
this.hoveredAircraft = null;
});
// Click on canvas to deselect
this.canvas.addEventListener('click', () => {
this.selectedAircraftIcao = null;
this.updateAircraftSidebar();
});
// Sidebar click handler (delegated)
const sidebar = document.getElementById('aircraft-sidebar');
if (sidebar) {
sidebar.addEventListener('click', (e) => {
const aircraftEl = e.target.closest('.sidebar-aircraft');
if (aircraftEl) {
const icao = aircraftEl.dataset.icao;
// Toggle selection
if (this.selectedAircraftIcao === icao) {
this.selectedAircraftIcao = null;
} else {
this.selectedAircraftIcao = icao;
}
this.updateAircraftSidebar();
}
});
}
// Update initial compass display
this.updateCompassDisplay();
}
rotateView(degrees) {
this.viewDirection = (this.viewDirection + degrees + 360) % 360;
this.updateCompassDisplay();
console.log(`View direction: ${this.viewDirectionNames[this.viewDirection]} (${this.viewDirection}°)`);
}
updateCompassDisplay() {
const compassEl = document.getElementById('compass-direction');
if (compassEl) {
const dirName = this.viewDirectionNames[this.viewDirection];
const fullNames = { 'N': 'NORTH', 'E': 'EAST', 'S': 'SOUTH', 'W': 'WEST' };
compassEl.textContent = `VIEWING: ${fullNames[dirName]}`;
}
}
// Check if a bearing falls within the current field of view
isInFieldOfView(bearing) {
const halfFov = this.fieldOfView / 2;
const minAngle = (this.viewDirection - halfFov + 360) % 360;
const maxAngle = (this.viewDirection + halfFov) % 360;
// Handle wrap-around at 0/360
if (minAngle > maxAngle) {
return bearing >= minAngle || bearing <= maxAngle;
} else {
return bearing >= minAngle && bearing <= maxAngle;
}
}
// Get X position based on bearing within field of view
bearingToX(bearing) {
const halfFov = this.fieldOfView / 2;
// Calculate angle difference from view direction
let angleDiff = bearing - this.viewDirection;
// Normalize to -180 to 180
if (angleDiff > 180) angleDiff -= 360;
if (angleDiff < -180) angleDiff += 360;
// Map -45 to +45 degrees to screen X (with padding)
const padding = 60;
const usableWidth = this.width - (padding * 2);
// -45° = left edge, +45° = right edge
const normalizedAngle = (angleDiff + halfFov) / this.fieldOfView;
return padding + (normalizedAngle * usableWidth);
}
async fetchConfig() {
try {
const response = await fetch('/api/config');
const data = await response.json();
this.theme = data.theme || 'desert';
this.receiverLat = data.location?.lat || 0;
this.receiverLon = data.location?.lon || 0;
this.locationName = data.location?.name || 'My Location';
this.receivers = data.receivers || [];
// Apply site config
if (data.site) {
this.siteConfig = { ...this.siteConfig, ...data.site };
const titleEl = document.getElementById('site-title');
if (titleEl) titleEl.textContent = this.siteConfig.title;
document.title = `${this.siteConfig.title} - ${this.siteConfig.subtitle}`;
}
// Apply display config
if (data.display) {
this.displayConfig = { ...this.displayConfig, ...data.display };
// Apply default view direction
if (this.displayConfig.default_view_direction) {
this.viewDirection = this.displayConfig.default_view_direction;
}
// Show/hide sidebar
const sidebar = document.getElementById('aircraft-sidebar');
if (sidebar) {
sidebar.style.display = this.displayConfig.show_sidebar ? '' : 'none';
}
// Show/hide weather bar
const weatherBar = document.getElementById('weather-info');
if (weatherBar) {
weatherBar.style.display = this.displayConfig.show_weather ? '' : 'none';
}
}
console.log(`Config loaded - Theme: ${this.theme}, Location: ${this.locationName} (${this.receiverLat}, ${this.receiverLon})`);
console.log(`Receivers: ${this.receivers.join(', ') || 'none'}`);
} catch (error) {
console.warn('Could not fetch config, using defaults');
// Fallback to receiver-location API for backwards compatibility
await this.fetchReceiverLocation();
}
}
loadBackgroundImages() {
const directions = [
{ deg: 0, name: 'north' },
{ deg: 90, name: 'east' },
{ deg: 180, name: 'south' },
{ deg: 270, name: 'west' }
];
directions.forEach(dir => {
this.backgroundImages[dir.deg].onload = () => {
this.backgroundImagesLoaded[dir.deg] = true;
console.log(`${this.theme}/${dir.name}.png loaded`);
};
this.backgroundImages[dir.deg].onerror = () => {
console.warn(`Failed to load backgrounds/${this.theme}/${dir.name}.png`);
};
this.backgroundImages[dir.deg].src = `backgrounds/${this.theme}/${dir.name}.png?v=1`;
});
}
async fetchReceiverLocation() {
try {
// Fetch from same server that serves ADS-Bit
const response = await fetch('/api/receiver-location');
const data = await response.json();
this.receiverLat = data.lat;
this.receiverLon = data.lon;
this.locationName = data.name || 'My Location';
console.log(`Receiver location: ${this.locationName} (${this.receiverLat}, ${this.receiverLon})`);
} catch (error) {
console.warn('Could not fetch receiver location, using default');
}
}
async fetchWeather() {
try {
// Use Open-Meteo API (free, no API key needed) with daily forecast for sunrise/sunset
const url = `https://api.open-meteo.com/v1/forecast?latitude=${this.receiverLat}&longitude=${this.receiverLon}¤t_weather=true&daily=sunrise,sunset&timezone=auto`;
const response = await fetch(url);
const data = await response.json();
const weatherCode = data.current_weather.weathercode;
this.weather.temp = data.current_weather.temperature;
// Get today's sunrise and sunset times
if (data.daily && data.daily.sunrise && data.daily.sunset) {
this.weather.sunrise = new Date(data.daily.sunrise[0]);
this.weather.sunset = new Date(data.daily.sunset[0]);
}
// Map weather codes to conditions
// 0 = clear, 1-3 = partly cloudy, 45-48 = fog, 51-67 = rain, 71-77 = snow, 80-99 = rain/thunderstorm
if (weatherCode === 0) {
this.weather.condition = 'clear';
this.weather.description = 'Clear';
} else if (weatherCode <= 3) {
this.weather.condition = 'cloudy';
this.weather.description = 'Partly Cloudy';
} else if ((weatherCode >= 51 && weatherCode <= 67) || (weatherCode >= 80 && weatherCode <= 99)) {
this.weather.condition = 'rain';
this.weather.description = 'Rainy';
} else if (weatherCode >= 71 && weatherCode <= 77) {
this.weather.condition = 'snow';
this.weather.description = 'Snowy';
} else {
this.weather.condition = 'cloudy';
this.weather.description = 'Cloudy';
}
this.weather.lastUpdate = Date.now();
this.updateWeatherDisplay();
console.log(`Weather updated: ${this.weather.condition}, ${this.weather.temp}°C`);
} catch (error) {
console.warn('Could not fetch weather data', error);
this.weather.condition = 'clear'; // Default to clear
}
}
updateWeatherDisplay() {
// Update date/time display
const now = new Date();
const options = {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
hour12: true
};
const dateTimeStr = now.toLocaleString('en-US', options);
document.getElementById('datetime-display').textContent = `${this.locationName} - ${dateTimeStr}`;
// Update weather display with configured unit
let tempDisplay;
if (this.displayConfig.temperature_unit === 'C') {
tempDisplay = `${Math.round(this.weather.temp)}°C`;
} else {
tempDisplay = `${Math.round((this.weather.temp * 9/5) + 32)}°F`;
}
document.getElementById('weather-display').textContent = `${tempDisplay} - ${this.weather.description}`;
// Update sunrise/sunset times
if (this.weather.sunrise && this.weather.sunset) {
const sunriseStr = this.weather.sunrise.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
const sunsetStr = this.weather.sunset.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
document.getElementById('sun-times').textContent = `☀ ${sunriseStr} / 🌙 ${sunsetStr}`;
}
}
connectWebSocket() {
// Dynamically build WebSocket URL based on current page
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = window.location.host;
const wsUrl = `${protocol}//${host}/ws`;
console.log(`Connecting to WebSocket: ${wsUrl}`);
this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => {
console.log('WebSocket connected');
const receiverText = this.receivers && this.receivers.length > 0
? `CONNECTED: ${this.receivers.join(', ')}`
: 'CONNECTED';
document.getElementById('connection-status').textContent = receiverText;
document.getElementById('connection-status').classList.remove('blink');
this.reconnectDelay = 1000;
};
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'flights') {
this.updateFlights(data.flights);
}
};
this.ws.onclose = () => {
console.log('WebSocket disconnected, reconnecting...');
document.getElementById('connection-status').textContent = 'RECONNECTING...';
document.getElementById('connection-status').classList.add('blink');
setTimeout(() => this.connectWebSocket(), this.reconnectDelay);
this.reconnectDelay = Math.min(this.reconnectDelay * 2, 30000);
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
updateFlights(flights) {
this.flights.clear();
flights.forEach(flight => {
if (flight.lat && flight.lon && flight.altitude) {
this.flights.set(flight.icao, flight);
// Use ADS-B emitter category if available (from dump1090 JSON API),
// otherwise fall back to heuristics. Re-evaluate when new data arrives.
const hasEmitterCat = flight.category && flight.category.length >= 2;
const cached = this.aircraftTypes.get(flight.icao);
if (hasEmitterCat && (!cached || !cached.fromEmitter)) {
// Real ADS-B emitter category arrived - always prefer it
this.categorizeFromEmitter(flight);
} else if (!cached) {
// No data yet - use heuristics
this.categorizeAircraft(flight);
} else if (!cached.fromEmitter && (flight.speed > 0 && flight.callsign)) {
// Better heuristic data arrived, re-evaluate
this.categorizeAircraft(flight);
}
}
});
// Aircraft count is now updated in drawAircraft() with visible/total format
}
categorizeFromEmitter(flight) {
// Map ADS-B emitter category to sprite type
// See DO-260B Table 2-75 for full list
const cat = flight.category;
let type = 'narrowBody';
switch (cat) {
case 'A1': type = 'smallProp'; break; // Light (< 15,500 lbs)
case 'A2': type = 'regionalJet'; break; // Small (15,500 - 75,000 lbs)
case 'A3': type = 'narrowBody'; break; // Large (75,000 - 300,000 lbs)
case 'A4': type = 'narrowBody'; break; // High vortex large (B757)
case 'A5': // Heavy (> 300,000 lbs)
// Distinguish wideBody vs heavy sprite by altitude/speed
type = ((flight.altitude > 42000) || (flight.speed > 550)) ? 'heavy' : 'wideBody';
break;
case 'A6': type = 'narrowBody'; break; // High performance (> 5g, > 400 kts)
case 'A7': type = 'helicopter'; break; // Rotorcraft
case 'B1': type = 'glider'; break; // Glider / sailplane
case 'B2': type = 'balloon'; break; // Lighter-than-air
case 'B4': type = 'smallProp'; break; // Skydiver drop plane
case 'B6': type = 'uav'; break; // UAV
default: type = 'narrowBody'; break; // Unknown or surface vehicles
}
this.aircraftTypes.set(flight.icao, { type, fromEmitter: true });
}
categorizeAircraft(flight) {
// Heuristic fallback when ADS-B emitter category is not available.
// Priority: 1. Callsign-based, 2. Altitude/Speed heuristics, 3. Default
//
// NOTE: speed=0 or altitude=0 means data not yet received, so we
// avoid making assumptions from missing data. The caller should
// re-categorize once better data arrives.
let type = 'narrowBody'; // Default
const callsign = (flight.callsign || '').trim();
const altitude = flight.altitude || 0;
const speed = flight.speed || 0;
const hasSpeed = speed > 0;
const hasAlt = altitude > 0;
// --- Callsign-based detection (most reliable) ---
const airline = callsign.length >= 3 ? callsign.substring(0, 3) : '';
// Known helicopter operator callsign prefixes
const heliOperators = ['LFE', 'MED', 'CHP', 'PHI', 'ERA', 'BHS'];
// Keywords that appear anywhere in helicopter callsigns
const heliKeywords = ['LIFE', 'MERCY', 'REACH', 'COPTER', 'HELO', 'MEDEVAC', 'CARE'];
const isHeliCallsign = heliOperators.includes(airline) ||
heliKeywords.some(kw => callsign.includes(kw));
const heavyCallsigns = ['CPA', 'UAE', 'ETH', 'QTR', 'SIA', 'KLM', 'AFL', 'BAW', 'AAL', 'DAL', 'UAL', 'FDX', 'UPS'];
const regionalCallsigns = ['SKW', 'RPA', 'ASH', 'PDT', 'CHQ', 'ENY', 'JIA', 'CPZ'];
// N-number = US general aviation registration (Cessna, Piper, etc.)
const isNNumber = callsign.startsWith('N') && callsign.length >= 4 && callsign.length <= 6 && /^N\d/.test(callsign);
// --- Apply rules ---
// 1. Helicopter: callsign match
if (isHeliCallsign) {
type = 'helicopter';
}
// 2. Heavy / Wide body
else if (heavyCallsigns.includes(airline)) {
type = (hasAlt && altitude > 42000) || (hasSpeed && speed > 550) ? 'heavy' : 'wideBody';
}
else if ((hasAlt && altitude > 42000) || (hasSpeed && speed > 550)) {
type = 'heavy';
}
else if ((hasAlt && altitude > 40000) || (hasSpeed && speed > 500)) {
type = 'wideBody';
}
// 3. N-number = general aviation (small prop unless data says otherwise)
else if (isNNumber) {
type = (hasAlt && altitude > 25000) ? 'narrowBody' : 'smallProp';
}
// 4. Regional jets
else if (regionalCallsigns.includes(airline)) {
type = 'regionalJet';
}
// 5. Speed/altitude heuristics (only when we have real data)
else if (hasSpeed && hasAlt) {
if (speed < 60 && altitude < 5000) {
type = 'helicopter';
} else if (altitude < 18000 && speed < 300) {
type = (speed < 170 && altitude < 12000) ? 'smallProp' : 'regionalJet';
} else {
type = 'narrowBody';
}
}
// 6. Altitude-only heuristic
else if (hasAlt && !hasSpeed) {
if (altitude < 10000) {
type = 'smallProp';
} else if (altitude < 25000) {
type = 'regionalJet';
} else {
type = 'narrowBody';
}
}
// 7. No useful data yet - stay with default
this.aircraftTypes.set(flight.icao, { type, fromEmitter: false });
}
getAircraftSprite(icao) {
const cached = this.aircraftTypes.get(icao);
const category = cached ? cached.type : 'narrowBody';
return this.sprites[category] || this.sprites.narrowBody;
}
// Calculate distance in nautical miles
calculateDistance(lat1, lon1, lat2, lon2) {
const R = 3440.065; // Earth radius in nautical miles
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
// Calculate bearing from receiver to aircraft
calculateBearing(lat1, lon1, lat2, lon2) {
const dLon = (lon2 - lon1) * Math.PI / 180;
const y = Math.sin(dLon) * Math.cos(lat2 * Math.PI / 180);
const x = Math.cos(lat1 * Math.PI / 180) * Math.sin(lat2 * Math.PI / 180) -
Math.sin(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.cos(dLon);
const bearing = Math.atan2(y, x) * 180 / Math.PI;
return (bearing + 360) % 360;
}
// Check if plane is flying towards or away from receiver
isFlyingTowards(flight) {
const bearingToReceiver = this.calculateBearing(
flight.lat, flight.lon,
this.receiverLat, this.receiverLon
);
const headingDiff = Math.abs(flight.track - bearingToReceiver);
const normalizedDiff = headingDiff > 180 ? 360 - headingDiff : headingDiff;
return normalizedDiff < 90; // Less than 90 degrees = flying towards
}
render() {
// Draw sky gradient
this.drawSky();
// Draw clouds
this.drawClouds();
// Draw sun
this.drawSun();
// Draw moon
this.drawMoon();
// Weather is represented by cloud sprites (rain clouds vs happy clouds)
// No additional weather effects needed
// Draw ground (directional background) - after celestial bodies so horizon covers low sun/moon
this.drawGround();
// Draw grid lines for altitude reference
this.drawGrid();
// Calculate auto-scaling
const scale = this.calculateScale();
// Draw aircraft on top of everything
this.drawAircraft(scale);
// Draw scale indicators
this.drawScaleIndicators(scale);
// Draw compass indicators
this.drawCompassIndicators();
}
getSkyColors() {
// Calculate sun position to determine sky colors
const now = new Date();
if (!this.weather.sunrise || !this.weather.sunset) {
// Default day colors if no sun data
return { top: this.colors.skyTop, bottom: this.colors.skyBottom };
}
const sunrise = this.weather.sunrise.getTime();
const sunset = this.weather.sunset.getTime();
const current = now.getTime();
// Dawn/Dusk transition period (30 minutes)
const transitionTime = 30 * 60 * 1000;
// Dawn colors (orange/pink sunrise)
const dawnTop = '#4c5c8c';
const dawnBottom = '#dc8c5c';
// Day colors (bright blue)
const dayTop = '#6ca4dc';
const dayBottom = '#b4d4ec';
// Dusk colors (orange/purple sunset)
const duskTop = '#6c5c9c';
const duskBottom = '#dc9c6c';
// Night colors (dark blue/purple)
const nightTop = '#1c2c4c';
const nightBottom = '#2c3c5c';
// Determine time of day and interpolate colors
if (current < sunrise - transitionTime) {
// Night (before dawn)
return { top: nightTop, bottom: nightBottom };
} else if (current < sunrise) {
// Dawn transition
const progress = (current - (sunrise - transitionTime)) / transitionTime;
return {
top: this.interpolateColor(nightTop, dawnTop, progress),
bottom: this.interpolateColor(nightBottom, dawnBottom, progress)