-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathsensor.py
More file actions
2265 lines (2052 loc) · 85.2 KB
/
sensor.py
File metadata and controls
2265 lines (2052 loc) · 85.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
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
from __future__ import annotations
from collections import namedtuple
from datetime import timedelta
from datetime import datetime
from dateutil import parser
import time
import logging
import json
import hashlib
import asyncio
import voluptuous as vol
from homeassistant.components.rest.data import RestData
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorStateClass,
PLATFORM_SCHEMA,
SensorEntity,
)
from homeassistant.const import (
ATTR_DATE,
ATTR_TIME,
CONF_PASSWORD,
CONF_USERNAME,
CONF_NAME,
UnitOfPower,
UnitOfTemperature,
UnitOfEnergy,
UnitOfElectricPotential,
UnitOfElectricCurrent,
UnitOfFrequency,
UnitOfReactivePower,
PERCENTAGE,
)
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from homeassistant.util.ssl import SSLCipherList
from homeassistant.helpers.icon import icon_for_battery_level
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
_ENDPOINT_OA_DOMAIN = "https://www.foxesscloud.com"
_ENDPOINT_OA_BATTERY_SETTINGS = "/op/v0/device/battery/soc/get?sn="
_ENDPOINT_OA_REPORT = "/op/v0/device/report/query"
_ENDPOINT_OA_DEVICE_DETAIL = "/op/v0/device/detail"
_ENDPOINT_OA_DEVICE_DETAIL_V1 = "/op/v1/device/detail"
_ENDPOINT_OA_DEVICE_VARIABLES = "/op/v0/device/real/query"
_ENDPOINT_OA_DEVICE_VARIABLES_V1 = "/op/v1/device/real/query"
_ENDPOINT_OA_DAILY_GENERATION = "/op/v0/device/generation?sn="
METHOD_POST = "POST"
METHOD_GET = "GET"
DEFAULT_ENCODING = "UTF-8"
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
DEFAULT_TIMEOUT = 75 # increase the size of inherited timeout, the API is a bit slow
ATTR_DEVICE_SN = "deviceSN"
ATTR_PLANTNAME = "plantName"
ATTR_MODULESN = "moduleSN"
ATTR_DEVICE_TYPE = "deviceType"
ATTR_MASTER = "masterVersion"
ATTR_MANAGER = "managerVersion"
ATTR_SLAVE = "slaveVersion"
ATTR_BATTERYLIST = "batteryList"
ATTR_LASTCLOUDSYNC = "lastCloudSync"
BATTERY_LEVELS = {"High": 80, "Medium": 50, "Low": 25, "Empty": 10}
CONF_APIKEY = "apiKey"
CONF_DEVICESN = "deviceSN"
CONF_DEVICEID = "deviceID"
CONF_SYSTEM_ID = "system_id"
CONF_EXTPV = "extendPV"
CONF_XTZONE = "xtZone"
CONF_GET_VARIABLES = "Restrict"
CONF_V1_API = "Use_V1_Api"
CONF_EVO = "Evo"
RETRY_NEXT_SLOT = -1
RETRY_IN_5_MINS = 25
DNS_ERROR = 101
DEFAULT_NAME = "FoxESS"
DEFAULT_VERIFY_SSL = False # True
SCAN_MINUTES = 1 # number of minutes betwen API requests
SCAN_INTERVAL = timedelta(minutes=SCAN_MINUTES)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_USERNAME): cv.string,
vol.Optional(CONF_PASSWORD): cv.string,
vol.Required(CONF_APIKEY): cv.string,
vol.Required(CONF_DEVICESN): cv.string,
vol.Required(CONF_DEVICEID): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_EXTPV): cv.boolean,
vol.Optional(CONF_XTZONE): cv.boolean,
vol.Optional(CONF_GET_VARIABLES): cv.boolean,
vol.Optional(CONF_V1_API): cv.boolean,
vol.Optional(CONF_EVO): cv.boolean,
}
)
token = None
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the FoxESS sensor."""
global LastHour, timeslice, last_api, RestrictGetVar, xtzone, V1_Api, Evo
Evo = False
name = config.get(CONF_NAME)
deviceID = config.get(CONF_DEVICEID)
devicesn = config.get(CONF_DEVICESN)
apiKey = config.get(CONF_APIKEY)
ExtPV = config.get(CONF_EXTPV)
xtzone = config.get(CONF_XTZONE)
RestrictGetVar = config.get(CONF_GET_VARIABLES)
V1_Api = config.get(CONF_V1_API)
Evo = config.get(CONF_EVO)
_LOGGER.debug("API Key: %s", apiKey)
_LOGGER.debug("Device SN: %s", devicesn)
_LOGGER.debug("Device ID: %s", deviceID)
_LOGGER.debug("FoxESS Scan Interval: %s minutes", SCAN_MINUTES)
_LOGGER.debug("Cross Time Zone: %s", xtzone)
_LOGGER.debug("Restrict Variables: %s", RestrictGetVar)
_LOGGER.debug("Extended PV: %s", ExtPV)
_LOGGER.debug("v1 Api Calls: %s", V1_Api)
_LOGGER.debug("EVO: %s", Evo)
if V1_Api is not False:
V1_Api = True
_LOGGER.debug("v1 Api Calls Enabled")
else:
_LOGGER.warning("v1 Api Calls Disabled, using v0")
if ExtPV is not True:
ExtPV = False
_LOGGER.debug("Extended PV Disabled")
else:
_LOGGER.warning("Extended PV 1-18 strings enabled")
if RestrictGetVar is not True:
RestrictGetVar = False
_LOGGER.debug("Get Variables is full variable mode")
else:
_LOGGER.warning("Get Variables is in restricted mode")
timeslice = {}
timeslice[devicesn] = RETRY_NEXT_SLOT
last_api = 0
LastHour = 0
allData = {
"report": {},
"reportDailyGeneration": {},
"raw": {},
"battery": {},
"addressbook": {},
"online": False,
}
allData["addressbook"]["hasBattery"] = False # assume no battery is fitted for now
allData["addressbook"]["status"] = "3" # assume inverter is off-line for now
async def async_update_data():
_LOGGER.debug("Updating data from https://www.foxesscloud.com/")
global token, timeslice, LastHour
hournow = datetime.now().strftime("%H") # update hour now
_LOGGER.debug("Time now: %s, last %s", hournow, LastHour)
tslice = timeslice[devicesn] + 1 # increment current device time slice
timeslice[devicesn] = tslice
if tslice % 5 == 0:
_LOGGER.debug("Main Poll, interval: %s, %s", devicesn, timeslice[devicesn])
# try the openapi see if we get a response
geterror = False
if tslice % 15 == 0:
# get device detail at startup, then every 15 minutes to save api calls
if Evo:
# Evo not currently in device detail, use list and fill partial blanks
geterror = await getOADeviceList(hass, allData, devicesn, apiKey)
else:
geterror = await getOADeviceDetail(hass, allData, devicesn, apiKey)
await asyncio.sleep(1) # OpenAPI demand
if not geterror:
if allData["addressbook"]["status"] is not None:
statetest = int(allData["addressbook"]["status"])
if statetest in [3]:
allData["raw"]["runningState"] = "164" # off-grid
else:
statetest = 0
_LOGGER.debug(" Statetest %s", statetest)
if statetest in [1, 2]:
allData["online"] = True
if tslice == 0:
# read in battery settings if fitted at startup, then every 60 mins
await getOABatterySettings(hass, allData, devicesn, apiKey)
await asyncio.sleep(1) # OpenAPI demand
# main real time data fetch, followed by reports
geterror = await getRaw(hass, allData, apiKey, devicesn)
if not geterror:
if tslice % 15 == 0: # do at startup and every 15 minutes
await asyncio.sleep(1) # OpenAPI demand limit
geterror = await getReport(hass, allData, apiKey, devicesn)
if not geterror:
if tslice == 0:
# get daily generation at startup, then every 60 minutes
await asyncio.sleep(1) # OpenAPI demand
geterror = await getReportDailyGeneration(hass, allData, apiKey, devicesn)
if geterror:
_LOGGER.debug("getReportDailyGeneration False")
else:
_LOGGER.debug("getReport False")
if geterror:
geterror = False
allData["online"] = False
tslice = RETRY_IN_5_MINS # retry in 5 minutes
else:
_LOGGER.debug("get variables failed")
if statetest == 2:
# The inverter is in alarm, don't check every minute
_LOGGER.debug(
"Inverter in alarm, slowing retry response for SN: %s",
devicesn,
)
allData["online"] = False
tslice = RETRY_IN_5_MINS # retry in 5 minutes
else:
if geterror==DNS_ERROR:
_LOGGER.warning("Fox Cloud - DNS fail, retry in 1 minute")
# retry in 1 minute
if tslice != 0:
tslice = (tslice-1)
else:
tslice = RETRY_NEXT_SLOT
else:
# The get variables api call failed, leave it 5 minutes
_LOGGER.debug("slowing retry response for SN: %s", devicesn)
allData["online"] = False
tslice = RETRY_IN_5_MINS # retry in 5 minutes
geterror = False
else:
if statetest == 3:
# The inverter is off-line, no raw data polling, don't update entities
# retry device detail call every 5 minutes until it comes back on-line
allData["online"] = False
tslice = RETRY_IN_5_MINS # retry in 5 minutes
_LOGGER.debug("Inverter off-line for SN: %s", devicesn)
if not allData["online"]:
if not geterror:
_LOGGER.warning("%s Inverter is off-line, waiting to retry", name)
else:
_LOGGER.warning("%s Cloud timeout, retry in 1 minute", name)
else:
_LOGGER.warning("%s Cloud timeout on Device Detail, retry in 1 minute.", name)
if geterror is not False:
allData["online"] = False
if tslice != 0:
tslice = tslice-1
# failed to get specific detail so retry slot in 1 minute
else:
tslice = RETRY_NEXT_SLOT # failed to get full data, try again in 1 minute
# actions here are every minute
if tslice >= 59:
tslice = RETRY_NEXT_SLOT # reset timeslot, ready for full data fetch at 0
_LOGGER.debug("Auxilliary timeslice %s, %s", devicesn, tslice)
if LastHour != hournow:
LastHour = hournow # update the hour the last poll was run
timeslice[devicesn] = tslice
_LOGGER.debug(allData)
return allData
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
# Name of the data. For logging purposes.
name=DEFAULT_NAME,
update_method=async_update_data,
# Polling interval. Will only be polled if there are subscribers.
update_interval=SCAN_INTERVAL,
)
await coordinator.async_refresh()
if not coordinator.last_update_success:
_LOGGER.error(
"FoxESS Cloud initialisation failed, Fatal Error - correct error and restart Home Assistant"
)
return False
async_add_entities(
[
FoxESSCurrent(
coordinator, name, deviceID, "PV1 Current", "pv1-current", "pv1Current"
),
FoxESSPower(
coordinator, name, deviceID, "PV1 Power", "pv1-power", "pv1Power"
),
FoxESSVolt(coordinator, name, deviceID, "PV1 Volt", "pv1-volt", "pv1Volt"),
FoxESSCurrent(
coordinator, name, deviceID, "PV2 Current", "pv2-current", "pv2Current"
),
FoxESSPower(
coordinator, name, deviceID, "PV2 Power", "pv2-power", "pv2Power"
),
FoxESSVolt(coordinator, name, deviceID, "PV2 Volt", "pv2-volt", "pv2Volt"),
FoxESSCurrent(
coordinator, name, deviceID, "PV3 Current", "pv3-current", "pv3Current"
),
FoxESSPower(
coordinator, name, deviceID, "PV3 Power", "pv3-power", "pv3Power"
),
FoxESSVolt(coordinator, name, deviceID, "PV3 Volt", "pv3-volt", "pv3Volt"),
FoxESSCurrent(
coordinator, name, deviceID, "PV4 Current", "pv4-current", "pv4Current"
),
FoxESSPower(
coordinator, name, deviceID, "PV4 Power", "pv4-power", "pv4Power"
),
FoxESSVolt(coordinator, name, deviceID, "PV4 Volt", "pv4-volt", "pv4Volt"),
FoxESSCurrent(
coordinator, name, deviceID, "PV5 Current", "pv5-current", "pv5Current"
),
FoxESSPower(
coordinator, name, deviceID, "PV5 Power", "pv5-power", "pv5Power"
),
FoxESSVolt(coordinator, name, deviceID, "PV5 Volt", "pv5-volt", "pv5Volt"),
FoxESSCurrent(
coordinator, name, deviceID, "PV6 Current", "pv6-current", "pv6Current"
),
FoxESSPower(
coordinator, name, deviceID, "PV6 Power", "pv6-power", "pv6Power"
),
FoxESSVolt(coordinator, name, deviceID, "PV6 Volt", "pv6-volt", "pv6Volt"),
FoxESSPower(coordinator, name, deviceID, "PV Power", "pv-power", "pvPower"),
FoxESSCurrent(
coordinator, name, deviceID, "R Current", "r-current", "RCurrent"
),
FoxESSFreq(coordinator, name, deviceID, "R Freq", "r-freq", "RFreq"),
FoxESSPower(coordinator, name, deviceID, "R Power", "r-power", "RPower"),
FoxESSPowerString(
coordinator,
name,
deviceID,
"Meter2 Power",
"meter2-power",
"meterPower2",
),
FoxESSVolt(coordinator, name, deviceID, "R Volt", "r-volt", "RVolt"),
FoxESSCurrent(
coordinator, name, deviceID, "S Current", "s-current", "SCurrent"
),
FoxESSFreq(coordinator, name, deviceID, "S Freq", "s-freq", "SFreq"),
FoxESSPower(coordinator, name, deviceID, "S Power", "s-power", "SPower"),
FoxESSVolt(coordinator, name, deviceID, "S Volt", "s-volt", "SVolt"),
FoxESSCurrent(
coordinator, name, deviceID, "T Current", "t-current", "TCurrent"
),
FoxESSFreq(coordinator, name, deviceID, "T Freq", "t-freq", "TFreq"),
FoxESSPower(coordinator, name, deviceID, "T Power", "t-power", "TPower"),
FoxESSVolt(coordinator, name, deviceID, "T Volt", "t-volt", "TVolt"),
FoxESSReactivePower(coordinator, name, deviceID),
FoxESSPowerFactor(coordinator, name, deviceID),
FoxESSTemp(
coordinator,
name,
deviceID,
"Bat Temperature",
"bat-temperature",
"batTemperature",
),
FoxESSTemp(
coordinator,
name,
deviceID,
"Bat Temperature2",
"bat-temperature2",
"batTemperature_2",
),
FoxESSTemp(
coordinator,
name,
deviceID,
"Ambient Temperature",
"ambient-temperature",
"ambientTemperation",
),
FoxESSTemp(
coordinator,
name,
deviceID,
"Boost Temperature",
"boost-temperature",
"boostTemperation",
),
FoxESSTemp(
coordinator,
name,
deviceID,
"Inv Temperature",
"inv-temperature",
"invTemperation",
),
FoxESSBatSoC(coordinator, name, deviceID, "Bat SoC", "bat-soc", "SoC"),
FoxESSBatSoC(coordinator, name, deviceID, "Bat SoC1", "bat-soc1", "SoC_1"),
FoxESSBatSoC(coordinator, name, deviceID, "Bat SoC2", "bat-soc2", "SoC_2"),
FoxESSBatSoC(coordinator, name, deviceID, "Bat SoH", "bat-soh", "SOH"),
FoxESSPower(
coordinator,
name,
deviceID,
"Inverter Bat Power",
"inv-Bat-Power",
"invBatPower",
),
FoxESSPower(
coordinator,
name,
deviceID,
"Inverter Bat Power2",
"inv-Bat-Power2",
"invBatPower_2",
),
FoxESSBatMinSoC(coordinator, name, deviceID),
FoxESSBatMinSoConGrid(coordinator, name, deviceID),
FoxESSSolarPower(coordinator, name, deviceID),
FoxESSEnergyThroughput(coordinator, name, deviceID),
FoxESSEnergySolar(coordinator, name, deviceID),
FoxESSInverter(coordinator, name, deviceID),
FoxESSPowerString(
coordinator,
name,
deviceID,
"Generation Power",
"-generation-power",
"generationPower",
),
FoxESSPowerString(
coordinator,
name,
deviceID,
"Grid Consumption Power",
"grid-consumption-power",
"gridConsumptionPower",
),
FoxESSPowerString(
coordinator,
name,
deviceID,
"FeedIn Power",
"feedIn-power",
"feedinPower",
),
FoxESSPowerString(
coordinator,
name,
deviceID,
"Bat Discharge Power",
"bat-discharge-power",
"batDischargePower",
),
FoxESSPowerString(
coordinator,
name,
deviceID,
"Bat Charge Power",
"bat-charge-power",
"batChargePower",
),
FoxESSPowerString(
coordinator, name, deviceID, "Load Power", "load-power", "loadsPower"
),
FoxESSEnergyGenerated(
coordinator,
name,
deviceID,
"Energy Generated",
"energy-generated",
"value",
),
FoxESSEnergyGenerated(
coordinator,
name,
deviceID,
"Energy Generated Month",
"energy-generated-month",
"month",
),
FoxESSEnergyGenerated(
coordinator,
name,
deviceID,
"Energy Generated Cumulative",
"energy-generated-cumulative",
"cumulative",
),
FoxESSEnergyGridConsumption(coordinator, name, deviceID),
FoxESSEnergyFeedin(coordinator, name, deviceID),
FoxESSEnergyBatCharge(coordinator, name, deviceID),
FoxESSEnergyBatDischarge(coordinator, name, deviceID),
FoxESSEnergyLoad(coordinator, name, deviceID),
FoxESSPVEnergyTotal(coordinator, name, deviceID),
FoxESSResidualEnergy(coordinator, name, deviceID),
FoxESSResponseTime(coordinator, name, deviceID),
FoxESSMaxBatChargeCurrent(coordinator, name, deviceID),
FoxESSMaxBatDischargeCurrent(coordinator, name, deviceID),
FoxESSRunningState(
coordinator,
name,
deviceID,
"Running State",
"running-state",
"runningState",
),
]
)
if ExtPV:
async_add_entities(
[
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV7 Current",
"pv7-current",
"pv7Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV7 Power", "pv7-power", "pv7Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV7 Volt", "pv7-volt", "pv7Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV8 Current",
"pv8-current",
"pv8Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV8 Power", "pv8-power", "pv8Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV8 Volt", "pv8-volt", "pv8Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV9 Current",
"pv9-current",
"pv9Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV9 Power", "pv9-power", "pv9Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV9 Volt", "pv9-volt", "pv9Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV10 Current",
"pv10-current",
"pv10Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV10 Power", "pv10-power", "pv10Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV10 Volt", "pv10-volt", "pv10Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV11 Current",
"pv11-current",
"pv11Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV11 Power", "pv11-power", "pv11Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV11 Volt", "pv11-volt", "pv11Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV12 Current",
"pv12-current",
"pv12Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV12 Power", "pv12-power", "pv12Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV12 Volt", "pv12-volt", "pv12Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV13 Current",
"pv13-current",
"pv13Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV13 Power", "pv13-power", "pv13Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV13 Volt", "pv13-volt", "pv13Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV14 Current",
"pv14-current",
"pv14Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV14 Power", "pv14-power", "pv14Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV14 Volt", "pv14-volt", "pv14Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV15 Current",
"pv15-current",
"pv15Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV15 Power", "pv15-power", "pv15Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV15 Volt", "pv15-volt", "pv15Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV16 Current",
"pv16-current",
"pv16Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV16 Power", "pv16-power", "pv16Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV16 Volt", "pv16-volt", "pv16Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV17 Current",
"pv17-current",
"pv17Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV17 Power", "pv17-power", "pv17Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV17 Volt", "pv17-volt", "pv17Volt"
),
FoxESSCurrent(
coordinator,
name,
deviceID,
"PV18 Current",
"pv18-current",
"pv18Current",
),
FoxESSPower(
coordinator, name, deviceID, "PV18 Power", "pv18-power", "pv18Power"
),
FoxESSVolt(
coordinator, name, deviceID, "PV18 Volt", "pv18-volt", "pv18Volt"
),
]
)
class GetAuth:
def get_signature(self, token, path, lang="en"):
"""
This function is used to generate a signature consisting of URL, token, and timestamp, and return a dictionary containing the signature and other information.
:param token: your key
:param path: your request path
:param lang: language, default is English.
:return: with authentication header
"""
timestamp = round(time.time() * 1000)
signature = rf"{path}\r\n{token}\r\n{timestamp}"
# or use user_agent_rotator.get_random_user_agent() for user-agent
result = {
"token": token,
"lang": lang,
"timestamp": str(timestamp),
"Content-Type": "application/json",
"signature": self.md5c(text=signature),
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/117.0.0.0 Safari/537.36",
"Connection": "close",
}
return result
@staticmethod
def md5c(text="", _type="lower"):
res = hashlib.md5(text.encode(encoding="UTF-8")).hexdigest()
if _type.__eq__("lower"):
return res
else:
return res.upper()
async def waitforAPI():
global last_api
# wait for openAPI, there is a minimum of 1 second allowed between OpenAPI query calls
# check if last_api call was less than a second ago and if so delay the balance of 1 second
now = time.time()
last = last_api
diff = now - last if last != 0 else 1
diff = round((diff + 0.2), 2)
if diff < 1:
await asyncio.sleep(diff)
_LOGGER.debug("API enforced delay, wait: %s", diff)
now = time.time()
last_api = now
return False
async def getOADeviceDetail(hass, allData, devicesn, apiKey):
await waitforAPI()
if V1_Api:
path = _ENDPOINT_OA_DEVICE_DETAIL_V1
_LOGGER.debug("Device Detail using V1 API")
else:
path = _ENDPOINT_OA_DEVICE_DETAIL
headerData = GetAuth().get_signature(token=apiKey, path=path)
path = _ENDPOINT_OA_DOMAIN + path + "?sn="
_LOGGER.debug("OADevice Detail fetch %s%s", path, devicesn)
timestamp = round(time.time() * 1000)
restOADeviceDetail = RestData(
hass,
METHOD_GET,
path + devicesn,
DEFAULT_ENCODING,
None,
headerData,
None,
None,
DEFAULT_VERIFY_SSL,
SSLCipherList.PYTHON_DEFAULT,
DEFAULT_TIMEOUT,
)
await restOADeviceDetail.async_update()
if restOADeviceDetail.data is None or restOADeviceDetail.data == "":
_LOGGER.debug("Unable to get OA Device Detail from FoxESS Cloud")
return True
else:
response = json.loads(restOADeviceDetail.data)
if response["errno"] == 0 and (response["msg"]=='success' or response["msg"]=='Operation successful'):
ResponseTime = round(time.time() * 1000) - timestamp
if ResponseTime > 0:
allData["raw"]["ResponseTime"] = ResponseTime
else:
allData["raw"]["ResponseTime"] = 0
_LOGGER.debug("OA Device Detail Good Response: %s", response["result"])
result = response["result"]
allData["addressbook"] = result
# manually poke this in as on the old cloud it was called plantname, need to keep in line with old entity name
plantName = result["stationName"]
allData["addressbook"]["plantName"] = plantName
testBattery = result["hasBattery"]
if testBattery:
_LOGGER.debug("OA Device Detail System has Battery: %s", testBattery)
else:
_LOGGER.debug("OA Device Detail System has No Battery: %s", testBattery)
allData["addressbook"][ATTR_BATTERYLIST] = "No Battery"
return False
else:
_LOGGER.error("OA Device Detail Bad Response: %s", response)
return True
async def getOADeviceList(hass, allData, devicesn, apiKey):
await waitforAPI()
path = "/op/v0/device/list"
headerData = GetAuth().get_signature(token=apiKey, path=path)
path = _ENDPOINT_OA_DOMAIN + "/op/v0/device/list"
_LOGGER.debug("OADevice List fetch %s%s", path, devicesn)
timestamp = round(time.time() * 1000)
listData = (
'{ "currentPage": 1, "pageSize": 10}'
)
restOADeviceList = RestData(
hass,
METHOD_POST,
path,
DEFAULT_ENCODING,
None,
headerData,
None,
listData,
DEFAULT_VERIFY_SSL,
SSLCipherList.PYTHON_DEFAULT,
DEFAULT_TIMEOUT,
)
await restOADeviceList.async_update()
if restOADeviceList.data is None or restOADeviceList.data == "":
_LOGGER.debug("Unable to get OA Device List from FoxESS Cloud")
return True
else:
response = json.loads(restOADeviceList.data)
if response["errno"] == 0 and (response["msg"]=='success' or response["msg"]=='Operation successful'):
ResponseTime = round(time.time() * 1000) - timestamp
if ResponseTime > 0:
allData["raw"]["ResponseTime"] = ResponseTime
else:
allData["raw"]["ResponseTime"] = 0
_LOGGER.debug("OA Device List Good Response: %s", response["result"])
result = json.loads(restOADeviceList.data)["result"]["data"]
for item in result:
variableName = item["stationName"]
_LOGGER.debug("OA Device List item: %s", item)
break
allData["addressbook"] = item
plantName = item["stationName"]
allData["addressbook"]["plantName"] = plantName
allData["addressbook"]["masterVersion"] = 'not provided'
allData["addressbook"]["managerVersion"] = 'not provided'
allData["addressbook"]["slaveVersion"] = 'not provided'
allData["addressbook"]["batteryList"] = 'not provided'
testBattery = item["hasBattery"]
if testBattery:
_LOGGER.debug("OA Device List System has Battery: %s", testBattery)
else:
_LOGGER.debug("OA Device List System has No Battery: %s", testBattery)
allData["addressbook"][ATTR_BATTERYLIST] = "No Battery"
return False
else:
_LOGGER.error("OA Device List Bad Response: %s", response)
return True
async def getOABatterySettings(hass, allData, devicesn, apiKey):
await waitforAPI() # check for api delay
path = "/op/v0/device/battery/soc/get"
headerData = GetAuth().get_signature(token=apiKey, path=path)
path = _ENDPOINT_OA_DOMAIN + _ENDPOINT_OA_BATTERY_SETTINGS
if "hasBattery" not in allData["addressbook"]:
hasBattery = False
else:
hasBattery = allData["addressbook"]["hasBattery"]
if hasBattery:
# only make this call if device detail reports battery fitted
_LOGGER.debug("OABattery Settings fetch %s %s", path, devicesn)
restOABatterySettings = RestData(
hass,
METHOD_GET,
path + devicesn,
DEFAULT_ENCODING,
None,
headerData,
None,
None,
DEFAULT_VERIFY_SSL,
SSLCipherList.PYTHON_DEFAULT,
DEFAULT_TIMEOUT,
)
await restOABatterySettings.async_update()
if restOABatterySettings.data is None:
_LOGGER.debug("Unable to get OA Battery Settings from FoxESS Cloud")
return True
else:
response = json.loads(restOABatterySettings.data)
if response["errno"] == 0 and (response["msg"]=='success' or response["msg"]=='Operation successful'):
_LOGGER.debug(
"OA Battery Settings Good Response: %s", response["result"]
)
result = response["result"]
minSoc = result["minSoc"]
minSocOnGrid = result["minSocOnGrid"]
allData["battery"]["minSoc"] = minSoc
allData["battery"]["minSocOnGrid"] = minSocOnGrid
_LOGGER.debug(
"OA Battery Settings read MinSoc: %d, MinSocOnGrid: %d",
minSoc,
minSocOnGrid,
)
return False
else:
_LOGGER.error("OA Battery Settings Bad Response: %s", response)
return True
else:
# device detail reports no battery fitted so reset these variables to show unknown
allData["battery"]["minSoc"] = None
allData["battery"]["minSocOnGrid"] = None
return False
async def getReport(hass, allData, apiKey, devicesn):
await waitforAPI() # check for api delay
path = _ENDPOINT_OA_REPORT
headerData = GetAuth().get_signature(token=apiKey, path=path)
path = _ENDPOINT_OA_DOMAIN + _ENDPOINT_OA_REPORT
_LOGGER.debug("OA Report fetch %s ", path)
now = datetime.now()
month = str(datetime.now().month) # now.strftime("%-m")
reportData = (
'{"sn":"'
+ devicesn
+ '","year":'
+ now.strftime("%Y")
+ ',"month":'
+ month
+ ',"dimension":"month","variables":["feedin","generation","gridConsumption","chargeEnergyToTal","dischargeEnergyToTal","loads","PVEnergyTotal"]}'
)
_LOGGER.debug("getReport OA request: %s", reportData)
restOAReport = RestData(
hass,
METHOD_POST,
path,
DEFAULT_ENCODING,
None,
headerData,
None,
reportData,
DEFAULT_VERIFY_SSL,
SSLCipherList.PYTHON_DEFAULT,
DEFAULT_TIMEOUT,
)
await restOAReport.async_update()
if restOAReport.data is None or restOAReport.data == "":
_LOGGER.debug("Unable to get OA Report from FoxESS Cloud")
return True
else:
# Openapi responded so process data
response = json.loads(restOAReport.data)
if response["errno"] == 0 and (response["msg"]=='success' or response["msg"]=='Operation successful'):
_LOGGER.debug(
"OA Report Data fetched OK: %s %s ", response, restOAReport.data[:350]
)
result = json.loads(restOAReport.data)["result"]
today = int(
now.strftime("%d")
) # need today as an integer to locate in the monthly report index
for item in result:
variableName = item["variable"]
# Daily reports break down the data hour by month for each day
# so locate the current days index and use that as the sum
index = 1
cumulative_total = 0
for dataItem in item["values"]:
if today == index: # we're only interested in the total for today
if dataItem != None:
cumulative_total = dataItem
else:
_LOGGER.debug("Report month fetch, None received")
break
index += 1