File size: 52,099 Bytes
124666a
23ee138
 
 
908dd8a
57d4a2a
 
 
 
 
124666a
1458d90
 
 
 
23ee138
908dd8a
 
57d4a2a
6345a5c
 
 
 
2e19dc1
1a52aea
 
acb53e4
1a52aea
0edaf9d
 
 
 
 
57d4a2a
3d56b37
908dd8a
 
 
 
 
 
 
 
e49c0e0
 
908dd8a
 
 
23ee138
 
 
908dd8a
 
 
 
 
 
 
 
 
 
 
e49c0e0
 
 
908dd8a
e49c0e0
908dd8a
 
 
1bfc16c
 
 
8f1ac30
1bfc16c
908dd8a
 
 
 
 
 
 
23ee138
 
57d4a2a
23ee138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e19dc1
1a52aea
 
acb53e4
23ee138
 
2e19dc1
1a52aea
 
acb53e4
23ee138
57d4a2a
 
 
 
6345a5c
 
 
 
 
 
 
57d4a2a
 
 
 
 
 
 
 
 
 
 
 
 
6345a5c
57d4a2a
6345a5c
 
 
 
 
57d4a2a
 
 
6345a5c
57d4a2a
 
 
 
 
 
 
6345a5c
57d4a2a
5c3c458
 
 
 
 
 
 
acb53e4
5c3c458
 
 
 
 
 
 
 
 
 
 
acb53e4
 
 
 
 
 
 
 
 
6345a5c
1a52aea
 
 
 
 
 
 
 
 
 
 
 
0edaf9d
 
acb53e4
 
 
 
 
 
 
 
 
 
1a52aea
6345a5c
 
 
 
 
 
 
 
 
 
 
 
5c3c458
 
23ee138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
908dd8a
 
 
 
 
23ee138
 
908dd8a
23ee138
 
 
908dd8a
2e19dc1
 
 
 
 
 
 
 
1a52aea
 
 
 
e49c0e0
 
 
 
 
 
acb53e4
 
23ee138
908dd8a
 
 
 
 
 
 
 
e49c0e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acb53e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
908dd8a
 
 
 
 
 
eccddd2
908dd8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a7be7a
 
908dd8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd63cb6
 
 
 
 
 
 
 
 
 
 
 
5d6aa39
fd63cb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57d4a2a
fd63cb6
 
 
 
 
 
 
 
 
 
 
 
 
57d4a2a
fd63cb6
 
 
57d4a2a
fd63cb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a7be7a
 
fd63cb6
 
 
 
 
 
 
 
 
 
12f0f4c
fd63cb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a7be7a
fd63cb6
 
 
 
57d4a2a
 
5c3c458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e49c0e0
5c3c458
 
 
 
 
 
 
 
 
 
 
5a7be7a
5c3c458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a7be7a
5c3c458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a7be7a
5c3c458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a7be7a
5c3c458
 
 
 
 
 
 
 
 
 
 
57d4a2a
 
 
1df51fa
57d4a2a
1df51fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57d4a2a
1df51fa
 
57d4a2a
1df51fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57d4a2a
1a52aea
 
 
 
 
 
 
0edaf9d
1a52aea
 
 
 
 
0edaf9d
1a52aea
 
 
 
 
0edaf9d
1a52aea
 
 
 
 
0edaf9d
1a52aea
 
 
0edaf9d
 
 
 
 
 
1a52aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0edaf9d
 
 
 
 
1a52aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0edaf9d
 
 
 
 
 
1a52aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0edaf9d
 
 
 
 
 
1a52aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba55472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acb586b
ba55472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acb586b
ba55472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a52aea
 
 
57d4a2a
 
6345a5c
57d4a2a
 
6345a5c
 
57d4a2a
 
 
 
1fdaa53
57d4a2a
 
6345a5c
 
 
 
 
 
 
 
 
 
 
 
 
cdf65a4
57d4a2a
c2dccf3
 
 
 
 
 
 
 
 
 
 
 
 
6345a5c
57d4a2a
e62cde7
 
 
6345a5c
 
 
 
 
c2dccf3
e49c0e0
c2dccf3
e49c0e0
c2dccf3
e49c0e0
c2dccf3
6345a5c
 
 
 
 
57d4a2a
6345a5c
57d4a2a
 
5979d27
57d4a2a
 
e62cde7
57d4a2a
 
e62cde7
7e876f8
 
 
6345a5c
acb53e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6345a5c
acb53e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdf65a4
6345a5c
 
57d4a2a
 
 
6345a5c
57d4a2a
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
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
import streamlit as st
import paho.mqtt.client as mqtt
import json
import time
import os
import asyncio
import pandas as pd

from datetime import datetime
import pytz

# The web app that will connect to the PioReactor MQTT broker and control the reactor

# Author: Enrui (Edison) Lin


experiment = None
running = []
temp_graph = None
od_graph = None
norm_od_graph = None
growth_rate_graph = None
all_graph = False
temp_mqtt_auto = None
rpm_mqtt = None
led_mqtt = None
experiments = []

# if st.session_state.get("channels", None) is not None:
#     st.session_state["channel_a"] = int(st.session_state["channels"].get("A", 0))
#     st.session_state["channel_b"] = int(st.session_state["channels"].get("B", 0))
#     st.session_state["channel_c"] = int(st.session_state["channels"].get("C", 0))
#     st.session_state["channel_d"] = int(st.session_state["channels"].get("D", 0))

REQUEST_INTERVAL = 120

if "experiment" not in st.session_state:
    st.session_state["experiment"] = None
    st.session_state["jobs"] = {
        "temperature_automation": False, 
        "growth_rate_calculating": False, 
        "stirring": False, 
        "od_reading": False, 
        "led_automation": False,
        "dosing_automation": False
    }
    st.session_state["client"] = None

# Create a form to get the MQTT broker details
st.title("PioReactor MQTT Client")

# Create a button to choose whether or not to use custom credentials
use_custom_credentials = st.checkbox("Use Custom Credentials")

