-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2109 lines (1740 loc) · 89.8 KB
/
script.js
File metadata and controls
2109 lines (1740 loc) · 89.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
// WiFi 간섭 실험실 JavaScript 코드
class WiFiInterferenceLab {
constructor() {
this.isExperimentRunning = false;
this.experimentInterval = null;
this.signalData = [];
this.currentTime = 0;
this.ctx = null;
this.chartData = [];
this.canvas = null;
this.initializeElements();
this.bindEvents();
// Canvas 차트 초기화
this.initializeCanvasChart();
// Initialize drag and drop for settings button
this.initializeDragAndDrop();
// 초기화 완료 후 기본값 로드
setTimeout(() => {
this.loadDefaultValues();
this.updateSpecsSummary();
this.updateDynamicMessages();
this.updateBroadbandMessages();
// 줌과 리사이즈 기능 재초기화
this.initializeZoomAndResize();
// 강력한 차트 초기화
this.forceChartInitialization();
}, 100);
}
// Canvas 차트 초기화
initializeCanvasChart() {
console.log('=== Canvas 차트 초기화 시작 ===');
this.canvas = document.getElementById('signalChart');
if (!this.canvas) {
console.error('❌ Signal chart canvas not found!');
return;
}
this.ctx = this.canvas.getContext('2d');
if (!this.ctx) {
console.error('❌ Failed to get canvas context!');
return;
}
// 정확한 크기로 Canvas 설정 (1006×564.94) - 고정 크기
this.canvas.width = 1006;
this.canvas.height = 564.94;
// 정확한 표시 크기 설정
this.canvas.style.width = '1006px';
this.canvas.style.height = '564.94px';
// 렌더링 품질 향상
this.ctx.imageSmoothingEnabled = true;
this.ctx.imageSmoothingQuality = 'high';
console.log('✅ Fixed-size Canvas initialized:', this.canvas.width, 'x', this.canvas.height);
console.log('Display size:', this.canvas.style.width, 'x', this.canvas.style.height);
// 즉시 초기 차트 그리기
this.drawInitialChart();
}
// 초기 차트 그리기
drawInitialChart() {
if (!this.ctx || !this.canvas) {
console.error('❌ Canvas not ready in drawInitialChart');
return;
}
console.log('=== 초기 차트 그리기 시작 ===');
console.log('Canvas dimensions:', this.canvas.width, 'x', this.canvas.height);
try {
// Canvas 클리어
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// 배경 그리기
this.ctx.fillStyle = '#ffffff';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
// 테두리 그리기
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 1;
this.ctx.strokeRect(0, 0, this.canvas.width, this.canvas.height);
// 격자 그리기
this.drawGrid();
// 축 그리기
this.drawAxes();
// 초기 데이터로 사인파 그리기
this.drawSineWave();
console.log('✅ 초기 차트 그리기 완료');
} catch (error) {
console.error('❌ 차트 그리기 중 에러:', error);
}
}
// 고화질 격자 그리기
drawGrid() {
if (!this.ctx || !this.canvas) return;
this.ctx.strokeStyle = '#e8e8e8';
this.ctx.lineWidth = 0.5;
this.ctx.lineCap = 'round';
this.ctx.lineJoin = 'round';
// 격자 간격 (고정)
const gridSpacingX = 25;
const gridSpacingY = 20;
// 세로 격자 (시간축)
for (let x = 0; x <= this.canvas.width; x += gridSpacingX) {
this.ctx.beginPath();
this.ctx.moveTo(x, 0);
this.ctx.lineTo(x, this.canvas.height);
this.ctx.stroke();
}
// 가로 격자 (RSSI축)
for (let y = 0; y <= this.canvas.height; y += gridSpacingY) {
this.ctx.beginPath();
this.ctx.moveTo(0, y);
this.ctx.lineTo(this.canvas.width, y);
this.ctx.stroke();
}
}
// 고화질 축 그리기
drawAxes() {
if (!this.ctx || !this.canvas) return;
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 2;
this.ctx.lineCap = 'round';
this.ctx.lineJoin = 'round';
this.ctx.fillStyle = '#000000';
this.ctx.font = 'bold 12px Arial';
this.ctx.textAlign = 'center';
this.ctx.textBaseline = 'middle';
// Y축 (RSSI) - 선명한 선
this.ctx.lineWidth = 2;
this.ctx.beginPath();
this.ctx.moveTo(50, 20);
this.ctx.lineTo(50, this.canvas.height - 20);
this.ctx.stroke();
// Y축 라벨 - 회전된 텍스트 (범위 표시, 가독성 향상)
this.ctx.save();
this.ctx.translate(20, this.canvas.height / 2);
this.ctx.rotate(-Math.PI / 2);
this.ctx.font = 'bold 14px Arial';
this.ctx.fillStyle = '#000000'; // 색상 명확하게
this.ctx.fillText('RSSI (-40~-100 dBm)', 0, 0);
this.ctx.restore();
// Y축 범위 표시 (상단과 하단)
this.ctx.font = 'bold 10px Arial';
this.ctx.fillStyle = '#000000';
this.ctx.textAlign = 'center';
// Y축 눈금 - 캔버스 전체 높이 활용 (범위 -40 ~ -100 dBm, 가독성 향상)
this.ctx.font = 'bold 12px Arial';
this.ctx.fillStyle = '#000000'; // 색상 명확하게
this.ctx.textAlign = 'right'; // 오른쪽 정렬로 더 깔끔하게
for (let i = 0; i <= 12; i++) {
const y = 20 + (this.canvas.height - 40) * i / 12;
const rssi = -40 - (60 * i / 12); // -40 dBm ~ -100 dBm 범위 (60dB 범위)
this.ctx.beginPath();
this.ctx.moveTo(45, y);
this.ctx.lineTo(55, y);
this.ctx.stroke();
// 숫자 텍스트를 더 명확하게 표시
this.ctx.fillText(rssi.toString(), 35, y);
}
// -100 dBm이 확실히 보이도록 추가 눈금
const y100 = 20 + (this.canvas.height - 40) * 12 / 12; // 맨 아래
this.ctx.beginPath();
this.ctx.moveTo(45, y100);
this.ctx.lineTo(55, y100);
this.ctx.stroke();
this.ctx.fillText('-100', 35, y100);
// X축 (시간) - 선명한 선
this.ctx.lineWidth = 2;
this.ctx.beginPath();
this.ctx.moveTo(50, this.canvas.height - 20);
this.ctx.lineTo(this.canvas.width - 20, this.canvas.height - 20);
this.ctx.stroke();
// X축 라벨 (가독성 향상, 줌 적용)
this.ctx.font = 'bold 14px Arial'; // 줌에 따른 폰트 크기 조정
this.ctx.fillStyle = '#000000'; // 색상 명확하게
this.ctx.textAlign = 'center'; // 중앙 정렬
this.ctx.fillText('시간 (초)', this.canvas.width / 2, this.canvas.height - 5);
// X축 눈금 - 캔버스 전체 너비 활용 (가독성 향상, 줌 적용)
this.ctx.font = 'bold 12px Arial'; // 줌에 따른 폰트 크기 조정
this.ctx.fillStyle = '#000000'; // 색상 명확하게
this.ctx.textAlign = 'center'; // 중앙 정렬
for (let i = 0; i <= 20; i++) {
const x = 50 + (this.canvas.width - 70) * i / 20;
const time = i * 2.5;
this.ctx.beginPath();
this.ctx.moveTo(x, this.canvas.height - 25);
this.ctx.lineTo(x, this.canvas.height - 15);
this.ctx.stroke();
// 시간 텍스트를 더 명확하게 표시
this.ctx.fillText(time.toString(), x, this.canvas.height - 5);
}
}
// 고화질 사인파 그리기
drawSineWave() {
if (!this.ctx || !this.canvas) {
console.error('❌ Canvas not ready in drawSineWave');
return;
}
console.log('🎵 사인파 그리기 시작...');
try {
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 2.5;
this.ctx.lineCap = 'round';
this.ctx.lineJoin = 'round';
this.ctx.beginPath();
const startX = 50;
const endX = this.canvas.width - 20;
const amplitude = 30;
console.log('사인파 범위:', startX, '~', endX, 'px');
// 더 조밀한 포인트로 부드러운 곡선
for (let x = startX; x <= endX; x += 0.5) {
const normalizedX = (x - startX) / (endX - startX);
const time = normalizedX * 50; // 0-50초
// 복잡한 파형 (사인파 + 코사인파 + 노이즈) - 범위 중앙에 맞춤
const rssi = -60 +
Math.sin(time * 0.3) * 15 + // 진폭을 15로 조정 (범위의 1/3)
Math.cos(time * 0.2) * 10 + // 진폭을 10으로 조정
Math.sin(time * 0.1) * 5; // 진폭을 5로 조정
// RSSI를 Y좌표로 변환 (-100 ~ -40 dBm -> 20 ~ height-20, 캔버스 전체 높이 활용)
let y = 20 + (this.canvas.height - 40) * (rssi + 100) / 60;
// -100 dBm이 맨 아래에 오도록 보장
if (rssi <= -100) {
y = this.canvas.height - 20;
}
if (x === startX) {
this.ctx.moveTo(x, y);
} else {
this.ctx.lineTo(x, y);
}
}
this.ctx.stroke();
console.log('✅ 사인파 그리기 완료');
} catch (error) {
console.error('❌ 사인파 그리기 중 에러:', error);
}
}
// 실시간 데이터 추가 및 차트 업데이트
addChartData(rssi) {
console.log('=== 차트 데이터 추가 시작 ===');
if (!this.ctx || !this.canvas) {
console.log('⚠️ Canvas not ready, storing data only');
return;
}
// 데이터 저장
let time = this.currentTime;
let enhancedRSSI = rssi + Math.sin(time * 0.2) * 3; // 진폭을 3으로 조정
enhancedRSSI = Math.max(-100, Math.min(-40, enhancedRSSI)); // 범위를 -100 ~ -40 dBm으로 조정
// -100 dBm까지 확실히 표시되도록 범위 확장
if (enhancedRSSI < -95) {
enhancedRSSI = -95; // -100 dBm 근처까지 표시
}
this.chartData.push({ time, rssi: enhancedRSSI });
// 최근 100개 데이터만 유지
if (this.chartData.length > 100) {
this.chartData.shift();
}
// 차트 업데이트
this.updateCanvasChart();
console.log(`✅ Data added: time=${time}, rssi=${enhancedRSSI}`);
}
// Canvas 차트 업데이트
updateCanvasChart() {
console.log('🔄 updateCanvasChart 호출됨');
console.log('Canvas 상태:', { ctx: !!this.ctx, canvas: !!this.canvas, dataLength: this.chartData.length });
if (!this.ctx || !this.canvas) {
console.log('⚠️ Canvas not ready');
return;
}
// 데이터가 없어도 초기 차트는 그리기
if (this.chartData.length === 0) {
console.log('📊 데이터 없음, 초기 차트 그리기');
this.drawInitialChart();
return;
}
console.log('✅ 실시간 데이터로 차트 업데이트');
// Canvas 클리어
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// 배경 그리기
this.ctx.fillStyle = '#ffffff';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
// 테두리 그리기
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 1;
this.ctx.strokeRect(0, 0, this.canvas.width, this.canvas.height);
// 격자 그리기
this.drawGrid();
// 축 그리기
this.drawAxes();
// 고화질 실시간 데이터 그리기
this.drawRealTimeData();
}
// 고화질 실시간 데이터 그리기
drawRealTimeData() {
console.log('🎨 drawRealTimeData 호출됨, 데이터 개수:', this.chartData.length);
if (!this.ctx || !this.canvas) {
console.log('⚠️ Canvas not ready in drawRealTimeData');
return;
}
if (this.chartData.length === 0) {
console.log('📊 데이터 없음, 초기 차트 그리기');
this.drawInitialChart();
return;
}
console.log('✅ 실시간 데이터로 차트 그리기 시작');
// 메인 라인 그리기
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 3;
this.ctx.lineCap = 'round';
this.ctx.lineJoin = 'round';
this.ctx.beginPath();
const startX = 50;
const endX = this.canvas.width - 20;
this.chartData.forEach((point, index) => {
// 시간을 X좌표로 변환
const x = startX + (endX - startX) * (index / (this.chartData.length - 1));
// RSSI를 Y좌표로 변환 (-100 ~ -40 dBm -> 20 ~ height-20)
const y = 20 + (this.canvas.height - 40) * (point.rssi + 100) / 60;
if (index === 0) {
this.ctx.moveTo(x, y);
} else {
this.ctx.lineTo(x, y);
}
});
this.ctx.stroke();
// 데이터 포인트 표시 (고화질)
this.ctx.fillStyle = '#000000';
this.chartData.forEach((point, index) => {
const x = startX + (endX - startX) * (index / (this.chartData.length - 1));
const y = 20 + (this.canvas.height - 40) * (point.rssi + 100) / 60;
// 그라데이션 효과가 있는 포인트
this.ctx.beginPath();
this.ctx.arc(x, y, 3, 0, 2 * Math.PI);
this.ctx.fill();
// 포인트 테두리
this.ctx.strokeStyle = '#ffffff';
this.ctx.lineWidth = 1;
this.ctx.stroke();
});
console.log('✅ 실시간 데이터 차트 그리기 완료');
}
initializeElements() {
// DOM 요소들 초기화
this.elements = {
frequency: document.getElementById('frequency'),
distance: document.getElementById('distance'),
walls: document.getElementById('walls'),
interference: document.getElementById('interference'),
channel: document.getElementById('channel'),
power: document.getElementById('power'),
weather: document.getElementById('weather'),
time: document.getElementById('time'),
// 값 표시 요소들
distanceValue: document.getElementById('distanceValue'),
wallsValue: document.getElementById('wallsValue'),
interferenceValue: document.getElementById('interferenceValue'),
powerValue: document.getElementById('powerValue'),
// 결과 표시 요소들
rssiMeter: document.getElementById('rssiMeter'),
rssiValue: document.getElementById('rssiValue'),
downloadSpeed: document.getElementById('downloadSpeed'),
uploadSpeed: document.getElementById('uploadSpeed'),
qualityBar: document.getElementById('qualityBar'),
qualityText: document.getElementById('qualityText'),
interferenceMeter: document.getElementById('interferenceMeter'),
interferenceIndex: document.getElementById('interferenceIndex'),
// 버튼들
startExperiment: document.getElementById('startExperiment'),
resetExperiment: document.getElementById('resetExperiment'),
saveResults: document.getElementById('saveResults'),
// 차트
signalChart: document.getElementById('signalChart')
};
// Router specifications elements
this.router24Power = document.getElementById('router24Power');
this.router24PowerValue = document.getElementById('router24PowerValue');
this.router24Channels = document.getElementById('router24Channels');
this.router24Bandwidth = document.getElementById('router24Bandwidth');
this.router5Power = document.getElementById('router5Power');
this.router5PowerValue = document.getElementById('router5PowerValue');
this.router5Channels = document.getElementById('router5Channels');
this.router5Bandwidth = document.getElementById('router5Bandwidth');
this.routerAntenna = document.getElementById('routerAntenna');
this.routerHeight = document.getElementById('routerHeight');
this.routerHeightValue = document.getElementById('routerHeightValue');
this.routerLocation = document.getElementById('routerLocation');
// Summary elements
this.summary24 = document.getElementById('summary24');
this.summary5 = document.getElementById('summary5');
this.summaryAntenna = document.getElementById('summaryAntenna');
this.summaryLocation = document.getElementById('summaryLocation');
// Broadband specifications elements
this.maxDownloadSpeed = document.getElementById('maxDownloadSpeed');
this.downloadSpeedUnit = document.getElementById('downloadSpeedUnit');
this.downloadSpeedStability = document.getElementById('downloadSpeedStability');
this.maxUploadSpeed = document.getElementById('maxUploadSpeed');
this.uploadSpeedUnit = document.getElementById('uploadSpeedUnit');
this.uploadSpeedStability = document.getElementById('uploadSpeedStability');
this.internetType = document.getElementById('internetType');
this.networkCongestion = document.getElementById('networkCongestion');
// Broadband summary elements
this.summaryDownload = document.getElementById('summaryDownload');
this.summaryUpload = document.getElementById('summaryUpload');
this.summaryInternet = document.getElementById('summaryInternet');
// Settings button and modal elements
this.settingsButton = document.getElementById('settingsButton');
this.settingsModal = document.getElementById('settingsModal');
this.closeSettings = document.getElementById('closeSettings');
this.settingsButton.addEventListener('click', () => this.openSettings());
this.closeSettings.addEventListener('click', () => this.closeSettingsModal());
// 모달 외부 클릭 시 닫기
this.settingsModal.addEventListener('click', (e) => {
if (e.target === this.settingsModal) {
this.closeSettingsModal();
}
});
// ESC 키로 모달 닫기
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.settingsModal.classList.contains('show')) {
this.closeSettingsModal();
}
});
// Navigation button events
this.navStartExperiment = document.getElementById('navStartExperiment');
this.navResetExperiment = document.getElementById('navResetExperiment');
this.navLoadResults = document.getElementById('navLoadResults');
this.navJsonFileInput = document.getElementById('navJsonFileInput');
this.navStartExperiment.addEventListener('click', () => this.toggleExperiment());
this.navResetExperiment.addEventListener('click', () => this.resetExperiment());
this.navLoadResults.addEventListener('click', () => this.navJsonFileInput.click());
this.navJsonFileInput.addEventListener('change', (e) => this.handleNavFileSelection(e));
// 시그널 차트 요소 확인
this.signalChart = document.getElementById('signalChart');
}
bindEvents() {
// 슬라이더 이벤트 바인딩
this.elements.distance.addEventListener('input', (e) => {
this.elements.distanceValue.textContent = `${e.target.value}m`;
this.updateCalculations();
});
this.elements.walls.addEventListener('input', (e) => {
this.elements.wallsValue.textContent = `${e.target.value}개`;
this.updateCalculations();
});
this.elements.interference.addEventListener('input', (e) => {
this.elements.interferenceValue.textContent = `${e.target.value}%`;
this.updateCalculations();
});
this.elements.power.addEventListener('input', (e) => {
this.elements.powerValue.textContent = `${e.target.value}%`;
this.updateCalculations();
});
// 드롭다운 이벤트 바인딩
this.elements.frequency.addEventListener('change', () => this.updateCalculations());
this.elements.channel.addEventListener('change', () => this.updateCalculations());
this.elements.weather.addEventListener('change', () => this.updateCalculations());
this.elements.time.addEventListener('change', () => this.updateCalculations());
// 버튼 이벤트 바인딩
this.elements.startExperiment.addEventListener('click', () => this.toggleExperiment());
this.elements.resetExperiment.addEventListener('click', () => this.resetExperiment());
this.elements.saveResults.addEventListener('click', () => this.saveResults());
// Router specifications events
this.router24Power.addEventListener('input', () => this.updateRouterSpecs());
this.router24Channels.addEventListener('change', () => this.updateRouterSpecs());
this.router24Bandwidth.addEventListener('change', () => this.updateRouterSpecs());
this.router5Power.addEventListener('input', () => this.updateRouterSpecs());
this.router5Channels.addEventListener('change', () => this.updateRouterSpecs());
this.router5Bandwidth.addEventListener('change', () => this.updateRouterSpecs());
this.routerAntenna.addEventListener('change', () => this.updateRouterSpecs());
this.routerHeight.addEventListener('input', () => this.updateRouterSpecs());
this.routerLocation.addEventListener('change', () => this.updateRouterSpecs());
// Broadband specifications events
this.maxDownloadSpeed.addEventListener('input', () => this.updateBroadbandSpecs());
this.downloadSpeedUnit.addEventListener('change', () => this.updateBroadbandSpecs());
this.downloadSpeedStability.addEventListener('change', () => this.updateBroadbandSpecs());
this.maxUploadSpeed.addEventListener('input', () => this.updateBroadbandSpecs());
this.uploadSpeedUnit.addEventListener('change', () => this.updateBroadbandSpecs());
this.uploadSpeedStability.addEventListener('change', () => this.updateBroadbandSpecs());
this.internetType.addEventListener('change', () => this.updateBroadbandSpecs());
this.networkCongestion.addEventListener('change', () => this.updateBroadbandSpecs());
}
loadDefaultValues() {
// 기본값으로 계산 실행
this.updateCalculations();
// Canvas가 완전히 초기화되었는지 확인 후 초기 차트 그리기
if (this.canvas && this.ctx) {
console.log('✅ Canvas is ready, drawing initial chart...');
if (this.chartData.length === 0) {
this.drawInitialChart();
}
} else {
console.log('⏳ Canvas not ready yet, retrying in 100ms...');
// Canvas가 준비되지 않았다면 다시 시도
setTimeout(() => {
this.loadDefaultValues();
}, 100);
}
}
updateCalculations() {
console.log('🔄 계산 업데이트 시작...');
// 실험 중일 때도 차트 업데이트 허용
const frequency = parseFloat(this.elements.frequency.value);
const distance = parseFloat(this.elements.distance.value);
const walls = parseInt(this.elements.walls.value);
const interference = parseInt(this.elements.interference.value);
const channel = this.elements.channel.value;
const power = parseInt(this.elements.power.value);
const weather = this.elements.weather.value;
const time = this.elements.time.value;
// 공유기 스펙 가져오기
const router24Power = parseInt(this.router24Power?.value || 100);
const router5Power = parseInt(this.router5Power?.value || 100);
const router24Bandwidth = parseInt(this.router24Bandwidth?.value || 20);
const router5Bandwidth = parseInt(this.router5Bandwidth?.value || 80);
// 브로드밴드 설정 가져오기
const maxDownloadSpeed = parseFloat(this.maxDownloadSpeed?.value || 100);
const maxUploadSpeed = parseFloat(this.maxUploadSpeed?.value || 50);
const downloadSpeedUnit = this.downloadSpeedUnit?.value || 'Mbps';
const uploadSpeedUnit = this.uploadSpeedUnit?.value || 'Mbps';
console.log('📊 공유기 스펙:', { router24Power, router5Power, router24Bandwidth, router5Bandwidth });
console.log('🌐 브로드밴드 설정:', { maxDownloadSpeed, maxUploadSpeed, downloadSpeedUnit, uploadSpeedUnit });
// 주파수별 전송 파워 적용
let actualPower;
if (frequency === 2.4) {
actualPower = router24Power;
} else {
actualPower = router5Power;
}
console.log('⚡ 실제 적용 파워:', actualPower, 'mW (주파수:', frequency, 'GHz)');
// RSSI 계산 (실제 WiFi 공학 공식 기반)
let baseRSSI = this.calculateBaseRSSI(frequency, distance, walls, actualPower);
let interferenceEffect = this.calculateInterferenceEffect(interference, channel, weather, time);
let finalRSSI = baseRSSI - interferenceEffect;
// 전송 속도 계산 (브로드밴드 제한 적용)
let speeds = this.calculateSpeed(frequency, finalRSSI, interference, maxDownloadSpeed, maxUploadSpeed);
// 신호 품질 계산
let quality = this.calculateQuality(finalRSSI, interference);
// UI 업데이트
this.updateUI(finalRSSI, speeds, quality, interference);
console.log('✅ 계산 업데이트 완료');
}
updateChart() {
if (!this.chart) {
console.error('Chart is not initialized!');
return;
}
if (!this.chartData || this.chartData.length === 0) {
console.log('No chart data available for update');
return;
}
console.log('Updating chart with', this.chartData.length, 'data points');
try {
// 차트 데이터 업데이트
this.chart.data.labels = this.chartData.map(point => point.time);
this.chart.data.datasets[0].data = this.chartData.map(point => point.rssi);
// 차트 업데이트 (애니메이션 없이)
this.chart.update('none');
console.log('Chart updated successfully with', this.chart.data.datasets[0].data.length, 'points');
// 차트 컨테이너가 보이는지 확인
const chartContainer = document.querySelector('.chart-container');
if (chartContainer) {
console.log('Chart container found, dimensions:', chartContainer.offsetWidth, 'x', chartContainer.offsetHeight);
} else {
console.error('Chart container not found!');
}
} catch (error) {
console.error('Error updating chart:', error);
}
}
calculateBaseRSSI(frequency, distance, walls, power) {
// 자유 공간 경로 손실 공식 기반 (5GHz는 더 큰 손실)
let pathLoss = 20 * Math.log10(frequency) + 20 * Math.log10(distance) + 20 * Math.log10(4 * Math.PI / 3e8);
// 벽 손실 (2.4GHz: 약 4dB, 5GHz: 약 8-12dB per wall)
let wallLoss;
if (frequency === 2.4) {
wallLoss = walls * 4; // 2.4GHz: 4dB per wall
} else {
wallLoss = walls * 10; // 5GHz: 10dB per wall (더 큰 손실)
}
// 전송 파워 효과 (5GHz는 더 민감)
let powerEffect;
if (frequency === 2.4) {
powerEffect = (power - 100) * 0.5;
} else {
powerEffect = (power - 100) * 0.8; // 5GHz는 파워 변화에 더 민감
}
// 기본 RSSI (주파수별로 다름, 항상 음수)
let baseRSSI;
if (frequency === 2.4) {
baseRSSI = -30; // 2.4GHz 기본값
} else {
baseRSSI = -35; // 5GHz는 기본적으로 더 낮은 RSSI
}
// RSSI 계산 및 범위 제한 (-100 ~ -30 dBm)
let calculatedRSSI = baseRSSI - pathLoss - wallLoss + powerEffect;
return Math.max(-100, Math.min(-30, calculatedRSSI));
}
calculateInterferenceEffect(interference, channel, weather, time) {
let totalInterference = 0;
// 기본 간섭
totalInterference += interference * 0.3;
// 채널 간섭 (주파수별로 다름)
if (this.elements.frequency.value === '2.4') {
// 2.4GHz 채널 간섭
if (channel === '1' || channel === '6' || channel === '11') {
totalInterference += 5; // 최적 채널
} else if (channel === 'auto') {
totalInterference += 15; // 자동 선택은 간섭이 많을 수 있음
} else {
totalInterference += 25; // 인접 채널
}
} else {
// 5GHz 채널 간섭 (일반적으로 더 적음)
if (channel === '36' || channel === '40' || channel === '44' || channel === '48') {
totalInterference += 3; // UNII-1 대역 (최적)
} else if (channel === '149' || channel === '153' || channel === '157' || channel === '161') {
totalInterference += 5; // UNII-3 대역 (DFS 채널, 간섭 적음)
} else if (channel === 'auto') {
totalInterference += 8; // 자동 선택
} else {
totalInterference += 10; // 기타 채널
}
}
// 날씨 효과 (5GHz는 더 민감)
let weatherEffect;
switch(weather) {
case 'rainy': weatherEffect = this.elements.frequency.value === '2.4' ? 20 : 35; break;
case 'humid': weatherEffect = this.elements.frequency.value === '2.4' ? 15 : 25; break;
case 'dry': weatherEffect = this.elements.frequency.value === '2.4' ? 5 : 8; break;
default: weatherEffect = 0; break;
}
totalInterference += weatherEffect;
// 시간대 효과
switch(time) {
case 'evening': totalInterference += 25; break; // 저녁 시간대 간섭 최대
case 'afternoon': totalInterference += 15; break;
case 'morning': totalInterference += 10; break;
default: totalInterference += 5; break;
}
return totalInterference;
}
calculateSpeed(frequency, rssi, interference, maxDownloadSpeed = 100, maxUploadSpeed = 50) {
console.log('🚀 속도 계산 시작:', { frequency, rssi, interference, maxDownloadSpeed, maxUploadSpeed });
// RSSI 기반 최대 속도 계산 (주파수별로 다른 특성)
let maxSpeed;
if (frequency === 2.4) {
// 2.4GHz: 37 ~ 600 Mbps 범위로 제한
maxSpeed = Math.max(37, Math.min(600, 600 * Math.pow(10, (rssi + 30) / 30)));
} else {
// 5GHz: 270 ~ 9600 Mbps 범위로 제한 (더 현실적인 계산)
let rssiFactor = Math.max(0.1, (rssi + 100) / 70); // RSSI를 0~1 범위로 정규화
maxSpeed = Math.max(270, Math.min(9600, 270 + (9600 - 270) * rssiFactor));
}
// 간섭에 의한 속도 감소 (주파수별로 다른 감소율)
let interferenceFactor;
if (frequency === 2.4) {
interferenceFactor = Math.max(0.1, 1 - (interference / 150)); // 2.4GHz는 간섭에 덜 민감
} else {
interferenceFactor = Math.max(0.05, 1 - (interference / 120)); // 5GHz는 간섭에 더 민감
}
let actualMaxSpeed = maxSpeed * interferenceFactor;
// 브로드밴드 제한 적용 (가장 중요한 부분!)
let limitedMaxSpeed = Math.min(actualMaxSpeed, maxDownloadSpeed);
console.log('📊 속도 제한:', {
actualMaxSpeed: Math.round(actualMaxSpeed),
maxDownloadSpeed,
limitedMaxSpeed: Math.round(limitedMaxSpeed)
});
// 다운로드/업로드 속도 계산 (브로드밴드 제한 적용)
let downloadSpeed, uploadSpeed;
if (frequency === 2.4) {
// 2.4GHz: 다운로드 70-90%, 업로드 40-70%
downloadSpeed = limitedMaxSpeed * (0.7 + Math.random() * 0.2);
uploadSpeed = limitedMaxSpeed * (0.4 + Math.random() * 0.3);
} else {
// 5GHz: 다운로드 80-95%, 업로드 60-85% (더 균형잡힌 비율)
downloadSpeed = limitedMaxSpeed * (0.8 + Math.random() * 0.15);
uploadSpeed = limitedMaxSpeed * (0.6 + Math.random() * 0.25);
}
// 업로드 속도가 다운로드 속도를 넘지 않도록 보장
uploadSpeed = Math.min(uploadSpeed, downloadSpeed * 0.9);
// 최종 브로드밴드 제한 적용
downloadSpeed = Math.min(downloadSpeed, maxDownloadSpeed);
uploadSpeed = Math.min(uploadSpeed, maxUploadSpeed);
console.log('✅ 최종 속도:', {
download: Math.round(downloadSpeed),
upload: Math.round(uploadSpeed)
});
return {
download: Math.round(downloadSpeed),
upload: Math.round(uploadSpeed)
};
}
calculateQuality(rssi, interference) {
let quality = 100;
// RSSI 기반 품질 (음수 값 기준)
if (rssi > -30) quality -= 0; // -30dBm 이상: 우수
else if (rssi > -50) quality -= 10; // -50dBm ~ -30dBm: 양호
else if (rssi > -70) quality -= 30; // -70dBm ~ -50dBm: 보통
else if (rssi > -90) quality -= 60; // -90dBm ~ -70dBm: 나쁨
else quality -= 80; // -90dBm 이하: 매우 나쁨
// 간섭 기반 품질
quality -= interference * 0.5;
quality = Math.max(0, Math.min(100, quality));
return quality;
}
updateUI(rssi, speeds, quality, interference) {
// RSSI 미터 업데이트
let rssiPercentage = Math.max(0, Math.min(100, ((rssi + 100) / 70) * 100));
this.elements.rssiMeter.style.width = `${rssiPercentage}%`;
this.elements.rssiValue.textContent = `${rssi.toFixed(1)} dBm`;
// 속도 업데이트
this.elements.downloadSpeed.textContent = `${speeds.download} Mbps`;
this.elements.uploadSpeed.textContent = `${speeds.upload} Mbps`;
// 품질 바 업데이트
this.elements.qualityBar.style.setProperty('--quality-width', `${quality}%`);
let qualityText = quality > 80 ? '우수' : quality > 60 ? '양호' : quality > 40 ? '보통' : quality > 20 ? '나쁨' : '매우 나쁨';
this.elements.qualityText.textContent = qualityText;
// 간섭 미터 업데이트
let interferencePercentage = Math.min(100, interference);
this.elements.interferenceMeter.style.width = `${interferencePercentage}%`;
let interferenceText = interference < 20 ? '낮음' : interference < 50 ? '보통' : interference < 80 ? '높음' : '매우 높음';
this.elements.interferenceIndex.textContent = interferenceText;
// 차트 데이터 추가 - Canvas 상태를 안전하게 확인
if (this.isExperimentRunning) {
this.addChartData(rssi);
} else if (this.chartData.length === 0 && this.canvas && this.ctx) {
// 실험 중이 아니고 차트 데이터가 없으며 Canvas가 준비된 경우에만 초기 데이터 생성
console.log('✅ Adding initial chart data in updateUI...');
this.drawInitialChart();
}
// 페이지 로드 시 차트가 보이지 않는 경우 강제로 초기 차트 그리기
if (!this.isExperimentRunning && this.canvas && this.ctx && this.chartData.length === 0) {
console.log('🔄 페이지 로드 시 초기 차트 강제 그리기');
setTimeout(() => {
this.drawInitialChart();
}, 50);
}
}
toggleExperiment() {
if (this.isExperimentRunning) {
this.stopExperiment();
} else {
this.startExperiment();
}
}
startExperiment() {
console.log('Starting experiment...');
this.isExperimentRunning = true;
// 네비게이션 버튼 업데이트
if (this.navStartExperiment) {
this.navStartExperiment.innerHTML = '<span class="btn-icon">⏸️</span><span class="btn-text">실험 중지</span>';
this.navStartExperiment.classList.remove('nav-btn-primary');
this.navStartExperiment.classList.add('nav-btn-secondary');
}
// 기존 버튼 업데이트 (아직 남아있다면)
if (this.elements.startExperiment) {
this.elements.startExperiment.textContent = '실험 중지';
this.elements.startExperiment.classList.remove('btn-primary');
this.elements.startExperiment.classList.add('btn-secondary');
}
// 실험 데이터 초기화
this.currentTime = 0;
this.chartData = [];
console.log('Chart data reset, current time:', this.currentTime);
// Canvas 차트 초기화 및 확인
if (this.canvas && this.ctx) {
console.log('✅ Canvas is ready, starting experiment...');
// 초기 차트 그리기
this.drawInitialChart();
} else {
console.error('❌ Canvas is not ready during experiment start!');
// Canvas가 준비되지 않았다면 초기화 시도
setTimeout(() => {
this.initializeCanvasChart();
}, 100);
}
// 초기 데이터 포인트 추가
this.updateCalculations();
// 실시간 업데이트 시작 (더 빠른 업데이트로 부드러운 사인파)
this.experimentInterval = setInterval(() => {
this.currentTime += 1;
console.log(`Experiment tick: ${this.currentTime}`);
this.updateCalculations();
}, 500); // 0.5초마다 업데이트 (더 부드러운 곡선)
// 사용자 피드백
this.showExperimentStatus('실험이 시작되었습니다! 🚀', 'success');
}
stopExperiment() {
console.log('Stopping experiment...');
this.isExperimentRunning = false;
// 네비게이션 버튼 업데이트
if (this.navStartExperiment) {
this.navStartExperiment.innerHTML = '<span class="btn-icon">▶️</span><span class="btn-text">실험 시작</span>';
this.navStartExperiment.classList.remove('nav-btn-secondary');
this.navStartExperiment.classList.add('nav-btn-primary');
}
// 기존 버튼 업데이트 (아직 남아있다면)
if (this.elements.startExperiment) {
this.elements.startExperiment.textContent = '실험 시작';
this.elements.startExperiment.classList.remove('btn-secondary');
this.elements.startExperiment.classList.add('btn-primary');
}
if (this.experimentInterval) {
clearInterval(this.experimentInterval);
this.experimentInterval = null;
}
// 실험 중지 후 차트를 초기 상태로 복원