Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
6314 lines (5817 loc) · 305 KB
/
Copy path__init__.py
File metadata and controls
6314 lines (5817 loc) · 305 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
"""Solar Energy Management Integration.
This integration provides comprehensive solar energy management with:
- Real-time energy flow monitoring and optimization
- EV charging control with solar priority
- Battery management and discharge protection
- Peak load management and demand control
- Energy dashboard integration
- Sankey flow visualization
Best Practices Implementation:
- Async-first with proper error handling
- Graceful degradation for optional features
- Non-blocking initialization for better startup performance
- Service registry checks to prevent conflicts
- Comprehensive logging and diagnostics
"""
from __future__ import annotations
import json
import logging
import os
import re
from typing import TYPE_CHECKING, Any, Dict, List
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform, EVENT_HOMEASSISTANT_STARTED
from homeassistant.core import HomeAssistant, SupportsResponse, callback
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError, ServiceValidationError
from homeassistant.helpers import device_registry as dr, issue_registry as ir
from homeassistant.util import dt as dt_util
import voluptuous as vol
from homeassistant.helpers import config_validation as cv
from .coordinator.charge_pause import forget_on_mode_write
from .coordinator.install_modules import MODULE_EVIDENCE_KEYS
from .const import (
DOMAIN,
MIN_PEAK_LIMIT_KW,
MAX_PEAK_LIMIT_KW,
)
from .consts.core import DEFAULT_LOAD_MANAGEMENT_ENABLED
from .coordinator.sensor_reader import GRID_TRIGGER_HINTS
from .coordinator import SEMCoordinator
if TYPE_CHECKING:
from .devices.base import ControllableDevice
_LOGGER = logging.getLogger(__name__)
# (#901) ``sem-localize.<lang>.js`` is an ASSET, never a Lovelace resource.
# Since the #738 split, ``sem-localize.js`` is a loader that injects the
# user's own language on demand over ``/local``; the siblings must be copied
# to ``/config/www`` so that fetch resolves, and registered nowhere.
#
# Upgraded installs still carried 15 of them, registered by the pre-#738
# generate_dashboard path and refreshed by nothing (HA-PROD on 2.1.0-beta.5
# had the bundle and the loader at the current version and every sibling
# still pinned at 1.7.6-beta.13). Two costs: the same language table gets
# written from two URLs — the stale resource and the loader's fresh
# injection, last write wins — which is the #240 stale-cache class reopened
# for the siblings; and every registered resource loads at frontend boot, so
# ~1.3 MB of language tables was fetched per page for a user who needs one.
#
# One predicate, used by BOTH registration paths, so neither can re-register
# what the other just swept.
_LOCALIZE_SIBLING_RE = re.compile(r"sem-localize\.[A-Za-z]{2,3}(?:-[A-Za-z]+)?\.js$")
def _is_localize_sibling(name: str) -> bool:
"""True for ``sem-localize.<lang>.js`` — never for the loader itself.
Accepts a bare filename, a path or a full resource URL with its ``?v=``
cache-bust suffix, because the two call sites hold different shapes.
"""
return bool(_LOCALIZE_SIBLING_RE.search(str(name).split("?")[0]))
def _registrable_card_files(fnames: "list[str]") -> "list[str]":
"""The installed card files that may become Lovelace resources."""
return [f for f in fnames if not _is_localize_sibling(f)]
def _content_hash_cache_bust(card_root: str, base_url: str, version: str) -> str:
"""Compute ``{version}-{sha1(content)[:8]}`` for a dashboard card asset.
Used by every Lovelace-resource registration path so the ``?v=`` query
follows file content. A bare timestamp (the previous behaviour) stayed
constant across rsync deploys and let browsers serve a stale cached
``sem-localize.js`` even after the on-disk file was updated — surfacing
as raw translation keys on the EV charge-mode selector (#301).
``base_url`` is the ``/local/custom_components/.../card/<path>`` URL;
the trailing relative path is resolved against ``card_root`` (the
deployed copy under ``/config/www/...``). Falls back to a bare
``version`` if the file can't be read so a transient disk error still
busts the cache once and never deregisters a resource.
"""
import hashlib
rel = base_url.split("/dashboard/card/", 1)[-1]
try:
with open(os.path.join(card_root, rel), "rb") as f:
return f"{version}-{hashlib.sha1(f.read()).hexdigest()[:8]}"
except OSError:
return version
_VERSION_STORE_VERSION = 1
_VERSION_STORE_KEY_PREFIX = "sem_seen_version_"
# #656 — entry_id → the devices detached at unload, parked so
# ``async_remove_entry`` still has something to deactivate. HA runs unload
# FIRST and pops the coordinator out of ``hass.data``, so by remove time there
# is no other way back to the loads SEM is holding. The controller's registry
# is still cleared at unload (the reload-leak contract); only the detached
# device objects live here. A reload drops the stash in ``async_setup_entry``
# without deactivating anything.
_PENDING_LOAD_TEARDOWN: Dict[str, List["ControllableDevice"]] = {}
# (#949) Same shape, for the charge pacer's hold on the inverter's
# max-charge-power register: ``(entity_id, captured_value, store)`` parked at
# unload and either replayed by ``async_remove_entry`` or dropped by the next
# ``async_setup_entry``. A removed or disabled entry has no next lifetime to
# adopt the engagement, so without this the register keeps SEM's cap for good.
_PENDING_PACING_RESTORE: Dict[str, tuple] = {}
#: (#955) entry_id -> {battery_id: release recipe} stashed by unload for a
#: removal, exactly like the pacer's tuple above; a reload never pops it and
#: the next setup clears it.
_PENDING_EXPORT_RELEASE: dict = {}
# (#935) And the same for a wallbox SEM parked: the box holds a standing "no"
# — disabled contactor, 0 A stored, a persisted dead-man failsafe — which is
# the point while SEM is away for a moment, and abandonment once SEM is gone.
_PENDING_CHARGER_RELEASE: Dict[str, List[Any]] = {}
async def _maybe_emit_upgrade_notification(hass, entry) -> None:
"""Fire a one-shot persistent notification when SEM has upgraded.
Compares the integration's current ``manifest.json`` version to a
locally-stored "last seen" version from ``hass.helpers.storage.Store``
(per config entry). On version change — and only on change — emits
a persistent notification telling the user to hard-refresh the
browser. First install is silent (stored=None → record current,
skip notify) so the user doesn't see an upgrade banner on day one.
The notification message names the specific cache-bust failure
mode (raw translation keys like ``today_plan_title`` showing in
the dashboard) so the user can correlate what they see with the
advice to hard-refresh.
Failure of any sub-step (Store read/write, ``async_get_integration``,
notification service call) is non-fatal — the caller wraps this in
a ``try/except`` because a transient frontend issue should never
block coordinator setup. We log at DEBUG so a healthy install
stays quiet.
"""
from homeassistant.helpers.storage import Store
from homeassistant.loader import async_get_integration
integration = await async_get_integration(hass, DOMAIN)
current_version = str(integration.version or "unknown")
store = Store(
hass,
_VERSION_STORE_VERSION,
f"{_VERSION_STORE_KEY_PREFIX}{entry.entry_id}",
)
stored = await store.async_load() or {}
previous_version = stored.get("version")
if previous_version == current_version:
return # No change.
# Record the new version regardless of whether we notify, so the
# next setup compares against today's version.
await store.async_save({"version": current_version})
if not previous_version:
# First install — silent record.
return
# Upgrade path — fire the one-shot notification.
await hass.services.async_call(
"persistent_notification",
"create",
{
"title": f"SEM updated to v{current_version}",
"message": (
f"Solar Energy Management was upgraded from "
f"v{previous_version} to v{current_version}.\n\n"
"**Please hard-refresh your browser** "
"(Ctrl+Shift+R on Windows/Linux, Cmd+Shift+R on Mac, "
"or Shift+reload on the HA companion app) so the "
"updated dashboard cards and translations load.\n\n"
"Without a hard refresh you may see raw translation "
"keys (e.g. `today_plan_title`, `charge_mode_off`) "
"in some cards — that's HA's frontend bootstrap "
"loading from cache and not picking up the new "
"asset URLs.\n\n"
"[CHANGELOG]"
"(https://github.com/traktore-org/sem-community/"
"blob/main/CHANGELOG.md)"
),
"notification_id": (
f"sem_upgrade_{current_version.replace('.', '_')}"
),
},
blocking=False,
)
_LOGGER.info(
"SEM upgraded from v%s to v%s — emitted hard-refresh notification.",
previous_version, current_version,
)
class _SEMYAMLModeSkip(Exception):
"""Sentinel: bail out of the Lovelace resource registration block
when the user is running YAML-mode Lovelace (#283). YAML-mode
resources are read-only; the user has to add SEM's bundle to
``configuration.yaml`` themselves. Logged with the exact URLs above
the raise; the outer ``except`` clause swallows this quietly so it
doesn't get reported as a generic "could not register" warning."""
type SEMConfigEntry = ConfigEntry[SEMCoordinator]
PLATFORMS: list[Platform] = [
Platform.SENSOR,
Platform.SWITCH,
Platform.NUMBER,
Platform.BINARY_SENSOR,
Platform.SELECT,
Platform.BUTTON,
Platform.TIME,
]
# ─────────────────────────────────────────────────────────────────────
# set_option helpers (#462/#464)
# ─────────────────────────────────────────────────────────────────────
# Structural option keys — changes to these require re-instantiating
# controllers because they wire SEM to HA entities. Everything else
# (modes, thresholds, targets, tunables) is read each cycle from
# coordinator.config and can be hot-swapped without a reload.
#
# Conservative on ``ev_chargers``: any change to the list shape
# (charger added/removed/per-charger entity rewired) needs a reload
# so the actuator bindings get refreshed. Per-charger tunables inside
# the list (charge_mode, target_soc, daily_ev_target) go through the
# select.py / number.py paths instead of set_option, so they don't
# hit this list.
# #485 G5: how long an armed reload-skip snapshot stays valid. The
# listener fires within milliseconds of the runtime write that armed
# it; anything older is a leftover that must not mask a real reload.
_SKIP_RELOAD_SNAPSHOT_TTL_S = 60.0
_SET_OPTION_STRUCTURAL_KEYS: frozenset[str] = frozenset({
# #529: manual override for the battery SOC sensor when autodetect can't
# reach it (SOC on a different device than the power sensor, or a generic
# template helper). Read at SensorReader construction → must reload.
"battery_soc_sensor",
# #592/#597 — the solar/battery/grid POWER sensor overrides are read at
# SensorReader construction too (same as battery_soc_sensor), so a
# set_option change must reload for it to take effect; without this the
# override only applied on the next full restart.
"solar_production_sensor", "battery_power_sensor", "grid_power_sensor",
# (#891) the fourth source. It also decides whether the two house-meter
# SENSORS exist at all, so naming one has to reload or the entities do
# not appear until the next restart.
"house_power_sensor",
# #593: hardware battery lifetime-cycle sensor (preferred over the estimate).
"battery_cycles_sensor",
"heat_pump_relay1_entity", "heat_pump_relay2_entity",
# (#801) the ON/OFF values of a text/number/select contact — read at
# controller construction, so a change must reload like the entity itself.
"heat_pump_relay1_on_value", "heat_pump_relay1_off_value",
"heat_pump_relay2_on_value", "heat_pump_relay2_off_value",
"heat_pump_climate_entity", "heat_pump_power_sensor",
"heat_pump_temperature_sensor",
# #600 — load-device kWh energy counters (derive power when no power sensor);
# read at controller construction → reload on change.
"heat_pump_energy_sensor", "hot_water_energy_sensor",
# #602 — heat pump / hot water rated power (W), read at controller
# construction; was config-flow-only, now settable from the dashboard.
"heat_pump_rated_power", "hot_water_rated_power",
# #523: read at HeatPumpController construction, so a change must reload
# to rebuild the controller with the new relay polarity.
"heat_pump_invert_sg_ready",
"hot_water_entity", "hot_water_power_sensor",
"hot_water_temperature_sensor",
"ev_chargers",
# #523 Tier 3: the forced-discharge entity is read at battery-adapter
# construction, so changing it must reload to rebuild the adapter.
"battery_force_discharge_control_entity",
# #528: the discharge-LIMIT control entity (battery protection) is read
# from the coordinator's config snapshot, so a change must reload to take
# effect (the snapshot is rebuilt on reload).
"battery_discharge_control_entity",
# #528: the discharge-protection toggle has no runtime switch entity, so a
# set_option would otherwise hit the "unrouted → reload" path silently.
# Declare it structural so the reload is explicit (decide_battery reads it
# from the config snapshot, which is rebuilt on reload). Rarely changed.
"battery_discharge_protection_enabled",
# #523 multi-battery: per-battery control-entity lists are read at
# adapter construction too, so a change must reload.
"battery_force_discharge_entities",
"battery_discharge_control_entities",
# #523 Sessy / AC-coupled: per-battery power-strategy selects, also read
# at adapter construction.
"battery_strategy_entities",
"battery_strategy_control_entity",
# #523 AC-coupled bidirectional setpoint (charge = negative on the
# force-discharge entity) — read at adapter construction.
"battery_setpoint_bidirectional",
# (#809/#869) the setpoint model and its direction select — read at
# adapter construction like the flag above.
"battery_setpoint_model",
"battery_power_direction_entity",
"battery_direction_discharge_value",
"battery_direction_charge_value",
# (#923) ...plus every module wiring key the install-modules oracle
# reads (MODULE_EVIDENCE_KEYS, joined below): setting one through
# set_option must reload, or the module's entities wait for the next
# restart. Joined from the oracle, not listed here, so the two cannot
# drift — and so this file never names a key it must not write (#845).
}) | MODULE_EVIDENCE_KEYS
def _require_load_manager(coordinator):
"""(#913) The load manager, or the honest reason there is none.
Four service handlers used to gate on ``coordinator._load_manager`` and
answer "not initialized — wait" when it was None. Since #897 it is None
BY DEFAULT: load management ships off, so the sentence blamed the clock
for a setting, and for two of the four handlers the gate tested the
wrong precondition altogether (their own branch never touched the
manager). This helper exists for the two that genuinely need it, and
it says which of the two things is actually true.
"""
lm = getattr(coordinator, "_load_manager", None)
if lm is not None:
return lm
enabled = bool(coordinator.config.get(
"load_management_enabled", DEFAULT_LOAD_MANAGEMENT_ENABLED))
if not enabled:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="load_management_disabled",
)
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="load_management_failed_to_start",
)
def _warn_missing_charger_entities(hass, charger_name, charger_id, to_check,
charger_service=None):
"""Warn about configured charger entity_ids absent from the state
registry — DEFERRED past HA's warm-up (#763 beta.7).
At SEM's setup many upstream integrations have not loaded yet; the
old registration-time check declared onkelfu's (perfectly healthy)
wallbox switch missing and sent the diagnosis down a dead end. Run
after warm-up: entities still missing warn exactly as before —
that's the real #315/#357/#462 symptom — and entities that appeared
in the meantime log the recovery at DEBUG only. Returns the
still-missing pairs.
(#991) One of those entities is not like the others. The current
control entity is how SEM commands a `number`-driven charger, and the
only thing that can stand in for it is a brand ``charger_service``;
with neither there is no way to set this charger's current at all — and
a fallback that has nowhere to fall is an error, not a line in a list.
This is the honest place to say so: past warm-up the absence is a FACT,
where the same read at registration would have been a warm-up artefact
(the defect this issue is about).
"Has a service" is not the same question as "has a fallback". An
ENTITY-PLATFORM service (`number.set_value` and its `input_number` /
`select` twins, #462 / #485 K1) is not its own transport: it writes
THROUGH ``ev_current_control_entity or ev_charger_service_entity_id``,
current entity first. So when the current entity is the thing that
vanished, such a service falls exactly where the entity did — it is not
an alternative and must not buy silence here.
"""
missing = []
for _attr, _eid in to_check:
if not _eid:
continue
if hass.states.get(_eid) is None:
missing.append((_attr, _eid))
# (#991) No current entity and nothing that can stand in for it = no
# control method. Said before the generic warning so the ERROR is the
# first thing in the log.
_svc = str(charger_service or "").strip().lower()
_svc_is_own_transport = bool(_svc) and not (
"." in _svc
and _svc.split(".", 1)[0] in ("number", "input_number", "select")
)
_no_control = (
any(_attr == "ev_current_control_entity" for _attr, _ in missing)
and not _svc_is_own_transport
)
if _no_control:
_LOGGER.error(
"EV charger '%s' (%s): its current control entity (%s) is "
"missing past warm-up and there is no charger service that "
"could stand in for it (configured: %s) — SEM has NO way to set "
"this charger's current and will not throttle it. Check the "
"entity ID, or configure a brand charger service as the "
"fallback.",
charger_name, charger_id,
", ".join(e for a, e in missing
if a == "ev_current_control_entity"),
charger_service or "none",
)
if missing:
_LOGGER.warning(
"EV charger '%s' (%s): %d configured entity ID(s) "
"missing from HA's state registry — SEM commands to "
"these silently no-op. Likely cause: the upstream "
"integration renamed entities after a version upgrade "
"(common with Wallbox/KEBA/Easee on HA core upgrades). "
"Affected: %s",
charger_name, charger_id, len(missing),
", ".join(f"{a}={e}" for a, e in missing),
)
else:
_LOGGER.debug(
"EV charger '%s' (%s): all configured entity IDs present "
"after warm-up", charger_name, charger_id,
)
return missing
def build_welcome_message(config: dict, presence: dict | None = None) -> str:
"""The first-run checklist, describing THIS install (#805 fix 2).
The old text told everyone to "pick an EV charge mode on the EV tab",
but #595 removes that tab when no charger is configured — so the one
reader who most needed guidance (owns a wallbox, hasn't told SEM about
it) was pointed into a void and concluded the controls were missing
(#803, they uninstalled). Every line here is either about something
this install HAS, or an invitation to add what it lacks.
It also states plainly what SEM will and will not touch. The previous
wording promised "sensible defaults" while SEM was about to manage
auto-discovered devices; since #805 those are monitor-only, and saying
so is how the user can consent to it.
(#923) Both answers come from the install-modules oracle: the EV line
from ``has_managed_charger`` (the #595 tab rule), the battery line from
the setup verdict — PRESENT only, because an UNKNOWN battery must be
invited, not sent to a tab.
"""
from .coordinator.install_modules import (
Module, Presence, has_managed_charger, module_verdict,
)
if presence is None:
presence = module_verdict(config, None, False)
has_ev = has_managed_charger(config)
has_battery = presence.get(Module.BATTERY) is Presence.PRESENT
lines = ["1. Confirm solar is reporting on the Energy tab"]
if has_ev:
lines.append("2. Pick a charge mode on the EV tab "
"(solar only, min + solar, solar + cheap, always max)")
else:
lines.append("2. Add your EV charger to let SEM manage charging — "
"Settings → Devices & Services → SEM → Configure. "
"Until then SEM leaves it alone.")
if has_battery:
lines.append("3. Set your battery reserve on the Battery tab")
else:
lines.append("3. Add your home battery, if you have one — "
"same Configure screen")
return (
"👋 Welcome! Your SEM dashboard is ready at "
"[Open the SEM Dashboard](/sem-dashboard/home).\n\n"
"**First-day checklist:**\n"
+ "\n".join(lines)
+ "\n\n**What SEM does right now:** it watches, and it controls "
"only what you have configured. Devices it discovers on its own "
"are set to *monitor* until you give them a mode in the device "
"list — nothing gets switched behind your back."
)
# (#805) What "looks like a car charger" means when SEM has to guess.
# Word-ish matching on purpose: a bare substring test turns the guess into
# noise (#781 — "charge" would fire on recharge_reminder), so a marker must
# sit on a word boundary of the object_id.
CHARGER_NAME_MARKERS = (
"wallbox", "keba", "easee", "goe", "go_e", "echarger", "evse",
"zaptec", "ladefreigabe", "ladestrom", "chargepoint", "openevse",
"openwb", "heidelberg", "peblar", "charger",
)
def charger_shaped_devices(entity_ids) -> list:
"""Entity ids that look like an EV charger (#805).
A guess, and labelled as one wherever its result is shown: the point is
to turn an invisible import into an offer the user can accept or ignore,
never to act on the guess.
"""
import re
out = []
for eid in entity_ids or []:
obj = str(eid).split(".", 1)[-1].lower()
words = [w for w in re.split(r"[^a-z0-9]+", obj) if w]
if any(m in words or any(w.startswith(m) and len(w) - len(m) <= 2
for w in words)
for m in CHARGER_NAME_MARKERS):
out.append(eid)
return out
def unmanaged_charger_repair(config: dict, candidates: list):
"""Should SEM raise "found a charger it does not manage"? (#805)
Replaces the blanket ``ev_charger_not_configured`` repair, which fired
for every install without a charger — including solar-only homes that
own no car — and named nothing. This one fires only when discovery
actually found something charger-shaped, and says WHICH device, which
is the line that would have prevented #803.
Returns the repair's translation payload, or None for silence.
"""
if config.get("ev_chargers") or config.get("ev_charging_power_sensor") \
or config.get("ev_connected_sensor"):
return None
if not candidates:
return None
return {
"translation_key": "unmanaged_charger_found",
"placeholders": {"name": candidates[0], "count": str(len(candidates))},
}
def yaml_mode_repair(yaml_mode: bool, urls) -> dict | None:
"""(#799) Should SEM raise "your Lovelace is YAML-mode"?
#283 detected the case and logged the resource URLs — but a log line
is not a surface: the reporter met a dashboard full of Configuration
Error cards, reinstalled twice, and only recovered by finding that one
WARNING himself. The Repair says the same thing where a user looks,
with the block to paste.
Returns the repair's translation payload, or None for silence.
"""
if not yaml_mode or not urls:
return None
block = "\n".join(f" - url: {u}\n type: module" for u in urls)
return {
"translation_key": "lovelace_yaml_mode",
"placeholders": {"resources": block},
}
def _coerce_switch_on(value) -> bool:
"""Interpret a set_option value as a switch on/off intent.
YAML service data arrives as strings — plain truthiness turned
``"off"`` / ``"false"`` / ``"0"`` into turn_on (#485 G3).
"""
if isinstance(value, str):
return value.strip().lower() not in ("", "0", "false", "off", "no")
return bool(value)
def _merge_ev_chargers_by_id(
existing: list, incoming: list,
) -> list:
"""Merge an ``ev_chargers`` list by ``id`` rather than full-replace.
Built for the set_option service path so a partial submit from the
Config card (one charger's worth of fields) can never drop sibling
chargers from the persisted state — the bug class behind #464.
Contract:
* Each entry in ``incoming`` is merged INTO the matching entry in
``existing`` by ``id``, with incoming fields winning. Fields
present in the existing entry but absent from the incoming entry
are preserved (no key is silently removed) — with ONE exception:
an incoming ``charge_mode`` other than ``off`` drops the (#980)
pause record, ``pause_charging_until`` / ``pause_resume_mode``. A
pause is Off; a charger written into another mode carries none.
* Existing chargers whose ``id`` is NOT in the incoming list are
kept verbatim. This is the actual fix for the cross-talk: a
one-charger update never affects siblings.
* Incoming chargers without a matching existing ``id`` (a fresh
add) are appended verbatim.
* Non-dict entries on either side are skipped (defensive).
* Output preserves the existing order; new chargers are appended.
Pure function — no I/O, no HA dependencies. Tested in
``tests/test_set_option_smart_merge.py``.
"""
incoming_by_id: dict[str, dict] = {}
new_ids: list[str] = []
existing_ids = {
c.get("id") for c in (existing or []) if isinstance(c, dict)
}
for inc in incoming or []:
if not isinstance(inc, dict):
continue
cid = inc.get("id")
if not cid:
# Id-less entries are untargetable ghosts: per-charger writes
# match on ``id``, and at registration a ghost gets assigned a
# positional ``ev_charger_<idx>`` id that can collide with a
# real sibling. The Config card's nested editors used to
# materialize such entries (``newChargers[idx] = {}``) — drop
# them instead of appending.
_LOGGER.warning(
"Dropping id-less ev_chargers entry from merge: %s",
dict(inc),
)
continue
if cid in incoming_by_id:
incoming_by_id[cid].update(inc)
else:
incoming_by_id[cid] = dict(inc)
if cid not in existing_ids:
new_ids.append(cid)
# EXISTING order is the output order (#485 G2): charger list order
# is load-bearing — index 0 is the fleet primary for the strategy
# sensors and default surplus priorities derive from the position.
# The previous incoming-first iteration let a partial submit (or
# the setup-time heal, whose ``incoming`` is the poisoned options
# list) silently reorder the fleet.
merged: list[dict] = []
merged_ids: set[str] = set()
for c in existing or []:
if not isinstance(c, dict):
continue
cid = c.get("id")
if not cid or cid in merged_ids:
continue
base = dict(c)
if cid in incoming_by_id:
inc = incoming_by_id[cid]
base.update(inc)
if "charge_mode" in inc:
forget_on_mode_write(base, "charge_mode", inc["charge_mode"])
merged.append(base)
merged_ids.add(cid)
for cid in new_ids:
fresh = dict(incoming_by_id[cid])
forget_on_mode_write(fresh, "charge_mode", fresh.get("charge_mode"))
merged.append(fresh)
return merged
def persist_per_charger_option(
hass, entry, coordinator, charger_id: str, key: str, value,
) -> None:
"""Persist ONE per-charger option without an integration reload.
Single write path for every per-charger entity platform (#485 K2 —
select/number/time each carried a ~30-line copy of this hardening,
and the time.py copy was missed by the original #469 patch round,
clobbering ev_chargers until v1.7.3-beta.5):
* Copies charger dicts — in-place mutation leaves entry.options
unchanged, so async_update_entry never persists (#245).
* Falls back to ``entry.data.ev_chargers`` when options lacks the
key — otherwise ``[]`` is written back and the ``{**data,
**options}`` merge hides every charger on the next reload.
* Recovers THIS charger from entry.data when a partially poisoned
options list dropped its id (#462/#464) instead of silently
no-op'ing the write.
* Mirrors into ``coordinator.config`` and arms the reload-skip
snapshot before the entry write.
* (#980) A ``charge_mode`` other than ``off`` drops the pause record in
the same write — ``charge_pause.forget_on_mode_write``, the one rule
both config writers apply (see ``_merge_ev_chargers_by_id``).
"""
new_options = {**(entry.options or {})}
data_chargers = (entry.data or {}).get("ev_chargers") or []
source_chargers = new_options.get("ev_chargers") or data_chargers
ev_chargers = [dict(c) for c in source_chargers if isinstance(c, dict)]
for charger in ev_chargers:
if charger.get("id") == charger_id:
charger[key] = value
forget_on_mode_write(charger, key, value) # (#980)
break
else:
recovered = next(
(dict(c) for c in data_chargers
if isinstance(c, dict) and c.get("id") == charger_id),
{"id": charger_id},
)
recovered[key] = value
forget_on_mode_write(recovered, key, value) # (#980)
ev_chargers.append(recovered)
_LOGGER.warning(
"Charger '%s' was missing from the stored ev_chargers list "
"(ids: %s) — recovered it from entry.data so the %s write "
"isn't lost",
charger_id,
[c.get("id") for c in ev_chargers[:-1]],
key,
)
new_options["ev_chargers"] = ev_chargers
if isinstance(getattr(coordinator, "config", None), dict):
coordinator.config.update({**(entry.data or {}), **new_options})
_refresh_runtime_config(coordinator) # #547: apply without reload
coordinator._skip_options_reload = new_options
hass.config_entries.async_update_entry(entry, options=new_options)
def _refresh_runtime_config(coordinator) -> None:
"""Push construction-cached scalars into live controllers (#547).
The ``persist_*`` writers update ``coordinator.config`` in place and arm
``_skip_options_reload`` so the entry write does NOT trigger a reload —
which means any knob cached on a controller at construction would stay
stale until a manual reload. Mirror ``async_update_config``'s refresh so
those no-reload writes apply immediately too. Defensive: never let a
refresh hiccup break the option persist itself.
"""
# (#637) a changed mobile_notification_service must re-run service
# detection — the notifier caches validation on first send (#47).
_nm = getattr(coordinator, "_notification_manager", None)
if _nm is not None:
_nm._mobile_service_checked = False
fn = getattr(coordinator, "refresh_runtime_config", None)
if callable(fn):
try:
fn()
except Exception: # noqa: BLE001 — refresh must never break persist
_LOGGER.debug("refresh_runtime_config failed", exc_info=True)
def _seed_legionella_time(coordinator, hw_device) -> None:
"""(#640) Seed the hot-water legionella timestamp AT registration.
The old first-refresh restore ran BEFORE the device was registered —
always a no-op — so a None timestamp read as 999 h overdue and every
restart forced a grid-powered 65°C disinfection cycle (audit class 14).
Stored time → restore; fresh install / unparsable → seed NOW so the
first cycle is ~interval_hours away, not immediate. Idempotent across
reloads (re-seeds from the same persisted value)."""
from homeassistant.util import dt as dt_util
try:
stored = coordinator._storage.get_legionella_time() \
if getattr(coordinator, "_storage", None) else None
ts = dt_util.parse_datetime(stored) if stored else None
hw_device.record_legionella_cycle(ts or dt_util.now())
except (ValueError, TypeError):
hw_device.record_legionella_cycle(dt_util.now())
def persist_global_option(hass, entry, coordinator, key: str, value) -> None:
"""Persist ONE scalar option key without an integration reload (#523).
Used by the SINGLE-battery mode/reserve entities (``select.sem_battery_mode``
/ ``number.sem_battery_reserve_soc``), which write the global
``battery_mode`` / ``battery_reserve_soc`` keys rather than the per-battery
list. Same no-reload contract as the per-charger / per-battery paths.
"""
new_options = {**(entry.options or {})}
new_options[key] = value
if isinstance(getattr(coordinator, "config", None), dict):
coordinator.config.update({**(entry.data or {}), **new_options})
_refresh_runtime_config(coordinator) # #547: apply without reload
coordinator._skip_options_reload = new_options
hass.config_entries.async_update_entry(entry, options=new_options)
def persist_per_battery_option(
hass, entry, coordinator, idx: int, list_key: str, value, count: int,
) -> None:
"""Persist ONE per-battery option without an integration reload (#523).
The battery-side mirror of :func:`persist_per_charger_option`, but
POSITIONAL — per-battery control lives in idx-aligned list keys
(``battery_modes`` / ``battery_reserve_socs``) parallel to the Energy
Dashboard ``battery_power_list`` order, not an id-keyed dict list. The
list is padded to ``count`` so a write to battery 2 never drops
battery 1, and the no-reload contract (copy options, mirror into
``coordinator.config``, arm the reload-skip snapshot) matches the
charger path so a live mode flip doesn't bounce the integration.
"""
new_options = {**(entry.options or {})}
src = new_options.get(list_key)
if not isinstance(src, list):
src = (entry.data or {}).get(list_key)
lst = list(src) if isinstance(src, list) else []
while len(lst) < count:
lst.append(None)
if 0 <= idx < len(lst):
lst[idx] = value
new_options[list_key] = lst
if isinstance(getattr(coordinator, "config", None), dict):
coordinator.config.update({**(entry.data or {}), **new_options})
_refresh_runtime_config(coordinator) # #547: apply without reload
coordinator._skip_options_reload = new_options
hass.config_entries.async_update_entry(entry, options=new_options)
def _heal_ev_chargers_options(
data_chargers: list | None, opts_chargers: list | None,
) -> list | None:
"""Reconcile a poisoned ``entry.options.ev_chargers`` against entry.data.
v1.7.2 through v1.7.3-beta.3 builds could corrupt the options-side
charger list in several ways: the naive set_option full-replace from a
stale Config-card cache (#464), the pre-#469 ``[]`` clobber in the
per-charger select/number writers, the pre-beta.4 smart-merge
fall-through, and the setup-time auto-discovery reseed that plants a
single ``id: "ev_charger"`` entry when the merged list comes up empty.
Once poisoned, the merge ``{**data, **options}`` hides data-side
chargers forever and per-charger writes for the missing ids silently
no-op — the "charger 2 does nothing" symptom (#462/#464).
Heals by union-by-id: options-side fields win per charger, chargers
that only exist in ``entry.data`` are restored, id-less ghost entries
are dropped. Returns the healed list, or ``None`` when the stored list
is already complete (no write needed). Pure function — tested in
``tests/test_ev_chargers_storage_heal.py``.
"""
cleaned = [
c for c in (opts_chargers or [])
if isinstance(c, dict) and c.get("id")
]
healed = _merge_ev_chargers_by_id(data_chargers or [], cleaned)
if healed == list(opts_chargers or []):
return None
return healed
#: (#876) The Energy-Dashboard ENERGY COUNTERS, and only those.
#: ``EnergyDashboardConfig.to_dict()`` also carries power sensors and
#: ``has_*`` flags; those are live steering inputs the coordinator resolves
#: itself every cycle, and a migration that silently rewrote them would be a
#: far larger promise than the one being made here.
_ENERGY_COUNTER_KEYS = (
"solar_energy_sensor",
"grid_import_energy_sensor",
"grid_export_energy_sensor",
"battery_charge_energy_sensor",
"battery_discharge_energy_sensor",
)
async def async_migrate_entry(hass: HomeAssistant, entry: SEMConfigEntry) -> bool:
"""Migrate old config entry data to current schema.
Migrations:
- v1 → v2 (#98): `battery_priority_soc` semantics changed from
legacy 3-zone "battery target before EV" (default 80) to 4-zone
"Zone 1 floor: below this all solar → battery, EV blocked"
(default 30). Existing entries that still carry the legacy 80%
get remapped down to 30% so the 4-zone strategy actually leaves
Zone 1 on a normally-charged battery.
"""
_LOGGER.info(
"Migrating SEM config entry from version %s.%s",
entry.version, entry.minor_version
)
# Accumulators threaded across all migration steps. Each step starts
# from these (not from ``entry.options`` / ``entry.data``) so a
# multi-version upgrade (e.g. v3 → v5 in one call) doesn't lose the
# earlier step's mutations. Pre-#277 each step read ``entry.options``
# afresh; in real HA ``async_update_entry`` mutates the entry and the
# next read picks up the change, but in tests (and in any harness
# mocking the entry) the second step then overwrote the first. The
# explicit accumulator makes the chain deterministic on both paths.
accumulated_data = {**entry.data}
accumulated_options = {**entry.options}
if entry.version < 2:
try:
from .consts.core import (
DEFAULT_BATTERY_BUFFER_SOC,
DEFAULT_BATTERY_AUTO_START_SOC,
)
new_data = {**accumulated_data}
new_options = {**accumulated_options}
legacy_priority = max(
new_options.get("battery_priority_soc") if new_options.get("battery_priority_soc") is not None else 0,
new_data.get("battery_priority_soc") if new_data.get("battery_priority_soc") is not None else 0,
)
# Anything ≥ 50 is the legacy 3-zone meaning — remap.
if legacy_priority >= 50:
_LOGGER.warning(
"Migrating battery_priority_soc %s → 30 (4-zone semantics, see #98)",
legacy_priority,
)
new_data["battery_priority_soc"] = 30
new_options.pop("battery_priority_soc", None)
# Seed any 4-zone keys missing or null on legacy entries so the
# number entities boot with sensible state.
for key, default in (
("battery_buffer_soc", DEFAULT_BATTERY_BUFFER_SOC),
("battery_auto_start_soc", DEFAULT_BATTERY_AUTO_START_SOC),
):
if new_data.get(key) is None:
new_data[key] = default
hass.config_entries.async_update_entry(
entry,
data=new_data,
options=new_options,
version=2,
minor_version=1,
)
accumulated_data, accumulated_options = new_data, new_options
except Exception as e:
_LOGGER.error(
"Migration from v%s failed — keeping original config: %s",
entry.version, e,
)
return False
if entry.version < 3:
try:
# v2 → v3: Wrap flat ev_* keys into ev_chargers list for multi-charger support
new_data = {**accumulated_data}
new_options = {**accumulated_options}
full = {**new_data, **new_options}
# Only migrate if flat EV keys exist and ev_chargers doesn't
if full.get("ev_charging_power_sensor") and "ev_chargers" not in full:
_EV_FLAT_KEYS = [
"ev_connected_sensor", "ev_charging_sensor",
"ev_charging_power_sensor", "ev_charger_service",
"ev_charger_service_entity_id", "ev_current_control_entity",
"ev_current_sensor", "ev_total_energy_sensor",
"ev_session_energy_sensor", "ev_service_param_name",
"ev_service_device_id", "ev_start_stop_entity",
"ev_charge_mode_entity", "ev_charge_mode_start",
"ev_charge_mode_stop", "ev_start_service",
"ev_start_service_data", "ev_stop_service",
"ev_stop_service_data", "ev_charger_needs_cycle",
"ev_surplus_priority", "ev_load_priority",
]
charger_0 = {"id": "ev_charger", "name": "EV Charger"}
for k in _EV_FLAT_KEYS:
val = new_options.get(k) or new_data.get(k)
if val is not None:
charger_0[k] = val
new_options["ev_chargers"] = [charger_0]
_LOGGER.info(
"Migrated flat EV config to ev_chargers list (1 charger)"
)
hass.config_entries.async_update_entry(
entry,
data=new_data,
options=new_options,
version=3,
minor_version=1,
)
accumulated_data, accumulated_options = new_data, new_options
except Exception as e:
_LOGGER.error(
"Migration from v%s to v3 failed — keeping original config: %s",
entry.version, e,
)
return False
if entry.version < 4:
try:
# v3 → v4 (#255): per-charger entities are becoming the source of truth, so
# the duplicate GLOBAL EV settings will be removed. Seed each charger's
# per-charger value from the matching global where it's unset, so removing the
# global later never silently resets a user's configured value. Behaviour-
# neutral today (per-charger already falls back to the global at runtime).
_SEED_KEYS = (
"daily_ev_target", "daily_ev_target_max",
"ev_target_soc", "ev_target_soc_max",
# ``ev_night_initial_current`` is the LEGACY key name at
# v3 time — v9→v10 (#441) renames it to ``initial_current``
# later in the chain. Keep the legacy spelling here so a
# v3 entry's global value is actually picked up.
"ev_min_current", "ev_night_initial_current",
"ev_kwh_per_100km", "ev_target_type",
# #255 Phase 4 — also converted to per-charger
"ev_charging_mode", "ev_phases",
# #246 Phase 2 — per-charger charge-by deadline
"ev_target_time",
)
new_data = {**accumulated_data}