-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solcast_WeatherData.py
186 lines (165 loc) · 9.31 KB
/
Solcast_WeatherData.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
import requests
import json
import os.path
import pytz
import time
from pathlib import Path
from datetime import datetime, timedelta
import FUNCTIONS.functions
def loadLatestWeatherData():
# Varablen definieren
format = "%Y-%m-%d %H:%M:%S"
dict_watts = {}
dict_watts['result'] = {}
dict_watts['result']['watts'] = {}
heute = datetime.strftime(now, "%Y-%m-%d")
morgen = datetime.strftime(now + timedelta(days=1), "%Y-%m-%d")
sommerzeit = time.localtime().tm_isdst
Abfragebereich = ['forecasts', 'estimated_actuals']
# Wenn no_history == 1 nur forecasts abrufen
if no_history == 1:
Abfragebereich = ['forecasts']
#die Daten müssen 2x abgerufen werden forecasts (Zukunft) und estimated_actuals (aktuell und Vergangenheit
for datenloop in Abfragebereich:
try:
url = 'https://api.solcast.com.au/rooftop_sites/{}/{}?format=json&api_key={}'.format(resource_id, datenloop, api_key)
try:
apiResponse = requests.get(url, timeout=99.50)
#apiResponse.raise_for_status()
if apiResponse.status_code != 204:
json_data1 = dict(json.loads(apiResponse.text))
else:
print("### ERROR: Keine forecasts-Daten von api.solcast.com.au")
exit()
except requests.exceptions.Timeout:
print("### ERROR: Timeout von api.solcast.com.au")
exit()
if Strings == 2:
url = 'https://api.solcast.com.au/rooftop_sites/{}/{}?format=json&api_key={}'.format(resource_id2, datenloop, api_key)
try:
apiResponse2 = requests.get(url, timeout=99.50)
apiResponse2.raise_for_status()
if apiResponse2.status_code != 204:
json_data2 = dict(json.loads(apiResponse2.text))
else:
print("### ERROR: Keine estimated_actuals-Daten von api.solcast.com.au")
exit()
except requests.exceptions.Timeout:
print("### ERROR: Timeout von api.solcast.com.au")
exit()
try:
# wenn zuviele Zugriffe
istda = json_data1['response_status']['error_code']
return(dict_watts, json_data1)
except:
Puffer = ['2000-01-01',5]
try:
for wetterwerte in json_data1[datenloop]:
key_neu_1 = (wetterwerte['period_end'][:19]).replace('T',' ',1)
if ('00:00' in key_neu_1 and (heute in key_neu_1 or morgen in key_neu_1)):
key_neu = datetime.strftime(datetime.strptime(key_neu_1, format) + timedelta(hours=Zeitzone+sommerzeit), format)
#hier Werte mit NULLEN weg
if (wetterwerte['pv_estimate'] == 0):
if (Puffer[1] == 0):
Puffer = [key_neu, int(wetterwerte['pv_estimate']*1000*KW_Faktor)]
continue
else:
Puffer = [key_neu, int(wetterwerte['pv_estimate']*1000*KW_Faktor)]
dict_watts['result']['watts'][key_neu] = int(wetterwerte['pv_estimate']*1000*KW_Faktor)
continue
else:
if (Puffer[1] == 0):
dict_watts['result']['watts'][Puffer[0]] = Puffer[1]
Puffer = [key_neu, int(wetterwerte['pv_estimate']*1000*KW_Faktor)]
dict_watts['result']['watts'][key_neu] = int(wetterwerte['pv_estimate']*1000*KW_Faktor)
except:
continue
if Strings == 2:
Puffer = ['2000-01-01',5]
try:
for wetterwerte in json_data2[datenloop]:
key_neu_1 = (wetterwerte['period_end'][:19]).replace('T',' ',1)
if ('00:00' in key_neu_1 and (heute in key_neu_1 or morgen in key_neu_1)):
key_neu = datetime.strftime(datetime.strptime(key_neu_1, format) + timedelta(hours=Zeitzone+sommerzeit), format)
#hier Werte mit NULLEN weg
if (wetterwerte['pv_estimate'] == 0):
if (Puffer[1] == 0):
Puffer = [key_neu, int(wetterwerte['pv_estimate']*1000*KW_Faktor2)]
continue
else:
Puffer = [key_neu, int(wetterwerte['pv_estimate']*1000*KW_Faktor2)]
dict_watts['result']['watts'][key_neu] = dict_watts['result']['watts'][key_neu] + int(wetterwerte['pv_estimate']*1000*KW_Faktor2)
continue
else:
if (Puffer[1] == 0):
dict_watts['result']['watts'][Puffer[0]] = Puffer[1]
Puffer = [key_neu, int(wetterwerte['pv_estimate']*1000*KW_Faktor2)]
dict_watts['result']['watts'][key_neu] = dict_watts['result']['watts'][key_neu] + int(wetterwerte['pv_estimate']*1000*KW_Faktor2)
except:
continue
# Wenn no_history == 1 historische Daten aus weatherData.json holen
if no_history == 1:
try:
with open(weatherfile, 'r') as datei:
json_data_old = json.load(datei)
#print(json_data_old)
for wetterwerte_old in json_data_old['result']['watts']:
if heute in wetterwerte_old and wetterwerte_old not in dict_watts['result']['watts']:
dict_watts['result']['watts'][wetterwerte_old] = int(json_data_old['result']['watts'][wetterwerte_old])
#print (wetterwerte_old)
except:
print("Fehler beim Lesen von ", weatherfile)
#solcast_2.json Nun wieder nach Datum und Stunden sortieren
dict_watts['result']['watts'] = dict(sorted(dict_watts['result']['watts'].items()))
except requests.exceptions.RequestException as error:
json_data1 = error
return(dict_watts, json_data1)
if __name__ == '__main__':
basics = FUNCTIONS.functions.basics()
config = basics.loadConfig(['default', 'weather'])
# Benoetigte Variablen definieren und prüfen
Strings = basics.getVarConf('pv.strings', 'anzahl', 'eval')
dataAgeMaxInMinutes = basics.getVarConf('solcast.com', 'dataAgeMaxInMinutes', 'eval')
Zeitzone = basics.getVarConf('solcast.com', 'Zeitzone', 'eval')
no_history = basics.getVarConf('solcast.com', 'no_history', 'eval')
KW_Faktor = basics.getVarConf('solcast.com2', 'KW_Faktor', 'eval')
KW_Faktor2 = basics.getVarConf('solcast.com', 'KW_Faktor', 'eval')
weatherfile = basics.getVarConf('solcast.com', 'weatherfile', 'str')
api_key = basics.getVarConf('solcast.com', 'api_key', 'str')
resource_id = basics.getVarConf('solcast.com', 'resource_id', 'str')
resource_id2 = basics.getVarConf('solcast.com2', 'resource_id', 'str')
format = "%Y-%m-%d %H:%M:%S"
now = datetime.now()
data = basics.loadWeatherData(weatherfile)
# print(data['messageCreated'])
dataIsExpired = True
if (data):
dateCreated = None
if (data['messageCreated']):
dateCreated = datetime.strptime(data['messageCreated'], format)
if (dateCreated):
diff = now - dateCreated
dataAgeInMinutes = diff.total_seconds() / 60
if (dataAgeInMinutes < dataAgeMaxInMinutes):
print_level = basics.getVarConf('env','print_level','eval')
if ( print_level != 0 ):
print('solcast.com: Die Minuten aus "dataAgeMaxInMinutes" ', dataAgeMaxInMinutes ,' Minuten sind noch nicht abgelaufen!!')
print(f'[Now: {now}] [Data created: {dateCreated}] -> age in min: {dataAgeInMinutes}')
dataIsExpired = False
if (dataIsExpired):
data_all = loadLatestWeatherData()
data = data_all[0]
data_err = data_all[1]
#print(data)
if(data['result']['watts'] != {}):
if not data == "False":
# hier evtl Begrenzungen der Prognose anbringen
MaximalPrognosebegrenzung = basics.getVarConf('env','MaximalPrognosebegrenzung','eval')
if (MaximalPrognosebegrenzung == 1):
data = basics.checkMaxPrognose(data)
if (MaximalPrognosebegrenzung == 2):
data = basics.Prognoseoptimierung(data)
basics.storeWeatherData(weatherfile, data, now, 'solcast.com')
else:
print("Fehler bei Datenanforderung api.solcast.com.au:")
print(data_err)