-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1466 lines (1327 loc) · 113 KB
/
Copy pathapp.js
File metadata and controls
1466 lines (1327 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ============================================================
TSCRIC-LoRa Dashboard — app.js v4.0 RESEARCH EDITION
Original v3.0 fully preserved + new systems added
============================================================ */
// ============================================================
// LOGIN
// ============================================================
const DASHBOARD_PASSWORD = "Aman";
function doLogin() {
const passEl = document.getElementById('loginPass');
const errEl = document.getElementById('loginError');
if (!passEl) return;
if (passEl.value.trim() === DASHBOARD_PASSWORD) {
setDisplay('loginScreen','none');
setDisplay('mainHeader','block');
setDisplay('mainContent','block');
if (errEl) errEl.style.display = 'none';
sessionStorage.setItem('tscric_auth','1');
loadChartJS();
initFirebase();
} else {
if (errEl) errEl.style.display = 'block';
passEl.value = ''; passEl.focus();
}
}
function doLogout() {
sessionStorage.removeItem('tscric_auth');
setDisplay('mainHeader','none'); setDisplay('mainContent','none');
setDisplay('loginScreen','flex');
const p = document.getElementById('loginPass');
if (p) p.value = '';
}
// ============================================================
// FIREBASE CONFIG
// ============================================================
const FIREBASE_CONFIG = {
apiKey: "AIzaSyDtWF8l4QCBdwmojwClGfd32AVNuf8alAk",
authDomain: "ai-irrigation-system-1e112.firebaseapp.com",
databaseURL: "https://ai-irrigation-system-1e112-default-rtdb.firebaseio.com",
projectId: "ai-irrigation-system-1e112",
storageBucket: "ai-irrigation-system-1e112.firebasestorage.app",
messagingSenderId: "1052849462072",
appId: "1:1052849462072:web:a1062de83ec2f869a8ffcd"
};
// ============================================================
// CONSTANTS
// ============================================================
const BIGHA_TO_M2 = 1333.33;
const MAX_HISTORY = 50;
const OWM_DIRECT_KEY = "e4efeb48999d7e673042ae4700395ed2";
let owmDirectData = null;
const CROP_DATA = [
{ name:"Wheat", delta:450, fc:38, pwp:13 },
{ name:"Rice", delta:1200, fc:50, pwp:28 },
{ name:"Maize", delta:550, fc:38, pwp:13 },
{ name:"Cotton", delta:750, fc:37, pwp:13 },
{ name:"Soybean", delta:500, fc:37, pwp:13 },
{ name:"Chickpea", delta:350, fc:35, pwp:12 },
{ name:"Mustard", delta:380, fc:34, pwp:12 },
{ name:"Sugarcane", delta:1800, fc:42, pwp:16 }
];
const WEATHER_LOCATIONS = {
bhopal:{label:"Bhopal",lat:23.26,lon:77.41,alt:527},
indore:{label:"Indore",lat:22.72,lon:75.86,alt:553},
jabalpur:{label:"Jabalpur",lat:23.18,lon:79.94,alt:412},
gwalior:{label:"Gwalior",lat:26.22,lon:78.18,alt:197},
ujjain:{label:"Ujjain",lat:23.18,lon:75.78,alt:491},
sagar:{label:"Sagar",lat:23.84,lon:78.74,alt:523},
rewa:{label:"Rewa",lat:24.53,lon:81.30,alt:327},
satna:{label:"Satna",lat:24.60,lon:80.83,alt:318},
chhindwara:{label:"Chhindwara",lat:22.06,lon:78.93,alt:682},
vidisha:{label:"Vidisha",lat:23.52,lon:77.81,alt:430},
hoshangabad:{label:"Hoshangabad",lat:22.75,lon:77.72,alt:310},
narsinghpur:{label:"Narsinghpur",lat:22.95,lon:79.19,alt:363},
delhi:{label:"New Delhi",lat:28.61,lon:77.20,alt:216},
mumbai:{label:"Mumbai",lat:19.08,lon:72.88,alt:14},
pune:{label:"Pune",lat:18.52,lon:73.86,alt:560},
nagpur:{label:"Nagpur",lat:21.15,lon:79.09,alt:310},
lucknow:{label:"Lucknow",lat:26.85,lon:80.95,alt:111},
patna:{label:"Patna",lat:25.60,lon:85.12,alt:55},
jaipur:{label:"Jaipur",lat:26.91,lon:75.79,alt:431},
chandigarh:{label:"Chandigarh",lat:30.73,lon:76.78,alt:321},
hyderabad:{label:"Hyderabad",lat:17.38,lon:78.47,alt:536},
bangalore:{label:"Bengaluru",lat:12.97,lon:77.59,alt:920},
ahmedabad:{label:"Ahmedabad",lat:23.03,lon:72.58,alt:55},
kolkata:{label:"Kolkata",lat:22.57,lon:88.36,alt:9},
amritsar:{label:"Amritsar",lat:31.63,lon:74.87,alt:234},
varanasi:{label:"Varanasi",lat:25.32,lon:83.00,alt:80},
agra:{label:"Agra",lat:27.18,lon:78.01,alt:169}
};
// ============================================================
// STATE
// ============================================================
let firebaseApp=null, firebaseDB=null;
let irrigHistory=[], lastData=null, isConnected=false;
let selectedWeatherLocation='bhopal';
let watchdogTimer=null, lastDataTime=0;
let localConfig={plotArea_m2:6.0, plotArea_bigha:6.0/BIGHA_TO_M2, crop:0, weatherLocation:'bhopal'};
let updatingM2=false, updatingBigha=false;
let calibData=[
{adc_dry:850,adc_fc:600,adc_pwp:750,vwc_fc:0.35,vwc_pwp:0.12},
{adc_dry:845,adc_fc:595,adc_pwp:745,vwc_fc:0.35,vwc_pwp:0.12},
{adc_dry:855,adc_fc:605,adc_pwp:755,vwc_fc:0.35,vwc_pwp:0.12}
];
// v4.0 state
const CHART_BUF = 60;
let chartBuffers={labels:[],sm1:[],sm2:[],sm3:[],csmi:[],flow:[],aiScore:[],eto:[],rainfall:[],effectiveRain:[],appliedL:[],rainfallL:[],etoLoss:[],temp:[],hum:[]};
let chartInstances={}, chartsReady=false;
let alertList_data=[], alertIdCounter=0;
let lastPumpState=false, lastFlowRate=0;
let tipAccum_mm=0, lastRainEvent=null;
let loraPacketCount=0, loraTxTimestamp=0;
// ============================================================
// INIT
// ============================================================
document.addEventListener('DOMContentLoaded',()=>{
if(sessionStorage.getItem('tscric_auth')==='1'){
setDisplay('loginScreen','none');
setDisplay('mainHeader','block');
setDisplay('mainContent','block');
loadHistory(); updatePreviewCard(0,6.0);
loadChartJS(); initFirebase();
} else {
setTimeout(()=>{const el=document.getElementById('loginPass');if(el)el.focus();},300);
}
});
// ============================================================
// CHART.JS LAZY LOAD
// ============================================================
function loadChartJS(){
if(window.Chart){initAllCharts();return;}
const s=document.createElement('script');
s.src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js';
s.onload=()=>{chartsReady=true;initAllCharts();};
s.onerror=()=>console.warn('Chart.js load failed');
document.head.appendChild(s);
}
// ============================================================
// FIREBASE INIT
// ============================================================
function initFirebase(){
loadHistory(); updatePreviewCard(localConfig.crop,localConfig.plotArea_m2);
loadScript('https://www.gstatic.com/firebasejs/9.23.0/firebase-app-compat.js',()=>{
loadScript('https://www.gstatic.com/firebasejs/9.23.0/firebase-database-compat.js',()=>{
try{
if(!firebaseApp) firebaseApp=firebase.initializeApp(FIREBASE_CONFIG);
firebaseDB=firebase.database();
startSensorsListener(); startConfigListener();
fetchOWMDirect(); setInterval(fetchOWMDirect,600000);
setConnectionStatus('online');
if(watchdogTimer) clearInterval(watchdogTimer);
watchdogTimer=setInterval(connectionWatchdog,10000);
setInterval(updateLoRaDiagnostics,30000);
setInterval(updateSoilHealthEstimates,60000);
setInterval(checkRainfallIntelligence,120000);
}catch(e){
console.error(e); setConnectionStatus('error'); showAlert('Firebase init failed: '+e.message);
}
});
});
bootstrapAIChat();
}
function loadScript(src,cb){
const s=document.createElement('script'); s.src=src; s.onload=cb;
s.onerror=()=>{setConnectionStatus('error');showAlert('SDK load failed');};
document.head.appendChild(s);
}
function startSensorsListener(){
firebaseDB.ref('tscric/sensors').on('value',snap=>{
const data=snap.val();
if(data){lastData=data;isConnected=true;lastDataTime=Date.now();setConnectionStatus('online');updateDashboard(data);updateLastUpdateTime();}
},err=>{console.error(err);isConnected=false;setConnectionStatus('error');});
}
function startConfigListener(){
firebaseDB.ref('tscric/config').on('value',snap=>{
const cfg=snap.val(); if(!cfg) return;
if(cfg.plotArea!==undefined){
const area=parseFloat(cfg.plotArea);
if(area>=1&&area<=100000){
localConfig.plotArea_m2=area; localConfig.plotArea_bigha=area/BIGHA_TO_M2;
silentFill('plotAreaM2',area.toFixed(2)); silentFill('plotAreaBigha',(area/BIGHA_TO_M2).toFixed(6));
updatePreviewCard(localConfig.crop,area); updateLiveAreaBanner(area);
}
}
if(cfg.crop!==undefined){
const c=parseInt(cfg.crop); if(c>=0&&c<=7){
localConfig.crop=c; const sel=document.getElementById('cropSelectMain'); if(sel) sel.value=c;
updatePreviewCard(c,localConfig.plotArea_m2);
}
}
if(cfg.weatherLocation!==undefined&&WEATHER_LOCATIONS[cfg.weatherLocation]){
selectedWeatherLocation=cfg.weatherLocation; localConfig.weatherLocation=cfg.weatherLocation;
const sel=document.getElementById('weatherLocation'); if(sel) sel.value=cfg.weatherLocation;
onWeatherLocationChange(cfg.weatherLocation);
}
});
}
function saveConfig(){
if(!firebaseDB){showAlert("Firebase not connected");return;}
const m2=localConfig.plotArea_m2;
const loc=WEATHER_LOCATIONS[localConfig.weatherLocation]||WEATHER_LOCATIONS.bhopal;
firebaseDB.ref('tscric/config').set({
plotArea:parseFloat(m2.toFixed(2)), plotArea_bigha:parseFloat((m2/BIGHA_TO_M2).toFixed(6)),
crop:localConfig.crop, cropName:CROP_DATA[localConfig.crop].name,
weatherLocation:localConfig.weatherLocation, weatherLocationLabel:loc.label,
weatherLat:loc.lat, weatherLon:loc.lon, weatherAlt:loc.alt, updatedAt:Date.now()
}).then(()=>{showSavedBadge();updateLiveAreaBanner(m2);})
.catch(e=>showAlert("Save failed: "+e.message));
}
function sendCmd(cmd){
if(!firebaseDB){showAlert("Firebase not connected");return;}
const MAP={pump_on:{pumpOn:true,pumpOff:false},pump_off:{pumpOn:false,pumpOff:true},auto_on:{auto:true},manual_on:{auto:false}};
firebaseDB.ref('tscric/commands').update(MAP[cmd]).catch(e=>showAlert("Command error: "+e.message));
}
function saveCalibration(){
if(!firebaseDB){showAlert("Firebase not connected");return;}
const payload={soilCalib:{}};
for(let i=0;i<3;i++){
const d={
adc_dry:parseInt(document.getElementById('calib_dry_'+i)?.value)||calibData[i].adc_dry,
adc_fc: parseInt(document.getElementById('calib_fc_'+i)?.value) ||calibData[i].adc_fc,
adc_pwp:parseInt(document.getElementById('calib_pwp_'+i)?.value)||calibData[i].adc_pwp,
vwc_fc: parseFloat(document.getElementById('vwc_fc_'+i)?.value) ||calibData[i].vwc_fc,
vwc_pwp:parseFloat(document.getElementById('vwc_pwp_'+i)?.value)||calibData[i].vwc_pwp
};
calibData[i]=d; payload.soilCalib['ch'+i]=d;
}
firebaseDB.ref('tscric/config').update(payload).then(()=>{
const b=document.getElementById('calibSavedBadge');
if(b){b.style.display='inline-block';setTimeout(()=>b.style.display='none',3000);}
}).catch(e=>showAlert("Calib save failed: "+e.message));
}
// ============================================================
// MASTER DASHBOARD UPDATE
// ============================================================
function updateDashboard(d){
const sm1=fv(d.sm1),sm2=fv(d.sm2),sm3=fv(d.sm3),csmi=fv(d.csmi);
setText('sm1Val',sm1.toFixed(1)+'%'); setText('sm2Val',sm2.toFixed(1)+'%');
setText('sm3Val',sm3.toFixed(1)+'%'); setText('csmiVal',csmi.toFixed(1)+'%');
setBarHeight('bar1',sm1); setBarHeight('bar2',sm2); setBarHeight('bar3',sm3); setBarHeight('barCSMI',csmi);
setText('tempVal',fv(d.temperature).toFixed(1)); setText('humVal',fv(d.humidity).toFixed(0));
setText('presVal',fv(d.pressure).toFixed(1)); setText('flowVal',fv(d.flowRate).toFixed(2));
setText('aiScore',fv(d.aiScore).toFixed(1));
setText('smvVal',fv(d.smv).toFixed(4)); setText('smaVal',fv(d.sma).toFixed(4));
setText('tprVal',fv(d.tprScore).toFixed(3));setText('etoVal',fv(d.eto).toFixed(2));
setText('rainVal',fv(d.rainProb).toFixed(0));
setText('cropName',d.crop||'--'); setText('stageName',d.stage||'--'); setText('gddVal',fv(d.gdd).toFixed(0));
// OWM
const owmOK=d.owm_valid===true;
setText('owmTemp', owmOK?fv(d.owm_temp).toFixed(1)+' \u00b0C':'--');
setText('owmHumidity',owmOK?fv(d.owm_humidity).toFixed(0)+' %':'--');
setText('owmPressure',owmOK?fv(d.owm_pressure).toFixed(1)+' hPa':'--');
setText('owmRain', owmOK?fv(d.owm_rain_mm).toFixed(2)+' mm':'--');
const owmEl=document.getElementById('owmStatus');
if(owmEl){owmEl.textContent=owmOK?'\ud83d\udfe2 OWM Live':'\ud83d\udd34 OWM Unavailable';owmEl.className='owm-status '+(owmOK?'owm-live':'owm-dead');}
// Comparison
if(owmOK){
const td=fv(d.temperature)-fv(d.owm_temp), hd=fv(d.humidity)-fv(d.owm_humidity);
setText('cmpTemp',(td>=0?'+':'')+td.toFixed(1)+' \u00b0C vs OWM');
setText('cmpHum', (hd>=0?'+':'')+hd.toFixed(0)+' % vs OWM');
setEl('cmpTemp',el=>el.style.color=Math.abs(td)>3?'var(--orange)':'var(--green-light)');
setEl('cmpHum', el=>el.style.color=Math.abs(hd)>10?'var(--orange)':'var(--green-light)');
} else {
setText('cmpTemp','OWM offline'); setText('cmpHum','OWM offline');
}
updateSensorHealth(d);
// Water budget
const applied=fv(d.deltaApplied),required=fv(d.deltaRequired),balance=fv(d.deltaBalance);
const totalFlow=fv(d.totalLitres),effRain=fv(d.effectiveRain),estRain=fv(d.estimatedRain),rainCtrib=fv(d.rainfallContrib);
setText('appliedVal', applied.toFixed(1)+' L'); setText('requiredVal',required.toFixed(1)+' L');
setText('balanceVal', balance.toFixed(1)+' L'); setText('totalFlowVal',totalFlow.toFixed(1)+' L');
setText('rainfallContrib',rainCtrib.toFixed(1)+' L');
const pct=required>0?Math.min((applied/required)*100,100):0;
setEl('budgetProgress',el=>el.style.width=pct.toFixed(1)+'%');
setText('budgetPct',pct.toFixed(1)+'% of seasonal budget used');
const eff=required>0?Math.min(((applied+rainCtrib)/required)*100,100):0;
setText('irrigEfficiency',eff.toFixed(1)+'%');
// Rainfall
const tipMM=fv(d.tipBucket_mm), owmMM=owmOK?fv(d.owm_rain_mm):0;
setText('tipBucketVal', tipMM>0 ?tipMM.toFixed(2)+' mm':'No data');
setText('owmRainfall', owmMM>0 ?owmMM.toFixed(2)+' mm':'No data');
setText('estimatedRainVal',estRain>0?'~'+estRain.toFixed(1)+' mm':'None detected');
setText('effectiveRainVal',effRain.toFixed(2)+' mm');
const rainProb=fv(d.rainProb);
setText('rainProbVal',rainProb.toFixed(0)+'%');
const rpBar=document.getElementById('rainProbBar');
if(rpBar){rpBar.style.width=rainProb+'%';rpBar.style.background=rainProb>75?'#f85149':rainProb>35?'#f0a500':'#2ea043';}
setText('rainCategory',rainProb<20?'\u2600\ufe0f Clear':rainProb<40?'\u26c5 Possible':rainProb<70?'\ud83c\udf26\ufe0f Likely':'\ud83c\udf27\ufe0f Rain Expected');
// Pump
const pumpOn=d.pump||false, autoMode=d.autoMode!==undefined?d.autoMode:true, faultOn=d.pipelineFault||false;
setText('pumpStatusText',pumpOn?'\ud83d\udca7 PUMP ON':'\u2b55 PUMP OFF');
setText('pumpModeText',autoMode?'\ud83e\udd16 Auto Mode':'\u270b Manual Mode');
setEl('pumpIndicator',el=>el.className='pump-indicator'+(pumpOn?' on':''));
setDisplay('faultBanner',faultOn?'block':'none');
// Mode banners
const safeMode=d.safeMode||false, offlineMode=d.offlineMode||false, adaptiveMode=d.adaptiveMode||false;
setDisplay('safeModePanel',safeMode?'block':'none');
setDisplay('offlineBanner',(offlineMode||adaptiveMode)?'block':'none');
if(offlineMode||adaptiveMode) setText('offlineBannerMsg',adaptiveMode?'\ud83c\udf3f Adaptive Root-Zone Control Mode (Offline)':'\ud83d\udce1 Autonomous Offline Mode \u2014 Data stored locally');
setDisplay('dhtFallbackBadge',(d.dhtFallback||false)?'inline-block':'none');
setDisplay('bmpFallbackBadge',(d.bmpFallback||false)?'inline-block':'none');
// AI circle color
const score=fv(d.aiScore);
setEl('aiCircle',el=>el.className='ai-circle '+(score>=65?'high':score>=35?'medium':'low'));
// Remaining
const daysRem=balance>0&&fv(d.eto)>0?((balance/(fv(d.eto)*(fv(d.plotArea_m2)||localConfig.plotArea_m2)*0.001)).toFixed(0)):'0';
setText('daysRemaining',daysRem+' days'); setText('balRemaining',balance.toFixed(1)+' L');
if(d.plotArea_m2) updateLiveAreaBanner(parseFloat(d.plotArea_m2));
setText('connMode',d.wifiMode||'--');
const wifiOnline=(d.wifiMode==='Online');
setText('connStatus2',wifiOnline?'\ud83d\udfe2 Online':'\ud83d\udd34 Offline / Hotspot');
setEl('connStatus2',el=>{el.style.background=wifiOnline?'rgba(46,160,67,0.15)':'rgba(248,81,73,0.12)';el.style.color=wifiOnline?'var(--green-light)':'var(--red)';});
setText('loraStatus','Active');
const pendingLogs=fv(d.offlineLogCount)||0;
setText('offlineLogCount',pendingLogs>0?pendingLogs+' pending':'0 (synced)');
setEl('offlineLogCount',el=>el.style.color=pendingLogs>0?'var(--orange)':'var(--green-light)');
setText('cropStageInfo','Stage: '+(d.stage||'--')+'\u00a0|\u00a0GDD: '+fv(d.gdd).toFixed(0)+' \u00b0C\u00b7day');
setText('owmPressure2',owmOK?'OWM: '+fv(d.owm_pressure).toFixed(1)+' hPa':'OWM: --');
// History on pump ON
if(pumpOn&&!lastPumpState){
addHistoryEntry({time:new Date().toLocaleTimeString(),csmi:csmi.toFixed(1),ai:score.toFixed(1),dose:totalFlow.toFixed(1),reason:adaptiveMode?'Adaptive':autoMode?'Auto-AI':'Manual'});
}
lastPumpState=pumpOn;
// v4.0 extensions
appendChartData(d,owmOK);
updateExplainabilityEngine(d,owmOK);
runAlertEngine(d,owmOK);
updateFaultDiagnostics(d);
updateTippingBucketPanel(d);
updateLoRaDiagnostics(d);
updateSoilHealthEstimates(d);
lastData=d;
}
// ============================================================
// SENSOR HEALTH
// ============================================================
function updateSensorHealth(d){
const allFail=d.safeMode||false;
const s1f=allFail||(fv(d.sm1)<=0&&fv(d.csmi)<=0);
const s2f=allFail||(fv(d.sm2)<=0&&fv(d.csmi)<=0);
const s3f=allFail||(fv(d.sm3)<=0&&fv(d.csmi)<=0);
const items=[
{id:'sh_sm1',name:'SM1 (15cm)',ok:!s1f,fb:false},
{id:'sh_sm2',name:'SM2 (30cm)',ok:!s2f,fb:false},
{id:'sh_sm3',name:'SM3 (45cm)',ok:!s3f,fb:false},
{id:'sh_dht',name:'DHT22',ok:!d.dhtFallback,fb:d.dhtFallback},
{id:'sh_bmp',name:'BMP280',ok:!d.bmpFallback,fb:d.bmpFallback},
{id:'sh_flow',name:'YF-S201',ok:!d.pipelineFault,fb:false},
{id:'sh_lora',name:'LoRa SX1278',ok:true,fb:false}
];
items.forEach(s=>{
const el=document.getElementById(s.id); if(!el) return;
if(s.fb) el.innerHTML=`<span class="sh-dot warn"></span><span class="sh-name">${s.name}</span><span class="sh-stat warn">OWM Fallback</span>`;
else el.innerHTML=`<span class="sh-dot ${s.ok?'ok':'fail'}"></span><span class="sh-name">${s.name}</span><span class="sh-stat ${s.ok?'ok':'fail'}">${s.ok?'OK':'FAULT'}</span>`;
});
}
// ============================================================
// HELPERS
// ============================================================
function fv(v,def=0){return isNaN(parseFloat(v))?def:parseFloat(v);}
function setText(id,v){const e=document.getElementById(id);if(e)e.textContent=v;}
function setDisplay(id,d){const e=document.getElementById(id);if(e)e.style.display=d;}
function setEl(id,fn){const e=document.getElementById(id);if(e)fn(e);}
function silentFill(id,v){const e=document.getElementById(id);if(e)e.value=v;}
function setBarHeight(id,pct){const el=document.getElementById(id);if(!el)return;el.style.height=Math.max(2,Math.min(100,pct))+'%';}
function showAlert(msg){const b=document.getElementById('alertBar');if(b){b.style.display='block';b.innerText=msg;}}
function showSavedBadge(){const b=document.getElementById('configSavedBadge');if(b){b.style.display='inline-block';setTimeout(()=>b.style.display='none',3000);}}
function updateLastUpdateTime(){setText('lastUpdate','Updated '+new Date().toLocaleTimeString());}
function updateLiveAreaBanner(area_m2){const el=document.getElementById('liveArea');if(el)el.innerHTML=area_m2.toFixed(2)+' m\u00b2 ('+( area_m2/BIGHA_TO_M2).toFixed(4)+' Bigha)';}
function updatePreviewCard(cropIdx,area_m2){
const crop=CROP_DATA[cropIdx]||CROP_DATA[0];
const need=crop.delta*area_m2,bigha=area_m2/BIGHA_TO_M2;
setText('prevDelta',crop.delta+' mm'); setText('prevArea',area_m2.toFixed(2)+' m\u00b2');
setText('prevBigha',bigha.toFixed(6)+' Bigha'); setText('prevNeed',need.toFixed(1)+' L');
setText('prevFC',crop.fc+'%'); setText('prevPWP',crop.pwp+'%');
}
function onCropChange(val){localConfig.crop=parseInt(val);updatePreviewCard(localConfig.crop,localConfig.plotArea_m2);}
function onM2Input(val){
if(updatingM2)return;
const m2=parseFloat(val); if(isNaN(m2))return;
localConfig.plotArea_m2=m2; localConfig.plotArea_bigha=m2/BIGHA_TO_M2;
updatingBigha=true; silentFill('plotAreaBigha',localConfig.plotArea_bigha.toFixed(6)); updatingBigha=false;
updatePreviewCard(localConfig.crop,m2);
}
function onBighaInput(val){
if(updatingBigha)return;
const bigha=parseFloat(val); if(isNaN(bigha))return;
const m2=bigha*BIGHA_TO_M2; localConfig.plotArea_m2=m2; localConfig.plotArea_bigha=bigha;
updatingM2=true; silentFill('plotAreaM2',m2.toFixed(2)); updatingM2=false;
updatePreviewCard(localConfig.crop,m2);
}
function onWeatherLocationChange(val){
selectedWeatherLocation=val; localConfig.weatherLocation=val;
const loc=WEATHER_LOCATIONS[val];
if(loc){setText('weatherLocationInfo','\ud83d\udccd Lat: '+loc.lat+'\u00b0N | Lon: '+loc.lon+'\u00b0E | Alt: '+loc.alt+' m');setText('weatherLocBanner',loc.label);fetchOWMDirect();}
}
function addHistoryEntry(entry){
irrigHistory.unshift(entry); if(irrigHistory.length>MAX_HISTORY)irrigHistory.pop();
try{localStorage.setItem('tscric_history',JSON.stringify(irrigHistory));}catch(e){}
renderHistory();
}
function loadHistory(){try{const s=localStorage.getItem('tscric_history');if(s)irrigHistory=JSON.parse(s);renderHistory();}catch(e){}}
function renderHistory(){
const tbody=document.getElementById('historyBody'); if(!tbody)return;
if(!irrigHistory.length){tbody.innerHTML='<tr><td colspan="5" style="text-align:center;color:#8b949e">No events yet</td></tr>';return;}
tbody.innerHTML=irrigHistory.map(e=>`<tr><td>${e.time}</td><td>${e.csmi}%</td><td>${e.ai}</td><td>${e.dose} L</td><td><span class="badge badge-${e.reason==='Manual'?'manual':e.reason==='Adaptive'?'tpr':'auto'}">${e.reason}</span></td></tr>`).join('');
}
function connectionWatchdog(){
const stale=(Date.now()-lastDataTime)/1000;
if(lastDataTime>0&&stale>60){
isConnected=false; setConnectionStatus('offline'); setDisplay('offlineBanner','block');
setText('offlineBannerMsg','\u26a0\ufe0f No data for '+Math.round(stale)+'s \u2014 Device may be offline');
if(stale>300) addAlert('warning','\u26a0\ufe0f Long Offline Period','No sensor data for '+Math.round(stale/60)+' minutes. Device offline or hotspot-only mode.',false,'alert_watchdog');
}
}
function setConnectionStatus(status){
const text=document.getElementById('connStatus'),dot=document.getElementById('connDot');
if(!text)return;
const map={online:{t:'\ud83d\udfe2 Live',c:'status-dot online'},offline:{t:'\ud83d\udfe1 Offline',c:'status-dot offline'},error:{t:'\ud83d\udd34 Error',c:'status-dot error'}};
const s=map[status]||map.error; text.innerText=s.t; if(dot)dot.className=s.c;
}
// ============================================================
// OWM DIRECT
// ============================================================
async function fetchOWMDirect(){
const loc=WEATHER_LOCATIONS[selectedWeatherLocation]||WEATHER_LOCATIONS.bhopal;
const wUrl='https://api.openweathermap.org/data/2.5/weather?lat='+loc.lat+'&lon='+loc.lon+'&appid='+OWM_DIRECT_KEY+'&units=metric';
const fUrl='https://api.openweathermap.org/data/2.5/forecast?lat='+loc.lat+'&lon='+loc.lon+'&appid='+OWM_DIRECT_KEY+'&units=metric&cnt=4';
try{
const [r1,r2]=await Promise.all([fetch(wUrl),fetch(fUrl)]);
if(!r1.ok)return;
const j=await r1.json(); const jf=r2.ok?await r2.json():null;
let rainProb=0; if(jf&&jf.list) jf.list.forEach(s=>{if(s.pop!==undefined&&s.pop*100>rainProb)rainProb=s.pop*100;});
owmDirectData={owm_temp:j.main?j.main.temp:null,owm_humidity:j.main?j.main.humidity:null,owm_pressure:j.main?j.main.pressure:null,owm_rain_mm:j.rain?(j.rain['1h']||j.rain['3h']||0):0,owm_rain_prob:rainProb,owm_valid:true};
setText('owmTemp', owmDirectData.owm_temp!==null?owmDirectData.owm_temp.toFixed(1)+' \u00b0C':'--');
setText('owmHumidity',owmDirectData.owm_humidity!==null?owmDirectData.owm_humidity.toFixed(0)+' %':'--');
setText('owmPressure', owmDirectData.owm_pressure!==null?owmDirectData.owm_pressure.toFixed(1)+' hPa':'--');
setText('owmRain', owmDirectData.owm_rain_mm>0?owmDirectData.owm_rain_mm.toFixed(2)+' mm':'0.00 mm');
setText('owmRainfall',owmDirectData.owm_rain_mm>0?owmDirectData.owm_rain_mm.toFixed(2)+' mm':'0.00 mm');
setText('owmPressure2','OWM: '+(owmDirectData.owm_pressure!==null?owmDirectData.owm_pressure.toFixed(1)+' hPa':'--'));
const el=document.getElementById('owmStatus'); if(el){el.textContent='\ud83d\udfe2 OWM Live';el.className='owm-status owm-live';}
if(!lastData){
setText('rainVal',rainProb.toFixed(0)); setText('rainProbVal',rainProb.toFixed(0)+'%');
const bar=document.getElementById('rainProbBar');
if(bar){bar.style.width=(rainProb>0?rainProb:2)+'%';bar.style.background=rainProb>75?'#f85149':rainProb>35?'#f0a500':'#2ea043';}
setText('rainCategory',rainProb<20?'\u2600\ufe0f Clear':rainProb<40?'\u26c5 Possible':rainProb<70?'\ud83c\udf26\ufe0f Likely':'\ud83c\udf27\ufe0f Rain Expected');
}
if(rainProb>80) addAlert('info','\ud83c\udf27\ufe0f Heavy Rain Forecast','Rain probability '+rainProb.toFixed(0)+'%. Irrigation will be suppressed automatically.',true,'alert_heavyrain');
}catch(e){console.warn('OWM fetch failed:',e.message);}
}
// ============================================================
// v4.0 — SMART ALERT ENGINE
// ============================================================
function addAlert(severity,title,message,autoDismiss,id){
const alertId=id||('alert_'+(++alertIdCounter));
if(alertList_data.some(a=>a.id===alertId))return;
alertList_data.unshift({id:alertId,severity,title,message,time:new Date().toLocaleTimeString(),autoDismiss});
if(alertList_data.length>30)alertList_data.pop();
renderAlertCenter();
showToast(severity,title,message,autoDismiss?6000:0);
}
function dismissAlert(alertId){
alertList_data=alertList_data.filter(a=>a.id!==alertId);
renderAlertCenter();
}
function clearAllAlerts(){
alertList_data=alertList_data.filter(a=>!a.autoDismiss);
renderAlertCenter();
}
function renderAlertCenter(){
const listEl=document.getElementById('alertList');
const countEl=document.getElementById('alertBadgeCount');
if(!listEl)return;
const critCount=alertList_data.filter(a=>a.severity==='critical').length;
if(countEl){
countEl.textContent=alertList_data.length;
countEl.className='alert-badge-count'+(alertList_data.length===0?' zero':'');
if(critCount>0)countEl.style.background='var(--red)';
else if(alertList_data.length>0)countEl.style.background='var(--orange)';
else countEl.style.background='';
}
if(!alertList_data.length){listEl.innerHTML='<div class="alert-empty">\u2705 No active alerts \u2014 all systems nominal</div>';return;}
listEl.innerHTML=alertList_data.map(a=>`
<div class="alert-item sev-${a.severity}">
<span class="alert-sev-dot"></span>
<div class="alert-item-body">
<div class="alert-item-title">${a.title}</div>
<div class="alert-item-msg">${a.message}</div>
<div class="alert-item-time">${a.time}</div>
</div>
<button class="alert-item-dismiss" onclick="dismissAlert('${a.id}')" title="Dismiss">\u2715</button>
</div>`).join('');
}
function showToast(severity,title,message,duration){
const container=document.getElementById('toast-container'); if(!container)return;
const toast=document.createElement('div');
toast.className=`toast toast--${severity==='critical'?'critical':severity==='warning'?'warning':severity==='success'?'success':'info'}`;
const icons={critical:'\ud83d\udea8',warning:'\u26a0\ufe0f',info:'\u2139\ufe0f',success:'\u2705'};
const dur=duration||(severity==='critical'?0:5000);
toast.innerHTML=`<span class="toast-icon">${icons[severity]||'\u2139\ufe0f'}</span><div class="toast-body"><div class="toast-title">${title}</div><div class="toast-msg">${message}</div></div><button class="toast-close" onclick="this.closest('.toast').remove()">\u2715</button>${dur>0?`<div class="toast-progress" style="animation-duration:${dur}ms;color:${severity==='critical'?'var(--red)':severity==='warning'?'var(--orange)':'var(--blue)'}"></div>`:''}`;
container.appendChild(toast);
if(dur>0)setTimeout(()=>{toast.classList.add('toast-exit');setTimeout(()=>toast.remove(),300);},dur);
}
function runAlertEngine(d,owmValid){
const csmi=fv(d.csmi),flow=fv(d.flowRate),aiS=fv(d.aiScore),pumpOn=d.pump||false;
if(csmi>0&&csmi<18){addAlert('critical','\ud83c\udf35 Critical Soil Moisture','CSMI '+csmi.toFixed(1)+'% \u2014 root zone severely dry. Immediate irrigation required.',false,'alert_lowsoil');}
else if(csmi>0&&csmi<28){addAlert('warning','\u26a0\ufe0f Low Soil Moisture','CSMI '+csmi.toFixed(1)+'% below optimal. Schedule irrigation soon.',true,'alert_soil_warn');}
else{alertList_data=alertList_data.filter(a=>a.id!=='alert_lowsoil'&&a.id!=='alert_soil_warn');renderAlertCenter();}
if(csmi>80&&pumpOn) addAlert('warning','\ud83d\udca6 Overwatering Risk','Soil moisture '+csmi.toFixed(1)+'% with pump ON. Risk of deep percolation.',false,'alert_overwater');
if(d.safeMode) addAlert('critical','\ud83d\udd34 All Soil Sensors Failed','Safe Mode activated \u2014 all 3 soil sensors offline. Check CD4051 MUX wiring immediately.',false,'alert_safemode');
else{alertList_data=alertList_data.filter(a=>a.id!=='alert_safemode');renderAlertCenter();}
if(d.pipelineFault) addAlert('critical','\ud83d\udeb0 Pipeline Fault','No flow detected while pump ON. Check for blockage, burst pipe, or empty tank.',false,'alert_pipeline');
else{alertList_data=alertList_data.filter(a=>a.id!=='alert_pipeline');renderAlertCenter();}
if(d.dhtFallback) addAlert('warning','\ud83c\udf21\ufe0f DHT22 Fault','Temperature/Humidity sensor failed. OWM fallback active.',true,'alert_dht');
if(d.bmpFallback) addAlert('warning','\ud83c\udf00 BMP280 Fault','Pressure sensor failed. OWM fallback active.',true,'alert_bmp');
if(d.offlineMode&&fv(d.offlineLogCount)>=40)
addAlert('warning','\ud83d\udce1 EEPROM Near Full',fv(d.offlineLogCount)+' offline events pending. Buffer approaching 50-event limit.',true,'alert_eeprom');
if(aiS>100) addAlert('warning','\ud83e\udd16 High AI Score','AI Score '+aiS.toFixed(1)+'/120 \u2014 extreme irrigation urgency.',true,'alert_hiai');
if(!pumpOn&&flow>0.5){addAlert('critical','\ud83d\udca7 Flow Detected \u2014 Pump OFF','Flow '+flow.toFixed(2)+' L/min detected while pump OFF. Possible leakage or pipe burst!',false,'alert_flow_leak');}
else{alertList_data=alertList_data.filter(a=>a.id!=='alert_flow_leak');renderAlertCenter();}
}
// ============================================================
// v4.0 — AI EXPLAINABILITY ENGINE
// ============================================================
function updateExplainabilityEngine(d,owmValid){
const explainBody=document.getElementById('explainBody');
const decisionText=document.getElementById('decisionText');
if(!explainBody||!d)return;
const csmi=fv(d.csmi),sm1=fv(d.sm1),sm2=fv(d.sm2),sm3=fv(d.sm3);
const aiScore=fv(d.aiScore),rainProb=fv(d.rainProb),eto=fv(d.eto),flow=fv(d.flowRate),pumpOn=d.pump||false;
const crop=CROP_DATA[localConfig.crop];
const cards=[];
// Soil analysis
if(csmi<20) cards.push({type:'alert',icon:'\ud83c\udf35',title:'Critical Root-Zone Depletion',text:`CSMI ${csmi.toFixed(1)}% \u2014 deep zone (${sm3.toFixed(1)}% at 45cm) below Permanent Wilting Point. Immediate irrigation required to prevent permanent crop damage.`,badge:'CRITICAL',badgeType:'alert'});
else if(csmi<35) cards.push({type:'warn',icon:'\u26a0\ufe0f',title:'Root-Zone Below Field Capacity',text:`CSMI ${csmi.toFixed(1)}% \u2014 SM1:${sm1.toFixed(1)}%, SM2:${sm2.toFixed(1)}%, SM3:${sm3.toFixed(1)}%. Approaching lower threshold. Plan irrigation within 2\u20134 hours.`,badge:'DRY',badgeType:'warn'});
else if(csmi>70) cards.push({type:'info',icon:'\ud83d\udca6',title:'Root-Zone Near Field Capacity',text:`CSMI ${csmi.toFixed(1)}% \u2014 high moisture across all depths. Deep sensor (${sm3.toFixed(1)}%) shows good retention. No irrigation needed; monitor for deep percolation.`,badge:'WET',badgeType:'info'});
else cards.push({type:'good',icon:'\u2705',title:'Optimal Root-Zone Moisture',text:`CSMI ${csmi.toFixed(1)}% in optimal range \u2014 SM1:${sm1.toFixed(1)}%, SM2:${sm2.toFixed(1)}%, SM3:${sm3.toFixed(1)}%. Crop water demand is being met.`,badge:'OPTIMAL',badgeType:'good'});
// Depth profile
const surfDiff=sm1-sm3;
if(surfDiff>15) cards.push({type:'info',icon:'\ud83c\udf0a',title:'Surface Wetter Than Deep Zone',text:`Surface (${sm1.toFixed(1)}%) is ${surfDiff.toFixed(1)}% wetter than deep zone (${sm3.toFixed(1)}%). Infiltration front moving downward. Recent irrigation or rainfall detected.`,badge:'INFILTRATING',badgeType:'info'});
else if(surfDiff<-10) cards.push({type:'warn',icon:'\ud83c\udf31',title:'Deep Zone Retaining More Moisture',text:`Deep zone (${sm3.toFixed(1)}%) holds more moisture than surface (${sm1.toFixed(1)}%). Surface evaporation active. Consider mulching to reduce moisture loss.`,badge:'EVAP LOSS',badgeType:'warn'});
// Rain suppression
if(rainProb>75) cards.push({type:'info',icon:'\ud83c\udf27\ufe0f',title:'Irrigation Suppressed \u2014 High Rain Probability',text:`Rain probability ${rainProb.toFixed(0)}% (threshold: 75%). Irrigation auto-delayed. Expected rainfall will contribute to root-zone moisture budget.`,badge:'RAIN DELAY',badgeType:'info'});
else if(rainProb>35) cards.push({type:'warn',icon:'\u26c5',title:'Moderate Rain Probability \u2014 Monitoring',text:`Rain probability ${rainProb.toFixed(0)}%. System monitoring. If rain occurs, irrigation cancelled. Otherwise, normal scheduling resumes.`,badge:'MONITORING',badgeType:'warn'});
// ETo
if(eto>6) cards.push({type:'warn',icon:'\u2600\ufe0f',title:'High Evapotranspiration Demand',text:`ETo ${eto.toFixed(2)} mm/day indicates high atmospheric water demand. Irrigation frequency should increase to compensate for accelerated soil moisture depletion.`,badge:'HIGH ETo',badgeType:'warn'});
// Flow
if(pumpOn&&flow<0.5) cards.push({type:'alert',icon:'\ud83d\udeb0',title:'Low Flow During Active Pump',text:`Pump ON but flow only ${flow.toFixed(2)} L/min. Possible pipe blockage, air lock, empty tank, or pump failure. Check pipeline immediately.`,badge:'FLOW FAULT',badgeType:'alert'});
else if(pumpOn&&flow>0) cards.push({type:'good',icon:'\u2705',title:'Water Delivery Confirmed',text:`Pump ON \u2014 flow confirmed at ${flow.toFixed(2)} L/min. Water reaching field. Monitor soil sensors for root-zone response.`,badge:'DELIVERING',badgeType:'good'});
// AI score
if(aiScore>=65) cards.push({type:'warn',icon:'\ud83e\udd16',title:`AI Score ${aiScore.toFixed(1)}/120 \u2014 Irrigation Triggered`,text:`Score crossed 65-point threshold. Integrates CSMI (${csmi.toFixed(1)}%), moisture velocity (SMV), temporal pattern (TPR), and ETo demand. All conditions satisfied.`,badge:'TRIGGERED',badgeType:'warn'});
else cards.push({type:'info',icon:'\ud83e\udd16',title:`AI Score ${aiScore.toFixed(1)}/120 \u2014 Monitoring`,text:`Score is ${(65-aiScore).toFixed(0)} points below trigger. System monitoring depletion rate (SMV) and temporal pattern (TPR: ${fv(d.tprScore).toFixed(3)}) until threshold crossed.`,badge:'MONITORING',badgeType:'info'});
explainBody.innerHTML=cards.map(c=>`<div class="explain-card explain-${c.type}"><span class="explain-icon">${c.icon}</span><div class="explain-body"><div class="explain-title">${c.title}</div><div class="explain-text">${c.text}</div></div><span class="explain-badge ${c.badgeType}">${c.badge}</span></div>`).join('');
if(decisionText){
let dec='';
if(d.safeMode) dec='<strong style="color:var(--red)">IRRIGATION SUSPENDED \u2014 SAFE MODE:</strong> All soil sensors offline. Check sensor wiring immediately.';
else if(rainProb>75) dec=`<strong style="color:var(--rain-blue)">IRRIGATION DELAYED \u2014 RAIN EXPECTED:</strong> ${rainProb.toFixed(0)}% rain probability. System will resume after rain event.`;
else if(csmi<25&&aiScore>=65) dec=`<strong style="color:var(--red)">IRRIGATION TRIGGERED:</strong> CSMI ${csmi.toFixed(1)}% below PWP AND AI Score ${aiScore.toFixed(1)} above 65. Pulse irrigation active (30s ON / 2min OFF). Flow sensor monitoring delivery.`;
else if(csmi<35) dec=`<strong style="color:var(--orange)">IRRIGATION PENDING:</strong> CSMI ${csmi.toFixed(1)}% approaching trigger. AI Score ${aiScore.toFixed(1)}/65 required. Monitoring moisture depletion rate.`;
else if(csmi>70) dec=`<strong style="color:var(--blue)">NO IRRIGATION NEEDED:</strong> Root-zone ${csmi.toFixed(1)}% above optimal. Pump will not activate until CSMI drops below stage threshold.`;
else dec=`<strong style="color:var(--green-light)">MONITORING \u2014 OPTIMAL:</strong> CSMI ${csmi.toFixed(1)}% in optimal range for ${CROP_DATA[localConfig.crop].name}. AI Score ${aiScore.toFixed(1)}/120. Standard monitoring cycle active (10s interval).`;
decisionText.innerHTML=dec;
}
}
// ============================================================
// v4.0 — FAULT DIAGNOSTICS
// ============================================================
function updateFaultDiagnostics(d){
const pumpOn=d.pump||false,flow=fv(d.flowRate);
lastFlowRate=flow;
const expFlow=5;
// Leakage: flow when pump OFF
const leakScore=(!pumpOn&&flow>0.3)?Math.min(100,flow*30):0;
updateFaultCard('fd-leakage',leakScore,leakScore>50?'alert':leakScore>10?'warn':'ok',leakScore>50?'\ud83d\udea8 LEAKAGE DETECTED!':leakScore>10?'\u26a0\ufe0f Possible Leakage':'OK \u2014 Normal Flow',leakScore.toFixed(0)+'/100');
// Dry-run: pump ON, no flow
const dryScore=(pumpOn&&flow<0.3)?80:0;
updateFaultCard('fd-dryrun',dryScore,dryScore>60?'alert':'ok',dryScore>60?'\ud83d\udd34 DRY-RUN RISK!':'OK \u2014 No Dry-Run',dryScore>60?'HIGH':'Low');
// Blockage: low flow during pump
const blockScore=(pumpOn&&flow>0&&flow<expFlow*0.4)?Math.round((1-flow/(expFlow*0.4))*100):0;
updateFaultCard('fd-blockage',blockScore,blockScore>60?'alert':blockScore>30?'warn':'ok',blockScore>60?'\ud83d\udeab BLOCKAGE DETECTED':blockScore>30?'\u26a0\ufe0f Reduced Flow':'OK \u2014 Flow Normal',blockScore.toFixed(0)+'%');
// Tampering: high flow when pump OFF
const tamperScore=(flow>expFlow*2&&!pumpOn)?85:(!pumpOn&&flow>0.1?40:0);
updateFaultCard('fd-theft',tamperScore,tamperScore>70?'alert':tamperScore>30?'warn':'ok',tamperScore>70?'\u26a0\ufe0f ABNORMAL FLOW!':tamperScore>30?'\u26a0\ufe0f Unusual Reading':'OK \u2014 No Anomaly',tamperScore>30?flow.toFixed(2)+' L/min unexpected':'None');
}
function updateFaultCard(id,score,state,statusText,detail){
const card=document.getElementById(id);
const sEl=document.getElementById(id+'-status');
const bEl=document.getElementById(id+'-bar');
const dEl=document.getElementById(id+'-score');
if(!card)return;
const colors={ok:'var(--green)',warn:'var(--orange)',alert:'var(--red)'};
card.className='fault-card fault-'+state;
if(sEl){sEl.textContent=statusText;sEl.className='fault-card-status '+state;}
if(bEl){bEl.style.width=Math.min(100,score)+'%';bEl.style.background=colors[state];}
if(dEl)dEl.textContent=detail;
}
// ============================================================
// v4.0 — TIPPING BUCKET RAINFALL
// ============================================================
function updateTippingBucketPanel(d){
const tipMM=fv(d.tipBucket_mm),tipPulse=fv(d.tipBucket_pulses)||Math.round(tipMM/0.2);
const rainMM=fv(d.owm_rain_mm)||tipMM;
if(tipMM>tipAccum_mm)tipAccum_mm=tipMM;
setText('tipPulseCount',tipPulse.toFixed(0)); setText('tipAccumMM',tipAccum_mm.toFixed(2));
setText('rainIntensityInner',rainMM.toFixed(1)+' mm/h');
const gaugeEl=document.getElementById('rainIntensityGauge');
if(gaugeEl){const p=Math.min(100,(rainMM/25)*100);gaugeEl.style.background=`conic-gradient(var(--rain-blue) ${p*3.6}deg, var(--bg-tertiary) 0deg)`;}
const S=(25400/75)-254,Ia=0.2*S;
const runoff=tipAccum_mm>Ia?Math.pow(tipAccum_mm-Ia,2)/(tipAccum_mm-Ia+S):0;
setText('runoffEstMM',runoff.toFixed(2));
const eff=tipAccum_mm>0?Math.round(((tipAccum_mm-runoff)/tipAccum_mm)*100):0;
setText('effectiveRainPct',eff.toString()); setEl('rainEffBar',el=>el.style.width=eff+'%');
if(tipMM>0||(owmDirectData&&owmDirectData.owm_rain_mm>0))lastRainEvent=Date.now();
if(lastRainEvent){setText('dryDaysCount',((Date.now()-lastRainEvent)/86400000).toFixed(0));}
else setText('dryDaysCount','>7');
}
function checkRainfallIntelligence(){
if(!lastData)return;
const tipMM=fv(lastData.tipBucket_mm);
if(tipMM>20)addAlert('info','\ud83c\udf27\ufe0f Significant Rainfall','Tipping bucket recorded '+tipMM.toFixed(1)+' mm. Irrigation suppressed. Water budget updated.',true,'alert_rain_event');
}
// ============================================================
// v4.0 — SOIL HEALTH (REAL HARDWARE ONLY — no fake estimates)
// ============================================================
function updateSoilHealthEstimates(d){
const data=d||lastData; if(!data)return;
// ── STRICT HARDWARE DETECTION ──────────────────────────────
// Only show real values if actual sensor data came from Firebase.
// Firebase key present AND non-zero = hardware connected.
// Missing key OR exactly 0 = hardware NOT connected → show "Not Connected"
const hasSoilTemp = data.hasOwnProperty('soilTemp') && fv(data.soilTemp) !== 0;
const hasEC = data.hasOwnProperty('ecValue') && fv(data.ecValue) !== 0;
const hasPH = data.hasOwnProperty('phValue') && fv(data.phValue) !== 0;
// Salinity is derived from EC — only show if EC hardware present
const hasAll = hasSoilTemp && hasEC && hasPH;
// ── Soil Temperature (DS18B20) ─────────────────────────────
if(hasSoilTemp){
const soilTemp=fv(data.soilTemp);
setText('soilTempVal', soilTemp.toFixed(1));
const tStat=soilTemp<5||soilTemp>40?'critical':soilTemp<10||soilTemp>35?'caution':'optimal';
const tText={optimal:'\u2705 Optimal',caution:'\u26a0\ufe0f Caution',critical:'\ud83d\udd34 Critical'};
setText('soilTempStatus', tText[tStat]);
setEl('soilTempStatus', el=>el.className='soil-health-status '+tStat);
setEl('soilTempBar', el=>{ el.style.width=Math.min(100,(soilTemp/50)*100)+'%'; el.style.background='var(--orange)'; });
} else {
// Hardware not connected — show clearly
setText('soilTempVal', '--');
setText('soilTempStatus', '\ud83d\udd0c Not Connected');
setEl('soilTempStatus', el=>el.className='soil-health-status disconnected');
setEl('soilTempBar', el=>{ el.style.width='0%'; });
}
// ── EC Sensor ──────────────────────────────────────────────
if(hasEC){
const ec=fv(data.ecValue);
setText('ecVal', ec.toFixed(2));
const eStat=ec<0.5?'caution':ec>4?'critical':'optimal';
const eText={optimal:'\u2705 Optimal',caution:'\u26a0\ufe0f Caution',critical:'\ud83d\udd34 Critical'};
setText('ecStatus', eText[eStat]);
setEl('ecStatus', el=>el.className='soil-health-status '+eStat);
setEl('ecBar', el=>{ el.style.width=Math.min(100,(ec/6)*100)+'%'; el.style.background='var(--cyan)'; });
if(eStat==='critical') addAlert('warning','\u26a1 High Soil Salinity','EC '+ec.toFixed(2)+' mS/cm — high salinity. Reduce fertilizer and increase leaching irrigation.',true,'alert_ec');
// Salinity from real EC
const salinity=ec*640;
setText('salinityVal', salinity.toFixed(0));
const sStat=salinity>1500?'critical':salinity>800?'caution':'optimal';
const sText={optimal:'\u2705 Optimal',caution:'\u26a0\ufe0f Caution',critical:'\ud83d\udd34 Critical'};
setText('salinityStatus', sText[sStat]);
setEl('salinityStatus', el=>el.className='soil-health-status '+sStat);
setEl('salinityBar', el=>{ el.style.width=Math.min(100,(salinity/2000)*100)+'%'; el.style.background='var(--amber)'; });
} else {
setText('ecVal', '--');
setText('ecStatus', '\ud83d\udd0c Not Connected');
setEl('ecStatus', el=>el.className='soil-health-status disconnected');
setEl('ecBar', el=>{ el.style.width='0%'; });
setText('salinityVal', '--');
setText('salinityStatus', '\ud83d\udd0c Not Connected');
setEl('salinityStatus', el=>el.className='soil-health-status disconnected');
setEl('salinityBar', el=>{ el.style.width='0%'; });
}
// ── pH Sensor ──────────────────────────────────────────────
if(hasPH){
const ph=fv(data.phValue);
setText('phVal', ph.toFixed(1));
const pStat=ph<5.5||ph>8.0?'critical':ph<6.0||ph>7.5?'caution':'optimal';
const pText={optimal:'\u2705 Optimal',caution:'\u26a0\ufe0f Caution',critical:'\ud83d\udd34 Critical'};
setText('phStatus', pText[pStat]);
setEl('phStatus', el=>el.className='soil-health-status '+pStat);
setEl('phBar', el=>{ el.style.width=Math.min(100,(ph/14)*100)+'%'; el.style.background='var(--violet)'; });
if(pStat==='critical') addAlert('warning','\ud83e\uddea Soil pH Critical','pH '+ph.toFixed(1)+' — outside optimal range (6.0–7.5). Crop nutrient uptake impaired.',true,'alert_ph');
} else {
setText('phVal', '--');
setText('phStatus', '\ud83d\udd0c Not Connected');
setEl('phStatus', el=>el.className='soil-health-status disconnected');
setEl('phBar', el=>{ el.style.width='0%'; });
}
}
// ============================================================
// v4.0 — LoRa DIAGNOSTICS (real hardware values only)
// ============================================================
function updateLoRaDiagnostics(d){
const data=d||lastData;
// ── STRICT HARDWARE DETECTION ──────────────────────────────
// loraPackets comes from firmware. If it's missing from Firebase
// or is 0, the LoRa hardware has not sent any packets yet.
const hasLoRaData = data && data.hasOwnProperty('loraPackets') && fv(data.loraPackets) > 0;
const hasRSSI = data && data.hasOwnProperty('loraRSSI') && fv(data.loraRSSI) !== 0;
const hasSNR = data && data.hasOwnProperty('loraSNR') && fv(data.loraSNR) !== 0;
if(hasLoRaData){
// Real firmware data present — update counter
loraPacketCount = fv(data.loraPackets);
loraTxTimestamp = Date.now();
setText('loraPacketsSent', loraPacketCount.toString());
setText('loraTxAge', 'just now');
} else {
// No real LoRa hardware data — show clearly
setText('loraPacketsSent', '--');
setText('loraTxAge', 'No data');
}
// RSSI — only show if firmware sent real value
if(hasRSSI){
const rssi = fv(data.loraRSSI);
setText('loraRSSI', rssi.toFixed(0)+' dBm');
const sigQual = rssi>-80?'Excellent':rssi>-100?'Good':rssi>-110?'Fair':'Weak';
const sigColor = rssi>-80?'var(--green-light)':rssi>-100?'var(--teal)':rssi>-110?'var(--orange)':'var(--red)';
setText('loraSignalQuality', 'Signal: '+sigQual);
setEl('loraSignalQuality', el=>el.style.color=sigColor);
const rssiPct = Math.max(0,Math.min(100,((rssi+120)/60)*100));
setEl('loraRSSIBar', el=>el.style.width=rssiPct+'%');
} else {
setText('loraRSSI', '--');
setText('loraSignalQuality', 'No RSSI data');
setEl('loraSignalQuality', el=>el.style.color='var(--text-muted)');
setEl('loraRSSIBar', el=>el.style.width='0%');
}
// SNR — only show if firmware sent real value
if(hasSNR){
setText('loraSNR', fv(data.loraSNR).toFixed(1)+' dB');
} else {
setText('loraSNR', '--');
}
// Network status badge
const netEl = document.getElementById('loraNetStatus');
if(netEl){
const isActive = data && (data.offlineMode || data.wifiMode==='Offline');
if(!hasLoRaData){
netEl.textContent = '\u25cb Hardware Not Connected';
netEl.style.color = 'var(--text-muted)';
} else if(isActive){
netEl.textContent = '\u25cf Fallback Active';
netEl.style.color = 'var(--orange)';
} else {
netEl.textContent = '\u25cf Standby';
netEl.style.color = '#b08eff';
}
}
}
// ============================================================
// v4.0 — HISTORICAL CHARTS
// ============================================================
let currentChartTab='soilMoisture';
function switchChartTab(tabId,btn){
currentChartTab=tabId;
document.querySelectorAll('.chart-tab').forEach(t=>t.classList.remove('active'));
document.querySelectorAll('.chart-panel').forEach(p=>p.classList.remove('active'));
if(btn)btn.classList.add('active');
const panel=document.getElementById('panel-'+tabId);
if(panel)panel.classList.add('active');
}
function appendChartData(d,owmOK){
if(!chartsReady||!window.Chart)return;
const lbl=new Date().toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});
const B=chartBuffers;
B.labels.push(lbl); B.sm1.push(fv(d.sm1)); B.sm2.push(fv(d.sm2)); B.sm3.push(fv(d.sm3)); B.csmi.push(fv(d.csmi));
B.flow.push(fv(d.flowRate)); B.aiScore.push(fv(d.aiScore)); B.eto.push(fv(d.eto));
B.rainfall.push(fv(d.tipBucket_mm)||(owmOK?fv(d.owm_rain_mm):0));
B.effectiveRain.push(fv(d.effectiveRain)); B.appliedL.push(fv(d.totalLitres));
B.rainfallL.push(fv(d.rainfallContrib)); B.etoLoss.push(fv(d.eto)*(fv(d.plotArea_m2)||6)*0.001);
B.temp.push(fv(d.temperature)); B.hum.push(fv(d.humidity));
Object.keys(B).forEach(k=>{if(B[k].length>CHART_BUF)B[k].shift();});
updateAllCharts();
if(B.sm1.length>1){
const avg=arr=>(arr.reduce((a,b)=>a+b,0)/arr.length).toFixed(1);
setText('cstat-sm1-avg',avg(B.sm1)+'%'); setText('cstat-sm2-avg',avg(B.sm2)+'%');
setText('cstat-sm3-avg',avg(B.sm3)+'%'); setText('cstat-csmi-avg',avg(B.csmi)+'%');
setText('cstat-ai-max',Math.max(...B.aiScore).toFixed(1));
setText('cstat-ai-avg',avg(B.aiScore));
setText('cstat-ai-triggers',B.aiScore.filter(s=>s>=65).length.toString());
}
}
function initAllCharts(){
if(!window.Chart)return;
Chart.defaults.color='#8b949e'; Chart.defaults.borderColor='#30363d';
const co={
responsive:true,maintainAspectRatio:false,animation:{duration:300},
plugins:{legend:{display:false},tooltip:{backgroundColor:'#161b22',borderColor:'#30363d',borderWidth:1,titleColor:'#e6edf3',bodyColor:'#8b949e'}},
scales:{x:{grid:{color:'rgba(48,54,61,0.5)'},ticks:{color:'#8b949e',maxTicksLimit:8,font:{size:10}}},y:{grid:{color:'rgba(48,54,61,0.5)'},ticks:{color:'#8b949e',font:{size:10}}}}
};
const coLeg={...co,plugins:{...co.plugins,legend:{display:true,labels:{color:'#8b949e',boxWidth:10,font:{size:10}}}}};
createChart('chart-soilMoisture',{type:'line',data:{labels:[],datasets:[
{label:'SM1 15cm',data:[],borderColor:'#56d364',backgroundColor:'rgba(86,211,100,0.08)',tension:0.4,pointRadius:2},
{label:'SM2 30cm',data:[],borderColor:'#58a6ff',backgroundColor:'rgba(88,166,255,0.08)',tension:0.4,pointRadius:2},
{label:'SM3 45cm',data:[],borderColor:'#f0a500',backgroundColor:'rgba(240,165,0,0.08)',tension:0.4,pointRadius:2},
{label:'CSMI', data:[],borderColor:'#2dff80',backgroundColor:'rgba(45,255,128,0.1)',tension:0.4,borderWidth:2,pointRadius:2}
]},options:{...coLeg,scales:{...coLeg.scales,y:{...coLeg.scales.y,min:0,max:100,ticks:{...coLeg.scales.y.ticks,callback:v=>v+'%'}}}}});
createChart('chart-irrigation',{type:'bar',data:{labels:[],datasets:[
{label:'Applied (L)',data:[],backgroundColor:'rgba(31,111,235,0.6)',borderColor:'#1f6feb',borderWidth:1}
]},options:{...co}});
createChart('chart-rainfall',{type:'bar',data:{labels:[],datasets:[
{label:'Rainfall (mm)', data:[],backgroundColor:'rgba(88,166,255,0.6)',borderColor:'#58a6ff',borderWidth:1},
{label:'Effective (mm)',data:[],backgroundColor:'rgba(46,160,67,0.5)',borderColor:'#56d364',borderWidth:1}
]},options:{...coLeg}});
createChart('chart-eto',{type:'line',data:{labels:[],datasets:[
{label:'ETo (mm/day)', data:[],borderColor:'#f85149',backgroundColor:'rgba(248,81,73,0.08)',tension:0.4,pointRadius:2},
{label:'Eff. Rain (mm)', data:[],borderColor:'#58a6ff',backgroundColor:'rgba(88,166,255,0.08)',tension:0.4,pointRadius:2}
]},options:{...coLeg}});
createChart('chart-aiScore',{type:'line',data:{labels:[],datasets:[
{label:'AI Score',data:[],borderColor:'#39d353',backgroundColor:'rgba(57,211,83,0.1)',tension:0.4,pointRadius:2,fill:true}
]},options:{...co,scales:{...co.scales,y:{...co.scales.y,min:0,max:120}}}});
createChart('chart-flowRate',{type:'line',data:{labels:[],datasets:[
{label:'Flow Rate (L/min)',data:[],borderColor:'#00d4ff',backgroundColor:'rgba(0,212,255,0.08)',tension:0.4,pointRadius:2}
]},options:{...co}});
createChart('chart-waterBalance',{type:'bar',data:{labels:[],datasets:[
{label:'Applied (L)', data:[],backgroundColor:'rgba(88,166,255,0.6)',borderColor:'#58a6ff',borderWidth:1},
{label:'Rainfall (L)',data:[],backgroundColor:'rgba(46,160,67,0.5)',borderColor:'#56d364',borderWidth:1},
{label:'ETo Loss (L)',data:[],backgroundColor:'rgba(248,81,73,0.4)',borderColor:'#f85149',borderWidth:1}
]},options:{...coLeg}});
createChart('chart-envSensors',{type:'line',data:{labels:[],datasets:[
{label:'Temp (\u00b0C)', data:[],borderColor:'#f85149',backgroundColor:'rgba(248,81,73,0.08)',tension:0.4,pointRadius:2,yAxisID:'y'},
{label:'Humidity (%)',data:[],borderColor:'#58a6ff',backgroundColor:'rgba(88,166,255,0.08)',tension:0.4,pointRadius:2,yAxisID:'y1'}
]},options:{...coLeg,scales:{x:co.scales.x,y:{grid:{color:'rgba(48,54,61,0.5)'},ticks:{color:'#f85149',font:{size:10}},position:'left'},y1:{grid:{color:'rgba(48,54,61,0.2)'},ticks:{color:'#58a6ff',font:{size:10}},position:'right',min:0,max:100}}}});
chartsReady=true;
}
function createChart(id,config){
const canvas=document.getElementById(id); if(!canvas)return;
if(chartInstances[id]){chartInstances[id].destroy();}
try{chartInstances[id]=new Chart(canvas,config);}catch(e){console.warn('Chart create failed:',id,e);}
}
function updateAllCharts(){
if(!chartsReady||!window.Chart)return;
const B=chartBuffers;
updateChart('chart-soilMoisture',B.labels,[B.sm1,B.sm2,B.sm3,B.csmi]);
updateChart('chart-irrigation', B.labels,[B.appliedL]);
updateChart('chart-rainfall', B.labels,[B.rainfall,B.effectiveRain]);
updateChart('chart-eto', B.labels,[B.eto,B.effectiveRain]);
updateChart('chart-aiScore', B.labels,[B.aiScore]);
updateChart('chart-flowRate', B.labels,[B.flow]);
updateChart('chart-waterBalance',B.labels,[B.appliedL,B.rainfallL,B.etoLoss]);
updateChart('chart-envSensors', B.labels,[B.temp,B.hum]);
}
function updateChart(id,labels,dataSets){
const chart=chartInstances[id]; if(!chart)return;
chart.data.labels=[...labels];
dataSets.forEach((ds,i)=>{if(chart.data.datasets[i])chart.data.datasets[i].data=[...ds];});
chart.update('none');
}
// ============================================================
// AI FARM ASSISTANT (original v3.0 fully preserved)
// ============================================================
let aiChatHistory=[], aiIsLoading=false, aiChatBooted=false;
function initAIChat(){
const container=document.getElementById('aiChatMessages'); if(!container)return;
container.innerHTML='';
const offlineMode=lastData&&lastData.offlineMode;
const welcomeMsg=offlineMode?
'\ud83d\udce1 **Offline Mode Active**\n\nSystem autonomous mode mein chal raha hai. Local sensor data use kar raha hoon.\n\n**Poochh sakte ho:**\nMitti ki condition | Pump status | Water budget | Sensor health | Offline sync status':
'\ud83c\udf3e **TSCRIC-LoRa AI Farm Assistant v4.0**\n\nNamaskar! Main aapke farm ka intelligent assistant hoon.\n\nMujhe pata hai:\n\u2022 **Live sensor data** \u2014 SM1/SM2/SM3, CSMI, temperature, humidity, pressure, flow\n\u2022 **AI score** \u2014 SMV, SMA, TPR, ETo components\n\u2022 **Water budget** \u2014 applied, rainfall, balance, efficiency\n\u2022 **Weather** \u2014 OWM forecast, rain probability, tipping bucket\n\u2022 **System** \u2014 pump, LoRa, offline mode, Firebase, sensors\n\n**50+ topics cover karta hoon** \u2014 Hindi ya English mein poochho!\n\nType \`help\` to see all topics, or use **Quick Ask** buttons above.\n\n\u26a0\ufe0f Advisory only \u2014 pump control seedha nahi karta.';
appendAIMessage('model',welcomeMsg,true);
}
function buildFarmContext(){
if(!lastData)return "No live sensor data available yet \u2014 waiting for Firebase connection.";
const d=lastData, _fv=v=>isNaN(parseFloat(v))?0:parseFloat(v);
const sh=[
(!d.safeMode&&_fv(d.sm1)>0)?"SM1(15cm) OK":"SM1(15cm) FAULT",
(!d.safeMode&&_fv(d.sm2)>0)?"SM2(30cm) OK":"SM2(30cm) FAULT",
(!d.safeMode&&_fv(d.sm3)>0)?"SM3(45cm) OK":"SM3(45cm) FAULT",
d.dhtFallback?"DHT22 FAULT [OWM fallback]":"DHT22 OK",
d.bmpFallback?"BMP280 FAULT [OWM fallback]":"BMP280 OK",
d.pipelineFault?"Flow/Pipeline FAULT":"Flow sensor OK"
].join(" | ");
const rainSrc=_fv(d.tipBucket_mm)>0?`Tipping bucket: ${_fv(d.tipBucket_mm).toFixed(2)} mm`:_fv(d.owm_rain_mm)>0?`OWM API: ${_fv(d.owm_rain_mm).toFixed(2)} mm`:_fv(d.estimatedRain)>0?`Sensor estimate: ~${_fv(d.estimatedRain).toFixed(1)} mm`:"No rainfall detected";
return [
`Crop: ${d.crop||'Unknown'} | Stage: ${d.stage||'Unknown'} | GDD: ${_fv(d.gdd).toFixed(0)} \u00b0C\u00b7day`,
`Plot: ${_fv(d.plotArea_m2).toFixed(2)} m\u00b2`,
`SM1@15cm:${_fv(d.sm1).toFixed(1)}% | SM2@30cm:${_fv(d.sm2).toFixed(1)}% | SM3@45cm:${_fv(d.sm3).toFixed(1)}%`,
`CSMI: ${_fv(d.csmi).toFixed(1)}%`,
`Temp:${_fv(d.temperature).toFixed(1)}\u00b0C | Humidity:${_fv(d.humidity).toFixed(0)}% | Pressure:${_fv(d.pressure).toFixed(1)}hPa`,
`ETo:${_fv(d.eto).toFixed(2)}mm/day`,
`AI Score:${_fv(d.aiScore).toFixed(1)}/120 | SMV:${_fv(d.smv).toFixed(4)} | TPR:${_fv(d.tprScore).toFixed(3)}`,
`Rain Prob:${_fv(d.rainProb).toFixed(0)}%`,
rainSrc,
`Effective Rain:${_fv(d.effectiveRain).toFixed(2)}mm`,
`Flow:${_fv(d.flowRate).toFixed(2)}L/min | Total:${_fv(d.totalLitres).toFixed(1)}L`,
`Pump:${d.pump?'ON':'OFF'} | Mode:${d.autoMode?'Auto':'Manual'} | Fault:${d.pipelineFault?'YES':'None'}`,
`Required:${_fv(d.deltaRequired).toFixed(1)}L | Applied:${_fv(d.deltaApplied).toFixed(1)}L | Balance:${_fv(d.deltaBalance).toFixed(1)}L`,
`Mode:${d.offlineMode?'OFFLINE':'ONLINE'} | SafeMode:${d.safeMode?'ACTIVE':'OK'}`,
sh
].join("\n");
}
async function sendAIMessage(){
const input=document.getElementById('aiUserInput'); if(!input)return;