Repository navigation
Expand file tree
/
Copy pathdashboard.html
More file actions
807 lines (759 loc) · 47.2 KB
/
Copy pathdashboard.html
File metadata and controls
807 lines (759 loc) · 47.2 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>Home power</title>
<style>
:root {
--bg: #f4f5f7; --card: #fff; --ink: #111318; --muted: #5f6672; --faint: #8a919c;
--line: #e7e9ee; --soft: #f1f3f6;
/* bright tones for fills and dots; -ink tones for text on white */
--solar: #f5a524; --solar-ink: #a35a00;
--load: #3b82f6; --load-ink: #1d4ed8;
--batt: #10b981; --batt-ink: #047857;
--grid: #8b5cf6; --grid-ink: #6d28d9;
--good: #16a34a; --warn: #d97706; --bad: #dc2626; --info: #64748b;
--shadow: 0 0 0 1px rgba(17,19,24,.06), 0 1px 2px rgba(17,19,24,.04), 0 6px 16px -6px rgba(17,19,24,.06);
--r-card: 18px; --r-inner: 10px;
}
* { box-sizing: border-box; }
html { background: var(--bg); }
body {
margin: 0; color: var(--ink); background: var(--bg);
font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
-webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;
font-variant-numeric: tabular-nums;
}
.wrap { max-width: 1120px; margin: 0 auto; padding: 28px 20px 72px; }
p { text-wrap: pretty; }
/* ---- header ---- */
.top { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
.brand { font-weight: 650; font-size: 15px; letter-spacing: -0.01em; }
.chips { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
.chip { display: inline-flex; align-items: center; gap: 7px; height: 30px; padding: 0 12px;
border-radius: 999px; background: var(--card); box-shadow: var(--shadow);
font-size: 13px; font-weight: 560; color: var(--muted); white-space: nowrap; }
.chip b { color: var(--ink); font-weight: 600; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--good);
box-shadow: 0 0 0 3px rgba(22,163,74,.15); transition-property: background-color, box-shadow;
transition-duration: .3s; }
.dot.warn { background: var(--warn); box-shadow: 0 0 0 3px rgba(217,119,6,.15); }
.dot.bad { background: var(--bad); box-shadow: 0 0 0 3px rgba(220,38,38,.15); }
.hero { margin: 26px 0 22px; }
.headline { margin: 0; font-size: clamp(24px, 3.6vw, 32px); line-height: 1.2; font-weight: 660;
letter-spacing: -0.022em; text-wrap: balance; max-width: 30ch; }
.subline { margin: 8px 0 0; color: var(--muted); font-size: 16.5px; max-width: 62ch; }
/* ---- cards ---- */
.card { background: var(--card); border-radius: var(--r-card); box-shadow: var(--shadow); padding: 20px; }
h2 { margin: 0 0 14px; font-size: 12.5px; font-weight: 650; letter-spacing: .06em;
text-transform: uppercase; color: var(--faint); }
.row { display: grid; gap: 16px; margin-bottom: 16px; }
.row.two { grid-template-columns: 1fr 1fr; }
.row.wide-left { grid-template-columns: 1.35fr 1fr; }
@media (max-width: 820px) { .row.two, .row.wide-left { grid-template-columns: 1fr; } }
/* ---- tiles ---- */
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 16px; margin-bottom: 16px; }
@media (max-width: 480px) { .tiles { gap: 12px; } .tile { padding: 16px; } .tile .big { font-size: 30px; } .tile .note { font-size: 12.5px; } }
.tile { position: relative; overflow: hidden; }
.tile::before { content: ""; position: absolute; inset: 0 auto 0 0; width: 4px; background: var(--c); }
.tile .label { font-size: 13.5px; color: var(--muted); font-weight: 560; }
.tile .big { font-size: 36px; font-weight: 680; letter-spacing: -0.03em; line-height: 1.1; margin: 8px 0 4px; }
.tile .big .unit { font-size: 15px; font-weight: 560; color: var(--faint); margin-left: 4px; letter-spacing: 0; }
.tile .note { font-size: 13.5px; color: var(--muted); }
.tile.off .big { color: var(--faint); }
/* ---- flow ---- */
.flow { width: 100%; height: auto; display: block; }
.node { fill: var(--card); stroke: var(--line); stroke-width: 1.5; }
.node-t { font-size: 13px; fill: var(--muted); font-weight: 600; }
.node-v { font-size: 20px; font-weight: 680; fill: var(--ink); }
.pipe { fill: none; stroke: var(--line); stroke-width: 4; stroke-linecap: round; }
.pipe.on { stroke-width: 5; stroke-dasharray: 9 11; animation: run 1.1s linear infinite; }
.pipe.rev { animation-direction: reverse; }
@keyframes run { to { stroke-dashoffset: -20; } }
@media (prefers-reduced-motion: reduce) { .pipe.on { animation: none; } }
@media (max-width: 560px) { .flow-card { display: none; } }
.node-s { font-size: 12.5px; fill: var(--faint); font-weight: 560; }
.legend { display: flex; gap: 16px; flex-wrap: wrap; font-size: 13px; color: var(--muted); margin-top: 12px; }
.legend i { display: inline-block; width: 10px; height: 10px; border-radius: 3px; margin-right: 6px; vertical-align: -1px; }
/* ---- battery ---- */
.soc { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
.soc-num { font-size: 48px; font-weight: 700; letter-spacing: -0.035em; line-height: 1; }
.soc-kwh { color: var(--muted); font-size: 15px; }
.bar { height: 14px; border-radius: 7px; background: var(--soft); overflow: hidden; margin-top: 16px;
box-shadow: inset 0 0 0 1px rgba(17,19,24,.04); }
.bar > i { display: block; height: 100%; border-radius: 7px; background: var(--batt); }
/* animate later changes only; the first render should show the real level at once */
body.ready .bar > i { transition-property: width, background-color; transition-duration: .6s;
transition-timing-function: cubic-bezier(.2,0,0,1); }
.batt-note { margin: 14px 0 0; font-size: 15px; color: var(--ink); }
.batt-note span { color: var(--muted); }
/* ---- health ---- */
.list { margin: 0; padding: 0; list-style: none; }
.list li { display: flex; gap: 12px; padding: 11px 0; border-bottom: 1px solid var(--line); }
.list li:last-child { border-bottom: 0; padding-bottom: 0; }
.list li:first-child { padding-top: 0; }
.mark { flex: 0 0 auto; width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center;
font-size: 12px; font-weight: 750; color: #fff; margin-top: 1px; }
.mark.ok { background: var(--good); } .mark.warn { background: var(--warn); }
.mark.bad { background: var(--bad); } .mark.info { background: var(--info); }
.what { font-weight: 600; }
.why { color: var(--muted); font-size: 13.5px; }
/* ---- today ---- */
.stat { display: flex; justify-content: space-between; align-items: baseline; padding: 10px 0;
border-bottom: 1px solid var(--line); }
.stat:first-child { padding-top: 0; }
.stat:last-of-type { border-bottom: 0; }
.stat b { font-size: 24px; font-weight: 680; letter-spacing: -0.02em; }
.stat .u { font-size: 13.5px; color: var(--faint); margin-left: 4px; font-weight: 560; }
.gq-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; flex-wrap: wrap; }
.seg { display: inline-flex; background: var(--soft); border-radius: 9px; padding: 3px; }
.seg button { border: 0; background: none; font: inherit; font-size: 12.5px; color: var(--muted);
padding: 4px 10px; border-radius: 7px; cursor: pointer; }
.seg button.on { background: var(--card); color: var(--ink); box-shadow: 0 1px 2px rgba(0,0,0,.08); }
.gq-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; margin: 6px 0 14px; }
.gq-stats div { background: var(--soft); border-radius: 10px; padding: 10px 12px; }
.gq-stats b { display: block; font-size: 19px; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; }
.gq-stats span { font-size: 12px; color: var(--muted); }
.gq-label { font-size: 12px; color: var(--muted); margin: 10px 0 2px; }
.small { color: var(--faint); font-size: 12.5px; margin: 12px 0 0; }
/* ---- events ---- */
.events { max-height: 316px; overflow-y: auto; margin-right: -8px; padding-right: 8px; }
.events li { align-items: baseline; padding: 9px 0; font-size: 14px; }
.when { flex: 0 0 auto; color: var(--faint); font-size: 12.5px; min-width: 96px; }
.kdot { flex: 0 0 auto; width: 8px; height: 8px; border-radius: 50%; align-self: center; }
/* ---- technical ---- */
details { margin-top: 8px; }
summary { list-style: none; cursor: pointer; display: flex; align-items: center; gap: 10px;
min-height: 44px; padding: 0 4px; color: var(--muted); font-weight: 600; font-size: 14px;
border-radius: var(--r-inner); user-select: none; }
summary::-webkit-details-marker { display: none; }
summary:hover { color: var(--ink); }
summary .chev { width: 18px; height: 18px; transition-property: transform; transition-duration: .2s;
transition-timing-function: cubic-bezier(.2,0,0,1); }
details[open] summary .chev { transform: rotate(90deg); }
.tech { display: grid; gap: 16px; margin-top: 6px; }
.flags { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 0 24px; }
.flags li { padding: 8px 0; font-size: 14px; align-items: center; }
.yn { flex: 0 0 auto; font-size: 11px; font-weight: 750; letter-spacing: .04em; padding: 3px 8px;
border-radius: 6px; background: var(--soft); color: var(--faint); min-width: 38px; text-align: center; }
.yn.on { background: rgba(22,163,74,.12); color: var(--good); }
.tag { margin-left: auto; font-size: 11.5px; color: var(--faint); }
.table-wrap { overflow-x: auto; margin: 0 -4px; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
td { padding: 10px 4px; border-bottom: 1px solid var(--line); vertical-align: top; }
tr:last-child td { border-bottom: 0; }
td.name { font-weight: 600; white-space: nowrap; padding-right: 16px; }
td.val { text-align: right; white-space: nowrap; font-weight: 600; padding-right: 16px; }
td.desc { color: var(--muted); font-size: 13.5px; min-width: 260px; }
.conf { display: inline-block; margin-left: 8px; font-size: 10.5px; font-weight: 750; letter-spacing: .03em;
padding: 1px 6px; border-radius: 5px; vertical-align: 1px; }
.conf.confirmed { background: rgba(22,163,74,.12); color: var(--good); }
.conf.spec, .conf.derived { background: var(--soft); color: var(--faint); }
.conf.unverified { background: rgba(217,119,6,.12); color: var(--warn); }
code { font: 500 .92em ui-monospace, SFMono-Regular, Menlo, monospace; background: var(--soft);
padding: 1px 5px; border-radius: 5px; }
footer { margin-top: 28px; color: var(--faint); font-size: 12.5px; text-align: center; }
</style>
</head>
<body>
<div class="wrap">
<header class="top">
<div class="brand">Home power</div>
<div class="chips">
<span class="chip"><i class="dot" id="conn-dot"></i><span id="conn-text">Connecting…</span></span>
<span class="chip" id="updated">—</span>
</div>
</header>
<section class="hero">
<h1 class="headline" id="headline">Reading your inverter…</h1>
<p class="subline" id="subline">One moment.</p>
</section>
<div class="tiles" id="tiles"></div>
<div class="row wide-left">
<div class="card flow-card">
<h2>Where your power is going</h2>
<svg class="flow" viewBox="0 0 720 300" id="flow" role="img" aria-label="Power flow diagram"></svg>
<div class="legend">
<span><i style="background:var(--solar)"></i>Solar</span>
<span><i style="background:var(--grid)"></i>Grid</span>
<span><i style="background:var(--batt)"></i>Battery</span>
<span><i style="background:var(--load)"></i>House</span>
</div>
<p class="small" id="flow-note"></p>
</div>
<div class="card">
<h2>Battery</h2>
<div class="soc"><span class="soc-num" id="soc-text">—</span><span class="soc-kwh" id="batt-kwh"></span></div>
<div class="bar"><i id="soc-bar" style="width:0%"></i></div>
<p class="batt-note" id="batt-note"></p>
<h2 style="margin-top:22px">Health</h2>
<ul class="list" id="checks"></ul>
</div>
</div>
<div class="row two">
<div class="card">
<h2>Today</h2>
<div id="today"></div>
</div>
<div class="card">
<h2>What happened</h2>
<ul class="list events" id="events"></ul>
</div>
</div>
<div class="row two">
<div class="card">
<h2>Solar vs house · watts · last 24 h</h2>
<svg viewBox="0 0 480 170" id="chart-power" style="width:100%;height:auto;display:block"></svg>
<div class="legend">
<span><i style="background:var(--solar)"></i>Solar</span>
<span><i style="background:var(--load)"></i>House</span>
</div>
</div>
<div class="card">
<h2>Battery · % · last 24 h</h2>
<svg viewBox="0 0 480 170" id="chart-soc" style="width:100%;height:auto;display:block"></svg>
<div class="legend" id="soc-legend"></div>
</div>
</div>
<div class="card" style="margin-bottom:16px">
<h2>Last 14 days · the inverter's own record</h2>
<svg viewBox="0 0 960 200" id="chart-days" style="width:100%;height:auto;display:block"></svg>
<div class="legend">
<span><i style="background:var(--solar)"></i>Solar made</span>
<span><i style="background:var(--load)"></i>House used</span>
<span id="day-month"></span>
</div>
</div>
<div class="card" style="margin-bottom:16px">
<div class="gq-head">
<h2>Grid quality</h2>
<div class="seg" id="gq-range">
<button data-h="24" class="on">24 h</button><button data-h="72">3 days</button><button data-h="168">7 days</button>
</div>
</div>
<div class="gq-stats" id="gq-stats"></div>
<div class="gq-label">When the grid was on</div>
<svg viewBox="0 0 960 44" id="gq-on" style="width:100%;height:auto;display:block"></svg>
<div class="legend" style="margin-top:4px">
<span><i style="background:var(--grid)"></i>On</span>
<span><i style="background:var(--bad);opacity:.55"></i>Cut</span>
<span><i style="background:var(--soft);outline:1px solid var(--line)"></i>Not recorded</span>
</div>
<div class="gq-label">Voltage · V <span style="color:var(--faint)">— shaded = lowest to highest in each 5 min · normal 207–253 V</span></div>
<svg viewBox="0 0 960 170" id="gq-v" style="width:100%;height:auto;display:block"></svg>
<div class="gq-label">Frequency · Hz <span style="color:var(--faint)">— normal 49.5–50.5 Hz · dips below 49 mean the grid is overloaded</span></div>
<svg viewBox="0 0 960 130" id="gq-hz" style="width:100%;height:auto;display:block"></svg>
<p class="small" id="gq-note"></p>
</div>
<details id="tech">
<summary>
<svg class="chev" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="2"><path d="M7.5 5l5 5-5 5"/></svg>
Technical details — status flags, every field explained, settings
</summary>
<div class="tech">
<div class="card">
<h2>What the inverter says it's doing</h2>
<ul class="list flags" id="doing"></ul>
</div>
<div class="card">
<h2>Live readings — what each number is</h2>
<div class="table-wrap"><table id="t-live"></table></div>
<p class="small"><b>confirmed</b> = proved by watching it move with something it must track.
<b>spec</b> = documented and consistent, not yet seen change. Re-check with <code>validate.py</code>.</p>
</div>
<div class="card">
<h2>Settings & lifetime totals</h2>
<div class="table-wrap"><table id="t-cfg"></table></div>
</div>
</div>
</details>
<footer id="footer">All data stays on this computer.</footer>
</div>
<script>
const $ = id => document.getElementById(id);
const W = n => Math.round(n).toLocaleString();
let lastOk = 0;
const MODE_SHORT = { L: "On grid", B: "On battery", P: "Powering on", S: "Standby",
F: "Fault", H: "Power saving", D: "Shut down", Y: "Bypass" };
function fmtHours(h) {
if (h < 1) return `${Math.round(h * 60)} min`;
if (h >= 48) return `${Math.round(h / 24)} days`;
const w = Math.floor(h), m = Math.round((h - w) * 60);
return m ? `${w} h ${m} min` : `${w} h`;
}
// for estimates: whole hours once it's long, so it doesn't look more exact than it is
function approxHours(h) { return h >= 3 ? `${Math.round(h)} h` : fmtHours(h); }
function energy(wh) {
return wh >= 1000 ? [(wh / 1000).toFixed(2), "kWh"] : [Math.round(wh), "Wh"];
}
function tile(label, colour, value, unit, note, dim) {
return `<div class="card tile ${dim ? "off" : ""}" style="--c:${colour}">
<div class="label">${label}</div>
<div class="big">${value}<span class="unit">${unit}</span></div>
<div class="note">${note}</div>
</div>`;
}
function sentence(s) {
const solar = s.solar_w, load = s.load_w, idle = load <= 5;
let head, sub;
if (!s.grid_on) {
head = "Running on your own power.";
if (idle && s.battery_direction !== "discharging")
sub = "Nothing in the house is drawing power right now.";
else if (s.battery_direction === "charging")
sub = `Solar is running the house and charging the battery.`;
else if (s.battery_direction === "discharging" && solar > 20)
sub = `Solar is making ${W(solar)} W; the battery tops up the rest of the ${W(load)} W the house uses.`;
else if (s.battery_direction === "discharging")
sub = `The battery is carrying the house — ${W(load)} W right now.`;
else
sub = `Your house is using ${W(load)} W.`;
sub += " No grid power is reaching the inverter.";
} else if (s.mode === "L") {
head = "The grid is powering your house.";
// in line mode the panels can only charge the battery; the house is on the grid
const gb = s.grid_to_batt_w >= 30 ? s.grid_to_batt_w : 0;
sub = `Your house is using ${W(load)} W from the grid. ` + (
solar > 20 ? `Solar's ${W(solar)} W goes into the battery${gb ? `, and the grid tops it up with ~${W(gb)} W` : ""}.`
: gb ? `No sun, so the grid is charging the battery at ~${W(gb)} W.` : "Solar isn't producing right now.");
const c = s.config || {};
if (c.battery_return_percent && s.battery_soc < c.battery_return_percent)
sub += s.battery_direction === "charging"
? ` Back to battery once it's refilled to ${c.battery_return_percent}%.`
: ` Back to battery once it reaches ${c.battery_return_percent}%.`;
} else {
head = "Running on solar and battery — the grid is ready as backup.";
sub = `Your house is using ${W(load)} W. Solar is making ${W(solar)} W.`;
}
if (s.battery_soc >= 99 && s.battery_direction !== "discharging") sub += " Battery is full.";
return [head, sub];
}
function battLine(s) {
const h = s.runtime_hours;
if (s.battery_direction === "charging") {
const both = s.mode === "L" && s.solar_w > 20 && s.grid_to_batt_w >= 30;
const split = both ? ` (${W(s.solar_w)} solar + ~${W(s.grid_to_batt_w)} grid, 1-min avg)`
: s.mode === "L" && s.grid_to_batt_w >= 30 ? " from the grid" : s.solar_w > 20 ? " from solar" : "";
const w = both ? "~" + W(s.solar_w + s.grid_to_batt_w) : W(Math.abs(s.battery_w));
return h !== null && h < 0 ? `Charging at ${w} W${split} <span>· ${s.charge_target < 100 ? `${s.charge_target}% in about ${fmtHours(-h)}, then back to battery` : `full in about ${fmtHours(-h)}`}</span>`
: `Charging at ${w} W${split}`;
}
const w = W(Math.abs(s.battery_w));
if (s.battery_direction === "discharging")
return h !== null && h > 0 ? `About <b>${fmtHours(h)}</b> ${s.grid_on ? "until the grid takes over" : "left"} <span>· draining at ${w} W</span>`
: `Draining at ${w} W`;
return `Idle <span>· nothing going in or out</span>`;
}
function checks(s) {
const out = [], push = (level, what, why) => out.push({ level, what, why });
for (const w of s.warnings || []) {
if (w.name === "Line fail")
push("info", "No grid at the inverter", "A blackout, or your grid switch is off — the inverter can't tell which.");
else push(w.severity === "fault" ? "bad" : "warn", w.name, "Reported by the inverter.");
}
if (s.temp_c >= 70) push("bad", "Running hot", `Heatsink is ${s.temp_c}°C. Check the fan and airflow.`);
else if (s.temp_c >= 55) push("warn", "Getting warm", `Heatsink is ${s.temp_c}°C.`);
if (s.load_percent >= 90) push("bad", "Nearly overloaded", `${s.load_percent}% of what it can deliver.`);
else if (s.load_percent >= 75) push("warn", "Heavy load", `${s.load_percent}% of capacity.`);
const reserve = s.config?.battery_reserve_percent ?? 20, floor = s.config?.battery_cutoff_percent ?? 10;
if (s.battery_soc <= floor + 10 && s.battery_direction === "discharging")
push("bad", "Battery is low", `${s.battery_soc}% left and still draining.`);
else if (s.battery_soc <= reserve && s.battery_direction === "discharging")
push("warn", "Battery getting low",
s.grid_on ? `Down to ${s.battery_soc}% — the grid should have taken over at ${reserve}%. Check program 12 on the screen.`
: `Down to ${s.battery_soc}% with no grid. It shuts off at ${floor}%.`);
const drift = s.slow?.clock_drift_seconds;
if (drift !== undefined && Math.abs(drift) > 3600)
push("warn", "Inverter clock is wrong", `Off by ${fmtHours(Math.abs(drift) / 3600)}, so its daily history is misdated.`);
const f = s.slow?.flags || {};
if (f["Overload restart"] === false || f["Over-temperature restart"] === false)
push("warn", "Won't restart itself after a fault",
"Auto-restart is off: an overload or overheat leaves the house dark until someone resets it.");
const br = s.slow?.bridge;
if (br && br.wifi_rssi < -80) push("warn", "Weak ESP32 WiFi", `Signal ${br.wifi_rssi} dBm — readings may drop out.`);
if (!out.some(c => c.level !== "info")) push("ok", "All good", "No faults, normal temperature, battery healthy.");
return out;
}
// ---- flow diagram ----
const NODES = {
solar: { x: 20, y: 20, label: "Solar", colour: "var(--solar)" },
grid: { x: 20, y: 180, label: "Grid", colour: "var(--grid)" },
inv: { x: 290, y: 100, label: "Inverter", colour: "var(--ink)" },
house: { x: 545, y: 20, label: "House", colour: "var(--load)" },
batt: { x: 545, y: 180, label: "Battery", colour: "var(--batt)" },
};
const NW = 155, NH = 92;
function box(k, value, sub) {
const n = NODES[k];
return `<g><rect class="node" x="${n.x}" y="${n.y}" width="${NW}" height="${NH}" rx="14"/>
<rect x="${n.x + 14}" y="${n.y + 18}" width="8" height="8" rx="2" fill="${n.colour}"/>
<text class="node-t" x="${n.x + 30}" y="${n.y + 27}">${n.label}</text>
<text class="node-v" x="${n.x + 14}" y="${n.y + (sub ? 58 : 64)}">${value}</text>
${sub ? `<text class="node-s" x="${n.x + 14}" y="${n.y + 79}">${sub}</text>` : ""}</g>`;
}
function pipe(d, colour, on, rev) {
return `<path class="pipe ${on ? "on" : ""} ${rev ? "rev" : ""}" d="${d}" style="${on ? `stroke:${colour}` : ""}"/>`;
}
function drawFlow(s) {
const charging = s.battery_direction === "charging" && Math.abs(s.battery_w) > 5;
const draining = s.battery_direction === "discharging" && Math.abs(s.battery_w) > 5;
const line = s.mode === "L";
// pipes are coloured by where the power comes from: on grid the house is fed
// by the grid, and the battery by solar (plus any grid top-up)
const battFrom = line && !(s.solar_w > 20) ? "var(--grid)" : charging ? "var(--solar)" : "var(--batt)";
const bw = s.battery_w > 0 ? `+${W(s.battery_w)} W` : `${W(s.battery_w)} W`;
$("flow").innerHTML = [
pipe("M 175 66 C 240 66, 240 130, 288 138", "var(--solar)", s.solar_w > 5),
pipe("M 175 226 C 240 226, 240 160, 288 154", "var(--grid)", s.grid_on && s.grid_w > 5),
pipe("M 447 138 C 500 130, 505 66, 543 66", line ? "var(--grid)" : "var(--load)", s.load_w > 5),
pipe("M 447 154 C 500 160, 505 226, 543 226", battFrom, charging || draining, draining),
box("solar", `${W(s.solar_w)} W`),
box("grid", line ? `${W(s.grid_w)} W` : s.grid_on ? "Ready" : "Off"),
box("inv", MODE_SHORT[s.mode] || s.mode_text),
box("house", `${W(s.load_w)} W`),
box("batt", Math.abs(s.battery_w) > 5 ? bw : "Idle", `${Math.round(s.battery_soc)}% full`),
].join("");
$("flow-note").textContent = line
? (s.solar_w > 20 ? "On grid: the grid feeds the house directly, and solar can only charge the battery."
: "On grid: the grid feeds the house directly.")
: "Moving dashes show which way power is flowing.";
}
// ---- charts ----
function fit(el, h) {
const w = Math.max(280, Math.round(el.clientWidth || el.parentNode.clientWidth || 480));
el.setAttribute("viewBox", `0 0 ${w} ${h}`);
return w;
}
// round an axis top up to 1, 2 or 2.5, 5 × a power of ten so gridlines are round numbers
function niceTop(v) {
const p = 10 ** Math.floor(Math.log10(v)), m = v / p;
return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 2.5 ? 2.5 : m <= 5 ? 5 : 10) * p;
}
function chart(el, series, yMax, labels) {
const h = 170, w = fit(el, h), pad = { l: 40, r: 8, t: 10, b: 22 };
const iw = w - pad.l - pad.r, ih = h - pad.t - pad.b;
const n = Math.max(...series.map(s => s.data.length), 2);
const top = yMax || niceTop(Math.max(10, ...series.flatMap(s => s.data.filter(v => v != null))) * 1.05);
const x = i => pad.l + (i / (n - 1)) * iw, y = v => pad.t + ih - (Math.min(v, top) / top) * ih;
let g = "";
for (let k = 0; k <= 4; k++) {
const yy = pad.t + (ih / 4) * k, val = top - (top / 4) * k;
g += `<line x1="${pad.l}" y1="${yy}" x2="${w - pad.r}" y2="${yy}" stroke="var(--line)"/>
<text x="${pad.l - 8}" y="${yy + 4}" text-anchor="end" font-size="10" fill="var(--faint)">${Math.round(val)}</text>`;
}
for (const s of series) {
for (const run of runsOf(s.data)) {
if (run.length < 2) continue;
const pts = run.map(i => `${x(i).toFixed(1)},${y(s.data[i]).toFixed(1)}`);
g += `<polygon points="${x(run[0])},${pad.t + ih} ${pts.join(" ")} ${x(run[run.length - 1])},${pad.t + ih}"
fill="${s.colour}" fill-opacity=".08"/>
<polyline points="${pts.join(" ")}" fill="none" stroke="${s.colour}" stroke-width="2"
stroke-linejoin="round" stroke-linecap="round"/>`;
}
}
for (const m of s_marks(series)) g += m(x, y, pad, w);
g += timeAxis(labels || [], pad, w, h);
el.innerHTML = g;
}
// indices split into runs, so gaps (no data) break the line instead of bridging it
function runsOf(data) {
const runs = []; let cur = [];
data.forEach((v, i) => { if (v != null) cur.push(i); else if (cur.length) { runs.push(cur); cur = []; } });
if (cur.length) runs.push(cur);
return runs;
}
function s_marks(series) { return series.flatMap(s => s.marks || []); }
// time labels along the bottom, thinned to fit the width
function timeAxis(labels, pad, w, h) {
const n = labels.length;
if (!n) return "";
const iw = w - pad.l - pad.r, every = Math.max(1, Math.ceil(n / Math.max(2, Math.floor(iw / 70))));
let g = "";
for (let i = 0; i < n - every / 2; i += every)
g += `<text x="${pad.l + i / Math.max(1, n - 1) * iw}" y="${h - 5}" font-size="11" fill="var(--faint)">${labels[i]}</text>`;
return g + `<text x="${w - pad.r}" y="${h - 5}" font-size="11" fill="var(--faint)" text-anchor="end">now</text>`;
}
function dayChart(el, days) {
const h = 200, w = fit(el, h), pad = { l: 44, r: 8, t: 10, b: 30 };
const iw = w - pad.l - pad.r, ih = h - pad.t - pad.b;
if (!days.length) { el.innerHTML = `<text x="10" y="24" font-size="13" fill="var(--faint)">Reading the inverter's daily counters…</text>`; return; }
const top = niceTop(Math.max(100, ...days.map(d => Math.max(d.solar_wh, d.load_wh))) * 1.05);
const slot = iw / days.length, bw = Math.min(18, slot / 2.8);
let g = "";
for (let k = 0; k <= 4; k++) {
const yy = pad.t + (ih / 4) * k, val = top - (top / 4) * k;
g += `<line x1="${pad.l}" y1="${yy}" x2="${w - pad.r}" y2="${yy}" stroke="var(--line)"/>
<text x="${pad.l - 8}" y="${yy + 4}" text-anchor="end" font-size="11" fill="var(--faint)">${val >= 1000 ? (val / 1000).toFixed(1) + "k" : Math.round(val)}</text>`;
}
days.forEach((d, i) => {
const cx = pad.l + slot * (i + 0.5);
for (const [val, colour, off] of [[d.solar_wh, "var(--solar)", -bw * 0.58], [d.load_wh, "var(--load)", bw * 0.58]]) {
const bh = Math.max(val > 0 ? 2 : 0, (Math.min(val, top) / top) * ih);
g += `<rect x="${(cx + off - bw / 2).toFixed(1)}" y="${(pad.t + ih - bh).toFixed(1)}" width="${bw.toFixed(1)}"
height="${bh.toFixed(1)}" rx="3" fill="${colour}"><title>${d.date}: ${W(val)} Wh</title></rect>`;
}
// day number, with the month on the first bar and whenever it changes
const mon = d.date.split(" ").pop(), showMon = i === 0 || mon !== days[i - 1].date.split(" ").pop();
g += `<text x="${cx.toFixed(1)}" y="${h - 10}" text-anchor="middle" font-size="11" fill="var(--faint)">${d.label}${showMon ? " " + mon : ""}</text>`;
});
g += `<text x="4" y="${h - 10}" font-size="11" fill="var(--faint)">Wh</text>`;
el.innerHTML = g;
}
// ---- render ----
function render(s) {
if (!s.connected) {
$("conn-dot").className = "dot bad";
$("conn-text").innerHTML = "<b>Not connected</b>";
$("headline").textContent = "Can't reach the inverter right now.";
$("subline").textContent = (s.error || "") + " — check the ESP32 has power and WiFi. Readings it takes meanwhile are kept and filled in later.";
return;
}
lastOk = Date.now();
const br = s.slow?.bridge;
$("conn-dot").className = "dot";
$("conn-text").innerHTML = s.source === "esp32" ? "<b>Live</b> · via ESP32 WiFi" : "<b>Live</b> · via USB";
const [head, sub] = sentence(s);
$("headline").textContent = head;
$("subline").textContent = sub;
const h = s.runtime_hours, cut = s.blackout_hours;
const battNote = !s.grid_on ? (h > 0 ? `≈ ${fmtHours(h)} left` : s.battery_direction === "charging" ? "Charging from solar" : "Idle")
: cut != null ? (s.battery_direction === "charging" && h < 0
? `${s.charge_target}% in ${fmtHours(-h)} · ~${approxHours(cut)} if the grid cuts`
: `Lasts ~${approxHours(cut)} if the grid cuts`)
: s.battery_direction === "charging" ? `Charging to ${s.charge_target}%` : "Idle";
$("tiles").innerHTML = [
tile("Solar", "var(--solar)", W(s.solar_w), "W",
s.solar_w > 5 ? `${s.pv_v.toFixed(0)} V from the panels` : "Not producing right now", s.solar_w <= 5),
tile("House using", "var(--load)", W(s.load_w), "W",
`${energy(s.energy_today.load_wh).join(" ")} so far today`, s.load_w <= 5),
tile("Battery", "var(--batt)", Math.round(s.battery_soc), "%", battNote, false),
s.mode === "L"
? tile("Grid", "var(--grid)", W(s.grid_w), "W",
s.grid_to_batt_w >= 30 ? `${W(s.load_w)} W house · ~${W(s.grid_to_batt_w)} W battery · ${s.grid_v.toFixed(0)} V`
: `Powering the house · ${s.grid_v.toFixed(0)} V`, false)
: s.grid_on
? tile("Grid", "var(--grid)", "Ready", "", `${s.grid_v.toFixed(0)} V · backup, not in use`, false)
: tile("Grid", "var(--grid)", "Off", "", "Blackout, or switch off", true),
].join("");
drawFlow(s);
const soc = Math.round(s.battery_soc), kwh = s.config?.battery_kwh;
const bar = $("soc-bar");
bar.style.width = soc + "%";
const c = s.config || {};
bar.style.background = soc <= (c.battery_cutoff_percent ?? 10) + 10 ? "var(--bad)"
: soc <= (c.battery_reserve_percent ?? 40) ? "var(--warn)" : "var(--batt)";
$("soc-text").textContent = soc + "%";
$("batt-kwh").textContent = kwh ? `${(kwh * soc / 100).toFixed(1)} of ${kwh} kWh` : "";
$("batt-note").innerHTML = battLine(s)
+ (s.grid_on && cut != null ? `<br><b>If the grid cuts now:</b> about ${approxHours(cut)} <span>· at your usual ${W(s.typical_load_w)} W, down to ${c.battery_cutoff_percent}%</span>` : "")
+ (c.battery_return_percent
? `<br><span>Grid takes over below ${c.battery_reserve_percent}% · back to battery at ${c.battery_return_percent}% · in a blackout it runs down to ${c.battery_cutoff_percent}%</span>` : "");
const ICON = { ok: "✓", warn: "!", bad: "!", info: "i" };
$("checks").innerHTML = checks(s).map(c => `<li><span class="mark ${c.level}">${ICON[c.level]}</span>
<span><span class="what">${c.what}</span><br><span class="why">${c.why}</span></span></li>`).join("");
lastState = s;
drawDay();
// measured here from every reading (the ESP32 fills any gaps), so all rows share one source
const dly = s.daily || {}, et = s.energy_today;
const gridH = et.grid_on_h || 0;
const rows = [["Solar made", energy(et.solar_wh), "var(--solar-ink)"],
["House used", energy(et.load_wh), "var(--load-ink)"],
["Taken from the grid", energy(et.grid_wh), "var(--grid-ink)"],
["Grid was on", [gridH < 1 ? Math.round(gridH * 60) : gridH.toFixed(1),
`${gridH < 1 ? "min" : "h"} of ${((Date.now() - new Date().setHours(0, 0, 0, 0)) / 3.6e6).toFixed(1)} h today`], "var(--grid-ink)"]];
$("today").innerHTML = rows.map(([label, [v, u], c]) =>
`<div class="stat"><span>${label}</span><span style="color:${c}"><b>${v}</b><span class="u">${u}</span></span></div>`
).join("") + `<p class="small">Measured here from every reading since midnight.` +
(dly.today_solar_wh !== undefined ? ` The inverter's own counter says ${energy(dly.today_solar_wh).join(" ")} solar and
${energy(dly.today_load_wh).join(" ")} used — it counts differently, and the 14-day chart below uses its figures.` : "") + `</p>`;
dayChart($("chart-days"), dly.days || []);
const daysWithData = (dly.days || []).filter(d => d.solar_wh || d.load_wh).length;
$("day-month").textContent = (dly.month_label || "") +
(daysWithData && daysWithData < 4 ? " · fills in day by day since the inverter's clock was corrected" : "");
const EV = { grid: "var(--grid)", charge: "var(--batt)", discharge: "var(--batt)", monitor: "var(--faint)", warning: "var(--warn)" };
const evColour = e => e.kind === "mode" ? (/battery/i.test(e.text) ? "var(--batt)" : "var(--grid)") : EV[e.kind] || "var(--faint)";
// newest first; a run of "Monitoring started" (dashboard restarts) shows once
const evs = (s.events || []).filter((e, i, a) => !(e.kind === "monitor" && e.text === "Monitoring started"
&& a[i - 1] && a[i - 1].kind === "monitor" && a[i - 1].text === "Monitoring started"))
.map(e => ({ ...e, text: e.text.replace("Switched to Line / grid", "Switched to grid").replace("Switched to Battery", "Switched to battery") }));
$("events").innerHTML = evs.length ? evs.map(e => {
const d = new Date(e.timestamp), today = d.toDateString() === new Date().toDateString();
const when = (today ? "" : d.toLocaleDateString(undefined, { day: "numeric", month: "short" }) + " ") + d.toTimeString().slice(0, 5);
return `<li><span class="when">${when}</span><span class="kdot" style="background:${evColour(e)}"></span><span>${e.text}</span></li>`;
}).join("") : `<li class="why">Nothing has changed yet.</li>`;
$("doing").innerHTML = (s.status_flags || []).map(f => `<li><span class="yn ${f.on ? "on" : ""}">${f.on ? "YES" : "NO"}</span>
<span>${f.label}</span>${f.confirmed ? "" : '<span class="tag">from spec</span>'}</li>`).join("");
const R = s.raw;
const FIELDS = [
["Grid voltage", R.grid_voltage, "V", "confirmed", "What's arriving at the inverter's grid input. 0 means a blackout or your grid switch is off — it can't tell which."],
["Grid frequency", R.grid_frequency, "Hz", "spec", "Utility frequency. 0 whenever no grid reaches the inverter."],
["Output voltage", R.ac_out_voltage, "V", "confirmed", "What the inverter feeds the house. Tracks its 230 V rating."],
["Output frequency", R.ac_out_frequency, "Hz", "confirmed", "Matches the 50 Hz rating."],
["Apparent power", R.ac_out_va, "VA", "confirmed", "Volts × amps, including the reactive part electronics draw. Always ≥ real power."],
["Real power", R.ac_out_w, "W", "confirmed", "The power actually doing work — what drains the battery."],
["Load percent", R.load_percent, "%", "confirmed", `Exactly floor(VA ÷ ${W(s.rated_va)} × 100) — based on VA, not watts.`],
["Bus voltage", R.bus_voltage, "V", "spec", "Internal DC link between battery side and AC side. Steady ~370 V is healthy."],
["Battery voltage", R.battery_voltage, "V", "confirmed", "At the battery terminals. The energy balance closes with it."],
["Battery charge current", R.battery_charge_current, "A", "confirmed", "Amps into the battery. Whole amps only, so ±27 W resolution."],
["Battery capacity", R.battery_capacity, "%", "confirmed", "State of charge. Agrees with the BMS's own figure."],
["Heatsink temperature", R.heatsink_temp, "°C", "confirmed", "Moves with load through the day. The health panel warns from 55 °C."],
["PV current", R.pv_current, "A", "confirmed", "Amps from the panels, in 0.1 A steps."],
["PV voltage", R.pv_voltage, "V", "confirmed", "Panel array voltage. Wanders when little light hits them."],
["SCC voltage", R.scc_voltage, "V", "unverified", "Battery voltage as the solar charger sees it. Reads 0 on some firmware."],
["Battery discharge current", R.battery_discharge_current, "A", "confirmed", "Amps leaving the battery."],
["Status bits", R.status_bits, "", "confirmed", "Eight on/off flags, decoded above. The charging bits flip with the charge current."],
["Fan voltage offset", R.fan_offset, "×10 mV", "spec", "Fan trim value."],
["EEPROM version", R.eeprom_version, "", "spec", "Settings-memory layout version."],
["PV charging power", R.pv_charging_power, "W", "confirmed", "Solar power reaching the battery after conversion losses — never above volts × amps."],
["Status bits 2", R.status_bits2, "", "spec", "Float mode, main switch, dustproof kit."],
["Feed to grid", R.feed_to_grid, "", "spec", "Grid export on/off. Only some firmware reports this."],
["Country regulation", R.country_regulation, "", "spec", "Grid code, only relevant when exporting."],
["Power fed to grid", R.feed_to_grid_power, "W", "spec", "Watts exported. Zero with export off."],
["Power factor", s.power_factor ?? "—", "", "derived", "Real ÷ apparent power. Low is normal for chargers and LEDs."],
["Inverter's own draw", s.overhead_w ?? "—", "W", "derived", "Solar + battery minus the house load: the inverter's electronics and losses."],
];
$("t-live").innerHTML = FIELDS.map(([label, val, unit, conf, desc]) =>
`<tr><td class="name">${label}<span class="conf ${conf}">${conf}</span></td>
<td class="val">${val ?? "—"} ${unit}</td><td class="desc">${desc}</td></tr>`).join("");
const g = s.slow || {}, r = g.rating || {}, b = g.bms || {};
const v = (o, k) => (o[k] ? `${o[k].pretty} ${o[k].unit}`.trim() : "—");
const drift = g.clock_drift_seconds;
const CFG = [
["Model", g.model || "—", "As the inverter reports itself (QMN)."],
["Serial · firmware", `${g.serial || "—"} · ${(g.firmware || "").replace("VERFW:", "")}`, "Some firmware returns 24 live fields instead of the usual 21; both work."],
["Output priority", v(r, "output_source_priority"), "Where the house gets power first."],
["Charger priority", v(r, "charger_source_priority"), "What's allowed to charge the battery. Solar first: solar charges first, and on grid the grid adds whatever solar can't supply."],
["Switch points (12 / 13 / 29)", s.config?.battery_return_percent ? `${s.config.battery_reserve_percent}% / ${s.config.battery_return_percent}% / ${s.config.battery_cutoff_percent}%` : "—",
"To grid / back to battery / blackout floor. Set on the screen — the inverter doesn't report these, so they're copied into config.json."],
["Battery type", v(r, "battery_type"), "With a lithium BMS link, the battery sets voltages and charge current itself."],
["Max charge current", v(r, "max_charge_current"), "Set by the BMS — it lowers this as the battery fills."],
["Stored bulk / float", `${v(r, "battery_bulk_voltage")} / ${v(r, "battery_float_voltage")}`, `Old stored values. In BMS mode the battery's own ${v(b, "bms_bulk_voltage") !== "—" ? (b.bms_bulk_voltage.value / 10).toFixed(1) + " V" : "values"} apply.`],
["Stored cut-off", v(r, "battery_under_voltage"), `Old stored value. The BMS's ${b.bms_cutoff_voltage ? (b.bms_cutoff_voltage.value / 10).toFixed(1) + " V" : ""} cut-off applies.`],
["BMS max discharge", v(b, "bms_max_discharge_current"), "How hard the battery lets you pull."],
["Lifetime solar", g.pv_total_wh ? (g.pv_total_wh / 1000).toFixed(1) + " kWh" : "—", "The inverter's own counter."],
["Lifetime used", g.load_total_wh ? (g.load_total_wh / 1000).toFixed(1) + " kWh" : "—", "The inverter's own counter."],
["Inverter clock", g.clock || "—", drift === undefined ? "" : Math.abs(drift) < 3600 ? "Correct." : `Off by ${fmtHours(Math.abs(drift) / 3600)}.`],
];
$("t-cfg").innerHTML = CFG.map(([label, val, desc]) =>
`<tr><td class="name">${label}</td><td class="val">${val}</td><td class="desc">${desc}</td></tr>`).join("");
if (!document.body.classList.contains("ready"))
requestAnimationFrame(() => requestAnimationFrame(() => document.body.classList.add("ready")));
$("footer").textContent = "All data stays on this computer" + (br ? ` · ESP32 ${br.version}, WiFi ${br.wifi_rssi} dBm, ${W(br.samples_ok)} readings stored on it` : "") + ".";
}
function freshness() {
if (!lastOk) return;
const age = Math.round((Date.now() - lastOk) / 1000);
$("updated").textContent = age < 3 ? "Updated just now" : `Updated ${age < 60 ? age + " s" : Math.round(age / 60) + " min"} ago`;
if (age > 30) $("conn-dot").className = "dot warn";
}
// ---- grid quality ----
let gqHours = 24;
function gqChart(el, b, key, lo, hi, band, fmt) {
const h = +el.getAttribute("viewBox").split(" ")[3], w = fit(el, h), pad = { l: 44, r: 8, t: 8, b: 20 };
const iw = w - pad.l - pad.r, ih = h - pad.t - pad.b, n = b.length;
const x = i => pad.l + (i + 0.5) / n * iw;
const y = v => pad.t + ih - (Math.max(lo, Math.min(hi, v)) - lo) / (hi - lo) * ih;
let g = `<rect x="${pad.l}" y="${y(band[1])}" width="${iw}" height="${y(band[0]) - y(band[1])}" fill="var(--good)" fill-opacity=".07"/>`;
for (let k = 0; k <= 4; k++) {
const val = lo + (hi - lo) * k / 4, yy = y(val);
g += `<line x1="${pad.l}" y1="${yy}" x2="${w - pad.r}" y2="${yy}" stroke="var(--line)"/>
<text x="${pad.l - 8}" y="${yy + 4}" text-anchor="end" font-size="11" fill="var(--faint)">${fmt(val)}</text>`;
}
// split into runs so gaps (grid off, no data) break the line
let runs = [], cur = [];
b.forEach((d, i) => { if (d[key] != null) cur.push(i); else if (cur.length) { runs.push(cur); cur = []; } });
if (cur.length) runs.push(cur);
for (const r of runs) {
if (r.length === 1) { g += `<circle cx="${x(r[0])}" cy="${y(b[r[0]][key])}" r="2" fill="var(--grid)"/>`; continue; }
const top = r.map(i => `${x(i).toFixed(1)},${y(b[i][key + "_max"]).toFixed(1)}`);
const bot = r.slice().reverse().map(i => `${x(i).toFixed(1)},${y(b[i][key + "_min"]).toFixed(1)}`);
g += `<polygon points="${top.join(" ")} ${bot.join(" ")}" fill="var(--grid)" fill-opacity=".16"/>
<polyline points="${r.map(i => `${x(i).toFixed(1)},${y(b[i][key]).toFixed(1)}`).join(" ")}" fill="none"
stroke="var(--grid)" stroke-width="1.8" stroke-linejoin="round"/>`;
}
g += timeAxis(b.map(d => d.t), pad, w, h);
el.innerHTML = g;
}
function gqOn(el, b) {
const h = 44, w = fit(el, h), pad = { l: 44, r: 8 }, iw = w - pad.l - pad.r, bw = iw / b.length;
el.innerHTML = b.map((d, i) => {
const fill = d.on == null ? "var(--soft)" : d.on >= 0.5 ? "var(--grid)" : "var(--bad)";
return `<rect x="${(pad.l + i * bw).toFixed(1)}" y="2" width="${(bw + 0.4).toFixed(1)}" height="20" fill="${fill}"
fill-opacity="${d.on == null ? 1 : d.on >= 0.5 ? 0.25 + 0.6 * d.on : 0.55}"><title>${d.t}: ${d.on == null ? "no data" : d.on >= 0.5 ? "grid on" : "grid off"}</title></rect>`;
}).join("") + `<text x="${pad.l - 8}" y="16" text-anchor="end" font-size="11" fill="var(--faint)">on</text>`
+ timeAxis(b.map(d => d.t), pad, w, h);
}
let lastState = null, day = null, gq = null;
// 24 h solar/house/battery charts, from the same 5-minute buckets as the grid report
function drawDay() {
if (!day) return;
const b = day.buckets, t = b.map(d => d.t), c = lastState?.config || {};
chart($("chart-power"), [{ data: b.map(d => d.solar ?? null), colour: "var(--solar)" },
{ data: b.map(d => d.load ?? null), colour: "var(--load)" }], null, t);
const line = (v, text) => (x, y, pad, w) =>
`<line x1="${pad.l}" x2="${w - pad.r}" y1="${y(v)}" y2="${y(v)}" stroke="var(--muted)" stroke-opacity=".5" stroke-dasharray="4 4"/>
<text x="${w - pad.r - 4}" y="${y(v) - 4}" text-anchor="end" font-size="11" fill="var(--muted)">${text}</text>`;
chart($("chart-soc"), [{ data: b.map(d => d.soc ?? null), colour: "var(--batt)",
marks: c.battery_reserve_percent ? [line(c.battery_reserve_percent, `below ${c.battery_reserve_percent}%: grid`),
line(c.battery_return_percent, `${c.battery_return_percent}%: back to battery`)] : [] }], 100, t);
$("soc-legend").innerHTML = "";
}
async function gqLoad() {
try {
if (gqHours !== 24) day = await (await fetch("/api/grid?hours=24")).json();
gq = await (await fetch(`/api/grid?hours=${gqHours}`)).json();
if (gqHours === 24) day = gq;
} catch { return; }
drawDay();
drawGrid();
}
function drawGrid() {
if (!gq) return;
const g = gq, b = g.buckets, f1 = v => v == null ? "—" : v.toFixed(1);
const stat = (big, small) => `<div><b>${big}</b><span>${small}</span></div>`;
$("gq-stats").innerHTML = [
stat(`${g.grid_on_h} h`, `grid on, of ${g.covered_h} h recorded`),
stat(g.cuts, g.cuts === 1 ? "cut" : "cuts"),
stat(g.longest_cut_h ? fmtHours(g.longest_cut_h) : "—", "longest cut"),
stat(g.v_min == null ? "—" : `${Math.round(g.v_min)}–${Math.round(g.v_max)} V`, `avg ${f1(g.v_avg)} V`),
stat(g.low_v_pct == null ? "—" : `${g.low_v_pct}%`, "time below 207 V"),
stat(g.hz_min == null ? "—" : `${g.hz_min.toFixed(1)}–${g.hz_max.toFixed(1)}`, "Hz range"),
].join("");
gqOn($("gq-on"), b);
const vs = b.flatMap(d => d.v_min != null ? [d.v_min, d.v_max] : []);
gqChart($("gq-v"), b, "v", Math.min(180, ...vs.map(v => Math.floor(v / 10) * 10)),
Math.max(260, ...vs.map(v => Math.ceil(v / 10) * 10)), [207, 253], v => Math.round(v));
// stretch to fit the real dips; a fixed 49–51 axis would flatten them
// span kept to 2 or 4 Hz so the four gridlines land on round numbers
const hzLo = Math.min(49, Math.floor(g.hz_min ?? 49)), hzHi = hzLo + (Math.max(51, Math.ceil(g.hz_max ?? 51)) - hzLo > 2 ? 4 : 2);
gqChart($("gq-hz"), b, "hz", hzLo, hzHi, [49.5, 50.5], v => v.toFixed(1));
$("gq-note").textContent = g.covered_h < g.hours * 0.9
? `Only ${g.covered_h} of the last ${g.hours} h are recorded so far. Frequency is logged from now on; gaps filled from the ESP32 have voltage but no Hz.`
: "Gaps filled from the ESP32 have voltage but no frequency.";
}
document.querySelectorAll("#gq-range button").forEach(btn => btn.onclick = () => {
document.querySelectorAll("#gq-range button").forEach(x => x.classList.toggle("on", x === btn));
gqHours = +btn.dataset.h; gqLoad();
});
gqLoad();
setInterval(gqLoad, 60000);
let resizeTimer;
addEventListener("resize", () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => {
drawDay(); drawGrid(); if (lastState) dayChart($("chart-days"), lastState.daily?.days || []); }, 150); });
async function tick() {
try {
render(await (await fetch("/api/state")).json());
} catch (e) {
$("conn-dot").className = "dot bad";
$("conn-text").innerHTML = "<b>Dashboard offline</b>";
}
freshness();
}
tick();
setInterval(tick, 5000);
setInterval(freshness, 1000);
</script>
</body>
</html>