-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathha_api_controller.py
More file actions
3718 lines (3280 loc) · 159 KB
/
Copy pathha_api_controller.py
File metadata and controls
3718 lines (3280 loc) · 159 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
"""Home Assistant REST API Controller.
This controller provides the same interface as HomeAssistantController
but uses the REST API instead of direct pyscript access.
"""
import json
import logging
import re
import ssl
import time
import urllib.parse
from datetime import datetime, timedelta
from typing import ClassVar
import requests
import websocket
from . import time_utils
from .exceptions import ConsumptionForecastUnavailableError, SystemConfigurationError
from .runtime_failure_tracker import RuntimeFailureTracker
logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)
def run_request(http_method, *args, **kwargs):
"""Log the request and response for debugging purposes."""
try:
# Log the request details
logger.debug("HTTP Method: %s", http_method.__name__.upper())
logger.debug("Request Args: %s", args)
logger.debug("Request Kwargs: %s", kwargs)
# Make the HTTP request
response = http_method(*args, **kwargs)
# Log the response details
logger.debug("Response Status Code: %s", response.status_code)
logger.debug("Response Headers: %s", response.headers)
logger.debug("Response Content: %s", response.text)
return response
except Exception as e:
# Don't log at ERROR here: the caller (_api_request) doesn't yet know
# whether this attempt will be retried. It logs WARNING for retryable
# attempts and ERROR only once retries are exhausted.
logger.debug("Error during HTTP request: %s", str(e))
raise
class HomeAssistantAPIController:
"""A class for interacting with Inverter controls via Home Assistant REST API."""
failure_tracker: RuntimeFailureTracker | None
def _get_sensor_display_name(self, sensor_key: str) -> str:
"""Get display name for a sensor key from METHOD_SENSOR_MAP."""
for method_info in self.METHOD_SENSOR_MAP.values():
if method_info["sensor_key"] == sensor_key:
name = method_info["name"]
return str(name) if name else f"sensor '{sensor_key}'"
return f"sensor '{sensor_key}'"
def _get_entity_for_service(self, sensor_key: str) -> str:
"""Get entity ID for service calls with proper error handling."""
try:
entity_id, _ = self._resolve_entity_id(sensor_key)
return entity_id
except ValueError as e:
description = self._get_sensor_display_name(sensor_key)
raise ValueError(f"No entity ID configured for {description}") from e
def __init__(
self,
ha_url: str,
token: str,
sensor_config: dict | None = None,
growatt_device_id: str | None = None,
huawei_device_id: str | None = None,
):
"""Initialize the Controller with Home Assistant API access.
Args:
ha_url: Base URL of Home Assistant (default: "http://supervisor/core")
token: Long-lived access token for Home Assistant
sensor_config: Sensor configuration mapping from options.json
growatt_device_id: Growatt device ID for TOU segment operations
huawei_device_id: Huawei battery device ID for TOU period operations
"""
self.base_url = ha_url
self.token = token
self.headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
self.max_attempts = 4
self.retry_base_delay = 2 # seconds (exponential backoff: 2, 4, 8)
self.test_mode = False
# Use provided sensor configuration
self.sensors = sensor_config or {}
# Store Growatt device ID for TOU operations
self.growatt_device_id = growatt_device_id
# Store Huawei battery device ID for TOU period operations
self.huawei_device_id = huawei_device_id
# Runtime failure tracker (injected by BatterySystemManager)
self.failure_tracker = None
# Create persistent session for connection reuse (400x faster)
self.session = requests.Session()
self.session.headers.update(self.headers)
logger.info(
"Initialized HomeAssistantAPIController with %d sensor mappings",
len(self.sensors),
)
# Class-level sensor mapping - immutable mapping
METHOD_SENSOR_MAP: ClassVar[dict[str, dict[str, object]]] = {
# Battery control methods
"get_battery_soc": {
"sensor_key": "battery_soc",
"name": "Battery State of Charge",
"unit": "%",
"precision": 1,
"conversion_threshold": None,
},
"get_charging_power_rate": {
"sensor_key": "battery_charging_power_rate",
"name": "Battery Charging Power Rate",
"unit": "%",
"precision": 1,
"conversion_threshold": None,
},
"get_discharging_power_rate": {
"sensor_key": "battery_discharging_power_rate",
"name": "Battery Discharging Power Rate",
"unit": "%",
"precision": 1,
"conversion_threshold": None,
},
"get_charge_stop_soc": {
"sensor_key": "battery_charge_stop_soc",
"name": "Battery Charge Stop SOC",
"unit": "%",
"precision": 1,
"conversion_threshold": None,
},
"get_discharge_stop_soc": {
"sensor_key": "battery_discharge_stop_soc",
"name": "Battery Discharge Stop SOC",
"unit": "%",
"precision": 1,
"conversion_threshold": None,
},
"grid_charge_enabled": {
"sensor_key": "grid_charge",
"name": "Grid Charge Enabled",
"unit": "bool",
"precision": 1,
"conversion_threshold": None,
},
# Power monitoring methods
"get_pv_power": {
"sensor_key": "pv_power",
"name": "Solar Power",
"unit": "W",
"precision": 0,
"conversion_threshold": 1000,
},
"get_import_power": {
"sensor_key": "import_power",
"name": "Grid Import Power",
"unit": "W",
"precision": 0,
"conversion_threshold": 1000,
},
"get_export_power": {
"sensor_key": "export_power",
"name": "Grid Export Power",
"unit": "W",
"precision": 0,
"conversion_threshold": 1000,
},
"get_local_load_power": {
"sensor_key": "local_load_power",
"name": "Home Load Power",
"unit": "W",
"precision": 0,
"conversion_threshold": 1000,
},
"get_battery_charge_power": {
"sensor_key": "battery_charge_power",
"name": "Battery Charging Power",
"unit": "W",
"precision": 0,
"conversion_threshold": 1000,
},
"get_battery_discharge_power": {
"sensor_key": "battery_discharge_power",
"name": "Battery Discharging Power",
"unit": "W",
"precision": 0,
"conversion_threshold": 1000,
},
"get_l1_current": {
"sensor_key": "current_l1",
"name": "Current L1",
"unit": "A",
"precision": 1,
"conversion_threshold": None,
},
"get_l2_current": {
"sensor_key": "current_l2",
"name": "Current L2",
"unit": "A",
"precision": 1,
"conversion_threshold": None,
},
"get_l3_current": {
"sensor_key": "current_l3",
"name": "Current L3",
"unit": "A",
"precision": 1,
"conversion_threshold": None,
},
# Energy totals
# Home consumption forecast
"get_estimated_consumption": {
"sensor_key": "48h_avg_grid_import",
"name": "Average Hourly Power Consumption",
"unit": "W",
"precision": 1,
"conversion_threshold": 1000,
},
"get_consumption_forecast_series": {
"sensor_key": "consumption_forecast_series",
"name": "Consumption Forecast Series",
"unit": "list",
"precision": 1,
"conversion_threshold": None,
},
# Solar forecast
"get_solar_forecast": {
"sensor_key": "solar_forecast_today",
"name": "Solar Forecast",
"unit": "list",
"precision": 1,
"conversion_threshold": None,
},
"get_solar_forecast_tomorrow": {
"sensor_key": "solar_forecast_tomorrow",
"name": "Solar Forecast Tomorrow",
"unit": "list",
"precision": 1,
"conversion_threshold": None,
},
# Lifetime and meter sensors (added for abstraction)
"get_battery_charged_lifetime": {
"sensor_key": "lifetime_battery_charged",
"name": "Lifetime Total Battery Charged",
"unit": "kWh",
"precision": 1,
"conversion_threshold": None,
},
"get_battery_discharged_lifetime": {
"sensor_key": "lifetime_battery_discharged",
"name": "Lifetime Total Battery Discharged",
"unit": "kWh",
"precision": 1,
"conversion_threshold": None,
},
"get_solar_production_lifetime": {
"sensor_key": "lifetime_solar_energy",
"name": "Lifetime Total Solar Energy",
"unit": "kWh",
"precision": 1,
"conversion_threshold": None,
},
"get_grid_import_lifetime": {
"sensor_key": "lifetime_import_from_grid",
"name": "Lifetime Import from Grid",
"unit": "kWh",
"precision": 1,
"conversion_threshold": None,
},
"get_grid_export_lifetime": {
"sensor_key": "lifetime_export_to_grid",
"name": "Lifetime Total Export to Grid",
"unit": "kWh",
"precision": 1,
"conversion_threshold": None,
},
"get_load_consumption_lifetime": {
"sensor_key": "lifetime_load_consumption",
"name": "Lifetime Total Load Consumption",
"unit": "kWh",
"precision": 1,
"conversion_threshold": None,
},
"get_system_production_lifetime": {
"sensor_key": "lifetime_system_production",
"name": "Lifetime System Production",
"unit": "kWh",
"precision": 1,
"conversion_threshold": None,
},
"get_self_consumption_lifetime": {
"sensor_key": "lifetime_self_consumption",
"name": "Lifetime Self Consumption",
"unit": "kWh",
"precision": 1,
"conversion_threshold": None,
},
"get_discharge_inhibit_active": {
"sensor_key": "discharge_inhibit",
"name": "Discharge Inhibit",
"unit": "binary",
"precision": 0,
"conversion_threshold": None,
},
}
# ── Entity Discovery Architecture ─────────────────────────────────────
# HA's entity registry has three key fields per entity:
# unique_id — assigned by the integration, NEVER changes (e.g. "rkm0d7n04x_import_power")
# entity_id — the API-callable name (e.g. "sensor.rkm0d7n04x_import_power"), user CAN rename
# platform — which integration created it (e.g. "growatt_server"), NEVER changes
#
# Discovery uses unique_id + platform (both immutable) to FIND the correct
# entities regardless of user renaming. It then stores the entity_id because
# that is what HA's REST/WebSocket APIs require for reading sensor values.
# Re-running discovery after a rename will update the stored entity_id.
#
# ── BESS Sensor Key Mapping ───────────────────────────────────────────
# Each BESS key has a unique_id suffix per integration. Discovery matches
# unique_id.endswith("_<suffix>") to resolve the entity.
#
# solax_modbus unique_ids follow the pattern "{serial}_solax_{plugin_key}".
# The suffix map uses the FULL suffix including the "solax_" prefix to
# ensure exact, deterministic matching with no ambiguity.
#
# growatt_server unique_ids use "{SN}_{key}" or "{SN}-{sensor_key}".
#
# BESS key growatt_server suffix solax_modbus suffix (full)
# ───────────────────────────── ───────────────────────────────── ─────────────────────────────────
# battery_soc state_of_charge_soc solax_battery_capacity / solax_battery_soc
# battery_charge_power battery_1_charging_w solax_battery_power_charge / solax_battery_charge_power
# battery_discharge_power battery_1_discharging_w solax_battery_power_discharge / solax_battery_discharge_power
# import_power import_power solax_measured_power / solax_total_forward_power / solax_ac_power_to_user
# export_power export_power solax_grid_export / solax_total_reverse_power / solax_ac_power_to_grid
# local_load_power local_load_power solax_house_load / solax_total_load_power
# pv_power internal_wattage solax_pv_power_1 / solax_pv_power_total / solax_total_pv_power
# grid_charge charge_from_grid solax_charger_switch
# battery_charging_power_rate battery_charge_power_limit solax_ems_charging_rate
# battery_discharging_power_rate battery_discharge_power_limit solax_ems_discharging_rate
# battery_charge_stop_soc battery_charge_soc_limit solax_ems_charging_stop_soc
# battery_discharge_stop_soc soc_limit_on_grid solax_ems_discharging_stop_soc_on_grid
# lifetime_battery_charged lifetime_total_all_batteries_charged solax_battery_input_energy_total / solax_total_battery_input_energy
# lifetime_battery_discharged lifetime_total_all_batteries_discharged solax_battery_output_energy_total / solax_total_battery_output_energy
# lifetime_solar_energy lifetime_total_solar_energy solax_total_solar_energy
# lifetime_export_to_grid lifetime_total_export_to_grid solax_grid_export_total / solax_total_grid_export
# lifetime_import_from_grid lifetime_import_from_grid solax_grid_import_total / solax_total_grid_import
# lifetime_load_consumption lifetime_total_load_consumption solax_total_yield (GEN4) / solax_total_load (GEN3)
# lifetime_system_production lifetime_system_production solax_total_power_generation (GEN4) / solax_total_yield (native SolaX)
#
# GEN3-only EMS entities (MIX/SPA/SPH via solax_modbus):
# battery_charging_power_rate — solax_battery_first_charge_rate
# battery_discharging_power_rate — solax_grid_first_discharge_rate
# lifetime_self_consumption lifetime_self_consumption — (growatt_server only)
#
# SOLAX-ONLY (VPP control — native SolaX inverters):
# solax_power_control_mode — solax_remotecontrol_power_control
# solax_active_power — solax_remotecontrol_active_power
# solax_autorepeat_duration — solax_remotecontrol_autorepeat_duration
# solax_power_control_trigger — solax_remotecontrol_trigger
# solax_battery_min_soc — solax_battery_minimum_capacity_gridtied
# solax_charger_use_mode — solax_charger_use_mode (SolaX native only)
#
# GROWATT-VIA-SOLAX-ONLY (TOU time slots — Growatt MIN via solax_modbus):
# Note: plugin key="time_N_enabled" (used in unique_id) but
# name="Time N Active" (used in entity_id → *_time_N_active).
# Detection and mapping match on unique_id, so the suffix is "enabled".
# Slots 4-9 are disabled by default in HA entity registry.
# tou_time_N_enabled — solax_time_N_enabled (N=1..9)
# tou_time_N_begin — solax_time_N_begin
# tou_time_N_end — solax_time_N_end
# tou_time_N_mode — solax_time_N_mode
# tou_time_N_update — solax_time_N_update
# ───────────────────────────────────────────────────────────────────────────
# ── Per-platform suffix maps for growatt_server discovery ─────────────
#
# The growatt_server HA integration uses different sensor key prefixes
# depending on the Growatt Cloud device_type:
# - "min"/"tlx" (AC-coupled) → sensors from tlx.py → unique_id "{SN}-tlx_*"
# - "mix"/"sph" (DC-coupled) → sensors from sph.py → unique_id "{SN}-mix_*"
#
# Number/switch entities (battery limits, grid charge) exist ONLY for
# MIN inverters (V1 API). SPH has no number/switch entities.
#
# unique_id formats:
# - Sensor entities: "{SN}-{sensor_key}" (hyphen separator)
# - Number/switch entities: "{SN}_{key}" (underscore separator)
#
# The sensor key differs from the entity_id suffix because HA generates
# entity IDs from the slugified translation name, not the key.
#
# Each map includes both entity_id-based suffixes (for fallback matching)
# and unique_id sensor keys (for reliable matching).
# Growatt MIN/TLX (AC-coupled) via growatt_server cloud integration
GROWATT_MIN_SUFFIX_MAP: ClassVar[dict[str, str]] = {
# ── SOC ──────────────────────────────────────────────────────────
"state_of_charge_soc": "battery_soc", # entity_id suffix (current translation)
"statement_of_charge_soc": "battery_soc", # entity_id suffix (old translation)
"tlx_statement_of_charge": "battery_soc", # unique_id sensor key
# ── Real-time power sensors ──────────────────────────────────────
"battery_1_charging_w": "battery_charge_power", # entity_id suffix
"tlx_battery_1_charge_w": "battery_charge_power", # unique_id sensor key
"battery_1_discharging_w": "battery_discharge_power", # entity_id suffix
"tlx_battery_1_discharge_w": "battery_discharge_power", # unique_id sensor key
"import_power": "import_power", # entity_id suffix
"tlx_pac_to_user_total": "import_power", # unique_id sensor key
"export_power": "export_power", # entity_id suffix
"tlx_pac_to_grid_total": "export_power", # unique_id sensor key
"local_load_power": "local_load_power", # entity_id suffix
"tlx_pac_to_local_load": "local_load_power", # unique_id sensor key
"internal_wattage": "pv_power", # entity_id suffix
"tlx_internal_wattage": "pv_power", # unique_id sensor key
# ── Grid charge switch (MIN only, V1 API) ────────────────────────
"charge_from_grid": "grid_charge", # entity_id suffix (translation name)
"ac_charge": "grid_charge", # unique_id key / old entity_id suffix
# ── Number entities (MIN only, V1 API) ──────────────────────────
"battery_charge_power_limit": "battery_charging_power_rate",
"battery_discharge_power_limit": "battery_discharging_power_rate",
"battery_charge_soc_limit": "battery_charge_stop_soc",
# Only the on-grid variant is mapped: BESS only operates grid-tied,
# and "battery_discharge_soc_limit" (off-grid, api_key
# wdisChargeSOCLowLimit) has no effect while grid-connected — see
# #270. Matching it would silently bind a control that does nothing.
"soc_limit_on_grid": "battery_discharge_stop_soc",
# ── Lifetime energy sensors ──────────────────────────────────────
"lifetime_total_all_batteries_charged": "lifetime_battery_charged",
"tlx_all_batteries_charge_total": "lifetime_battery_charged",
"lifetime_total_all_batteries_discharged": "lifetime_battery_discharged",
"tlx_all_batteries_discharge_total": "lifetime_battery_discharged",
"lifetime_total_solar_energy": "lifetime_solar_energy",
"tlx_solar_generation_total": "lifetime_solar_energy",
"lifetime_total_export_to_grid": "lifetime_export_to_grid",
"tlx_export_to_grid_total": "lifetime_export_to_grid",
"lifetime_import_from_grid": "lifetime_import_from_grid",
"tlx_import_from_grid_total": "lifetime_import_from_grid",
"lifetime_total_load_consumption": "lifetime_load_consumption",
"mix_load_consumption_total": "lifetime_load_consumption", # TLX reuses mix_ key
"lifetime_system_production": "lifetime_system_production",
"tlx_system_production_total": "lifetime_system_production",
"lifetime_self_consumption": "lifetime_self_consumption",
"tlx_self_consumption_total": "lifetime_self_consumption",
}
# Growatt MIX/SPH (DC-coupled) via growatt_server cloud integration
# SPH reuses mix_ sensor key names from the HA integration.
# SPH power sensors are in W; MIX power sensors are in kW (but both
# use the same unique_id keys — the unit difference is in the API response).
# SPH has NO number/switch entities — battery control is via service calls.
GROWATT_SPH_SUFFIX_MAP: ClassVar[dict[str, str]] = {
# ── SOC ──────────────────────────────────────────────────────────
"state_of_charge": "battery_soc", # entity_id suffix (SPH translation)
"mix_statement_of_charge": "battery_soc", # unique_id sensor key
# ── Real-time power sensors ──────────────────────────────────────
"battery_charging": "battery_charge_power", # entity_id suffix
"mix_battery_charge": "battery_charge_power", # unique_id sensor key
"battery_discharging_w": "battery_discharge_power", # entity_id suffix
"mix_battery_discharge_w": "battery_discharge_power", # unique_id sensor key
"import_from_grid": "import_power", # entity_id suffix
"mix_import_from_grid": "import_power", # unique_id sensor key
"export_to_grid": "export_power", # entity_id suffix
"mix_export_to_grid": "export_power", # unique_id sensor key
"all_pv_wattage": "pv_power", # entity_id suffix
"mix_wattage_pv_all": "pv_power", # unique_id sensor key
# ── Lifetime energy sensors ──────────────────────────────────────
"lifetime_battery_charged": "lifetime_battery_charged", # entity_id suffix
"mix_battery_charge_lifetime": "lifetime_battery_charged", # unique_id sensor key
"lifetime_battery_discharged": "lifetime_battery_discharged", # entity_id suffix
"mix_battery_discharge_lifetime": "lifetime_battery_discharged", # unique_id
"lifetime_solar_energy": "lifetime_solar_energy", # entity_id suffix
"mix_solar_generation_lifetime": "lifetime_solar_energy", # unique_id sensor key
"lifetime_export_to_grid": "lifetime_export_to_grid", # entity_id suffix
"mix_export_to_grid_lifetime": "lifetime_export_to_grid", # unique_id sensor key
"lifetime_import_from_grid": "lifetime_import_from_grid", # entity_id suffix
"mix_import_from_grid_total": "lifetime_import_from_grid", # unique_id sensor key
"lifetime_load_consumption": "lifetime_load_consumption", # entity_id suffix
"mix_load_consumption_lifetime": "lifetime_load_consumption", # unique_id sensor key
}
# ── Octopus Energy rate event patterns ────────────────────────────────
#
# The Octopus Energy integration (BottlecapDave/HomeAssistant-OctopusEnergy)
# creates event entities for electricity and gas rate data. unique_id format:
#
# Electricity import: octopus_energy_electricity_{serial}_{mpan}_current_day_rates
# Electricity export: octopus_energy_electricity_{serial}_{mpan}_export_current_day_rates
# Gas: octopus_energy_gas_{serial}_{mprn}_current_day_rates
#
# Discovery uses regex on unique_id to match electricity entities only
# (gas entities are excluded by the ``_electricity_`` requirement).
# Named groups map directly to the BESS form field keys.
_OCTOPUS_RATE_PATTERNS: ClassVar[list[tuple[re.Pattern, str]]] = [
(
re.compile(r"octopus_energy_electricity_.+_export_current_day_rates$"),
"exportToday",
),
(
re.compile(r"octopus_energy_electricity_.+_export_next_day_rates$"),
"exportTomorrow",
),
(
re.compile(r"octopus_energy_electricity_.+(?<!export)_current_day_rates$"),
"importToday",
),
(
re.compile(r"octopus_energy_electricity_.+(?<!export)_next_day_rates$"),
"importTomorrow",
),
]
# ── Per-platform suffix maps for solax_modbus discovery ─────────────
#
# The solax_modbus integration (github.com/wills106/homeassistant-solax-modbus)
# constructs unique_ids as "{serial}_solax_{plugin_key}". Every suffix below
# is the full deterministic suffix including the "solax_" prefix.
#
# Each platform has its own map — no collisions, no remapping.
# Growatt GEN4 (MIN/MOD/MID) via solax_modbus Growatt plugin
# solax_modbus unique_id format: {user_chosen_device_name}_{register_key}
# The device name prefix is user-configurable (default "SolaX"), so suffix
# maps use only the fixed register key. The matching code uses
# endswith(f"_{suffix}") which strips any prefix.
SOLAX_GROWATT_MIN_SUFFIX_MAP: ClassVar[dict[str, str]] = {
# Real-time power
"battery_soc": "battery_soc",
"battery_charge_power": "battery_charge_power",
"battery_discharge_power": "battery_discharge_power",
"total_forward_power": "import_power", # register 3041
"total_reverse_power": "export_power", # register 3043
"pv_power_total": "pv_power", # register 1, enabled by default
"total_pv_power": "pv_power", # disabled by default
"total_load_power": "local_load_power",
# Lifetime energy
"total_battery_input_energy": "lifetime_battery_charged",
"total_battery_output_energy": "lifetime_battery_discharged",
"total_solar_energy": "lifetime_solar_energy",
"total_grid_import": "lifetime_import_from_grid",
"total_grid_export": "lifetime_export_to_grid",
"total_yield": "lifetime_load_consumption", # register 3077, "Total Load Energy"
"total_power_generation": "lifetime_system_production", # register 3051
# EMS control
"ems_charging_rate": "battery_charging_power_rate",
"ems_discharging_rate": "battery_discharging_power_rate",
"ems_charging_stop_soc": "battery_charge_stop_soc",
# Only the on-grid variant is mapped: BESS only operates grid-tied,
# and "ems_discharging_stop_soc" (off-grid, register 3037) has no
# effect while grid-connected — see #270. Matching it would
# silently bind a control that does nothing.
"ems_discharging_stop_soc_on_grid": "battery_discharge_stop_soc",
"charger_switch": "grid_charge",
# VPP remote power control (registers 30100/30407-30410, GEN3|GEN4).
# See issue #118 — verified against wills106/homeassistant-solax-modbus
# plugin_growatt.py NUMBER_TYPES/SELECT_TYPES.
"vpp_status": "growatt_vpp_status",
"vpp_remote_control": "growatt_vpp_remote_control",
"vpp_allow_ac_charging": "growatt_vpp_allow_ac_charging",
"vpp_time": "growatt_vpp_time",
"vpp_power": "growatt_vpp_power",
# TOU time slots (9 slots)
"time_1_enabled": "tou_time_1_enabled",
"time_1_begin": "tou_time_1_begin",
"time_1_end": "tou_time_1_end",
"time_1_mode": "tou_time_1_mode",
"time_1_update": "tou_time_1_update",
"time_2_enabled": "tou_time_2_enabled",
"time_2_begin": "tou_time_2_begin",
"time_2_end": "tou_time_2_end",
"time_2_mode": "tou_time_2_mode",
"time_2_update": "tou_time_2_update",
"time_3_enabled": "tou_time_3_enabled",
"time_3_begin": "tou_time_3_begin",
"time_3_end": "tou_time_3_end",
"time_3_mode": "tou_time_3_mode",
"time_3_update": "tou_time_3_update",
"time_4_enabled": "tou_time_4_enabled",
"time_4_begin": "tou_time_4_begin",
"time_4_end": "tou_time_4_end",
"time_4_mode": "tou_time_4_mode",
"time_4_update": "tou_time_4_update",
"time_5_enabled": "tou_time_5_enabled",
"time_5_begin": "tou_time_5_begin",
"time_5_end": "tou_time_5_end",
"time_5_mode": "tou_time_5_mode",
"time_5_update": "tou_time_5_update",
"time_6_enabled": "tou_time_6_enabled",
"time_6_begin": "tou_time_6_begin",
"time_6_end": "tou_time_6_end",
"time_6_mode": "tou_time_6_mode",
"time_6_update": "tou_time_6_update",
"time_7_enabled": "tou_time_7_enabled",
"time_7_begin": "tou_time_7_begin",
"time_7_end": "tou_time_7_end",
"time_7_mode": "tou_time_7_mode",
"time_7_update": "tou_time_7_update",
"time_8_enabled": "tou_time_8_enabled",
"time_8_begin": "tou_time_8_begin",
"time_8_end": "tou_time_8_end",
"time_8_mode": "tou_time_8_mode",
"time_8_update": "tou_time_8_update",
"time_9_enabled": "tou_time_9_enabled",
"time_9_begin": "tou_time_9_begin",
"time_9_end": "tou_time_9_end",
"time_9_mode": "tou_time_9_mode",
"time_9_update": "tou_time_9_update",
}
# Growatt GEN3 (MIX/SPA/SPH) via solax_modbus Growatt plugin
SOLAX_GROWATT_SPH_SUFFIX_MAP: ClassVar[dict[str, str]] = {
# Real-time power
"battery_soc": "battery_soc",
"battery_charge_power": "battery_charge_power",
"battery_discharge_power": "battery_discharge_power",
"ac_power_to_user": "import_power", # register 1015
"ac_power_to_grid": "export_power", # register 1023
"pv_power_total": "pv_power",
"total_load_power": "local_load_power",
# Lifetime energy
"total_battery_input_energy": "lifetime_battery_charged",
"total_battery_output_energy": "lifetime_battery_discharged",
"total_solar_energy": "lifetime_solar_energy",
"total_grid_import": "lifetime_import_from_grid",
"total_grid_export": "lifetime_export_to_grid",
"total_load": "lifetime_load_consumption", # register 1062
# No lifetime_system_production — BESS derives from lifetime_solar_energy
# EMS control
"battery_first_charge_rate": "battery_charging_power_rate",
"grid_first_discharge_rate": "battery_discharging_power_rate",
"battery_first_maximum_soc": "battery_charge_stop_soc",
"load_first_battery_minimum_soc": "battery_discharge_stop_soc",
"charger_switch": "grid_charge",
# VPP remote power control (registers 30100/30407-30410, GEN3|GEN4).
# Same registers as GEN4 — verified allowedtypes=GEN3|GEN4 in
# wills106/homeassistant-solax-modbus plugin_growatt.py.
"vpp_status": "growatt_vpp_status",
"vpp_remote_control": "growatt_vpp_remote_control",
"vpp_allow_ac_charging": "growatt_vpp_allow_ac_charging",
"vpp_time": "growatt_vpp_time",
"vpp_power": "growatt_vpp_power",
}
# SolaX native inverters via solax_modbus integration
SOLAX_NATIVE_SUFFIX_MAP: ClassVar[dict[str, str]] = {
# Real-time power
"battery_capacity": "battery_soc",
"battery_power_charge": "battery_charge_power",
"battery_power_discharge": "battery_discharge_power",
"measured_power": "import_power",
"grid_import": "import_power", # alternative suffix
"grid_export": "export_power",
"pv_power_1": "pv_power",
"house_load": "local_load_power",
# Lifetime energy
"battery_input_energy_total": "lifetime_battery_charged",
"battery_output_energy_total": "lifetime_battery_discharged",
"total_solar_energy": "lifetime_solar_energy",
"grid_import_total": "lifetime_import_from_grid",
"grid_export_total": "lifetime_export_to_grid",
"total_yield": "lifetime_system_production", # register 0x52, "Total Yield" (production)
# No native register for lifetime_load_consumption
# VPP control
"remotecontrol_power_control": "solax_power_control_mode",
"remotecontrol_active_power": "solax_active_power",
"remotecontrol_autorepeat_duration": "solax_autorepeat_duration",
"remotecontrol_trigger": "solax_power_control_trigger",
# Only the on-grid variant is mapped: BESS only operates grid-tied,
# and "battery_minimum_capacity" (register 0x20, general/off-grid)
# has no effect while grid-connected — see #270. Also fixes a
# pre-existing typo: upstream's key is "gridtied" (no underscore),
# not "grid_tied", so this suffix never matched before.
"battery_minimum_capacity_gridtied": "solax_battery_min_soc",
"charger_use_mode": "solax_charger_use_mode",
}
# ── Solis hybrid inverters via the Pho3niX90/solis_modbus integration ──
#
# (github.com/Pho3niX90/solis_modbus, verified against release v4.1.6).
# DOMAIN = "solis_modbus" (const.py:1). Credits SA7BNT's research and
# implementation in bess-manager-beta PR #51, re-verified here against
# the actual integration source per the add-inverter-platform skill.
#
# unique_id_generator(controller, third_value) (helpers.py:40-49) builds
# unique_id = f"solis_modbus_{serial_or_identification_or_host}_{third_value}".
#
# Control entities pass a clean string as third_value and are safely
# matched by suffix (this map, via the normal _map_registry_entities
# endswith() matching — same mechanism every other platform uses):
# - time.py:52 (TOU start/end pickers):
# unique_id_generator(controller, entity_definition.get("unique", ...))
# where entity["unique"] = f"time_entity_{register}" (time_sensors.py:63).
# - solis_binary_sensor.py:36 (TOU per-slot enable switches):
# unique_id_generator_binary(controller, register, bit_position, None)
# -> f"{register}_{bit_position}" (switch_sensors.py:207-216).
#
# IMPORTANT — verified integration bug, not an assumption: for entities
# built via SolisSensorGroup.__init__ (sensors/solis_base_sensor.py:254),
# `unique_id=unique_id_generator(controller, entity)` passes the *entire
# entity definition dict* as third_value instead of `entity["unique"]`.
# This means most read-only sensors AND all "editable" number entities
# (per-slot TOU current/cutoff-SOC, global charge/discharge stop SOC)
# get a unique_id containing the Python repr of their whole definition
# dict, e.g. ``solis_modbus_SN123_{'name': 'Battery SOC', ..., 'unique':
# 'solis_modbus_inverter_battery_soc', ...}`` — not a clean suffix.
# Present in v4.1.6 (stable) and unchanged on HEAD as of 2026-07-05;
# reported upstream as Pho3niX90/solis_modbus#<TBD>.
# These CANNOT be matched with endswith() and are handled separately by
# `_match_solis_dict_embedded_entities` (substring match on the verified
# ``'unique': '<key>'`` fragment), never by changing the shared
# `_map_registry_entities` matching logic used by every other platform.
#
# `hybrid_sensors_derived` entities (__init__.py:280) go through the
# *correct* call path (`entity.get("unique", "reserve")`) and therefore
# DO have clean, endswith()-matchable unique_ids — those are in this map.
SOLIS_SUFFIX_MAP: ClassVar[dict[str, str]] = {
# ── Real-time power (hybrid_sensors_derived — clean unique_id) ────
"solis_modbus_inverter_battery_charge_power": "battery_charge_power",
"solis_modbus_inverter_battery_discharge_power": "battery_discharge_power",
# Solis exposes only a single signed net grid power sensor (no
# separate import/export power entities, hybrid_sensors_derived
# "Grid Power Net" register 33263/33264, positive=import,
# negative=export). A suffix map key can only resolve to one BESS
# sensor key, so auto-discovery wires it to import_power only;
# export_power is left unconfigured (see docs/INVERTER_PLATFORMS.md
# Solis section) rather than guessing a second mapping for the same
# entity.
"solis_modbus_inverter_grid_power_net": "import_power",
# PV Power 1 only (hybrid_sensors_derived, register 33049/33050).
# Solis hybrids have up to 4 MPPT strings (dc_power_1..4); summing
# them into a single pv_power reading is not implemented in this
# first pass — installations with a single MPPT string get accurate
# readings, multi-string installations will under-report.
"solis_modbus_inverter_dc_power_1": "pv_power",
# ── Grid Time of Use v2 charge/discharge period times (6 slots) ───
# unique key = f"time_entity_{register}" (time_sensors.py:34-63).
"time_entity_43711": "solis_charge_start_1",
"time_entity_43713": "solis_charge_end_1",
"time_entity_43753": "solis_discharge_start_1",
"time_entity_43755": "solis_discharge_end_1",
"time_entity_43718": "solis_charge_start_2",
"time_entity_43720": "solis_charge_end_2",
"time_entity_43760": "solis_discharge_start_2",
"time_entity_43762": "solis_discharge_end_2",
"time_entity_43725": "solis_charge_start_3",
"time_entity_43727": "solis_charge_end_3",
"time_entity_43767": "solis_discharge_start_3",
"time_entity_43769": "solis_discharge_end_3",
"time_entity_43732": "solis_charge_start_4",
"time_entity_43734": "solis_charge_end_4",
"time_entity_43774": "solis_discharge_start_4",
"time_entity_43776": "solis_discharge_end_4",
"time_entity_43739": "solis_charge_start_5",
"time_entity_43741": "solis_charge_end_5",
"time_entity_43781": "solis_discharge_start_5",
"time_entity_43783": "solis_discharge_end_5",
"time_entity_43746": "solis_charge_start_6",
"time_entity_43748": "solis_charge_end_6",
"time_entity_43788": "solis_discharge_start_6",
"time_entity_43790": "solis_discharge_end_6",
# ── Grid Time of Use v2 per-slot enable switches (register 43707) ─
# unique key = f"switch_{register}_{bit_position}" (switch_sensors.py
# :207-216); actual unique_id uses unique_id_generator_binary, whose
# suffix is f"{register}_{bit_position}" (solis_binary_sensor.py:36).
# Bits 0-5 = charge periods 1-6, bits 6-11 = discharge periods 1-6
# (switch_sensors.py:176-191).
"43707_0": "solis_charge_enable_1",
"43707_1": "solis_charge_enable_2",
"43707_2": "solis_charge_enable_3",
"43707_3": "solis_charge_enable_4",
"43707_4": "solis_charge_enable_5",
"43707_5": "solis_charge_enable_6",
"43707_6": "solis_discharge_enable_1",
"43707_7": "solis_discharge_enable_2",
"43707_8": "solis_discharge_enable_3",
"43707_9": "solis_discharge_enable_4",
"43707_10": "solis_discharge_enable_5",
"43707_11": "solis_discharge_enable_6",
}
# ── Solis monitoring sensors affected by the dict-embedded unique_id bug
# (see SOLIS_SUFFIX_MAP docstring above). Matched by a Solis-only
# substring check on the verified ``'unique': '<key>'`` fragment — this
# is scoped narrowly to Solis and never touches the shared, endswith()-
# based `_map_registry_entities` used by every other platform.
# Keys are the verified "unique" field from hybrid_sensors.py (the
# *non-derived* sensor list, whose SolisSensorGroup construction path
# has the bug); values are BESS sensor keys.
SOLIS_DICT_EMBEDDED_SUFFIX_MAP: ClassVar[dict[str, str]] = {
"solis_modbus_inverter_battery_soc": "battery_soc", # hybrid_sensors.py:656
"solis_modbus_inverter_household_load_power": "local_load_power", # :725
"solis_modbus_inverter_total_battery_charge_energy": "lifetime_battery_charged", # :811
"solis_modbus_inverter_total_battery_discharge_energy": "lifetime_battery_discharged", # :841
"solis_modbus_inverter_pv_total_generation": "lifetime_solar_energy", # :155
"solis_modbus_inverter_total_energy_imported_from_grid": "lifetime_import_from_grid", # :871
"solis_modbus_inverter_total_energy_fed_into_grid": "lifetime_export_to_grid", # :901
}
SOLCAST_SUFFIX_MAP: ClassVar[dict[str, str]] = {
"total_kwh_forecast_today": "solar_forecast_today",
"total_kwh_forecast_tomorrow": "solar_forecast_tomorrow",
}
# Huawei LUNA2000 via the huawei_solar integration. unique_id format is
# f"{device.serial_number}_{register_key}" — verified against
# wlcrs/huawei_solar select.py:204, number.py:358, switch.py:200.
HUAWEI_SUFFIX_MAP: ClassVar[dict[str, str]] = {
"storage_state_of_capacity": "battery_soc",
"storage_charge_discharge_power": "battery_charge_power",
"storage_maximum_charging_power": "battery_charging_power_rate",
"storage_maximum_discharging_power": "battery_discharging_power_rate",
"storage_charging_cutoff_capacity": "battery_charge_stop_soc",
"storage_grid_charge_cutoff_state_of_charge": "battery_discharge_stop_soc",
"storage_charge_from_grid_function": "grid_charge",
"storage_working_mode_settings": "huawei_working_mode",
"active_power": "local_load_power",
}
def resolve_sensor_for_influxdb(self, sensor_key: str) -> str | None:
"""Resolve sensor key to entity ID formatted for InfluxDB (without 'sensor.' prefix).
Args:
sensor_key: The sensor key from config
Returns:
Entity ID without 'sensor.' prefix, or None if not configured
Raises:
TypeError: If sensor_key is not a string
"""
if not isinstance(sensor_key, str):
raise TypeError(f"sensor_key must be a string, got {type(sensor_key)}")
try:
entity_id, _ = self._resolve_entity_id(sensor_key)
return entity_id[7:] if entity_id.startswith("sensor.") else entity_id
except ValueError:
return None
def _resolve_entity_id(self, sensor_key: str) -> tuple[str, str]:
"""Unified entity ID resolution with consistent logic.
Args:
sensor_key: The sensor key to resolve
Returns:
tuple: (entity_id, resolution_method)
Raises:
ValueError: If sensor_key not found
"""
# First check our sensor configuration
if sensor_key in self.sensors:
entity_id = self.sensors[sensor_key]
if not entity_id or not entity_id.strip():
raise ValueError(
f"Empty entity ID configured for sensor '{sensor_key}'"
)
return entity_id, "configured"
# Require explicit configuration for all operations
# This ensures proper sensor mapping and prevents silent failures
raise ValueError(f"No entity ID configured for sensor '{sensor_key}'")
def get_method_sensor_info(self, method_name: str) -> dict:
"""Get sensor configuration info for a controller method."""
method_info = self.METHOD_SENSOR_MAP.get(method_name)
if not method_info:
return {
"method_name": method_name,
"name": method_name,
"sensor_key": None,
"entity_id": None,
"status": "unknown_method",
"error": f"Method '{method_name}' not found in sensor mapping",
}
sensor_key = str(method_info["sensor_key"])
try:
entity_id, resolution_method = self._resolve_entity_id(sensor_key)
except ValueError as e:
return {
"method_name": method_name,
"name": method_info["name"],
"sensor_key": sensor_key,
"entity_id": "Not configured",
"status": "not_configured",
"error": str(e),
"current_value": None,
}
result = {
"method_name": method_name,
"name": method_info["name"],
"sensor_key": sensor_key,
"entity_id": entity_id,
"status": "unknown",
"error": None,
"current_value": None,
"resolution_method": resolution_method,
}
try:
response = self._api_request(
"get",
f"/api/states/{entity_id}",
operation=f"Check sensor info for '{method_name}'",
category="sensor_read",
)
if not response:
result.update(
{
"status": "entity_missing",
"error": f"Entity '{entity_id}' does not exist in Home Assistant",
}
)
elif response.get("state") in ["unavailable", "unknown"]:
result.update(
{
"status": "entity_unavailable",
"error": f"Entity '{entity_id}' state is '{response.get('state')}'",
}
)
else:
result.update({"status": "ok", "current_value": response.get("state")})
except (requests.RequestException, ValueError, KeyError) as e:
result.update(
{
"status": "error",
"error": f"Failed to check entity '{entity_id}': {e!s}",
}
)
return result
def validate_methods_sensors(self, method_list: list) -> list:
"""Validate sensors for multiple methods at once."""
return [self.get_method_sensor_info(method) for method in method_list]
def get_entity_state_raw(self, entity_id: str) -> dict | None:
"""Fetch raw HA state dict for a known entity ID.
Intended for debug/export use where the caller already has a resolved
entity ID and wants the full state response without going through the
sensor-key lookup path.
Args:
entity_id: Fully-qualified HA entity ID (e.g. "sensor.battery_soc")
Returns:
Full HA state dict, or None if the entity does not exist
"""
return self._api_request(
"get",
f"/api/states/{entity_id}",
operation=f"Fetch raw state for '{entity_id}'",
category="sensor_read",
)
def _api_request(
self,
method,
path,
operation=None,
category=None,
context: dict | None = None,
optional: bool = False,
**kwargs,
):
"""Make an API request to Home Assistant with retry logic.
Args:
method: HTTP method ('get', 'post', etc.)
path: API path (without base URL)
operation: Optional human-readable operation description for failure tracking
category: Optional operation category for failure tracking
context: Optional dict of contextual parameters for failure diagnostics
optional: If True, a 404 is expected (e.g. probing a legacy/disabled
entity) and is logged at debug level instead of error
**kwargs: Additional arguments for requests