Repository navigation
Expand file tree
/
Copy pathgecloud.py
More file actions
3785 lines (3372 loc) · 207 KB
/
Copy pathgecloud.py
File metadata and controls
3785 lines (3372 loc) · 207 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
# -----------------------------------------------------------------------------
# Predbat Home Battery System
# Copyright Trefor Southwell 2026 - All Rights Reserved
# This application maybe used for personal use only and not for commercial use
# -----------------------------------------------------------------------------
"""GivEnergy Cloud API integration.
Direct cloud API client for GivEnergy inverters, providing real-time
status monitoring, meter data collection, and inverter control settings
management via the GivEnergy Cloud REST API.
"""
import re
import aiohttp
import pytz
from datetime import timedelta, datetime, timezone
from utils import str2time, dp1, dp2, dp4, parse_car_plan_windows, in_car_plan_window
from predbat_metrics import record_api_call
import asyncio
import math
import json
import random
from component_base import ComponentBase
from coordinator import inverter_record
from mock_base import MockBase as SharedMockBase
from control_handoff import control_mutation
"""
GE Cloud data download
"""
GE_API_URL = "https://api.givenergy.cloud/v1/"
GE_API_ACCOUNT = "account"
GE_API_INVERTER_STATUS = "inverter/{inverter_serial_number}/system-data/latest"
GE_API_INVERTER_METER = "inverter/{inverter_serial_number}/meter-data/latest"
GE_API_INVERTER_SETTINGS = "inverter/{inverter_serial_number}/settings"
GE_API_INVERTER_READ_SETTING = "inverter/{inverter_serial_number}/settings/{setting_id}/read"
GE_API_INVERTER_WRITE_SETTING = "inverter/{inverter_serial_number}/settings/{setting_id}/write"
GE_API_DEVICES = "communication-device"
GE_API_SITE = "site/{uuid}"
GE_API_DEVICE_INFO = "communication-device"
GE_API_SMART_DEVICES = "smart-device"
GE_API_SMART_DEVICE = "smart-device/{uuid}"
GE_API_SMART_DEVICE_DATA = "smart-device/{uuid}/data"
GE_API_EVC_DEVICES = "ev-charger"
GE_API_EVC_DEVICE = "ev-charger/{uuid}"
GE_API_EVC_DEVICE_DATA = "ev-charger/{uuid}/meter-data?start_time={start_time}&end_time={end_time}&meter_ids[]={meter_ids}&page=1"
GE_API_EVC_COMMANDS = "ev-charger/{uuid}/commands"
GE_API_EVC_COMMAND_DATA = "ev-charger/{uuid}/commands/{command}"
GE_API_EVC_SEND_COMMAND = "ev-charger/{uuid}/commands/{command}"
GE_API_EVC_SESSIONS = "ev-charger/{uuid}/charging-sessions?start_time={start_time}&end_time={end_time}&pageSize=32"
GE_REGISTER_BATTERY_CUTOFF_LIMIT = 75
def ge_write_response_definitive(result):
"""Accept only documented single-device success with a valid setting value.
GivEnergy's Remote Control Codes contract describes this as the device's
resulting value. This is provider completion evidence, never an exclusive
controller handoff acknowledgement. Optimistic pending_writes is not used.
"""
if not isinstance(result, dict) or result.get("success") is not True:
return False
value = result.get("value")
if isinstance(value, bool):
return True
return isinstance(value, (int, float)) and math.isfinite(value) and value >= 0
# How long the cached customer account details stay valid for before they are fetched again
ACCOUNT_MAX_AGE_MINUTES = 24 * 60
# How long to wait before retrying a failed account fetch
ACCOUNT_RETRY_MINUTES = 30
# How long the cached site details (including its export limit) stay valid for before they are fetched again
SITE_MAX_AGE_MINUTES = 12 * 60
# How long to wait before retrying a failed site fetch
SITE_RETRY_MINUTES = 30
# Under EMS control Predbat drives the plant device's slot 1 registers, so the battery inverters' own
# settings do not need re-reading every settings cycle - but they are not static either, and a slot
# changed behind Predbat's back silently overrides the EMS, so they are re-read on a slow cadence (#5103).
SETTINGS_SLOW_REFRESH_SECONDS = 60 * 60
# How often the device list is re-read, so an inverter, EMS, Gateway or EV charger added to or removed
# from the account is picked up without a restart (#5294). Must be a multiple of 60, as run() is only
# called once a minute; a cycle that finds a change polls and reads settings whatever else is due.
DEVICE_REFRESH_SECONDS = 60 * 60
# An inverter under EMS control is expected to leave its own slot 1 windows spanning the whole day so
# that they never override a command from the EMS (see #3781). Anything else is reported.
EMS_SLOT_FULL_DAY_START = "00:00"
EMS_SLOT_FULL_DAY_END = "23:59"
EMS_SLOT_FAMILIES = ("ac_charge_1", "dc_discharge_1")
# 0 Current.Export Instantaneous current flow from EV
# 1 Current.Import Instantaneous current flow to EV
# 2 Current.Offered Maximum current offered to EV
# 3 Energy.Active.Export.Register Energy exported by EV (Wh or kWh)
# 4 Energy.Active.Import.Register Energy imported by EV (Wh or kWh)
# 5 Energy.Reactive.Export.Register Reactive energy exported by EV (varh or kvarh)
# 6 Energy.Reactive.Import.Register Reactive energy imported by EV (varh or kvarh)
# 7 Energy.Active.Export.Interval Energy exported by EV (Wh or kWh)
# 8 Energy.Active.Import.Interval Energy imported by EV (Wh or kWh)
# 9 Energy.Reactive.Export.Interval Reactive energy exported by EV. (varh or kvarh)
# 10 Energy.Reactive.Import.Interval Reactive energy imported by EV. (varh or kvarh)
# 11 Frequency Instantaneous reading of powerline frequency
# 12 Power.Active.Export Instantaneous active power exported by EV. (W or kW)
# 13 Power.Active.Import Instantaneous active power imported by EV. (W or kW)
# 14 Power.Factor Instantaneous power factor of total energy flow
# 15 Power.Offered Maximum power offered to EV
# 16 Power.Reactive.Export Instantaneous reactive power exported by EV. (var or kvar)
# 17 Power.Reactive.Import Instantaneous reactive power imported by EV. (var or kvar)
# 19 SoC State of charge of charging vehicle in percentage
# 18 RPM Fan speed in RPM
# 20 Temperature Temperature reading inside Charge Point.
# 21 Voltage Instantaneous AC RMS supply voltage
EVC_DATA_POINTS = {
0: "Current.Export",
1: "Current.Import",
2: "Current.Offered",
3: "Energy.Active.Export.Register",
4: "Energy.Active.Import.Register",
5: "Energy.Reactive.Export.Register",
6: "Energy.Reactive.Import.Register",
7: "Energy.Active.Export.Interval",
8: "Energy.Active.Import.Interval",
9: "Energy.Reactive.Export.Interval",
10: "Energy.Reactive.Import.Interval",
11: "Frequency",
12: "Power.Active.Export",
13: "Power.Active.Import",
14: "Power.Factor",
15: "Power.Offered",
16: "Power.Reactive.Export",
17: "Power.Reactive.Import",
18: "RPM",
19: "SoC",
20: "Temperature",
21: "Voltage",
}
# 0 EV Charger These readings are taken by the EV charger internally
# 1 Grid Meter These readings are taken by the EM115 meter monitoring the grid, if there is one installed
# 2 PV 1 Meter These readings are taken by the EM115 meter monitoring PV generation source 1, if there is one installed
# 3 PV 2 Meter These readings are taken by the EM115 meter monitoring PV generation source 2, if there is one installed
EVC_METER_CHARGER = 0
EVC_METER_GRID = 1
EVC_METER_PV1 = 2
EVC_METER_PV2 = 3
# The charger statuses that mean a car is physically plugged in. GivEnergy reports the
# OCPP vocabulary, where every stage of a session from Preparing to Finishing has a car
# on the end of the cable - only Available and the fault states do not.
EVC_CONNECTED_STATUSES = {"preparing", "charging", "suspendedev", "suspendedevse", "finishing", "connected", "plugged_in", "charge_complete"}
# The statuses that mean no car. Listed rather than inferred from the set above so an
# unrecognised value can be reported instead of silently reading as "nothing plugged in",
# which would look exactly like a working charger that Predbat quietly ignores.
EVC_DISCONNECTED_STATUSES = {"available", "idle", "offline", "unavailable", "faulted", "reserved", "unknown"}
def evc_status_key(status):
"""Normalise a charger status into the form the status tables use.
The API has been seen returning both 'charging' and 'SuspendedEV', and a status is
only ever compared here, never displayed, so case and separator differences are
flattened rather than every spelling being listed in the tables.
"""
return str(status or "").strip().lower().replace(" ", "_").replace("-", "_")
# Commands
# ['start-charge', 'stop-charge', 'adjust-charge-power-limit', 'set-plug-and-go', 'set-session-energy-limit', 'set-schedule', 'unlock-connector', 'delete-charging-profile', 'change-mode', 'restart-charger', 'change-randomised-delay-duration', 'add-id-tags', 'delete-id-tags', 'rename-id-tag', 'installation-mode', 'setup-version', 'set-active-schedule', 'set-max-import-capacity', 'enable-front-panel-led', 'configure-inverter-control', 'perform-factory-reset', 'configuration-mode', 'enable-local-control']
# Command adjust-charge-power-limit {'min': 6, 'max': 32, 'value': 32, 'unit': 'A'}
# Command set-plug-and-go {'value': False, 'disabled': False, 'message': None}
# Command {'min': 0.1, 'max': 250, 'value': None, 'unit': 'kWh'}
# Command set-schedule {'schedules': []}
# Command unlock-connector []
# Command delete-charging-profile data None response None
# Command change-mode [{'active': False, 'available': True, 'image_path': '/images/dashboard/cards/ev/modes/eco-with-sun.png', 'title': 'Solar', 'key': 'SuperEco', 'description': 'Your vehicle will only charge when there is >1.4kW excess solar power available.'}, {'active': False, 'available': True, 'image_path': '/images/dashboard/cards/ev/modes/eco-with-sun-grid.png', 'title': 'Hybrid', 'key': 'Eco', 'description': 'Your vehicle will start charging using grid or solar at >1.4kW. As excess power becomes available, the charge rate will adjust automatically to maximise self consumption.'}, {'active': True, 'available': True, 'image_path': '/images/dashboard/cards/ev/modes/eco-with-grid.png', 'title': 'Grid', 'key': 'Boost', 'description': 'Your vehicle will charge using whichever power source is available up to the current limit you set.'}, {'active': False, 'available': False, 'image_path': '/images/dashboard/cards/ev/modes/eco-with-inverter.png', 'title': 'Inverter Control', 'key': 'ModbusSlave', 'description': 'Your vehicle will charge based upon instructions that it has been given by the GivEnergy Inverter.'}]
# Command restart-charger []
# Command change-randomised-delay-duration []
# Command add-id-tags {'id_tags': [], 'maximum_id_tags': 200}
# Command delete-id-tags []
# Command rename-id-tag []
# Command installation-mode ct_meter
# Command setup-version 1
# Command set-active-schedule {'schedule': None}
# Command set-max-import-capacity {'value': '80', 'min': 40, 'max': 100}
# Command enable-front-panel-led {'value': True}
# Command configure-inverter-control {'inverter_battery_export_split': 0, 'max_battery_discharge_power_to_evc': 0, 'mode': 'SuperEco'}
# Command perform-factory-reset []
# Command configuration-mode {'value': 'C'}
# Command enable-local-control {'value': True}
EVC_COMMAND_NAMES = {
"start-charge": "Start Charge",
"stop-charge": "Stop Charge",
"adjust-charge-power-limit": "Adjust Charge Power Limit",
"set-plug-and-go": "Set Plug and Go",
"set-session-energy-limit": "Set Session Energy Limit",
"set-schedule": "Set Schedule",
"unlock-connector": "Unlock Connector",
"delete-charging-profile": "Delete Charging Profile",
"change-mode": "Change Mode",
"restart-charger": "Restart Charger",
"change-randomised-delay-duration": "Change Randomised Delay Duration",
"add-id-tags": "Add ID Tags",
"delete-id-tags": "Delete ID Tags",
"rename-id-tag": "Rename ID Tag",
"installation-mode": "Installation Mode",
"setup-version": "Setup Version",
"set-active-schedule": "Set Active Schedule",
"set-max-import-capacity": "Set Max Import Capacity",
"enable-front-panel-led": "Enable Front Panel LED",
"configure-inverter-control": "Configure Inverter Control",
"perform-factory-reset": "Perform Factory Reset",
"configuration-mode": "Configuration Mode",
"enable-local-control": "Enable Local Control",
}
EVC_SELECT_VALUE_KEY = {
"change-mode": "mode",
"adjust-charge-power-limit": "limit",
"set-session-energy-limit": "limit",
"change-randomised-delay-duration": "delay",
"set-plug-and-go": "enabled",
}
# The two commands Predbat-led charge control drives a charger between. They are commands
# rather than modes, so there is nothing to restore on release - see release_evc_devices().
EVC_COMMAND_START = "start-charge"
EVC_COMMAND_STOP = "stop-charge"
# Where the EVC control switch is persisted, so an off survives a restart
EVC_STORAGE_MODULE = "gecloud"
EVC_CONTROL_STATE = "evc_control_state"
# Unsupported commands
EVC_BLACKLIST_COMMANDS = ["installation-mode", "perform-factory-reset", "rename-id-tag", "delete-id-tags", "change-randomised-delay-duration"]
TIMEOUT = 240
RETRIES = 10
RETRY_FACTOR = 1
MAX_THREADS = 2
MAX_START_TIME = 10 * 60
# GivEnergy setting read/write result codes. "retry" mirrors the API documentation's own
# "Potentially Successful?" column - a code marked False never clears on a repeat attempt, so
# retrying it only burns the retry budget and its backoff (issue #4896). "reason" is the label
# the failure is recorded under in the API metrics. -2 is documented as not potentially
# successful too, but an offline device does come back, so it stays retryable as it always was.
GE_SETTING_ERROR_CODES = {
-1: {"retry": True, "reason": "device_timeout", "text": "the device did not respond before the request timed out"},
-2: {"retry": True, "reason": "device_offline", "text": "the device is offline"},
-3: {"retry": False, "reason": "device_not_found", "text": "the device does not exist or your account does not have access to it"},
-4: {"retry": False, "reason": "validation_error", "text": "there were one or more validation errors"},
-5: {"retry": True, "reason": "server_error", "text": "there was a server error"},
-6: {"retry": True, "reason": "no_response", "text": "there was no response from the server the device was last connected to"},
-7: {"retry": False, "reason": "inverter_locked", "text": "inverter locked - the device is currently locked and cannot be modified"},
}
GE_SETTING_RETRY_CODES = [code for code, info in GE_SETTING_ERROR_CODES.items() if info["retry"]]
# The endpoints whose "value" carries a result code rather than a reading
GE_SETTING_ENDPOINTS = [GE_API_INVERTER_READ_SETTING, GE_API_INVERTER_WRITE_SETTING]
# The behaviour of the two GE Cloud inverter types, for the discovery record's `capabilities`: the
# seven INVERTER_DEF behaviour keys, valued as the "GEC" and "GEE" rows state them today
# (support_feedin_first is absent from both rows and defaults to False in inverter.py). Literal on
# purpose - reading the rows back would make the discovery completeness test prove nothing.
GE_CLOUD_CAPABILITIES = {
"GEC": {
"support_charge_freeze": True,
"support_discharge_freeze": True,
"support_feedin_first": False,
"can_span_midnight": True,
"charge_discharge_with_rate": False,
"charge_control_immediate": False,
"target_soc_used_for_discharge": False,
},
"GEE": {
"support_charge_freeze": True,
"support_discharge_freeze": False,
"support_feedin_first": False,
"can_span_midnight": False,
"charge_discharge_with_rate": False,
"charge_control_immediate": True,
"target_soc_used_for_discharge": False,
},
}
# Settings async_automatic_config() binds that inverter.py replaces with a dummy entity for the type
# (the row's presence flag is False), so the discovery record leaves them out. Behind an EMS the
# battery inverters' own charge/discharge enables, pause and eco switches are never driven.
GE_CLOUD_DUMMIED_SETTINGS = {
"GEC": frozenset(),
"GEE": frozenset({"scheduled_charge_enable", "scheduled_discharge_enable", "pause_mode", "inverter_mode"}),
}
# publish_registers() publishes every "date_format:H:i" register as a select whose options and state
# are HH:MM:SS
GE_CLOUD_TIME_SELECT_FORMAT = "HH:MM:SS"
# The format of the inverter_time sensor: publish_status() publishes the API's ISO timestamp
# ("2025-02-09T15:00:03Z") unchanged. The GEC/GEE rows keep "%H:%M:%S" for installs that do not use
# this component (spec D13), so the discovery record describes the sensor, not the row.
GE_CLOUD_CLOCK_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
def ge_code_message(data, code):
"""Describe a GivEnergy result code, preferring the plain-English message the API returned."""
message = data.get("message", None) if isinstance(data, dict) else None
if not message:
info = GE_SETTING_ERROR_CODES.get(code, None)
message = info["text"] if info else "unknown error"
return message
def classify_ge_failure(data, endpoint=None):
"""Classify a response body that reports a device-level failure.
GivEnergy reports these with HTTP 200, either flagging the body with success=false or just
returning a negative result code in "value" alongside a plain-English "message" (for example
-7 "Inverter Locked"); the setting endpoints use both shapes. Returns None when the body
reports no failure, otherwise a dict holding the code, its message, the metrics reason and
whether the code is worth retrying.
"""
if not isinstance(data, dict):
return None
code = data.get("value", None)
if not isinstance(code, int) or isinstance(code, bool):
code = None
known = GE_SETTING_ERROR_CODES.get(code, None) if code is not None else None
# A bare code only means failure on the setting endpoints, where the table applies -
# anywhere else a negative "value" could be a genuine reading
if data.get("success", True) and not (known and endpoint in GE_SETTING_ENDPOINTS):
return None
# An unrecognised failure keeps the caller's existing retry behaviour rather than giving up
reason = known["reason"] if known else "api_error"
retry = known["retry"] if known else True
return {"code": code, "message": ge_code_message(data, code), "reason": reason, "retry": retry}
class GECloudTerminalError(Exception):
"""Raised when the GE Cloud API reports a failure that no retry can clear.
Only codes GivEnergy documents as never succeeding on a repeat attempt (-3, -4 and -7) are
raised. A retryable failure (-1, -2, -5, -6) is recorded but its body is handed back to the
caller, so a caller that catches this can give up immediately without re-checking the code.
"""
def __init__(self, code, message, reason):
"""Record the GivEnergy result code, its message and the metrics failure reason."""
super().__init__(message)
self.code = code
self.message = message
self.reason = reason
attribute_table = {
"time": {"friendly_name": "Time", "icon": "mdi:clock", "unit_of_measurement": "Time", "state_class": "timestamp"},
"status": {"friendly_name": "Status", "icon": "mdi:alert", "unit_of_measurement": "Status"},
"solar_power": {"friendly_name": "Solar Power", "icon": "mdi:solar-power", "unit_of_measurement": "W", "device_class": "power"},
"consumption_power": {"friendly_name": "Consumption", "icon": "mdi:flash", "unit_of_measurement": "W", "device_class": "power"},
"battery_power": {"friendly_name": "Battery Power", "icon": "mdi:battery", "unit_of_measurement": "W", "device_class": "power"},
"battery_percent": {"friendly_name": "Battery Percent", "icon": "mdi:battery", "unit_of_measurement": "%", "device_class": "battery"},
"battery_temperature": {"friendly_name": "Battery Temperature", "icon": "mdi:thermometer", "unit_of_measurement": "°C", "device_class": "temperature"},
"inverter_temperature": {"friendly_name": "Inverter Temperature", "icon": "mdi:thermometer", "unit_of_measurement": "°C", "device_class": "temperature"},
"inverter_power": {"friendly_name": "Inverter Power", "icon": "mdi:flash", "unit_of_measurement": "W", "device_class": "power"},
"inverter_voltage": {"friendly_name": "Inverter Voltage", "icon": "mdi:flash", "unit_of_measurement": "V", "device_class": "voltage"},
"inverter_frequency": {"friendly_name": "Inverter Frequency", "icon": "mdi:flash", "unit_of_measurement": "Hz", "device_class": "frequency"},
"grid_power": {"friendly_name": "Grid Power", "icon": "mdi:transmission-tower", "unit_of_measurement": "W", "device_class": "power"},
"grid_voltage": {"friendly_name": "Grid Voltage", "icon": "mdi:transmission-tower", "unit_of_measurement": "V", "device_class": "voltage"},
"grid_current": {"friendly_name": "Grid Current", "icon": "mdi:transmission-tower", "unit_of_measurement": "A", "device_class": "current"},
"grid_frequency": {"friendly_name": "Grid Frequency", "icon": "mdi:transmission-tower", "unit_of_measurement": "Hz", "device_class": "frequency"},
"solar_today": {"friendly_name": "Solar Today", "icon": "mdi:solar-power", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"consumption_today": {"friendly_name": "Consumption Today", "icon": "mdi:flash", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"battery_charge_today": {"friendly_name": "Battery Charge Today", "icon": "mdi:battery", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"battery_discharge_today": {"friendly_name": "Battery Discharge Today", "icon": "mdi:battery", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"grid_import_today": {"friendly_name": "Grid Import Today", "icon": "mdi:transmission-tower", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"grid_export_today": {"friendly_name": "Grid Export Today", "icon": "mdi:transmission-tower", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"solar_total": {"friendly_name": "Solar Total", "icon": "mdi:solar-power", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"consumption_total": {"friendly_name": "Consumption Total", "icon": "mdi:flash", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"battery_charge_total": {"friendly_name": "Battery Charge Total", "icon": "mdi:battery", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"battery_discharge_total": {"friendly_name": "Battery Discharge Total", "icon": "mdi:battery", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"grid_import_total": {"friendly_name": "Grid Import Total", "icon": "mdi:transmission-tower", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"grid_export_total": {"friendly_name": "Grid Export Total", "icon": "mdi:transmission-tower", "unit_of_measurement": "kWh", "device_class": "energy", "state_class": "total"},
"max_charge_rate": {"friendly_name": "Max Charge Rate", "icon": "mdi:battery", "unit_of_measurement": "W", "device_class": "power"},
"max_inverter_rate": {"friendly_name": "Max Inverter Rate", "icon": "mdi:flash", "unit_of_measurement": "W", "device_class": "power"},
"export_limit": {"friendly_name": "Export Limit", "icon": "mdi:transmission-tower-export", "unit_of_measurement": "W", "device_class": "power"},
"battery_size": {"friendly_name": "Battery Size", "icon": "mdi:battery", "unit_of_measurement": "kWh", "device_class": "energy"},
"battery_dod": {"friendly_name": "Battery Depth of Discharge", "icon": "mdi:battery", "unit_of_measurement": "*", "device_class": "battery"},
"battery_soh": {"friendly_name": "Battery State of Health", "icon": "mdi:battery", "unit_of_measurement": "*", "device_class": "battery"},
"battery_dod_soh": {"friendly_name": "Battery Depth of Discharge Adjusted for State of Health", "icon": "mdi:battery", "unit_of_measurement": "*", "device_class": "battery"},
"model": {"friendly_name": "Model", "icon": "mdi:information", "unit_of_measurement": None},
"account": {"friendly_name": "GE Cloud Account", "icon": "mdi:account", "unit_of_measurement": None},
"timezone": {"friendly_name": "GE Cloud Account Timezone", "icon": "mdi:map-clock", "unit_of_measurement": None},
}
BASE_TIME = datetime.strptime("00:00", "%H:%M")
OPTIONS_TIME = [((BASE_TIME + timedelta(seconds=minute * 60)).strftime("%H:%M")) for minute in range(0, 24 * 60, 1)]
OPTIONS_TIME_FULL = [((BASE_TIME + timedelta(seconds=minute * 60)).strftime("%H:%M") + ":00") for minute in range(0, 24 * 60, 1)]
def regname_to_ha(name):
"""
Convert register name to HA style
"""
name = name.lower().replace(" ", "_").replace("%", "percent").replace("-", "_")
return name
def register_switch_on(value):
"""
Is a switch register value on, read the same way publish_registers() reads it for the HA entity
"""
if isinstance(value, bool):
return value
return isinstance(value, str) and value in ["on", "true", "True"]
VALIDATION_OPTIONS_PREFIX = "Value must be one of:"
def parse_validation_options(validation):
"""
Return the option labels from a 'Value must be one of: (a, b, c)' validation string, or None when it cannot be parsed
"""
if not isinstance(validation, str) or not validation.startswith(VALIDATION_OPTIONS_PREFIX) or "(" not in validation:
return None
# Split on the first '(' and drop only the final ')' so option labels that contain brackets survive intact
post = validation.split("(", 1)[1]
post = post.rsplit(")", 1)[0]
if not post.strip():
return None
# Split only on commas outside brackets so a label such as 'Pause (Battery, Grid)' stays whole
options = []
label = ""
depth = 0
for char in post:
if char == "(":
depth += 1
elif char == ")":
depth = max(depth - 1, 0)
elif char == "," and depth == 0:
options.append(label)
label = ""
continue
label += char
options.append(label)
return [option[1:] if index > 0 and option.startswith(" ") else option for index, option in enumerate(options)]
def normalise_register_time(value):
"""
Return a register time value as an HH:MM string, or None when it is not a time
"""
if not isinstance(value, str):
return None
parts = value.strip().split(":")
if len(parts) < 2:
return None
try:
return "{:02d}:{:02d}".format(int(parts[0]), int(parts[1]))
except ValueError:
return None
def find_ems_slot_overrides(registers):
"""
Return the slot 1 charge/DC discharge window registers that do not span the whole day, keyed by HA name
"""
overrides = {}
for key in registers:
entry = registers[key]
if not isinstance(entry, dict):
continue
ha_name = regname_to_ha(entry.get("name", None) or "")
value = normalise_register_time(entry.get("value", None))
if value is None:
continue
for family in EMS_SLOT_FAMILIES:
if "{}_start_time".format(family) in ha_name:
expected = EMS_SLOT_FULL_DAY_START
elif "{}_end_time".format(family) in ha_name:
expected = EMS_SLOT_FULL_DAY_END
else:
continue
if value != expected:
overrides[ha_name] = value
return overrides
def coerce_watts(value):
"""Return a non-negative power in watts taken from an API value, or None when it is not one."""
if value is None or isinstance(value, bool):
return None
if isinstance(value, str):
try:
value = float(value.strip())
except (TypeError, ValueError):
return None
if not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0:
return None
return float(value)
def parse_site_export_limit(limits):
"""
Read a site's enforced grid export power limit, in watts, from the GivEnergy site metadata.
The published API schema says a site carries import/export limits but not how one is
encoded, so every shape GivEnergy plausibly returns is accepted - a bare number, a numeric
string, or a nested object - and anything else is reported as not understood rather than
guessed at, leaving the configured/default limit in place.
The object's "enabled" flag separates an enforced curtailment from a merely declared
connection capacity, and only an enforced one is applied - confirmed across a fleet survey.
A site reports its supply rating the same way it reports a limit, so
{"import": {"enabled": False, "power": {"watts": 46000, "amps": 200}},
"export": {"enabled": True, "power": {"watts": 4500, "amps": 19.6}}} is a 200A supply whose
export really is curtailed to 4.5kW, while a disabled export at 6kW is the connection's
declared capacity and no restriction on Predbat. A site with no limit at all reports a null
import/export, which is what the published examples show.
An enforced zero is a real zero-export connection and is applied as one.
Returns:
A (watts, reason) tuple. watts is a float when an enforced limit was found and None
otherwise, with reason saying why for the log.
"""
if not isinstance(limits, dict):
return None, "the site data carries no limits"
export = limits.get("export", None)
if export is None:
return None, "the site has no export limit"
if isinstance(export, dict):
enabled = export.get("enabled", True)
if isinstance(enabled, str):
enabled = enabled.strip().lower() not in ("false", "0", "no", "off", "")
if not enabled:
return None, "the site export limit is not enforced, so it states the connection capacity rather than a curtailment"
power = export.get("power", None)
candidates = [power.get("watts", None), power.get("value", None)] if isinstance(power, dict) else [power]
candidates += [export.get("watts", None), export.get("value", None), export.get("limit", None)]
else:
candidates = [export]
for candidate in candidates:
watts = coerce_watts(candidate)
if watts is not None:
return watts, ""
return None, "the site export limit {} was not understood".format(export)
def merge_non_null(fresh, previous):
"""
Overlay a fresh API reading onto the previous one, ignoring null leaves.
GE Cloud (notably on Gateway devices) intermittently answers with HTTP 200 and a well-formed
envelope whose leaf values are explicitly null. Those nulls mean "no fresh datalog sample this
poll", not "zero" - coercing them to 0 is indistinguishable from a real idle inverter or a flat
battery, and passing None through poisons every downstream consumer.
A null leaf keeps the last good value for that field. With no previous reading to fall back on
the null is kept as None rather than dropped, so the field carries on reporting "no value" as it
does today instead of a fabricated zero (dropping the key would let a .get(field, 0) default
invent one).
"""
if fresh is None:
return previous
if not isinstance(fresh, dict):
return fresh
merged = dict(previous) if isinstance(previous, dict) else {}
for key, value in fresh.items():
if value is None:
if key not in merged:
# Never had a good reading for this field - report no value rather than a fake zero
merged[key] = None
continue
merged[key] = merge_non_null(value, merged.get(key))
return merged
class GECloudDirect(ComponentBase):
"""
GivEnergy Cloud Direct API interface
"""
# GivEnergy's cloud applies a write some seconds after accepting it; the GEC and GEE rows wait 10
WRITE_AND_POLL_SLEEP = 10
def initialize(self, ge_cloud_direct, api_key, automatic, automatic_evc=False, evc_control=False):
"""Initialise the GE Cloud Direct component"""
self.api_key = api_key
self.automatic = automatic
# Kept apart from automatic, which existing users already have on: wiring the
# chargers into the car planning registers a car and moves num_cars, so it has to
# be something a user turns on rather than something an upgrade does to them.
self.automatic_evc = automatic_evc
self.evc_control = evc_control
self.evc_control_active = False
# The runtime switch, on unless the user turns it off. Restored from storage at startup.
self.evc_control_enabled = True
self.evc_control_released = False
# What Predbat last asked each charger to do, so a poll that changes nothing sends
# nothing - every command goes through async_send_evc_command's retry loop.
self.evc_control_state = {}
self.evc_control_windows = {}
self.register_list = {}
self.settings = {}
self.status = {}
self.meter = {}
self.info = {}
self.register_entity_map = {}
self.long_poll_active = False
self.pending_writes = {}
self.evc_device = {}
self.evc_data = {}
self.evc_sessions = {}
self.evc_status_unknown = set()
self.api_fatal = False
self.api_auth_failed = False
self.auth_denied_reported = False
# Battery inverters already reported as overriding the EMS, so a standing misconfiguration
# raises the Predbat status once rather than on every settings refresh
self.ems_slot_warned = set()
# (device, key) registers whose option validation text could not be parsed, so the warning is logged once
self.validation_parse_warned = set()
# Hybrid model names whose inverter rating could not be parsed, so the fallback warning is logged once
self.model_rate_warned = set()
self.devices_dict = {}
self.device_list = []
self.ems_device = None
self.gateway_device = None
self.evc_devices_dict = {}
self.evc_device_list = []
self.settings_from_cache = False
self.default_options_stamp = None
# Devices found by the periodic device check still waiting for their default options, kept across
# cycles so a device found while read only is set up once read only ends
self.pending_default_options = set()
# An EMS turns GE Cloud Data off; what it replaced is kept so it can be put back if the EMS leaves
self.ems_disabled_ge_cloud_data = False
self.ge_cloud_data_before_ems = None
# Customer account details, including the timezone the inverter register times are expressed in
self.account = {}
self.account_timezone = None
self.account_timezone_name = None
self.account_stamp = None
self.account_fetch_stamp = None
# Site details, including the grid export limit, cached in storage between restarts
self.site = {}
self.site_id = None
self.site_export_limit = None
self.site_inverters = []
self.site_stamp = None
self.site_fetch_stamp = None
# API request metrics for monitoring
self.requests_total = 0
self.failures_total = 0
def set_account_timezone(self, account):
"""
Record the customer timezone taken from the GE Cloud account details.
The inverter start/end time registers are held in the account timezone, which is not
necessarily the timezone Predbat is running in, so it is stored here to translate them.
"""
tz_name = account.get("standard_timezone", None) or account.get("timezone", None)
if not tz_name:
self.log("GECloud: Warn: No timezone found in account details, using the Predbat timezone for register times")
return
if tz_name == self.account_timezone_name:
return
try:
account_tz = pytz.timezone(tz_name)
except pytz.exceptions.UnknownTimeZoneError:
self.log("GECloud: Warn: Unknown account timezone {}, using the Predbat timezone for register times".format(tz_name))
return
self.account_timezone = account_tz
self.account_timezone_name = tz_name
self.log("GECloud: Account timezone is {}, offset from the Predbat timezone is {} minutes".format(tz_name, self.get_timezone_offset_minutes()))
def get_timezone_offset_minutes(self):
"""
Return how many minutes ahead of the Predbat timezone the customer account timezone is right now.
Returns 0 when the account timezone is unknown, so times are left as-is.
"""
if self.account_timezone is None or self.local_tz is None:
return 0
now = datetime.now(timezone.utc)
account_offset = now.astimezone(self.account_timezone).utcoffset()
local_offset = now.astimezone(self.local_tz).utcoffset()
if account_offset is None or local_offset is None:
return 0
return int((account_offset - local_offset).total_seconds() // 60)
def shift_time_string(self, value, offset_minutes):
"""
Shift a HH:MM or HH:MM:SS register time string by the given number of minutes, wrapping at midnight.
"""
if not offset_minutes or not isinstance(value, str):
return value
parts = value.strip().split(":")
if len(parts) < 2:
return value
try:
total = int(parts[0]) * 60 + int(parts[1])
except ValueError:
return value
total = (total + offset_minutes) % (24 * 60)
shifted = "{:02d}:{:02d}".format(total // 60, total % 60)
if len(parts) > 2:
shifted += ":" + parts[2]
return shifted
def register_time_to_local(self, value):
"""
Convert a time register value from the customer account timezone into the Predbat timezone.
"""
return self.shift_time_string(value, -self.get_timezone_offset_minutes())
def local_time_to_register(self, value):
"""
Convert a time from the Predbat timezone into the customer account timezone for writing to a register.
"""
return self.shift_time_string(value, self.get_timezone_offset_minutes())
async def switch_event(self, entity_id, service):
"""
Switch event
"""
if entity_id.endswith("_gecloud_evc_control"):
self.evc_control_enabled = service == "turn_on"
self.log("GECloud: EV charger control switched {}".format("on" if self.evc_control_enabled else "off"))
await self.save_evc_control_enabled()
return
mapping = self.register_entity_map.get(entity_id, None)
if mapping:
device = mapping.get("device", None)
key = mapping.get("key", None)
if device and key:
setting = self.settings.get(device, {}).get(key, None)
if setting:
value = register_switch_on(setting.get("value", None))
new_value = value
if service == "turn_on":
new_value = True
elif service == "turn_off":
new_value = False
elif service == "toggle":
new_value = not value
# validation_rules = setting.get("validation_rules", [])
result = await self.async_write_inverter_setting(device, key, new_value)
if result and ("value" in result):
setting["value"] = result["value"]
await self.publish_registers(device, self.settings[device], select_key=key)
# Starting a force charge only imports if the AC charge gate is also on (GH#5269)
if new_value is True and regname_to_ha(setting.get("name", "")) == "enable_force_charge":
await self.ensure_ac_charge_gate(device)
else:
self.log("GECloud: Warn: Failed to write setting {} {} to {}".format(device, key, new_value))
def ac_charge_gate_keys(self, device):
"""
Return the enable_ac_charge register keys that gate grid charging alongside enable_force_charge.
Only a device that also exposes enable_force_charge has the two-switch gate (GH#5040); on any
other device enable_ac_charge is itself the scheduled charge control, so an empty list is
returned. The AC charge upper limit switches share the prefix but are a different control, so
they are excluded as enable_default_options() does. A write-only register is cached as off on
every settings read, so its state cannot be checked and it is left to enable_default_options().
"""
registers = self.settings.get(device, {})
ha_names = {key: regname_to_ha(registers[key].get("name", "")) for key in registers}
if "enable_force_charge" not in ha_names.values():
return []
return [key for key, ha_name in ha_names.items() if ("enable_ac_charge" in ha_name) and ("limit" not in ha_name) and ("writeonly" not in (registers[key].get("validation_rules", None) or []))]
def force_charge_is_charge_control(self, device):
"""
Is this device's enable_force_charge switch the one Predbat drives as scheduled_charge_enable
Only then is enable_ac_charge a static gate; if scheduled_charge_enable was bound to
enable_ac_charge by hand, Predbat turns it off to end a charge and must not turn it back on.
"""
scheduled_charge_enable = self.get_arg("scheduled_charge_enable", default=None, indirect=False)
if not isinstance(scheduled_charge_enable, list):
scheduled_charge_enable = [scheduled_charge_enable] if scheduled_charge_enable else []
force_entity = "switch.{}_gecloud_{}_enable_force_charge".format(self.prefix, device).lower()
return force_entity in {str(entity).lower() for entity in scheduled_charge_enable if entity}
def force_charge_on(self, device):
"""
Is the device's enable_force_charge register on in the cached settings
"""
registers = self.settings.get(device, {})
return any(regname_to_ha(register.get("name", "")) == "enable_force_charge" and register_switch_on(register.get("value", None)) for register in registers.values())
async def ensure_ac_charge_gate(self, device):
"""
Turn the AC charge gate back on for a device that is force charging, if something else turned it off.
enable_default_options() holds the gate on only once every 24 hours, so an Axle event, the
GivEnergy app or another integration clearing it in between left every planned grid charge
importing nothing (GH#5269). Reads the cached settings, so costs no API call when the gate is
already on. Returns True if a write was made.
Uses the live read only attribute, not just the switch, because an active Axle VPP event
forces read only through the attribute alone and the gate must be left to Axle then.
"""
if self.read_only_now() or not self.force_charge_is_charge_control(device):
return False
registers = self.settings.get(device, {})
changed = False
for key in self.ac_charge_gate_keys(device):
value = registers[key].get("value", None)
if register_switch_on(value):
continue
ha_name = regname_to_ha(registers[key].get("name", ""))
self.log("GECloud: Warn: {} is off for {} while force charge is on, so grid charging would import nothing - turning it back on".format(ha_name, device))
result = await self.async_write_inverter_setting(device, key, True)
if result and ("value" in result):
registers[key]["value"] = result["value"]
await self.publish_registers(device, registers, select_key=key)
changed = True
else:
self.log("GECloud: Warn: Failed to enable AC charge for {}".format(device))
return changed
async def number_event(self, entity_id, value):
"""
Number event
"""
mapping = self.register_entity_map.get(entity_id, None)
if mapping:
device = mapping.get("device", None)
key = mapping.get("key", None)
if device and key:
setting = self.settings.get(device, {}).get(key, None)
if setting:
try:
new_value = float(value)
except (ValueError, TypeError):
self.log("GECloud: Warn: Failed to convert {} to float".format(value))
return
validation_rules = setting.get("validation_rules", [])
if validation_rules:
for validation_rule in validation_rules:
if validation_rule.startswith("between:"):
range_min, range_max = validation_rule.split(":")[1].split(",")
if new_value < float(range_min):
new_value = float(range_min)
if new_value > float(range_max):
new_value = float(range_max)
result = await self.async_write_inverter_setting(device, key, new_value)
if result and ("value" in result):
setting["value"] = result["value"]
await self.publish_registers(device, self.settings[device], select_key=key)
else:
self.log("GECloud: Warn: Failed to write setting {} {} to {}".format(device, key, new_value))
async def select_event(self, entity_id, value):
"""
Select event
"""
mapping = self.register_entity_map.get(entity_id, None)
if mapping:
device = mapping.get("device", None)
key = mapping.get("key", None)
if device and key:
setting = self.settings.get(device, {}).get(key, None)
if setting:
new_value = value
validation_rules = setting.get("validation_rules", [])
validation = setting.get("validation", None)
options_text = None
options_values = None
if validation_rules:
for validation_rule in validation_rules:
if validation_rule.startswith("in:"):
options_values = validation_rule.split(":")[1].split(",")
if isinstance(validation, str) and validation.startswith(VALIDATION_OPTIONS_PREFIX):
options_text = parse_validation_options(validation)
if options_text is None:
self.log("GECloud: Warn: Unable to parse options for setting {} {} from validation '{}'".format(device, key, validation))
if options_text is not None:
if new_value not in options_text:
self.log("GECloud: Error: Invalid option {} for setting {} {}, valid values are {}".format(new_value, device, key, options_text))
return
elif options_values is not None:
if new_value not in options_values:
self.log("GECloud: Error: Invalid option {} for setting {} {}, valid values are {}".format(new_value, device, key, options_values))
return
is_time = mapping.get("time", False)
if is_time:
# The register is held in the customer account timezone, the value we are given is in the Predbat timezone
new_value = self.local_time_to_register(new_value)
# We actually write as HH:MM
new_value = new_value[:5]
result = await self.async_write_inverter_setting(device, key, new_value)
if result and ("value" in result):
setting["value"] = result["value"]
await self.publish_registers(device, self.settings[device], select_key=key)
else:
self.log("GECloud: Warn: Failed to write setting {} {} to {}".format(device, key, new_value))
def get_max_inverter_rate_from_model(self, model, max_charge_rate=None):
"""
GivEnergy models (descriptive names):
- All-In-One - 6kW inverter with integrated battery, should use the max_charge_rate value as the inverter rating
- Gateway - Not an inverter, should use the individual inverter values
- GIV-AC3.0. - 3kW inverter
- GIV-AIO-AC-13.5-12.0 - 12kW inverter (last decimal number is the inverter power)
- GIV-HY-10.0-G3-HV - 10kW inverter (decimal number is mid-string)
- GIV-HY3.6 - 3.6kW inverter
- GIV-HY5.0 - 5.0kW inverter
- GIV-HY-8.0-G3-HV. - 8kW inverter
- GIV-3HY-11 - 11kW 3-phase hybrid (integer rating as its own segment after 3HY)
- GIV-AIO-GW2 - Gateway variant, the trailing 2 is not a rating
- Plant EMS - Not an inverter, should use the individual inverter values
"""
# GE Cloud can send an explicit null model, which would crash every regex below
if not isinstance(model, str):
return max_charge_rate
# Trailing whitespace or a trailing '.' (GIV-HY-8.0-G3-HV.) must not defeat the segment anchors below
model_clean = model.strip().rstrip(".")
# Integer rating only as a whole segment straight after the 3-phase hybrid token (GIV-3HY-11),
# bounded by '-' or end of string so suffixes such as GW2 / G3 are never read as a rating.
# Checked before the decimal pass so a later decimal segment cannot hide the explicit 3HY rating
match = re.search(r"(?:^|-)3HY-(\d{1,2})(?=-|$)", model_clean, re.IGNORECASE)
if match:
return int(match.group(1)) * 1000
# Find all decimal numbers anywhere in the model string (e.g. 3.6, 10.0, 12.0)
# Use the last match so that e.g. GIV-AIO-AC-13.5-12.0 resolves to 12kW not 13.5kW
matches = re.findall(r"\d+\.\d+", model_clean)
if matches:
try:
max_inverter_rate = int(float(matches[-1]) * 1000)
return max_inverter_rate
except ValueError:
pass
# A hybrid with no parseable rating is using a battery rate as its AC rating, warn once per model
if "HY" in model_clean.upper() and model not in self.model_rate_warned:
fallback = "max charge rate {}W".format(max_charge_rate) if max_charge_rate is not None else "no rating"
self.log("GECloud: Warn: Unable to determine inverter rating from model '{}', using {} instead - set inverter_limit in apps.yaml if this is wrong".format(model, fallback))
self.model_rate_warned.add(model)
return max_charge_rate
async def publish_account(self, account):
"""
Publish the customer account details and the account timezone as sensors.
The account sensor uses the account name as its state; the timezone sensor uses the timezone name as its state. All remaining values are stored in a 'data' attribute.
"""
if not account:
return
entity_name = f"sensor.{self.prefix}_gecloud".lower()
account_data = {key: value for key, value in account.items() if key != "name"}
attributes = dict(attribute_table.get("account", {}))
attributes["data"] = account_data
self.dashboard_item(entity_name + "_account", state=account.get("name", "unknown"), attributes=attributes, app="gecloud")
timezone_name = self.account_timezone_name or account.get("standard_timezone", None) or account.get("timezone", None)
timezone_data = {
"timezone": account.get("timezone", None),
"standard_timezone": account.get("standard_timezone", None),
"predbat_timezone": str(self.local_tz) if self.local_tz else None,
"offset_minutes": self.get_timezone_offset_minutes(),
}