-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisualizer_api.py
2208 lines (1996 loc) · 96.4 KB
/
visualizer_api.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
import io
import zipfile
import numpy as np
import pandas as pd
from typing import List, Optional
import time
import asyncio
import async_timeout
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
import dotenv
import pendulum
from datetime import timedelta
from pydantic import BaseModel
from sqlalchemy import create_engine, asc, or_
from sqlalchemy.orm import sessionmaker
from fake_config import Settings
from fake_models import MessageSql
# from gjk.models import ReadingSql, DataChannelSql
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import plotly.graph_objects as go
from analysis import download_excel
import os
from fastapi.responses import FileResponse
RUNNING_LOCALLY = False
PYPLOT_PLOT = True
MATPLOTLIB_PLOT = False
MESSAGE_SQL = True
TIMEOUT_SECONDS = 5*60
MAX_DAYS_WARNING = 3
settings = Settings(_env_file=dotenv.find_dotenv())
valid_password = settings.visualizer_api_password.get_secret_value()
engine = create_engine(settings.db_url.get_secret_value())
Session = sessionmaker(bind=engine)
app = FastAPI()
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
# allow_origins=["https://thegridelectric.github.io"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ------------------------------
# Useful conversions
# ------------------------------
tank_temperatures = [
'tank1-depth1', 'tank1-depth2', 'tank1-depth3', 'tank1-depth4',
'tank2-depth1', 'tank2-depth2', 'tank2-depth3', 'tank2-depth4',
'tank3-depth1', 'tank3-depth2', 'tank3-depth3', 'tank3-depth4'
]
def to_fahrenheit(t):
return t*9/5+32
# ------------------------------
# Request types
# ------------------------------
class DataRequest(BaseModel):
house_alias: str
password: str
start_ms: int
end_ms: int
selected_channels: List[str]
ip_address: str
user_agent: str
timezone: str
continue_option: Optional[bool] = False
darkmode: Optional[bool] = False
class CsvRequest(BaseModel):
house_alias: str
password: str
start_ms: int
end_ms: int
selected_channels: List[str]
timestep: int
continue_option: Optional[bool] = False
class DijkstraRequest(BaseModel):
house_alias: str
password: str
time_ms: int
class MessagesRequest(BaseModel):
password: str
selected_message_types: List[str]
house_alias: str = ""
start_ms: int
end_ms: int
darkmode: Optional[bool] = False
# ------------------------------
# Plot colors
# ------------------------------
def to_hex(rgba):
r, g, b, a = (int(c * 255) for c in rgba)
return f'#{r:02x}{g:02x}{b:02x}'
gradient = plt.get_cmap('coolwarm', 4)
buffer_colors = {
'buffer-depth1': gradient(3),
'buffer-depth2': gradient(2),
'buffer-depth3': gradient(1),
'buffer-depth4': gradient(0)
}
buffer_colors_hex = {key: to_hex(value) for key, value in buffer_colors.items()}
gradient = plt.get_cmap('coolwarm', 12)
storage_colors = {
'tank1-depth1': gradient(11),
'tank1-depth2': gradient(10),
'tank1-depth3': gradient(9),
'tank1-depth4': gradient(8),
'tank2-depth1': gradient(7),
'tank2-depth2': gradient(6),
'tank2-depth3': gradient(5),
'tank2-depth4': gradient(4),
'tank3-depth1': gradient(3),
'tank3-depth2': gradient(2),
'tank3-depth3': gradient(1),
'tank3-depth4': gradient(0),
}
storage_colors_hex = {key: to_hex(value) for key, value in storage_colors.items()}
zone_colors_hex = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
modes_colors_hex = {
'HpOffStoreDischarge': '#EF553B',
'HpOffStoreOff': '#00CC96',
'HpOnStoreOff': '#636EFA',
'HpOnStoreCharge': '#feca52',
'Initializing': '#a3a3a3',
'WaitingForTemperaturesOnPeak': '#a3a3a3',
'WaitingForTemperaturesOffPeak': '#4f4f4f',
'Dormant': '#4f4f4f'
}
modes_order = [
'HpOffStoreDischarge', 'HpOffStoreOff', 'HpOnStoreOff', 'HpOnStoreCharge', 'Initializing', 'Dormant']
top_modes_colors_hex = {
'HomeAlone': '#EF553B',
'Atn': '#00CC96',
'Admin': '#636EFA'
}
top_modes_order = ['HomeAlone', 'Atn', 'Dormant']
aa_modes_colors_hex = {
'HpOffStoreDischarge': '#EF553B',
'HpOffStoreOff': '#00CC96',
'HpOnStoreOff': '#636EFA',
'HpOnStoreCharge': '#feca52',
'WaitingNoElec': '#a3a3a3',
'WaitingElec': '#4f4f4f',
'Dormant': '#4f4f4f'
}
aa_modes_order = [
'HpOffStoreDischarge', 'HpOffStoreOff', 'HpOnStoreOff', 'HpOnStoreCharge', 'WaitingNoElec', 'WaitingElec', 'Dormant'
]
# ------------------------------
# Pull data from journaldb
# ------------------------------
def get_data(request):
import time
request_start = time.time()
if request.password != valid_password:
with open('failed_logins.log', 'a') as log_file:
log_entry = f"{pendulum.now()} - Failed login from {request.ip_address} with password: {request.password}\n"
log_entry += f"Timezone '{request.timezone}', device: {request.user_agent}\n\n"
log_file.write(log_entry)
return {
"success": False,
"message": "Wrong password.",
"reload":True
}, 0, 0, 0, 0, 0, 0, 0
if request.house_alias == '':
return {
"success": False,
"message": "Please enter a house alias.",
"reload": True
}, 0, 0, 0, 0, 0, 0, 0
if not request.continue_option:
if (request.end_ms - request.start_ms)/1000/60/60/24 > MAX_DAYS_WARNING:
warning_message = f"That's a lot of data! This could take a while, "
warning_message += f"and eventually trigger a timeout (after {int(TIMEOUT_SECONDS/60)} minutes). "
warning_message += f"It might be best to get this data in several smaller requests.\n\nAre you sure you would like to continue?"
return {
"success": False,
"message": warning_message,
"reload":False,
"continue_option": True,
}, 0, 0, 0, 0, 0, 0, 0
if not RUNNING_LOCALLY:
if (request.end_ms - request.start_ms)/1000/60/60/24 > 5 and isinstance(request, DataRequest):
return {
"success": False,
"message": "That's too many days to plot.",
"reload": False,
}, 0, 0, 0, 0, 0, 0, 0
if (request.end_ms - request.start_ms)/1000/60/60/24 > 21 and isinstance(request, CsvRequest):
return {
"success": False,
"message": "That's too many days of data to download.",
"reload": False,
}, 0, 0, 0, 0, 0, 0, 0
if MESSAGE_SQL:
session = Session()
messages = session.query(MessageSql).filter(
MessageSql.from_alias.like(f'%{request.house_alias}%'),
or_(
MessageSql.message_type_name == "batched.readings",
MessageSql.message_type_name == "report"
),
MessageSql.message_persisted_ms >= request.start_ms,
MessageSql.message_persisted_ms <=request.end_ms,
).order_by(asc(MessageSql.message_persisted_ms)).all()
if not messages:
return {
"success": False,
"message": f"No data found for house '{request.house_alias}' in the selected timeframe.",
"reload":False
}, 0, 0, 0, 0, 0, 0, 0
channels = {}
for message in messages:
if time.time() - request_start > TIMEOUT_SECONDS:
return {
"success": False,
"message": f"Timeout: getting the data took too much time.",
"reload":False
}, 0, 0, 0, 0, 0, 0, 0
for channel in message.payload['ChannelReadingList']:
# Find the channel name
if message.message_type_name == 'report':
channel_name = channel['ChannelName']
elif message.message_type_name == 'batched.readings':
for dc in message.payload['DataChannelList']:
if dc['Id'] == channel['ChannelId']:
channel_name = dc['Name']
# Store the values and times for the channel
if not (channel_name=='oat' and 'oak' in request.house_alias):
if channel_name not in channels:
channels[channel_name] = {
'values': channel['ValueList'],
'times': channel['ScadaReadTimeUnixMsList']
}
else:
channels[channel_name]['values'].extend(channel['ValueList'])
channels[channel_name]['times'].extend(channel['ScadaReadTimeUnixMsList'])
# Sort values according to time and find min/max
min_time_ms, max_time_ms = 1e20, 0
keys_to_delete = []
for key in channels.keys():
# Check the length
if (len(channels[key]['times']) != len(channels[key]['values'])
or not channels[key]['times']):
print(f"Warning: channel data is empty or has length mismatch: {key}")
keys_to_delete.append(key)
continue
sorted_times_values = sorted(zip(channels[key]['times'], channels[key]['values']))
sorted_times, sorted_values = zip(*sorted_times_values)
if list(sorted_times)[0] < min_time_ms:
min_time_ms = list(sorted_times)[0]
if list(sorted_times)[-1] > max_time_ms:
max_time_ms = list(sorted_times)[-1]
channels[key]['values'] = list(sorted_values)
channels[key]['times'] = list(sorted_times)
# channels[key]['times'] = pd.to_datetime(list(sorted_times), unit='ms', utc=True)
# channels[key]['times'] = channels[key]['times'].tz_convert('America/New_York')
# channels[key]['times'] = [x.replace(tzinfo=None) for x in channels[key]['times']]
for key in keys_to_delete:
del channels[key]
# Add snapshots
snapshots = session.query(MessageSql).filter(
MessageSql.from_alias.like(f'%{request.house_alias}%'),
MessageSql.message_type_name == "snapshot.spaceheat",
MessageSql.message_persisted_ms >= max_time_ms,
MessageSql.message_persisted_ms <= request.end_ms,
).order_by(asc(MessageSql.message_persisted_ms)).all()
for snapshot in snapshots:
for snap in snapshot.payload['LatestReadingList']:
if snap['ChannelName'] in channels:
channels[snap['ChannelName']]['times'].append(snap['ScadaReadTimeUnixMs'])
channels[snap['ChannelName']]['values'].append(snap['Value'])
# Sort values according to time and find new max
max_time_ms = 0
for key in channels:
sorted_times_values = sorted(zip(channels[key]['times'], channels[key]['values']))
sorted_times, sorted_values = zip(*sorted_times_values)
if list(sorted_times)[-1] > max_time_ms:
max_time_ms = list(sorted_times)[-1]
channels[key]['values'] = list(sorted_values)
channels[key]['times'] = pd.to_datetime(list(sorted_times), unit='ms', utc=True)
channels[key]['times'] = channels[key]['times'].tz_convert('America/New_York')
channels[key]['times'] = [x.replace(tzinfo=None) for x in channels[key]['times']]
# Find all zone channels
zones = {}
for channel_name in channels.keys():
if 'zone' in channel_name and 'gw-temp' not in channel_name:
if 'state' not in channel_name:
channels[channel_name]['values'] = [x/1000 for x in channels[channel_name]['values']]
zone_name = channel_name.split('-')[0]
if zone_name not in zones:
zones[zone_name] = [channel_name]
else:
zones[zone_name].append(channel_name)
# HomeAlone state
relays = {}
for message in messages:
if 'StateList' in message.payload:
for state in message.payload['StateList']:
if state['MachineHandle'] not in relays:
relays[state['MachineHandle']] = {}
relays[state['MachineHandle']]['times'] = []
relays[state['MachineHandle']]['values'] = []
relays[state['MachineHandle']]['times'].extend(state['UnixMsList'])
relays[state['MachineHandle']]['values'].extend(state['StateList'])
modes = {}
if 'auto.h.n' in relays:
modes['all'] = {}
modes['all']['times'] = []
modes['all']['values'] = []
formatted_times = [pendulum.from_timestamp(x/1000, tz='America/New_York') for x in relays['auto.h.n']['times']]
# print(set(relays['auto.h.n']['values']))
for state in [x for x in modes_order if x in list(set(relays['auto.h.n']['values']))]:
modes[state] = {}
modes[state]['times'] = []
modes[state]['values'] = []
final_states = []
for time, state in zip(formatted_times, relays['auto.h.n']['values']):
if state not in modes_order:
final_states.append(state)
else:
modes['all']['times'].append(time)
modes['all']['values'].append(4 if 'Waiting' in state else modes_order.index(state))
modes[state]['times'].append(time)
modes[state]['values'].append(4 if 'Waiting' in state else modes_order.index(state))
idx = len(modes_order)+1
final_states = list(set(final_states))
for time, state in zip(formatted_times, relays['auto.h.n']['values']):
if state in final_states:
modes['all']['times'].append(time)
modes['all']['values'].append(idx)
modes[state]['times'].append(time)
modes[state]['values'].append(idx)
if not modes:
modes = {}
if 'auto.h' in relays:
modes['all'] = {}
modes['all']['times'] = []
modes['all']['values'] = []
formatted_times = [pendulum.from_timestamp(x/1000, tz='America/New_York') for x in relays['auto.h']['times']]
# print(set(relays['auto.h']['values']))
for state in list(set(relays['auto.h']['values'])):
modes[state] = {}
modes[state]['times'] = []
modes[state]['values'] = []
for time, state in zip(formatted_times, relays['auto.h']['values']):
position = len(modes_order) if state not in modes_order else modes_order.index(state)
modes['all']['times'].append(time)
modes['all']['values'].append(position)
modes[state]['times'].append(time)
modes[state]['values'].append(position)
idx = len(modes_order)+1
top_modes = {}
if 'auto' in relays:
top_modes['all'] = {}
top_modes['all']['times'] = []
top_modes['all']['values'] = []
formatted_times = [pendulum.from_timestamp(x/1000, tz='America/New_York') for x in relays['auto']['times']]
# print(set(relays['auto']['values']))
for state in list(set(relays['auto']['values'])):
top_modes[state] = {}
top_modes[state]['times'] = []
top_modes[state]['values'] = []
for time, state in zip(formatted_times, relays['auto']['values']):
if state in top_modes_order:
top_modes['all']['times'].append(time)
top_modes['all']['values'].append(top_modes_order.index(state))
top_modes[state]['times'].append(time)
top_modes[state]['values'].append(top_modes_order.index(state))
aa_modes = {}
if 'a.aa' in relays:
aa_modes['all'] = {}
aa_modes['all']['times'] = []
aa_modes['all']['values'] = []
formatted_times = [pendulum.from_timestamp(x/1000, tz='America/New_York') for x in relays['a.aa']['times']]
for state in [x for x in aa_modes_order if x in list(set(relays['a.aa']['values']))]:
aa_modes[state] = {}
aa_modes[state]['times'] = []
aa_modes[state]['values'] = []
for time, state in zip(formatted_times, relays['a.aa']['values']):
if state in aa_modes_order:
aa_modes['all']['times'].append(time)
aa_modes['all']['values'].append(aa_modes_order.index(state))
aa_modes[state]['times'].append(time)
aa_modes[state]['values'].append(aa_modes_order.index(state))
if "Dormant" in top_modes:
top_modes['Admin'] = top_modes['Dormant']
del top_modes['Dormant']
# Start and end times on plots
min_time_ms += -(max_time_ms-min_time_ms)*0.05
max_time_ms += (max_time_ms-min_time_ms)*0.05
min_time_ms_dt = pd.to_datetime(min_time_ms, unit='ms', utc=True)
max_time_ms_dt = pd.to_datetime(max_time_ms, unit='ms', utc=True)
min_time_ms_dt = min_time_ms_dt.tz_convert('America/New_York').replace(tzinfo=None)
max_time_ms_dt = max_time_ms_dt.tz_convert('America/New_York').replace(tzinfo=None)
return "", channels, zones, modes, top_modes, aa_modes, min_time_ms_dt, max_time_ms_dt
# ------------------------------
# Get messages for message tracker
# ------------------------------
def get_requested_messages(request: MessagesRequest, running_locally:bool=False):
total_errors, total_warnings = 0, 0
if not running_locally and (request.end_ms - request.start_ms)/1000/60/60/24 > 5:
return {
"success": False,
"message": "That's too many days of messages to load.",
"reload": False,
}
session = Session()
messages: List[MessageSql] = session.query(MessageSql).filter(
MessageSql.from_alias.like(f'%{request.house_alias}%'),
MessageSql.message_type_name.in_(request.selected_message_types),
MessageSql.message_persisted_ms >= request.start_ms,
MessageSql.message_persisted_ms <=request.end_ms,
).order_by(asc(MessageSql.message_persisted_ms)).all()
if not messages:
return {
"success": False,
"message": f"No data found.",
"reload":False
}
levels = {
'critical': 1,
'error': 2,
'warning': 3,
'info': 4,
'debug': 5,
'trace': 6
}
sources = []
pb_types = []
summaries = []
details = []
times_created = []
sorted_problem_types = sorted(
[m for m in messages if m.message_type_name == 'gridworks.event.problem'],
key=lambda x: (levels[x.payload['ProblemType']], x.payload['TimeCreatedMs'])
)
for message in sorted_problem_types:
source = message.payload['Src']
if ".scada" in source:
source = source.split('.scada')[0].split('.')[-1]
sources.append(source)
pb_types.append(message.payload['ProblemType'])
summaries.append(message.payload['Summary'])
details.append(message.payload['Details'].replace('<','').replace('>','').replace('\n','<br>'))
times_created.append(str(pendulum.from_timestamp(message.payload['TimeCreatedMs']/1000, tz='America/New_York').replace(microsecond=0)))
summary_table = {
'critical': str(len([x for x in pb_types if x=='critical'])),
'error': str(len([x for x in pb_types if x=='error'])),
'warning': str(len([x for x in pb_types if x=='warning'])),
'info': str(len([x for x in pb_types if x=='info'])),
'debug': str(len([x for x in pb_types if x=='debug'])),
'trace': str(len([x for x in pb_types if x=='trace'])),
}
for key in summary_table.keys():
if summary_table[key]=='0':
summary_table[key]=''
table_data_columns = {
"Log level": pb_types,
"From node": sources,
"Summary": summaries,
"Details": details,
"Time created": times_created,
"SummaryTable": summary_table
}
return table_data_columns
@app.post('/messages')
async def get_messages(request: MessagesRequest):
if request.password != valid_password:
return {
"success": False,
"message": "Wrong password.",
"reload":True
}
try:
async with async_timeout.timeout(TIMEOUT_SECONDS):
response = await asyncio.to_thread(get_requested_messages, request, RUNNING_LOCALLY)
return response
except asyncio.TimeoutError:
print("Request timed out.")
return {
"success": False,
"message": "The data request timed out. Please try loading a smaller amount of data at a time.",
"reload": False
}
except asyncio.CancelledError:
print("Request cancelled or client disconnected.")
return {
"success": False,
"message": "The request was cancelled because the client disconnected.",
"reload": False
}
except Exception as e:
return {
"success": False,
"message": f"An error occurred: {str(e)}",
"reload": False
}
# ------------------------------
# Export as CSV
# ------------------------------
@app.post('/csv')
async def get_csv(request: CsvRequest, apirequest: Request):
request_start = time.time()
try:
async with async_timeout.timeout(TIMEOUT_SECONDS):
error_msg, channels, _, __, ___, ____, _____, ______ = await asyncio.to_thread(get_data, request)
print(f"Time to fetch data: {round(time.time() - request_start,2)} sec")
if time.time() - request_start > TIMEOUT_SECONDS:
raise asyncio.TimeoutError('Timed out')
if await apirequest.is_disconnected():
raise asyncio.CancelledError("Client disconnected.")
if error_msg != '':
return error_msg
if 'all-data' in request.selected_channels:
channels_to_export = channels.keys()
else:
channels_to_export = []
for channel in request.selected_channels:
if channel in channels:
channels_to_export.append(channel)
elif channel == 'zone-heat-calls':
for c in channels.keys():
if 'zone' in c:
channels_to_export.append(c)
elif channel == 'buffer-depths':
for c in channels.keys():
if 'depth' in c and 'buffer' in c and 'micro' not in c:
channels_to_export.append(c)
elif channel == 'storage-depths':
for c in channels.keys():
if 'depth' in c and 'tank' in c and 'micro' not in c:
channels_to_export.append(c)
elif channel == 'relays':
for c in channels.keys():
if 'relay' in c:
channels_to_export.append(c)
elif channel == 'zone-heat-calls':
for c in channels.keys():
if 'zone' in c:
channels_to_export.append(c)
elif channel == 'store-energy':
for c in channels.keys():
if 'required-energy' in c or 'available-energy':
channels_to_export.append(c)
num_points = int((request.end_ms - request.start_ms) / (request.timestep * 1000) + 1)
if num_points * len(channels_to_export) > 3600 * 24 * 10 * len(channels):
error_message = f"This request would generate {num_points} data points, which is too much data in one go."
error_message += "\n\nSuggestions:\n- Increase the time step\n- Reduce the number of channels"
error_message += "\n- Change the start and end times"
return {"success": False, "message": error_message, "reload": False}
csv_times = np.linspace(request.start_ms, request.end_ms, num_points)
csv_times_dt = pd.to_datetime(csv_times, unit='ms', utc=True)
csv_times_dt = [x.tz_convert('America/New_York').replace(tzinfo=None) for x in csv_times_dt]
csv_values = {}
for channel in channels_to_export:
if time.time() - request_start > TIMEOUT_SECONDS:
raise asyncio.TimeoutError('Timed out')
if await apirequest.is_disconnected():
raise asyncio.CancelledError("Client disconnected.")
merged = await asyncio.to_thread(pd.merge_asof,
pd.DataFrame({'times': csv_times_dt}),
pd.DataFrame(channels[channel]),
on='times',
direction='backward')
csv_values[channel] = list(merged['values'])
df = pd.DataFrame(csv_values)
df['timestamps'] = csv_times_dt
df = df[['timestamps'] + [col for col in df.columns if col != 'timestamps']]
csv_buffer = io.StringIO()
start_date = pendulum.from_timestamp(request.start_ms / 1000)
end_date = pendulum.from_timestamp(request.end_ms / 1000)
formatted_start_date = start_date.to_iso8601_string()[:16].replace('T', '-')
formatted_end_date = end_date.to_iso8601_string()[:16].replace('T', '-')
filename = f'{request.house_alias}_{request.timestep}s_{formatted_start_date}-{formatted_end_date}.csv'.replace(':','_')
csv_buffer.write(filename+'\n')
df.to_csv(csv_buffer, index=False)
csv_buffer.seek(0)
response = StreamingResponse(
iter([csv_buffer.getvalue()]),
media_type="text/csv",
headers={"Content-Disposition": f"attachment; filename={filename}"}
)
return response
except asyncio.TimeoutError:
print("Request timed out.")
return {
"success": False,
"message": "The data request timed out. Please try loading a smaller amount of data at a time.",
"reload": False
}
except asyncio.CancelledError:
print("Request cancelled or client disconnected.")
return {
"success": False,
"message": "The request was cancelled because the client disconnected.",
"reload": False
}
except Exception as e:
return {
"success": False,
"message": f"An error occurred: {str(e)}",
"reload": False
}
# ------------------------------
# Download Dijkstra Excel
# ------------------------------
@app.post('/download_excel')
async def get_excel(request: DijkstraRequest):
print("made it here")
download_excel(request.house_alias, request.time_ms)
if os.path.exists('result.xlsx'):
return FileResponse(
'result.xlsx',
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers={"Content-Disposition": "attachment; filename=file.xlsx"}
)
else:
return {"error": "File not found"}
# ------------------------------
# Generate interactive plots
# ------------------------------
from typing import Union
@app.post('/plots')
async def get_plots(request: Union[DataRequest, DijkstraRequest], apirequest: Request):
if isinstance(request, DijkstraRequest):
download_excel(request.house_alias, request.time_ms)
if os.path.exists('result.xlsx'):
print("PATH EXISTS")
return FileResponse(
'result.xlsx',
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers={"Content-Disposition": "attachment; filename=file.xlsx"}
)
else:
return {"error": "File not found"}
request_start = time.time()
try:
async with async_timeout.timeout(TIMEOUT_SECONDS):
error_msg, channels, zones, modes, top_modes, aa_modes, min_time_ms_dt, max_time_ms_dt = await asyncio.to_thread(get_data, request)
print(f"Time to fetch data: {round(time.time() - request_start,2)} sec")
if error_msg != '':
return error_msg
zone_colors_hex = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']*200
if request.darkmode:
plot_background_hex = '#222222'
gridcolor_hex = '#424242'
fontcolor_hex = '#b5b5b5'
home_alone_line = '#f0f0f0'
oat_color = 'gray'
else:
plot_background_hex = 'white'
gridcolor_hex = 'LightGray'
fontcolor_hex = 'rgb(42,63,96)'
home_alone_line = '#5e5e5e'
oat_color = '#d6d6d6'
if PYPLOT_PLOT:
line_style = 'lines+markers' if 'show-points'in request.selected_channels else 'lines'
# --------------------------------------
# PLOT 1: Heat pump
# --------------------------------------
if time.time() - request_start > TIMEOUT_SECONDS:
raise asyncio.TimeoutError('Timed out')
if await apirequest.is_disconnected():
raise asyncio.CancelledError("Client disconnected.")
fig = go.Figure()
# Temperature
temp_plot = False
if 'hp-lwt' in request.selected_channels and 'hp-lwt' in channels:
temp_plot = True
fig.add_trace(
go.Scatter(
x=channels['hp-lwt']['times'],
y=[to_fahrenheit(x/1000) for x in channels['hp-lwt']['values']],
mode=line_style,
opacity=0.7,
line=dict(color='#d62728', dash='solid'),
name='HP LWT'
)
)
if 'hp-ewt' in request.selected_channels and 'hp-ewt' in channels:
temp_plot = True
fig.add_trace(
go.Scatter(
x=channels['hp-ewt']['times'],
y=[to_fahrenheit(x/1000) for x in channels['hp-ewt']['values']],
mode=line_style,
opacity=0.7,
line=dict(color='#1f77b4', dash='solid'),
name='HP EWT'
)
)
if time.time() - request_start > TIMEOUT_SECONDS:
raise asyncio.TimeoutError('Timed out')
if await apirequest.is_disconnected():
raise asyncio.CancelledError("Client disconnected.")
# Secondary yaxis
y_axis_power = 'y2' if temp_plot else 'y'
# Power and flow
power_plot = False
if 'hp-odu-pwr' in request.selected_channels and 'hp-odu-pwr' in channels:
power_plot = True
fig.add_trace(
go.Scatter(
x=channels['hp-odu-pwr']['times'],
y=[x/1000 for x in channels['hp-odu-pwr']['values']],
mode=line_style,
opacity=0.7,
line=dict(color='#2ca02c', dash='solid'),
name='HP outdoor power',
yaxis=y_axis_power
)
)
if 'hp-idu-pwr' in request.selected_channels and 'hp-idu-pwr' in channels:
power_plot = True
fig.add_trace(
go.Scatter(
x=channels['hp-idu-pwr']['times'],
y=[x/1000 for x in channels['hp-idu-pwr']['values']],
mode=line_style,
opacity=0.7,
line=dict(color='#ff7f0e', dash='solid'),
name='HP indoor power',
yaxis=y_axis_power
)
)
if 'oil-boiler-pwr' in request.selected_channels and 'oil-boiler-pwr' in channels:
power_plot = True
fig.add_trace(
go.Scatter(
x=channels['oil-boiler-pwr']['times'],
y=[x/100 for x in channels['oil-boiler-pwr']['values']],
mode=line_style,
opacity=0.7,
line=dict(color=home_alone_line, dash='solid'),
name='Oil boiler power x10',
yaxis=y_axis_power
)
)
if time.time() - request_start > TIMEOUT_SECONDS:
raise asyncio.TimeoutError('Timed out')
if await apirequest.is_disconnected():
raise asyncio.CancelledError("Client disconnected.")
if 'primary-flow' in request.selected_channels and 'primary-flow' in channels:
power_plot = True
fig.add_trace(
go.Scatter(
x=channels['primary-flow']['times'],
y=[x/100 for x in channels['primary-flow']['values']],
mode=line_style,
opacity=0.4,
line=dict(color='purple', dash='solid'),
name='Primary pump flow',
yaxis=y_axis_power
)
)
if 'primary-pump-pwr' in request.selected_channels and 'primary-pump-pwr' in channels:
power_plot = True
fig.add_trace(
go.Scatter(
x=channels['primary-pump-pwr']['times'],
y=[x/1000*100 for x in channels['primary-pump-pwr']['values']],
mode=line_style,
opacity=0.7,
line=dict(color='pink', dash='solid'),
name='Primary pump power x100',
yaxis=y_axis_power,
visible='legendonly',
)
)
if power_plot and temp_plot:
fig.update_layout(yaxis=dict(title='Temperature [F]', range=[0,260]))
fig.update_layout(yaxis2=dict(title='Power [kW] or Flow [GPM]', range=[0,35]))
elif temp_plot and not power_plot:
fig.update_layout(yaxis=dict(title='Temperature [F]'))
elif power_plot and not temp_plot:
fig.update_layout(yaxis=dict(title='Power [kW] or Flow [GPM]', range=[0,10]))
fig.update_layout(
title=dict(text='Heat pump', x=0.5, xanchor='center'),
margin=dict(t=30, b=30),
plot_bgcolor=plot_background_hex,
paper_bgcolor=plot_background_hex,
font_color=fontcolor_hex,
title_font_color=fontcolor_hex,
xaxis=dict(
range=[min_time_ms_dt, max_time_ms_dt],
mirror=True,
ticks='outside',
showline=True,
linecolor=fontcolor_hex,
showgrid=False
),
yaxis=dict(
mirror=True,
ticks='outside',
showline=True,
linecolor=fontcolor_hex,
zeroline=False,
showgrid=True,
gridwidth=1,
gridcolor=gridcolor_hex
),
yaxis2=dict(
mirror=True,
ticks='outside',
zeroline=False,
showline=True,
linecolor=fontcolor_hex,
showgrid=False,
overlaying='y',
side='right'
),
legend=dict(
x=0,
y=1,
xanchor='left',
yanchor='top',
bgcolor='rgba(0, 0, 0, 0)'
)
)
html_buffer1 = io.StringIO()
fig.write_html(html_buffer1)
html_buffer1.seek(0)
# --------------------------------------
# PLOT 2: Distribution
# --------------------------------------
if time.time() - request_start > TIMEOUT_SECONDS:
raise asyncio.TimeoutError('Timed out')
if await apirequest.is_disconnected():
raise asyncio.CancelledError("Client disconnected.")
fig = go.Figure()
# Temperature
temp_plot = False
if 'dist-swt' in request.selected_channels and 'dist-swt' in channels:
temp_plot = True
fig.add_trace(
go.Scatter(
x=channels['dist-swt']['times'],
y=[to_fahrenheit(x/1000) for x in channels['dist-swt']['values']],
mode=line_style,
opacity=0.7,
line=dict(color='#d62728', dash='solid'),
name='Distribution SWT'
)
)
if 'dist-rwt' in request.selected_channels and 'dist-rwt' in channels:
temp_plot = True
fig.add_trace(
go.Scatter(
x=channels['dist-rwt']['times'],
y=[to_fahrenheit(x/1000) for x in channels['dist-rwt']['values']],
mode=line_style,
opacity=0.7,
line=dict(color='#1f77b4', dash='solid'),
name='Distribution RWT'
)
)
# Secondary yaxis
y_axis_power = 'y2' if temp_plot else 'y'
# Power and flow
power_plot = False
if 'dist-flow' in request.selected_channels and 'dist-flow' in channels:
power_plot = True
fig.add_trace(
go.Scatter(
x=channels['dist-flow']['times'],
y=[x/100 for x in channels['dist-flow']['values']],
mode=line_style,
opacity=0.4,
line=dict(color='purple', dash='solid'),
name='Distribution flow',
yaxis = y_axis_power
)
)
if 'dist-pump-pwr' in request.selected_channels and 'dist-pump-pwr' in channels:
power_plot = True
fig.add_trace(
go.Scatter(
x=channels['dist-pump-pwr']['times'],
y=[x/10 for x in channels['dist-pump-pwr']['values']],
mode=line_style,
opacity=0.7,
line=dict(color='pink', dash='solid'),
name='Distribution pump power /10',
yaxis = y_axis_power,
visible='legendonly',
)
)