File size: 55,845 Bytes
a06557f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
"""

Smart Waste Segregation System - Hardware-Realistic Simulator with Real Model

Simulates complete edge deployment with realistic sensor protocols, motor control, and hardware timing

Dependencies: pip install streamlit numpy pillow opencv-python-headless sqlite3 torch torchvision

"""

import streamlit as st
import sqlite3
import json
import time
import random
import numpy as np
from PIL import Image
import io
import base64
from datetime import datetime
from dataclasses import dataclass, asdict
from typing import Dict, List, Optional, Tuple
import threading
import queue
from enum import Enum
import os

# PyTorch imports
import torch
import torch.nn as nn
from torchvision import transforms, models

# ==================== HARDWARE CONSTANTS ====================
class HardwareConfig:
    """Realistic hardware specifications"""
    # Ultrasonic Sensor (HC-SR04)
    ULTRASONIC_MIN_DISTANCE = 2.0  # cm
    ULTRASONIC_MAX_DISTANCE = 400.0  # cm
    ULTRASONIC_ACCURACY = 0.3  # cm
    ULTRASONIC_READ_TIME = 0.015  # seconds (15ms)
    
    # Capacitive Moisture Sensor
    MOISTURE_MIN_VOLTAGE = 0.0  # V (dry)
    MOISTURE_MAX_VOLTAGE = 3.3  # V (wet)
    MOISTURE_ADC_RESOLUTION = 12  # bits (4096 levels)
    MOISTURE_READ_TIME = 0.010  # seconds (10ms)
    
    # Load Cell (HX711)
    WEIGHT_MAX_CAPACITY = 5000.0  # grams (5kg)
    WEIGHT_RESOLUTION = 0.1  # grams
    WEIGHT_STABILIZATION_TIME = 0.5  # seconds
    WEIGHT_READ_TIME = 0.100  # seconds (100ms)
    
    # Servo Motor (MG996R)
    SERVO_MIN_ANGLE = 0
    SERVO_MAX_ANGLE = 180
    SERVO_SPEED = 60  # degrees per 0.17 seconds (at 4.8V)
    SERVO_CURRENT_IDLE = 10  # mA
    SERVO_CURRENT_MOVING = 500  # mA
    SERVO_TORQUE = 11  # kg-cm
    
    # Camera (Raspberry Pi Camera Module v2)
    CAMERA_RESOLUTION = (1920, 1080)
    CAMERA_CAPTURE_TIME = 0.150  # seconds
    CAMERA_WARMUP_TIME = 2.0  # seconds
    
    # Edge Device (Raspberry Pi 4)
    CPU_CORES = 4
    RAM_MB = 4096
    INFERENCE_OVERHEAD = 0.050  # seconds

# ==================== DATABASE SETUP ====================
def init_database():
    """Initialize SQLite database with required tables"""
    conn = sqlite3.connect('waste_segregation.db', check_same_thread=False)
    cursor = conn.cursor()
    
    # Check if we need to migrate old database
    try:
        cursor.execute("SELECT total_pipeline_time_ms FROM events LIMIT 1")
    except sqlite3.OperationalError:
        # Column doesn't exist, need to add it
        try:
            cursor.execute("ALTER TABLE events ADD COLUMN total_pipeline_time_ms REAL")
            conn.commit()
            st.info("βœ… Database schema updated successfully")
        except sqlite3.OperationalError:
            # Table doesn't exist at all, will be created below
            pass
    
    # Events table
    cursor.execute('''

        CREATE TABLE IF NOT EXISTS events (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            timestamp TEXT NOT NULL,

            image_name TEXT,

            waste_class TEXT NOT NULL,

            confidence REAL NOT NULL,

            distance_cm REAL,

            moisture_raw INTEGER,

            moisture_percent REAL,

            weight_g REAL,

            servo_angle INTEGER,

            inference_time_ms REAL,

            total_pipeline_time_ms REAL,

            status TEXT,

            power_consumption_mw REAL

        )

    ''')
    
    # Telemetry table
    cursor.execute('''

        CREATE TABLE IF NOT EXISTS telemetry (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            timestamp TEXT NOT NULL,

            component TEXT NOT NULL,

            data TEXT NOT NULL

        )

    ''')
    
    # Hardware diagnostics table
    cursor.execute('''

        CREATE TABLE IF NOT EXISTS hardware_diagnostics (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            timestamp TEXT NOT NULL,

            component TEXT NOT NULL,

            status TEXT NOT NULL,

            voltage REAL,

            current_ma REAL,

            temperature_c REAL,

            error_count INTEGER

        )

    ''')
    
    conn.commit()
    return conn

# ==================== DATA MODELS ====================
@dataclass
class SensorReading:
    """Raw sensor reading with hardware-realistic properties"""
    value: float
    raw_value: int  # ADC value
    voltage: float
    read_time_ms: float
    noise_level: float
    timestamp: str

@dataclass
class SensorData:
    """Complete sensor suite readings"""
    distance_cm: float
    distance_raw: SensorReading
    moisture_percent: float
    moisture_raw: SensorReading
    weight_g: float
    weight_raw: SensorReading
    temperature: float
    timestamp: str
    total_read_time_ms: float

@dataclass
class InferenceResult:
    """AI model inference output with edge device metrics"""
    waste_class: str
    confidence: float
    inference_time_ms: float
    preprocessing_time_ms: float
    postprocessing_time_ms: float
    probabilities: Dict[str, float]
    model_version: str
    device_temperature: float
    cpu_usage_percent: float

@dataclass
class MotorControl:
    """Servo motor control with realistic physics"""
    target_angle: int
    current_angle: int
    start_angle: int
    status: str
    duration_ms: float
    power_consumption_mw: float
    torque_applied: float
    movement_profile: List[Tuple[float, int]]  # (time_ms, angle)

class SensorStatus(Enum):
    """Sensor operational status"""
    READY = "ready"
    READING = "reading"
    STABILIZING = "stabilizing"
    ERROR = "error"
    CALIBRATING = "calibrating"

