-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgowatt.py
More file actions
571 lines (461 loc) · 19.2 KB
/
gowatt.py
File metadata and controls
571 lines (461 loc) · 19.2 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
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
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).
'''
from random import randint
from datetime import datetime
from time import time
import json
import requests
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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.81"
username = None # needed for relogging in on timeout
password = None # needed for relogging in on timeout
session = None
plantId = None
device = {} # { type: '', datalogSN: '' } -> index = deviceSN, type = deviceType, datalogSN = datalogSN -> logical change
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(0,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 __getDeviceSN(self,deviceSN):
# if the user didn't specify a deviceSN
# we'll return the first we have
if not self.device:
return None # safety
if not deviceSN:
keys = list(self.device.keys())
deviceSN = keys[0]
return deviceSN
def getBatteryRate(self, deviceSN = None):
'''
Returns battery rate in Watt Hours as an integer
Battery is positive +Wh if discharging (power out), and negative -Wh (power in) if charging
'''
device = self.rawGetStatusData(deviceSN = deviceSN)
if not device: return None
# convert to Wh
# Battery: positive for power out, negative for power in if charging battery
charge = float(device['chargePower']) * -1000
if charge == 0:
charge = float(device['pdisCharge1']) * 1000
return 0 if device == None else int(charge)
def getBatteryLevel(self, deviceSN = None):
'''
Returns battery level is a percentage integer
'''
device = self.rawGetStatusData(deviceSN = deviceSN)
if not device: return None
return 0 if device == None else int(device['SOC'])
def getDataLogSN(self, deviceSN = None):
deviceSN = self.__getDeviceSN(deviceSN)
return self.device[deviceSN]['datalogSN']
def getDeviceSNlist(self):
return self.device.keys()
def getDeviceType(self, deviceSN = None):
deviceSN = self.__getDeviceSN(deviceSN)
return self.device[deviceSN]['type']
def getGridRate(self,deviceSN = None):
'''
Returns FROM grid in Watt Hours as an integer
Positive for power out (to local/house), negative for power in (to grid)
'''
device = self.rawGetStatusData(deviceSN = deviceSN)
if not device: return None
# convert to Wh
# Solar: positive for power out
# Battery: positive for power out, negative for power in if charging battery
# Local: negative as power in
# Grid: positive for power out (to local/house), negative for power in (to grid)
grid = float(device['pactogrid']) * 1000
if grid == 0:
# if not positive, the local/house plus battery drain minus solar
# should equal what's coming FROM the grid or TO the grid
local = float(device['pLocalLoad']) * -1000
battery = self.getBatteryRate() # positive for discharging (power out)
solar = self.getSolarRate() # positive for power out
grid = local + battery + solar
# Grid: positive for power out (to local/house), negative for power in (to grid)
return -grid
def getLocalLoad(self, deviceSN = None):
'''
Returns local load to local/house in Watt Hours as an integer
Local load is negative (-Wh) as power in being consumed/used
'''
device = self.rawGetStatusData(deviceSN = deviceSN)
if not device: return None
# battery = self.getBatteryRate()
# if battery < 0: battery = 0 # remove impact if not helping load
grid = float(device['pactogrid']) * -1000
if grid < 0: grid = 0 # remove impact if not helping load
# convert to Wh
# Local: negative as power in
return (-float(device['pLocalLoad']) * 1000) + grid
def getPlantId(self):
return self.plantId
def getSolarRate(self, deviceSN = None):
'''
Returns ppv in Watt Hours as an integer
Positive Wh as power out
'''
device = self.rawGetStatusData(deviceSN = deviceSN)
if not device: return None
# convert to Wh
# Solar: positive for power out
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
self.username = username # save for relogin
self.password = password # save for relogin
for url in self.server_urls:
self.server_url = 'https://' + url + '/'
try:
self.session.cookies.clear()
data = self.post(
'login', # page
formData = {
'account': username,
'password': password
},
cached = False,
retry = False
)
except:
continue
if data == None: continue
self.plantId = self.session.cookies.get('onePlantId')
data = self.rawGetDevices()
if data == None: continue
# self.device[deviceSN]['type'] = data[0]['deviceTypeName']
# self.device[deviceSN] = data[0]['sn']
# self.device[deviceSN]['datalogSN'] = data[0]['datalogSn']
for item in data:
deviceSN = item['sn']
self.device[deviceSN] = {
'type': item['deviceTypeName'],
'datalogSN': item['datalogSn']
}
data = self.rawGetDataLoggerInfo(deviceSN = deviceSN)
if data:
# update cache with real refresh time
self.refreshTime = int(data['interval']) / 2 # half actual so we don't drift past
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, retry = 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:
success = False
while not success:
response = self.session.post(
self.server_url + page + attributes,
data = formData
)
if not response.ok: return None
if not response.content: return None
content = str(response.content)
success = (content.find('<!DOCTYPE html') == -1)
if not success:
# happens if we get logged out - no longer a JSON response
if retry:
logged_in = self.login(self.username,self.password)
if not logged_in: return None
else:
return None
data = json.loads(response.content.decode('utf-8'))
except:
# fatal failure
return None
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,deviceSN = None):
deviceSN = self.__getDeviceSN(deviceSN)
datalogSN = self.device[deviceSN]['datalogSN']
return self.post(
'panel/getDeviceInfo',
formData = {
'plantId': self.plantId,
'deviceTypeName': 'datalog',
'sn': 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, deviceSN = None):
deviceSN = self.__getDeviceSN(deviceSN)
deviceType = self.device[deviceSN]['type']
return self.post(
'panel/{}/get{}StatusData'.format(self.device[deviceSN]['type'],self.device[deviceSN]['type'].upper()),
args = { 'plantId': self.plantId },
formData = { '{}Sn'.format(deviceType): deviceSN }
)
def rawGetBatChart(self,date = datetime.today().strftime('%Y-%m-%d'), deviceSN = None):
deviceSN = self.__getDeviceSN(deviceSN)
deviceType = self.device[deviceSN]['type']
return self.post(
'panel/{}/get{}BatChart'.format(self.device[deviceSN]['type'],self.device[deviceSN]['type'].upper()),
formData = {
'plantId': self.plantId,
'{}Sn'.format(deviceType): deviceSN,
'date': date
}
)
def rawGetEnergyDayChart(self,date = datetime.today().strftime('%Y-%m-%d'), deviceSN = None):
deviceSN = self.__getDeviceSN(deviceSN)
deviceType = self.device[deviceSN]['type']
return self.post(
'panel/{}/get{}EnergyDayChart'.format(deviceType,deviceType.upper()),
formData = {
'plantId': self.plantId,
'{}Sn'.format(deviceType): deviceSN,
'date': date
}
)
def rawGetEnergyMonthChart(self,date = datetime.today().strftime('%Y-%m'), deviceSN = None):
deviceSN = self.__getDeviceSN(deviceSN)
deviceType = self.device[deviceSN]['type']
return self.post(
'panel/{}/get{}EnergyMonthChart'.format(self.device[deviceSN]['type'],self.device[deviceSN]['type'].upper()),
formData = {
'plantId': self.plantId,
'{}Sn'.format(deviceType): deviceSN,
'date': date
}
)
def rawGetEnergyYearChart(self,year = datetime.today().strftime('%Y'), deviceSN = None):
deviceSN = self.__getDeviceSN(deviceSN)
deviceType = self.device[deviceSN]['type']
return self.post(
'panel/{}/get{}EnergyYearChart'.format(self.device[deviceSN]['type'],self.device[deviceSN]['type'].upper()),
formData = {
'plantId': self.plantId,
'{}Sn'.format(deviceType): deviceSN,
'year': year
}
)
def rawGetEnergyTotalChart(self,year = datetime.today().strftime('%Y'), deviceSN = None):
deviceSN = self.__getDeviceSN(deviceSN)
deviceType = self.device[deviceSN]['type']
return self.post(
'panel/{}/get{}EnergyTotalChart'.format(self.device[deviceSN]['type'],self.device[deviceSN]['type'].upper()),
formData = {
'plantId': self.plantId,
'{}Sn'.format(deviceType): 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, deviceSN = None):
deviceSN = self.__getDeviceSN(deviceSN)
deviceType = self.device[deviceSN]['type']
common = {
'action': '{}Set'.format(deviceType),
'serialNum': deviceSN,
'type': type
}
return self.__rawSetInternal(type, common, settings)
def setRuleBatteryFirst(self,amount,startHour,endHour,enable,startMin = 0,endMin = 0,deviceSN = None):
'''
Sets the amount to charge the battery.
Only the first schedule is used, all others are zero'd
Parameters:
amount -> percentage to charge battery to
startHour -> when to start
endHour -> when to finish
enable -> whether rule is enabled or disabled
'''
deviceSN = self.__getDeviceSN(deviceSN)
# All parameters need to be given, including zeros
# All parameters must be strings
schedule_settings = [
'100', # Charging power %
str(amount), # Stop charging when above SoC %
str(startHour), str(startMin), # Schedule 1 - Start time
str(endHour), str(endMin), # Schedule 1 - End time
str('1' if enable else '0'), # Schedule 1 - Enabled/Disabled (1 = Enabled)
'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.device[deviceSN]['type'] == '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'))
deviceType = self.device[deviceSN]['type']
response = self.rawSet('{}_ac_charge_time_period'.format(deviceType),schedule_settings)
print(json.dumps(response)) # used to show working
if not response or not 'msg' in response: return False
if response['msg'] != 'inv_set_success':
print('failed - NEED RECOVERY - ' + response['msg'])
return False
return True
def setRuleLoadFirst(self,startHour,endHour,enable,startMin = 0,endMin = 0,deviceSN = None):
'''
Sets the time to use load.
Only the first schedule is used, all others are zero'd
Parameters:
startHour -> when to start
endHour -> when to finish
enable -> whether rule is enabled or disabled
'''
deviceSN = self.__getDeviceSN(deviceSN)
# All parameters need to be given, including zeros
# All parameters must be strings
schedule_settings = [
str(startHour), str(startMin), # Schedule 1 - Start time
str(endHour), str(endMin), # Schedule 1 - End time
str('1' if enable else '0'), # Schedule 1 - Enabled/Disabled (1 = Enabled)
'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)
]
deviceType = self.device[deviceSN]['type']
if 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('{}_load_flast'.format(deviceType),schedule_settings,deviceSN = deviceSN)
print(json.dumps(response)) # used to show working
if not response or not 'msg' in response: return False
if response['msg'] != 'inv_set_success':
print('failed - NEED RECOVERY - ' + response['msg'])
return False
return True
def setTime(self,hour,min,date = datetime.today().strftime('%Y-%m-%d'),deviceSN = None):
'''
Sets the system time.
Parameters:
hour -> to set
min -> to set
date -> override today's date (prob not needed)
'''
settings = [
'{} {}:{}'.format(date,hour,min)
]
response = self.rawSet('pf_sys_year',settings,deviceSN)
print(json.dumps(response)) # used to show working
if not response or not 'msg' in response: return False
if response['msg'] != 'inv_set_success':
print('failed - NEED RECOVERY - ' + response['msg'])
return False
return True