if use_custom_credentials:
    with st.form("mqtt_form"):
        # hivemq_host = st.text_input("HiveMQ Host", type="password")
        # hivemq_username = st.text_input("HiveMQ Username", type="password")
        # hivemq_password = st.text_input("HiveMQ Password", type="password")
        # hivemq_port = st.number_input("HiveMQ Port", min_value=1, max_value=65535, step=1, value=8883)
        # reactor = st.text_input("PioReactor")

        hivemq_host = st.text_input("HiveMQ Host", type="password")
        hivemq_username = st.text_input("HiveMQ Username", type="password")
        hivemq_password = st.text_input("HiveMQ Password", type="password")
        hivemq_port = st.number_input("HiveMQ Port", min_value=1, max_value=65535, step=1, value=8883)
        reactor = st.text_input("PioReactor")

        submit_button = st.form_submit_button("Connect")
else:
    hivemq_host = os.getenv("host")
    hivemq_username = os.getenv("username")
    hivemq_password = os.getenv("password")
    hivemq_port = int(os.getenv("port"))
    reactor = os.getenv("reactor")

    # button to submit the form
    if st.session_state["experiment"] is None:
        submit_button = st.button("Connect")
    else:
        submit_button = st.button("Reconnect")


# Create the MQTT client
# @st.cache_resource
def create_mqtt_client(hivemq_host, hivemq_port, hivemq_username, hivemq_password):
    client = mqtt.Client()

    # Set authentication and TLS settings
    client.username_pw_set(hivemq_username, hivemq_password)
    client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS_CLIENT)

    # Define callback functions
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            st.success("Connected to HiveMQ successfully!")
        else:
            st.error(f"Failed to connect, return code {rc}")

    client.on_connect = on_connect
    
    return client

def on_message_worker(client, userdata, message):
    payload = message.payload.decode("utf-8")
    data = json.loads(payload)
    global experiment
    global running
    global temp_mqtt_auto
    global rpm_mqtt
    global led_mqtt
    global experiments
    experiment = data.get("experiment", None)
    running = data.get("running", [])
    temp_mqtt_auto = data.get("temperature_automation", None)
    rpm_mqtt = data.get("stirring", None)
    led_mqtt = data.get("leds", None)
    experiments = data.get("experiments", [])

def on_message(client, userdata, message):
    payload = message.payload.decode("utf-8")
    data = json.loads(payload)
    global temp_graph
    global od_graph
    global norm_od_graph
    global growth_rate_graph
    temp_graph = data.get("temperature", None)
    od_graph = data.get("od", None)
    norm_od_graph = data.get("normalized_od", None) 
    growth_rate_graph = data.get("growth_rate", None)

async def publish_temperature_request(client, experiment, filter_mod_N, lookback, reactor):
        """Publish a temperature request to the request topic."""
        payload = {
            "command": "get_temperature_readings",
            "experiment": experiment,
            "filter_mod": filter_mod_N,
            "lookback": lookback,
            "reactor": reactor
        }
        payload_str = json.dumps(payload)
        client.publish("pioreactor/control", payload_str)

async def periodic_temp_reading(client, reactor, experiment, placeholder):
    try:
        while True:
            await publish_temperature_request(client, experiment, 1, 100000, reactor)
            global temp_graph
            placeholder.write(temp_graph)
            await asyncio.sleep(REQUEST_INTERVAL)
    except asyncio.CancelledError:
        pass

async def run_mqtt_client(client, placeholder):
    client.subscribe(f"pioreactor/{reactor}/temp_reading")
    client.subscribe(f"pioreactor/{reactor}/od_reading")
    client.subscribe(f"pioreactor/{reactor}/growth_rate")

    client.on_message = on_message

    client.loop_start()
    await periodic_temp_reading(client, reactor, st.session_state["experiment"], placeholder)

def get_running_jobs(client, reactor):
    payload = {
        "command": "get_worker",
        "reactor": reactor
    }
    payload_str = json.dumps(payload)
    client.publish("pioreactor/control", payload_str)
    global experiment
    experiment = None
    running = []

    client.subscribe(f"pioreactor/{reactor}/worker")
    client.message_callback_add(f"pioreactor/{reactor}/worker", on_message_worker)

    timeout = 10
    start_time = time.time()

    while experiment is None and (time.time() - start_time) < timeout:
        time.sleep(1)

    if experiment is None: 
        st.error("Failed to get info")
        st.session_state["experiment"] = None
        time.sleep(3)
        st.rerun()

    if experiment != st.session_state["experiment"]:
        st.session_state["experiment"] = experiment
    
    if st.session_state["jobs"]["temperature_automation"]:
        if temp_mqtt_auto == "thermostat":
            st.session_state["temp_auto"] = "Heat To Temp"
        elif temp_mqtt_auto == "only_record_temperature":
            st.session_state["temp_auto"] = "Record Temp Only"

        st.session_state["temp"] = None
        
    if st.session_state["jobs"]["stirring"]:
        print(rpm_mqtt)
        st.session_state["stirring_speed"] = rpm_mqtt
    
    # st.session_state["channels"] = led_mqtt

    if led_mqtt is not None:
        st.session_state["channel_a"] = int(led_mqtt.get("A", 0))
        st.session_state["channel_b"] = int(led_mqtt.get("B", 0))
        st.session_state["channel_c"] = int(led_mqtt.get("C", 0))
        st.session_state["channel_d"] = int(led_mqtt.get("D", 0))

    st.session_state["experiments"] = experiments 

    for run in running:
        st.session_state["jobs"][run] = True

async def get_graph(placeholder):
    try:
        st.session_state["client"].loop_start()
        st.session_state["client"].subscribe(f"pioreactor/{reactor}/temperature")
        st.session_state["client"].message_callback_add(f"pioreactor/{reactor}/temperature", on_message)
        while True:
            await publish_temperature_request(st.session_state["client"], st.session_state["experiment"], 1, 100000, reactor)
            await asyncio.sleep(REQUEST_INTERVAL)
            global temp_graph
            placeholder.write(temp_graph)
    except asyncio.CancelledError:
        pass