# ==================== REALISTIC SENSOR SIMULATION ====================
class UltrasonicSensor:
    """HC-SR04 Ultrasonic Sensor Simulation"""
    
    def __init__(self):
        self.status = SensorStatus.READY
        self.error_count = 0
        self.last_reading = None
        self.calibration_offset = random.uniform(-0.2, 0.2)
    
    def trigger_read(self, actual_distance: float) -> SensorReading:
        """Simulate ultrasonic pulse and echo timing"""
        start_time = time.time()
        self.status = SensorStatus.READING
        
        # Simulate trigger pulse (10ΞΌs) and echo wait
        time.sleep(HardwareConfig.ULTRASONIC_READ_TIME)
        
        # Add realistic noise and environmental factors
        noise = random.gauss(0, HardwareConfig.ULTRASONIC_ACCURACY)
        temperature_factor = 1.0 + random.uniform(-0.02, 0.02)
        
        # Simulate occasional read errors (1% chance)
        if random.random() < 0.01:
            self.error_count += 1
            measured_distance = -1.0  # Error code
        else:
            measured_distance = (actual_distance + noise + self.calibration_offset) * temperature_factor
            measured_distance = max(HardwareConfig.ULTRASONIC_MIN_DISTANCE, 
                                   min(HardwareConfig.ULTRASONIC_MAX_DISTANCE, measured_distance))
        
        # Calculate echo time (distance = speed * time / 2)
        echo_time_us = (measured_distance * 2) / 0.0343 if measured_distance > 0 else 0
        
        read_time = (time.time() - start_time) * 1000
        self.status = SensorStatus.READY
        self.last_reading = measured_distance
        
        return SensorReading(
            value=round(measured_distance, 2),
            raw_value=int(echo_time_us),
            voltage=3.3,
            read_time_ms=round(read_time, 3),
            noise_level=abs(noise),
            timestamp=datetime.now().isoformat()
        )

class MoistureSensor:
    """Capacitive Soil Moisture Sensor Simulation"""
    
    def __init__(self):
        self.status = SensorStatus.READY
        self.adc_resolution = 2 ** HardwareConfig.MOISTURE_ADC_RESOLUTION
        self.calibration_dry = random.randint(3200, 3400)
        self.calibration_wet = random.randint(1200, 1400)
    
    def read_moisture(self, actual_moisture: float) -> SensorReading:
        """Read capacitive moisture sensor via ADC"""
        start_time = time.time()
        self.status = SensorStatus.READING
        
        time.sleep(HardwareConfig.MOISTURE_READ_TIME)
        
        # Convert moisture percentage to ADC value
        adc_range = self.calibration_dry - self.calibration_wet
        adc_value = self.calibration_dry - (actual_moisture * adc_range)
        
        # Add ADC noise (Β±2 LSB typical)
        adc_noise = random.randint(-2, 2)
        adc_value = int(adc_value + adc_noise)
        adc_value = max(0, min(self.adc_resolution - 1, adc_value))
        
        # Convert ADC to voltage
        voltage = (adc_value / self.adc_resolution) * HardwareConfig.MOISTURE_MAX_VOLTAGE
        
        # Convert back to percentage
        measured_moisture = (self.calibration_dry - adc_value) / adc_range
        measured_moisture = max(0.0, min(1.0, measured_moisture))
        
        read_time = (time.time() - start_time) * 1000
        self.status = SensorStatus.READY
        
        return SensorReading(
            value=round(measured_moisture, 4),
            raw_value=adc_value,
            voltage=round(voltage, 3),
            read_time_ms=round(read_time, 3),
            noise_level=abs(adc_noise / adc_range) if adc_range != 0 else 0.0,
            timestamp=datetime.now().isoformat()
        )

class LoadCellSensor:
    """HX711 Load Cell Amplifier Simulation"""
    
    def __init__(self):
        self.status = SensorStatus.READY
        self.tare_value = random.randint(-50000, 50000)
        self.calibration_factor = random.uniform(420, 450)
        self.last_stable_reading = 0.0
        self.reading_buffer = []
    
    def read_weight(self, actual_weight: float) -> SensorReading:
        """Read load cell with stabilization"""
        start_time = time.time()
        self.status = SensorStatus.STABILIZING
        
        # Simulate mechanical settling time
        time.sleep(HardwareConfig.WEIGHT_STABILIZATION_TIME * 0.2)
        
        self.status = SensorStatus.READING
        
        # Take multiple readings and average
        readings = []
        for _ in range(10):
            adc_value = self.tare_value + int(actual_weight * self.calibration_factor)
            noise = random.randint(-2, 2)
            vibration = random.gauss(0, 5)
            adc_value += int(noise + vibration)
            readings.append(adc_value)
            time.sleep(HardwareConfig.WEIGHT_READ_TIME / 10)
        
        # Average and filter
        avg_adc = int(np.mean(readings))
        measured_weight = (avg_adc - self.tare_value) / self.calibration_factor
        measured_weight = max(0.0, min(HardwareConfig.WEIGHT_MAX_CAPACITY, measured_weight))
        measured_weight = round(measured_weight / HardwareConfig.WEIGHT_RESOLUTION) * HardwareConfig.WEIGHT_RESOLUTION
        
        read_time = (time.time() - start_time) * 1000
        self.status = SensorStatus.READY
        self.last_stable_reading = measured_weight
        
        return SensorReading(
            value=round(measured_weight, 2),
            raw_value=avg_adc,
            voltage=3.3,
            read_time_ms=round(read_time, 3),
            noise_level=np.std(readings) / self.calibration_factor,
            timestamp=datetime.now().isoformat()
        )

class SensorHub:
    """Integrated sensor management system"""
    
    def __init__(self):
        self.ultrasonic = UltrasonicSensor()
        self.moisture = MoistureSensor()
        self.load_cell = LoadCellSensor()
        self.temperature = 28.0
        
        self.baseline = {
            'distance_cm': 25.0,
            'moisture': 0.3,
            'weight_g': 150.0
        }
    
    def read_all_sensors(self) -> SensorData:
        """Read all sensors with realistic timing"""
        start_time = time.time()
        
        distance_reading = self.ultrasonic.trigger_read(self.baseline['distance_cm'])
        moisture_reading = self.moisture.read_moisture(self.baseline['moisture'])
        weight_reading = self.load_cell.read_weight(self.baseline['weight_g'])
        
        self.temperature = 28.0 + random.uniform(-2, 2)
        
        total_time = (time.time() - start_time) * 1000
        
        return SensorData(
            distance_cm=distance_reading.value,
            distance_raw=distance_reading,
            moisture_percent=moisture_reading.value * 100,
            moisture_raw=moisture_reading,
            weight_g=weight_reading.value,
            weight_raw=weight_reading,
            temperature=round(self.temperature, 2),
            timestamp=datetime.now().isoformat(),
            total_read_time_ms=round(total_time, 2)
        )
    
    def set_baseline(self, distance=None, moisture=None, weight=None):
        """Update sensor baselines for simulation"""
        if distance is not None: 
            self.baseline['distance_cm'] = distance
        if moisture is not None: 
            self.baseline['moisture'] = moisture
        if weight is not None: 
            self.baseline['weight_g'] = weight

