-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
963 lines (876 loc) · 38.9 KB
/
Copy pathindex.html
File metadata and controls
963 lines (876 loc) · 38.9 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
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>CaffePeso</title>
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#197C28">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="CaffePeso">
<link rel="apple-touch-icon" href="/icon-maskable.png">
<link rel="stylesheet" href="/output.css">
<script src="/js/alpine.min.js" defer></script>
<script src="/chart.min.js"></script>
<link rel="stylesheet" href="/css/all.min.css">
<link rel="stylesheet" href="/css/theme.css">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@1,700&display=swap" rel="stylesheet" media="print" onload="this.media='all'">
<style>
.caffepeso-title {
font-family: 'Playfair Display', serif;
font-size: clamp(1rem, 2.5vmin, 1.8rem);
font-weight: 700;
font-style: italic;
color: #f5e9dc;
text-decoration: none;
}
</style>
<!-- RESPONSIVE LAYOUT CSS -->
<style>
html, body { overflow-x: hidden; max-width: 100%; }
/* Desktop: Your exact pixel control (768px and up) */
@media (min-width: 768px) {
.graph-container-responsive {
width: 700px !important;
height: 300px !important;
margin: 20px auto 0 auto !important;
}
.dashboard-container-responsive {
width: 700px !important;
margin: 8px auto 0 auto !important;
}
.graph-canvas-responsive {
width: 660px !important;
height: 260px !important;
}
}
/* Push content below the fixed mobile nav bar */
@media (max-width: 767px) {
.content-wrapper {
padding-top: 60px;
}
}
/* Mobile: all screens under 768px (phones + tablets in portrait) */
@media (max-width: 767px) {
.graph-container-responsive {
width: 95% !important;
height: 220px !important;
margin: 0 auto !important;
padding: 12px !important;
}
.dashboard-container-responsive {
width: 95% !important;
margin: 8px auto 0 auto !important;
padding: 12px !important;
}
.graph-canvas-responsive {
width: 100% !important;
height: 180px !important;
}
}
/* Mobile Landscape */
@media (max-width: 767px) and (orientation: landscape) {
.graph-container-responsive {
width: 90% !important;
height: 180px !important;
margin: 0 auto !important;
}
.graph-canvas-responsive {
width: 100% !important;
max-width: 420px !important;
height: 160px !important; /* Taller canvas for landscape */
}
.dashboard-container-responsive {
padding: 10px !important; /* Reduced padding to save space */
}
}
</style>
<style>
#toast { transition: opacity 0.3s ease; }
#shotTable th, #shotTable td { text-align: right; padding: 6px 10px; white-space: nowrap; }
#shotTable th:first-child, #shotTable td:first-child,
#shotTable th:nth-child(2), #shotTable td:nth-child(2) { text-align: left; }
</style>
</head>
<body class="bg-black-background text-white font-sans min-h-screen">
<div id="toast" style="position:fixed;bottom:1.5rem;left:50%;transform:translateX(-50%);opacity:0;pointer-events:none;z-index:9999;"
class="bg-gray-700 text-white text-sm px-5 py-2 rounded-full shadow-lg"></div>
<!-- Mobile Navigation (Hidden by default, shown on mobile) -->
<div @click.away="open = false" class="md:hidden fixed top-0 left-0 right-0 z-50 bg-black-discord" x-data="{ open: false }">
<div class="flex justify-between items-center px-4 py-3">
<a href="#" class="caffepeso-title">CaffePeso</a>
<button class="focus:outline-none" @click="open = !open">
<svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6">
<path x-show="!open" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path>
<path x-show="open" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
</svg>
</button>
</div>
<nav :class="{'block': open, 'hidden': !open}" class="px-4 pb-4 bg-black-discord">
<a class="block px-4 py-2 mt-2 text-sm font-semibold text-stone-50 bg-black-select rounded-lg" href="/"><i class="fa fa-tachometer mr-2" style="color: rgb(71, 168, 100);"></i>Dashboard</a>
<a class="block px-4 py-2 mt-2 text-sm font-semibold text-gray-400 bg-transparent rounded-lg hover:text-stone-50 hover:bg-black-hover" href="/calibration.html"><i class="fa fa-balance-scale mr-2" style="color: rgb(71, 168, 100);"></i>Calibration</a>
<a class="block px-4 py-2 mt-2 text-sm font-semibold text-gray-400 bg-transparent rounded-lg hover:text-stone-50 hover:bg-black-hover" href="/settings.html"><i class="fa fa-cogs mr-2" style="color: rgb(71, 168, 100);"></i>Settings</a>
<a class="block px-4 py-2 mt-2 text-sm font-semibold text-gray-400 bg-transparent rounded-lg hover:text-stone-50 hover:bg-black-hover" href="/history.html"><i class="fa fa-coffee mr-2" style="color: rgb(71, 168, 100);"></i>Shot Log</a>
<a class="block px-4 py-2 mt-2 text-sm font-semibold text-gray-400 bg-transparent rounded-lg hover:text-stone-50 hover:bg-black-hover" href="/updates.html"><i class="fa fa-upload mr-2" style="color: rgb(71, 168, 100);"></i>Updates</a>
</nav>
</div>
<!-- Desktop Navigation (Fixed sidebar) -->
<div class="hidden md:flex md:flex-col md:w-64 md:fixed md:left-0 md:top-0 md:h-full bg-black-discord">
<div class="px-8 py-4">
<a href="#" class="caffepeso-title">CaffePeso</a>
</div>
<nav class="flex-grow px-4 pb-4">
<a class="block px-4 py-2 mt-2 text-sm font-semibold text-stone-50 bg-black-select rounded-lg" href="/"><i class="fa fa-tachometer mr-2" style="color: rgb(71, 168, 100);"></i>Dashboard</a>
<a class="block px-4 py-2 mt-2 text-sm font-semibold text-gray-400 bg-transparent rounded-lg hover:text-stone-50 hover:bg-black-hover" href="/calibration.html"><i class="fa fa-balance-scale mr-2" style="color: rgb(71, 168, 100);"></i>Calibration</a>
<a class="block px-4 py-2 mt-2 text-sm font-semibold text-gray-400 bg-transparent rounded-lg hover:text-stone-50 hover:bg-black-hover" href="/settings.html"><i class="fa fa-cogs mr-2" style="color: rgb(71, 168, 100);"></i>Settings</a>
<a class="block px-4 py-2 mt-2 text-sm font-semibold text-gray-400 bg-transparent rounded-lg hover:text-stone-50 hover:bg-black-hover" href="/history.html"><i class="fa fa-coffee mr-2" style="color: rgb(71, 168, 100);"></i>Shot Log</a>
<a class="block px-4 py-2 mt-2 text-sm font-semibold text-gray-400 bg-transparent rounded-lg hover:text-stone-50 hover:bg-black-hover" href="/updates.html"><i class="fa fa-upload mr-2" style="color: rgb(71, 168, 100);"></i>Updates</a>
</nav>
</div>
<!-- Content Layout - Graph Above Main Container -->
<div class="flex flex-col content-wrapper">
<!-- GRAPH CONTAINER - RESPONSIVE DESIGN -->
<!-- Desktop: 400px×250px | Tablet: 350px×220px | Mobile: 95%×200px -->
<div style="width: 400px; height: 250px; padding: 20px; margin: 20px auto 0 280px;" class="graph-container-responsive bg-black-select rounded-xl">
<div style="width: 100%; height: 100%;" class="bg-gray-900 rounded-lg">
<!-- GRAPH CANVAS - RESPONSIVE SIZING -->
<!-- Desktop: 360×210px | Tablet: 310×180px | Mobile: 280×170px -->
<canvas id="weightFlowChart" width="360" height="210" class="graph-canvas-responsive" style="display: block !important; margin: auto; border: none !important; outline: none !important;"></canvas>
<div id="chartError" class="hidden text-center text-gray-400 text-sm pt-32">
Chart loading...
</div>
</div>
</div>
<!-- DASHBOARD CONTAINER - RESPONSIVE DESIGN -->
<!-- Desktop: 700px | Tablet: 90% | Mobile: 95% -->
<div style="width: 700px; padding: 20px; margin: 8px auto 0 280px;" class="dashboard-container-responsive bg-black-select rounded-xl space-y-4">
<!-- Header with Title and Icons -->
<div class="flex justify-between items-center">
<h1 class="text-xl font-semibold">Dashboard</h1>
<div class="flex items-center" style="gap: 12px;">
<!-- WiFi signal strength indicator -->
<div id="wifiStatus" class="flex items-center" title="WiFi Signal Strength">
<i id="wifiIcon" class="fa fa-wifi" style="font-size: 14px; color: #9ca3af;"></i>
<span id="wifiSignalText" class="text-xs ml-1" style="color: #9ca3af;">-</span>
</div>
<!-- Bluetooth signal strength indicator -->
<div id="bluetoothSignalStatus" class="flex items-center" title="Bluetooth Connection Status">
<i id="bluetoothIcon" class="fa fa-bluetooth" style="font-size: 14px; color: #9ca3af;"></i>
</div>
<!-- Scale connection status -->
<div class="flex items-center" title="Scale Status">
<i id="scaleStatus" class="fa fa-balance-scale" style="font-size: 14px; color: #22c55e;"></i>
</div>
<!-- Phone-style battery indicator -->
<div id="batteryStatus" class="flex items-center space-x-1">
<!-- Battery icon with Font Awesome as backup -->
<i class="fa fa-battery-three-quarters" id="batteryIconFA" style="font-size: 14px; color: #22c55e; display: none;"></i>
<!-- Custom SVG battery icon (primary) -->
<svg class="w-6 h-3" viewBox="0 0 24 12" fill="none">
<!-- Battery body -->
<rect x="1" y="2" width="20" height="8" rx="1" stroke="currentColor" stroke-width="1" fill="none"/>
<!-- Battery tip -->
<rect x="21.5" y="4" width="1.5" height="4" rx="0.5" fill="currentColor"/>
<!-- Battery segments (filled based on battery level) -->
<rect id="batterySegment1" x="2" y="3" width="4" height="6" rx="0.5" fill="currentColor"/>
<rect id="batterySegment2" x="7" y="3" width="4" height="6" rx="0.5" fill="currentColor"/>
<rect id="batterySegment3" x="12" y="3" width="4" height="6" rx="0.5" fill="currentColor"/>
<rect id="batterySegment4" x="17" y="3" width="3" height="6" rx="0.5" fill="currentColor"/>
</svg>
<span id="batteryPercentage" class="text-sm font-medium">100%</span>
</div>
</div>
</div>
<!-- Compact Metrics Grid -->
<div class="grid grid-cols-3 text-center text-base font-medium">
<div>
<div id="weight" class="text-2xl font-bold">0.0</div>
<div class="text-xs text-gray-300">Weight<br/><span class="text-xs">g</span></div>
</div>
<div>
<div id="flowrate" class="text-2xl font-bold">0.000</div>
<div class="text-xs text-gray-300">Flow Rate<br/><span class="text-xs">g/s</span></div>
</div>
<div>
<div id="timer" class="text-2xl font-bold">0:00.000</div>
<div class="text-xs text-gray-300">Time</div>
</div>
</div>
<!-- Timer Status -->
<div class="text-center">
<p class="text-sm text-gray-400" id="timerStatus">Stopped</p>
<p class="text-sm text-amber-400 font-semibold" id="armedIndicator" style="display:none;">● Armed — waiting for drip</p>
<p class="text-sm text-blue-400" id="avgFlowRate" style="display: none;"></p>
<p class="text-sm text-green-400" id="brewRatio" style="visibility: hidden;"> </p>
</div>
<!-- Dose + Cup weight entries -->
<div class="inline-grid gap-x-2 gap-y-2 mx-auto" style="grid-template-columns: auto auto auto auto;">
<label class="text-sm text-gray-400 self-center text-right">Dose:</label>
<input type="number" id="doseInput" step="0.1" min="0" max="100" placeholder="g"
class="w-20 px-2 py-1 rounded text-black text-sm" />
<button onclick="saveDose()" class="bg-gray-600 hover:bg-button-green active:bg-green-900 text-white px-3 py-1 rounded text-sm">Set</button>
<span id="doseMessage" class="text-xs text-green-400 self-center"></span>
<label class="text-sm text-gray-400 self-center text-right">Cup:</label>
<input type="number" id="cupWeightInput" step="0.1" min="5" max="500" placeholder="g"
class="w-20 px-2 py-1 rounded text-black text-sm" />
<button onclick="saveCupWeight()" class="bg-gray-600 hover:bg-button-green active:bg-green-900 text-white px-3 py-1 rounded text-sm">Set</button>
<span id="cupWeightMessage" class="text-xs text-green-400 self-center"></span>
</div>
<p id="doseHint" class="text-xs text-amber-400 text-center mt-1" style="display:none;">Set dose for live ratio & shot history</p>
<p id="cupWeightHint" class="text-xs text-amber-400 text-center mt-1" style="display:none;">Set cup weight to enable auto re-arm</p>
<!-- Action Buttons -->
<div class="grid grid-cols-2 gap-2 mt-2">
<button onclick="tareScale()" class="bg-gray-700 hover:bg-gray-600 py-2 rounded-lg text-sm font-semibold">
Tare
</button>
<button id="armBtn" onclick="toggleArm()" class="text-white font-bold py-2 rounded-lg text-sm" style="background:#15803d;">
Arm
</button>
<button onclick="stopTimer()" class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 rounded-lg text-sm">
<i class="fa fa-stop mr-1"></i>Stop
</button>
<button onclick="resetTimer()" class="bg-yellow-600 hover:bg-yellow-700 text-white font-bold py-2 rounded-lg text-sm">
<i class="fa fa-undo mr-1"></i>Reset
</button>
</div>
<!-- Last Shot -->
<div class="mt-4">
<div class="flex justify-between items-center mb-2">
<h2 class="text-sm font-semibold text-gray-300">Last Shot</h2>
<a href="/history.html" class="text-xs text-gray-500 hover:text-gray-300">View Shot Log ›</a>
</div>
<div id="shotHistoryContainer">
<p class="text-xs text-gray-500 text-center" id="noShotsMsg">No shots recorded yet</p>
<table id="shotTable" class="w-full text-sm" style="display:none; border-collapse:collapse;">
<thead>
<tr class="text-gray-400 border-b border-gray-700">
<th class="py-1 text-left">#</th>
<th class="py-1 text-left">When</th>
<th class="py-1 text-right">Dose</th>
<th class="py-1 text-right">Yield</th>
<th class="py-1 text-right">Time</th>
<th class="py-1 text-right">Ratio</th>
</tr>
</thead>
<tbody id="shotTableBody"></tbody>
</table>
</div>
</div>
<!-- Status -->
<div class="text-center">
</div>
<p class="text-center text-xs mt-2 mb-2" style="color:#6b5f5f;">Based on <a href="https://github.com/031devstudios/weighmybru2" style="color:#a08880;">WeighMyBru²</a> by 031devstudios — <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" style="color:#a08880;">CC BY-NC-SA 4.0</a></p>
</div>
</div>
<script>
let decimalPlaces = 1;
// Load persisted dose weight on startup
fetch('/api/dose').then(r => r.json()).then(d => {
if (d.dose_weight > 0) {
document.getElementById('doseInput').value = d.dose_weight;
} else {
document.getElementById('doseHint').style.display = 'block';
}
}).catch(() => {});
// Load persisted cup weight on startup
fetch('/api/cup-weight').then(r => r.json()).then(d => {
if (d.cup_weight > 0) {
document.getElementById('cupWeightInput').value = d.cup_weight;
} else {
document.getElementById('cupWeightHint').style.display = 'block';
}
}).catch(() => {});
async function saveCupWeight() {
const val = document.getElementById('cupWeightInput').value;
const msg = document.getElementById('cupWeightMessage');
try {
await fetch('/api/cup-weight', { method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'weight=' + val });
msg.textContent = '✓';
document.getElementById('cupWeightHint').style.display = parseFloat(val) > 0 ? 'none' : 'block';
setTimeout(() => { msg.textContent = ''; }, 2000);
} catch(e) { msg.textContent = '✗'; }
}
async function toggleArm() {
const btn = document.getElementById('armBtn');
const armed = btn.dataset.armed === 'true';
await fetch(armed ? '/api/disarm' : '/api/arm', { method: 'POST' }).catch(() => {});
}
async function saveDose() {
const val = document.getElementById('doseInput').value;
const msg = document.getElementById('doseMessage');
try {
await fetch('/api/dose', { method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'dose_weight=' + val });
msg.textContent = '✓';
document.getElementById('doseHint').style.display = parseFloat(val) > 0 ? 'none' : 'block';
setTimeout(() => { msg.textContent = ''; }, 2000);
} catch(e) { msg.textContent = '✗'; }
}
// Chart.js configuration and data
let weightFlowChart;
let chartData = {
weight: [],
flowrate: [],
time: []
};
let maxDataPoints = 1200; // Keep last 1200 data points (2 minutes at 10Hz)
// Graph recording control - follows timer state
let isGraphRecording = false;
let previousTimerElapsed = 0;
// Initialize Chart.js when page loads
function initializeChart() {
console.log('Initializing chart...');
// Check if Chart.js is loaded
if (typeof Chart === 'undefined') {
console.error('Chart.js not loaded!');
return;
}
const canvas = document.getElementById('weightFlowChart');
if (!canvas) {
console.error('Chart canvas not found!');
return;
}
console.log('Canvas found, creating chart...');
const ctx = canvas.getContext('2d');
try {
weightFlowChart = new Chart(ctx, {
type: 'line',
data: {
labels: [], // Time labels
datasets: [{
label: 'Weight (g)',
data: [],
borderColor: '#22c55e', // Green for weight
backgroundColor: 'rgba(34, 197, 94, 0.1)',
borderWidth: 2,
fill: false,
yAxisID: 'y',
pointRadius: 0, // No points for smoother look
tension: 0.1 // Slight curve for smooth line
}, {
label: 'Flow Rate (g/s)',
data: [],
borderColor: '#3b82f6', // Blue for flow rate
backgroundColor: 'rgba(59, 130, 246, 0.1)',
borderWidth: 2,
fill: false,
yAxisID: 'y1',
pointRadius: 0, // No points for smoother look
tension: 0.1 // Slight curve for smooth line
}]
},
options: {
responsive: false,
maintainAspectRatio: false,
layout: {
padding: 5
},
interaction: {
intersect: false,
mode: 'index'
},
plugins: {
legend: {
display: true,
position: 'top',
labels: {
color: '#d1d5db', // Light gray text
font: {
size: 14,
weight: 'bold'
},
usePointStyle: true,
pointStyle: 'line',
padding: 20
}
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0.8)',
titleColor: '#ffffff',
bodyColor: '#ffffff',
borderColor: '#374151',
borderWidth: 1
}
},
scales: {
x: {
display: true,
title: {
display: false
},
grid: {
color: '#374151'
},
ticks: {
color: '#9ca3af',
font: {
size: 12
},
maxTicksLimit: 10
}
},
y: {
type: 'linear',
display: true,
position: 'left',
title: {
display: true,
text: 'Weight (g)',
color: '#22c55e',
font: {
size: 14,
weight: 'bold'
}
},
grid: {
color: '#374151'
},
ticks: {
color: '#22c55e',
font: {
size: 12,
weight: 'bold'
}
}
},
y1: {
type: 'linear',
display: true,
position: 'right',
title: {
display: true,
text: 'Flow Rate (g/s)',
color: '#3b82f6',
font: {
size: 14,
weight: 'bold'
}
},
grid: {
drawOnChartArea: false
},
ticks: {
color: '#3b82f6',
font: {
size: 12,
weight: 'bold'
}
}
}
},
animation: {
duration: 0 // Disable animations for real-time updates
}
}
});
// Responsive canvas sizing function - simplified to work with CSS
function updateCanvasSize() {
const canvas = document.getElementById('weightFlowChart');
if (!canvas) return;
const screenWidth = window.innerWidth;
// Force chart to resize and let CSS handle the container sizing
if (weightFlowChart) {
weightFlowChart.resize();
console.log('Chart resized for screen width:', screenWidth);
}
}
// Force chart to use container size and setup responsive behavior
if (weightFlowChart) {
setTimeout(() => {
updateCanvasSize();
// Listen for multiple resize and orientation events
window.addEventListener('resize', () => {
console.log('Window resize detected');
setTimeout(updateCanvasSize, 100); // Small delay for orientation changes
});
// Listen specifically for orientation changes
window.addEventListener('orientationchange', () => {
console.log('Orientation change detected');
setTimeout(updateCanvasSize, 200); // Longer delay for orientation
});
// Screen orientation API if available
if (screen.orientation) {
screen.orientation.addEventListener('change', () => {
console.log('Screen orientation API change detected');
setTimeout(updateCanvasSize, 200);
});
}
}, 100);
}
console.log('Chart created successfully!');
} catch (error) {
console.error('Error creating chart:', error);
}
}
// Try to initialize chart when DOM is ready
document.addEventListener('DOMContentLoaded', initializeChart);
// Fallback: try again after a short delay if first attempt fails
setTimeout(function() {
if (!weightFlowChart) {
console.log('Chart not initialized, trying again...');
initializeChart();
}
}, 1000);
// Show error if chart still not working after 3 seconds
setTimeout(function() {
if (!weightFlowChart) {
console.error('Chart failed to initialize after multiple attempts');
const errorDiv = document.getElementById('chartError');
if (errorDiv) {
errorDiv.textContent = 'Chart loading failed. Check console for errors.';
errorDiv.classList.remove('hidden');
document.getElementById('weightFlowChart').style.display = 'none';
}
}
}, 3000);
// Function to clear chart data
function clearChartData() {
try {
// Clear all data arrays
chartData.weight = [];
chartData.flowrate = [];
chartData.time = [];
// Update chart to show empty state
if (weightFlowChart) {
weightFlowChart.data.labels = [];
weightFlowChart.data.datasets[0].data = [];
weightFlowChart.data.datasets[1].data = [];
weightFlowChart.update('none');
console.log('Chart data cleared');
}
} catch (error) {
console.error('Error clearing chart data:', error);
}
}
// Function to add data to chart
function addChartData(weight, flowrate, timestamp) {
// Only add data to chart if graph is recording (timer is running)
if (!isGraphRecording) {
return; // Exit early if not recording
}
try {
const timeLabel = new Date(timestamp).toLocaleTimeString('en-US', {
hour12: false,
minute: '2-digit',
second: '2-digit'
});
// Add new data
chartData.weight.push(weight);
chartData.flowrate.push(flowrate);
chartData.time.push(timeLabel);
// Remove old data if we have too many points
if (chartData.weight.length > maxDataPoints) {
chartData.weight.shift();
chartData.flowrate.shift();
chartData.time.shift();
}
// Update chart
if (weightFlowChart) {
weightFlowChart.data.labels = [...chartData.time];
weightFlowChart.data.datasets[0].data = [...chartData.weight];
weightFlowChart.data.datasets[1].data = [...chartData.flowrate];
weightFlowChart.update('none'); // No animation for smooth real-time updates
} else {
console.log('Chart not initialized yet, data:', weight, flowrate);
}
} catch (error) {
console.error('Error updating chart data:', error);
}
}
function showToast(msg, duration = 2000) {
const t = document.getElementById('toast');
t.textContent = msg;
t.style.opacity = '1';
clearTimeout(t._timer);
t._timer = setTimeout(() => { t.style.opacity = '0'; }, duration);
}
function tareScale() {
fetch('/api/tare', { method: 'POST' })
.then(response => response.text())
.then(() => {
showToast('Scale tared');
document.getElementById('avgFlowRate').style.display = 'none';
})
.catch(() => showToast('Tare failed'));
}
function startTimer() {
fetch('/api/timer/start', { method: 'POST' })
.then(response => response.text())
.then(data => {
console.log("Timer started:", data);
// Start graph recording when timer starts
isGraphRecording = true;
console.log("Graph recording started");
})
.catch(err => console.error("Timer start failed:", err));
}
function stopTimer() {
fetch('/api/timer/stop', { method: 'POST' })
.then(response => response.text())
.then(data => {
console.log("Timer stopped:", data);
// Stop graph recording when timer stops
isGraphRecording = false;
console.log("Graph recording stopped");
})
.catch(err => console.error("Timer stop failed:", err));
}
function resetTimer() {
fetch('/api/timer/reset', { method: 'POST' })
.then(response => response.text())
.then(data => {
console.log("Timer reset:", data);
// Reset graph when timer resets
isGraphRecording = false;
clearChartData();
console.log("Graph cleared and recording stopped");
})
.catch(err => console.error("Timer reset failed:", err));
}
function updateWeight() {
// Use combined endpoint for better performance
fetch('/api/dashboard')
.then(response => response.json())
.then(data => {
let weight = parseFloat(data.weight);
let flowrate = parseFloat(data.flowrate);
if (isNaN(weight)) weight = 0;
if (isNaN(flowrate)) flowrate = 0;
document.getElementById('weight').innerText = weight.toFixed(decimalPlaces);
document.getElementById('flowrate').innerText = flowrate.toFixed(1);
// Add data to real-time chart
addChartData(weight, flowrate, Date.now());
// Update scale connection status
const scaleStatus = document.getElementById('scaleStatus');
if (data.scale_connected) {
scaleStatus.style.color = '#22c55e';
scaleStatus.parentElement.title = 'Scale Connected';
} else {
scaleStatus.style.color = '#ef4444';
scaleStatus.parentElement.title = 'Scale Disconnected';
}
// Update battery status indicator
if (data.battery_percentage !== undefined) {
const batteryPercentage = document.getElementById('batteryPercentage');
const batteryStatus = document.getElementById('batteryStatus');
const segment1 = document.getElementById('batterySegment1');
const segment2 = document.getElementById('batterySegment2');
const segment3 = document.getElementById('batterySegment3');
const segment4 = document.getElementById('batterySegment4');
batteryPercentage.innerText = data.battery_percentage + '%';
// Calculate segments based on percentage (0-4 segments)
let activeSegments = 0;
if (data.battery_percentage >= 25) activeSegments = 1;
if (data.battery_percentage >= 50) activeSegments = 2;
if (data.battery_percentage >= 75) activeSegments = 3;
if (data.battery_percentage >= 90) activeSegments = 4;
// Update segments visibility with smooth fade
segment1.style.opacity = activeSegments >= 1 ? '1' : '0.3';
segment2.style.opacity = activeSegments >= 2 ? '1' : '0.3';
segment3.style.opacity = activeSegments >= 3 ? '1' : '0.3';
segment4.style.opacity = activeSegments >= 4 ? '1' : '0.3';
// Color code based on battery level
let batteryColor = '#22c55e'; // green
if (data.battery_critical) {
batteryColor = '#ef4444'; // red
} else if (data.battery_low) {
batteryColor = '#f59e0b'; // orange/yellow
}
// Apply color to battery elements
batteryStatus.style.color = batteryColor;
segment1.style.fill = activeSegments >= 1 ? batteryColor : 'rgba(107, 114, 128, 0.5)';
segment2.style.fill = activeSegments >= 2 ? batteryColor : 'rgba(107, 114, 128, 0.5)';
segment3.style.fill = activeSegments >= 3 ? batteryColor : 'rgba(107, 114, 128, 0.5)';
segment4.style.fill = activeSegments >= 4 ? batteryColor : 'rgba(107, 114, 128, 0.5)';
}
// Update signal strength indicators
updateSignalStrength(data);
// Update timer display
if (data.timer_display) {
document.getElementById('timer').innerText = data.timer_display;
document.getElementById('timerStatus').innerText = data.timer_running ? 'Running' : 'Stopped';
// Sync graph recording state with server timer state
const previousRecordingState = isGraphRecording;
isGraphRecording = data.timer_running;
if (previousRecordingState !== isGraphRecording) {
console.log(`Graph recording ${isGraphRecording ? 'started' : 'stopped'} (synced with server timer)`);
}
// Detect device-side timer reset (re-arm, idle reset, manual reset from device).
// timer_elapsed going from non-zero to zero is the unambiguous reset signal,
// regardless of running/paused state.
if (previousTimerElapsed > 0 && data.timer_elapsed === 0) {
clearChartData();
console.log('Graph cleared on device-side timer reset');
}
previousTimerElapsed = data.timer_elapsed;
// Color code timer based on status
const timerElement = document.getElementById('timer');
timerElement.className = 'text-3xl font-bold ' + (data.timer_running ? 'text-green-400' : 'text-white');
// Show timer average flow rate when timer is stopped and average is available
const avgFlowRateElement = document.getElementById('avgFlowRate');
if (!data.timer_running && data.timer_avg_flowrate !== null && data.timer_avg_flowrate > 0) {
avgFlowRateElement.innerText = `Avg Flow Rate: ${data.timer_avg_flowrate.toFixed(2)} g/s`;
avgFlowRateElement.style.display = 'block';
} else {
avgFlowRateElement.style.display = 'none';
}
// Sync dose and cup weight fields from device (skip if field has focus)
const doseEl = document.getElementById('doseInput');
if (document.activeElement !== doseEl && data.dose_weight !== undefined) {
const serverDose = parseFloat(data.dose_weight);
if (serverDose > 0) {
doseEl.value = serverDose;
document.getElementById('doseHint').style.display = 'none';
}
}
const cupEl = document.getElementById('cupWeightInput');
if (document.activeElement !== cupEl && data.cup_weight !== undefined) {
const serverCup = parseFloat(data.cup_weight);
if (serverCup > 0) {
cupEl.value = serverCup;
document.getElementById('cupWeightHint').style.display = 'none';
}
}
// Show brew ratio when timer is stopped and dose is set
const ratioEl = document.getElementById('brewRatio');
const dose = parseFloat(data.dose_weight) || parseFloat(doseEl.value) || 0;
const yieldW = parseFloat(data.weight);
if (!data.timer_running && dose > 0 && yieldW > 5) {
ratioEl.innerText = `Ratio: 1:${(yieldW / dose).toFixed(1)} (${dose.toFixed(1)}g → ${yieldW.toFixed(1)}g)`;
ratioEl.style.visibility = 'visible';
} else {
ratioEl.style.visibility = 'hidden';
}
// Target yield alert: turn weight amber when approaching target
const weightEl = document.getElementById('weight');
const targetRatio = parseFloat(data.target_ratio || 0);
if (data.timer_running && dose > 0 && targetRatio > 0) {
const alertThreshold = dose * targetRatio - 2;
weightEl.style.color = weight >= alertThreshold ? '#f59e0b' : '';
} else {
weightEl.style.color = '';
}
// Armed indicator and Arm button state
const armedEl = document.getElementById('armedIndicator');
if (armedEl) armedEl.style.display = data.armed ? 'block' : 'none';
const armBtn = document.getElementById('armBtn');
if (armBtn) {
armBtn.dataset.armed = data.armed ? 'true' : 'false';
if (data.armed) {
armBtn.textContent = 'Disarm';
armBtn.style.background = '#d97706';
} else {
armBtn.textContent = 'Arm';
armBtn.style.background = '#15803d';
}
}
}
})
.catch(err => console.error("Dashboard fetch error:", err));
}
let updateTimer = setInterval(updateWeight, 100);
updateWeight();
// Shot history
let lastShotNum = -1;
function renderShotHistory(shots) {
const table = document.getElementById('shotTable');
const noMsg = document.getElementById('noShotsMsg');
const tbody = document.getElementById('shotTableBody');
if (!shots || shots.length === 0) {
table.style.display = 'none';
noMsg.style.display = 'block';
return;
}
noMsg.style.display = 'none';
table.style.display = 'table';
const s = shots[0]; // most recent only
const d = s.ts ? new Date(s.ts * 1000) : null;
const when = d
? `${d.toLocaleDateString(undefined,{day:'numeric',month:'short',year:'2-digit'})}<br>${d.toLocaleTimeString(undefined,{hour:'2-digit',minute:'2-digit'})}`
: '—';
tbody.innerHTML = `<tr class="border-b border-gray-800">
<td class="py-1 text-gray-400">#${s.shot}</td>
<td class="date-col text-gray-300 leading-tight">${when}</td>
<td class="py-1 text-right">${s.dose}g</td>
<td class="py-1 text-right">${s.yield}g</td>
<td class="py-1 text-right">${s.time}s</td>
<td class="py-1 text-right">1:${s.ratio}</td>
</tr>`;
lastShotNum = s.shot;
}
function loadShotHistory() {
fetch('/api/shot-history').then(r => r.json()).then(renderShotHistory).catch(() => {});
}
function clearShotHistory() {
fetch('/api/shot-history', { method: 'DELETE' })
.then(() => { renderShotHistory([]); showToast('Shot history cleared'); })
.catch(() => showToast('Clear failed'));
}
loadShotHistory();
// Refresh shot history when timer stops (detect transition)
let prevTimerRunningForShots = false;
const origUpdateWeight = updateWeight;
// Patch updateWeight to also check for timer stop (shot saved)
setInterval(() => {
fetch('/api/shot-history').then(r => r.json()).then(shots => {
if (shots && shots.length > 0 && shots[0].shot !== lastShotNum) renderShotHistory(shots);
}).catch(() => {});
}, 5000); // poll every 5s for new shots
// Signal strength update function
function updateSignalStrength(data) {
// Update WiFi icon and signal display in header
const wifiIcon = document.getElementById('wifiIcon');
const wifiSignalText = document.getElementById('wifiSignalText');
if (data.wifi_signal_strength !== undefined && data.wifi_signal_quality !== undefined) {
const signalStrength = data.wifi_signal_strength;
const signalQuality = data.wifi_signal_quality;
// Color code WiFi icon based on signal strength
let wifiColor = '#9ca3af'; // Default grey
if (signalStrength >= -50) {
wifiColor = '#22c55e'; // Green - Excellent/Very Good
} else if (signalStrength >= -70) {
wifiColor = '#f59e0b'; // Orange - Good/Fair
} else if (signalStrength >= -80) {
wifiColor = '#ef4444'; // Red - Weak
}
wifiIcon.style.color = wifiColor;
wifiSignalText.style.color = wifiColor;
wifiSignalText.textContent = signalStrength + 'dBm';
} else {
wifiIcon.style.color = '#9ca3af';
wifiSignalText.style.color = '#9ca3af';
wifiSignalText.textContent = 'Off';
}
// Update Bluetooth signal display in header
const bluetoothIcon = document.getElementById('bluetoothIcon');
if (data.bluetooth_connected) {
// Connected - make it blue
bluetoothIcon.style.color = '#3b82f6'; // Blue
} else {
// Disconnected - make it grey
bluetoothIcon.style.color = '#9ca3af'; // Grey
}
}
// Load decimal setting once (no need to poll this frequently)
fetch('/api/decimal-setting')
.then(response => response.json())
.then(data => {
if (typeof data.decimals !== 'undefined') {
decimalPlaces = parseInt(data.decimals);
} else {
decimalPlaces = 1;
}
})
.catch(err => {
console.error("Decimal setting fetch error:", err);
decimalPlaces = 1; // fallback
});
</script>
</body>
</html>