if submit_button:
    client = create_mqtt_client(hivemq_host, hivemq_port, hivemq_username, hivemq_password)

    # Publish a message to the MQTT broker
    if client:
        client.connect(hivemq_host, hivemq_port)
        client.loop_start()

        # Subscribe to the worker topic
        client.subscribe(f"pioreactor/{reactor}/worker")
        client.message_callback_add(f"pioreactor/{reactor}/worker", on_message_worker)

        payload = {
            "command": "get_worker",
            "reactor": reactor
        }
        payload_str = json.dumps(payload)
        client.publish("pioreactor/control", payload_str)
        
        timeout = 10
        start_time = time.time()   

        while experiment is None and (time.time() - start_time) < timeout:
            time.sleep(1)
        
        st.session_state["experiment"] = experiment

        # Unsubscribe from the worker topic
        # client.unsubscribe(f"pioreactor/{reactor}/worker")
        # client.message_callback_remove(f"pioreactor/{reactor}/worker")
        client.loop_stop()

        if st.session_state["experiment"] is None:
            st.error("No experiment assigned to the reactor.")
        
        for run in running:
            st.session_state["jobs"][run] = True
        
        if st.session_state["jobs"]["temperature_automation"]:
            if temp_mqtt_auto == "thermostat":
                st.session_state["temp_auto"] = "Heat To Temp"
            elif temp_mqtt_auto == "only_record_temperature":
                st.session_state["temp_auto"] = "Record Temp Only"

            st.session_state["temp"] = None
        
        if st.session_state["jobs"]["stirring"]:
            print(rpm_mqtt)
            st.session_state["stirring_speed"] = rpm_mqtt

        if led_mqtt is not None:
            st.session_state["channel_a"] = int(led_mqtt.get("A", 0))
            st.session_state["channel_b"] = int(led_mqtt.get("B", 0))
            st.session_state["channel_c"] = int(led_mqtt.get("C", 0))   
            st.session_state["channel_d"] = int(led_mqtt.get("D", 0))

        st.session_state["experiments"] = experiments
    
    # Save the client to the session state
    st.session_state["client"] = client