# ==================== REAL EDGE AI INFERENCE ====================
class EdgeAIProcessor:
    """Edge device AI inference with REAL trained model"""
    
    def __init__(self, model_path: Optional[str] = None):
        self.model_path = model_path or 'best_trash_classifier.pth'
        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        self.model = None
        self.model_loaded = False
        self.model_version = "v1.0.0-mock"
        self.warmup_complete = False
        self.classes = []
        
        # Edge device specs
        self.device_temp = 45.0
        self.cpu_usage = 25.0
        
        # Image preprocessing transform
        self.transform = transforms.Compose([
            transforms.Resize((224, 224)),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        ])
        
        # Try to load real model
        self.load_model()
    
    def load_model(self):
        """Load the trained PyTorch model"""
        try:
            if not os.path.exists(self.model_path):
                st.warning(f"⚠️ Model file '{self.model_path}' not found. Using mock inference.")
                self.classes = ["organic", "recyclable", "non-recyclable"]
                return
            
            # Load checkpoint
            checkpoint = torch.load(self.model_path, map_location=self.device)
            
            # Get class names from checkpoint
            self.classes = checkpoint.get('class_names', ["organic", "recyclable", "non-recyclable"])
            num_classes = len(self.classes)
            
            # Build model architecture (same as training)
            self.model = models.efficientnet_v2_s(weights=None)
            num_features = self.model.classifier[1].in_features
            self.model.classifier = nn.Sequential(
                nn.Dropout(p=0.3, inplace=True),
                nn.Linear(num_features, 512),
                nn.ReLU(),
                nn.Dropout(p=0.3),
                nn.Linear(512, num_classes)
            )
            
            # Load weights
            self.model.load_state_dict(checkpoint['model_state_dict'])
            self.model = self.model.to(self.device)
            self.model.eval()
            
            self.model_loaded = True
            self.model_version = f"v1.0.0-efficientnet-epoch{checkpoint.get('epoch', 'unknown')}"
            
            st.success(f"βœ… Model loaded successfully! Classes: {self.classes}")
            
        except Exception as e:
            st.error(f"❌ Failed to load model: {e}")
            st.info("Using mock inference mode")
            self.classes = ["organic", "recyclable", "non-recyclable"]
            self.model_loaded = False
    
    def warmup(self):
        """Warm up model (first inference is slower)"""
        if not self.warmup_complete and self.model_loaded:
            try:
                dummy_input = torch.randn(1, 3, 224, 224).to(self.device)
                with torch.no_grad():
                    _ = self.model(dummy_input)
                self.warmup_complete = True
            except:
                pass
    
    def preprocess_image(self, image: Image.Image) -> Tuple[torch.Tensor, float]:
        """Preprocess image for inference with timing"""
        start_time = time.time()
        
        # Convert to RGB if needed
        if image.mode != 'RGB':
            image = image.convert('RGB')
        
        # Apply transforms
        img_tensor = self.transform(image)
        img_tensor = img_tensor.unsqueeze(0)  # Add batch dimension
        
        preprocess_time = (time.time() - start_time) * 1000
        return img_tensor, preprocess_time
    
    def infer(self, image: Image.Image, sensor_data: SensorData) -> InferenceResult:
        """Run inference with real or mock model"""
        self.warmup()
        
        # Preprocessing
        input_tensor, preprocess_time = self.preprocess_image(image)
        
        # Inference
        inference_start = time.time()
        
        if self.model_loaded and self.model is not None:
            # REAL MODEL INFERENCE
            try:
                input_tensor = input_tensor.to(self.device)
                
                with torch.no_grad():
                    outputs = self.model(input_tensor)
                    logits = outputs[0].cpu().numpy()
                
            except Exception as e:
                st.error(f"Inference error: {e}")
                # Fallback to mock
                logits = self._mock_inference_with_fusion(sensor_data)
        else:
            # MOCK INFERENCE with sensor fusion
            logits = self._mock_inference_with_fusion(sensor_data)
            # Simulate realistic inference time
            time.sleep(random.uniform(0.050, 0.150))
        
        inference_time = (time.time() - inference_start) * 1000
        
        # Postprocessing
        postprocess_start = time.time()
        
        # Softmax
        exp_logits = np.exp(logits - np.max(logits))
        probs = exp_logits / np.sum(exp_logits)
        
        class_idx = int(np.argmax(probs))
        waste_class = self.classes[class_idx]
        confidence = float(probs[class_idx])
        
        prob_dict = {cls: float(probs[i]) for i, cls in enumerate(self.classes)}
        
        postprocess_time = (time.time() - postprocess_start) * 1000
        
        # Update device metrics
        self.device_temp = min(85.0, self.device_temp + random.uniform(-1, 2))
        self.cpu_usage = min(100.0, max(20.0, self.cpu_usage + random.uniform(-10, 15)))
        
        return InferenceResult(
            waste_class=waste_class,
            confidence=round(confidence, 4),
            inference_time_ms=round(inference_time, 2),
            preprocessing_time_ms=round(preprocess_time, 2),
            postprocessing_time_ms=round(postprocess_time, 2),
            probabilities=prob_dict,
            model_version=self.model_version,
            device_temperature=round(self.device_temp, 1),
            cpu_usage_percent=round(self.cpu_usage, 1)
        )
    
    def _mock_inference_with_fusion(self, sensor_data: SensorData) -> np.ndarray:
        """Mock inference using multi-modal sensor fusion"""
        logits = np.random.randn(len(self.classes)) * 0.3
        
        # Moisture-based classification
        moisture = sensor_data.moisture_percent / 100.0
        if moisture > 0.5:
            logits[0] += 2.5  # High moisture -> organic
        elif moisture < 0.2:
            logits[1] += 1.5  # Low moisture -> recyclable
        else:
            logits[2] += 1.0  # Medium moisture -> non-recyclable
        
        # Weight-based refinement
        weight = sensor_data.weight_g
        if weight < 50:
            logits[1] += 0.5  # Light items often recyclable
        elif weight > 300:
            logits[2] += 0.5  # Heavy items often non-recyclable
        
        # Distance-based confidence adjustment
        distance_factor = 1.0 - (sensor_data.distance_cm / 100.0)
        logits *= (0.7 + 0.3 * distance_factor)
        
        return logits

