From 2b8b004fc2d95cb3c7da9c4fe8c1a3a38be37134 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:22:58 -0800 Subject: [PATCH 1/2] fix(monitoring): name alerts as Home Assistant shows the circuit, and refuse an unloaded panel Current monitoring notifications name a circuit by its Home Assistant name, {name} in custom templates included, and the span_panel_current_alert event gains alert_display_name while alert_name stays as it was. {entity_id} carries the circuit's Current sensor, else its Power sensor, or the mains leg's. Every monitoring service now finds its panel through one path: a config entry that is not a SPAN Panel's is refused as monitoring_panel_unknown, an unloaded panel as monitoring_panel_not_loaded, and monitoring_not_enabled is left for a loaded panel with monitoring off. Get monitoring status no longer answers "off" for an unloaded panel, and turning monitoring off on one no longer reports success while doing nothing. The legacy enable_current_monitoring option is moved into the monitoring store once at setup and removed from the entry, so monitoring turned off stays off across a restart. --- CHANGELOG.md | 26 +- custom_components/span_panel/__init__.py | 12 +- .../span_panel/alert_dispatcher.py | 56 ++- custom_components/span_panel/const.py | 1 - .../span_panel/current_monitor.py | 100 +++- custom_components/span_panel/entry_reloads.py | 24 +- custom_components/span_panel/services.py | 159 +++--- custom_components/span_panel/strings.json | 11 +- .../span_panel/translations/en.json | 11 +- .../span_panel/translations/es.json | 11 +- .../span_panel/translations/fr.json | 11 +- .../span_panel/translations/ja.json | 11 +- .../span_panel/translations/pt.json | 11 +- custom_components/span_panel/util.py | 35 ++ frontend.md | 61 +-- tests/replayed_panel.py | 30 +- tests/test_alert_display_names.py | 456 ++++++++++++++++++ tests/test_current_monitor.py | 49 +- tests/test_current_monitor_services.py | 345 ++++++++++++- tests/test_current_monitor_setup.py | 99 +++- tests/test_device_id_migration.py | 13 +- tests/test_package_rating_services.py | 6 +- tests/test_package_ratings.py | 3 +- tests/test_remote_ct_inverter_naming.py | 7 +- 24 files changed, 1316 insertions(+), 232 deletions(-) create mode 100644 tests/test_alert_display_names.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 33ea9e2b..307b44f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,24 @@ All notable changes to this project will be documented in this file. - **An error from a breaker, circuit priority, charger or adopted-device control now names the circuit or device by the name you gave it in Home Assistant**, where it kept the name the panel or the integration gave it. +- **Current monitoring notifications now name a circuit by the name you gave it in Home Assistant, including through `{name}` in a custom title or message**, + where they used its name in the SPAN app; the `span_panel_current_alert` event carries that name in a new `alert_display_name` field and leaves `alert_name` + as it was. + +- **The Get monitoring status action now fails with an error when the panel it is asked about has not finished loading, such as while Home Assistant starts, or + when the config entry it names is not a SPAN Panel's**, where it answered that monitoring was off, so a script step that calls it then stops unless it is set + to continue on error, and Home Assistant logs the error. + +- **Changing a panel's current monitoring while the panel is not loaded, or naming a config entry that is not a SPAN Panel's, now fails with an error, turning + monitoring off included**, where turning it off reported success and left monitoring to start again once the panel loaded, and turning it on, changing its + settings or a threshold named by circuit id or leg, or sending a test notification said monitoring was not enabled. + +- **The `{entity_id}` placeholder in a current monitoring notification's title or message now carries the entity ID of the circuit's Current sensor, or its + Power sensor where it has none, or of the mains leg's Current sensor**, where it carried the circuit's internal id or the leg's name. + +- **Current monitoring turned off now stays off after Home Assistant restarts on a panel whose options still hold the monitoring switch an earlier release + stored there**, where it came back on at every restart. + ## [2.3.3] - 11/2026 **Install 2.3.3 before your panel updates to firmware r202645**, which gives the panel's circuits new device IDs: 2.3.3 carries every circuit entity, device, @@ -72,8 +90,8 @@ setting and favorite across to them, and each entity keeps its entity ID and his - **A panel reloads once, not twice, after reauthentication, reconfiguration or re-pinning its certificate authority.** Reconfiguring no longer logs Home Assistant's warning that the integration "has an update listener and should use it for scheduling a reload". -- **A reload no longer starts in the middle of the panel's own update**, and a change that nothing in the integration reads, such as the system option for - new entities, or a rediscovery that changes nothing, no longer reloads the panel. +- **A reload no longer starts in the middle of the panel's own update**, and a change that nothing in the integration reads, such as the system option for new + entities, or a rediscovery that changes nothing, no longer reloads the panel. - **A change made while a panel is setting up is applied.** An options save that landed during setup was stored but not used until the next restart, and a reconfigure completed while the panel was retrying waited for Home Assistant's next retry, up to ten minutes later. Both now reload the panel straight away. @@ -99,8 +117,8 @@ Home Assistant 2026.11. ### Fixed -- **Discovering or adding a panel no longer logs a warning that its credentials are being sent over plaintext HTTP**, which the schema read that set it off never - carries. +- **Discovering or adding a panel no longer logs a warning that its credentials are being sent over plaintext HTTP**, which the schema read that set it off + never carries. ## [2.3.1] - 11/2026 diff --git a/custom_components/span_panel/__init__.py b/custom_components/span_panel/__init__.py index 63cc1142..2eac1be3 100644 --- a/custom_components/span_panel/__init__.py +++ b/custom_components/span_panel/__init__.py @@ -79,7 +79,6 @@ DEFAULT_MQTTS_PORT, DEFAULT_SNAPSHOT_INTERVAL, DOMAIN, - ENABLE_CURRENT_MONITORING, PANEL_CA_PENDING, ) from .control_gate import ControlGate, ControlLock, ControlPolicy @@ -90,7 +89,11 @@ ) from .coordinator import SpanPanelCoordinator from .curation import async_forget_curation, async_load_curation -from .current_monitor import CurrentMonitor, async_forget_monitoring +from .current_monitor import ( + CurrentMonitor, + async_adopt_legacy_enable_option, + async_forget_monitoring, +) from .device_id_rekey import async_migrate_device_ids, entry_holds_old_ids from .entry_issues import async_clear_unlinked_issues, entry_removed from .entry_reloads import ( @@ -914,9 +917,8 @@ async def _async_setup_entry(hass: HomeAssistant, entry: SpanPanelConfigEntry) - await coordinator.async_setup_streaming() - if entry.options.get( - ENABLE_CURRENT_MONITORING, False - ) or await CurrentMonitor.async_is_enabled(hass, entry): + await async_adopt_legacy_enable_option(hass, entry) + if await CurrentMonitor.async_is_enabled(hass, entry): # Held, not judged: the first judgement, and any alert it raises, # is the next update's. monitor = CurrentMonitor( diff --git a/custom_components/span_panel/alert_dispatcher.py b/custom_components/span_panel/alert_dispatcher.py index 14c64b61..d3a6ec8b 100644 --- a/custom_components/span_panel/alert_dispatcher.py +++ b/custom_components/span_panel/alert_dispatcher.py @@ -39,8 +39,8 @@ def format_notification( *, alert_type: str, - alert_name: str, - alert_id: str, + display_name: str, + entity_id: str, current_a: float, monitoring_rating_a: float, threshold_pct: int, @@ -52,13 +52,22 @@ def format_notification( ) -> tuple[str, str]: """Format notification title and message using templates. - `monitoring_rating_a` is the rating the point was judged against, which the - `{breaker_rating_a}` placeholder carries. + `display_name` is the point's name as Home Assistant shows it, which the + `{name}` placeholder carries, and `entity_id` the entity it is shown under, + which `{entity_id}` carries. `monitoring_rating_a` is the rating the point + was judged against, which the `{breaker_rating_a}` placeholder carries. Available placeholders: - {name} - The circuit's name in the SPAN app, or the mains leg + {name} - The circuit's name as Home Assistant shows it: the + name the user gave its device, else the name the + device is registered under, those of circuits that + share a meter joined with " + "; or the mains leg (e.g. "Mains Upstream L1") - {entity_id} - Entity ID (e.g. sensor.kitchen_current) + {entity_id} - The entity ID of the circuit's Current sensor, or + its Power sensor where it has none, that of the + circuit `alert_id` names for circuits that share a + meter; for the mains, the leg's Current sensor + (e.g. sensor.kitchen_current) {alert_type} - "spike" or "continuous_overload" {current_a} - Current draw in amps (e.g. 18.3) {breaker_rating_a}- The rating in amps the circuit is judged against (e.g. 20): @@ -73,8 +82,8 @@ def format_notification( """ window_m = (window_duration_s or 0) // 60 template_vars = { - "name": alert_name, - "entity_id": alert_id, + "name": display_name, + "entity_id": entity_id, "alert_type": alert_type, "current_a": f"{current_a:.1f}", "breaker_rating_a": f"{monitoring_rating_a:.0f}", @@ -86,12 +95,12 @@ def format_notification( try: title = title_template.format_map(template_vars) except (KeyError, ValueError): - title = f"SPAN: {alert_name} {alert_type}" + title = f"SPAN: {display_name} {alert_type}" try: message = message_template.format_map(template_vars) except (KeyError, ValueError): message = ( - f"{alert_name} at {current_a:.1f}A " + f"{display_name} at {current_a:.1f}A " f"({utilization_pct}% of {monitoring_rating_a:.0f}A rating) at {local_time or ''}" ) return title, message @@ -163,7 +172,9 @@ def dispatch_alert( *, alert_type: str, alert_name: str, + display_name: str, alert_id: str, + entity_id: str, alert_source: str, current_a: float, breaker_rating_a: float | None, @@ -179,6 +190,15 @@ def dispatch_alert( ) -> None: """Dispatch alert through all enabled notification channels. + `alert_name` is the panel's name for the point and `display_name` the name + Home Assistant shows for it, the user's where they renamed the circuit's + device. The event carries both, as `alert_name` and `alert_display_name`: + automations read `alert_name`, so a rename in Home Assistant never changes + it. The title and message are read by a person, so their `{name}` is the + name that person finds the circuit under. `alert_id` is the point's id, + which the event carries, and `entity_id` the entity the point is shown + under, which only the text's `{entity_id}` carries. + The event payload carries the ratings as `get_monitoring_status` does: `breaker_rating_a` is the panel's rating (a shared meter's capacity over its members' ratings, None if any is unknown), `monitoring_rating_a` the rating the @@ -199,6 +219,7 @@ def dispatch_alert( "alert_source": alert_source, "alert_id": alert_id, "alert_name": alert_name, + "alert_display_name": display_name, "alert_type": alert_type, "current_a": round(current_a, 1), "breaker_rating_a": breaker_rating_a, @@ -227,8 +248,8 @@ def dispatch_alert( title, message = format_notification( alert_type=alert_type, - alert_name=alert_name, - alert_id=alert_id, + display_name=display_name, + entity_id=entity_id, current_a=current_a, monitoring_rating_a=monitoring_rating_a, threshold_pct=threshold_pct, @@ -274,7 +295,13 @@ def dispatch_test_alert( """Dispatch a test notification using sample values through all enabled channels.""" alert_type = "spike" alert_name = "Kitchen Oven" + # The sample circuit is one nobody renamed, so Home Assistant shows it by + # the panel's name. + display_name = alert_name alert_id = "sensor.kitchen_oven_current" + # The sample's id has always been its sensor's entity ID, so the text's + # `{entity_id}` carries the same one. + entity_id = alert_id alert_source = "circuit" current_a = 18.3 breaker_rating_a = 20.0 @@ -296,6 +323,7 @@ def dispatch_test_alert( "alert_source": alert_source, "alert_id": alert_id, "alert_name": alert_name, + "alert_display_name": display_name, "alert_type": alert_type, "current_a": current_a, "breaker_rating_a": breaker_rating_a, @@ -316,8 +344,8 @@ def dispatch_test_alert( title, message = format_notification( alert_type=alert_type, - alert_name=alert_name, - alert_id=alert_id, + display_name=display_name, + entity_id=entity_id, current_a=current_a, monitoring_rating_a=monitoring_rating_a, threshold_pct=threshold_pct, diff --git a/custom_components/span_panel/const.py b/custom_components/span_panel/const.py index 4e029670..e4c83172 100644 --- a/custom_components/span_panel/const.py +++ b/custom_components/span_panel/const.py @@ -114,7 +114,6 @@ """The config flow's starting choice for a new install, which it stores.""" # Current monitoring configuration -ENABLE_CURRENT_MONITORING = "enable_current_monitoring" DEFAULT_CONTINUOUS_THRESHOLD_PCT = 80 DEFAULT_SPIKE_THRESHOLD_PCT = 100 DEFAULT_WINDOW_DURATION_M = 15 diff --git a/custom_components/span_panel/current_monitor.py b/custom_components/span_panel/current_monitor.py index e871f571..5896ddc9 100644 --- a/custom_components/span_panel/current_monitor.py +++ b/custom_components/span_panel/current_monitor.py @@ -15,13 +15,13 @@ from dataclasses import dataclass from datetime import datetime import logging -from typing import TYPE_CHECKING, Any, Literal, TypedDict +from typing import TYPE_CHECKING, Any, Final, Literal, TypedDict -from homeassistant.helpers import entity_registry as er +from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.storage import Store from span_panel_api import SpanPanelSnapshot, shared_meter_groups -from .alert_dispatcher import dispatch_alert, format_notification +from .alert_dispatcher import dispatch_alert from .const import ( DEFAULT_CONTINUOUS_THRESHOLD_PCT, DEFAULT_COOLDOWN_DURATION_M, @@ -34,6 +34,7 @@ ) from .device_id_migration import rekeyed from .entity_resolver import resolve_circuit_id +from .entry_reloads import async_update_entry_options_applied from .helpers import build_circuit_unique_id, build_panel_unique_id, construct_circuit_label from .meter_capacity import meter_capacity_a from .options import ( @@ -59,6 +60,7 @@ is_monitoring_disabled, resolve_thresholds, ) +from .util import circuit_display_name if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry @@ -85,6 +87,12 @@ _STORAGE_VERSION = 1 _STORAGE_KEY_PREFIX = "span_panel_current_monitor" +_LEGACY_ENABLE_OPTION: Final = "enable_current_monitoring" +"""The option a release before the monitoring store switched monitoring on by. + +Read only by `async_adopt_legacy_enable_option`, which moves it into the store. +""" + StoredMonitoring = TypedDict( "StoredMonitoring", { @@ -175,6 +183,11 @@ class MonitoredCircuit: its first member: that key is stable while the membership is, which is enough for alerts and overrides, neither of which is an entity. + `name` is the panel's name for the point, each member's label joined with " + ": + the alert event's `alert_name`, which automations read, so a rename in Home + Assistant never changes it. The alert's text names the point as Home + Assistant shows it instead (`CurrentMonitor._display_name`). + `rating_a` is the rating judged against and `panel_rating_a` the breaker rating the panel published, each None where a circuit, or the capacity of a group, is unknown. For a group, both are capacities by the same rule, `rating_a` over the ratings its @@ -461,10 +474,13 @@ def set_global_settings(self, settings: MonitoringSettings) -> None: self._hass.async_create_task(self.async_save_overrides()) def _resolve_circuit_entity_id(self, circuit_id: str) -> str: - """Resolve circuit_id to a sensor entity_id for monitoring status keys. + """Return the entity a circuit is shown under: its monitoring status key, and its alert's `{entity_id}`. - Tries the current sensor first, then falls back to power, matching - the frontend lookup order (circuit.entities.current ?? .power). + Its Current sensor, else its Power sensor, matching the frontend lookup + order (circuit.entities.current ?? .power): a circuit that never publishes + a current has no Current sensor, nor does one whose current first arrived + after setup until the next reload. The circuit's id where Home Assistant + holds neither, as for a circuit the panel added since the entry was set up. """ serial = self._last_snapshot.serial_number entity_reg = er.async_get(self._hass) @@ -524,7 +540,12 @@ def resolve_entity_to_mains_leg(self, entity_id: str) -> str: return entity_id def _resolve_mains_entity_id(self, leg: str) -> str: - """Resolve mains leg to its current sensor entity_id, or fall back to leg name.""" + """Return a mains leg's Current sensor, which its alert's `{entity_id}` carries. + + Upstream L1's is also the key the monitoring status shows the mains + under. The leg's name where Home Assistant holds no such sensor, as for a + leg whose current first arrived after setup. + """ serial = self._last_snapshot.serial_number # The sensor key matches the leg name + "_current" (e.g., "upstream_l1_current") unique_id = build_panel_unique_id(serial, f"{leg}_current") @@ -761,6 +782,7 @@ def _evaluate_circuits(self, snapshot: SpanPanelSnapshot) -> None: self.get_global_settings(), alert_type=alert.alert_type, alert_name=point.name, + display_name=self._display_name(point, snapshot), alert_id=circuit_id, alert_source="circuit", current_a=alert.current_a, @@ -772,6 +794,7 @@ def _evaluate_circuits(self, snapshot: SpanPanelSnapshot) -> None: threshold_pct=alert.threshold_pct, utilization_pct=alert.utilization_pct, panel_serial=snapshot.serial_number, + entity_id=self._resolve_circuit_entity_id(circuit_id), ) alert = check_continuous(state, current, rating, cont_pct, window_m, cooldown_m) @@ -781,6 +804,7 @@ def _evaluate_circuits(self, snapshot: SpanPanelSnapshot) -> None: self.get_global_settings(), alert_type=alert.alert_type, alert_name=point.name, + display_name=self._display_name(point, snapshot), alert_id=circuit_id, alert_source="circuit", current_a=alert.current_a, @@ -794,8 +818,29 @@ def _evaluate_circuits(self, snapshot: SpanPanelSnapshot) -> None: panel_serial=snapshot.serial_number, window_duration_s=alert.window_duration_s, over_threshold_since=alert.over_threshold_since, + entity_id=self._resolve_circuit_entity_id(circuit_id), ) + def _display_name(self, point: MonitoredCircuit, snapshot: SpanPanelSnapshot) -> str: + """Name a point as Home Assistant shows it, for the text of the alert it raises. + + Each member's device as Home Assistant shows it (`util.circuit_display_name`), + joined as `MonitoredCircuit.name` joins the panel's names. Asked when an + alert fires rather than held, so a device renamed since setup is named + by its new name in the next alert. + """ + device_registry = dr.async_get(self._hass) + return " + ".join( + circuit_display_name( + device_registry, + snapshot.serial_number, + snapshot.circuits[member], + member, + config_entry_id=self._entry.entry_id, + ) + for member in point.members + ) + # --- Mains evaluation --- def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: @@ -819,7 +864,9 @@ def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: self._mains_overrides.get(leg, {}), self.get_global_settings() ) - leg_label = leg.replace("_", " ").title() + # The mains has no device of its own, so its text and its event both + # name the leg by its own name. + leg_name = f"Mains {leg.replace('_', ' ').title()}" alert = check_spike(state, current, rating, spike_pct, cooldown_m) if alert is not None: @@ -827,7 +874,8 @@ def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: self._hass, self.get_global_settings(), alert_type=alert.alert_type, - alert_name=f"Mains {leg_label}", + alert_name=leg_name, + display_name=leg_name, alert_id=leg, alert_source="mains", current_a=alert.current_a, @@ -840,6 +888,7 @@ def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: threshold_pct=alert.threshold_pct, utilization_pct=alert.utilization_pct, panel_serial=snapshot.serial_number, + entity_id=self._resolve_mains_entity_id(leg), ) alert = check_continuous(state, current, rating, cont_pct, window_m, cooldown_m) @@ -848,7 +897,8 @@ def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: self._hass, self.get_global_settings(), alert_type=alert.alert_type, - alert_name=f"Mains {leg_label}", + alert_name=leg_name, + display_name=leg_name, alert_id=leg, alert_source="mains", current_a=alert.current_a, @@ -863,17 +913,41 @@ def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: panel_serial=snapshot.serial_number, window_duration_s=alert.window_duration_s, over_threshold_since=alert.over_threshold_since, + entity_id=self._resolve_mains_entity_id(leg), ) - # Backward-compatible static alias kept for existing callers/tests. - _format_notification = staticmethod(format_notification) - def _store_for(hass: HomeAssistant, entry: ConfigEntry) -> Store[StoredMonitoring]: """Return the store holding one panel's monitoring settings.""" return Store(hass, _STORAGE_VERSION, f"{_STORAGE_KEY_PREFIX}.{entry.entry_id}") +async def async_adopt_legacy_enable_option(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Move an entry's legacy `enable_current_monitoring` option into the monitoring store, once. + + Monitoring is switched on and off in the store alone, which turning it off + writes; an option left in the entry turned it on again at every setup, so an + entry holding it could not stay off across a restart. Setup calls this + before it reads the store. Where the store already holds a flag, that flag + is the user's last word and the option carries nothing; otherwise an option + that is on is recorded as on, and one that is off needs no record, since a + store holding no flag is off. Either way the option leaves the entry, through + a write that asks for no reload, because this setup has already applied it. + """ + if _LEGACY_ENABLE_OPTION not in entry.options: + return + store = _store_for(hass, entry) + data = _read_stored(await store.async_load(), entry) or StoredMonitoring() + if "enabled" not in data and entry.options[_LEGACY_ENABLE_OPTION]: + data["enabled"] = True + await store.async_save(data) + async_update_entry_options_applied( + hass, + entry, + {key: value for key, value in entry.options.items() if key != _LEGACY_ENABLE_OPTION}, + ) + + async def async_forget_monitoring(hass: HomeAssistant, entry: ConfigEntry) -> None: """Drop the monitoring settings when the config entry is removed. diff --git a/custom_components/span_panel/entry_reloads.py b/custom_components/span_panel/entry_reloads.py index 597d67c7..e3f1320a 100644 --- a/custom_components/span_panel/entry_reloads.py +++ b/custom_components/span_panel/entry_reloads.py @@ -36,9 +36,9 @@ A preference or a discovery key written to the entry asks for nothing: Home Assistant reloads for the polling preference itself, and nothing here reads the others. A writer that applies its own change, as setup does when it pins a CA or -renames an entry titled with its serial, writes through -`async_update_entry_data_applied` or `async_update_entry_title_applied` and asks -for nothing either. +renames an entry titled with its serial, or removes the legacy monitoring option, +writes through `async_update_entry_data_applied`, `async_update_entry_title_applied` +or `async_update_entry_options_applied` and asks for nothing either. """ from __future__ import annotations @@ -197,6 +197,24 @@ def async_update_entry_title_applied(hass: HomeAssistant, entry: ConfigEntry, ti ) +@callback +def async_update_entry_options_applied( + hass: HomeAssistant, entry: ConfigEntry, options: Mapping[str, object] +) -> bool: + """Write the entry's options for a writer that applies them itself, asking for no reload. + + For setup's removal of the legacy `enable_current_monitoring` option, which + it has already carried into the monitoring store. Only the options are + written and recorded; see `_async_write_applied`. + """ + return _async_write_applied( + hass, + entry, + lambda applied: replace(applied, options=copy.deepcopy(dict(options))), + lambda: hass.config_entries.async_update_entry(entry, options=options), + ) + + @callback def _async_write_applied( hass: HomeAssistant, diff --git a/custom_components/span_panel/services.py b/custom_components/span_panel/services.py index a231f421..b4f8d4c0 100644 --- a/custom_components/span_panel/services.py +++ b/custom_components/span_panel/services.py @@ -309,28 +309,51 @@ def _service_name(call: ServiceCall) -> str: return f"{call.domain}.{call.service}" -def _raise_if_entitys_panel_not_loaded( - hass: HomeAssistant, target: str, panel_entry_id: str | None -) -> None: - """Refuse a threshold call whose entity's own panel is chosen but not loaded. +def _named_panel_entry_id(hass: HomeAssistant, call: ServiceCall) -> str | None: + """Return the config entry a monitoring call names, or None where it names none. - Said as that, rather than as monitoring being off, which nothing has read. A - loaded panel, no chosen panel, and a raw id, which belongs to no entity, are - all left to the caller's own refusal. + Refused where the id is no SPAN Panel's entry, whether no entry has it or + another integration's does: said as that, rather than as a panel that is + not loaded, which a caller waiting for it to load would wait on for good. """ - if panel_entry_id is None: - return - config_entry = hass.config_entries.async_get_entry(panel_entry_id) - if config_entry is not None and loaded_runtime_data(config_entry) is not None: - return - entity_entry = er.async_get(hass).async_get(target) - if entity_entry is not None and entity_entry.platform == DOMAIN: + entry_id: str | None = call.data.get("config_entry_id") + if entry_id is None: + return None + entry = hass.config_entries.async_get_entry(entry_id) + if entry is None or entry.domain != DOMAIN: raise ServiceValidationError( - f"The SPAN Panel that entity {target} belongs to is not loaded.", + f"No SPAN Panel has config entry {entry_id}.", translation_domain=DOMAIN, - translation_key="favorite_panel_not_loaded", - translation_placeholders={"entity_id": target}, + translation_key="monitoring_panel_unknown", + translation_placeholders={"config_entry_id": entry_id}, ) + return entry_id + + +def _loaded_monitoring_panel( + hass: HomeAssistant, config_entry_id: str | None +) -> tuple[SpanPanelRuntimeData, ConfigEntry]: + """Return the loaded panel a monitoring service acts on: the one chosen, else the first loaded. + + Every monitoring service, read or write, finds its panel here. One that is + not loaded is refused, in every state that keeps it so (setting up, + retrying, failed, disabled), and said as that, never as monitoring being + off, which nothing has read: a script asking while Home Assistant started + was told monitoring was off on a panel that had it on, and turning it off + was answered with success while the stored setting turned it on again once + the panel loaded. For a status read, the card waits for the entry to load on + this refusal, by its error code, translation domain and key; it waits on no + write's. + """ + for entry in hass.config_entries.async_loaded_entries(DOMAIN): + runtime_data = loaded_runtime_data(entry) + if runtime_data is not None and config_entry_id in (None, entry.entry_id): + return runtime_data, entry + raise ServiceValidationError( + "The SPAN Panel is not loaded, so its monitoring cannot be read or changed.", + translation_domain=DOMAIN, + translation_key="monitoring_panel_not_loaded", + ) def _threshold_panel_entry_id( @@ -387,25 +410,10 @@ def _async_register_monitoring_services(hass: HomeAssistant) -> None: """Register current monitoring services. Every service here but `get_monitoring_status` changes monitoring, so each - is registered through `_async_register_monitoring_write`. + is registered through `_async_register_monitoring_write`. Each finds its + panel through `_named_panel_entry_id` and `_loaded_monitoring_panel`. """ - def _get_runtime_data( - config_entry_id: str | None = None, - ) -> tuple[SpanPanelRuntimeData, ConfigEntry] | None: - """Find SPAN panel runtime data and entry. - - When config_entry_id is provided, returns that specific entry. - Otherwise falls back to the first loaded entry. - """ - for entry in hass.config_entries.async_loaded_entries(DOMAIN): - runtime_data = loaded_runtime_data(entry) - if runtime_data is None: - continue - if config_entry_id is None or entry.entry_id == config_entry_id: - return runtime_data, entry - return None - def _get_monitored( call: ServiceCall, target: str ) -> tuple[CurrentMonitor, SpanPanelRuntimeData]: @@ -416,32 +424,24 @@ def _get_monitored( live snapshot, as every service resolves its target, rather than the monitor's own, which is the last it judged or, before the first, the one it was built holding. - """ - panel_entry_id = _threshold_panel_entry_id(hass, target, call.data.get("config_entry_id")) - result = _get_runtime_data(panel_entry_id) - if result is not None: - runtime_data, _entry = result - if runtime_data.coordinator.current_monitor is not None: - return runtime_data.coordinator.current_monitor, runtime_data - _raise_if_entitys_panel_not_loaded(hass, target, panel_entry_id) - raise ServiceValidationError( - "No SPAN panel with current monitoring enabled.", - translation_domain=DOMAIN, - translation_key="monitoring_not_enabled", - ) - async def _get_or_create_monitor( - config_entry_id: str | None = None, - ) -> CurrentMonitor: - """Find or bootstrap a CurrentMonitor for the specified panel.""" - result = _get_runtime_data(config_entry_id) - if result is None: + `monitoring_not_enabled` is this refusal alone: the panel is loaded, and + its monitoring is off. + """ + panel_entry_id = _threshold_panel_entry_id(hass, target, _named_panel_entry_id(hass, call)) + runtime_data, _entry = _loaded_monitoring_panel(hass, panel_entry_id) + monitor = runtime_data.coordinator.current_monitor + if monitor is None: raise ServiceValidationError( - "No SPAN panel integration loaded.", + "Current monitoring is off on this SPAN Panel.", translation_domain=DOMAIN, translation_key="monitoring_not_enabled", ) - runtime_data, entry = result + return monitor, runtime_data + + async def _get_or_create_monitor(config_entry_id: str | None) -> CurrentMonitor: + """Find or bootstrap a CurrentMonitor for the specified panel.""" + runtime_data, entry = _loaded_monitoring_panel(hass, config_entry_id) if runtime_data.coordinator.current_monitor is not None: return runtime_data.coordinator.current_monitor monitor = CurrentMonitor( @@ -493,11 +493,7 @@ async def async_handle_clear_mains_threshold(call: ServiceCall) -> None: async def async_handle_get_monitoring_status( call: ServiceCall, ) -> ServiceResponse: - entry_id = call.data.get("config_entry_id") - result = _get_runtime_data(entry_id) - if result is None: - return {"enabled": False} - runtime_data, _entry = result + runtime_data, _entry = _loaded_monitoring_panel(hass, _named_panel_entry_id(hass, call)) monitor = runtime_data.coordinator.current_monitor if monitor is None: return {"enabled": False} @@ -545,18 +541,19 @@ async def async_handle_get_monitoring_status( async def async_handle_set_global_monitoring(call: ServiceCall) -> None: data = dict(call.data) enabled = data.pop("enabled", None) - entry_id = data.pop("config_entry_id", None) + data.pop("config_entry_id", None) + entry_id = _named_panel_entry_id(hass, call) if enabled is False: - # Disable monitoring: stop the monitor and mark storage as disabled - result = _get_runtime_data(entry_id) - if result is not None: - runtime_data, entry = result - monitor = runtime_data.coordinator.current_monitor - if monitor is not None: - monitor.async_stop() - await monitor.async_save_disabled() - runtime_data.coordinator.current_monitor = None + # Disable monitoring: stop the monitor and mark storage as disabled. + # Only a loaded panel's: one that is not loaded is refused, where a + # success would have left its stored setting to turn it on again. + runtime_data, _entry = _loaded_monitoring_panel(hass, entry_id) + monitor = runtime_data.coordinator.current_monitor + if monitor is not None: + monitor.async_stop() + await monitor.async_save_disabled() + runtime_data.coordinator.current_monitor = None return monitor = await _get_or_create_monitor(entry_id) @@ -580,8 +577,7 @@ async def async_handle_set_global_monitoring(call: ServiceCall) -> None: async def async_handle_test_notification(call: ServiceCall) -> None: from .alert_dispatcher import dispatch_test_alert # pylint: disable=import-outside-toplevel - entry_id = call.data.get("config_entry_id") - monitor = await _get_or_create_monitor(entry_id) + monitor = await _get_or_create_monitor(_named_panel_entry_id(hass, call)) settings = monitor.get_global_settings() dispatch_test_alert(hass, settings) @@ -609,21 +605,12 @@ def _get_runtime_data(call: ServiceCall, target: str) -> SpanPanelRuntimeData: The panel is `_threshold_panel_entry_id`'s choice, as for the threshold services: an entity belongs to one panel, and a raw circuit id goes to the - panel the call names, or else the first loaded. + panel the call names, or else the first loaded. Refused as every other + monitoring write is, by `_named_panel_entry_id` and `_loaded_monitoring_panel`. """ - panel_entry_id = _threshold_panel_entry_id(hass, target, call.data.get("config_entry_id")) - for entry in hass.config_entries.async_loaded_entries(DOMAIN): - runtime_data = loaded_runtime_data(entry) - if runtime_data is None: - continue - if panel_entry_id is None or entry.entry_id == panel_entry_id: - return runtime_data - _raise_if_entitys_panel_not_loaded(hass, target, panel_entry_id) - raise ServiceValidationError( - "No SPAN panel is loaded.", - translation_domain=DOMAIN, - translation_key="package_ratings_panel_not_loaded", - ) + panel_entry_id = _threshold_panel_entry_id(hass, target, _named_panel_entry_id(hass, call)) + runtime_data, _entry = _loaded_monitoring_panel(hass, panel_entry_id) + return runtime_data async def async_handle_set_circuit_package_ratings(call: ServiceCall) -> None: target = call.data["circuit_id"] diff --git a/custom_components/span_panel/strings.json b/custom_components/span_panel/strings.json index 7625542f..70d6a297 100644 --- a/custom_components/span_panel/strings.json +++ b/custom_components/span_panel/strings.json @@ -530,7 +530,13 @@ "message": "Entity {entity_id} belongs to a different SPAN Panel than config entry {config_entry_id}. Leave config_entry_id out, or name the entity's own panel." }, "monitoring_not_enabled": { - "message": "No SPAN panel with current monitoring enabled." + "message": "Current monitoring is off on this SPAN Panel. Turn it on before changing its thresholds." + }, + "monitoring_panel_not_loaded": { + "message": "The SPAN Panel is not loaded, so its current monitoring, and the ratings it judges against, cannot be read or changed." + }, + "monitoring_panel_unknown": { + "message": "No SPAN Panel has config entry {config_entry_id}, so there is no monitoring to read or change." }, "panel_auth_failed": { "message": "Authentication with the SPAN Panel failed. Please reauthenticate." @@ -612,9 +618,6 @@ }, "package_ratings_circuit_unknown": { "message": "This panel has no circuit with that id." - }, - "package_ratings_panel_not_loaded": { - "message": "No SPAN Panel is loaded, so no ratings can be copied or cleared." } }, "options": { diff --git a/custom_components/span_panel/translations/en.json b/custom_components/span_panel/translations/en.json index 7625542f..70d6a297 100644 --- a/custom_components/span_panel/translations/en.json +++ b/custom_components/span_panel/translations/en.json @@ -530,7 +530,13 @@ "message": "Entity {entity_id} belongs to a different SPAN Panel than config entry {config_entry_id}. Leave config_entry_id out, or name the entity's own panel." }, "monitoring_not_enabled": { - "message": "No SPAN panel with current monitoring enabled." + "message": "Current monitoring is off on this SPAN Panel. Turn it on before changing its thresholds." + }, + "monitoring_panel_not_loaded": { + "message": "The SPAN Panel is not loaded, so its current monitoring, and the ratings it judges against, cannot be read or changed." + }, + "monitoring_panel_unknown": { + "message": "No SPAN Panel has config entry {config_entry_id}, so there is no monitoring to read or change." }, "panel_auth_failed": { "message": "Authentication with the SPAN Panel failed. Please reauthenticate." @@ -612,9 +618,6 @@ }, "package_ratings_circuit_unknown": { "message": "This panel has no circuit with that id." - }, - "package_ratings_panel_not_loaded": { - "message": "No SPAN Panel is loaded, so no ratings can be copied or cleared." } }, "options": { diff --git a/custom_components/span_panel/translations/es.json b/custom_components/span_panel/translations/es.json index 433bf900..f9a5b97e 100644 --- a/custom_components/span_panel/translations/es.json +++ b/custom_components/span_panel/translations/es.json @@ -484,9 +484,6 @@ "package_ratings_circuit_unknown": { "message": "Este panel no tiene ningún circuito con ese identificador." }, - "package_ratings_panel_not_loaded": { - "message": "No hay ningún SPAN Panel cargado, por lo que no se pueden copiar ni borrar capacidades." - }, "circuit_priority_failed": { "message": "Se rechazó el cambio de prioridad para {circuit}: {reason}. No se envió nada al panel, por lo que la prioridad no ha cambiado." }, @@ -560,7 +557,13 @@ "message": "La entidad {entity_id} pertenece a un SPAN Panel distinto de la entrada de configuración {config_entry_id}. Omita config_entry_id o indique el panel propio de la entidad." }, "monitoring_not_enabled": { - "message": "Ningún SPAN Panel tiene el monitoreo de corriente habilitado." + "message": "El monitoreo de corriente está desactivado en este SPAN Panel. Actívelo antes de cambiar sus umbrales." + }, + "monitoring_panel_not_loaded": { + "message": "El SPAN Panel no está cargado, por lo que su monitoreo de corriente, y las capacidades con las que lo evalúa, no se pueden leer ni cambiar." + }, + "monitoring_panel_unknown": { + "message": "Ningún SPAN Panel tiene la entrada de configuración {config_entry_id}, por lo que no hay monitoreo que leer ni cambiar." }, "panel_auth_failed": { "message": "La autenticación con el SPAN Panel falló. Por favor vuelva a autenticarse." diff --git a/custom_components/span_panel/translations/fr.json b/custom_components/span_panel/translations/fr.json index 0f1a837b..0de5fbe9 100644 --- a/custom_components/span_panel/translations/fr.json +++ b/custom_components/span_panel/translations/fr.json @@ -484,9 +484,6 @@ "package_ratings_circuit_unknown": { "message": "Ce panneau n'a aucun circuit avec cet identifiant." }, - "package_ratings_panel_not_loaded": { - "message": "Aucun SPAN Panel n'est chargé ; aucun calibre ne peut donc être copié ni effacé." - }, "circuit_priority_failed": { "message": "Le changement de priorité pour {circuit} a été refusé : {reason}. Rien n'a été envoyé au panneau, la priorité est donc inchangée." }, @@ -560,7 +557,13 @@ "message": "L'entité {entity_id} appartient à un autre SPAN Panel que l'entrée de configuration {config_entry_id}. Omettez config_entry_id ou indiquez le panneau de l'entité." }, "monitoring_not_enabled": { - "message": "Aucun panneau SPAN n'a la surveillance de courant activée." + "message": "La surveillance du courant est désactivée sur ce SPAN Panel. Activez-la avant de modifier ses seuils." + }, + "monitoring_panel_not_loaded": { + "message": "Le SPAN Panel n'est pas chargé, sa surveillance du courant, et les calibres auxquels elle se compare, ne peuvent donc être ni lus ni modifiés." + }, + "monitoring_panel_unknown": { + "message": "Aucun SPAN Panel n'a l'entrée de configuration {config_entry_id} ; il n'y a donc aucune surveillance à lire ni à modifier." }, "panel_auth_failed": { "message": "L'authentification avec le SPAN Panel a échoué. Veuillez vous réauthentifier." diff --git a/custom_components/span_panel/translations/ja.json b/custom_components/span_panel/translations/ja.json index a6a210f5..a11b56a6 100644 --- a/custom_components/span_panel/translations/ja.json +++ b/custom_components/span_panel/translations/ja.json @@ -484,9 +484,6 @@ "package_ratings_circuit_unknown": { "message": "このパネルには、その ID の回路がありません。" }, - "package_ratings_panel_not_loaded": { - "message": "SPAN Panel が読み込まれていないため、定格をコピーすることもクリアすることもできません。" - }, "circuit_priority_failed": { "message": "{circuit}の優先度変更は拒否されました: {reason}。パネルには何も送信されていないため、優先度は変わっていません。" }, @@ -560,7 +557,13 @@ "message": "エンティティ {entity_id} は、設定エントリ {config_entry_id} とは別の SPAN Panel に属しています。config_entry_id を省略するか、エンティティ自身のパネルを指定してください。" }, "monitoring_not_enabled": { - "message": "電流監視が有効なSPANパネルがありません。" + "message": "この SPAN Panel では電流監視がオフになっています。しきい値を変更する前にオンにしてください。" + }, + "monitoring_panel_not_loaded": { + "message": "SPAN Panel が読み込まれていないため、電流監視とその判定に使う定格を読み取ることも変更することもできません。" + }, + "monitoring_panel_unknown": { + "message": "設定エントリ {config_entry_id} を持つ SPAN Panel がないため、読み取りや変更ができる監視はありません。" }, "panel_auth_failed": { "message": "SPAN Panelとの認証に失敗しました。再認証してください。" diff --git a/custom_components/span_panel/translations/pt.json b/custom_components/span_panel/translations/pt.json index 70f91148..f57efd21 100644 --- a/custom_components/span_panel/translations/pt.json +++ b/custom_components/span_panel/translations/pt.json @@ -484,9 +484,6 @@ "package_ratings_circuit_unknown": { "message": "Este painel não tem nenhum circuito com esse identificador." }, - "package_ratings_panel_not_loaded": { - "message": "Não há nenhum SPAN Panel carregado, por isso não é possível copiar nem limpar capacidades." - }, "circuit_priority_failed": { "message": "A alteração de prioridade para {circuit} foi recusada: {reason}. Nada foi enviado ao painel, portanto a prioridade permanece inalterada." }, @@ -560,7 +557,13 @@ "message": "A entidade {entity_id} pertence a um SPAN Panel diferente da entrada de configuração {config_entry_id}. Omita config_entry_id ou indique o painel da própria entidade." }, "monitoring_not_enabled": { - "message": "Nenhum painel SPAN com monitoramento de corrente ativado." + "message": "A monitorização de corrente está desativada neste SPAN Panel. Ative-a antes de alterar os seus limiares." + }, + "monitoring_panel_not_loaded": { + "message": "O SPAN Panel não está carregado, por isso a sua monitorização de corrente, e as capacidades com que a avalia, não podem ser lidas nem alteradas." + }, + "monitoring_panel_unknown": { + "message": "Nenhum SPAN Panel tem a entrada de configuração {config_entry_id}, por isso não há monitorização para ler nem alterar." }, "panel_auth_failed": { "message": "A autenticação com o SPAN Panel falhou. Por favor, reautentique." diff --git a/custom_components/span_panel/util.py b/custom_components/span_panel/util.py index 55dd7c4e..25416b27 100644 --- a/custom_components/span_panel/util.py +++ b/custom_components/span_panel/util.py @@ -597,3 +597,38 @@ def effective_circuit_device_name( if device is not None and device.name_by_user: return device.name_by_user return circuit_device_name(circuit, circuit_id) + + +def circuit_display_name( + device_registry: DeviceRegistry, + serial: str, + circuit: SpanCircuitSnapshot, + circuit_id: str, + *, + config_entry_id: str, +) -> str: + """Return a circuit's name as Home Assistant shows it, for text that names the circuit to a person. + + Its own device's name (`device_display_name`): the user's where they renamed + the device, else the name it is registered under. Read from the registry + each time it is asked, so a rename made since setup is the name the next + message carries. Unlike `effective_circuit_device_name`, a registered + device's `name` is read rather than the one it is about to be given: + between a rename on the panel and the reload that renames the device, Home + Assistant still shows the old one. + + A circuit with no device takes the name `circuit_device_info` would give it + (`circuit_device_name`). A charger's feed circuit has none where it has + neither a breaker switch nor a priority select, and on the first setup after + an upgrade from a release before circuits had devices, the monitor judges + pushes before they are registered. + + A circuit's device is always registered under a name, and Home Assistant + offers a user no way to clear it. + """ + device = circuit_device(device_registry, serial, circuit_id, config_entry_id=config_entry_id) + if device is None: + return circuit_device_name(circuit, circuit_id) + if not (name := device_display_name(device)): + raise RuntimeError(f"The device of circuit {circuit_id} has no name to show") + return name diff --git a/frontend.md b/frontend.md index a1a9ff88..c6620671 100644 --- a/frontend.md +++ b/frontend.md @@ -80,42 +80,43 @@ user. Any user can read monitoring's settings and status. - **Priority** — Notification priority level (controls iOS interruption level and Android notification channel) - **Title/Message Templates** — Customizable templates with the following variables: - | Variable | Description | Example | - | -------------------- | ---------------------------------------------------- | --------------------------- | - | `{name}` | The circuit's name in the SPAN app, or the mains leg | Kitchen Oven | - | `{entity_id}` | HA entity ID | sensor.kitchen_oven_current | - | `{alert_type}` | Alert category | spike, continuous_overload | - | `{current_a}` | Current draw in amps | 18.3 | - | `{breaker_rating_a}` | Rating in amps the circuit is judged against | 20 | - | `{threshold_pct}` | Configured threshold percentage | 80 | - | `{utilization_pct}` | Actual utilization percentage | 91.5 | - | `{window_m}` | Window duration in minutes | 5 | - | `{local_time}` | Local time of the alert | 2:15 PM | + | Variable | Description | Example | + | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | + | `{name}` | The circuit's name as Home Assistant shows it, the name you gave its device where you renamed it, or the mains leg; for circuits that share a meter, their names joined with " + " | Kitchen Oven | + | `{entity_id}` | The entity ID of the circuit's Current sensor, or its Power sensor where it has none; for circuits that share a meter, that of the circuit the event's `alert_id` names; for the mains, the leg's Current sensor | sensor.kitchen_oven_current | + | `{alert_type}` | Alert category | spike, continuous_overload | + | `{current_a}` | Current draw in amps | 18.3 | + | `{breaker_rating_a}` | Rating in amps the circuit is judged against | 20 | + | `{threshold_pct}` | Configured threshold percentage | 80 | + | `{utilization_pct}` | Actual utilization percentage | 91.5 | + | `{window_m}` | Window duration in minutes | 5 | + | `{local_time}` | Local time of the alert | 2:15 PM | `{breaker_rating_a}` keeps its name so existing templates still work, but it carries the rating the circuit is judged against: both breakers of a tandem whose ratings you copied from the SPAN app, else the breaker rating the panel publishes. - **Event bus** — With the HA event bus selected, each alert fires a `span_panel_current_alert` event for automations. Its data: - | Key | Description | - | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | - | `alert_source` | `circuit` or `mains` | - | `alert_id` | The circuit's id, or the mains leg (such as `upstream_l1`) | - | `alert_name` | The circuit's name in the SPAN app, or the mains leg | - | `alert_type` | `spike` or `continuous_overload` | - | `current_a` | Current draw in amps | - | `breaker_rating_a` | The breaker rating the panel publishes; for circuits that share a meter, the group's capacity over those ratings, and null if any has none | - | `monitoring_rating_a` | The rating the alert judged against: both breakers of a tandem whose ratings you copied from the SPAN app, else the panel's rating | - | `monitoring_rating_user_set` | Whether `monitoring_rating_a` comes from ratings you copied | - | `package_ratings_a` | The ratings you copied from the SPAN app, such as `[20, 30]`; null where there are none, and for a shared meter and the mains | - | `package_ratings_state` | `applies`, or `averaged_legs` where a copy across two spaces is kept but not applied; null where `package_ratings_a` is | - | `threshold_pct` | Configured threshold percentage | - | `utilization_pct` | Actual utilization percentage, against `monitoring_rating_a` | - | `panel_serial` | The panel's serial number | - | `local_time` | Local time of the alert | - | `window_duration_s` | Seconds spent over the continuous threshold (continuous overloads; the test event carries a sample) | - | `over_threshold_since` | When the circuit went over the continuous threshold, as an ISO 8601 time (continuous overloads only) | - | `test` | Present, and true, only on the event the test notification fires | + | Key | Description | + | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | + | `alert_source` | `circuit` or `mains` | + | `alert_id` | The circuit's id, or the mains leg (such as `upstream_l1`) | + | `alert_name` | The circuit's name in the SPAN app, or the mains leg; renaming the circuit's device in Home Assistant leaves it as it is | + | `alert_display_name` | The circuit's name as Home Assistant shows it, the name you gave its device where you renamed it, which the notification's `{name}` carries; for circuits that share a meter, their names joined with " + "; for the mains, the same as `alert_name` | + | `alert_type` | `spike` or `continuous_overload` | + | `current_a` | Current draw in amps | + | `breaker_rating_a` | The breaker rating the panel publishes; for circuits that share a meter, the group's capacity over those ratings, and null if any has none | + | `monitoring_rating_a` | The rating the alert judged against: both breakers of a tandem whose ratings you copied from the SPAN app, else the panel's rating | + | `monitoring_rating_user_set` | Whether `monitoring_rating_a` comes from ratings you copied | + | `package_ratings_a` | The ratings you copied from the SPAN app, such as `[20, 30]`; null where there are none, and for a shared meter and the mains | + | `package_ratings_state` | `applies`, or `averaged_legs` where a copy across two spaces is kept but not applied; null where `package_ratings_a` is | + | `threshold_pct` | Configured threshold percentage | + | `utilization_pct` | Actual utilization percentage, against `monitoring_rating_a` | + | `panel_serial` | The panel's serial number | + | `local_time` | Local time of the alert | + | `window_duration_s` | Seconds spent over the continuous threshold (continuous overloads; the test event carries a sample) | + | `over_threshold_since` | When the circuit went over the continuous threshold, as an ISO 8601 time (continuous overloads only) | + | `test` | Present, and true, only on the event the test notification fires | Copied ratings never change `breaker_rating_a`, which is the panel's rating, as the Breaker Rating sensor shows. The rating the `{breaker_rating_a}` text placeholder carries is `monitoring_rating_a` here. For the mains both are its rating, `monitoring_rating_user_set` is false and `package_ratings_a` and diff --git a/tests/replayed_panel.py b/tests/replayed_panel.py index a459f66b..f17847b0 100644 --- a/tests/replayed_panel.py +++ b/tests/replayed_panel.py @@ -28,8 +28,8 @@ CONF_EBUS_BROKER_PORT, CONF_EBUS_BROKER_USERNAME, DOMAIN, - ENABLE_CURRENT_MONITORING, ) +from custom_components.span_panel.current_monitor import StoredMonitoring, _store_for from custom_components.span_panel.id_builder import ( build_circuit_device_identifier, build_circuit_unique_id, @@ -45,12 +45,6 @@ PANEL_NAME: Final = "Span Panel" -MONITORED_OPTIONS: Final[Mapping[str, object]] = { - **FRESH_INSTALL_OPTIONS, - ENABLE_CURRENT_MONITORING: True, -} -"""A fresh install's options, with current monitoring switched on.""" - # --------------------------------------------------------------------------- # One panel, over the trees a test sets it up on @@ -64,7 +58,10 @@ class Panel: hass: HomeAssistant entry: MockConfigEntry tree: RetainedTree + monitored: bool = False + """Whether current monitoring was switched on before the first setup, as the store records it.""" clients: list[ReplayClient] = field(default_factory=list) + _seeded: bool = False def client(self) -> ReplayClient: """Build the client a setup connects with, over the tree served now.""" @@ -92,11 +89,25 @@ def serial(self) -> str: async def set_up(self, tree: RetainedTree) -> None: """Set the entry up over `tree`, then stream it once, as a live panel's first push.""" self.tree = tree + if self.monitored and not self._seeded: + await self._switch_monitoring_on() assert await self.hass.config_entries.async_setup(self.entry.entry_id) is True await self.hass.async_block_till_done() assert self.entry.state is ConfigEntryState.LOADED await self.push(tree) + async def _switch_monitoring_on(self) -> None: + """Record monitoring as on in the store, keeping whatever else a test seeded there. + + Once, before the first setup: a later setup reads whatever the test has + made of it since. + """ + store = _store_for(self.hass, self.entry) + stored = await store.async_load() or StoredMonitoring() + stored["enabled"] = True + await store.async_save(stored) + self._seeded = True + async def push(self, tree: RetainedTree) -> None: """Stream `tree` to the running session, as the panel publishing it does.""" await self.clients[-1].push(replay(tree)) @@ -158,7 +169,8 @@ def replayed_panels(hass: HomeAssistant) -> Iterator[Callable[..., Panel]]: def make( tree: RetainedTree, *, - options: Mapping[str, object] = MONITORED_OPTIONS, + options: Mapping[str, object] = FRESH_INSTALL_OPTIONS, + monitored: bool = True, entry_id: str = "entry-device-ids", ) -> Panel: serial = snapshot(tree).serial_number @@ -181,7 +193,7 @@ def make( minor_version=CURRENT_CONFIG_MINOR_VERSION, ) entry.add_to_hass(hass) - made[serial] = Panel(hass, entry, tree) + made[serial] = Panel(hass, entry, tree, monitored=monitored) return made[serial] def client_for(_host: str, serial: str, *_args: object, **_kwargs: object) -> ReplayClient: diff --git a/tests/test_alert_display_names.py b/tests/test_alert_display_names.py new file mode 100644 index 00000000..a1ab43d0 --- /dev/null +++ b/tests/test_alert_display_names.py @@ -0,0 +1,456 @@ +"""A current alert's text names the circuit as Home Assistant shows it; its event keeps the panel's name. + +A user who renames a circuit's device in Home Assistant finds it under that name +everywhere Home Assistant shows it, so a notification naming the circuit by the +panel's name names one they cannot find. The notification's title and message, +through `{name}`, carry the device's name as Home Assistant shows it +(`util.circuit_display_name`), read when the alert fires, so a rename made since +setup reaches the next alert. Their `{entity_id}` is the entity ID of the +point's Current sensor, as the documentation has always said. + +The `span_panel_current_alert` event is read by automations, so its +`alert_name` stays the panel's name and its `alert_id` the circuit's id, and +`alert_display_name` carries the name the text uses beside them. +""" + +from __future__ import annotations + +from dataclasses import replace +from datetime import UTC, datetime, timedelta +from typing import Final + +from homeassistant.core import Event, HomeAssistant, ServiceCall +from homeassistant.helpers import device_registry as dr, entity_registry as er +import pytest +from pytest_homeassistant.common import MockConfigEntry, async_capture_events, async_mock_service +from span_panel_api import FieldMetadata, SpanCircuitSnapshot, SpanPanelSnapshot + +from custom_components.span_panel.alert_dispatcher import dispatch_test_alert +from custom_components.span_panel.const import DOMAIN, EVENT_CURRENT_ALERT +from custom_components.span_panel.current_monitor import CurrentMonitor +from custom_components.span_panel.id_builder import build_circuit_unique_id, build_panel_unique_id +from custom_components.span_panel.options import ( + CONTINUOUS_THRESHOLD_PCT, + NOTIFICATION_MESSAGE_TEMPLATE, + NOTIFICATION_TITLE_TEMPLATE, + NOTIFY_TARGETS, + SPIKE_THRESHOLD_PCT, + WINDOW_DURATION_M, +) +from custom_components.span_panel.package_rating_manager import PackageRatingManager + +from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory +from .helpers import register_circuit_device, register_panel_device + +SERIAL: Final = "sp3-display-001" +_DECLARED: Final = {"panel.main_breaker_rating_a": FieldMetadata(unit="A", datatype="integer")} +_NOTIFY_SERVICE: Final = "synthetic_phone" +_TITLE: Final = "SPAN: {name} {alert_type}" +_MESSAGE: Final = "{name} at {current_a}A" + + +def _circuit( + circuit_id: str, + name: str, + tab: int, + *, + current_a: float = 25.0, + device_type: str = "circuit", +) -> SpanCircuitSnapshot: + """Return a 20 A circuit drawing `current_a`, over its rating by default, so it spikes.""" + return SpanCircuitSnapshotFactory.create( + circuit_id=circuit_id, + name=name, + tabs=[tab], + breaker_rating_a=20.0, + current_a=current_a, + device_type=device_type, + ) + + +def _panel(*circuits: SpanCircuitSnapshot) -> SpanPanelSnapshot: + """Return a panel whose mains draw too little to alert, so every alert is a circuit's.""" + return SpanPanelSnapshotFactory.create( + serial_number=SERIAL, + circuits={c.circuit_id: c for c in circuits}, + main_breaker_rating_a=200, + upstream_l1_current_a=1.0, + upstream_l2_current_a=1.0, + downstream_l1_current_a=1.0, + downstream_l2_current_a=1.0, + ) + + +class _Panel: + """One panel's entry, its registered panel device and its monitor.""" + + def __init__( + self, hass: HomeAssistant, entry: MockConfigEntry, monitor: CurrentMonitor + ) -> None: + self.hass = hass + self.entry = entry + self.monitor = monitor + self.panel_device_id = register_panel_device(hass, entry, SERIAL) + + def register(self, circuit: SpanCircuitSnapshot) -> dr.ChildDeviceEntry: + """Register the circuit's own device, as its first entity would.""" + return register_circuit_device( + self.hass, self.entry, SERIAL, circuit, panel_device_id=self.panel_device_id + ) + + def rename(self, device: dr.ChildDeviceEntry, name: str) -> None: + """Rename the device in Home Assistant, as a user does on its page.""" + dr.async_get(self.hass).async_update_child_device(device.id, name_by_user=name) + + def sensor(self, unique_id: str, object_id: str) -> str: + """Register one of the panel's sensors under `unique_id`, as its platform would, and return its entity ID.""" + return ( + er.async_get(self.hass) + .async_get_or_create( + "sensor", DOMAIN, unique_id, config_entry=self.entry, suggested_object_id=object_id + ) + .entity_id + ) + + +async def _set_up(hass: HomeAssistant, snapshot: SpanPanelSnapshot, **options: object) -> _Panel: + entry = MockConfigEntry( + domain=DOMAIN, + data={}, + unique_id=SERIAL, + options={ + SPIKE_THRESHOLD_PCT: 100, + NOTIFY_TARGETS: f"event_bus, notify.{_NOTIFY_SERVICE}", + NOTIFICATION_TITLE_TEMPLATE: _TITLE, + NOTIFICATION_MESSAGE_TEMPLATE: _MESSAGE, + **options, + }, + ) + entry.add_to_hass(hass) + manager = PackageRatingManager(hass, entry) + await manager.async_load() + manager.begin(snapshot, _DECLARED) + return _Panel(hass, entry, CurrentMonitor(hass, entry, manager, snapshot)) + + +async def _judge(panel: _Panel, snapshot: SpanPanelSnapshot) -> None: + panel.monitor.process_snapshot(snapshot) + await panel.hass.async_block_till_done() + + +def _texts(calls: list[ServiceCall]) -> list[tuple[object, object]]: + return [(call.data["title"], call.data["message"]) for call in calls] + + +def _names(events: list[Event]) -> list[tuple[object, object]]: + return [(event.data["alert_name"], event.data["alert_display_name"]) for event in events] + + +@pytest.fixture +def notified(hass: HomeAssistant) -> list[ServiceCall]: + """Every call to the notify target the panel's alerts are sent to.""" + return async_mock_service(hass, "notify", _NOTIFY_SERVICE) + + +@pytest.fixture +def alerts(hass: HomeAssistant) -> list[Event]: + """Every `span_panel_current_alert` event fired.""" + return async_capture_events(hass, EVENT_CURRENT_ALERT) + + +async def test_a_renamed_circuits_notification_carries_the_rename( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """The title and message name the circuit by the user's name, and the event's `alert_name` stays the panel's.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + panel.rename(panel.register(circuit), "Synthetic Workshop") + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Synthetic Workshop spike", "Synthetic Workshop at 25.0A")] + assert _names(alerts) == [("Panel Name Seven", "Synthetic Workshop")] + + +async def test_a_rename_after_setup_reaches_the_next_alert( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """The name is read when the alert fires, not when the monitor is built.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + device = panel.register(circuit) + await _judge(panel, snapshot) + + panel.rename(device, "Synthetic Workshop") + state = panel.monitor.get_circuit_state("circuit-7") + assert state is not None + # Past the cooldown, so the same spike alerts again. + state.last_spike_alert = datetime.now(UTC) - timedelta(hours=1) + await _judge(panel, snapshot) + + assert _texts(notified) == [ + ("SPAN: Panel Name Seven spike", "Panel Name Seven at 25.0A"), + ("SPAN: Synthetic Workshop spike", "Synthetic Workshop at 25.0A"), + ] + assert _names(alerts) == [ + ("Panel Name Seven", "Panel Name Seven"), + ("Panel Name Seven", "Synthetic Workshop"), + ] + + +async def test_an_unrenamed_circuit_is_named_as_before( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """A circuit nobody renamed is named by the panel's name, in its text and in both event fields.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + panel.register(circuit) + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Panel Name Seven spike", "Panel Name Seven at 25.0A")] + assert _names(alerts) == [("Panel Name Seven", "Panel Name Seven")] + + +async def test_a_circuit_with_no_device_is_named_as_its_device_would_be( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """A circuit with no device takes the name `circuit_device_info` would give it (`circuit_device_name`). + + A charger's feed circuit has none where it has neither a breaker switch nor + a priority select, and on the first setup after an upgrade from a release + before circuits had devices, the monitor judges pushes before they are + registered. + """ + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Panel Name Seven spike", "Panel Name Seven at 25.0A")] + assert _names(alerts) == [("Panel Name Seven", "Panel Name Seven")] + + +async def test_a_shared_meter_is_named_by_each_members_name_as_home_assistant_shows_it( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """A shared meter's alert joins its members' names, each the user's where they renamed it. + + Two 20 A circuits at one space carry 40 A together, so both report 45 A. + """ + first = replace( + _circuit("circuit-52", "Panel Name A", 44, current_a=45.0), + meter_shared_with=("circuit-53",), + relay_shared_with=("circuit-53",), + ) + second = replace( + _circuit("circuit-53", "Panel Name B", 44, current_a=45.0), + meter_shared_with=("circuit-52",), + relay_shared_with=("circuit-52",), + ) + snapshot = replace(_panel(first, second), publishes_shared_meters=True) + panel = await _set_up(hass, snapshot) + panel.rename(panel.register(first), "Synthetic Fan") + panel.register(second) + + await _judge(panel, snapshot) + + assert _texts(notified) == [ + ("SPAN: Synthetic Fan + Panel Name B spike", "Synthetic Fan + Panel Name B at 45.0A") + ] + assert _names(alerts) == [("Panel Name A + Panel Name B", "Synthetic Fan + Panel Name B")] + + +async def test_the_mains_is_named_by_its_own_name( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """The mains has no device of its own: its text and both event fields carry the leg's name.""" + snapshot = replace(_panel(), upstream_l1_current_a=250.0) + panel = await _set_up(hass, snapshot) + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Mains Upstream L1 spike", "Mains Upstream L1 at 250.0A")] + assert _names(alerts) == [("Mains Upstream L1", "Mains Upstream L1")] + + +async def test_the_test_event_carries_the_display_name_too( + hass: HomeAssistant, alerts: list[Event] +) -> None: + """An automation written against the test event finds `alert_display_name` beside `alert_name`.""" + dispatch_test_alert(hass, {NOTIFY_TARGETS: "event_bus"}) + await hass.async_block_till_done() + + assert _names(alerts) == [("Kitchen Oven", "Kitchen Oven")] + + +async def test_an_unnamed_solar_circuit_with_no_device_is_named_solar( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """Its device would be named "Solar", so its text is, while `alert_name` keeps its positions. + + The name its device would be given, not the label a message used before: + once the device is registered, Home Assistant shows "Solar". + """ + circuit = _circuit("circuit-7", "", 7, device_type="pv") + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Solar spike", "Solar at 25.0A")] + assert _names(alerts) == [("Circuit 7", "Solar")] + + +async def test_a_continuous_overload_names_the_circuit_as_home_assistant_shows_it( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """The sustained alert's text carries the rename, as the spike's does.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7, current_a=18.0) + snapshot = _panel(circuit) + panel = await _set_up( + hass, + snapshot, + **{SPIKE_THRESHOLD_PCT: 500, CONTINUOUS_THRESHOLD_PCT: 80, WINDOW_DURATION_M: 15}, + ) + panel.rename(panel.register(circuit), "Synthetic Workshop") + await _judge(panel, snapshot) + state = panel.monitor.get_circuit_state("circuit-7") + assert state is not None + # Over the threshold for longer than the window. + state.over_threshold_since = datetime.now(UTC) - timedelta(minutes=16) + + await _judge(panel, snapshot) + + assert _texts(notified) == [ + ("SPAN: Synthetic Workshop continuous_overload", "Synthetic Workshop at 18.0A") + ] + assert _names(alerts) == [("Panel Name Seven", "Synthetic Workshop")] + + +async def test_a_circuit_renamed_on_the_panel_keeps_the_name_home_assistant_shows_until_its_reload( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """Between a rename on the panel and the reload that renames its device, Home Assistant shows the old name. + + So the text carries the name the device is registered under, not the one it + is about to be given, which `effective_circuit_device_name` answers for an + entity id. The event's `alert_name` is the panel's, so it already carries the + new one. + """ + registered = _circuit("circuit-7", "Old Panel Name", 7) + snapshot = _panel(replace(registered, name="New Panel Name")) + panel = await _set_up(hass, snapshot) + panel.register(registered) + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Old Panel Name spike", "Old Panel Name at 25.0A")] + assert _names(alerts) == [("New Panel Name", "Old Panel Name")] + + +@pytest.mark.usefixtures("notified") +async def test_the_monitoring_status_keeps_the_panels_name_after_a_rename( + hass: HomeAssistant, +) -> None: + """Scripts read the status's `name`, so a rename in Home Assistant leaves it the panel's.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + panel.rename(panel.register(circuit), "Synthetic Workshop") + + await _judge(panel, snapshot) + + assert [c["name"] for c in panel.monitor.get_monitoring_status()["circuits"].values()] == [ + "Panel Name Seven" + ] + + +_ENTITY_TITLE: Final = {NOTIFICATION_TITLE_TEMPLATE: "{entity_id}"} + + +def _titles(calls: list[ServiceCall]) -> list[object]: + return [call.data["title"] for call in calls] + + +def _alert_ids(events: list[Event]) -> list[object]: + return [event.data["alert_id"] for event in events] + + +async def test_entity_id_is_the_circuits_current_sensor( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """`{entity_id}` carries the circuit's Current sensor, while the event's `alert_id` stays the circuit's id.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot, **_ENTITY_TITLE) + panel.sensor(build_circuit_unique_id(SERIAL, "circuit-7", "instantPowerW"), "seven_power") + current = panel.sensor(build_circuit_unique_id(SERIAL, "circuit-7", "current"), "seven_current") + + await _judge(panel, snapshot) + + assert _titles(notified) == [current] + assert current == "sensor.seven_current" + assert _alert_ids(alerts) == ["circuit-7"] + + +async def test_entity_id_is_the_power_sensor_of_a_circuit_without_a_current_sensor( + hass: HomeAssistant, notified: list[ServiceCall] +) -> None: + """A circuit whose current arrived after setup has no Current sensor yet, so its Power sensor stands in. + + The Monitoring tab shows the circuit under the same entity. + """ + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot, **_ENTITY_TITLE) + power = panel.sensor( + build_circuit_unique_id(SERIAL, "circuit-7", "instantPowerW"), "seven_power" + ) + + await _judge(panel, snapshot) + + assert _titles(notified) == [power] + + +async def test_entity_id_of_a_shared_meter_is_the_sensor_of_the_circuit_alert_id_names( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """A shared meter is judged under its first member's id, and `{entity_id}` is that member's sensor.""" + first = replace( + _circuit("circuit-52", "Panel Name A", 44, current_a=45.0), + meter_shared_with=("circuit-53",), + relay_shared_with=("circuit-53",), + ) + second = replace( + _circuit("circuit-53", "Panel Name B", 44, current_a=45.0), + meter_shared_with=("circuit-52",), + relay_shared_with=("circuit-52",), + ) + snapshot = replace(_panel(first, second), publishes_shared_meters=True) + panel = await _set_up(hass, snapshot, **_ENTITY_TITLE) + current = panel.sensor(build_circuit_unique_id(SERIAL, "circuit-52", "current"), "a_current") + panel.sensor(build_circuit_unique_id(SERIAL, "circuit-53", "current"), "b_current") + + await _judge(panel, snapshot) + + assert _titles(notified) == [current] + assert _alert_ids(alerts) == ["circuit-52"] + + +async def test_entity_id_of_the_mains_is_the_legs_current_sensor( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """The mains leg's Current sensor, while the event's `alert_id` stays the leg.""" + snapshot = replace(_panel(), upstream_l1_current_a=250.0) + panel = await _set_up(hass, snapshot, **_ENTITY_TITLE) + leg = panel.sensor(build_panel_unique_id(SERIAL, "upstream_l1_current"), "upstream_l1_current") + + await _judge(panel, snapshot) + + assert _titles(notified) == [leg] + assert _alert_ids(alerts) == ["upstream_l1"] diff --git a/tests/test_current_monitor.py b/tests/test_current_monitor.py index c05812d0..b778c075 100644 --- a/tests/test_current_monitor.py +++ b/tests/test_current_monitor.py @@ -16,12 +16,13 @@ DEFAULT_SPIKE_THRESHOLD_PCT, DEFAULT_WINDOW_DURATION_M, DOMAIN, - ENABLE_CURRENT_MONITORING, EVENT_CURRENT_ALERT, ) from homeassistant.core import CoreState from homeassistant.exceptions import ServiceValidationError +from homeassistant.helpers import device_registry as dr +from custom_components.span_panel.alert_dispatcher import format_notification from custom_components.span_panel.package_rating_manager import PackageRatingManager from custom_components.span_panel.current_monitor import CurrentMonitor from custom_components.span_panel.curation import CurationOverlay @@ -47,7 +48,6 @@ def _make_options(**overrides): """Create options dict with monitoring enabled and defaults.""" opts = { - ENABLE_CURRENT_MONITORING: True, CONTINUOUS_THRESHOLD_PCT: DEFAULT_CONTINUOUS_THRESHOLD_PCT, SPIKE_THRESHOLD_PCT: DEFAULT_SPIKE_THRESHOLD_PCT, WINDOW_DURATION_M: DEFAULT_WINDOW_DURATION_M, @@ -106,6 +106,9 @@ def _make_hass(): hass.states = MagicMock() hass.states.get = MagicMock(return_value=None) hass.async_create_task = MagicMock(side_effect=_run_coro) + # Its device registry holds no device, as before a panel's entities register + # theirs, so an alert names each circuit by the name its device will be given. + dr.async_get(hass).async_get_child_device_by_identifier.return_value = None return hass @@ -664,8 +667,16 @@ def _panel_with_a_fresh_monitor( def _loaded(hass: MagicMock, *entries: MagicMock) -> None: - """Make these the loaded entries, in this order: the first is the old default panel.""" + """Make these the loaded entries, in this order: the first is the old default panel. + + They are the SPAN Panel entries Home Assistant holds too, so a call naming + one finds it, and a call naming any other id names no panel. + """ + for entry in entries: + entry.domain = DOMAIN + by_id = {entry.entry_id: entry for entry in entries} hass.config_entries.async_loaded_entries = MagicMock(return_value=list(entries)) + hass.config_entries.async_get_entry = MagicMock(side_effect=by_id.get) def _call(**data: Any) -> MagicMock: @@ -719,7 +730,10 @@ async def test_the_override_of_a_circuit_that_left_the_panel_is_cleared(self): assert "gone" not in monitor._circuit_overrides async def test_an_entity_whose_panel_is_not_loaded_says_so(self): - """Not that monitoring is off: nothing about monitoring was read.""" + """Not that monitoring is off: nothing about monitoring was read. + + Said as every monitoring service says it, which the card waits on. + """ hass = _make_hass() entry, _monitor, _snapshot = _panel_with_a_fresh_monitor(hass, "panel_a", "c-1") _loaded(hass, entry) @@ -731,8 +745,7 @@ async def test_an_entity_whose_panel_is_not_loaded_says_so(self): ): await handlers["clear_circuit_threshold"](_call(circuit_id="sensor.b_c_1_current")) - assert raised.value.translation_key == "favorite_panel_not_loaded" - assert raised.value.translation_placeholders == {"entity_id": "sensor.b_c_1_current"} + assert raised.value.translation_key == "monitoring_panel_not_loaded" def _drawing(current_a: float) -> SpanPanelSnapshot: @@ -1072,10 +1085,10 @@ def test_no_notifications_during_startup(self): def test_notification_message_format_spike(self): """Spike notification message includes current and rating.""" - title, message = CurrentMonitor._format_notification( + title, message = format_notification( alert_type="spike", - alert_name="Kitchen", - alert_id="sensor.kitchen_current", + display_name="Kitchen", + entity_id="sensor.kitchen_current", current_a=22.1, monitoring_rating_a=20.0, threshold_pct=100, @@ -1091,10 +1104,10 @@ def test_notification_message_format_spike(self): def test_notification_message_format_continuous(self): """Continuous notification message includes window duration.""" - title, message = CurrentMonitor._format_notification( + title, message = format_notification( alert_type="continuous_overload", - alert_name="Kitchen", - alert_id="sensor.kitchen_current", + display_name="Kitchen", + entity_id="sensor.kitchen_current", current_a=18.4, monitoring_rating_a=20.0, threshold_pct=80, @@ -1114,10 +1127,10 @@ def test_notification_message_format_continuous(self): def test_notification_custom_template_with_entity_id(self): """Custom templates produce expected output with entity_id placeholder.""" - title, message = CurrentMonitor._format_notification( + title, message = format_notification( alert_type="spike", - alert_name="Kitchen", - alert_id="sensor.kitchen_current", + display_name="Kitchen", + entity_id="sensor.kitchen_current", current_a=22.1, monitoring_rating_a=20.0, threshold_pct=100, @@ -1131,10 +1144,10 @@ def test_notification_custom_template_with_entity_id(self): def test_notification_invalid_template_falls_back(self): """Invalid template placeholders fall back to defaults.""" - title, message = CurrentMonitor._format_notification( + title, message = format_notification( alert_type="spike", - alert_name="Kitchen", - alert_id="sensor.kitchen_current", + display_name="Kitchen", + entity_id="sensor.kitchen_current", current_a=22.1, monitoring_rating_a=20.0, threshold_pct=100, diff --git a/tests/test_current_monitor_services.py b/tests/test_current_monitor_services.py index edf8833f..68c5b72f 100644 --- a/tests/test_current_monitor_services.py +++ b/tests/test_current_monitor_services.py @@ -2,23 +2,30 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import replace -from typing import Final -from unittest.mock import MagicMock +from typing import Any, Final +from unittest.mock import AsyncMock, MagicMock -from homeassistant.config_entries import ConfigEntryState +from homeassistant.config_entries import ConfigEntryDisabler, ConfigEntryState from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ServiceValidationError import probatio as vol import pytest from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.typing import WebSocketGenerator from span_panel_api import FieldMetadata, SpanPanelSnapshot from custom_components.span_panel.const import DOMAIN from custom_components.span_panel.curation import CurationOverlay from custom_components.span_panel.current_monitor import CurrentMonitor +from custom_components.span_panel.options import SPIKE_THRESHOLD_PCT from custom_components.span_panel.package_rating_manager import PackageRatingManager from custom_components.span_panel.runtime import SpanPanelRuntimeData -from custom_components.span_panel.services import _async_register_monitoring_services +from custom_components.span_panel.services import ( + _async_register_monitoring_services, + _async_register_package_rating_services, +) from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory, pv_binding_for from .helpers import register_panel_device @@ -82,8 +89,10 @@ def _rated_panel(*, publishes_shared_meters: bool | None) -> SpanPanelSnapshot: return replace(snapshot, publishes_shared_meters=publishes_shared_meters) -async def _monitoring_status(hass: HomeAssistant, snapshot: SpanPanelSnapshot) -> dict[str, object]: - """Answer `get_monitoring_status` for a panel set up on, and still holding, `snapshot`.""" +async def _load_panel( + hass: HomeAssistant, snapshot: SpanPanelSnapshot, *, monitored: bool = True +) -> MockConfigEntry: + """Return the entry of a panel set up on, and still holding, `snapshot`, with monitoring on or off.""" entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=snapshot.serial_number) entry.add_to_hass(hass) manager = PackageRatingManager(hass, entry) @@ -92,7 +101,11 @@ async def _monitoring_status(hass: HomeAssistant, snapshot: SpanPanelSnapshot) - coordinator = MagicMock() coordinator.data = snapshot coordinator.package_rating_manager = manager - coordinator.current_monitor = CurrentMonitor(hass, entry, manager, snapshot) + # Awaited when the harness unloads the entry at teardown. + coordinator.async_shutdown = AsyncMock() + coordinator.current_monitor = ( + CurrentMonitor(hass, entry, manager, snapshot) if monitored else None + ) entry.runtime_data = SpanPanelRuntimeData( coordinator=coordinator, panel_device_id=register_panel_device(hass, entry, snapshot.serial_number), @@ -101,15 +114,25 @@ async def _monitoring_status(hass: HomeAssistant, snapshot: SpanPanelSnapshot) - setup_snapshot=snapshot, ) entry.mock_state(hass, ConfigEntryState.LOADED) - _async_register_monitoring_services(hass) + return entry + +async def _ask_for_status(hass: HomeAssistant, **fields: str) -> dict[str, object]: + """Call `get_monitoring_status` with `fields` and return its answer.""" response = await hass.services.async_call( - DOMAIN, "get_monitoring_status", {}, blocking=True, return_response=True + DOMAIN, "get_monitoring_status", fields, blocking=True, return_response=True ) assert response is not None return dict(response) +async def _monitoring_status(hass: HomeAssistant, snapshot: SpanPanelSnapshot) -> dict[str, object]: + """Answer `get_monitoring_status` for a panel set up on, and still holding, `snapshot`.""" + await _load_panel(hass, snapshot) + _async_register_monitoring_services(hass) + return await _ask_for_status(hass) + + class TestMonitoringStatusSaysWhetherThePanelTakesCopies: """The status root says, as the topology root does, whether the panel takes copied package ratings.""" @@ -130,3 +153,307 @@ async def test_the_root_carries_monitoring_rating_offered( assert status["enabled"] is True assert status["monitoring_rating_offered"] is offered + + +def _unloaded_entry( + hass: HomeAssistant, state: ConfigEntryState, *, disabled: bool = False +) -> MockConfigEntry: + """Return a SPAN Panel entry Home Assistant holds in `state`, which is not loaded.""" + entry = MockConfigEntry( + domain=DOMAIN, + data={}, + unique_id="sp3-unloaded-001", + disabled_by=ConfigEntryDisabler.USER if disabled else None, + ) + entry.add_to_hass(hass) + entry.mock_state(hass, state) + return entry + + +def _another_integrations_entry(hass: HomeAssistant) -> MockConfigEntry: + """Return a loaded config entry that belongs to another integration.""" + entry = MockConfigEntry(domain="synthetic_other", data={}) + entry.add_to_hass(hass) + entry.mock_state(hass, ConfigEntryState.LOADED) + return entry + + +class TestMonitoringStatusRefusesAPanelThatIsNotLoaded: + """A panel that is not loaded is refused, never reported as having monitoring off. + + A script asking while Home Assistant starts, or while the integration retries + a panel it cannot reach, was told `{"enabled": False}` of a panel whose + monitoring is on. The card waits for the entry to load on exactly this + refusal: Core's `service_validation_error`, under this integration's + translation domain and the `monitoring_panel_not_loaded` key. + """ + + @pytest.mark.parametrize( + ("state", "disabled"), + [ + pytest.param(ConfigEntryState.NOT_LOADED, False, id="not loaded"), + pytest.param(ConfigEntryState.NOT_LOADED, True, id="disabled"), + pytest.param(ConfigEntryState.SETUP_IN_PROGRESS, False, id="setting up"), + pytest.param(ConfigEntryState.SETUP_RETRY, False, id="retrying setup"), + pytest.param(ConfigEntryState.SETUP_ERROR, False, id="setup failed"), + ], + ) + async def test_an_entry_that_is_not_loaded_is_refused( + self, hass: HomeAssistant, state: ConfigEntryState, disabled: bool + ) -> None: + """The entry the call names is refused while it is not loaded, whatever keeps it so.""" + entry = _unloaded_entry(hass, state, disabled=disabled) + _async_register_monitoring_services(hass) + + with pytest.raises(ServiceValidationError) as refused: + await _ask_for_status(hass, config_entry_id=entry.entry_id) + + assert (refused.value.translation_domain, refused.value.translation_key) == ( + DOMAIN, + "monitoring_panel_not_loaded", + ) + + async def test_an_entry_that_is_not_loaded_is_refused_while_another_panel_is_loaded( + self, hass: HomeAssistant + ) -> None: + """The panel the call names decides: another panel being loaded answers nothing for it.""" + await _load_panel(hass, _rated_panel(publishes_shared_meters=None)) + entry = _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + _async_register_monitoring_services(hass) + + with pytest.raises(ServiceValidationError) as refused: + await _ask_for_status(hass, config_entry_id=entry.entry_id) + + assert refused.value.translation_key == "monitoring_panel_not_loaded" + + @pytest.mark.parametrize( + "configured", [False, True], ids=["no entry", "an entry retrying setup"] + ) + async def test_a_call_naming_no_entry_is_refused_while_no_panel_is_loaded( + self, hass: HomeAssistant, configured: bool + ) -> None: + """With no entry named and none loaded, there is no panel to answer for.""" + if configured: + _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + _async_register_monitoring_services(hass) + + with pytest.raises(ServiceValidationError) as refused: + await _ask_for_status(hass) + + assert (refused.value.translation_domain, refused.value.translation_key) == ( + DOMAIN, + "monitoring_panel_not_loaded", + ) + + @pytest.mark.parametrize( + "named", ["no-such-entry", None], ids=["an id no entry has", "another integration's entry"] + ) + async def test_an_entry_id_that_is_no_panels_is_refused_as_unknown( + self, hass: HomeAssistant, named: str | None + ) -> None: + """An id that names no SPAN Panel's entry is refused as such, not as a panel still loading. + + A loaded panel is there too, so the refusal is about the id the call named. + """ + await _load_panel(hass, _rated_panel(publishes_shared_meters=None)) + entry_id = named if named is not None else _another_integrations_entry(hass).entry_id + _async_register_monitoring_services(hass) + + with pytest.raises(ServiceValidationError) as refused: + await _ask_for_status(hass, config_entry_id=entry_id) + + assert ( + refused.value.translation_domain, + refused.value.translation_key, + refused.value.translation_placeholders, + ) == (DOMAIN, "monitoring_panel_unknown", {"config_entry_id": entry_id}) + + async def test_a_loaded_panel_with_monitoring_off_still_says_so( + self, hass: HomeAssistant + ) -> None: + """Only a loaded panel can say its monitoring is off.""" + entry = await _load_panel(hass, _rated_panel(publishes_shared_meters=None), monitored=False) + _async_register_monitoring_services(hass) + + assert await _ask_for_status(hass, config_entry_id=entry.entry_id) == {"enabled": False} + assert await _ask_for_status(hass) == {"enabled": False} + + async def test_a_loaded_panel_with_monitoring_on_answers_its_status( + self, hass: HomeAssistant + ) -> None: + """A loaded, monitored panel answers its status, named or not.""" + entry = await _load_panel(hass, _rated_panel(publishes_shared_meters=None)) + _async_register_monitoring_services(hass) + + for status in ( + await _ask_for_status(hass, config_entry_id=entry.entry_id), + await _ask_for_status(hass), + ): + assert status["enabled"] is True + circuits = status["circuits"] + assert isinstance(circuits, dict) + assert [c["name"] for c in circuits.values() if isinstance(c, dict)] == [ + "Synthetic Circuit" + ] + + async def test_the_card_reads_the_refusal_over_the_websocket( + self, hass: HomeAssistant, hass_ws_client: WebSocketGenerator + ) -> None: + """The refusal reaches a WebSocket caller as the contract the card waits on.""" + entry = _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + _async_register_monitoring_services(hass) + client = await hass_ws_client(hass) + + await client.send_json_auto_id( + { + "type": "call_service", + "domain": DOMAIN, + "service": "get_monitoring_status", + "service_data": {"config_entry_id": entry.entry_id}, + "return_response": True, + } + ) + reply = await client.receive_json() + + assert reply["success"] is False + error = reply["error"] + assert (error["code"], error["translation_domain"], error["translation_key"]) == ( + "service_validation_error", + "span_panel", + "monitoring_panel_not_loaded", + ) + + +_WRITES: Final[list[Any]] = [ + pytest.param("set_global_monitoring", {"enabled": True}, id="turn monitoring on"), + pytest.param("set_global_monitoring", {"enabled": False}, id="turn monitoring off"), + pytest.param("set_global_monitoring", {SPIKE_THRESHOLD_PCT: 90}, id="change settings"), + pytest.param("test_notification", {}, id="test notification"), + pytest.param( + "set_circuit_threshold", + {"circuit_id": "circuit-5", SPIKE_THRESHOLD_PCT: 90}, + id="set circuit", + ), + pytest.param("clear_circuit_threshold", {"circuit_id": "circuit-5"}, id="clear circuit"), + pytest.param( + "set_mains_threshold", {"leg": "upstream_l1", SPIKE_THRESHOLD_PCT: 90}, id="set mains" + ), + pytest.param("clear_mains_threshold", {"leg": "upstream_l1"}, id="clear mains"), + pytest.param( + "set_circuit_package_ratings", + {"circuit_id": "circuit-5", "package_ratings_a": [20, 30]}, + id="copy ratings", + ), + pytest.param("clear_circuit_package_ratings", {"circuit_id": "circuit-5"}, id="clear ratings"), +] +"""Every monitoring write, with data its schema accepts, naming a raw circuit id or leg.""" + + +def _register_every_monitoring_service(hass: HomeAssistant) -> None: + _async_register_monitoring_services(hass) + _async_register_package_rating_services(hass) + + +async def _refusal( + hass: HomeAssistant, service: str, data: Mapping[str, object] +) -> ServiceValidationError: + """Call `service` with `data` and return the refusal it must raise.""" + with pytest.raises(ServiceValidationError) as refused: + await hass.services.async_call(DOMAIN, service, dict(data), blocking=True) + return refused.value + + +class TestMonitoringWritesRefuseAPanelThatIsNotLoaded: + """A monitoring write says the panel is not loaded, or is no panel, never that monitoring is off. + + `monitoring_not_enabled` is left to a loaded panel whose monitoring is off, so + a caller can tell a panel still loading from one it has to turn monitoring on + for. + """ + + @pytest.mark.parametrize(("service", "data"), _WRITES) + async def test_a_write_to_a_panel_that_is_not_loaded_is_refused( + self, hass: HomeAssistant, service: str, data: Mapping[str, object] + ) -> None: + """The panel the call names decides, though another panel is loaded with monitoring on.""" + await _load_panel(hass, _rated_panel(publishes_shared_meters=None)) + entry = _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + _register_every_monitoring_service(hass) + + refusal = await _refusal(hass, service, {**data, "config_entry_id": entry.entry_id}) + + assert (refusal.translation_domain, refusal.translation_key) == ( + DOMAIN, + "monitoring_panel_not_loaded", + ) + + @pytest.mark.parametrize(("service", "data"), _WRITES) + async def test_a_write_with_no_panel_loaded_is_refused( + self, hass: HomeAssistant, service: str, data: Mapping[str, object] + ) -> None: + """With no entry named and none loaded, there is no panel to change.""" + _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + _register_every_monitoring_service(hass) + + refusal = await _refusal(hass, service, data) + + assert refusal.translation_key == "monitoring_panel_not_loaded" + + @pytest.mark.parametrize(("service", "data"), _WRITES) + async def test_a_write_naming_an_entry_that_is_no_panels_is_refused_as_unknown( + self, hass: HomeAssistant, service: str, data: Mapping[str, object] + ) -> None: + """An id no SPAN Panel's entry has is refused as such, though a panel is loaded.""" + await _load_panel(hass, _rated_panel(publishes_shared_meters=None)) + _register_every_monitoring_service(hass) + + refusal = await _refusal(hass, service, {**data, "config_entry_id": "no-such-entry"}) + + assert (refusal.translation_key, refusal.translation_placeholders) == ( + "monitoring_panel_unknown", + {"config_entry_id": "no-such-entry"}, + ) + + async def test_turning_monitoring_off_on_a_panel_that_is_not_loaded_leaves_it_on( + self, hass: HomeAssistant, hass_storage: dict[str, Any] + ) -> None: + """Refused rather than answered with success, since nothing is turned off. + + The panel's stored monitoring is still on, so it monitors once it loads, + which a success would have told the caller it would not. + """ + entry = _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + hass_storage[f"span_panel_current_monitor.{entry.entry_id}"] = { + "version": 1, + "minor_version": 1, + "key": f"span_panel_current_monitor.{entry.entry_id}", + "data": {"enabled": True}, + } + _register_every_monitoring_service(hass) + + refusal = await _refusal( + hass, "set_global_monitoring", {"enabled": False, "config_entry_id": entry.entry_id} + ) + + assert refusal.translation_key == "monitoring_panel_not_loaded" + assert await CurrentMonitor.async_is_enabled(hass, entry) is True + + @pytest.mark.parametrize( + ("service", "data"), + [ + ("set_circuit_threshold", {"circuit_id": "circuit-5", SPIKE_THRESHOLD_PCT: 90}), + ("clear_circuit_threshold", {"circuit_id": "circuit-5"}), + ("set_mains_threshold", {"leg": "upstream_l1", SPIKE_THRESHOLD_PCT: 90}), + ("clear_mains_threshold", {"leg": "upstream_l1"}), + ], + ) + async def test_a_threshold_on_a_loaded_panel_with_monitoring_off_says_monitoring_is_off( + self, hass: HomeAssistant, service: str, data: Mapping[str, object] + ) -> None: + """The one refusal that says monitoring is off: the panel is loaded, and its monitoring is.""" + entry = await _load_panel(hass, _rated_panel(publishes_shared_meters=None), monitored=False) + _register_every_monitoring_service(hass) + + refusal = await _refusal(hass, service, {**data, "config_entry_id": entry.entry_id}) + + assert refusal.translation_key == "monitoring_not_enabled" diff --git a/tests/test_current_monitor_setup.py b/tests/test_current_monitor_setup.py index 251aa6ba..7d397ae1 100644 --- a/tests/test_current_monitor_setup.py +++ b/tests/test_current_monitor_setup.py @@ -33,13 +33,17 @@ from custom_components.span_panel.options import NOTIFY_TARGETS from .captures_replay import ReplayClient, RetainedTree, capture, snapshot -from .replayed_panel import MONITORED_OPTIONS, Panel, replayed_panels +from .replayed_panel import Panel, replayed_panels +from .test_expected_entities import FRESH_INSTALL_OPTIONS _NOTIFY_SERVICE: Final = "synthetic_phone" """A notify service standing in for a user's phone.""" -_OPTIONS: Final = {**MONITORED_OPTIONS, NOTIFY_TARGETS: f"event_bus, notify.{_NOTIFY_SERVICE}"} -"""Monitoring on, alerting through both channels: the event bus and a notify service.""" +_OPTIONS: Final = {**FRESH_INSTALL_OPTIONS, NOTIFY_TARGETS: f"event_bus, notify.{_NOTIFY_SERVICE}"} +"""Alerting through both channels: the event bus and a notify service.""" + +_LEGACY_OPTION: Final = "enable_current_monitoring" +"""The option a release before the monitoring store switched monitoring on by, as entries still hold it.""" _BETWEEN: Final = timedelta(seconds=30) """Time let pass after the monitor is built, and again before the first push.""" @@ -217,3 +221,92 @@ async def live_until_built(client: ReplayClient) -> SpanPanelSnapshot: assert [(event.data["alert_id"], event.data["alert_type"]) for event in alerts] == [ (circuit_id, "spike") ] + + +# --------------------------------------------------------------------------- +# The legacy `enable_current_monitoring` option +# --------------------------------------------------------------------------- + + +async def _stored_monitoring(hass: HomeAssistant, panel: Panel) -> bool: + return await CurrentMonitor.async_is_enabled(hass, panel.entry) + + +async def test_an_entry_with_the_legacy_option_and_no_stored_flag_starts_monitoring_and_loses_the_option( + hass: HomeAssistant, panels: Callable[..., Panel] +) -> None: + """The option is moved into the store once, at setup, and asks for no reload in leaving the options.""" + tree, _circuit_id, _rating = _overloaded() + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, _LEGACY_OPTION: True}, monitored=False) + + await panel.set_up(tree) + runtime = panel.runtime + await hass.async_block_till_done() + + assert panel.runtime is runtime + assert runtime.coordinator.current_monitor is not None + assert _LEGACY_OPTION not in panel.entry.options + assert dict(panel.entry.options) == dict(FRESH_INSTALL_OPTIONS) + assert await _stored_monitoring(hass, panel) is True + + +async def test_an_entry_with_the_legacy_option_off_stays_off_and_loses_the_option( + hass: HomeAssistant, panels: Callable[..., Panel] +) -> None: + """An option that is off needs no record: a store holding no flag is off.""" + tree, _circuit_id, _rating = _overloaded() + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, _LEGACY_OPTION: False}, monitored=False) + + await panel.set_up(tree) + + assert panel.runtime.coordinator.current_monitor is None + assert dict(panel.entry.options) == dict(FRESH_INSTALL_OPTIONS) + assert await _stored_monitoring(hass, panel) is False + + +async def test_monitoring_turned_off_stays_off_across_a_restart_on_an_entry_that_held_the_option( + hass: HomeAssistant, panels: Callable[..., Panel] +) -> None: + """Turning monitoring off writes only the store, so the option must not turn it on again.""" + tree, _circuit_id, _rating = _overloaded() + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, _LEGACY_OPTION: True}, monitored=False) + await panel.set_up(tree) + + await panel.call("set_global_monitoring", enabled=False) + await panel.restart_on(tree) + + assert panel.runtime.coordinator.current_monitor is None + assert await _stored_monitoring(hass, panel) is False + + +async def test_a_stored_off_wins_over_the_legacy_option( + hass: HomeAssistant, panels: Callable[..., Panel], hass_storage: dict[str, object] +) -> None: + """Where the store already holds a flag, the option carries nothing over, and still leaves the options.""" + tree, _circuit_id, _rating = _overloaded() + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, _LEGACY_OPTION: True}, monitored=False) + key = f"span_panel_current_monitor.{panel.entry.entry_id}" + hass_storage[key] = {"version": 1, "minor_version": 1, "key": key, "data": {"enabled": False}} + + await panel.set_up(tree) + assert panel.runtime.coordinator.current_monitor is None + await panel.restart_on(tree) + + assert panel.runtime.coordinator.current_monitor is None + assert _LEGACY_OPTION not in panel.entry.options + assert await _stored_monitoring(hass, panel) is False + + +@pytest.mark.parametrize("monitored", [True, False], ids=["monitoring on", "monitoring off"]) +async def test_an_entry_without_the_legacy_option_is_unchanged( + hass: HomeAssistant, panels: Callable[..., Panel], monitored: bool +) -> None: + """Its options are left as they are, and monitoring follows the store alone.""" + tree, _circuit_id, _rating = _overloaded() + panel = panels(tree, options=FRESH_INSTALL_OPTIONS, monitored=monitored) + + await panel.set_up(tree) + + assert dict(panel.entry.options) == dict(FRESH_INSTALL_OPTIONS) + assert (panel.runtime.coordinator.current_monitor is not None) is monitored + assert await _stored_monitoring(hass, panel) is monitored diff --git a/tests/test_device_id_migration.py b/tests/test_device_id_migration.py index e8792e07..5a6d8e66 100644 --- a/tests/test_device_id_migration.py +++ b/tests/test_device_id_migration.py @@ -86,7 +86,8 @@ without_topics, ) from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory -from .replayed_panel import MONITORED_OPTIONS, PANEL_NAME, Panel, replayed_panels +from .replayed_panel import PANEL_NAME, Panel, replayed_panels +from .test_expected_entities import FRESH_INSTALL_OPTIONS BEFORE: Final = "r202639-e" AFTER: Final = "r202645-e" @@ -415,7 +416,7 @@ async def install_and_update( panels: Callable[..., Panel], hass_storage: dict[str, object], *, - options: Mapping[str, object] = MONITORED_OPTIONS, + options: Mapping[str, object] = FRESH_INSTALL_OPTIONS, serial: str | None = None, ) -> tuple[Panel, Registered, str]: """Install on r202639-e with every setting the panel can hold, then restart on r202645-e.""" @@ -484,9 +485,11 @@ def with_first_letters_upper_cased(serial: str) -> str: @pytest.mark.parametrize( ("options", "serial"), [ - pytest.param(MONITORED_OPTIONS, None, id="circuit-names"), - pytest.param({**MONITORED_OPTIONS, USE_CIRCUIT_NUMBERS: True}, None, id="circuit-numbers"), - pytest.param(MONITORED_OPTIONS, MIXED_CASE_SERIAL, id="a-mixed-case-serial"), + pytest.param(FRESH_INSTALL_OPTIONS, None, id="circuit-names"), + pytest.param( + {**FRESH_INSTALL_OPTIONS, USE_CIRCUIT_NUMBERS: True}, None, id="circuit-numbers" + ), + pytest.param(FRESH_INSTALL_OPTIONS, MIXED_CASE_SERIAL, id="a-mixed-case-serial"), ], ) async def test_an_install_keeps_everything_across_the_update( diff --git a/tests/test_package_rating_services.py b/tests/test_package_rating_services.py index a7594d2d..81c36271 100644 --- a/tests/test_package_rating_services.py +++ b/tests/test_package_rating_services.py @@ -360,21 +360,21 @@ async def test_an_entity_whose_panel_is_not_loaded_says_so(self, hass: HomeAssis with pytest.raises(ServiceValidationError) as raised: await _set(hass, circuit_id=entity_id, package_ratings_a=[20, 30]) - assert raised.value.translation_key == "favorite_panel_not_loaded" + assert raised.value.translation_key == "monitoring_panel_not_loaded" assert entry_a.state is ConfigEntryState.LOADED @pytest.mark.parametrize("service", ["set", "clear"]) async def test_with_no_panel_loaded_the_call_says_so( self, hass: HomeAssistant, service: str ) -> None: - """With no panel loaded either call says so, with the one message that fits both.""" + """With no panel loaded either call says so, as every monitoring service does.""" with pytest.raises(ServiceValidationError) as raised: if service == "set": await _set(hass, circuit_id="circuit-2", package_ratings_a=[20, 30]) else: await _clear(hass, circuit_id="circuit-2") - assert raised.value.translation_key == "package_ratings_panel_not_loaded" + assert raised.value.translation_key == "monitoring_panel_not_loaded" def _panel_of(*circuit_ids: str) -> SpanPanelSnapshot: diff --git a/tests/test_package_ratings.py b/tests/test_package_ratings.py index e50b5b70..00383c4b 100644 --- a/tests/test_package_ratings.py +++ b/tests/test_package_ratings.py @@ -548,5 +548,4 @@ def test_every_reason_the_rule_removes_an_entry_for_is_a_refusal_for_entered_rat def test_every_refusal_has_its_own_message_and_every_message_a_refusal() -> None: strings = json.loads((Path(__file__).parent.parent / "custom_components/span_panel/strings.json").read_text(encoding="utf-8")) keys = {key for key in strings["exceptions"] if key.startswith("package_ratings_")} - # Raised by the services, before any rule is asked: no panel to judge by. - assert keys - {"package_ratings_panel_not_loaded"} == {f"package_ratings_{reason}" for reason in get_args(Refusal.__value__)} + assert keys == {f"package_ratings_{reason}" for reason in get_args(Refusal.__value__)} diff --git a/tests/test_remote_ct_inverter_naming.py b/tests/test_remote_ct_inverter_naming.py index 6ca8147b..c85116d6 100644 --- a/tests/test_remote_ct_inverter_naming.py +++ b/tests/test_remote_ct_inverter_naming.py @@ -33,7 +33,8 @@ from custom_components.span_panel.util import pv_inverter_device_identifier from .captures_replay import RetainedTree, capture, panel_device_id, snapshot -from .replayed_panel import MONITORED_OPTIONS, Panel, replayed_panels +from .replayed_panel import Panel, replayed_panels +from .test_expected_entities import FRESH_INSTALL_OPTIONS TREE: Final = "r202645-a" DONOR: Final = "main32_r202639-upstream-pv" @@ -167,7 +168,7 @@ async def test_an_inverter_a_remote_ct_feeds_is_named_by_its_label( remote CT does not have. """ tree, remote = derived_tree() - panel = panels(tree, options={**MONITORED_OPTIONS, USE_CIRCUIT_NUMBERS: numbers}) + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, USE_CIRCUIT_NUMBERS: numbers}) await panel.set_up(tree) card, rows = card_and_rows(panel, remote) @@ -222,7 +223,7 @@ async def test_an_install_the_earlier_naming_built_keeps_its_entity_ids( the wire id. """ tree, remote = derived_tree(name) - panel = panels(tree, options={**MONITORED_OPTIONS, USE_CIRCUIT_NUMBERS: numbers}) + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, USE_CIRCUIT_NUMBERS: numbers}) with patch("custom_components.span_panel.helpers.resolve_pv_display_suffix", _earlier_suffix): await panel.set_up(tree) card, rows = card_and_rows(panel, remote) From 22e7dbce14ffc245331a8e3988f0ddb7bcf5eb9c Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:33:51 -0800 Subject: [PATCH 2/2] build: bundle span-card v0.12.1-beta.3 The release build of span-card v0.12.1-beta.3 (8151fac), which handles the monitoring_panel_not_loaded refusal; span-panel-card.js is byte-identical to the release asset. --- .../frontend/dist/span-panel-card.js | 32 +++++++-------- .../span_panel/frontend/dist/span-panel.js | 39 +++++++------------ 2 files changed, 31 insertions(+), 40 deletions(-) diff --git a/custom_components/span_panel/frontend/dist/span-panel-card.js b/custom_components/span_panel/frontend/dist/span-panel-card.js index 46454b6f..32e76a09 100644 --- a/custom_components/span_panel/frontend/dist/span-panel-card.js +++ b/custom_components/span_panel/frontend/dist/span-panel-card.js @@ -1,4 +1,4 @@ -let t="en";const e={en:{"tab.panel":"Panel","tab.by_panel":"By Panel","tab.by_activity":"By Activity","tab.by_area":"By Area","tab.monitoring":"Monitoring","tab.settings":"Settings","tab.adopted":"Adopted","list.search_placeholder":"Search circuits...","list.unassigned_area":"Unassigned","list.no_results":"No circuits found","monitoring.heading":"Monitoring","monitoring.global_settings":"Global Settings","monitoring.enabled":"Enabled","monitoring.continuous":"Continuous (%)","monitoring.spike":"Spike (%)","monitoring.window":"Window (min)","monitoring.cooldown":"Cooldown (min)","monitoring.monitored_points":"Monitored Points","monitoring.col.name":"Name","monitoring.col.continuous":"Continuous","monitoring.col.spike":"Spike","monitoring.col.window":"Window","monitoring.col.cooldown":"Cooldown","monitoring.rating":"Rating","monitoring.all_none":"All / None","monitoring.reset":"Reset","monitoring.limit_invalid":"Enter a whole number from {min} to {max}.","monitoring.enable_invalid":"Monitoring was not turned on: correct the fields marked.","monitoring.point_field":"{field} for {name}","monitoring.reset_point":"Reset {name}","monitoring.admin_only":"Only an administrator can change monitoring.","notification.heading":"Notification Settings","notification.targets":"Notify Targets","notification.none_selected":"None selected","notification.targets_button":"Notify Targets: {targets}","notification.no_targets":"No notify targets found","notification.all_targets":"All","notification.event_bus_target":"Event Bus (HA event bus)","notification.priority":"Priority","notification.priority.default":"Default","notification.priority.passive":"Passive","notification.priority.active":"Active","notification.priority.time_sensitive":"Time-sensitive","notification.priority.critical":"Critical","notification.hint.critical":"Overrides silent/DND","notification.hint.time_sensitive":"Breaks through Focus","notification.hint.passive":"Delivers silently","notification.hint.active":"Standard delivery","notification.title_template":"Title Template","notification.message_template":"Message Template","notification.placeholders":"Placeholders:","notification.event_bus_help":"Event Bus fires event type","notification.event_bus_payload":"with payload:","notification.test_label":"Test Notification","notification.test_button":"Send Test","notification.test_sending":"Sending...","notification.test_sent":"Test notification sent","error.prefix":"Error:","error.failed_save":"Failed to save","error.failed":"Failed","error.panel_offline":"SPAN Panel unreachable","error.panel_reconnected":"SPAN Panel reconnected","error.panel_offline_named":"{name} unreachable","error.panel_reconnected_named":"{name} reconnected","error.discovery_failed":"Unable to connect to SPAN Panel","error.relay_failed":"Unable to toggle relay","error.shedding_failed":"Unable to update shedding priority","error.threshold_failed":"Unable to save threshold","error.graph_horizon_failed":"Unable to update graph time horizon","error.favorites_fetch_failed":"Unable to load favorites","error.favorites_toggle_failed":"Unable to update favorite","error.history_failed":"Unable to load historical data","error.monitoring_failed":"Unable to load monitoring status","error.graph_settings_failed":"Unable to load graph settings","error.areas_failed":"Area assignments may be out of sync","error.retry":"Retry","card.connecting":"Connecting to SPAN Panel...","card.waiting_for_load":"Waiting for SPAN Panel to load...","monitoringRating.none":"no rating","monitoringRating.copied":"{package} from your SPAN app (the panel publishes {panel} A)","monitoringRating.copied_unnamed":"Copied from your SPAN app","monitoringRating.judged_copied":"Judged against {rating} A: {copied}","settings.heading":"Settings","settings.description":"General integration settings (entity naming, device prefix, circuit numbers) are managed through the integration's options flow.","settings.open_link":"Open SPAN Panel Integration Settings","adopted.heading":"Adopted entities","adopted.description":"Vendor readings and adopted devices arrive with minimal metadata. Curate one to set its device class, statistics class, and prominence — saved changes reload the integration and apply from the next startup on.","adopted.filter_placeholder":"Filter by entity or device name","adopted.no_results":"No adopted entities match this filter","adopted.none":"This panel publishes nothing to curate.","adopted.load_failed":"Unable to load adopted entities","adopted.count":"{count} adopted","adopted.vendor_readings":"VENDOR READINGS","adopted.adopted_device":"ADOPTED DEVICE","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURATED","adopted.stale":"STALE","adopted.stale_note":"The panel no longer supports what was saved for: {fields}","adopted.enable_entity":"Enable entity","adopted.enabled":"ENABLED","adopted.disabled":"DISABLED","adopted.enable_note":"Enabled when saved — curating never enables on its own","adopted.registry_unavailable":"Enable and name become available once this entity exists in the registry.","adopted.name":"Name","adopted.device_class":"Device class","adopted.device_class_note":"choices limited by the panel's unit ({unit})","adopted.device_class_note_unitless":"choices limited by what the panel publishes","adopted.no_device_class":"No device class","adopted.statistics_class":"Statistics class","adopted.statistics_note":"long-term statistics begin after the next reload","adopted.no_statistics":"No statistics","adopted.prominence":"Prominence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Display unit","adopted.unit_as_published":"As published","adopted.precision":"Precision","adopted.precision_default":"Default","adopted.read_only":"read-only","adopted.settable":"settable","adopted.save":"Save","adopted.clear":"Clear curation","adopted.reload_note":"Saving reloads the SPAN Panel integration","adopted.saved":"Saved — the integration is reloading","adopted.confirm_heading":"Confirm statistics class","adopted.confirm_setting":"You are setting {name} to {value}.","adopted.confirm_clearing_subject":"You are clearing the statistics class on {name}.","adopted.confirm_total_increasing":"Total increasing treats every drop in the value as a meter reset. If this reading can decrease for any other reason, long-term statistics will be permanently corrupted — fixing the class later does not repair history already written.","adopted.confirm_clearing":"Long-term statistics stop being compiled for this entity, and Home Assistant raises a repair against the statistics already collected under the class you are removing.","adopted.save_anyway":"Save anyway","adopted.cancel":"Cancel","adopted.warn_total_increasing":"Saved as total increasing — every drop in the reading now counts as a meter reset.","adopted.warn_statistics_removed":"This entity has no statistics class any more; Home Assistant will raise a repair against the statistics already collected.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Panel monitoring settings","header.graph_settings":"Graph time horizon settings","header.site":"Site","header.grid":"Grid","header.upstream":"Upstream","header.downstream":"Downstream","header.solar":"Solar","header.battery":"Battery","header.toggle_units":"Toggle Watts / Amps","header.enable_switches":"Enable Switches","header.switches_enabled":"Switches Enabled","controls.admin_only":"Only an administrator can operate this panel's controls.","controls.disabled":"Control of this panel is switched off in its options.","controls.read_only":"Your Home Assistant account can't operate this panel's controls.","controls.entity_unauthorized":"Your Home Assistant account can't operate this control.","controls.not_operable":"You can't operate this panel's controls.","grid.unknown":"Unknown","grid.configure":"Configure circuit","grid.configure_subdevice":"Configure device","grid.on":"On","grid.off":"Off","grid.shared_switch":"Switches every circuit in this space","meters.title":"Meters","meters.importing":"importing","meters.exporting":"exporting","meters.imported":"imported","meters.exported":"exported","subdevice.ev_charger":"EV Charger","subdevice.battery":"Battery","subdevice.fallback":"Sub-device","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Power","subdevice.solar":"Solar","subdevice.solar_inverter":"Solar inverter","subdevice.site_total":"Site total","subdevice.in_site_total":"Included in the site total","sidepanel.graph_settings":"Graph Settings","sidepanel.global_defaults":"Global defaults for all circuits","sidepanel.favorites_subtitle":"Favorites","sidepanel.global_default":"Global Default","sidepanel.list_view_columns":"List View Columns","sidepanel.columns":"Columns","sidepanel.circuit_scales":"Circuit Graph Scales","sidepanel.subdevice_scales":"Sub-Device Graph Scales","sidepanel.reset_to_global":"Reset to global default","sidepanel.relay":"Relay","sidepanel.breaker":"Breaker","sidepanel.capacity":"{amps} A capacity","monitoringRating.title":"Breaker ratings from the SPAN app","monitoringRating.panel_rating":"Panel publishes {panel} A","monitoringRating.other_breaker":"Other breaker (A)","monitoringRating.other_breaker_label":"Other breaker in the space of {circuit}","monitoringRating.reset":"Remove copied ratings","monitoringRating.invalid_other":"Enter the other breaker's rating as a whole number of amps, 1 or more.","monitoringRating.guidance":"If your SPAN app shows two ratings for this circuit, such as 20-20A, enter the second one here. SPAN Panel MAIN 32 panels report only the first, and monitoring then judges this space against both breakers together.","monitoringRating.guidance_two_spaces":"If your SPAN app shows two ratings for this circuit, such as 20-30A, enter the second one here.","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 panels report only the average of this circuit's two legs, which can hide an overloaded leg. We recommend turning monitoring off for this circuit.","monitoringRating.turn_off_monitoring":"Turn off monitoring","monitoringRating.threshold_warning":"This circuit's custom thresholds are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass.","monitoringRating.threshold_warning_global":"The global thresholds this circuit uses are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass; change them under {settings} on the {tab} tab.","monitoringRating.use_global_thresholds":"Use global thresholds","monitoringRating.note_title":"Tandem breakers on SPAN Panel MAIN 32","monitoringRating.note_problem":"SPAN Panel MAIN 32 panels do not report which breakers are tandems, or the rating of a tandem's second breaker. A tandem puts two breakers in one space, but the panel reports it as one circuit with only the first breaker's rating, while one sensor reads both breakers together. A 20-20 tandem shows 20 A here and can carry 40 A, so monitoring raises false alerts on it.","monitoringRating.note_steps":"To fix this, copy the ratings from your SPAN app:","monitoringRating.note_step_find":"In the SPAN app, find each circuit whose breaker shows two ratings, such as 20-20A.","monitoringRating.note_step_enter":"In the table below, type the second rating in that circuit's {column} field. Then press Enter or move to the next field.","monitoringRating.note_step_single":"Leave the field empty for a circuit with a single breaker.","monitoringRating.note_judged":"Monitoring then judges that space against both breakers together: 40 A for a 20-20. Only monitoring uses the copy, and the circuit's Breaker Rating sensor still shows what the panel reports. To remove a copied rating, select ✕ beside its field.","monitoringRating.note_thresholds":"If you raised a tandem's thresholds above 100% to stop its alerts, select {reset} on its row. Those thresholds now apply to both breakers together.","monitoringRating.note_two_spaces":"For a circuit that spans two spaces, enter the second rating the same way if your SPAN app shows two, such as 20-30A. SPAN Panel MAIN 32 panels report only the average of such a circuit's two legs, which can hide an overloaded leg, so the copy can't be applied and we recommend turning monitoring off for that circuit.","monitoringRating.note_guide":"Read more in the guide to tandem and multi-load breakers.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remove copied ratings for {circuit}","monitoringRating.table_threshold_warning":"This circuit's thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Select {reset} to use the global thresholds.","monitoringRating.table_threshold_warning_global":"The global thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Change them under {settings} above.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Unable to update the ratings copied from the SPAN app","sidepanel.judged_against":"Judged against: {rating}","sidepanel.shedding_priority":"Shedding Priority","sidepanel.priority_label":"Priority","sidepanel.monitoring":"Monitoring","sidepanel.global":"Global","sidepanel.custom":"Custom","sidepanel.continuous_pct":"Continuous %","sidepanel.spike_pct":"Spike %","sidepanel.window_duration":"Window duration","sidepanel.cooldown":"Cooldown","sidepanel.favorite":"Favorite","sidepanel.save_to_favorites":"Save to favorites","panel.favorites":"Favorites","status.monitoring":"Monitoring","status.circuits":"circuits","status.mains":"mains","status.warning":"warning","status.warnings":"warnings","status.alert":"alert","status.alerts":"alerts","status.override":"override","status.overrides":"overrides","card.no_device":"Open the card editor and select your SPAN Panel device.","card.device_not_found":"Panel device not found. Check device_id in card config.","card.topology_error":"Topology response missing panel_size and no circuits found. Update the SPAN Panel integration.","editor.panel_label":"SPAN Panel","editor.select_panel":"Select a panel...","editor.chart_window":"Chart time window","editor.days":"days","editor.hours":"hours","editor.minutes":"minutes","editor.chart_metric":"Chart metric","editor.visible_sections":"Visible sections","editor.panel_circuits":"Panel circuits","editor.battery_bess":"Battery (BESS)","editor.ev_charger_evse":"EV Charger (EVSE)","editor.solar_pv":"Solar (PV)","editor.no_entities":"No entities to show","editor.tab_style":"Tab Style","editor.tab_style_text":"Text","editor.tab_style_icon":"Icon","metric.power":"Power","metric.current":"Current","metric.soc":"State of Charge","metric.soe":"State of Energy","shedding.always_on":"Critical","shedding.never":"Non-sheddable","shedding.soc_threshold":"SoC Threshold","shedding.off_grid":"Sheddable","shedding.unknown":"Unknown","shedding.select.never":"Stays on in an outage","shedding.select.soc_threshold":"Stays on until battery threshold","shedding.select.off_grid":"Turns off in an outage"},es:{"tab.panel":"Panel","tab.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","tab.settings":"Configuración","tab.adopted":"Adoptadas","list.search_placeholder":"Buscar circuitos...","list.unassigned_area":"Sin asignar","list.no_results":"No se encontraron circuitos","monitoring.heading":"Monitoreo","monitoring.global_settings":"Configuración Global","monitoring.enabled":"Activado","monitoring.continuous":"Continuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Ventana (min)","monitoring.cooldown":"Enfriamiento (min)","monitoring.monitored_points":"Puntos Monitoreados","monitoring.col.name":"Nombre","monitoring.col.continuous":"Continuo","monitoring.col.spike":"Pico","monitoring.col.window":"Ventana","monitoring.col.cooldown":"Enfriamiento","monitoring.rating":"Calibre","monitoring.all_none":"Todos / Ninguno","monitoring.reset":"Restablecer","monitoring.limit_invalid":"Introduzca un número entero de {min} a {max}.","monitoring.enable_invalid":"No se activó el monitoreo: corrija los campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Restablecer {name}","monitoring.admin_only":"Solo un administrador puede cambiar el monitoreo.","notification.heading":"Configuración de Notificaciones","notification.targets":"Destinos de Notificación","notification.none_selected":"Ninguno seleccionado","notification.targets_button":"Destinos de Notificación: {targets}","notification.no_targets":"No se encontraron destinos de notificación","notification.all_targets":"Todos","notification.event_bus_target":"Bus de Eventos (bus de eventos de HA)","notification.priority":"Prioridad","notification.priority.default":"Predeterminado","notification.priority.passive":"Pasivo","notification.priority.active":"Activo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Anula silencio/No molestar","notification.hint.time_sensitive":"Atraviesa el modo Concentración","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega estándar","notification.title_template":"Plantilla de Título","notification.message_template":"Plantilla de Mensaje","notification.placeholders":"Variables:","notification.event_bus_help":"El Bus de Eventos dispara el tipo de evento","notification.event_bus_payload":"con datos:","notification.test_label":"Notificación de prueba","notification.test_button":"Enviar prueba","notification.test_sending":"Enviando...","notification.test_sent":"Notificación de prueba enviada","error.prefix":"Error:","error.failed_save":"Error al guardar","error.failed":"Falló","error.panel_offline":"SPAN Panel inaccesible","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inaccesible","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"No se puede conectar al SPAN Panel","error.relay_failed":"No se pudo cambiar el relé","error.shedding_failed":"No se pudo actualizar la prioridad de desconexión","error.threshold_failed":"No se pudo guardar el umbral","error.graph_horizon_failed":"No se pudo actualizar el horizonte temporal del gráfico","error.favorites_fetch_failed":"No se pudieron cargar los favoritos","error.favorites_toggle_failed":"No se pudo actualizar el favorito","error.history_failed":"No se pudieron cargar los datos históricos","error.monitoring_failed":"No se pudo cargar el estado de monitoreo","error.graph_settings_failed":"No se pudo cargar la configuración del gráfico","error.areas_failed":"Las asignaciones de áreas pueden estar desincronizadas","error.retry":"Reintentar","card.connecting":"Conectando al SPAN Panel...","card.waiting_for_load":"Esperando a que cargue el SPAN Panel...","monitoringRating.none":"sin calibre","monitoringRating.copied":"{package} de su app de SPAN (el panel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado de su app de SPAN","monitoringRating.judged_copied":"Evaluado según {rating} A: {copied}","settings.heading":"Configuración","settings.description":"La configuración general de la integración (nombres de entidades, prefijo de dispositivo, números de circuito) se administra a través del flujo de opciones de la integración.","settings.open_link":"Abrir Configuración de Integración SPAN Panel","adopted.heading":"Entidades adoptadas","adopted.description":"Las lecturas del proveedor y los dispositivos adoptados llegan con metadatos mínimos. Cura una para definir su clase de dispositivo, clase de estadísticas y prominencia — los cambios guardados recargan la integración y se aplican desde el siguiente arranque.","adopted.filter_placeholder":"Filtrar por nombre de entidad o dispositivo","adopted.no_results":"Ninguna entidad adoptada coincide con este filtro","adopted.none":"Este panel no publica nada que curar.","adopted.load_failed":"No se pudieron cargar las entidades adoptadas","adopted.count":"{count} adoptadas","adopted.vendor_readings":"LECTURAS DEL PROVEEDOR","adopted.adopted_device":"DISPOSITIVO ADOPTADO","adopted.via_panel":"vía SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"El panel ya no admite lo guardado para: {fields}","adopted.enable_entity":"Activar entidad","adopted.enabled":"ACTIVADA","adopted.disabled":"DESACTIVADA","adopted.enable_note":"Se activa al guardar — curar nunca activa por sí solo","adopted.registry_unavailable":"La activación y el nombre estarán disponibles cuando esta entidad exista en el registro.","adopted.name":"Nombre","adopted.device_class":"Clase de dispositivo","adopted.device_class_note":"opciones limitadas por la unidad del panel ({unit})","adopted.device_class_note_unitless":"opciones limitadas por lo que publica el panel","adopted.no_device_class":"Sin clase de dispositivo","adopted.statistics_class":"Clase de estadísticas","adopted.statistics_note":"las estadísticas a largo plazo comienzan tras la próxima recarga","adopted.no_statistics":"Sin estadísticas","adopted.prominence":"Prominencia","adopted.diagnostic":"Diagnóstico","adopted.standard":"Estándar","adopted.display_unit":"Unidad mostrada","adopted.unit_as_published":"Tal como se publica","adopted.precision":"Precisión","adopted.precision_default":"Predeterminada","adopted.read_only":"solo lectura","adopted.settable":"editable","adopted.save":"Guardar","adopted.clear":"Borrar curación","adopted.reload_note":"Guardar recarga la integración SPAN Panel","adopted.saved":"Guardado — la integración se está recargando","adopted.confirm_heading":"Confirmar clase de estadísticas","adopted.confirm_setting":"Vas a definir {name} como {value}.","adopted.confirm_clearing_subject":"Vas a borrar la clase de estadísticas de {name}.","adopted.confirm_total_increasing":"Total creciente interpreta cada caída del valor como un reinicio del contador. Si esta lectura puede disminuir por cualquier otro motivo, las estadísticas a largo plazo quedarán corrompidas de forma permanente — corregir la clase más tarde no repara el historial ya escrito.","adopted.confirm_clearing":"Dejarán de compilarse estadísticas a largo plazo para esta entidad, y Home Assistant abrirá una reparación sobre las estadísticas ya recogidas bajo la clase que estás quitando.","adopted.save_anyway":"Guardar de todos modos","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Guardado como total creciente — cada caída de la lectura cuenta ahora como un reinicio del contador.","adopted.warn_statistics_removed":"Esta entidad ya no tiene clase de estadísticas; Home Assistant abrirá una reparación sobre las estadísticas ya recogidas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configuración de monitoreo del panel","header.graph_settings":"Configuración del horizonte temporal del gráfico","header.site":"Sitio","header.grid":"Red","header.upstream":"Aguas arriba","header.downstream":"Aguas abajo","header.solar":"Solar","header.battery":"Batería","header.toggle_units":"Alternar Watts / Amperios","header.enable_switches":"Habilitar Interruptores","header.switches_enabled":"Interruptores Habilitados","controls.admin_only":"Solo un administrador puede operar los controles de este panel.","controls.disabled":"El control de este panel está desactivado en sus opciones.","controls.read_only":"Su cuenta de Home Assistant no puede operar los controles de este panel.","controls.entity_unauthorized":"Su cuenta de Home Assistant no puede operar este control.","controls.not_operable":"No puede operar los controles de este panel.","grid.unknown":"Desconocido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Enc","grid.off":"Apag","grid.shared_switch":"Conmuta todos los circuitos de este espacio","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Cargador EV","subdevice.battery":"Batería","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potencia","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total del sitio","subdevice.in_site_total":"Incluido en el total del sitio","sidepanel.graph_settings":"Configuración de Gráficos","sidepanel.global_defaults":"Valores predeterminados globales para todos los circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Predeterminado Global","sidepanel.list_view_columns":"Columnas de la lista","sidepanel.columns":"Columnas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Restablecer al valor global","sidepanel.relay":"Relé","sidepanel.breaker":"Interruptor","sidepanel.capacity":"capacidad de {amps} A","monitoringRating.title":"Calibres de interruptor de la app de SPAN","monitoringRating.panel_rating":"El panel publica {panel} A","monitoringRating.other_breaker":"Otro interruptor (A)","monitoringRating.other_breaker_label":"Otro interruptor en el espacio de {circuit}","monitoringRating.reset":"Quitar los calibres copiados","monitoringRating.invalid_other":"Introduzca el calibre del otro interruptor como un número entero de amperios, 1 o más.","monitoringRating.guidance":"Si su app de SPAN muestra dos calibres para este circuito, como 20-20A, introduzca aquí el segundo. Los paneles SPAN Panel MAIN 32 informan solo el primero, y el monitoreo juzga entonces este espacio según ambos interruptores juntos.","monitoringRating.guidance_two_spaces":"Si su app de SPAN muestra dos calibres para este circuito, como 20-30A, introduzca aquí el segundo.","monitoringRating.averaged_legs":"Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de este circuito, lo que puede ocultar una fase sobrecargada. Recomendamos desactivar el monitoreo de este circuito.","monitoringRating.turn_off_monitoring":"Desactivar el monitoreo","monitoringRating.threshold_warning":"Los umbrales personalizados de este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real.","monitoringRating.threshold_warning_global":"Los umbrales globales que usa este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real; cámbielos en {settings}, en la pestaña {tab}.","monitoringRating.use_global_thresholds":"Usar los umbrales globales","monitoringRating.note_title":"Interruptores tándem en SPAN Panel MAIN 32","monitoringRating.note_problem":"Los paneles SPAN Panel MAIN 32 no informan qué interruptores son tándem ni el calibre del segundo interruptor de un tándem. Un tándem pone dos interruptores en un espacio, pero el panel lo informa como un solo circuito con solo el calibre del primer interruptor, mientras un solo sensor lee ambos interruptores juntos. Un tándem 20-20 muestra 20 A aquí y puede llevar 40 A, por lo que el monitoreo genera falsas alertas en él.","monitoringRating.note_steps":"Para corregirlo, copie los calibres de su app de SPAN:","monitoringRating.note_step_find":"En la app de SPAN, busque cada circuito cuyo interruptor muestre dos calibres, como 20-20A.","monitoringRating.note_step_enter":"En la tabla de abajo, escriba el segundo calibre en el campo {column} de ese circuito. Luego pulse Intro o pase al siguiente campo.","monitoringRating.note_step_single":"Deje el campo vacío para un circuito con un solo interruptor.","monitoringRating.note_judged":"El monitoreo juzga entonces ese espacio según ambos interruptores juntos: 40 A para un 20-20. Solo el monitoreo usa la copia, y el sensor Breaker Rating del circuito sigue mostrando lo que informa el panel. Para quitar un calibre copiado, seleccione ✕ junto a su campo.","monitoringRating.note_thresholds":"Si subió los umbrales de un tándem por encima del 100 % para detener sus alertas, seleccione {reset} en su fila. Esos umbrales se aplican ahora a ambos interruptores juntos.","monitoringRating.note_two_spaces":"Para un circuito que ocupa dos espacios, introduzca el segundo calibre del mismo modo si su app de SPAN muestra dos, como 20-30A. Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de un circuito así, lo que puede ocultar una fase sobrecargada, por lo que la copia no se puede aplicar y recomendamos desactivar el monitoreo de ese circuito.","monitoringRating.note_guide":"Lea más en la guía de interruptores tándem y de cargas múltiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Quitar los calibres copiados de {circuit}","monitoringRating.table_threshold_warning":"Los umbrales de este circuito superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Seleccione {reset} para usar los umbrales globales.","monitoringRating.table_threshold_warning_global":"Los umbrales globales superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Cámbielos en {settings}, arriba.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"No se pudieron actualizar los calibres copiados de la app de SPAN","sidepanel.judged_against":"Evaluado según: {rating}","sidepanel.shedding_priority":"Prioridad de Desconexción","sidepanel.priority_label":"Prioridad","sidepanel.monitoring":"Monitoreo","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Continuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duración de ventana","sidepanel.cooldown":"Enfriamiento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Guardar en favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoreo","status.circuits":"circuitos","status.mains":"alimentación","status.warning":"advertencia","status.warnings":"advertencias","status.alert":"alerta","status.alerts":"alertas","status.override":"anulación","status.overrides":"anulaciones","card.no_device":"Abra el editor de tarjeta y seleccione su dispositivo SPAN Panel.","card.device_not_found":"Dispositivo de panel no encontrado. Verifique device_id en la configuración de la tarjeta.","card.topology_error":"La respuesta de topología no contiene panel_size y no se encontraron circuitos. Actualice la integración SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Seleccione un panel...","editor.chart_window":"Ventana de tiempo del gráfico","editor.days":"días","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica del gráfico","editor.visible_sections":"Secciones visibles","editor.panel_circuits":"Circuitos del panel","editor.battery_bess":"Batería (BESS)","editor.ev_charger_evse":"Cargador EV (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"No hay entidades para mostrar","editor.tab_style":"Estilo de pestañas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícono","metric.power":"Potencia","metric.current":"Corriente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energía","shedding.always_on":"Crítico","shedding.never":"No desconectable","shedding.soc_threshold":"Umbral SoC","shedding.off_grid":"Desconectable","shedding.unknown":"Desconocido","shedding.select.never":"Permanece encendido en un corte","shedding.select.soc_threshold":"Encendido hasta umbral de batería","shedding.select.off_grid":"Se apaga en un corte"},fr:{"tab.panel":"Panneau","tab.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","tab.settings":"Paramètres","tab.adopted":"Adoptées","list.search_placeholder":"Rechercher des circuits...","list.unassigned_area":"Non attribué","list.no_results":"Aucun circuit trouvé","monitoring.heading":"Surveillance","monitoring.global_settings":"Paramètres Globaux","monitoring.enabled":"Activé","monitoring.continuous":"Continu (%)","monitoring.spike":"Pic (%)","monitoring.window":"Fenêtre (min)","monitoring.cooldown":"Refroidissement (min)","monitoring.monitored_points":"Points Surveillés","monitoring.col.name":"Nom","monitoring.col.continuous":"Continu","monitoring.col.spike":"Pic","monitoring.col.window":"Fenêtre","monitoring.col.cooldown":"Refroidissement","monitoring.rating":"Calibre","monitoring.all_none":"Tous / Aucun","monitoring.reset":"Réinitialiser","monitoring.limit_invalid":"Saisissez un nombre entier de {min} à {max}.","monitoring.enable_invalid":"La surveillance n'a pas été activée : corrigez les champs signalés.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Réinitialiser {name}","monitoring.admin_only":"Seul un administrateur peut modifier la surveillance.","notification.heading":"Paramètres de Notification","notification.targets":"Cibles de Notification","notification.none_selected":"Aucune sélection","notification.targets_button":"Cibles de Notification : {targets}","notification.no_targets":"Aucune cible de notification trouvée","notification.all_targets":"Tous","notification.event_bus_target":"Bus d'événements (bus d'événements HA)","notification.priority":"Priorité","notification.priority.default":"Par défaut","notification.priority.passive":"Passif","notification.priority.active":"Actif","notification.priority.time_sensitive":"Urgent","notification.priority.critical":"Critique","notification.hint.critical":"Outrepasse silencieux/NPD","notification.hint.time_sensitive":"Traverse le mode Concentration","notification.hint.passive":"Livraison silencieuse","notification.hint.active":"Livraison standard","notification.title_template":"Modèle de Titre","notification.message_template":"Modèle de Message","notification.placeholders":"Variables :","notification.event_bus_help":"Le Bus d'événements déclenche le type d'événement","notification.event_bus_payload":"avec les données :","notification.test_label":"Notification de test","notification.test_button":"Envoyer un test","notification.test_sending":"Envoi...","notification.test_sent":"Notification de test envoyée","error.prefix":"Erreur :","error.failed_save":"Échec de la sauvegarde","error.failed":"Échoué","error.panel_offline":"SPAN Panel inaccessible","error.panel_reconnected":"SPAN Panel reconnecté","error.panel_offline_named":"{name} inaccessible","error.panel_reconnected_named":"{name} reconnecté","error.discovery_failed":"Impossible de se connecter au SPAN Panel","error.relay_failed":"Impossible de basculer le relais","error.shedding_failed":"Impossible de mettre à jour la priorité de délestage","error.threshold_failed":"Impossible d'enregistrer le seuil","error.graph_horizon_failed":"Impossible de mettre à jour l'horizon temporel du graphique","error.favorites_fetch_failed":"Impossible de charger les favoris","error.favorites_toggle_failed":"Impossible de mettre à jour le favori","error.history_failed":"Impossible de charger les données historiques","error.monitoring_failed":"Impossible de charger l'état de surveillance","error.graph_settings_failed":"Impossible de charger les paramètres du graphique","error.areas_failed":"Les affectations de zones peuvent être désynchronisées","error.retry":"Réessayer","card.connecting":"Connexion au SPAN Panel...","card.waiting_for_load":"En attente du chargement du SPAN Panel...","monitoringRating.none":"aucun calibre","monitoringRating.copied":"{package} depuis votre application SPAN (le panneau publie {panel} A)","monitoringRating.copied_unnamed":"Copié depuis votre application SPAN","monitoringRating.judged_copied":"Évalué selon {rating} A : {copied}","settings.heading":"Paramètres","settings.description":"Les paramètres généraux de l'intégration (noms d'entités, préfixe de l'appareil, numéros de circuit) sont gérés via le flux d'options de l'intégration.","settings.open_link":"Ouvrir les Paramètres d'Intégration SPAN Panel","adopted.heading":"Entités adoptées","adopted.description":"Les relevés du fournisseur et les appareils adoptés arrivent avec des métadonnées minimales. Curez-en un pour définir sa classe d'appareil, sa classe de statistiques et sa proéminence — les modifications enregistrées rechargent l'intégration et s'appliquent dès le prochain démarrage.","adopted.filter_placeholder":"Filtrer par nom d'entité ou d'appareil","adopted.no_results":"Aucune entité adoptée ne correspond à ce filtre","adopted.none":"Ce panneau ne publie rien à curer.","adopted.load_failed":"Impossible de charger les entités adoptées","adopted.count":"{count} adoptées","adopted.vendor_readings":"RELEVÉS DU FOURNISSEUR","adopted.adopted_device":"APPAREIL ADOPTÉ","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURÉE","adopted.stale":"OBSOLÈTE","adopted.stale_note":"Le panneau ne prend plus en charge ce qui a été enregistré pour : {fields}","adopted.enable_entity":"Activer l'entité","adopted.enabled":"ACTIVÉE","adopted.disabled":"DÉSACTIVÉE","adopted.enable_note":"Activée à l'enregistrement — la curation n'active jamais d'elle-même","adopted.registry_unavailable":"L'activation et le nom seront disponibles dès que cette entité existera dans le registre.","adopted.name":"Nom","adopted.device_class":"Classe d'appareil","adopted.device_class_note":"choix limités par l'unité du panneau ({unit})","adopted.device_class_note_unitless":"choix limités par ce que le panneau publie","adopted.no_device_class":"Aucune classe d'appareil","adopted.statistics_class":"Classe de statistiques","adopted.statistics_note":"les statistiques à long terme commencent après le prochain rechargement","adopted.no_statistics":"Aucune statistique","adopted.prominence":"Proéminence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Unité affichée","adopted.unit_as_published":"Telle que publiée","adopted.precision":"Précision","adopted.precision_default":"Par défaut","adopted.read_only":"lecture seule","adopted.settable":"modifiable","adopted.save":"Enregistrer","adopted.clear":"Effacer la curation","adopted.reload_note":"L'enregistrement recharge l'intégration SPAN Panel","adopted.saved":"Enregistré — l'intégration se recharge","adopted.confirm_heading":"Confirmer la classe de statistiques","adopted.confirm_setting":"Vous définissez {name} sur {value}.","adopted.confirm_clearing_subject":"Vous effacez la classe de statistiques de {name}.","adopted.confirm_total_increasing":"Total croissant interprète chaque baisse de la valeur comme une remise à zéro du compteur. Si ce relevé peut diminuer pour une autre raison, les statistiques à long terme seront corrompues de façon permanente — corriger la classe plus tard ne répare pas l'historique déjà écrit.","adopted.confirm_clearing":"Les statistiques à long terme cesseront d'être compilées pour cette entité, et Home Assistant ouvrira une réparation sur les statistiques déjà collectées sous la classe que vous retirez.","adopted.save_anyway":"Enregistrer quand même","adopted.cancel":"Annuler","adopted.warn_total_increasing":"Enregistré en total croissant — chaque baisse du relevé compte désormais comme une remise à zéro du compteur.","adopted.warn_statistics_removed":"Cette entité n'a plus de classe de statistiques ; Home Assistant ouvrira une réparation sur les statistiques déjà collectées.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Paramètres de surveillance du panneau","header.graph_settings":"Paramètres d'horizon temporel du graphique","header.site":"Site","header.grid":"Réseau","header.upstream":"Amont","header.downstream":"Aval","header.solar":"Solaire","header.battery":"Batterie","header.toggle_units":"Basculer Watts / Ampères","header.enable_switches":"Activer les interrupteurs","header.switches_enabled":"Interrupteurs activés","controls.admin_only":"Seul un administrateur peut utiliser les commandes de ce panneau.","controls.disabled":"La commande de ce panneau est désactivée dans ses options.","controls.read_only":"Votre compte Home Assistant ne peut pas utiliser les commandes de ce panneau.","controls.entity_unauthorized":"Votre compte Home Assistant ne peut pas utiliser cette commande.","controls.not_operable":"Vous ne pouvez pas utiliser les commandes de ce panneau.","grid.unknown":"Inconnu","grid.configure":"Configurer le circuit","grid.configure_subdevice":"Configurer l'appareil","grid.on":"On","grid.off":"Off","grid.shared_switch":"Commute tous les circuits de cet emplacement","meters.title":"Compteurs","meters.importing":"en import","meters.exporting":"en export","meters.imported":"importés","meters.exported":"exportés","subdevice.ev_charger":"Chargeur VE","subdevice.battery":"Batterie","subdevice.fallback":"Sous-appareil","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Puissance","subdevice.solar":"Solaire","subdevice.solar_inverter":"Onduleur solaire","subdevice.site_total":"Total du site","subdevice.in_site_total":"Inclus dans le total du site","sidepanel.graph_settings":"Paramètres des Graphiques","sidepanel.global_defaults":"Valeurs par défaut globales pour tous les circuits","sidepanel.favorites_subtitle":"Favoris","sidepanel.global_default":"Défaut Global","sidepanel.list_view_columns":"Colonnes de la liste","sidepanel.columns":"Colonnes","sidepanel.circuit_scales":"Échelles des Graphiques de Circuits","sidepanel.subdevice_scales":"Échelles des Graphiques de Sous-Appareils","sidepanel.reset_to_global":"Réinitialiser à la valeur globale","sidepanel.relay":"Relais","sidepanel.breaker":"Disjoncteur","sidepanel.capacity":"capacité de {amps} A","monitoringRating.title":"Calibres des disjoncteurs dans l'application SPAN","monitoringRating.panel_rating":"Le panneau publie {panel} A","monitoringRating.other_breaker":"Autre disjoncteur (A)","monitoringRating.other_breaker_label":"Autre disjoncteur dans l'emplacement de {circuit}","monitoringRating.reset":"Supprimer les calibres copiés","monitoringRating.invalid_other":"Saisissez le calibre de l'autre disjoncteur en nombre entier d'ampères, 1 ou plus.","monitoringRating.guidance":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-20A, saisissez ici le second. Les panneaux SPAN Panel MAIN 32 n'indiquent que le premier, et la surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble.","monitoringRating.guidance_two_spaces":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-30A, saisissez ici le second.","monitoringRating.averaged_legs":"Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases de ce circuit, ce qui peut masquer une phase en surcharge. Nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.turn_off_monitoring":"Désactiver la surveillance","monitoringRating.threshold_warning":"Les seuils personnalisés de ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge.","monitoringRating.threshold_warning_global":"Les seuils globaux qu'utilise ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge ; modifiez-les dans {settings}, onglet {tab}.","monitoringRating.use_global_thresholds":"Utiliser les seuils globaux","monitoringRating.note_title":"Disjoncteurs tandem sur SPAN Panel MAIN 32","monitoringRating.note_problem":"Les panneaux SPAN Panel MAIN 32 n'indiquent pas quels disjoncteurs sont des tandems, ni le calibre du second disjoncteur d'un tandem. Un tandem place deux disjoncteurs dans un emplacement, mais le panneau l'indique comme un seul circuit avec le calibre du premier disjoncteur seulement, tandis qu'un seul capteur lit les deux disjoncteurs ensemble. Un tandem 20-20 affiche 20 A ici et peut supporter 40 A, si bien que la surveillance déclenche de fausses alertes sur lui.","monitoringRating.note_steps":"Pour corriger cela, copiez les calibres depuis votre application SPAN :","monitoringRating.note_step_find":"Dans l'application SPAN, trouvez chaque circuit dont le disjoncteur affiche deux calibres, par exemple 20-20A.","monitoringRating.note_step_enter":"Dans le tableau ci-dessous, saisissez le second calibre dans le champ {column} de ce circuit. Appuyez ensuite sur Entrée ou passez au champ suivant.","monitoringRating.note_step_single":"Laissez le champ vide pour un circuit à disjoncteur unique.","monitoringRating.note_judged":"La surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble : 40 A pour un 20-20. Seule la surveillance utilise la copie, et le capteur Breaker Rating du circuit affiche toujours ce que le panneau indique. Pour supprimer un calibre copié, sélectionnez ✕ à côté de son champ.","monitoringRating.note_thresholds":"Si vous avez relevé les seuils d'un tandem au-dessus de 100 % pour faire cesser ses alertes, sélectionnez {reset} sur sa ligne. Ces seuils s'appliquent désormais aux deux disjoncteurs ensemble.","monitoringRating.note_two_spaces":"Pour un circuit qui occupe deux emplacements, saisissez le second calibre de la même façon si votre application SPAN en affiche deux, par exemple 20-30A. Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases d'un tel circuit, ce qui peut masquer une phase en surcharge : la copie ne peut donc pas être appliquée, et nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.note_guide":"Pour en savoir plus, consultez le guide des disjoncteurs tandem et à charges multiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Supprimer les calibres copiés de {circuit}","monitoringRating.table_threshold_warning":"Les seuils de ce circuit dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Sélectionnez {reset} pour utiliser les seuils globaux.","monitoringRating.table_threshold_warning_global":"Les seuils globaux dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Modifiez-les dans {settings} ci-dessus.","monitoringRating.warning_announcement":"{circuit} : {warning}","error.package_ratings_failed":"Impossible de mettre à jour les calibres copiés depuis l'application SPAN","sidepanel.judged_against":"Évalué selon : {rating}","sidepanel.shedding_priority":"Priorité de Délestage","sidepanel.priority_label":"Priorité","sidepanel.monitoring":"Surveillance","sidepanel.global":"Global","sidepanel.custom":"Personnalisé","sidepanel.continuous_pct":"Continu %","sidepanel.spike_pct":"Pic %","sidepanel.window_duration":"Durée de fenêtre","sidepanel.cooldown":"Refroidissement","sidepanel.favorite":"Favori","sidepanel.save_to_favorites":"Enregistrer dans les favoris","panel.favorites":"Favoris","status.monitoring":"Surveillance","status.circuits":"circuits","status.mains":"alimentation","status.warning":"avertissement","status.warnings":"avertissements","status.alert":"alerte","status.alerts":"alertes","status.override":"remplacement","status.overrides":"remplacements","card.no_device":"Ouvrez l'éditeur de carte et sélectionnez votre appareil SPAN Panel.","card.device_not_found":"Appareil de panneau introuvable. Vérifiez device_id dans la configuration de la carte.","card.topology_error":"La réponse de topologie ne contient pas panel_size et aucun circuit trouvé. Mettez à jour l'intégration SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Sélectionnez un panneau...","editor.chart_window":"Fenêtre de temps du graphique","editor.days":"jours","editor.hours":"heures","editor.minutes":"minutes","editor.chart_metric":"Métrique du graphique","editor.visible_sections":"Sections visibles","editor.panel_circuits":"Circuits du panneau","editor.battery_bess":"Batterie (BESS)","editor.ev_charger_evse":"Chargeur VE (EVSE)","editor.solar_pv":"Solaire (PV)","editor.no_entities":"Aucune entité à afficher","editor.tab_style":"Style des onglets","editor.tab_style_text":"Texte","editor.tab_style_icon":"Icône","metric.power":"Puissance","metric.current":"Courant","metric.soc":"État de Charge","metric.soe":"État d'Énergie","shedding.always_on":"Critique","shedding.never":"Non délestable","shedding.soc_threshold":"Seuil SoC","shedding.off_grid":"Délestable","shedding.unknown":"Inconnu","shedding.select.never":"Reste allumé en cas de coupure","shedding.select.soc_threshold":"Allumé jusqu'au seuil batterie","shedding.select.off_grid":"S'éteint en cas de coupure"},ja:{"tab.panel":"パネル","tab.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","tab.settings":"設定","tab.adopted":"採用済み","list.search_placeholder":"回路を検索...","list.unassigned_area":"未割り当て","list.no_results":"回路が見つかりません","monitoring.heading":"モニタリング","monitoring.global_settings":"グローバル設定","monitoring.enabled":"有効","monitoring.continuous":"継続 (%)","monitoring.spike":"スパイク (%)","monitoring.window":"ウィンドウ (分)","monitoring.cooldown":"クールダウン (分)","monitoring.monitored_points":"監視ポイント","monitoring.col.name":"名前","monitoring.col.continuous":"継続","monitoring.col.spike":"スパイク","monitoring.col.window":"ウィンドウ","monitoring.col.cooldown":"クールダウン","monitoring.rating":"定格","monitoring.all_none":"全選択 / 全解除","monitoring.reset":"リセット","monitoring.limit_invalid":"{min} から {max} までの整数を入力してください。","monitoring.enable_invalid":"モニタリングは有効になっていません。マークされた項目を修正してください。","monitoring.point_field":"{name}の{field}","monitoring.reset_point":"{name}をリセット","monitoring.admin_only":"モニタリングを変更できるのは管理者のみです。","notification.heading":"通知設定","notification.targets":"通知先","notification.none_selected":"未選択","notification.targets_button":"通知先: {targets}","notification.no_targets":"通知先が見つかりません","notification.all_targets":"すべて","notification.event_bus_target":"イベントバス (HAイベントバス)","notification.priority":"優先度","notification.priority.default":"デフォルト","notification.priority.passive":"パッシブ","notification.priority.active":"アクティブ","notification.priority.time_sensitive":"緊急","notification.priority.critical":"重大","notification.hint.critical":"サイレント/おやすみモードを無視","notification.hint.time_sensitive":"集中モードを突破","notification.hint.passive":"サイレント配信","notification.hint.active":"標準配信","notification.title_template":"タイトルテンプレート","notification.message_template":"メッセージテンプレート","notification.placeholders":"プレースホルダー:","notification.event_bus_help":"イベントバスが発行するイベントタイプ","notification.event_bus_payload":"ペイロード:","notification.test_label":"テスト通知","notification.test_button":"テスト送信","notification.test_sending":"送信中...","notification.test_sent":"テスト通知を送信しました","error.prefix":"エラー:","error.failed_save":"保存に失敗","error.failed":"失敗","error.panel_offline":"SPANパネルに接続できません","error.panel_reconnected":"SPANパネルが再接続されました","error.panel_offline_named":"{name}に接続できません","error.panel_reconnected_named":"{name}が再接続されました","error.discovery_failed":"SPANパネルへの接続に失敗しました","error.relay_failed":"リレーの切り替えに失敗しました","error.shedding_failed":"シェディング優先度の更新に失敗しました","error.threshold_failed":"しきい値の保存に失敗しました","error.graph_horizon_failed":"グラフの時間範囲の更新に失敗しました","error.favorites_fetch_failed":"お気に入りの読み込みに失敗しました","error.favorites_toggle_failed":"お気に入りの更新に失敗しました","error.history_failed":"履歴データの読み込みに失敗しました","error.monitoring_failed":"監視ステータスの読み込みに失敗しました","error.graph_settings_failed":"グラフ設定の読み込みに失敗しました","error.areas_failed":"エリア割り当てが同期されていない可能性があります","error.retry":"再試行","card.connecting":"SPANパネルに接続中...","card.waiting_for_load":"SPANパネルの読み込みを待機中...","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","settings.heading":"設定","settings.description":"統合の一般設定(エンティティ名、デバイスプレフィックス、回路番号)は統合のオプションフローで管理されます。","settings.open_link":"SPAN Panel統合設定を開く","adopted.heading":"採用済みエンティティ","adopted.description":"ベンダーの測定値と採用済みデバイスは最小限のメタデータで登録されます。キュレーションでデバイスクラス、統計クラス、表示区分を設定できます。保存すると統合が再読み込みされ、次回の起動から適用されます。","adopted.filter_placeholder":"エンティティ名またはデバイス名で絞り込み","adopted.no_results":"この条件に一致する採用済みエンティティはありません","adopted.none":"このパネルにキュレーション対象はありません。","adopted.load_failed":"採用済みエンティティを読み込めません","adopted.count":"{count} 件","adopted.vendor_readings":"ベンダー測定値","adopted.adopted_device":"採用済みデバイス","adopted.via_panel":"SPAN Panel 経由","adopted.curated":"キュレーション済み","adopted.stale":"無効","adopted.stale_note":"パネルは保存された次の項目をサポートしなくなりました: {fields}","adopted.enable_entity":"エンティティを有効化","adopted.enabled":"有効","adopted.disabled":"無効","adopted.enable_note":"保存時に有効化されます — キュレーション自体が有効化することはありません","adopted.registry_unavailable":"有効化・名前は、このエンティティがレジストリに登録された後に利用できます。","adopted.name":"名前","adopted.device_class":"デバイスクラス","adopted.device_class_note":"パネルの単位({unit})により選択肢が制限されます","adopted.device_class_note_unitless":"パネルが公開する内容により選択肢が制限されます","adopted.no_device_class":"デバイスクラスなし","adopted.statistics_class":"統計クラス","adopted.statistics_note":"長期統計は次回の再読み込み後に開始されます","adopted.no_statistics":"統計なし","adopted.prominence":"表示区分","adopted.diagnostic":"診断","adopted.standard":"標準","adopted.display_unit":"表示単位","adopted.unit_as_published":"公開されたまま","adopted.precision":"小数点以下桁数","adopted.precision_default":"既定","adopted.read_only":"読み取り専用","adopted.settable":"書き込み可","adopted.save":"保存","adopted.clear":"キュレーションを消去","adopted.reload_note":"保存すると SPAN Panel 統合が再読み込みされます","adopted.saved":"保存しました — 統合を再読み込みしています","adopted.confirm_heading":"統計クラスの確認","adopted.confirm_setting":"{name} を {value} に設定しようとしています。","adopted.confirm_clearing_subject":"{name} の統計クラスを消去しようとしています。","adopted.confirm_total_increasing":"積算増加は値の低下をすべてメーターのリセットとして扱います。この測定値が他の理由でも下がる場合、長期統計は恒久的に破損します。後からクラスを直しても、既に書き込まれた履歴は修復されません。","adopted.confirm_clearing":"このエンティティの長期統計は収集されなくなり、削除するクラスの下で既に収集された統計について Home Assistant が修復項目を作成します。","adopted.save_anyway":"それでも保存","adopted.cancel":"キャンセル","adopted.warn_total_increasing":"積算増加として保存しました — 測定値の低下はすべてメーターのリセットとして数えられます。","adopted.warn_statistics_removed":"このエンティティに統計クラスはなくなりました。既に収集された統計について Home Assistant が修復項目を作成します。","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"パネルモニタリング設定","header.graph_settings":"グラフ時間範囲設定","header.site":"サイト","header.grid":"グリッド","header.upstream":"上流","header.downstream":"下流","header.solar":"ソーラー","header.battery":"バッテリー","header.toggle_units":"ワット/アンペア切り替え","header.enable_switches":"スイッチを有効化","header.switches_enabled":"スイッチ有効","controls.admin_only":"このパネルのコントロールを操作できるのは管理者のみです。","controls.disabled":"このパネルのコントロールはオプションで無効になっています。","controls.read_only":"お使いのHome Assistantアカウントでは、このパネルのコントロールを操作できません。","controls.entity_unauthorized":"お使いのHome Assistantアカウントでは、このコントロールを操作できません。","controls.not_operable":"このパネルのコントロールは操作できません。","grid.unknown":"不明","grid.configure":"回路を設定","grid.configure_subdevice":"デバイスを設定","grid.on":"オン","grid.off":"オフ","grid.shared_switch":"このスペースのすべての回路を切り替えます","meters.title":"メーター","meters.importing":"受電中","meters.exporting":"送電中","meters.imported":"受電","meters.exported":"送電","subdevice.ev_charger":"EV充電器","subdevice.battery":"バッテリー","subdevice.fallback":"サブデバイス","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"電力","subdevice.solar":"ソーラー","subdevice.solar_inverter":"ソーラーインバーター","subdevice.site_total":"サイト合計","subdevice.in_site_total":"サイト合計に含まれます","sidepanel.graph_settings":"グラフ設定","sidepanel.global_defaults":"全回路のグローバルデフォルト","sidepanel.favorites_subtitle":"お気に入り","sidepanel.global_default":"グローバルデフォルト","sidepanel.list_view_columns":"リスト表示の列数","sidepanel.columns":"列","sidepanel.circuit_scales":"回路グラフスケール","sidepanel.subdevice_scales":"サブデバイスグラフスケール","sidepanel.reset_to_global":"グローバルにリセット","sidepanel.relay":"リレー","sidepanel.breaker":"ブレーカー","sidepanel.capacity":"容量 {amps} A","monitoringRating.title":"SPAN アプリのブレーカー定格","monitoringRating.panel_rating":"パネルの公開値 {panel} A","monitoringRating.other_breaker":"もう一方のブレーカー (A)","monitoringRating.other_breaker_label":"{circuit} のスペースにあるもう一方のブレーカー","monitoringRating.reset":"コピーした定格を削除","monitoringRating.invalid_other":"もう一方のブレーカーの定格を 1 以上の整数のアンペアで入力してください。","monitoringRating.guidance":"SPAN アプリでこの回路に 20-20A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。SPAN Panel MAIN 32 パネルが報告するのは 1 つ目だけで、モニタリングはこのスペースを両方のブレーカーの合計で判定します。","monitoringRating.guidance_two_spaces":"SPAN アプリでこの回路に 20-30A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 パネルはこの回路の 2 本の線の平均値しか報告しないため、過負荷の線が見えなくなることがあります。この回路のモニタリングをオフにすることをおすすめします。","monitoringRating.turn_off_monitoring":"モニタリングをオフにする","monitoringRating.threshold_warning":"この回路のカスタムしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。","monitoringRating.threshold_warning_global":"この回路が使用するグローバルしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。{tab}タブの{settings}で変更してください。","monitoringRating.use_global_thresholds":"グローバルしきい値を使用","monitoringRating.note_title":"SPAN Panel MAIN 32 のタンデムブレーカー","monitoringRating.note_problem":"SPAN Panel MAIN 32 パネルは、どのブレーカーがタンデムかも、タンデムの 2 つ目のブレーカーの定格も報告しません。タンデムは 1 つのスペースに 2 つのブレーカーを収めますが、パネルはそれを 1 つ目のブレーカーの定格だけを持つ 1 つの回路として報告し、1 つのセンサーが両方のブレーカーの合計を読み取ります。20-20 のタンデムはここでは 20 A と表示されますが 40 A まで流せるため、モニタリングが誤ったアラートを出します。","monitoringRating.note_steps":"これを直すには、次の手順で SPAN アプリから定格をコピーします。","monitoringRating.note_step_find":"SPAN アプリで、ブレーカーに 20-20A のように 2 つの定格が表示されている回路をすべて探します。","monitoringRating.note_step_enter":"下の表で、その回路の{column}フィールドに 2 つ目の定格を入力します。続けて Enter キーを押すか、次のフィールドに移動します。","monitoringRating.note_step_single":"ブレーカーが 1 つだけの回路では、フィールドを空のままにします。","monitoringRating.note_judged":"するとモニタリングは、そのスペースを両方のブレーカーの合計で判定します。20-20 なら 40 A です。コピーを使うのはモニタリングだけで、回路の Breaker Rating センサーは引き続きパネルが報告する値を表示します。コピーした定格を削除するには、フィールドの横の ✕ を選択します。","monitoringRating.note_thresholds":"アラートを止めるためにタンデムのしきい値を 100% より上に上げていた場合は、その行の{reset}を選択してください。それらのしきい値は今後、両方のブレーカーの合計に適用されます。","monitoringRating.note_two_spaces":"2 つのスペースにまたがる回路でも、SPAN アプリに 20-30A のように 2 つの定格が表示されていれば、同じ方法で 2 つ目の定格を入力します。SPAN Panel MAIN 32 パネルはそのような回路の 2 本の線の平均値しか報告せず、過負荷の線が見えなくなることがあるため、コピーは適用できません。その回路のモニタリングをオフにすることをおすすめします。","monitoringRating.note_guide":"詳しくは、タンデムブレーカーと複数負荷ブレーカーのガイドをご覧ください。","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"{circuit} のコピーした定格を削除","monitoringRating.table_threshold_warning":"この回路のしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。{reset}を選択するとグローバルしきい値を使用します。","monitoringRating.table_threshold_warning_global":"グローバルしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。上の{settings}で変更してください。","monitoringRating.warning_announcement":"{circuit}:{warning}","error.package_ratings_failed":"SPAN アプリからコピーした定格の更新に失敗しました","sidepanel.judged_against":"判定基準: {rating}","sidepanel.shedding_priority":"シェディング優先度","sidepanel.priority_label":"優先度","sidepanel.monitoring":"モニタリング","sidepanel.global":"グローバル","sidepanel.custom":"カスタム","sidepanel.continuous_pct":"継続 %","sidepanel.spike_pct":"スパイク %","sidepanel.window_duration":"ウィンドウ時間","sidepanel.cooldown":"クールダウン","sidepanel.favorite":"お気に入り","sidepanel.save_to_favorites":"お気に入りに保存","panel.favorites":"お気に入り","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","card.device_not_found":"パネルデバイスが見つかりません。カード設定のdevice_idを確認してください。","card.topology_error":"トポロジー応答にpanel_sizeがなく、回路が見つかりません。SPAN Panel統合を更新してください。","editor.panel_label":"SPAN Panel","editor.select_panel":"パネルを選択...","editor.chart_window":"グラフ時間ウィンドウ","editor.days":"日","editor.hours":"時間","editor.minutes":"分","editor.chart_metric":"グラフ指標","editor.visible_sections":"表示セクション","editor.panel_circuits":"パネル回路","editor.battery_bess":"バッテリー (BESS)","editor.ev_charger_evse":"EV充電器 (EVSE)","editor.solar_pv":"ソーラー (PV)","editor.no_entities":"表示するエンティティがありません","editor.tab_style":"タブスタイル","editor.tab_style_text":"テキスト","editor.tab_style_icon":"アイコン","metric.power":"電力","metric.current":"電流","metric.soc":"充電状態","metric.soe":"エネルギー状態","shedding.always_on":"重要","shedding.never":"切断不可","shedding.soc_threshold":"SoCしきい値","shedding.off_grid":"切断可能","shedding.unknown":"不明","shedding.select.never":"停電時もオンを維持","shedding.select.soc_threshold":"バッテリーしきい値までオン","shedding.select.off_grid":"停電時にオフ"},pt:{"tab.panel":"Painel","tab.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","tab.settings":"Configurações","tab.adopted":"Adotadas","list.search_placeholder":"Pesquisar circuitos...","list.unassigned_area":"Não atribuído","list.no_results":"Nenhum circuito encontrado","monitoring.heading":"Monitoramento","monitoring.global_settings":"Configurações Globais","monitoring.enabled":"Ativado","monitoring.continuous":"Contínuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Janela (min)","monitoring.cooldown":"Resfriamento (min)","monitoring.monitored_points":"Pontos Monitorados","monitoring.col.name":"Nome","monitoring.col.continuous":"Contínuo","monitoring.col.spike":"Pico","monitoring.col.window":"Janela","monitoring.col.cooldown":"Resfriamento","monitoring.rating":"Corrente nominal","monitoring.all_none":"Todos / Nenhum","monitoring.reset":"Redefinir","monitoring.limit_invalid":"Digite um número inteiro de {min} a {max}.","monitoring.enable_invalid":"O monitoramento não foi ativado: corrija os campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Redefinir {name}","monitoring.admin_only":"Somente um administrador pode alterar o monitoramento.","notification.heading":"Configurações de Notificação","notification.targets":"Destinos de Notificação","notification.none_selected":"Nenhum selecionado","notification.targets_button":"Destinos de Notificação: {targets}","notification.no_targets":"Nenhum destino de notificação encontrado","notification.all_targets":"Todos","notification.event_bus_target":"Barramento de Eventos (barramento de eventos do HA)","notification.priority":"Prioridade","notification.priority.default":"Padrão","notification.priority.passive":"Passivo","notification.priority.active":"Ativo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Substitui silencioso/Não perturbar","notification.hint.time_sensitive":"Atravessa o modo Foco","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega padrão","notification.title_template":"Modelo de Título","notification.message_template":"Modelo de Mensagem","notification.placeholders":"Variáveis:","notification.event_bus_help":"O Barramento de Eventos dispara o tipo de evento","notification.event_bus_payload":"com dados:","notification.test_label":"Notificação de teste","notification.test_button":"Enviar teste","notification.test_sending":"Enviando...","notification.test_sent":"Notificação de teste enviada","error.prefix":"Erro:","error.failed_save":"Falha ao salvar","error.failed":"Falhou","error.panel_offline":"SPAN Panel inacessível","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inacessível","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"Não foi possível conectar ao SPAN Panel","error.relay_failed":"Não foi possível alternar o relé","error.shedding_failed":"Não foi possível atualizar a prioridade de desligamento","error.threshold_failed":"Não foi possível salvar o limite","error.graph_horizon_failed":"Não foi possível atualizar o horizonte temporal do gráfico","error.favorites_fetch_failed":"Não foi possível carregar os favoritos","error.favorites_toggle_failed":"Não foi possível atualizar o favorito","error.history_failed":"Não foi possível carregar os dados históricos","error.monitoring_failed":"Não foi possível carregar o status de monitoramento","error.graph_settings_failed":"Não foi possível carregar as configurações do gráfico","error.areas_failed":"As atribuições de áreas podem estar fora de sincronização","error.retry":"Tentar novamente","card.connecting":"Conectando ao SPAN Panel...","card.waiting_for_load":"Aguardando o carregamento do SPAN Panel...","monitoringRating.none":"sem corrente nominal","monitoringRating.copied":"{package} do seu app SPAN (o painel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado do seu app SPAN","monitoringRating.judged_copied":"Avaliado com base em {rating} A: {copied}","settings.heading":"Configurações","settings.description":"As configurações gerais da integração (nomes de entidades, prefixo do dispositivo, números de circuito) são gerenciadas através do fluxo de opções da integração.","settings.open_link":"Abrir Configurações de Integração SPAN Panel","adopted.heading":"Entidades adotadas","adopted.description":"As leituras do fornecedor e os dispositivos adotados chegam com metadados mínimos. Faça a curadoria de uma para definir sua classe de dispositivo, classe de estatísticas e proeminência — alterações salvas recarregam a integração e valem a partir da próxima inicialização.","adopted.filter_placeholder":"Filtrar por nome de entidade ou dispositivo","adopted.no_results":"Nenhuma entidade adotada corresponde a este filtro","adopted.none":"Este painel não publica nada para curadoria.","adopted.load_failed":"Não foi possível carregar as entidades adotadas","adopted.count":"{count} adotadas","adopted.vendor_readings":"LEITURAS DO FORNECEDOR","adopted.adopted_device":"DISPOSITIVO ADOTADO","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"O painel não suporta mais o que foi salvo para: {fields}","adopted.enable_entity":"Ativar entidade","adopted.enabled":"ATIVADA","adopted.disabled":"DESATIVADA","adopted.enable_note":"Ativada ao salvar — a curadoria nunca ativa por conta própria","adopted.registry_unavailable":"Ativação e nome ficam disponíveis assim que esta entidade existir no registro.","adopted.name":"Nome","adopted.device_class":"Classe de dispositivo","adopted.device_class_note":"opções limitadas pela unidade do painel ({unit})","adopted.device_class_note_unitless":"opções limitadas pelo que o painel publica","adopted.no_device_class":"Sem classe de dispositivo","adopted.statistics_class":"Classe de estatísticas","adopted.statistics_note":"as estatísticas de longo prazo começam após a próxima recarga","adopted.no_statistics":"Sem estatísticas","adopted.prominence":"Proeminência","adopted.diagnostic":"Diagnóstico","adopted.standard":"Padrão","adopted.display_unit":"Unidade exibida","adopted.unit_as_published":"Como publicada","adopted.precision":"Precisão","adopted.precision_default":"Padrão","adopted.read_only":"somente leitura","adopted.settable":"editável","adopted.save":"Salvar","adopted.clear":"Limpar curadoria","adopted.reload_note":"Salvar recarrega a integração SPAN Panel","adopted.saved":"Salvo — a integração está recarregando","adopted.confirm_heading":"Confirmar classe de estatísticas","adopted.confirm_setting":"Você está definindo {name} como {value}.","adopted.confirm_clearing_subject":"Você está limpando a classe de estatísticas de {name}.","adopted.confirm_total_increasing":"Total crescente trata toda queda do valor como uma reinicialização do medidor. Se esta leitura puder diminuir por qualquer outro motivo, as estatísticas de longo prazo ficarão permanentemente corrompidas — corrigir a classe depois não repara o histórico já gravado.","adopted.confirm_clearing":"As estatísticas de longo prazo deixarão de ser compiladas para esta entidade, e o Home Assistant abrirá um reparo sobre as estatísticas já coletadas na classe que você está removendo.","adopted.save_anyway":"Salvar mesmo assim","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Salvo como total crescente — cada queda da leitura agora conta como uma reinicialização do medidor.","adopted.warn_statistics_removed":"Esta entidade não tem mais classe de estatísticas; o Home Assistant abrirá um reparo sobre as estatísticas já coletadas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configurações de monitoramento do painel","header.graph_settings":"Configurações do horizonte temporal do gráfico","header.site":"Local","header.grid":"Rede","header.upstream":"Montante","header.downstream":"Jusante","header.solar":"Solar","header.battery":"Bateria","header.toggle_units":"Alternar Watts / Amperes","header.enable_switches":"Ativar Interruptores","header.switches_enabled":"Interruptores Ativados","controls.admin_only":"Somente um administrador pode operar os controles deste painel.","controls.disabled":"O controle deste painel está desativado nas suas opções.","controls.read_only":"Sua conta do Home Assistant não pode operar os controles deste painel.","controls.entity_unauthorized":"Sua conta do Home Assistant não pode operar este controle.","controls.not_operable":"Você não pode operar os controles deste painel.","grid.unknown":"Desconhecido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Lig","grid.off":"Des","grid.shared_switch":"Liga e desliga todos os circuitos deste espaço","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Carregador VE","subdevice.battery":"Bateria","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potência","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total do local","subdevice.in_site_total":"Incluído no total do local","sidepanel.graph_settings":"Configurações de Gráficos","sidepanel.global_defaults":"Padrões globais para todos os circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Padrão Global","sidepanel.list_view_columns":"Colunas da Lista","sidepanel.columns":"Colunas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Redefinir para o padrão global","sidepanel.relay":"Relé","sidepanel.breaker":"Disjuntor","sidepanel.capacity":"capacidade de {amps} A","monitoringRating.title":"Correntes nominais dos disjuntores no app SPAN","monitoringRating.panel_rating":"O painel publica {panel} A","monitoringRating.other_breaker":"Outro disjuntor (A)","monitoringRating.other_breaker_label":"Outro disjuntor no espaço de {circuit}","monitoringRating.reset":"Remover as correntes nominais copiadas","monitoringRating.invalid_other":"Digite a corrente nominal do outro disjuntor como um número inteiro de amperes, 1 ou mais.","monitoringRating.guidance":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-20A, digite a segunda aqui. Os painéis SPAN Panel MAIN 32 informam apenas a primeira, e o monitoramento então avalia este espaço pelos dois disjuntores juntos.","monitoringRating.guidance_two_spaces":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-30A, digite a segunda aqui.","monitoringRating.averaged_legs":"Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases deste circuito, o que pode esconder uma fase sobrecarregada. Recomendamos desativar o monitoramento deste circuito.","monitoringRating.turn_off_monitoring":"Desativar o monitoramento","monitoringRating.threshold_warning":"Os limites personalizados deste circuito passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real.","monitoringRating.threshold_warning_global":"Os limites globais que este circuito usa passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real; altere-os em {settings}, na aba {tab}.","monitoringRating.use_global_thresholds":"Usar os limites globais","monitoringRating.note_title":"Disjuntores tandem no SPAN Panel MAIN 32","monitoringRating.note_problem":"Os painéis SPAN Panel MAIN 32 não informam quais disjuntores são tandem, nem a corrente nominal do segundo disjuntor de um tandem. Um tandem coloca dois disjuntores em um espaço, mas o painel o informa como um único circuito com apenas a corrente nominal do primeiro disjuntor, enquanto um único sensor lê os dois disjuntores juntos. Um tandem 20-20 mostra 20 A aqui e pode conduzir 40 A, então o monitoramento gera alertas falsos nele.","monitoringRating.note_steps":"Para corrigir isso, copie as correntes nominais do seu app SPAN:","monitoringRating.note_step_find":"No app SPAN, encontre cada circuito cujo disjuntor mostra duas correntes nominais, como 20-20A.","monitoringRating.note_step_enter":"Na tabela abaixo, digite a segunda corrente nominal no campo {column} desse circuito. Depois pressione Enter ou vá para o próximo campo.","monitoringRating.note_step_single":"Deixe o campo vazio para um circuito com um único disjuntor.","monitoringRating.note_judged":"O monitoramento então avalia esse espaço pelos dois disjuntores juntos: 40 A para um 20-20. Só o monitoramento usa a cópia, e o sensor Breaker Rating do circuito continua mostrando o que o painel informa. Para remover uma corrente nominal copiada, selecione ✕ ao lado do seu campo.","monitoringRating.note_thresholds":"Se você aumentou os limites de um tandem acima de 100% para interromper os alertas dele, selecione {reset} na linha dele. Esses limites agora se aplicam aos dois disjuntores juntos.","monitoringRating.note_two_spaces":"Para um circuito que ocupa dois espaços, digite a segunda corrente nominal da mesma forma se o seu app SPAN mostrar duas, como 20-30A. Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases de um circuito assim, o que pode esconder uma fase sobrecarregada, então a cópia não pode ser aplicada e recomendamos desativar o monitoramento desse circuito.","monitoringRating.note_guide":"Leia mais no guia de disjuntores tandem e de cargas múltiplas.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remover as correntes nominais copiadas de {circuit}","monitoringRating.table_threshold_warning":"Os limites deste circuito passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Selecione {reset} para usar os limites globais.","monitoringRating.table_threshold_warning_global":"Os limites globais passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Altere-os em {settings}, acima.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Não foi possível atualizar as correntes nominais copiadas do app SPAN","sidepanel.judged_against":"Avaliado com base em: {rating}","sidepanel.shedding_priority":"Prioridade de Desligamento","sidepanel.priority_label":"Prioridade","sidepanel.monitoring":"Monitoramento","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Contínuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duração da janela","sidepanel.cooldown":"Resfriamento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Salvar nos favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoramento","status.circuits":"circuitos","status.mains":"alimentação","status.warning":"aviso","status.warnings":"avisos","status.alert":"alerta","status.alerts":"alertas","status.override":"substituição","status.overrides":"substituições","card.no_device":"Abra o editor do cartão e selecione seu dispositivo SPAN Panel.","card.device_not_found":"Dispositivo do painel não encontrado. Verifique device_id na configuração do cartão.","card.topology_error":"A resposta de topologia não contém panel_size e nenhum circuito encontrado. Atualize a integração SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Selecione um painel...","editor.chart_window":"Janela de tempo do gráfico","editor.days":"dias","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica do gráfico","editor.visible_sections":"Seções visíveis","editor.panel_circuits":"Circuitos do painel","editor.battery_bess":"Bateria (BESS)","editor.ev_charger_evse":"Carregador VE (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"Nenhuma entidade para mostrar","editor.tab_style":"Estilo das abas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícone","metric.power":"Potência","metric.current":"Corrente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energia","shedding.always_on":"Crítico","shedding.never":"Não desligável","shedding.soc_threshold":"Limite SoC","shedding.off_grid":"Desligável","shedding.unknown":"Desconhecido","shedding.select.never":"Permanece ligado em uma queda","shedding.select.soc_threshold":"Ligado até limite da bateria","shedding.select.off_grid":"Desliga em uma queda"}};function n(n){t=n&&e[n]?n:"en"}function i(n){return e[t]?.[n]??e.en?.[n]??n}function r(n,i){return(e[t]?.[n]??e.en?.[n]??n).replace(/\{(\w+)\}/g,(t,e)=>Object.prototype.hasOwnProperty.call(i,e)?i[e]:`{${e}}`)}const o="power",a="5m",s={"5m":{ms:3e5,refreshMs:1e3,useRealtime:!0},"1h":{ms:36e5,refreshMs:3e4,useRealtime:!1},"1d":{ms:864e5,refreshMs:6e4,useRealtime:!1},"1w":{ms:6048e5,refreshMs:6e4,useRealtime:!1},"1M":{ms:2592e6,refreshMs:6e4,useRealtime:!1}},l="span_panel",c="span-panel-card",u=`custom:${c}`,d="span-panel",h=`custom:${d}`,p=`ll-strategy-section-${d}`,f="bess",g="evse",m="pv",v="sub_",y={power:{entityRole:"power",label:()=>i("metric.power"),unit:t=>Math.abs(t)>=1e3?"kW":"W",format:t=>{const e=Math.abs(t);return e>=1e3?(e/1e3).toFixed(1):e<10&&e>0?e.toFixed(1):String(Math.round(e))}},current:{entityRole:"current",label:()=>i("metric.current"),unit:()=>"A",format:t=>Math.abs(t).toFixed(1)}},_={soc:{entityRole:"soc",label:()=>i("metric.soc"),unit:()=>"%",format:t=>String(Math.round(t)),fixedMin:0,fixedMax:100},soe:{entityRole:"soe",label:()=>i("metric.soe"),unit:()=>"kWh",format:t=>t.toFixed(1)},power:y.power},b={always_on:{icon:"mdi:battery",icon2:"mdi:router-wireless",color:"#4caf50",label:()=>i("shedding.always_on")},never:{icon:"mdi:battery",color:"#4caf50",label:()=>i("shedding.never")},soc_threshold:{icon:"mdi:battery-alert-variant-outline",color:"#9c27b0",label:()=>i("shedding.soc_threshold"),textLabel:"SoC"},off_grid:{icon:"mdi:transmission-tower",color:"#ff9800",label:()=>i("shedding.off_grid")},unknown:{icon:"mdi:help-circle-outline",color:"#888",label:()=>i("shedding.unknown")}},x=Object.keys(b).filter(t=>"unknown"!==t&&"always_on"!==t);var w=function(t,e){return w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},w(t,e)};function S(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}w(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function C(t,e,n,i){var r,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(r=t[s])&&(a=(o<3?r(a):o>3?r(e,n,a):r(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}"function"==typeof SuppressedError&&SuppressedError; +let t="en";const e={en:{"tab.by_panel":"By Panel","tab.by_activity":"By Activity","tab.by_area":"By Area","tab.monitoring":"Monitoring","tab.adopted":"Adopted","list.search_placeholder":"Search circuits...","list.unassigned_area":"Unassigned","list.no_results":"No circuits found","monitoring.heading":"Monitoring","monitoring.global_settings":"Global Settings","monitoring.enabled":"Enabled","monitoring.continuous":"Continuous (%)","monitoring.spike":"Spike (%)","monitoring.window":"Window (min)","monitoring.cooldown":"Cooldown (min)","monitoring.monitored_points":"Monitored Points","monitoring.col.name":"Name","monitoring.col.continuous":"Continuous","monitoring.col.spike":"Spike","monitoring.col.window":"Window","monitoring.col.cooldown":"Cooldown","monitoring.rating":"Rating","monitoring.all_none":"All / None","monitoring.reset":"Reset","monitoring.limit_invalid":"Enter a whole number from {min} to {max}.","monitoring.enable_invalid":"Monitoring was not turned on: correct the fields marked.","monitoring.point_field":"{field} for {name}","monitoring.reset_point":"Reset {name}","monitoring.admin_only":"Only an administrator can change monitoring.","notification.heading":"Notification Settings","notification.targets":"Notify Targets","notification.none_selected":"None selected","notification.targets_button":"Notify Targets: {targets}","notification.no_targets":"No notify targets found","notification.all_targets":"All","notification.event_bus_target":"Event Bus (HA event bus)","notification.priority":"Priority","notification.priority.default":"Default","notification.priority.passive":"Passive","notification.priority.active":"Active","notification.priority.time_sensitive":"Time-sensitive","notification.priority.critical":"Critical","notification.hint.critical":"Overrides silent/DND","notification.hint.time_sensitive":"Breaks through Focus","notification.hint.passive":"Delivers silently","notification.hint.active":"Standard delivery","notification.title_template":"Title Template","notification.message_template":"Message Template","notification.placeholders":"Placeholders:","notification.event_bus_help":"Event Bus fires event type","notification.event_bus_payload":"with payload:","notification.test_label":"Test Notification","notification.test_button":"Send Test","notification.test_sending":"Sending...","notification.test_sent":"Test notification sent","error.prefix":"Error:","error.failed_save":"Failed to save","error.panel_offline":"SPAN Panel unreachable","error.panel_reconnected":"SPAN Panel reconnected","error.panel_offline_named":"{name} unreachable","error.panel_reconnected_named":"{name} reconnected","error.discovery_failed":"Unable to connect to SPAN Panel","error.relay_failed":"Unable to toggle relay","error.shedding_failed":"Unable to update shedding priority","error.threshold_failed":"Unable to save threshold","error.graph_horizon_failed":"Unable to update graph time horizon","error.favorites_fetch_failed":"Unable to load favorites","error.favorites_toggle_failed":"Unable to update favorite","error.history_failed":"Unable to load historical data","error.monitoring_failed":"Unable to load monitoring status","error.graph_settings_failed":"Unable to load graph settings","error.areas_failed":"Area assignments may be out of sync","error.retry":"Retry","card.connecting":"Connecting to SPAN Panel...","card.waiting_for_load":"Waiting for SPAN Panel to load...","card.setup_failed":"SPAN Panel could not be set up. Check Settings → Devices & services.","card.panel_disabled":"This SPAN Panel is disabled. Enable it in Settings → Devices & services.","card.restart_needed":"SPAN Panel could not be loaded. Restart Home Assistant to try again.","monitoringRating.none":"no rating","monitoringRating.copied":"{package} from your SPAN app (the panel publishes {panel} A)","monitoringRating.copied_unnamed":"Copied from your SPAN app","monitoringRating.judged_copied":"Judged against {rating} A: {copied}","adopted.heading":"Adopted entities","adopted.description":"Vendor readings and adopted devices arrive with minimal metadata. Curate one to set its device class, statistics class, and prominence — saved changes reload the integration and apply from the next startup on.","adopted.filter_placeholder":"Filter by entity or device name","adopted.no_results":"No adopted entities match this filter","adopted.none":"This panel publishes nothing to curate.","adopted.load_failed":"Unable to load adopted entities","adopted.count":"{count} adopted","adopted.vendor_readings":"VENDOR READINGS","adopted.adopted_device":"ADOPTED DEVICE","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURATED","adopted.stale":"STALE","adopted.stale_note":"The panel no longer supports what was saved for: {fields}","adopted.enable_entity":"Enable entity","adopted.enabled":"ENABLED","adopted.disabled":"DISABLED","adopted.enable_note":"Enabled when saved — curating never enables on its own","adopted.registry_unavailable":"Enable and name become available once this entity exists in the registry.","adopted.name":"Name","adopted.device_class":"Device class","adopted.device_class_note":"choices limited by the panel's unit ({unit})","adopted.device_class_note_unitless":"choices limited by what the panel publishes","adopted.no_device_class":"No device class","adopted.statistics_class":"Statistics class","adopted.statistics_note":"long-term statistics begin after the next reload","adopted.no_statistics":"No statistics","adopted.prominence":"Prominence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Display unit","adopted.unit_as_published":"As published","adopted.precision":"Precision","adopted.precision_default":"Default","adopted.read_only":"read-only","adopted.settable":"settable","adopted.save":"Save","adopted.clear":"Clear curation","adopted.reload_note":"Saving reloads the SPAN Panel integration","adopted.saved":"Saved — the integration is reloading","adopted.confirm_heading":"Confirm statistics class","adopted.confirm_setting":"You are setting {name} to {value}.","adopted.confirm_clearing_subject":"You are clearing the statistics class on {name}.","adopted.confirm_total_increasing":"Total increasing treats every drop in the value as a meter reset. If this reading can decrease for any other reason, long-term statistics will be permanently corrupted — fixing the class later does not repair history already written.","adopted.confirm_clearing":"Long-term statistics stop being compiled for this entity, and Home Assistant raises a repair against the statistics already collected under the class you are removing.","adopted.save_anyway":"Save anyway","adopted.cancel":"Cancel","adopted.warn_total_increasing":"Saved as total increasing — every drop in the reading now counts as a meter reset.","adopted.warn_statistics_removed":"This entity has no statistics class any more; Home Assistant will raise a repair against the statistics already collected.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.graph_settings":"Graph time horizon settings","header.site":"Site","header.grid":"Grid","header.upstream":"Upstream","header.downstream":"Downstream","header.solar":"Solar","header.battery":"Battery","header.toggle_units":"Toggle Watts / Amps","header.enable_switches":"Enable Switches","header.switches_enabled":"Switches Enabled","controls.admin_only":"Only an administrator can operate this panel's controls.","controls.disabled":"Control of this panel is switched off in its options.","controls.read_only":"Your Home Assistant account can't operate this panel's controls.","controls.entity_unauthorized":"Your Home Assistant account can't operate this control.","controls.not_operable":"You can't operate this panel's controls.","grid.unknown":"Unknown","grid.configure":"Configure circuit","grid.configure_subdevice":"Configure device","grid.on":"On","grid.off":"Off","grid.shared_switch":"Switches every circuit in this space","meters.title":"Meters","meters.importing":"importing","meters.exporting":"exporting","meters.imported":"imported","meters.exported":"exported","subdevice.ev_charger":"EV Charger","subdevice.battery":"Battery","subdevice.fallback":"Sub-device","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Power","subdevice.solar":"Solar","subdevice.solar_inverter":"Solar inverter","subdevice.site_total":"Site total","subdevice.in_site_total":"Included in the site total","sidepanel.graph_settings":"Graph Settings","sidepanel.global_defaults":"Global defaults for all circuits","sidepanel.favorites_subtitle":"Favorites","sidepanel.global_default":"Global Default","sidepanel.list_view_columns":"List View Columns","sidepanel.columns":"Columns","sidepanel.circuit_scales":"Circuit Graph Scales","sidepanel.subdevice_scales":"Sub-Device Graph Scales","sidepanel.reset_to_global":"Reset to global default","sidepanel.relay":"Relay","sidepanel.breaker":"Breaker","sidepanel.capacity":"{amps} A capacity","monitoringRating.title":"Breaker ratings from the SPAN app","monitoringRating.panel_rating":"Panel publishes {panel} A","monitoringRating.other_breaker":"Other breaker (A)","monitoringRating.other_breaker_label":"Other breaker in the space of {circuit}","monitoringRating.reset":"Remove copied ratings","monitoringRating.invalid_other":"Enter the other breaker's rating as a whole number of amps, 1 or more.","monitoringRating.guidance":"If your SPAN app shows two ratings for this circuit, such as 20-20A, enter the second one here. SPAN Panel MAIN 32 panels report only the first, and monitoring then judges this space against both breakers together.","monitoringRating.guidance_two_spaces":"If your SPAN app shows two ratings for this circuit, such as 20-30A, enter the second one here.","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 panels report only the average of this circuit's two legs, which can hide an overloaded leg. We recommend turning monitoring off for this circuit.","monitoringRating.turn_off_monitoring":"Turn off monitoring","monitoringRating.threshold_warning":"This circuit's custom thresholds are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass.","monitoringRating.threshold_warning_global":"The global thresholds this circuit uses are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass; change them under {settings} on the {tab} tab.","monitoringRating.use_global_thresholds":"Use global thresholds","monitoringRating.note_title":"Tandem breakers on SPAN Panel MAIN 32","monitoringRating.note_problem":"SPAN Panel MAIN 32 panels do not report which breakers are tandems, or the rating of a tandem's second breaker. A tandem puts two breakers in one space, but the panel reports it as one circuit with only the first breaker's rating, while one sensor reads both breakers together. A 20-20 tandem shows 20 A here and can carry 40 A, so monitoring raises false alerts on it.","monitoringRating.note_steps":"To fix this, copy the ratings from your SPAN app:","monitoringRating.note_step_find":"In the SPAN app, find each circuit whose breaker shows two ratings, such as 20-20A.","monitoringRating.note_step_enter":"In the table below, type the second rating in that circuit's {column} field. Then press Enter or move to the next field.","monitoringRating.note_step_single":"Leave the field empty for a circuit with a single breaker.","monitoringRating.note_judged":"Monitoring then judges that space against both breakers together: 40 A for a 20-20. Only monitoring uses the copy, and the circuit's Breaker Rating sensor still shows what the panel reports. To remove a copied rating, select ✕ beside its field.","monitoringRating.note_thresholds":"If you raised a tandem's thresholds above 100% to stop its alerts, select {reset} on its row. Those thresholds now apply to both breakers together.","monitoringRating.note_two_spaces":"For a circuit that spans two spaces, enter the second rating the same way if your SPAN app shows two, such as 20-30A. SPAN Panel MAIN 32 panels report only the average of such a circuit's two legs, which can hide an overloaded leg, so the copy can't be applied and we recommend turning monitoring off for that circuit.","monitoringRating.note_guide":"Read more in the guide to tandem and multi-load breakers.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remove copied ratings for {circuit}","monitoringRating.table_threshold_warning":"This circuit's thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Select {reset} to use the global thresholds.","monitoringRating.table_threshold_warning_global":"The global thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Change them under {settings} above.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Unable to update the ratings copied from the SPAN app","sidepanel.judged_against":"Judged against: {rating}","sidepanel.shedding_priority":"Shedding Priority","sidepanel.priority_label":"Priority","sidepanel.monitoring":"Monitoring","sidepanel.global":"Global","sidepanel.custom":"Custom","sidepanel.continuous_pct":"Continuous %","sidepanel.spike_pct":"Spike %","sidepanel.window_duration":"Window duration","sidepanel.cooldown":"Cooldown","sidepanel.favorite":"Favorite","sidepanel.save_to_favorites":"Save to favorites","panel.favorites":"Favorites","panel.no_panels":"No SPAN Panel found. Add one in Settings → Devices & services.","status.monitoring":"Monitoring","status.circuits":"circuits","status.mains":"mains","status.warning":"warning","status.warnings":"warnings","status.alert":"alert","status.alerts":"alerts","status.override":"override","status.overrides":"overrides","card.no_device":"Open the card editor and select your SPAN Panel device.","card.topology_error":"Topology response missing panel_size and no circuits found. Update the SPAN Panel integration.","editor.panel_label":"SPAN Panel","editor.select_panel":"Select a panel...","editor.chart_window":"Chart time window","editor.days":"days","editor.hours":"hours","editor.minutes":"minutes","editor.chart_metric":"Chart metric","editor.visible_sections":"Visible sections","editor.panel_circuits":"Panel circuits","editor.battery_bess":"Battery (BESS)","editor.ev_charger_evse":"EV Charger (EVSE)","editor.solar_pv":"Solar (PV)","editor.no_entities":"No entities to show","editor.tab_style":"Tab Style","editor.tab_style_text":"Text","editor.tab_style_icon":"Icon","metric.power":"Power","metric.current":"Current","metric.soc":"State of Charge","metric.soe":"State of Energy","shedding.always_on":"Critical","shedding.never":"Non-sheddable","shedding.soc_threshold":"SoC Threshold","shedding.off_grid":"Sheddable","shedding.unknown":"Unknown","shedding.select.never":"Stays on in an outage","shedding.select.soc_threshold":"Stays on until battery threshold","shedding.select.off_grid":"Turns off in an outage"},es:{"tab.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","tab.adopted":"Adoptadas","list.search_placeholder":"Buscar circuitos...","list.unassigned_area":"Sin asignar","list.no_results":"No se encontraron circuitos","monitoring.heading":"Monitoreo","monitoring.global_settings":"Configuración Global","monitoring.enabled":"Activado","monitoring.continuous":"Continuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Ventana (min)","monitoring.cooldown":"Enfriamiento (min)","monitoring.monitored_points":"Puntos Monitoreados","monitoring.col.name":"Nombre","monitoring.col.continuous":"Continuo","monitoring.col.spike":"Pico","monitoring.col.window":"Ventana","monitoring.col.cooldown":"Enfriamiento","monitoring.rating":"Calibre","monitoring.all_none":"Todos / Ninguno","monitoring.reset":"Restablecer","monitoring.limit_invalid":"Introduzca un número entero de {min} a {max}.","monitoring.enable_invalid":"No se activó el monitoreo: corrija los campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Restablecer {name}","monitoring.admin_only":"Solo un administrador puede cambiar el monitoreo.","notification.heading":"Configuración de Notificaciones","notification.targets":"Destinos de Notificación","notification.none_selected":"Ninguno seleccionado","notification.targets_button":"Destinos de Notificación: {targets}","notification.no_targets":"No se encontraron destinos de notificación","notification.all_targets":"Todos","notification.event_bus_target":"Bus de Eventos (bus de eventos de HA)","notification.priority":"Prioridad","notification.priority.default":"Predeterminado","notification.priority.passive":"Pasivo","notification.priority.active":"Activo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Anula silencio/No molestar","notification.hint.time_sensitive":"Atraviesa el modo Concentración","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega estándar","notification.title_template":"Plantilla de Título","notification.message_template":"Plantilla de Mensaje","notification.placeholders":"Variables:","notification.event_bus_help":"El Bus de Eventos dispara el tipo de evento","notification.event_bus_payload":"con datos:","notification.test_label":"Notificación de prueba","notification.test_button":"Enviar prueba","notification.test_sending":"Enviando...","notification.test_sent":"Notificación de prueba enviada","error.prefix":"Error:","error.failed_save":"Error al guardar","error.panel_offline":"SPAN Panel inaccesible","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inaccesible","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"No se puede conectar al SPAN Panel","error.relay_failed":"No se pudo cambiar el relé","error.shedding_failed":"No se pudo actualizar la prioridad de desconexión","error.threshold_failed":"No se pudo guardar el umbral","error.graph_horizon_failed":"No se pudo actualizar el horizonte temporal del gráfico","error.favorites_fetch_failed":"No se pudieron cargar los favoritos","error.favorites_toggle_failed":"No se pudo actualizar el favorito","error.history_failed":"No se pudieron cargar los datos históricos","error.monitoring_failed":"No se pudo cargar el estado de monitoreo","error.graph_settings_failed":"No se pudo cargar la configuración del gráfico","error.areas_failed":"Las asignaciones de áreas pueden estar desincronizadas","error.retry":"Reintentar","card.connecting":"Conectando al SPAN Panel...","card.waiting_for_load":"Esperando a que cargue el SPAN Panel...","card.setup_failed":"No se pudo configurar el SPAN Panel. Revise Ajustes → Dispositivos y servicios.","card.panel_disabled":"Este SPAN Panel está deshabilitado. Habilítelo en Ajustes → Dispositivos y servicios.","card.restart_needed":"No se pudo cargar el SPAN Panel. Reinicie Home Assistant para volver a intentarlo.","monitoringRating.none":"sin calibre","monitoringRating.copied":"{package} de su app de SPAN (el panel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado de su app de SPAN","monitoringRating.judged_copied":"Evaluado según {rating} A: {copied}","adopted.heading":"Entidades adoptadas","adopted.description":"Las lecturas del proveedor y los dispositivos adoptados llegan con metadatos mínimos. Cura una para definir su clase de dispositivo, clase de estadísticas y prominencia — los cambios guardados recargan la integración y se aplican desde el siguiente arranque.","adopted.filter_placeholder":"Filtrar por nombre de entidad o dispositivo","adopted.no_results":"Ninguna entidad adoptada coincide con este filtro","adopted.none":"Este panel no publica nada que curar.","adopted.load_failed":"No se pudieron cargar las entidades adoptadas","adopted.count":"{count} adoptadas","adopted.vendor_readings":"LECTURAS DEL PROVEEDOR","adopted.adopted_device":"DISPOSITIVO ADOPTADO","adopted.via_panel":"vía SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"El panel ya no admite lo guardado para: {fields}","adopted.enable_entity":"Activar entidad","adopted.enabled":"ACTIVADA","adopted.disabled":"DESACTIVADA","adopted.enable_note":"Se activa al guardar — curar nunca activa por sí solo","adopted.registry_unavailable":"La activación y el nombre estarán disponibles cuando esta entidad exista en el registro.","adopted.name":"Nombre","adopted.device_class":"Clase de dispositivo","adopted.device_class_note":"opciones limitadas por la unidad del panel ({unit})","adopted.device_class_note_unitless":"opciones limitadas por lo que publica el panel","adopted.no_device_class":"Sin clase de dispositivo","adopted.statistics_class":"Clase de estadísticas","adopted.statistics_note":"las estadísticas a largo plazo comienzan tras la próxima recarga","adopted.no_statistics":"Sin estadísticas","adopted.prominence":"Prominencia","adopted.diagnostic":"Diagnóstico","adopted.standard":"Estándar","adopted.display_unit":"Unidad mostrada","adopted.unit_as_published":"Tal como se publica","adopted.precision":"Precisión","adopted.precision_default":"Predeterminada","adopted.read_only":"solo lectura","adopted.settable":"editable","adopted.save":"Guardar","adopted.clear":"Borrar curación","adopted.reload_note":"Guardar recarga la integración SPAN Panel","adopted.saved":"Guardado — la integración se está recargando","adopted.confirm_heading":"Confirmar clase de estadísticas","adopted.confirm_setting":"Vas a definir {name} como {value}.","adopted.confirm_clearing_subject":"Vas a borrar la clase de estadísticas de {name}.","adopted.confirm_total_increasing":"Total creciente interpreta cada caída del valor como un reinicio del contador. Si esta lectura puede disminuir por cualquier otro motivo, las estadísticas a largo plazo quedarán corrompidas de forma permanente — corregir la clase más tarde no repara el historial ya escrito.","adopted.confirm_clearing":"Dejarán de compilarse estadísticas a largo plazo para esta entidad, y Home Assistant abrirá una reparación sobre las estadísticas ya recogidas bajo la clase que estás quitando.","adopted.save_anyway":"Guardar de todos modos","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Guardado como total creciente — cada caída de la lectura cuenta ahora como un reinicio del contador.","adopted.warn_statistics_removed":"Esta entidad ya no tiene clase de estadísticas; Home Assistant abrirá una reparación sobre las estadísticas ya recogidas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.graph_settings":"Configuración del horizonte temporal del gráfico","header.site":"Sitio","header.grid":"Red","header.upstream":"Aguas arriba","header.downstream":"Aguas abajo","header.solar":"Solar","header.battery":"Batería","header.toggle_units":"Alternar Watts / Amperios","header.enable_switches":"Habilitar Interruptores","header.switches_enabled":"Interruptores Habilitados","controls.admin_only":"Solo un administrador puede operar los controles de este panel.","controls.disabled":"El control de este panel está desactivado en sus opciones.","controls.read_only":"Su cuenta de Home Assistant no puede operar los controles de este panel.","controls.entity_unauthorized":"Su cuenta de Home Assistant no puede operar este control.","controls.not_operable":"No puede operar los controles de este panel.","grid.unknown":"Desconocido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Enc","grid.off":"Apag","grid.shared_switch":"Conmuta todos los circuitos de este espacio","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Cargador EV","subdevice.battery":"Batería","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potencia","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total del sitio","subdevice.in_site_total":"Incluido en el total del sitio","sidepanel.graph_settings":"Configuración de Gráficos","sidepanel.global_defaults":"Valores predeterminados globales para todos los circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Predeterminado Global","sidepanel.list_view_columns":"Columnas de la lista","sidepanel.columns":"Columnas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Restablecer al valor global","sidepanel.relay":"Relé","sidepanel.breaker":"Interruptor","sidepanel.capacity":"capacidad de {amps} A","monitoringRating.title":"Calibres de interruptor de la app de SPAN","monitoringRating.panel_rating":"El panel publica {panel} A","monitoringRating.other_breaker":"Otro interruptor (A)","monitoringRating.other_breaker_label":"Otro interruptor en el espacio de {circuit}","monitoringRating.reset":"Quitar los calibres copiados","monitoringRating.invalid_other":"Introduzca el calibre del otro interruptor como un número entero de amperios, 1 o más.","monitoringRating.guidance":"Si su app de SPAN muestra dos calibres para este circuito, como 20-20A, introduzca aquí el segundo. Los paneles SPAN Panel MAIN 32 informan solo el primero, y el monitoreo juzga entonces este espacio según ambos interruptores juntos.","monitoringRating.guidance_two_spaces":"Si su app de SPAN muestra dos calibres para este circuito, como 20-30A, introduzca aquí el segundo.","monitoringRating.averaged_legs":"Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de este circuito, lo que puede ocultar una fase sobrecargada. Recomendamos desactivar el monitoreo de este circuito.","monitoringRating.turn_off_monitoring":"Desactivar el monitoreo","monitoringRating.threshold_warning":"Los umbrales personalizados de este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real.","monitoringRating.threshold_warning_global":"Los umbrales globales que usa este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real; cámbielos en {settings}, en la pestaña {tab}.","monitoringRating.use_global_thresholds":"Usar los umbrales globales","monitoringRating.note_title":"Interruptores tándem en SPAN Panel MAIN 32","monitoringRating.note_problem":"Los paneles SPAN Panel MAIN 32 no informan qué interruptores son tándem ni el calibre del segundo interruptor de un tándem. Un tándem pone dos interruptores en un espacio, pero el panel lo informa como un solo circuito con solo el calibre del primer interruptor, mientras un solo sensor lee ambos interruptores juntos. Un tándem 20-20 muestra 20 A aquí y puede llevar 40 A, por lo que el monitoreo genera falsas alertas en él.","monitoringRating.note_steps":"Para corregirlo, copie los calibres de su app de SPAN:","monitoringRating.note_step_find":"En la app de SPAN, busque cada circuito cuyo interruptor muestre dos calibres, como 20-20A.","monitoringRating.note_step_enter":"En la tabla de abajo, escriba el segundo calibre en el campo {column} de ese circuito. Luego pulse Intro o pase al siguiente campo.","monitoringRating.note_step_single":"Deje el campo vacío para un circuito con un solo interruptor.","monitoringRating.note_judged":"El monitoreo juzga entonces ese espacio según ambos interruptores juntos: 40 A para un 20-20. Solo el monitoreo usa la copia, y el sensor Breaker Rating del circuito sigue mostrando lo que informa el panel. Para quitar un calibre copiado, seleccione ✕ junto a su campo.","monitoringRating.note_thresholds":"Si subió los umbrales de un tándem por encima del 100 % para detener sus alertas, seleccione {reset} en su fila. Esos umbrales se aplican ahora a ambos interruptores juntos.","monitoringRating.note_two_spaces":"Para un circuito que ocupa dos espacios, introduzca el segundo calibre del mismo modo si su app de SPAN muestra dos, como 20-30A. Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de un circuito así, lo que puede ocultar una fase sobrecargada, por lo que la copia no se puede aplicar y recomendamos desactivar el monitoreo de ese circuito.","monitoringRating.note_guide":"Lea más en la guía de interruptores tándem y de cargas múltiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Quitar los calibres copiados de {circuit}","monitoringRating.table_threshold_warning":"Los umbrales de este circuito superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Seleccione {reset} para usar los umbrales globales.","monitoringRating.table_threshold_warning_global":"Los umbrales globales superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Cámbielos en {settings}, arriba.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"No se pudieron actualizar los calibres copiados de la app de SPAN","sidepanel.judged_against":"Evaluado según: {rating}","sidepanel.shedding_priority":"Prioridad de Desconexción","sidepanel.priority_label":"Prioridad","sidepanel.monitoring":"Monitoreo","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Continuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duración de ventana","sidepanel.cooldown":"Enfriamiento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Guardar en favoritos","panel.favorites":"Favoritos","panel.no_panels":"No se encontró ningún SPAN Panel. Agregue uno en Ajustes → Dispositivos y servicios.","status.monitoring":"Monitoreo","status.circuits":"circuitos","status.mains":"alimentación","status.warning":"advertencia","status.warnings":"advertencias","status.alert":"alerta","status.alerts":"alertas","status.override":"anulación","status.overrides":"anulaciones","card.no_device":"Abra el editor de tarjeta y seleccione su dispositivo SPAN Panel.","card.topology_error":"La respuesta de topología no contiene panel_size y no se encontraron circuitos. Actualice la integración SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Seleccione un panel...","editor.chart_window":"Ventana de tiempo del gráfico","editor.days":"días","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica del gráfico","editor.visible_sections":"Secciones visibles","editor.panel_circuits":"Circuitos del panel","editor.battery_bess":"Batería (BESS)","editor.ev_charger_evse":"Cargador EV (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"No hay entidades para mostrar","editor.tab_style":"Estilo de pestañas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícono","metric.power":"Potencia","metric.current":"Corriente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energía","shedding.always_on":"Crítico","shedding.never":"No desconectable","shedding.soc_threshold":"Umbral SoC","shedding.off_grid":"Desconectable","shedding.unknown":"Desconocido","shedding.select.never":"Permanece encendido en un corte","shedding.select.soc_threshold":"Encendido hasta umbral de batería","shedding.select.off_grid":"Se apaga en un corte"},fr:{"tab.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","tab.adopted":"Adoptées","list.search_placeholder":"Rechercher des circuits...","list.unassigned_area":"Non attribué","list.no_results":"Aucun circuit trouvé","monitoring.heading":"Surveillance","monitoring.global_settings":"Paramètres Globaux","monitoring.enabled":"Activé","monitoring.continuous":"Continu (%)","monitoring.spike":"Pic (%)","monitoring.window":"Fenêtre (min)","monitoring.cooldown":"Refroidissement (min)","monitoring.monitored_points":"Points Surveillés","monitoring.col.name":"Nom","monitoring.col.continuous":"Continu","monitoring.col.spike":"Pic","monitoring.col.window":"Fenêtre","monitoring.col.cooldown":"Refroidissement","monitoring.rating":"Calibre","monitoring.all_none":"Tous / Aucun","monitoring.reset":"Réinitialiser","monitoring.limit_invalid":"Saisissez un nombre entier de {min} à {max}.","monitoring.enable_invalid":"La surveillance n'a pas été activée : corrigez les champs signalés.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Réinitialiser {name}","monitoring.admin_only":"Seul un administrateur peut modifier la surveillance.","notification.heading":"Paramètres de Notification","notification.targets":"Cibles de Notification","notification.none_selected":"Aucune sélection","notification.targets_button":"Cibles de Notification : {targets}","notification.no_targets":"Aucune cible de notification trouvée","notification.all_targets":"Tous","notification.event_bus_target":"Bus d'événements (bus d'événements HA)","notification.priority":"Priorité","notification.priority.default":"Par défaut","notification.priority.passive":"Passif","notification.priority.active":"Actif","notification.priority.time_sensitive":"Urgent","notification.priority.critical":"Critique","notification.hint.critical":"Outrepasse silencieux/NPD","notification.hint.time_sensitive":"Traverse le mode Concentration","notification.hint.passive":"Livraison silencieuse","notification.hint.active":"Livraison standard","notification.title_template":"Modèle de Titre","notification.message_template":"Modèle de Message","notification.placeholders":"Variables :","notification.event_bus_help":"Le Bus d'événements déclenche le type d'événement","notification.event_bus_payload":"avec les données :","notification.test_label":"Notification de test","notification.test_button":"Envoyer un test","notification.test_sending":"Envoi...","notification.test_sent":"Notification de test envoyée","error.prefix":"Erreur :","error.failed_save":"Échec de la sauvegarde","error.panel_offline":"SPAN Panel inaccessible","error.panel_reconnected":"SPAN Panel reconnecté","error.panel_offline_named":"{name} inaccessible","error.panel_reconnected_named":"{name} reconnecté","error.discovery_failed":"Impossible de se connecter au SPAN Panel","error.relay_failed":"Impossible de basculer le relais","error.shedding_failed":"Impossible de mettre à jour la priorité de délestage","error.threshold_failed":"Impossible d'enregistrer le seuil","error.graph_horizon_failed":"Impossible de mettre à jour l'horizon temporel du graphique","error.favorites_fetch_failed":"Impossible de charger les favoris","error.favorites_toggle_failed":"Impossible de mettre à jour le favori","error.history_failed":"Impossible de charger les données historiques","error.monitoring_failed":"Impossible de charger l'état de surveillance","error.graph_settings_failed":"Impossible de charger les paramètres du graphique","error.areas_failed":"Les affectations de zones peuvent être désynchronisées","error.retry":"Réessayer","card.connecting":"Connexion au SPAN Panel...","card.waiting_for_load":"En attente du chargement du SPAN Panel...","card.setup_failed":"Le SPAN Panel n'a pas pu être configuré. Consultez Paramètres → Appareils et services.","card.panel_disabled":"Ce SPAN Panel est désactivé. Activez-le dans Paramètres → Appareils et services.","card.restart_needed":"Le SPAN Panel n'a pas pu être chargé. Redémarrez Home Assistant pour réessayer.","monitoringRating.none":"aucun calibre","monitoringRating.copied":"{package} depuis votre application SPAN (le panneau publie {panel} A)","monitoringRating.copied_unnamed":"Copié depuis votre application SPAN","monitoringRating.judged_copied":"Évalué selon {rating} A : {copied}","adopted.heading":"Entités adoptées","adopted.description":"Les relevés du fournisseur et les appareils adoptés arrivent avec des métadonnées minimales. Curez-en un pour définir sa classe d'appareil, sa classe de statistiques et sa proéminence — les modifications enregistrées rechargent l'intégration et s'appliquent dès le prochain démarrage.","adopted.filter_placeholder":"Filtrer par nom d'entité ou d'appareil","adopted.no_results":"Aucune entité adoptée ne correspond à ce filtre","adopted.none":"Ce panneau ne publie rien à curer.","adopted.load_failed":"Impossible de charger les entités adoptées","adopted.count":"{count} adoptées","adopted.vendor_readings":"RELEVÉS DU FOURNISSEUR","adopted.adopted_device":"APPAREIL ADOPTÉ","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURÉE","adopted.stale":"OBSOLÈTE","adopted.stale_note":"Le panneau ne prend plus en charge ce qui a été enregistré pour : {fields}","adopted.enable_entity":"Activer l'entité","adopted.enabled":"ACTIVÉE","adopted.disabled":"DÉSACTIVÉE","adopted.enable_note":"Activée à l'enregistrement — la curation n'active jamais d'elle-même","adopted.registry_unavailable":"L'activation et le nom seront disponibles dès que cette entité existera dans le registre.","adopted.name":"Nom","adopted.device_class":"Classe d'appareil","adopted.device_class_note":"choix limités par l'unité du panneau ({unit})","adopted.device_class_note_unitless":"choix limités par ce que le panneau publie","adopted.no_device_class":"Aucune classe d'appareil","adopted.statistics_class":"Classe de statistiques","adopted.statistics_note":"les statistiques à long terme commencent après le prochain rechargement","adopted.no_statistics":"Aucune statistique","adopted.prominence":"Proéminence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Unité affichée","adopted.unit_as_published":"Telle que publiée","adopted.precision":"Précision","adopted.precision_default":"Par défaut","adopted.read_only":"lecture seule","adopted.settable":"modifiable","adopted.save":"Enregistrer","adopted.clear":"Effacer la curation","adopted.reload_note":"L'enregistrement recharge l'intégration SPAN Panel","adopted.saved":"Enregistré — l'intégration se recharge","adopted.confirm_heading":"Confirmer la classe de statistiques","adopted.confirm_setting":"Vous définissez {name} sur {value}.","adopted.confirm_clearing_subject":"Vous effacez la classe de statistiques de {name}.","adopted.confirm_total_increasing":"Total croissant interprète chaque baisse de la valeur comme une remise à zéro du compteur. Si ce relevé peut diminuer pour une autre raison, les statistiques à long terme seront corrompues de façon permanente — corriger la classe plus tard ne répare pas l'historique déjà écrit.","adopted.confirm_clearing":"Les statistiques à long terme cesseront d'être compilées pour cette entité, et Home Assistant ouvrira une réparation sur les statistiques déjà collectées sous la classe que vous retirez.","adopted.save_anyway":"Enregistrer quand même","adopted.cancel":"Annuler","adopted.warn_total_increasing":"Enregistré en total croissant — chaque baisse du relevé compte désormais comme une remise à zéro du compteur.","adopted.warn_statistics_removed":"Cette entité n'a plus de classe de statistiques ; Home Assistant ouvrira une réparation sur les statistiques déjà collectées.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.graph_settings":"Paramètres d'horizon temporel du graphique","header.site":"Site","header.grid":"Réseau","header.upstream":"Amont","header.downstream":"Aval","header.solar":"Solaire","header.battery":"Batterie","header.toggle_units":"Basculer Watts / Ampères","header.enable_switches":"Activer les interrupteurs","header.switches_enabled":"Interrupteurs activés","controls.admin_only":"Seul un administrateur peut utiliser les commandes de ce panneau.","controls.disabled":"La commande de ce panneau est désactivée dans ses options.","controls.read_only":"Votre compte Home Assistant ne peut pas utiliser les commandes de ce panneau.","controls.entity_unauthorized":"Votre compte Home Assistant ne peut pas utiliser cette commande.","controls.not_operable":"Vous ne pouvez pas utiliser les commandes de ce panneau.","grid.unknown":"Inconnu","grid.configure":"Configurer le circuit","grid.configure_subdevice":"Configurer l'appareil","grid.on":"On","grid.off":"Off","grid.shared_switch":"Commute tous les circuits de cet emplacement","meters.title":"Compteurs","meters.importing":"en import","meters.exporting":"en export","meters.imported":"importés","meters.exported":"exportés","subdevice.ev_charger":"Chargeur VE","subdevice.battery":"Batterie","subdevice.fallback":"Sous-appareil","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Puissance","subdevice.solar":"Solaire","subdevice.solar_inverter":"Onduleur solaire","subdevice.site_total":"Total du site","subdevice.in_site_total":"Inclus dans le total du site","sidepanel.graph_settings":"Paramètres des Graphiques","sidepanel.global_defaults":"Valeurs par défaut globales pour tous les circuits","sidepanel.favorites_subtitle":"Favoris","sidepanel.global_default":"Défaut Global","sidepanel.list_view_columns":"Colonnes de la liste","sidepanel.columns":"Colonnes","sidepanel.circuit_scales":"Échelles des Graphiques de Circuits","sidepanel.subdevice_scales":"Échelles des Graphiques de Sous-Appareils","sidepanel.reset_to_global":"Réinitialiser à la valeur globale","sidepanel.relay":"Relais","sidepanel.breaker":"Disjoncteur","sidepanel.capacity":"capacité de {amps} A","monitoringRating.title":"Calibres des disjoncteurs dans l'application SPAN","monitoringRating.panel_rating":"Le panneau publie {panel} A","monitoringRating.other_breaker":"Autre disjoncteur (A)","monitoringRating.other_breaker_label":"Autre disjoncteur dans l'emplacement de {circuit}","monitoringRating.reset":"Supprimer les calibres copiés","monitoringRating.invalid_other":"Saisissez le calibre de l'autre disjoncteur en nombre entier d'ampères, 1 ou plus.","monitoringRating.guidance":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-20A, saisissez ici le second. Les panneaux SPAN Panel MAIN 32 n'indiquent que le premier, et la surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble.","monitoringRating.guidance_two_spaces":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-30A, saisissez ici le second.","monitoringRating.averaged_legs":"Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases de ce circuit, ce qui peut masquer une phase en surcharge. Nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.turn_off_monitoring":"Désactiver la surveillance","monitoringRating.threshold_warning":"Les seuils personnalisés de ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge.","monitoringRating.threshold_warning_global":"Les seuils globaux qu'utilise ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge ; modifiez-les dans {settings}, onglet {tab}.","monitoringRating.use_global_thresholds":"Utiliser les seuils globaux","monitoringRating.note_title":"Disjoncteurs tandem sur SPAN Panel MAIN 32","monitoringRating.note_problem":"Les panneaux SPAN Panel MAIN 32 n'indiquent pas quels disjoncteurs sont des tandems, ni le calibre du second disjoncteur d'un tandem. Un tandem place deux disjoncteurs dans un emplacement, mais le panneau l'indique comme un seul circuit avec le calibre du premier disjoncteur seulement, tandis qu'un seul capteur lit les deux disjoncteurs ensemble. Un tandem 20-20 affiche 20 A ici et peut supporter 40 A, si bien que la surveillance déclenche de fausses alertes sur lui.","monitoringRating.note_steps":"Pour corriger cela, copiez les calibres depuis votre application SPAN :","monitoringRating.note_step_find":"Dans l'application SPAN, trouvez chaque circuit dont le disjoncteur affiche deux calibres, par exemple 20-20A.","monitoringRating.note_step_enter":"Dans le tableau ci-dessous, saisissez le second calibre dans le champ {column} de ce circuit. Appuyez ensuite sur Entrée ou passez au champ suivant.","monitoringRating.note_step_single":"Laissez le champ vide pour un circuit à disjoncteur unique.","monitoringRating.note_judged":"La surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble : 40 A pour un 20-20. Seule la surveillance utilise la copie, et le capteur Breaker Rating du circuit affiche toujours ce que le panneau indique. Pour supprimer un calibre copié, sélectionnez ✕ à côté de son champ.","monitoringRating.note_thresholds":"Si vous avez relevé les seuils d'un tandem au-dessus de 100 % pour faire cesser ses alertes, sélectionnez {reset} sur sa ligne. Ces seuils s'appliquent désormais aux deux disjoncteurs ensemble.","monitoringRating.note_two_spaces":"Pour un circuit qui occupe deux emplacements, saisissez le second calibre de la même façon si votre application SPAN en affiche deux, par exemple 20-30A. Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases d'un tel circuit, ce qui peut masquer une phase en surcharge : la copie ne peut donc pas être appliquée, et nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.note_guide":"Pour en savoir plus, consultez le guide des disjoncteurs tandem et à charges multiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Supprimer les calibres copiés de {circuit}","monitoringRating.table_threshold_warning":"Les seuils de ce circuit dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Sélectionnez {reset} pour utiliser les seuils globaux.","monitoringRating.table_threshold_warning_global":"Les seuils globaux dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Modifiez-les dans {settings} ci-dessus.","monitoringRating.warning_announcement":"{circuit} : {warning}","error.package_ratings_failed":"Impossible de mettre à jour les calibres copiés depuis l'application SPAN","sidepanel.judged_against":"Évalué selon : {rating}","sidepanel.shedding_priority":"Priorité de Délestage","sidepanel.priority_label":"Priorité","sidepanel.monitoring":"Surveillance","sidepanel.global":"Global","sidepanel.custom":"Personnalisé","sidepanel.continuous_pct":"Continu %","sidepanel.spike_pct":"Pic %","sidepanel.window_duration":"Durée de fenêtre","sidepanel.cooldown":"Refroidissement","sidepanel.favorite":"Favori","sidepanel.save_to_favorites":"Enregistrer dans les favoris","panel.favorites":"Favoris","panel.no_panels":"Aucun SPAN Panel trouvé. Ajoutez-en un dans Paramètres → Appareils et services.","status.monitoring":"Surveillance","status.circuits":"circuits","status.mains":"alimentation","status.warning":"avertissement","status.warnings":"avertissements","status.alert":"alerte","status.alerts":"alertes","status.override":"remplacement","status.overrides":"remplacements","card.no_device":"Ouvrez l'éditeur de carte et sélectionnez votre appareil SPAN Panel.","card.topology_error":"La réponse de topologie ne contient pas panel_size et aucun circuit trouvé. Mettez à jour l'intégration SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Sélectionnez un panneau...","editor.chart_window":"Fenêtre de temps du graphique","editor.days":"jours","editor.hours":"heures","editor.minutes":"minutes","editor.chart_metric":"Métrique du graphique","editor.visible_sections":"Sections visibles","editor.panel_circuits":"Circuits du panneau","editor.battery_bess":"Batterie (BESS)","editor.ev_charger_evse":"Chargeur VE (EVSE)","editor.solar_pv":"Solaire (PV)","editor.no_entities":"Aucune entité à afficher","editor.tab_style":"Style des onglets","editor.tab_style_text":"Texte","editor.tab_style_icon":"Icône","metric.power":"Puissance","metric.current":"Courant","metric.soc":"État de Charge","metric.soe":"État d'Énergie","shedding.always_on":"Critique","shedding.never":"Non délestable","shedding.soc_threshold":"Seuil SoC","shedding.off_grid":"Délestable","shedding.unknown":"Inconnu","shedding.select.never":"Reste allumé en cas de coupure","shedding.select.soc_threshold":"Allumé jusqu'au seuil batterie","shedding.select.off_grid":"S'éteint en cas de coupure"},ja:{"tab.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","tab.adopted":"採用済み","list.search_placeholder":"回路を検索...","list.unassigned_area":"未割り当て","list.no_results":"回路が見つかりません","monitoring.heading":"モニタリング","monitoring.global_settings":"グローバル設定","monitoring.enabled":"有効","monitoring.continuous":"継続 (%)","monitoring.spike":"スパイク (%)","monitoring.window":"ウィンドウ (分)","monitoring.cooldown":"クールダウン (分)","monitoring.monitored_points":"監視ポイント","monitoring.col.name":"名前","monitoring.col.continuous":"継続","monitoring.col.spike":"スパイク","monitoring.col.window":"ウィンドウ","monitoring.col.cooldown":"クールダウン","monitoring.rating":"定格","monitoring.all_none":"全選択 / 全解除","monitoring.reset":"リセット","monitoring.limit_invalid":"{min} から {max} までの整数を入力してください。","monitoring.enable_invalid":"モニタリングは有効になっていません。マークされた項目を修正してください。","monitoring.point_field":"{name}の{field}","monitoring.reset_point":"{name}をリセット","monitoring.admin_only":"モニタリングを変更できるのは管理者のみです。","notification.heading":"通知設定","notification.targets":"通知先","notification.none_selected":"未選択","notification.targets_button":"通知先: {targets}","notification.no_targets":"通知先が見つかりません","notification.all_targets":"すべて","notification.event_bus_target":"イベントバス (HAイベントバス)","notification.priority":"優先度","notification.priority.default":"デフォルト","notification.priority.passive":"パッシブ","notification.priority.active":"アクティブ","notification.priority.time_sensitive":"緊急","notification.priority.critical":"重大","notification.hint.critical":"サイレント/おやすみモードを無視","notification.hint.time_sensitive":"集中モードを突破","notification.hint.passive":"サイレント配信","notification.hint.active":"標準配信","notification.title_template":"タイトルテンプレート","notification.message_template":"メッセージテンプレート","notification.placeholders":"プレースホルダー:","notification.event_bus_help":"イベントバスが発行するイベントタイプ","notification.event_bus_payload":"ペイロード:","notification.test_label":"テスト通知","notification.test_button":"テスト送信","notification.test_sending":"送信中...","notification.test_sent":"テスト通知を送信しました","error.prefix":"エラー:","error.failed_save":"保存に失敗","error.panel_offline":"SPANパネルに接続できません","error.panel_reconnected":"SPANパネルが再接続されました","error.panel_offline_named":"{name}に接続できません","error.panel_reconnected_named":"{name}が再接続されました","error.discovery_failed":"SPANパネルへの接続に失敗しました","error.relay_failed":"リレーの切り替えに失敗しました","error.shedding_failed":"シェディング優先度の更新に失敗しました","error.threshold_failed":"しきい値の保存に失敗しました","error.graph_horizon_failed":"グラフの時間範囲の更新に失敗しました","error.favorites_fetch_failed":"お気に入りの読み込みに失敗しました","error.favorites_toggle_failed":"お気に入りの更新に失敗しました","error.history_failed":"履歴データの読み込みに失敗しました","error.monitoring_failed":"監視ステータスの読み込みに失敗しました","error.graph_settings_failed":"グラフ設定の読み込みに失敗しました","error.areas_failed":"エリア割り当てが同期されていない可能性があります","error.retry":"再試行","card.connecting":"SPANパネルに接続中...","card.waiting_for_load":"SPANパネルの読み込みを待機中...","card.setup_failed":"SPANパネルをセットアップできませんでした。設定 → デバイスとサービス を確認してください。","card.panel_disabled":"このSPANパネルは無効になっています。設定 → デバイスとサービス で有効にしてください。","card.restart_needed":"SPANパネルを読み込めませんでした。Home Assistant を再起動してもう一度お試しください。","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","adopted.heading":"採用済みエンティティ","adopted.description":"ベンダーの測定値と採用済みデバイスは最小限のメタデータで登録されます。キュレーションでデバイスクラス、統計クラス、表示区分を設定できます。保存すると統合が再読み込みされ、次回の起動から適用されます。","adopted.filter_placeholder":"エンティティ名またはデバイス名で絞り込み","adopted.no_results":"この条件に一致する採用済みエンティティはありません","adopted.none":"このパネルにキュレーション対象はありません。","adopted.load_failed":"採用済みエンティティを読み込めません","adopted.count":"{count} 件","adopted.vendor_readings":"ベンダー測定値","adopted.adopted_device":"採用済みデバイス","adopted.via_panel":"SPAN Panel 経由","adopted.curated":"キュレーション済み","adopted.stale":"無効","adopted.stale_note":"パネルは保存された次の項目をサポートしなくなりました: {fields}","adopted.enable_entity":"エンティティを有効化","adopted.enabled":"有効","adopted.disabled":"無効","adopted.enable_note":"保存時に有効化されます — キュレーション自体が有効化することはありません","adopted.registry_unavailable":"有効化・名前は、このエンティティがレジストリに登録された後に利用できます。","adopted.name":"名前","adopted.device_class":"デバイスクラス","adopted.device_class_note":"パネルの単位({unit})により選択肢が制限されます","adopted.device_class_note_unitless":"パネルが公開する内容により選択肢が制限されます","adopted.no_device_class":"デバイスクラスなし","adopted.statistics_class":"統計クラス","adopted.statistics_note":"長期統計は次回の再読み込み後に開始されます","adopted.no_statistics":"統計なし","adopted.prominence":"表示区分","adopted.diagnostic":"診断","adopted.standard":"標準","adopted.display_unit":"表示単位","adopted.unit_as_published":"公開されたまま","adopted.precision":"小数点以下桁数","adopted.precision_default":"既定","adopted.read_only":"読み取り専用","adopted.settable":"書き込み可","adopted.save":"保存","adopted.clear":"キュレーションを消去","adopted.reload_note":"保存すると SPAN Panel 統合が再読み込みされます","adopted.saved":"保存しました — 統合を再読み込みしています","adopted.confirm_heading":"統計クラスの確認","adopted.confirm_setting":"{name} を {value} に設定しようとしています。","adopted.confirm_clearing_subject":"{name} の統計クラスを消去しようとしています。","adopted.confirm_total_increasing":"積算増加は値の低下をすべてメーターのリセットとして扱います。この測定値が他の理由でも下がる場合、長期統計は恒久的に破損します。後からクラスを直しても、既に書き込まれた履歴は修復されません。","adopted.confirm_clearing":"このエンティティの長期統計は収集されなくなり、削除するクラスの下で既に収集された統計について Home Assistant が修復項目を作成します。","adopted.save_anyway":"それでも保存","adopted.cancel":"キャンセル","adopted.warn_total_increasing":"積算増加として保存しました — 測定値の低下はすべてメーターのリセットとして数えられます。","adopted.warn_statistics_removed":"このエンティティに統計クラスはなくなりました。既に収集された統計について Home Assistant が修復項目を作成します。","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.graph_settings":"グラフ時間範囲設定","header.site":"サイト","header.grid":"グリッド","header.upstream":"上流","header.downstream":"下流","header.solar":"ソーラー","header.battery":"バッテリー","header.toggle_units":"ワット/アンペア切り替え","header.enable_switches":"スイッチを有効化","header.switches_enabled":"スイッチ有効","controls.admin_only":"このパネルのコントロールを操作できるのは管理者のみです。","controls.disabled":"このパネルのコントロールはオプションで無効になっています。","controls.read_only":"お使いのHome Assistantアカウントでは、このパネルのコントロールを操作できません。","controls.entity_unauthorized":"お使いのHome Assistantアカウントでは、このコントロールを操作できません。","controls.not_operable":"このパネルのコントロールは操作できません。","grid.unknown":"不明","grid.configure":"回路を設定","grid.configure_subdevice":"デバイスを設定","grid.on":"オン","grid.off":"オフ","grid.shared_switch":"このスペースのすべての回路を切り替えます","meters.title":"メーター","meters.importing":"受電中","meters.exporting":"送電中","meters.imported":"受電","meters.exported":"送電","subdevice.ev_charger":"EV充電器","subdevice.battery":"バッテリー","subdevice.fallback":"サブデバイス","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"電力","subdevice.solar":"ソーラー","subdevice.solar_inverter":"ソーラーインバーター","subdevice.site_total":"サイト合計","subdevice.in_site_total":"サイト合計に含まれます","sidepanel.graph_settings":"グラフ設定","sidepanel.global_defaults":"全回路のグローバルデフォルト","sidepanel.favorites_subtitle":"お気に入り","sidepanel.global_default":"グローバルデフォルト","sidepanel.list_view_columns":"リスト表示の列数","sidepanel.columns":"列","sidepanel.circuit_scales":"回路グラフスケール","sidepanel.subdevice_scales":"サブデバイスグラフスケール","sidepanel.reset_to_global":"グローバルにリセット","sidepanel.relay":"リレー","sidepanel.breaker":"ブレーカー","sidepanel.capacity":"容量 {amps} A","monitoringRating.title":"SPAN アプリのブレーカー定格","monitoringRating.panel_rating":"パネルの公開値 {panel} A","monitoringRating.other_breaker":"もう一方のブレーカー (A)","monitoringRating.other_breaker_label":"{circuit} のスペースにあるもう一方のブレーカー","monitoringRating.reset":"コピーした定格を削除","monitoringRating.invalid_other":"もう一方のブレーカーの定格を 1 以上の整数のアンペアで入力してください。","monitoringRating.guidance":"SPAN アプリでこの回路に 20-20A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。SPAN Panel MAIN 32 パネルが報告するのは 1 つ目だけで、モニタリングはこのスペースを両方のブレーカーの合計で判定します。","monitoringRating.guidance_two_spaces":"SPAN アプリでこの回路に 20-30A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 パネルはこの回路の 2 本の線の平均値しか報告しないため、過負荷の線が見えなくなることがあります。この回路のモニタリングをオフにすることをおすすめします。","monitoringRating.turn_off_monitoring":"モニタリングをオフにする","monitoringRating.threshold_warning":"この回路のカスタムしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。","monitoringRating.threshold_warning_global":"この回路が使用するグローバルしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。{tab}タブの{settings}で変更してください。","monitoringRating.use_global_thresholds":"グローバルしきい値を使用","monitoringRating.note_title":"SPAN Panel MAIN 32 のタンデムブレーカー","monitoringRating.note_problem":"SPAN Panel MAIN 32 パネルは、どのブレーカーがタンデムかも、タンデムの 2 つ目のブレーカーの定格も報告しません。タンデムは 1 つのスペースに 2 つのブレーカーを収めますが、パネルはそれを 1 つ目のブレーカーの定格だけを持つ 1 つの回路として報告し、1 つのセンサーが両方のブレーカーの合計を読み取ります。20-20 のタンデムはここでは 20 A と表示されますが 40 A まで流せるため、モニタリングが誤ったアラートを出します。","monitoringRating.note_steps":"これを直すには、次の手順で SPAN アプリから定格をコピーします。","monitoringRating.note_step_find":"SPAN アプリで、ブレーカーに 20-20A のように 2 つの定格が表示されている回路をすべて探します。","monitoringRating.note_step_enter":"下の表で、その回路の{column}フィールドに 2 つ目の定格を入力します。続けて Enter キーを押すか、次のフィールドに移動します。","monitoringRating.note_step_single":"ブレーカーが 1 つだけの回路では、フィールドを空のままにします。","monitoringRating.note_judged":"するとモニタリングは、そのスペースを両方のブレーカーの合計で判定します。20-20 なら 40 A です。コピーを使うのはモニタリングだけで、回路の Breaker Rating センサーは引き続きパネルが報告する値を表示します。コピーした定格を削除するには、フィールドの横の ✕ を選択します。","monitoringRating.note_thresholds":"アラートを止めるためにタンデムのしきい値を 100% より上に上げていた場合は、その行の{reset}を選択してください。それらのしきい値は今後、両方のブレーカーの合計に適用されます。","monitoringRating.note_two_spaces":"2 つのスペースにまたがる回路でも、SPAN アプリに 20-30A のように 2 つの定格が表示されていれば、同じ方法で 2 つ目の定格を入力します。SPAN Panel MAIN 32 パネルはそのような回路の 2 本の線の平均値しか報告せず、過負荷の線が見えなくなることがあるため、コピーは適用できません。その回路のモニタリングをオフにすることをおすすめします。","monitoringRating.note_guide":"詳しくは、タンデムブレーカーと複数負荷ブレーカーのガイドをご覧ください。","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"{circuit} のコピーした定格を削除","monitoringRating.table_threshold_warning":"この回路のしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。{reset}を選択するとグローバルしきい値を使用します。","monitoringRating.table_threshold_warning_global":"グローバルしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。上の{settings}で変更してください。","monitoringRating.warning_announcement":"{circuit}:{warning}","error.package_ratings_failed":"SPAN アプリからコピーした定格の更新に失敗しました","sidepanel.judged_against":"判定基準: {rating}","sidepanel.shedding_priority":"シェディング優先度","sidepanel.priority_label":"優先度","sidepanel.monitoring":"モニタリング","sidepanel.global":"グローバル","sidepanel.custom":"カスタム","sidepanel.continuous_pct":"継続 %","sidepanel.spike_pct":"スパイク %","sidepanel.window_duration":"ウィンドウ時間","sidepanel.cooldown":"クールダウン","sidepanel.favorite":"お気に入り","sidepanel.save_to_favorites":"お気に入りに保存","panel.favorites":"お気に入り","panel.no_panels":"SPANパネルが見つかりません。設定 → デバイスとサービス で追加してください。","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","card.topology_error":"トポロジー応答にpanel_sizeがなく、回路が見つかりません。SPAN Panel統合を更新してください。","editor.panel_label":"SPAN Panel","editor.select_panel":"パネルを選択...","editor.chart_window":"グラフ時間ウィンドウ","editor.days":"日","editor.hours":"時間","editor.minutes":"分","editor.chart_metric":"グラフ指標","editor.visible_sections":"表示セクション","editor.panel_circuits":"パネル回路","editor.battery_bess":"バッテリー (BESS)","editor.ev_charger_evse":"EV充電器 (EVSE)","editor.solar_pv":"ソーラー (PV)","editor.no_entities":"表示するエンティティがありません","editor.tab_style":"タブスタイル","editor.tab_style_text":"テキスト","editor.tab_style_icon":"アイコン","metric.power":"電力","metric.current":"電流","metric.soc":"充電状態","metric.soe":"エネルギー状態","shedding.always_on":"重要","shedding.never":"切断不可","shedding.soc_threshold":"SoCしきい値","shedding.off_grid":"切断可能","shedding.unknown":"不明","shedding.select.never":"停電時もオンを維持","shedding.select.soc_threshold":"バッテリーしきい値までオン","shedding.select.off_grid":"停電時にオフ"},pt:{"tab.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","tab.adopted":"Adotadas","list.search_placeholder":"Pesquisar circuitos...","list.unassigned_area":"Não atribuído","list.no_results":"Nenhum circuito encontrado","monitoring.heading":"Monitoramento","monitoring.global_settings":"Configurações Globais","monitoring.enabled":"Ativado","monitoring.continuous":"Contínuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Janela (min)","monitoring.cooldown":"Resfriamento (min)","monitoring.monitored_points":"Pontos Monitorados","monitoring.col.name":"Nome","monitoring.col.continuous":"Contínuo","monitoring.col.spike":"Pico","monitoring.col.window":"Janela","monitoring.col.cooldown":"Resfriamento","monitoring.rating":"Corrente nominal","monitoring.all_none":"Todos / Nenhum","monitoring.reset":"Redefinir","monitoring.limit_invalid":"Digite um número inteiro de {min} a {max}.","monitoring.enable_invalid":"O monitoramento não foi ativado: corrija os campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Redefinir {name}","monitoring.admin_only":"Somente um administrador pode alterar o monitoramento.","notification.heading":"Configurações de Notificação","notification.targets":"Destinos de Notificação","notification.none_selected":"Nenhum selecionado","notification.targets_button":"Destinos de Notificação: {targets}","notification.no_targets":"Nenhum destino de notificação encontrado","notification.all_targets":"Todos","notification.event_bus_target":"Barramento de Eventos (barramento de eventos do HA)","notification.priority":"Prioridade","notification.priority.default":"Padrão","notification.priority.passive":"Passivo","notification.priority.active":"Ativo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Substitui silencioso/Não perturbar","notification.hint.time_sensitive":"Atravessa o modo Foco","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega padrão","notification.title_template":"Modelo de Título","notification.message_template":"Modelo de Mensagem","notification.placeholders":"Variáveis:","notification.event_bus_help":"O Barramento de Eventos dispara o tipo de evento","notification.event_bus_payload":"com dados:","notification.test_label":"Notificação de teste","notification.test_button":"Enviar teste","notification.test_sending":"Enviando...","notification.test_sent":"Notificação de teste enviada","error.prefix":"Erro:","error.failed_save":"Falha ao salvar","error.panel_offline":"SPAN Panel inacessível","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inacessível","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"Não foi possível conectar ao SPAN Panel","error.relay_failed":"Não foi possível alternar o relé","error.shedding_failed":"Não foi possível atualizar a prioridade de desligamento","error.threshold_failed":"Não foi possível salvar o limite","error.graph_horizon_failed":"Não foi possível atualizar o horizonte temporal do gráfico","error.favorites_fetch_failed":"Não foi possível carregar os favoritos","error.favorites_toggle_failed":"Não foi possível atualizar o favorito","error.history_failed":"Não foi possível carregar os dados históricos","error.monitoring_failed":"Não foi possível carregar o status de monitoramento","error.graph_settings_failed":"Não foi possível carregar as configurações do gráfico","error.areas_failed":"As atribuições de áreas podem estar fora de sincronização","error.retry":"Tentar novamente","card.connecting":"Conectando ao SPAN Panel...","card.waiting_for_load":"Aguardando o carregamento do SPAN Panel...","card.setup_failed":"Não foi possível configurar o SPAN Panel. Verifique Configurações → Dispositivos e serviços.","card.panel_disabled":"Este SPAN Panel está desativado. Ative-o em Configurações → Dispositivos e serviços.","card.restart_needed":"Não foi possível carregar o SPAN Panel. Reinicie o Home Assistant para tentar novamente.","monitoringRating.none":"sem corrente nominal","monitoringRating.copied":"{package} do seu app SPAN (o painel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado do seu app SPAN","monitoringRating.judged_copied":"Avaliado com base em {rating} A: {copied}","adopted.heading":"Entidades adotadas","adopted.description":"As leituras do fornecedor e os dispositivos adotados chegam com metadados mínimos. Faça a curadoria de uma para definir sua classe de dispositivo, classe de estatísticas e proeminência — alterações salvas recarregam a integração e valem a partir da próxima inicialização.","adopted.filter_placeholder":"Filtrar por nome de entidade ou dispositivo","adopted.no_results":"Nenhuma entidade adotada corresponde a este filtro","adopted.none":"Este painel não publica nada para curadoria.","adopted.load_failed":"Não foi possível carregar as entidades adotadas","adopted.count":"{count} adotadas","adopted.vendor_readings":"LEITURAS DO FORNECEDOR","adopted.adopted_device":"DISPOSITIVO ADOTADO","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"O painel não suporta mais o que foi salvo para: {fields}","adopted.enable_entity":"Ativar entidade","adopted.enabled":"ATIVADA","adopted.disabled":"DESATIVADA","adopted.enable_note":"Ativada ao salvar — a curadoria nunca ativa por conta própria","adopted.registry_unavailable":"Ativação e nome ficam disponíveis assim que esta entidade existir no registro.","adopted.name":"Nome","adopted.device_class":"Classe de dispositivo","adopted.device_class_note":"opções limitadas pela unidade do painel ({unit})","adopted.device_class_note_unitless":"opções limitadas pelo que o painel publica","adopted.no_device_class":"Sem classe de dispositivo","adopted.statistics_class":"Classe de estatísticas","adopted.statistics_note":"as estatísticas de longo prazo começam após a próxima recarga","adopted.no_statistics":"Sem estatísticas","adopted.prominence":"Proeminência","adopted.diagnostic":"Diagnóstico","adopted.standard":"Padrão","adopted.display_unit":"Unidade exibida","adopted.unit_as_published":"Como publicada","adopted.precision":"Precisão","adopted.precision_default":"Padrão","adopted.read_only":"somente leitura","adopted.settable":"editável","adopted.save":"Salvar","adopted.clear":"Limpar curadoria","adopted.reload_note":"Salvar recarrega a integração SPAN Panel","adopted.saved":"Salvo — a integração está recarregando","adopted.confirm_heading":"Confirmar classe de estatísticas","adopted.confirm_setting":"Você está definindo {name} como {value}.","adopted.confirm_clearing_subject":"Você está limpando a classe de estatísticas de {name}.","adopted.confirm_total_increasing":"Total crescente trata toda queda do valor como uma reinicialização do medidor. Se esta leitura puder diminuir por qualquer outro motivo, as estatísticas de longo prazo ficarão permanentemente corrompidas — corrigir a classe depois não repara o histórico já gravado.","adopted.confirm_clearing":"As estatísticas de longo prazo deixarão de ser compiladas para esta entidade, e o Home Assistant abrirá um reparo sobre as estatísticas já coletadas na classe que você está removendo.","adopted.save_anyway":"Salvar mesmo assim","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Salvo como total crescente — cada queda da leitura agora conta como uma reinicialização do medidor.","adopted.warn_statistics_removed":"Esta entidade não tem mais classe de estatísticas; o Home Assistant abrirá um reparo sobre as estatísticas já coletadas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.graph_settings":"Configurações do horizonte temporal do gráfico","header.site":"Local","header.grid":"Rede","header.upstream":"Montante","header.downstream":"Jusante","header.solar":"Solar","header.battery":"Bateria","header.toggle_units":"Alternar Watts / Amperes","header.enable_switches":"Ativar Interruptores","header.switches_enabled":"Interruptores Ativados","controls.admin_only":"Somente um administrador pode operar os controles deste painel.","controls.disabled":"O controle deste painel está desativado nas suas opções.","controls.read_only":"Sua conta do Home Assistant não pode operar os controles deste painel.","controls.entity_unauthorized":"Sua conta do Home Assistant não pode operar este controle.","controls.not_operable":"Você não pode operar os controles deste painel.","grid.unknown":"Desconhecido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Lig","grid.off":"Des","grid.shared_switch":"Liga e desliga todos os circuitos deste espaço","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Carregador VE","subdevice.battery":"Bateria","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potência","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total do local","subdevice.in_site_total":"Incluído no total do local","sidepanel.graph_settings":"Configurações de Gráficos","sidepanel.global_defaults":"Padrões globais para todos os circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Padrão Global","sidepanel.list_view_columns":"Colunas da Lista","sidepanel.columns":"Colunas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Redefinir para o padrão global","sidepanel.relay":"Relé","sidepanel.breaker":"Disjuntor","sidepanel.capacity":"capacidade de {amps} A","monitoringRating.title":"Correntes nominais dos disjuntores no app SPAN","monitoringRating.panel_rating":"O painel publica {panel} A","monitoringRating.other_breaker":"Outro disjuntor (A)","monitoringRating.other_breaker_label":"Outro disjuntor no espaço de {circuit}","monitoringRating.reset":"Remover as correntes nominais copiadas","monitoringRating.invalid_other":"Digite a corrente nominal do outro disjuntor como um número inteiro de amperes, 1 ou mais.","monitoringRating.guidance":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-20A, digite a segunda aqui. Os painéis SPAN Panel MAIN 32 informam apenas a primeira, e o monitoramento então avalia este espaço pelos dois disjuntores juntos.","monitoringRating.guidance_two_spaces":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-30A, digite a segunda aqui.","monitoringRating.averaged_legs":"Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases deste circuito, o que pode esconder uma fase sobrecarregada. Recomendamos desativar o monitoramento deste circuito.","monitoringRating.turn_off_monitoring":"Desativar o monitoramento","monitoringRating.threshold_warning":"Os limites personalizados deste circuito passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real.","monitoringRating.threshold_warning_global":"Os limites globais que este circuito usa passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real; altere-os em {settings}, na aba {tab}.","monitoringRating.use_global_thresholds":"Usar os limites globais","monitoringRating.note_title":"Disjuntores tandem no SPAN Panel MAIN 32","monitoringRating.note_problem":"Os painéis SPAN Panel MAIN 32 não informam quais disjuntores são tandem, nem a corrente nominal do segundo disjuntor de um tandem. Um tandem coloca dois disjuntores em um espaço, mas o painel o informa como um único circuito com apenas a corrente nominal do primeiro disjuntor, enquanto um único sensor lê os dois disjuntores juntos. Um tandem 20-20 mostra 20 A aqui e pode conduzir 40 A, então o monitoramento gera alertas falsos nele.","monitoringRating.note_steps":"Para corrigir isso, copie as correntes nominais do seu app SPAN:","monitoringRating.note_step_find":"No app SPAN, encontre cada circuito cujo disjuntor mostra duas correntes nominais, como 20-20A.","monitoringRating.note_step_enter":"Na tabela abaixo, digite a segunda corrente nominal no campo {column} desse circuito. Depois pressione Enter ou vá para o próximo campo.","monitoringRating.note_step_single":"Deixe o campo vazio para um circuito com um único disjuntor.","monitoringRating.note_judged":"O monitoramento então avalia esse espaço pelos dois disjuntores juntos: 40 A para um 20-20. Só o monitoramento usa a cópia, e o sensor Breaker Rating do circuito continua mostrando o que o painel informa. Para remover uma corrente nominal copiada, selecione ✕ ao lado do seu campo.","monitoringRating.note_thresholds":"Se você aumentou os limites de um tandem acima de 100% para interromper os alertas dele, selecione {reset} na linha dele. Esses limites agora se aplicam aos dois disjuntores juntos.","monitoringRating.note_two_spaces":"Para um circuito que ocupa dois espaços, digite a segunda corrente nominal da mesma forma se o seu app SPAN mostrar duas, como 20-30A. Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases de um circuito assim, o que pode esconder uma fase sobrecarregada, então a cópia não pode ser aplicada e recomendamos desativar o monitoramento desse circuito.","monitoringRating.note_guide":"Leia mais no guia de disjuntores tandem e de cargas múltiplas.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remover as correntes nominais copiadas de {circuit}","monitoringRating.table_threshold_warning":"Os limites deste circuito passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Selecione {reset} para usar os limites globais.","monitoringRating.table_threshold_warning_global":"Os limites globais passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Altere-os em {settings}, acima.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Não foi possível atualizar as correntes nominais copiadas do app SPAN","sidepanel.judged_against":"Avaliado com base em: {rating}","sidepanel.shedding_priority":"Prioridade de Desligamento","sidepanel.priority_label":"Prioridade","sidepanel.monitoring":"Monitoramento","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Contínuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duração da janela","sidepanel.cooldown":"Resfriamento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Salvar nos favoritos","panel.favorites":"Favoritos","panel.no_panels":"Nenhum SPAN Panel encontrado. Adicione um em Configurações → Dispositivos e serviços.","status.monitoring":"Monitoramento","status.circuits":"circuitos","status.mains":"alimentação","status.warning":"aviso","status.warnings":"avisos","status.alert":"alerta","status.alerts":"alertas","status.override":"substituição","status.overrides":"substituições","card.no_device":"Abra o editor do cartão e selecione seu dispositivo SPAN Panel.","card.topology_error":"A resposta de topologia não contém panel_size e nenhum circuito encontrado. Atualize a integração SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Selecione um painel...","editor.chart_window":"Janela de tempo do gráfico","editor.days":"dias","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica do gráfico","editor.visible_sections":"Seções visíveis","editor.panel_circuits":"Circuitos do painel","editor.battery_bess":"Bateria (BESS)","editor.ev_charger_evse":"Carregador VE (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"Nenhuma entidade para mostrar","editor.tab_style":"Estilo das abas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícone","metric.power":"Potência","metric.current":"Corrente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energia","shedding.always_on":"Crítico","shedding.never":"Não desligável","shedding.soc_threshold":"Limite SoC","shedding.off_grid":"Desligável","shedding.unknown":"Desconhecido","shedding.select.never":"Permanece ligado em uma queda","shedding.select.soc_threshold":"Ligado até limite da bateria","shedding.select.off_grid":"Desliga em uma queda"}};function n(n){t=n&&e[n]?n:"en"}function i(n){return e[t]?.[n]??e.en?.[n]??n}function r(n,i){return(e[t]?.[n]??e.en?.[n]??n).replace(/\{(\w+)\}/g,(t,e)=>Object.prototype.hasOwnProperty.call(i,e)?i[e]:`{${e}}`)}const o="power",a="5m",s={"5m":{ms:3e5,refreshMs:1e3,useRealtime:!0},"1h":{ms:36e5,refreshMs:3e4,useRealtime:!1},"1d":{ms:864e5,refreshMs:6e4,useRealtime:!1},"1w":{ms:6048e5,refreshMs:6e4,useRealtime:!1},"1M":{ms:2592e6,refreshMs:6e4,useRealtime:!1}},l="span_panel",c="span-panel-card",u=`custom:${c}`,d="span-panel",h=`custom:${d}`,p=`ll-strategy-section-${d}`,f="bess",g="evse",m="pv",v="sub_",y={power:{entityRole:"power",label:()=>i("metric.power"),unit:t=>Math.abs(t)>=1e3?"kW":"W",format:t=>{const e=Math.abs(t);return e>=1e3?(e/1e3).toFixed(1):e<10&&e>0?e.toFixed(1):String(Math.round(e))}},current:{entityRole:"current",label:()=>i("metric.current"),unit:()=>"A",format:t=>Math.abs(t).toFixed(1)}},_={soc:{entityRole:"soc",label:()=>i("metric.soc"),unit:()=>"%",format:t=>String(Math.round(t)),fixedMin:0,fixedMax:100},soe:{entityRole:"soe",label:()=>i("metric.soe"),unit:()=>"kWh",format:t=>t.toFixed(1)},power:y.power},b={always_on:{icon:"mdi:battery",icon2:"mdi:router-wireless",color:"#4caf50",label:()=>i("shedding.always_on")},never:{icon:"mdi:battery",color:"#4caf50",label:()=>i("shedding.never")},soc_threshold:{icon:"mdi:battery-alert-variant-outline",color:"#9c27b0",label:()=>i("shedding.soc_threshold"),textLabel:"SoC"},off_grid:{icon:"mdi:transmission-tower",color:"#ff9800",label:()=>i("shedding.off_grid")},unknown:{icon:"mdi:help-circle-outline",color:"#888",label:()=>i("shedding.unknown")}},x=Object.keys(b).filter(t=>"unknown"!==t&&"always_on"!==t);var w=function(t,e){return w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},w(t,e)};function S(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}w(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function C(t,e,n,i){var r,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(r=t[s])&&(a=(o<3?r(a):o>3?r(e,n,a):r(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}"function"==typeof SuppressedError&&SuppressedError; /** * @license * Copyright 2019 Google LLC @@ -36,7 +36,7 @@ const Ot={attribute:!0,type:String,converter:j,reflect:!1,hasChanged:q},zt=(t=Ot * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */function Bt(t){return Ht({...t,state:!0,attribute:!1})}const Ft="span_panel_list_columns";function $t(){try{const t=localStorage.getItem(Ft);if(!t)return 1;const e=parseInt(t,10);return 1===e||2===e||3===e?e:1}catch{return 1}}function Vt(t){try{localStorage.setItem(Ft,String(t))}catch{}}const Wt={"&":"&","<":"<",">":">",'"':""","'":"'"};function jt(t){return String(t).replace(/[&<>"']/g,t=>Wt[t]??t)}function qt(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}const Ut=y.power,Gt=y.current,Xt="--",Yt=`${Xt}`;function Zt(t){return Ut.unit(t)}function Kt(t){return(t<0?"-":"")+Ut.format(t)}function Qt(t){return null===t?Yt:`${Kt(t)} ${Zt(t)}`}function Jt(t){return null===t?Yt:`${Kt(t)}${Zt(t)}`}function te(t){return null===t?Yt:`${Gt.format(t)}A`}function ee(t){return t instanceof Error||"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message?t.message:String(t)}const ne=new Set(["Unauthorized","UnknownUser"]);function ie(t){if("object"!=typeof t||null===t)return!1;const e="code"in t?t.code:void 0;return"unauthorized"===e||"home_assistant_error"===e&&"message"in t&&ne.has(t.message)}const re="Validation error: ",oe={translation_domain:t=>"translation_domain"in t?t.translation_domain:void 0,translation_key:t=>"translation_key"in t?t.translation_key:void 0,translation_placeholders:t=>"translation_placeholders"in t?t.translation_placeholders:void 0};function ae(t,e){return"object"==typeof t&&null!==t?oe[e](t):void 0}async function se(t,e,n,i){const r=ae(e,"translation_key");if(t&&"string"==typeof r&&ae(e,"translation_domain")===n){const i=`component.${n}.exceptions.${r}.message`;try{const r=t.loadBackendTranslation?await t.loadBackendTranslation("exceptions",n):t.localize,o=r?.(i,function(t){const e=ae(t,"translation_placeholders");if("object"!=typeof e||null===e)return{};const n={};for(const[t,i]of Object.entries(e))"string"!=typeof i&&"number"!=typeof i||(n[t]=i);return n}(e));if(o)return o}catch{}}const o=ee(e),a=o.startsWith(re)?o.slice(18):o;return a&&"[object Object]"!==a?a:i}const le=["relay_state","relay_state_target","priority","priority_target"];function ce(t){return"_favoriteRefs"in t}const ue=Object.freeze({mayOperate:!0,reason:null}),de=Object.freeze({mayOperate:!1,reason:null}),he=["control_disabled","admin_only","read_only"];function pe(t){const e=t?.control_access;return"object"==typeof e&&null!==e&&"may_operate"in e&&"boolean"==typeof e.may_operate?e.may_operate?ue:{mayOperate:!1,reason:"reason"in e&&(n=e.reason,he.some(t=>t===n))?e.reason:null}:ue;var n}function fe(t){return"circuit"===t?.kind}function ge(t,e){if(!t||!ce(t))return pe(t);const n=t._favoriteRefs[e];return fe(n)?n.controlAccess:de}function me(t){return!!t?.entities?.switch&&!1!==t.is_user_controllable}function ve(t,e){const n=new Map;for(const[i,r]of Object.entries(t._favoriteRefs))fe(r)&&e(t.circuits[i])&&n.set(r.panelDeviceId,r.controlAccess);return n}const ye={control_disabled:()=>i("controls.disabled"),admin_only:()=>i("controls.admin_only"),read_only:()=>i("controls.read_only")};function _e(t){return t.mayOperate?"":t.reason?ye[t.reason]():i("controls.not_operable")}class be extends Error{constructor(t){super(t),this.name="ControlChangeRefused"}}function xe(t,e){return{setRelay:(n,i)=>we(t,e,"switch",i?"turn_on":"turn_off",n,{}),setPriority:(n,i)=>we(t,e,"select","select_option",n,{option:i})}}async function we(t,e,n,r,o,a){if(!e.mayOperate)throw new be(_e(e));try{await t.callWS({type:"call_service",domain:n,service:r,service_data:a,target:{entity_id:o}})}catch(t){throw ie(t)?new be(i("controls.entity_unauthorized")):t}}const Se={relay:{key:"service:relay",fallback:()=>i("error.relay_failed")},priority:{key:"service:shedding",fallback:()=>i("error.shedding_failed")}};function Ce(t,e,n,i){console.warn(`SPAN Panel: ${i} change failed`,n);const{key:r,fallback:o}=Se[i];se(t,n,l,o()).then(t=>{e?.add({key:r,level:"error",message:t,persistent:!1})})}function ke(t,e){const n=_e(e);n?t.title=n:t.removeAttribute("title")}function Me(t){const e=_e(t);return e?`
${jt(e)}
`:""}function Te(t,e,n={}){const r=jt(t.device_name||i("header.default_name")),o=jt(t.serial||""),a=jt(t.firmware||""),s="current"===(e.chart_metric||"power"),l=!1!==n.showSwitches;return`\n=t.x&&e<=t.x+t.width&&n>=t.y&&n<=t.y+t.height},t.prototype.contain=function(e,n){return t.contain(this,e,n)},t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(e){t.copy(this,e)},t.prototype.plain=function(){return{x:this.x,y:this.y,width:this.width,height:this.height}},t.prototype.isFinite=function(){return isFinite(this.x)&&isFinite(this.y)&&isFinite(this.width)&&isFinite(this.height)},t.prototype.isZero=function(){return 0===this.width||0===this.height},t.create=function(e){return new t(e.x,e.y,e.width,e.height)},t.copy=function(t,e){return t.x=e.x,t.y=e.y,t.width=e.width,t.height=e.height,t},t.applyTransform=function(e,n,i){if(i){if(i[1]<1e-5&&i[1]>-1e-5&&i[2]<1e-5&&i[2]>-1e-5){var r=i[0],o=i[3],a=i[4],s=i[5];return e.x=n.x*r+a,e.y=n.y*o+s,e.width=n.width*r,e.height=n.height*o,e.width<0&&(e.x+=e.width,e.width=-e.width),void(e.height<0&&(e.y+=e.height,e.height=-e.height))}wo.x=Co.x=n.x,wo.y=ko.y=n.y,So.x=ko.x=n.x+n.width,So.y=Co.y=n.y+n.height,wo.transform(i),ko.transform(i),So.transform(i),Co.transform(i),e.x=vo(wo.x,So.x,Co.x,ko.x),e.y=vo(wo.y,So.y,Co.y,ko.y);var l=yo(wo.x,So.x,Co.x,ko.x),c=yo(wo.y,So.y,Co.y,ko.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),Po=new Do(0,0,0,0),Lo=new Do(0,0,0,0);function Eo(t,e,n,i,r,o,a,s){var l=_o(e-n),c=_o(i-t),u=vo(l,c),d=bo[r],h=bo[1-r],p=xo[r];e ${jt(e)} =t.x&&e<=t.x+t.width&&n>=t.y&&n<=t.y+t.height},t.prototype.contain=function(e,n){return t.contain(this,e,n)},t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(e){t.copy(this,e)},t.prototype.plain=function(){return{x:this.x,y:this.y,width:this.width,height:this.height}},t.prototype.isFinite=function(){return isFinite(this.x)&&isFinite(this.y)&&isFinite(this.width)&&isFinite(this.height)},t.prototype.isZero=function(){return 0===this.width||0===this.height},t.create=function(e){return new t(e.x,e.y,e.width,e.height)},t.copy=function(t,e){return t.x=e.x,t.y=e.y,t.width=e.width,t.height=e.height,t},t.applyTransform=function(e,n,i){if(i){if(i[1]<1e-5&&i[1]>-1e-5&&i[2]<1e-5&&i[2]>-1e-5){var r=i[0],o=i[3],a=i[4],s=i[5];return e.x=n.x*r+a,e.y=n.y*o+s,e.width=n.width*r,e.height=n.height*o,e.width<0&&(e.x+=e.width,e.width=-e.width),void(e.height<0&&(e.y+=e.height,e.height=-e.height))}To.x=Io.x=n.x,To.y=Do.y=n.y,Ao.x=Do.x=n.x+n.width,Ao.y=Io.y=n.y+n.height,To.transform(i),Do.transform(i),Ao.transform(i),Io.transform(i),e.x=wo(To.x,Ao.x,Io.x,Do.x),e.y=wo(To.y,Ao.y,Io.y,Do.y);var l=So(To.x,Ao.x,Io.x,Do.x),c=So(To.y,Ao.y,Io.y,Do.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),Oo=new Ro(0,0,0,0),zo=new Ro(0,0,0,0);function Ho(t,e,n,i,r,o,a,s){var l=Co(e-n),c=Co(i-t),u=wo(l,c),d=ko[r],h=ko[1-r],p=Mo[r];e qp[1]){if(r=!1,Up.negativeSize||n)return r;var s=Wp(qp[0]-jp[1]),l=Wp(jp[0]-qp[1]);$p(s,l)>Xp.len()&&(s 1&&i>0?s:a}};return o;function a(){return e=0;o--){var a=t[o],s=void 0;if(a!==r&&!a.ignore&&(s=Vo(a,n,i))&&(!e.topTarget&&(e.topTarget=a),s!==Ro)){e.target=a;break}}}function jo(t,e,n){var i=t.painter;return e<0||e>i.getWidth()||n<0||n>i.getHeight()}ji(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){$o.prototype[t]=function(e){var n,i,r=e.zrX,o=e.zrY,a=jo(this,r,o);if("mouseup"===t&&a||(i=(n=this.findHover(r,o)).target),"mousedown"===t)this._downEl=i,this._downPoint=[e.zrX,e.zrY],this._upEl=i;else if("mouseup"===t)this._upEl=i;else if("click"===t){if(this._downEl!==this._upEl||!this._downPoint||Er(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function qo(t,e,n,i){var r=e+1;if(r===n)return 1;if(i(t[r++],t[e])<0){for(;r0;)a=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),a+=r,l+=r}else{for(s=r+1;ls&&(l=s);var c=a;a=r-l,l=r-c}for(a++;as&&(l=s);var c=a;a=r-l,l=r-c}else{for(s=i-r;l=0;)a=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),a+=r,l+=r}for(a++;a=0;l--)t[p+l]=t[h+l];return void(t[d]=a[u])}var f=r;for(;;){var g=0,m=0,v=!1;do{if(e(a[u],t[c])<0){if(t[d--]=t[c--],g++,m=0,0===--i){v=!0;break}}else if(t[d--]=a[u--],m++,g=0,1===--s){v=!0;break}}while((g|m)1;){var t=o-2;if(t>=1&&i[t-1]<=i[t]+i[t+1]||t>=2&&i[t-2]<=i[t]+i[t-1])i[t-1]i[t+1])break;s(t)}},forceMergeRuns:function(){for(;o>1;){var t=o-2;t>0&&i[t-1]=32;)e|=1&t,t>>=1;return t+e}(r);do{if((o=qo(t,n,i,e))s&&(l=s),Uo(t,n,n+l,n+o,e),o=l}a.pushRun(n,o),a.mergeRuns(),r-=o,n+=o}while(0!==r);a.forceMergeRuns()}}}var Ko=!1;function Qo(){Ko||(Ko=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function Jo(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var ta,ea=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=Jo}return t.prototype.traverse=function(t,e){for(var n=0;n${r}
\n ${o}\n \n ${l?function(t,e={}){const n=!t.mayOperate;return`${!1===e.note?"":Me(t)}`}(function(t){if(!t||!ce(t))return pe(t);const e=[...ve(t,me).values()],[n]=e;return!n||e.some(t=>t.mayOperate)?ue:n}(t)):""}\n =0;o--){var a=t[o],s=void 0;if(a!==r&&!a.ignore&&(s=Go(a,n,i))&&(!e.topTarget&&(e.topTarget=a),s!==Fo)){e.target=a;break}}}function Yo(t,e,n){var i=t.painter;return e<0||e>i.getWidth()||n<0||n>i.getHeight()}Yi(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){Uo.prototype[t]=function(e){var n,i,r=e.zrX,o=e.zrY,a=Yo(this,r,o);if("mouseup"===t&&a||(i=(n=this.findHover(r,o)).target),"mousedown"===t)this._downEl=i,this._downPoint=[e.zrX,e.zrY],this._upEl=i;else if("mouseup"===t)this._upEl=i;else if("click"===t){if(this._downEl!==this._upEl||!this._downPoint||Hr(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function Zo(t,e,n,i){var r=e+1;if(r===n)return 1;if(i(t[r++],t[e])<0){for(;r0;)a=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),a+=r,l+=r}else{for(s=r+1;ls&&(l=s);var c=a;a=r-l,l=r-c}for(a++;as&&(l=s);var c=a;a=r-l,l=r-c}else{for(s=i-r;l=0;)a=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),a+=r,l+=r}for(a++;a=0;l--)t[p+l]=t[h+l];return void(t[d]=a[u])}var f=r;for(;;){var g=0,m=0,v=!1;do{if(e(a[u],t[c])<0){if(t[d--]=t[c--],g++,m=0,0===--i){v=!0;break}}else if(t[d--]=a[u--],m++,g=0,1===--s){v=!0;break}}while((g|m)1;){var t=o-2;if(t>=1&&i[t-1]<=i[t]+i[t+1]||t>=2&&i[t-2]<=i[t]+i[t-1])i[t-1]i[t+1])break;s(t)}},forceMergeRuns:function(){for(;o>1;){var t=o-2;t>0&&i[t-1]=32;)e|=1&t,t>>=1;return t+e}(r);do{if((o=Zo(t,n,i,e))s&&(l=s),Ko(t,n,n+l,n+o,e),o=l}a.pushRun(n,o),a.mergeRuns(),r-=o,n+=o}while(0!==r);a.forceMergeRuns()}}}var na=!1;function ia(){na||(na=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function ra(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var oa,aa=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=ra}return t.prototype.traverse=function(t,e){for(var n=0;n0&&t.arc(c+U.cx,u+U.cy,q,dp(U.y0,U.x0),dp(U.y1,U.x1),!d),t.arc(c,u,r,dp(U.cy+U.y1,U.cx+U.x1),dp(G.cy+G.y1,G.cx+G.x1),d),j>0&&t.arc(c+G.cx,u+G.cy,j,dp(G.y1,G.x1),dp(G.y0,G.x0),!d))}else t.lineTo(c+L,u+E),t.arc(c,u,r,l,s,d);else t.lineTo(c+L,u+E)}else t.moveTo(c,u);t.closePath()}}}var _p=function(){this.cx=0,this.cy=0,this.r0=0,this.r=0,this.startAngle=0,this.endAngle=2*Math.PI,this.clockwise=!0,this.cornerRadius=0},bp=function(t){function e(e){return t.call(this,e)||this}return S(e,t),e.prototype.getDefaultShape=function(){return new _p},e.prototype.buildPath=function(t,e){yp(t,e)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(gd);bp.prototype.type="sector";var xp=function(){this.cx=0,this.cy=0,this.r=0,this.r0=0},wp=function(t){function e(e){return t.call(this,e)||this}return S(e,t),e.prototype.getDefaultShape=function(){return new xp},e.prototype.buildPath=function(t,e){var n=e.cx,i=e.cy,r=2*Math.PI;t.moveTo(n+e.r,i),t.arc(n,i,e.r,0,r,!1),t.moveTo(n+e.r0,i),t.arc(n,i,e.r0,0,r,!0)},e}(gd);function Sp(t,e,n){var i=e.smooth,r=e.points;if(r&&r.length>=2){if(i){var o=function(t,e,n,i){var r,o,a,s,l=[],c=[],u=[],d=[];if(i){a=[1/0,1/0],s=[-1/0,-1/0];for(var h=0,p=t.length;hg[1]&&(g[1]=f)}return this._rawCount=this._count=s,{start:a,end:s}},t.prototype._initDataFromProvider=function(t,e,n){for(var i=this._provider,r=this._chunks,o=this._dimensions,a=o.length,s=this._rawExtent,l=qi(o,function(t){return t.property}),c=0;cm[1]&&(m[1]=g)}}!i.persistent&&i.clean&&i.clean(),this._rawCount=this._count=e,this._extent=[]},t.prototype.count=function(){return this._count},t.prototype.get=function(t,e){if(!(e>=0&&eu[1]&&(u[1]=m),d[h++]=v}return r._count=h,r._indices=d,r._updateGetRawIdx(),r},t.prototype.each=function(t,e){if(this._count)for(var n=t.length,i=this._chunks,r=0,o=this.count();r
",g=c.join(f);this._showOrMove(o,function(){this._updateContentNotChangedOnAxis(t,s)?this._updatePosition(o,d,r[0],r[1],this._tooltipContent,s):this._showTooltipContent(o,g,s,Math.random()+"",r[0],r[1],d,null,u)})},e.prototype._showSeriesItemTooltip=function(t,e,n){var i=this._ecModel,r=jd(e),o=r.seriesIndex,a=i.getSeriesByIndex(o),s=r.dataModel||a,l=r.dataIndex,c=r.dataType,u=s.getData(c),d=this._renderMode,h=t.positionDefault,p=oT([u.getItemModel(l),s,a&&(a.coordinateSystem||{}).model],this._tooltipModel,h?{position:h}:null),f=p.get("trigger");if(null==f||"item"===f){var g=s.getDataParams(l,c),m=new Qy;g.marker=m.makeTooltipMarker("item",rm(g.color),d);var v=cy(s.formatTooltip(l,!1,c)),y=p.get("order"),_=p.get("valueFormatter"),b=v.frag,x=b?Xy(_?Bi({valueFormatter:_},b):b,m,d,y,i.get("useUTC"),p.get("textStyle")):v.text,w="item_"+s.name+"_"+l;this._showOrMove(p,function(){this._showTooltipContent(p,x,g,w,t.offsetX,t.offsetY,t.position,t.target,m)}),n({type:"showTip",dataIndexInside:l,dataIndex:u.getRawIndex(l),seriesIndex:o,from:this.uid})}},e.prototype._showComponentItemTooltip=function(t,e,n){var i="html"===this._renderMode,r=jd(e),o=r.tooltipConfig.option||{},a=o.encodeHTMLContent;if(Ji(o)){o={content:o,formatter:o},a=!0}a&&i&&o.content&&((o=zi(o)).content=Zr(o.content));var s=[o],l=this._ecModel.getComponent(r.componentMainType,r.componentIndex);l&&s.push(l),s.push({formatter:o.content});var c=t.positionDefault,u=oT(s,this._tooltipModel,c?{position:c}:null),d=u.get("content"),h=Math.random()+"",p=new Qy;this._showOrMove(u,function(){var n=zi(u.get("formatterParams")||{});this._showTooltipContent(u,d,n,h,t.offsetX,t.offsetY,t.position,e,p)}),n({type:"showTip",from:this.uid})},e.prototype._showTooltipContent=function(t,e,n,i,r,o,a,s,l){if(this._ticket="",t.get("showContent")&&t.get("show")){var c=this._tooltipContent;c.setEnterable(t.get("enterable"));var u=t.get("formatter");a=a||t.get("position");var d=e,h=this._getNearestPoint([r,o],n,t.get("trigger"),t.get("borderColor"),t.get("defaultBorderColor",!0)).color;if(u)if(Ji(u)){var p=t.ecModel.get("useUTC"),f=Ki(n)?n[0]:n;d=u,f&&f.axisType&&f.axisType.indexOf("time")>=0&&(d=Ng(f.axisValue,d,p)),d=im(d,n,!0)}else if(Qi(u)){var g=Yi(function(e,i){e===this._ticket&&(c.setContent(i,l,t,h,a),this._updatePosition(t,a,r,o,c,n,s))},this);this._ticket=i,d=u(n,i,g)}else d=u;c.setContent(d,l,t,h,a),c.show(t,h),this._updatePosition(t,a,r,o,c,n,s)}},e.prototype._getNearestPoint=function(t,e,n,i,r){return"axis"===n||Ki(e)?{color:i||r}:Ki(e)?void 0:{color:i||e.color||e.borderColor}},e.prototype._updatePosition=function(t,e,n,i,r,o,a){var s=this._api.getWidth(),l=this._api.getHeight();e=e||t.get("position");var c=r.getSize(),u=t.get("align"),d=t.get("verticalAlign"),h=a&&a.getBoundingRect().clone();if(a&&h.applyTransform(a.transform),Qi(e)&&(e=e([n,i],o,r.el,h,{viewSize:[s,l],contentSize:c.slice()})),Ki(e))n=Wl(e[0],s),i=Wl(e[1],l);else if(nr(e)){var p=e;p.width=c[0],p.height=c[1];var f=_m(p,{width:s,height:l});n=f.x,i=f.y,u=null,d=null}else if(Ji(e)&&a){var g=function(t,e,n,i){var r=n[0],o=n[1],a=Math.ceil(Math.SQRT2*i)+8,s=0,l=0,c=e.width,u=e.height;switch(t){case"inside":s=e.x+c/2-r/2,l=e.y+u/2-o/2;break;case"top":s=e.x+c/2-r/2,l=e.y-o-a;break;case"bottom":s=e.x+c/2-r/2,l=e.y+u+a;break;case"left":s=e.x-r-a,l=e.y+u/2-o/2;break;case"right":s=e.x+c+a,l=e.y+u/2-o/2}return[s,l]}(e,h,c,t.get("borderWidth"));n=g[0],i=g[1]}else{g=function(t,e,n,i,r,o,a){var s=n.getSize(),l=s[0],c=s[1];null!=o&&(t+l+o+2>i?t-=l+o:t+=o);null!=a&&(e+c+a>r?e-=c+a:e+=a);return[t,e]}(n,i,r,s,l,u?null:20,d?null:20);n=g[0],i=g[1]}if(u&&(n-=sT(u)?c[0]/2:"right"===u?c[0]:0),d&&(i-=sT(d)?c[1]/2:"bottom"===d?c[1]:0),VM(t)){g=function(t,e,n,i,r){var o=n.getSize(),a=o[0],s=o[1];return t=Math.min(t+a,i)-a,e=Math.min(e+s,r)-s,t=Math.max(t,0),e=Math.max(e,0),[t,e]}(n,i,r,s,l);n=g[0],i=g[1]}r.moveTo(n,i)},e.prototype._updateContentNotChangedOnAxis=function(t,e){var n=this._lastDataByCoordSys,i=this._cbParamsList,r=!!n&&n.length===t.length;return r&&ji(n,function(n,o){var a=n.dataByAxis||[],s=(t[o]||{}).dataByAxis||[];(r=r&&a.length===s.length)&&ji(a,function(t,n){var o=s[n]||{},a=t.seriesDataIndices||[],l=o.seriesDataIndices||[];(r=r&&t.value===o.value&&t.axisType===o.axisType&&t.axisId===o.axisId&&a.length===l.length)&&ji(a,function(t,e){var n=l[e];r=r&&t.seriesIndex===n.seriesIndex&&t.dataIndex===n.dataIndex}),i&&ji(t.seriesDataIndices,function(t){var n=t.seriesIndex,o=e[n],a=i[n];o&&a&&a.data!==o.data&&(r=!1)})})}),this._lastDataByCoordSys=t,this._cbParamsList=e,!!r},e.prototype._hide=function(t){this._lastDataByCoordSys=null,t({type:"hideTip",from:this.uid})},e.prototype.dispose=function(t,e){!mi.node&&e.getDom()&&(k_(this,"_updatePosition"),this._tooltipContent.dispose(),DM("itemTooltip",e))},e.type="tooltip",e}(u_);function oT(t,e,n){var i,r=e.ecModel;n?(i=new lg(n,r,r),i=new lg(e.option,i,r)):i=e;for(var o=t.length-1;o>=0;o--){var a=t[o];a&&(a instanceof lg&&(a=a.get("tooltip",!0)),Ji(a)&&(a={formatter:a}),a&&(i=new lg(a,i,r)))}return i}function aT(t,e){return t.dispatchAction||Yi(e.dispatchAction,e)}function sT(t){return"center"===t||"middle"===t}var lT=Math.sin,cT=Math.cos,uT=Math.PI,dT=2*Math.PI,hT=180/uT,pT=function(){function t(){}return t.prototype.reset=function(t){this._start=!0,this._d=[],this._str="",this._p=Math.pow(10,t||4)},t.prototype.moveTo=function(t,e){this._add("M",t,e)},t.prototype.lineTo=function(t,e){this._add("L",t,e)},t.prototype.bezierCurveTo=function(t,e,n,i,r,o){this._add("C",t,e,n,i,r,o)},t.prototype.quadraticCurveTo=function(t,e,n,i){this._add("Q",t,e,n,i)},t.prototype.arc=function(t,e,n,i,r,o){this.ellipse(t,e,n,n,0,i,r,o)},t.prototype.ellipse=function(t,e,n,i,r,o,a,s){var l=a-o,c=!s,u=Math.abs(l),d=ts(u-dT)||(c?l>=dT:-l>=dT),h=l>0?l%dT:l%dT+dT,p=!1;p=!!d||!ts(u)&&h>=uT==!!c;var f=t+n*cT(o),g=e+i*lT(o);this._start&&this._add("M",f,g);var m=Math.round(r*hT);if(d){var v=1/this._p,y=(c?1:-1)*(dT-v);this._add("A",n,i,m,1,+c,t+n*cT(o+y),e+i*lT(o+y)),v>.01&&this._add("A",n,i,m,0,+c,f,g)}else{var _=t+n*cT(a),b=e+i*lT(a);this._add("A",n,i,m,+p,+c,_,b)}},t.prototype.rect=function(t,e,n,i){this._add("M",t,e),this._add("l",n,0),this._add("l",0,i),this._add("l",-n,0),this._add("Z")},t.prototype.closePath=function(){this._d.length>0&&this._add("Z")},t.prototype._add=function(t,e,n,i,r,o,a,s,l){for(var c=[],u=this._p,d=1;d