forked from vtraveller/gowatt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgowatt.py
More file actions
447 lines (368 loc) · 14.5 KB
/
gowatt.py
File metadata and controls
447 lines (368 loc) · 14.5 KB
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
import requests
import json
from time import time
from datetime import datetime
from random import randint
name = "gowatt"
'''
Gowatt
======
Gowatt is a layered client API designed to access and control Growatt SPA/SPH series
Inverters and A/C Couplers.
It automatically goes through a list of growatt.com servers until login is
successful. This can be overridden when connecting.
It uses a layered cache with a half-life of the SPA/SPH's Shine Adapters poll
time. This ensures that excessive requests to the Growatt Servers are limited.
All non-time based raw data functions store in the cache on-demand. All highlevel
functions use the cached data.
The idea of having a raw API that maps 1:1 to the Growatt Server, and a highlevel API
is to allow for abstraction, and some client stability. Whether you use the raw or
highlevel functions is based entirely on whether you need stability or variable not
provided at the high level.
This code is inspired by https://github.com/indykoning/PyPi_GrowattServer
Tested on an SPA3000. Dom3442 provided SPH3600 information (Mix).
'''
class Gowatt(object):
'''
Class Variables
'''
server_urls = [
'server.growatt.com',
'server-api.growatt.com',
'openapi.growatt.com'
]
server_url = None
agent_identifier = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/118.0'
session = None
plantId = None
deviceType = None
deviceSN = None
datalogSN = None
dataCache = {}
refreshTime = 1 # time in minutes before data expires
def __init__(self, add_random_user_id=False, agent_identifier=None, server_urls=None):
'''
Init the object
'''
if (agent_identifier != None):
# replace the agent if needed
self.agent_identifier = agent_identifier
if (server_urls != None):
# replace server list
self.server_urls = server_urls
if (add_random_user_id):
# add random user id at end of agent_identifier
random_number = ''.join(["{}".format(randint(0, 9))
for num in range(5)])
self.agent_identifier += " - " + random_number
self.session = requests.Session()
# for debug
# self.session.hooks = {
# 'response': lambda response, *args, **kwargs: response.raise_for_status()
# }
headers = {
'User-Agent': self.agent_identifier
}
self.session.headers.update(headers)
def getBatteryChargeRate(self):
'''
Returns battery charge rate in Watt Hours as an integer
'''
device = self.rawGetStatusData()
# convert to Wh
charge = float(device['chargePower']) * 1000
if charge == 0:
charge = float(device['pdisCharge1']) * -1000
return 0 if device == None else int(charge)
def getBatteryLevel(self):
'''
Returns battery level is a percentage integer
'''
device = self.rawGetStatusData()
return 0 if device == None else int(device['SOC'])
def getDataLogSN(self):
return self.datalogSN
def getDeviceSN(self):
return self.deviceSN
def getDeviceType(self):
return self.deviceType
def getGridRate(self):
'''
Returns FROM grid in Watt Hours as an integer
A negative number means TO the grid
'''
device = self.rawGetStatusData()
grid = float(device['pactogrid']) * -1000
local = self.getLocalLoad()
battery = self.getBatteryChargeRate()
solar = self.getSolarRate()
if grid == 0:
# if not positive, the house plus battery drain minus solar
# should equal what's coming FROM the grid
grid = local + battery - solar
# convert to Wh
return grid
def getLocalLoad(self):
'''
Returns local load to house in Watt Hours as an integer
'''
device = self.rawGetStatusData()
# convert to Wh
return float(device['pLocalLoad']) * 1000
def getPlantId(self):
return self.plantId
def getSolarRate(self):
'''
Returns ppv in Watt Hours as an integer
'''
device = self.rawGetStatusData()
# convert to Wh
return float(device['ppv']) * 1000
def login(self, username, password):
'''
Log the user in. This grabs critical data needed later:
plantId
deviceSN
datalogSN
Returns
True - if logged in and ready
'''
loaded = False
for url in self.server_urls:
self.server_url = 'https://' + url + '/'
try:
data = self.post(
'login', # page
formData={
'account': username,
'password': password
},
cached=False
)
except:
continue
if data == None:
continue
self.plantId = self.session.cookies.get('onePlantId')
data = self.rawGetDevices()
if data == None:
continue
# TODO: can support multiple devices here - if needed
self.deviceType = data[0]['deviceTypeName']
self.deviceSN = data[0]['sn']
self.datalogSN = data[0]['datalogSn']
data = self.rawGetDataLoggerInfo()
if data:
# update cache with real refresh time
# half actual so we don't drift past
self.refreshTime = int(data['interval']) / 2
for item in self.dataCache:
self.dataCache[item]['TTL'] = int(
time()) + self.refreshTime
loaded = True
break
return loaded
def post(self, page, args={}, formData={}, cached=True):
'''
Simple helper function to get data
'''
if cached == True:
lut = page + ':' + str(args) + ':' + str(formData)
if lut in self.dataCache:
# check cache to see if timed out
if self.dataCache[lut]['TTL'] > int(time()):
# return cache rather than request again
return self.dataCache[lut]['obj']
attributes = ''
for arg in args:
attributes += '?' if len(attributes) == 0 else '&'
attributes += arg + '=' + args[arg]
try:
response = self.session.post(
self.server_url + page + attributes,
data=formData
)
except:
return None
if not response.ok:
return None
if not response.content:
return None
data = json.loads(response.content.decode('utf-8'))
if not 'result' in data:
return data
if data['result'] != 1:
return None
if not 'obj' in data:
return data
if cached == True:
self.dataCache[lut] = {
'TTL': int(time()) + (self.refreshTime * 60),
'obj': data['obj']
}
return self.dataCache[lut]['obj']
def rawGetDataLoggerInfo(self):
return self.post(
'panel/getDeviceInfo',
formData={
'plantId': self.plantId,
'deviceTypeName': 'datalog',
'sn': self.datalogSN
}
)
def rawGetDevices(self):
data = self.post(
'panel/getDevicesByPlantList',
formData={
'currPage': '1',
'plantId': self.plantId
}
)
if 'datas' in data:
return data['datas']
return data
def rawGetEicDevices(self):
return self.post(
'panel/getEicDevicesByPlant',
formData={'plantId': self.plantId}
)
def rawGetPlantData(self):
return self.post(
'panel/getPlantData',
args={'plantId': self.plantId}
)
def rawGetStatusData(self):
return self.post(
'panel/{}/get{}StatusData'.format(self.deviceType,
self.deviceType.upper()),
args={'plantId': self.plantId},
formData={'{}Sn'.format(self.deviceType): self.deviceSN}
)
def rawGetBatChart(self, date=datetime.today().strftime('%Y-%m-%d')):
return self.post(
'panel/{}/get{}BatChart'.format(self.deviceType,
self.deviceType.upper()),
formData={
'plantId': self.plantId,
'{}Sn'.format(self.deviceType): self.deviceSN,
'date': date
}
)
def rawGetEnergyDayChart(self, date=datetime.today().strftime('%Y-%m-%d')):
return self.post(
'panel/{}/get{}EnergyDayChart'.format(
self.deviceType, self.deviceType.upper()),
formData={
'plantId': self.plantId,
'{}Sn'.format(self.deviceType): self.deviceSN,
'date': date
}
)
def rawGetEnergyMonthChart(self, date=datetime.today().strftime('%Y-%m')):
return self.post(
'panel/{}/get{}EnergyMonthChart'.format(
self.deviceType, self.deviceType.upper()),
formData={
'plantId': self.plantId,
'{}Sn'.format(self.deviceType): self.deviceSN,
'date': date
}
)
def rawGetEnergyYearChart(self, year=datetime.today().strftime('%Y')):
return self.post(
'panel/{}/get{}EnergyYearChart'.format(
self.deviceType, self.deviceType.upper()),
formData={
'plantId': self.plantId,
'{}Sn'.format(self.deviceType): self.deviceSN,
'year': year
}
)
def rawGetEnergyTotalChart(self, year=datetime.today().strftime('%Y')):
return self.post(
'panel/{}/get{}EnergyTotalChart'.format(
self.deviceType, self.deviceType.upper()),
formData={
'plantId': self.plantId,
'{}Sn'.format(self.deviceType): self.deviceSN,
'year': year
}
)
def rawSetInternal(self, type, common, values):
'''
Applies settings for specified system based on serial number
Arguments:
type Setting to be configured (str)
common Set of parameters for the setting call (dict)
values Parameters to be sent to the system (dict or list of str)
(array which will be converted to a dictionary)
Returns:
JSON response from the server whether the configuration was successful
'''
settings = values
# If we've been passed an array then convert it into a dictionary
if isinstance(values, list):
settings = {}
for index, param in enumerate(values, start=1):
settings['param' + str(index)] = param
parameters = {**common, **settings}
return self.post(
'tcpSet.do',
formData=parameters,
cached=False
)
def rawSet(self, type, settings):
common = {
'action': '{}Set'.format(self.deviceType),
'serialNum': self.deviceSN,
'type': type
}
return self.rawSetInternal(type, common, settings)
def setRuleBatteryFirst(self, start_hour: int, start_minute: int,
end_hour: int, end_minute: int,
amount: int = 80, rate: int = 50,
enable: bool = True) -> bool:
'''Sets the amount to charge the battery.
Only the first schedule is used, all others are zeroed
Args:
start_hour (int): hour to begin charging
start_minute (int): minute to begin charging
end_hour (int): hour to end charging
end_minute (int): minute to end charging
amount (int, optional): target SoC percentage. Defaults to 80.
rate (int, optional): percent of maximum charging rate. Defaults to 50.
enable (bool, optional): whether charging is enabled. Defaults to True.
Returns:
bool: success setting parameter
'''
# All parameters need to be given, including zeros
# All parameters must be strings
schedule_settings = [
str(rate), # Charging power %
str(amount), # Stop charging when above SoC %
'{:02d}'.format(int(start_hour)),
# Schedule 1 - Start time
'{:02d}'.format(int(start_minute)),
'{:02d}'.format(int(end_hour)),
'{:02d}'.format(int(end_minute)), # Schedule 1 - End time
# Schedule 1 - Enabled/Disabled (1 = Enabled)
str('1' if enable else '0'),
'00', '00', # Schedule 2 - Start time
'00', '00', # Schedule 2 - End time
'0', # Schedule 2 - Enabled/Disabled (1 = Enabled)
'00', '00', # Schedule 3 - Start time
'00', '00', # Schedule 3 - End time
'0' # Schedule 3 - Enabled/Disabled (1 = Enabled)
]
if self.deviceType == 'mix':
# same as 'spa' but needs to enable AC charging (index 2 - between amount and start)
schedule_settings.insert(2, str('1' if enable else '0'))
response = self.rawSet('{}_ac_charge_time_period'.format(
self.deviceType), schedule_settings)
print(json.dumps(response)) # used to show working
if not 'msg' in response:
return False
if response['msg'] != 'inv_set_success':
print('failed - NEED RECOVERY - ' + response['msg'])
return False
return True