# ==================== REALISTIC MOTOR CONTROL ====================
class ServoMotor:
    """MG996R Servo Motor Simulation with realistic physics"""
    
    # Bin routing angles
    BIN_POSITIONS = {
        "organic": 0,
        "recyclable": 90,
        "non-recyclable": 180
    }
    
    def __init__(self):
        self.current_angle = 90
        self.target_angle = 90
        self.is_moving = False
        self.speed_deg_per_sec = HardwareConfig.SERVO_SPEED / 0.17
        self.voltage = 5.0
        self.current_ma = HardwareConfig.SERVO_CURRENT_IDLE
        self.position_history = []
    
    def calculate_movement_profile(self, start: int, end: int, duration_s: float) -> List[Tuple[float, int]]:
        """Calculate realistic servo movement with acceleration/deceleration"""
        profile = []
        steps = max(10, int(duration_s * 50))
        
        for i in range(steps + 1):
            t = i / steps
            
            # S-curve motion profile
            if t < 0.3:
                progress = (t / 0.3) ** 2 * 0.3
            elif t > 0.7:
                progress = 1.0 - ((1.0 - t) / 0.3) ** 2 * 0.3
            else:
                progress = 0.3 + (t - 0.3) * (0.4 / 0.4)
            
            angle = int(start + (end - start) * progress)
            time_ms = t * duration_s * 1000
            profile.append((round(time_ms, 1), angle))
        
        return profile
    
    def move_to_bin(self, waste_class: str) -> MotorControl:
        """Move servo to route waste to correct bin with realistic physics"""
        target = self.BIN_POSITIONS.get(waste_class, 90)
        start_angle = self.current_angle
        
        start_time = time.time()
        self.is_moving = True
        self.target_angle = target
        self.current_ma = HardwareConfig.SERVO_CURRENT_MOVING

        angle_distance = abs(target - start_angle)
        duration_s = (angle_distance / 60.0) * 0.17

        movement_profile = self.calculate_movement_profile(start_angle, target, duration_s)

        # Simulate movement
        time.sleep(duration_s * 0.3)

        avg_current = (HardwareConfig.SERVO_CURRENT_MOVING + HardwareConfig.SERVO_CURRENT_IDLE) / 2
        power_mw = self.voltage * avg_current
        torque_applied = HardwareConfig.SERVO_TORQUE * 0.7

        self.current_angle = target
        self.is_moving = False
        self.current_ma = HardwareConfig.SERVO_CURRENT_IDLE
        
        actual_duration = (time.time() - start_time) * 1000
        
        return MotorControl(
            target_angle=target,
            current_angle=target,
            start_angle=start_angle,
            status="completed",
            duration_ms=round(actual_duration, 2),
            power_consumption_mw=round(power_mw, 2),
            torque_applied=round(torque_applied, 2),
            movement_profile=movement_profile
        )
    
    def get_diagnostics(self) -> dict:
        """Get motor diagnostic information"""
        return {
            'current_angle': self.current_angle,
            'target_angle': self.target_angle,
            'is_moving': self.is_moving,
            'current_ma': self.current_ma,
            'voltage': self.voltage,
            'temperature_c': 35.0 + random.uniform(-2, 5)
        }

# ==================== CAMERA SIMULATION ====================
class CameraModule:
    """Raspberry Pi Camera Module v2 Simulation"""
    
    def __init__(self):
        self.resolution = HardwareConfig.CAMERA_RESOLUTION
        self.is_warmed_up = False
        self.frame_count = 0
    
    def warmup(self):
        """Camera warmup (auto-exposure, white balance)"""
        if not self.is_warmed_up:
            time.sleep(HardwareConfig.CAMERA_WARMUP_TIME * 0.1)
            self.is_warmed_up = True
    
    def capture_image(self, uploaded_image: Optional[Image.Image] = None) -> Tuple[Image.Image, float]:
        """Capture image with realistic timing"""
        self.warmup()
        
        start_time = time.time()
        time.sleep(HardwareConfig.CAMERA_CAPTURE_TIME * 0.5)
        
        if uploaded_image:
            image = uploaded_image
        else:
            image = self._generate_synthetic_waste()
        
        capture_time = (time.time() - start_time) * 1000
        self.frame_count += 1
        
        return image, capture_time

    def _generate_synthetic_waste(self) -> Image.Image:
        """Generate synthetic waste image for testing"""
        colors = [
            (139, 90, 43),   # Brown (organic)
            (200, 200, 200), # Gray (recyclable)
            (50, 50, 50)     # Dark (non-recyclable)
        ]
        color = random.choice(colors)
        color = tuple(max(0, min(255, c + random.randint(-30, 30))) for c in color)
        image = Image.new('RGB', (224, 224), color=color)
        return image