# Display the experiment and running jobs if available
if st.session_state["experiment"] is not None:
    st.title(f"Experiment: {st.session_state['experiment']}")

    st.header("Running Jobs")
        
    cols = st.columns(6)

    with cols[0]:
        st.write("Temperature")
        st.write(st.session_state["jobs"]["temperature_automation"])

    with cols[1]:
        st.write("Growth Rate")
        st.write(st.session_state["jobs"]["growth_rate_calculating"])

    with cols[2]:
        st.write("Stirring")
        st.write(st.session_state["jobs"]["stirring"])

    with cols[3]:
        st.write("OD Reading")
        st.write(st.session_state["jobs"]["od_reading"])

    with cols[4]:
        st.write("LED")
        st.write(st.session_state["jobs"]["led_automation"])

    with cols[5]:
        st.write("Dosing")
        st.write(st.session_state["jobs"]["dosing_automation"])

    st.divider()

    with st.form("experiment_form"):
        new_name = st.text_input("New Experiment Name")
        submit_new_experiment = st.form_submit_button("Create New Experiment")

    change_experiment_submit = False
    delete_experiment = False
    
    with st.form("experiment_edit"):
        if len(st.session_state["experiments"]) > 0:
            experiment_change = st.selectbox("Select Experiment", st.session_state["experiments"])
            cols = st.columns(2)
            with cols[0]:
                change_experiment_submit = st.form_submit_button("Change Experiment")
            with cols[1]:
                delete_experiment = st.form_submit_button("Delete Experiment")
        else:
            st.write("No experiments available.")
            st.form_submit_button("Nothing Button")
    
    if submit_new_experiment:
        payload = {
            "command": "new_experiment",
            "experiment": new_name,
            "reactor": reactor
        }
        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        get_running_jobs(st.session_state["client"], reactor)

        if new_name in st.session_state["experiments"]:
            st.success("Experiment created successfully!")
        else:
            st.error("Failed to create experiment.")

        
        st.session_state["client"].loop_stop()

        time.sleep(3)
        st.rerun()
    
    if change_experiment_submit:
        payload = {
            "command": "change_experiment",
            "experiment": st.session_state["experiment"],
            "experiment_new": experiment_change,
            "reactor": reactor
        }
        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(3)

        get_running_jobs(st.session_state["client"], reactor)

        if experiment_change == st.session_state["experiment"]:
            st.success("Experiment changed successfully!")

        else:
            st.error("Failed to change experiment.")

        st.info(f"Experiment name changed to {experiment_change} from {st.session_state['experiment']}")

        st.session_state["client"].loop_stop()

        time.sleep(3)
        st.rerun()

    if delete_experiment:
        payload = {
            "command": "delete_experiment",
            "experiment": experiment_change,
            "reactor": reactor
        }
        payload_str = json.dumps(payload)

        time.sleep(1)

        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        get_running_jobs(st.session_state["client"], reactor)

        if experiment_change not in st.session_state["experiments"]:
            st.success("Experiment deleted successfully!")
        else:
            st.error("Failed to delete experiment.")

        st.session_state["client"].loop_stop()
        time.sleep(3)
        st.rerun()

    st.divider()

    # Display the job details
    st.header("Stirring")
    if st.session_state["jobs"]["stirring"]:
        with st.form("stirring_form"):
            if st.session_state.get("stirring_speed", None) is None:
                st.write("Current Stirring Speed Unknown")
            else:
                st.write(f"Current Stirring Speed: {st.session_state['stirring_speed']} RPM")
            stirring_speed = st.slider("Stirring Speed", min_value=100, max_value=3000, step=50, value=st.session_state.get("stirring_speed", 500))
            
            cols = st.columns(2)
            with cols[0]:
                stirring = st.form_submit_button("Update Stirring Speed")
            with cols[1]:
                stop_stirring = st.form_submit_button("Stop Stirring")
    else:
        with st.form("stirring_form"):
            stirring_speed = st.slider("Stirring Speed", min_value=100, max_value=3000, step=50, value=500)
            stirring = st.form_submit_button("Start Stirring")
        
        stop_stirring = False

    if stirring:
        if st.session_state["jobs"]["stirring"]:
            payload = {
                "command": "update_stirring_rpm",
                "reactor": reactor,
                "experiment": st.session_state["experiment"],
                "rpm": stirring_speed
            }
        else:
            payload = {
                "command": "start_stirring",
                "experiment": st.session_state["experiment"],
                "reactor": reactor,
                "rpm": stirring_speed
            }
        
        payload_str = json.dumps(payload)

        # Start looping
        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)

        # Check if the stirring job is running
        payload = {
            "command": "get_worker",
            "reactor": reactor
        }

        experiment = None
        running = []

        st.session_state["client"].subscribe(f"pioreactor/{reactor}/worker")
        st.session_state["client"].message_callback_add(f"pioreactor/{reactor}/worker", on_message_worker)

        payload_str = json.dumps(payload)
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)
        
        timeout = 10
        start_time = time.time()

        while experiment is None and (time.time() - start_time) < timeout:
            time.sleep(1)

        st.session_state["client"].loop_stop()
        
        if "stirring" in running and st.session_state["jobs"]["stirring"]:
            st.success("Stirring speed updated successfully!")
            st.session_state["stirring_speed"] = stirring_speed
        elif "stirring" in running:
            st.success("Stirring started successfully!")
            st.session_state["jobs"]["stirring"] = True
            st.session_state["stirring_speed"] = stirring_speed
        else:
            st.error("Failed to update stirring speed.")
            st.session_state["experiment"] = None
            st.session_state["jobs"]["stirring_speed"] = None
        
        time.sleep(3)
        st.rerun()

    if stop_stirring:
        payload = {
            "command": "stop_stirring",
            "reactor": reactor,
            "experiment": st.session_state["experiment"]
        }
        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)
        st.session_state["client"].loop_stop()

        # Check if the stirring job is running
        payload = {
            "command": "get_worker",
            "reactor": reactor
        }

        st.session_state["client"].subscribe(f"pioreactor/{reactor}/worker")
        st.session_state["client"].message_callback_add(f"pioreactor/{reactor}/worker", on_message_worker)

        experiment = None
        running = []

        payload_str = json.dumps(payload)
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        timeout = 10
        start_time = time.time()

        while experiment is None and (time.time() - start_time) < timeout:
            time.sleep(1)

        if "stirring" not in running:
            st.success("Stirring stopped successfully!")
            st.session_state["stirring_speed"] = None
            st.session_state["jobs"]["stirring"] = False
        else:
            st.error("Failed to stop stirring.")

        time.sleep(3)
        st.rerun()

    st.divider()

    st.header("Temperature Automation")

    if st.session_state["jobs"]["temperature_automation"]:
        temp = None
        if st.session_state.get("temp_auto", None) is None:
            st.write("Current Temperature Automation Unknown, changes will result in restart of the automation to new settings.")
            temp_auto = st.selectbox("Temperature Automation", ["Record Temp Only", "Heat To Temp"], placeholder="UNKNOWN")
            with st.form("temperature_form"):
                if temp_auto == "Heat To Temp":
                    temp = st.slider("Temperature", min_value=0, max_value=60, step=1, value=30)
                    cols = st.columns(2)
                    with cols[0]:
                        temp_submit = st.form_submit_button("Restart Temperature Automation")
                    with cols[1]:
                        temp_stop = st.form_submit_button("Stop Temperature Automation")
                elif temp_auto == "Record Temp Only":
                    cols = st.columns(2)
                    with cols[0]:
                        temp_submit = st.form_submit_button("Restart Temperature Automation")
                    with cols[1]:
                        temp_stop = st.form_submit_button("Stop Temperature Automation")
        else:
            if st.session_state["temp_auto"] == "Heat To Temp":
                index = 1
            elif st.session_state["temp_auto"] == "Record Temp Only":
                index = 0
            temp_auto = st.selectbox("Temperature Automation", ["Record Temp Only", "Heat To Temp"], index=index)
            with st.form("temperature_form"):
                st.write(f"Current Temperature Automation: {st.session_state['temp_auto']}")
                if temp_auto == "Heat To Temp":
                    if st.session_state.get("temp", None) is not None:
                        st.write(f"Current Temperature: {st.session_state['temp']} °C")
                    temp = st.slider("Temperature", min_value=0, max_value=60, step=1, value=st.session_state["temp"] if st.session_state["temp"] is not None else 30)
                    cols = st.columns(2)
                    with cols[0]:
                        temp_submit = st.form_submit_button("Update Temperature Automation")
                    with cols[1]:
                        temp_stop = st.form_submit_button("Stop Temperature Automation")
                elif temp_auto == "Record Temp Only":
                    cols = st.columns(2)
                    with cols[0]:
                        temp_submit = st.form_submit_button("Update Temperature Automation", disabled=(st.session_state["temp_auto"] == "Record Temp Only"))
                    with cols[1]:
                        temp_stop = st.form_submit_button("Stop Temperature Automation")

    else:
        temp = None
        temp_auto = st.selectbox("Temperature Automation", ["Record Temp Only", "Heat To Temp"], placeholder="Select an option")
        with st.form("temperature_form"):
            if temp_auto == "Heat To Temp":
                temp = st.slider("Temperature", min_value=0, max_value=60, step=1, value=30)
                temp_submit = st.form_submit_button("Start Temperature Automation")
                temp_stop = False
            elif temp_auto == "Record Temp Only":
                temp_submit = st.form_submit_button("Start Temperature Automation")
                temp_stop = False
    
    if temp_submit:
        # Convert the temperature automation to the payload
        if temp_auto == "Heat To Temp":
                payload_auto = "thermostat"
        elif temp_auto == "Record Temp Only":
            payload_auto = "only_record_temperature"

        # Update the temperature automation
        if st.session_state["jobs"]["temperature_automation"]:
            #Check if the temperature automation is the same as the current one
            if temp_auto == st.session_state.get("temp_auto", None):
                # Same automation, update the temperature
                # Update the temperature automation
                payload = {
                    "command": "temp_update",
                    "reactor": reactor,
                    "experiment": st.session_state["experiment"],
                    "settings": {
                        "target_temperature": temp
                    }
                }
            else:
                # Different automation, restart the automation
                payload = {
                    "command": "temp_restart",
                    "reactor": reactor,
                    "experiment": st.session_state["experiment"],
                    "automation": payload_auto,
                    "temp": temp
                }
        else:
            # Start the temperature automation
            payload = {
                "command": "set_temperature_automation",
                "reactor": reactor,
                "experiment": st.session_state["experiment"],
                "automation": payload_auto,
                "temp": temp
            }
        
        payload_str = json.dumps(payload)

        # Start looping
        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)

        # Check if the stirring job is running
        payload = {
            "command": "get_worker",
            "reactor": reactor
        }

        experiment = None
        running = []

        st.session_state["client"].subscribe(f"pioreactor/{reactor}/worker")
        st.session_state["client"].message_callback_add(f"pioreactor/{reactor}/worker", on_message_worker)

        payload_str = json.dumps(payload)
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)
        
        timeout = 10
        start_time = time.time()

        while experiment is None and (time.time() - start_time) < timeout:
            time.sleep(1)

        st.session_state["client"].loop_stop()
        
        if "temperature_automation" in running and st.session_state["jobs"]["temperature_automation"]:
            st.success("Temperature automation updated!")
            st.session_state["temp_auto"] = temp_auto
            st.session_state["temp"] = temp
        elif "temperature_automation" in running:
            st.success("Temperature automation started successfully!")
            st.session_state["jobs"]["temperature_automation"] = True
            st.session_state["temp_auto"] = temp_auto
            st.session_state["temp"] = temp
        else:
            st.error("Failed to update temperature automation speed.")
            st.session_state["experiment"] = None
            st.session_state["jobs"]["temperature_automation"] = None
        
        time.sleep(3)
        st.rerun()

    if temp_stop:
        payload = {
            "command": "temp_update",
            "reactor": reactor,
            "experiment": st.session_state["experiment"],
            "settings": {
                "$state": "disconnected"
            }
        }

        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)

        # Check if the temperature automation job has stopped
        payload = {
            "command": "get_worker",
            "reactor": reactor
        }

        experiment = None
        running = []

        st.session_state["client"].subscribe(f"pioreactor/{reactor}/worker")
        st.session_state["client"].message_callback_add(f"pioreactor/{reactor}/worker", on_message_worker)

        payload_str = json.dumps(payload)

        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        timeout = 10
        start_time = time.time()

        while experiment is None and (time.time() - start_time) < timeout:
            time.sleep(1)

        if "temperature_automation" not in running:
            st.success("Temperature automation stopped successfully!")
            st.session_state["temp_auto"] = None
            st.session_state["temp"] = None
        else:
            st.error("Failed to stop temperature automation.")
            st.session_state["experiment"] = None
        
        time.sleep(3)
        st.rerun()

    st.divider()

    cols = st.columns(2)

    start_od = False
    stop_od = False
    start_growth = False
    stop_growth = False

    with cols[0]:
        st.header("OD Reading")
        if st.session_state["jobs"]["od_reading"]:
            stop_od = st.button("Stop OD Reading")
        else:
            start_od = st.button("Start OD Reading")
    
    with cols[1]:
        st.header("Growth Rate")
        if st.session_state["jobs"]["growth_rate_calculating"]:
            stop_growth = st.button("Stop Growth Rate Calculation")
        else:
            start_growth = st.button("Start Growth Rate Calculation")

    if start_od:
        payload = {
            "command": "start_od_reading",
            "reactor": reactor,
            "experiment": st.session_state["experiment"]
        }
        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(2)

        # Check if the OD reading job is running
        get_running_jobs(st.session_state["client"], reactor)

        st.session_state["client"].loop_stop()

        if "od_reading" in running:
            st.success("OD Reading started successfully!")
            st.session_state["jobs"]["od_reading"] = True
        else:
            st.error("Failed to start OD Reading.")
            st.session_state["experiment"] = None
        
        for run in running:
            st.session_state["jobs"][run] = True
        
        st.session_state["experiment"] = experiment
        
        time.sleep(3)
        st.rerun()
    
    if stop_od:
        payload = {
            "command": "stop_od_reading",
            "reactor": reactor,
            "experiment": st.session_state["experiment"]
        }
        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)

        # Check if the OD reading job has stopped
        get_running_jobs(st.session_state["client"], reactor)

        st.session_state["client"].loop_stop()

        if "od_reading" not in running:
            st.success("OD Reading stopped successfully!")
            st.session_state["jobs"]["od_reading"] = False
        else:
            st.error("Failed to stop OD Reading.")
            st.session_state["experiment"] = None
        
        for run in running:
            st.session_state["jobs"][run] = True
        
        st.session_state["experiment"] = experiment
        
        time.sleep(3)
        st.rerun()
    
    if start_growth:
        payload = {
            "command": "start_growth_rate",
            "reactor": reactor,
            "experiment": st.session_state["experiment"]
        }
        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)

        # Check if the growth rate job is running
        get_running_jobs(st.session_state["client"], reactor)

        st.session_state["client"].loop_stop()

        if "growth_rate_calculating" in running:
            st.success("Growth Rate Calculation started successfully!")
            st.session_state["jobs"]["growth_rate_calculating"] = True
        else:
            st.error("Failed to start Growth Rate Calculation.")
            st.session_state["experiment"] = None
        
        for run in running:
            st.session_state["jobs"][run] = True
        
        st.session_state["experiment"] = experiment
        
        time.sleep(3)
        st.rerun()

    if stop_growth:
        payload = {
            "command": "stop_growth_rate",
            "reactor": reactor,
            "experiment": st.session_state["experiment"]
        }
        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)

        # Check if the growth rate job has stopped
        get_running_jobs(st.session_state["client"], reactor)

        st.session_state["client"].loop_stop()

        if "growth_rate_calculating" not in running:
            st.success("Growth Rate Calculation stopped successfully!")
            st.session_state["jobs"]["growth_rate_calculating"] = False
        else:
            st.error("Failed to stop Growth Rate Calculation.")
            st.session_state["experiment"] = None
        
        for run in running:
            st.session_state["jobs"][run] = True
        
        st.session_state["experiment"] = experiment
        
        time.sleep(3)
        st.rerun()

    st.divider()

    # Display the temperature graph 
    # Using asyncio to run the loop in the background and periodically update the graph

    # st.header("LED Automation")

    # with st.form("led_form"):
    #     channel_a = st.slider("Channel A", min_value=0, max_value=100, step=1, value=0)
    #     channel_a_submit = st.form_submit_button("Update Channel A")
    
    # if channel_a_submit:
    #     payload = {
    #         "command": "set_led_intensity",
    #         "reactor": reactor,
    #         "experiment": st.session_state["experiment"],
    #         "brightness": channel_a,
    #         "led": "A"
    #     }
    #     payload_str = json.dumps(payload)

    #     st.session_state["client"].loop_start()
    #     st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

    #     time.sleep(1)

    #     # Check if the LED automation job is running
    #     get_running_jobs(st.session_state["client"], reactor)

    #     st.session_state["client"].loop_stop()

    #     if "led_automation" in running:
    #         st.success("LED Automation updated!")
    #     else:
    #         st.error("Failed to update LED Automation.")
    #         st.session_state["experiment"] = None
        
    #     for run in running:
    #         st.session_state["jobs"][run] = True
        
    #     st.session_state["experiment"] = experiment
        
    #     time.sleep(3)
    #     st.rerun()
    
    # with st.form("led_form_b"):
    #     channel_b = st.slider("Channel B", min_value=0, max_value=100, step=1, value=0)
    #     channel_b_submit = st.form_submit_button("Update Channel B")

    # if channel_b_submit:
    #     payload = {
    #         "command": "set_led_intensity",
    #         "reactor": reactor,
    #         "experiment": st.session_state["experiment"],
    #         "brightness": channel_b,
    #         "led": "B"
    #     }
    #     payload_str = json.dumps(payload)

    #     st.session_state["client"].loop_start()
    #     st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

    #     time.sleep(1)

    #     # Check if the LED automation job is running
    #     get_running_jobs(st.session_state["client"], reactor)

    #     st.session_state["client"].loop_stop()

    #     if "led_automation" in running: 
    #         st.success("LED Automation updated!")
    #     else:
    #         st.error("Failed to update LED Automation.")
    #         st.session_state["experiment"] = None

    #     for run in running:
    #         st.session_state["jobs"][run] = True
        
    #     st.session_state["experiment"] = experiment

    #     time.sleep(3)
    #     st.rerun()

    # with st.form("led_form_c"):
    #     channel_c = st.slider("Channel C", min_value=0, max_value=100, step=1, value=0)
    #     channel_c_submit = st.form_submit_button("Update Channel C")
        
    # if channel_c_submit:
    #     payload = {
    #         "command": "set_led_intensity",
    #         "reactor": reactor,
    #         "experiment": st.session_state["experiment"],
    #         "brightness": channel_c,
    #         "led": "C"
    #     }
    #     payload_str = json.dumps(payload)

    #     st.session_state["client"].loop_start()
    #     st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

    #     time.sleep(1)

    #     # Check if the LED automation job is running
    #     get_running_jobs(st.session_state["client"], reactor)

    #     st.session_state["client"].loop_stop()

    #     if "led_automation" in running:
    #         st.success("LED Automation updated!")
    #     else:
    #         st.error("Failed to update LED Automation.")
    #         st.session_state["experiment"] = None
        
    #     for run in running:
    #         st.session_state["jobs"][run] = True
        
    #     st.session_state["experiment"] = experiment

    #     time.sleep(3)
    #     st.rerun()

    # with st.form("led_form_d"):
    #     channel_d = st.slider("Channel D", min_value=0, max_value=100, step=1, value=0)
    #     channel_d_submit = st.form_submit_button("Update Channel D")

    # if channel_d_submit:
    #     payload = {
    #         "command": "set_led_intensity",
    #         "reactor": reactor,
    #         "experiment": st.session_state["experiment"],
    #         "brightness": channel_d,
    #         "led": "D"
    #     }
    #     payload_str = json.dumps(payload)

    #     st.session_state["client"].loop_start()
    #     st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

    #     time.sleep(1)

    #     # Check if the LED automation job is running
    #     get_running_jobs(st.session_state["client"], reactor)

    #     st.session_state["client"].loop_stop()

    #     if "led_automation" in running:
    #         st.success("LED Automation updated!")
    #     else:
    #         st.error("Failed to update LED Automation.")
    #         st.session_state["experiment"] = None
        
    #     for run in running:
    #         st.session_state["jobs"][run] = True
        
    #     st.session_state["experiment"] = experiment

    #     time.sleep(3)
    #     st.rerun()
    
    # st.divider()

    st.header("LEDS")

    cols = st.columns(4)

    with cols[0]:
        st.write("Channel A")
        with st.form("led_form_a"):
            channel_a_placeholder = st.empty()
            channel_a_submit = st.form_submit_button("Update Channel A")
    
    with cols[1]:
        st.write("Channel B")
        with st.form("led_form_b"):
            channel_b_placeholder = st.empty()
            channel_b_submit = st.form_submit_button("Update Channel B")

    with cols[2]:
        st.write("Channel C")
        with st.form("led_form_c"):
            channel_c_placeholder = st.empty()
            channel_c_submit = st.form_submit_button("Update Channel C")

    with cols[3]:
        st.write("Channel D")
        with st.form("led_form_d"):
            channel_d_placeholder = st.empty()
            channel_d_submit = st.form_submit_button("Update Channel D")

    
    channel_a = channel_a_placeholder.number_input("Channel A", min_value=0, max_value=100, step=1, value=st.session_state.get("channel_a", 0))
    channel_b = channel_b_placeholder.number_input("Channel B", min_value=0, max_value=100, step=1, value=st.session_state.get("channel_b", 0))
    channel_c = channel_c_placeholder.number_input("Channel C", min_value=0, max_value=100, step=1, value=st.session_state.get("channel_c", 0))
    channel_d = channel_d_placeholder.number_input("Channel D", min_value=0, max_value=100, step=1, value=st.session_state.get("channel_d", 0))

    
    if channel_a_submit:
        pass

    if channel_b_submit:
        payload = {
            "command": "set_led_intensity",
            "reactor": reactor,
            "experiment": st.session_state["experiment"],
            "brightness": channel_b,
            "led": "B"
        }

        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()

        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)

        channel_a_placeholder.empty()
        channel_b_placeholder.empty()
        channel_c_placeholder.empty()
        channel_d_placeholder.empty()

        # Check if the LED automation job is running
        get_running_jobs(st.session_state["client"], reactor)

        st.session_state["client"].loop_stop()

        if channel_b == int(led_mqtt.get("B", 0)):
            st.success("LED Intensity updated!")
        else:
            st.error("Failed to update LED Intensity.")
            st.session_state["experiment"] = None
        
        for run in running:
            st.session_state["jobs"][run] = True

        st.session_state["experiment"] = experiment

        time.sleep(3)
        st.rerun()

    if channel_c_submit:
        payload = {
            "command": "set_led_intensity",
            "reactor": reactor,
            "experiment": st.session_state["experiment"],
            "brightness": channel_c,
            "led": "C"
        }

        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()

        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)


        channel_a_placeholder.empty()
        channel_b_placeholder.empty()
        channel_c_placeholder.empty()
        channel_d_placeholder.empty()

        # Check if the LED automation job is running
        get_running_jobs(st.session_state["client"], reactor)

        st.session_state["client"].loop_stop()

        if channel_c == int(led_mqtt.get("C", 0)):
            st.success("LED Intensity updated!")
        else:
            st.error("Failed to update LED Intensity.")
            st.session_state["experiment"] = None
        
        for run in running:
            st.session_state["jobs"][run] = True

        st.session_state["experiment"] = experiment

        time.sleep(3)
        st.rerun()

    if channel_d_submit:
        payload = {
            "command": "set_led_intensity",
            "reactor": reactor,
            "experiment": st.session_state["experiment"],
            "brightness": channel_d,
            "led": "D"
        }

        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()

        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)


        channel_a_placeholder.empty()
        channel_b_placeholder.empty()
        channel_c_placeholder.empty()
        channel_d_placeholder.empty()

        # Check if the LED automation job is running
        get_running_jobs(st.session_state["client"], reactor)

        st.session_state["client"].loop_stop()

        if channel_d == int(led_mqtt.get("D", 0)):
            st.success("LED Intensity updated!")
        else:
            st.error("Failed to update LED Intensity.")
            st.session_state["experiment"] = None
        
        for run in running:
            st.session_state["jobs"][run] = True

        st.session_state["experiment"] = experiment

        time.sleep(3)
        st.rerun()

    st.divider()

    st.header("Dosing")

    cols = st.columns(3)

    with cols[0]:
        st.subheader("Add Media")
        with st.form("media_form"):
            media_ml = st.number_input("Media (mL)", min_value=0, step=1, value=0)
            media_submit = st.form_submit_button("Add Media")
    
    with cols[1]:
        st.subheader("Remove Waste")
        with st.form("waste_form"):
            waste_ml = st.number_input("Waste (mL)", min_value=0, step=1, value=0)
            waste_submit = st.form_submit_button("Remove Waste")
    
    with cols[2]:
        st.subheader("Cycle Media")
        with st.form("cycle_form"):
            cycle_s = st.number_input("Cycle (s)", min_value=0, step=1, value=0)
            cycle_submit = st.form_submit_button("Cycle Media")
    
    if media_submit:
        payload = {
            "command": "pump_add_media",
            "reactor": reactor,
            "experiment": st.session_state["experiment"],
            "volume": media_ml
        }

        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()

        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)

        # Check if the dosing job is running
        # get_running_jobs(st.session_state["client"], reactor)

        # st.session_state["client"].loop_stop()

        # if "dosing" in running:
        #     st.success("Media added successfully!")
        # else:
        #     st.error("Failed to add media.")
        #     st.session_state["experiment"] = None
        
        # for run in running:
        #     st.session_state["jobs"][run] = True

        # st.session_state["experiment"] = experiment

        st.success("Media added successfully!")

        time.sleep(3)
        st.rerun()
    
    if waste_submit:
        payload = {
            "command": "pump_remove_media",
            "reactor": reactor,
            "experiment": st.session_state["experiment"],
            "volume": waste_ml
        }

        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()

        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)

        # Check if the dosing job is running
        # get_running_jobs(st.session_state["client"], reactor)

        # st.session_state["client"].loop_stop()

        # if "dosing" in running:
        #     st.success("Waste removed successfully!")
        # else:
        #     st.error("Failed to remove waste.")
        #     st.session_state["experiment"] = None
        
        # for run in running:
        #     st.session_state["jobs"][run] = True

        # st.session_state["experiment"] = experiment

        st.success("Waste removed successfully!")

        time.sleep(3)
        st.rerun()

    if cycle_submit:
        payload = {
            "command": "circulate_media",
            "reactor": reactor,
            "experiment": st.session_state["experiment"],
            "duration": cycle_s
        }

        payload_str = json.dumps(payload)

        st.session_state["client"].loop_start()

        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        time.sleep(1)

        # Check if the dosing job is running
        # get_running_jobs(st.session_state["client"], reactor)

        # st.session_state["client"].loop_stop()

        # if "dosing" in running:
        #     st.success("Media cycled successfully!")
        # else:
        #     st.error("Failed to cycle media.")
        #     st.session_state["experiment"] = None
        
        # for run in running:
        #     st.session_state["jobs"][run] = True

        # st.session_state["experiment"] = experiment

        st.success("Media cycled successfully!")

        time.sleep(3)
        st.rerun()

    st.divider()

    st.header("Graphs")

    

    st.session_state["client"].loop_start()
    st.session_state["client"].subscribe(f"pioreactor/{reactor}/readings")
    st.session_state["client"].message_callback_add(f"pioreactor/{reactor}/readings", on_message)

    temp_graph_actual = []

    st.subheader("Temperature Graph")
    amount_of_data = st.radio("Amount of data", ["1 hour", "24 hours", "All data"], index=1, key="temperature")
    placeholder = st.empty()

    st.subheader("OD Reading Graph")
    amount_of_data2 = st.radio("Amount of data", ["1 hour", "24 hours", "All data"], index=1, key="od")
    placeholder2 = st.empty()

    st.subheader("Normalized OD Reading Graph")
    amount_of_data3 = st.radio("Amount of data", ["1 hour", "24 hours", "All data"], index=1, key="norm_od")
    placeholder3 = st.empty()

    st.subheader("Growth Rate Graph")
    amount_of_data4 = st.radio("Amount of data", ["1 hour", "24 hours", "All data"], index=1, key="growth_rate")
    placeholder4 = st.empty()

    # get_graph(placeholder)

    while True:
        if st.session_state.get("df", None) is not None and st.session_state.get("temp_radio", None) == amount_of_data:
            placeholder.line_chart(st.session_state["df"], x_label="Time", y_label="Temperature (°C)")
        if st.session_state.get("df2", None) is not None and st.session_state.get("od_radio", None) == amount_of_data2:
            placeholder2.line_chart(st.session_state["df2"], x_label="Time", y_label="OD Reading")
        if st.session_state.get("df3", None) is not None and st.session_state.get("norm_od_radio", None) == amount_of_data3:
            placeholder3.line_chart(st.session_state["df3"], x_label="Time", y_label="Normalized OD Reading")
        if st.session_state.get("df4", None) is not None and st.session_state.get("growth_rate_radio", None) == amount_of_data4:
            placeholder4.line_chart(st.session_state["df4"], x_label="Time", y_label="Growth Rate")

        st.session_state["temp_radio"] = amount_of_data
        st.session_state["od_radio"] = amount_of_data2
        st.session_state["norm_od_radio"] = amount_of_data3
        st.session_state["growth_rate_radio"] = amount_of_data4

        temp_graph = None
        od_graph = None
        norm_od_graph = None
        growth_rate_graph = None
        payload = {
            "command": "get_readings",
            "experiment": st.session_state["experiment"],
            "reactor": reactor,
            "filter_mod": 1,
            "lookback": 10000000,
            "filter_mod2": 1,
            "lookback2": 10000000,
            "filter_mod3": 1,
            "lookback3": 10000000,
            "filter_mod4": 1,
            "lookback4": 10000000,
            "amount": amount_of_data,
            "amount2": amount_of_data2,
            "amount3": amount_of_data3,
            "amount4": amount_of_data4
        }

        payload_str = json.dumps(payload)
        st.session_state["client"].publish("pioreactor/control", payload_str, qos=1)

        timeout = 10
        start_time = time.time()

        while (temp_graph is None or od_graph is None or norm_od_graph is None or growth_rate_graph is None) and (time.time() - start_time) < timeout:
            time.sleep(1)

        # Check if all is None
        # if temp_graph is None and od_graph is None and norm_od_graph is None and growth_rate_graph is None:
        #     st.error("Failed to retrieve data.")
        #     st.stop()

        if len(temp_graph) != 0:

            for temp in temp_graph:
                utc_time = datetime.strptime(temp["x"], "%Y-%m-%dT%H:%M:%S.%fZ")
                local_tz = pytz.timezone("America/New_York")
                utc_time = utc_time.replace(tzinfo=pytz.utc)
                local_time = utc_time.astimezone(local_tz)
                temp["x"] = local_time.strftime("%Y-%m-%d %H:%M:%S")
                df = pd.DataFrame(temp_graph)
                df = df.set_index("x")
            placeholder.line_chart(df, x_label="Time", y_label="Temperature (°C)")
            st.session_state["df"] = df

        if len(od_graph) != 0:

            for od in od_graph:
                utc_time = datetime.strptime(od["x"], "%Y-%m-%dT%H:%M:%S.%fZ")
                local_tz = pytz.timezone("America/New_York")
                utc_time = utc_time.replace(tzinfo=pytz.utc)
                local_time = utc_time.astimezone(local_tz)
                od["x"] = local_time.strftime("%Y-%m-%d %H:%M:%S")
                df2 = pd.DataFrame(od_graph)
                df2 = df2.set_index("x")
            placeholder2.line_chart(df2, x_label="Time", y_label="OD Reading")
            st.session_state["df2"] = df2

        if len(norm_od_graph) != 0:
        
            for norm_od in norm_od_graph:
                utc_time = datetime.strptime(norm_od["x"], "%Y-%m-%dT%H:%M:%S.%fZ")
                local_tz = pytz.timezone("America/New_York")
                utc_time = utc_time.replace(tzinfo=pytz.utc)
                local_time = utc_time.astimezone(local_tz)
                norm_od["x"] = local_time.strftime("%Y-%m-%d %H:%M:%S")
                df3 = pd.DataFrame(norm_od_graph)
                df3 = df3.set_index("x")
            placeholder3.line_chart(df3, x_label="Time", y_label="Normalized OD Reading")
            st.session_state["df3"] = df3

        if len(growth_rate_graph) != 0:

            for growth_rate in growth_rate_graph:
                utc_time = datetime.strptime(growth_rate["x"], "%Y-%m-%dT%H:%M:%S.%fZ")
                local_tz = pytz.timezone("America/New_York")
                utc_time = utc_time.replace(tzinfo=pytz.utc)
                local_time = utc_time.astimezone(local_tz)
                growth_rate["x"] = local_time.strftime("%Y-%m-%d %H:%M:%S")
                df4 = pd.DataFrame(growth_rate_graph)
                df4 = df4.set_index("x")
            placeholder4.line_chart(df4, x_label="Time", y_label="Growth Rate")
            st.session_state["df4"] = df4

        # Filter the data based on the amount of data requested
        # Data is in 4 minute intervals
        
        time.sleep(REQUEST_INTERVAL)