-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathhome.component.ts
More file actions
1996 lines (1736 loc) · 76 KB
/
Copy pathhome.component.ts
File metadata and controls
1996 lines (1736 loc) · 76 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
import {
Component,
AfterViewChecked,
OnInit,
OnDestroy,
ElementRef,
ViewChild,
HostBinding,
ChangeDetectorRef,
ChangeDetectionStrategy,
NgZone,
Renderer2 } from '@angular/core';
import { map,
Observable,
Subscription,
firstValueFrom } from 'rxjs';
import { HashSuffixPipe } from '../../pipes/hash-suffix.pipe';
import { SystemService } from '../../services/system.service';
import { ISystemInfo } from '../../models/ISystemInfo';
import { Chart } from 'chart.js'; // Import Chart.js
import { registerHomeChartPlugins } from './plugins';
import { HOME_CFG,
createAxisPaddingCfg } from './home.cfg';
import {
findLastFinite,
HomeChartState,
HomeChartStorage,
HomeHistoryDrainer,
createHomeChartConfig,
createHomeChart,
applyHomeChartTheme,
createSystemInfoPolling$,
installNerdChartsDebugBootstrap,
GraphGuard,
computeXWindow,
computeHomeChartScales,
applyAxisBoundsToChartOptions,
shouldUnlockStartup,
HomeWarmupMachine,
shouldInsertRestartCut,
syncHomeChartDataAndSmoothing,
getHistoryOldestTimestampMs,
shouldStartHr1mFromHistory,
shouldShowZoomWindowLabel,
clampWindowMs,
stepWindowMs,
toggleWindowMs,
ChartZoomCfg,
formatZoomWindowLabel,
updateChartWithZoomAnimation,
} from './chart';
import { NbThemeService, NbDialogService, NbToastrService } from '@nebular/theme';
import { NbTrigger } from '@nebular/theme';
import { TranslateService } from '@ngx-translate/core';
import { LocalStorageService } from '../../services/local-storage.service';
import { IPool } from 'src/app/models/IStratum';
import {
getPoolIconUrl as resolvePoolIconUrl,
getQuickLink,
supportsPing,
isLocalHost,
DEFAULT_POOL_ICON_URL,
DEFAULT_EXTERNAL_POOL_ICON_URL,
} from './home.quicklinks';
// Tile helpers (keep this component as a thin container)
import { maxAsicTemp,
splitHumanReadable,
toPct,
isBarWarn,
isBarCrit,
isBarMax,
BAR_LIMITS,
poolDiff,
abbrevMiddle,
getAsicFrequencyBoundsFromAsic,
FreqBounds,
getAsicCoreVoltageBoundsFromAsic,
VoltBounds,
shutdownTempC,
isAsicTempWarn,
isAsicTempCrit,
isBarOver,
isOutsideBand,
isAtLeast,
isBetween,
formatUptime,
normalizeHomeTileInfo,
HomeBarDomSync,
hexToRgba
} from './tiles/utils';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HomeComponent implements AfterViewChecked, OnInit, OnDestroy {
@ViewChild('myChart') ctx!: ElementRef<HTMLCanvasElement>;
// Persisted UI state: chart collapsed (visual-only; data continues tracking).
public isChartCollapsed: boolean = false;
private readonly chartCollapsedKey: string = HOME_CFG.storage.keys.chartCollapsed;
private chartWindowMs: number = HOME_CFG.xAxis.fixedWindowMs;
private zoomCfg: ChartZoomCfg = {
minWindowMs: HOME_CFG.xAxis.minWindowMs,
maxWindowMs: HOME_CFG.xAxis.maxWindowMs,
zoomStepMs: HOME_CFG.xAxis.zoomStepMs,
};
// CSS vars for meter bars (kept in sync with HOME_CFG)
@HostBinding('style.--bar-fill') barFill: string = HOME_CFG.colors.hashrateBase;
@HostBinding('style.--bar-track') barTrack: string = HOME_CFG.colors.chartGridColor;
@HostBinding('style.--asic-temp-pill') asicTempPill: string = HOME_CFG.colors.asicTemp;
// DOM hook: special-case bar fills without complicating templates
private currentInputBarMaxWanted: boolean = false;
private vrTempBarCritWanted: boolean = false;
private barDomSync: HomeBarDomSync;
// Track current Nebular theme name so we can apply small light-theme-only overrides.
private currentThemeName: string = '';
private applyXWindowToChart(xMinMs: number, xMaxMs: number): void {
// Update shared chart options (used on theme refresh etc.)
try {
const x = (this.chartOptions as any)?.scales?.x;
if (x) {
x.min = xMinMs;
x.max = xMaxMs;
}
} catch {}
// Update the live chart instance options so the viewport changes immediately
try {
const x = (this.chart as any)?.options?.scales?.x;
if (x) {
x.min = xMinMs;
x.max = xMaxMs;
}
} catch {}
}
private setChartWindowMs(nextMs: number): void {
const next = clampWindowMs(nextMs, this.zoomCfg);
if (next === this.chartWindowMs) return;
const prev = this.chartWindowMs;
this.chartWindowMs = next;
// Reset sticky temp bounds so the axis re-fits to the new window.
this.lastTempAxisMin = null;
this.lastTempAxisMax = null;
if (next > prev) {
const oldest = this.dataLabel?.length ? this.dataLabel[0] : null;
const cutoff = Date.now() - next;
const needsBackfill = !Number.isFinite(oldest as any) || Number(oldest) > cutoff + 2000;
if (needsBackfill) {
void this.reloadHistoryForWindow(next);
}
}
this.updateAxesScaleAdaptive();
this.syncChartDatasetsAndSmoothing();
// Force immediate dataset refresh so smoothing changes apply before any next tick.
this.ngZone.runOutsideAngular(() => {
try { this.chart?.update?.('none'); } catch {}
updateChartWithZoomAnimation(this.chart, 160);
});
}
public zoomOut(evt?: Event): void {
try { (evt?.currentTarget as HTMLElement | null)?.blur?.(); } catch {}
this.setChartWindowMs(stepWindowMs(this.chartWindowMs, this.zoomCfg.zoomStepMs, this.zoomCfg));
}
public zoomIn(evt?: Event): void {
try { (evt?.currentTarget as HTMLElement | null)?.blur?.(); } catch {}
this.setChartWindowMs(stepWindowMs(this.chartWindowMs, -this.zoomCfg.zoomStepMs, this.zoomCfg));
}
public toggleZoomWindow(evt?: Event): void {
try { (evt?.currentTarget as HTMLElement | null)?.blur?.(); } catch {}
this.setChartWindowMs(toggleWindowMs(this.chartWindowMs, this.zoomCfg));
}
public get zoomWindowLabel(): string {
const hourShort = this.translateService.instant('UNITS.HOUR_SHORT');
const minuteShort = this.translateService.instant('UNITS.MINUTE_SHORT');
return formatZoomWindowLabel(this.chartWindowMs, hourShort, minuteShort);
}
public get showZoomWindowLabel(): boolean {
return shouldShowZoomWindowLabel(this.chartWindowMs, this.zoomCfg);
}
/**
* Tile helpers exposed to the template.
* Kept here as public function refs so the HTML can call them.
*/
public maxAsicTemp = maxAsicTemp;
public splitHumanReadable = splitHumanReadable;
public toPct = toPct;
public isBarWarn = isBarWarn;
public isBarCrit = isBarCrit;
public isBarMax = isBarMax;
public isBarOver = isBarOver;
public BAR_LIMITS = BAR_LIMITS;
/**
* Input Voltage warn-band (yellow) should be data-driven (HOME_CFG) and centralized.
* We keep the template free of thresholds by routing through this method.
*/
public isInputVoltageWarn(voltage: any, voltageMin?: number, voltageMax?: number): boolean {
const low = voltageMin ?? HOME_CFG.tiles.inputVoltageBand.low;
const high = voltageMax ?? HOME_CFG.tiles.inputVoltageBand.high;
return isOutsideBand(voltage, low, high);
}
/**
* Input current warning thresholds depend on device max current.
* - For devices < lowMaxAThreshold: warn/crit at 98% / 99%
* - For devices >= lowMaxAThreshold: use default warn/crit
*/
public isInputCurrentWarn(currentA: any, minA: any, maxA: any): boolean {
const cfg = HOME_CFG.tiles.inputCurrent;
const max = Number(maxA);
const useLow = Number.isFinite(max) && max < Number(cfg.lowMaxAThreshold ?? 8);
const warnRel = useLow ? Number(cfg.lowWarnRel ?? 0.98) : Number(cfg.warnRel ?? 0.94);
return isBarWarn(currentA, minA, maxA, warnRel);
}
public isInputCurrentCrit(currentA: any, minA: any, maxA: any): boolean {
const cfg = HOME_CFG.tiles.inputCurrent;
const max = Number(maxA);
const useLow = Number.isFinite(max) && max < Number(cfg.lowMaxAThreshold ?? 8);
const critRel = useLow ? Number(cfg.lowCritRel ?? 0.99) : Number(cfg.critRel ?? 0.98);
return isBarCrit(currentA, minA, maxA, critRel);
}
/** Voltage Regulator temperature bands (yellow/red) are configured in HOME_CFG. */
public isVrTempWarn(vrTempC: any): boolean {
const band = HOME_CFG.tiles.vrTempBand;
return isBetween(vrTempC, band.warnC, band.critC);
}
public isVrTempCrit(vrTempC: any): boolean {
const band = HOME_CFG.tiles.vrTempBand;
return isAtLeast(vrTempC, band.critC);
}
private readonly lowRpmHintThresholdPct: number = 35;
private readonly hoverTooltipOffsetX: number = 14;
private readonly hoverTooltipOffsetY: number = 18;
private readonly hoverTooltipWidthPx: number = 360;
private readonly hoverTooltipHeightPx: number = 140;
public activeHoverTooltipId: string | null = null;
public hoverTooltipX: number = 0;
public hoverTooltipY: number = 0;
public shouldShowLowRpmHint(percent: any, rpm: any): boolean {
const pct = Number(percent);
const rpmValue = Number(rpm);
return Number.isFinite(pct)
&& pct > 0
&& pct < this.lowRpmHintThresholdPct
&& !(Number.isFinite(rpmValue) && rpmValue > 0);
}
public shouldShowFanRpm(percent: any, rpm: any): boolean {
const rpmValue = Number(rpm);
return Number.isFinite(rpmValue) && rpmValue > 0;
}
public getFanAriaLabel(channel: number | null, percent: any, rpm: any): string {
const pctValue = Number(percent);
const rpmValue = Number(rpm);
const pctText = `${Number.isFinite(pctValue) ? Math.round(pctValue) : 0} %`;
const label = channel != null
? this.translateService.instant('HOME.FAN_CHANNEL', { channel })
: this.translateService.instant('HOME.FAN_SPEED');
if (this.shouldShowLowRpmHint(percent, rpm)) {
return `${label}: ${pctText}. ${this.translateService.instant('HOME.FAN_LOW_RPM_HINT')}`;
}
if (!(Number.isFinite(rpmValue) && rpmValue > 0)) {
return `${label}: ${pctText}`;
}
const rpmText = `${Number.isFinite(rpmValue) ? Math.round(rpmValue) : 0} RPM`;
return `${label}: ${pctText} (${rpmText})`;
}
public showHoverTooltip(id: string, event: MouseEvent): void {
this.activeHoverTooltipId = id;
this.updateHoverTooltipPosition(event);
}
public showConditionalHoverTooltip(id: string, enabled: boolean, event: MouseEvent): void {
if (!enabled) return;
this.showHoverTooltip(id, event);
}
public moveHoverTooltip(event: MouseEvent): void {
if (!this.activeHoverTooltipId) return;
this.updateHoverTooltipPosition(event);
}
public moveConditionalHoverTooltip(enabled: boolean, event: MouseEvent): void {
if (!enabled || !this.activeHoverTooltipId) return;
this.updateHoverTooltipPosition(event);
}
public hideHoverTooltip(id?: string): void {
if (!id || this.activeHoverTooltipId === id) {
this.activeHoverTooltipId = null;
}
}
private updateHoverTooltipPosition(event: MouseEvent): void {
const viewportWidth = window.innerWidth || 0;
const viewportHeight = window.innerHeight || 0;
const pad = 12;
let x = event.clientX + this.hoverTooltipOffsetX;
let y = event.clientY + this.hoverTooltipOffsetY;
if (x + this.hoverTooltipWidthPx > viewportWidth - pad) {
x = Math.max(pad, viewportWidth - this.hoverTooltipWidthPx - pad);
}
if (y + this.hoverTooltipHeightPx > viewportHeight - pad) {
y = Math.max(pad, event.clientY - this.hoverTooltipHeightPx - 10);
}
this.hoverTooltipX = x;
this.hoverTooltipY = y;
}
// ASIC temperature scaling + warn/crit thresholds (used by ASIC °C + A1/A2… squares)
public shutdownTempC = shutdownTempC;
public isAsicTempWarn = isAsicTempWarn;
public isAsicTempCrit = isAsicTempCrit;
/**
* Uptime formatting for the hashrate tile (months/weeks/days/hours/minutes).
* Always shows minutes.
*/
public formatUptime = (totalSeconds: number): string =>
formatUptime(totalSeconds, HOME_CFG.tiles.uptime);
// ASIC frequency scaling (device-specific)
private _freqBoundsCacheKey: any = null;
private _freqBoundsCacheVal: FreqBounds = { min: 0, max: 1 };
// Snapshot of `/asic` endpoint (same data source as SETTINGS.FREQUENCY)
private _asicInfo: any = null;
public asicFreqBounds(info: any): FreqBounds {
if (info && info === this._freqBoundsCacheKey) return this._freqBoundsCacheVal;
const bounds = getAsicFrequencyBoundsFromAsic(info, this._asicInfo);
this._freqBoundsCacheKey = info;
this._freqBoundsCacheVal = bounds;
return bounds;
}
public asicFreqMax(info: any): number { return this.asicFreqBounds(info).max; }
// ASIC core-voltage scaling (device-specific, Settings-aligned)
private _voltBoundsCacheKey: any = null;
private _voltBoundsCacheVal: VoltBounds = { min: 0.9, max: 1.8 };
public asicVoltBounds(info: any): VoltBounds {
if (info && info === this._voltBoundsCacheKey) return this._voltBoundsCacheVal;
const bounds = getAsicCoreVoltageBoundsFromAsic(info, this._asicInfo);
this._voltBoundsCacheKey = info;
this._voltBoundsCacheVal = bounds;
return bounds;
}
public asicVoltMin(info: any): number { return this.asicVoltBounds(info).min; }
public asicVoltMax(info: any): number { return this.asicVoltBounds(info).max; }
/**
* Backwards-compatible alias used by the template.
* (The template calls asicCoreVoltageMax(info) to match the label in the UI.)
*/
public asicCoreVoltageMax(info: any): number { return this.asicVoltMax(info); }
public poolDiff = poolDiff;
public abbrevMiddle = abbrevMiddle;
// --- GraphGuard
// Step-Confirmation: how many consecutive "suspicious" samples in the same direction
// are required before accepting a step. Increase to 3 to be more conservative.
private graphGuardConfirmSamples: number = HOME_CFG.graphGuard.cfg.confirmSamples;
// If a "suspicious" hashrate step matches the live pool-sum reference within this tolerance,
// accept immediately (so the Y-scale reacts in 1–2 ticks).
private graphGuardLiveRefTolerance: number = HOME_CFG.graphGuard.cfg.liveRefTolerance;
// A step >= this relative delta vs previous sample is treated as a likely real change (e.g. freq up/down)
// and will not be blocked by the live-ref gate. (5s updates -> reacts in ~10s with confirmSamples=2)
private graphGuardBigStepRel: number = HOME_CFG.graphGuard.cfg.bigStepRel;
// Live pool-sum stability detector to avoid trusting a single live tick.
private graphGuardLiveRefStableSamples: number = HOME_CFG.graphGuard.cfg.liveRefStableSamples;
private graphGuardLiveRefStableRel: number = HOME_CFG.graphGuard.cfg.liveRefStableRel;
private lastLivePoolSumHs: number = 0;
// Timestamp of the last inserted NaN break-point (hard cut). Used to avoid collisions with history timestamps
private lastHardBreakTs: number = 0;
// Controls how many tick labels are shown on the left hashrate Y axis (Chart.js 'maxTicksLimit').
private hashrateYAxisMaxTicks: number = HOME_CFG.yAxis.hashrateMaxTicksDefault;
private hashrateYAxisMinStepThs: number = HOME_CFG.yAxis.minTickSteps.hashrateMinStepThs;
private tempYAxisMinStepC: number = HOME_CFG.yAxis.minTickSteps.tempMinStepC;
private lastTempAxisMin: number | null = null;
private lastTempAxisMax: number | null = null;
// Chunk size for the history drainer (0 means no limit)
private chunkSizeDrainer: number = HOME_CFG.historyDrain.chunkSize;
// --- Rendering smoothing (visual only)
// Applies to the 1min hashrate dataset. This does not modify data, only the curve rendering.
// Rule: high point density => higher tension, low density => lower tension.
private hashrate1mSmoothingCfg = { ...HOME_CFG.smoothing.hashrate1m };
private setHashrateYAxisLabelCount(count: number): void {
const clamp = HOME_CFG.yAxis.hashrateTickCountClamp;
const n = Math.max(clamp.min, Math.min(clamp.max, Math.round(Number(count))));
this.hashrateYAxisMaxTicks = n;
try {
const scales: any = (this.chartOptions as any)?.scales;
if (scales?.y?.ticks) {
scales.y.ticks.maxTicksLimit = n;
}
} catch {}
try {
const chart: any = this.chart as any;
if (chart?.options?.scales?.y?.ticks) {
chart.options.scales.y.ticks.maxTicksLimit = n;
this.ngZone.runOutsideAngular(() => {
chart.update('none');
});
}
} catch {}
}
protected readonly NbTrigger = NbTrigger;
private chart?: Chart;
private themeSubscription?: Subscription;
private chartInitialized = false;
private _info: any;
private timeFormatListener: any;
private wasLoaded = false;
private saveLock = false;
public info$: Observable<ISystemInfo>;
public quickLink$: Observable<string | undefined>;
public fallbackQuickLink$!: Observable<string | undefined>;
public expectedHashRate$: Observable<number | undefined>;
public chartOptions: any;
private chartState: HomeChartState = new HomeChartState();
private chartStorage: HomeChartStorage;
// Backward-compatible accessors (keeps the rest of the component diff small)
public get dataLabel(): number[] { return this.chartState.labels; }
public set dataLabel(v: number[]) { this.chartState.labels = v; }
public get dataData(): number[] { return []; }
public set dataData(_v: number[]) { /* unused */ }
public get dataData1m(): number[] { return this.chartState.hr1m; }
public set dataData1m(v: number[]) { this.chartState.hr1m = v; }
public get dataData10m(): number[] { return this.chartState.hr10m; }
public set dataData10m(v: number[]) { this.chartState.hr10m = v; }
public get dataData1h(): number[] { return this.chartState.hr1h; }
public set dataData1h(v: number[]) { this.chartState.hr1h = v; }
public get dataData1d(): number[] { return this.chartState.hr1d; }
public set dataData1d(v: number[]) { this.chartState.hr1d = v; }
public get dataVregTemp(): number[] { return this.chartState.vregTemp; }
public set dataVregTemp(v: number[]) { this.chartState.vregTemp = v; }
public get dataAsicTemp(): number[] { return this.chartState.asicTemp; }
public set dataAsicTemp(v: number[]) { this.chartState.asicTemp = v; }
public chartData?: any;
public historyDrainRunning = false;
private historyDrainer: HomeHistoryDrainer;
public hasChipTemps: boolean = false;
public isDualPool: boolean = false;
private historyMinTimestampMs: number | null = null;
// History drain rendering (to avoid "laggy" incremental build)
private historyDrainRenderThrottleMs: number = HOME_CFG.historyDrain.renderThrottleMs;
private historyDrainUseThrottledRender: boolean = HOME_CFG.historyDrain.useThrottledRender;
private suppressChartUpdatesDuringHistoryDrain = HOME_CFG.historyDrain.suppressChartUpdatesDuringDrain;
// Debug/test: allow toggling spike-guard for hashrate series (default: enabled)
private enableHashrateSpikeGuard: boolean = HOME_CFG.graphGuard.enableHashrateSpikeGuard;
public debugSpikeGuard: boolean = false;
private readonly graphGuardEngine = new GraphGuard({
confirmSamples: this.graphGuardConfirmSamples,
liveRefTolerance: this.graphGuardLiveRefTolerance,
bigStepRel: this.graphGuardBigStepRel,
liveRefStableSamples: this.graphGuardLiveRefStableSamples,
liveRefStableRel: this.graphGuardLiveRefStableRel,
debug: this.debugSpikeGuard,
});
public debugPillsLayout: boolean = false;
// Adaptive axis padding so lines don't stick to frame; tweak here.
private axisPadCfg = createAxisPaddingCfg();
// --- Warmup / restart gating (controlled start sequence after miner restarts)
private readonly warmupMachine = new HomeWarmupMachine(HOME_CFG.warmup);
private warmupStagePrev: string = this.warmupMachine.getStage();
// --- Startup behavior for hashrate (GraphGuard bypass for initial points)
private expectedHashrateHsLast: number = 0;
private startupUnlocked: boolean = false;
private bypassRemaining: Record<string, number> = {};
// 1m hashrate plotting must not start from 0 after restart; gate the very first plotted point.
private hr1mStarted: boolean = false;
// Timestamp (ms) when the first visible 1m hashrate point was plotted after a restart.
// Used for "super smooth" startup: temporarily require more confirmation before accepting
// short-lived dips. After the window, we switch to a snappier confirmation level.
private hr1mStartTsMs: number | null = null;
// Smooth startup should only trigger after an actual miner restart (hard cut), not on normal page loads.
private hr1mSmoothArmed: boolean = false;
private hr1mRestartTokenMs: number | null = null;
private hr1mReloadTimer: any = null;
private readonly hr1mReloadConsumedKey: string = '__nerdCharts_hr1mReloadConsumedToken';
private readonly hr1mReloadCooldownUntilKey: string = '__nerdCharts_hr1mReloadCooldownUntil';
private isHistoryImporting: boolean = false;
// NOTE: For hashrate charts, the pill/live value is used ONLY as a warmup gate signal.
// The plotted data continues to come from the history series (as before).
// To avoid a visible "shoot" or a brief drop right after restart, we simply do NOT start
// plotting 1m until the HISTORY 1m value itself is valid and has reached the expected unlock ratio.
private debugAxisPadding: boolean = false;
private readonly axisPadOverrideEnabledKey: string = '__nerdCharts_axisPaddingOverrideEnabled';
private readonly axisPadStorageKey: string = '__nerdCharts_axisPadding';
public nerdOsLogoColor: string = hexToRgba(HOME_CFG.colors.hashrateBase, 0.6);
ngAfterViewChecked(): void {
// Ensure chart is initialized only once when the canvas becomes available
if (!this.chartInitialized && this.ctx && this.ctx.nativeElement) {
this.chartInitialized = true; // Prevent re-initialization
this.initChart();
}
// Keep the Input Current bar coloring in sync even when it hits 100%
this.barDomSync.syncCurrentInputBarMaxFill(!!this.currentInputBarMaxWanted, this.currentThemeName);
// Keep the VR Temp bar coloring in sync for the CRIT band (>= 99%)
this.barDomSync.syncVrTempBarCritFill(!!this.vrTempBarCritWanted, this.currentThemeName);
}
private initChart(): void {
this.chart = createHomeChart(this.ctx.nativeElement, this.chartData, this.chartOptions);
// Restore legend visibility
const storedVisibility = this.chartStorage.loadLegendVisibility();
const visibility = storedVisibility ?? [
!!HOME_CFG.uiDefaults.legendHidden.hr1m,
!!HOME_CFG.uiDefaults.legendHidden.hr10m,
!!HOME_CFG.uiDefaults.legendHidden.hr1h,
!!HOME_CFG.uiDefaults.legendHidden.hr1d,
!!HOME_CFG.uiDefaults.legendHidden.vregTemp,
!!HOME_CFG.uiDefaults.legendHidden.asicTemp,
];
if (visibility && visibility.length) {
visibility.forEach((hidden: boolean, i: number) => {
if (hidden) this.chart.getDatasetMeta(i).hidden = true;
});
this.ngZone.runOutsideAngular(() => {
this.chart!.update();
});
}
try {
const flagKey = '__nerdCharts_clearChartHistoryOnce';
if (this.localStorageGet(flagKey) === '1') {
this.localStorageRemove(flagKey);
this.clearChartHistoryInternal(false);
}
} catch {}
this.loadChartData();
if (this._info?.history) {
if (this.dataLabel.length === 0) {
this.importHistoricalDataChunked(this._info.history);
} else {
this.importHistoricalData(this._info.history);
}
}
}
constructor(
private themeService: NbThemeService,
private systemService: SystemService,
private translateService: TranslateService,
private localStorage: LocalStorageService,
private hostEl: ElementRef<HTMLElement>,
private renderer: Renderer2,
private cdr: ChangeDetectorRef,
private ngZone: NgZone,
private dialogService: NbDialogService,
private toastrService: NbToastrService
) {
// Local persistence wrapper for chart state/settings
this.chartStorage = new HomeChartStorage({
getItem: (k) => this.localStorageGet(k),
setItem: (k, v) => this.localStorageSet(k, v),
removeItem: (k) => this.localStorageRemove(k),
});
// Restore chart collapsed state (visual-only)
this.isChartCollapsed = this.localStorageGet(this.chartCollapsedKey) === '1';
this.barDomSync = new HomeBarDomSync(this.hostEl, this.renderer, HOME_CFG.tiles.domSync);
this.historyDrainer = new HomeHistoryDrainer(
{
fetchInfo: (startTimestampMs, chunkSize) =>
this.systemService.getInfoWithSpan(startTimestampMs, chunkSize, HOME_CFG.xAxis.maxWindowMs),
importHistoryChunk: (history) => this.importHistoricalData(history),
setRunning: (running) => (this.historyDrainRunning = running),
setSuppressed: (suppressed) => (this.suppressChartUpdatesDuringHistoryDrain = suppressed),
render: () => this.updateChart(),
finalize: () => {
this.filterOldData();
if (this.wasLoaded) {
this.saveChartData();
}
},
log: (...args: any[]) => {
// keep noise low unless debug flags are enabled
if (this.debugSpikeGuard || this.debugAxisPadding) {
// eslint-disable-next-line no-console
console.log(...args);
}
},
},
{
chunkSize: this.chunkSizeDrainer,
renderThrottleMs: this.historyDrainRenderThrottleMs,
useThrottledRender: this.historyDrainUseThrottledRender,
}
);
// Load optional min-history timestamp (used after debug clear to prevent immediate refill)
try {
const v = Number(this.chartStorage.loadMinHistoryTimestampMs());
if (Number.isFinite(v) && v > 0) {
this.historyMinTimestampMs = v;
}
} catch {}
const cfg = createHomeChartConfig({
series: {
labels: this.dataLabel,
hr1m: this.dataData1m,
hr10m: this.dataData10m,
hr1h: this.dataData1h,
hr1d: this.dataData1d,
vregTemp: this.dataVregTemp,
asicTemp: this.dataAsicTemp,
},
translate: (key: string) => this.translateService.instant(key),
maxTicksLimit: this.hashrateYAxisMaxTicks,
getTimeFormatIs12h: () => this.localStorage.getItem('timeFormat') === '12h',
formatHashrate: (v: number) => HashSuffixPipe.transform(v),
persistLegendVisibility: (visibility: boolean[]) => this.chartStorage.saveLegendVisibility(visibility),
debugPillsLayout: this.debugPillsLayout,
});
this.chartData = cfg.chartData;
this.chartOptions = cfg.chartOptions;
applyHomeChartTheme(this.chartOptions);
this.info$ = createSystemInfoPolling$({
pollMs: 5000,
chunkSize: this.chunkSizeDrainer,
historyWindowMs: HOME_CFG.xAxis.maxWindowMs,
fetchInfo: (startTimestampMs, chunkSize) =>
this.systemService.getInfoWithSpan(startTimestampMs, chunkSize, HOME_CFG.xAxis.maxWindowMs),
defaultInfo: () => SystemService.defaultInfo(),
getStoredLastTimestampMs: () => this.getStoredTimestamp(),
getForceStartTimestampMs: () => {
try {
const forcedStart = Number(this.localStorageGet('__nerdCharts_forceStartTimestampMs'));
return Number.isFinite(forcedStart) && forcedStart > 0 ? forcedStart : null;
} catch {
return null;
}
},
clearForceStartTimestampMs: () => {
try {
this.localStorageRemove('__nerdCharts_forceStartTimestampMs');
} catch {}
},
logError: (...args: any[]) => console.error(...args),
onInfo: (info) => {
if (!info) return;
this._info = info;
try {
const flagKey = '__nerdCharts_clearChartHistoryOnce';
if (this.localStorageGet(flagKey) === '1') {
this.localStorageRemove(flagKey);
this.clearChartHistoryInternal(false);
}
} catch {}
// Skip chart updates until the chart is actually created
if (!this.chart) {
return;
}
// --- Warmup / startup signals (use live values, not history series)
// expectedHashRate$ returns an "expected" value used in UI. For internal comparisons
// we keep everything in H/s to match live pool sums and chart values.
try {
const expectedGh = Math.floor(Number(info.frequency) * ((Number(info.smallCoreCount) * Number(info.asicCount)) / 1000));
const expectedHs = Number.isFinite(expectedGh) && expectedGh > 0 ? expectedGh * 1e9 : 0;
this.expectedHashrateHsLast = expectedHs;
} catch {
this.expectedHashrateHsLast = 0;
}
const nowMs = Date.now();
const liveHs = this.getPoolHashrateHsSum();
const unlockRatio = Number(HOME_CFG.startup.expectedUnlockRatio ?? 0.75);
// 1m hashrate warmup gate: only unlock once expected is known and live reaches
// the configured ratio (e.g. 75%). If expected is 0/unknown, keep locked.
const unlockOk = this.expectedHashrateHsLast > 0
? (Number.isFinite(liveHs) && liveHs >= this.expectedHashrateHsLast * unlockRatio)
: false;
// "systemOk" is a cheap proxy to detect restarts even if temperatures remain high.
// After a real restart, expectedHashrate/frequency often drops to 0 or becomes unstable for a moment.
const systemOk = Number.isFinite(this.expectedHashrateHsLast) && this.expectedHashrateHsLast > 0;
this.warmupMachine.observeLive({
nowMs,
vregTempC: (info as any).vrTemp,
asicTempC: (info as any).temp,
liveHashrateHs: liveHs,
expectedHashrateHs: this.expectedHashrateHsLast,
systemOk,
unlockOk,
});
// Track stage changes (useful for debug, but also allows future hooks).
this.warmupStagePrev = this.warmupMachine.getStage();
// Only drain on cold start (no cached points yet)
if (this.dataLabel.length === 0) {
this.importHistoricalDataChunked(info.history);
} else {
this.importHistoricalData(info.history);
}
},
mapInfo: (info) => {
// MOCK
//(info as any).asicTemps = [50, 51, 52, 53, 54, 55, 53, 51];
// Normalize/derive everything the tiles need (bars + squares).
const derived = normalizeHomeTileInfo(info as any, {
powerUsageAliases: HOME_CFG.tiles.powerUsageAliases,
vrTempLimits: (BAR_LIMITS as any).vrTemp,
});
this.currentInputBarMaxWanted = derived.currentInputBarMaxWanted;
this.vrTempBarCritWanted = derived.vrTempBarCritWanted;
this.isDualPool = derived.isDualPool;
this.hasChipTemps = derived.hasChipTemps;
return info;
},
});
this.expectedHashRate$ = this.info$.pipe(map(info => {
if (!info || info.frequency == null || info.smallCoreCount == null || info.asicCount == null) return undefined;
const val = Math.floor(info.frequency * ((info.smallCoreCount * info.asicCount) / 1000));
return Number.isFinite(val) ? val : undefined;
}));
this.quickLink$ = this.info$.pipe(
map(info => this.getQuickLink(info.stratumURL, info.stratumUser))
);
this.fallbackQuickLink$ = this.info$.pipe(
map(info => this.getQuickLink(info.fallbackStratumURL, info.fallbackStratumUser))
);
}
public toggleChartCollapsed(evt?: Event): void {
this.isChartCollapsed = !this.isChartCollapsed;
// Remove focus after click so Nebular doesn't keep the button in a "pressed"/focused visual state.
// (Keeps the interaction clean while still allowing keyboard users to focus intentionally.)
try { (evt?.currentTarget as HTMLElement | null)?.blur?.(); } catch {}
if (this.isChartCollapsed) {
this.localStorageSet(this.chartCollapsedKey, '1');
return;
}
// Expanded again: clear persisted flag and make sure Chart.js recalculates layout.
this.localStorageRemove(this.chartCollapsedKey);
setTimeout(() => {
this.ngZone.runOutsideAngular(() => {
try { (this.chart as any)?.resize?.(); } catch {}
try { this.chart?.update?.('none' as any); } catch {}
});
}, 280);
}
/**
* Returns a pool-specific dashboard / stats URL for the given stratum endpoint.
*
* The function delegates to the shared quicklink helper which:
* - normalizes the stratum URL (supports stratum+tcp://, host:port, host)
* - extracts the wallet / address from the stratum user
* - maps known pools to their corresponding web dashboards
*
* If no known pool matches, a normalized URL representation of the stratum
* endpoint is returned as a fallback.
*
* @param stratumURL Stratum pool URL or host
* @param stratumUser Stratum user string (wallet[.worker])
* @returns A pool-specific dashboard URL or `undefined` if input is empty
*/
public getQuickLink(stratumURL: string, stratumUser: string): string | undefined {
return getQuickLink(stratumURL, stratumUser);
}
/**
* Ensure the "Input current" meter bar can still colorize correctly.
*
* The HTML expects these aliases:
* - info.currentA
* - info.minCurrentA
* - info.maxCurrentA
*
* Priority for limits:
* 1) If the backend already provides explicit current limits (in A or mA), keep them.
* 2) Otherwise derive maxCurrentA from configured power/voltage bounds.
*/
public supportsPing(stratumURL: string): boolean {
return supportsPing(stratumURL);
}
private readonly poolIconErrorCache = new Set<string>();
/**
* Resolves the icon URL for a given pool host.
*
* Logic:
* - Uses the existing pool registry / quicklink resolution via `getPoolIconUrl`
* - If the pool host previously failed to load an icon (favicon or registry icon),
* the default pool icon is returned immediately
* - This guarantees a valid icon for:
* - local pools
* - registered pools
* - unknown public pools
*
* @param host Pool hostname
* @returns URL to the pool icon or the default pool icon
*/
public poolIconUrl(host: string | undefined | null): string {
const key = (host ?? '').trim().toLowerCase();
if (!key) return DEFAULT_POOL_ICON_URL;
if (this.poolIconErrorCache.has(key)) {
return isLocalHost(key) ? DEFAULT_POOL_ICON_URL : DEFAULT_EXTERNAL_POOL_ICON_URL;
}
return resolvePoolIconUrl(key);
}
/**
* Handles icon load errors for pool icons.
*
* When a favicon or registry-provided icon cannot be loaded (e.g. 404, CORS),
* this method:
* - stores the host in an internal error cache
* - replaces the broken image with the default pool icon
* - prevents repeated failing network requests for the same pool
*
* This ensures graceful fallback behavior for unknown public pools.
*
* @param evt Image error event
* @param host Pool hostname associated with the icon
*/
public onPoolIconError(evt: Event, host: string | undefined | null): void {
const key = (host ?? '').trim().toLowerCase();
if (key) this.poolIconErrorCache.add(key);
const img = evt.target as HTMLImageElement | null;
if (!img) return;
const fallback = isLocalHost(key)
? DEFAULT_POOL_ICON_URL
: DEFAULT_EXTERNAL_POOL_ICON_URL;
if (img.src.includes(fallback)) return;
img.src = fallback;
}
// LocalStorage can throw (privacy mode/quota) and may be unavailable in some environments.
// Centralize access to keep persistence robust.
/**
* Read a value from localStorage safely (guards against privacy/quota errors).
*/
private localStorageGet(key: string): string | null {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
/**
* Write a value to localStorage safely (no-ops if storage is unavailable).
*/
private localStorageSet(key: string, value: string): void {
try {
localStorage.setItem(key, value);
} catch {
// Ignore storage errors (e.g., privacy mode/quota).
}
}
/**
* Remove a localStorage key safely (ignores storage access errors).
*/
private localStorageRemove(key: string): void {
try {
localStorage.removeItem(key);
} catch {
// Ignore storage errors.
}
}
ngOnInit() {
this.chartWindowMs = clampWindowMs(HOME_CFG.xAxis.fixedWindowMs, this.zoomCfg);
// Chart.js plugins are global; register once.
registerHomeChartPlugins();
installNerdChartsDebugBootstrap(globalThis, {
storage: {
getItem: (k: string) => this.localStorageGet(k),
setItem: (k: string, v: string) => this.localStorageSet(k, v),
removeItem: (k: string) => this.localStorageRemove(k),
},
clearChartHistoryInternal: (updateChartNow: boolean) => this.clearChartHistoryInternal(!!updateChartNow),
setAxisPadding: (cfg: any, persist: boolean) => this.setAxisPadding(cfg, persist),
saveAxisPaddingOverrides: () => this.saveAxisPaddingOverrides(),
disableAxisPaddingOverride: () => {
try { window?.localStorage?.removeItem(this.axisPadOverrideEnabledKey); } catch (e) {
console.warn("[nerdCharts] axis padding override disable failed", e);
}
},
setHashrateTicks: (n: number) => this.setHashrateYAxisLabelCount(n),
setHashrateMinTickStep: (ths: number) => {
this.hashrateYAxisMinStepThs = ths;
this.updateAxesScaleAdaptive();
try { this.chart?.update?.("none"); } catch { try { this.chart?.update?.(); } catch {} }
},
dumpAxisScale: () => {
try {
const y: any = (this.chartOptions.scales as any).y || {};
const ticks: any = y.ticks || {};
return {
yMin: y.min,
yMax: y.max,
maxTicksLimit: ticks.maxTicksLimit,
stepSize: ticks.stepSize,
hashrateYAxisMaxTicks: this.hashrateYAxisMaxTicks,
hashrateYAxisMinStepThs: this.hashrateYAxisMinStepThs,
};
} catch (e: any) {
return { error: String(e) };
}
},
flushHistoryDrainRender: () => {
try {
this.filterOldData();
if (this.wasLoaded) this.saveChartData();
this.updateChart();
} catch {}
},
// Console helper: restart device via backend endpoint.
// Note: mirrors the SystemComponent.restart() backend call; OTP is optional depending on device settings.
restart: async (totp?: string) => {
try {
const res = await firstValueFrom(this.systemService.restart('', (totp || '').trim()));
return { ok: true, res };
} catch (e: any) {
// eslint-disable-next-line no-console
console.warn('[nerdCharts] restart failed', e);
return { ok: false, error: String(e) };
}
},
});
this.graphGuardEngine.configure({ debug: !!this.debugSpikeGuard });
this.loadAxisPaddingOverrides();