# ==================== DATA LOGGER ====================
class DataLogger:
    """Logs all events, telemetry, and hardware diagnostics to SQLite"""
    
    def __init__(self, conn):
        self.conn = conn
        self.lock = threading.Lock()
    
    def log_event(self, sensor_data: SensorData, inference: InferenceResult, 

                  motor: MotorControl, image_name: str = "sample.jpg"):
        """Log complete segregation event with hardware metrics"""
        with self.lock:
            cursor = self.conn.cursor()
            
            total_time = (sensor_data.total_read_time_ms + 
                         inference.preprocessing_time_ms +
                         inference.inference_time_ms +
                         inference.postprocessing_time_ms +
                         motor.duration_ms)
            
            cursor.execute('''

                INSERT INTO events (

                    timestamp, image_name, waste_class, confidence,

                    distance_cm, moisture_raw, moisture_percent, weight_g, 

                    servo_angle, inference_time_ms, total_pipeline_time_ms,

                    status, power_consumption_mw

                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

            ''', (
                sensor_data.timestamp,
                image_name,
                inference.waste_class,
                inference.confidence,
                sensor_data.distance_cm,
                sensor_data.moisture_raw.raw_value,
                sensor_data.moisture_percent,
                sensor_data.weight_g,
                motor.target_angle,
                inference.inference_time_ms,
                total_time,
                motor.status,
                motor.power_consumption_mw
            ))
            self.conn.commit()
    
    def log_telemetry(self, component: str, data: dict):
        """Log component telemetry"""
        with self.lock:
            cursor = self.conn.cursor()
            cursor.execute('''

                INSERT INTO telemetry (timestamp, component, data)

                VALUES (?, ?, ?)

            ''', (
                datetime.now().isoformat(),
                component,
                json.dumps(data)
            ))
            self.conn.commit()
    
    def log_hardware_diagnostics(self, component: str, status: str, 

                                 voltage: float = 0, current_ma: float = 0,

                                 temperature: float = 0, error_count: int = 0):
        """Log hardware diagnostics"""
        with self.lock:
            cursor = self.conn.cursor()
            cursor.execute('''

                INSERT INTO hardware_diagnostics 

                (timestamp, component, status, voltage, current_ma, temperature_c, error_count)

                VALUES (?, ?, ?, ?, ?, ?, ?)

            ''', (
                datetime.now().isoformat(),
                component,
                status,
                voltage,
                current_ma,
                temperature,
                error_count
            ))
            self.conn.commit()
    
    def get_recent_events(self, limit: int = 10) -> List[dict]:
        """Retrieve recent events"""
        cursor = self.conn.cursor()
        cursor.execute('''

            SELECT * FROM events 

            ORDER BY timestamp DESC 

            LIMIT ?

        ''', (limit,))
        
        columns = [desc[0] for desc in cursor.description]
        return [dict(zip(columns, row)) for row in cursor.fetchall()]
    
    def get_statistics(self) -> dict:
        """Get overall statistics"""
        cursor = self.conn.cursor()
        
        # Class distribution
        cursor.execute('''

            SELECT waste_class, COUNT(*) as count 

            FROM events 

            GROUP BY waste_class

        ''')
        class_dist = dict(cursor.fetchall())
        
        # Average confidence
        cursor.execute('SELECT AVG(confidence) FROM events')
        avg_conf = cursor.fetchone()[0] or 0
        
        # Average pipeline time
        cursor.execute('SELECT AVG(total_pipeline_time_ms) FROM events')
        avg_time = cursor.fetchone()[0] or 0
        
        # Total events
        cursor.execute('SELECT COUNT(*) FROM events')
        total = cursor.fetchone()[0]
        
        # Total power consumption
        cursor.execute('SELECT SUM(power_consumption_mw) FROM events')
        total_power = cursor.fetchone()[0] or 0
        
        return {
            'total_events': total,
            'class_distribution': class_dist,
            'average_confidence': round(avg_conf, 4),
            'average_pipeline_time_ms': round(avg_time, 2),
            'total_power_consumption_mwh': round(total_power / 3600000, 4)
        }
    
    def get_hardware_diagnostics(self, limit: int = 20) -> List[dict]:
        """Get recent hardware diagnostics"""
        cursor = self.conn.cursor()
        cursor.execute('''

            SELECT * FROM hardware_diagnostics 

            ORDER BY timestamp DESC 

            LIMIT ?

        ''', (limit,))
        
        columns = [desc[0] for desc in cursor.description]
        return [dict(zip(columns, row)) for row in cursor.fetchall()]

