From b4b5bf1efaa328edbcf795650465117d6d7a4d62 Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 10:29:27 -0800
Subject: [PATCH 01/15] refactor(controls): say once who the control mode lets
operate the panel
ControlPolicy.refusal_for answers why the mode refuses a caller, judged by whether the caller is an administrator, or None for a caller with no logged-in user, whom only Nobody refuses. The gate asks it once per command and acts on the answer in its own order: Nobody first, then the lock, then contextless control, then Administrators only. Every refusal and its message is unchanged.
---
custom_components/span_panel/control_gate.py | 70 +++++++++++++++++---
tests/test_control_gate.py | 19 ++++++
2 files changed, 81 insertions(+), 8 deletions(-)
diff --git a/custom_components/span_panel/control_gate.py b/custom_components/span_panel/control_gate.py
index b2e7bb26..5b5506b6 100644
--- a/custom_components/span_panel/control_gate.py
+++ b/custom_components/span_panel/control_gate.py
@@ -96,6 +96,22 @@ class ControlMode(StrEnum):
"""
+class ControlAccessRefusal(StrEnum):
+ """Why the control mode refuses a caller, judged by who the caller is.
+
+ The values are wire values: `span_panel/panel_topology` reports them to the
+ card as `control_access.reason`. They are not the gate's translation keys,
+ which name the refusal a service caller is shown and are free to be worded
+ for that reader.
+ """
+
+ CONTROL_DISABLED = "control_disabled"
+ """The mode is `disabled`, so no one may operate the panel."""
+
+ ADMIN_ONLY = "admin_only"
+ """The mode is `admin_only` and the caller is not an administrator."""
+
+
@dataclass(frozen=True, slots=True)
class ControlCaller:
"""Who issued the command currently being published, if anyone.
@@ -171,6 +187,30 @@ def lock_enabled(self) -> bool:
"""
return self.lock_timeout_minutes is not None and self.mode is not ControlMode.DISABLED
+ def refusal_for(self, *, is_admin: bool | None) -> ControlAccessRefusal | None:
+ """Why the control mode refuses this caller, or None where it does not.
+
+ The one statement of who the mode lets operate the panel. The gate
+ enforces it on every command, and `span_panel/panel_topology` reports it
+ for whoever is viewing the card, so the controls the card offers and the
+ commands the gate lets through cannot come to disagree.
+
+ `is_admin` is None for a caller with no logged-in user. `disabled`
+ refuses that caller as it refuses everyone. `admin_only` does not judge
+ it, there being no user to judge: whether a command with no user is let
+ through is `allow_contextless`'s question, which the gate asks on its
+ own.
+
+ Nothing here is about the moment. Whether the control lock is armed
+ changes while a page is open, and the relay debounce is about one
+ circuit's last command; the gate asks both itself.
+ """
+ if self.mode is ControlMode.DISABLED:
+ return ControlAccessRefusal.CONTROL_DISABLED
+ if self.mode is ControlMode.ADMIN_ONLY and is_admin is False:
+ return ControlAccessRefusal.ADMIN_ONLY
+ return None
+
@classmethod
def default(cls) -> ControlPolicy:
"""Return the policy an entry with no control options configured has.
@@ -386,13 +426,18 @@ async def before_publish(self, command: ControlCommand) -> None:
context = caller.context if caller is not None else None
user_id = context.user_id if context is not None else None
+ # Judged once, by the rule the topology reports to the card, and acted
+ # on below in this method's own order: `disabled` before everything,
+ # `admin_only` last.
+ refusal = self._policy.refusal_for(is_admin=await self._caller_is_admin(user_id))
+
# First, because it is the entry-wide answer and the most useful thing
# to be told. Not creating the entities is what a user sees, but it is
# not a choke point: a command arriving by any other route -- a service
# this integration grows later, a code path that forgets the helper --
# would otherwise be published by an entry whose owner switched control
# off. That is the promise this module opens with.
- if self._policy.mode is ControlMode.DISABLED:
+ if refusal is ControlAccessRefusal.CONTROL_DISABLED:
self._refuse(
"control_disabled",
"Control of this SPAN panel is switched off in its options. "
@@ -413,13 +458,11 @@ async def before_publish(self, command: ControlCommand) -> None:
parent_id=context.parent_id if context is not None else None,
)
- if self._policy.mode is ControlMode.ADMIN_ONLY and user_id is not None:
- user = await self._hass.auth.async_get_user(user_id)
- if user is None or not user.is_admin:
- self._refuse(
- "admin_only_control",
- "Only a Home Assistant administrator may operate this SPAN panel.",
- )
+ if refusal is ControlAccessRefusal.ADMIN_ONLY:
+ self._refuse(
+ "admin_only_control",
+ "Only a Home Assistant administrator may operate this SPAN panel.",
+ )
if command.property_id == RELAY_PROPERTY:
self._refuse_a_debounced_relay(command)
@@ -461,6 +504,17 @@ async def after_publish(self, command: ControlCommand, outcome: PublishOutcome)
# -- internals ----------------------------------------------------------
+ async def _caller_is_admin(self, user_id: str | None) -> bool | None:
+ """Whether the caller is an administrator, or None when there is no logged-in user.
+
+ A user id that no longer resolves -- a user deleted since the call was
+ made -- is not an administrator.
+ """
+ if user_id is None:
+ return None
+ user = await self._hass.auth.async_get_user(user_id)
+ return user is not None and user.is_admin
+
def _refuse_a_debounced_relay(self, command: ControlCommand) -> None:
"""Refuse a relay command that follows too closely on the last one.
diff --git a/tests/test_control_gate.py b/tests/test_control_gate.py
index 309e3174..7fdbab2c 100644
--- a/tests/test_control_gate.py
+++ b/tests/test_control_gate.py
@@ -8,6 +8,7 @@
from __future__ import annotations
+from dataclasses import replace
from datetime import timedelta
from unittest.mock import AsyncMock, MagicMock, patch
@@ -21,6 +22,7 @@
from custom_components.span_panel.const import DOMAIN, EVENT_CONTROL_COMMAND
from custom_components.span_panel.control_gate import (
CONTROL_CALLER,
+ ControlAccessRefusal,
ControlGate,
ControlLock,
ControlMode,
@@ -683,6 +685,23 @@ def test_an_entry_with_no_control_options_gets_the_defaults() -> None:
assert policy.relay_debounce_seconds == 2.0
+@pytest.mark.parametrize(
+ ("mode", "refusal"),
+ [
+ (ControlMode.ALL_USERS, None),
+ (ControlMode.ADMIN_ONLY, None),
+ (ControlMode.DISABLED, ControlAccessRefusal.CONTROL_DISABLED),
+ ],
+)
+def test_the_mode_judges_a_caller_with_no_user_only_by_refusing_everyone(
+ mode: ControlMode, refusal: ControlAccessRefusal | None
+) -> None:
+ """`admin_only` has no user to judge; whether such a command goes through is `allow_contextless`'s question."""
+ policy = replace(ControlPolicy.default(), mode=mode)
+
+ assert policy.refusal_for(is_admin=None) is refusal
+
+
def test_an_unrecognised_mode_falls_back_to_the_permissive_one() -> None:
"""A typo in `.storage` must not lock a household out of its own panel."""
policy = ControlPolicy.from_options({"control_mode": "nonsense"})
From f9997bbecaa388b8078c8b9779bdd3c5f2c64168 Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 10:32:13 -0800
Subject: [PATCH 02/15] feat(websocket): tell the topology's asker whether they
may operate the panel
span_panel/panel_topology answers control_access, {may_operate, reason}, for the user the connection is authenticated as. The reason is what ControlPolicy.refusal_for, the rule the gate refuses a command by, answers for that user under the entry's policy: null, admin_only or control_disabled. The card can then disable the relay and priority controls of a user the gate would refuse. The control lock is not part of it, and contextless control never applies to a WebSocket caller.
A test runs the topology and the gate for every mode and every kind of user and holds them to one answer. The capture topologies gain the key, and the test that an open command answers a non-admin as it answers an administrator now sets aside what the answer says about its asker.
---
custom_components/span_panel/websocket.py | 31 ++-
tests/fixtures/topology/main32_r202633.json | 4 +
.../main32_r202639-battery-unvalued.json | 4 +
.../topology/main32_r202639-no-battery.json | 4 +
.../main32_r202639-unpublished-readings.json | 4 +
tests/fixtures/topology/main32_r202639.json | 4 +
tests/fixtures/topology/r202639-a.json | 4 +
tests/fixtures/topology/r202639-b.json | 4 +
tests/fixtures/topology/r202639-c.json | 4 +
tests/fixtures/topology/r202639-d.json | 4 +
tests/fixtures/topology/r202639-e.json | 4 +
tests/test_topology_control_access.py | 197 ++++++++++++++++++
tests/test_websocket_admin_rule.py | 36 +++-
13 files changed, 300 insertions(+), 4 deletions(-)
create mode 100644 tests/test_topology_control_access.py
diff --git a/custom_components/span_panel/websocket.py b/custom_components/span_panel/websocket.py
index 01eac0a0..b37bdb63 100644
--- a/custom_components/span_panel/websocket.py
+++ b/custom_components/span_panel/websocket.py
@@ -13,7 +13,7 @@
from span_panel_api import shared_meter_groups
from .const import DOMAIN
-from .control_gate import ControlMode
+from .control_gate import ControlAccessRefusal, ControlMode, ControlPolicy
from .current_monitor import MonitoredCircuit, monitored_circuits
from .energy_orientation import circuit_is_generation
from .entity_resolver import entity_id_in_entry
@@ -38,6 +38,7 @@
from .websocket_panel import resolve_panel_device
if TYPE_CHECKING:
+ from homeassistant.auth.models import User
from span_panel_api import SpanCircuitSnapshot, SpanPanelSnapshot
# Mapping from unique_id suffixes to semantic role names for circuit sensors.
@@ -110,7 +111,9 @@ async def handle_panel_topology(
each circuit and device, the ratings current monitoring judges each circuit
against, and the registry IDs that tie them together; no host, credential
or certificate is in it. Whether a control it names may be operated is
- decided by the control policy when the control is used, not here.
+ decided by the control policy when the control is used, not here; what
+ `control_access` carries is that policy's answer for the user asking, so
+ the card can offer no control the gate would refuse them.
The caller passes the HA device registry ID for the **main SPAN panel**
device only (not a sub-device or a circuit's device). Returns panel
@@ -325,6 +328,10 @@ async def handle_panel_topology(
# circuit's `package_ratings_form` says whether it takes a copy, and in
# which form.
"monitoring_rating_offered": not describes_breakers,
+ # Whether the user asking may operate the panel, by the policy the
+ # gate holds. It is the same object: setup hands one policy to the
+ # gate and to the runtime data, and an options change reloads both.
+ "control_access": _control_access_record(runtime_data.control_policy, connection.user),
"circuits": circuits,
# Each shared meter by the key its members carry in `shared_meter_group`.
"shared_meter_groups": meter_groups,
@@ -359,6 +366,26 @@ def _meter_group_record(point: MonitoredCircuit) -> MeterGroupRecord:
)
+class ControlAccessRecord(TypedDict):
+ """Whether the user asking may operate the panel, and if not, why.
+
+ `reason` is `ControlPolicy.refusal_for`'s answer for that user, the answer
+ the gate refuses a command by, and `may_operate` is true exactly where it is
+ null. Neither says whether the control lock is armed, which changes while
+ the card is open and which the card reads from the lock's own switch. A
+ WebSocket connection always has a logged-in user, so whether control
+ without one is allowed never comes into it.
+ """
+
+ may_operate: bool
+ reason: ControlAccessRefusal | None
+
+
+def _control_access_record(policy: ControlPolicy, user: User) -> ControlAccessRecord:
+ refusal = policy.refusal_for(is_admin=user.is_admin)
+ return ControlAccessRecord(may_operate=refusal is None, reason=refusal)
+
+
def _group_of(groups: Mapping[str, tuple[str, ...]]) -> dict[str, str]:
"""Map every member of every group to its group's key."""
return {member: key for key, members in groups.items() for member in members}
diff --git a/tests/fixtures/topology/main32_r202633.json b/tests/fixtures/topology/main32_r202633.json
index 882f9062..1c236fcb 100644
--- a/tests/fixtures/topology/main32_r202633.json
+++ b/tests/fixtures/topology/main32_r202633.json
@@ -687,6 +687,10 @@
}
},
"config_entry_id": "entry-main32_r202633",
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"device_id": "nt-0000-panel",
"device_name": "Span Panel",
"firmware": "spanos3/r202633/02",
diff --git a/tests/fixtures/topology/main32_r202639-battery-unvalued.json b/tests/fixtures/topology/main32_r202639-battery-unvalued.json
index eb465977..e57cf43f 100644
--- a/tests/fixtures/topology/main32_r202639-battery-unvalued.json
+++ b/tests/fixtures/topology/main32_r202639-battery-unvalued.json
@@ -589,6 +589,10 @@
}
},
"config_entry_id": "entry-main32_r202639-battery-unvalued",
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"device_id": "nt-9874-s7rxt",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
diff --git a/tests/fixtures/topology/main32_r202639-no-battery.json b/tests/fixtures/topology/main32_r202639-no-battery.json
index 26c46d22..faf256bb 100644
--- a/tests/fixtures/topology/main32_r202639-no-battery.json
+++ b/tests/fixtures/topology/main32_r202639-no-battery.json
@@ -589,6 +589,10 @@
}
},
"config_entry_id": "entry-main32_r202639-no-battery",
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"device_id": "nt-9874-s7rxt",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
diff --git a/tests/fixtures/topology/main32_r202639-unpublished-readings.json b/tests/fixtures/topology/main32_r202639-unpublished-readings.json
index b07f0e97..4bcf02b3 100644
--- a/tests/fixtures/topology/main32_r202639-unpublished-readings.json
+++ b/tests/fixtures/topology/main32_r202639-unpublished-readings.json
@@ -589,6 +589,10 @@
}
},
"config_entry_id": "entry-main32_r202639-unpublished-readings",
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"device_id": "nt-9874-s7rxt",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
diff --git a/tests/fixtures/topology/main32_r202639.json b/tests/fixtures/topology/main32_r202639.json
index c6120988..06464ab8 100644
--- a/tests/fixtures/topology/main32_r202639.json
+++ b/tests/fixtures/topology/main32_r202639.json
@@ -589,6 +589,10 @@
}
},
"config_entry_id": "entry-main32_r202639",
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"device_id": "nt-9874-s7rxt",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
diff --git a/tests/fixtures/topology/r202639-a.json b/tests/fixtures/topology/r202639-a.json
index e6581ef8..caecbb59 100644
--- a/tests/fixtures/topology/r202639-a.json
+++ b/tests/fixtures/topology/r202639-a.json
@@ -105,6 +105,10 @@
}
},
"config_entry_id": "entry-r202639-a",
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"device_id": "xg-3940-9ooto",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
diff --git a/tests/fixtures/topology/r202639-b.json b/tests/fixtures/topology/r202639-b.json
index fb373d16..7994cac0 100644
--- a/tests/fixtures/topology/r202639-b.json
+++ b/tests/fixtures/topology/r202639-b.json
@@ -609,6 +609,10 @@
}
},
"config_entry_id": "entry-r202639-b",
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"device_id": "xg-1155-18fkf",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
diff --git a/tests/fixtures/topology/r202639-c.json b/tests/fixtures/topology/r202639-c.json
index 4d28f4e9..07831b6b 100644
--- a/tests/fixtures/topology/r202639-c.json
+++ b/tests/fixtures/topology/r202639-c.json
@@ -181,6 +181,10 @@
}
},
"config_entry_id": "entry-r202639-c",
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"device_id": "xg-7814-15i6h",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
diff --git a/tests/fixtures/topology/r202639-d.json b/tests/fixtures/topology/r202639-d.json
index 4d67083b..e77e7f51 100644
--- a/tests/fixtures/topology/r202639-d.json
+++ b/tests/fixtures/topology/r202639-d.json
@@ -254,6 +254,10 @@
}
},
"config_entry_id": "entry-r202639-d",
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"device_id": "xg-1334-066e8",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
diff --git a/tests/fixtures/topology/r202639-e.json b/tests/fixtures/topology/r202639-e.json
index d2eb7340..a7ec7161 100644
--- a/tests/fixtures/topology/r202639-e.json
+++ b/tests/fixtures/topology/r202639-e.json
@@ -1661,6 +1661,10 @@
}
},
"config_entry_id": "entry-r202639-e",
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"device_id": "xg-6159-74dlx",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
diff --git a/tests/test_topology_control_access.py b/tests/test_topology_control_access.py
new file mode 100644
index 00000000..5d985056
--- /dev/null
+++ b/tests/test_topology_control_access.py
@@ -0,0 +1,197 @@
+"""`span_panel/panel_topology` tells the card whether the user asking may operate the panel.
+
+`control_access` is the control mode's answer for the WebSocket connection's
+user, by `ControlPolicy.refusal_for` -- the rule the gate refuses a command by.
+The card disables the panel's controls for a user it says may not operate them,
+so what it says and what the gate does must not come apart: the last test runs
+both, for every mode and every kind of user, and holds them to one answer.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import replace
+from typing import Final
+from unittest.mock import AsyncMock, MagicMock
+
+from homeassistant.auth.const import GROUP_ID_ADMIN, GROUP_ID_READ_ONLY, GROUP_ID_USER
+from homeassistant.config_entries import ConfigEntryState
+from homeassistant.core import Context, HomeAssistant
+from homeassistant.exceptions import ServiceValidationError
+import pytest
+from pytest_homeassistant.common import CLIENT_ID, MockConfigEntry, MockUser
+from pytest_homeassistant.typing import WebSocketGenerator
+from span_panel_api import ControlCommand, FieldMetadata
+
+from custom_components.span_panel.const import DOMAIN
+from custom_components.span_panel.control_gate import (
+ CONTROL_CALLER,
+ ControlGate,
+ ControlLock,
+ ControlMode,
+ ControlPolicy,
+ async_bind_caller,
+)
+from custom_components.span_panel.curation import CurationOverlay
+from custom_components.span_panel.package_rating_manager import PackageRatingManager
+from custom_components.span_panel.runtime import SpanPanelRuntimeData
+from custom_components.span_panel.websocket import async_register_commands
+
+from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory, pv_binding_for
+from .helpers import register_panel_device
+
+_SERIAL: Final = "sp3-synthetic-access-001"
+_CIRCUIT_ID: Final = "circuit-3"
+_DECLARED: Final = {"panel.main_breaker_rating_a": FieldMetadata(unit="A", datatype="integer")}
+
+_PRIORITY: Final = ControlCommand(
+ device_id=_SERIAL,
+ node_id=_CIRCUIT_ID,
+ property_id="priority",
+ value="OFF_GRID",
+ topic=f"ebus/5/{_CIRCUIT_ID}/load-shed/priority/set",
+)
+"""A command the relay debounce never touches, so a refusal is only ever about who asked."""
+
+EXPECTED_REASON: Final[Mapping[tuple[ControlMode, bool], str | None]] = {
+ (ControlMode.ALL_USERS, True): None,
+ (ControlMode.ALL_USERS, False): None,
+ (ControlMode.ADMIN_ONLY, True): None,
+ (ControlMode.ADMIN_ONLY, False): "admin_only",
+ (ControlMode.DISABLED, True): "control_disabled",
+ (ControlMode.DISABLED, False): "control_disabled",
+}
+"""`control_access.reason` by control mode and whether the asker is an administrator.
+
+Written as the wire values the card reads, so renaming one fails here.
+"""
+
+GATE_REFUSAL: Final[Mapping[str | None, str | None]] = {
+ None: None,
+ "admin_only": "admin_only_control",
+ "control_disabled": "control_disabled",
+}
+"""The refusal the gate gives a command, by the `control_access.reason` the topology reports.
+
+None is no refusal on either side: the topology says the user may operate the
+panel, and the gate lets the command through.
+"""
+
+_GROUPS: Final = {
+ "administrator": GROUP_ID_ADMIN,
+ "ordinary user": GROUP_ID_USER,
+ "read-only user": GROUP_ID_READ_ONLY,
+}
+
+
+@pytest.fixture(params=list(_GROUPS.values()), ids=list(_GROUPS))
+async def asker(hass: HomeAssistant, request: pytest.FixtureRequest) -> MockUser:
+ """Return a logged-in user from each group a Home Assistant user can be in."""
+ group = await hass.auth.async_get_group(request.param)
+ assert group is not None
+ user = MockUser(groups=[group]).add_to_hass(hass)
+ assert user.is_admin is (request.param == GROUP_ID_ADMIN)
+ return user
+
+
+async def _load_panel(hass: HomeAssistant, mode: ControlMode) -> tuple[MockConfigEntry, str]:
+ """Load a one-circuit panel whose control mode is `mode`, and return its entry and device's registry ID."""
+ snapshot = SpanPanelSnapshotFactory.create(
+ serial_number=_SERIAL,
+ circuits={
+ _CIRCUIT_ID: SpanCircuitSnapshotFactory.create(
+ circuit_id=_CIRCUIT_ID, name="Synthetic Circuit", tabs=[3], breaker_rating_a=20.0
+ )
+ },
+ main_breaker_rating_a=100,
+ )
+ entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=_SERIAL)
+ entry.add_to_hass(hass)
+ manager = PackageRatingManager(hass, entry)
+ await manager.async_load()
+ manager.begin(snapshot, _DECLARED)
+ coordinator = MagicMock()
+ coordinator.data = snapshot
+ coordinator.package_rating_manager = manager
+ # Home Assistant unloads the loaded entry as the test ends, which shuts the
+ # coordinator down.
+ coordinator.async_shutdown = AsyncMock()
+ device_id = register_panel_device(hass, entry, _SERIAL)
+ entry.runtime_data = SpanPanelRuntimeData(
+ coordinator=coordinator,
+ panel_device_id=device_id,
+ curation=CurationOverlay.empty(),
+ pv_binding=pv_binding_for(snapshot),
+ setup_snapshot=snapshot,
+ control_policy=replace(ControlPolicy.default(), mode=mode),
+ )
+ entry.mock_state(hass, ConfigEntryState.LOADED)
+ async_register_commands(hass)
+ return entry, device_id
+
+
+async def _control_access(
+ hass: HomeAssistant, hass_ws_client: WebSocketGenerator, user: MockUser, device_id: str
+) -> dict[str, object]:
+ """Ask for the topology as `user` and return its `control_access`."""
+ refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID)
+ client = await hass_ws_client(hass, hass.auth.async_create_access_token(refresh_token))
+ await client.send_json_auto_id({"type": "span_panel/panel_topology", "device_id": device_id})
+ reply = await client.receive_json()
+ assert reply["success"] is True, reply
+ control_access = reply["result"]["control_access"]
+ assert isinstance(control_access, dict)
+ return control_access
+
+
+async def _gate_refusal(hass: HomeAssistant, entry: MockConfigEntry, user: MockUser) -> str | None:
+ """Return the refusal the entry's gate gives `user`'s command, or None where it lets it through.
+
+ The gate is built as setup builds it, from the policy the runtime data
+ holds, with the lock open so the only refusal left is about who asked.
+ """
+ gate = ControlGate(hass, entry, entry.runtime_data.control_policy, ControlLock(armed=False))
+ token = async_bind_caller(Context(user_id=user.id), "select.span_panel_synthetic_circuit")
+ try:
+ await gate.before_publish(_PRIORITY)
+ except ServiceValidationError as refused:
+ return refused.translation_key
+ finally:
+ CONTROL_CALLER.reset(token)
+ return None
+
+
+def test_every_mode_has_an_expected_answer_for_both_kinds_of_user() -> None:
+ """A mode added later has to be given its answers here before the card can rely on them."""
+ assert set(EXPECTED_REASON) == {
+ (mode, is_admin) for mode in ControlMode for is_admin in (True, False)
+ }
+
+
+@pytest.mark.parametrize("mode", list(ControlMode))
+async def test_the_topology_says_whether_the_asker_may_operate_the_panel(
+ hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mode: ControlMode, asker: MockUser
+) -> None:
+ """`may_operate` is true exactly where `reason` is null, and `reason` is the mode's answer for the asker."""
+ _, device_id = await _load_panel(hass, mode)
+
+ control_access = await _control_access(hass, hass_ws_client, asker, device_id)
+
+ reason = EXPECTED_REASON[(mode, asker.is_admin)]
+ assert control_access == {"may_operate": reason is None, "reason": reason}
+
+
+@pytest.mark.parametrize("mode", list(ControlMode))
+async def test_the_topology_and_the_gate_give_the_asker_the_same_answer(
+ hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mode: ControlMode, asker: MockUser
+) -> None:
+ """The gate refuses the asker's command exactly where the topology says they may not operate the panel, and for the reason it gives."""
+ entry, device_id = await _load_panel(hass, mode)
+
+ control_access = await _control_access(hass, hass_ws_client, asker, device_id)
+ refusal = await _gate_refusal(hass, entry, asker)
+
+ assert control_access["may_operate"] is (refusal is None)
+ reason = control_access["reason"]
+ assert reason is None or isinstance(reason, str)
+ assert GATE_REFUSAL[reason] == refusal
diff --git a/tests/test_websocket_admin_rule.py b/tests/test_websocket_admin_rule.py
index 1fd40220..2765cbe2 100644
--- a/tests/test_websocket_admin_rule.py
+++ b/tests/test_websocket_admin_rule.py
@@ -75,6 +75,16 @@
}
"""The commands every logged-in user may send."""
+ABOUT_THE_ASKER: Final[Mapping[str, frozenset[str]]] = {
+ "span_panel/panel_topology": frozenset({"control_access"}),
+}
+"""The keys of an open command's answer that describe the user asking, and so differ by user.
+
+`control_access` is the control policy's answer for that user; see
+`test_topology_control_access.py`. Everything else an open command answers is
+the same for every user.
+"""
+
async def _non_admin(hass: HomeAssistant, group_id: str) -> MockUser:
"""Add a logged-in user in `group_id`, one of the groups a user who is not an administrator is in."""
@@ -108,6 +118,11 @@ async def _send(
return reply
+def _apart_from(result: Mapping[str, object], keys: frozenset[str]) -> dict[str, object]:
+ """Return a command's answer without `keys`."""
+ return {key: value for key, value in result.items() if key not in keys}
+
+
def _error_code(reply: Mapping[str, object]) -> object:
"""Return the code of a refused command's error."""
error = reply["error"]
@@ -189,6 +204,11 @@ def test_the_classifications_do_not_overlap() -> None:
assert not set(ADMINISTRATOR_ONLY) & set(OPEN_TO_EVERY_USER)
+def test_only_an_open_command_answers_about_the_asker() -> None:
+ """A key set aside as describing the asker belongs to a command every user may send."""
+ assert set(ABOUT_THE_ASKER) <= set(OPEN_TO_EVERY_USER)
+
+
def _registered_commands(hass: HomeAssistant) -> set[str]:
"""Return the type of every WebSocket command registered on `hass`, whoever registered it."""
handlers = hass.data.get(websocket_api.DOMAIN, {})
@@ -254,7 +274,12 @@ async def test_an_open_command_answers_a_non_admin_as_it_answers_an_administrato
command: str,
fields: CommandFields,
) -> None:
- """The answer does not depend on who asks: a non-admin gets exactly what an administrator gets."""
+ """A non-admin gets exactly what an administrator gets, apart from what the answer says about the asker.
+
+ The keys that describe the asker are set aside only once both answers are
+ seen to carry them, so naming one that the command does not answer fails
+ here rather than excusing nothing.
+ """
as_admin = await _send(await hass_ws_client(hass), command, fields(panel_device_id))
as_non_admin = await _send(
await _client_for(hass, hass_ws_client, non_admin_user), command, fields(panel_device_id)
@@ -262,7 +287,14 @@ async def test_an_open_command_answers_a_non_admin_as_it_answers_an_administrato
assert as_admin["success"] is True
assert as_non_admin["success"] is True
- assert as_non_admin["result"] == as_admin["result"]
+ admin_result, non_admin_result = as_admin["result"], as_non_admin["result"]
+ assert isinstance(admin_result, dict)
+ assert isinstance(non_admin_result, dict)
+ about_the_asker = ABOUT_THE_ASKER.get(command, frozenset())
+ assert about_the_asker <= set(admin_result) & set(non_admin_result)
+ assert _apart_from(non_admin_result, about_the_asker) == _apart_from(
+ admin_result, about_the_asker
+ )
async def test_a_non_admin_reads_the_panels_topology(
From 804410eef3878552be236f3cedb6113e2e692801 Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 10:34:42 -0800
Subject: [PATCH 03/15] docs(websocket-api): document the topology's
control_access
Says what may_operate and reason answer, for whom, and what they leave out: the control lock, the relay debounce and contextless control. Prettier rewraps the paragraph on the package-ratings event, which was committed unwrapped.
---
websocket-api.md | 25 ++++++++++++++++++++++---
1 file changed, 22 insertions(+), 3 deletions(-)
diff --git a/websocket-api.md b/websocket-api.md
index b783bb7c..541c5146 100644
--- a/websocket-api.md
+++ b/websocket-api.md
@@ -17,7 +17,8 @@ provides all of these relationships explicitly, keyed by circuit UUID, so the ca
Any logged-in user may call it, administrator or not, so the sidebar dashboard and the card work for whoever is viewing them. It carries the panel's layout,
what the panel publishes about each circuit and device, the ratings current monitoring judges each circuit against, and the registry IDs that tie them together;
no host, credential or certificate is in it. Whether a switch or select it names can be operated is decided when it is used, by
-[Who may operate the panel](README.md#restricting-who-can-operate-the-panel).
+[Who may operate the panel](README.md#restricting-who-can-operate-the-panel). `control_access` reports that option's answer for the user asking, so a card can
+disable the controls that user would be refused.
### Request
@@ -49,6 +50,10 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID.
"config_entry_id": "e5f6a7b8c9d0",
"device_name": "SPAN Panel",
"monitoring_rating_offered": true,
+ "control_access": {
+ "may_operate": true,
+ "reason": null
+ },
"circuits": {
"a1b2c3d4e5f6": {
"device_id": "c7d8e9f0a1b2",
@@ -209,10 +214,24 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID.
| `config_entry_id` | string | The config entry that owns the panel |
| `device_name` | string | HA device display name |
| `monitoring_rating_offered` | bool | Whether `set_circuit_package_ratings` takes ratings on this panel: false where the panel publishes each circuit of a multi-load breaker with its own rating |
+| `control_access` | object | Whether the user asking may operate the panel, and if not, why (see below) |
| `circuits` | object | Circuit UUID keyed map (see below) |
| `shared_meter_groups` | object | Each group of circuits that share a meter, keyed by the group key its members carry in `shared_meter_group` (see below); empty where no meter is shared |
| `sub_devices` | object | HA device ID keyed map of BESS/MID/EVSE/PV (see below) |
+#### Control Access Object
+
+| Field | Type | Description |
+| ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `may_operate` | bool | Whether **Who may operate the panel** lets the user asking operate the panel's controls |
+| `reason` | string/null | Why not: `control_disabled` where the option is `Nobody`, `admin_only` where it is `Administrators only` and the user is not an administrator; null where `may_operate` is true |
+
+The answer is for the user the WebSocket connection is authenticated as, so two users asking about the same panel can be told different things. It comes from
+the rule the integration refuses a control command by, so a card that disables its relay and priority controls where `may_operate` is false offers no control
+that rule would refuse. It says nothing about the control lock, which can be armed or disarmed while a page is open and which its switch reports, nor about the
+relay debounce. **Allow control without a logged-in user** never applies, because a WebSocket connection always has a logged-in user. Changing **Who may operate
+the panel** reloads the entry, and the topology then answers by the new setting.
+
#### Circuit Object
| Field | Type | Description |
@@ -387,8 +406,8 @@ snapshot removes one or changes its `package_ratings_state`. A consumer showing
| `circuit_ids` | array[string] | The circuits whose package ratings, or what they are judged as, changed |
Subscribing to this event over the WebSocket API (`subscribe_events`) requires an administrator: Home Assistant lets any other user subscribe only to the events
-on its own allowlist, and this integration's event is not on it. Any other user reads the same ratings from `span_panel/panel_topology`, and sees a change the next
-time it fetches the topology.
+on its own allowlist, and this integration's event is not on it. Any other user reads the same ratings from `span_panel/panel_topology`, and sees a change the
+next time it fetches the topology.
## `span_panel/adopted/list`
From a95484fbc40bbc4086e3a9d65f37c1acd9cdac6d Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 10:49:24 -0800
Subject: [PATCH 04/15] feat(websocket): report a user whose permissions allow
no control as read_only
control_access.reason may also be read_only. Home Assistant refuses a user who is not an administrator control of any entity their permissions do not allow, before the gate is asked, so the card would otherwise offer a read-only user controls that fail.
The new control_access module asks the control mode first and the user's permissions second, over the relay switches and priority selects the topology offers, and reports read_only only where the user may control none of them. Administrators are not checked, as Core does not check them, and a panel offering no circuit control reports no permission refusal. The gate is unchanged.
Tests hold the topology to Core's own refusal of a switch.turn_on and to the gate's refusals, for every mode and every kind of user.
---
.../span_panel/control_access.py | 96 ++++++
custom_components/span_panel/control_gate.py | 7 +-
custom_components/span_panel/websocket.py | 60 ++--
tests/test_topology_control_access.py | 293 ++++++++++++++----
tests/test_websocket_admin_rule.py | 2 +-
5 files changed, 366 insertions(+), 92 deletions(-)
create mode 100644 custom_components/span_panel/control_access.py
diff --git a/custom_components/span_panel/control_access.py b/custom_components/span_panel/control_access.py
new file mode 100644
index 00000000..b41a555d
--- /dev/null
+++ b/custom_components/span_panel/control_access.py
@@ -0,0 +1,96 @@
+"""Whether the user asking may operate the panel, as `span_panel/panel_topology` reports it.
+
+The card disables a panel's relay and priority controls for a user this says may
+not operate them, so it answers from the two rules that would refuse that user
+and restates neither:
+
+- **The control mode**, `ControlPolicy.refusal_for`, which the gate enforces on
+ every command. It comes first, because it is the integration's own answer
+ and holds for every control the entry has.
+- **The user's Home Assistant permissions.** Core refuses an entity service
+ call from a user who is not an administrator, with `Unauthorized`, for each
+ entity that `user.permissions.check_entity(entity_id, POLICY_CONTROL)` does
+ not allow, and administrators are not checked at all (`helpers/service.py`).
+ That happens before any entity, and so before the gate, is asked, which is
+ why the gate never answers it and this module has to.
+
+`control_access` asks the mode, then the permissions, and reports the first
+refusal.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Collection
+from enum import StrEnum
+from typing import TYPE_CHECKING, TypedDict
+
+from homeassistant.auth.permissions.const import POLICY_CONTROL
+
+from .control_gate import ControlAccessRefusal, ControlPolicy
+
+if TYPE_CHECKING:
+ from homeassistant.auth.models import User
+
+
+class PermissionRefusal(StrEnum):
+ """Why the user's own Home Assistant permissions keep them from operating the panel.
+
+ A wire value beside `ControlAccessRefusal`'s, in the same
+ `control_access.reason` field. Separate because Core decides it, not the
+ control mode, and the gate never refuses for it.
+ """
+
+ READ_ONLY = "read_only"
+ """The user may control none of the panel's circuit controls, as a Read Only user may control nothing."""
+
+
+class ControlAccessRecord(TypedDict):
+ """Whether the user asking may operate the panel, and if not, why.
+
+ `may_operate` is true exactly where `reason` is null. Neither says whether
+ the control lock is armed, which changes while the card is open and which
+ the card reads from the lock's own switch. A WebSocket connection always
+ has a logged-in user, so whether control without one is allowed never comes
+ into it.
+ """
+
+ may_operate: bool
+ reason: ControlAccessRefusal | PermissionRefusal | None
+
+
+def control_access(
+ policy: ControlPolicy, user: User, circuit_controls: Collection[str]
+) -> ControlAccessRecord:
+ """Return whether `user` may operate the panel whose policy is `policy`.
+
+ `circuit_controls` is the entity id of every relay switch and priority
+ select the topology offers for the panel's circuits. The permissions are
+ checked against those, and only those, because they are what the card
+ disables on this answer: a user able to control only the control lock's
+ switch, or an EVSE's, could still operate none of them.
+
+ `read_only` is reported where there is at least one such control and the
+ user may control none of them. Where they may control some, the card keeps
+ its controls and Core refuses the rest, one at a time, as it would anywhere
+ else -- the answer is one flag for the whole panel, and a user who can
+ operate something is not told they can operate nothing. Where the panel
+ offers no circuit control there is nothing to disable and nothing for Core
+ to refuse, so the permissions are not reported.
+ """
+ reason: ControlAccessRefusal | PermissionRefusal | None = policy.refusal_for(
+ is_admin=user.is_admin
+ )
+ if reason is None:
+ reason = _permission_refusal(user, circuit_controls)
+ return ControlAccessRecord(may_operate=reason is None, reason=reason)
+
+
+def _permission_refusal(user: User, circuit_controls: Collection[str]) -> PermissionRefusal | None:
+ """Core's answer for `user` over `circuit_controls`, by the check its entity services make."""
+ if user.is_admin or not circuit_controls:
+ return None
+ if any(
+ user.permissions.check_entity(entity_id, POLICY_CONTROL) for entity_id in circuit_controls
+ ):
+ return None
+ return PermissionRefusal.READ_ONLY
diff --git a/custom_components/span_panel/control_gate.py b/custom_components/span_panel/control_gate.py
index 5b5506b6..02b2536b 100644
--- a/custom_components/span_panel/control_gate.py
+++ b/custom_components/span_panel/control_gate.py
@@ -100,9 +100,10 @@ class ControlAccessRefusal(StrEnum):
"""Why the control mode refuses a caller, judged by who the caller is.
The values are wire values: `span_panel/panel_topology` reports them to the
- card as `control_access.reason`. They are not the gate's translation keys,
- which name the refusal a service caller is shown and are free to be worded
- for that reader.
+ card as `control_access.reason`, beside the one Home Assistant's own
+ permissions give, which `control_access` adds. They are not the gate's
+ translation keys, which name the refusal a service caller is shown and are
+ free to be worded for that reader.
"""
CONTROL_DISABLED = "control_disabled"
diff --git a/custom_components/span_panel/websocket.py b/custom_components/span_panel/websocket.py
index b37bdb63..a5de01f8 100644
--- a/custom_components/span_panel/websocket.py
+++ b/custom_components/span_panel/websocket.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from collections.abc import Collection, Mapping
-from typing import TYPE_CHECKING, Any, TypedDict
+from typing import TYPE_CHECKING, Any, Final, TypedDict
from homeassistant.components import websocket_api
from homeassistant.config_entries import ConfigEntryState
@@ -13,7 +13,8 @@
from span_panel_api import shared_meter_groups
from .const import DOMAIN
-from .control_gate import ControlAccessRefusal, ControlMode, ControlPolicy
+from .control_access import control_access
+from .control_gate import ControlMode
from .current_monitor import MonitoredCircuit, monitored_circuits
from .energy_orientation import circuit_is_generation
from .entity_resolver import entity_id_in_entry
@@ -38,7 +39,6 @@
from .websocket_panel import resolve_panel_device
if TYPE_CHECKING:
- from homeassistant.auth.models import User
from span_panel_api import SpanCircuitSnapshot, SpanPanelSnapshot
# Mapping from unique_id suffixes to semantic role names for circuit sensors.
@@ -111,9 +111,10 @@ async def handle_panel_topology(
each circuit and device, the ratings current monitoring judges each circuit
against, and the registry IDs that tie them together; no host, credential
or certificate is in it. Whether a control it names may be operated is
- decided by the control policy when the control is used, not here; what
- `control_access` carries is that policy's answer for the user asking, so
- the card can offer no control the gate would refuse them.
+ decided by the control policy and by Home Assistant's permissions when the
+ control is used, not here; `control_access` carries their answer for the
+ user asking, so the card can disable the controls that user would be
+ refused. See `control_access`.
The caller passes the HA device registry ID for the **main SPAN panel**
device only (not a sub-device or a circuit's device). Returns panel
@@ -194,6 +195,9 @@ async def handle_panel_topology(
# Build circuits section.
circuits: dict[str, dict[str, Any]] = {}
+ # Every relay switch and priority select offered below, which
+ # `control_access` checks the user's permissions against.
+ circuit_controls: list[str] = []
for circuit_id, circuit in snapshot.circuits.items():
if circuit_id not in circuit_ids:
continue
@@ -203,6 +207,10 @@ async def handle_panel_topology(
own_device = circuit_device(
device_registry, snapshot.serial_number, circuit_id, config_entry_id=config_entry_id
)
+ offered = _offered_roles(
+ entity_map.get(circuit_id, {}), circuit, runtime_data.control_policy.mode
+ )
+ circuit_controls.extend(offered[role] for role in _CONTROL_ROLES if role in offered)
circuits[circuit_id] = {
# The circuit's own device, a child of the panel's, by its registry
# id; null where the circuit has none. A consumer reads the name and
@@ -260,9 +268,7 @@ async def handle_panel_topology(
# circuit, because a consumer rendering from this record has no
# other way to tell a pinned priority from an absent one.
"is_never_backup": None if circuit.measures_outside_panel else circuit.is_never_backup,
- "entities": _offered_roles(
- entity_map.get(circuit_id, {}), circuit, runtime_data.control_policy.mode
- ),
+ "entities": offered,
}
# Build sub-devices section from devices linked via via_device_id.
@@ -328,10 +334,14 @@ async def handle_panel_topology(
# circuit's `package_ratings_form` says whether it takes a copy, and in
# which form.
"monitoring_rating_offered": not describes_breakers,
- # Whether the user asking may operate the panel, by the policy the
- # gate holds. It is the same object: setup hands one policy to the
- # gate and to the runtime data, and an options change reloads both.
- "control_access": _control_access_record(runtime_data.control_policy, connection.user),
+ # Whether the user asking may operate the panel: by the policy the
+ # gate holds, then by their own permissions over the controls offered
+ # above. The policy is the gate's own object: setup hands one policy
+ # to the gate and to the runtime data, and an options change reloads
+ # both.
+ "control_access": control_access(
+ runtime_data.control_policy, connection.user, circuit_controls
+ ),
"circuits": circuits,
# Each shared meter by the key its members carry in `shared_meter_group`.
"shared_meter_groups": meter_groups,
@@ -366,26 +376,6 @@ def _meter_group_record(point: MonitoredCircuit) -> MeterGroupRecord:
)
-class ControlAccessRecord(TypedDict):
- """Whether the user asking may operate the panel, and if not, why.
-
- `reason` is `ControlPolicy.refusal_for`'s answer for that user, the answer
- the gate refuses a command by, and `may_operate` is true exactly where it is
- null. Neither says whether the control lock is armed, which changes while
- the card is open and which the card reads from the lock's own switch. A
- WebSocket connection always has a logged-in user, so whether control
- without one is allowed never comes into it.
- """
-
- may_operate: bool
- reason: ControlAccessRefusal | None
-
-
-def _control_access_record(policy: ControlPolicy, user: User) -> ControlAccessRecord:
- refusal = policy.refusal_for(is_admin=user.is_admin)
- return ControlAccessRecord(may_operate=refusal is None, reason=refusal)
-
-
def _group_of(groups: Mapping[str, tuple[str, ...]]) -> dict[str, str]:
"""Map every member of every group to its group's key."""
return {member: key for key, members in groups.items() for member in members}
@@ -440,6 +430,10 @@ def _solar_block(
return None
+_CONTROL_ROLES: Final = ("switch", "select")
+"""The roles that name a circuit control: its relay switch and its priority select."""
+
+
def _offered_roles(
roles: Mapping[str, str], circuit: SpanCircuitSnapshot, mode: ControlMode
) -> dict[str, str]:
diff --git a/tests/test_topology_control_access.py b/tests/test_topology_control_access.py
index 5d985056..f0d4e6b4 100644
--- a/tests/test_topology_control_access.py
+++ b/tests/test_topology_control_access.py
@@ -1,10 +1,13 @@
"""`span_panel/panel_topology` tells the card whether the user asking may operate the panel.
-`control_access` is the control mode's answer for the WebSocket connection's
-user, by `ControlPolicy.refusal_for` -- the rule the gate refuses a command by.
-The card disables the panel's controls for a user it says may not operate them,
-so what it says and what the gate does must not come apart: the last test runs
-both, for every mode and every kind of user, and holds them to one answer.
+`control_access` answers from two rules and restates neither: the control mode,
+by `ControlPolicy.refusal_for`, which the gate refuses a command by, and then the
+user's own Home Assistant permissions over the circuit controls, which Core
+refuses an entity service call by before the gate is asked. The card disables
+the panel's controls for a user it says may not operate them, so what it says
+must not come apart from what either rule does: two tests here run the rule
+itself -- the gate, and a service call through Core -- beside the topology and
+hold them to one answer.
"""
from __future__ import annotations
@@ -17,15 +20,19 @@
from homeassistant.auth.const import GROUP_ID_ADMIN, GROUP_ID_READ_ONLY, GROUP_ID_USER
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import Context, HomeAssistant
-from homeassistant.exceptions import ServiceValidationError
+from homeassistant.exceptions import ServiceValidationError, Unauthorized
+from homeassistant.helpers import entity_registry as er
+from homeassistant.setup import async_setup_component
import pytest
from pytest_homeassistant.common import CLIENT_ID, MockConfigEntry, MockUser
from pytest_homeassistant.typing import WebSocketGenerator
from span_panel_api import ControlCommand, FieldMetadata
from custom_components.span_panel.const import DOMAIN
+from custom_components.span_panel.control_access import PermissionRefusal, control_access
from custom_components.span_panel.control_gate import (
CONTROL_CALLER,
+ ControlAccessRefusal,
ControlGate,
ControlLock,
ControlMode,
@@ -33,6 +40,7 @@
async_bind_caller,
)
from custom_components.span_panel.curation import CurationOverlay
+from custom_components.span_panel.id_builder import build_select_unique_id, build_switch_unique_id
from custom_components.span_panel.package_rating_manager import PackageRatingManager
from custom_components.span_panel.runtime import SpanPanelRuntimeData
from custom_components.span_panel.websocket import async_register_commands
@@ -53,15 +61,31 @@
)
"""A command the relay debounce never touches, so a refusal is only ever about who asked."""
-EXPECTED_REASON: Final[Mapping[tuple[ControlMode, bool], str | None]] = {
- (ControlMode.ALL_USERS, True): None,
- (ControlMode.ALL_USERS, False): None,
- (ControlMode.ADMIN_ONLY, True): None,
- (ControlMode.ADMIN_ONLY, False): "admin_only",
- (ControlMode.DISABLED, True): "control_disabled",
- (ControlMode.DISABLED, False): "control_disabled",
+_ADMINISTRATOR: Final = "administrator"
+_ORDINARY: Final = "ordinary user"
+_READ_ONLY: Final = "read-only user"
+
+_GROUPS: Final = {
+ _ADMINISTRATOR: GROUP_ID_ADMIN,
+ _ORDINARY: GROUP_ID_USER,
+ _READ_ONLY: GROUP_ID_READ_ONLY,
}
-"""`control_access.reason` by control mode and whether the asker is an administrator.
+"""Each group a Home Assistant user can be in, by the name its tests carry."""
+
+EXPECTED_REASON: Final[Mapping[tuple[ControlMode, str], str | None]] = {
+ (ControlMode.ALL_USERS, _ADMINISTRATOR): None,
+ (ControlMode.ALL_USERS, _ORDINARY): None,
+ (ControlMode.ALL_USERS, _READ_ONLY): "read_only",
+ (ControlMode.ADMIN_ONLY, _ADMINISTRATOR): None,
+ (ControlMode.ADMIN_ONLY, _ORDINARY): "admin_only",
+ # The mode's answer comes first, so a read-only user is told it rather than
+ # their own permissions'.
+ (ControlMode.ADMIN_ONLY, _READ_ONLY): "admin_only",
+ (ControlMode.DISABLED, _ADMINISTRATOR): "control_disabled",
+ (ControlMode.DISABLED, _ORDINARY): "control_disabled",
+ (ControlMode.DISABLED, _READ_ONLY): "control_disabled",
+}
+"""`control_access.reason` by control mode and the group the asker is in, on a panel with circuit controls.
Written as the wire values the card reads, so renaming one fails here.
"""
@@ -70,37 +94,46 @@
None: None,
"admin_only": "admin_only_control",
"control_disabled": "control_disabled",
+ # Core's reason, reported only where the mode has none, so the gate lets
+ # the command through: Core refuses it before the gate is asked.
+ "read_only": None,
}
"""The refusal the gate gives a command, by the `control_access.reason` the topology reports.
-None is no refusal on either side: the topology says the user may operate the
-panel, and the gate lets the command through.
+None is no refusal by the gate.
"""
-_GROUPS: Final = {
- "administrator": GROUP_ID_ADMIN,
- "ordinary user": GROUP_ID_USER,
- "read-only user": GROUP_ID_READ_ONLY,
-}
-
-@pytest.fixture(params=list(_GROUPS.values()), ids=list(_GROUPS))
-async def asker(hass: HomeAssistant, request: pytest.FixtureRequest) -> MockUser:
- """Return a logged-in user from each group a Home Assistant user can be in."""
- group = await hass.auth.async_get_group(request.param)
+@pytest.fixture(params=list(_GROUPS), ids=list(_GROUPS))
+async def asker(hass: HomeAssistant, request: pytest.FixtureRequest) -> tuple[str, MockUser]:
+ """Return a logged-in user from each group, with the group's name."""
+ name: str = request.param
+ group = await hass.auth.async_get_group(_GROUPS[name])
assert group is not None
user = MockUser(groups=[group]).add_to_hass(hass)
- assert user.is_admin is (request.param == GROUP_ID_ADMIN)
- return user
+ assert user.is_admin is (name == _ADMINISTRATOR)
+ return name, user
-async def _load_panel(hass: HomeAssistant, mode: ControlMode) -> tuple[MockConfigEntry, str]:
- """Load a one-circuit panel whose control mode is `mode`, and return its entry and device's registry ID."""
+async def _load_panel(
+ hass: HomeAssistant, mode: ControlMode, *, with_controls: bool = True
+) -> tuple[MockConfigEntry, str, list[str]]:
+ """Load a one-circuit panel whose control mode is `mode`.
+
+ Returns its entry, its device's registry ID, and the entity ids of the
+ circuit's relay switch and priority select, which are registered only
+ `with_controls`.
+ """
snapshot = SpanPanelSnapshotFactory.create(
serial_number=_SERIAL,
circuits={
_CIRCUIT_ID: SpanCircuitSnapshotFactory.create(
- circuit_id=_CIRCUIT_ID, name="Synthetic Circuit", tabs=[3], breaker_rating_a=20.0
+ circuit_id=_CIRCUIT_ID,
+ name="Synthetic Circuit",
+ tabs=[3],
+ breaker_rating_a=20.0,
+ is_user_controllable=True,
+ is_never_backup=False,
)
},
main_breaker_rating_a=100,
@@ -126,22 +159,46 @@ async def _load_panel(hass: HomeAssistant, mode: ControlMode) -> tuple[MockConfi
control_policy=replace(ControlPolicy.default(), mode=mode),
)
entry.mock_state(hass, ConfigEntryState.LOADED)
+
+ controls: list[str] = []
+ if with_controls:
+ entities = er.async_get(hass)
+ for domain, unique_id in (
+ ("switch", build_switch_unique_id(_SERIAL, _CIRCUIT_ID)),
+ ("select", build_select_unique_id(_SERIAL, _CIRCUIT_ID)),
+ ):
+ registered = entities.async_get_or_create(
+ domain, DOMAIN, unique_id, config_entry=entry, device_id=device_id
+ )
+ controls.append(registered.entity_id)
+
async_register_commands(hass)
- return entry, device_id
+ return entry, device_id, controls
-async def _control_access(
+async def _topology(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, user: MockUser, device_id: str
) -> dict[str, object]:
- """Ask for the topology as `user` and return its `control_access`."""
+ """Ask for the topology as `user` and return it."""
refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID)
client = await hass_ws_client(hass, hass.auth.async_create_access_token(refresh_token))
await client.send_json_auto_id({"type": "span_panel/panel_topology", "device_id": device_id})
reply = await client.receive_json()
assert reply["success"] is True, reply
- control_access = reply["result"]["control_access"]
- assert isinstance(control_access, dict)
- return control_access
+ topology = reply["result"]
+ assert isinstance(topology, dict)
+ return topology
+
+
+async def _control_access(
+ hass: HomeAssistant, hass_ws_client: WebSocketGenerator, user: MockUser, device_id: str
+) -> dict[str, object]:
+ """Ask for the topology as `user` and return its `control_access`."""
+ control_access_record = (await _topology(hass, hass_ws_client, user, device_id))[
+ "control_access"
+ ]
+ assert isinstance(control_access_record, dict)
+ return control_access_record
async def _gate_refusal(hass: HomeAssistant, entry: MockConfigEntry, user: MockUser) -> str | None:
@@ -161,37 +218,163 @@ async def _gate_refusal(hass: HomeAssistant, entry: MockConfigEntry, user: MockU
return None
-def test_every_mode_has_an_expected_answer_for_both_kinds_of_user() -> None:
- """A mode added later has to be given its answers here before the card can rely on them."""
- assert set(EXPECTED_REASON) == {
- (mode, is_admin) for mode in ControlMode for is_admin in (True, False)
- }
+async def _core_refuses_control(hass: HomeAssistant, user: MockUser, entity_id: str) -> bool:
+ """Whether Core refuses `user` a `switch.turn_on` of `entity_id` for want of control permission.
+
+ The switch is only registered, never added, so a call Core lets through
+ reaches no entity and does nothing: what is asked is Core's permission
+ check, which comes first.
+ """
+ try:
+ await hass.services.async_call(
+ "switch",
+ "turn_on",
+ {"entity_id": entity_id},
+ blocking=True,
+ context=Context(user_id=user.id),
+ )
+ except Unauthorized:
+ return True
+ return False
+
+
+# ---------------------------------------------------------------------------
+# What the topology answers
+# ---------------------------------------------------------------------------
+
+
+def test_every_mode_has_an_expected_answer_for_every_group() -> None:
+ """A mode or group added later has to be given its answers here before the card can rely on them."""
+ assert set(EXPECTED_REASON) == {(mode, group) for mode in ControlMode for group in _GROUPS}
@pytest.mark.parametrize("mode", list(ControlMode))
async def test_the_topology_says_whether_the_asker_may_operate_the_panel(
- hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mode: ControlMode, asker: MockUser
+ hass: HomeAssistant,
+ hass_ws_client: WebSocketGenerator,
+ mode: ControlMode,
+ asker: tuple[str, MockUser],
) -> None:
- """`may_operate` is true exactly where `reason` is null, and `reason` is the mode's answer for the asker."""
- _, device_id = await _load_panel(hass, mode)
+ """`may_operate` is true exactly where `reason` is null, and `reason` is the first refusal that applies."""
+ group, user = asker
+ _, device_id, _ = await _load_panel(hass, mode)
+
+ reason = EXPECTED_REASON[(mode, group)]
+ assert await _control_access(hass, hass_ws_client, user, device_id) == {
+ "may_operate": reason is None,
+ "reason": reason,
+ }
- control_access = await _control_access(hass, hass_ws_client, asker, device_id)
- reason = EXPECTED_REASON[(mode, asker.is_admin)]
- assert control_access == {"may_operate": reason is None, "reason": reason}
+async def test_a_panel_offering_no_circuit_control_reports_no_permission_refusal(
+ hass: HomeAssistant, hass_ws_client: WebSocketGenerator
+) -> None:
+ """With no relay switch or priority select there is nothing to disable, and nothing for Core to refuse."""
+ group = await hass.auth.async_get_group(GROUP_ID_READ_ONLY)
+ assert group is not None
+ user = MockUser(groups=[group]).add_to_hass(hass)
+ _, device_id, _ = await _load_panel(hass, ControlMode.ALL_USERS, with_controls=False)
+
+ assert await _control_access(hass, hass_ws_client, user, device_id) == {
+ "may_operate": True,
+ "reason": None,
+ }
+
+
+# ---------------------------------------------------------------------------
+# The topology and the rules it reports
+# ---------------------------------------------------------------------------
@pytest.mark.parametrize("mode", list(ControlMode))
async def test_the_topology_and_the_gate_give_the_asker_the_same_answer(
- hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mode: ControlMode, asker: MockUser
+ hass: HomeAssistant,
+ hass_ws_client: WebSocketGenerator,
+ mode: ControlMode,
+ asker: tuple[str, MockUser],
) -> None:
- """The gate refuses the asker's command exactly where the topology says they may not operate the panel, and for the reason it gives."""
- entry, device_id = await _load_panel(hass, mode)
+ """The gate refuses the asker's command exactly where the topology reports one of its reasons, and for that reason."""
+ _, user = asker
+ entry, device_id, _ = await _load_panel(hass, mode)
- control_access = await _control_access(hass, hass_ws_client, asker, device_id)
- refusal = await _gate_refusal(hass, entry, asker)
+ control_access_record = await _control_access(hass, hass_ws_client, user, device_id)
+ refusal = await _gate_refusal(hass, entry, user)
- assert control_access["may_operate"] is (refusal is None)
- reason = control_access["reason"]
+ reason = control_access_record["reason"]
assert reason is None or isinstance(reason, str)
assert GATE_REFUSAL[reason] == refusal
+
+
+async def test_the_topology_reports_read_only_exactly_where_core_refuses_control(
+ hass: HomeAssistant, hass_ws_client: WebSocketGenerator, asker: tuple[str, MockUser]
+) -> None:
+ """Core refuses the asker the panel's relay switch exactly where the topology says `read_only`.
+
+ Under All users, where the mode refuses no one, so the permissions are the
+ whole answer.
+ """
+ _, user = asker
+ assert await async_setup_component(hass, "switch", {})
+ _, device_id, controls = await _load_panel(hass, ControlMode.ALL_USERS)
+ topology = await _topology(hass, hass_ws_client, user, device_id)
+ circuit = topology["circuits"]
+ assert isinstance(circuit, dict)
+ switch = circuit[_CIRCUIT_ID]["entities"]["switch"]
+ assert switch in controls
+
+ control_access_record = topology["control_access"]
+ assert isinstance(control_access_record, dict)
+ assert (control_access_record["reason"] == "read_only") is await _core_refuses_control(
+ hass, user, switch
+ )
+
+
+# ---------------------------------------------------------------------------
+# The rule, directly
+# ---------------------------------------------------------------------------
+
+
+_ALL_USERS: Final = replace(ControlPolicy.default(), mode=ControlMode.ALL_USERS)
+_SWITCH: Final = "switch.synthetic_circuit_breaker"
+_SELECT: Final = "select.synthetic_circuit_priority"
+
+
+def test_a_user_who_may_control_some_circuit_controls_may_operate_the_panel() -> None:
+ """One flag for the whole panel: a user who can operate something is not told they can operate nothing."""
+ user = MockUser()
+ user.mock_policy({"entities": {"entity_ids": {_SWITCH: True}}})
+
+ assert control_access(_ALL_USERS, user, [_SWITCH, _SELECT]) == {
+ "may_operate": True,
+ "reason": None,
+ }
+
+
+def test_a_user_who_may_read_but_not_control_them_is_read_only() -> None:
+ """Reading a control is not operating it."""
+ user = MockUser()
+ user.mock_policy({"entities": {"entity_ids": {_SWITCH: {"read": True}}}})
+
+ assert control_access(_ALL_USERS, user, [_SWITCH, _SELECT]) == {
+ "may_operate": False,
+ "reason": PermissionRefusal.READ_ONLY,
+ }
+
+
+@pytest.mark.parametrize("mode", list(ControlMode))
+def test_an_administrator_is_never_read_only(mode: ControlMode) -> None:
+ """Core does not check an administrator's permissions at all, so neither does this.
+
+ The administrator here holds a policy that would refuse anyone else, which
+ is what shows the check is skipped rather than passed.
+ """
+ user = MockUser(is_owner=True)
+ user.mock_policy({"entities": {"entity_ids": {_SWITCH: {"read": True}}}})
+ policy = replace(ControlPolicy.default(), mode=mode)
+
+ reason = control_access(policy, user, [_SWITCH, _SELECT])["reason"]
+
+ assert reason is not PermissionRefusal.READ_ONLY
+ assert reason is (
+ ControlAccessRefusal.CONTROL_DISABLED if mode is ControlMode.DISABLED else None
+ )
diff --git a/tests/test_websocket_admin_rule.py b/tests/test_websocket_admin_rule.py
index 2765cbe2..ce34a932 100644
--- a/tests/test_websocket_admin_rule.py
+++ b/tests/test_websocket_admin_rule.py
@@ -80,7 +80,7 @@
}
"""The keys of an open command's answer that describe the user asking, and so differ by user.
-`control_access` is the control policy's answer for that user; see
+`control_access` says whether that user may operate the panel; see
`test_topology_control_access.py`. Everything else an open command answers is
the same for every user.
"""
From 65ebb3dbc5b3ebbd017e0555b2831aa633c7c4ce Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 10:52:02 -0800
Subject: [PATCH 05/15] docs(websocket-api): document read_only and the panel's
breaker position range
control_access gains its third reason, with the order the reasons are reported in and what read_only is checked against. first_position and last_position, which the topology already sends, are named in the example and the top-level table, with what they cover.
---
websocket-api.md | 42 +++++++++++++++++++++++++++++++-----------
1 file changed, 31 insertions(+), 11 deletions(-)
diff --git a/websocket-api.md b/websocket-api.md
index 541c5146..0a53ca07 100644
--- a/websocket-api.md
+++ b/websocket-api.md
@@ -17,8 +17,8 @@ provides all of these relationships explicitly, keyed by circuit UUID, so the ca
Any logged-in user may call it, administrator or not, so the sidebar dashboard and the card work for whoever is viewing them. It carries the panel's layout,
what the panel publishes about each circuit and device, the ratings current monitoring judges each circuit against, and the registry IDs that tie them together;
no host, credential or certificate is in it. Whether a switch or select it names can be operated is decided when it is used, by
-[Who may operate the panel](README.md#restricting-who-can-operate-the-panel). `control_access` reports that option's answer for the user asking, so a card can
-disable the controls that user would be refused.
+[Who may operate the panel](README.md#restricting-who-can-operate-the-panel) and by the user's own Home Assistant permissions. `control_access` reports their
+answer for the user asking, so a card can disable the controls that user would be refused.
### Request
@@ -45,6 +45,8 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID.
"serial": "sim-main32-0001",
"firmware": "spanos3/r202639/03",
"panel_size": 32,
+ "first_position": 1,
+ "last_position": 32,
"device_id": "abc123def456",
"panel_device_id": "abc123def456",
"config_entry_id": "e5f6a7b8c9d0",
@@ -209,6 +211,8 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID.
| `serial` | string | Panel serial number |
| `firmware` | string | Panel firmware version |
| `panel_size` | int or null | Total breaker spaces (e.g., 32, 40) |
+| `first_position` | int or null | The panel's first breaker position (see below) |
+| `last_position` | int or null | The panel's last breaker position (see below) |
| `device_id` | string | HA device registry ID (echoed from request) |
| `panel_device_id` | string | The panel's current HA device registry ID |
| `config_entry_id` | string | The config entry that owns the panel |
@@ -219,18 +223,34 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID.
| `shared_meter_groups` | object | Each group of circuits that share a meter, keyed by the group key its members carry in `shared_meter_group` (see below); empty where no meter is shared |
| `sub_devices` | object | HA device ID keyed map of BESS/MID/EVSE/PV (see below) |
+`first_position` and `last_position` say which breaker positions the panel has, occupied or not: the reported model's range where the integration knows the
+model, otherwise the lowest and highest occupied spaces, and null where neither is known. `circuits` lists only the circuits that are there, so a position in
+the range with no circuit is an empty space.
+
#### Control Access Object
-| Field | Type | Description |
-| ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `may_operate` | bool | Whether **Who may operate the panel** lets the user asking operate the panel's controls |
-| `reason` | string/null | Why not: `control_disabled` where the option is `Nobody`, `admin_only` where it is `Administrators only` and the user is not an administrator; null where `may_operate` is true |
+| Field | Type | Description |
+| ------------- | ----------- | ------------------------------------------------------------------------------------------------------ |
+| `may_operate` | bool | Whether the user asking may operate the panel's relay and priority controls |
+| `reason` | string/null | Why not: `control_disabled`, `admin_only` or `read_only` (see below); null where `may_operate` is true |
+
+`reason` is the first of these that applies:
+
+| Reason | Meaning |
+| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `control_disabled` | **Who may operate the panel** is `Nobody`, so no one may |
+| `admin_only` | **Who may operate the panel** is `Administrators only` and the user is not an administrator |
+| `read_only` | The user's Home Assistant permissions let them control none of the relay switches and priority selects named in `circuits`, as for a read-only user |
+
+The answer is for the user the WebSocket connection is authenticated as, so two users asking about the same panel can be told different things. The first two
+come from the rule the integration refuses a control command by. `read_only` comes from Home Assistant, which refuses a user without control permission before
+the integration is asked; it is never reported for an administrator, whose permissions Home Assistant does not check, nor for a panel whose circuits name no
+relay switch or priority select. A user who may control some of those controls but not others may operate the panel, and is refused the others one at a time.
-The answer is for the user the WebSocket connection is authenticated as, so two users asking about the same panel can be told different things. It comes from
-the rule the integration refuses a control command by, so a card that disables its relay and priority controls where `may_operate` is false offers no control
-that rule would refuse. It says nothing about the control lock, which can be armed or disarmed while a page is open and which its switch reports, nor about the
-relay debounce. **Allow control without a logged-in user** never applies, because a WebSocket connection always has a logged-in user. Changing **Who may operate
-the panel** reloads the entry, and the topology then answers by the new setting.
+A card that disables its relay and priority controls where `may_operate` is false therefore offers them only to a user who may operate at least one of them. The
+answer says nothing about the control lock, which can be armed or disarmed while a page is open and which its switch reports, nor about the relay debounce.
+**Allow control without a logged-in user** never applies, because a WebSocket connection always has a logged-in user. Changing **Who may operate the panel**
+reloads the entry, and the topology then answers by the new setting.
#### Circuit Object
From 5c7b76a5504309782b0192f2f580aef203a60921 Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 10:54:08 -0800
Subject: [PATCH 06/15] docs: say that the card disables controls for a user
who may not operate the panel
Beside the existing Nobody wording: under Administrators only for anyone but an administrator, and for an account whose Home Assistant permissions do not allow control.
---
README.md | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 8989a1c5..8c577b41 100644
--- a/README.md
+++ b/README.md
@@ -714,7 +714,9 @@ see [Recommended deployment](#recommended-deployment), where network topology an
**Choosing `Nobody` is reversible.** The control entities stop being created and read as unavailable, but their registry entries, names, areas and
customizations are kept, so turning the option back on restores exactly the entities you had. The control lock comes back armed or disarmed as you left it, with
any auto-relock still due at the same moment, and armed if Home Assistant no longer holds its last state. The shipped SPAN Panel card and dashboard offer no
-breaker switch or priority while `Nobody` is chosen, and other dashboards show those entities unavailable.
+breaker switch or priority while `Nobody` is chosen, and other dashboards show those entities unavailable. For a user who may not operate the panel — anyone but
+an administrator while `Administrators only` is chosen, or an account whose Home Assistant permissions do not allow control — the card and dashboard show the
+relay and priority controls disabled.
### The record of what was commanded
From b9c3013c72b11cf30a08841da372c0ea9511bf1b Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 11:13:12 -0800
Subject: [PATCH 07/15] docs(websocket-api): document the topology's
panel_entities
The map is in the response and was named nowhere. It is now in the example and the top-level table, with a table of its roles, when a role is present, and which one stays available while the panel is offline.
---
websocket-api.md | 37 +++++++++++++++++++++++++++++++++++++
1 file changed, 37 insertions(+)
diff --git a/websocket-api.md b/websocket-api.md
index 0a53ca07..e226f0c9 100644
--- a/websocket-api.md
+++ b/websocket-api.md
@@ -51,6 +51,17 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID.
"panel_device_id": "abc123def456",
"config_entry_id": "e5f6a7b8c9d0",
"device_name": "SPAN Panel",
+ "panel_entities": {
+ "current_power": "sensor.span_panel_current_power",
+ "site_power": "sensor.span_panel_site_power",
+ "grid_power": "sensor.span_panel_grid_power",
+ "pv_power": "sensor.span_panel_solar_pv_power",
+ "battery_power": "sensor.span_panel_battery_battery_power",
+ "battery_level": "sensor.span_panel_battery_battery_level",
+ "l1_voltage": "sensor.span_panel_l1_voltage",
+ "l2_voltage": "sensor.span_panel_l2_voltage",
+ "panel_status": "binary_sensor.span_panel_panel_status"
+ },
"monitoring_rating_offered": true,
"control_access": {
"may_operate": true,
@@ -217,6 +228,7 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID.
| `panel_device_id` | string | The panel's current HA device registry ID |
| `config_entry_id` | string | The config entry that owns the panel |
| `device_name` | string | HA device display name |
+| `panel_entities` | object | Role-keyed map of the entity IDs of the panel's own readings and its status (see below) |
| `monitoring_rating_offered` | bool | Whether `set_circuit_package_ratings` takes ratings on this panel: false where the panel publishes each circuit of a multi-load breaker with its own rating |
| `control_access` | object | Whether the user asking may operate the panel, and if not, why (see below) |
| `circuits` | object | Circuit UUID keyed map (see below) |
@@ -227,6 +239,31 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID.
model, otherwise the lowest and highest occupied spaces, and null where neither is known. `circuits` lists only the circuits that are there, so a position in
the range with no circuit is an empty space.
+#### Panel Entity Roles
+
+| Role | Domain | Entity |
+| ----------------------- | ------------- | --------------------- |
+| `current_power` | sensor | Current Power |
+| `site_power` | sensor | Site Power |
+| `grid_power` | sensor | Grid Power |
+| `feedthrough_power` | sensor | Feed Through Power |
+| `pv_power` | sensor | PV Power |
+| `battery_power` | sensor | Battery Power |
+| `battery_level` | sensor | Battery Level |
+| `dsm_state` | sensor | DSM Grid State |
+| `main_breaker_rating` | sensor | Main Breaker Rating |
+| `upstream_l1_current` | sensor | Upstream L1 Current |
+| `upstream_l2_current` | sensor | Upstream L2 Current |
+| `downstream_l1_current` | sensor | Downstream L1 Current |
+| `downstream_l2_current` | sensor | Downstream L2 Current |
+| `l1_voltage` | sensor | L1 Voltage |
+| `l2_voltage` | sensor | L2 Voltage |
+| `panel_status` | binary_sensor | Panel Status |
+
+A role is present while its entity is registered for this panel, enabled or not, and omitted otherwise: a panel without a battery has no `battery_power` or
+`battery_level`. Each value is the entity's current ID, so a renamed entity is still found. `panel_status` stays available while the panel is offline, so a
+consumer can watch it for whether the panel is online.
+
#### Control Access Object
| Field | Type | Description |
From 91bbfa410a10aa205a6960efa38b001b12193d3b Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 11:29:13 -0800
Subject: [PATCH 08/15] refactor(controls): name the mode's refusals
ControlModeRefusal, and the reason both rules give ControlAccessReason
ControlAccessRefusal held only the control mode's two reasons, while read_only, Core's, is PermissionRefusal. The mode's enum is renamed for what it holds, and ControlAccessReason names the union that control_access.reason carries.
A docs test holds the two enums' values disjoint and, together, equal to the reason table in websocket-api.md.
---
.../span_panel/control_access.py | 14 ++++----
custom_components/span_panel/control_gate.py | 12 +++----
tests/test_control_gate.py | 6 ++--
tests/test_docs_agree_with_code.py | 34 +++++++++++++++++++
tests/test_topology_control_access.py | 6 ++--
5 files changed, 53 insertions(+), 19 deletions(-)
diff --git a/custom_components/span_panel/control_access.py b/custom_components/span_panel/control_access.py
index b41a555d..20929309 100644
--- a/custom_components/span_panel/control_access.py
+++ b/custom_components/span_panel/control_access.py
@@ -26,7 +26,7 @@
from homeassistant.auth.permissions.const import POLICY_CONTROL
-from .control_gate import ControlAccessRefusal, ControlPolicy
+from .control_gate import ControlModeRefusal, ControlPolicy
if TYPE_CHECKING:
from homeassistant.auth.models import User
@@ -35,7 +35,7 @@
class PermissionRefusal(StrEnum):
"""Why the user's own Home Assistant permissions keep them from operating the panel.
- A wire value beside `ControlAccessRefusal`'s, in the same
+ A wire value beside `ControlModeRefusal`'s, in the same
`control_access.reason` field. Separate because Core decides it, not the
control mode, and the gate never refuses for it.
"""
@@ -44,6 +44,10 @@ class PermissionRefusal(StrEnum):
"""The user may control none of the panel's circuit controls, as a Read Only user may control nothing."""
+type ControlAccessReason = ControlModeRefusal | PermissionRefusal
+"""Every reason `control_access` can give: the control mode's, then Core's permissions'."""
+
+
class ControlAccessRecord(TypedDict):
"""Whether the user asking may operate the panel, and if not, why.
@@ -55,7 +59,7 @@ class ControlAccessRecord(TypedDict):
"""
may_operate: bool
- reason: ControlAccessRefusal | PermissionRefusal | None
+ reason: ControlAccessReason | None
def control_access(
@@ -77,9 +81,7 @@ def control_access(
offers no circuit control there is nothing to disable and nothing for Core
to refuse, so the permissions are not reported.
"""
- reason: ControlAccessRefusal | PermissionRefusal | None = policy.refusal_for(
- is_admin=user.is_admin
- )
+ reason: ControlAccessReason | None = policy.refusal_for(is_admin=user.is_admin)
if reason is None:
reason = _permission_refusal(user, circuit_controls)
return ControlAccessRecord(may_operate=reason is None, reason=reason)
diff --git a/custom_components/span_panel/control_gate.py b/custom_components/span_panel/control_gate.py
index 02b2536b..f0cf0af2 100644
--- a/custom_components/span_panel/control_gate.py
+++ b/custom_components/span_panel/control_gate.py
@@ -96,7 +96,7 @@ class ControlMode(StrEnum):
"""
-class ControlAccessRefusal(StrEnum):
+class ControlModeRefusal(StrEnum):
"""Why the control mode refuses a caller, judged by who the caller is.
The values are wire values: `span_panel/panel_topology` reports them to the
@@ -188,7 +188,7 @@ def lock_enabled(self) -> bool:
"""
return self.lock_timeout_minutes is not None and self.mode is not ControlMode.DISABLED
- def refusal_for(self, *, is_admin: bool | None) -> ControlAccessRefusal | None:
+ def refusal_for(self, *, is_admin: bool | None) -> ControlModeRefusal | None:
"""Why the control mode refuses this caller, or None where it does not.
The one statement of who the mode lets operate the panel. The gate
@@ -207,9 +207,9 @@ def refusal_for(self, *, is_admin: bool | None) -> ControlAccessRefusal | None:
circuit's last command; the gate asks both itself.
"""
if self.mode is ControlMode.DISABLED:
- return ControlAccessRefusal.CONTROL_DISABLED
+ return ControlModeRefusal.CONTROL_DISABLED
if self.mode is ControlMode.ADMIN_ONLY and is_admin is False:
- return ControlAccessRefusal.ADMIN_ONLY
+ return ControlModeRefusal.ADMIN_ONLY
return None
@classmethod
@@ -438,7 +438,7 @@ async def before_publish(self, command: ControlCommand) -> None:
# this integration grows later, a code path that forgets the helper --
# would otherwise be published by an entry whose owner switched control
# off. That is the promise this module opens with.
- if refusal is ControlAccessRefusal.CONTROL_DISABLED:
+ if refusal is ControlModeRefusal.CONTROL_DISABLED:
self._refuse(
"control_disabled",
"Control of this SPAN panel is switched off in its options. "
@@ -459,7 +459,7 @@ async def before_publish(self, command: ControlCommand) -> None:
parent_id=context.parent_id if context is not None else None,
)
- if refusal is ControlAccessRefusal.ADMIN_ONLY:
+ if refusal is ControlModeRefusal.ADMIN_ONLY:
self._refuse(
"admin_only_control",
"Only a Home Assistant administrator may operate this SPAN panel.",
diff --git a/tests/test_control_gate.py b/tests/test_control_gate.py
index 7fdbab2c..67edda2b 100644
--- a/tests/test_control_gate.py
+++ b/tests/test_control_gate.py
@@ -22,10 +22,10 @@
from custom_components.span_panel.const import DOMAIN, EVENT_CONTROL_COMMAND
from custom_components.span_panel.control_gate import (
CONTROL_CALLER,
- ControlAccessRefusal,
ControlGate,
ControlLock,
ControlMode,
+ ControlModeRefusal,
ControlPolicy,
async_bind_caller,
outcome_is_failure,
@@ -690,11 +690,11 @@ def test_an_entry_with_no_control_options_gets_the_defaults() -> None:
[
(ControlMode.ALL_USERS, None),
(ControlMode.ADMIN_ONLY, None),
- (ControlMode.DISABLED, ControlAccessRefusal.CONTROL_DISABLED),
+ (ControlMode.DISABLED, ControlModeRefusal.CONTROL_DISABLED),
],
)
def test_the_mode_judges_a_caller_with_no_user_only_by_refusing_everyone(
- mode: ControlMode, refusal: ControlAccessRefusal | None
+ mode: ControlMode, refusal: ControlModeRefusal | None
) -> None:
"""`admin_only` has no user to judge; whether such a command goes through is `allow_contextless`'s question."""
policy = replace(ControlPolicy.default(), mode=mode)
diff --git a/tests/test_docs_agree_with_code.py b/tests/test_docs_agree_with_code.py
index 61dba0cc..67238744 100644
--- a/tests/test_docs_agree_with_code.py
+++ b/tests/test_docs_agree_with_code.py
@@ -11,6 +11,7 @@
downgrade is refused across, and states the oldest Home Assistant the release
installs on, which `hacs.json` enforces;
- `AGENTS.md` names the schema library a service is validated with;
+- `websocket-api.md` lists each reason the topology's `control_access` can give;
- the card the integration bundles links to a section of the tandem guide
(`tandems.md`) by the anchor GitHub gives that section's heading.
"""
@@ -22,12 +23,14 @@
import json
from pathlib import Path, PurePosixPath
import re
+from typing import get_args
from urllib.parse import urlsplit
import pytest
import custom_components.span_panel as span_panel
from custom_components.span_panel.const import ENTITY_NAMING_PATTERN
+from custom_components.span_panel.control_access import ControlAccessReason
REPO = Path(__file__).resolve().parent.parent
PACKAGE = Path(span_panel.__file__).resolve().parent
@@ -37,6 +40,7 @@
AGENTS = REPO / "AGENTS.md"
HACS = REPO / "hacs.json"
TANDEM_GUIDE = REPO / "tandems.md"
+WEBSOCKET_API = REPO / "websocket-api.md"
BUNDLED_PANEL = PACKAGE / "frontend" / "dist" / "span-panel.js"
CITED_MODULES = (
@@ -306,6 +310,36 @@ def test_agents_names_the_schema_library_services_import() -> None:
assert f"`{libraries[0]}`" in requirements
+def _documented_control_access_reasons() -> list[str]:
+ """Return the reasons the WebSocket API's reason table lists, in its order."""
+ section = _section(_read(WEBSOCKET_API), "#### Control Access Object")
+ lines = section.splitlines()
+ header = next(index for index, line in enumerate(lines) if line.startswith("| Reason "))
+ reasons: list[str] = []
+ for line in lines[header + 2 :]:
+ if not line.startswith("|"):
+ break
+ cell = line.split("|")[1].strip()
+ assert cell.startswith("`") and cell.endswith("`"), line
+ reasons.append(cell.strip("`"))
+ return reasons
+
+
+def test_the_websocket_api_lists_each_reason_control_access_can_give() -> None:
+ """The reason table names every value `ControlAccessReason` holds, and nothing else.
+
+ The reason is one field fed by two enums, one per rule. Their values must
+ not overlap, or the card could not tell which rule refused, and the table is
+ what the card is written against.
+ """
+ members = [member.value for enum in get_args(ControlAccessReason.__value__) for member in enum]
+ documented = _documented_control_access_reasons()
+ assert documented, "the reason table lists nothing, so this test reads nothing"
+
+ assert len(members) == len(set(members)), members
+ assert sorted(documented) == sorted(members)
+
+
TANDEM_GUIDE_URL = "https://github.com/SpanPanel/span/blob/main/tandems.md#main-32"
"""Where the card's MAIN 32 tandem note links: the tandem guide's MAIN 32 section, on `main`."""
diff --git a/tests/test_topology_control_access.py b/tests/test_topology_control_access.py
index f0d4e6b4..405874d4 100644
--- a/tests/test_topology_control_access.py
+++ b/tests/test_topology_control_access.py
@@ -32,10 +32,10 @@
from custom_components.span_panel.control_access import PermissionRefusal, control_access
from custom_components.span_panel.control_gate import (
CONTROL_CALLER,
- ControlAccessRefusal,
ControlGate,
ControlLock,
ControlMode,
+ ControlModeRefusal,
ControlPolicy,
async_bind_caller,
)
@@ -375,6 +375,4 @@ def test_an_administrator_is_never_read_only(mode: ControlMode) -> None:
reason = control_access(policy, user, [_SWITCH, _SELECT])["reason"]
assert reason is not PermissionRefusal.READ_ONLY
- assert reason is (
- ControlAccessRefusal.CONTROL_DISABLED if mode is ControlMode.DISABLED else None
- )
+ assert reason is (ControlModeRefusal.CONTROL_DISABLED if mode is ControlMode.DISABLED else None)
From 441156c38bfaf0385437d1c1a34975551d96ee99 Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 11:33:01 -0800
Subject: [PATCH 09/15] test(controls): pin the order the gate refuses in
A table of every mode, lock state, contextless option and kind of caller, with the refusal the gate gives a priority command or none. Written out, so moving one check past another changes a row: admin_only ahead of the lock, or disabled behind the lock and contextless checks, each passed the suite before this.
---
tests/test_control_gate.py | 115 +++++++++++++++++++++++++++++++++++++
1 file changed, 115 insertions(+)
diff --git a/tests/test_control_gate.py b/tests/test_control_gate.py
index 67edda2b..ceb0a0e1 100644
--- a/tests/test_control_gate.py
+++ b/tests/test_control_gate.py
@@ -8,8 +8,10 @@
from __future__ import annotations
+from collections.abc import Mapping
from dataclasses import replace
from datetime import timedelta
+from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
from homeassistant.core import Context, Event, HomeAssistant
@@ -546,6 +548,119 @@ async def test_a_disabled_entry_refuses_an_administrator_too(hass: HomeAssistant
assert err.value.translation_key == "control_disabled"
+# ---------- the order the gate refuses in ----------
+
+_NO_USER: Final = "no user"
+_ADMIN: Final = "administrator"
+_NON_ADMIN: Final = "non-admin"
+
+_CONTROL_DISABLED: Final = "control_disabled"
+_LOCKED: Final = "control_locked"
+_CONTEXTLESS: Final = "contextless_control_refused"
+_ADMIN_ONLY: Final = "admin_only_control"
+
+_ALL, _ADMINS, _NOBODY = ControlMode.ALL_USERS, ControlMode.ADMIN_ONLY, ControlMode.DISABLED
+_ARMED, _OPEN = True, False
+_CONTEXTLESS_ALLOWED, _CONTEXTLESS_REFUSED = True, False
+
+GATE_ORDER: Final[Mapping[tuple[ControlMode, bool, bool, str], str | None]] = {
+ # `disabled` comes first, so it is the answer whatever else holds.
+ (_NOBODY, _ARMED, _CONTEXTLESS_ALLOWED, _NO_USER): _CONTROL_DISABLED,
+ (_NOBODY, _ARMED, _CONTEXTLESS_ALLOWED, _ADMIN): _CONTROL_DISABLED,
+ (_NOBODY, _ARMED, _CONTEXTLESS_ALLOWED, _NON_ADMIN): _CONTROL_DISABLED,
+ (_NOBODY, _ARMED, _CONTEXTLESS_REFUSED, _NO_USER): _CONTROL_DISABLED,
+ (_NOBODY, _ARMED, _CONTEXTLESS_REFUSED, _ADMIN): _CONTROL_DISABLED,
+ (_NOBODY, _ARMED, _CONTEXTLESS_REFUSED, _NON_ADMIN): _CONTROL_DISABLED,
+ (_NOBODY, _OPEN, _CONTEXTLESS_ALLOWED, _NO_USER): _CONTROL_DISABLED,
+ (_NOBODY, _OPEN, _CONTEXTLESS_ALLOWED, _ADMIN): _CONTROL_DISABLED,
+ (_NOBODY, _OPEN, _CONTEXTLESS_ALLOWED, _NON_ADMIN): _CONTROL_DISABLED,
+ (_NOBODY, _OPEN, _CONTEXTLESS_REFUSED, _NO_USER): _CONTROL_DISABLED,
+ (_NOBODY, _OPEN, _CONTEXTLESS_REFUSED, _ADMIN): _CONTROL_DISABLED,
+ (_NOBODY, _OPEN, _CONTEXTLESS_REFUSED, _NON_ADMIN): _CONTROL_DISABLED,
+ # Then the lock, which refuses everyone while armed, administrators too.
+ (_ALL, _ARMED, _CONTEXTLESS_ALLOWED, _NO_USER): _LOCKED,
+ (_ALL, _ARMED, _CONTEXTLESS_ALLOWED, _ADMIN): _LOCKED,
+ (_ALL, _ARMED, _CONTEXTLESS_ALLOWED, _NON_ADMIN): _LOCKED,
+ (_ALL, _ARMED, _CONTEXTLESS_REFUSED, _NO_USER): _LOCKED,
+ (_ALL, _ARMED, _CONTEXTLESS_REFUSED, _ADMIN): _LOCKED,
+ (_ALL, _ARMED, _CONTEXTLESS_REFUSED, _NON_ADMIN): _LOCKED,
+ (_ADMINS, _ARMED, _CONTEXTLESS_ALLOWED, _NO_USER): _LOCKED,
+ (_ADMINS, _ARMED, _CONTEXTLESS_ALLOWED, _ADMIN): _LOCKED,
+ (_ADMINS, _ARMED, _CONTEXTLESS_ALLOWED, _NON_ADMIN): _LOCKED,
+ (_ADMINS, _ARMED, _CONTEXTLESS_REFUSED, _NO_USER): _LOCKED,
+ (_ADMINS, _ARMED, _CONTEXTLESS_REFUSED, _ADMIN): _LOCKED,
+ (_ADMINS, _ARMED, _CONTEXTLESS_REFUSED, _NON_ADMIN): _LOCKED,
+ # Then a command with no user, where the option refuses one.
+ (_ALL, _OPEN, _CONTEXTLESS_ALLOWED, _NO_USER): None,
+ (_ALL, _OPEN, _CONTEXTLESS_ALLOWED, _ADMIN): None,
+ (_ALL, _OPEN, _CONTEXTLESS_ALLOWED, _NON_ADMIN): None,
+ (_ALL, _OPEN, _CONTEXTLESS_REFUSED, _NO_USER): _CONTEXTLESS,
+ (_ALL, _OPEN, _CONTEXTLESS_REFUSED, _ADMIN): None,
+ (_ALL, _OPEN, _CONTEXTLESS_REFUSED, _NON_ADMIN): None,
+ # Then `admin_only`, which judges only a caller who has a user.
+ (_ADMINS, _OPEN, _CONTEXTLESS_ALLOWED, _NO_USER): None,
+ (_ADMINS, _OPEN, _CONTEXTLESS_ALLOWED, _ADMIN): None,
+ (_ADMINS, _OPEN, _CONTEXTLESS_ALLOWED, _NON_ADMIN): _ADMIN_ONLY,
+ (_ADMINS, _OPEN, _CONTEXTLESS_REFUSED, _NO_USER): _CONTEXTLESS,
+ (_ADMINS, _OPEN, _CONTEXTLESS_REFUSED, _ADMIN): None,
+ (_ADMINS, _OPEN, _CONTEXTLESS_REFUSED, _NON_ADMIN): _ADMIN_ONLY,
+}
+"""What the gate answers a priority command, by mode, lock, contextless option and caller.
+
+The translation key it refuses with, or None where it lets the command
+through. A priority command, so the relay debounce never comes into it.
+Written out rather than derived, so it states the order the gate checks in --
+`disabled`, the lock, contextless control, `admin_only` -- and moving one
+check past another changes a row.
+"""
+
+
+def _order_id(case: tuple[ControlMode, bool, bool, str]) -> str:
+ mode, armed, allow_contextless, caller = case
+ lock = "armed" if armed else "open"
+ contextless = "contextless allowed" if allow_contextless else "contextless refused"
+ return f"{mode}-{lock}-{contextless}-{caller}"
+
+
+def test_the_order_table_covers_every_case() -> None:
+ """Every mode, lock state, contextless option and kind of caller has a row."""
+ assert set(GATE_ORDER) == {
+ (mode, armed, allow_contextless, caller)
+ for mode in ControlMode
+ for armed in (_ARMED, _OPEN)
+ for allow_contextless in (_CONTEXTLESS_ALLOWED, _CONTEXTLESS_REFUSED)
+ for caller in (_NO_USER, _ADMIN, _NON_ADMIN)
+ }
+
+
+@pytest.mark.parametrize("case", list(GATE_ORDER), ids=[_order_id(case) for case in GATE_ORDER])
+@pytest.mark.asyncio
+async def test_the_gate_refuses_in_its_order(
+ hass: HomeAssistant, case: tuple[ControlMode, bool, bool, str]
+) -> None:
+ """The first check that applies is the refusal, whichever others would also apply."""
+ mode, armed, allow_contextless, caller = case
+ gate = _gate(
+ hass, mode=mode, allow_contextless=allow_contextless, lock=ControlLock(armed=armed)
+ )
+ context = (
+ Context()
+ if caller == _NO_USER
+ else Context(user_id=MockUser(is_owner=caller == _ADMIN).add_to_hass(hass).id)
+ )
+
+ refused: str | None = None
+ token = async_bind_caller(context, "select.span_panel_kitchen_priority")
+ try:
+ await gate.before_publish(PRIORITY)
+ except ServiceValidationError as err:
+ refused = err.translation_key
+ finally:
+ CONTROL_CALLER.reset(token)
+
+ assert refused == GATE_ORDER[case]
+
+
# ---------- the audit ----------
From 12abfcdbf60052132d2d7cc3d58ebade56a086ee Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 11:39:21 -0800
Subject: [PATCH 10/15] test(controls): hold the topology and the gate to the
policy setup gives them
Every other topology test hands the topology and the gate one policy object by construction, so a setup that gave runtime data all_users while the gate enforced admin_only passed the whole suite. That divergence is the bug control_access exists to prevent.
The new test runs the entry's real setup under admin_only, asks the topology as a non-admin and turns a real relay switch on: the topology says admin_only and the gate refuses with admin_only_control. After switching to all_users through the options and the reload it causes, both let the user through.
The lock tests' real-setup harness moves to switch_platform_setup and both use it. Its stand-in client now puts relay commands to the interceptor setup installed, its coordinator holds the real hass and a connected panel, and its rating manager answers as one holding no copy.
---
tests/switch_platform_setup.py | 198 ++++++++++++++++++++++++++
tests/test_control_lock_state.py | 125 +++-------------
tests/test_topology_control_access.py | 76 +++++++++-
3 files changed, 294 insertions(+), 105 deletions(-)
create mode 100644 tests/switch_platform_setup.py
diff --git a/tests/switch_platform_setup.py b/tests/switch_platform_setup.py
new file mode 100644
index 00000000..09135aef
--- /dev/null
+++ b/tests/switch_platform_setup.py
@@ -0,0 +1,198 @@
+"""A v2 entry set up for real, with only the switch platform forwarded.
+
+For tests whose subject is what the entry's own setup builds: the control policy
+it resolves from the options, the gate it installs on the transport, the runtime
+data it hands the platforms and the WebSocket commands, the switch platform it
+forwards, and the reload an options change asks for. Those are all the real
+ones. The transport and the coordinator are stand-ins, because none of that
+reads the panel.
+
+A command a relay switch sends goes through the interceptor setup installed, as
+the library's publish does, so a test can operate a switch through Home
+Assistant and see the real gate decide.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Mapping
+import contextlib
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from homeassistant.const import CONF_HOST, Platform
+from homeassistant.core import HomeAssistant
+from pytest_homeassistant.common import MockConfigEntry
+from span_panel_api import (
+ ControlCommand,
+ ControlInterceptor,
+ PublishOutcome,
+ PublishState,
+ SpanCircuitSnapshot,
+ SpanPanelSnapshot,
+)
+
+from custom_components.span_panel.const import (
+ CONF_API_VERSION,
+ CONF_EBUS_BROKER_HOST,
+ CONF_EBUS_BROKER_PASSWORD,
+ CONF_EBUS_BROKER_PORT,
+ CONF_EBUS_BROKER_USERNAME,
+ CONF_HTTP_PORT,
+ DOMAIN,
+)
+from custom_components.span_panel.control_gate import ControlMode
+from custom_components.span_panel.migrations import (
+ CURRENT_CONFIG_MINOR_VERSION,
+ CURRENT_CONFIG_VERSION,
+)
+from custom_components.span_panel.options import CONTROL_MODE
+from custom_components.span_panel.package_ratings import MonitoringRating
+
+from .factories import SpanPanelSnapshotFactory
+from .helpers import ensure_device_registered_stand_in
+
+
+def v2_entry(*, serial: str, entry_id: str, options: Mapping[str, object]) -> MockConfigEntry:
+ """Build a v2 entry for the panel `serial`, at the current config version, with `options`."""
+ return MockConfigEntry(
+ domain=DOMAIN,
+ data={
+ CONF_API_VERSION: "v2",
+ CONF_HOST: "192.168.1.50",
+ CONF_EBUS_BROKER_HOST: "span-panel.local",
+ CONF_EBUS_BROKER_USERNAME: "mqtt-user",
+ CONF_EBUS_BROKER_PASSWORD: "hunter2-synthetic",
+ CONF_EBUS_BROKER_PORT: 8883,
+ CONF_HTTP_PORT: 80,
+ },
+ options=dict(options),
+ entry_id=entry_id,
+ title="SPAN Panel",
+ unique_id=serial,
+ version=CURRENT_CONFIG_VERSION,
+ minor_version=CURRENT_CONFIG_MINOR_VERSION,
+ )
+
+
+class GatedControls:
+ """The coordinator's client, as far as a relay switch uses it.
+
+ Each command is put to the interceptor setup installed on the transport and
+ recorded in `published` once the interceptor lets it through, which is the
+ part of the library's publish a gate test needs. The library also reports
+ every outcome back to the interceptor; nothing here does, so no audit event
+ fires and no relay debounce window opens.
+ """
+
+ def __init__(self, serial: str) -> None:
+ """Start with no interceptor, as the transport does before setup installs one."""
+ self._serial = serial
+ self.interceptor: ControlInterceptor | None = None
+ self.published: list[ControlCommand] = []
+
+ def install(self, interceptor: ControlInterceptor | None) -> None:
+ """Replace the interceptor, as `set_control_interceptor` on the transport does."""
+ self.interceptor = interceptor
+
+ async def set_circuit_relay(self, circuit_id: str, state: str) -> PublishOutcome:
+ """Put a relay command to the interceptor, and publish it if it is let through."""
+ return await self._publish(
+ ControlCommand(
+ device_id=self._serial,
+ node_id=circuit_id,
+ property_id="relay",
+ value=state,
+ topic=f"ebus/5/{self._serial}/{circuit_id}/switch/relay/set",
+ )
+ )
+
+ async def _publish(self, command: ControlCommand) -> PublishOutcome:
+ assert self.interceptor is not None, "setup installed no interceptor"
+ await self.interceptor.before_publish(command)
+ self.published.append(command)
+ return PublishOutcome(
+ state=PublishState.CONFIRMED, topic=command.topic, value=command.value
+ )
+
+
+def _no_copied_rating(circuit_id: str, snapshot: SpanPanelSnapshot) -> MonitoringRating:
+ """Answer as a package-rating manager holding no copy does: with the panel's own rating."""
+ circuit = snapshot.circuits.get(circuit_id)
+ rating = circuit.breaker_rating_a if circuit is not None else None
+ return MonitoringRating(rating, rating, False, None, None)
+
+
+@contextlib.asynccontextmanager
+async def switch_platform_setup(
+ hass: HomeAssistant,
+ entry: MockConfigEntry,
+ *,
+ circuits: Mapping[str, SpanCircuitSnapshot] | None = None,
+) -> AsyncIterator[MockConfigEntry]:
+ """Add `entry`, set it up for real with only the switch platform forwarded, and unload it after.
+
+ The panel publishes `circuits`, none by default. The stand-in coordinator's
+ client is a `GatedControls` (see `gated_controls`), and its package-rating
+ manager answers as one holding no copied rating, so the topology can be
+ asked of the entry. The WebSocket commands are not registered by setup; a
+ test that sends one registers them itself.
+ """
+ entry.add_to_hass(hass)
+ serial = str(entry.unique_id)
+
+ snapshot = SpanPanelSnapshotFactory.create(serial_number=serial, circuits=dict(circuits or {}))
+ controls = GatedControls(serial)
+ client = MagicMock()
+ client.connect = AsyncMock()
+ client.close = AsyncMock()
+ client.set_control_interceptor = MagicMock(side_effect=controls.install)
+ coordinator = MagicMock()
+ # As the real coordinator is: the panel's device info is built from its
+ # entry, and a circuit entity's id from the registries its `hass` holds.
+ coordinator.hass = hass
+ coordinator.config_entry = entry
+ coordinator.data = snapshot
+ coordinator.client = controls
+ # A connected panel, so its relay switches are available: Core skips an
+ # unavailable entity without an error, and the command would never be sent.
+ coordinator.panel_offline = False
+ coordinator.transport_dead = False
+ coordinator.current_monitor = None
+ coordinator.async_config_entry_first_refresh = AsyncMock()
+ coordinator.package_rating_manager.async_load = AsyncMock()
+ coordinator.package_rating_manager.resolve = MagicMock(side_effect=_no_copied_rating)
+ coordinator.async_setup_streaming = AsyncMock()
+ coordinator.async_shutdown = AsyncMock()
+
+ with (
+ patch("custom_components.span_panel.async_register_commands"),
+ patch("custom_components.span_panel.SpanMqttClient", return_value=client),
+ patch("custom_components.span_panel.SpanPanelCoordinator", return_value=coordinator),
+ patch(
+ "custom_components.span_panel.ensure_device_registered",
+ AsyncMock(side_effect=ensure_device_registered_stand_in),
+ ),
+ patch("custom_components.span_panel.PLATFORMS", [Platform.SWITCH]),
+ ):
+ assert await hass.config_entries.async_setup(entry.entry_id) is True
+ await hass.async_block_till_done()
+ try:
+ yield entry
+ finally:
+ await hass.config_entries.async_unload(entry.entry_id)
+ await hass.async_block_till_done()
+
+
+def gated_controls(entry: MockConfigEntry) -> GatedControls:
+ """Return the stand-in client the loaded `entry`'s relay switches publish through."""
+ controls = entry.runtime_data.coordinator.client
+ assert isinstance(controls, GatedControls)
+ return controls
+
+
+async def set_control_mode(hass: HomeAssistant, entry: MockConfigEntry, mode: ControlMode) -> None:
+ """Change the control mode as an options save does, and let the reload it asks for run."""
+ hass.config_entries.async_update_entry(
+ entry, options={**entry.options, CONTROL_MODE: mode.value}
+ )
+ await hass.async_block_till_done()
+ assert entry.runtime_data.control_policy.mode is mode
diff --git a/tests/test_control_lock_state.py b/tests/test_control_lock_state.py
index e3d33ed2..df341748 100644
--- a/tests/test_control_lock_state.py
+++ b/tests/test_control_lock_state.py
@@ -10,18 +10,15 @@
from __future__ import annotations
-from collections.abc import AsyncIterator, Awaitable, Callable
+from collections.abc import Awaitable, Callable
import contextlib
from datetime import timedelta
-from unittest.mock import AsyncMock, MagicMock, patch
from homeassistant.const import (
ATTR_RESTORED,
- CONF_HOST,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
- Platform,
)
from homeassistant.core import Context, HomeAssistant, State
from homeassistant.helpers import area_registry as ar, entity_registry as er
@@ -34,108 +31,39 @@
mock_restore_cache_with_extra_data,
)
-from custom_components.span_panel.const import (
- CONF_API_VERSION,
- CONF_EBUS_BROKER_HOST,
- CONF_EBUS_BROKER_PASSWORD,
- CONF_EBUS_BROKER_PORT,
- CONF_EBUS_BROKER_USERNAME,
- CONF_HTTP_PORT,
- DOMAIN,
-)
+from custom_components.span_panel.const import DOMAIN
from custom_components.span_panel.control_gate import ControlLock, ControlMode
-from custom_components.span_panel.migrations import (
- CURRENT_CONFIG_MINOR_VERSION,
- CURRENT_CONFIG_VERSION,
-)
from custom_components.span_panel.options import CONTROL_LOCK_TIMEOUT, CONTROL_MODE
from custom_components.span_panel.switch import SpanPanelControlLockSwitch
from .common import async_fire_time_changed
-from .factories import SpanPanelSnapshotFactory
-from .helpers import ensure_device_registered_stand_in, watch_add_and_remove
+from .helpers import watch_add_and_remove
+from .switch_platform_setup import set_control_mode, switch_platform_setup, v2_entry
LOCK_ENTITY = "switch.span_panel_control_lock"
EDITED_LOCK_ENTITY = "switch.panel_control_lock"
SERIAL = "sp3-lock-001"
-def _entry(timeout: float, mode: ControlMode | None) -> MockConfigEntry:
- """Build a v2 entry with the control-lock feature configured to `timeout`.
-
- `mode` None leaves the control mode unset, as most entries have it.
+def _panel(
+ hass: HomeAssistant, *, timeout: float, mode: ControlMode | None = None
+) -> contextlib.AbstractAsyncContextManager[MockConfigEntry]:
+ """Set up, for real, an entry with the control-lock feature configured to `timeout`.
+
+ `mode` None leaves the control mode unset, as most entries have it. The
+ transport and the coordinator are stubs -- neither has anything to do with
+ the lock -- but the entry setup, the platform forward, the entity registry
+ and the unload path are all the real ones, because a reload is exactly
+ those four things. See `switch_platform_setup`.
"""
options: dict[str, object] = {CONTROL_LOCK_TIMEOUT: timeout}
if mode is not None:
options[CONTROL_MODE] = mode.value
- return MockConfigEntry(
- domain=DOMAIN,
- data={
- CONF_API_VERSION: "v2",
- CONF_HOST: "192.168.1.50",
- CONF_EBUS_BROKER_HOST: "span-panel.local",
- CONF_EBUS_BROKER_USERNAME: "mqtt-user",
- CONF_EBUS_BROKER_PASSWORD: "hunter2-synthetic",
- CONF_EBUS_BROKER_PORT: 8883,
- CONF_HTTP_PORT: 80,
- },
- options=options,
- entry_id="entry-control-lock",
- title="SPAN Panel",
- unique_id=SERIAL,
- version=CURRENT_CONFIG_VERSION,
- minor_version=CURRENT_CONFIG_MINOR_VERSION,
+ return switch_platform_setup(
+ hass, v2_entry(serial=SERIAL, entry_id="entry-control-lock", options=options)
)
-@contextlib.asynccontextmanager
-async def _panel(
- hass: HomeAssistant, *, timeout: float, mode: ControlMode | None = None
-) -> AsyncIterator[MockConfigEntry]:
- """Set the entry up for real, with only the switch platform forwarded.
-
- The transport and the coordinator are stubs -- neither has anything to do
- with the lock -- but the entry setup, the platform forward, the entity
- registry and the unload path are all the real ones, because a reload is
- exactly those four things.
- """
- entry = _entry(timeout, mode)
- entry.add_to_hass(hass)
-
- snapshot = SpanPanelSnapshotFactory.create(serial_number=SERIAL, circuits={})
- client = MagicMock()
- client.connect = AsyncMock()
- client.close = AsyncMock()
- coordinator = MagicMock()
- # As the real coordinator is: the panel's device info is built from it.
- coordinator.config_entry = entry
- coordinator.data = snapshot
- coordinator.transport_dead = False
- coordinator.current_monitor = None
- coordinator.async_config_entry_first_refresh = AsyncMock()
- coordinator.package_rating_manager.async_load = AsyncMock()
- coordinator.async_setup_streaming = AsyncMock()
- coordinator.async_shutdown = AsyncMock()
-
- with (
- patch("custom_components.span_panel.async_register_commands"),
- patch("custom_components.span_panel.SpanMqttClient", return_value=client),
- patch("custom_components.span_panel.SpanPanelCoordinator", return_value=coordinator),
- patch(
- "custom_components.span_panel.ensure_device_registered",
- AsyncMock(side_effect=ensure_device_registered_stand_in),
- ),
- patch("custom_components.span_panel.PLATFORMS", [Platform.SWITCH]),
- ):
- assert await hass.config_entries.async_setup(entry.entry_id) is True
- await hass.async_block_till_done()
- try:
- yield entry
- finally:
- await hass.config_entries.async_unload(entry.entry_id)
- await hass.async_block_till_done()
-
-
def _lock(entry: MockConfigEntry) -> ControlLock:
"""Return the live lock object this entry's gate consults."""
lock = entry.runtime_data.control_lock
@@ -158,9 +86,7 @@ async def _reload(hass: HomeAssistant, entry: MockConfigEntry) -> None:
async def _arm(hass: HomeAssistant) -> None:
"""Arm through the service, so the entity writes its own state."""
- await hass.services.async_call(
- "switch", "turn_on", {"entity_id": LOCK_ENTITY}, blocking=True
- )
+ await hass.services.async_call("switch", "turn_on", {"entity_id": LOCK_ENTITY}, blocking=True)
async def _disarm(hass: HomeAssistant) -> None:
@@ -446,15 +372,6 @@ async def test_the_lock_stays_operable_when_the_transport_dies(hass: HomeAssista
# ---------- while control is disabled ----------
-async def _set_mode(hass: HomeAssistant, entry: MockConfigEntry, mode: ControlMode) -> None:
- """Change the control mode as an options save does, and let the reload it asks for run."""
- hass.config_entries.async_update_entry(
- entry, options={**entry.options, CONTROL_MODE: mode.value}
- )
- await hass.async_block_till_done()
- assert entry.runtime_data.control_policy.mode is mode
-
-
def _registry_row(hass: HomeAssistant) -> er.RegistryEntry:
row = er.async_get(hass).async_get(LOCK_ENTITY)
assert row is not None
@@ -475,7 +392,7 @@ async def test_disabling_control_stops_creating_the_lock_switch_and_keeps_its_re
async with _panel(hass, timeout=0, mode=ControlMode.ALL_USERS) as entry:
before = _registry_row(hass)
- await _set_mode(hass, entry, ControlMode.DISABLED)
+ await set_control_mode(hass, entry, ControlMode.DISABLED)
after = _registry_row(hass)
assert (after.id, after.entity_id, after.unique_id) == (
@@ -520,8 +437,8 @@ async def test_turning_control_back_on_brings_the_same_lock_switch_back_as_it_wa
er.async_get(hass).async_update_entity(LOCK_ENTITY, name="Breaker lock", area_id=garage.id)
before = _registry_row(hass)
- await _set_mode(hass, entry, ControlMode.DISABLED)
- await _set_mode(hass, entry, ControlMode.ALL_USERS)
+ await set_control_mode(hass, entry, ControlMode.DISABLED)
+ await set_control_mode(hass, entry, ControlMode.ALL_USERS)
after = _registry_row(hass)
assert (after.id, after.entity_id, after.unique_id, after.name, after.area_id) == (
@@ -583,7 +500,7 @@ async def test_a_restart_while_control_is_disabled_keeps_the_lock_state_for_late
async with _panel(hass, timeout=0, mode=ControlMode.DISABLED) as entry:
assert _lock(entry).armed is False
- await _set_mode(hass, entry, ControlMode.ALL_USERS)
+ await set_control_mode(hass, entry, ControlMode.ALL_USERS)
assert _lock(entry).armed is False
restored = hass.states.get(LOCK_ENTITY)
diff --git a/tests/test_topology_control_access.py b/tests/test_topology_control_access.py
index 405874d4..7556b9b6 100644
--- a/tests/test_topology_control_access.py
+++ b/tests/test_topology_control_access.py
@@ -7,7 +7,8 @@
the panel's controls for a user it says may not operate them, so what it says
must not come apart from what either rule does: two tests here run the rule
itself -- the gate, and a service call through Core -- beside the topology and
-hold them to one answer.
+hold them to one answer. A third runs the entry's own setup, so a setup that
+handed the topology one policy and the gate another would fail it.
"""
from __future__ import annotations
@@ -41,12 +42,19 @@
)
from custom_components.span_panel.curation import CurationOverlay
from custom_components.span_panel.id_builder import build_select_unique_id, build_switch_unique_id
+from custom_components.span_panel.options import CONTROL_MODE
from custom_components.span_panel.package_rating_manager import PackageRatingManager
from custom_components.span_panel.runtime import SpanPanelRuntimeData
from custom_components.span_panel.websocket import async_register_commands
from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory, pv_binding_for
from .helpers import register_panel_device
+from .switch_platform_setup import (
+ gated_controls,
+ set_control_mode,
+ switch_platform_setup,
+ v2_entry,
+)
_SERIAL: Final = "sp3-synthetic-access-001"
_CIRCUIT_ID: Final = "circuit-3"
@@ -329,6 +337,72 @@ async def test_the_topology_reports_read_only_exactly_where_core_refuses_control
)
+# ---------------------------------------------------------------------------
+# Through the entry's own setup
+# ---------------------------------------------------------------------------
+
+_SETUP_SERIAL: Final = "sp3-synthetic-access-002"
+
+
+async def _turn_on(hass: HomeAssistant, user: MockUser, entity_id: str) -> None:
+ """Turn `entity_id` on as `user`, through Home Assistant's service call."""
+ await hass.services.async_call(
+ "switch",
+ "turn_on",
+ {"entity_id": entity_id},
+ blocking=True,
+ context=Context(user_id=user.id),
+ )
+
+
+async def test_setup_gives_the_topology_the_policy_its_gate_enforces(
+ hass: HomeAssistant, hass_ws_client: WebSocketGenerator
+) -> None:
+ """A non-admin is told what the gate then does to their relay command, before and after an options change.
+
+ Everything else here hands the topology and the gate one policy object by
+ construction, so it cannot see setup give them different ones -- which is
+ the bug the topology exists to prevent: the card offering a toggle the gate
+ refuses. This runs the entry's real setup, a real `switch.turn_on` on a relay
+ switch the real platform created, the real gate, and the reload an options
+ change causes.
+ """
+ group = await hass.auth.async_get_group(GROUP_ID_USER)
+ assert group is not None
+ user = MockUser(groups=[group]).add_to_hass(hass)
+ entry = v2_entry(
+ serial=_SETUP_SERIAL,
+ entry_id="entry-control-access",
+ options={CONTROL_MODE: ControlMode.ADMIN_ONLY.value},
+ )
+ circuit = SpanCircuitSnapshotFactory.create(
+ circuit_id=_CIRCUIT_ID, name="Synthetic Circuit", tabs=[3], is_user_controllable=True
+ )
+
+ async with switch_platform_setup(hass, entry, circuits={_CIRCUIT_ID: circuit}):
+ async_register_commands(hass)
+ device_id = entry.runtime_data.panel_device_id
+ topology = await _topology(hass, hass_ws_client, user, device_id)
+ circuits = topology["circuits"]
+ assert isinstance(circuits, dict)
+ relay = circuits[_CIRCUIT_ID]["entities"]["switch"]
+
+ assert topology["control_access"] == {"may_operate": False, "reason": "admin_only"}
+ with pytest.raises(ServiceValidationError) as refused:
+ await _turn_on(hass, user, relay)
+ assert refused.value.translation_key == "admin_only_control"
+ assert gated_controls(entry).published == []
+
+ await set_control_mode(hass, entry, ControlMode.ALL_USERS)
+
+ assert await _control_access(hass, hass_ws_client, user, device_id) == {
+ "may_operate": True,
+ "reason": None,
+ }
+ await _turn_on(hass, user, relay)
+ assert [command.node_id for command in gated_controls(entry).published] == [_CIRCUIT_ID]
+
+
# ---------------------------------------------------------------------------
# The rule, directly
# ---------------------------------------------------------------------------
From 301d1827387a072f2c56ba14b64a2e59f941f8e9 Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 11:42:14 -0800
Subject: [PATCH 11/15] test(websocket): hold read_only to Core's refusal of
the priority select too, and of a custom policy
The Core-agreement test asked only switch.turn_on of the relay switch. It now asks select.select_option of the priority select as well. A group whose policy allows control of the relay alone may operate the panel, and Core refuses that group the priority select.
---
tests/test_topology_control_access.py | 60 +++++++++++++++++++++------
1 file changed, 48 insertions(+), 12 deletions(-)
diff --git a/tests/test_topology_control_access.py b/tests/test_topology_control_access.py
index 7556b9b6..22911170 100644
--- a/tests/test_topology_control_access.py
+++ b/tests/test_topology_control_access.py
@@ -19,6 +19,7 @@
from unittest.mock import AsyncMock, MagicMock
from homeassistant.auth.const import GROUP_ID_ADMIN, GROUP_ID_READ_ONLY, GROUP_ID_USER
+from homeassistant.auth.models import Group
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import Context, HomeAssistant
from homeassistant.exceptions import ServiceValidationError, Unauthorized
@@ -227,17 +228,22 @@ async def _gate_refusal(hass: HomeAssistant, entry: MockConfigEntry, user: MockU
async def _core_refuses_control(hass: HomeAssistant, user: MockUser, entity_id: str) -> bool:
- """Whether Core refuses `user` a `switch.turn_on` of `entity_id` for want of control permission.
+ """Whether Core refuses `user` control of `entity_id` for want of control permission.
- The switch is only registered, never added, so a call Core lets through
- reaches no entity and does nothing: what is asked is Core's permission
- check, which comes first.
+ A relay switch is asked `switch.turn_on` and a priority select
+ `select.select_option`, the calls the card makes. The entity is only
+ registered, never added, so a call Core lets through reaches no entity and
+ does nothing: what is asked is Core's permission check, which comes first.
"""
+ domain = entity_id.split(".", 1)[0]
+ service, data = (
+ ("select_option", {"option": "OFF_GRID"}) if domain == "select" else ("turn_on", {})
+ )
try:
await hass.services.async_call(
- "switch",
- "turn_on",
- {"entity_id": entity_id},
+ domain,
+ service,
+ {"entity_id": entity_id, **data},
blocking=True,
context=Context(user_id=user.id),
)
@@ -316,25 +322,55 @@ async def test_the_topology_and_the_gate_give_the_asker_the_same_answer(
async def test_the_topology_reports_read_only_exactly_where_core_refuses_control(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, asker: tuple[str, MockUser]
) -> None:
- """Core refuses the asker the panel's relay switch exactly where the topology says `read_only`.
+ """Core refuses the asker the panel's relay switch and priority select exactly where the topology says `read_only`.
Under All users, where the mode refuses no one, so the permissions are the
whole answer.
"""
_, user = asker
assert await async_setup_component(hass, "switch", {})
+ assert await async_setup_component(hass, "select", {})
_, device_id, controls = await _load_panel(hass, ControlMode.ALL_USERS)
topology = await _topology(hass, hass_ws_client, user, device_id)
circuit = topology["circuits"]
assert isinstance(circuit, dict)
- switch = circuit[_CIRCUIT_ID]["entities"]["switch"]
- assert switch in controls
+ entities = circuit[_CIRCUIT_ID]["entities"]
+ offered = [entities["switch"], entities["select"]]
+ assert offered == controls
control_access_record = topology["control_access"]
assert isinstance(control_access_record, dict)
- assert (control_access_record["reason"] == "read_only") is await _core_refuses_control(
- hass, user, switch
+ read_only = control_access_record["reason"] == "read_only"
+ assert [await _core_refuses_control(hass, user, entity_id) for entity_id in offered] == [
+ read_only,
+ read_only,
+ ]
+
+
+async def test_a_policy_that_allows_one_relay_may_operate_and_is_refused_the_rest(
+ hass: HomeAssistant, hass_ws_client: WebSocketGenerator
+) -> None:
+ """A group whose policy allows control of the relay switch alone: the panel may be operated, the priority select may not.
+
+ The answer is one flag for the panel, so it is true for a user who can
+ control any of its controls, and Core refuses the others one at a time.
+ """
+ assert await async_setup_component(hass, "switch", {})
+ assert await async_setup_component(hass, "select", {})
+ _, device_id, controls = await _load_panel(hass, ControlMode.ALL_USERS)
+ relay, priority = controls
+ relay_only = Group(
+ name="Synthetic relay only", policy={"entities": {"entity_ids": {relay: True}}}
)
+ user = MockUser(groups=[relay_only]).add_to_hass(hass)
+ assert not user.is_admin
+
+ assert await _control_access(hass, hass_ws_client, user, device_id) == {
+ "may_operate": True,
+ "reason": None,
+ }
+ assert await _core_refuses_control(hass, user, relay) is False
+ assert await _core_refuses_control(hass, user, priority) is True
# ---------------------------------------------------------------------------
From 754cef02fd2e9bc8bf98621fc74b0c569162f453 Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 11:44:51 -0800
Subject: [PATCH 12/15] docs(controls): say what keeps the gate and the
topology agreeing, and where Core refuses
refusal_for no longer claims the two cannot disagree; it says they are decided by one rule and which tests hold them to one answer. The gate's ordering comment places admin_only before the relay debounce rather than last, and control_access says Core raises Unauthorized at the first entity a call names that the user may not control.
---
custom_components/span_panel/control_access.py | 11 ++++++-----
custom_components/span_panel/control_gate.py | 9 ++++++---
2 files changed, 12 insertions(+), 8 deletions(-)
diff --git a/custom_components/span_panel/control_access.py b/custom_components/span_panel/control_access.py
index 20929309..6d5a9fea 100644
--- a/custom_components/span_panel/control_access.py
+++ b/custom_components/span_panel/control_access.py
@@ -8,11 +8,12 @@
every command. It comes first, because it is the integration's own answer
and holds for every control the entry has.
- **The user's Home Assistant permissions.** Core refuses an entity service
- call from a user who is not an administrator, with `Unauthorized`, for each
- entity that `user.permissions.check_entity(entity_id, POLICY_CONTROL)` does
- not allow, and administrators are not checked at all (`helpers/service.py`).
- That happens before any entity, and so before the gate, is asked, which is
- why the gate never answers it and this module has to.
+ call from a user who is not an administrator, raising `Unauthorized` at the
+ first entity it names that `user.permissions.check_entity(entity_id,
+ POLICY_CONTROL)` does not allow, and administrators are not checked at all
+ (`helpers/service.py`). That happens before any entity, and so before the
+ gate, is asked, which is why the gate never answers it and this module has
+ to.
`control_access` asks the mode, then the permissions, and reports the first
refusal.
diff --git a/custom_components/span_panel/control_gate.py b/custom_components/span_panel/control_gate.py
index f0cf0af2..19e11141 100644
--- a/custom_components/span_panel/control_gate.py
+++ b/custom_components/span_panel/control_gate.py
@@ -194,7 +194,9 @@ def refusal_for(self, *, is_admin: bool | None) -> ControlModeRefusal | None:
The one statement of who the mode lets operate the panel. The gate
enforces it on every command, and `span_panel/panel_topology` reports it
for whoever is viewing the card, so the controls the card offers and the
- commands the gate lets through cannot come to disagree.
+ commands the gate lets through are decided by one rule rather than two
+ copies of it. `test_topology_control_access.py` runs both, the gate
+ through a real setup too, and holds them to the same answer.
`is_admin` is None for a caller with no logged-in user. `disabled`
refuses that caller as it refuses everyone. `admin_only` does not judge
@@ -428,8 +430,9 @@ async def before_publish(self, command: ControlCommand) -> None:
user_id = context.user_id if context is not None else None
# Judged once, by the rule the topology reports to the card, and acted
- # on below in this method's own order: `disabled` before everything,
- # `admin_only` last.
+ # on below in this method's own order: `disabled` before everything
+ # else, `admin_only` after the lock and contextless checks and before
+ # the relay debounce.
refusal = self._policy.refusal_for(is_admin=await self._caller_is_admin(user_id))
# First, because it is the entry-wide answer and the most useful thing
From 2d3dada5a369f302c10c214fd682823cfc539c15 Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 11:47:46 -0800
Subject: [PATCH 13/15] docs: state the topology's empty spaces, panel roles
and the README's permission case precisely
An empty space is a position in the range that no circuit's tabs include. The panel roles are read from the entity registry, and the battery example says a panel set up without one, which is what was checked. The README's account is one whose permissions allow control of none of the relay and priority controls.
---
README.md | 4 ++--
websocket-api.md | 8 ++++----
2 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/README.md b/README.md
index 8c577b41..98d8c6e4 100644
--- a/README.md
+++ b/README.md
@@ -715,8 +715,8 @@ see [Recommended deployment](#recommended-deployment), where network topology an
customizations are kept, so turning the option back on restores exactly the entities you had. The control lock comes back armed or disarmed as you left it, with
any auto-relock still due at the same moment, and armed if Home Assistant no longer holds its last state. The shipped SPAN Panel card and dashboard offer no
breaker switch or priority while `Nobody` is chosen, and other dashboards show those entities unavailable. For a user who may not operate the panel — anyone but
-an administrator while `Administrators only` is chosen, or an account whose Home Assistant permissions do not allow control — the card and dashboard show the
-relay and priority controls disabled.
+an administrator while `Administrators only` is chosen, or an account whose Home Assistant permissions allow control of none of its relay and priority controls
+— the card and dashboard show those controls disabled.
### The record of what was commanded
diff --git a/websocket-api.md b/websocket-api.md
index e226f0c9..75d93553 100644
--- a/websocket-api.md
+++ b/websocket-api.md
@@ -237,7 +237,7 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID.
`first_position` and `last_position` say which breaker positions the panel has, occupied or not: the reported model's range where the integration knows the
model, otherwise the lowest and highest occupied spaces, and null where neither is known. `circuits` lists only the circuits that are there, so a position in
-the range with no circuit is an empty space.
+the range that no circuit's `tabs` include is an empty space.
#### Panel Entity Roles
@@ -260,9 +260,9 @@ the range with no circuit is an empty space.
| `l2_voltage` | sensor | L2 Voltage |
| `panel_status` | binary_sensor | Panel Status |
-A role is present while its entity is registered for this panel, enabled or not, and omitted otherwise: a panel without a battery has no `battery_power` or
-`battery_level`. Each value is the entity's current ID, so a renamed entity is still found. `panel_status` stays available while the panel is offline, so a
-consumer can watch it for whether the panel is online.
+The roles are read from the entity registry: a role is present while its entity is registered for this panel, enabled or not, and omitted otherwise. A panel set
+up without a battery, for example, has no `battery_power` or `battery_level`. Each value is the entity's current ID, so a renamed entity is still found.
+`panel_status` stays available while the panel is offline, so a consumer can watch it for whether the panel is online.
#### Control Access Object
From 11c775ab05bc6cb7640ba6c46c9de42858aa9d06 Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 11:56:14 -0800
Subject: [PATCH 14/15] docs(websocket-api): say which controls each
control_access reason covers
control_disabled and admin_only hold for every control the integration sends the panel through the gate: circuit relays and priorities, the GFE override, EVSE charge limits and locks, and adopted controls. read_only is judged over the relay switches and priority selects alone, which a consumer other than the card needs to know.
Also renames the gate test for a caller with no user to say plainly what it shows: such a caller is refused only when control is disabled.
---
tests/test_control_gate.py | 2 +-
websocket-api.md | 4 +++-
2 files changed, 4 insertions(+), 2 deletions(-)
diff --git a/tests/test_control_gate.py b/tests/test_control_gate.py
index ceb0a0e1..494da374 100644
--- a/tests/test_control_gate.py
+++ b/tests/test_control_gate.py
@@ -808,7 +808,7 @@ def test_an_entry_with_no_control_options_gets_the_defaults() -> None:
(ControlMode.DISABLED, ControlModeRefusal.CONTROL_DISABLED),
],
)
-def test_the_mode_judges_a_caller_with_no_user_only_by_refusing_everyone(
+def test_a_caller_with_no_user_is_refused_only_when_control_is_disabled(
mode: ControlMode, refusal: ControlModeRefusal | None
) -> None:
"""`admin_only` has no user to judge; whether such a command goes through is `allow_contextless`'s question."""
diff --git a/websocket-api.md b/websocket-api.md
index 75d93553..437a0cc4 100644
--- a/websocket-api.md
+++ b/websocket-api.md
@@ -280,7 +280,9 @@ up without a battery, for example, has no `battery_power` or `battery_level`. Ea
| `read_only` | The user's Home Assistant permissions let them control none of the relay switches and priority selects named in `circuits`, as for a read-only user |
The answer is for the user the WebSocket connection is authenticated as, so two users asking about the same panel can be told different things. The first two
-come from the rule the integration refuses a control command by. `read_only` comes from Home Assistant, which refuses a user without control permission before
+come from the rule the integration refuses a control command by, and hold for every control it sends the panel: circuit relays and priorities, the GFE override,
+EVSE charge limits and locks, and adopted controls. `read_only` is judged over the relay switches and priority selects alone, so for any other control
+`may_operate` true does not say the user's permissions allow it. `read_only` comes from Home Assistant, which refuses a user without control permission before
the integration is asked; it is never reported for an administrator, whose permissions Home Assistant does not check, nor for a panel whose circuits name no
relay switch or priority select. A user who may control some of those controls but not others may operate the panel, and is refused the others one at a time.
From d2e634dae4adc44500677386a46bf91918428f4d Mon Sep 17 00:00:00 2001
From: cayossarian <23534755+cayossarian@users.noreply.github.com>
Date: Wed, 18 Nov 2026 12:01:03 -0800
Subject: [PATCH 15/15] build: bundle the card that disables the controls a
user may not operate
Built from span-card main 8c95a56 (SpanPanel/span-card#44), which reads the topology's control_access.
---
.../frontend/dist/span-panel-card.js | 129 ++++++++++++------
.../span_panel/frontend/dist/span-panel.js | 117 +++++++++++-----
2 files changed, 172 insertions(+), 74 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 422bed1d..4cb6f4c0 100644
--- a/custom_components/span_panel/frontend/dist/span-panel-card.js
+++ b/custom_components/span_panel/frontend/dist/span-panel-card.js
@@ -1,42 +1,42 @@
-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}","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...","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","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.","card.panel_size_error":"Could not determine panel_size. No circuits found and no panel_size attribute. 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}","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...","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","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.","card.panel_size_error":"No se pudo determinar panel_size. No se encontraron circuitos ni atributo panel_size. 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}","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...","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","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.","card.panel_size_error":"Impossible de déterminer panel_size. Aucun circuit trouvé et aucun attribut panel_size. 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}をリセット","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パネルに接続中...","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":"スイッチ有効","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統合を更新してください。","card.panel_size_error":"panel_sizeを判定できません。回路が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}","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...","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","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.","card.panel_size_error":"Não foi possível determinar panel_size. Nenhum circuito encontrado e nenhum atributo panel_size. 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="bess",u="evse",d="pv",h="sub_",p={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)}},f={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:p.power},g={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")}},m=Object.keys(g).filter(t=>"unknown"!==t&&"always_on"!==t);var v=function(t,e){return v=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])},v(t,e)};function y(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}v(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function _(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.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...","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.","card.panel_size_error":"Could not determine panel_size. No circuits found and no panel_size attribute. 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...","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.","card.panel_size_error":"No se pudo determinar panel_size. No se encontraron circuitos ni atributo panel_size. 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...","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.","card.panel_size_error":"Impossible de déterminer panel_size. Aucun circuit trouvé et aucun attribut panel_size. 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パネルに接続中...","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統合を更新してください。","card.panel_size_error":"panel_sizeを判定できません。回路が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...","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.","card.panel_size_error":"Não foi possível determinar panel_size. Nenhum circuito encontrado e nenhum atributo panel_size. 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
* SPDX-License-Identifier: BSD-3-Clause
*/
-const b=globalThis,x=b.ShadowRoot&&(void 0===b.ShadyCSS||b.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,w=Symbol(),S=new WeakMap;let C=class{constructor(t,e,n){if(this._$cssResult$=!0,n!==w)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(x&&void 0===t){const n=void 0!==e&&1===e.length;n&&(t=S.get(e)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&S.set(e,t))}return t}toString(){return this.cssText}};const k=t=>new C("string"==typeof t?t:t+"",void 0,w),M=(t,...e)=>{const n=1===t.length?t[0]:e.reduce((e,n,i)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+t[i+1],t[0]);return new C(n,t,w)},T=x?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const n of t.cssRules)e+=n.cssText;return k(e)})(t):t,{is:A,defineProperty:I,getOwnPropertyDescriptor:D,getOwnPropertyNames:P,getOwnPropertySymbols:L,getPrototypeOf:E}=Object,N=globalThis,R=N.trustedTypes,O=R?R.emptyScript:"",z=N.reactiveElementPolyfillSupport,H=(t,e)=>t,B={toAttribute(t,e){switch(e){case Boolean:t=t?O:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let n=t;switch(e){case Boolean:n=null!==t;break;case Number:n=null===t?null:Number(t);break;case Object:case Array:try{n=JSON.parse(t)}catch(t){n=null}}return n}},$=(t,e)=>!A(t,e),F={attribute:!0,type:String,converter:B,reflect:!1,useDefault:!1,hasChanged:$};
+const k=globalThis,M=k.ShadowRoot&&(void 0===k.ShadyCSS||k.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,T=Symbol(),A=new WeakMap;let I=class{constructor(t,e,n){if(this._$cssResult$=!0,n!==T)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(M&&void 0===t){const n=void 0!==e&&1===e.length;n&&(t=A.get(e)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&A.set(e,t))}return t}toString(){return this.cssText}};const D=t=>new I("string"==typeof t?t:t+"",void 0,T),P=(t,...e)=>{const n=1===t.length?t[0]:e.reduce((e,n,i)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+t[i+1],t[0]);return new I(n,t,T)},L=M?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const n of t.cssRules)e+=n.cssText;return D(e)})(t):t,{is:E,defineProperty:N,getOwnPropertyDescriptor:R,getOwnPropertyNames:O,getOwnPropertySymbols:z,getPrototypeOf:H}=Object,B=globalThis,$=B.trustedTypes,F=$?$.emptyScript:"",V=B.reactiveElementPolyfillSupport,W=(t,e)=>t,j={toAttribute(t,e){switch(e){case Boolean:t=t?F:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let n=t;switch(e){case Boolean:n=null!==t;break;case Number:n=null===t?null:Number(t);break;case Object:case Array:try{n=JSON.parse(t)}catch(t){n=null}}return n}},q=(t,e)=>!E(t,e),U={attribute:!0,type:String,converter:j,reflect:!1,useDefault:!1,hasChanged:q};
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
- */Symbol.metadata??=Symbol("metadata"),N.litPropertyMetadata??=new WeakMap;let V=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=F){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const n=Symbol(),i=this.getPropertyDescriptor(t,n,e);void 0!==i&&I(this.prototype,t,i)}}static getPropertyDescriptor(t,e,n){const{get:i,set:r}=D(this.prototype,t)??{get(){return this[e]},set(t){this[e]=t}};return{get:i,set(e){const o=i?.call(this);r?.call(this,e),this.requestUpdate(t,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??F}static _$Ei(){if(this.hasOwnProperty(H("elementProperties")))return;const t=E(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(H("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(H("properties"))){const t=this.properties,e=[...P(t),...L(t)];for(const n of e)this.createProperty(n,t[n])}const t=this[Symbol.metadata];if(null!==t){const e=litPropertyMetadata.get(t);if(void 0!==e)for(const[t,n]of e)this.elementProperties.set(t,n)}this._$Eh=new Map;for(const[t,e]of this.elementProperties){const n=this._$Eu(t,e);void 0!==n&&this._$Eh.set(n,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const n=new Set(t.flat(1/0).reverse());for(const t of n)e.unshift(T(t))}else void 0!==t&&e.push(T(t));return e}static _$Eu(t,e){const n=e.attribute;return!1===n?void 0:"string"==typeof n?n:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const n of e.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((t,e)=>{if(x)t.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const n of e){const e=document.createElement("style"),i=b.litNonce;void 0!==i&&e.setAttribute("nonce",i),e.textContent=n.cssText,t.appendChild(e)}})(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,n){this._$AK(t,n)}_$ET(t,e){const n=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,n);if(void 0!==i&&!0===n.reflect){const r=(void 0!==n.converter?.toAttribute?n.converter:B).toAttribute(e,n.type);this._$Em=t,null==r?this.removeAttribute(i):this.setAttribute(i,r),this._$Em=null}}_$AK(t,e){const n=this.constructor,i=n._$Eh.get(t);if(void 0!==i&&this._$Em!==i){const t=n.getPropertyOptions(i),r="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:B;this._$Em=i;const o=r.fromAttribute(e,t.type);this[i]=o??this._$Ej?.get(i)??o,this._$Em=null}}requestUpdate(t,e,n,i=!1,r){if(void 0!==t){const o=this.constructor;if(!1===i&&(r=this[t]),n??=o.getPropertyOptions(t),!((n.hasChanged??$)(r,e)||n.useDefault&&n.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,n))))return;this.C(t,e,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,e,{useDefault:n,reflect:i,wrapped:r},o){n&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??e??this[t]),!0!==r||void 0!==o)||(this._$AL.has(t)||(this.hasUpdated||n||(e=void 0),this._$AL.set(t,e)),!0===i&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,e]of this._$Ep)this[t]=e;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[e,n]of t){const{wrapped:t}=n,i=this[e];!0!==t||this._$AL.has(e)||void 0===i||this.C(e,void 0,n,i)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw t=!1,this._$EM(),e}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}};V.elementStyles=[],V.shadowRootOptions={mode:"open"},V[H("elementProperties")]=new Map,V[H("finalized")]=new Map,z?.({ReactiveElement:V}),(N.reactiveElementVersions??=[]).push("2.1.2");
+ */Symbol.metadata??=Symbol("metadata"),B.litPropertyMetadata??=new WeakMap;let G=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=U){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const n=Symbol(),i=this.getPropertyDescriptor(t,n,e);void 0!==i&&N(this.prototype,t,i)}}static getPropertyDescriptor(t,e,n){const{get:i,set:r}=R(this.prototype,t)??{get(){return this[e]},set(t){this[e]=t}};return{get:i,set(e){const o=i?.call(this);r?.call(this,e),this.requestUpdate(t,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??U}static _$Ei(){if(this.hasOwnProperty(W("elementProperties")))return;const t=H(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(W("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(W("properties"))){const t=this.properties,e=[...O(t),...z(t)];for(const n of e)this.createProperty(n,t[n])}const t=this[Symbol.metadata];if(null!==t){const e=litPropertyMetadata.get(t);if(void 0!==e)for(const[t,n]of e)this.elementProperties.set(t,n)}this._$Eh=new Map;for(const[t,e]of this.elementProperties){const n=this._$Eu(t,e);void 0!==n&&this._$Eh.set(n,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const n=new Set(t.flat(1/0).reverse());for(const t of n)e.unshift(L(t))}else void 0!==t&&e.push(L(t));return e}static _$Eu(t,e){const n=e.attribute;return!1===n?void 0:"string"==typeof n?n:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const n of e.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((t,e)=>{if(M)t.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const n of e){const e=document.createElement("style"),i=k.litNonce;void 0!==i&&e.setAttribute("nonce",i),e.textContent=n.cssText,t.appendChild(e)}})(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,n){this._$AK(t,n)}_$ET(t,e){const n=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,n);if(void 0!==i&&!0===n.reflect){const r=(void 0!==n.converter?.toAttribute?n.converter:j).toAttribute(e,n.type);this._$Em=t,null==r?this.removeAttribute(i):this.setAttribute(i,r),this._$Em=null}}_$AK(t,e){const n=this.constructor,i=n._$Eh.get(t);if(void 0!==i&&this._$Em!==i){const t=n.getPropertyOptions(i),r="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:j;this._$Em=i;const o=r.fromAttribute(e,t.type);this[i]=o??this._$Ej?.get(i)??o,this._$Em=null}}requestUpdate(t,e,n,i=!1,r){if(void 0!==t){const o=this.constructor;if(!1===i&&(r=this[t]),n??=o.getPropertyOptions(t),!((n.hasChanged??q)(r,e)||n.useDefault&&n.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,n))))return;this.C(t,e,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,e,{useDefault:n,reflect:i,wrapped:r},o){n&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??e??this[t]),!0!==r||void 0!==o)||(this._$AL.has(t)||(this.hasUpdated||n||(e=void 0),this._$AL.set(t,e)),!0===i&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,e]of this._$Ep)this[t]=e;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[e,n]of t){const{wrapped:t}=n,i=this[e];!0!==t||this._$AL.has(e)||void 0===i||this.C(e,void 0,n,i)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw t=!1,this._$EM(),e}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}};G.elementStyles=[],G.shadowRootOptions={mode:"open"},G[W("elementProperties")]=new Map,G[W("finalized")]=new Map,V?.({ReactiveElement:G}),(B.reactiveElementVersions??=[]).push("2.1.2");
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
-const W=globalThis,j=t=>t,q=W.trustedTypes,U=q?q.createPolicy("lit-html",{createHTML:t=>t}):void 0,G="$lit$",X=`lit$${Math.random().toFixed(9).slice(2)}$`,Y="?"+X,Z=`<${Y}>`,K=document,Q=()=>K.createComment(""),J=t=>null===t||"object"!=typeof t&&"function"!=typeof t,tt=Array.isArray,et="[ \t\n\f\r]",nt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,it=/-->/g,rt=/>/g,ot=RegExp(`>|${et}(?:([^\\s"'>=/]+)(${et}*=${et}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),at=/'/g,st=/"/g,lt=/^(?:script|style|textarea|title)$/i,ct=t=>(e,...n)=>({_$litType$:t,strings:e,values:n}),ut=ct(1),dt=ct(2),ht=Symbol.for("lit-noChange"),pt=Symbol.for("lit-nothing"),ft=new WeakMap,gt=K.createTreeWalker(K,129);function mt(t,e){if(!tt(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==U?U.createHTML(e):e}const vt=(t,e)=>{const n=t.length-1,i=[];let r,o=2===e?"":3===e?"":"")),i]};class yt{constructor({strings:t,_$litType$:e},n){let i;this.parts=[];let r=0,o=0;const a=t.length-1,s=this.parts,[l,c]=vt(t,e);if(this.el=yt.createElement(l,n),gt.currentNode=this.el.content,2===e||3===e){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(i=gt.nextNode())&&s.length0){i.textContent=q?q.emptyScript:"";for(let n=0;ntt(t)||"function"==typeof t?.[Symbol.iterator])(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==pt&&J(this._$AH)?this._$AA.nextSibling.data=t:this.T(K.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:n}=t,i="number"==typeof n?this._$AC(t):(void 0===n.el&&(n.el=yt.createElement(mt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===i)this._$AH.p(e);else{const t=new bt(i,this),n=t.u(this.options);t.p(e),this.T(n),this._$AH=t}}_$AC(t){let e=ft.get(t.strings);return void 0===e&&ft.set(t.strings,e=new yt(t)),e}k(t){tt(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let n,i=0;for(const r of t)i===e.length?e.push(n=new xt(this.O(Q()),this.O(Q()),this,this.options)):n=e[i],n._$AI(r),i++;i2||""!==n[0]||""!==n[1]?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=pt}_$AI(t,e=this,n,i){const r=this.strings;let o=!1;if(void 0===r)t=_t(this,t,e,0),o=!J(t)||t!==this._$AH&&t!==ht,o&&(this._$AH=t);else{const i=t;let a,s;for(t=r[0],a=0;at,Z=X.trustedTypes,K=Z?Z.createPolicy("lit-html",{createHTML:t=>t}):void 0,Q="$lit$",J=`lit$${Math.random().toFixed(9).slice(2)}$`,tt="?"+J,et=`<${tt}>`,nt=document,it=()=>nt.createComment(""),rt=t=>null===t||"object"!=typeof t&&"function"!=typeof t,ot=Array.isArray,at="[ \t\n\f\r]",st=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,lt=/-->/g,ct=/>/g,ut=RegExp(`>|${at}(?:([^\\s"'>=/]+)(${at}*=${at}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),dt=/'/g,ht=/"/g,pt=/^(?:script|style|textarea|title)$/i,ft=t=>(e,...n)=>({_$litType$:t,strings:e,values:n}),gt=ft(1),mt=ft(2),vt=Symbol.for("lit-noChange"),yt=Symbol.for("lit-nothing"),_t=new WeakMap,bt=nt.createTreeWalker(nt,129);function xt(t,e){if(!ot(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==K?K.createHTML(e):e}const wt=(t,e)=>{const n=t.length-1,i=[];let r,o=2===e?"":3===e?"":"")),i]};class St{constructor({strings:t,_$litType$:e},n){let i;this.parts=[];let r=0,o=0;const a=t.length-1,s=this.parts,[l,c]=wt(t,e);if(this.el=St.createElement(l,n),bt.currentNode=this.el.content,2===e||3===e){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(i=bt.nextNode())&&s.length0){i.textContent=Z?Z.emptyScript:"";for(let n=0;not(t)||"function"==typeof t?.[Symbol.iterator])(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==yt&&rt(this._$AH)?this._$AA.nextSibling.data=t:this.T(nt.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:n}=t,i="number"==typeof n?this._$AC(t):(void 0===n.el&&(n.el=St.createElement(xt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===i)this._$AH.p(e);else{const t=new kt(i,this),n=t.u(this.options);t.p(e),this.T(n),this._$AH=t}}_$AC(t){let e=_t.get(t.strings);return void 0===e&&_t.set(t.strings,e=new St(t)),e}k(t){ot(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let n,i=0;for(const r of t)i===e.length?e.push(n=new Mt(this.O(it()),this.O(it()),this,this.options)):n=e[i],n._$AI(r),i++;i2||""!==n[0]||""!==n[1]?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=yt}_$AI(t,e=this,n,i){const r=this.strings;let o=!1;if(void 0===r)t=Ct(this,t,e,0),o=!rt(t)||t!==this._$AH&&t!==vt,o&&(this._$AH=t);else{const i=t;let a,s;for(t=r[0],a=0;a{const i=n?.renderBefore??e;let r=i._$litPart$;if(void 0===r){const t=n?.renderBefore??null;i._$litPart$=r=new xt(e.insertBefore(Q(),t),t,void 0,n??{})}return r._$AI(t),r})(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ht}}It._$litElement$=!0,It.finalized=!0,At.litElementHydrateSupport?.({LitElement:It});const Dt=At.litElementPolyfillSupport;Dt?.({LitElement:It}),(At.litElementVersions??=[]).push("4.2.2");
+ */class Nt extends G{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=((t,e,n)=>{const i=n?.renderBefore??e;let r=i._$litPart$;if(void 0===r){const t=n?.renderBefore??null;i._$litPart$=r=new Mt(e.insertBefore(it(),t),t,void 0,n??{})}return r._$AI(t),r})(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return vt}}Nt._$litElement$=!0,Nt.finalized=!0,Et.litElementHydrateSupport?.({LitElement:Nt});const Rt=Et.litElementPolyfillSupport;Rt?.({LitElement:Nt}),(Et.litElementVersions??=[]).push("4.2.2");
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
-const Pt={attribute:!0,type:String,converter:B,reflect:!1,hasChanged:$},Lt=(t=Pt,e,n)=>{const{kind:i,metadata:r}=n;let o=globalThis.litPropertyMetadata.get(r);if(void 0===o&&globalThis.litPropertyMetadata.set(r,o=new Map),"setter"===i&&((t=Object.create(t)).wrapped=!0),o.set(n.name,t),"accessor"===i){const{name:i}=n;return{set(n){const r=e.get.call(this);e.set.call(this,n),this.requestUpdate(i,r,t,!0,n)},init(e){return void 0!==e&&this.C(i,void 0,t,e),e}}}if("setter"===i){const{name:i}=n;return function(n){const r=this[i];e.call(this,n),this.requestUpdate(i,r,t,!0,n)}}throw Error("Unsupported decorator location: "+i)};
+const Ot={attribute:!0,type:String,converter:j,reflect:!1,hasChanged:q},zt=(t=Ot,e,n)=>{const{kind:i,metadata:r}=n;let o=globalThis.litPropertyMetadata.get(r);if(void 0===o&&globalThis.litPropertyMetadata.set(r,o=new Map),"setter"===i&&((t=Object.create(t)).wrapped=!0),o.set(n.name,t),"accessor"===i){const{name:i}=n;return{set(n){const r=e.get.call(this);e.set.call(this,n),this.requestUpdate(i,r,t,!0,n)},init(e){return void 0!==e&&this.C(i,void 0,t,e),e}}}if("setter"===i){const{name:i}=n;return function(n){const r=this[i];e.call(this,n),this.requestUpdate(i,r,t,!0,n)}}throw Error("Unsupported decorator location: "+i)};
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
- */function Et(t){return(e,n)=>"object"==typeof n?Lt(t,e,n):((t,e,n)=>{const i=e.hasOwnProperty(n);return e.constructor.createProperty(n,t),i?Object.getOwnPropertyDescriptor(e,n):void 0})(t,e,n)}
+ */function Ht(t){return(e,n)=>"object"==typeof n?zt(t,e,n):((t,e,n)=>{const i=e.hasOwnProperty(n);return e.constructor.createProperty(n,t),i?Object.getOwnPropertyDescriptor(e,n):void 0})(t,e,n)}
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
- */function Nt(t){return Et({...t,state:!0,attribute:!1})}const Rt={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ot(t){return String(t).replace(/[&<>"']/g,t=>Rt[t]??t)}const zt="span_panel_list_columns";function Ht(){try{const t=localStorage.getItem(zt);if(!t)return 1;const e=parseInt(t,10);return 1===e||2===e||3===e?e:1}catch{return 1}}function Bt(t){try{localStorage.setItem(zt,String(t))}catch{}}function $t(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}const Ft=p.power,Vt=p.current,Wt="--",jt=`${Wt}`;function qt(t){return Ft.unit(t)}function Ut(t){return(t<0?"-":"")+Ft.format(t)}function Gt(t){return null===t?jt:`${Ut(t)}${qt(t)}`}function Xt(t){return null===t?jt:`${Ut(t)}${qt(t)}`}function Yt(t){return null===t?jt:`${Vt.format(t)}A`}function Zt(t,e,n={}){const r=Ot(t.device_name||i("header.default_name")),o=Ot(t.serial||""),a=Ot(t.firmware||""),s="current"===(e.chart_metric||"power"),l=!1!==n.showSwitches;return`\n