/
main.py
2153 lines (1862 loc) · 78.8 KB
/
main.py
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
"""
Created by Julian Fawkes, 2020, and Chris Kelly, 2021/2022
Contributions and minor edits by: Naomi Zimmerman, Melanie MacArthur, Stefan Colbow, Rachel Habermehl, and Davi Monticelli
PLUME Dashboard - A browser-based pollutant data visualization program built using Dash. The dashboard pulls data
from a DAQ script using a locally-hosted redis server. Each instrument sends data using a
different transfer protocol and is taken in by a CR1000X datalogger.
Either modbus-tcp_daq.py or another DAQ script must first be running in order for this script to work. Additionally, the
'user_defined_settings.ini' file must first be set up before running this script.
"""
import os
import math
import sys
import dash
import csv
import statistics
from dash.dependencies import Output, Input, State
from plotly.subplots import make_subplots
from collections import deque
import collections
import plotly.express as px
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import datetime as dt
import dash_daq as daq
import redis
import openpyxl
import pandas as pd
import numpy as np
from configparser import ConfigParser
from pathlib import Path
import json
from os.path import exists
import pyuac
#NOTE: when you see variables like "fold_start = 0" or "avs = 0", those are just lines of folds starting and ending (pycharm doesn't want fold borders to be comments)
'''#########################
## SECTION 1. Bookkeeping ##
#########################'''
fold_start = 0
# Create a dash object 'app' with name '__name__'. Stop the title from changing when content updates.
app = dash.Dash(__name__,update_title=None, external_stylesheets=[dbc.themes.MINTY])
server = app.server
app_color = dict(graph_bg="#E3E4E0", red="#E94029", green="#00703D", yellow="#E4BC3F")
app.title = 'PLUME Dashboard'
interval_s = 2 #Instrument polling rates in seconds.normally 2
graph_range = 2 * 60 #Range of graph display in seconds.
#trace_length = math.trunc(graph_range / interval_s)
trace_length = 60 #no. of points on the graph
#list of dropdown options
instrumentdict = [
{"label": "NO2", "value": "NO2"},
{"label": "WCPC", "value": "WCPC"},
{"label": "O3", "value": "O3"},
{"label": "CO", "value": "CO"},
{"label": "CO2", "value": "CO2"},
{"label": "NO", "value": "NO"},
{"label": "WS", "value": "WS"},
{"label": "WD", "value": "WD"},
]
#unit dictionary, this MUST be matched with instrumentdict
labeldict = {"NO2": "Concentration (ppb)", "WCPC": "Concentration (#/cm\u00B3)",
"O3": "Concentration (ppb)", "CO": "Concentration (ppm)",
"CO2": "Concentration (ppm)", "NO": "Concentration (ppb)",
"WS": "Wind-speed (m/s)", "WD": "Wind-direction (degrees)"}
#define our deques
no2_trace_y = deque([0], maxlen=trace_length)
no2_trace_x = deque([0], maxlen=trace_length)
wcpc_trace_y = deque([0], maxlen=trace_length)
wcpc_trace_x = deque([0], maxlen=trace_length)
o3_trace_y = deque([0], maxlen=trace_length)
o3_trace_x = deque([0], maxlen=trace_length)
co_trace_y = deque([0], maxlen=trace_length)
co_trace_x = deque([0], maxlen=trace_length)
co2_trace_y = deque([0], maxlen=trace_length)
co2_trace_x = deque([0], maxlen=trace_length)
no_trace_y = deque([0], maxlen=trace_length)
no_trace_x = deque([0], maxlen=trace_length)
ws_trace_y = deque([0], maxlen=trace_length)
ws_trace_x = deque([0], maxlen=trace_length)
wd_trace_y = deque([0], maxlen=trace_length)
wd_trace_x = deque([0], maxlen=trace_length)
#define our container deques, these are used to pass data to the live plot
no2_trace_container = deque([dict(x=0, y=0)], maxlen=1)
wcpc_trace_container = deque([dict(x=0, y=0)], maxlen=1)
o3_trace_container = deque([dict(x=0, y=0)], maxlen=1)
co_trace_container = deque([dict(x=0, y=0)], maxlen=1)
co2_trace_container = deque([dict(x=0, y=0)], maxlen=1)
no_trace_container = deque([dict(x=0, y=0)], maxlen=1)
ws_trace_container = deque([dict(x=0, y=0)], maxlen=1)
wd_trace_container = deque([dict(x=0, y=0)], maxlen=1)
#helper function for settings loading, changes "int,int" into [int,int]
def string_to_list_interval(string_in):
# remove all spaces from string_in
string_in = string_in.replace(" ", "")
#define vars
comma_index = 0
lower=""
upper=""
result=[]
#append to lower until comma is found
for i in range(0,len(string_in)):
if string_in[i] == ",":
comma_index=i
break
else:
lower+=string_in[i]
#append to upper until end of string, starting from first index after comma
for i in range(comma_index+1,len(string_in)):
upper+=string_in[i]
#return result as list
result.append(int(lower))
result.append(int(upper))
return result
foldend = 0
'''###################################
## SECTION 2. Auto event algorithms ##
###################################'''
avs = 0
#peak detection algorithm
def A1ap(data_points, pollutant):
#exiting the function if A1 is disabled
global A1
global A1_startup_bypass
global index_clock
if (A1 == False) or (index_clock<A1_startup_bypass):
return None
# defining vars and importing global vars
#m = statistics.median(data_points) #old command using 50th percentile (median)
global A1_percentile
global A1_thresh_bump_percentile
m = np.percentile(data_points, A1_percentile[pollutant]) #using a custom percentile as our median
below_m = []
global A1_auto_event_count
global A1_n
global A1_coeff
if A1_thresh_bump_percentile[pollutant] == 0:
thresh_bump = 0
else:
thresh_bump = np.percentile(data_points, A1_thresh_bump_percentile[pollutant])
#creating list of points below median and determining the threshold
for i in data_points:
if i < m:
below_m.append(i)
if len(below_m) < 2:
return None
sd = statistics.stdev(below_m) #stdev will do sample sd and pstdev will do population sd
thresh = A1_coeff[pollutant] * sd
thresh += thresh_bump #adding thresh bumpp
#(printing info for debugging purposes, only implemented for NO2)
'''
if pollutant == "no2":
global no2_clock_y
global no2_clock_x
below_m_rounded = [round(num, 2) for num in below_m]
print("x="+str(no2_clock_x)+", y=" + str(round(no2_clock_y, 2)) + ", median: " + str(round(m, 2)) + ", bm-sd: " + str(
round(sd, 2)) + ", thresh: " + str(round(thresh, 2)) + " A1_n=" + str(A1_n["no2"]) + ", below_m: " + str(
below_m_rounded))
'''
# checking the appropriate threshold
if A1_n[pollutant] == 0:
if data_points[-1] >= thresh:
A1_n[pollutant] += 1
auto_event_mark("A1-"+pollutant+"-" + str(A1_auto_event_count[pollutant]),"peak",pollutant)
A1_auto_event_count[pollutant] += 1
#for debugging
#if pollutant == "no2":
#print("peak")
return None
else:
return None
else:
if data_points[-1] >= (thresh + sd * math.sqrt(A1_n[pollutant])):
A1_n[pollutant] += 1
auto_event_mark("A1-" + pollutant + "-" + str(A1_auto_event_count[pollutant]),"peak",pollutant)
A1_auto_event_count[pollutant] += 1
# for debugging
#if pollutant == "no2":
#print("s-peak")
return None
else:
A1_n[pollutant] = 0
return None
#A2 was originally designed to detect a steady increase... however we have disabled it. The code is here for anyone who wants to dabble with it
def A2ap(data_points, pollutant):
# exiting the function if A2 is disabled
global A2
if A2 == False:
return None
#importing global vars and defining local vars
global A2_interval
global A2_slope_thresh
global A2_hits_to_sink
global A2_n
global A2_auto_event_count
interval_size = A2_interval[pollutant].maxlen
#importing next data point to the interval and exiting function if there isn't enough data
A2_interval[pollutant].append(data_points[-1])
if len(A2_interval[pollutant]) != interval_size:
return None
#computing slope and comparing to threshold
slope = ( A2_interval[pollutant][-1] - A2_interval[pollutant][0] ) / interval_size
if abs(slope) >= A2_slope_thresh[pollutant]:
A2_n[pollutant] += 1
else:
A2_n[pollutant] = 0
#debugging purpose, only implemented for no2
if pollutant == "no2":
rounded_interval = [round(num, 2) for num in A2_interval[pollutant]]
print("slope="+str(round(slope,2))+", n="+str(A2_n[pollutant])+", interval: "+str(rounded_interval))
if abs(slope) >= A2_slope_thresh[pollutant]:
print("^HIT")
if A2_n[pollutant] == A2_hits_to_sink[pollutant]:
A2_n[pollutant] = 0
#printing for debugging, only implemented for no2
if pollutant == "no2":
print("and sunk!")
if slope > 0:
auto_event_mark("A2-" + pollutant + "-I-" + str(A2_auto_event_count[pollutant]),"increase",pollutant)
A2_auto_event_count[pollutant] += 1
return None
else:
auto_event_mark("A2-" + pollutant + "-D-" + str(A2_auto_event_count[pollutant]),"decrease",pollutant)
A2_auto_event_count[pollutant] += 1
return None
else:
return None
#AQ over/under detection
def AQap(data_points, pollutant):
#exitting function if AQ is disabled
global AQ
if AQ == False:
return None
#import global vars
global AQ_thresh
global AQ_over
global AQ_auto_event_count
#detecting if the graph moves upward over the line
if (data_points[-1] > AQ_thresh[pollutant]) and (AQ_over[pollutant] == False):
AQ_over[pollutant] = True
#print(pollutant + " AQ over threshold of " + str(AQ_thresh[pollutant]))
##
auto_event_mark("AQ-" + pollutant.upper() + "-over-" + str(AQ_auto_event_count[pollutant]), "AQ over", pollutant)
AQ_auto_event_count[pollutant] += 1
return None
#detecting if the graph moves downward over the line
if (data_points[-1] < AQ_thresh[pollutant]) and (AQ_over[pollutant] == True):
AQ_over[pollutant] = False
#print(pollutant + " AQ back to under threshold of " + str(AQ_thresh[pollutant]))
auto_event_mark("AQ-" + pollutant.upper() + "-under-" + str(AQ_auto_event_count[pollutant]), "AQ under", pollutant)
AQ_auto_event_count[pollutant] += 1
return None
#detects when the wind direction is within a certain radial range
def wind_direction_alert(data_points, pollutant):
#exitting function if wind direction alert is disabled
global enable_wind_direction_alert
if enable_wind_direction_alert == False:
return None
#import global vars, uses same counter variables as AQ algorithm
global wind_direction_alert_range
global AQ_over
global AQ_auto_event_count
#detecting if the direction moves INTO the alert range
if (data_points[-1] >= wind_direction_alert_range[0]) and (data_points[-1] <= wind_direction_alert_range[1]) and (AQ_over[pollutant] == False):
AQ_over[pollutant] = True
print("Wind direction is within alert range")
auto_event_mark("WD-alert-begin-" + str(AQ_auto_event_count[pollutant]), "WD alert begin", pollutant)
AQ_auto_event_count[pollutant] += 1
return None
#detecting if the direction moves OUT OF the alert range
if (not ( (data_points[-1] >= wind_direction_alert_range[0]) and (data_points[-1] <= wind_direction_alert_range[1]))) and (AQ_over[pollutant] == True):
AQ_over[pollutant] = False
print("Wind direction is no longer within alert range")
auto_event_mark("WD-alert-end-" + str(AQ_auto_event_count[pollutant]), "WD alert end", pollutant)
AQ_auto_event_count[pollutant] += 1
return None
#helper function to remove the leftmost zero of traces so that A1 can work properly
def zero_flush():
#import our global switch and exit function if it's already been ran or if the queues are too small
global left_zero_popped
global no2_trace_y
if (left_zero_popped == True) or len(no2_trace_y) < 4:
return None
#import all of our other pollutant queues
global wcpc_trace_y
global o3_trace_y
global co_trace_y
global co2_trace_y
global no_trace_y
global ws_trace_y
global wd_trace_y
#delete the leftmost entry (the trailing 0)
#print("flushing zeros")
no2_trace_y.popleft()
wcpc_trace_y.popleft()
o3_trace_y.popleft()
co_trace_y.popleft()
co2_trace_y.popleft()
no_trace_y.popleft()
ws_trace_y.popleft()
wd_trace_y.popleft()
#prevent function from running again
left_zero_popped = True
srgdfg = 0
'''##################
## SECTION 3. Dash ##
##################'''
avs=0
# Helper function definitions for complex or repeated operations.
def create_graduatedbar_helper(name):
"""Helper function to create graduated bars (saves lines of code)"""
# Create each graduated bar row
bar_row = dbc.Row(
[
# Create the graduated bar to the left
dbc.Col(
[
daq.GraduatedBar(
color={"gradient": True,
"ranges": {app_color['green']: [0, 60],
app_color['yellow']: [60, 75],
app_color['red']: [75, 100]}
},
showCurrentValue=False,
label=str(name),
id=str(name) + "-bar",
max=100,
step=2,
style={"padding-bottom": "5px"},
size=205
)
]
),
# Create the text displaying the actual data on the right
dbc.Col(
[
html.P(
id=str(name) + "-bar-text",
children=['No data'],
style={'position': 'absolute',
'bottom': '0',
'font-size': '.9rem'},
)
],
)
]
)
# Define the graduated bar styling and return it
return bar_row
def update_liveplot_helper(trace_dict, dropdown_value):
"""Helper function to populate liveplot depending on selected pollutants"""
# Find number of pollutants selected to be plotted
numplots = len(list(dropdown_value))
# Create figure layout depending on number of selected pollutants. Also create a list of figure titles.
if numplots == 1:
figure_title_list = [dropdown_value[0]]
figspec = [
[{'rowspan': 2, 'colspan': 2}, None],
[None, None]
]
elif numplots == 2:
figure_title_list = dropdown_value[:2]
figspec = [
[{'rowspan': 2}, {'rowspan': 2}],
[None, None]
]
elif numplots == 3:
figure_title_list = dropdown_value[:3]
figspec = [
[{}, {}],
[{'colspan': 2}, None]
]
elif numplots == 4:
figure_title_list = dropdown_value[:4]
figspec = [
[{}, {}],
[{}, {}]
]
else:
figure_title_list = ["Select pollutants"]
figspec = [
[None, None],
[None, None]
]
# Create the figure container with row and column divisions.
fig = make_subplots(rows=2, cols=2, specs=figspec, subplot_titles=figure_title_list, vertical_spacing=0.10)
# Populate the divisions with scatter plots depending on number of selected pollutants.
if numplots > 0:
# Add a scatter in its respective row and column using the dropdown values to select pollutants
fig.add_scatter(y=list(trace_dict[list(dropdown_value)[0]]['y']),
x=list(trace_dict[list(dropdown_value)[0]]['x']),
row=1, col=1, name=dropdown_value[0], mode='lines')
# Update axis labels to correspond with those being plotted using the label dictionary.
fig.update_xaxes(title_text="Time (HH:MM:SS)", row=1, col=1),
fig.update_yaxes(title_text=labeldict[dropdown_value[0]], row=1, col=1, range=y_range_dict[dropdown_value[0]])
if numplots > 1:
# Add a scatter in its respective row and column using the dropdown values to select pollutants
fig.add_scatter(y=list(trace_dict[list(dropdown_value)[1]]['y']),
x=list(trace_dict[list(dropdown_value)[1]]['x']),
row=1, col=2, name=dropdown_value[1], mode='lines')
# Update axis labels to correspond with those being plotted using the label dictionary.
fig.update_xaxes(title_text="Time (HH:MM:SS)", row=1, col=2),
fig.update_yaxes(title_text=labeldict[dropdown_value[1]], row=1, col=2, range=y_range_dict[dropdown_value[1]])
if numplots > 2:
# Add a scatter in its respective row and column using the dropdown values to select pollutants
fig.add_scatter(y=list(trace_dict[list(dropdown_value)[2]]['y']),
x=list(trace_dict[list(dropdown_value)[2]]['x']),
row=2, col=1, name=dropdown_value[2], mode='lines')
# Update axis labels to correspond with those being plotted using the label dictionary.
fig.update_xaxes(title_text="Time (HH:MM:SS)", row=2, col=1),
fig.update_yaxes(title_text=labeldict[dropdown_value[2]], row=2, col=1, range=y_range_dict[dropdown_value[2]])
if numplots > 3:
# Add a scatter in its respective row and column using the dropdown values to select pollutants
fig.add_scatter(y=list(trace_dict[list(dropdown_value)[3]]['y']),
x=list(trace_dict[list(dropdown_value)[3]]['x']),
row=2, col=2, name=dropdown_value[3], mode='lines')
# Update axis labels to correspond with those being plotted using the label dictionary.
fig.update_xaxes(title_text="Time (HH:MM:SS)", row=2, col=2),
fig.update_yaxes(title_text=labeldict[dropdown_value[3]], row=2, col=2, range=y_range_dict[dropdown_value[3]])
# Apply plot styling
fig.update_layout(
autosize=True,
margin=dict(t=20, b=20),
plot_bgcolor=app_color["graph_bg"],
showlegend=False,
)
# Set the number of ticks on the x axis in all plots to declutter the axis tick text.
fig.update_xaxes(
nticks=4
)
return fig
#define live plots
liveplot = dbc.Card(
[
dbc.Row(
[
dbc.Col(
html.H5("Pollutant Histogram"),
),
]
),
dcc.Graph(
id='liveplot',
config={'displayModeBar': False},
style={"height": "100%", "overflow": "hidden"}
),
dbc.Row(
[
dbc.Col(
[
dcc.Dropdown(
id='graph-dropdown',
placeholder="Select plotted pollutants...",
options=instrumentdict,
multi=True,
),
],
width=6,
),
# This col-row nest is ugly. It's the only way to output something pretty for an operator, so it stays.
dbc.Col(
[
dbc.Row(
[
dbc.Col(
[
dbc.Input(
id='mark-event-input',
placeholder="Enter a short, descriptive event tag",
className='appended-input'
),
dbc.FormFeedback(
"Event marker logged to file",
valid=True
),
dbc.FormFeedback(
"Error marking event",
valid=False
)
]
),
dbc.Col(
[
dbc.Button(
"Mark Event",
id="mark-event",
n_clicks=0,
size="sm",
color="warning",
className="appended-button"
),
],
width="auto"
)
],
)
],
width=6
)
]
),
],
style={"padding": "5px 5px 5px 5px"},
className="h-100",
)
#define graduated bars on right
livebar = dbc.Card(
[
html.H5("Live Pollutant Data"),
create_graduatedbar_helper("NO2"),
create_graduatedbar_helper("WCPC"),
create_graduatedbar_helper("O3"),
create_graduatedbar_helper("CO"),
create_graduatedbar_helper("CO2"),
create_graduatedbar_helper("NO"),
create_graduatedbar_helper("WS"),
create_graduatedbar_helper("WD"),
],
style={"padding": "5px 5px 5px 5px"},
className="h-100"
)
#define wind direction plot
wind_direction = dbc.Card(
[
html.H5(
"Wind Direction", className="graph__title"
),
dcc.Graph(
id="wind-direction",
config={'displayModeBar': False},
figure=dict(
layout=dict(
plot_bgcolor=app_color["graph_bg"],
paper_bgcolor=app_color["graph_bg"],
)
),
style={"width": "100%",
"height": "100%",
"justify-content": "center",
"align-items": "center",
"display": "flex",
}
),
],
style={"padding": "5px 5px 5px 5px"},
className="h-100"
)
#define the layout of the dashboard
app.layout = dbc.Container(
[
# Data Display Panel
dbc.Row(
[
# Left column
dbc.Col(
html.Div(
liveplot,
style={"height": "96vh"}
),
width=9,
),
# Right column
dbc.Col(
[
# Top
html.Div(
livebar,
style={"height": "52vh"}
),
# Bottom
html.Div(
wind_direction,
style={"height": "44vh"}
),
],
width=3,
),
],
),
# Update interval for the wind direction module
dcc.Interval(
id='wind-interval',
interval=interval_s * 1000,
n_intervals=0,
),
# Update interval for instrument input
dcc.Interval(
id='daq-interval',
interval=1000,
n_intervals=0
),
# Update interval for the live figures
dcc.Interval(
id='figure-interval',
interval=500,
n_intervals=0
),
html.Div(
id='dump-hdiv',
style={'display': 'none'}
)
],
fluid=True,
)
avs=0
'''########################################
## SECTION 4. CSV data marking functions ##
########################################'''
avs=0
#shared auto event marking function
def auto_event_mark(auto_event_name,algorithm,pollutant):
try:
# get today's date
this_day = dt.date.today()
# Create a file name.
filename = log_folder_path + "/Event Markers " + str(this_day) + ".csv"
txt_filename = log_folder_path + "/Event Markers Backup " + str(this_day) + ".txt"
# Check if the file exists already.
file_exists = os.path.isfile(filename)
with open(filename, 'a', newline='\n') as file, open(txt_filename, 'a', newline='\n') as txt_file:
# Create a dictionary with our seven csv columns
markerdict = dict.fromkeys(['Type','Pollutant','Event Tag', 'Time','NO2 (ppb)', 'WCPC (#/cm^3)', 'O3 (ppb)', 'CO (ppm)', 'CO2 (ppm)','NO (ppb)','WS (m/s)','WD (degrees)'])
# Populate our columns with the user input and current time and current values of pollutants
markerdict['Type'] = algorithm
markerdict['Pollutant'] = pollutant
markerdict['Time'] = (dt.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
markerdict['Event Tag'] = auto_event_name
markerdict['NO2 (ppb)'] = no2_trace_y[-1]
markerdict['WCPC (#/cm^3)'] = wcpc_trace_y[-1]
markerdict['O3 (ppb)'] = o3_trace_y[-1]
markerdict['CO (ppm)'] = co_trace_y[-1]
markerdict['CO2 (ppm)'] = co2_trace_y[-1]
markerdict['NO (ppb)'] = no_trace_y[-1]
markerdict['WS (m/s)'] = ws_trace_y[-1]
markerdict['WD (degrees)'] = wd_trace_y[-1]
# Write our data to our csv
writer = csv.DictWriter(file, delimiter=',', fieldnames=list(markerdict.keys()))
# prepare a string to be written to our txt and then write to it
txt_string = str((dt.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")) + ", " + auto_event_name + ", " + str(
no2_trace_y[-1]) + ", " + str(wcpc_trace_y[-1]) + ", " + str(o3_trace_y[-1]) + ", " + str(
co_trace_y[-1]) + ", " + str(co2_trace_y[-1]) +', ' +str(no_trace_y[-1]) +', ' +str(ws_trace_y[-1]) +', ' +str(wd_trace_y[-1]) +"\n"
txt_file.write(txt_string)
# If the log file did not already exist, write the column headers.
if not file_exists:
writer.writeheader()
# Write our row of data
writer.writerow(markerdict)
# If an IO error occurs, do the following
except IOError:
print(
"Error marking event. Check log folder read/write permissions or run bash script as administrator")
return False, not False
#sensor transcript function, writes current row to sensor transcript
def sensor_dump():
global index_clock
try:
# get today's date
this_day = dt.date.today()
# Create a file name.
filename = log_folder_path + "/Sensor Transcript " + str(this_day) + ".csv"
txt_filename = log_folder_path + "/Sensor Transcript Backup " + str(this_day) + ".txt"
# Check if the file exists already.
file_exists = os.path.isfile(filename)
with open(filename, 'a', newline='\n') as file, open(txt_filename, 'a', newline='\n') as txt_file:
# Create a dictionary with our seven csv columns
markerdict = dict.fromkeys(['Row','Time','NO2 (ppb)', 'WCPC (#/cm^3)', 'O3 (ppb)', 'CO (ppm)', 'CO2 (ppm)','NO (ppb)','WS (m/s)','WD (degrees)'])
# Populate our columns with the user input and current time and current values of pollutants
markerdict['Row'] = index_clock
markerdict['Time'] = (dt.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
markerdict['NO2 (ppb)'] = no2_trace_y[-1]
markerdict['WCPC (#/cm^3)'] = wcpc_trace_y[-1]
markerdict['O3 (ppb)'] = o3_trace_y[-1]
markerdict['CO (ppm)'] = co_trace_y[-1]
markerdict['CO2 (ppm)'] = co2_trace_y[-1]
markerdict['NO (ppb)'] = no_trace_y[-1]
markerdict['WS (m/s)'] = ws_trace_y[-1]
markerdict['WD (degrees)'] = wd_trace_y[-1]
# Write our data to our csv
writer = csv.DictWriter(file, delimiter=',', fieldnames=list(markerdict.keys()))
# prepare a string to be written to our txt and then write to it
txt_string = str(index_clock)+", "+str((dt.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")) + ", " +str(
no2_trace_y[-1]) + ", " + str(wcpc_trace_y[-1]) + ", " + str(o3_trace_y[-1]) + ", " +str(
co_trace_y[-1]) + ", " + str(co2_trace_y[-1]) + ", "+ str(no_trace_y[-1]) +', ' +str(ws_trace_y[-1]) +', ' +str(wd_trace_y[-1]) +"\n"
txt_file.write(txt_string)
index_clock += 1
# If the log file did not already exist, write the column headers.
if not file_exists:
writer.writeheader()
# Write our row of data
writer.writerow(markerdict)
# If an IO error occurs, do the following
except IOError:
print(
"Error marking event. Check log folder read/write permissions or run bash script as administrator")
return False, not False
#function for reading commands and executing them
def read_command(raw_command):
#exiting function if not a command
global command_character
if raw_command[0] != command_character:
return None
#setting all to lowercase and removing spaces
command=""
raw_command = raw_command.lower()
for p in raw_command:
if p != " ":
command += p
#marking as a valid command for tagging purposes
global is_valid_command
is_valid_command = True
##################
## COMMAND LIST ##
##################
#change of A1_coeff command
"""
'*coeff = 12 - no2' #changes A1_coeff for no2 to 12
'*coeff = 456 - wcpc' #changes A1_coeff for wcpc to 456
"""
if command[1:7] == "coeff=":
global A1_coeff
#finding new coeff and pollutant from command
new_coeff=""
pollutant=""
for i in range(7,len(command)):
if command[i] == "-":
pollutant = command[(i+1):len(command)]
break
new_coeff += command[i]
print("changing A1_coeff for " + pollutant + " to " + new_coeff)
A1_coeff[pollutant] = int(new_coeff)
return None
#change of A1_percentile command
"""
'*percentile = 75 - no2' #changes A1_percentile for no2 to 75
'*percentile = 50 - wcpc' #changes A1_coeff for wcpc to 50
"""
if command[1:12] == "percentile=":
global A1_percentile
# finding new percentile and pollutant from command
new_percentile = ""
pollutant = ""
for i in range(12, len(command)):
if command[i] == "-":
pollutant = command[(i + 1):len(command)]
break
new_percentile += command[i]
print("changing A1_percentile for " + pollutant + " to " + new_percentile)
A1_percentile[pollutant] = int(new_percentile)
return None
#change of AQ_thresh command
"""
'*AQ_thresh = 40 - no2' #changes AQ_thresh for no2 to 40
'*AQ_thresh = 8000 - wcpc' #changes AQ_thresh for wcpc to 8000
"""
if command[1:11] == "aq_thresh=":
global AQ_thresh
# finding new thresh and pollutant from command
new_thresh = ""
pollutant = ""
for i in range(11, len(command)):
if command[i] == "-":
pollutant = command[(i + 1):len(command)]
break
new_thresh += command[i]
print("changing AQ_thresh for " + pollutant + " to " + new_thresh)
AQ_thresh[pollutant] = int(new_thresh)
return None
#simple A1, AQ, and wind direction alert toggle switch
"""
'*tA1' - toggles A1 on/off
'*tAQ' - toggles AQ on/off
'*tWDRW' - toggles wind direction alert on/off
"""
if command[1] == 't':
global toggle_type
if command[2:4] == 'a1':
global A1
if A1 == True:
A1 = False
print("toggling A1 OFF")
toggle_type = '(A1 OFF)'
return None
else:
A1 = True
print("toggling A1 ON")
toggle_type = '(A1 ON)'
return None
if command[2:4] == 'aq':
global AQ
if AQ == True:
AQ = False
print("toggling AQ OFF")
toggle_type = '(AQ OFF)'
return None
else:
AQ = True
print("toggling AQ ON")
toggle_type = '(AQ ON)'
return None
if command[2:5] == 'wdrw':
global enable_wind_direction_alert
if enable_wind_direction_alert:
enable_wind_direction_alert = False
print("toggling wind direction range warning OFF")
toggle_type = '(WDRW OFF)'
return None
else:
enable_wind_direction_alert = True
print("toggling wind direction range warning ON")
toggle_type = '(WDRW ON)'
return None
#change of graph y axes range command (if statement accounting for both possible notations)
"""
'*y_range = 0,80-no2' #changes graph y_range for no2 to [0,80]
'*y_range = 6000,9000 - wcpc' #changes graph y_range for wcpc to [6000,9000]
OR (shortcut version)
'*0,80 no2' #changes graph y_range for no2 to [0,80]
'*6000,9000 wcpc' #changes graph y_range for wcpc to [6000,9000]
"""
if (command[1:9] == "y_range=") or (command[1].isnumeric()):
global y_range_dict
#alternate shortcut version
if command[1].isnumeric():
lower_bound = ""
upper_bound = ""
pollutant = ""
for i in range(1,len(command)):
if command[i] == ",":
for f in range((i+1),len(command)):
if command[f].isnumeric() == False:
pollutant = command[f:len(command)]
break
upper_bound += command[f]
break
lower_bound += command[i]
print("changing graph y_range for " + pollutant + " to [" + lower_bound + "," + upper_bound + "]")
y_range_dict[pollutant.upper()] = [int(lower_bound), int(upper_bound)]
return None
#finding interval lower bound, upper bound, and pollutant from command
lower_bound=""
upper_bound=""
pollutant = ""
for i in range(9,len(command)):
if command[i] == ",":
for f in range((i+1),len(command)):
if command[f] == "-":
pollutant = command[(f+1):len(command)]
break
upper_bound += command[f]
break
lower_bound += command[i]
print("changing graph y_range for " + pollutant + " to [" + lower_bound +","+upper_bound+"]" )
y_range_dict[pollutant.upper()] = [int(lower_bound),int(upper_bound)]
return None
#autoscale toggle switch
"""
'*AS no2' - toggles autoscale on/off for NO2
'*AS wcpc' - toggles autoscale on/off for NO2
"""
if command[1:3] == "as":
global enable_autoscale_dict
pollutant = ''
for i in range(3, len(command)):
pollutant += command[i]
pollutant = pollutant.upper()
if enable_autoscale_dict[pollutant]:
print("Disabling autoscale for "+pollutant)
enable_autoscale_dict[pollutant] = False
y_range_dict[pollutant] = y_range_dict_original[pollutant]
else:
print("Enabling autoscale for " + pollutant)
enable_autoscale_dict[pollutant] = True
#change wind direction alert range
"""
'*WDrange = 150,180' - changes wind direction alert range to 150 - 180
'*WDrange = 200,300' - changes wind direction alert range to 200 - 300
"""
if command[1:9] == 'wdrange=':