# ==================== STREAMLIT DASHBOARD ====================
def main():
    st.set_page_config(
        page_title="Smart Waste Segregation System",
        page_icon="♻️",
        layout="wide"
    )
    
    # Initialize components
    if 'db_conn' not in st.session_state:
        st.session_state.db_conn = init_database()
    if 'sensor_hub' not in st.session_state:
        st.session_state.sensor_hub = SensorHub()
    if 'edge_ai' not in st.session_state:
        st.session_state.edge_ai = EdgeAIProcessor()
    if 'servo' not in st.session_state:
        st.session_state.servo = ServoMotor()
    if 'camera' not in st.session_state:
        st.session_state.camera = CameraModule()
    if 'logger' not in st.session_state:
        st.session_state.logger = DataLogger(st.session_state.db_conn)
    if 'execution_log' not in st.session_state:
        st.session_state.execution_log = []
    
    # Header
    st.title("♻️ Smart Waste Segregation System - Hardware Simulator")
    st.markdown("**IDEA-ONE Hackathon | Team Trackify | Edge AI Deployment Demo**")
    
    # Model status indicator
    if st.session_state.edge_ai.model_loaded:
        st.success(f"βœ… Real Model Loaded: {st.session_state.edge_ai.model_version}")
    else:
        st.warning("⚠️ Using Mock Inference (Model not found)")
    
    st.markdown("---")
    
    # Hardware status bar
    col1, col2, col3, col4, col5 = st.columns(5)
    with col1:
        st.metric("🌑️ Device Temp", f"{st.session_state.edge_ai.device_temp:.1f}°C")
    with col2:
        st.metric("πŸ’» CPU Usage", f"{st.session_state.edge_ai.cpu_usage:.1f}%")
    with col3:
        st.metric("⚑ Servo Angle", f"{st.session_state.servo.current_angle}°")
    with col4:
        st.metric("πŸ“· Frames", st.session_state.camera.frame_count)
    with col5:
        st.metric("πŸ”Œ Servo Current", f"{st.session_state.servo.current_ma} mA")
    
    st.markdown("---")
    
    # Tabs
    tab1, tab2, tab3, tab4, tab5 = st.tabs([
        "πŸ”„ Live Pipeline", 
        "πŸ“Š Dashboard", 
        "πŸ“‹ Event Logs", 
        "πŸ”§ Hardware Diagnostics",
        "πŸ“‘ Sensor Details"
    ])
    
    # ==================== TAB 1: LIVE PIPELINE ====================
    with tab1:
        col1, col2 = st.columns([1, 2])
        
        with col1:
            st.subheader("βš™οΈ Sensor Configuration")
            
            st.markdown("##### Ultrasonic Sensor (HC-SR04)")
            distance = st.slider("Distance (cm)", 2.0, 60.0, 25.0, 0.5)
            
            st.markdown("##### Capacitive Moisture Sensor")
            moisture = st.slider("Moisture (%)", 0.0, 100.0, 30.0, 1.0) / 100.0
            
            st.markdown("##### Load Cell (HX711)")
            weight = st.slider("Weight (g)", 0.0, 1000.0, 150.0, 1.0)
            
            st.session_state.sensor_hub.set_baseline(distance, moisture, weight)
            
            st.markdown("---")
            
            # Image upload
            st.subheader("πŸ“· Camera Input")
            uploaded_file = st.file_uploader(
                "Upload waste image (optional)", 
                type=['jpg', 'png', 'jpeg']
            )
            
            if uploaded_file:
                image = Image.open(uploaded_file)
                st.image(image, width=250, caption="Uploaded Image")
            else:
                st.info("No image uploaded. Will use synthetic waste image.")
            
            st.markdown("---")
            
            # Execute button
            if st.button("πŸš€ Run Complete Pipeline", type="primary", use_container_width=True):
                st.session_state.execution_log = []
                
                with st.spinner("Processing..."):
                    pipeline_start = time.time()
                    
                    # Step 1: Camera capture
                    st.session_state.execution_log.append("πŸ“· Capturing image from camera...")
                    try:
                        if uploaded_file:
                            image = Image.open(uploaded_file)
                            capture_time = 0
                        else:
                            image, capture_time = st.session_state.camera.capture_image()
                        st.session_state.execution_log.append(f"   βœ“ Image captured ({capture_time:.2f}ms)")
                    except Exception as e:
                        st.session_state.execution_log.append(f"   ⚠️ Image capture failed: {e}")
                        st.session_state.execution_log.append("   πŸ”„ Generating synthetic image...")
                        image = st.session_state.camera._generate_synthetic_waste()
                        capture_time = 0
                    
                    # Step 2: Sensor reading
                    st.session_state.execution_log.append("πŸ“‘ Reading sensor suite...")
                    sensor_data = st.session_state.sensor_hub.read_all_sensors()
                    st.session_state.execution_log.append(f"   βœ“ Sensors read ({sensor_data.total_read_time_ms:.2f}ms)")
                    st.session_state.execution_log.append(f"      - Distance: {sensor_data.distance_cm} cm")
                    st.session_state.execution_log.append(f"      - Moisture: {sensor_data.moisture_percent:.1f}%")
                    st.session_state.execution_log.append(f"      - Weight: {sensor_data.weight_g} g")
                    
                    # Log sensor telemetry
                    st.session_state.logger.log_telemetry("sensors", {
                        'distance': asdict(sensor_data.distance_raw),
                        'moisture': asdict(sensor_data.moisture_raw),
                        'weight': asdict(sensor_data.weight_raw),
                        'temperature': sensor_data.temperature
                    })
                    
                    # Step 3: AI Inference
                    st.session_state.execution_log.append("πŸ€– Running edge AI inference...")
                    inference = st.session_state.edge_ai.infer(image, sensor_data)
                    st.session_state.execution_log.append(f"   βœ“ Inference complete ({inference.inference_time_ms:.2f}ms)")
                    st.session_state.execution_log.append(f"      - Preprocessing: {inference.preprocessing_time_ms:.2f}ms")
                    st.session_state.execution_log.append(f"      - Model inference: {inference.inference_time_ms:.2f}ms")
                    st.session_state.execution_log.append(f"      - Postprocessing: {inference.postprocessing_time_ms:.2f}ms")
                    st.session_state.execution_log.append(f"      - Classification: {inference.waste_class} ({inference.confidence*100:.2f}%)")
                    
                    # Log AI telemetry
                    st.session_state.logger.log_telemetry("edge_ai", asdict(inference))
                    
                    # Step 4: Motor control
                    st.session_state.execution_log.append(f"βš™οΈ Actuating servo to {inference.waste_class} bin...")
                    motor = st.session_state.servo.move_to_bin(inference.waste_class)
                    st.session_state.execution_log.append(f"   βœ“ Servo moved ({motor.duration_ms:.2f}ms)")
                    st.session_state.execution_log.append(f"      - Start angle: {motor.start_angle}Β°")
                    st.session_state.execution_log.append(f"      - Target angle: {motor.target_angle}Β°")
                    st.session_state.execution_log.append(f"      - Power consumption: {motor.power_consumption_mw:.2f} mW")
                    
                    # Log motor telemetry
                    st.session_state.logger.log_telemetry("servo_motor", asdict(motor))
                    
                    # Step 5: Log event
                    st.session_state.execution_log.append("πŸ’Ύ Logging event to database...")
                    image_name = uploaded_file.name if uploaded_file else "synthetic.jpg"
                    st.session_state.logger.log_event(sensor_data, inference, motor, image_name)
                    
                    # Log hardware diagnostics
                    st.session_state.logger.log_hardware_diagnostics(
                        "ultrasonic", "operational", 3.3, 15, sensor_data.temperature,
                        st.session_state.sensor_hub.ultrasonic.error_count
                    )
                    st.session_state.logger.log_hardware_diagnostics(
                        "servo_motor", "operational", 5.0, st.session_state.servo.current_ma,
                        35.0, 0
                    )
                    
                    pipeline_time = (time.time() - pipeline_start) * 1000
                    st.session_state.execution_log.append(f"βœ… Pipeline completed! Total time: {pipeline_time:.2f}ms")

                    # Store results
                    st.session_state.last_result = {
                        'sensor': sensor_data,
                        'inference': inference,
                        'motor': motor,
                        'image': image,
                        'pipeline_time': pipeline_time
                    }
                
                st.success("βœ… Segregation completed successfully!")
                st.balloons()
        
        with col2:
            st.subheader("πŸ”„ Pipeline Execution Log")
            
            # Execution log
            if st.session_state.execution_log:
                log_container = st.container()
                with log_container:
                    for log_entry in st.session_state.execution_log:
                        if "βœ“" in log_entry or "βœ…" in log_entry:
                            st.success(log_entry)
                        elif "πŸ“‘" in log_entry or "πŸ€–" in log_entry or "βš™οΈ" in log_entry or "πŸ“·" in log_entry:
                            st.info(log_entry)
                        else:
                            st.write(log_entry)
                
                st.markdown("---")
                
                # Results
                if 'last_result' in st.session_state:
                    res = st.session_state.last_result
                    
                    st.subheader("πŸ“Š Pipeline Results")
                    
                    # Display captured image
                    col_img, col_metrics = st.columns([1, 2])
                    
                    with col_img:
                        st.image(res['image'], caption="Processed Image", use_container_width=True)
                    
                    with col_metrics:
                        st.metric("πŸ—‘οΈ Classification", res['inference'].waste_class.upper())
                        st.metric("πŸ“Š Confidence", f"{res['inference'].confidence*100:.2f}%")
                        st.metric("πŸ€– Inference Time", f"{res['inference'].inference_time_ms:.2f} ms")
                        st.metric("⏱️ Total Pipeline Time", f"{res['pipeline_time']:.2f} ms")
                        
                        st.markdown("---")
                        
                        st.metric("βš™οΈ Servo Angle", f"{res['motor'].target_angle}Β°")
                        st.metric("⚑ Power Used", f"{res['motor'].power_consumption_mw:.2f} mW")
                    
                    st.markdown("---")
                    
                    # Class probabilities
                    st.markdown("#### πŸ“ˆ Classification Probabilities")
                    for cls, prob in res['inference'].probabilities.items():
                        st.progress(prob, text=f"{cls.capitalize()}: {prob*100:.2f}%")
                    
                    st.markdown("---")
                    
                    # Detailed telemetry
                    st.subheader("πŸ“‘ Detailed Component Telemetry")
                    
                    tel_col1, tel_col2, tel_col3 = st.columns(3)
                    
                    with tel_col1:
                        with st.expander("πŸ“ Sensor Readings", expanded=False):
                            sensor_data = {
                                'distance_cm': res['sensor'].distance_cm,
                                'distance_raw_adc': res['sensor'].distance_raw.raw_value,
                                'moisture_percent': res['sensor'].moisture_percent,
                                'moisture_raw_adc': res['sensor'].moisture_raw.raw_value,
                                'weight_g': res['sensor'].weight_g,
                                'weight_raw_adc': res['sensor'].weight_raw.raw_value,
                                'temperature_c': res['sensor'].temperature,
                                'total_read_time_ms': res['sensor'].total_read_time_ms
                            }
                            st.json(sensor_data)
                    
                    with tel_col2:
                        with st.expander("πŸ€– AI Inference", expanded=False):
                            inference_data = {
                                'waste_class': res['inference'].waste_class,
                                'confidence': res['inference'].confidence,
                                'probabilities': res['inference'].probabilities,
                                'preprocessing_ms': res['inference'].preprocessing_time_ms,
                                'inference_ms': res['inference'].inference_time_ms,
                                'postprocessing_ms': res['inference'].postprocessing_time_ms,
                                'model_version': res['inference'].model_version,
                                'device_temp_c': res['inference'].device_temperature,
                                'cpu_usage_percent': res['inference'].cpu_usage_percent
                            }
                            st.json(inference_data)
                    
                    with tel_col3:
                        with st.expander("βš™οΈ Motor Control", expanded=False):
                            motor_data = {
                                'start_angle': res['motor'].start_angle,
                                'target_angle': res['motor'].target_angle,
                                'current_angle': res['motor'].current_angle,
                                'duration_ms': res['motor'].duration_ms,
                                'power_consumption_mw': res['motor'].power_consumption_mw,
                                'torque_applied_kgcm': res['motor'].torque_applied,
                                'status': res['motor'].status,
                                'movement_steps': len(res['motor'].movement_profile)
                            }
                            st.json(motor_data)
            else:
                st.info("πŸ‘ˆ Configure sensors and click 'Run Complete Pipeline' to start")
                st.markdown("### πŸ—ΊοΈ System Architecture")
                st.markdown("""

                **Hardware Components:**

                - πŸ“· **Camera**: Raspberry Pi Camera Module v2 (1920x1080)

                - πŸ“ **Ultrasonic**: HC-SR04 (2-400cm range)

                - πŸ’§ **Moisture**: Capacitive sensor (12-bit ADC)

                - βš–οΈ **Weight**: HX711 Load Cell (5kg capacity)

                - βš™οΈ **Servo**: MG996R (180Β° rotation, 11 kg-cm torque)

                - πŸ’» **Edge Device**: Raspberry Pi 4 (4GB RAM, Quad-core)

                

                **Pipeline Flow:**

                1. Camera captures waste image

                2. Sensors read physical properties

                3. Edge AI processes multi-modal data

                4. Servo routes waste to correct bin

                5. Event logged to database

                """)
    
    # ==================== TAB 2: DASHBOARD ====================
    with tab2:
        st.subheader("πŸ“Š System Statistics")
        
        stats = st.session_state.logger.get_statistics()
        
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric("Total Events", stats['total_events'])
        
        with col2:
            st.metric("Avg Confidence", f"{stats['average_confidence']*100:.2f}%")
        
        with col3:
            st.metric("Avg Pipeline Time", f"{stats.get('average_pipeline_time_ms', 0):.2f} ms")
        
        with col4:
            st.metric("Total Power Used", f"{stats.get('total_power_consumption_mwh', 0):.4f} mWh")
        
        st.markdown("---")
        
        # Class distribution chart
        col_chart1, col_chart2 = st.columns(2)
        
        with col_chart1:
            st.subheader("πŸ“ˆ Waste Class Distribution")
            
            if stats['class_distribution']:
                import pandas as pd
                df = pd.DataFrame(
                    list(stats['class_distribution'].items()),
                    columns=['Class', 'Count']
                )
                st.bar_chart(df.set_index('Class'))
            else:
                st.info("No data yet. Run some segregations first!")
        
        with col_chart2:
            st.subheader("⚑ System Performance")
            
            if stats['total_events'] > 0:
                st.metric("Average Inference", f"{stats.get('average_pipeline_time_ms', 0):.2f} ms")
                st.metric("System Efficiency", f"{stats['average_confidence']*100:.1f}%")
                st.metric("Power Efficiency", f"{stats.get('total_power_consumption_mwh', 0)*1000:.2f} mW")
            else:
                st.info("No performance data yet.")
    
    # ==================== TAB 3: EVENT LOGS ====================
    with tab3:
        st.subheader("πŸ“‹ Recent Events")
        
        num_events = st.slider("Number of events to display", 5, 50, 10)
        
        events = st.session_state.logger.get_recent_events(num_events)
        if events:
            import pandas as pd
            df = pd.DataFrame(events)
            
            display_cols = [
                'timestamp', 'waste_class', 'confidence', 
                'distance_cm', 'moisture_percent', 'weight_g', 
                'servo_angle', 'inference_time_ms', 'total_pipeline_time_ms',
                'power_consumption_mw', 'status'
            ]
            
            available_cols = [col for col in display_cols if col in df.columns]
            
            st.dataframe(
                df[available_cols],
                use_container_width=True,
                hide_index=True
            )
            
            # Download button
            csv = df.to_csv(index=False)
            st.download_button(
                "πŸ“₯ Download CSV",
                csv,
                "events.csv",
                "text/csv",
                use_container_width=True
            )
        else:
            st.info("No events logged yet.")
    
    # ==================== TAB 4: HARDWARE DIAGNOSTICS ====================
    with tab4:
        st.subheader("πŸ”§ Hardware Diagnostics")
        
        diagnostics = st.session_state.logger.get_hardware_diagnostics(20)
        
        if diagnostics:
            import pandas as pd
            df = pd.DataFrame(diagnostics)
            
            st.dataframe(
                df[['timestamp', 'component', 'status', 'voltage', 'current_ma', 'temperature_c', 'error_count']],
                use_container_width=True,
                hide_index=True
            )
            
            st.markdown("---")
            
            # Component status
            st.subheader("πŸ“Š Component Status")
            
            col1, col2, col3 = st.columns(3)
            
            with col1:
                st.markdown("##### Ultrasonic Sensor")
                st.write(f"Status: {st.session_state.sensor_hub.ultrasonic.status.value}")
                st.write(f"Errors: {st.session_state.sensor_hub.ultrasonic.error_count}")
                st.write(f"Last Reading: {st.session_state.sensor_hub.ultrasonic.last_reading} cm")
            
            with col2:
                st.markdown("##### Servo Motor")
                motor_diag = st.session_state.servo.get_diagnostics()
                st.write(f"Angle: {motor_diag['current_angle']}Β°")
                st.write(f"Current: {motor_diag['current_ma']} mA")
                st.write(f"Temperature: {motor_diag['temperature_c']:.1f}Β°C")
            
            with col3:
                st.markdown("##### Edge Device")
                st.write(f"CPU: {st.session_state.edge_ai.cpu_usage:.1f}%")
                st.write(f"Temperature: {st.session_state.edge_ai.device_temp:.1f}Β°C")
                st.write(f"Model: {st.session_state.edge_ai.model_version}")
        else:
            st.info("No diagnostics data yet.")
    
    # ==================== TAB 5: SENSOR DETAILS ====================
    with tab5:
        st.subheader("πŸ“‘ Detailed Sensor Information")
        
        col1, col2 = st.columns(2)
        
        with col1:
            st.markdown("### Ultrasonic Sensor (HC-SR04)")
            st.markdown(f"""

            - **Range**: {HardwareConfig.ULTRASONIC_MIN_DISTANCE} - {HardwareConfig.ULTRASONIC_MAX_DISTANCE} cm

            - **Accuracy**: Β±{HardwareConfig.ULTRASONIC_ACCURACY} cm

            - **Read Time**: {HardwareConfig.ULTRASONIC_READ_TIME*1000:.1f} ms

            - **Operating Voltage**: 5V DC

            - **Current**: 15 mA

            - **Frequency**: 40 kHz

            """)
            
            st.markdown("### Capacitive Moisture Sensor")
            st.markdown(f"""

            - **Voltage Range**: {HardwareConfig.MOISTURE_MIN_VOLTAGE} - {HardwareConfig.MOISTURE_MAX_VOLTAGE} V

            - **ADC Resolution**: {HardwareConfig.MOISTURE_ADC_RESOLUTION} bits ({2**HardwareConfig.MOISTURE_ADC_RESOLUTION} levels)

            - **Read Time**: {HardwareConfig.MOISTURE_READ_TIME*1000:.1f} ms

            - **Operating Voltage**: 3.3V - 5.5V

            - **Current**: 5 mA

            """)
        
        with col2:
            st.markdown("### Load Cell (HX711)")
            st.markdown(f"""

            - **Capacity**: {HardwareConfig.WEIGHT_MAX_CAPACITY} g

            - **Resolution**: {HardwareConfig.WEIGHT_RESOLUTION} g

            - **Stabilization Time**: {HardwareConfig.WEIGHT_STABILIZATION_TIME*1000:.0f} ms

            - **Read Time**: {HardwareConfig.WEIGHT_READ_TIME*1000:.0f} ms

            - **ADC**: 24-bit

            - **Sample Rate**: 10/80 Hz

            """)
            
            st.markdown("### Servo Motor (MG996R)")
            st.markdown(f"""

            - **Rotation**: {HardwareConfig.SERVO_MIN_ANGLE}Β° - {HardwareConfig.SERVO_MAX_ANGLE}Β°

            - **Speed**: 60Β°/0.17s (at 4.8V)

            - **Torque**: {HardwareConfig.SERVO_TORQUE} kg-cm

            - **Operating Voltage**: 4.8V - 7.2V

            - **Current (Idle)**: {HardwareConfig.SERVO_CURRENT_IDLE} mA

            - **Current (Moving)**: {HardwareConfig.SERVO_CURRENT_MOVING} mA

            """)
        
        st.markdown("---")
        
        st.markdown("### πŸ“· Camera Module (Raspberry Pi Camera v2)")
        st.markdown(f"""

        - **Sensor**: Sony IMX219 8MP

        - **Resolution**: {HardwareConfig.CAMERA_RESOLUTION[0]}x{HardwareConfig.CAMERA_RESOLUTION[1]}

        - **Capture Time**: {HardwareConfig.CAMERA_CAPTURE_TIME*1000:.0f} ms

        - **Warmup Time**: {HardwareConfig.CAMERA_WARMUP_TIME:.1f} s

        - **Interface**: CSI (Camera Serial Interface)

        - **Frame Rate**: 30 fps (1080p)

        """)
        
        st.markdown("### πŸ’» Edge Device (Raspberry Pi 4)")
        st.markdown(f"""

        - **CPU**: Quad-core Cortex-A72 @ 1.5GHz

        - **RAM**: {HardwareConfig.RAM_MB} MB

        - **Cores**: {HardwareConfig.CPU_CORES}

        - **Inference Overhead**: {HardwareConfig.INFERENCE_OVERHEAD*1000:.0f} ms

        - **Operating System**: Raspberry Pi OS (Linux)

        - **AI Framework**: PyTorch / ONNX Runtime

        """)
    
    # Footer
    st.markdown("---")
    st.caption("Smart Waste Segregation System | LDRP-ITR, Gandhinagar | IDEA-ONE Hackathon 2025")
    st.caption("Hardware-Realistic Simulation | Edge AI Deployment | Multi-Modal Sensor Fusion")

if __name__ == "__main__":
    main()