Rebuild device discovery on the ClientHello probe and resolve identity up front

Two problems, one setup path.

Port detection (issue #211): the config flow found the DTLS port by
elimination -- a 1-byte UDP probe can't tell a silent port from a real
DTLS server, so every port it couldn't rule out got a full certificate
handshake, and every false positive cost the whole 12s HANDSHAKE_TIMEOUT_S
before the next was tried. Adding an appliance took 30-40s.

smartthings-local 0.1.2 ships a stateless ClientHello probe that settles
this positively: a real DTLS server answers with a HelloVerifyRequest in
~1 RTT, and per RFC 6347 4.2.1 it does so without allocating association
state, so the probe leaves nothing behind on the appliance. The whole
49152-49160 range is probed at once and exactly one confirmed port is
given a certificate handshake. Fanning out is safe here in a way racing
real handshakes is not -- each probe is bounded by a 3s budget, so the
pool costs one probe's wall clock rather than the sum of the range, with
no losing threads left running behind us.

The UDP sweep stays as the fallback for when the probe confirms nothing:
it errs in the opposite direction (it reports everything it can't rule
out), so it still surfaces a device on a path that eats our ClientHello,
and it keeps its issue #192 preferred-port rescue.

Port detection now runs first and needs no credentials, so an unreachable
host fails before any round trip to Samsung's cloud. And a second
appliance reuses the existing entry's leaf cert rather than re-minting --
every device accepts the same one -- which makes adding one independent
of Samsung-cloud reachability. A confirmed-live device rejecting the
reused leaf (the UUID does rotate) re-mints and retries once, so reuse
stays self-correcting; a timeout doesn't, since a fresh cert can't fix
nothing answering.

Identity (issue #236): the coordinator seeded device_serial with the
configured host and only replaced it after the first successful poll. But
device_serial mints *permanent* registry keys -- entity unique_ids and
device identifiers -- so anything registering before that poll returned
was written into the registry keyed on the IP address forever. The
connection-mode sensor is added unconditionally rather than from `bound`,
so it was the reliable victim: when the serial-keyed identity appeared
moments later HA created a second device and entity, and the IP-keyed
pair was orphaned. Deleting them didn't help; the next restart that lost
the race recreated them.

The probe already learns the identity, so store it on the config entry --
serial, model, manufacturer, device type. The coordinator seeds
device_serial and its DeviceInfo from those at construction, so keys are
correct from the first entity that registers even if the first poll is
slow or fails outright. There is no placeholder left to correct.

Discovery now treats the registered identity as authoritative rather than
re-keying a device that already has registry entries; it adopts and
persists the polled identity only for an entry that has none, and warns
if a different appliance answers on the same IP.

Entry version 1 -> 2 recovers the serial from the entry's unique_id (the
flow has always keyed it on the probe's serial) and repairs what the old
registration orphaned: IP-keyed devices and entities are rewritten in
place where the serial-keyed key is free -- keeping entity_id, name, area
and every automation referencing them -- and removed where both exist,
since the IP-keyed one has been dead since the restart that made it.
Placeholder-serial boards (issues #83/#189) were keyed two ways at once,
`host:port` on the entry and `host` in the registry; migration collapses
the entry onto the registry's form. One resolve_serial() now serves both
sides, so they can't drift apart again.

The remaining step in the desired pipeline -- probe for subdevices, then
register devices, then populate entities -- already holds:
_enumerate_subdevices_blocking runs before _run_discovery, which runs
before platforms are forwarded. Duplicating it in the config flow would
mean re-running Pattern B's per-href fallback probe, which is the
opposite of what issue #211 is about.
This commit is contained in:
Marc Billow committed 2026-08-03 20:14:54 +00:00
1 parent cdaff4a1ca
commit 15be379243
18 files changed
+1186 -210

No files matched your search

+114 -2
View File
@@ -6,16 +6,128 @@ import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import Event, HomeAssistant
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 .const import DOMAIN, PLATFORMS
from .const import CONF_HOST, CONF_PORT, CONF_SERIAL, DOMAIN, PLATFORMS
from .coordinator import LocalThingsCoordinator
_LOGGER = logging.getLogger(__name__)
def _serial_from_unique_id(entry: ConfigEntry) -> str | None:
"""The device identity a pre-v2 entry was created with.
The config flow has always keyed the entry's unique_id on the serial the
probe read (`localthings_<serial>`), so that string is the identity the
entry's registry entries were minted from -- there is no need to reach the
device to recover it.
One wrinkle: for a board reporting a placeholder serial (issues #83/#189)
the two sides used to disagree. The config flow fell back to `host:port`
while the coordinator fell back to `host`, so the entry and its own
devices/entities were keyed differently. Collapse that to the
coordinator's form, which is the one the registry actually holds.
"""
prefix = f"{DOMAIN}_"
unique_id = entry.unique_id or ""
if not unique_id.startswith(prefix):
return None
serial = unique_id[len(prefix) :]
if serial == f"{entry.data[CONF_HOST]}:{entry.data.get(CONF_PORT)}":
return entry.data[CONF_HOST]
return serial or None
@callback
def _repair_placeholder_keys(hass: HomeAssistant, entry: ConfigEntry, serial: str) -> None:
"""Re-key registry entries this entry minted from the placeholder identity.
Before the identity moved onto the config entry, the coordinator seeded
`device_serial` with the host and only replaced it after the first
successful poll. Anything that registered in between -- the connection-mode
sensor especially, since it is added unconditionally rather than from
`bound` -- was written into the registry keyed on the IP address
permanently, and was orphaned the moment the serial-keyed identity
appeared (issue #236). Deleting the orphans by hand didn't help: the next
restart that lost the same race recreated them.
Rewriting beats deleting where it's possible -- an entity keeps its
entity_id, name, area and every automation that references it. It's only
possible when the serial-keyed key is still free, though; where both exist
the placeholder-keyed one is the dead duplicate (it has been unavailable
since the restart that created it), so it goes.
"""
host = entry.data[CONF_HOST]
if serial == host:
# A board with no usable serial resolves *to* the host, so its keys
# were never placeholders -- there is nothing here to re-key.
return
ent_reg = er.async_get(hass)
stale_prefix = f"{DOMAIN}_{host}_"
for entity in list(er.async_entries_for_config_entry(ent_reg, entry.entry_id)):
if not entity.unique_id.startswith(stale_prefix):
continue
new_unique_id = f"{DOMAIN}_{serial}_{entity.unique_id[len(stale_prefix) :]}"
if ent_reg.async_get_entity_id(entity.domain, DOMAIN, new_unique_id):
_LOGGER.debug("removing orphaned entity %s", entity.entity_id)
ent_reg.async_remove(entity.entity_id)
else:
_LOGGER.debug("re-keying entity %s to %s", entity.entity_id, new_unique_id)
ent_reg.async_update_entity(entity.entity_id, new_unique_id=new_unique_id)
dev_reg = dr.async_get(hass)
for device in list(dr.async_entries_for_config_entry(dev_reg, entry.entry_id)):
# `host` for the master, `host_<key>` for a subdevice (device_info_for).
stale = {
ident
for ident in device.identifiers
if ident[0] == DOMAIN and (ident[1] == host or ident[1].startswith(f"{host}_"))
}
if not stale:
continue
fresh = {(DOMAIN, f"{serial}{ident[1][len(host) :]}") for ident in stale}
existing = dev_reg.async_get_device(identifiers=fresh)
if existing is not None and existing.id != device.id:
_LOGGER.debug("removing orphaned device %s", device.id)
dev_reg.async_remove_device(device.id)
else:
_LOGGER.debug("re-keying device %s to %s", device.id, fresh)
dev_reg.async_update_device(
device.id, new_identifiers=(device.identifiers - stale) | fresh
)
async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Migrate an entry to the current version.
v1 -> v2 stores the device's identity on the entry so the coordinator can
key its registry entries before the first poll (issue #236), and repairs
whatever the old placeholder-keyed registration already orphaned.
"""
if entry.version > 2:
# Downgrade: this release doesn't know the newer entry's shape.
return False
if entry.version == 1:
serial = (
entry.data.get(CONF_SERIAL) or _serial_from_unique_id(entry) or entry.data[CONF_HOST]
)
hass.config_entries.async_update_entry(
entry,
data={**entry.data, CONF_SERIAL: serial},
unique_id=f"{DOMAIN}_{serial}",
version=2,
)
_repair_placeholder_keys(hass, entry, serial)
_LOGGER.debug("migrated entry %s to version 2 (serial=%s)", entry.entry_id, serial)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data.setdefault(DOMAIN, {})
coordinator = LocalThingsCoordinator(hass, entry)
+244 -67
View File
@@ -11,6 +11,8 @@ import selectors
import socket
import ssl
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any
import voluptuous as vol
@@ -31,19 +33,26 @@ from homeassistant.helpers.selector import (
)
from .const import (
CLIENTHELLO_PROBE_RETRIES,
CLIENTHELLO_PROBE_TIMEOUT_S,
CONF_BYPASS_REMOTE_CONTROL,
CONF_CA_CERT_PEM,
CONF_CA_KEY_PEM,
CONF_DEVICE_TYPE,
CONF_FINISH_TIME_HYSTERESIS_MINUTES,
CONF_HOST,
CONF_LEAF_CERT_PEM,
CONF_LEAF_KEY_PEM,
CONF_MANUFACTURER,
CONF_MODEL,
CONF_PORT,
CONF_SERIAL,
DEFAULT_FINISH_TIME_HYSTERESIS_MINUTES,
DOMAIN,
LIVENESS_PROBE_TIMEOUT_S,
PREFERRED_PROBE_PORTS,
PROBE_GET_TIMEOUT_S,
PROBE_MAX_WORKERS,
PROBE_PORT_RANGE,
)
@@ -248,38 +257,118 @@ def _find_live_ports(host: str, ports: list[int], timeout: float) -> list[int]:
return _order_candidates(live + rescued)
def _is_placeholder_serial(serial: str) -> bool:
"""True for a non-empty serialNum that isn't actually a real identity.
@dataclass(frozen=True)
class _PortScan:
"""The result of the port-detection pass: which ports to hand a full DTLS
handshake, and whether a DTLS server was actually *proven* to be on one of
them (as opposed to merely not ruled out)."""
The ARTIK051_DONGLE_REF firmware family reports the literal string
'Nothing(SVC)' for every unit -- non-empty, so the plain `if not
serial` check here (and the equivalent one in coordinator.py's
`_run_discovery`) doesn't catch it, and two such units get the same
config-entry unique_id / entity unique_ids and collide (issue #83).
candidates: list[int]
confirmed: bool
Issue #189: the DA_WM_A51_20_COMMON (ARTIK051) laundry board family
reports a flash-unset sentinel instead -- every character the same
repeated hex digit (a washer and a dryer, two different physical
units, both reported the literal serialNum 'FFFFFFFFFFFFFFF') -- which
the 'nothing' check above doesn't catch either, so the second unit's
config flow aborted as already configured.
def _clienthello_probe(host: str, port: int):
"""One stateless DTLS ClientHello against `host:port`.
Imported lazily so an install whose smartthings-local predates the probe
(< 0.1.2) degrades to the UDP sweep at scan time rather than failing to
load the config flow at all.
"""
s = serial.strip()
if s.lower().startswith("nothing"):
return True
upper = s.upper()
return len(upper) >= 8 and len(set(upper)) == 1 and upper[0] in "0123456789ABCDEF"
from smartthings_local.protocol.dtls_probe import probe
return probe(
host,
port,
stateless=True,
timeout=CLIENTHELLO_PROBE_TIMEOUT_S,
retries=CLIENTHELLO_PROBE_RETRIES,
)
def _probe_and_validate(host: str, ca_cert_pem: str, ca_key_pem: str) -> dict:
"""Fetch UUID, mint leaf cert, probe each port. Returns config entry data dict."""
import cbor2
from smartthings_local.protocol.dtls_session import DtlsCoapSession
def _clienthello_scan(host: str, ports: list[int]) -> list[int]:
"""Ports on `host` that answered a DTLS ClientHello -- i.e. ports a real
DTLS server is listening on (issue #211).
from .registry.batch import parse_device0_batch
from .registry.by_type import resolve as resolve_registry
from .registry.identity import read_identity
smartthings-local's stateless probe sends one ClientHello and stops the
moment the server proves itself with a HelloVerifyRequest, which per RFC
6347 §4.2.1 the server answers *without* allocating association state. So
this identifies the device's real port in ~1 RTT, leaves nothing behind on
the appliance, and costs it far less than the alternative of throwing N
full certificate handshakes at it to find out.
The whole range goes out at once. That's safe in a way racing real
handshakes is not: each probe is bounded by CLIENTHELLO_PROBE_TIMEOUT_S
rather than DtlsCoapSession's 12s handshake timeout, so the pool's
shutdown-and-wait on exit costs one probe's budget, not the sum of the
range -- no `shutdown(wait=False)` and no losing threads left running
behind us.
"""
with ThreadPoolExecutor(max_workers=min(len(ports), PROBE_MAX_WORKERS)) as ex:
results = list(ex.map(lambda port: _clienthello_probe(host, port), ports))
live = []
for result in results:
if result.is_dtls_server:
live.append(result.port)
_LOGGER.debug("DTLS server on %s:%d (%s)", host, result.port, result)
return _order_candidates(live)
def _scan_ports(host: str) -> _PortScan:
"""Find the device's DTLS port, preferring proof over absence of evidence.
The ClientHello probe is authoritative when it finds something: a port
that answered one is running a DTLS server, so exactly one port gets the
expensive certificate handshake instead of every port the old UDP sweep
couldn't rule out (each of which cost a full 12s handshake timeout --
issue #211's 30-40s adds).
It stays a *gate*, not a replacement: when it confirms nothing we fall
back to the ICMP-based sweep, which is wrong in the opposite direction
(it reports everything it can't rule out) and so still surfaces a device
the probe couldn't reach -- e.g. a network path that drops our
ClientHello outright, or an install still on smartthings-local < 0.1.2.
Issue #192's segregated-VLAN device is the reason that fallback keeps its
own preferred-port rescue.
"""
try:
confirmed = _clienthello_scan(host, PROBE_PORT_RANGE)
except Exception as exc:
_LOGGER.debug("ClientHello probe unavailable (%s); falling back to UDP sweep", exc)
confirmed = []
if confirmed:
_LOGGER.debug("DTLS port(s) confirmed on %s: %s", host, confirmed)
return _PortScan(confirmed, True)
candidates = _find_live_ports(host, PROBE_PORT_RANGE, LIVENESS_PROBE_TIMEOUT_S)
# No early "every port refused" fast-fail here: _find_live_ports always
# rescues PREFERRED_PROBE_PORTS (issue #192), so candidates is never
# empty as long as that table is non-empty and within PROBE_PORT_RANGE --
# both true today, which made this branch permanently unreachable. A
# genuinely dead host fails in _handshake_and_read instead, whose error
# carries the actual per-port timeout/refusal reason rather than a generic
# "no live port found" message.
_LOGGER.debug("No DTLS server confirmed on %s; sweep candidates: %s", host, candidates)
return _PortScan(candidates, False)
class _HandshakeFailed(CannotConnect):
"""No candidate port completed a handshake.
`cert_rejected` is True when every attempt failed with a ConnectionError
-- the library's error for a handshake the peer actively broke off (a
fatal alert), as opposed to the TimeoutError it raises when nothing
answered at all. It's the signal for retrying with freshly-minted
credentials; see _probe_and_validate.
"""
def __init__(self, message: str, cert_rejected: bool) -> None:
super().__init__(message)
self.cert_rejected = cert_rejected
def _mint_credentials(ca_cert_pem: str, ca_key_pem: str) -> tuple[str, str]:
"""Fetch the current UUID from Samsung's cloud and mint a leaf cert for it."""
_LOGGER.debug("Fetching Samsung cloud UUID from %s", _SAMSUNG_CLOUD_HOST)
try:
uuid = _fetch_samsung_uuid()
@@ -298,66 +387,129 @@ def _probe_and_validate(host: str, ca_cert_pem: str, ca_key_pem: str) -> dict:
_LOGGER.debug("Leaf cert minting failed: %s", exc, exc_info=True)
raise CannotConnect(f"Failed to mint leaf cert: {exc}") from exc
_LOGGER.debug("Leaf cert minted successfully")
return fullchain_pem, leaf_key_pem
candidates = _find_live_ports(host, PROBE_PORT_RANGE, LIVENESS_PROBE_TIMEOUT_S)
# No early "every port refused" fast-fail here: _find_live_ports always
# rescues PREFERRED_PROBE_PORTS (issue #192), so candidates is never
# empty as long as that table is non-empty and within PROBE_PORT_RANGE --
# both true today, which made this branch permanently unreachable. A
# genuinely dead host now fails via the handshake loop's own error below,
# which carries the actual per-port timeout/refusal reason instead of a
# generic "no live port found" message.
_LOGGER.debug("Live DTLS port candidates on %s: %s", host, candidates)
last_exc = None
def _read_device(sess, host: str, port: int) -> dict:
"""Resolve this device's identity over an already-connected session.
/oic/d before /device/0, deliberately: the device's own OCF device-type
declaration is the primary detection signal when a board populates it
(see registry/by_type's resolve()), and read_identity's three small GETs
settle it long before the blockwise /device/0 dump lands. read_identity is
defensive on every GET it makes, so a device that answers neither /oic/p
nor /oic/d just yields an empty device_types tuple and detection falls
through to the model-string/resource-signature path.
Everything the entry needs to name and key the device comes from here --
resolved serial, model, manufacturer, device type -- so the coordinator
never has to mint a registry key from a placeholder (issue #236).
"""
import cbor2
from .registry.batch import parse_device0_batch
from .registry.by_type import resolve as resolve_registry
from .registry.identity import read_identity, resolve_serial
identity = read_identity(sess, None)
code, payload = sess.get(["device", "0"], timeout=PROBE_GET_TIMEOUT_S)
if code != 0x45 or not payload:
raise CannotConnect(f"port {port}: unexpected code {code:#04x}")
body = cbor2.loads(payload)
resources = parse_device0_batch(body) if isinstance(body, list) else {}
info = resources.get("/information/vs/0", {})
model_num = info.get("x.com.samsung.da.modelNum", "")
registry = resolve_registry(resources, device_types=identity.device_types)
return {
"port": port,
"serial": resolve_serial(info.get("x.com.samsung.da.serialNum"), host),
# Same derivation _run_discovery uses, so the device the coordinator
# registers up front is the one discovery would have produced.
"model": model_num.split("|", 1)[0] if model_num else identity.model,
"manufacturer": identity.manufacturer or "Samsung",
"device_type_name": registry.name if registry is not None else None,
"device_type_recognized": registry is not None,
}
def _handshake_and_read(host: str, candidates: list[int], cert_pem: str, key_pem: str) -> dict:
"""Handshake each candidate in turn, returning the first device that answers."""
from smartthings_local.protocol.dtls_session import DtlsCoapSession
last_exc: Exception | None = None
rejected_only = True
for port in candidates:
sess = None
try:
sess = DtlsCoapSession(
host,
port,
cert_pem=fullchain_pem,
key_pem=leaf_key_pem,
)
sess = DtlsCoapSession(host, port, cert_pem=cert_pem, key_pem=key_pem)
sess.connect()
sess.start_reader()
code, payload = sess.get(["device", "0"], timeout=PROBE_GET_TIMEOUT_S)
if code != 0x45 or not payload:
raise CannotConnect(f"port {port}: unexpected code {code:#04x}")
body = cbor2.loads(payload)
resources = parse_device0_batch(body) if isinstance(body, list) else {}
serial = resources.get("/information/vs/0", {}).get("x.com.samsung.da.serialNum", "")
if not serial or _is_placeholder_serial(serial):
serial = f"{host}:{port}"
# /oic/d's device type (read_identity) is the primary detection
# signal when a board populates it -- see registry/by_type's
# resolve(). read_identity is defensive on every GET it makes, so
# a device that doesn't answer /oic/p or /oic/d just yields an
# empty device_types tuple here, falling through to the model-
# string/resource-signature detection resolve() already did.
identity = read_identity(sess, None)
recognized_registry = resolve_registry(resources, device_types=identity.device_types)
return {
"port": port,
"serial": serial,
"leaf_cert_pem": fullchain_pem,
"leaf_key_pem": leaf_key_pem,
"device_type_recognized": recognized_registry is not None,
}
return _read_device(sess, host, port)
except CannotConnect:
# The device answered, just not with something we can use --
# trying the remaining ports can't improve on that.
raise
except Exception as exc:
last_exc = exc
rejected_only = rejected_only and isinstance(exc, ConnectionError)
_LOGGER.debug("port %d failed: %s", port, exc)
finally:
if sess is not None:
with contextlib.suppress(Exception):
sess.close()
raise CannotConnect(f"no port responded on {host}: {last_exc}")
raise _HandshakeFailed(
f"no port responded on {host}: {last_exc}",
cert_rejected=rejected_only and last_exc is not None,
)
def _probe_and_validate(
host: str,
ca_cert_pem: str,
ca_key_pem: str,
existing_leaf: tuple[str, str] | None = None,
) -> dict:
"""Find the device's port, authenticate to it, and resolve its identity.
Port detection runs first and needs no credentials at all, so an
unreachable host fails here rather than after a round trip to Samsung's
cloud.
`existing_leaf` is another entry's already-minted leaf (issue #211).
Every appliance accepts the same leaf -- CA `AC14K_M` plus the UUID from
Samsung's cloud cert -- so adding a second device can skip the fetch and
mint entirely, which makes it independent of Samsung-cloud reachability
rather than merely faster. If that reused leaf turns out to be stale (the
UUID does rotate), a confirmed-live device rejecting it is unambiguous
enough to re-mint and try once more, so the reuse stays self-correcting.
"""
scan = _scan_ports(host)
if existing_leaf is not None:
cert_pem, key_pem = existing_leaf
_LOGGER.debug("Reusing the leaf certificate from an existing entry")
else:
cert_pem, key_pem = _mint_credentials(ca_cert_pem, ca_key_pem)
try:
info = _handshake_and_read(host, scan.candidates, cert_pem, key_pem)
except _HandshakeFailed as exc:
# Only the reused-leaf case is worth a second pass, and only when the
# device proved it is there and broke the handshake off itself: a
# timeout means nothing answered, which a fresh cert won't change.
if existing_leaf is None or not (scan.confirmed and exc.cert_rejected):
raise
_LOGGER.debug("Reused leaf rejected by %s; re-minting and retrying", host)
cert_pem, key_pem = _mint_credentials(ca_cert_pem, ca_key_pem)
info = _handshake_and_read(host, scan.candidates, cert_pem, key_pem)
return {**info, "leaf_cert_pem": cert_pem, "leaf_key_pem": key_pem}
class LocalThingsConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 1
VERSION = 2
def __init__(self) -> None:
self._host: str = ""
@@ -373,8 +525,18 @@ class LocalThingsConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return LocalThingsOptionsFlow()
def _create_entry(self, info: dict) -> ConfigFlowResult:
"""Persist everything the probe resolved, identity included.
The identity fields are not decoration: the coordinator seeds
`device_serial` and its DeviceInfo from them at construction time, so
entity unique_ids and device identifiers are correct from the very
first entity that registers -- even if the first poll is slow, or
fails outright (issue #236).
"""
from .registry.identity import device_display_name
return self.async_create_entry(
title=f"Samsung Appliance ({self._host})",
title=f"{device_display_name(info['device_type_name'], '')} ({self._host})",
data={
CONF_HOST: self._host,
CONF_PORT: info["port"],
@@ -382,6 +544,10 @@ class LocalThingsConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
CONF_CA_KEY_PEM: self._ca_key_pem,
CONF_LEAF_CERT_PEM: info["leaf_cert_pem"],
CONF_LEAF_KEY_PEM: info["leaf_key_pem"],
CONF_SERIAL: info["serial"],
CONF_MODEL: info["model"],
CONF_MANUFACTURER: info["manufacturer"],
CONF_DEVICE_TYPE: info["device_type_name"],
},
)
@@ -393,9 +559,14 @@ class LocalThingsConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
if user_input is not None:
self._host = user_input[CONF_HOST].strip()
existing_leaf = None
if has_creds:
self._ca_cert_pem = existing[0].data[CONF_CA_CERT_PEM]
self._ca_key_pem = existing[0].data[CONF_CA_KEY_PEM]
leaf_cert = existing[0].data.get(CONF_LEAF_CERT_PEM)
leaf_key = existing[0].data.get(CONF_LEAF_KEY_PEM)
if leaf_cert and leaf_key:
existing_leaf = (leaf_cert, leaf_key)
else:
self._ca_cert_pem = user_input[CONF_CA_CERT_PEM].strip()
self._ca_key_pem = user_input[CONF_CA_KEY_PEM].strip()
@@ -406,6 +577,7 @@ class LocalThingsConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self._host,
self._ca_cert_pem,
self._ca_key_pem,
existing_leaf,
)
except InvalidCA:
errors["base"] = "invalid_ca"
@@ -451,12 +623,17 @@ class LocalThingsConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Shown only when the probe already knows the device type is unrecognized."""
info = self._pending_info or {}
if user_input is not None:
assert self._pending_info is not None
return self._create_entry(self._pending_info)
return self.async_show_form(
step_id="confirm_unknown_type",
data_schema=vol.Schema({}),
# The probe already knows the board string detection failed on;
# showing it here means a user filing the device-support issue
# this step asks for can quote it without digging through logs.
description_placeholders={"model": info.get("model") or "unknown"},
)
+35 -1
View File
@@ -20,6 +20,24 @@ CONF_CA_KEY_PEM = "ca_key_pem"
CONF_LEAF_CERT_PEM = "leaf_cert_pem"
CONF_LEAF_KEY_PEM = "leaf_key_pem"
# Device identity, resolved once by the config flow's probe and persisted on
# the entry (issue #236). These are what the coordinator mints registry keys
# from at __init__ time, before any poll has happened -- see
# LocalThingsCoordinator.__init__. Without them the coordinator had to seed
# `device_serial` with the host and rebuild its DeviceInfo after the first
# successful poll, so anything that registered in between (the connection-mode
# sensor, which is added unconditionally rather than from `bound`) was written
# into the entity/device registry keyed on the IP address permanently.
#
# CONF_SERIAL is the *resolved* serial -- registry.identity.resolve_serial's
# output, i.e. the host itself for a board that reports a placeholder serial
# (issues #83/#189) -- so it matches what _run_discovery computes on the first
# poll exactly, and the device identity never changes underneath the registry.
CONF_SERIAL = "serial"
CONF_MODEL = "model"
CONF_MANUFACTURER = "manufacturer"
CONF_DEVICE_TYPE = "device_type"
# 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 report remote control off yet still accept certain
@@ -53,9 +71,25 @@ PREFERRED_PROBE_PORTS = [49154, 49155]
# Per-port timeout for the cheap UDP liveness sweep. Closed ports return an
# ICMP port-unreachable almost immediately; a live-but-silent port is only
# detected by this timeout elapsing, so keep it short.
# detected by this timeout elapsing, so keep it short. Only reached now as the
# fallback for when the ClientHello probe below confirms nothing.
LIVENESS_PROBE_TIMEOUT_S = 1.5
# Per-port budget for the DTLS ClientHello probe (smartthings-local >= 0.1.2),
# the primary port-detection gate. A real DTLS server answers with a
# HelloVerifyRequest in ~1 RTT, so a live port resolves well inside this; the
# budget only bounds how long a *silent* port takes to give up, since the
# probe services OpenSSL's retransmit timer rather than reading one dropped
# ClientHello as dead. 3s covers two retransmits on a slow LAN.
CLIENTHELLO_PROBE_TIMEOUT_S = 3.0
CLIENTHELLO_PROBE_RETRIES = 2
# The whole port range is probed at once: each stateless probe is bounded by
# CLIENTHELLO_PROBE_TIMEOUT_S (unlike a full handshake's 12s), so the sweep
# costs one probe's wall clock rather than the sum of the range. Capped so a
# widened PROBE_PORT_RANGE can't spawn an unbounded thread pool.
PROBE_MAX_WORKERS = 12
# Deadline for the blockwise /device/0 GET during the config-flow probe. The
# slowest device observed returns a full dump in ~8s, so 10s leaves headroom
# without stalling setup; it matches the per-resource read timeout elsewhere.
+86 -42
View File
@@ -24,10 +24,14 @@ from smartthings_local.protocol.dtls_session import DtlsCoapSession
from .const import (
CONF_BYPASS_REMOTE_CONTROL,
CONF_DEVICE_TYPE,
CONF_HOST,
CONF_LEAF_CERT_PEM,
CONF_LEAF_KEY_PEM,
CONF_MANUFACTURER,
CONF_MODEL,
CONF_PORT,
CONF_SERIAL,
DEVICE_SUPPORT_ISSUE_URL,
DOMAIN,
DTLS_LOCAL_PORT_BASE,
@@ -45,7 +49,12 @@ from .registry.capabilities.common import (
remote_control_required_for_write,
)
from .registry.discovery import BoundEntity
from .registry.identity import DeviceIdentity, read_identity
from .registry.identity import (
DeviceIdentity,
device_display_name,
read_identity,
resolve_serial,
)
from .registry.subdevices import (
Subdevice,
canonical_view,
@@ -94,36 +103,6 @@ def _local_source_port(host: str) -> int:
return DTLS_LOCAL_PORT_BASE + offset
def _is_placeholder_serial(serial: str) -> bool:
"""True for a non-empty serialNum that isn't actually a real identity.
The ARTIK051_DONGLE_REF firmware family reports the literal string
'Nothing(SVC)' for every unit -- non-empty, so the plain `if not
serial` check below doesn't catch it, and `device_serial` feeds both
the HA device-registry identifier and every entity's unique_id
(entity.py), so two such units on the same install silently collide
and the second one's entities get dropped (issue #83).
Issue #189: the DA_WM_A51_20_COMMON (ARTIK051) laundry board family
reports a flash-unset sentinel instead -- every character the same
repeated hex digit (a washer and a dryer, two different physical
units, both reported the literal serialNum 'FFFFFFFFFFFFFFF') -- which
the 'nothing' check above doesn't catch either, so two such units
collided on the config-entry unique_id and the second couldn't be
added at all.
Mirrors the identical helper in config_flow.py's `_probe_and_validate`
-- kept separate rather than imported to avoid pulling the config-flow
module into the runtime coordinator's import graph for a two-line
check.
"""
s = serial.strip()
if s.lower().startswith("nothing"):
return True
upper = s.upper()
return len(upper) >= 8 and len(set(upper)) == 1 and upper[0] in "0123456789ABCDEF"
class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
"""Manages one Samsung appliance: session, discovery, polling."""
@@ -229,11 +208,28 @@ class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
self._observe = ObserveManager(self._cache, logger=self._log)
self._push_pending = False
self._push_pending_lock = threading.Lock()
self.device_serial = entry.data[CONF_HOST] # placeholder until first poll
# Identity comes from the config entry, resolved once by the config
# flow's probe (issue #236). `device_serial` mints *permanent*
# registry keys -- entity unique_ids (entity.py, sensor.py) and device
# identifiers (device_info_for) -- so it must be the device's real
# identity before the first entity registers, not a placeholder that
# gets corrected once the first poll lands. Anything registered
# against a placeholder is keyed on it in the registry forever; when
# the real identity showed up moments later, HA created a second
# device and a second entity and orphaned the first pair.
#
# The host fallback covers a config entry created before this was
# stored and whose migration couldn't recover it. It is also what
# resolve_serial itself returns for a board reporting a placeholder
# serial (issues #83/#189), so the two agree by construction.
self.device_serial = entry.data.get(CONF_SERIAL) or entry.data[CONF_HOST]
self.device_info = DeviceInfo(
identifiers={(DOMAIN, entry.data[CONF_HOST])},
name=f"Samsung Appliance ({entry.data[CONF_HOST]})",
manufacturer="Samsung",
identifiers={(DOMAIN, self.device_serial)},
name=device_display_name(
entry.data.get(CONF_DEVICE_TYPE), entry.data.get(CONF_MODEL) or ""
),
manufacturer=entry.data.get(CONF_MANUFACTURER) or "Samsung",
model=entry.data.get(CONF_MODEL) or None,
)
self._session_lock = asyncio.Lock()
self._subpoll_task: asyncio.Task | None = None
@@ -632,6 +628,38 @@ class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
self._skipped_subdevice_resources = skipped
return kept
def _persist_identity(
self,
serial: str,
model: str,
manufacturer: str,
device_type_name: str | None,
) -> None:
"""Write this device's resolved identity back onto the config entry.
For an entry added by the current config flow this is a no-op -- the
probe already stored all four. It matters for an entry migrated from
before they were stored: the first poll is where its model and device
type become known, and persisting them means the *next* restart
registers the device fully named before any entity exists, instead of
renaming it a second time once the poll lands.
Runs on the event loop (_run_discovery is called directly from
_async_update_data, not in an executor), which async_update_entry
requires.
"""
identity = {
CONF_SERIAL: serial,
CONF_MODEL: model,
CONF_MANUFACTURER: manufacturer,
CONF_DEVICE_TYPE: device_type_name,
}
if all(self._entry.data.get(k) == v for k, v in identity.items()):
return
self.hass.config_entries.async_update_entry(
self._entry, data={**self._entry.data, **identity}
)
def _run_discovery(self, resources: dict[str, dict]) -> None:
# Reported for diagnostics only -- it names the firmware generation
# ('7.0 Air conditioner' is Tizen Lite), which is useful when triaging
@@ -725,17 +753,32 @@ class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
self.bound = bound
self._unbound_hrefs = unbound
serial = info.get("x.com.samsung.da.serialNum", "")
if not serial or _is_placeholder_serial(serial):
serial = self._entry.data[CONF_HOST]
# The identity the entry was registered under wins. This poll's own
# answer is only adopted when the entry has nothing stored -- a legacy
# entry whose migration couldn't recover a serial -- and is then
# written back so it stops changing. Re-keying a device that already
# has registry entries is what issue #236 is about: the old keys don't
# follow, they orphan.
polled_serial = resolve_serial(
info.get("x.com.samsung.da.serialNum"), self._entry.data[CONF_HOST]
)
serial = self._entry.data.get(CONF_SERIAL) or polled_serial
if serial != polled_serial:
# Same IP, different appliance (or a firmware that changed what it
# reports). Keeping the stored identity is the safe half of that;
# re-adding the device is the user's call.
self._log.warning(
"device at %s reports serial %r but this entry is registered "
"as %r; keeping the registered identity",
self._entry.data[CONF_HOST],
polled_serial,
serial,
)
self.device_serial = serial
ident = self._identity
device_type = (
device_type_name.replace("_", " ").title() if device_type_name else "Appliance"
)
model = model_num.split("|", 1)[0] if model_num else (ident.model if ident else "")
name = f"Samsung {device_type} ({model})" if model else f"Samsung {device_type}"
name = device_display_name(device_type_name, model)
mfr = (ident.manufacturer if ident else "") or "Samsung"
self.device_info = DeviceInfo(
@@ -744,6 +787,7 @@ class LocalThingsCoordinator(DataUpdateCoordinator[dict[str, Any]]):
manufacturer=mfr,
model=model,
)
self._persist_identity(serial, model, mfr, device_type_name)
self._update_coverage_gap_issue(device_type_name is None, unbound, name)
self._hot_hrefs = sorted(hot)
+2 -2
View File
@@ -10,7 +10,7 @@
"requirements": [
"cbor2>=5.4.6",
"pyOpenSSL>=23.0",
"smartthings-local>=0.1.1"
"smartthings-local>=0.1.2"
],
"version": "0.18.0"
"version": "0.19.0"
}
@@ -17,6 +17,63 @@ class DeviceIdentity:
raw: dict[str, dict | list] = field(default_factory=dict)
def is_placeholder_serial(serial: str) -> bool:
"""True for a non-empty serialNum that isn't actually a real identity.
The ARTIK051_DONGLE_REF firmware family reports the literal string
'Nothing(SVC)' for every unit -- non-empty, so a plain `if not serial`
check doesn't catch it, and the resolved serial feeds both the HA
device-registry identifier and every entity's unique_id (entity.py), so
two such units on the same install silently collide and the second one's
entities get dropped (issue #83).
Issue #189: the DA_WM_A51_20_COMMON (ARTIK051) laundry board family
reports a flash-unset sentinel instead -- every character the same
repeated hex digit (a washer and a dryer, two different physical units,
both reported the literal serialNum 'FFFFFFFFFFFFFFF') -- which the
'nothing' check above doesn't catch either, so the second unit's config
flow aborted as already configured.
Lives here, rather than being duplicated in config_flow.py and
coordinator.py as it once was, because the config flow now resolves the
serial once and persists it on the entry for the coordinator to seed its
registry keys from (issue #236). Two copies of this rule meant the two
sides could disagree about what a device's identity is -- and a
disagreement is exactly what orphans a registry entry.
"""
s = serial.strip()
if s.lower().startswith("nothing"):
return True
upper = s.upper()
return len(upper) >= 8 and len(set(upper)) == 1 and upper[0] in "0123456789ABCDEF"
def resolve_serial(raw_serial: str | None, host: str) -> str:
"""The device identity to mint registry keys from.
`raw_serial` is /information/vs/0's x.com.samsung.da.serialNum as the
device reported it. Boards that report nothing usable fall back to the
host, which is stable per install and unique across devices on one
network -- see is_placeholder_serial for the two families that need it.
"""
s = (raw_serial or "").strip()
if not s or is_placeholder_serial(s):
return host
return s
def device_display_name(device_type_name: str | None, model: str) -> str:
"""The HA device name for a resolved device type + model.
Shared by the config flow (which builds the entry's stored identity) and
the coordinator's post-discovery rebuild, so the name a device is first
registered under is the same string discovery would produce later --
otherwise every setup would rename the device once the first poll landed.
"""
device_type = device_type_name.replace("_", " ").title() if device_type_name else "Appliance"
return f"Samsung {device_type} ({model})" if model else f"Samsung {device_type}"
def _get(sess, path) -> dict:
try:
code, pl = sess.get(path, timeout=10.0)
@@ -1235,7 +1235,7 @@
},
"confirm_unknown_type": {
"title": "Typ spotřebiče nebyl rozpoznán",
"description": "Typ tohoto spotřebiče se nepodařilo rozpoznat. Přesto bude přidán, ale pouze se společnými funkcemi (napájení, alarmy atd., pokud jsou k dispozici), nikoli s plnou sadou funkcí pro danou rodinu spotřebičů. Podporu můžete později pomoci rozšířit stažením diagnostiky pro toto zařízení (Nastavení > Zařízení a služby > toto zařízení > nabídka > Stáhnout diagnostiku) a jejím vložením do nového issue. Odesláním zařízení přidáte i tak."
"description": "Tento spotřebič hlásí model „{model}“, což je typ, který LocalThings zatím nerozpoznává. Přesto bude přidán, ale pouze se společnými funkcemi (napájení, alarmy atd., pokud jsou k dispozici), nikoli s plnou sadou funkcí pro danou rodinu spotřebičů. Podporu můžete později pomoci rozšířit stažením diagnostiky pro toto zařízení (Nastavení > Zařízení a služby > toto zařízení > nabídka > Stáhnout diagnostiku) a jejím vložením do nového issue. Odesláním zařízení přidáte i tak."
}
},
"error": {
@@ -1235,7 +1235,7 @@
},
"confirm_unknown_type": {
"title": "Appliance type not recognized",
"description": "This appliance's type couldn't be recognized. It'll still be added, but only with common capabilities (power, alarms, etc. where present) rather than the full set for its family. You can help add full support afterward by downloading diagnostics for this device (Settings > Devices & Services > this device > the menu > Download diagnostics) and filing them in a new issue. Submit to add it anyway."
"description": "This appliance reported model \"{model}\", which isn't a type LocalThings recognizes yet. It'll still be added, but only with common capabilities (power, alarms, etc. where present) rather than the full set for its family. You can help add full support afterward by downloading diagnostics for this device (Settings > Devices & Services > this device > the menu > Download diagnostics) and filing them in a new issue. Submit to add it anyway."
}
},
"error": {
@@ -27,7 +27,7 @@
},
"confirm_unknown_type": {
"title": "Tipo de electrodoméstico no reconocido",
"description": "No se ha podido reconocer el tipo de este electrodoméstico. Se añadirá igualmente, pero solo con las capacidades comunes (alimentación, alarmas, etc. donde existan) en lugar del conjunto completo de su familia. Puedes ayudar a añadir soporte completo después descargando los diagnósticos de este dispositivo (Ajustes > Dispositivos y servicios > este dispositivo > el menú > Descargar diagnósticos) y reportándolos en una nueva incidencia. Envía para añadirlo de todos modos."
"description": "Este electrodoméstico informa del modelo «{model}», un tipo que LocalThings aún no reconoce. Se añadirá igualmente, pero solo con las capacidades comunes (alimentación, alarmas, etc. donde existan) en lugar del conjunto completo de su familia. Puedes ayudar a añadir soporte completo después descargando los diagnósticos de este dispositivo (Ajustes > Dispositivos y servicios > este dispositivo > el menú > Descargar diagnósticos) y reportándolos en una nueva incidencia. Envía para añadirlo de todos modos."
}
},
"error": {
@@ -1235,7 +1235,7 @@
},
"confirm_unknown_type": {
"title": "Tipo di elettrodomestico non riconosciuto",
"description": "Il tipo di questo apparecchio non è stato riconosciuto. Verrà comunque aggiunto, ma solo con le funzionalità di base (alimentazione, allarmi, ... se presenti) anziché con tutte le funzionalità della sua famiglia. Puoi contribuire all'aggiunta del supporto completo in seguito scaricando i dati diagnostici per questo dispositivo (Impostazioni > Dispositivi e servizi > questo dispositivo > il menu > Scarica diagnostica) e inviandoli in una nuova segnalazione. Invia comunque la segnalazione per aggiungerlo."
"description": "Questo apparecchio dichiara il modello \"{model}\", un tipo che LocalThings non riconosce ancora. Verrà comunque aggiunto, ma solo con le funzionalità di base (alimentazione, allarmi, ... se presenti) anziché con tutte le funzionalità della sua famiglia. Puoi contribuire all'aggiunta del supporto completo in seguito scaricando i dati diagnostici per questo dispositivo (Impostazioni > Dispositivi e servizi > questo dispositivo > il menu > Scarica diagnostica) e inviandoli in una nuova segnalazione. Invia comunque la segnalazione per aggiungerlo."
}
},
"error": {
@@ -1235,7 +1235,7 @@
},
"confirm_unknown_type": {
"title": "Apparaattype niet herkend",
"description": "Het apparaattype van dit apparaat kon niet worden herkend. Het apparaat wordt toch toegevoegd, maar alleen met algemene mogelijkheden (zoals voeding en alarmen, voor zover aanwezig), in plaats van alle mogelijkheden voor deze apparaatfamilie. Je kunt daarna helpen volledige ondersteuning toe te voegen door diagnostische gegevens voor dit apparaat te downloaden (Instellingen > Apparaten & diensten > dit apparaat > het menu > Diagnostische gegevens downloaden) en deze bij een nieuw issue te voegen. Kies Verzenden om het apparaat toch toe te voegen."
"description": "Dit apparaat meldt model \"{model}\", een type dat LocalThings nog niet herkent. Het apparaat wordt toch toegevoegd, maar alleen met algemene mogelijkheden (zoals voeding en alarmen, voor zover aanwezig), in plaats van alle mogelijkheden voor deze apparaatfamilie. Je kunt daarna helpen volledige ondersteuning toe te voegen door diagnostische gegevens voor dit apparaat te downloaden (Instellingen > Apparaten & diensten > dit apparaat > het menu > Diagnostische gegevens downloaden) en deze bij een nieuw issue te voegen. Kies Verzenden om het apparaat toch toe te voegen."
}
},
"error": {