-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpowerguru.py
executable file
·1639 lines (1250 loc) · 63.1 KB
/
powerguru.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
#!/usr/bin/env /usr/bin/python3.9
# coding: utf-8
from multiprocessing.dummy.connection import families
from pickle import NONE
import traceback #error reporting
import sys
import json
import os
import signal
#from threading import Thread
from enum import Enum
import settings as s
import subprocess
import time
import pytz #time zone
import random
import re #regular expression
from glob import glob #Unix style pathname pattern expansion
from datetime import datetime, timezone,date, timedelta
#aiohttp
import asyncio
from aiohttp import web
from aiohttp.web import Response
from aiohttp_sse import sse_response
from aiohttp_session import get_session, SimpleCookieStorage, session_middleware #pip3 install aiohttp_session[secure]
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from aiohttp_basicauth_middleware import basic_auth_middleware
import hashlib
from datetime import datetime
import socket
from threading import Thread, current_thread
from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS
#
import importlib.util
GPIOInstalled = True
try:
spec = importlib.util.find_spec('RPi.GPIO')
except:
spec = None
if spec is None:
print("GPIO is not installed")
GPIOInstalled = False
else:
import RPi.GPIO as GPIO # handle Rpi GPIOs for connected to relays
GPIO.setwarnings(False)
#use GPIO-numbers to refer GPIO pins
GPIO.setmode(GPIO.BCM)
import pprint
pp = pprint.PrettyPrinter(indent=4)
data_updates = {}
gridenergy_data = None
temperature_data = None
dayahead_list = None
forecastpv_list = None
current_states = None
netPreviousTotalEnergyPeriod = -999
netPreviousTotalEnergy = -1
netEnergyInPeriod = 0
netPeriodMeasurementCount = 0
sensor_settings = None
states = None
channels_list = None
# global variables
channels = []
sensorData = None
#init config class
powerGuru = None
def aggregate_dayahead_prices():
global dayahead_list, powerGuru
# Aggregate day-ahead prices
energyPriceSpot = None
if dayahead_list is not None:
for price_entry in dayahead_list:
if price_entry["timestamp"] < time.time() and price_entry["timestamp"] > time.time()-3600:
energyPriceSpot = price_entry["fields"]["energyPriceSpot"]
powerGuru.set_variable("energyPriceSpot" , round(energyPriceSpot,2))
# now calculate spot price rank of current hour in different window sizes
for bCode in powerGuru.dayaheadWindowBlocks:
rank = get_current_period_rank(bCode)
if rank is not None:
variable_code = s.spot_price_variable_code.format(bCode)
powerGuru.set_variable(variable_code , rank)
def aggregate_dayahead_prices_timeser(start,end):
#VAATII TESTAUSTA
global dayahead_list, powerGuru
for time in range(start, end+1, powerGuru.nettingPeriodMinutes*60):
# Aggregate day-ahead prices
energyPriceSpot = None
if dayahead_list is not None:
for price_entry in dayahead_list:
if price_entry["timestamp"] <= time and time< price_entry["timestamp"]+3600: # 60 minutesperiod
energyPriceSpot = price_entry["fields"]["energyPriceSpot"]
powerGuru.set_variable_timeser("energyPriceSpot",time,round(energyPriceSpot,2))
# now calculate spot price rank of current hour in different window sizes
for bCode in powerGuru.dayaheadWindowBlocks:
rank = get_period_rank_timeser(time,bCode)
if rank is not None:
variable_code = s.spot_price_variable_code.format(bCode)
powerGuru.set_variable_timeser(variable_code,time,rank)
def aggregate_solar_forecast():
global forecastpv_list, powerGuru
blockSums = {}
for bCodei in powerGuru.solarForecastBlocks:
blockSums[str(bCodei)] = 0
if forecastpv_list is not None:
for fcst_entry in forecastpv_list:
if powerGuru.bcdcenergiaLocation ==fcst_entry["tags"]["location"]:
for bCodei in powerGuru.solarForecastBlocks:
futureHours = bCodei
if fcst_entry["timestamp"] < time.time()+(futureHours*3600):
blockSums[str(bCodei)] += fcst_entry["fields"]["pvrefvalue"]
for sfbCode,sfb in blockSums.items():
blockCode = s.solar_forecast_variable_code.format(sfbCode)
powerGuru.set_variable(blockCode , round(sfb,2))
def aggregate_solar_forecast_timeser(start,end,location):
#TESTATTAVA
global forecastpv_list, powerGuru
for time in range(start, end+1, powerGuru.nettingPeriodMinutes*60):
blockSums = {}
for bCodei in powerGuru.solarForecastBlocks:
blockSums[str(bCodei)] = 0
if forecastpv_list is not None:
for fcst_entry in forecastpv_list:
if location == fcst_entry["tags"]["location"]:
for bCodei in powerGuru.solarForecastBlocks:
futureHours = bCodei
if fcst_entry["timestamp"] < time+(futureHours*3600):
blockSums[str(bCodei)] += fcst_entry["fields"]["pvrefvalue"]
for sfbCode,sfb in blockSums.items():
blockCode = s.solar_forecast_variable_code.format(sfbCode)
# print(location, blockCode,time,round(sfb,2))
powerGuru.set_variable_timeser(blockCode,time,round(sfb,2))
#helper for setting gpio
def setOutGPIO(gpio,enable,init=False):
global channels_list
#enable: True ->GPIO.HIGH, False -> GPIO.LOW
if init:
GPIO.setup(gpio, GPIO.OUT)
GPIO.output(gpio,GPIO.HIGH if enable else GPIO.LOW)
"""
for channel_row in channels_list:
if channel_row["gpio"]==gpio:
channel_row["enabled"] = enable
break
"""
"""
for channel in channels:
if channel.gpio==gpio:
channel.up = enable
break
"""
# This class handles line resources (phases) e.g.
#TODO; disabling line capacity handling
class PowerGuru:
def __init__(self,init_file_name):
self.settings = s.read_settings(init_file_name)
#add most important settings to attributes
self.maxLoadPerPhaseA = self.get_setting("maxLoadPerPhaseA")
self.nettingPeriodMinutes = self.get_setting("nettingPeriodMinutes")
self.dayaheadWindowBlocks = self.get_setting("dayaheadWindowBlocks")
self.solarForecastBlocks = self.get_setting("solarForecastBlocks")
self.groupServer = self.get_setting("groupServer",True)
self.bcdcenergiaLocation = self.get_setting("bcdcenergiaLocation")
self.bcdcLocationsHandled = self.get_setting("bcdcLocationsHandled")
if not GPIOInstalled or self.groupServer:
self.localChannelsEnabled =False #no RPI package or other system
else:
self.localChannelsEnabled = self.get_setting("localChannelsEnabled")
self.lines = [ (1, 0),(2, 0),(3, 0)]
self.lines_sorted = self.lines
self.status_propagated = True
self.variables = {}
self.variables_timeser = {}
def get_current_period_id(self):
return int(time.time()/(self.nettingPeriodMinutes*60))
def get_current_period_start(self):
return int(time.time()/(self.nettingPeriodMinutes*60))*(self.nettingPeriodMinutes*60)
# time series
# { "type" : "num", "values": {"time": value }}
def set_variable_timeser(self,field_code,time,value,type = "num"):
#print("set_variable_timeser:", field_code, time,value)
if field_code not in self.variables_timeser: # time series exists, use it
self.variables_timeser[field_code] = {"values": {}, "type" : type}
self.variables_timeser[field_code]["values"][str(time)] = value
def get_values_timeser(self,field_code,time_first=None, time_last=None,states_requested=None):
if time_first is None:
time_first = self.get_current_period_start()
if time_last is None:
time_last = time_first+24*3600-1
if field_code not in self.variables_timeser:
return {}
return_values = {}
#print("states_requested", " ", states_requested)
for vkey,variable in self.variables_timeser[field_code]["values"].items():
if str(time_first) <= vkey and vkey <= str(time_last):
if states_requested is None:
return_values[vkey] = variable
else: #state filter
var_out = []
for var in variable:
if var in states_requested:
var_out.append(var)
return_values[vkey] = var_out
#print(vkey, " ", var_out)
return return_values
def get_value_timeser(self,field_code,time,default_value = None):
if field_code == 'mmdd' or field_code == 'hhmm':
tz_local = pytz.timezone(powerGuru.get_setting("timeZoneLocal"))
dt = datetime.fromtimestamp(time, tz_local)
if field_code == 'mmdd':
return dt.strftime("'%m%d'")
elif field_code == 'hhmm':
return dt.strftime("'%H%M'")
else:
if field_code in self.variables_timeser:
if str(time) in self.variables_timeser[field_code]["values"]:
if self.variables_timeser[field_code]["type"] == "str":
return "'{}'".format(self.variables[field_code]["values"][str(time)])
else:
return self.variables_timeser[field_code]["values"][str(time)]
else:
return default_value
else:
return default_value
def set_variable(self,field_code,value):
self.variables[field_code] = {"value": value, "ts" : time.time(), "type" : "num"}
def get_value(self,field_code,default_value = None):
#TODO: check if value is expired, expiration in variables settings file .. coming later
if field_code in self.variables:
if self.variables[field_code]["type"] == "str":
return "'{}'".format(self.variables[field_code]["value"])
else:
return self.variables[field_code]["value"]
else:
return default_value
def get_setting(self,field_code,default_value = None):
if field_code in self.settings:
return self.settings[field_code]
else:
return default_value
# adds pseudo variables like time
def get_variables(self):
return_object = self.variables
# pseudo variables date, time etc
return_object["hhmm"] = {"value": datetime.now().strftime("%H%M"), "ts" : time.time(), "type" : "str"}
return_object["mmdd"] = {"value": datetime.now().strftime("%m%d"), "ts" : time.time(), "type" : "str"}
return return_object.items()
def set_status_unpropagated(self):
self.status_propagated = False
# check if there is enough line capacity in off lines used by the channel
#TODO: powerW...
def requestCapacity(self,requested_lines):
for line in self.lines:
requested_phase_current = 0
for rline in requested_lines:
if rline["l"] == line[0]:
requested_phase_current = rline["A"]
projectedOverload = line[1]-self.maxLoadPerPhaseA+requested_phase_current
if projectedOverload>0:
print("Line ", line[0], " could cause overload: ", projectedOverload)
return False
return True
def setLoad(self,importL1A,importL2A,importL3A): # tällä voisi asettaa mittausten luvun jälkeen nykyisen kuorman
# jos joku ylittää sallitun kuorman voisi käydä katkomassa
self.lines = [ (1, importL1A),(2, importL2A),(3, importL3A)]
# overload control
# check each line, if overload -> decrease load (if possible) until no overload exists
for line in self.lines:
overLoad = line[1]-self.maxLoadPerPhaseA
if overLoad<0:
#print("No overload in line ", line,", overload:" ,overLoad)
continue
for channel in channels:
channel_lines = []
for act_line in channel.lines:
if act_line.get("l",-1)==line[0] and channel.up:
channel.loadDown()
print("OVERLOAD, channel {}, line {:d} lowering down, releasing {:f} A".format(channel.code, line[0],act_line["A"] ))
self.lines_sorted = sorted(self.lines, key=lambda line: line[1])
print("setLoad")
pp.pprint(self.lines_sorted)
return self.lines_sorted
def getLineCapacity(self,reverse=False): # antaa vähiten kuormitetuimmat linjat ekaksi tai jos revrse niin toisin päin
available_lines = []
for line in sorted(self.lines, key=lambda line: line[1],reverse=reverse):
available_lines.append({"l" : line[0],"availableA":self.maxLoadPerPhaseA-line[1]})
return available_lines #näitä voisi kuormittaa jos ei ole jo kuormitettu
#for the dashboard
def get_status(self,set_status_propagated):
if set_status_propagated:
self.status_propagated = True
tz_utc = pytz.timezone("UTC")
status = {"channels": [], "updates":[], "sensors":[], "variables":[], "current_states":None}
for idx,channel in enumerate(channels):
status["channels"].append({ "idx" : idx, "code" : channel.code, "name" : channel.name, "up": channel.up, "target" : channel.target })
for variable_code,variable in powerGuru.get_variables():
status["variables"].append({ "code" : variable_code, "value" : variable["value"], "ts": variable["ts"], "type" : variable["type"] })
for update_key, update_values in data_updates.items():
updated_dt = (tz_utc.localize(datetime.utcnow())-update_values["updated"])
updated_dt = updated_dt - timedelta(microseconds=updated_dt.microseconds) #round
latest_ts_str = datetime.fromtimestamp(update_values["latest_ts"]).strftime("%Y-%m-%dT%H:%M:%S%z")
status["updates"].append({ "code" : update_key, "updated" : update_values["updated"].strftime("%Y-%m-%dT%H:%M:%S%z") , "latest_ts": latest_ts_str })
for sensor in sensorData.sensors:
status["sensors"].append({ "code" : sensor["code"], "id" : sensor["id"], "name" : sensor["name"], "value": sensor["value"] })
if current_states:
status["current_states"] = current_states
if gridenergy_data:
status["Wsys"] = gridenergy_data["fields"]["Wsys"]
else:
status["Wsys"] = None
return status
# this is the main calculation function
def recalculate(self):
print ('#recalculate')
#global self
global netEnergyInPeriod, netPreviousTotalEnergy, netPreviousTotalEnergyPeriod,netPeriodMeasurementCount
global current_states
global gridenergy_data, temperature_data, dayahead_list, forecastpv_list
#todo: check data age
if not powerGuru.groupServer and (gridenergy_data is None or "fields" not in gridenergy_data):
print("No gridenergy_data")
return False
#TODO: read from cache , check validity (in init) , handle cases if not used
#if dayahead_list is None or forecastpv_list is None:
# return False
importTot = 0
price_fields = {}
loadsA = [0,0,0]
# Go through all connected thermometers
dtnow = datetime.now()
tz_local = pytz.timezone(powerGuru.get_setting("timeZoneLocal"))
now_local = dtnow.astimezone(tz_local).isoformat()
#TODO: check how often to run
#get current prices and expected future solar, e.g. solar6h is solar within next 6 hours
# block updates?, should we get it once a hour
aggregate_solar_forecast()
if powerGuru.groupServer:
loadsA[0]=0
loadsA[1]=0
loadsA[2]=0
importTot = 0
cumulativeEnergy = 0
else:
loadsA[0] = gridenergy_data["fields"]["AL1"]
loadsA[1] = gridenergy_data["fields"]["AL2"]
loadsA[2] = gridenergy_data["fields"]["AL3"]
importTot = gridenergy_data["fields"]["Wsys"]
cumulativeEnergy = gridenergy_data["fields"]["kWhTOT"]
price_fields[ "sale"]= (-importTot if importTot<0 else 0.0)
price_fields[ "purchase"]= (importTot if importTot>0 else 0.0)
# sales only for negative import
price_fields[ "sale"]= (-importTot if importTot<0 else 0.0)
price_fields[ "purchase"]= (importTot if importTot>0 else 0.0)
#TODO: tarvitaanko, yösähkö erikseen, tää olisi hyvä parametroida
local_time = now_local[11:19]
#TODO nämä parametreistä
if "07:00:00" < local_time < "22:00:00":# and dtnow.isoweekday()!=7:
price_fields[ "purchaseDay"]= (importTot if importTot>0 else 0.0)
price_fields[ "purchaseNight"]= 0.0
else:
price_fields[ "purchaseNight"]= (importTot if importTot>0 else 0.0)
price_fields[ "purchaseDay"]= 0.0
# new, todo: tähän tallennukset influxiin
if netPreviousTotalEnergy == -1:
netPreviousTotalEnergy = cumulativeEnergy
#currentNettingPeriod = int(time.time()/(self.nettingPeriodMinutes*60))
currentNettingPeriod = self.get_current_period_id()
if netPreviousTotalEnergyPeriod != currentNettingPeriod:
# this should probably be run when a new hour (period) starts, not always
aggregate_dayahead_prices()
netPreviousTotalEnergyPeriod = currentNettingPeriod
netPeriodMeasurementCount = 0
#TODO: tsekkaa miksi netEnergyInPeriod nollaantuu viivellä periodin vaihtuessa
netEnergyInPeriod = cumulativeEnergy-netPreviousTotalEnergy
netPeriodMeasurementCount += 1
if netPeriodMeasurementCount == 1:
netPreviousTotalEnergy = cumulativeEnergy
self.set_variable("netEnergyInPeriod" , round(netEnergyInPeriod,2))
print(" {} cumulativeEnergy- {} netPreviousTotalEnergy = {} netEnergyInPeriod ".format(cumulativeEnergy,netPreviousTotalEnergy,netEnergyInPeriod))
self.setLoad(loadsA[0],loadsA[1],loadsA[2])
#main call
current_states = check_states()
# start channels
if powerGuru.localChannelsEnabled:
#TODO: OVERLOAD CONTROL!!!
#TODO:miksi eri loopit, randomin takia?, vai jäänne
for channel in channels:
target = channel.getTarget(current_states)
#print(channel.name, " got target: ",target)
random_channels = channels.copy()
random.seed()
random.shuffle(random_channels) # set up load in random order
for channel in random_channels:
target = channel.getTarget(current_states)
channels[channel.idx].target = target
if target["keep_up"]:
#channel.on = True
loadChange = channel.loadUp() #
if abs(loadChange) > 0: #only 1 v´chnage at one time, eli ei liikaa muutosta minuutissa
break
elif not target["keep_up"] and target["state"]:
loadChange = channel.loadDown()
#channel.on = False
if abs(loadChange) > 0:
# print ("loadDown loadChange:", loadChange)
break
self.set_status_unpropagated() # latest status not propagated to clients
# export to influxDB
if not powerGuru.groupServer:
reportState(price_fields)
# Stores sensor values (from thermometers)
class SensorData:
def __init__(self, sensors):
self.sensors = []
for sensor in sensors:
self.addSensor(sensor["code"],sensor["id"], sensor.get("name",""),False,sensor["type"])
#pp.pprint(self.sensors)
def addSensor(self,code,id,name,enabled,type = "1-wire"):
self.sensors.append({"code":code,"type": type,"id" : id,"name" :name,"value":None, "enabled" : enabled })
def setEnabledById(self,id,enabled):
for sensor in self.sensors:
if sensor["id"] == id:
sensor["enabled"]= enabled
return True
return False
def setValueById(self,id,value):
global powerGuru
for sensor in self.sensors:
if sensor["id"] == id:
sensor["value"]= value
# set sensor value to variables, so it can be used in states
powerGuru.set_variable(sensor["code"],round(value,1))
return
def getValueByCode(self,code):
for sensor in self.sensors:
if sensor["code"] == code:
# print ("getValueByCode ",sensor["code"], " ", sensor["value"] )
return sensor["value"]
return None
class channelType(Enum): #RFU
SWITCH = 0 #default
SWITCH_TO_TARGET = 1 # target
TESLA_VEHICLE = 101 # more an idea now, not implemented yet, could send start/stop charging commands via Tesla API
TESLA_POWERWALL = 102 # see previous
""" Tesla API interface would probably need:
- OAuth authentication
- minimum uptime for the channel (re)
- reading battery state (like temp sensor in boilers) /api/1/vehicles/:id/vehicle_data : response.charge_state.battery_level
"""
# Channel can be e.g. one boiler with 1 or 3 lines (phases)
class Channel:
def __init__(self, idx,code, data):
self.type = channelType.SWITCH #RFU, could be eg. battery system
self.idx = idx # 0-indexed
self.code = code #ch + 1-indexed nbr
self.name = data["name"]
self.gpio = data["gpio"]
self.sensor = data.get("sensor",None)
#self.defaultTarget = data.get("defaultTarget",None)
self.t = data.get("reachedWhen",None)
self.upIf = data.get("upIf",None)
self.loadW = data.get("loadW",0)
self.up = False
self.reverse_output = data.get("reverse_output",False) #esim. lattialämmityksen poissa-kytkin, todo gpio-handleen
self.target = None
lines = []
if not "lines" in data:
data["lines"] = [1,2,3]
if "lines" in data and len(data["lines"])>0:
current_per_phase = round((self.loadW /s.volts_per_phase)/len(data["lines"]),2)
else:
current_per_phase = 0
for line in data["lines"]:
lines.append({'l':line, 'A': current_per_phase} )
self.lines = lines
if self.gpio:
setOutGPIO(self.gpio,self.up,True) #init
"""
self.lines = [{"l" : 1, "gpio" : None, "A" : 0 ,"up": False},{"l" : 2, "gpio" : None, "A" : 0,"up": False },{"l" : 3, "gpio" : None, "A" : 0,"up": False }]
print("LINES A initiated")
pp.pprint(self.lines)
for line in data["lines"]:
ln = {"l" : line["l"], "gpio" : line["gpio"], "A" : line.get("A",0),"up": False }
lineInd = line["l"]-1 #HUOM INDEKSOINTI
print("debug:", ln, lineInd)
self.lines[lineInd] = ln
GPIO.setup(ln["gpio"], GPIO.OUT)
#TODO:: nyt olisi hyvä hetki ajaa GPIOT alas, jos jääneet ylös ennestään
GPIO.output(ln["gpio"],GPIO.HIGH if ln["up"] else GPIO.LOW)
print("LINES B")
pp.pprint(self.lines)
"""
self.targets = []
if "targets" in data:
for target in data["targets"]:
tn = {"targetStates" : target["targetStates"], "sensor" : target.get("sensor",None), "upIf": target.get("upIf",None),"valueabove": target.get("valueabove",None), "valuebelow": target.get("valuebelow",None), "forceOn" : target.get("forceOn",None)}
self.targets.append(tn)
"""
print()
print()
print("class Channel", self.code)
print("lines:",self.lines)
print("targets:",self.targets)
print()
print()
print()
"""
def getTarget(self,current_states):
# get first channel target where state is matching
for target in self.targets:
#targetStates
# if target["state"] in current_states:
matching_state = None
if "targetStates" in target:
for condi in target["targetStates"]:
if condi in current_states:
matching_state = condi
break
if matching_state:
if "upIf" in target and target["upIf"] is not None:
keep_up,error_in_test = test_formula( target["upIf"],self.name+ ":" +matching_state )
if error_in_test: #possibly error in target t, try next one (should we panic and break )
#TODO: error in formula (e.g. wrong variable) should be reported somehow to dashboard - error list...
continue # try next target
else: #found first matching target
return {"state" : matching_state,"keep_up":keep_up,"upIf": target["upIf"] }
return {"state" : None,"keep_up":False} # no matching target
def getLine(self,l):
for line in self.lines:
if line["l"] == l:
return line
return None
def loadUp(self):
global powerGuru
print("loadUp", self.name)
if powerGuru.requestCapacity(self.lines):
#print("requestCapacity ok")
setOutGPIO(self.gpio,True)
self.up = True
else:
print("requestCapacity failed")
"""
lineResources = powerGuru.getLineCapacity(reverse=False)
for lr in lineResources:
line = self.getLine(lr["l"])
#print("line",line)
if line is not None:
if not line["up"] and lineResources[ line["l"]-1]["availableA"]>10:
print("line {:d} raising up with {:d} A".format(line["l"],line["A"]))
line["up"] = True
setOutGPIO(line["gpio"],line["up"])
print("self.lines after loadUp", self.lines,"lineResources:",lineResources)
return line["A"]
"""
return 0
# check if available lines, if not return 0
# check which line to increase
#return increased power in A, 0 if nothing to descrease
def loadDown(self):
#TODO tsekkaa onko yli kapasiteettirajan tai yli tehorajan
setOutGPIO(self.gpio,False)
self.up = False
"""
lineResources = powerGuru.getLineCapacity(reverse=True) #katso saisiko ton amppeerimäärän laitteelta
for lr in lineResources:
line = self.getLine(lr["l"])
#print("line",line)
if line is not None:
if line["up"]:
print("line {:d} lowering down up with {:d} A".format(line["l"],line["A"]))
line["up"] = False
#lineResources[]
setOutGPIO(line["gpio"],line["up"])
print("self.lines after loadUp", self.lines,"lineResources:",lineResources)
return -line["A"]
"""
return 0
# if line defined decrease only if this line is high - load regulation (eli jos vaiheessa ylikuormaa , koskee vain tätä vaihetta)
# check if current power > 0, if not return 0
# check which line to decrease
#return decreased power in A, 0 if nothing to descrease
#- - - - - - - - -
def sig_handler(signum, frame):
pass
exit(1)
def check_states():
ok_states = []
global states
global powerGuru
#TODO: spotlowesthours - kuluvan päivän x halvinta tuntia, tässä pitäisi kyllä ottaa myös kuluneet
#voisi ottaa ko päivän kuluneet ja koko tiedetyn tulevaisuuden
for state_key,state in states.items(): # check
#print(state_key,state )
if "enabledIf" in state:
state_returned, error_in_test = test_formula( state["enabledIf"],state_key)
if state_returned and not error_in_test:
ok_states.append(state_key)
for state_key,state in states.items():
states[state_key]["enabled"] = (state_key in ok_states)
print("check_states result:")
pp.pprint (ok_states)
return ok_states
def check_states_timeser(start, end):
global states
global powerGuru
print("aikaväli:",start, end)
for time in range(start, end+1, powerGuru.nettingPeriodMinutes*60):
ok_states = []
for state_key,state in states.items(): # check
if "enabledIf" in state:
state_returned, error_in_test = test_formula_timeser( state["enabledIf"],time)
# do not replicate internal states, typically max 999
if state_returned and not error_in_test and int(state_key)>s.states_internal_max:
ok_states.append(int(state_key)) #Voisi olla kai int tästä
#print (time, ok_states)
powerGuru.set_variable_timeser("states",time,ok_states,"list")
return
def test_formula(formula,info):
#returns: value,isError
#print("#######")
eval_string = formula
# powerguru:time
for vkey,v in powerGuru.get_variables():
if vkey in eval_string:
variable_value = powerGuru.get_value(vkey,None)
if variable_value is not None:
eval_string = eval_string.replace(vkey,str(variable_value))
else:
print("Variable {} value was None:".format(vkey))
return False, True
try:
eval_value = eval(eval_string,{})
except NameError:
print("Variable(s) undefined in " + eval_string)
return False, True
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception( exc_type,exc_value, exc_traceback,limit=5, file=sys.stdout)
print("eval_string: ",eval_string)
return False, True
#print("formula {}, [{}] => {}".format(info,eval_string, eval_value))
return eval_value, False
def test_formula_timeser(formula,time,debudError=False):
global powerGuru
variable_keys = list(powerGuru.variables_timeser.keys())
#print(variable_keys)
#pp.pprint(variable_keys)
variable_keys.append("hhmm")
variable_keys.append("mmdd")
eval_string = formula
for vkey in variable_keys:
if vkey in eval_string:
variable_value = powerGuru.get_value_timeser(vkey,time,None) ########
if variable_value is not None:
eval_string = eval_string.replace(vkey,str(variable_value))
else:
print("Variable {} value was None:".format(vkey))
return False, True
try:
eval_value = eval(eval_string,{})
except NameError:
if debudError:
print("Variable(s) undefined in " + eval_string)
return False, True
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception( exc_type,exc_value, exc_traceback,limit=5, file=sys.stdout)
print("eval_string: ",eval_string)
return False, True
#print("formula {}, [{}] => {}".format(info,eval_string, eval_value))
return eval_value, False
def reportState(price_fields):
global powerGuru
state_fields = {}
channel_fields = {}
# via Telegraf relay to influxDB
#TODO: add to parameters
ifClientUrl = powerGuru.get_setting("InfluxDBClientUrl","http://127.0.0.1:8086")
ifClientToken = powerGuru.get_setting("InfluxDBClientToken","")
ifclient = InfluxDBClient(url = ifClientUrl,token=ifClientToken)
try:
json_body = []
json_body.append( {
"measurement": "prices",
"time": datetime.now(timezone.utc),
"fields": price_fields
})
if powerGuru.localChannelsEnabled:
for channel in channels:
channel_fields[channel.code]= (1 if channel.up else 0)
json_body.append( {
"measurement": "channels",
"time": datetime.now(timezone.utc),
"fields": channel_fields
})
for state_key,state in states.items():
state_fields[state_key]= (1 if state["enabled"] else 0)
json_body.append( {
"measurement": "states",
"time": datetime.now(timezone.utc),
"fields": state_fields
})
write_api = ifclient.write_api(write_options=SYNCHRONOUS)
write_api.write("", "", json_body)
# print ("Wrote to influx")
except:
print ("Cannot write to influx")
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception( exc_type,exc_value, exc_traceback,limit=5, file=sys.stdout)
def get_spot_sliding_window_periods(current_period_start_ts, window_duration_hours):
# get entries from now to requested duration in the future,
# if not enough future exists, include periods from history to get full window size
global dayahead_list
if dayahead_list is None:
return None
# get max and min
min_dayahead_time = current_period_start_ts +10*24*3600
max_dayahead_time = 0
for price_entry in dayahead_list:
min_dayahead_time = min(min_dayahead_time,price_entry["timestamp"])
max_dayahead_time = max(max_dayahead_time,price_entry["timestamp"])
window_end_excl = min(current_period_start_ts + window_duration_hours*3600,max_dayahead_time)
window_start_incl = window_end_excl-window_duration_hours*3600
#print("current_period_start_ts", current_period_start_ts)
#print("dayahead_list ts range",min_dayahead_time, max_dayahead_time)
#print("window_start_incl - window_end_excl",window_start_incl, window_end_excl)
entry_window = []
for price_entry in dayahead_list:
if window_start_incl <= price_entry["timestamp"] and price_entry["timestamp"] < window_end_excl:
tsstr = datetime.fromtimestamp(price_entry["timestamp"]).strftime("%Y-%m-%dT%H:%M")
entry_window.append({"ts":price_entry["timestamp"],"value":round(price_entry["fields"]["energyPriceSpot"],2), "tsstr":tsstr})
entry_window_sorted = sorted(entry_window, key=lambda entry: entry["value"])
return entry_window_sorted
def get_current_period_rank(window_duration_hours):
global powerGuru
period_in_seconds = 60*powerGuru.nettingPeriodMinutes
current_period_start_ts = int(time.time()/period_in_seconds)*period_in_seconds
price_window_sorted = get_spot_sliding_window_periods(current_period_start_ts, window_duration_hours)
rank = 1
if price_window_sorted is not None:
for entry in price_window_sorted:
if current_period_start_ts == entry["ts"]:
#print("window size hours:", window_duration_hours, ", rank:", rank )
#pp.pprint(price_window_sorted)
return rank
rank += 1
print("****Cannot find current_period_start_ts in the window", current_period_start_ts)
return None
def get_period_rank_timeser(time, window_duration_hours):
global powerGuru
#period_in_seconds = 60*powerGuru.nettingPeriodMinutes
#current_period_start_ts = int(time.time()/period_in_seconds)*period_in_seconds
price_window_sorted = get_spot_sliding_window_periods(time, window_duration_hours)
rank = 1
if price_window_sorted is not None:
for entry in price_window_sorted:
if time == entry["ts"]:
#print("window size hours:", window_duration_hours, ", rank:", rank )
#pp.pprint(price_window_sorted)
return rank
rank += 1
print("****Cannot find current_period_start_ts in the window", time)
return None
def load_program_config():
global actuators,sensorData,thermometers, powerGuru
global sensor_settings,states #,switches
global dayahead_list, forecastpv_list