-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
893 lines (797 loc) · 33.5 KB
/
Copy pathscript.js
File metadata and controls
893 lines (797 loc) · 33.5 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
/* ================================================================
PLANTCARE PRO — script.js
ESP32 soil monitor
================================================================ */
'use strict';
const DB = {
get : (k, fb = null) => { try { const v = localStorage.getItem(k); return v !== null ? JSON.parse(v) : fb; } catch { return fb; } },
set : (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} },
push : (k, v, max = 200) => {
const a = DB.get(k, []);
a.push(v);
if (a.length > max) a.splice(0, a.length - max);
DB.set(k, a);
},
};
/* ── CONSTANTS ──────────────────────────────────────── */
const ESP_URL = 'http://soilmonitor.local/data';
const POLL_INTERVAL = 10_000; // ms
const WEATHER_LAT = 13.0827; // Chennai — change to your city
const WEATHER_LON = 80.2707;
/* ── STATE ──────────────────────────────────────────── */
let lastMoisture = null;
let realtimeChart = null;
let hourlyChart = null;
/* ================================================================
BOOT
================================================================ */
document.addEventListener('DOMContentLoaded', () => {
if (DB.get('loggedIn')) bootApp();
// Enter-key shortcut on login form
document.getElementById('lp').addEventListener('keydown', e => { if (e.key === 'Enter') doLogin(); });
document.getElementById('lu').addEventListener('keydown', e => { if (e.key === 'Enter') document.getElementById('lp').focus(); });
});
/* ================================================================
AUTH
================================================================ */
function doLogin() {
const u = document.getElementById('lu').value.trim();
const p = document.getElementById('lp').value;
if (!u) { toast('Error', 'Please enter a username', 'td', '⚠️'); return; }
const stored = DB.get('passwd');
if (stored && stored !== p) { toast('Error', 'Incorrect password', 'td', '🔒'); return; }
if (!stored) DB.set('passwd', p || '');
DB.set('loggedIn', true);
DB.set('username', u);
bootApp();
}
function doLogout() {
DB.set('loggedIn', false);
location.reload();
}
/* ================================================================
APP BOOT
================================================================ */
function bootApp() {
document.getElementById('login-page').style.display = 'none';
document.getElementById('app').style.display = 'block';
const u = DB.get('username', 'User');
const name = u.charAt(0).toUpperCase() + u.slice(1);
document.getElementById('nav-uname').textContent = name;
document.getElementById('dd-name').textContent = name;
// Restore saved avatar
const photo = DB.get('profilePhoto');
if (photo) {
document.getElementById('nav-avatar').src = photo;
document.getElementById('photo-preview').src = photo;
}
setDateBadge();
loadPlantName();
loadLastWatered();
fetchWeather();
startESPPolling();
buildPlantsPage();
buildTrackerCharts();
renderWateringLog();
renderBell();
checkNotificationPermission();
setInterval(fetchWeather, 5 * 60_000); // refresh weather every 5 min
}
/* ── DATE BADGE ─────────────────────────────────────── */
function setDateBadge() {
const s = new Date().toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
document.getElementById('date-badge').textContent = s;
}
/* ================================================================
PLANT NAME
================================================================ */
function loadPlantName() {
const saved = DB.get('plantName');
if (saved) document.getElementById('plant-name').innerHTML = saved;
}
function toggleEditName() {
const p = document.getElementById('edit-name-panel');
p.classList.toggle('open');
if (p.classList.contains('open')) {
const cur = document.getElementById('plant-name').textContent.replace('\n', ' ').trim();
document.getElementById('name-input').value = cur;
document.getElementById('name-input').focus();
}
}
function saveName() {
const v = document.getElementById('name-input').value.trim();
if (!v) return;
DB.set('plantName', v);
document.getElementById('plant-name').textContent = v;
document.getElementById('edit-name-panel').classList.remove('open');
toast('Saved', 'Plant name updated', 'ts', '🌿');
}
/* ================================================================
LAST WATERED BADGE
================================================================ */
function loadLastWatered() {
const ts = DB.get('lastWatered');
const el = document.getElementById('last-w-badge');
if (!ts) { el.textContent = '💧 Not recorded yet'; return; }
const hrs = Math.round((Date.now() - ts) / 3_600_000);
el.textContent = hrs < 24
? `💧 Watered ${hrs}h ago`
: `💧 Watered ${Math.floor(hrs / 24)}d ago`;
}
async function fetchWeather() {
try {
const url =
`https://api.open-meteo.com/v1/forecast` +
`?latitude=${WEATHER_LAT}&longitude=${WEATHER_LON}` +
`¤t=temperature_2m,relative_humidity_2m,apparent_temperature,weather_code` +
`&forecast_days=1&timezone=auto`;
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const d = await res.json();
const c = d.current;
const T = Math.round(c.temperature_2m);
const FL = Math.round(c.apparent_temperature);
const RH = c.relative_humidity_2m;
// Update home page
document.getElementById('wx-temp').innerHTML = `${T}<small>°C</small>`;
document.getElementById('wx-feels').textContent = `Feels like ${FL}°C`;
document.getElementById('wx-hum').innerHTML = `${RH}<small>%</small>`;
// Update navbar pill
document.getElementById('nav-temp').textContent = `${T}°C`;
document.getElementById('nav-hum').textContent = `${RH}%`;
// Cache for offline fallback
DB.set('wx', { T, FL, RH, ts: Date.now() });
// Recompute derived math now that weather is fresh
runMath();
console.log('✅ Weather fetched', { T, FL, RH });
} catch (err) {
console.error('⚠️ Weather fetch failed:', err.message);
// Use cached values if available
const cached = DB.get('wx');
if (cached) {
document.getElementById('wx-temp').innerHTML = `${cached.T}<small>°C</small>`;
document.getElementById('wx-feels').textContent = `Feels like ${cached.FL}°C`;
document.getElementById('wx-hum').innerHTML = `${cached.RH}<small>%</small>`;
document.getElementById('nav-temp').textContent = `${cached.T}°C`;
document.getElementById('nav-hum').textContent = `${cached.RH}%`;
}
runMath();
}
}
/* ================================================================
ESP32 POLLING
================================================================ */
function startESPPolling() {
pollESP32();
setInterval(pollESP32, POLL_INTERVAL);
}
async function pollESP32() {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 4000);
const res = await fetch(ESP_URL, { signal: controller.signal });
clearTimeout(timeout);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
const m = Math.min(100, Math.max(0, Math.round(data.moisture)));
setConnStatus(true);
handleMoisture(m);
} catch {
setConnStatus(false);
// No data — leave display as-is, don't fabricate readings
}
}
function setConnStatus(ok) {
const dot = document.getElementById('conn-dot');
const txt = document.getElementById('conn-txt');
dot.className = 'conn-dot ' + (ok ? 'ok' : 'err');
txt.textContent = ok ? 'ESP32 Connected' : 'Sensor Offline';
}
/* ================================================================
MOISTURE HANDLING
================================================================ */
function handleMoisture(m) {
// ── Detect automatic watering event (spike > 15%) ──
if (lastMoisture !== null && m - lastMoisture > 15) {
recordWateringEvent('auto', lastMoisture, m);
}
lastMoisture = m;
// ── Store to hourly bucket ──
const todayKey = 'hourlyData_' + new Date().toDateString();
const hourlyData = DB.get(todayKey, {});
const hr = new Date().getHours();
if (!hourlyData[hr]) hourlyData[hr] = { sum: 0, count: 0 };
hourlyData[hr].sum += m;
hourlyData[hr].count += 1;
DB.set(todayKey, hourlyData);
// ── Rolling moisture log ──
DB.push('moistureLog', { ts: Date.now(), m });
// ── Update all UI ──
updateGauge(m);
updateRealtimeDisplay(m);
updateHourlyChart();
runMath();
updateTrackerSuggestion();
}
/* ── GAUGE ──────────────────────────────────────────── */
function updateGauge(m) {
const ARC_MAX = 290; // px span of the 270° arc
const fill = Math.round((m / 100) * ARC_MAX);
const arc = document.getElementById('gauge-arc');
arc.setAttribute('stroke-dasharray', `${fill} 365`);
const col = m < 30 ? 'var(--danger)' : m < 60 ? 'var(--warn)' : 'var(--acc)';
arc.setAttribute('stroke', col);
arc.style.filter = `drop-shadow(0 0 8px ${m < 30 ? '#f87171' : m < 60 ? '#fbbf24' : '#4ade80'}55)`;
document.getElementById('gauge-pct').textContent = `${m}%`;
document.getElementById('curr-bar').style.width = `${m}%`;
document.getElementById('curr-bar').style.background = col;
document.getElementById('curr-bar-val').textContent = `${m}%`;
// Status text
const status = m < 30 ? '🚨 Water Immediately!' :
m < 45 ? '⚠️ Getting Dry' :
m < 65 ? '✅ Optimal Range' : '💦 Well Watered';
const desc = m < 30 ? 'Soil at critical level — water now to prevent wilting.' :
m < 45 ? 'Moisture dropping. Plan to water within 12–24 hours.' :
m < 65 ? 'Soil moisture is in the ideal range. Plant is thriving.' :
'Soil is well saturated. Monitor for over-watering.';
document.getElementById('gauge-status').textContent = status;
document.getElementById('gauge-desc').textContent = desc;
// Health badge & status chip
const hb = document.getElementById('health-badge');
const ps = document.getElementById('status-txt');
const pd = document.getElementById('plant-status');
const dot = pd.querySelector('.ps-dot');
if (m < 30) {
hb.textContent = '🚨 Needs Water'; hb.className = 'badge bg-red';
ps.textContent = 'Needs Water'; dot.style.background = 'var(--danger)';
} else if (m < 45) {
hb.textContent = '⚠️ Getting Dry'; hb.className = 'badge bg-yellow';
ps.textContent = 'Getting Dry'; dot.style.background = 'var(--warn)';
} else {
hb.textContent = '● Healthy'; hb.className = 'badge bg-green';
ps.textContent = 'Healthy'; dot.style.background = 'var(--acc)';
}
}
/* ── REALTIME DISPLAY (Tracker page) ──────────────────── */
function updateRealtimeDisplay(m) {
document.getElementById('rt-val').textContent = `${m}%`;
document.getElementById('rt-bar').style.width = `${m}%`;
document.getElementById('rt-status').textContent =
m < 30 ? '🚨 Critical — Water Now' :
m < 45 ? '⚠️ Low — Plan to Water' :
m < 65 ? '✅ Optimal' : '💦 Saturated';
// Push to rolling realtime chart
if (realtimeChart) {
const lbl = new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
if (realtimeChart.data.labels.length >= 20) {
realtimeChart.data.labels.shift();
realtimeChart.data.datasets[0].data.shift();
}
realtimeChart.data.labels.push(lbl);
realtimeChart.data.datasets[0].data.push(m);
realtimeChart.update('none');
}
}
/* ================================================================
MATH MODELS
================================================================ */
function runMath() {
const wx = DB.get('wx', { T: 30, RH: 60, FL: 30 });
const T = wx.T || 30;
const RH = wx.RH || 60;
const M = lastMoisture ?? DB.get('moistureLog', []).slice(-1)[0]?.m ?? null;
if (M === null) return; // no sensor data yet
/* 1. Saturated Vapour Pressure — Magnus formula */
const SVP = 0.6108 * Math.exp((17.27 * T) / (T + 237.3));
/* 2. Vapour Pressure Deficit */
const VPD = +(SVP * (1 - RH / 100)).toFixed(3);
/* 3. Estimated ET rate (Penman-Monteith proxy) %/hr */
const ET = +(Math.max(0.1, 0.4 + VPD * 0.6 + T * 0.012)).toFixed(2);
/* 4. Time to Critical (30% threshold) */
const TTC = M > 30 ? +(( M - 30) / ET).toFixed(1) : 0;
/* 5. Health Score (weighted composite, 0-100) */
const Mn = Math.min(1, Math.max(0, (M - 20) / 60));
const Vn = Math.min(1, Math.max(0, (2 - VPD) / 2));
const Tn = Math.min(1, Math.max(0, 1 - Math.abs(T - 25) / 20));
const score = Math.round(40 * Mn + 30 * Vn + 20 * Tn + 10 * (M > 30 ? 1 : 0));
/* 6. Water urgency (0–100) */
const urgency = Math.round(Math.min(100, Math.max(0, (60 - M) / 30 * 100)));
/* 7. Moisture trend via linear regression on last 6 hourly readings */
const log = DB.get('moistureLog', []);
const recent = log.slice(-6).map(x => x.m);
let slope = 0;
if (recent.length >= 3) {
const n = recent.length;
const mx = (n - 1) / 2;
const my = recent.reduce((a, b) => a + b) / n;
const num = recent.reduce((s, y, i) => s + (i - mx) * (y - my), 0);
const den = recent.reduce((s, _, i) => s + (i - mx) ** 2, 0);
slope = den ? +(num / den).toFixed(2) : 0;
}
const trendTxt = slope > 1 ? '↑ Rising' : slope < -1 ? '↓ Falling' : '→ Stable';
const stressTxt = VPD < 0.8 ? 'Low' : VPD < 1.2 ? 'Medium' : VPD < 1.6 ? 'High' : 'Very High';
// ── Update science strip (home page) ──────────────── */
document.getElementById('sci-vpd').textContent = VPD;
document.getElementById('sci-ttc').textContent = TTC;
document.getElementById('sci-et').textContent = ET;
document.getElementById('sci-score').textContent = score;
document.getElementById('as-stress').textContent = stressTxt;
document.getElementById('as-stress-sub').textContent = `VPD: ${VPD} kPa`;
document.getElementById('as-trend').textContent = trendTxt;
document.getElementById('as-trend-sub').textContent = `Slope: ${slope > 0 ? '+' : ''}${slope}/hr`;
document.getElementById('as-water-score').textContent = `${urgency}%`;
document.getElementById('as-water-sub').textContent = urgency < 30 ? 'No rush' : urgency < 70 ? 'Water soon' : 'Urgent!';
// ── Update tracker meta values ─────────────────────── */
document.getElementById('sg-et').textContent = `${ET} %/h`;
document.getElementById('sg-ttc').textContent = `${TTC}h`;
// Build prediction
buildPrediction(M, ET, TTC);
// Critical notification (throttled to 30 min)
const lastNotif = DB.get('lastCritNotif', 0);
if (M < 30 && Date.now() - lastNotif > 30 * 60_000) {
pushNotification('🚨 Water Now!', `Soil moisture is at ${M}% — critical!`);
addBellNotif('🚨', 'Moisture Critical', `Soil at ${M}% — water immediately!`);
DB.set('lastCritNotif', Date.now());
}
return { M, VPD, ET, TTC, score, urgency, slope };
}
/* ================================================================
TRACKER — SUGGESTION BANNER
================================================================ */
function updateTrackerSuggestion() {
const M = lastMoisture;
if (M === null) return;
const ET = parseFloat(document.getElementById('sg-et').textContent) || 1;
const TTC = parseFloat(document.getElementById('sg-ttc').textContent) || 24;
let title, msg, next;
if (M < 30) {
title = '🚨 Water Immediately!';
msg = `Soil moisture is critically low at ${M}%. Your plant risks wilting. Water now.`;
next = 'Right now';
} else if (M < 45) {
title = '⚠️ Water Soon';
msg = `Moisture is ${M}% and dropping. At current ET rate, critical threshold reached in ~${TTC}h.`;
next = `Within ${Math.min(Math.round(TTC / 2), 8)}h`;
} else if (M < 65) {
title = '✅ All Good — Next watering scheduled';
msg = `Soil is healthy at ${M}%. Estimated time to critical: ${TTC} hours.`;
next = `In ~${Math.round(TTC)}h`;
} else {
title = '💦 Plant is Well Watered';
msg = `Soil is saturated at ${M}%. No watering needed. Watch for over-watering if persistently above 80%.`;
next = `In ~${Math.round(TTC)}h`;
}
document.getElementById('sg-title').textContent = title;
document.getElementById('sg-msg').textContent = msg;
document.getElementById('sg-next').textContent = next;
}
/* ================================================================
PREDICTION PANEL
================================================================ */
function buildPrediction(M, ET, TTC) {
const todayLog = DB.get('wateringLog_today', []);
const allLogs = DB.get('wateringLogAll', []);
const forecast = [
{ label: 'Time to 45% (low)', val: M > 45 ? `${Math.round((M - 45) / ET)}h` : 'Now' },
{ label: 'Time to 30% (critical)', val: M > 30 ? `${Math.round((M - 30) / ET)}h` : 'Critical!' },
{ label: 'Suggested next water', val: M > 30 ? `~${Math.round((M - 30) / ET)}h` : 'Immediately' },
{ label: "Today's watering count", val: todayLog.length },
];
const avgGap = allLogs.length > 1
? Math.round((allLogs[allLogs.length - 1].ts - allLogs[0].ts) / allLogs.length / 3_600_000)
: null;
const patterns = [
{ label: 'Total watering events', val: allLogs.length },
{ label: 'Avg interval between waters', val: avgGap ? `${avgGap}h` : 'Not enough data' },
{ label: 'Current ET rate', val: `${ET} %/h` },
{ label: 'Soil health score', val: document.getElementById('sci-score').textContent || '--' },
];
const fmt = items => items.map(i =>
`<div class="pred-item"><span>${i.label}</span><strong>${i.val}</strong></div>`
).join('');
document.getElementById('pred-list').innerHTML = fmt(forecast);
document.getElementById('pattern-list').innerHTML = fmt(patterns);
}
/* ================================================================
WATERING LOG
================================================================ */
function recordWateringEvent(type, before, after) {
const now = new Date();
const event = {
ts: now.getTime(),
time: now.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }),
date: now.toDateString(),
type, before, after,
};
DB.push('wateringLogAll', event);
const today = DB.get('wateringLog_today', []);
today.push(event);
DB.set('wateringLog_today', today);
DB.set('lastWatered', now.getTime());
loadLastWatered();
renderWateringLog();
toast('Watering Logged',
type === 'auto' ? `Auto-detected: ${before}% → ${after}%` : 'Manually recorded',
'ts', '💧');
addBellNotif('💧', 'Watering Logged', `Recorded at ${event.time}`);
}
function logWateringManual() {
const M = lastMoisture ?? 0;
recordWateringEvent('manual', M, M);
}
function renderWateringLog() {
const today = DB.get('wateringLog_today', []);
const list = document.getElementById('log-list');
if (!list) return;
if (!today.length) {
list.innerHTML = '<div class="log-empty">No watering events recorded today</div>';
return;
}
list.innerHTML = today.map(e => `
<div class="log-item">
<div class="li-icon">💧</div>
<div class="li-info">
<div class="li-time">${e.time}</div>
<div class="li-detail">${
e.type === 'auto'
? `Before: ${e.before}% → After: ${e.after}%`
: 'Manually recorded'
}</div>
</div>
<span class="li-badge ${e.type === 'auto' ? 'lb-auto' : 'lb-manual'}">
${e.type === 'auto' ? 'Auto' : 'Manual'}
</span>
</div>
`).join('');
}
/* ================================================================
CHARTS
================================================================ */
const CHART_OPT = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
tooltip: {
backgroundColor: '#0a1d12',
titleColor: '#4ade80',
bodyColor: '#ecfdf5',
padding: 10, cornerRadius: 10,
borderColor: 'rgba(74,222,128,0.2)', borderWidth: 1,
},
},
scales: {
x: { grid: { color: 'rgba(255,255,255,0.04)' }, ticks: { color: 'rgba(236,253,245,0.35)', font: { size: 10 } } },
y: { grid: { color: 'rgba(255,255,255,0.04)' }, ticks: { color: 'rgba(236,253,245,0.35)', font: { size: 10 } } },
},
};
function buildTrackerCharts() {
buildHourlyChart();
buildRealtimeChart();
}
function buildHourlyChart() {
const ctx = document.getElementById('hourlyChart').getContext('2d');
const todayKey = 'hourlyData_' + new Date().toDateString();
const hourlyData = DB.get(todayKey, {});
const labels = Array.from({ length: 24 }, (_, i) => `${String(i).padStart(2,'0')}:00`);
const data = labels.map((_, i) => {
const h = hourlyData[i];
return h && h.count ? Math.round(h.sum / h.count) : null;
});
hourlyChart = new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [{
label: 'Moisture %',
data,
borderColor: '#4ade80',
backgroundColor: 'rgba(74,222,128,0.07)',
fill: true, tension: 0.4,
pointRadius: 3,
pointBackgroundColor: '#4ade80',
spanGaps: true,
}],
},
options: {
...CHART_OPT,
scales: { ...CHART_OPT.scales, y: { ...CHART_OPT.scales.y, min: 0, max: 100 } },
},
});
}
function updateHourlyChart() {
if (!hourlyChart) return;
const todayKey = 'hourlyData_' + new Date().toDateString();
const hourlyData = DB.get(todayKey, {});
hourlyChart.data.datasets[0].data = Array.from({ length: 24 }, (_, i) => {
const h = hourlyData[i];
return h && h.count ? Math.round(h.sum / h.count) : null;
});
hourlyChart.update('none');
}
function buildRealtimeChart() {
const ctx = document.getElementById('realtimeChart').getContext('2d');
realtimeChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Live %',
data: [],
borderColor: '#22c55e',
backgroundColor: 'rgba(34,197,94,0.07)',
fill: true, tension: 0.5, pointRadius: 2,
}],
},
options: {
...CHART_OPT,
scales: { ...CHART_OPT.scales, y: { ...CHART_OPT.scales.y, min: 0, max: 100 } },
},
});
}
/* ================================================================
NAVIGATION
================================================================ */
function goPage(id) {
['home', 'explore', 'tracker', 'about'].forEach(p => {
document.getElementById('p-' + p).classList.toggle('active', p === id);
document.getElementById('nt-' + p).classList.toggle('active', p === id);
});
}
/* ================================================================
EXPLORE — PLANT DATABASE
<img> tags are NOT subject to CORB/CORS — only fetch() is.
Each card has a gradient bg so if any URL 404s the card
still looks clean (onerror hides the broken img element).
================================================================ */
const PLANTS = [
{
name: "Maranta Leuconeura",
sci: "Prayer Plant",
img: "https://upload.wikimedia.org/wikipedia/commons/4/4a/Maranta_leuconeura3.jpg",
grad: "linear-gradient(135deg,#1a4a28,#0a1d12)",
diff: "medium",
mMin: 50,
mMax: 70,
water: "Every 7–10 days",
light: "Indirect bright",
origin: "Brazil",
tip: "Keep soil consistently moist but never soggy. Leaves fold up at night — totally normal!",
},
{
name: "Monstera Deliciosa",
sci: "Swiss Cheese Plant",
img: "https://images.pexels.com/photos/3097770/pexels-photo-3097770.jpeg?auto=compress&cs=tinysrgb&w=400",
grad: "linear-gradient(135deg,#1e5530,#091410)",
diff: "easy",
mMin: 40,
mMax: 65,
water: "Every 7–14 days",
light: "Medium indirect",
origin: "Mexico",
tip: "Allow top 2 inches of soil to dry before watering. Slightly under-watered is safer.",
},
{
name: "Snake Plant",
sci: "Sansevieria trifasciata",
img: "https://images.pexels.com/photos/2123482/pexels-photo-2123482.jpeg?auto=compress&cs=tinysrgb&w=400",
grad: "linear-gradient(135deg,#163d22,#050d08)",
diff: "easy",
mMin: 20,
mMax: 40,
water: "Every 2–6 weeks",
light: "Any light level",
origin: "West Africa",
tip: "The most forgiving plant. Let soil dry completely between waterings. Thrives on neglect.",
},
{
name: "Peace Lily",
sci: "Spathiphyllum wallisii",
img: "https://images.pexels.com/photos/4503273/pexels-photo-4503273.jpeg?auto=compress&cs=tinysrgb&w=400",
grad: "linear-gradient(135deg,#1a4a2e,#091410)",
diff: "medium",
mMin: 55,
mMax: 75,
water: "Every 5–7 days",
light: "Low to medium",
origin: "Colombia",
tip: "Will visibly droop when thirsty — a great indicator! Use filtered water if possible.",
},
{
name: "Pothos",
sci: "Epipremnum aureum",
img: "https://images.pexels.com/photos/1084540/pexels-photo-1084540.jpeg?auto=compress&cs=tinysrgb&w=400",
grad: "linear-gradient(135deg,#1e5c35,#071209)",
diff: "easy",
mMin: 40,
mMax: 60,
water: "Every 7–10 days",
light: "Low to bright indirect",
origin: "Solomon Islands",
tip: "Nearly indestructible. Yellowing leaves usually mean overwatering, not underwatering.",
},
{
name: "ZZ Plant",
sci: "Zamioculcas zamiifolia",
img: "https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Zamioculcas_zamiifolia_1.jpg/960px-Zamioculcas_zamiifolia_1.jpg",
grad: "linear-gradient(135deg,#0d2b1a,#050d08)",
diff: "easy",
mMin: 15,
mMax: 35,
water: "Every 2–3 weeks",
light: "Low light tolerant",
origin: "Eastern Africa",
tip: "Stores water in rhizomes. Over-watering is the #1 cause of death for this plant.",
},
{
name: "Spider Plant",
sci: "Chlorophytum comosum",
img: "https://images.pexels.com/photos/4751978/pexels-photo-4751978.jpeg?auto=compress&cs=tinysrgb&w=400",
grad: "linear-gradient(135deg,#1a4d2e,#050d08)",
diff: "easy",
mMin: 45,
mMax: 65,
water: "Every 5–7 days",
light: "Bright indirect",
origin: "South Africa",
tip: 'Extremely adaptable. Produces "spiderettes" for propagation. A great air purifier.',
},
{
name: "Fiddle Leaf Fig",
sci: "Ficus lyrata",
img: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/Ficus_lyrata_393081768.jpg/960px-Ficus_lyrata_393081768.jpg",
grad: "linear-gradient(135deg,#163d22,#050d08)",
diff: "hard",
mMin: 55,
mMax: 70,
water: "Every 7 days",
light: "Bright indirect",
origin: "West Africa",
tip: "Hates being moved. Brown spots = over-watering; crispy edges = under-watering.",
},
];
function buildPlantsPage() {
const grid = document.getElementById('plants-grid');
if (!grid) return;
grid.innerHTML = PLANTS.map(p => {
const diffCls = p.diff === 'easy' ? 'd-easy' : p.diff === 'medium' ? 'd-med' : 'd-hard';
const diffTxt = p.diff.charAt(0).toUpperCase() + p.diff.slice(1);
return `
<div class="pc">
<div class="pc-img-wrap" style="background:${p.grad}">
<img src="${p.img}" alt="${p.name}" loading="lazy"
onerror="this.style.display='none'"/>
<span class="pc-diff ${diffCls}">${diffTxt}</span>
</div>
<div class="pc-body">
<h3>${p.name}</h3>
<p class="sci-name">${p.sci}</p>
<div class="pc-stats">
<div class="pcs"><div class="pcs-l">Watering</div><div class="pcs-v">${p.water}</div></div>
<div class="pcs"><div class="pcs-l">Light</div><div class="pcs-v">${p.light}</div></div>
<div class="pcs"><div class="pcs-l">Origin</div><div class="pcs-v">${p.origin}</div></div>
<div class="pcs"><div class="pcs-l">Ideal Moisture</div><div class="pcs-v">${p.mMin}–${p.mMax}%</div></div>
</div>
<div class="mrb">
<div class="mrb-hdr"><span>Moisture Range</span><span>${p.mMin}–${p.mMax}%</span></div>
<div class="mrb-track">
<div class="mrb-range" style="left:${p.mMin}%;width:${p.mMax - p.mMin}%"></div>
</div>
</div>
<p class="pc-tip">💡 ${p.tip}</p>
</div>
</div>`;
}).join('');
}
/* ================================================================
NOTIFICATIONS
================================================================ */
function checkNotificationPermission() {
if ('Notification' in window && Notification.permission === 'default') {
Notification.requestPermission();
}
}
function pushNotification(title, msg) {
toast(title, msg, 'td', '🚨');
if ('Notification' in window && Notification.permission === 'granted') {
new Notification(title, { body: msg });
}
}
const bellItems = DB.get('bellItems', []);
function addBellNotif(icon, title, msg) {
const t = new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
bellItems.unshift({ icon, title, msg, t });
if (bellItems.length > 10) bellItems.pop();
DB.set('bellItems', bellItems);
renderBell();
}
function renderBell() {
const list = document.getElementById('bell-list');
const badge = document.getElementById('bell-badge');
if (!bellItems.length) {
list.innerHTML = '<p style="font-size:13px;color:rgba(236,253,245,.3);text-align:center;padding:14px 0">No notifications yet</p>';
badge.classList.remove('show');
return;
}
badge.textContent = Math.min(bellItems.length, 9);
badge.classList.add('show');
list.innerHTML = bellItems.slice(0, 6).map(n => `
<div class="ni">
<div class="ni-icon">${n.icon}</div>
<div>
<div class="ni-title">${n.title}</div>
<div class="ni-msg">${n.msg}</div>
<div class="ni-time">${n.t}</div>
</div>
</div>
`).join('');
}
function toggleBell() {
document.getElementById('bell-panel').classList.toggle('open');
document.getElementById('prof-dd').classList.remove('open');
}
/* ================================================================
PROFILE DROPDOWN
================================================================ */
function toggleProfile() {
document.getElementById('prof-dd').classList.toggle('open');
document.getElementById('bell-panel').classList.remove('open');
}
// Close dropdowns on outside click
document.addEventListener('click', e => {
if (!e.target.closest('.prof-wrap')) document.getElementById('prof-dd').classList.remove('open');
if (!e.target.closest('.bell-wrap')) document.getElementById('bell-panel').classList.remove('open');
});
/* ================================================================
MODALS
================================================================ */
function openPhotoModal() {
document.getElementById('modal-photo').classList.add('open');
document.getElementById('prof-dd').classList.remove('open');
}
function openPassModal() {
document.getElementById('modal-pass').classList.add('open');
document.getElementById('prof-dd').classList.remove('open');
}
function closeModal(id) {
document.getElementById(id).classList.remove('open');
}
function previewPhoto(e) {
const f = e.target.files[0];
if (!f) return;
const r = new FileReader();
r.onload = ev => { document.getElementById('photo-preview').src = ev.target.result; };
r.readAsDataURL(f);
}
function savePhoto() {
const src = document.getElementById('photo-preview').src;
DB.set('profilePhoto', src);
document.getElementById('nav-avatar').src = src;
closeModal('modal-photo');
toast('Photo Updated', 'Profile photo saved', 'ts', '📷');
}
function savePass() {
const np = document.getElementById('pass-new').value;
if (np.length < 6) { toast('Error', 'Password must be at least 6 characters', 'td', '⚠️'); return; }
DB.set('passwd', np);
closeModal('modal-pass');
document.getElementById('pass-new').value = '';
toast('Password Changed', 'Updated successfully', 'ts', '🔑');
}
/* ================================================================
TOAST
================================================================ */
function toast(title, msg, type, icon) {
const wrap = document.getElementById('toast-wrap');
const el = document.createElement('div');
el.className = `toast ${type}`;
el.innerHTML = `
<div class="toast-i">${icon}</div>
<div>
<div class="toast-t">${title}</div>
<div class="toast-m">${msg}</div>
</div>
`;
wrap.appendChild(el);
setTimeout(() => el.remove(), 4000);
}