Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3675d8087b | ||
|
|
4f3bdde6e5 | ||
|
|
d65735ac47 | ||
|
|
867f4b0ae8 | ||
|
|
9da775a8de | ||
|
|
6ee60beae9 | ||
|
|
fffe923afc | ||
|
|
a6d818dfc0 | ||
|
|
cec3dd4a68 | ||
|
|
5dbe990c1d | ||
|
|
9228da1d9c |
No files matched your search
@@ -95,6 +95,73 @@ Each device has its own **Configure** option in Settings > Devices & Services, u
|
||||
|
||||
- **Allow writes even when remote control is reported off** — by default, LocalThings blocks every write with a clear error whenever a device reports remote control off, rather than letting the device silently reject it. Some devices accept certain writes anyway (e.g. default detergent/softener dosing on a washer) even while reporting remote control off. Only enable this if you've confirmed writes actually work on your device with remote control off — otherwise you trade a clear error for a silent failure.
|
||||
- **Estimated finish -- minimum change (minutes)** — a washer/dryer/dishwasher's `finish_time` sensor is recomputed from the device's own remaining-time estimate on every poll, which commonly drifts or gets revised by a minute or two between updates. This setting holds `finish_time` at its last reported value until a new estimate differs by at least this many minutes, cutting down on Home Assistant history/logbook noise from a value that hasn't meaningfully changed. Defaults to `3`; set it to `0` to report every computed change.
|
||||
- **Remember modes the device reports but doesn't advertise** — some firmware reports a current mode it never lists as supported. Issue #327's air conditioner sits in `Quiet` while offering only `Off/Sleep/Speed/Nano/NanoSleep`, so Home Assistant showed the preset as active but refused to select it. LocalThings remembers any such mode it sees and keeps offering it afterwards, stored on the config entry so it survives a restart — the device only names the mode while it is in it, and you shouldn't have to reach for the physical remote after every reboot. Defaults to on. Turning it off offers only what the device advertises, without discarding what was already learned.
|
||||
|
||||
The same **Configure** menu has a **Forget remembered modes** step, which clears what has been learned for that device. Use it if a mode was learned that turns out not to be selectable — otherwise, by design, it stays forever.
|
||||
|
||||
---
|
||||
|
||||
## Part 5: Reading and writing resources directly
|
||||
|
||||
Two HA actions, `localthings.write_resource` and `localthings.read_resource`, talk to a device's OCF resources directly instead of through this integration's entity model. They exist for two overlapping jobs: pinning down a device-specific write contract (the reverse-engineering work `docs/investigations/` and the provenance comments throughout `registry/capabilities/` are all about), and driving a resource this integration doesn't model as an entity yet, without waiting on a release.
|
||||
|
||||
Both take a `device_id` (a device picker filtered to this integration) and resolve to exactly one appliance — a target that expands to more than one LocalThings device is rejected rather than silently fanned out across all of them. `href` is always canonical (e.g. `/mode/vs/0`); if the device you targeted is a subdevice — an oven's second cavity, an AC's second indoor unit — it's translated to the real on-the-wire href for you (`/mode/vs/1`, say), and the response reports both forms so there's no ambiguity about what was actually sent.
|
||||
|
||||
`write_resource` exists because a single write, one at a time, isn't enough to probe some boards. Issue #300's Samsung wall oven answers `2.04 Changed` to a settings write while idle and then silently reverts it — the write only sticks once a cycle is already running. Finding what actually triggers a cycle needs an *ordered sequence* of writes to different resources, with real delays between them, and a way to check afterward whether anything actually held:
|
||||
|
||||
```yaml
|
||||
action: localthings.write_resource
|
||||
data:
|
||||
device_id: abc123...
|
||||
writes:
|
||||
- href: /mode/vs/0
|
||||
payload:
|
||||
x.com.samsung.da.modes: ["Bake"]
|
||||
settle: 5
|
||||
- href: /operational/state/vs/0
|
||||
payload:
|
||||
x.com.samsung.da.state: "Run"
|
||||
verify_after: 30
|
||||
```
|
||||
|
||||
Mind the shapes: what you write is sent verbatim, so the field names and types have to be the ones that resource actually uses. `/mode/vs/0` takes `modes` as an *array* on this board; a bare string, or the singular `mode`, is a different field the device will simply ignore. `read_resource` (below) with no `href` is the quickest way to see the real shape of everything before you write to any of it.
|
||||
|
||||
Each write in `writes` (1-10 of them) needs `href` and a non-empty `payload`, sent verbatim as a partial-rep POST — this bypasses the remote-control-off block and every `write_fn`/`validate_fn` a normal entity write goes through, and sends exactly the fields you give it, so it can misconfigure your appliance if you get it wrong. `settle` (0-30s, default 0) is how long to wait *after* that write before starting the next one.
|
||||
|
||||
By default the whole sequence holds the device session from the first write to the last, settle delays included, so a routine poll or another entity's write can't land between two steps and blur which write the appliance was reacting to. The cost is that nothing else on that device updates until the sequence ends — up to 10 × 30s if you ask for the maximum of both. Set `hold_session_lock: false` to take the session per write and release it across the waits instead, trading that certainty for a device whose entities keep updating throughout.
|
||||
|
||||
The response has one `results` entry per write, with `before`/`after` reps and a `changed` flag (every key/value in `payload` present and equal in the immediate readback):
|
||||
|
||||
```json
|
||||
{
|
||||
"device_id": "abc123...",
|
||||
"results": [
|
||||
{"href": "/mode/vs/0", "actual_href": "/mode/vs/0", "code": "2.04", "raw_code": 68,
|
||||
"accepted": true, "before": {...}, "after": {...}, "changed": true},
|
||||
...
|
||||
],
|
||||
"verified": {
|
||||
"/mode/vs/0": {"code": "2.05", "raw_code": 69, "rep": {...}, "held": false}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`verify_after` (0-60s, default 0, omit to skip) is what actually answers the "did it stick" question: after the sequence finishes, it waits that long and then re-reads every distinct href the sequence touched, reporting the result under `verified`, keyed by canonical href. `changed` tells you the write was accepted and reflected immediately; `held` tells you whether it was still there N seconds later, or whether the board quietly put it back — issue #300's exact symptom. Where an href was written more than once in a sequence, `held` compares against the *last* payload sent to it. A `held` of `null` means the re-read itself didn't come back (check `code` next to it) — unknown, deliberately not reported as a revert.
|
||||
|
||||
If the session drops partway through a sequence, the action raises rather than returning, and the error names how many writes completed and which — the appliance is left holding a partial sequence, so knowing where it stopped is the difference between a usable result and starting over blind.
|
||||
|
||||
`read_resource` is the read half, and it's deliberately not just a cache lookup:
|
||||
|
||||
```yaml
|
||||
action: localthings.read_resource
|
||||
data:
|
||||
device_id: abc123...
|
||||
href: /mode/vs/0
|
||||
```
|
||||
|
||||
returning `{"href", "actual_href", "code", "raw_code", "rep"}` off a **live GET straight from the device**, not the cache — which can be up to a poll interval stale, exactly the staleness that would make `held` above meaningless. Omit `href` and you get `{"resources": {href: rep, ...}}`, the cached snapshot of everything this integration currently tracks on that device, with no GET at all — useful for seeing what's there before you start writing to it, without hammering the appliance.
|
||||
|
||||
The **Debug write** panel under a device's Configure menu (Part 4) is the friendlier single-write path over this same machinery — pick an href, type a payload, see the result — for when you don't need a sequence.
|
||||
|
||||
---
|
||||
|
||||
@@ -135,6 +202,8 @@ custom_components/localthings/
|
||||
coordinator.py Polling + push update coordination, stale-state fallback, write dispatch
|
||||
observe.py CoAP OBSERVE (push-mode) support layered on the coordinator
|
||||
diagnostics.py Redacted diagnostics download (device state + coverage metadata)
|
||||
services.py write_resource/read_resource actions (device resolution, href translation)
|
||||
services.yaml Selectors/descriptions for the two services above
|
||||
const.py Domain, config keys, probe ports
|
||||
entity.py Base entity wiring capability registry -> HA entity
|
||||
sensor.py / binary_sensor.py / switch.py / number.py / select.py / button.py / time.py / fan.py / climate.py / water_heater.py
|
||||
@@ -172,6 +241,11 @@ email, access tokens, device IDs, MAC addresses, serial numbers) before it's gen
|
||||
directly to a new issue using the linked device-support template. This is the fastest way to help add or expand
|
||||
support for hardware the maintainers don't have.
|
||||
|
||||
When a diagnostics dump alone isn't enough to pin down how a resource actually behaves — whether a write sticks,
|
||||
what order things need to happen in, whether the device reverts a change on its own — the `localthings.write_resource`
|
||||
and `localthings.read_resource` actions from Part 5 are the tool for probing it directly and reporting back what
|
||||
you found.
|
||||
|
||||
---
|
||||
|
||||
## Adding a new appliance type
|
||||
|
||||
@@ -10,14 +10,23 @@ from homeassistant.core import Event, HomeAssistant, callback
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
|
||||
from .const import CONF_HOST, CONF_PORT, CONF_SERIAL, DOMAIN, PLATFORMS
|
||||
from .coordinator import LocalThingsCoordinator
|
||||
from .registry.identity import resolve_serial
|
||||
from .services import async_setup_services
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
# Services are process-global, registered once here rather than per
|
||||
# config entry (issue #300) -- see services.async_setup_services.
|
||||
async_setup_services(hass)
|
||||
return True
|
||||
|
||||
|
||||
def _serial_from_unique_id(entry: ConfigEntry) -> str:
|
||||
"""The device identity a pre-v2 entry was created with.
|
||||
|
||||
|
||||
@@ -448,7 +448,16 @@ class LocalThingsClimate(LocalThingsEntity, ClimateEntity):
|
||||
return bool(self._rep(POWER_HREF).get("value"))
|
||||
|
||||
def _supported(self, href: str) -> list[str]:
|
||||
return list(self._rep(href).get(_SUPPORTED_FIELD) or [])
|
||||
"""The resource's own supportedModes, plus any code this unit has
|
||||
been seen in but never advertised (issue #327, learned.py).
|
||||
|
||||
Both the option lists (preset_modes, fan_modes, ...) and the write
|
||||
paths resolve codes through here, so a learned code is selectable
|
||||
and writable by virtue of appearing in one list.
|
||||
"""
|
||||
supported = list(self._rep(href).get(_SUPPORTED_FIELD) or [])
|
||||
learned = self.coordinator.learned_modes(self._bound.subdevice.to_actual(href))
|
||||
return supported + [code for code in learned if code not in supported]
|
||||
|
||||
def _warn_unmapped(self, href: str, code: str) -> None:
|
||||
"""Log once per (href, code) when a device-reported mode has no
|
||||
|
||||
@@ -20,6 +20,7 @@ import voluptuous as vol
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.config_entries import ConfigFlowResult
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
from homeassistant.helpers.selector import (
|
||||
NumberSelector,
|
||||
NumberSelectorConfig,
|
||||
@@ -44,18 +45,23 @@ from .const import (
|
||||
CONF_HOST,
|
||||
CONF_LEAF_CERT_PEM,
|
||||
CONF_LEAF_KEY_PEM,
|
||||
CONF_LEARN_MODES,
|
||||
CONF_MANUFACTURER,
|
||||
CONF_MODEL,
|
||||
CONF_PORT,
|
||||
CONF_SERIAL,
|
||||
DEFAULT_FINISH_TIME_HYSTERESIS_MINUTES,
|
||||
DEFAULT_LEARN_MODES,
|
||||
DOMAIN,
|
||||
LIVENESS_PROBE_TIMEOUT_S,
|
||||
PREFERRED_PROBE_PORTS,
|
||||
PROBE_GET_TIMEOUT_S,
|
||||
PROBE_MAX_WORKERS,
|
||||
PROBE_PORT_RANGE,
|
||||
SERVICE_WRITE_RESOURCE,
|
||||
)
|
||||
from .learned import persist as learned_persist
|
||||
from .learned import stored as learned_stored
|
||||
|
||||
_TEXT = TextSelector(TextSelectorConfig(type=TextSelectorType.TEXT))
|
||||
_MULTILINE = TextSelector(TextSelectorConfig(type=TextSelectorType.TEXT, multiline=True))
|
||||
@@ -828,7 +834,7 @@ class LocalThingsOptionsFlow(config_entries.OptionsFlow):
|
||||
async def async_step_init(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
|
||||
return self.async_show_menu(
|
||||
step_id="init",
|
||||
menu_options=["settings", "debug_write"],
|
||||
menu_options=["settings", "forget_learned_modes", "debug_write"],
|
||||
)
|
||||
|
||||
async def async_step_settings(
|
||||
@@ -852,10 +858,49 @@ class LocalThingsOptionsFlow(config_entries.OptionsFlow):
|
||||
DEFAULT_FINISH_TIME_HYSTERESIS_MINUTES,
|
||||
),
|
||||
): _HYSTERESIS_MINUTES,
|
||||
vol.Required(
|
||||
CONF_LEARN_MODES,
|
||||
default=self.config_entry.options.get(
|
||||
CONF_LEARN_MODES, DEFAULT_LEARN_MODES
|
||||
),
|
||||
): bool,
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
async def async_step_forget_learned_modes(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Confirm-and-clear for the learned-mode store (issue #327).
|
||||
|
||||
The point of learning is that it's permanent, so a code learned
|
||||
from a one-off firmware hiccup would otherwise sit in an option
|
||||
list forever. An empty schema renders as a plain confirmation
|
||||
form; the description lists what's about to be forgotten.
|
||||
"""
|
||||
coord = self._coordinator()
|
||||
# learned.py owns the entry key and the persisted shape, so this
|
||||
# step never parses or writes it itself -- including on an unloaded
|
||||
# entry, where a malformed record would otherwise abort the one
|
||||
# screen that can clear it.
|
||||
learned = (
|
||||
coord.learned_snapshot() if coord is not None else learned_stored(self.config_entry)
|
||||
)
|
||||
codes = sorted({code for codes in learned.values() for code in codes})
|
||||
|
||||
if user_input is not None:
|
||||
if coord is not None:
|
||||
coord.forget_learned_modes()
|
||||
else:
|
||||
learned_persist(self.hass, self.config_entry, {})
|
||||
return self.async_create_entry(data=dict(self.config_entry.options))
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="forget_learned_modes",
|
||||
data_schema=vol.Schema({}),
|
||||
description_placeholders={"codes": ", ".join(codes) if codes else "(none)"},
|
||||
)
|
||||
|
||||
async def async_step_debug_write(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
@@ -925,8 +970,33 @@ class LocalThingsOptionsFlow(config_entries.OptionsFlow):
|
||||
return self._show_debug_edit_form(
|
||||
href, current, {"payload": "empty_payload"}, payload
|
||||
)
|
||||
# Goes through the write_resource service (issue #300), not
|
||||
# coord.async_raw_write directly, so there is exactly one code
|
||||
# path that performs a raw write. MAIN's own device -- the
|
||||
# panel's href dropdown already lists actual hrefs off
|
||||
# coord.last_resources, and MAIN.to_actual is identity, so
|
||||
# this preserves the panel's existing behavior byte for byte.
|
||||
dev = dr.async_get(self.hass).async_get_device(
|
||||
identifiers=coord.device_info["identifiers"]
|
||||
)
|
||||
if dev is None:
|
||||
return self.async_abort(reason="not_loaded")
|
||||
try:
|
||||
code, new_rep = await coord.async_raw_write(href, payload)
|
||||
response = await self.hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_WRITE_RESOURCE,
|
||||
{"writes": [{"href": href, "payload": payload}]},
|
||||
target={"device_id": dev.id},
|
||||
blocking=True,
|
||||
return_response=True,
|
||||
)
|
||||
results = (response or {}).get("results")
|
||||
first = results[0] if isinstance(results, list) and results else None
|
||||
raw_code = first.get("raw_code") if isinstance(first, dict) else None
|
||||
after = first.get("after") if isinstance(first, dict) else None
|
||||
if not isinstance(raw_code, int) or not isinstance(after, dict):
|
||||
raise RuntimeError("write_resource service returned an unexpected shape")
|
||||
code, new_rep = raw_code, after
|
||||
except Exception:
|
||||
_LOGGER.exception("debug raw write failed for %s", href)
|
||||
return self._show_debug_edit_form(href, current, {"base": "write_failed"}, payload)
|
||||
|
||||
@@ -34,6 +34,20 @@ CONF_MODEL = "model"
|
||||
CONF_MANUFACTURER = "manufacturer"
|
||||
CONF_DEVICE_TYPE = "device_type"
|
||||
|
||||
# entry.data key: modes this device reported itself in but never advertised
|
||||
# in the same resource's supportedModes (issue #327). Stored on the entry
|
||||
# rather than kept in memory so a mode the device only names while it is
|
||||
# active survives a restart -- see learned.py. Shape:
|
||||
# {actual_href: [code, ...]}.
|
||||
CONF_LEARNED_MODES = "learned_modes"
|
||||
|
||||
# Options-flow key: whether learned modes are remembered and offered.
|
||||
# Defaults to on; turning it off stops both halves at once (nothing new is
|
||||
# learned, nothing already learned is offered) without discarding what was
|
||||
# already remembered -- the options flow's reset step does that.
|
||||
CONF_LEARN_MODES = "learn_device_modes"
|
||||
DEFAULT_LEARN_MODES = True
|
||||
|
||||
# Options-flow key (entry.options, not entry.data): lets a user override
|
||||
# the device-wide remote-control-off write block for a specific device
|
||||
# (issue #54). Some devices accept certain writes even while reporting
|
||||
@@ -96,3 +110,9 @@ SUMMARY_INTERVAL_S = 30.0
|
||||
DEVICE_SUPPORT_ISSUE_URL = (
|
||||
"https://github.com/mbillow/localthings/issues/new?template=device-support.yml"
|
||||
)
|
||||
|
||||
# Service names (services.py), shared with config_flow.py so the
|
||||
# options-flow debug panel calls the exact same service a user could call
|
||||
# from an automation (issue #300) -- one code path performs a raw write.
|
||||
SERVICE_WRITE_RESOURCE = "write_resource"
|
||||
SERVICE_READ_RESOURCE = "read_resource"
|
||||
@@ -28,15 +28,19 @@ from .const import (
|
||||
CONF_HOST,
|
||||
CONF_LEAF_CERT_PEM,
|
||||
CONF_LEAF_KEY_PEM,
|
||||
CONF_LEARN_MODES,
|
||||
CONF_LEARNED_MODES,
|
||||
CONF_MANUFACTURER,
|
||||
CONF_MODEL,
|
||||
CONF_PORT,
|
||||
CONF_SERIAL,
|
||||
DEFAULT_LEARN_MODES,
|
||||
DEVICE_SUPPORT_ISSUE_URL,
|
||||
DOMAIN,
|
||||
DTLS_LOCAL_PORT_BASE,
|
||||
SUMMARY_INTERVAL_S,
|
||||
)
|
||||
from .learned import LEARNABLE, LearnedModes, persist
|
||||
from .observe import GRACE_PERIOD_S, MODE_OBSERVE, MODE_POLL, ObserveManager
|
||||
from .registry import CAPABILITIES
|
||||
from .registry.adapter import flatten
|
||||
@@ -49,6 +53,7 @@ from .registry.capabilities.common import (
|
||||
remote_control_required_for_write,
|
||||
)
|
||||
from .registry.discovery import BoundEntity
|
||||
from .registry.entities import ClimateDesc
|
||||
from .registry.identity import (
|
||||
DeviceIdentity,
|
||||
device_display_name,
|
||||
@@ -100,6 +105,68 @@ def _local_source_port(host: str) -> int:
|
||||
return DTLS_LOCAL_PORT_BASE + offset
|
||||
|
||||
|
||||
# Debug raw write/read caps (issue #300) -- generous enough for a real
|
||||
# probing session (the wall-oven reporter's own sequences run well under
|
||||
# 10 steps) while bounding how long one service call can hold up polling.
|
||||
_DEBUG_MAX_WRITES = 10
|
||||
_DEBUG_MAX_SETTLE_S = 30.0
|
||||
_DEBUG_MAX_VERIFY_AFTER_S = 60.0
|
||||
|
||||
|
||||
def _href_to_path_segs(href: str) -> list[str]:
|
||||
"""'/mode/vs/0' -> ['mode', 'vs', '0'], the shape `sess.get`/`sess.post`
|
||||
take. Shared by every raw debug read/write path."""
|
||||
return [s for s in str(href).strip("/").split("/") if s]
|
||||
|
||||
|
||||
def normalize_href(href: str) -> str:
|
||||
"""A user-typed href in one canonical spelling. Public because
|
||||
services.py must normalize before `Subdevice.to_actual`, which rewrites
|
||||
only a trailing '0' segment: '/mode/vs/0/' slips through it unchanged
|
||||
and would land on the master's resource, not the subdevice's."""
|
||||
return "/" + "/".join(_href_to_path_segs(href))
|
||||
|
||||
|
||||
def _coap_code_str(code: int) -> str:
|
||||
"""Raw CoAP response code -> its 'C.DD' rendering (e.g. 0x44 -> '2.04'),
|
||||
the class/detail split RFC 7252 §12.1.2 defines. `raw_code` is kept
|
||||
alongside it in every debug response so a caller can format it
|
||||
differently."""
|
||||
return f"{code >> 5}.{code & 0x1F:02d}"
|
||||
|
||||
|
||||
def _coap_accepted(code: int) -> bool:
|
||||
"""True for a 2.xx class CoAP response."""
|
||||
return (code >> 5) == 2
|
||||
|
||||
|
||||
def _validate_debug_write_item(item: dict) -> tuple[list[str], str, dict, float]:
|
||||
"""The checks `async_raw_write` has always applied to a single write
|
||||
(issue #54), reused per-item by `async_raw_write_sequence` (issue
|
||||
#300). Payload is checked before href, matching the original
|
||||
single-write order -- not load-bearing for any test, just avoiding a
|
||||
silent behavior change in the refactor."""
|
||||
payload = item.get("payload")
|
||||
if not isinstance(payload, dict) or not payload:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="debug_payload_empty",
|
||||
)
|
||||
path_segs = _href_to_path_segs(item.get("href", ""))
|
||||
if not path_segs:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="resource_href_required",
|
||||
)
|
||||
settle = item.get("settle") or 0.0
|
||||
if not 0 <= settle <= _DEBUG_MAX_SETTLE_S:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="debug_settle_out_of_range",
|
||||
)
|
||||
return path_segs, "/" + "/".join(path_segs), payload, settle
|
||||
|
||||
|
||||
class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
"""Manages one Samsung appliance: session, discovery, polling."""
|
||||
|
||||
@@ -177,6 +244,14 @@ class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
self._cache = StateCache(_NoOpDescriptor())
|
||||
self._cache.set_on_change(self._on_cache_changed)
|
||||
self._observe = ObserveManager(self._cache, logger=self._log)
|
||||
# Modes this device reported itself in but never advertised as
|
||||
# supported (issue #327), restored from the entry so one learned
|
||||
# last week is still offered today. See learned.py.
|
||||
self._learned = LearnedModes(entry.data.get(CONF_LEARNED_MODES))
|
||||
# Narrowed to this device's own climate hrefs once discovery has
|
||||
# run -- see _refresh_learnable_hrefs.
|
||||
self._learnable_hrefs: set[str] = set()
|
||||
self._observe.set_on_applied(self._on_rep_applied)
|
||||
self._push_pending = False
|
||||
self._push_pending_lock = threading.Lock()
|
||||
# Identity is resolved once by the config flow's probe (issue #236).
|
||||
@@ -243,6 +318,83 @@ class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
self._canonical_cache[view_key] = view
|
||||
return view
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Learned modes (issue #327)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def learning_enabled(self) -> bool:
|
||||
return bool(self._entry.options.get(CONF_LEARN_MODES, DEFAULT_LEARN_MODES))
|
||||
|
||||
def learned_modes(self, actual_href: str) -> list[str]:
|
||||
"""Codes learned for `actual_href`, or [] while the option is off.
|
||||
|
||||
Gating the read here rather than only the write is what makes the
|
||||
option a single switch: turning it off restores stock behavior
|
||||
immediately, without also throwing away what was already learned
|
||||
(the options flow's reset step is for that)."""
|
||||
if not self.learning_enabled:
|
||||
return []
|
||||
return self._learned.codes(actual_href)
|
||||
|
||||
def learned_snapshot(self) -> dict[str, list[str]]:
|
||||
"""Everything learned, option state ignored -- for diagnostics and
|
||||
the options flow, both of which need to show what is remembered
|
||||
even when it isn't currently being offered."""
|
||||
return self._learned.snapshot()
|
||||
|
||||
def forget_learned_modes(self) -> None:
|
||||
"""Drop every learned mode, here and on the entry.
|
||||
|
||||
Persists even when the in-memory store was already empty: a record
|
||||
_coerce rejected at startup exists only on the entry, and this is
|
||||
the one control that can clear it."""
|
||||
self._learned.clear()
|
||||
if self._entry.data.get(CONF_LEARNED_MODES):
|
||||
self._persist_learned()
|
||||
|
||||
def _refresh_learnable_hrefs(self) -> None:
|
||||
"""The actual hrefs learning applies to on this device: LEARNABLE's
|
||||
canonical set, narrowed to the ones a climate entity is bound to
|
||||
read back (climate._supported is the only consumer) and translated
|
||||
through that entity's own subdevice (issue #177).
|
||||
|
||||
The href alone isn't a sufficient key here. `/mode/convenient/vs/0`
|
||||
is also declared by the dehumidifier registry (explicitly
|
||||
unmodeled) and the air purifier's (empty), so a global match would
|
||||
persist a code for a resource that family will never offer.
|
||||
"""
|
||||
self._learnable_hrefs = {
|
||||
bound.subdevice.to_actual(href)
|
||||
for bound in self.bound
|
||||
if isinstance(bound.desc, ClimateDesc)
|
||||
for href in LEARNABLE
|
||||
}
|
||||
|
||||
def _on_rep_applied(self, href: str, rep: dict, source: str) -> None:
|
||||
"""ObserveManager.set_on_applied hook. Runs on whichever thread
|
||||
applied the update, so the persist goes through hass.add_job the
|
||||
same way _on_cache_changed marshals its state push.
|
||||
|
||||
An 'optimistic' rep is the value this integration just wrote, not
|
||||
one the device reported, so there is nothing to learn from it."""
|
||||
if source == "optimistic" or href not in self._learnable_hrefs:
|
||||
return
|
||||
if not self.learning_enabled:
|
||||
return
|
||||
if new := self._learned.observe(href, rep):
|
||||
self._log.info(
|
||||
"%s reported mode(s) it does not advertise as supported; "
|
||||
"remembering %s so they stay selectable (issue #327)",
|
||||
href,
|
||||
new,
|
||||
)
|
||||
self.hass.add_job(self._persist_learned)
|
||||
|
||||
@callback
|
||||
def _persist_learned(self) -> None:
|
||||
persist(self.hass, self._entry, self._learned.snapshot())
|
||||
|
||||
def device_info_for(self, subdevice: Subdevice) -> DeviceInfo:
|
||||
"""DeviceInfo for one logical subdevice on this connection (issue
|
||||
#177): the master's own device_info for MAIN, or a linked child
|
||||
@@ -663,6 +815,7 @@ class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
self.device_type_name = device_type_name
|
||||
self.bound = bound
|
||||
self._unbound_hrefs = unbound
|
||||
self._refresh_learnable_hrefs()
|
||||
|
||||
# The entry's stored identity wins; this poll's answer is only
|
||||
# adopted when nothing is stored (a legacy migration couldn't
|
||||
@@ -1119,10 +1272,12 @@ class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
await self.async_request_refresh()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Debug raw write (issue #54): a power-user escape hatch for the
|
||||
# options-flow debug panel to POST an arbitrary partial body without a
|
||||
# new release. Deliberately bypasses the remote-control block and all
|
||||
# write_fn/validate_fn above -- use with care.
|
||||
# Debug raw write/read (issue #54, extended for issue #300): a
|
||||
# power-user escape hatch shared by the options-flow debug panel and
|
||||
# the write_resource/read_resource services (services.py) for probing
|
||||
# a device's write contract directly. Deliberately bypasses the
|
||||
# remote-control block and all write_fn/validate_fn above -- use with
|
||||
# care.
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _raw_write_blocking(self, path_segs: list[str], body: dict, href: str) -> tuple[int, dict]:
|
||||
@@ -1148,17 +1303,34 @@ class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
self._log.debug("raw write follow-up read failed: %s", e)
|
||||
return code, new_rep
|
||||
|
||||
async def async_raw_write(self, href: str, body: dict) -> tuple[int, dict]:
|
||||
"""Debug-only arbitrary write (issue #54). Bypasses remote-control
|
||||
and write_fn/validate_fn; sends `body` verbatim as a partial-rep
|
||||
PATCH to `href`. Returns (coap_code, new_rep) read back right
|
||||
after."""
|
||||
if not isinstance(body, dict) or not body:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="debug_payload_empty",
|
||||
)
|
||||
path_segs = [s for s in href.strip("/").split("/") if s]
|
||||
def _raw_read_blocking(self, path_segs: list[str], href: str) -> tuple[int, dict]:
|
||||
"""Debug primitive: a live GET, deliberately bypassing the cache
|
||||
(issue #300) -- the cache can be up to a poll interval stale,
|
||||
exactly the staleness that makes testing whether a write held or
|
||||
got silently reverted by the board unreliable. Blocking -- runs in
|
||||
executor."""
|
||||
if self._session is None:
|
||||
self._connect_session()
|
||||
sess = self._session
|
||||
if sess is None:
|
||||
raise RuntimeError("no session")
|
||||
code, payload = sess.get(path_segs, timeout=10.0)
|
||||
rep: dict = {}
|
||||
if code == 0x45 and payload:
|
||||
try:
|
||||
body = cbor2.loads(payload)
|
||||
except Exception as e:
|
||||
self._log.debug("raw read decode failed for %s: %s", href, e)
|
||||
body = None
|
||||
if isinstance(body, dict):
|
||||
self._observe.apply(href, body, source="poll")
|
||||
rep = body
|
||||
return code, rep
|
||||
|
||||
async def async_raw_read(self, href: str) -> tuple[int, dict]:
|
||||
"""Debug-only live GET (issue #300, backs the read_resource
|
||||
service). Same href validation as async_raw_write."""
|
||||
path_segs = _href_to_path_segs(href)
|
||||
if not path_segs:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
@@ -1166,10 +1338,150 @@ class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
)
|
||||
norm_href = "/" + "/".join(path_segs)
|
||||
async with self._session_lock:
|
||||
code, new_rep = await self.hass.async_add_executor_job(
|
||||
self._raw_write_blocking, path_segs, body, norm_href
|
||||
return await self.hass.async_add_executor_job(
|
||||
self._raw_read_blocking, path_segs, norm_href
|
||||
)
|
||||
|
||||
async def async_raw_write_sequence(
|
||||
self,
|
||||
writes: list[dict],
|
||||
*,
|
||||
verify_after: float = 0.0,
|
||||
hold_session_lock: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Debug-only ordered multi-write (issue #300): a Samsung wall oven
|
||||
board discards settings writes while idle and only keeps them once
|
||||
a cycle is already running, which no single-write debug pass can
|
||||
probe for.
|
||||
|
||||
`hold_session_lock` (default) keeps `_session_lock` for the whole
|
||||
sequence, settle waits included, so nothing interleaves between
|
||||
steps and blurs which write the appliance reacted to -- at the cost
|
||||
of blocking polls and entity writes for the sequence's full length
|
||||
(up to 10 x 30s). Pass False to take the lock per write and release
|
||||
it across the waits, for a long sequence where a stalled poll costs
|
||||
more than an interleaved read.
|
||||
|
||||
`writes` are already on-the-wire hrefs: subdevice translation
|
||||
(canonical -> actual) is services.py's job, not this method's --
|
||||
this primitive has no notion of subdevices, same as the original
|
||||
single-write async_raw_write never did.
|
||||
|
||||
`async_raw_write` below delegates here with a one-item sequence, so
|
||||
its signature/return and tests/test_coordinator_raw_write.py stay
|
||||
unchanged.
|
||||
"""
|
||||
if not writes or len(writes) > _DEBUG_MAX_WRITES:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="debug_too_many_writes",
|
||||
)
|
||||
if not 0 <= verify_after <= _DEBUG_MAX_VERIFY_AFTER_S:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="debug_verify_after_out_of_range",
|
||||
)
|
||||
# Validate every item before touching the session -- a rejected
|
||||
# call must fail before any write goes out (same posture the
|
||||
# single-write path has always had; see
|
||||
# test_raw_write_validation_errors_do_not_touch_the_session).
|
||||
parsed = [_validate_debug_write_item(w) for w in writes]
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
last_payload_by_href: dict[str, dict] = {}
|
||||
# Exactly one of these is the real lock, never both -- asyncio.Lock
|
||||
# isn't reentrant, so nesting the same one would deadlock.
|
||||
outer_lock = self._session_lock if hold_session_lock else contextlib.nullcontext()
|
||||
try:
|
||||
async with outer_lock:
|
||||
for i, (path_segs, href, payload, settle) in enumerate(parsed):
|
||||
per_write_lock = (
|
||||
contextlib.nullcontext() if hold_session_lock else self._session_lock
|
||||
)
|
||||
async with per_write_lock:
|
||||
before = self.resource(href)
|
||||
code, after = await self.hass.async_add_executor_job(
|
||||
self._raw_write_blocking, path_segs, payload, href
|
||||
)
|
||||
last_payload_by_href[href] = payload
|
||||
results.append(
|
||||
{
|
||||
"href": href,
|
||||
"code": _coap_code_str(code),
|
||||
"raw_code": code,
|
||||
"accepted": _coap_accepted(code),
|
||||
"before": before,
|
||||
"after": after,
|
||||
"changed": all(after.get(k) == v for k, v in payload.items()),
|
||||
}
|
||||
)
|
||||
# Under the default this wait happens inside the lock, so
|
||||
# nothing lands between two writes to blur which one the
|
||||
# appliance reacted to; see hold_session_lock above.
|
||||
if settle and i < len(parsed) - 1:
|
||||
await asyncio.sleep(settle)
|
||||
except Exception as err:
|
||||
# A drop partway leaves the appliance holding whatever already
|
||||
# landed, so the error has to say which writes got through.
|
||||
done = ", ".join(r["href"] for r in results) or "none"
|
||||
self._log.warning(
|
||||
"raw write sequence failed after %d of %d writes (completed: %s): %s",
|
||||
len(results),
|
||||
len(parsed),
|
||||
done,
|
||||
err,
|
||||
)
|
||||
await self.async_request_refresh()
|
||||
raise HomeAssistantError(
|
||||
f"Raw write sequence failed after {len(results)} of {len(parsed)} writes "
|
||||
f"(completed: {done}). The appliance may be holding a partial sequence."
|
||||
) from err
|
||||
|
||||
response: dict[str, Any] = {"results": results}
|
||||
if verify_after > 0:
|
||||
# Released, not held, across this wait: holding _session_lock
|
||||
# through up to 60s would stall the summary poll for that whole
|
||||
# window (same reasoning as _attempt_observe_mode's grace wait,
|
||||
# issue #294). A poll interleaving here is harmless -- just
|
||||
# another read of the same hrefs.
|
||||
await asyncio.sleep(verify_after)
|
||||
verified: dict[str, Any] = {}
|
||||
async with self._session_lock:
|
||||
for href in dict.fromkeys(r["href"] for r in results):
|
||||
vcode, vrep = await self.hass.async_add_executor_job(
|
||||
self._raw_read_blocking, _href_to_path_segs(href), href
|
||||
)
|
||||
# None, not False, when the re-read brought back nothing
|
||||
# to compare: every comparison against an empty rep is
|
||||
# False, which would report a 4.04 as a revert -- the one
|
||||
# distinction verify_after exists to draw.
|
||||
read_ok = _coap_accepted(vcode) and bool(vrep)
|
||||
verified[href] = {
|
||||
"code": _coap_code_str(vcode),
|
||||
"raw_code": vcode,
|
||||
"rep": vrep,
|
||||
"held": (
|
||||
all(vrep.get(k) == v for k, v in last_payload_by_href[href].items())
|
||||
if read_ok
|
||||
else None
|
||||
),
|
||||
}
|
||||
response["verified"] = verified
|
||||
|
||||
# Hasten a summary poll so entities on other resources catch up
|
||||
# too -- a debug write can affect siblings, not just its href.
|
||||
# too -- a debug write can affect siblings, not just its href. Once
|
||||
# per sequence, not per write: the whole point of ordering writes
|
||||
# under one lock hold is to control exactly what the device sees
|
||||
# and when, which a refresh racing in mid-sequence would undermine.
|
||||
await self.async_request_refresh()
|
||||
return code, new_rep
|
||||
return response
|
||||
|
||||
async def async_raw_write(self, href: str, body: dict) -> tuple[int, dict]:
|
||||
"""Debug-only arbitrary write (issue #54). Bypasses remote-control
|
||||
and write_fn/validate_fn; sends `body` verbatim as a partial-rep
|
||||
PATCH to `href`. Returns (coap_code, new_rep) read back right
|
||||
after -- a thin single-write wrapper over async_raw_write_sequence
|
||||
(issue #300)."""
|
||||
sequence = await self.async_raw_write_sequence([{"href": href, "payload": body}])
|
||||
only = sequence["results"][0]
|
||||
return only["raw_code"], only["after"]
|
||||
@@ -128,6 +128,15 @@ async def async_get_config_entry_diagnostics(
|
||||
# about the connection rather than one subdevice's state, and
|
||||
# nothing polls it after discovery so it would go stale in there.
|
||||
"multidevice": redact_resources(coordinator._multidevice),
|
||||
# Modes this unit reported itself in but never advertised (issue
|
||||
# #327). Reported separately from `resources` on purpose: the dump
|
||||
# above stays exactly what the device said, so a triager can still
|
||||
# see the gap these codes were inferred from. Keyed by actual href,
|
||||
# like the store itself.
|
||||
"learned_modes": {
|
||||
"enabled": coordinator.learning_enabled,
|
||||
"codes": coordinator.learned_snapshot(),
|
||||
},
|
||||
"integration_version": integration.version,
|
||||
"smartthings_local_version": stl_version,
|
||||
"observe_mode": coordinator.observe_mode,
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Modes a device reports itself in but never advertises as supported.
|
||||
|
||||
Some firmwares report a current mode that is missing from the same
|
||||
resource's own supported list (issue #327: an ARTIK051 air conditioner
|
||||
sitting in 'Quiet' with supportedModes [Off, Sleep, Speed, Nano,
|
||||
NanoSleep]). The mode is real -- the remote and the SmartThings app select
|
||||
it, and the unit accepts it written back -- so once the device has been
|
||||
seen in it, it is remembered and offered alongside the advertised ones.
|
||||
|
||||
Learning is deliberately not global. A current value that isn't a
|
||||
selectable option is common across this corpus -- an oven idling in
|
||||
'NoOperation', a fridge's /mode/vs/0 carrying capability tokens like
|
||||
'WATERFILTER_DISABLE' -- and remembering one of those permanently would
|
||||
put an option in the UI that the device can only reject. LEARNABLE names
|
||||
the canonical hrefs where a reported mode is known to be genuinely
|
||||
selectable, and the coordinator narrows it further to the hrefs this
|
||||
device actually binds a climate entity to (see _refresh_learnable_hrefs):
|
||||
the same href is declared explicitly unmodeled on a dehumidifier and
|
||||
empty on an air purifier, and learning for those would persist a code
|
||||
nothing ever offers.
|
||||
|
||||
This module also owns the entry key the store persists under, so the
|
||||
shape lives in exactly one place.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from .const import CONF_LEARNED_MODES
|
||||
from .registry.capabilities.airconditioner import HREF_CONVENIENT
|
||||
|
||||
MODES_FIELD = "x.com.samsung.da.modes"
|
||||
SUPPORTED_FIELD = "x.com.samsung.da.supportedModes"
|
||||
|
||||
# Convenient (preset) mode: firmware omits an active preset (e.g. Quiet)
|
||||
# from its own supportedModes -- a reporting gap, not a capability
|
||||
# difference (issue #327).
|
||||
LEARNABLE: frozenset[str] = frozenset({HREF_CONVENIENT})
|
||||
|
||||
|
||||
def _codes(value) -> list[str]:
|
||||
"""Mode codes from a `modes`-style field, which some firmwares send as
|
||||
a bare string rather than an array."""
|
||||
if isinstance(value, str):
|
||||
return [value]
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [v for v in value if isinstance(v, str)]
|
||||
return []
|
||||
|
||||
|
||||
def _coerce(stored) -> dict[str, list[str]]:
|
||||
"""Restore the persisted map, dropping anything that isn't the shape
|
||||
this module writes. It round-trips through the config entry as plain
|
||||
JSON, and a hand-edited .storage file shouldn't be able to crash
|
||||
setup."""
|
||||
if not isinstance(stored, dict):
|
||||
return {}
|
||||
restored = {}
|
||||
for href, codes in stored.items():
|
||||
if isinstance(href, str) and (valid := [c for c in _codes(codes) if c]):
|
||||
restored[href] = valid
|
||||
return restored
|
||||
|
||||
|
||||
def stored(entry) -> dict[str, list[str]]:
|
||||
"""What `entry` has persisted, coerced -- for a reader that can't go
|
||||
through a coordinator (the options flow, on an unloaded entry)."""
|
||||
return _coerce(entry.data.get(CONF_LEARNED_MODES))
|
||||
|
||||
|
||||
def persist(hass, entry, codes: dict[str, list[str]]) -> None:
|
||||
"""Write `codes` onto the entry. Runs on the event loop, which
|
||||
async_update_entry requires."""
|
||||
hass.config_entries.async_update_entry(entry, data={**entry.data, CONF_LEARNED_MODES: codes})
|
||||
|
||||
|
||||
class LearnedModes:
|
||||
"""Per-device store of learned codes, keyed by actual (on-the-wire)
|
||||
href so two subdevices of one composite appliance learn separately.
|
||||
|
||||
Mutated from whichever thread applied the update (the DTLS reader for
|
||||
an OBSERVE notify, an executor thread for a poll -- see
|
||||
ObserveManager.apply), so every access takes the lock; persistence is
|
||||
the caller's job, on the event loop.
|
||||
"""
|
||||
|
||||
def __init__(self, stored=None) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._learned = _coerce(stored)
|
||||
|
||||
def observe(self, actual_href: str, rep: dict) -> list[str]:
|
||||
"""Learn from one applied rep; returns the codes newly learned, so
|
||||
an empty list means there is nothing to persist.
|
||||
|
||||
A rep that carries no supported list teaches nothing: "missing from
|
||||
the list" is only meaningful against a list that exists, and
|
||||
inventing one for a device that publishes none would offer options
|
||||
nothing ever said were selectable. `rep` is the merged rep
|
||||
ObserveManager.apply stores, so a partial notify carrying `modes`
|
||||
alone (issue #27) still sees the supported list from the last full
|
||||
poll.
|
||||
"""
|
||||
supported = _codes(rep.get(SUPPORTED_FIELD))
|
||||
if not supported:
|
||||
return []
|
||||
with self._lock:
|
||||
known = self._learned.get(actual_href, [])
|
||||
new = [
|
||||
code
|
||||
for code in _codes(rep.get(MODES_FIELD))
|
||||
if code and code not in supported and code not in known
|
||||
]
|
||||
if new:
|
||||
self._learned[actual_href] = [*known, *new]
|
||||
return new
|
||||
|
||||
def codes(self, actual_href: str) -> list[str]:
|
||||
with self._lock:
|
||||
return list(self._learned.get(actual_href, ()))
|
||||
|
||||
def snapshot(self) -> dict[str, list[str]]:
|
||||
with self._lock:
|
||||
return {href: list(codes) for href, codes in self._learned.items()}
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self._learned = {}
|
||||
@@ -12,5 +12,5 @@
|
||||
"pyOpenSSL>=23.0",
|
||||
"smartthings-local>=0.1.2"
|
||||
],
|
||||
"version": "0.19.0"
|
||||
"version": "0.20.0"
|
||||
}
|
||||
@@ -14,6 +14,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
import cbor2
|
||||
from smartthings_local.ocf.observe_refresh import ObserveRefreshTask
|
||||
@@ -77,10 +78,21 @@ class ObserveManager:
|
||||
# have notified. Guards only `_notified` mutations + the `wait_for`.
|
||||
self._notify_cond = threading.Condition()
|
||||
self.fallback_hrefs: set[str] = set()
|
||||
self._on_applied: Callable[[str, dict, str], None] | None = None
|
||||
self._refresh_task: ObserveRefreshTask | None = None
|
||||
self._refresh_stop: threading.Event | None = None
|
||||
self._refresh_thread: threading.Thread | None = None
|
||||
|
||||
def set_on_applied(self, callback: Callable[[str, dict, str], None]) -> None:
|
||||
"""Hook run after every accepted rep, on the applying thread.
|
||||
|
||||
Unlike StateCache.set_on_change it carries the href and rep, and
|
||||
fires even when the rep is unchanged -- which learned.py needs, a
|
||||
device sitting in an unadvertised mode re-sending the same rep
|
||||
every poll.
|
||||
"""
|
||||
self._on_applied = callback
|
||||
|
||||
def mark_write_pending(self, href: str, settle_s: float = DEFAULT_SETTLE_S) -> None:
|
||||
with self._settle_lock:
|
||||
self._settle_until[href] = time.monotonic() + settle_s
|
||||
@@ -138,7 +150,14 @@ class ObserveManager:
|
||||
return False
|
||||
with self._cache_lock:
|
||||
merged = {**(self.cache.get(href) or {}), **rep}
|
||||
return self.cache.apply_rep(href, merged, source=source)
|
||||
changed = self.cache.apply_rep(href, merged, source=source)
|
||||
# Outside the cache lock -- the hook takes locks of its own and
|
||||
# never reads the cache back. `source` is passed along rather than
|
||||
# filtered here: which sources are worth acting on is the hook's
|
||||
# policy, not this manager's.
|
||||
if self._on_applied is not None:
|
||||
self._on_applied(href, merged, source)
|
||||
return changed
|
||||
|
||||
def on_notification(self, href: str, payload: bytes) -> None:
|
||||
"""Wired as DtlsCoapSession.on_notification. Runs on the DTLS
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
"""Home Assistant services for direct OCF resource read/write access
|
||||
(issue #300): a raw-transport escape hatch for reverse-engineering a
|
||||
device's write contract -- an ordered multi-write sequence with settle
|
||||
delays and a delayed re-read, which the single-write options-flow debug
|
||||
panel can't express. Both sit on the same coordinator primitives the panel
|
||||
now calls too (config_flow.py), so there is exactly one code path that
|
||||
performs a raw write.
|
||||
|
||||
Kept thin on purpose: session/lock ownership lives on the coordinator
|
||||
(coordinator.py). This module only resolves the service call's device
|
||||
target to a `(coordinator, subdevice)` pair, translates canonical hrefs
|
||||
through that subdevice, and shapes the response.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, cast
|
||||
|
||||
import voluptuous as vol
|
||||
from homeassistant.core import HomeAssistant, ServiceCall, ServiceResponse, SupportsResponse
|
||||
from homeassistant.exceptions import ServiceValidationError
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
|
||||
from .const import DOMAIN, SERVICE_READ_RESOURCE, SERVICE_WRITE_RESOURCE
|
||||
from .coordinator import LocalThingsCoordinator, normalize_href
|
||||
from .registry.subdevices import MAIN, Subdevice
|
||||
|
||||
ATTR_HREF = "href"
|
||||
ATTR_PAYLOAD = "payload"
|
||||
ATTR_SETTLE = "settle"
|
||||
ATTR_WRITES = "writes"
|
||||
ATTR_VERIFY_AFTER = "verify_after"
|
||||
ATTR_HOLD_SESSION_LOCK = "hold_session_lock"
|
||||
ATTR_DEVICE_ID = "device_id"
|
||||
|
||||
_WRITE_ITEM_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required(ATTR_HREF): str,
|
||||
# Not `dict` here: a non-dict payload must fail the same way an
|
||||
# empty one does -- coordinator.async_raw_write_sequence's
|
||||
# ServiceValidationError -- not a raw schema vol.Invalid, so every
|
||||
# caller sees one consistent error shape regardless of which rule
|
||||
# a bad payload tripped.
|
||||
vol.Required(ATTR_PAYLOAD): object,
|
||||
vol.Optional(ATTR_SETTLE): vol.Coerce(float),
|
||||
}
|
||||
)
|
||||
|
||||
# Structural validation only (types, and unwrapping a bare dict into a
|
||||
# one-item list) -- the semantic checks (non-empty payload, non-root href,
|
||||
# the 1..10/settle/verify_after ranges) live on
|
||||
# LocalThingsCoordinator.async_raw_write_sequence, so every caller gets the
|
||||
# same ServiceValidationError + translation key regardless of whether it
|
||||
# reached the primitive through this service, the options-flow panel, or a
|
||||
# future caller.
|
||||
_WRITE_RESOURCE_SCHEMA = vol.Schema(
|
||||
{
|
||||
**cv.TARGET_SERVICE_FIELDS,
|
||||
vol.Required(ATTR_WRITES): vol.All(cv.ensure_list, [_WRITE_ITEM_SCHEMA]),
|
||||
vol.Optional(ATTR_VERIFY_AFTER): vol.Coerce(float),
|
||||
vol.Optional(ATTR_HOLD_SESSION_LOCK): cv.boolean,
|
||||
}
|
||||
)
|
||||
|
||||
_READ_RESOURCE_SCHEMA = vol.Schema(
|
||||
{
|
||||
**cv.TARGET_SERVICE_FIELDS,
|
||||
vol.Optional(ATTR_HREF): str,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _resolve_target(
|
||||
hass: HomeAssistant, call: ServiceCall
|
||||
) -> tuple[LocalThingsCoordinator, Subdevice, str]:
|
||||
"""The one `(coordinator, subdevice, device_id)` a service call's
|
||||
device target names.
|
||||
|
||||
Deliberately strict about count, not just presence: the `target:
|
||||
device:` selector in services.yaml still lets a user pick an area or
|
||||
label in the picker, and the frontend expands that into a `device_id`
|
||||
list before the call reaches here -- more than one entry means an
|
||||
area/label fanned this out across several appliances, which a raw
|
||||
debug write must never do silently (issue #300).
|
||||
"""
|
||||
device_ids = cv.ensure_list(call.data.get(ATTR_DEVICE_ID) or [])
|
||||
if len(device_ids) != 1:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="service_device_target_invalid",
|
||||
)
|
||||
device_id = device_ids[0]
|
||||
|
||||
dev_reg = dr.async_get(hass)
|
||||
device = dev_reg.async_get(device_id)
|
||||
if device is None:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="service_device_not_found",
|
||||
)
|
||||
|
||||
for coordinator in hass.data.get(DOMAIN, {}).values():
|
||||
if device.identifiers & coordinator.device_info.get("identifiers", set()):
|
||||
return coordinator, MAIN, device_id
|
||||
for sub in coordinator.subdevices:
|
||||
if device.identifiers & coordinator.device_info_for(sub).get("identifiers", set()):
|
||||
return coordinator, sub, device_id
|
||||
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="service_device_not_loaded",
|
||||
)
|
||||
|
||||
|
||||
async def _async_write_resource(hass: HomeAssistant, call: ServiceCall) -> ServiceResponse:
|
||||
coordinator, subdevice, device_id = _resolve_target(hass, call)
|
||||
writes_in: list[dict[str, Any]] = call.data[ATTR_WRITES]
|
||||
|
||||
# Canonical -> actual translation happens here, not in the coordinator
|
||||
# (issue #177), whose raw-write primitive has no notion of subdevices --
|
||||
# identity transform for MAIN. Normalized first, or a trailing slash
|
||||
# slips past to_actual onto the master (see coordinator.normalize_href).
|
||||
canonicals = [normalize_href(w[ATTR_HREF]) for w in writes_in]
|
||||
raw_writes = [
|
||||
{
|
||||
"href": subdevice.to_actual(canonical),
|
||||
"payload": w.get(ATTR_PAYLOAD),
|
||||
"settle": w.get(ATTR_SETTLE, 0.0),
|
||||
}
|
||||
for canonical, w in zip(canonicals, writes_in, strict=True)
|
||||
]
|
||||
sequence = await coordinator.async_raw_write_sequence(
|
||||
raw_writes,
|
||||
verify_after=call.data.get(ATTR_VERIFY_AFTER, 0.0),
|
||||
hold_session_lock=call.data.get(ATTR_HOLD_SESSION_LOCK, True),
|
||||
)
|
||||
|
||||
results = [
|
||||
{
|
||||
"href": canonical,
|
||||
"actual_href": result["href"],
|
||||
"code": result["code"],
|
||||
"raw_code": result["raw_code"],
|
||||
"accepted": result["accepted"],
|
||||
"before": result["before"],
|
||||
"after": result["after"],
|
||||
"changed": result["changed"],
|
||||
}
|
||||
for canonical, result in zip(canonicals, sequence["results"], strict=True)
|
||||
]
|
||||
response: dict[str, Any] = {"device_id": device_id, "results": results}
|
||||
if "verified" in sequence:
|
||||
# Keyed off the same normalized canonicals the sequence was built
|
||||
# from, so the lookup can't miss and return an actual href where the
|
||||
# contract promises a canonical one.
|
||||
canonical_by_actual = {subdevice.to_actual(c): c for c in canonicals}
|
||||
response["verified"] = {
|
||||
canonical_by_actual.get(actual_href, actual_href): verified
|
||||
for actual_href, verified in sequence["verified"].items()
|
||||
}
|
||||
return response
|
||||
|
||||
|
||||
async def _async_read_resource(hass: HomeAssistant, call: ServiceCall) -> ServiceResponse:
|
||||
coordinator, subdevice, _device_id = _resolve_target(hass, call)
|
||||
href = call.data.get(ATTR_HREF)
|
||||
if not href:
|
||||
# No href -> the cached snapshot, not a live sweep of every known
|
||||
# href: lets a user enumerate what exists without hammering the
|
||||
# device (see this module's docstring and the coordinator's
|
||||
# canonical_resources).
|
||||
snapshot: dict[str, Any] = {"resources": coordinator.canonical_resources(subdevice)}
|
||||
return cast(ServiceResponse, snapshot)
|
||||
|
||||
# Same normalize-before-translate order as the write path above.
|
||||
canonical = normalize_href(href)
|
||||
actual_href = subdevice.to_actual(canonical)
|
||||
code, rep = await coordinator.async_raw_read(actual_href)
|
||||
read_result: dict[str, Any] = {
|
||||
"href": canonical,
|
||||
"actual_href": actual_href,
|
||||
"code": f"{code >> 5}.{code & 0x1F:02d}",
|
||||
"raw_code": code,
|
||||
"rep": rep,
|
||||
}
|
||||
return cast(ServiceResponse, read_result)
|
||||
|
||||
|
||||
def async_setup_services(hass: HomeAssistant) -> None:
|
||||
"""Register the write_resource/read_resource services (issue #300).
|
||||
|
||||
Called once from `async_setup`, not per config entry: services are
|
||||
process-global, and `hass.services.async_register` on an
|
||||
already-registered name just replaces the handler, so re-registering
|
||||
on every entry setup would silently rebind to whichever entry loaded
|
||||
last. `async_unload_entry` must never call the inverse of this.
|
||||
"""
|
||||
|
||||
async def _handle_write(call: ServiceCall) -> ServiceResponse:
|
||||
return await _async_write_resource(hass, call)
|
||||
|
||||
async def _handle_read(call: ServiceCall) -> ServiceResponse:
|
||||
return await _async_read_resource(hass, call)
|
||||
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
SERVICE_WRITE_RESOURCE,
|
||||
_handle_write,
|
||||
schema=_WRITE_RESOURCE_SCHEMA,
|
||||
supports_response=SupportsResponse.OPTIONAL,
|
||||
)
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
SERVICE_READ_RESOURCE,
|
||||
_handle_read,
|
||||
schema=_READ_RESOURCE_SCHEMA,
|
||||
supports_response=SupportsResponse.ONLY,
|
||||
)
|
||||
@@ -0,0 +1,88 @@
|
||||
write_resource:
|
||||
name: Write resource
|
||||
description: >-
|
||||
Send one or more raw partial-rep writes straight to a device's OCF
|
||||
resources, in order, with an optional settle delay between steps and a
|
||||
delayed re-read at the end -- for reverse-engineering a device's write
|
||||
contract (issue #300), not day-to-day control. This bypasses the
|
||||
remote-control-off block and every write_fn/validate_fn a normal entity
|
||||
write goes through, and sends exactly the fields you give it verbatim:
|
||||
it can misconfigure your appliance. Prefer a real entity, or the Debug
|
||||
write panel in the integration's Configure menu, for anything this
|
||||
integration already models.
|
||||
fields:
|
||||
device_id:
|
||||
name: Device
|
||||
description: The appliance to write to, or one of its subdevices.
|
||||
required: true
|
||||
selector:
|
||||
device:
|
||||
integration: localthings
|
||||
writes:
|
||||
name: Writes
|
||||
description: >-
|
||||
1-10 writes to perform in order. Each item needs href (the
|
||||
canonical resource, e.g. /mode/vs/0) and payload (a non-empty
|
||||
object sent verbatim as a partial-rep POST); settle is how many
|
||||
seconds to wait after that write before starting the next one
|
||||
(0-30, default 0).
|
||||
required: true
|
||||
example: >-
|
||||
[{"href": "/mode/vs/0", "payload": {"x.com.samsung.da.modes":
|
||||
["Bake"]}, "settle": 3}]
|
||||
selector:
|
||||
object:
|
||||
hold_session_lock:
|
||||
name: Hold the session for the whole sequence
|
||||
description: >-
|
||||
Keep the device session for the entire sequence, settle delays
|
||||
included, so nothing else -- a routine poll, another entity's write
|
||||
-- can land between two steps and blur which write the appliance
|
||||
was reacting to. On by default. Turning it off takes the session
|
||||
per write and frees it across the waits, which lets entities keep
|
||||
updating during a long sequence at the cost of that certainty.
|
||||
required: false
|
||||
default: true
|
||||
selector:
|
||||
boolean:
|
||||
verify_after:
|
||||
name: Verify after
|
||||
description: >-
|
||||
Seconds to wait after the whole sequence finishes before
|
||||
re-reading every href touched, to see whether the values held or
|
||||
were reverted by the board. 0 (default) skips verification.
|
||||
required: false
|
||||
default: 0
|
||||
selector:
|
||||
number:
|
||||
min: 0
|
||||
max: 60
|
||||
step: 0.5
|
||||
unit_of_measurement: seconds
|
||||
mode: box
|
||||
|
||||
read_resource:
|
||||
name: Read resource
|
||||
description: >-
|
||||
Read a device's OCF resources directly, bypassing this integration's
|
||||
entity model. Give an href for a live GET straight from the device --
|
||||
deliberately not the cache, which can be up to a poll interval stale --
|
||||
or omit it to get the cached snapshot of every resource this
|
||||
integration currently tracks on that device.
|
||||
fields:
|
||||
device_id:
|
||||
name: Device
|
||||
description: The appliance to read from, or one of its subdevices.
|
||||
required: true
|
||||
selector:
|
||||
device:
|
||||
integration: localthings
|
||||
href:
|
||||
name: Resource href
|
||||
description: >-
|
||||
Canonical resource href to read (e.g. /mode/vs/0). Omit to get the
|
||||
cached snapshot of every tracked resource instead of a live GET.
|
||||
required: false
|
||||
example: /mode/vs/0
|
||||
selector:
|
||||
text:
|
||||
@@ -1348,17 +1348,23 @@
|
||||
"title": "Možnosti LocalThings",
|
||||
"menu_options": {
|
||||
"settings": "Nastavení zápisu pro dálkové ovládání",
|
||||
"forget_learned_modes": "Zapomenout zapamatované režimy",
|
||||
"debug_write": "Ladění: zápis do prostředku"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"title": "Nastavení zápisu pro dálkové ovládání",
|
||||
"description": "Některá zařízení přijímají určité zápisy (např. výchozí dávkování pracího prostředku/aviváže v pračce) i když hlásí vypnuté dálkové ovládání. LocalThings ve výchozím nastavení blokuje každý zápis srozumitelnou chybou, kdykoli zařízení hlásí vypnuté dálkové ovládání, místo aby jej zařízení tiše odmítlo. Povolte toto pouze tehdy, pokud jste ověřili, že zápisy na tomto zařízení skutečně fungují i s vypnutým dálkovým ovládáním – jinak tuto srozumitelnou chybu vyměníte za tiché selhání.",
|
||||
"description": "Některá zařízení přijímají určité zápisy (např. výchozí dávkování pracího prostředku/aviváže v pračce) i když hlásí vypnuté dálkové ovládání. LocalThings ve výchozím nastavení blokuje každý zápis srozumitelnou chybou, kdykoli zařízení hlásí vypnuté dálkové ovládání, místo aby jej zařízení tiše odmítlo. Povolte toto pouze tehdy, pokud jste ověřili, že zápisy na tomto zařízení skutečně fungují i s vypnutým dálkovým ovládáním – jinak tuto srozumitelnou chybu vyměníte za tiché selhání.\n\nNěkterá zařízení hlásí režim, který nikdy neuvedou mezi podporovanými – například klimatizace běžící v režimu Quiet, která nabízí pouze Off/Sleep/Speed. LocalThings si každý takový režim zapamatuje a dál jej nabízí, takže zůstane volitelný, jakmile v něm zařízení alespoň jednou bylo. Vypnutím této volby se budou nabízet pouze režimy, které zařízení samo uvádí; k vymazání již zapamatovaných použijte „Zapomenout zapamatované režimy“ v předchozí nabídce.",
|
||||
"data": {
|
||||
"bypass_remote_control_lock": "Povolit zápis i když je dálkové ovládání hlášeno jako vypnuté",
|
||||
"finish_time_hysteresis_minutes": "Odhadovaný konec -- minimální změna (minuty)"
|
||||
"finish_time_hysteresis_minutes": "Odhadovaný konec -- minimální změna (minuty)",
|
||||
"learn_device_modes": "Pamatovat si režimy, které zařízení hlásí, ale neuvádí jako podporované"
|
||||
}
|
||||
},
|
||||
"forget_learned_modes": {
|
||||
"title": "Zapomenout zapamatované režimy",
|
||||
"description": "Aktuálně zapamatováno: {codes}\n\nJde o režimy, ve kterých se toto zařízení samo hlásilo, aniž by je uvádělo mezi podporovanými; jsou uchovány, aby zůstaly volitelné. Zapomenutí je řešením, pokud se některý ukázal jako chybný – cokoli, co zařízení skutečně znovu nahlásí, si systém opět zapamatuje, pokud zároveň nevypnete volbu „Pamatovat si režimy, které zařízení hlásí, ale neuvádí jako podporované“ v nastavení."
|
||||
},
|
||||
"debug_write": {
|
||||
"title": "Ladění: zápis do prostředku",
|
||||
"description": "Nástroj pro pokročilé uživatele k odhalení chování zápisu specifického pro dané zařízení. Vyberte prostředek (href), do kterého chcete zapisovat, nebo zadejte vlastní, který není uveden v seznamu. Toto obchází blokování při vypnutém dálkovém ovládání a odesílá přesně ta pole, která zadáte -- může to špatně nakonfigurovat váš spotřebič, používejte tedy záměrně.",
|
||||
@@ -1417,6 +1423,24 @@
|
||||
},
|
||||
"command_failed": {
|
||||
"message": "Příkaz pro {href} selhal i po opětovném připojení: {error}"
|
||||
},
|
||||
"debug_too_many_writes": {
|
||||
"message": "Zadejte 1 až 10 zápisů."
|
||||
},
|
||||
"debug_settle_out_of_range": {
|
||||
"message": "Hodnota settle musí být mezi 0 a 30 sekundami."
|
||||
},
|
||||
"debug_verify_after_out_of_range": {
|
||||
"message": "Hodnota verify_after musí být mezi 0 a 60 sekundami."
|
||||
},
|
||||
"service_device_target_invalid": {
|
||||
"message": "Tato služba vyžaduje přesně jedno cílové zařízení."
|
||||
},
|
||||
"service_device_not_found": {
|
||||
"message": "Pro tento cíl nebylo nalezeno žádné odpovídající zařízení."
|
||||
},
|
||||
"service_device_not_loaded": {
|
||||
"message": "Toto zařízení ještě není připojeno. Zkuste to znovu, až se načte."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1348,17 +1348,23 @@
|
||||
"title": "LocalThings options",
|
||||
"menu_options": {
|
||||
"settings": "Device settings",
|
||||
"forget_learned_modes": "Forget remembered modes",
|
||||
"debug_write": "Debug: write to a resource"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"title": "Device settings",
|
||||
"description": "Some devices accept certain writes (e.g. default detergent/softener dosing on a washer) even while reporting remote control off. By default, LocalThings blocks every write with a clear error whenever a device reports remote control off, rather than letting the device silently reject it. Only enable this if you've confirmed writes actually work on this device with remote control off -- otherwise you'll trade that clear error for a silent failure.\n\nEstimated finish time is recomputed from the device's remaining-time estimate on every poll, which can drift or get revised by a minute or two between updates. Raise the minimum-change value below to hold the sensor at its last reported value until the estimate moves by at least that many minutes, cutting down on history/logbook noise. Set it to 0 to report every computed change.",
|
||||
"description": "Some devices accept certain writes (e.g. default detergent/softener dosing on a washer) even while reporting remote control off. By default, LocalThings blocks every write with a clear error whenever a device reports remote control off, rather than letting the device silently reject it. Only enable this if you've confirmed writes actually work on this device with remote control off -- otherwise you'll trade that clear error for a silent failure.\n\nEstimated finish time is recomputed from the device's remaining-time estimate on every poll, which can drift or get revised by a minute or two between updates. Raise the minimum-change value below to hold the sensor at its last reported value until the estimate moves by at least that many minutes, cutting down on history/logbook noise. Set it to 0 to report every computed change.\n\nSome models report a mode they never list as supported -- an air conditioner sitting in Quiet that only offers Off/Sleep/Speed, for instance. LocalThings remembers any such mode it sees and keeps offering it, so it stays selectable once the device has been in it at least once. Turn this off to offer only what the device advertises; use \"Forget remembered modes\" on the previous screen to clear what has already been remembered.",
|
||||
"data": {
|
||||
"bypass_remote_control_lock": "Allow writes even when remote control is reported off",
|
||||
"finish_time_hysteresis_minutes": "Estimated finish -- minimum change (minutes)"
|
||||
"finish_time_hysteresis_minutes": "Estimated finish -- minimum change (minutes)",
|
||||
"learn_device_modes": "Remember modes the device reports but doesn't advertise"
|
||||
}
|
||||
},
|
||||
"forget_learned_modes": {
|
||||
"title": "Forget remembered modes",
|
||||
"description": "Currently remembered: {codes}\n\nThese are modes this device reported itself in without listing them as supported, kept so they stay selectable. Forgetting them is the fix if one turned out to be bogus -- anything the device genuinely reports again will simply be remembered again, unless you also turn off \"Remember modes the device reports but doesn't advertise\" in Device settings."
|
||||
},
|
||||
"debug_write": {
|
||||
"title": "Debug: write to a resource",
|
||||
"description": "Power-user tool for pinning down device-specific write behavior. Pick the resource (href) you want to write to, or type a custom one that isn't listed. This bypasses the remote-control-off block and sends exactly the fields you provide -- it can misconfigure your appliance, so use it deliberately.",
|
||||
@@ -1417,6 +1423,24 @@
|
||||
},
|
||||
"command_failed": {
|
||||
"message": "The command to {href} failed even after reconnecting: {error}"
|
||||
},
|
||||
"debug_too_many_writes": {
|
||||
"message": "Provide between 1 and 10 writes."
|
||||
},
|
||||
"debug_settle_out_of_range": {
|
||||
"message": "settle must be between 0 and 30 seconds."
|
||||
},
|
||||
"debug_verify_after_out_of_range": {
|
||||
"message": "verify_after must be between 0 and 60 seconds."
|
||||
},
|
||||
"service_device_target_invalid": {
|
||||
"message": "This service requires exactly one target device."
|
||||
},
|
||||
"service_device_not_found": {
|
||||
"message": "No matching device was found for that target."
|
||||
},
|
||||
"service_device_not_loaded": {
|
||||
"message": "This device isn't connected yet. Try again once it has loaded."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,17 +53,23 @@
|
||||
"title": "Opciones de LocalThings",
|
||||
"menu_options": {
|
||||
"settings": "Ajustes del dispositivo",
|
||||
"forget_learned_modes": "Olvidar los modos recordados",
|
||||
"debug_write": "Depuración: escribir en un recurso"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"title": "Ajustes del dispositivo",
|
||||
"description": "Algunos dispositivos aceptan ciertas escrituras (p. ej. la dosificación por defecto de detergente/suavizante en una lavadora) incluso cuando informan de control remoto desactivado. Por defecto, LocalThings bloquea cada escritura con un error claro cuando un dispositivo informa de control remoto desactivado, en lugar de dejar que el dispositivo la rechace en silencio. Solo actívalo si has confirmado que las escrituras funcionan de verdad en este dispositivo con el control remoto desactivado; si no, cambiarás ese error claro por un fallo silencioso.\n\nLa hora estimada de finalización se recalcula a partir de la estimación de tiempo restante del dispositivo en cada sondeo, que puede variar o revisarse uno o dos minutos entre actualizaciones. Sube el valor de cambio mínimo siguiente para mantener el sensor en su último valor notificado hasta que la estimación varíe al menos esa cantidad de minutos, reduciendo el ruido en el historial/registro de actividad. Ponlo a 0 para notificar cada cambio calculado.",
|
||||
"description": "Algunos dispositivos aceptan ciertas escrituras (p. ej. la dosificación por defecto de detergente/suavizante en una lavadora) incluso cuando informan de control remoto desactivado. Por defecto, LocalThings bloquea cada escritura con un error claro cuando un dispositivo informa de control remoto desactivado, en lugar de dejar que el dispositivo la rechace en silencio. Solo actívalo si has confirmado que las escrituras funcionan de verdad en este dispositivo con el control remoto desactivado; si no, cambiarás ese error claro por un fallo silencioso.\n\nLa hora estimada de finalización se recalcula a partir de la estimación de tiempo restante del dispositivo en cada sondeo, que puede variar o revisarse uno o dos minutos entre actualizaciones. Sube el valor de cambio mínimo siguiente para mantener el sensor en su último valor notificado hasta que la estimación varíe al menos esa cantidad de minutos, reduciendo el ruido en el historial/registro de actividad. Ponlo a 0 para notificar cada cambio calculado.\n\nAlgunos modelos notifican un modo que nunca incluyen entre los admitidos: por ejemplo, un aire acondicionado en modo Quiet que solo ofrece Off/Sleep/Speed. LocalThings recuerda cualquier modo así que detecte y lo sigue ofreciendo, de modo que quede seleccionable en cuanto el dispositivo haya estado en él al menos una vez. Desactívalo para ofrecer solo lo que el dispositivo anuncia; usa «Olvidar los modos recordados» en la pantalla anterior para borrar lo ya recordado.",
|
||||
"data": {
|
||||
"bypass_remote_control_lock": "Permitir escrituras incluso cuando el control remoto se notifica como desactivado",
|
||||
"finish_time_hysteresis_minutes": "Finalización estimada -- cambio mínimo (minutos)"
|
||||
"finish_time_hysteresis_minutes": "Finalización estimada -- cambio mínimo (minutos)",
|
||||
"learn_device_modes": "Recordar los modos que el dispositivo notifica pero no anuncia"
|
||||
}
|
||||
},
|
||||
"forget_learned_modes": {
|
||||
"title": "Olvidar los modos recordados",
|
||||
"description": "Recordados actualmente: {codes}\n\nSon modos en los que este dispositivo se notificó a sí mismo sin incluirlos entre los admitidos; se conservan para que sigan siendo seleccionables. Olvidarlos es la solución si alguno resultó ser erróneo: cualquier modo que el dispositivo vuelva a notificar de verdad se recordará otra vez, salvo que además desactives «Recordar los modos que el dispositivo notifica pero no anuncia» en los ajustes del dispositivo."
|
||||
},
|
||||
"debug_write": {
|
||||
"title": "Depuración: escribir en un recurso",
|
||||
"description": "Herramienta para usuarios avanzados para precisar el comportamiento de escritura específico del dispositivo. Elige el recurso (href) sobre el que quieres escribir, o escribe uno personalizado que no esté en la lista. Esto omite el bloqueo de control remoto desactivado y envía exactamente los campos que proporciones; puede desconfigurar tu electrodoméstico, así que úsalo deliberadamente.",
|
||||
@@ -122,6 +128,24 @@
|
||||
},
|
||||
"command_failed": {
|
||||
"message": "El comando para {href} falló incluso después de reconectar: {error}"
|
||||
},
|
||||
"debug_too_many_writes": {
|
||||
"message": "Proporciona entre 1 y 10 escrituras."
|
||||
},
|
||||
"debug_settle_out_of_range": {
|
||||
"message": "settle debe estar entre 0 y 30 segundos."
|
||||
},
|
||||
"debug_verify_after_out_of_range": {
|
||||
"message": "verify_after debe estar entre 0 y 60 segundos."
|
||||
},
|
||||
"service_device_target_invalid": {
|
||||
"message": "Este servicio requiere exactamente un dispositivo de destino."
|
||||
},
|
||||
"service_device_not_found": {
|
||||
"message": "No se encontró ningún dispositivo coincidente para ese destino."
|
||||
},
|
||||
"service_device_not_loaded": {
|
||||
"message": "Este dispositivo aún no está conectado. Vuelve a intentarlo cuando se haya cargado."
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
|
||||
@@ -1348,17 +1348,23 @@
|
||||
"title": "Opzioni LocalThings",
|
||||
"menu_options": {
|
||||
"settings": "Impostazioni dispositivo",
|
||||
"forget_learned_modes": "Dimentica le modalità memorizzate",
|
||||
"debug_write": "Debug: scrivi su una risorsa"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"title": "Impostazioni dispositivo",
|
||||
"description": "Alcuni dispositivi accettano determinate scritture (ad esempio, il dosaggio predefinito di detersivo/ammorbidente su una lavatrice) anche quando segnalano che il controllo remoto è disattivato. Per impostazione predefinita, LocalThings blocca ogni scrittura con un errore chiaro ogni volta che un dispositivo segnala che il controllo remoto è disattivato, invece di consentire al dispositivo di rifiutarla silenziosamente. Abilitare questa opzione solo se si è verificato che le scritture funzionano effettivamente su questo dispositivo con il controllo remoto disattivato; in caso contrario, si sostituirà l'errore chiaro con un errore silenzioso.\n\nIl tempo di fine stimato viene ricalcolato dalla stima del tempo rimanente del dispositivo a ogni interrogazione, che può variare o essere rivista di uno o due minuti tra un aggiornamento e l'altro. Aumentare il valore di variazione minima riportato di seguito per mantenere il sensore al suo ultimo valore segnalato finché la stima non si sposta di almeno quel numero di minuti, riducendo il rumore nella cronologia/registro. Impostarlo su 0 per segnalare ogni variazione calcolata.",
|
||||
"description": "Alcuni dispositivi accettano determinate scritture (ad esempio, il dosaggio predefinito di detersivo/ammorbidente su una lavatrice) anche quando segnalano che il controllo remoto è disattivato. Per impostazione predefinita, LocalThings blocca ogni scrittura con un errore chiaro ogni volta che un dispositivo segnala che il controllo remoto è disattivato, invece di consentire al dispositivo di rifiutarla silenziosamente. Abilitare questa opzione solo se si è verificato che le scritture funzionano effettivamente su questo dispositivo con il controllo remoto disattivato; in caso contrario, si sostituirà l'errore chiaro con un errore silenzioso.\n\nIl tempo di fine stimato viene ricalcolato dalla stima del tempo rimanente del dispositivo a ogni interrogazione, che può variare o essere rivista di uno o due minuti tra un aggiornamento e l'altro. Aumentare il valore di variazione minima riportato di seguito per mantenere il sensore al suo ultimo valore segnalato finché la stima non si sposta di almeno quel numero di minuti, riducendo il rumore nella cronologia/registro. Impostarlo su 0 per segnalare ogni variazione calcolata.\n\nAlcuni modelli segnalano una modalità che non elencano mai tra quelle supportate: ad esempio un condizionatore in modalità Quiet che offre solo Off/Sleep/Speed. LocalThings memorizza ogni modalità di questo tipo che rileva e continua a proporla, così resta selezionabile una volta che il dispositivo vi è stato almeno una volta. Disattivare questa opzione per proporre solo ciò che il dispositivo dichiara; usare «Dimentica le modalità memorizzate» nella schermata precedente per cancellare quanto già memorizzato.",
|
||||
"data": {
|
||||
"bypass_remote_control_lock": "Consenti la scrittura anche quando il controllo remoto risulta disattivato.",
|
||||
"finish_time_hysteresis_minutes": "Tempo finale stimato - variazione minima (minuti)"
|
||||
"finish_time_hysteresis_minutes": "Tempo finale stimato - variazione minima (minuti)",
|
||||
"learn_device_modes": "Memorizza le modalità che il dispositivo segnala ma non dichiara supportate"
|
||||
}
|
||||
},
|
||||
"forget_learned_modes": {
|
||||
"title": "Dimentica le modalità memorizzate",
|
||||
"description": "Attualmente memorizzate: {codes}\n\nSono modalità in cui questo dispositivo si è dichiarato senza elencarle tra quelle supportate; vengono conservate perché restino selezionabili. Dimenticarle è la soluzione se una si è rivelata errata: qualsiasi modalità che il dispositivo segnali davvero di nuovo verrà memorizzata un'altra volta, a meno che non si disattivi anche «Memorizza le modalità che il dispositivo segnala ma non dichiara supportate» nelle impostazioni del dispositivo."
|
||||
},
|
||||
"debug_write": {
|
||||
"title": "Debug: scrivi su una risorsa",
|
||||
"description": "Strumento avanzato per definire con precisione il comportamento di scrittura specifico del dispositivo. Seleziona la risorsa (href) su cui desideri scrivere oppure digitane una personalizzata non presente nell'elenco. Questo bypassa il blocco di disattivazione del controllo remoto e invia esattamente i campi specificati; tuttavia, potrebbe causare una configurazione errata del dispositivo, quindi utilizzalo con cautela.",
|
||||
@@ -1417,6 +1423,24 @@
|
||||
},
|
||||
"command_failed": {
|
||||
"message": "Il comando per {href} è fallito anche dopo la riconnessione: {error}"
|
||||
},
|
||||
"debug_too_many_writes": {
|
||||
"message": "Specificare da 1 a 10 scritture."
|
||||
},
|
||||
"debug_settle_out_of_range": {
|
||||
"message": "settle deve essere compreso tra 0 e 30 secondi."
|
||||
},
|
||||
"debug_verify_after_out_of_range": {
|
||||
"message": "verify_after deve essere compreso tra 0 e 60 secondi."
|
||||
},
|
||||
"service_device_target_invalid": {
|
||||
"message": "Questo servizio richiede esattamente un dispositivo di destinazione."
|
||||
},
|
||||
"service_device_not_found": {
|
||||
"message": "Nessun dispositivo corrispondente trovato per quella destinazione."
|
||||
},
|
||||
"service_device_not_loaded": {
|
||||
"message": "Questo dispositivo non è ancora connesso. Riprova una volta caricato."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1348,17 +1348,23 @@
|
||||
"title": "LocalThings 옵션",
|
||||
"menu_options": {
|
||||
"settings": "기기 설정",
|
||||
"forget_learned_modes": "기억된 모드 지우기",
|
||||
"debug_write": "디버그: 리소스에 쓰기"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"title": "기기 설정",
|
||||
"description": "일부 기기는 스마트 컨트롤이 꺼져 있다고 보고하는 동안에도 특정 쓰기 요청(예: 세탁기의 기본 세제/섬유유연제 투입량)을 받아들입니다. 기본적으로 LocalThings는 기기가 스마트 컨트롤 꺼짐을 보고하면 기기가 쓰기 요청을 조용히 거부하도록 두지 않고, 명확한 오류와 함께 모든 쓰기를 차단합니다. 스마트 컨트롤이 꺼진 상태에서도 이 기기에 쓰기가 실제로 동작하는 것을 확인한 경우에만 이 옵션을 활성화하세요. 그렇지 않으면 명확한 오류 대신 아무 표시 없이 쓰기에 실패할 수 있습니다.\n\n예상 완료 시각은 기기가 보고하는 남은 시간 추정치를 사용하여 상태를 확인할 때마다 다시 계산합니다. 이 추정치는 업데이트 사이에 1~2분 정도 변하거나 수정될 수 있습니다. 아래의 최소 변경량을 늘리면 추정치가 설정한 시간(분) 이상 변할 때까지 센서가 마지막으로 보고된 값을 유지하므로 기록과 로그북에 불필요한 항목이 쌓이는 것을 줄일 수 있습니다. 계산된 모든 변경 사항을 보고하려면 0으로 설정하세요.",
|
||||
"description": "일부 기기는 스마트 컨트롤이 꺼져 있다고 보고하는 동안에도 특정 쓰기 요청(예: 세탁기의 기본 세제/섬유유연제 투입량)을 받아들입니다. 기본적으로 LocalThings는 기기가 스마트 컨트롤 꺼짐을 보고하면 기기가 쓰기 요청을 조용히 거부하도록 두지 않고, 명확한 오류와 함께 모든 쓰기를 차단합니다. 스마트 컨트롤이 꺼진 상태에서도 이 기기에 쓰기가 실제로 동작하는 것을 확인한 경우에만 이 옵션을 활성화하세요. 그렇지 않으면 명확한 오류 대신 아무 표시 없이 쓰기에 실패할 수 있습니다.\n\n예상 완료 시각은 기기가 보고하는 남은 시간 추정치를 사용하여 상태를 확인할 때마다 다시 계산합니다. 이 추정치는 업데이트 사이에 1~2분 정도 변하거나 수정될 수 있습니다. 아래의 최소 변경량을 늘리면 추정치가 설정한 시간(분) 이상 변할 때까지 센서가 마지막으로 보고된 값을 유지하므로 기록과 로그북에 불필요한 항목이 쌓이는 것을 줄일 수 있습니다. 계산된 모든 변경 사항을 보고하려면 0으로 설정하세요.\n\n일부 모델은 지원 목록에 없는 모드를 현재 모드로 보고합니다. 예를 들어 Off/Sleep/Speed만 제공하면서 Quiet 모드로 동작 중이라고 보고하는 에어컨이 그렇습니다. LocalThings는 이렇게 발견한 모드를 기억해 두고 계속 제공하므로, 기기가 한 번이라도 그 모드였다면 이후에도 선택할 수 있습니다. 이 옵션을 끄면 기기가 지원한다고 알린 모드만 제공합니다. 이미 기억된 항목을 지우려면 이전 화면의 '기억된 모드 지우기'를 사용하세요.",
|
||||
"data": {
|
||||
"bypass_remote_control_lock": "스마트 컨트롤이 꺼진 것으로 보고되어도 쓰기 허용",
|
||||
"finish_time_hysteresis_minutes": "예상 완료 시각 - 최소 변경량(분)"
|
||||
"finish_time_hysteresis_minutes": "예상 완료 시각 - 최소 변경량(분)",
|
||||
"learn_device_modes": "기기가 보고하지만 지원 목록에 없는 모드 기억하기"
|
||||
}
|
||||
},
|
||||
"forget_learned_modes": {
|
||||
"title": "기억된 모드 지우기",
|
||||
"description": "현재 기억된 항목: {codes}\n\n이 기기가 지원 목록에 넣지 않은 채 자신의 현재 모드로 보고했던 모드들이며, 계속 선택할 수 있도록 보관되어 있습니다. 잘못된 항목이 기억되었다면 지우면 됩니다. 다만 기기가 실제로 다시 보고하면 다시 기억되므로, 그러길 원하지 않는다면 기기 설정에서 '기기가 보고하지만 지원 목록에 없는 모드 기억하기'도 함께 꺼 주세요."
|
||||
},
|
||||
"debug_write": {
|
||||
"title": "디버그: 리소스에 쓰기",
|
||||
"description": "기기별 쓰기 동작을 파악하기 위한 고급 사용자용 도구입니다. 쓰려는 리소스(href)를 선택하거나 목록에 없는 값을 직접 입력하세요. 이 기능은 스마트 컨트롤 꺼짐 차단을 우회하고 입력한 필드를 그대로 전송합니다. 가전제품이 잘못 설정될 수 있으므로 신중하게 사용하세요.",
|
||||
@@ -1417,6 +1423,24 @@
|
||||
},
|
||||
"command_failed": {
|
||||
"message": "재연결 후에도 {href} 명령이 실패했습니다: {error}"
|
||||
},
|
||||
"debug_too_many_writes": {
|
||||
"message": "1~10개의 쓰기를 지정하세요."
|
||||
},
|
||||
"debug_settle_out_of_range": {
|
||||
"message": "settle 값은 0에서 30초 사이여야 합니다."
|
||||
},
|
||||
"debug_verify_after_out_of_range": {
|
||||
"message": "verify_after 값은 0에서 60초 사이여야 합니다."
|
||||
},
|
||||
"service_device_target_invalid": {
|
||||
"message": "이 서비스는 정확히 하나의 대상 기기가 필요합니다."
|
||||
},
|
||||
"service_device_not_found": {
|
||||
"message": "해당 대상에 일치하는 기기를 찾을 수 없습니다."
|
||||
},
|
||||
"service_device_not_loaded": {
|
||||
"message": "이 기기는 아직 연결되지 않았습니다. 로드된 후 다시 시도하세요."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1348,17 +1348,23 @@
|
||||
"title": "LocalThings-opties",
|
||||
"menu_options": {
|
||||
"settings": "Apparaatinstellingen",
|
||||
"forget_learned_modes": "Onthouden modi vergeten",
|
||||
"debug_write": "Foutopsporing: naar een resource schrijven"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"title": "Apparaatinstellingen",
|
||||
"description": "Sommige apparaten accepteren bepaalde schrijfbewerkingen (bijvoorbeeld de standaarddosering van wasmiddel of wasverzachter op een wasmachine), ook als ze melden dat de afstandsbediening is uitgeschakeld. LocalThings blokkeert standaard elke schrijfbewerking met een duidelijke foutmelding wanneer een apparaat meldt dat de afstandsbediening is uitgeschakeld, in plaats van het apparaat de opdracht stilzwijgend te laten weigeren. Schakel deze optie alleen in als je hebt bevestigd dat schrijfbewerkingen op dit apparaat echt werken wanneer de afstandsbediening is uitgeschakeld. Anders verruil je de duidelijke foutmelding voor een stille mislukking.\n\nDe geschatte eindtijd wordt bij elke poll opnieuw berekend op basis van de resterende tijd die het apparaat opgeeft, wat kan afwijken of met een minuut of wat worden bijgesteld tussen updates. Verhoog de minimale wijziging hieronder om de sensor op zijn laatst gerapporteerde waarde te houden totdat de schatting met minstens dat aantal minuten verandert, wat de ruis in geschiedenis/logboek vermindert. Zet op 0 om elke berekende wijziging te rapporteren.",
|
||||
"description": "Sommige apparaten accepteren bepaalde schrijfbewerkingen (bijvoorbeeld de standaarddosering van wasmiddel of wasverzachter op een wasmachine), ook als ze melden dat de afstandsbediening is uitgeschakeld. LocalThings blokkeert standaard elke schrijfbewerking met een duidelijke foutmelding wanneer een apparaat meldt dat de afstandsbediening is uitgeschakeld, in plaats van het apparaat de opdracht stilzwijgend te laten weigeren. Schakel deze optie alleen in als je hebt bevestigd dat schrijfbewerkingen op dit apparaat echt werken wanneer de afstandsbediening is uitgeschakeld. Anders verruil je de duidelijke foutmelding voor een stille mislukking.\n\nDe geschatte eindtijd wordt bij elke poll opnieuw berekend op basis van de resterende tijd die het apparaat opgeeft, wat kan afwijken of met een minuut of wat worden bijgesteld tussen updates. Verhoog de minimale wijziging hieronder om de sensor op zijn laatst gerapporteerde waarde te houden totdat de schatting met minstens dat aantal minuten verandert, wat de ruis in geschiedenis/logboek vermindert. Zet op 0 om elke berekende wijziging te rapporteren.\n\nSommige modellen melden een modus die ze nooit als ondersteund opgeven: bijvoorbeeld een airco die in Quiet staat maar alleen Off/Sleep/Speed aanbiedt. LocalThings onthoudt elke zo waargenomen modus en blijft die aanbieden, zodat hij selecteerbaar blijft zodra het apparaat er minstens één keer in heeft gestaan. Schakel dit uit om alleen aan te bieden wat het apparaat opgeeft; gebruik \"Onthouden modi vergeten\" in het vorige scherm om te wissen wat al is onthouden.",
|
||||
"data": {
|
||||
"bypass_remote_control_lock": "Schrijfbewerkingen toestaan wanneer afstandsbediening als uitgeschakeld wordt gemeld",
|
||||
"finish_time_hysteresis_minutes": "Geschatte eindtijd -- minimale wijziging (minuten)"
|
||||
"finish_time_hysteresis_minutes": "Geschatte eindtijd -- minimale wijziging (minuten)",
|
||||
"learn_device_modes": "Modi onthouden die het apparaat meldt maar niet als ondersteund opgeeft"
|
||||
}
|
||||
},
|
||||
"forget_learned_modes": {
|
||||
"title": "Onthouden modi vergeten",
|
||||
"description": "Nu onthouden: {codes}\n\nDit zijn modi waarin dit apparaat zichzelf meldde zonder ze als ondersteund op te geven; ze worden bewaard zodat ze selecteerbaar blijven. Vergeten is de oplossing als er een onterecht tussen staat: alles wat het apparaat echt opnieuw meldt, wordt gewoon opnieuw onthouden, tenzij je ook \"Modi onthouden die het apparaat meldt maar niet als ondersteund opgeeft\" bij Apparaatinstellingen uitzet."
|
||||
},
|
||||
"debug_write": {
|
||||
"title": "Foutopsporing: naar een resource schrijven",
|
||||
"description": "Geavanceerd hulpmiddel om apparaatspecifiek schrijfgedrag te onderzoeken. Kies de resource (href) waarnaar je wilt schrijven, of voer een aangepaste resource in die niet in de lijst staat. Hiermee wordt de blokkering bij een uitgeschakelde afstandsbediening omzeild en worden precies de opgegeven velden verzonden. Dit kan de configuratie van je apparaat verstoren, dus gebruik het bewust.",
|
||||
@@ -1417,6 +1423,24 @@
|
||||
},
|
||||
"command_failed": {
|
||||
"message": "Het commando naar {href} is ook na opnieuw verbinden mislukt: {error}"
|
||||
},
|
||||
"debug_too_many_writes": {
|
||||
"message": "Geef tussen de 1 en 10 schrijfacties op."
|
||||
},
|
||||
"debug_settle_out_of_range": {
|
||||
"message": "settle moet tussen 0 en 30 seconden liggen."
|
||||
},
|
||||
"debug_verify_after_out_of_range": {
|
||||
"message": "verify_after moet tussen 0 en 60 seconden liggen."
|
||||
},
|
||||
"service_device_target_invalid": {
|
||||
"message": "Deze service vereist precies één doelapparaat."
|
||||
},
|
||||
"service_device_not_found": {
|
||||
"message": "Er is geen bijpassend apparaat gevonden voor dat doel."
|
||||
},
|
||||
"service_device_not_loaded": {
|
||||
"message": "Dit apparaat is nog niet verbonden. Probeer het opnieuw zodra het is geladen."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ from custom_components.localthings.const import (
|
||||
CONF_CA_KEY_PEM,
|
||||
CONF_HOST,
|
||||
CONF_LEAF_CERT_PEM,
|
||||
CONF_LEARN_MODES,
|
||||
CONF_LEARNED_MODES,
|
||||
CONF_PORT,
|
||||
DOMAIN,
|
||||
)
|
||||
@@ -935,7 +937,11 @@ async def test_options_flow_init_shows_menu(hass: HomeAssistant) -> None:
|
||||
|
||||
assert result["type"] == FlowResultType.MENU
|
||||
assert result["step_id"] == "init"
|
||||
assert set(cast(Iterable[str], result["menu_options"])) == {"settings", "debug_write"}
|
||||
assert set(cast(Iterable[str], result["menu_options"])) == {
|
||||
"settings",
|
||||
"forget_learned_modes",
|
||||
"debug_write",
|
||||
}
|
||||
|
||||
|
||||
async def test_options_flow_default_is_off(hass: HomeAssistant) -> None:
|
||||
@@ -974,6 +980,72 @@ async def test_options_flow_can_enable_bypass(hass: HomeAssistant) -> None:
|
||||
assert entry.options[CONF_BYPASS_REMOTE_CONTROL] is True
|
||||
|
||||
|
||||
async def test_learned_modes_option_defaults_to_on(hass: HomeAssistant) -> None:
|
||||
"""Issue #327's remembering is on by default -- a device that hides a
|
||||
mode it's in should just work, not need the option found first."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f"localthings_{MOCK_SERIAL}")
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"], user_input={"next_step_id": "settings"}
|
||||
)
|
||||
|
||||
data_schema = result["data_schema"]
|
||||
assert data_schema is not None
|
||||
assert data_schema({})[CONF_LEARN_MODES] is True
|
||||
|
||||
|
||||
async def test_learned_modes_option_can_be_turned_off(hass: HomeAssistant) -> None:
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f"localthings_{MOCK_SERIAL}")
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"], user_input={"next_step_id": "settings"}
|
||||
)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_BYPASS_REMOTE_CONTROL: False, CONF_LEARN_MODES: False},
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert entry.options[CONF_LEARN_MODES] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("stored", "listed"),
|
||||
[
|
||||
({"/mode/convenient/vs/0": ["Quiet"]}, "Quiet"),
|
||||
# Malformed -- nothing writes this shape, but a hand-edited
|
||||
# .storage can hold it, and this step is the one screen that can
|
||||
# clear it, so it must not be the one screen that trips over it.
|
||||
({"/mode/convenient/vs/0": None}, "(none)"),
|
||||
],
|
||||
)
|
||||
async def test_forget_learned_modes_clears_the_entry(hass: HomeAssistant, stored, listed) -> None:
|
||||
"""The reset step works on an unloaded entry too, by dropping the
|
||||
persisted copy directly -- that's all a reload would restore from."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={**ENTRY_DATA, CONF_LEARNED_MODES: stored},
|
||||
unique_id=f"localthings_{MOCK_SERIAL}",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"], user_input={"next_step_id": "forget_learned_modes"}
|
||||
)
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["description_placeholders"] == {"codes": listed}
|
||||
|
||||
result = await hass.config_entries.options.async_configure(result["flow_id"], user_input={})
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert entry.data[CONF_LEARNED_MODES] == {}
|
||||
|
||||
|
||||
async def test_options_flow_reflects_previously_saved_value(hass: HomeAssistant) -> None:
|
||||
"""Reopening the form shows the currently-saved choice as the default,
|
||||
not always False."""
|
||||
@@ -1036,9 +1108,10 @@ async def test_options_flow_debug_edit_writes_and_shows_result(
|
||||
hass: HomeAssistant,
|
||||
mock_coordinator_session,
|
||||
) -> None:
|
||||
"""Picking an href, then submitting a payload, drives
|
||||
coordinator.async_raw_write and lands on the result menu with the
|
||||
device's response."""
|
||||
"""Picking an href, then submitting a payload, calls the write_resource
|
||||
service (issue #300) -- which drives
|
||||
coordinator.async_raw_write_sequence -- and lands on the result menu
|
||||
with the device's response."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id=f"localthings_{MOCK_SERIAL}")
|
||||
entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
@@ -1056,8 +1129,20 @@ async def test_options_flow_debug_edit_writes_and_shows_result(
|
||||
assert result["step_id"] == "debug_edit"
|
||||
|
||||
with patch(
|
||||
"custom_components.localthings.coordinator.LocalThingsCoordinator.async_raw_write",
|
||||
return_value=(0x44, {"a": 1}),
|
||||
"custom_components.localthings.coordinator.LocalThingsCoordinator.async_raw_write_sequence",
|
||||
return_value={
|
||||
"results": [
|
||||
{
|
||||
"href": "/washer/vs/0",
|
||||
"code": "2.04",
|
||||
"raw_code": 0x44,
|
||||
"accepted": True,
|
||||
"before": {},
|
||||
"after": {"a": 1},
|
||||
"changed": True,
|
||||
}
|
||||
]
|
||||
},
|
||||
):
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
@@ -1123,8 +1208,20 @@ async def test_options_flow_finish_preserves_existing_options(
|
||||
user_input={"href": "/washer/vs/0"},
|
||||
)
|
||||
with patch(
|
||||
"custom_components.localthings.coordinator.LocalThingsCoordinator.async_raw_write",
|
||||
return_value=(0x44, {"a": 1}),
|
||||
"custom_components.localthings.coordinator.LocalThingsCoordinator.async_raw_write_sequence",
|
||||
return_value={
|
||||
"results": [
|
||||
{
|
||||
"href": "/washer/vs/0",
|
||||
"code": "2.04",
|
||||
"raw_code": 0x44,
|
||||
"accepted": True,
|
||||
"before": {},
|
||||
"after": {"a": 1},
|
||||
"changed": True,
|
||||
}
|
||||
]
|
||||
},
|
||||
):
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
|
||||
@@ -64,6 +64,9 @@ class _FakeCoordinator:
|
||||
async def async_send_command(self, bound, payload):
|
||||
self.commands.append((bound, payload))
|
||||
|
||||
def learned_modes(self, href):
|
||||
return []
|
||||
|
||||
|
||||
def _discover(resources, registry=airconditioner.REGISTRY):
|
||||
unbound = []
|
||||
|
||||
@@ -48,6 +48,9 @@ class _FakeCoordinator:
|
||||
async def async_send_command(self, bound, payload):
|
||||
self.commands.append((bound, payload))
|
||||
|
||||
def learned_modes(self, href):
|
||||
return []
|
||||
|
||||
|
||||
def _climate(resources, coordinator=None):
|
||||
info = resources["/information/vs/0"]
|
||||
|
||||
@@ -119,6 +119,9 @@ def test_fac_bora_wind_strength_codes_fit_the_standard_scale():
|
||||
# canonical view is just the raw snapshot (issue #177).
|
||||
return self.last_resources
|
||||
|
||||
def learned_modes(self, href):
|
||||
return []
|
||||
|
||||
resources = _load_device("airconditioner_fac_bora")
|
||||
info = resources["/information/vs/0"]
|
||||
reg = by_type.for_device_by_model(
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
"""Tests for issue #327: remembering a mode the device reports itself in
|
||||
but never advertises in supportedModes.
|
||||
|
||||
The reporters' unit (ARTIK051_PRAC_20K) isn't in the corpus, so the
|
||||
scenario runs on an existing fixture whose /mode/convenient/vs/0 genuinely
|
||||
lacks Quiet -- airconditioner_tp1x_fac_time_23k, supportedModes [Off,
|
||||
Sleep, Nano, NanoSleep] -- by applying the rep their firmware sends: a
|
||||
current mode of 'Quiet' with that same supportedModes list unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
from homeassistant.core import HomeAssistant
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.localthings.climate import LocalThingsClimate
|
||||
from custom_components.localthings.const import (
|
||||
CONF_LEARN_MODES,
|
||||
CONF_LEARNED_MODES,
|
||||
DOMAIN,
|
||||
)
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
from custom_components.localthings.learned import (
|
||||
LEARNABLE,
|
||||
MODES_FIELD,
|
||||
SUPPORTED_FIELD,
|
||||
LearnedModes,
|
||||
)
|
||||
from custom_components.localthings.registry.entities import ClimateDesc
|
||||
from tests.test_subdevice_discovery import ENTRY_DATA, _climate_bound, _discover
|
||||
|
||||
FIXTURE = "airconditioner_tp1x_fac_time_23k"
|
||||
CONVENIENT = "/mode/convenient/vs/0"
|
||||
ADVERTISED = ["Off", "Sleep", "Nano", "NanoSleep"]
|
||||
|
||||
# What the reporters' firmware sends while the unit is in Quiet: the mode
|
||||
# named as current, and a supported list that still omits it. `modes` is a
|
||||
# bare string here, matching the dump in the issue.
|
||||
QUIET_REP = {MODES_FIELD: "Quiet", SUPPORTED_FIELD: ADVERTISED}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The store itself
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_learns_a_current_mode_missing_from_the_supported_list():
|
||||
learned = LearnedModes()
|
||||
assert learned.observe(CONVENIENT, QUIET_REP) == ["Quiet"]
|
||||
assert learned.codes(CONVENIENT) == ["Quiet"]
|
||||
|
||||
|
||||
def test_relearning_the_same_mode_is_not_a_change():
|
||||
"""The device reports the same rep on every poll while it sits in the
|
||||
mode, so only the first one may report back as something to persist."""
|
||||
learned = LearnedModes()
|
||||
assert learned.observe(CONVENIENT, QUIET_REP) == ["Quiet"]
|
||||
assert learned.observe(CONVENIENT, QUIET_REP) == []
|
||||
assert learned.codes(CONVENIENT) == ["Quiet"]
|
||||
|
||||
|
||||
def test_an_advertised_mode_is_never_learned():
|
||||
learned = LearnedModes()
|
||||
rep = {MODES_FIELD: "Sleep", SUPPORTED_FIELD: ADVERTISED}
|
||||
assert learned.observe(CONVENIENT, rep) == []
|
||||
assert learned.codes(CONVENIENT) == []
|
||||
|
||||
|
||||
def test_a_rep_with_no_supported_list_teaches_nothing():
|
||||
""" "Missing from the list" is only meaningful against a list that
|
||||
exists -- a board publishing none would otherwise get an option list
|
||||
invented out of whatever it happened to be doing."""
|
||||
learned = LearnedModes()
|
||||
assert learned.observe(CONVENIENT, {MODES_FIELD: "Quiet"}) == []
|
||||
assert learned.codes(CONVENIENT) == []
|
||||
|
||||
|
||||
def test_the_allowlist_is_only_the_convenient_href():
|
||||
"""The guard that keeps this feature off resources whose current value
|
||||
isn't a selectable option -- an oven idling in 'NoOperation' on
|
||||
/mode/vs/0, whose codes would become permanent junk options in that
|
||||
unit's cook-mode select."""
|
||||
assert set(LEARNABLE) == {CONVENIENT}
|
||||
|
||||
|
||||
def test_two_subdevices_learn_separately():
|
||||
"""Keyed by the actual on-the-wire href (issue #177), so a composite
|
||||
appliance's second indoor unit doesn't inherit the first's gap."""
|
||||
learned = LearnedModes()
|
||||
learned.observe("/mode/convenient/vs/1", QUIET_REP)
|
||||
assert learned.codes("/mode/convenient/vs/1") == ["Quiet"]
|
||||
assert learned.codes(CONVENIENT) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"stored",
|
||||
[
|
||||
None,
|
||||
"not-a-dict",
|
||||
{"/mode/convenient/vs/0": None},
|
||||
{"/mode/convenient/vs/0": [""]},
|
||||
{"/mode/convenient/vs/0": [1, 2]},
|
||||
{"/mode/convenient/vs/0": {"x.com.samsung.da.supportedModes": ["Quiet"]}},
|
||||
],
|
||||
)
|
||||
def test_malformed_stored_data_restores_as_empty(stored):
|
||||
"""It round-trips through the config entry as plain JSON, so a
|
||||
hand-edited .storage file must not be able to break setup."""
|
||||
assert LearnedModes(stored).snapshot() == {}
|
||||
|
||||
|
||||
def test_well_formed_stored_data_restores():
|
||||
learned = LearnedModes({CONVENIENT: ["Quiet"]})
|
||||
assert learned.codes(CONVENIENT) == ["Quiet"]
|
||||
|
||||
|
||||
def test_clear_forgets_everything():
|
||||
learned = LearnedModes({CONVENIENT: ["Quiet"]})
|
||||
learned.clear()
|
||||
assert learned.snapshot() == {}
|
||||
|
||||
|
||||
def test_every_learnable_href_is_one_climate_resolves():
|
||||
"""climate._supported is the only consumer that unions learned codes
|
||||
in today, so an href added to LEARNABLE that climate never reads would
|
||||
be learned, persisted, and never offered anywhere. The coordinator
|
||||
enforces the device half of this (only hrefs a climate entity binds
|
||||
are learnable); this is the static half."""
|
||||
from custom_components.localthings.climate import (
|
||||
CONVENIENT_HREF,
|
||||
MODE_HREF,
|
||||
WIND_DIRECTION_HREF,
|
||||
WIND_STRENGTH_HREF,
|
||||
)
|
||||
|
||||
assert set(LEARNABLE) <= {MODE_HREF, WIND_STRENGTH_HREF, WIND_DIRECTION_HREF, CONVENIENT_HREF}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# End to end: device reports it -> HA offers it -> the entry remembers it
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _entry(hass: HomeAssistant, data: dict | None = None, options: dict | None = None):
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={**ENTRY_DATA, **(data or {})},
|
||||
options=options or {},
|
||||
unique_id="localthings_LEARNED-TEST",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
return entry
|
||||
|
||||
|
||||
async def _flush(hass: HomeAssistant) -> None:
|
||||
"""Let a persist scheduled from the applying thread land.
|
||||
|
||||
The coordinator marshals it with hass.add_job (the same way it
|
||||
marshals its state push), which goes through call_soon_threadsafe --
|
||||
async_block_till_done alone doesn't pick that up in this harness.
|
||||
"""
|
||||
await asyncio.sleep(0)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
async def _climate(hass: HomeAssistant, entry) -> tuple[LocalThingsCoordinator, Any]:
|
||||
coordinator = LocalThingsCoordinator(hass, entry)
|
||||
await _discover(coordinator, FIXTURE)
|
||||
return coordinator, LocalThingsClimate(coordinator, _climate_bound(coordinator, None))
|
||||
|
||||
|
||||
async def test_the_fixture_really_does_not_advertise_quiet(hass: HomeAssistant):
|
||||
"""Guard for every assertion below: they'd all pass vacuously against a
|
||||
unit that advertised Quiet in the first place."""
|
||||
_, entity = await _climate(hass, _entry(hass))
|
||||
assert "quiet" not in entity.preset_modes
|
||||
|
||||
|
||||
async def test_a_reported_mode_becomes_a_preset(hass: HomeAssistant):
|
||||
coordinator, entity = await _climate(hass, _entry(hass))
|
||||
coordinator._observe.apply(CONVENIENT, QUIET_REP, source="poll")
|
||||
|
||||
assert entity.preset_mode == "quiet"
|
||||
assert "quiet" in entity.preset_modes
|
||||
# Alongside, not instead of, what the device does advertise.
|
||||
assert "sleep" in entity.preset_modes
|
||||
|
||||
|
||||
async def test_a_learned_preset_is_writable(hass: HomeAssistant, monkeypatch):
|
||||
"""The reason the union belongs in _supported: async_set_preset_mode
|
||||
reverse-resolves the device code from the same list, so read and write
|
||||
are fixed by one change."""
|
||||
coordinator, entity = await _climate(hass, _entry(hass))
|
||||
coordinator._observe.apply(CONVENIENT, QUIET_REP, source="poll")
|
||||
|
||||
sent: list = []
|
||||
|
||||
async def _record(bound, payload):
|
||||
sent.append(payload)
|
||||
|
||||
monkeypatch.setattr(coordinator, "async_send_command", _record)
|
||||
await entity.async_set_preset_mode("quiet")
|
||||
assert sent == [("preset", "Quiet")]
|
||||
|
||||
|
||||
async def test_learning_persists_onto_the_config_entry(hass: HomeAssistant):
|
||||
entry = _entry(hass)
|
||||
coordinator, _ = await _climate(hass, entry)
|
||||
coordinator._observe.apply(CONVENIENT, QUIET_REP, source="poll")
|
||||
await _flush(hass)
|
||||
|
||||
assert entry.data[CONF_LEARNED_MODES] == {CONVENIENT: ["Quiet"]}
|
||||
|
||||
|
||||
async def test_a_learned_preset_survives_a_restart(hass: HomeAssistant):
|
||||
"""The point of persisting: the unit only names Quiet while it is in
|
||||
Quiet, so a restart in any other mode would otherwise lose it until
|
||||
someone reached for the physical remote again."""
|
||||
entry = _entry(hass, data={CONF_LEARNED_MODES: {CONVENIENT: ["Quiet"]}})
|
||||
_, entity = await _climate(hass, entry)
|
||||
|
||||
# Nothing applied this run -- the fixture's own rep says Off, and its
|
||||
# supportedModes still omits Quiet.
|
||||
assert entity.preset_mode == "none"
|
||||
assert "quiet" in entity.preset_modes
|
||||
|
||||
|
||||
async def test_a_device_with_no_climate_entity_learns_nothing(hass: HomeAssistant):
|
||||
"""The href alone isn't a sufficient key: the dehumidifier registry
|
||||
declares this same /mode/convenient/vs/0 explicitly unmodeled (no live
|
||||
current-value field), so a code learned there would be persisted for a
|
||||
resource nothing will ever offer."""
|
||||
entry = _entry(hass)
|
||||
coordinator = LocalThingsCoordinator(hass, entry)
|
||||
await _discover(coordinator, "dehumidifier")
|
||||
assert not any(isinstance(b.desc, ClimateDesc) for b in coordinator.bound)
|
||||
|
||||
coordinator._observe.apply(
|
||||
CONVENIENT, {MODES_FIELD: "Quiet", SUPPORTED_FIELD: ADVERTISED}, source="poll"
|
||||
)
|
||||
|
||||
assert coordinator.learned_snapshot() == {}
|
||||
|
||||
|
||||
async def test_an_optimistic_write_teaches_nothing(hass: HomeAssistant):
|
||||
"""An optimistic cache entry is the value this integration just wrote,
|
||||
not something the device reported."""
|
||||
coordinator, _ = await _climate(hass, _entry(hass))
|
||||
coordinator._observe.apply(CONVENIENT, QUIET_REP, source="optimistic")
|
||||
|
||||
assert coordinator.learned_snapshot() == {}
|
||||
|
||||
|
||||
async def test_a_partial_notify_still_learns(hass: HomeAssistant):
|
||||
"""An OBSERVE notify can carry `modes` alone (issue #27). Learning sees
|
||||
the merged rep, so the supported list from the last full poll is still
|
||||
there to judge it against."""
|
||||
coordinator, entity = await _climate(hass, _entry(hass))
|
||||
coordinator._observe.apply(CONVENIENT, {MODES_FIELD: "Quiet"}, source="observe")
|
||||
|
||||
assert "quiet" in entity.preset_modes
|
||||
|
||||
|
||||
async def test_the_option_turns_off_both_halves(hass: HomeAssistant):
|
||||
"""Off means the stock list, immediately -- nothing new is learned and
|
||||
nothing already learned is offered."""
|
||||
entry = _entry(
|
||||
hass,
|
||||
data={CONF_LEARNED_MODES: {CONVENIENT: ["Smart"]}},
|
||||
options={CONF_LEARN_MODES: False},
|
||||
)
|
||||
coordinator, entity = await _climate(hass, entry)
|
||||
coordinator._observe.apply(CONVENIENT, QUIET_REP, source="poll")
|
||||
await _flush(hass)
|
||||
|
||||
assert "smart" not in entity.preset_modes
|
||||
assert "quiet" not in entity.preset_modes
|
||||
# Kept, not discarded -- turning the option back on restores it, and
|
||||
# nothing new was written while it was off.
|
||||
assert coordinator.learned_snapshot() == {CONVENIENT: ["Smart"]}
|
||||
assert entry.data[CONF_LEARNED_MODES] == {CONVENIENT: ["Smart"]}
|
||||
|
||||
|
||||
async def test_forgetting_clears_the_store_and_the_entry(hass: HomeAssistant):
|
||||
entry = _entry(hass, data={CONF_LEARNED_MODES: {CONVENIENT: ["Quiet"]}})
|
||||
coordinator, entity = await _climate(hass, entry)
|
||||
|
||||
coordinator.forget_learned_modes()
|
||||
await _flush(hass)
|
||||
|
||||
assert "quiet" not in entity.preset_modes
|
||||
assert entry.data[CONF_LEARNED_MODES] == {}
|
||||
|
||||
|
||||
async def test_forgetting_clears_a_record_the_store_rejected(hass: HomeAssistant):
|
||||
"""A malformed persisted record is dropped on restore, so the store is
|
||||
empty while the entry still holds it. Forget has to reach it anyway --
|
||||
it's the only control that can."""
|
||||
entry = _entry(hass, data={CONF_LEARNED_MODES: {CONVENIENT: None}})
|
||||
coordinator, _ = await _climate(hass, entry)
|
||||
assert coordinator.learned_snapshot() == {}
|
||||
|
||||
coordinator.forget_learned_modes()
|
||||
await _flush(hass)
|
||||
|
||||
assert entry.data[CONF_LEARNED_MODES] == {}
|
||||
|
||||
|
||||
async def test_diagnostics_report_what_was_learned(
|
||||
hass: HomeAssistant,
|
||||
enable_custom_integrations,
|
||||
):
|
||||
"""Kept out of the `resources` dump on purpose -- that stays exactly
|
||||
what the device said, so a triager can still see the gap."""
|
||||
from custom_components.localthings.diagnostics import (
|
||||
async_get_config_entry_diagnostics,
|
||||
)
|
||||
|
||||
entry = _entry(hass)
|
||||
coordinator, _ = await _climate(hass, entry)
|
||||
coordinator._observe.apply(CONVENIENT, QUIET_REP, source="poll")
|
||||
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
|
||||
|
||||
diag = await async_get_config_entry_diagnostics(hass, cast(Any, entry))
|
||||
|
||||
assert diag["learned_modes"] == {"enabled": True, "codes": {CONVENIENT: ["Quiet"]}}
|
||||
assert diag["resources"][CONVENIENT][SUPPORTED_FIELD] == ADVERTISED
|
||||
@@ -0,0 +1,636 @@
|
||||
"""Tests for the write_resource/read_resource services (issue #300) and the
|
||||
options-flow debug panel now that it goes through write_resource instead of
|
||||
calling coordinator.async_raw_write directly (config_flow.py). See
|
||||
tests/test_coordinator_raw_write.py for the underlying single-write
|
||||
primitive's own session/validation tests -- these focus on the service
|
||||
layer: device target resolution, subdevice href translation, ordered
|
||||
multi-write sequencing, settle/verify_after, and the options-flow rewiring.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import cbor2
|
||||
import pytest
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.localthings.config_flow import LocalThingsOptionsFlow
|
||||
from custom_components.localthings.const import (
|
||||
CONF_HOST,
|
||||
CONF_LEAF_CERT_PEM,
|
||||
CONF_LEAF_KEY_PEM,
|
||||
CONF_PORT,
|
||||
DOMAIN,
|
||||
SERVICE_READ_RESOURCE,
|
||||
SERVICE_WRITE_RESOURCE,
|
||||
)
|
||||
from custom_components.localthings.coordinator import LocalThingsCoordinator
|
||||
from custom_components.localthings.registry.subdevices import Subdevice
|
||||
from custom_components.localthings.services import async_setup_services
|
||||
|
||||
ENTRY_DATA = {
|
||||
CONF_HOST: "10.0.0.199",
|
||||
CONF_PORT: 49154,
|
||||
CONF_LEAF_CERT_PEM: "-----BEGIN CERTIFICATE-----\nTEST-LEAF\n-----END CERTIFICATE-----",
|
||||
CONF_LEAF_KEY_PEM: "-----BEGIN PRIVATE KEY-----\nTEST-LEAF-KEY\n-----END PRIVATE KEY-----",
|
||||
}
|
||||
|
||||
_SLEEP_TARGET = "custom_components.localthings.coordinator.asyncio.sleep"
|
||||
|
||||
|
||||
class _FakeSession:
|
||||
"""Stand-in for DtlsCoapSession: records every POST verbatim and answers
|
||||
GET from a per-href queue of canned representations, so a test can model
|
||||
a value that changes across successive reads of the same href (the
|
||||
write's own follow-up GET vs. a later verify_after re-read) -- no real
|
||||
DTLS/network involved. Modeled on test_coordinator_raw_write.py's
|
||||
_FakeRawWriteSession, extended for multi-step sequences."""
|
||||
|
||||
def __init__(self, post_code: int = 0x44):
|
||||
self.post_calls: list[tuple[list[str], bytes]] = []
|
||||
self.get_calls: list[list[str]] = []
|
||||
self._post_code = post_code
|
||||
self._get_reps: dict[str, list[dict]] = {}
|
||||
|
||||
def queue_get(self, href: str, rep: dict) -> None:
|
||||
"""Queue one more canned rep for `href`'s next GET. Once an href's
|
||||
queue is down to one entry, that entry keeps answering every
|
||||
further GET -- a test only needs to queue the values that
|
||||
actually change across calls."""
|
||||
self._get_reps.setdefault(href.strip("/"), []).append(rep)
|
||||
|
||||
def post(self, path_segs, payload, timeout=None):
|
||||
self.post_calls.append((list(path_segs), payload))
|
||||
return self._post_code, b""
|
||||
|
||||
def get(self, path_segs, timeout=None):
|
||||
self.get_calls.append(list(path_segs))
|
||||
key = "/".join(path_segs)
|
||||
queue = self._get_reps.get(key)
|
||||
if not queue:
|
||||
return 0x45, cbor2.dumps({})
|
||||
rep = queue.pop(0) if len(queue) > 1 else queue[0]
|
||||
return 0x45, cbor2.dumps(rep)
|
||||
|
||||
def pace(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def coordinator(hass: HomeAssistant) -> LocalThingsCoordinator:
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data=ENTRY_DATA,
|
||||
unique_id="localthings_SERVICES-TEST",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
coord = LocalThingsCoordinator(hass, entry)
|
||||
# async_raw_write_sequence kicks a refresh after the write; a real
|
||||
# refresh would try to poll a session that doesn't exist for this unit
|
||||
# test, so replace it with a no-op the same way
|
||||
# test_coordinator_raw_write.py does.
|
||||
coord.async_request_refresh = AsyncMock()
|
||||
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coord
|
||||
async_setup_services(hass)
|
||||
return coord
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def device_id(hass: HomeAssistant, coordinator: LocalThingsCoordinator) -> str:
|
||||
"""Register MAIN's HA device under the same identifiers a real config
|
||||
entry setup would have used (coordinator.device_info)."""
|
||||
dev_reg = dr.async_get(hass)
|
||||
device = dev_reg.async_get_or_create(
|
||||
config_entry_id=coordinator._entry.entry_id,
|
||||
identifiers=coordinator.device_info["identifiers"],
|
||||
)
|
||||
return device.id
|
||||
|
||||
|
||||
async def _call_write(hass: HomeAssistant, device: str, **data):
|
||||
return await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_WRITE_RESOURCE,
|
||||
data,
|
||||
target={"device_id": device},
|
||||
blocking=True,
|
||||
return_response=True,
|
||||
)
|
||||
|
||||
|
||||
async def _call_read(hass: HomeAssistant, device: str, **data):
|
||||
return await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_READ_RESOURCE,
|
||||
data,
|
||||
target={"device_id": device},
|
||||
blocking=True,
|
||||
return_response=True,
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# write_resource: ordered multi-write sequencing
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_write_resource_posts_in_order_with_exact_bodies(hass, coordinator, device_id):
|
||||
fake = _FakeSession(post_code=0x44)
|
||||
coordinator._session = fake
|
||||
|
||||
writes = [
|
||||
{"href": "/mode/vs/0", "payload": {"a": 1}},
|
||||
{"href": "/washer/vs/0", "payload": {"b": 2}},
|
||||
{"href": "/mode/vs/0", "payload": {"a": 3}},
|
||||
]
|
||||
response = await _call_write(hass, device_id, writes=writes)
|
||||
|
||||
assert [path for path, _ in fake.post_calls] == [
|
||||
["mode", "vs", "0"],
|
||||
["washer", "vs", "0"],
|
||||
["mode", "vs", "0"],
|
||||
]
|
||||
assert [cbor2.loads(body) for _, body in fake.post_calls] == [
|
||||
{"a": 1},
|
||||
{"b": 2},
|
||||
{"a": 3},
|
||||
]
|
||||
assert response is not None
|
||||
assert response["device_id"] == device_id
|
||||
assert len(response["results"]) == 3
|
||||
for result, write in zip(response["results"], writes, strict=True):
|
||||
assert result["href"] == write["href"]
|
||||
assert result["actual_href"] == write["href"] # MAIN -> identity transform
|
||||
assert result["raw_code"] == 0x44
|
||||
assert result["code"] == "2.04"
|
||||
assert result["accepted"] is True
|
||||
coordinator.async_request_refresh.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_write_resource_settle_honored_between_writes(hass, coordinator, device_id):
|
||||
"""settle waits *before the next write*, not after the last one --
|
||||
asserted on the recorded durations rather than a real sleep."""
|
||||
fake = _FakeSession()
|
||||
coordinator._session = fake
|
||||
|
||||
writes = [
|
||||
{"href": "/a/vs/0", "payload": {"x": 1}, "settle": 2},
|
||||
{"href": "/b/vs/0", "payload": {"x": 2}, "settle": 5},
|
||||
{"href": "/c/vs/0", "payload": {"x": 3}, "settle": 9},
|
||||
]
|
||||
with patch(_SLEEP_TARGET, new_callable=AsyncMock) as mock_sleep:
|
||||
await _call_write(hass, device_id, writes=writes)
|
||||
|
||||
assert [call.args[0] for call in mock_sleep.call_args_list] == [2.0, 5.0]
|
||||
|
||||
|
||||
async def test_write_resource_holds_the_session_across_settle_by_default(
|
||||
hass, coordinator, device_id
|
||||
):
|
||||
"""The default keeps the session for the whole sequence so nothing lands
|
||||
between two writes -- asserted on the lock's real state during the wait,
|
||||
not merely on the flag being accepted."""
|
||||
coordinator._session = _FakeSession()
|
||||
locked_during_settle = []
|
||||
|
||||
async def _record(_delay):
|
||||
locked_during_settle.append(coordinator._session_lock.locked())
|
||||
|
||||
with patch(_SLEEP_TARGET, new=_record):
|
||||
await _call_write(
|
||||
hass,
|
||||
device_id,
|
||||
writes=[
|
||||
{"href": "/a/vs/0", "payload": {"x": 1}, "settle": 2},
|
||||
{"href": "/b/vs/0", "payload": {"x": 2}},
|
||||
],
|
||||
)
|
||||
|
||||
assert locked_during_settle == [True]
|
||||
# ...and it's handed back afterward, rather than leaked to the next call.
|
||||
assert not coordinator._session_lock.locked()
|
||||
|
||||
|
||||
async def test_write_resource_releases_the_session_across_settle_when_asked(
|
||||
hass, coordinator, device_id
|
||||
):
|
||||
"""hold_session_lock=False frees the session across the waits, so polls
|
||||
and entity writes keep working through a long sequence."""
|
||||
coordinator._session = _FakeSession()
|
||||
locked_during_settle = []
|
||||
|
||||
async def _record(_delay):
|
||||
locked_during_settle.append(coordinator._session_lock.locked())
|
||||
|
||||
with patch(_SLEEP_TARGET, new=_record):
|
||||
response = await _call_write(
|
||||
hass,
|
||||
device_id,
|
||||
writes=[
|
||||
{"href": "/a/vs/0", "payload": {"x": 1}, "settle": 2},
|
||||
{"href": "/b/vs/0", "payload": {"x": 2}},
|
||||
],
|
||||
hold_session_lock=False,
|
||||
)
|
||||
|
||||
assert locked_during_settle == [False]
|
||||
assert not coordinator._session_lock.locked()
|
||||
# Both writes still go out, in order -- only the locking differs.
|
||||
assert [r["href"] for r in response["results"]] == ["/a/vs/0", "/b/vs/0"]
|
||||
|
||||
|
||||
async def test_write_resource_changed_true_when_readback_matches_payload(
|
||||
hass, coordinator, device_id
|
||||
):
|
||||
fake = _FakeSession()
|
||||
fake.queue_get("mode/vs/0", {"x.field": "target"})
|
||||
coordinator._session = fake
|
||||
|
||||
response = await _call_write(
|
||||
hass, device_id, writes=[{"href": "/mode/vs/0", "payload": {"x.field": "target"}}]
|
||||
)
|
||||
|
||||
assert response["results"][0]["changed"] is True
|
||||
|
||||
|
||||
async def test_write_resource_changed_false_when_readback_differs(hass, coordinator, device_id):
|
||||
fake = _FakeSession()
|
||||
fake.queue_get("mode/vs/0", {"x.field": "unchanged"})
|
||||
coordinator._session = fake
|
||||
|
||||
response = await _call_write(
|
||||
hass, device_id, writes=[{"href": "/mode/vs/0", "payload": {"x.field": "target"}}]
|
||||
)
|
||||
|
||||
assert response["results"][0]["changed"] is False
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# verify_after: the delayed re-read this feature exists for (issue #300)
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_write_resource_verify_after_reports_held(hass, coordinator, device_id):
|
||||
fake = _FakeSession()
|
||||
fake.queue_get("mode/vs/0", {"x.field": "target"}) # write's own follow-up read
|
||||
fake.queue_get("mode/vs/0", {"x.field": "target"}) # verify_after re-read: held
|
||||
coordinator._session = fake
|
||||
|
||||
with patch(_SLEEP_TARGET, new_callable=AsyncMock) as mock_sleep:
|
||||
response = await _call_write(
|
||||
hass,
|
||||
device_id,
|
||||
writes=[{"href": "/mode/vs/0", "payload": {"x.field": "target"}}],
|
||||
verify_after=30,
|
||||
)
|
||||
|
||||
assert 30.0 in [call.args[0] for call in mock_sleep.call_args_list]
|
||||
verified = response["verified"]["/mode/vs/0"]
|
||||
assert verified["held"] is True
|
||||
assert verified["rep"] == {"x.field": "target"}
|
||||
|
||||
|
||||
async def test_write_resource_verify_after_reports_reverted(hass, coordinator, device_id):
|
||||
"""Issue #300's own symptom: a Samsung wall oven board answers 2.04
|
||||
Changed to a settings write while idle and then silently reverts it
|
||||
once the follow-up read has already come back clean. verify_after's
|
||||
whole purpose is catching exactly this -- `changed` (immediate) and
|
||||
`held` (delayed) must be able to disagree."""
|
||||
fake = _FakeSession()
|
||||
fake.queue_get("mode/vs/0", {"x.field": "target"}) # looks accepted right after the write
|
||||
fake.queue_get("mode/vs/0", {"x.field": "original"}) # reverted by the time verify_after fires
|
||||
coordinator._session = fake
|
||||
|
||||
with patch(_SLEEP_TARGET, new_callable=AsyncMock):
|
||||
response = await _call_write(
|
||||
hass,
|
||||
device_id,
|
||||
writes=[{"href": "/mode/vs/0", "payload": {"x.field": "target"}}],
|
||||
verify_after=30,
|
||||
)
|
||||
|
||||
assert response["results"][0]["changed"] is True
|
||||
verified = response["verified"]["/mode/vs/0"]
|
||||
assert verified["held"] is False
|
||||
assert verified["rep"] == {"x.field": "original"}
|
||||
|
||||
|
||||
async def test_write_resource_no_verified_key_when_verify_after_is_zero(
|
||||
hass, coordinator, device_id
|
||||
):
|
||||
fake = _FakeSession()
|
||||
coordinator._session = fake
|
||||
|
||||
response = await _call_write(
|
||||
hass, device_id, writes=[{"href": "/mode/vs/0", "payload": {"x": 1}}]
|
||||
)
|
||||
|
||||
assert "verified" not in response
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Device target resolution
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_write_resource_zero_devices_rejected(hass, coordinator):
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_WRITE_RESOURCE,
|
||||
{"writes": [{"href": "/a/vs/0", "payload": {"x": 1}}]},
|
||||
blocking=True,
|
||||
return_response=True,
|
||||
)
|
||||
|
||||
|
||||
async def test_write_resource_two_devices_rejected(hass, coordinator, device_id):
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_WRITE_RESOURCE,
|
||||
{"writes": [{"href": "/a/vs/0", "payload": {"x": 1}}]},
|
||||
target={"device_id": [device_id, "some-other-unrelated-device-id"]},
|
||||
blocking=True,
|
||||
return_response=True,
|
||||
)
|
||||
|
||||
|
||||
async def test_write_resource_unresolvable_device_rejected(hass, coordinator):
|
||||
"""The device exists in the registry but no loaded coordinator claims
|
||||
it -- e.g. a device belonging to a different integration entirely."""
|
||||
dev_reg = dr.async_get(hass)
|
||||
other_entry = MockConfigEntry(domain="other_domain")
|
||||
other_entry.add_to_hass(hass)
|
||||
device = dev_reg.async_get_or_create(
|
||||
config_entry_id=other_entry.entry_id,
|
||||
identifiers={("other_domain", "unrelated")},
|
||||
)
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await _call_write(hass, device.id, writes=[{"href": "/a/vs/0", "payload": {"x": 1}}])
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Subdevice href translation (issue #177)
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_write_resource_translates_href_for_indexed_subdevice(hass, coordinator):
|
||||
sub = Subdevice(kind="indexed", key="1", seed_path=("device", "1"))
|
||||
coordinator.subdevices = [sub]
|
||||
dev_reg = dr.async_get(hass)
|
||||
device = dev_reg.async_get_or_create(
|
||||
config_entry_id=coordinator._entry.entry_id,
|
||||
identifiers=coordinator.device_info_for(sub)["identifiers"],
|
||||
)
|
||||
fake = _FakeSession()
|
||||
coordinator._session = fake
|
||||
|
||||
response = await _call_write(
|
||||
hass, device.id, writes=[{"href": "/mode/vs/0", "payload": {"x": 1}}]
|
||||
)
|
||||
|
||||
assert fake.post_calls[0][0] == ["mode", "vs", "1"]
|
||||
result = response["results"][0]
|
||||
assert result["href"] == "/mode/vs/0"
|
||||
assert result["actual_href"] == "/mode/vs/1"
|
||||
|
||||
|
||||
async def test_write_resource_normalizes_href_before_subdevice_translation(hass, coordinator):
|
||||
"""A trailing slash must not silently retarget the write at the master.
|
||||
|
||||
`Subdevice.to_actual` is a textual transform that rewrites only a
|
||||
trailing '0' segment, so '/mode/vs/0/' passes through it unchanged and
|
||||
then normalizes downstream to the master's '/mode/vs/0' -- landing on
|
||||
the wrong cavity while still answering 2.04. Nothing in the response
|
||||
would have given that away.
|
||||
"""
|
||||
sub = Subdevice(kind="indexed", key="1", seed_path=("device", "1"))
|
||||
coordinator.subdevices = [sub]
|
||||
dev_reg = dr.async_get(hass)
|
||||
device = dev_reg.async_get_or_create(
|
||||
config_entry_id=coordinator._entry.entry_id,
|
||||
identifiers=coordinator.device_info_for(sub)["identifiers"],
|
||||
)
|
||||
fake = _FakeSession()
|
||||
coordinator._session = fake
|
||||
|
||||
response = await _call_write(
|
||||
hass, device.id, writes=[{"href": "/mode/vs/0/", "payload": {"x": 1}}]
|
||||
)
|
||||
|
||||
assert fake.post_calls[0][0] == ["mode", "vs", "1"]
|
||||
result = response["results"][0]
|
||||
assert result["href"] == "/mode/vs/0"
|
||||
assert result["actual_href"] == "/mode/vs/1"
|
||||
|
||||
|
||||
async def test_write_resource_verified_is_keyed_by_canonical_href_for_subdevice(hass, coordinator):
|
||||
"""`verified` promises canonical keys; the coordinator reports actual
|
||||
ones, so the translation back has to line up with what was sent."""
|
||||
sub = Subdevice(kind="indexed", key="1", seed_path=("device", "1"))
|
||||
coordinator.subdevices = [sub]
|
||||
dev_reg = dr.async_get(hass)
|
||||
device = dev_reg.async_get_or_create(
|
||||
config_entry_id=coordinator._entry.entry_id,
|
||||
identifiers=coordinator.device_info_for(sub)["identifiers"],
|
||||
)
|
||||
fake = _FakeSession()
|
||||
fake.queue_get("/mode/vs/1", {"x": 1})
|
||||
coordinator._session = fake
|
||||
|
||||
response = await _call_write(
|
||||
hass,
|
||||
device.id,
|
||||
writes=[{"href": "/mode/vs/0", "payload": {"x": 1}}],
|
||||
verify_after=1,
|
||||
)
|
||||
|
||||
assert list(response["verified"]) == ["/mode/vs/0"]
|
||||
assert response["verified"]["/mode/vs/0"]["held"] is True
|
||||
|
||||
|
||||
async def test_write_resource_failure_midway_names_the_writes_that_landed(
|
||||
hass, coordinator, device_id
|
||||
):
|
||||
"""A drop partway through leaves the appliance holding a partial
|
||||
sequence; the error has to say how far it got, or the operator can't
|
||||
tell what state the device is in without starting over blind."""
|
||||
|
||||
class _DropsOnSecondWrite(_FakeSession):
|
||||
def post(self, path_segs, payload, timeout=None):
|
||||
if len(self.post_calls) == 1:
|
||||
raise OSError("session dropped")
|
||||
return super().post(path_segs, payload, timeout)
|
||||
|
||||
coordinator._session = _DropsOnSecondWrite()
|
||||
|
||||
with pytest.raises(HomeAssistantError) as excinfo:
|
||||
await _call_write(
|
||||
hass,
|
||||
device_id,
|
||||
writes=[
|
||||
{"href": "/mode/vs/0", "payload": {"a": 1}},
|
||||
{"href": "/temperatures/vs/0", "payload": {"b": 2}},
|
||||
{"href": "/operational/state/vs/0", "payload": {"c": 3}},
|
||||
],
|
||||
)
|
||||
|
||||
message = str(excinfo.value)
|
||||
assert "1 of 3" in message
|
||||
assert "/mode/vs/0" in message
|
||||
# Entities still get pulled back in line with whatever did land.
|
||||
coordinator.async_request_refresh.assert_awaited()
|
||||
|
||||
|
||||
async def test_write_resource_held_is_none_when_the_verify_read_fails(hass, coordinator, device_id):
|
||||
"""A re-read that doesn't come back is not evidence of a revert.
|
||||
|
||||
_raw_read_blocking answers a non-2.05 with an empty rep, and every
|
||||
payload comparison against {} is False -- so without this, a 4.04 or a
|
||||
dropped verify read is reported as `held: false`, indistinguishable
|
||||
from the board quietly putting the old value back. That distinction is
|
||||
the whole reason verify_after exists (issue #300).
|
||||
"""
|
||||
|
||||
class _FailingVerifyRead(_FakeSession):
|
||||
def get(self, path_segs, timeout=None):
|
||||
self.get_calls.append(list(path_segs))
|
||||
# The write's own follow-up GET succeeds; the later verify
|
||||
# re-read of the same href is the one that fails.
|
||||
if len(self.get_calls) == 1:
|
||||
return 0x45, cbor2.dumps({"x": 1})
|
||||
return 0x84, b""
|
||||
|
||||
coordinator._session = _FailingVerifyRead()
|
||||
|
||||
response = await _call_write(
|
||||
hass,
|
||||
device_id,
|
||||
writes=[{"href": "/mode/vs/0", "payload": {"x": 1}}],
|
||||
verify_after=1,
|
||||
)
|
||||
|
||||
verified = response["verified"]["/mode/vs/0"]
|
||||
assert verified["held"] is None
|
||||
assert verified["code"] == "4.04"
|
||||
# The immediate readback still saw the value land -- only the delayed
|
||||
# confirmation is unknown, and the two must not be conflated.
|
||||
assert response["results"][0]["changed"] is True
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Validation caps
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_write_resource_rejects_more_than_ten_writes(hass, coordinator, device_id):
|
||||
writes = [{"href": f"/x/vs/{i}", "payload": {"a": i}} for i in range(11)]
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await _call_write(hass, device_id, writes=writes)
|
||||
|
||||
|
||||
async def test_write_resource_rejects_settle_above_thirty_seconds(hass, coordinator, device_id):
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await _call_write(
|
||||
hass,
|
||||
device_id,
|
||||
writes=[{"href": "/a/vs/0", "payload": {"x": 1}, "settle": 31}],
|
||||
)
|
||||
|
||||
|
||||
async def test_write_resource_rejects_empty_payload(hass, coordinator, device_id):
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await _call_write(hass, device_id, writes=[{"href": "/a/vs/0", "payload": {}}])
|
||||
|
||||
|
||||
async def test_write_resource_rejects_non_dict_payload(hass, coordinator, device_id):
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await _call_write(
|
||||
hass, device_id, writes=[{"href": "/a/vs/0", "payload": ["not", "a", "dict"]}]
|
||||
)
|
||||
|
||||
|
||||
async def test_write_resource_rejects_empty_href(hass, coordinator, device_id):
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await _call_write(hass, device_id, writes=[{"href": "", "payload": {"x": 1}}])
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# read_resource
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_read_resource_with_href_does_live_get(hass, coordinator, device_id):
|
||||
fake = _FakeSession()
|
||||
fake.queue_get("mode/vs/0", {"x.field": "live"})
|
||||
coordinator._session = fake
|
||||
|
||||
response = await _call_read(hass, device_id, href="/mode/vs/0")
|
||||
|
||||
assert fake.get_calls == [["mode", "vs", "0"]]
|
||||
assert response["href"] == "/mode/vs/0"
|
||||
assert response["actual_href"] == "/mode/vs/0"
|
||||
assert response["rep"] == {"x.field": "live"}
|
||||
|
||||
|
||||
async def test_read_resource_without_href_returns_cached_snapshot_and_does_not_get(
|
||||
hass, coordinator, device_id
|
||||
):
|
||||
fake = _FakeSession()
|
||||
coordinator._session = fake
|
||||
# Seed the cache the way a poll would -- the fake session's `get` is
|
||||
# never touched by this test.
|
||||
coordinator._observe.apply("/mode/vs/0", {"x.field": "cached"}, source="poll")
|
||||
|
||||
response = await _call_read(hass, device_id)
|
||||
|
||||
assert fake.get_calls == []
|
||||
assert response["resources"]["/mode/vs/0"] == {"x.field": "cached"}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Options-flow debug panel, rewired onto write_resource (issue #300)
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_options_flow_debug_write_goes_through_write_resource_service(
|
||||
hass, coordinator, device_id
|
||||
):
|
||||
"""Drives LocalThingsOptionsFlow's real step methods directly (rather
|
||||
than through hass.config_entries.options.async_init/async_configure,
|
||||
which needs the integration resolvable through HA's loader -- not
|
||||
exercised by any test in this repo and orthogonal to what this test is
|
||||
actually checking): the panel's async_step_debug_edit must call the
|
||||
write_resource service and get back a result the rest of the flow can
|
||||
render, not coord.async_raw_write directly."""
|
||||
fake = _FakeSession(post_code=0x44)
|
||||
fake.queue_get("course/vs/0", {"x.field": "after"})
|
||||
coordinator._session = fake
|
||||
|
||||
flow = LocalThingsOptionsFlow()
|
||||
flow.hass = hass
|
||||
flow.handler = coordinator._entry.entry_id
|
||||
|
||||
write_result = await flow.async_step_debug_write({"href": "/course/vs/0"})
|
||||
assert write_result["step_id"] == "debug_edit"
|
||||
|
||||
edit_result = await flow.async_step_debug_edit({"payload": {"x.com.samsung.da.field": "value"}})
|
||||
assert edit_result["step_id"] == "debug_result"
|
||||
placeholders = edit_result["description_placeholders"]
|
||||
assert placeholders is not None
|
||||
assert placeholders["code"] == "2.04 (0x44)"
|
||||
|
||||
assert len(fake.post_calls) == 1
|
||||
posted_path, posted_body = fake.post_calls[0]
|
||||
assert posted_path == ["course", "vs", "0"]
|
||||
assert cbor2.loads(posted_body) == {"x.com.samsung.da.field": "value"}
|
||||
|
||||
assert len(fake.post_calls) == 1
|
||||
posted_path, posted_body = fake.post_calls[0]
|
||||
assert posted_path == ["course", "vs", "0"]
|
||||
assert cbor2.loads(posted_body) == {"x.com.samsung.da.field": "value"}
|
||||
Reference in new issue
Block a user