Compare commits

...
Author SHA1 Message Date
Marc Billow 867f4b0ae8 Bump version from 0.19.0 to 0.20.0 2026-08-07 19:55:02 -04:00
Marc Billow 9da775a8de Merge pull request #326 from mbillow/claude/oven-control-write-options-uthy5u
Add write_resource/read_resource services for probing write contracts (issue #300)
2026-08-07 19:52:12 -04:00
Marc Billow 6ee60beae9 Make holding the session across a sequence the caller's choice
Holding _session_lock for a whole write sequence buys certainty about what
the appliance saw and when, but blocks every poll and entity write for the
sequence's full length -- up to 10 x 30s. Which of those matters more
depends on what is being probed, so it is now hold_session_lock on
async_raw_write_sequence and a field on the service, defaulting to the
holding behavior that shipped.

Off, the lock is taken per write and released across the settle waits, so
entities keep updating through a long sequence. Exactly one of the two
context managers is ever the real lock -- asyncio.Lock isn't reentrant.

Tests assert the lock's actual state during the settle wait in both modes,
rather than just that the flag is accepted.
2026-08-07 23:46:28 +00:00
Marc Billow fffe923afc Take the device as a field, not a service target
Hassfest rejects a filtered device target outright ("Services do not
support device filters on target, use a device selector instead"), and an
unfiltered one would offer every device in the installation. Both services
now take device_id as a required field with a device selector scoped to
this integration -- the shape fully_kiosk, guardian and unifi already use.
No schema change needed: cv.TARGET_SERVICE_FIELDS already accepts
device_id, so the options-flow panel's target= call keeps working.

Also trims the comments added with the review fixes back to the one or two
sentences CONTRIBUTING asks for.
2026-08-07 22:58:48 +00:00
Marc Billow a6d818dfc0 Fix four review findings in the raw write/read services
- services.py: normalize an href before handing it to Subdevice.to_actual.
  That transform is textual and rewrites only a trailing '0' segment, so
  '/mode/vs/0/' passed through it untouched and normalized downstream to
  the master's '/mode/vs/0' -- landing the write on the wrong oven cavity
  while still answering 2.04, with nothing in the response to give it
  away. Same order now on the read path.
- services.py: key `verified` off those same normalized canonicals. It was
  built from un-normalized to_actual output against the coordinator's
  normalized hrefs, so a non-canonical input missed the lookup and handed
  back actual hrefs where the documented contract promises canonical ones.
- coordinator.py: report `held: None` when the verify re-read itself
  didn't come back. A non-2.05 yields an empty rep, against which every
  payload comparison is False, so a 4.04 or dropped read was reported as
  `held: false` -- indistinguishable from the board reverting the write,
  which is the one distinction verify_after exists to draw.
- coordinator.py: on a mid-sequence failure, say how many writes landed
  and which, and still kick the refresh. Raising bare threw that away, and
  the appliance is left holding a partial sequence.

Also documents why `settle` waits inside the session lock while
verify_after's wait deliberately doesn't: a poll landing between two
writes is exactly what the sequence exists to rule out, and the caps
bound the worst case at 10 x 30s.
2026-08-07 22:58:37 +00:00
Marc Billow cec3dd4a68 docs: use real field shapes in the write_resource examples
The README's worked example and services.yaml's field example both wrote
`x.com.samsung.da.mode: "Bake"` to /mode/vs/0 -- singular, and a bare
string. That resource takes `modes` as an array (issue #300's own dump
shows `["NoOperation"]`), so both examples were a shape the device would
have ignored, in the one place a user is most likely to copy from. The
README's other two steps were invented the same way; replaced with the
mode -> state: Run sequence issue #300 is actually trying to prove out.

Also adds a short note that payloads go out verbatim, so field names and
types have to match what the resource really uses, pointing at
read_resource with no href as the way to check first -- and aligns the
two new Repo layout rows with the column their neighbors use.
2026-08-07 22:58:37 +00:00
Marc Billow 5dbe990c1d Add write_resource/read_resource services for probing write contracts (issue #300)
The options-flow "Debug write" panel could only ever do one write to one
href per pass -- not enough for the issue #300 wall oven, whose board
discards settings writes while idle and only keeps them once a cycle is
already running. Finding what starts a cycle needs an ordered sequence of
writes across resources, with real settle delays between them, and a way
to check afterward whether anything actually held.

- coordinator.py: async_raw_write_sequence owns a whole ordered sequence
  under one _session_lock hold (so a poll can't interleave mid-sequence),
  with per-step settle and an optional delayed verify_after re-read done
  outside the lock. async_raw_write is now a one-item wrapper over it, so
  tests/test_coordinator_raw_write.py keeps passing unmodified. Also adds
  async_raw_read, a live GET bypassing the cache -- staleness is exactly
  what makes revert-testing unreliable.
- services.py (new): the two HA services. Device-target resolution scans
  loaded coordinators' MAIN/subdevice identifiers and requires exactly one
  match, so an area/label target can't silently fan a raw write out across
  several appliances. Canonical->actual href translation happens here, not
  in the coordinator, which stays subdevice-agnostic.
- services.yaml (new): selectors/descriptions for both services, inline
  per HA's custom-integration support -- keeps translations/en.json's
  mirror test (test_translations.py) green without touching all 6
  languages for a services block. New exception keys (write caps, device
  target resolution) still went into translations/*.json's existing
  exceptions section, mirrored across all 6 languages.
- __init__.py: adds async_setup to register the services once, process-wide.
- config_flow.py: the debug panel's async_step_debug_edit now calls
  write_resource instead of coord.async_raw_write directly, so there is
  exactly one code path that performs a raw write.
- README.md: new Part 5 documenting both services, with a worked
  write_resource example; points the capability-gap section at them.

tests/test_services.py (new): sequencing/ordering, settle timing, changed
vs. held (the reverted case is issue #300's own symptom), exactly-one-
device resolution, subdevice href translation, validation caps, and the
options-flow panel end to end through the service.
2026-08-07 22:08:28 +00:00
Marc Billow 9228da1d9c Merge pull request #323 from mbillow/claude/issue-triage-qgveie
Device support: A/C, fridge, cooktop, oven coverage gaps (issues #319, #318, #314, #300, #288)
2026-08-07 13:09:22 -04:00
Marc Billow ce60b6967b Clarify why windfree/windsleep are plain switches, not climate presets
Same feature name as the WindFree already modeled via climate.py's preset
system on regular AC boards, but a genuinely different wire mechanism --
this device's fields live on their own dedicated hrefs with no evidenced
coupling to hvac_mode, unlike the Comode_Nano token's real gating rules on
legacy boards. Recorded in-line so this doesn't come up as a 'why isn't
this a preset' question again without the answer already being there.
2026-08-07 17:05:39 +00:00
Marc Billow a7dc1db8ff Extract usable parts of PR #316 (System Fresh Air Ventilator support)
PR #316 (fork stale by several months, most of its ~2200-line diff was drift
against main rather than real changes) proposed device support for the
Samsung System Fresh Air Ventilator (ACA-KR-TP2-21-AN9000). Extracted what
holds up, adapted to this project's conventions, and left out what doesn't:

Extracted:
- ventilation_mode select on CLIMATE's own href, gated via
  _is_ventilation_mode_device so it can only ever bind on a device whose
  entire supportedModes set is Purification/Ventilation/SmartVentilation --
  verified against every real AC fixture in the corpus to confirm it can't
  false-positive on an actual air conditioner's climate card.
- WINDFREE / WINDSLEEP switches on their own dedicated hrefs.
- A CO2 sensor on AIR_QUALITY, matching air_monitor.SENSORS' already-bound
  device_class='carbon_dioxide'/unit='ppm' descriptor for the same field
  shape rather than guessing fresh.
- HEPA_FILTER / DEVICE_ACTIVE reuse from air_purifier.py.
- Removing /airlevelcheck/vs/0 from _AC_IGNORED and binding
  air_purifier.AIR_LEVEL_CHECK in its place: the PR's claim that this
  project's old "scheduler plumbing" description was wrong turned out to
  be independently verifiable against two of our own existing fixtures
  (airconditioner_cac and airconditioner_tp1x_da_ac_rac_01011 both already
  carry real, populated periodicSensingActivationState/autoExeState
  values), so this benefits existing users, not just the one new device.

Left out:
- Unit/device_class ('ug/m3', pm10/pm25/pm1) on the existing dust/
  fine_dust/super_fine_dust sensors, sourced from an unverified third-party
  screenshot description. air_monitor.py already has an explicit, reasoned
  rejection of this exact mapping for the exact same three fields:
  Samsung's PM10/PM2.5 convention doesn't confirm where a third tier or a
  PM1 reading fits, and a wrong guess mislabels the reading forever.
- A standalone common.POWER switch -- contradicts this registry's own
  documented design (power is deliberately the climate entity's job) and
  would affect every AC user, not just this device.
- Promoting wind/swing to independent selects for every AC user -- a UX
  opinion, not a coverage necessity, and out of scope for this device's
  own support.
- A model-name diagnostic sensor -- /information/vs/0 is already covered
  via the global ignore list, so this wasn't closing an actual gap.

No raw diagnostics dump for this model was ever attached to PR #316, so
there's no fixture for it here (fabricating one would violate this
project's fixture-integrity rule) -- see
tests/test_airconditioner_ventilation_windfree.py's module docstring.
2026-08-07 16:38:09 +00:00
Marc Billow 8551974719 Fix ty type-check failures in new test files
resolve()/for_device_by_model() return DeviceRegistry | None; four new
test files used reg.capabilities/reg.pattern_capabilities without
narrowing away None first. Add the same 'assert reg is not None' idiom
test_dehumidifier_tp1x_dhm01001_capabilities.py already uses.

Verified against a clean venv running the exact CI commands (ruff format
--check, ruff check, ty check, pytest) rather than trusting a stale local
venv that had picked up a mismatched python3.11/3.13 site-packages split.
2026-08-07 15:52:46 +00:00
Marc Billow e2dcc75ed5 Address Opus review findings on the device-support commits above
- Fix a real bug: airconditioner.SOUND_MODE had no exists_fn, so on
  boards (issue #319's FAC) that never report a live 'mode' value,
  entity.py's default field-presence gate silently kept the select from
  ever registering in HA -- while adapter.flatten() (what the golden/tests
  read) has no such gate, so the tests passed while documenting behavior
  the opposite of what shipped. Gate on supportedModes' presence instead.
- Add airconditioner.MDS_ABSENCE_CLEAN for the CAC-class board's
  /mds/absenceclean/vs/0 -- byte-identical shape to issue #319's
  /csi/absenceclean/vs/0, confirmed rather than guessed, closing one more
  of that board's documented coverage-gap hrefs.
- Add missing translation state labels (all 6 languages) for
  edge_lighting_mode/edge_lighting_color/indicator_light_mode's raw device
  codes, so they render as real words instead of a raw '3000K' -> '3000 K'
  fallback.
- Fix an orphaned comment above SOUND_MODE that actually described the
  unrelated DISPLAY reuse, and correct two inaccurate rationale comments:
  the sound/voice ignore reason claimed a distinction from SOUND_MODE that
  this same dump contradicts, and the /csi/* ignore block's 'same
  reasoning as air_purifier.COVERAGE' precedent only actually covers 1 of
  its 5 hrefs.
- Correct the false 'no board-token match' claim in the FAC test file and
  golden-regression docstring -- 'FAC' is a real _BOARD_TOKEN_TO_KEY entry
  (for_device_by_model alone already resolves this board); add a test
  that actually exercises that path, which nothing previously did despite
  the docstring's claim.
- Drop a tautological burner-slot test that only re-asserted what the
  golden regression test already covers via the same code path.
2026-08-07 14:50:24 +00:00
Marc Billow c203bd42c5 Add edge-lighting and indicator-light support for TP1X_DA-AC-CAC-01001 (issue #288)
Six System A/C cassette units on the same board test_airconditioner_cac.py
already documented as having an incomplete coverage gap gave real dump
evidence for two of its remaining unbound hrefs:

- /edgelighting/vs/0: an accent-light strip with on/off, a Smart/High/Low
  mode, and a Kelvin color-temperature select (3000K/4000K/6500K), all read
  from the device's own live supported-value lists.
- /light/stateful/vs/0: a second, distinct light resource with its own
  on/off and Smart/Low/High mode -- not to be confused with EDGE_LIGHTING
  or DISPLAY_LIGHT's ambient mood light.

convenientMode/operatingOption on /edgelighting/vs/0 stay unexposed: present
on every dump but no evidence of what either actually controls.

Only three hrefs remain in test_airconditioner_cac.py's documented gap now
(absence-clean, sound-optimization, smart-sensing-cooling).
2026-08-07 14:27:25 +00:00
Marc Billow 42fd9c2aa4 Close coverage gap and fix phantom lamp switch for TP2X_DA-KS-WALLOVEN (issue #300)
/diagnosis/vs/0 was the dump's only unbound href, now covered via
dishwasher.DIAGNOSIS (same shape already reused by airconditioner.py).

This steam-oven-class board's /mode/vs/0 options[] carries no UpperLamp_
token at all, unlike the NV7000BS-class board LAMP was proven against --
LAMP had no exists_fn, so it registered anyway, always read Off, and any
write to it was a no-op the device had no reason to honor. Gives it the
same options-token exists_fn gate issue #183 already added to
fast_preheat/natural_steam/energy_saving/cooktop_on_alert.
2026-08-07 14:22:32 +00:00
Marc Billow df5b704f3e Close gas-cooktop coverage gap for TP2X_DA-KS-COOKTOP-000001 (issue #314)
/alarms/vs/0 and /kidslock/vs/0 were the dump's two unbound hrefs -- both
are the exact shapes common.UNIVERSAL already models elsewhere
(common.ALARMS, common.KIDS_LOCK_VS_FALLBACK), picked individually rather
than pulling in all of UNIVERSAL to match this registry's existing
hand-picked-common style.

The six-vs-three burner count the reporter originally asked about is
expected behavior (the board's own /mode/vs/0 options genuinely advertise
six OperationState slots on hardware with three physical burners, with no
per-device signal to tell real slots from phantom ones) -- already
explained on the issue; this commit is scoped to the coverage warning.
2026-08-07 14:18:08 +00:00
Marc Billow 26c9168fb7 Add internal air-filter support for TP1X_REF_21K refrigerators (issue #318)
/filter/airdustfilter/vs/0 was the dump's only unbound href -- this board's
internal deodorizing filter, same filterUsage/filterStatus field pair as
common.WATER_FILTER, but filterUsage here is already a 0-100 percentage
with no filterCapacity to divide by (confirmed by filterStatus=="wash" at
filterUsage=="100"). Uses air_-prefixed keys so a fridge with both a
water and an air filter gets two distinct entities.
2026-08-07 14:13:38 +00:00
Marc Billow edf77309ba Add device support for AILP_DA-AC-FAC-02011 air conditioner (issue #319)
This board routes purely via /oic/d's oic.d.airconditioner type (no
board-token match) and reports several resources the sibling
TP1X_DA-AC-CAC-01001 board (issue #191) left as a documented gap:

- /display/vs/0, /settings/sound/output/vs/0, /settings/sound/volume/vs/0
  now reuse air_purifier.py's identical-shape capabilities instead of
  duplicating them.
- /settings/sound/mode/vs/0 gets a new airconditioner.SOUND_MODE reading
  the live supportedModes field, sharing laundry.py's existing
  voice/tone/mute translation catalog since the value vocabulary matches.
- /csi/absenceclean/vs/0 and /csi/energysaving/vs/0 are new, genuinely
  useful controls (absence auto-clean toggle, energy-saving mode select
  plus its state/operatingStatus diagnostics).
- /dnd/autosleep/vs/0, /outdoorsharing/vs/0, /lifestyle/survey/vs/0,
  /settings/sound/voice/vs/0 and /csi/information/vs/0 are ignored as
  plumbing/unconfirmed data with no user-actionable state.

Also fixes a latent bug in air_purifier.SOUND_VOLUME: boards that report
minLevel/resolution but no maxLevel (this one) would have produced a
min=0/max=0 number entity instead of self-gating off.

Updates test_airconditioner_cac.py's documented coverage gap now that
sound_mode/sound_output/sound_volume are covered there too.
2026-08-07 14:10:13 +00:00
Marc Billow f07ae4020e Merge pull request #310 from edenhaus/config-flow-prefill-on-error
Keep user input on error in the config flow
2026-08-06 08:47:48 -04:00
Marc Billow dd953b8150 Merge pull request #304 from perseus177/ac-presets-per-hvac-mode
feat(climate): derive legacy AC presets from the unit's own capability bits, per HVAC mode
2026-08-06 08:46:55 -04:00
perseus177 b820a96277 docs(airconditioner): record that the board zeroes Sleep_ on leaving a sleep mode
Review question on #304: a bare Comode_Off written over Comode_Sleep/Sleep_4
read back as Comode_Off/Sleep_0 at +8s and +38s, so the preset path cannot
leave a stale duration for the next nano selection to read as a running timer.
2026-08-06 12:20:18 +02:00
perseus177 eed04faaed fix(climate): derive presets only when the board publishes both capability maps
One map is not enough to judge by: with only OptionCode present, every
eoc-gated rule reads None, and None means the board does not publish the map
rather than that the feature is absent. artik051_dongle_fac_18k is exactly that
board and lost WindFree in every mode. Requiring both also keeps these bit
positions inside the family they were documented for -- the FAC and CAC dumps
carry only the older map, with values small enough that RAC positions read as
zeros.

Also from review: an unknown HVAC mode falls back the same way, Comfort is
spelled like the identical Speed rule, the unreachable AIComfort branch is
gone, the Cool code comes from the unit's own supportedModes, DlightCool gains
its catalog entry, and the Single User claim is dropped -- the app's own Single
User command sends Comode_Smart, so there is no distinct token to write.
2026-08-06 12:04:46 +02:00
Robert Resch 960eca2d6a Keep user input on error 2026-08-06 10:17:43 +02:00
Marc Billow 789aaf9849 Merge pull request #306 from mbillow/claude/issue-triage-backoff-xkeddl
Fix reconnect/retry gaps found in issue triage (#291, #287, #294)
2026-08-05 22:09:52 -04:00
Marc Billow e3e7f4f43c test: suppress ty's invalid-assignment on the fake-session swap
coordinator is explicitly typed as LocalThingsCoordinator here, so ty
correctly sees _session's declared type (DtlsCoapSession | None) and
flags assigning a FakeObserveSession to it. The fixture's own
_connect_session replacement does the same swap without tripping ty,
but only because its self parameter is unannotated -- ty has nothing to
check the assignment against there. Deliberate here (this is the whole
point of the test: substitute a stand-in session), so silenced rather
than restructured; ty's --add-ignore confirmed the comment syntax
(ty: ignore[...], not the mypy-style type: ignore[...] used elsewhere
in this suite, which ty doesn't appear to honor for this rule).
2026-08-06 02:07:39 +00:00
Marc Billow a3cc918343 fix(coordinator): two gaps a follow-up Opus review found in the split
A second review of the observe-mode phase split (previous commit) found
two real regressions it introduced, both in the same failure family it
was built to close:

- async_send_command's failed-retry branch closed the session, then
  raised without downgrading observe mode -- the downgrade only ran on
  the retry's success path. A retry that also fails still leaves the
  session dead, so mode was left claiming "Push" on a session that no
  longer exists, same as the bug this whole fix targets. Moved the
  downgrade to run right after the close, unconditionally on how the
  retry goes.

- _attempt_observe_mode's stale-session abandon (the identity-check
  branch added in the previous commit) didn't flag a resubscribe. A
  session swap discovered there means a fresh, never-tried session now
  exists, but _last_observe_attempt_ts was already stamped for the
  now-abandoned attempt -- so that new session sat unsubscribed for up
  to _RECOVERY_RETRY_S (600s) instead of being retried on the next
  cycle. Now sets _resubscribe_due, same as the two reconnect paths do.

Also closes two test-coverage gaps the same review surfaced by mutation
testing: no test asserted the lock actually holds during the subscribe
burst (only that it's released for the wait), and no test distinguished
the max() in _maybe_retry_observe_mode's throttle from using
_last_observe_attempt_ts alone -- both mutations left the full suite
green. Added one test for each, plus extended two existing tests for the
bug fixes above; all four confirmed via mutation testing (revert the
fix, watch the new/extended test fail; restore it, watch it pass).

One finding from the same review is intentionally left open: async_close
is the one self._session writer that doesn't take _session_lock, so a
close racing _attempt_observe_mode isn't covered by today's identity
check. This is pre-existing (the lock didn't cover any of
_attempt_observe_mode before this branch's earlier commits either), not
a regression from this branch's work, and is a shutdown/unload-path
question rather than the write-vs-observe-mode race this branch set out
to fix.
2026-08-06 02:01:30 +00:00
Marc Billow 69f93be4dc fix(coordinator): close the observe-mode race an Opus design review found
The command-retry fix (issue #294) added a self._close_session() call to
async_send_command that isn't synchronized against _attempt_observe_mode,
which reads self._session and subscribes to it without holding
_session_lock. A write's retry racing an in-flight subscribe attempt
could tear down the session mid-subscribe -- or worse, land the close
*after* the attempt's grace wait already succeeded, letting it commit
observe mode against a session that's already gone: mode claims "Push"
forever, with nothing left to notice the underlying socket is dead.

Split ObserveManager.try_enter_observe_mode into four pieces
(subscribe_hrefs / await_observe_notifies / enter_observe_mode /
abandon_observe_attempt), keeping try_enter_observe_mode as a thin
wrapper so its direct callers in test_observe.py are unaffected.
_attempt_observe_mode now holds _session_lock only for the subscribe
burst (each send is fire-and-forget, not a network round trip) and
re-checks self._session is sess under the lock right before committing
-- sess keeps the old session object alive, so identity can't be
recycled onto a new one, which is what makes the check sufficient
without a separate generation counter. The wait itself stays lock-free,
so a command write is never blocked behind it.

Two more bugs the same investigation turned up, fixed in the same pass
since they're direct consequences of the design above:

- async_send_command's own successful reconnect didn't downgrade observe
  mode the way the poll path's reconnect already does, leaving the same
  stale-commit problem reachable with zero concurrency at all -- just a
  write's retry succeeding while mode was observe. Replaced the poll
  path's local just_downgraded_from_observe with an instance flag both
  reconnect sites set, so either one triggers an immediate resubscribe.

- _maybe_retry_observe_mode's 600s throttle gated solely on
  last_mode_change_ts, which _set_mode only stamps on an actual
  transition -- a device that never succeeds at observe mode leaves that
  timestamp stuck at construction time, so the throttle opens once and
  never closes again, re-attempting on every single poll cycle instead
  of every 600s. Now gates on the more recent of that timestamp and a
  new _last_observe_attempt_ts, stamped on every attempt regardless of
  outcome.
2026-08-06 01:39:03 +00:00
Marc Billow 50bb893407 review: re-arm the settle window on retry, tighten comments, close a test gap
An Opus review of the three prior commits on this branch (PR #306)
turned up two real defects and a documentation/test gap, all fixed
here:

- async_send_command's retry (issue #294) armed the write-settle
  window before the retry existed, so the reconnect pause plus a
  second PUT could eat into the time meant for the confirming poll,
  reviving the revert-then-reapply symptom the window was sized to
  prevent (issue #9). Re-arm it after a successful retry lands.

- test_send_command_reconnects_and_retries_after_socket_closed relied
  on the observe-session fixture's no-op _close_session, so
  self._session never actually went None and _do_put's reconnect
  guard was never exercised -- the test passed even with that guard
  deleted. Now overrides _close_session/_connect_session to actually
  drop and rebuild the session, and asserts the reconnect happened.

- async_send_command's docstring still said "Fire-and-forget", which
  stopped being true the moment it started retrying and raising.

Also trimmed the three comment blocks the review flagged as
reproducing their commit messages verbatim, per CONTRIBUTING.md's
comment-style rules.

One review finding is not addressed here and needs a decision: the
new _close_session() call in the command-retry path isn't
synchronized against _attempt_observe_mode, which touches the session
without _session_lock. A write's reconnect can race an in-flight
observe-mode subscribe attempt and tear down the session it's using.
Fixing it properly means broadening lock scope around observe-mode
entry, which risks blocking a write behind an up to ~15s subscribe
grace period -- a tradeoff not made unilaterally here.

A second finding (dropping the old .strip()'s per-line whitespace
handling in _normalize_pem) did not reproduce against a real
certificate/key, only against the test suite's placeholder PEM body,
so it's left as-is.
2026-08-06 01:06:22 +00:00
Marc Billow 77c2d7831e fix(coordinator): retry a command once after a dead-session reconnect
async_send_command's _do_put caught any exception, logged it, and
returned -- no reconnect, no retry, no error the user could see. A
command landing on a session Samsung's firmware closed between polls
(the same 'known device behavior' _async_update_data already
reconnects around) was silently lost, with nothing to do about it but
a manual reload of the device (issue #294).

Mirror the poll path's own recovery: on failure, close the dead
session, pause, and retry the PUT once against a freshly reconnected
one. If that also fails, raise a HomeAssistantError instead of just
logging, so the user gets a visible error rather than a command that
quietly did nothing. The retry runs under the same session lock the
poll path uses, so a write landing mid-reconnect can't race a
concurrent poll cycle rebuilding the same session.
2026-08-06 00:44:35 +00:00
Marc Billow 252306838d fix(coordinator): downgrade observe mode when a device stays unreachable
When a poll fails and the immediate reconnect retry fails too,
_async_update_data returned the last-known snapshot as a degraded
success (issue #254) without ever touching observe mode. That's fine
for the data itself, but the connection-mode sensor reads straight
from self._observe.mode, and only the *successful* reconnect branch
ever changed it -- so a device that drops off the network entirely
(air-gapped, powered off, Wi-Fi down) left that sensor reporting
"Push" forever, hours after the session was actually dead (issue
#287).

Downgrade to poll mode on the failure branch too, without attempting
an immediate resubscribe: the reconnect that would normally justify
one just proved there's no live session to subscribe on. Recovery
still happens on its own once the device is reachable again, via the
existing poll-mode retry timer (_maybe_retry_observe_mode).
2026-08-06 00:42:31 +00:00
Marc Billow 455ed5b27c fix(config_flow): normalize a pasted PEM before parsing it
A PEM pasted from a text editor can carry bytes cryptography's parser
refuses outright: a UTF-8 BOM some Windows editors silently prepend,
CRLF line endings, and a stray blank line a paste can introduce
between the header/body/footer. None of those are meaningful in PEM,
but any of them surfaces as an opaque InvalidHeader with no hint of
what's wrong -- which is why the same certificate pasted from
Command Prompt's `type` (no BOM, no stray blank lines) loads fine
while the same file opened in an editor and copied doesn't (issue
#291).

Normalize at the point the pasted blob is first captured, not just
before minting the leaf cert: the same string is stored in the config
entry and reused to re-mint the leaf on a future reconfigure, so a
raw copy would keep failing every time it's read back, not just on
the first attempt.
2026-08-06 00:41:43 +00:00
Marc Billow 26e4c9c167 Merge pull request #267 from kkqq9320/fix/air-quality-state-class
fix(air_purifier): record long-term statistics for the particulate sensors
2026-08-05 19:55:56 -04:00
perseus177 2d772f16a7 feat(climate): offer legacy presets per HVAC mode, from the unit's own capability bits
The fixed list of six was offered in every mode on every legacy board. The
appliance publishes what it has as two bit maps in /mode/vs/0's options, and its
own app gates each comfort mode on a bit plus the current mode; this transcribes
that logic. WindFree also needs the mode written before it in Auto, which is
measured rather than assumed.
2026-08-05 17:24:40 +02:00
perseus177 30bd0fd2af fix(airconditioner): Good Sleep needs the mode token its duration belongs to
Sleep_<n> written on its own is answered 2.04 Changed and then discarded, so
the Number wrote nothing at all. Nano wind shares the same Comode_ slot, which
is why writing the nano preset over a running timer silently changed its
duration, and why the two sleep codes the board reports had to become presets:
a preset_mode outside preset_modes is not a state HA allows.
2026-08-05 15:46:53 +02:00
Marc Billow 4e47a1c3d9 Merge pull request #296 from perseus177/ac-good-sleep-halfhours
fix(airconditioner): good_sleep is hours, but the token counts half hours
2026-08-05 08:18:03 -04:00
Marc Billow bea5206c06 Merge pull request #293 from mbillow/claude/ac-filter-reset-cleanup
feat(airconditioner): reset the legacy filter counter locally
2026-08-05 08:16:02 -04:00
perseus177 75e985d392 style: let ruff format the write helper
`ruff format --check` is part of the Validate workflow and my hand-wrapped
version of the dict literal was not what it produces. No behaviour change.
2026-08-05 12:27:24 +02:00
perseus177 93f45cb356 fix(airconditioner): good_sleep is hours, but the token counts half hours
The Sleep_ token was published as if its value were hours. It is not: the
appliance's own app pairs a duration picker with the values it puts on the wire,
one to one, and the pairing is half hours.

  0:00 0:30 1:00 1:30 2:00 2:30 3:00 4:00 5:00 ... 12:00
     0    1    2    3    4    5    6    8   10  ...    24

So the entity capped at 12 hours actually set six, every value asked for was
halved on the appliance, and twelve hours -- the app's own maximum, stated in its
help text -- could not be reached at all. The reading is halved and the write
doubled, and the step drops to 0.5 because that is the resolution the picker
offers.

Half-hour steps are what the app offers below three hours; above that it offers
whole hours only, so a half hour up there is untested rather than known-bad. A
Number cannot change step part-way, and turning this into a Select of the app's
sixteen values would change the entity's domain on every unit that already has
one, so the step stays 0.5 throughout and the comment says why.

The descriptor's own comment used to admit the upper bound was a guess ("only 0
has been observed on hardware"). The guess of 12 was right; the unit it was
expressed in was not.
2026-08-05 12:21:10 +02:00
perseus177 e6909fb847 fix(translations): mirror the new button string into every catalog
test_every_language_mirrors_the_english_catalog is right to fail on this: a key
present only in English falls back silently at runtime, which reads as a
half-finished translation rather than a missing one.

Also fills in the same key for ko.json, which the original fix predates:
Korean's translation catalog was added after this branch was cut and never
picked up filter_time_reset either.
2026-08-05 01:48:08 +00:00
perseus177 9ee0329467 feat(airconditioner): reset the legacy filter counter locally
FilterCleanAlarm_Clear, through the same single-token options merge as every
other setting on /mode/vs/0. Measured on an ARTIK051_KRAC_18K: 2.04 Changed and
FilterTime_95 (9 h 30 min) -> FilterTime_0, still zero on a fresh DTLS session
and on every poll after; none of the other 17 tokens moved and the alarm
entries stayed Deleted.

The counter has had no reset until now, and the descriptor said so: two earlier
rounds against live hardware failed, and the conclusion drawn from them was
that the reset had to be cloud-only. That conclusion was wrong, and the way it
was reached is the interesting part -- it came from diffing every resource the
appliance reports before and after pressing reset in Samsung's app, which
showed only the counter zeroing and the alarm clearing. A trigger token cannot
show up in such a diff, because a trigger is never stored. The appliance's own
app sends this token and skips the write when the counter is already zero.

Both failures stay in the comment, because they say what this is not: writing
FilterTime_0 (the value is not writable -- 5595 -> 5595 after 69 s, 1925 ->
1925 after 65 s, two units, opposite power states), and POSTing the cloud
capability's command name to /actions/vs/0 (real name, wrong transport).

Gated on the FilterTime_ token, so it appears only where there is a counter to
reset; newer boards report filter usage through their own resource and would
need a different mechanism.
2026-08-05 01:46:29 +00:00
Marc Billow e9e278726a Merge pull request #280 from g1za/main
ITA typo fix
2026-08-04 21:40:34 -04:00
Marc Billow ccdfe7088e Merge pull request #281 from atc722/agent/nv9000d-regression-fix
Fix read-only sensor categories and add NV9000D coverage
2026-08-04 21:40:03 -04:00
Marc Billow c423efdd23 Merge pull request #292 from mbillow/claude/code-comments-guidelines-jiv4ta
Add code comment guidelines; dramatically trim excessive comments
2026-08-04 21:36:23 -04:00
Marc Billow 3918b1e5c8 Fill in the Korean translation gaps left by the AI Purify/auto-clean-stop merges
ko.json (PR #283) was written against an older en.json and never picked up
the ten keys two later PRs added: the AI Purify sensing entities
(switch.periodic_air_sensing, switch.periodic_sensing_skip_status,
number.sensing_interval, select.sensing_mode + its three states,
time.sensing_skip_start/end) and button.auto_clean_stop. Merging main
into this branch surfaced the gap via
test_every_language_mirrors_the_english_catalog.

Translated the missing entries, matching the terminology and phrasing
ko.json already uses for adjacent keys (e.g. periodic_air_sensing's
existing binary_sensor entry, auto_clean's "자동 청소"), and kept "AI
Purify" as the untranslated brand name the same way cs/es/it/nl do.
ko.json's topology now matches en.json's exactly; full suite (1213
tests), ruff, and ty all pass.
2026-08-05 01:33:08 +00:00
Marc Billow 6dd4de8b6b Merge remote-tracking branch 'origin/main' into claude/code-comments-guidelines-jiv4ta 2026-08-05 01:32:58 +00:00
Marc Billow 7086b134c0 Add code comment guidelines; dramatically trim excessive comments
CONTRIBUTING.md gains a "Code comments" section: comment the why not
the what, keep it to a sentence or two with a pointer to the load-bearing
evidence, don't re-derive a sibling's already-documented reasoning, and
move failed-attempt investigation logs out of inline comments.

Applied that policy across the codebase: condensed sprawling module
docstrings, per-entity essays, and multi-paragraph rationale blocks down
to their load-bearing conclusions, while preserving the actual "why"
(issue numbers, calibration evidence, gotchas, don't-guess rationale).
No functional code changed — verified via diff review, ruff, ty, and the
full pytest suite (1211 passed).

One inline investigation log (the AC filter-reset "tried and failed"
notes) moved to docs/investigations/ac-filter-reset.md rather than being
deleted, per the new guideline on where that kind of record belongs.
2026-08-05 01:24:17 +00:00
Marc Billow 7f66d21d73 Merge pull request #283 from atc722/agent/korean-translation
Add Korean translation
2026-08-04 21:07:42 -04:00
Marc Billow 9e12992cb4 Merge pull request #284 from rtvanhook/main
Update README.md
2026-08-04 21:01:09 -04:00
Marc Billow b59b5ae1b4 Merge pull request #290 from perseus177/ac-autoclean-stop
feat(airconditioner): stop a running auto clean, and read its progress
2026-08-04 20:53:44 -04:00
Marc Billow f8a7a1fa66 Merge pull request #268 from kkqq9320/feat/avt-ai-purify
feat(air_purifier): expose the AI Purify sensing engine on /airlevelcheck/vs/0
2026-08-04 20:02:16 -04:00
perseus177 290a348017 feat(airconditioner): stop a running auto clean, and read its progress
Three tokens describe the drying cycle these boards run after cooling, and the
switch only covered the first. AutocleanProgress_ is how far a running cycle
has got, and StopAutoClean_ is a channel for ending one early -- its presence
is what says the appliance accepts that at all, which is how the appliance's
own app gates its stop button. Both tokens are reported by the ARTIK051_KRAC_18K
that issue #136 was about, and by every KRAC fixture here.

The percentage scale is the app's own: it renders the token into a
`<progress max="100">` with a "{{value}}%" label beside it. An idle unit reports
1 rather than 0 -- the same floor the laundry firmware's progressPercentage sits
at when Ready -- so 0-vs-1 is not a reliable "is it running" test, and the
button is deliberately not gated on it.

The sensor shares AUTO_CLEAN's catalog entry the way auto_clean_legacy already
shares the switch's: same figure, different board generation, distinct key so
nothing collides if a board ever reported both.

Stacked on #289 (this branch is cut from it) -- rebase or merge that first.
2026-08-05 00:45:20 +02:00
GeekERDr 54a676f841 Update README.md 2026-08-04 05:31:24 -05:00
hoon a38437fca4 Add Korean translation 2026-08-04 17:13:32 +09:00
kkqq9320 15279066b5 review: move the state_class into the shared tuple's fourth column
The frozenset was a parallel structure for a per-row fact, and the comment
above the tuple already described it as a fourth column -- so the comment
promised the right shape and the code did something else. Fixed to the shape
the comment described: _AIR_QUALITY_SENSORS carries state_class per row and
the comprehension unpacks it, with _RECORDED_AIR_QUALITY and its duplicated
rationale block deleted.

air_monitor imports the same rows and now unpacks four, but discards the
fourth. That board (issue #210) has stamped all five readings as
`measurement` since it was added; consuming the column would silently drop
long-term statistics for Odor and CleanLevel on shipped devices, which is a
behaviour change this branch has no evidence to make. The grade/concentration
split stays scoped to the air purifier.

test_shared_sensor_tuple_keeps_its_three_column_shape asserted the premise
this replaces -- that widening the tuple breaks air_monitor's import -- so it
is replaced rather than renumbered: one test that the rows carry their own
state_class, and one that air_monitor still imports and still stamps all five.
2026-08-04 15:25:12 +09:00
hoon 3d0dca20f9 Add NV9000D cooktop coverage and fix sensor setup 2026-08-04 14:47:42 +09:00
kkqq9320 96d06369bc review: floor the sensing interval at one minute
Dropping native_min to 0 fixed the read range and quietly opened a write:
native_min governs what the user can enter, not just what renders, so 0
became enterable and would have gone out as periodicSensingInterval "0".
Nothing establishes what that does to this board -- both fixtures report 600,
the app's smallest choice is 10 min, and 60 s is the lowest value confirmed
accepted. The two precedents leaned on differ in exactly the way that matters:
oven.cook_time and operational.delay_start_hours sit at a zero floor under a
value where 0 is a real setting ("no timer", "no delay").

One minute is also the resolution this board reports results at.
lastSensingTime lands on an exact minute on every sample from the AVT-WW-TP1
and A-VTWW-TP2 boards -- both fixtures, plus eleven consecutive live readings
-- where the TP1X/AC/hood boards report arbitrary seconds. A sub-minute
interval is unobservable here whether or not the board honours it.

So native_min goes to 1 rather than 0, and the read rounds up instead of to
nearest so a sub-minute reading renders as 1 rather than falling below the
entity's own floor. The write still refuses anything under a minute -- a None
return, the silent no-op range_hood._lamp_level_write uses for a level the
device didn't advertise -- since native_min only guards the UI path, not a
service call.
2026-08-04 14:44:54 +09:00
g1za 330b2f344f ITA typo fix 2026-08-04 07:34:53 +02:00
kkqq9320 a5484f746a review: unfold AI Purify into one entity per field
Review feedback on #268. The largest change is that the sensing-mode select
no longer folds two device fields into one control.

periodicSensingActivationState and autoExeState are independent knobs, and the
appliance presents them that way -- its own UI has an on/off for AI Purify
separately from the three mode choices. Folding them lost two things: a
configured action was invisible while the feature was off, and no select
option could toggle the feature without also overwriting the action. The
switch was not the duplicate it looked like.

So the switch now owns periodicSensingActivationState alone, and the select
owns autoExeState alone. That resolves the hardcoded-options finding at the
source rather than working around it: the select reads supportedAutoExeState
via options_field -- the same shape SOUND_MODE already uses for
supportedModes -- instead of carrying a typed-in tuple, so a board advertising
a fourth action is accepted on both the options list and the write path.
_sensing_mode, _sensing_mode_write and _SENSING_MODE_BODIES are all gone with
the fold.

Option slugs are now the advertised values lowercased (off / airpurify /
alarm) rather than invented names. The catalog carries the labels, so the two
'off's stay distinguishable in the UI: the switch's means the unit isn't
sampling, the select's means it samples and doesn't act on the reading -- what
the app calls "sensing only".

Also from the review:

  * _interval_minutes checks `is None` so a reported 0 stays 0, and native_min
    drops to 0 since sub-30s values round there. oven.cook_time and
    operational's delay hours are the precedent -- both convert a device time
    value and floor at zero. The Number-rather-than-Select choice is now
    stated in the write helper: the app offers three fixed intervals, but this
    resource advertises no supported-values or range field (supportedAutoExeState
    sits right beside it, so the board does advertise constraints where it has
    them) and it accepted 60 s, six times finer than the app's smallest choice.
  * _skip_time_write no longer splices a malformed half back onto the wire.
    The read side already refuses one it can't parse; the write side now
    zeroes it to match.
  * air_sensing_state and last_air_sensing_level lose enabled_default=False,
    matching range_hood.AIR_LEVEL_CHECK. Hiding two of three read-only keys
    while claiming key parity with that capability -- and leaving the third
    visible -- had no justification behind it.
  * The catalog-parity test drops periodic_air_sensing from its key set: that
    key is a SwitchDesc here and a BinarySensorDesc on the hood, so the two
    live in different platform catalogs and are worded differently. The claim
    now covers only the three read-only sensor keys, where it holds.
  * Tests route through the descriptors (_desc(key).write_fn / .value_fn)
    rather than module-private helpers, matching test_air_monitor_capabilities.

startSensingOnce stays unbound, now explicitly rather than by omission -- the
module comment records it as deferred. It looks like a one-shot "sense now"
button, but this board acknowledges writes it discards, and nothing has
confirmed the side effect yet.

Goldens are untouched: the key set is unchanged, only sensing_mode's value
moves from the folded slug to the raw autoExeState.
2026-08-04 14:20:58 +09:00
kkqq9320 412fff9b99 feat(air_purifier): expose the AI Purify sensing engine on /airlevelcheck/vs/0
/airlevelcheck/vs/0 has been covered as "periodic air-quality sensing
scheduler plumbing" since the registry gained a coverage stub for it. Two
AVT-WW-TP1-23-AXX500 dumps (issues #84 and #190) show it is not plumbing: it
drives the feature the SmartThings app calls AI Purify, where the unit wakes
on a timer, samples the air, and optionally acts on the result. Every field
is named, none are opaque, and two of them are already user-set on the
reported units.

The select's three on-states are the app's own options rather than an
invented grouping -- it offers exactly "Sensing only" (sample, take no
action), "Auto clean" (purify while the air reads bad, stop once it
improves) and "Get notified" (raise a SmartThings notification). Labels were
transcribed from the Korean app and rendered in English; the auto-stop half
of "Auto clean" is the app's own description and is not otherwise visible in
the dump, which reports only the selected autoExeState. The remaining entity
names follow their raw fields rather than inventing a concept -- the skip
window is "sensing skip", after periodicSensingSkipStatus/Time.

Three of this registry's four board families report the resource with the
same field names -- TP1X_DA-AC-AIR (#130), A-VTWW-TP2 (#151) and AVT-WW-TP1
(#84, #190). Only ARTIK051_TVTL (#56) has no such href, and its golden is
unchanged. Bound unconditionally rather than behind a match_fn; the one field
that genuinely varies (periodicSensingInterval, absent on the #130 board) is
gated per-entity, so that board gets eight entities instead of nine rather
than a broken one.

range_hood.AIR_LEVEL_CHECK already models this same href, and its read-only
keys are reused verbatim here so both families share one catalog entry. It is
deliberately not imported: the hood exposes periodic_air_sensing as a
read-only BinarySensorDesc and this board needs a writable SwitchDesc on that
key, so reusing the hood's capability would migrate every hood user's entity
to a different platform.

Every write was exercised on AVT-WW-TP1-23-AXX500 hardware. This board hands
out 2.04 for writes it silently discards (see HEPA_FILTER's filter-reset
note), so an echo proves nothing -- each was judged by whether the value
survived a reconnect, which forces a new DTLS session, fresh discovery and a
fresh observe of the href, leaving no cached state to read back:

  * sensing_mode's combined two-field PUT lands both fields, both ways:
    sensing_only -> auto_purify raises autoExeState with activation still On,
    and back again lowers it.
  * The sensing-skip switch holds Off -> On and back.
  * The half-preserving time writes hold: from 13:00-23:00, writing
    start=07:30 then end=22:00 left the device on '07302200' -- each write
    kept the half it wasn't given.
  * periodic_air_sensing and sensing_interval: writing 60 s drove an observed
    ~60 s sensing cycle.
  * The read side of the skip window is separately cross-confirmed on two
    units: #84's sits at the inert '00000000', #190's carries a real
    '03002300' (03:00-23:00), which is what pins the HHMMHHMM split.
  * The other two families get the writes on field-shape grounds -- the same
    basis on which they already share MODE, HEPA_FILTER and the air-quality
    sensors.

range_hood._timestamp moves to common.epoch_to_utc so both callers share it,
matching how filter_usage_percent was shared. No behaviour change.

Every existing entity is untouched: the three golden updates are purely
additive, no renames, no unit or device_class changes.
2026-08-04 12:57:03 +09:00
Marc Billow 0c2e219464 Merge pull request #273 from mbillow/claude/device-discovery-config-flow-dmeagp
Rebuild device discovery on the ClientHello probe and resolve identity up front
2026-08-03 20:36:17 -04:00
Marc Billow b5699badbe Stop the v1 migration re-keying devices onto a placeholder serial
_serial_from_unique_id took the entry's unique_id at face value. That is
right for an entry whose unique_id holds a real serial, but the unique_id
records what the config flow believed when it ran, not what the registry
holds now -- and for two firmware families those are different things.

Entries added before the placeholder rules landed (issues #83/#189) were
keyed on the placeholder itself: `localthings_Nothing(SVC)` for the
ARTIK051_DONGLE_REF dongles, `localthings_FFFFFFFFFFFFFFF` for the
DA_WM_A51_20_COMMON laundry boards. The coordinator has been resolving
those same boards to the host ever since, so their devices and entities
are host-keyed today. Migration read the placeholder back off the
unique_id, decided the host-keyed rows were the stale ones, and rewrote
them onto the placeholder -- reintroducing exactly the collision those
issues exist to prevent, since every unit of the family reports the same
placeholder and would go back to sharing entity unique_ids.

Run the recovered string through resolve_serial, which is the whole point
of that helper being shared. The old `host:port` special case stays: it's
a config-flow-history artifact rather than a device-reported serial, so
resolve_serial can't recognize it.

The repair pass had a second, narrower way to lose data. Removing a device
takes its entities with it (entity_registry.async_device_modified), and
the removal branch ran after the entity pass -- so an entity that had just
been re-keyed rather than removed, because its serial-keyed key was free,
was destroyed a few lines later along with the entity_id, name and area
the rewrite existed to preserve. Move surviving entities onto the device
they now belong to before removing the duplicate.

Reachable when the serial-keyed device exists but a given entity's
serial-keyed key doesn't -- e.g. the user deleted the visible duplicate by
hand, which is the first thing anyone hitting #236 tries.

Also fold the modelNum `<model>|<board>` split into resolve_model beside
resolve_serial. The config flow and _run_discovery each had their own copy
under a comment promising they matched; a device that renames itself on
the first poll is what a drift there looks like.
2026-08-04 00:12:40 +00:00
Marc Billow d5adf311da Normalize cs.json to LF line endings
The Czech catalog was the only file in the repo still using CRLF, which
made every edit to it show up as a whole-file rewrite in diffs and hid the
one line that actually changed.

Content is byte-identical apart from the line endings, and the file now
matches the exact json.dumps(indent=2, ensure_ascii=False) formatting the
other four catalogs already use.
2026-08-03 20:33:30 +00:00
Marc Billow 6033709f24 Replace the blanket "cannot connect" with a real failure taxonomy
Adding a device had one message for nearly every way it could fail: "Cannot
connect to the device. Verify the IP address is reachable and the CA
credentials are correct." That covers an IP with nothing on it, an
appliance on cloud-only firmware, a device still holding the session from
the last attempt, a device that answered and rejected our certificate, and
Home Assistant having no internet to reach Samsung's cloud. Only one of
those is fixed by checking the IP and the CA credentials, and the message
gave no way to tell which one you had.

The probe already gathers enough to tell them apart, so classify it:

- cert_rejected     the appliance sent a certificate alert. The CA
                    credentials aren't the AC14K_M CA it trusts, or they
                    don't pair. Far and away the most common real setup
                    mistake, and previously indistinguishable from a typo
                    in the IP address.
- handshake_failed  a fatal alert unrelated to the certificate (protocol or
                    cipher mismatch) -- no amount of fiddling with CA
                    credentials will fix it.
- handshake_timeout the ClientHello probe proved a DTLS server is right
                    there, but the handshake never finished. Usually the
                    appliance is still holding the association from a
                    previous attempt; it clears on its own in about a
                    minute.
- ports_closed      ICMP port-unreachable on the whole range: something is
                    at that address and it isn't exposing a local API.
                    Cloud-only firmware (TCP 8888 only) lands here.
- no_dtls_server    some ports open|filtered, none speaking DTLS -- likely
                    another device on that IP.
- no_response       nothing came back at all.
- cloud_unreachable couldn't reach Samsung's cloud gateway for the UUID.
                    An internet problem on HA's side, not the appliance's.
- unexpected_response  authenticated fine, then returned something we can't
                    read. Neither connectivity nor credentials.

Certificate alerts are read back out of the error text OpenSSL puts in
DtlsCoapSession's ConnectionError, not by re-probing. The library's
diagnostic probe would report the alert authoritatively, but it drives the
handshake far enough to commit association state on the device -- and an
orphaned association is exactly what makes the *next* attempt time out
(RFC 6347 4.2.8), which is a bad trade on a path the user is about to
retry.

Telling ports_closed from no_response needs the UDP sweep to separate a
refusal from an unreachable. Both leave a port "not live", but ECONNREFUSED
is a *response* -- the host is there -- while EHOSTUNREACH/ENETUNREACH mean
the datagram never left. A wrong IP on the local subnet never answers ARP
and fails every send that way, so treating the two alike would have told
those users their appliance was on cloud-only firmware. The sweep now
returns live/refused/unreachable separately, and the preferred-port rescue
moved out of it into _sweep_ports: the rescue is a candidate-selection
decision, and folding it into the sweep's verdict destroyed the evidence
the message is built from.

Every failure carries the error key that fits it, so the flow maps
exceptions instead of guessing, and logs the specifics (alert name, per-port
outcome, response code) at warning level -- the messages that mention the
log now have something to point at.

Certificate re-minting for a reused leaf is also narrower and more correct
as a result: it now triggers on CertRejected specifically, rather than on
"every attempt raised ConnectionError and a port was confirmed".

All five translation catalogs carry the eight new messages. The non-English
ones are my own work rather than a native speaker's; corrections welcome.
2026-08-03 20:29:53 +00:00
Marc Billow 15be379243 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.
2026-08-03 20:14:54 +00:00
Marc Billow cdaff4a1ca Merge pull request #272 from mbillow/claude/issue-triaging-fuq5sn
Issue triage batch: dehumidifier, AC, dryer, fridge, dishwasher, climate fixes
2026-08-03 15:45:12 -04:00
kkqq9320 69844d9829 fix(air_purifier): record long-term statistics for the particulate sensors
dust / fine_dust / super_fine_dust show live values fine but Home Assistant
keeps no long-term statistics for them, so once recorder's purge window passes
(10 days by default) the history is gone and they can't back a long-range
air-quality graph.

HA only writes long-term statistics for sensors that declare a state_class,
and AIR_QUALITY's descriptors set none -- the entities come up carrying just
an icon. The values were never the problem: common.sensor_item_value already
returns int. Three sensors in this same module (filter_progress,
fan_speed_level, hepa_filter_usage) already declare one, so this reads as an
oversight rather than a decision.

Only the three particulate readings are stamped. They fall monotonically with
particle size on three independent board families -- 11/9/5 on ARTIK051_TVTL
(issue #56), 10/9/6 on AVT-WW-TP1 (issue #190), 18/14/9 on the range hood --
which is concentration behaviour, and averaging it over time is meaningful.
Odor and CleanLevel read 0-2 on every fixture and look like graded indices,
where the mean of a grade isn't obviously meaningful, so they are left alone
rather than guessed into statistics.

Worth flagging for the review: air_monitor.SENSORS already stamps all five of
these, and its module docstring describes that as "matching
air_purifier.AIR_QUALITY's existing precedent" -- a precedent this module did
not actually set. Extending to all five here is a one-line change if
consistency is preferred over the grade/concentration split.

The state_class is carried in a separate key set rather than a fourth tuple
column because air_monitor.py imports _AIR_QUALITY_SENSORS and unpacks it as a
triple; widening it breaks that module's import outright. Two of the new tests
guard exactly that coupling.

No device_class or unit is asserted: pm1/pm25/pm10 with µg/m³ would claim the
reading is a mass concentration, which no dump states. That is a separate call
from making the series recordable at all.

Metadata only -- no key, name, value or unit changes, so no entity changes
identity and every golden is untouched. Statistics start accumulating from the
upgrade onward; existing short-term history is unaffected.
2026-08-03 14:34:57 +09:00
93 changed files with 13779 additions and 4929 deletions
+34
View File
@@ -19,6 +19,40 @@ file covers how changes get committed.
assistant, or tool that helped produce the change. The commit is
attributed entirely to the accountable human.
## Code comments
This codebase reverse-engineers undocumented device APIs, so comments
recording *why* a decision was made (a calibration, a rejected write, an
issue number a quirk was confirmed against) are genuinely valuable — more
valuable than in most codebases. That's exactly why comments here need
discipline: it's easy for "explain the reasoning" to slide into "narrate
the whole investigation," and a file where every line has a paragraph
under it is as hard to read as one with no comments at all. Keep the
conclusion; cut the journey.
- **Comment the "why," never the "what."** If a comment just restates what
the next line already says, delete it. Code should read clearly enough
on its own that comments are only needed for the non-obvious.
- **One or two sentences, not an essay.** State the conclusion and the one
piece of evidence that makes it credible (an issue number, a model name,
a single confirming observation). Don't reproduce the full
investigation — every dump checked, every attempt that failed, every
hypothesis considered and discarded. A future reader needs to trust the
conclusion and know where to look if they need to redo the work, not
relive it.
- **A pointer, not a re-derivation.** Cite the issue/model once; don't
re-explain a sibling function's already-documented reasoning. Reference
it (`same reasoning as X above`) instead of restating it.
- **Module/class docstrings are a short orientation, not a design doc.**
A few lines on purpose and any cross-cutting invariant is enough.
- **Failed-attempt logs don't belong inline.** If an investigation into an
unsolved problem produced real negative results worth preserving (e.g. a
reset mechanism nobody could find), put them in an issue or docs, not a
block comment several times longer than the code it sits above.
- **When in doubt, cut.** If deleting a comment wouldn't lose real
understanding, it's noise. Prefer trimming an existing comment over
adding a new one.
## For AI coding agents
See `AGENTS.md`.
+1 -1
View File
@@ -6,4 +6,4 @@ FROM ghcr.io/home-assistant/home-assistant:stable
# repeats the install attempt on every container recreate. Baking
# smartthings-local into the image keeps the dev container usable
# offline and avoids relying on that runtime install path.
RUN pip3 install --no-cache-dir "smartthings-local>=0.1.0"
RUN pip3 install --no-cache-dir "smartthings-local>=0.1.2"
+78 -5
View File
@@ -63,7 +63,7 @@ Other Tizen RT / DAWIT-family appliances almost certainly speak the same protoco
nmap -Pn -sU -p 49152-49160 "$APPLIANCE_IP"
```
- Any UDP port in `49152-49160` open|filtered with a DTLS handshake responding: newer firmware (Tizen RT 3.x, DAWIT 3.0+). This is what the integration talks to. Most devices answer on `49154`/`49155`, but some builds bind lower (e.g. `49153`). The config flow sweeps the whole range and auto-detects the live port, so you don't need to know which one your device uses.
- Any UDP port in `49152-49160` open|filtered with a DTLS handshake responding: newer firmware (Tizen RT 3.x, DAWIT 3.0+). This is what the integration talks to. Most devices answer on `49154`/`49155`, but some builds bind lower (e.g. `49153`). The config flow probes the whole range and auto-detects the live port, so you don't need to know which one your device uses.
- Only `8888/tcp` open (token-based HTTPS): older firmware (roughly 2018-2022). **Not supported here.**
---
@@ -82,10 +82,10 @@ This repo doesn't include the needed CA bundle. For an example of how to obtain
2. Restart HA.
3. **Settings > Devices & Services > Add Integration > LocalThings.**
4. First device: paste the appliance's IP, plus the contents of the CA private and public key from Part 2.
5. The flow fetches the current UUID from Samsung's cloud gateway, mints a leaf cert signed by your CA, sweeps the `49152-49160` range to find the live DTLS port, and confirms the device answers `/device/0`. On success it creates the config entry and detects the device type automatically.
6. Every subsequent device only asks for the host IP; the stored CA credentials are reused to mint that device's leaf cert.
5. The flow sends a DTLS `ClientHello` to every port in the `49152-49160` range at once and keeps the one that answers -- a real DTLS server identifies itself in about one round trip, and the probe stops there, so nothing is left behind on the appliance. Only that port is then given a real certificate handshake: it fetches the current UUID from Samsung's cloud gateway, mints a leaf cert signed by your CA, and reads the device's identity and `/device/0`. On success it creates the config entry, already knowing the appliance's serial, model, and type.
6. Every subsequent device only asks for the host IP. The stored CA credentials are reused, and so is the leaf cert itself -- every appliance accepts the same one -- so adding a second appliance doesn't depend on Samsung's cloud being reachable at all. If a device rejects the reused cert (the UUID behind it does rotate), the flow mints a fresh one and retries by itself.
Entities appear under one HA device per appliance, named `Samsung Appliance (<ip>)` initially. Rename freely: the config entry is keyed on the device's serial, not the name.
Entities appear under one HA device per appliance, named for the appliance's type and model. Rename freely: the device is keyed on its serial, not its name.
---
@@ -98,6 +98,70 @@ Each device has its own **Configure** option in Settings > Devices & Services, u
---
## 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.
---
## Development
### Docker Compose dev environment
@@ -131,10 +195,12 @@ A large suite covering registry composition, discovery, entity descriptors, and
custom_components/localthings/
manifest.json Requirements (incl. the smartthings-local PyPI dep), version, domain
__init__.py async_setup_entry / async_unload_entry
config_flow.py UUID fetch, leaf cert minting, port probing, config entry creation
config_flow.py ClientHello port probe, UUID fetch, leaf cert minting, identity resolution
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 +238,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
@@ -194,6 +265,8 @@ Samsung's firmware occasionally drops the DTLS session briefly — this is norma
If reconnects become persistent (more than a handful per minute), something's actually wrong. Check the appliance's Wi-Fi link first, then look for a competing DTLS client on the LAN — only one active session per appliance is allowed at a time.
Deregistering a device in SmartThings causes a reset of its network settings as soon as it accesses Samsung's servers, dropping it off Wi-Fi until it's re-onboarded through the SmartThings app. As such, consider keeping devices registered even if egress-blocked, to avoid them resetting upon brief internet access.
### Multi-subdevice ("2-in-1") air conditioner systems
Some Samsung installs run more than one indoor subdevice off a single outdoor unit, all reachable over the *one* IP/DTLS session your config entry connects to (a floor-standing + wall-mounted 2-in-1 is a common shape). The integration discovers any sibling subdevices automatically, once, right after the first successful poll — there's nothing to configure. Each discovered subdevice gets its own HA device (linked to the main one via "via device") and its own `climate` card, so it lands in its own room in the dashboard instead of being invisible or mixed into the master's state.
+165 -41
View File
@@ -6,47 +6,176 @@ 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 homeassistant.helpers.typing import ConfigType
from .const import DOMAIN, PLATFORMS
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.
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 -- no need to reach the device
to recover it. Anything unrecoverable resolves to the host, matching
what the coordinator seeded such an entry with anyway.
The recovered string goes back through resolve_serial rather than being
taken at face value: entries created before the placeholder rules
(issues #83/#189) were keyed on the placeholder itself, while the
coordinator has since resolved those same boards to the host.
Re-keying onto the placeholder would reintroduce the collision those
issues are about -- two units of a family sharing the same placeholder
would share entity unique_ids again. A later wrinkle, same root cause:
for a stretch the flow wrote `host:port` while the coordinator wrote
`host`; collapsed here to the coordinator's form too.
"""
host = entry.data[CONF_HOST]
prefix = f"{DOMAIN}_"
unique_id = entry.unique_id or ""
if not unique_id.startswith(prefix):
return host
serial = unique_id[len(prefix) :]
if serial == f"{host}:{entry.data.get(CONF_PORT)}":
return host
return resolve_serial(serial, host)
@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 poll.
Anything that registered in between -- the connection-mode sensor
especially, added unconditionally rather than from `bound` -- was
written into the registry keyed on the IP permanently, 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 possible -- an entity keeps its
entity_id, name, area and automations. Only possible when the
serial-keyed key is still free; where both exist the placeholder-keyed
one is the dead duplicate (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.
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:
# Removing a device takes its entities with it. Anything still
# attached here was re-keyed rather than removed above -- the
# surviving copy, not a duplicate -- so move it onto the device
# it now belongs to before the removal destroys it too.
for entity in er.async_entries_for_device(
ent_reg, device.id, include_disabled_entities=True
):
ent_reg.async_update_entity(entity.entity_id, device_id=existing.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:
return False # downgrade: this release doesn't know the newer shape
if entry.version == 1:
serial = entry.data.get(CONF_SERIAL) or _serial_from_unique_id(entry)
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)
try:
await coordinator.async_config_entry_first_refresh()
except Exception as err:
# `_poll_once` deliberately leaves the session up on a `TimeoutError`
# (the transfer may just be slow -- see its docstring), so a refresh
# that fails that way ends here with a live, bound UDP socket that
# nothing would ever close. HA retries setup on its own backoff with
# a *new* coordinator, and each device's source port is fixed by
# design (`_local_source_port`), so an abandoned socket squats the
# exact port the next attempt binds -- SO_REUSEADDR lets that bind
# succeed, leaving two sockets racing for the device's datagrams.
# `_poll_once` deliberately leaves the session up on a TimeoutError
# (see its docstring), so a refresh failing that way leaves a live,
# bound UDP socket nothing would ever close. HA retries setup with a
# new coordinator, and the source port is fixed by design
# (`_local_source_port`), so an abandoned socket would squat the
# exact port the next attempt binds.
await coordinator.async_close()
raise ConfigEntryNotReady(f"Cannot connect to device: {err}") from err
hass.data[DOMAIN][entry.entry_id] = coordinator
# Send the DTLS close_notify on Core shutdown, not just on unload (issue
# #254). `async_close` otherwise only runs via `async_unload_entry`, and
# HA does not unload entries on a plain Core restart -- so a restart left
# the previous run's association orphaned on the appliance, which is what
# makes the *next* run's handshake time out. Complements the fixed source
# port, which covers the unclean-exit case this cannot (see
# `_local_source_port`).
# #254): HA doesn't unload entries on a plain Core restart, so a restart
# left the previous run's association orphaned, making the next
# handshake time out. Complements the fixed source port, which covers
# the unclean-exit case this can't.
#
# A coroutine listener, not one that spawns its own task: the event bus
# runs it as a hass-tracked job, so the close is awaited by the
# `async_block_till_done()` inside `hass.async_stop`. A detached task
# would likely be cancelled mid-shutdown -- the exact no-close_notify
# case this exists to prevent.
# runs it as a hass-tracked job, awaited by `async_block_till_done()`
# inside `hass.async_stop`. A detached task would likely be cancelled
# mid-shutdown -- the exact case this exists to prevent.
async def _async_close_on_stop(_event: Event) -> None:
await coordinator.async_close()
@@ -65,31 +194,26 @@ async def async_remove_config_entry_device(
) -> bool:
"""Allow deleting a device this entry no longer provides (issue #214).
Defining this at all is what makes Home Assistant offer the "Delete
device" action for our devices; without it a device registry entry
belonging to a loaded config entry can never be removed from the UI. That
matters because a subdevice's HA device outlives the discovery that
created it: a candidate that materialized under an older release (issue
#214's phantom second air conditioner, born from an unused /device/1 slot
reporting the appliance's energy counter -- see
registry/subdevices.py's liveness gate) leaves a device entry behind that
nothing recreates and nothing cleans up once the gate stops materializing
it. Same for a sibling that a firmware update stops exposing.
Defining this at all is what makes HA offer the "Delete device" action;
without it, a device belonging to a loaded config entry can never be
removed from the UI. That matters because a subdevice's HA device
outlives the discovery that created it: a candidate materialized under
an older release (issue #214's phantom second air conditioner, born
from an unused slot reporting the appliance's energy counter -- see
registry/subdevices.py's liveness gate) leaves a device entry nothing
recreates or cleans up once the gate stops materializing it. Same for a
sibling a firmware update stops exposing.
Removal is refused for devices this entry *does* currently provide --
HA would recreate them on the next entity add, so allowing it would look
like the delete silently failed. Deliberately no automatic pruning at
discovery time: subdevice enumeration is one-shot and a sibling can fail
to answer for a poll (issue #205 is exactly that on the reference
hardware), so auto-removal would throw away a real subdevice's name,
area and automation references on a transient miss. The user gets the
button; the integration doesn't guess.
Removal is refused for devices this entry does currently provide -- HA
would recreate them on the next entity add. Deliberately no automatic
pruning at discovery time: a sibling can fail to answer for a single
poll (issue #205), so auto-removal would throw away a real subdevice's
name/area/automations on a transient miss. The user gets the button;
the integration doesn't guess.
"""
coordinator: LocalThingsCoordinator | None = hass.data.get(DOMAIN, {}).get(entry.entry_id)
if coordinator is None:
# Entry not loaded (or already unloaded) -- nothing is claiming this
# device, so there's nothing to protect it from being removed.
return True
return True # entry not loaded -- nothing claims this device
live = set(coordinator.device_info.get("identifiers") or set())
for subdevice in coordinator.subdevices:
live |= set(coordinator.device_info_for(subdevice).get("identifiers") or set())
+257 -159
View File
@@ -1,26 +1,27 @@
"""Climate platform for Local Things.
The first composite entity in this integration: a single HA climate card that
unifies several OCF resources of a Samsung air conditioner. Unlike every other
platform here (one descriptor -> one resource field), a climate entity reads
power, HVAC mode, current/target temperature, fan (wind) strength, swing (wind
direction) and the convenient-mode preset from *different* resources.
The first composite entity in this integration: a single HA climate card
that unifies several OCF resources of a Samsung air conditioner. Unlike
every other platform here (one descriptor -> one resource field), a climate
entity reads power, HVAC mode, current/target temperature, fan (wind)
strength, swing (wind direction) and the convenient-mode preset from
*different* resources.
It binds one primary `BoundEntity` (the `/mode/vs/0` capability) so the registry
still tracks it, and reads the sibling resources straight from the coordinator
snapshot via `coordinator.resource(href)` -- the same cross-resource read that
`number.py` (live range/unit) and `select.py` (options callable) already do.
It binds one primary `BoundEntity` (the `/mode/vs/0` capability) so the
registry still tracks it, and reads the sibling resources straight from the
coordinator snapshot via `coordinator.resource(href)`.
Writes go through `coordinator.async_send_command(bound, (kind, value))`: the
CLIMATE capability's `write_fn` maps each `(kind, value)` payload to the right
`(path_segs, body)`, and `async_send_command` POSTs to those path_segs and
applies the optimistic value/settle guard to that same href -- not the bound
`/mode/vs/0` href -- so one descriptor drives writes to, and gets fresh state
back for, power, mode, temperature and wind resources alike.
Writes go through `coordinator.async_send_command(bound, (kind, value))`:
the CLIMATE capability's `write_fn` maps each `(kind, value)` payload to the
right `(path_segs, body)`, and `async_send_command` applies the optimistic
value/settle guard to that resource's own href -- not the bound
`/mode/vs/0` href -- so one descriptor drives writes across power, mode,
temperature and wind resources alike.
"""
from __future__ import annotations
import asyncio
import logging
from homeassistant.components.climate import (
@@ -79,7 +80,11 @@ from .registry.capabilities.airconditioner import (
HREF_WIND_STRENGTH as WIND_STRENGTH_HREF,
)
from .registry.capabilities.airconditioner import (
extend_option_code_bit,
has_extend_option_code,
has_option_code,
is_legacy_board,
option_code_bit,
)
from .registry.capabilities.common import normalize_temp_unit
from .registry.entities import ClimateDesc
@@ -95,56 +100,46 @@ _SUPPORTED_FIELD = "x.com.samsung.da.supportedModes"
_DEVICE_TO_HVAC: dict[str, HVACMode] = {
"Cool": HVACMode.COOL,
"Dry": HVACMode.DRY,
# Fan-only is spelled 'Wind' on some boards (e.g. TP1X_DA-AC-RAC-01001) and
# 'Fan' on others (e.g. TP1X_DA-AC-RAC-01011); both map to FAN_ONLY. The
# reverse write can't rely on this map alone (two codes, one HA value) --
# _device_code_for_hvac() resolves the code from the unit's own
# supportedModes, so this is only a fallback for a unit reporting no
# supportedModes at all. 'Fan' is listed first so the {v: k} reverse
# comprehension below has 'Wind' win that fallback (last-key-wins),
# preserving the original single-spelling behavior rather than silently
# flipping it when 'Fan' was added.
# Fan-only is spelled 'Wind' on some boards and 'Fan' on others; both map
# to FAN_ONLY. _device_code_for_hvac() resolves the write-side code from
# the unit's own supportedModes, so this reverse map is only a fallback
# for a unit with no supportedModes at all. 'Fan' listed first so the
# {v: k} comprehension below has 'Wind' win that fallback (last-key-wins,
# preserving the original single-spelling behavior).
"Fan": HVACMode.FAN_ONLY,
"Wind": HVACMode.FAN_ONLY,
# The device's 'Auto' is a single-setpoint "device decides" mode -> HA
# HVACMode.AUTO (renders "Auto"). Not HEAT_COOL: that renders "Heat/cool"
# and implies a two-setpoint heat+cool range these single-setpoint units
# (including cool-only models) don't have.
# A single-setpoint "device decides" mode -> HA AUTO, not HEAT_COOL
# (which implies a two-setpoint heat+cool range these units don't have).
"Auto": HVACMode.AUTO,
"Heat": HVACMode.HEAT,
}
_HVAC_TO_DEVICE = {v: k for k, v in _DEVICE_TO_HVAC.items()}
# AI-driven auto-comfort mode (issue #93, A-CAWW-TP2-20-COMMON). Not a flat
# _DEVICE_TO_HVAC entry: 'AIComfort' isn't a distinct thermodynamic operation
# like Cool/Dry/Heat, it's an AI overlay on top of the device's own 'Auto'
# behavior -- confirmed by this unit reporting both 'Auto' and 'AIComfort' as
# separate, mutually-exclusive entries in /mode/vs/0's supportedModes. Modeled
# the idiomatic HA way instead: hvac_mode reports AUTO (same as the plain
# 'Auto' code maps to) and a dedicated 'ai_comfort' preset carries the
# distinction a bare hvac_mode can't. Not reachable via async_set_hvac_mode --
# entered/left only through the preset, since there's no dedicated HVACMode
# value for it to write back to.
# AI-driven auto-comfort mode (issue #93, A-CAWW-TP2-20-COMMON): 'AIComfort'
# isn't a distinct thermodynamic operation like Cool/Dry/Heat, it's an AI
# overlay on the device's own 'Auto' -- the unit reports both as separate,
# mutually-exclusive supportedModes entries. hvac_mode reports AUTO (same as
# plain 'Auto') and a dedicated 'ai_comfort' preset carries the distinction.
# Not reachable via async_set_hvac_mode -- entered/left only through the
# preset, since there's no HVACMode value for it to write back to.
_AI_COMFORT_MODE = "AIComfort"
PRESET_AI_COMFORT = "ai_comfort"
# Codes that appear in /mode/vs/0's supportedModes but are option/capability
# flags rather than selectable thermodynamic operations -- dropped silently
# (no _warn_unmapped call) rather than every owner of an affected unit
# tripping the issue #93 warning on every start.
# Codes in /mode/vs/0's supportedModes that are option/capability flags, not
# selectable thermodynamic operations -- dropped silently rather than
# tripping the issue #93 unmapped-code warning on every start.
#
# HOMECARE_WIZARD_V2 (issue #235, TP2X_RAC_20K): also appears in
# /configuration/vs/0's x.com.samsung.da.airconOptionList alongside
# PRODUCT_GLOBAL/AI_3.0/SingleCommand_1 -- clearly a capability flag, not a
# mode, on that resource. The unit's own `modes` (current mode) never
# reported it as active across the reporter's logs, only ever a real
# thermodynamic mode -- consistent with it being echoed into supportedModes
# rather than genuinely selectable. Unlike _AI_COMFORT_MODE above, it isn't
# modeled as a preset: there's no confirmation it's user-selectable at all,
# so silently dropping it (rather than guessing a write contract) is the
# 'don't guess' rule applied to a mode code instead of a resource field.
# HOMECARE_WIZARD_V2 (issue #235, TP2X_RAC_20K) also appears in
# /configuration/vs/0's airconOptionList alongside other capability flags,
# and the unit's own current `modes` never reported it active -- consistent
# with an echoed capability flag, not a genuine mode. Unlike _AI_COMFORT_MODE,
# not modeled as a preset either: nothing confirms it's user-selectable.
_NON_HVAC_OPTION_CODES = frozenset({"HOMECARE_WIZARD_V2"})
# Seconds to let a legacy board settle into Cool before the WindFree token is
# written after it -- see _legacy_preset_needs_cool for the measurement.
_NANO_AFTER_MODE_DELAY = 3
# Fan (wind strength): device codes "0".."4" -> HA standard fan constants where
# a clean match exists so they auto-localize; "turbo" is custom (translated).
_DEVICE_TO_FAN: dict[str, str] = {
@@ -166,11 +161,9 @@ _DEVICE_TO_SWING: dict[str, str] = {
_SWING_TO_DEVICE = {v: k for k, v in _DEVICE_TO_SWING.items()}
# Swing fallback via /wind/oscillation/vs/0 (issue #126) -- boards without
# WIND_DIRECTION_HREF at all report two independent Swing|Fix toggles
# instead of one combined code. Same HA vocabulary as _DEVICE_TO_SWING
# above (off/vertical/horizontal/both), just read from/written to a pair
# of fields rather than a single one.
# Swing fallback via /wind/oscillation/vs/0 (issue #126): boards without
# WIND_DIRECTION_HREF report two independent Swing|Fix toggles instead of
# one combined code. Same HA vocabulary as _DEVICE_TO_SWING above.
def _oscillation_swing(rep: dict) -> str | None:
vertical = rep.get("vertical")
horizontal = rep.get("horizontal")
@@ -189,13 +182,12 @@ def _oscillation_swing(rep: dict) -> str | None:
def _wind_strength_label(code, rep: dict) -> str:
"""Human label for a /wind/strength/vs/0 code from the device's own
modesName array (parallel-indexed with supportedModes), lowercased for
HA -- used only for codes _DEVICE_TO_FAN doesn't already cover (issue
#155, TP1X_DA-AC-RAC-01001_0000: codes "0"/"31"-"35" instead of the
"0"-"4" scale _DEVICE_TO_FAN was built from, with modesName giving
"Auto"/"1"/"2"/"3"/"4"/"MAX"). No per-model numeric map -- mirrors
preset_mode's dynamic code->str resolution. Falls back to the raw code
lowercased when modesName is absent or misaligned."""
modesName array (parallel-indexed with supportedModes), lowercased --
used only for codes _DEVICE_TO_FAN doesn't already cover (issue #155:
a board using codes "0"/"31"-"35" instead of the "0"-"4" scale
_DEVICE_TO_FAN was built from, with modesName giving the real labels).
Falls back to the raw code lowercased when modesName is absent or
misaligned."""
supported = rep.get("x.com.samsung.da.supportedModes") or []
names = rep.get("x.com.samsung.da.modesName") or []
if code in supported and len(names) == len(supported):
@@ -204,15 +196,10 @@ def _wind_strength_label(code, rep: dict) -> str:
# Preset (convenient mode): resolved dynamically from the device's own
# /mode/convenient/vs/0 supportedModes -- no per-model table. The device 'Off'
# code maps to HA's PRESET_NONE ("no preset active"); every other code is
# exposed as its lowercased self and labelled in translations
# (entity.climate.airconditioner.state_attributes.preset_mode.state.<code>),
# so any board's convenient modes surface without code changes, and an
# unlabelled code just renders as its raw value until a label is added.
# (Samsung's WindFree still-air cooling shows up here as the 'Nano'/
# 'NanoSleep' codes on cool-only global RAC boards -- that's just a
# translation label, not a hard-coded mode.)
# /mode/convenient/vs/0 supportedModes -- no per-model table. Device 'Off'
# maps to PRESET_NONE; every other code is exposed lowercased and labelled
# in translations, so any board's convenient modes surface without code
# changes, and an unlabelled code renders as its raw value.
def _preset_to_ha(code) -> str:
return PRESET_NONE if code == "Off" else str(code).lower()
@@ -248,12 +235,11 @@ def _num(value):
def _temps_vs_item(rep: dict) -> dict:
"""First item of the vendor `/temperatures/vs/0` items[] array.
Newer AC firmware (Tizen Lite, oneUiVersion "7.0 Air conditioner", e.g.
model TP1X_DA-AC-RAC-01011) does NOT expose the OCF-standard
/temperature/current/0 + /temperature/desired/0 pair; it reports current
and target under a single `/temperatures/vs/0` resource whose
`x.com.samsung.da.items[0]` carries current/desired/minimum/maximum/
increment/unit. Returns {} when absent, so callers fall through cleanly.
Newer AC firmware (Tizen Lite) doesn't expose the OCF-standard
/temperature/current/0 + /temperature/desired/0 pair; it packs current/
desired/minimum/maximum/increment/unit into this one resource's
items[0] instead. Returns {} when absent, so callers fall through
cleanly.
"""
items = rep.get("x.com.samsung.da.items")
if isinstance(items, (list, tuple)) and items and isinstance(items[0], dict):
@@ -264,16 +250,12 @@ def _temps_vs_item(rep: dict) -> dict:
class LocalThingsClimate(LocalThingsEntity, ClimateEntity):
"""Composite climate entity for a Samsung air conditioner."""
# translation_key comes from the ClimateDesc (base __init__ sets
# _attr_translation_key from bound.desc), resolving the state_attributes
# translations under entity.climate.airconditioner.
# Modern climate entities opt out of the deprecated auto-added TURN_ON/OFF.
# Opts out of the deprecated auto-added TURN_ON/OFF backwards compat.
_enable_turn_on_off_backwards_compatibility = False
def __init__(self, coordinator: LocalThingsCoordinator, bound) -> None:
super().__init__(coordinator, bound)
# Primary/main entity for the device: no name suffix, just the device name.
self._attr_name = None
self._attr_name = None # primary entity: no name suffix
self._attr_supported_features = (
ClimateEntityFeature.TARGET_TEMPERATURE
| ClimateEntityFeature.FAN_MODE
@@ -283,9 +265,8 @@ class LocalThingsClimate(LocalThingsEntity, ClimateEntity):
| ClimateEntityFeature.TURN_OFF
)
# (href, raw device code) pairs already logged by _warn_unmapped --
# these properties are read on every coordinator refresh, so an
# un-deduped warning would spam the log for any device with a
# genuinely unrecognized code.
# these properties are read on every refresh, so an un-deduped
# warning would spam the log for a genuinely unrecognized code.
self._warned_unmapped: set[tuple[str, str]] = set()
# -- resource helpers ---------------------------------------------------
@@ -295,80 +276,172 @@ class LocalThingsClimate(LocalThingsEntity, ClimateEntity):
# Nano=windFree, Quiet, Comfort, 2Step, Speed=Fast Turbo, Off=none.
_LEGACY_PRESET_CODES = ("Off", "Nano", "Quiet", "Comfort", "2Step", "Speed")
# Good Sleep occupies the same Comode_ slot as the presets above, so a unit
# running it reports Comode_Sleep -- or Comode_NanoSleep, which the board
# will produce by itself when nano wind is asked for while the timer runs.
# Neither is in the list above, and a preset_mode outside preset_modes is
# not a state HA allows, so they are added for boards that have the Sleep_
# token these codes come with.
_LEGACY_SLEEP_PRESET_CODES = ("Sleep", "NanoSleep")
# HVAC modes _legacy_preset_codes() has a rule for. Anything else is a mode
# this transcription has never seen, which is the same "cannot judge" case as
# a board that publishes no capability map -- and gets the same fallback.
_LEGACY_KNOWN_HVAC = frozenset(
{"Cool", "Heat", "HeatClean", "Dry", "Fan", "Wind", "Auto", _AI_COMFORT_MODE}
)
# Which comfort modes a legacy board offers in which HVAC mode, and which of
# them it has at all. Both come from the appliance rather than from a table
# per model: the unit publishes its capabilities as two bit maps in
# /mode/vs/0's options (OptionCode, ExtendOptionCode), and its own app gates
# each item on a bit plus the current mode. _legacy_preset_codes() below is
# that logic, transcribed from the app's updateOptionsList() so the two can be
# compared line by line, with the bit each rule reads named in the comment.
#
# Confirmed against an ARTIK051_KRAC_18K whose owner read the same lists off
# the remote and the app: WindFree in Cool/Dry/Fan and (being an 18K model)
# Auto but never Heat, and Fast Turbo and Comfort in Heat because oc[12] is
# set. d'light Cool is gated the same way on oc[2], which is zero here -- and
# the appliance refuses the token locally too.
#
# Single User is deliberately not modelled, though the app does gate it on
# oc[3] / oc[11]: it has no token of its own. The app's own Single User
# command sends `Comode_Smart` -- the Smart Saver token -- with a hardcoded
# 24 desired alongside it, so there is nothing to write that would be
# distinguishable from the Smart preset below, and no name to give it that
# the appliance would recognise.
def _legacy_preset_codes(self, hvac: str, options: list) -> list[str]:
"""Comfort-mode codes this unit offers in this HVAC mode.
Derived only for boards that publish *both* capability maps. One map on
its own is not enough: every eoc-gated rule would then read None, and
None means "this board does not publish the map", never "the feature is
absent". The FAC/CAC boards on record carry only the older map, with
values small enough that RAC bit positions all read as zeros, so
requiring both also keeps these rules inside the family they were
documented for.
Within the derived path, a bit that cannot be read (a malformed or
over-wide token) is treated as permission rather than denial for the
codes the unconditional list already carried -- losing a working preset
to a parsing failure is worse than offering one too many. Codes that were
never in that list (d'light) still need their bit to be explicitly set.
"""
rep = self._rep(MODE_HREF)
if (
not has_option_code(rep)
or not has_extend_option_code(rep)
or hvac not in self._LEGACY_KNOWN_HVAC
):
return list(self._LEGACY_PRESET_CODES)
cool = hvac in ("Cool", _AI_COMFORT_MODE)
heat = hvac in ("Heat", "HeatClean")
codes = ["Off"]
# WindFree: shown on eoc[31]; disabled in Heat, in AIComfort, and in Auto
# unless this is an 18K model (eoc[30]), where the app switches to Cool for
# it instead -- which is what _legacy_preset_needs_cool does.
nano_mode_ok = not heat and hvac != _AI_COMFORT_MODE
if hvac == "Auto":
nano_mode_ok = extend_option_code_bit(rep, 30) is not False
if extend_option_code_bit(rep, 31) is not False and nano_mode_ok:
codes.append("Nano")
if cool or (heat and option_code_bit(rep, 12) is not False): # Fast Turbo
codes.append("Speed")
if cool:
codes.append("2Step")
if cool and option_code_bit(rep, 2): # d'light Cool -- needs the bit set
codes.append("DlightCool")
# Quiet reads oc[10] with no mode condition in the app, but the owner of
# the unit above sees it in Cool and Heat only, on the remote as well as
# in the app -- the observation wins over the reading.
if option_code_bit(rep, 10) is not False and (cool or heat):
codes.append("Quiet")
if cool or (heat and option_code_bit(rep, 12) is not False): # Comfort
codes.append("Comfort")
# Smart Saver has no bit of its own and the app hides it from every single
# RAC outright (showSaverOption = false), yet the appliance accepts it and
# behaves as Samsung documents -- so absence from the app is not absence
# from the hardware. Cool-only, per that documentation.
if hvac == "Cool":
codes.append("Smart")
# Good Sleep, which shares this slot: the app enables it in Cool, Heat and
# AIComfort only. Both codes, because the board turns Sleep into NanoSleep
# by itself when WindFree is running.
if (cool or heat) and any(
isinstance(option, str) and option.startswith("Sleep_") for option in options
):
codes += self._LEGACY_SLEEP_PRESET_CODES
return codes
def _legacy_convenient(self) -> dict:
"""A /mode/convenient/vs/0-shaped rep built from the Comode_* token in
/mode/vs/0's options, for boards that have no convenient resource."""
options = self._rep(MODE_HREF).get("x.com.samsung.da.options") or []
for option in options:
if isinstance(option, str) and option.startswith("Comode_"):
return {
_MODES_FIELD: [option.split("_", 1)[1]],
_SUPPORTED_FIELD: list(self._LEGACY_PRESET_CODES),
}
return {}
active = next(
(o.split("_", 1)[1] for o in options if isinstance(o, str) and o.startswith("Comode_")),
None,
)
if active is None:
return {}
codes = self._legacy_preset_codes(_first(self._rep(MODE_HREF).get(_MODES_FIELD)), options)
# Whatever the unit is actually running has to be listed whether the
# rules expect it there or not -- a preset_mode outside preset_modes is
# not a state HA allows, and the appliance has the last word on what it
# is doing (a remote can put it in a mode these rules would not offer).
if active not in codes:
codes.append(active)
return {_MODES_FIELD: [active], _SUPPORTED_FIELD: codes}
def _legacy_airflow(self) -> dict:
"""The /airflow/vs/0 rep, but only when it is the fan/swing channel to
use -- i.e. this board has no /wind/strength/vs/0.
"""The /airflow/vs/0 rep, but only when it is the fan/swing channel
to use -- i.e. this board has no /wind/strength/vs/0.
Delegates the board-generation test to is_legacy_board (the same
test capabilities/airconditioner.py's token entities are gated on)
instead of re-implementing it. Uses self._resources (this unit's own
canonical view, issue #177 -- see LocalThingsEntity._resources)
rather than a two-key presence dict built from coordinator.resource()'s
test the token entities in capabilities/airconditioner.py use)
instead of re-implementing it, using self._resources (issue #177)
rather than a presence dict built from coordinator.resource()'s
truthiness -- resource() collapses "href absent" and "href present
with an empty {} rep" to the same falsy value, while is_legacy_board
(and discover()'s own binding) test key membership, not truthiness. A
presence dict built from truthiness alone would disagree with the
token entities on a board reporting a genuinely empty /airflow/vs/0,
silently reintroducing the drift this delegation exists to prevent.
Reads the actual href through self._rep rather than
coordinator.resource() directly -- on a subdevice (a legacy-board
sibling has its own /airflow/vs/1, or /<id>/airflow/vs/0), the
canonical AIRFLOW_HREF must be translated through this bound
entity's own subdevice first, exactly like every other sibling read
below.
but empty" to the same falsy value, while is_legacy_board tests key
membership. Reads through self._rep, not coordinator.resource()
directly, so a subdevice's own /airflow/vs/1 gets translated first,
like every other sibling read below.
"""
if not is_legacy_board(self._resources):
return {}
return self._rep(AIRFLOW_HREF)
def _legacy_preset(self) -> bool:
"""Whether presets come from the Comode_* token rather than a resource.
"""Whether presets come from the Comode_* token rather than a
resource. Gated on the same board test as _legacy_airflow, not on
the convenient rep being empty alone: newer boards carry Comode
tokens too, so a momentarily empty /mode/convenient/vs/0 must not
silently switch the preset path over.
Gated on the same board test as _legacy_airflow, not on the convenient
rep being empty alone: newer boards carry Comode tokens too, so a
momentarily empty /mode/convenient/vs/0 there must not silently switch
the preset read (and write) over to the token path.
Deliberately reads the *raw* href (translated through this bound
entity's own subdevice, not through self._rep) rather than going
through _rep's own CONVENIENT_HREF fallback branch -- that fallback
is exactly the legacy_convenient() rep this method is deciding
whether to use, so routing through it here would make the resource
never look empty and this always resolve to the wrong side.
Reads the raw href directly rather than through self._rep's own
CONVENIENT_HREF fallback -- that fallback IS the legacy_convenient()
rep this method is deciding whether to use, so routing through it
would make the resource never look empty.
"""
convenient_href = self._bound.subdevice.to_actual(CONVENIENT_HREF)
return not self.coordinator.resource(convenient_href) and bool(self._legacy_airflow())
def _rep(self, href: str) -> dict:
"""`href` is one of this module's canonical HREF_* constants --
translated through this bound entity's own subdevice (issue #177) to
the real, on-the-wire href before the single-href cache lookup
(identity for MAIN, so a device with no subdevices reads exactly the
href it always did)."""
"""`href` is one of this module's canonical HREF_* constants,
translated through this bound entity's own subdevice (issue #177)
to the real on-the-wire href -- identity for MAIN."""
rep = self.coordinator.resource(self._bound.subdevice.to_actual(href)) or {}
if not rep and href == CONVENIENT_HREF and self._legacy_airflow():
return self._legacy_convenient()
return rep
def _is_on(self) -> bool:
# Prefer the vendor /power/vs/0 (present on every observed board and
# the resource writes target -- see airconditioner._climate_write).
# The OCF /power/0 is absent on many boards and a stale mirror on
# some, so reading it first showed pre-write state after a power
# toggle (issue #53: "can turn on but not off").
# Prefer the vendor /power/vs/0 -- the OCF /power/0 is absent on many
# boards and a stale mirror on some, so reading it first showed
# pre-write state after a power toggle (issue #53).
power = self._rep(POWER_VS_HREF).get("x.com.samsung.da.power")
if power is not None:
return str(power).lower() == "on"
@@ -379,16 +452,12 @@ class LocalThingsClimate(LocalThingsEntity, ClimateEntity):
def _warn_unmapped(self, href: str, code: str) -> None:
"""Log once per (href, code) when a device-reported mode has no
entry in the relevant device<->HA map, so a real device gap surfaces
in the log instead of silently vanishing (issue #93).
entry in the relevant device<->HA map, so a real gap surfaces in
the log instead of silently vanishing (issue #93).
Falls back to `unique_id` when `entity_id` is unset (issue #235):
this fires during setup's first discovery pass, before the entity is
added to hass, so `entity_id` is always None at that point --
indistinguishable across multiple same-type devices in the log.
`unique_id` is set eagerly in `__init__` (see entity.py), so it's
always available here even though `entity_id` isn't.
"""
this can fire during setup's first discovery pass, before the
entity is added to hass, when entity_id is still None."""
key = (href, code)
if key in self._warned_unmapped:
return
@@ -420,11 +489,10 @@ class LocalThingsClimate(LocalThingsEntity, ClimateEntity):
def _ocf_temp_authoritative(self) -> bool:
"""True when the OCF /temperature/{current,desired}/0 pair is the
authoritative temperature channel -- signalled by
/temperature/current/0 being present. Those boards honour reads/
writes on /temperature/desired/0 and ignore the vendor
/temperatures/vs/0; boards without the pair (only a desired stub, or
nothing) are the reverse. Confirmed on live units of both kinds."""
authoritative channel, signalled by /temperature/current/0 being
present. Those boards honor reads/writes on /temperature/desired/0
and ignore the vendor /temperatures/vs/0; boards without the pair
are the reverse. Confirmed on live units of both kinds."""
return bool(self._rep(TEMP_CURRENT_HREF))
def _temps_vs(self) -> dict:
@@ -597,11 +665,9 @@ class LocalThingsClimate(LocalThingsEntity, ClimateEntity):
return _HVAC_TO_DEVICE.get(hvac_mode)
async def async_set_temperature(self, **kwargs) -> None:
# HA's set_temperature service forwards an optional hvac_mode here; honour
# it (set the mode first -- that also powers the unit on when it was off),
# matching the climate contract other integrations follow. Without this a
# set_temperature call carrying hvac_mode (e.g. a dashboard "turn on to
# Auto 24" button) set the setpoint but never changed mode or powered on.
# HA's set_temperature service can carry an optional hvac_mode;
# honor it (setting the mode also powers the unit on) so a dashboard
# "turn on to Auto 24" button doesn't set the setpoint alone.
hvac_mode = kwargs.get("hvac_mode")
if hvac_mode is not None:
await self.async_set_hvac_mode(hvac_mode)
@@ -647,12 +713,11 @@ class LocalThingsClimate(LocalThingsEntity, ClimateEntity):
supported = self._supported(WIND_STRENGTH_HREF)
device = _FAN_TO_DEVICE.get(fan_mode)
# A static hit is only trustworthy if this unit's own supportedModes
# actually includes that code -- a board can use non-standard codes
# (issue #155's "31"-"35") while still spelling a standard label
# ("Low"/"High") in modesName, in which case _FAN_TO_DEVICE.get would
# return a plausible-looking code ('1'/'3') the device never
# advertised at all. Fall through to the live scan whenever the
# static guess isn't actually one of this unit's own codes.
# includes that code -- a board can use non-standard codes (issue
# #155) while still spelling a standard label in modesName, so the
# static guess could be a plausible code the device never
# advertised. Fall through to the live scan when it isn't one of
# this unit's own codes.
if device is None or (supported and device not in supported):
rep = self._rep(WIND_STRENGTH_HREF)
for code in supported:
@@ -674,6 +739,38 @@ class LocalThingsClimate(LocalThingsEntity, ClimateEntity):
if self._rep(WIND_OSCILLATION_HREF):
await self.coordinator.async_send_command(self._bound, ("oscillation", swing_mode))
async def _legacy_preset_needs_cool(self, code: str) -> None:
"""Switch a legacy board to Cool first when the preset needs it.
WindFree does not exist in Auto: `["Comode_Nano"]` written while the unit
is in Auto is answered 2.04 Changed and dropped (measured, still
Comode_Off at +8s and +45s), and putting `modes: Cool` in the *same* POST
does not help -- the mode moves and the token is still dropped, so the
board judges the option against the mode it was in. Sent as its own write
first, it holds. The appliance's own app pairs `modes: Cool` with its nano
command for the same reason.
Auto only. The app's builder also covers AIComfort, but its
`updateOptionsList()` disables the WindFree button there outright, so that
pairing can never fire -- and `_legacy_preset_codes()` likewise does not
offer `Nano` in AIComfort, which would leave such a branch unreachable.
The pause is measured, not padding: back to back (same session, no gap at
all) the token was dropped again, two seconds apart it held. Three is that
with a little margin, and it only ever runs for this one preset in this
one HVAC mode.
"""
if not self._legacy_preset() or code != "Nano":
return
if _first(self._rep(MODE_HREF).get(_MODES_FIELD)) != "Auto":
return
# Same resolver the rest of the platform uses -- the device code for an HA
# mode is read off the unit's own supportedModes rather than assumed.
await self.coordinator.async_send_command(
self._bound, ("mode", self._device_code_for_hvac(HVACMode.COOL))
)
await asyncio.sleep(_NANO_AFTER_MODE_DELAY)
async def async_set_preset_mode(self, preset_mode: str) -> None:
if preset_mode == PRESET_AI_COMFORT:
# Writes the primary mode resource, not the convenient one --
@@ -685,6 +782,7 @@ class LocalThingsClimate(LocalThingsEntity, ClimateEntity):
# a fixed transform of the HA value -- e.g. 'NanoSleep' -> 'nanosleep').
for code in self._supported(CONVENIENT_HREF):
if _preset_to_ha(code) == preset_mode:
await self._legacy_preset_needs_cool(code)
kind = "preset_legacy" if self._legacy_preset() else "preset"
await self.coordinator.async_send_command(self._bound, (kind, code))
return
+489 -120
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import contextlib
import datetime
import errno
import json
import logging
import re
@@ -11,12 +12,15 @@ 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
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,
@@ -31,20 +35,28 @@ 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,
SERVICE_WRITE_RESOURCE,
)
_TEXT = TextSelector(TextSelectorConfig(type=TextSelectorType.TEXT))
@@ -64,19 +76,74 @@ _SAMSUNG_CLOUD_HOST = "connect-v2.samsungiotcloud.com"
class CannotConnect(Exception):
pass
"""Base for every probe failure.
`error_key` selects which message the user sees. The subclasses below
exist because "cannot connect" used to cover wildly different situations
(nothing at that IP, cloud-only firmware, a stale held session, a
rejected certificate) all under one unhelpful message. Raising this base
class directly is still valid for a failure that can't be narrowed down.
"""
error_key = "cannot_connect"
class NoResponse(CannotConnect):
"""Nothing at that address answered anything at all."""
error_key = "no_response"
class PortsClosed(CannotConnect):
"""The host is up and actively refused every port in the range."""
error_key = "ports_closed"
class NoDtlsServer(CannotConnect):
"""Ports are reachable, but nothing there speaks DTLS."""
error_key = "no_dtls_server"
class HandshakeTimeout(CannotConnect):
"""A DTLS server is confirmed present but never finished the handshake."""
error_key = "handshake_timeout"
class CertRejected(CannotConnect):
"""The appliance broke off the handshake over our certificate."""
error_key = "cert_rejected"
class HandshakeFailed(CannotConnect):
"""The appliance broke off the handshake for a non-certificate reason."""
error_key = "handshake_failed"
class CloudUnreachable(CannotConnect):
"""Samsung's cloud gateway, which mints the UUID, was unreachable."""
error_key = "cloud_unreachable"
class UnexpectedResponse(CannotConnect):
"""We authenticated, but the device didn't return a usable description."""
error_key = "unexpected_response"
class InvalidCA(Exception):
pass
error_key = "invalid_ca"
def _fetch_samsung_uuid() -> str:
"""Connect to Samsung's cloud gateway and extract the UUID from its TLS cert.
Verification is disabled because Samsung's chain contains a self-signed cert.
We only need to read the UUID from the cert subject, not verify its trust.
"""
"""Connect to Samsung's cloud gateway and extract the UUID from its TLS
cert. Verification is disabled: Samsung's chain has a self-signed cert,
and we only need to read the UUID from the subject, not verify trust."""
from cryptography import x509 as _x509
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
@@ -98,6 +165,17 @@ def _fetch_samsung_uuid() -> str:
raise RuntimeError(f"UUID not found in {_SAMSUNG_CLOUD_HOST} certificate subject")
def _normalize_pem(text: str) -> str:
"""Strip a pasted PEM's BOM, CRLF endings, and blank lines before
`cryptography` sees it -- a text editor's copy carries all three and
fails with an opaque InvalidHeader, while the same file dumped via
`type` doesn't (issue #291)."""
text = text.lstrip("\ufeff")
text = text.replace("\r\n", "\n").replace("\r", "\n")
lines = [line for line in text.split("\n") if line.strip()]
return "\n".join(lines)
def _mint_leaf_cert(ca_cert_pem: str, ca_key_pem: str, uuid: str) -> tuple[str, str]:
"""Mint a fresh RSA-2048 leaf cert signed by the CA.
@@ -179,27 +257,49 @@ def _order_candidates(ports: list[int]) -> list[int]:
return preferred + rest
def _find_live_ports(host: str, ports: list[int], timeout: float) -> list[int]:
"""Fast UDP liveness sweep to narrow the range before the DTLS handshake.
# The kernel's way of saying the datagram never had anywhere to go: no route,
# or the host never answered ARP. Distinct from ECONNREFUSED, which is a
# response -- the host is there and told us the port is closed. Both leave a
# port "not live", but mean opposite things about whether anything exists at
# that address.
_UNREACHABLE_ERRNOS = frozenset({errno.EHOSTUNREACH, errno.ENETUNREACH, errno.ENETDOWN})
UDP is connectionless, but a *connected* UDP socket surfaces the ICMP
port-unreachable that a closed port returns as ECONNREFUSED on its next
recv. So we send one probe datagram per port and watch for that error:
* ECONNREFUSED -> port is closed (device actively rejected it)
* silence / any data -> port may be live (open|filtered); a candidate
@dataclass(frozen=True)
class _SweepResult:
"""What the UDP sweep observed, kept as three separate verdicts."""
This is the in-process equivalent of ``nmap -sU``: it lets us take a
nine-port range down to the one or two ports actually worth a full DTLS
handshake + /device/0 GET, and bounds the total wait to ``timeout``
instead of stalling on every dead port when a firewall swallows the ICMP
replies.
live: list[int] # silent -> open|filtered, worth a handshake
refused: list[int] # ICMP port-unreachable -> host is up, port closed
unreachable: list[int] # no route / no ARP -> nothing is at that address
def _find_live_ports(host: str, ports: list[int], timeout: float) -> _SweepResult:
"""Fast UDP liveness sweep -- the sweep's own verdict, nothing added.
UDP is connectionless, but a connected UDP socket surfaces the ICMP
port-unreachable a closed port returns as ECONNREFUSED on its next recv.
So we send one probe datagram per port and watch for that error:
ECONNREFUSED means closed; silence/data means possibly live. The
in-process equivalent of ``nmap -sU``: takes a nine-port range down to
the one or two worth a full DTLS handshake, bounded to ``timeout``.
Deliberately the raw verdict, with no preferred-port rescue folded in
(that's `_sweep_ports`) -- its shape is evidence about the host, and a
refusal vs. an unreachable are counted apart rather than both "not
live" for that reason (see _SweepResult).
"""
sockets: dict[int, socket.socket] = {}
sel = selectors.DefaultSelector()
refused: list[int] = []
unreachable: list[int] = []
# A single byte is enough to provoke an ICMP port-unreach from a closed
# port; a real DTLS ClientHello is unnecessary just to test for life.
probe = b"\x00"
def _rule_out(port: int, exc: OSError) -> None:
(unreachable if exc.errno in _UNREACHABLE_ERRNOS else refused).append(port)
try:
for port in ports:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
@@ -207,7 +307,10 @@ def _find_live_ports(host: str, ports: list[int], timeout: float) -> list[int]:
try:
sock.connect((host, port))
sock.send(probe)
except OSError:
except OSError as exc:
# Failing on the way out means the kernel already knows the
# datagram can't get there.
_rule_out(port, exc)
sock.close()
continue
sockets[port] = sock
@@ -223,10 +326,10 @@ def _find_live_ports(host: str, ports: list[int], timeout: float) -> list[int]:
for key, _ in sel.select(timeout=remaining):
sock = sockets[key.data]
try:
# Data back means live; ECONNREFUSED (or any other socket
# error) means the port is closed/unusable — rule it out.
# Data back means live; an error rules the port out.
sock.recv(1)
except OSError:
except OSError as exc:
_rule_out(key.data, exc)
sel.unregister(sock)
live = [key.data for key in sel.get_map().values()]
finally:
@@ -235,57 +338,213 @@ def _find_live_ports(host: str, ports: list[int], timeout: float) -> list[int]:
with contextlib.suppress(OSError):
sock.close()
# The sweep's ICMP-based verdict isn't reliable on every network path --
# issue #192 captured a segregated-VLAN device where it called three
# ports live that a concurrent nmap scan showed as closed, while the
# port nmap found genuinely open|filtered (49154, one of our historically
# confirmed ports) never showed up as live at all. Rather than trust a
# wrong "not live" verdict on a port we already have strong prior
# evidence for, always give the historically-confirmed ports a real
# handshake attempt too. Bounded cost: at most len(PREFERRED_PROBE_PORTS)
# extra handshakes, only when the sweep disagrees with the prior.
rescued = [p for p in PREFERRED_PROBE_PORTS if p in ports and p not in live]
return _order_candidates(live + rescued)
return _SweepResult(_order_candidates(live), sorted(refused), sorted(unreachable))
def _is_placeholder_serial(serial: str) -> bool:
"""True for a non-empty serialNum that isn't actually a real identity.
def _sweep_ports(host: str, ports: list[int], timeout: float) -> tuple[_SweepResult, list[int]]:
"""`(sweep, candidates)` -- what the host said, and what to actually try.
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).
The sweep's ICMP-based verdict isn't reliable on every network path --
issue #192 captured a segregated-VLAN device where it called live ports
that nmap showed closed, while the port nmap found genuinely open never
showed up as live at all. Rather than trust a wrong "not live" verdict
on a port with strong prior evidence, the historically-confirmed ports
always get a real handshake attempt too (bounded cost: at most
len(PREFERRED_PROBE_PORTS) extra handshakes, only when the sweep
disagrees with the prior).
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.
Both halves are returned, not just the union, since they answer
different questions: `candidates` is what to hand a handshake, `sweep`
is what the host actually told us about itself.
"""
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"
sweep = _find_live_ports(host, ports, timeout)
rescued = [p for p in PREFERRED_PROBE_PORTS if p in ports and p not in sweep.live]
return sweep, _order_candidates(sweep.live + rescued)
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
@dataclass(frozen=True)
class _PortScan:
"""What port detection learned about a host.
from .registry.batch import parse_device0_batch
from .registry.by_type import resolve as resolve_registry
from .registry.identity import read_identity
`candidates` is what gets a full DTLS handshake. The other two are the
evidence behind a failure message: `confirmed` names ports a DTLS
server was proven on, `swept` is the UDP sweep's own verdict (None
when the sweep never had to run).
"""
candidates: list[int]
confirmed: list[int]
swept: _SweepResult | None = None
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."""
from smartthings_local.protocol.dtls_probe import probe
return probe(
host,
port,
stateless=True,
timeout=CLIENTHELLO_PROBE_TIMEOUT_S,
retries=CLIENTHELLO_PROBE_RETRIES,
)
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).
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 --
identifies the device's real port in ~1 RTT, far cheaper than throwing N
full certificate handshakes at it.
The whole range goes out at once, safely: 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.
"""
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: exactly
one port gets the expensive certificate handshake instead of every port
the old UDP sweep couldn't rule out (issue #211's 30-40s of 12s handshake
timeouts).
It's a gate, not a replacement: when it confirms nothing, we fall back
to the ICMP-based sweep, which still surfaces a device the probe
couldn't reach (a network path dropping the ClientHello, or an install
on smartthings-local < 0.1.2). Issue #192's segregated-VLAN device is
why 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, confirmed)
sweep, candidates = _sweep_ports(host, PROBE_PORT_RANGE, LIVENESS_PROBE_TIMEOUT_S)
# No early "nothing here" fast-fail on an empty sweep: the rescue always
# keeps PREFERRED_PROBE_PORTS as candidates (issue #192), so a real
# handshake attempt still happens. What the sweep saw is carried along
# instead, and _classify_handshake_failure turns it into a message once
# those attempts have actually failed.
_LOGGER.debug(
"No DTLS server confirmed on %s; sweep saw live=%s refused=%s unreachable=%s, trying %s",
host,
sweep.live,
sweep.refused,
sweep.unreachable,
candidates,
)
return _PortScan(candidates, [], sweep)
# TLS alerts (RFC 5246 §7.2) that mean "I looked at your certificate and
# said no", as opposed to a protocol/cipher disagreement -- what an
# appliance sends when the CA behind the leaf isn't one it trusts, the
# single most common real setup mistake.
_CERT_ALERTS = frozenset(
{
"bad_certificate",
"unsupported_certificate",
"certificate_revoked",
"certificate_expired",
"certificate_unknown",
"unknown_ca",
"access_denied",
"decrypt_error",
"certificate_required",
}
)
# OpenSSL renders a received fatal alert into its error text as e.g.
# "tlsv1 alert unknown ca", which DtlsCoapSession.connect() wraps in a
# ConnectionError. Reading it back tells us what the appliance objected to.
#
# Deliberately not the library's diagnostic probe (stateless=False): that
# mode commits association state on the device, and an orphaned association
# makes the next attempt time out (RFC 6347 §4.2.8) -- a bad trade on a
# path the user is about to retry.
_ALERT_RE = re.compile(r"alert ([a-z0-9 ]+)")
def _alert_name(exc: Exception) -> str | None:
"""The TLS alert an appliance sent, if this failure carried one."""
match = _ALERT_RE.search(str(exc).lower())
return match.group(1).strip().replace(" ", "_") if match else None
def _classify_handshake_failure(
host: str,
scan: _PortScan,
failures: list[tuple[int, Exception]],
) -> CannotConnect:
"""Turn "no port worked" into the most specific thing we can honestly
say, in rough order of how much the evidence tells us: an alert means
the appliance refused us on purpose (and says whether it was our
certificate); a confirmed DTLS port that then timed out is likely still
holding a session from a previous attempt; otherwise the sweep's own
shape is the evidence.
"""
alerts = [name for name in (_alert_name(exc) for _, exc in failures) if name]
cert_alerts = [name for name in alerts if name in _CERT_ALERTS]
if cert_alerts:
return CertRejected(f"{host} rejected our certificate (alert {cert_alerts[0]})")
if alerts:
return HandshakeFailed(f"{host} refused the DTLS handshake (alert {alerts[0]})")
if scan.confirmed:
return HandshakeTimeout(
f"DTLS server confirmed on {host}:{scan.confirmed} but the handshake never completed"
)
sweep = scan.swept
if sweep is None:
return CannotConnect(f"no port on {host} completed a handshake")
if sweep.unreachable and not sweep.refused:
# Nothing was ever asked -- the kernel never got the datagrams off
# the host, so "ports closed" would be exactly wrong.
return NoResponse(f"{host} is unreachable (ports {sweep.unreachable})")
if not sweep.live:
# Every port answered ICMP port-unreachable: something is there and
# not exposing the local API.
return PortsClosed(
f"{host} refused every port in {PROBE_PORT_RANGE[0]}-{PROBE_PORT_RANGE[-1]}"
)
if len(sweep.live) == len(PROBE_PORT_RANGE):
# Not one refusal across a nine-port range -- a host that's
# actually there answers for at least some of it.
return NoResponse(f"nothing at {host} responded on any probed port")
return NoDtlsServer(f"ports on {host} are reachable but none answered a DTLS handshake")
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()
except Exception as exc:
_LOGGER.debug("UUID fetch failed: %s", exc, exc_info=True)
raise CannotConnect(f"Failed to fetch Samsung UUID: {exc}") from exc
raise CloudUnreachable(f"Failed to fetch Samsung UUID: {exc}") from exc
_LOGGER.debug("Got UUID: %s", uuid)
_LOGGER.debug("Minting leaf cert for UUID %s", uuid)
@@ -298,66 +557,127 @@ 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
for port in candidates:
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, so a device answering neither
/oic/p nor /oic/d falls through to the model-string/resource-signature
path.
Everything the entry needs to name and key the device comes from here,
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_model, resolve_serial
identity = read_identity(sess, None)
code, payload = sess.get(["device", "0"], timeout=PROBE_GET_TIMEOUT_S)
if code != 0x45 or not payload:
# Authenticated fine, so this isn't a connectivity or credentials
# problem -- whatever is on this port just isn't an appliance whose
# /device/0 we understand.
raise UnexpectedResponse(
f"{host}:{port} answered /device/0 with {code >> 5}.{code & 0x1F:02d} "
f"({code:#04x}), payload {len(payload or b'')} bytes"
)
body = cbor2.loads(payload)
resources = parse_device0_batch(body) if isinstance(body, list) else {}
info = resources.get("/information/vs/0", {})
registry = resolve_registry(resources, device_types=identity.device_types)
return {
"port": port,
# Resolved through the same helpers _run_discovery uses, so the device
# the coordinator registers up front is the one discovery would have
# produced -- no rename, and no re-key, once the first poll lands.
"serial": resolve_serial(info.get("x.com.samsung.da.serialNum"), host),
"model": resolve_model(info.get("x.com.samsung.da.modelNum", ""), identity),
"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, scan: _PortScan, 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
failures: list[tuple[int, Exception]] = []
for port in scan.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
failures.append((port, exc))
_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 _classify_handshake_failure(host, scan, failures)
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, 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, so adding a second device can
skip the fetch and mint entirely -- independent of Samsung-cloud
reachability, not merely faster. If that reused leaf turns out to be
stale (the UUID does rotate), a confirmed-live device rejecting it
re-mints and retries once, 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, cert_pem, key_pem)
except CertRejected:
# The only failure a fresh certificate can fix, and only worth a
# second pass when the certificate wasn't freshly minted already.
if existing_leaf is None:
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, 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 +693,17 @@ 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 aren't decoration: the coordinator seeds
`device_serial` and its DeviceInfo from them at construction time,
so entity unique_ids are correct from the first entity that
registers, even if the first poll is slow or fails (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 +711,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,12 +726,19 @@ 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()
# Normalized here, not just before minting: this is also
# what gets stored and reused to re-mint the leaf later.
self._ca_cert_pem = _normalize_pem(user_input[CONF_CA_CERT_PEM])
self._ca_key_pem = _normalize_pem(user_input[CONF_CA_KEY_PEM])
try:
info = await self.hass.async_add_executor_job(
@@ -406,11 +746,13 @@ 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"
except CannotConnect:
errors["base"] = "cannot_connect"
except (CannotConnect, InvalidCA) as exc:
# Every probe failure carries the message that fits it (see
# CannotConnect); the log line is where the specifics live.
_LOGGER.warning("Probe of %s failed [%s]: %s", self._host, exc.error_key, exc)
errors["base"] = exc.error_key
except Exception:
_LOGGER.exception("Unexpected error during device probe")
errors["base"] = "unknown"
@@ -437,7 +779,7 @@ class LocalThingsConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_show_form(
step_id=step_id,
data_schema=schema,
data_schema=self.add_suggested_values_to_schema(schema, user_input),
errors=errors,
)
@@ -451,12 +793,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"},
)
@@ -466,14 +813,11 @@ class LocalThingsOptionsFlow(config_entries.OptionsFlow):
arbitrary resource href, so a user can pin down device-specific write
behavior without waiting on a new release.
The remote-control override exists because most devices reject writes
outright while remote control is off and a clear error beats a silent
device-side rejection -- but not every model actually enforces that,
so this lets a user who's confirmed their device accepts writes anyway
turn the block off for just that device rather than it being
hardcoded on for everyone. The debug panel goes further: it bypasses
that block (and every write_fn/validate_fn) entirely, sending exactly
the body the user types to whatever href they pick.
The remote-control override exists because not every model actually
enforces the block most devices do, so a user who's confirmed their
device accepts writes anyway can turn it off for just that device. The
debug panel goes further, bypassing that block (and every write_fn/
validate_fn) entirely.
"""
def __init__(self) -> None:
@@ -583,8 +927,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)
+58 -29
View File
@@ -20,52 +20,75 @@ CONF_CA_KEY_PEM = "ca_key_pem"
CONF_LEAF_CERT_PEM = "leaf_cert_pem"
CONF_LEAF_KEY_PEM = "leaf_key_pem"
# 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
# writes (e.g. default detergent/softener dosing on a washer, applied even
# to the built-in programs) -- the block exists to give a clear error
# instead of a silent device-side rejection, but that assumption doesn't
# hold for every model. Defaults to False (block stays on) everywhere it's
# read, so devices this doesn't apply to see no behavior change.
# Device identity, resolved once by the config flow's probe and persisted
# on the entry (issue #236) -- what the coordinator mints registry keys
# from at __init__ time, before any poll has happened. Without them,
# anything registering before the first poll (e.g. the connection-mode
# sensor) got keyed on the IP address permanently.
#
# CONF_SERIAL is the resolved serial (registry.identity.resolve_serial's
# output, the host itself for a placeholder-serial board -- issues
# #83/#189), so it matches what _run_discovery computes on the first poll.
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 accept certain writes even while reporting
# remote control off (e.g. a washer's default detergent dosing), so the
# blanket-block assumption doesn't hold everywhere. Defaults to False
# (block stays on).
CONF_BYPASS_REMOTE_CONTROL = "bypass_remote_control_lock"
# Options-flow key: minimum change (in minutes) required before a
# hysteresis-gated timestamp sensor (currently just finish_time) is allowed
# to report a new value. Devices commonly revise their own remaining-time
# estimate by a minute or two throughout a cycle, and finish_time = now() +
# remaining drifts by the poll interval between those revisions -- both push
# a fresh state (and a recorder/logbook entry) far more often than the
# estimate is meaningfully different. 0 disables the gate (every computed
# change is reported, today's behavior).
# hysteresis-gated timestamp sensor (currently just finish_time) reports a
# new value. Devices commonly revise their remaining-time estimate by a
# minute or two throughout a cycle, and finish_time = now() + remaining
# drifts with the poll interval between revisions -- both push a fresh
# state far more often than the estimate is meaningfully different. 0
# disables the gate.
CONF_FINISH_TIME_HYSTERESIS_MINUTES = "finish_time_hysteresis_minutes"
DEFAULT_FINISH_TIME_HYSTERESIS_MINUTES = 3
# The DTLS/CoAP local API binds somewhere in this ephemeral range; which port
# depends on firmware. Newer builds answer on 49154/49155, but older ones have
# been seen as low as 49153, so we sweep the whole range for a live UDP port
# before attempting the (expensive) DTLS handshake.
# The DTLS/CoAP local API binds somewhere in this ephemeral range,
# depending on firmware (newer builds answer on 49154/49155, older ones as
# low as 49153) -- swept for a live UDP port before the expensive DTLS
# handshake.
PROBE_PORT_RANGE = list(range(49152, 49161))
# Ports we've historically seen complete a DTLS handshake. When more than one
# port in the range looks live, these are tried first.
# Ports we've historically seen complete a DTLS handshake; tried first when
# more than one port in the range looks live.
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 as the
# fallback for when the ClientHello probe below confirms nothing.
LIVENESS_PROBE_TIMEOUT_S = 1.5
# 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.
# Per-port budget for the DTLS ClientHello probe (smartthings-local >=
# 0.1.2), the primary port-detection gate. A real server answers with a
# HelloVerifyRequest in ~1 RTT; the budget only bounds how long a silent
# port takes to give up. 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, not 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.
PROBE_GET_TIMEOUT_S = 10.0
# Base for the local (client-side) DTLS source port, distinct from the
# destination probe ports above. See coordinator._local_source_port for why a
# fixed per-device source port matters and how the per-device offset is
# derived. Base mirrors the upstream smartthings-local reference bridge.
# Requires smartthings-local >= 0.1.1.
# destination probe ports above -- see coordinator._local_source_port for
# why a fixed per-device source port matters. Mirrors the upstream
# smartthings-local reference bridge. Requires smartthings-local >= 0.1.1.
DTLS_LOCAL_PORT_BASE = 49700
SUMMARY_INTERVAL_S = 30.0
@@ -73,3 +96,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"
File diff suppressed because it is too large Load Diff
+34 -64
View File
@@ -35,31 +35,24 @@ async def async_get_config_entry_diagnostics(
# /oic/p, /oic/d, and /oic/res sit outside the /device/0 batch captured
# below, so they'd otherwise never reach an issue report. /oic/d's `rt`
# is OCF's standard device-type declaration; /oic/res is OCF's
# discovery endpoint, listing every href/Collection the connection
# hosts -- relevant to the "Composite Device" model (issue #177) where
# a single physical device exposes more than one logical subdevice. See
# is OCF's device-type declaration; /oic/res is OCF's discovery
# endpoint, relevant to the "Composite Device" model (issue #177). See
# registry/identity.py.
identity = coordinator._identity
def _seed_diag(su) -> dict:
# A flat-mode subdevice (issue #205 -- no working /<uuid>/device/0
# Collection, so its state comes from individually-polled hrefs
# instead) has no meaningful seed_path; report the flat_hrefs list
# in its place rather than the misleading bare "/" a joined empty
# tuple would otherwise produce.
# A flat-mode subdevice (issue #205: no working /<uuid>/device/0
# Collection, state comes from individually-polled hrefs instead)
# has no meaningful seed_path; report flat_hrefs in its place.
return {
"seed_path": ("/" + "/".join(su.seed_path)) if su.seed_path else None,
"flat_hrefs": list(su.flat_hrefs),
}
def _subdevice_diag(su) -> dict:
# One pass over coordinator.bound for both fields below (count and
# the distinct hrefs), and one redaction of this subdevice's canonical
# view -- `model` reads modelNum off the already-redacted `resources`
# rather than redacting /information/vs/0 a second time. modelNum
# itself never matches redact.py's substring rules, so which side of
# redact_resources it's read from doesn't change the value.
# `model` reads modelNum off the already-redacted `resources` rather
# than redacting /information/vs/0 again -- modelNum never matches
# redact.py's substring rules, so the value is the same either way.
matching = [b for b in coordinator.bound if b.subdevice == su]
res = redact_resources(coordinator.canonical_resources(su))
return {
@@ -69,13 +62,10 @@ async def async_get_config_entry_diagnostics(
"bound_entity_count": len(matching),
"hrefs": sorted({b.href for b in matching}),
"model": res.get("/information/vs/0", {}).get("x.com.samsung.da.modelNum", ""),
# Keyed by this subdevice's *canonical* hrefs, not the real ones
# it answers on -- '/mode/vs/0' rather than '/mode/vs/1' or
# '/<uuid>/mode/vs/0'. That's the form the registry and every
# capability are written against, so a sibling's block can be
# read (or pasted into the skill's standalone-discovery
# recipe) exactly like the master's `resources` above,
# instead of having to be de-indexed by hand first.
# Keyed by this subdevice's canonical hrefs ('/mode/vs/0'), not
# the real ones it answers on ('/mode/vs/1', '/<uuid>/mode/vs/0')
# -- the form the registry is written against, so a sibling's
# block reads exactly like the master's `resources` below.
"resources": res,
}
@@ -91,49 +81,34 @@ async def async_get_config_entry_diagnostics(
if identity is not None
else None,
"unbound_hrefs": sorted(coordinator._unbound_hrefs),
# This subdevice's own resources, and only this subdevice's -- what
# the module docstring and the adding-device-support skill have
# always described it as ("the parsed /device/0 snapshot"). On a
# composite device (issue #177) `last_resources` is the union across
# every live subdevice keyed by real hrefs, so reporting it raw here
# would mix a sibling's /mode/vs/1 in with the master's /mode/vs/0
# under no attribution at all. Each sibling reports its own
# resources in its own `subdevices` entry below instead. For a
# device with no subdevices -- almost every device -- this is
# byte-identical to `last_resources`.
# This subdevice's own resources, and only this subdevice's. On a
# composite device (issue #177) `last_resources` is the union
# across every live subdevice keyed by real hrefs, so reporting it
# raw here would mix a sibling's /mode/vs/1 with the master's
# /mode/vs/0 under no attribution. Each sibling reports its own
# resources in `subdevices` below instead. For a device with no
# subdevices, this is byte-identical to `last_resources`.
"resources": redact_resources(coordinator.canonical_resources(MAIN)),
# Sibling indoor subdevices discovered on this connection (issue
# #177) -- per-subdevice kind/key/seed path plus what actually bound
# to it, so a report shows whether a composite device's subdevice
# was found at all and what it resolved to. subdeviceIdList (the
# UUID a prefixed subdevice's key comes from) is deliberately NOT
# redacted here even
# though the field matches redact.py's 'deviceid' substring rule
# elsewhere in `resources` above -- it's an appliance-internal
# pairing id, not account data, and reporting the key is what makes
# this block actionable.
# #177). subdeviceIdList (the UUID a prefixed subdevice's key comes
# from) is deliberately NOT redacted here, unlike elsewhere in
# `resources` -- it's an appliance-internal pairing id, not account
# data, and reporting it is what makes this block actionable.
"subdevices": [_subdevice_diag(su) for su in coordinator.subdevices],
# Candidates that answered their seed but that discover_partitioned's
# entity-level liveness gate rejected -- an unused SmartThings slot
# (the issue #177 reporter's /device/2) that still answers a
# same-shaped batch, not a real second subdevice. Reported alongside
# subdevices above so a report shows what was found *and* why it
# didn't become an entity, not just silence where a third climate
# card might otherwise be expected.
# liveness gate rejected -- an unused SmartThings slot, not a real
# second subdevice. Reported alongside subdevices above so a report
# shows what was found and why it didn't become an entity.
"subdevices_skipped": [
{
"kind": skip.subdevice.kind,
"key": skip.subdevice.key,
**_seed_diag(skip.subdevice),
"hrefs": list(skip.hrefs),
# The reps the liveness gate actually judged, canonicalized
# like the materialized subdevices above. These are the one
# thing a reader needs to second-guess a skip ("is my second
# subdevice really absent, or did the gate get it wrong?"),
# and they exist nowhere else in this dump: a rejected
# candidate is never polled again and never enters the state
# cache, so `resources` above cannot contain them by
# construction.
# The reps the liveness gate actually judged -- the one
# thing a reader needs to second-guess a skip, and they
# exist nowhere else in this dump: a rejected candidate is
# never polled again or entered into the state cache.
"resources": redact_resources(
{
canon: rep
@@ -146,17 +121,12 @@ async def async_get_config_entry_diagnostics(
],
# What each enumeration probe returned ({} vs a batch), keyed by the
# seed href attempted -- lets a report distinguish "checked, nothing
# there" from "never checked", the same posture the speculative
# /device/1 //device/2 probe this replaced used to document directly
# in identity.py before it moved to registry/subdevices.py.
# there" from "never checked".
"subdevice_probes": dict(sorted(coordinator._subdevice_probes.items())),
# /multidevice/vs/0's rep ({} when the board doesn't answer it).
# Reported on its own rather than inside `resources` because it is
# metadata about the connection rather than state of any one
# subdevice -- and because nothing polls it after discovery, so it
# would go stale in there. Its numofsubdevice count is what
# independently corroborates the subdevices/subdevices_skipped split
# above.
# Reported on its own, not inside `resources`, since it's metadata
# 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),
"integration_version": integration.version,
"smartthings_local_version": stl_version,
+30 -44
View File
@@ -18,28 +18,23 @@ from .registry.discovery import BoundEntity, _snake_to_title
def _is_included(bound: BoundEntity, coordinator: LocalThingsCoordinator) -> bool:
"""Return False if the entity should not be registered for this device.
Explicit exists_fn takes priority. Otherwise, if the entity has a field,
require that field to be present in the resource rep so that optional
fields on shared resources don't create phantom entities.
Explicit exists_fn takes priority. Otherwise, if the entity has a
field, require that field to be present in the resource rep so that
optional fields on shared resources don't create phantom entities.
A stub rep (is_stub_rep — /device/0's "resource exists, no data fetched
yet" marker) is included anyway so it can be populated by sub-polls. A
genuinely empty {} rep is included too by this default gate -- whether
empty means "not populated yet" or "permanently unsupported" needs
per-field domain knowledge this generic gate doesn't have: /alarms/vs/0's
{} is fridge.py's documented *normal* no-alarm state (see
_active_alarm_codes), not an absence signal, and it's far from the only
resource like that. Only a capability whose author has actually verified
a field is genuinely never populated on unsupported hardware opts into
stricter gating with its own is_stub_rep-based exists_fn (see
common.ENERGY_METER, issue #127) -- this default stays permissive.
A stub rep (is_stub_rep) is included anyway so it can be populated by
sub-polls. A genuinely empty {} rep is included too by this default
gate: whether empty means "not populated yet" or "permanently
unsupported" needs per-field domain knowledge this generic gate
doesn't have (e.g. /alarms/vs/0's {} is fridge.py's documented normal
no-alarm state, not an absence signal). Only a capability whose author
has verified a field is genuinely never populated opts into stricter
gating with its own exists_fn (see common.ENERGY_METER, issue #127).
`bound.href` is already the *actual* href (issue #177 -- see
BoundEntity/Subdevice), so the direct cache lookup below is correct as-is;
`exists_fn` gets `bound`'s own subdevice's *canonical* view instead of the
raw snapshot, same rule as everywhere else a whole-resources-dict scan
happens (coordinator.canonical_resources) -- this is a free function, not
an LocalThingsEntity method, so it can't use self._resources.
`bound.href` is already the actual href (issue #177); `exists_fn` gets
`bound`'s own subdevice's canonical view instead of the raw snapshot,
same rule as everywhere else a whole-resources-dict scan happens --
this is a free function, so it can't use self._resources.
"""
rep = coordinator.last_resources.get(bound.href)
if rep is None:
@@ -97,12 +92,10 @@ class LocalThingsEntity(CoordinatorEntity[LocalThingsCoordinator]):
"instance_name": _instance_display_name(bound, self._state_key)
}
# _attr_name is deliberately left unset: Home Assistant gives an
# explicitly-set name precedence over the translation catalog, so
# setting it here would make every entity untranslatable. Every
# descriptor resolves to a catalog entry (see translation_key below);
# a platform that wants the bare device name instead sets
# _attr_name = None itself, as fan.py does for the hood's main entity.
# _attr_name is deliberately left unset: HA gives an explicitly-set
# name precedence over the translation catalog, so setting it here
# would make every entity untranslatable. A platform that wants the
# bare device name sets _attr_name = None itself (see fan.py).
self._attr_icon = bound.desc.icon
raw_cat = bound.desc.entity_category
self._attr_entity_category = EntityCategory(raw_cat) if raw_cat else None
@@ -112,18 +105,12 @@ class LocalThingsEntity(CoordinatorEntity[LocalThingsCoordinator]):
def translation_key(self) -> str | None:
"""The descriptor's catalog key, defaulting to its own `key`.
Overrides Entity.translation_key (a property upstream, not a plain
attribute) so a callable descriptor -- e.g. laundry.cycle_select's
table-id-gated resolver -- is re-evaluated against live coordinator
data on every access, not resolved once at construction time.
Discovery runs on the first /device/0 poll, which the entity
registry already documents can hand a sibling resource an empty
stub rep before it's actually been fetched (see _is_included's
docstring) -- a static one-time resolution here would risk baking
in a permanent None (no translation) for the entity's whole
lifetime if that stub hadn't populated yet, even once the real
value arrives on a later poll.
Overrides Entity.translation_key so a callable descriptor (e.g.
laundry.cycle_select's table-id-gated resolver) is re-evaluated
against live coordinator data on every access, not resolved once
at construction time -- a static resolution would risk baking in
a permanent None if the first poll handed a sibling an empty stub
rep (see _is_included's docstring) before it populated.
"""
tk = self._bound.desc.translation_key
if callable(tk):
@@ -133,12 +120,11 @@ class LocalThingsEntity(CoordinatorEntity[LocalThingsCoordinator]):
@property
def _resources(self) -> dict:
"""This entity's own subdevice's canonical resources view (issue
#177) -- see coordinator.canonical_resources. Every platform
property that needs the *whole* resources dict, as opposed to one
href via `coordinator.resource(href)`, must read through this
instead of `coordinator.last_resources`, or a sibling subdevice's own
actual hrefs would leak into (or be missing from) this entity's
view. For MAIN (every device with no subdevices) this is exactly
#177) -- see coordinator.canonical_resources. Any platform property
needing the whole resources dict, not one href via
`coordinator.resource(href)`, must read through this instead of
`coordinator.last_resources`, or a sibling subdevice's own hrefs
could leak into this entity's view. For MAIN this is exactly
`coordinator.last_resources`."""
return self.coordinator.canonical_resources(self._bound.subdevice)
+34 -52
View File
@@ -4,15 +4,14 @@ Four FanDesc-bound hrefs exist, dispatched by href in async_setup_entry
below since each needs different HA fan semantics: the range hood's fan
speed and the older ARTIK051_TVTL air-purifier family's Auto/Sleep/Low/
Medium/High (issue #56) are both an ordered set of numeric levels
(SET_SPEED) -- the latter confirmed monotonic in capabilities/
air_purifier.py's module docstring, with no named-mode list to preserve
since this board never self-reports one. The TP1X air-purifier family's
modes (Smart/Max/Mid/WindFree/Sleep, issue #130) and the A-VTWW-TP2-21
family's /wind/strength/vs/0 modes (issue #151) are both named behaviors
with no linear order (PRESET_MODE) -- LocalThingsAirPurifierFan handles
both hrefs, the only difference being whether the label comes straight
from supportedModes or from a parallel modesName array (see
_label_for_code)."""
(SET_SPEED), confirmed monotonic in capabilities/air_purifier.py's module
docstring, with no named-mode list since this board never self-reports one.
The TP1X air-purifier family's modes (Smart/Max/Mid/WindFree/Sleep, issue
#130) and the A-VTWW-TP2-21 family's /wind/strength/vs/0 modes (issue #151)
are both named behaviors with no linear order (PRESET_MODE) --
LocalThingsAirPurifierFan handles both hrefs, the only difference being
whether the label comes from supportedModes or a parallel modesName array
(see _label_for_code)."""
from __future__ import annotations
@@ -76,19 +75,14 @@ class LocalThingsRangeHoodFan(LocalThingsEntity, FanEntity):
Some boards that reuse this capability (built-in microwave vent fans,
issues #137/#142) report no sibling `/power/0` or `/power/vs/0`
resource at all -- fan speed 0 is itself the off state there, with no
separate power toggle to write. `_speed_zero_is_off` detects that
shape from the hood resource's own settableMinFanSpeed/
supportedFanSpeed fields and switches every method below to drive
off/on purely through the fanSpeed field, including '0' in the
ordered speed codes as the off step instead of assuming every
advertised code is an active speed.
resource at all -- fan speed 0 is itself the off state there.
`_speed_zero_is_off` detects that shape and switches every method
below to drive off/on purely through the fanSpeed field.
This is deliberately not the same question as `_has_separate_power`,
which only proves *some* power resource exists on the device -- on a
combi appliance (e.g. an over-the-range microwave) that resource can
belong to the cavity, not the vent fan, and toggling it from here
would turn off the whole appliance instead of just the fan.
Deliberately not the same question as `_has_separate_power`, which
only proves some power resource exists on the device -- on a combi
appliance that resource can belong to the cavity, not the vent fan,
and toggling it from here would turn off the whole appliance.
"""
_enable_turn_on_off_backwards_compatibility = False
@@ -112,10 +106,9 @@ class LocalThingsRangeHoodFan(LocalThingsEntity, FanEntity):
def _speed_zero_is_off(self) -> bool:
"""Whether fan speed '0' is itself this hood's off step, with no
separate power resource to toggle. The board says so directly:
settableMinFanSpeed '0', or '0' inside supportedFanSpeed. The
standalone hood's codes start at 14 and it carries a real /power
resource instead, so this is False there."""
separate power resource to toggle -- settableMinFanSpeed '0', or
'0' inside supportedFanSpeed. False for the standalone hood, whose
codes start at 14 and which carries a real /power resource."""
rep = self._rep(self._bound.href)
return (
str(rep.get(_MIN_FAN_SPEED_FIELD, "")) == _OFF_SPEED_CODE
@@ -140,12 +133,10 @@ class LocalThingsRangeHoodFan(LocalThingsEntity, FanEntity):
def _active_speed_codes(self) -> list[str]:
codes = self._all_speed_codes()
if self._speed_zero_is_off():
# No separate power resource: '0' is the off step, not a speed.
return [code for code in codes if code != _OFF_SPEED_CODE]
# Power is carried by the separate /power resource. fanSpeed
# retains the selected setting while power is off (as the
# lamp's `current` field does), so every advertised code is an
# active ordered speed.
# Power is carried by the separate /power resource; fanSpeed
# retains the selected setting while power is off, so every
# advertised code is an active ordered speed.
return codes
def _power_payload(self, enabled: bool) -> tuple[str, bool, str]:
@@ -268,15 +259,12 @@ class LocalThingsAirPurifierFan(LocalThingsEntity, FanEntity):
def _label_for_code(self, code) -> str:
"""Lowercased HA preset label for a device mode code.
The TP1X_DA-AC-AIR board (issue #130) reports its named modes
directly as supportedModes ('Smart'/'Max'/...), so the code IS the
label. The A-VTWW-TP2-21 board (issue #151) instead reports numeric
wind-strength codes ('87'/'89'/...) with a separate modesName array
(parallel-indexed with supportedModes) giving the actual names --
same shape as climate.py's _wind_strength_label, and coincidentally
the same word set (Smart/Max/WindFree/Sleep), so both board
generations land on identical HA preset values without needing
their own translation catalog entry."""
The TP1X_DA-AC-AIR board (issue #130) reports named modes directly
as supportedModes, so the code IS the label. The A-VTWW-TP2-21
board (issue #151) instead reports numeric wind-strength codes with
a separate modesName array giving the real names -- same shape as
climate.py's _wind_strength_label, and coincidentally the same word
set, so both generations land on identical HA preset values."""
rep = self._mode_rep()
supported = list(rep.get(_SUPPORTED_MODES_FIELD, ()))
names = rep.get(_MODES_NAME_FIELD)
@@ -327,11 +315,8 @@ class LocalThingsAirPurifierFan(LocalThingsEntity, FanEntity):
_AIRFLOW_SPEED_FIELD = "speed"
# Raw `speed` codes, low-to-high -- confirmed monotonic (Auto=0, Sleep=1,
# Low=2, Medium=3, High=4) via air_purifier.py's module docstring. Ordered
# as plain strings, same as _all_speed_codes above, so
# ordered_list_item_to_percentage/percentage_to_ordered_list_item can treat
# it exactly like the range hood's numeric levels -- no named-preset table
# needed since this board never reports mode names to hang one off of.
# Low=2, Medium=3, High=4) via air_purifier.py's module docstring. Treated
# as plain ordered strings, same as the range hood's numeric levels.
_AIRFLOW_SPEED_CODES = ["0", "1", "2", "3", "4"]
@@ -354,14 +339,11 @@ class LocalThingsAirflowFan(LocalThingsEntity, FanEntity):
def _power_payload(self, enabled: bool) -> tuple[str, bool, str]:
"""Prefer /power/0 like LocalThingsRangeHoodFan above, NOT
LocalThingsAirPurifierFan's vs/0-first order -- that order is only
harmless for the TP1X board because it never reports /power/0 at
all. This family's dumps carry both hrefs, and common.POWER_GENERIC
(the power_switch entity) is unconditionally bound to /power/0
whenever it's present, so writing here to /power/vs/0 first would
leave power_switch and this fan reading/writing two different
resources -- disagreeing until the next poll refreshes the other
one (the same optimistic-apply lag coordinator.py's own comments
warn about)."""
harmless for the TP1X board because it never reports /power/0.
This family's dumps carry both hrefs, and common.POWER_GENERIC is
unconditionally bound to /power/0 when present, so writing to
/power/vs/0 first would leave power_switch and this fan
disagreeing until the next poll."""
resources = self._resources
target = POWER_HREF if POWER_HREF in resources else POWER_VS_HREF
return "power", enabled, target
+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.20.0"
}
+57 -23
View File
@@ -171,17 +171,16 @@ class ObserveManager:
self._last_notify_ts is not None and time.monotonic() - self._last_notify_ts < window_s
)
def try_enter_observe_mode(
self,
session,
hrefs: list[str],
grace_period_s: float = GRACE_PERIOD_S,
success_fraction: float = SUCCESS_FRACTION,
) -> bool:
"""Blocking — subscribes to every href then waits up to
`grace_period_s`, returning early once `success_fraction` of hrefs
have notified. Caller must run this in an executor, never on the
event loop."""
def subscribe_hrefs(self, session, hrefs: list[str]) -> set[str]:
"""Register OBSERVE on every href; returns the ones that took.
Blocking — run in an executor.
Split from the grace wait below (issue #294) so the coordinator can
hold its session lock for just these sends -- each is a fire-and-
forget UDP datagram (DtlsCoapSession.subscribe doesn't wait for the
device's ack), unlike the wait, which can block for the whole grace
period and must not hold a lock a command write is also waiting on.
"""
with self._notify_cond:
self._notified.clear()
subscribed: set[str] = set()
@@ -192,30 +191,65 @@ class ObserveManager:
subscribed.add(href)
except Exception as e:
self.log.warning("subscribe %s failed: %s", href, e)
return subscribed
def await_observe_notifies(
self,
subscribed: set[str],
grace_period_s: float = GRACE_PERIOD_S,
success_fraction: float = SUCCESS_FRACTION,
) -> bool:
"""Blocking — waits up to `grace_period_s`, returning early once
`success_fraction` of `subscribed` have notified. Touches no
session; safe to run without holding a session lock."""
if not subscribed:
self._stop_refresh_task()
self._set_mode(MODE_POLL)
self.subscribed_hrefs = set()
return False
def _fraction_reached() -> bool:
return len(set(self._notified) & subscribed) / len(subscribed) >= success_fraction
with self._notify_cond:
reached = self._notify_cond.wait_for(
_fraction_reached,
timeout=grace_period_s,
)
return self._notify_cond.wait_for(_fraction_reached, timeout=grace_period_s)
if reached:
self.subscribed_hrefs = subscribed
self._set_mode(MODE_OBSERVE)
self.start_refresh_task(session)
return True
def enter_observe_mode(self, session, subscribed: set[str]) -> None:
"""Commit a successful attempt. Caller must have re-confirmed
`session` is still the live one under its session lock (issue
#294) -- committing against a session a reconnect already replaced
would claim observe mode with nothing left to notice it's dead."""
self.subscribed_hrefs = set(subscribed)
self._set_mode(MODE_OBSERVE)
self.start_refresh_task(session)
def abandon_observe_attempt(self) -> None:
"""Drop a failed or stale attempt: no subscriptions worth keeping."""
self._stop_refresh_task()
self.subscribed_hrefs = set()
self._set_mode(MODE_POLL)
def try_enter_observe_mode(
self,
session,
hrefs: list[str],
grace_period_s: float = GRACE_PERIOD_S,
success_fraction: float = SUCCESS_FRACTION,
) -> bool:
"""Blocking — subscribes to every href then waits up to
`grace_period_s`, returning early once `success_fraction` of hrefs
have notified. Caller must run this in an executor, never on the
event loop.
Single-threaded convenience wrapper around the phase split above
(subscribe_hrefs / await_observe_notifies / enter_observe_mode /
abandon_observe_attempt) for callers -- direct and most existing
tests -- that don't need the lock-scoping those phases exist for."""
subscribed = self.subscribe_hrefs(session, hrefs)
if not subscribed:
self.abandon_observe_attempt()
return False
if self.await_observe_notifies(subscribed, grace_period_s, success_fraction):
self.enter_observe_mode(session, subscribed)
return True
self.abandon_observe_attempt()
return False
def _set_mode(self, mode: str) -> None:
@@ -18,12 +18,17 @@ def is_stub_rep(rep: dict) -> bool:
def parse_device0_batch(device0: list) -> dict[str, dict]:
"""Extract {href: rep} from a /device/0 CBOR list response.
Most devices put a collection representation without an ``href`` at
index 0, while some firmware starts directly with resource entries.
Iterate the whole list and let the existing href check ignore collection
metadata so the first real resource is preserved in either shape.
A stub rep is passed through unchanged rather than collapsed to {} --
downstream code (entity._is_included, capability exists_fns) uses
is_stub_rep to tell "not fetched yet" apart from a confirmed-empty {}.
"""
out = {}
for entry in device0[1:]: # skip [0] (device-level rep)
for entry in device0:
if not isinstance(entry, dict):
continue
href = entry.get("href")
@@ -63,9 +63,9 @@ _REGISTRY_BY_KEY: dict[str, DeviceRegistry] = {
# Consumer-model prefix (first two letters of the '_'-delimited token in
# `description` right before any '/board-info' suffix) -> registry key.
# NOT derived from `modelNum` -- washer and dryer share the same 'DA_WM_'
# internal board-family prefix there, and dishwasher's modelNum contains
# the substring 'WW', so a modelNum-only rule misroutes both.
# NOT derived from `modelNum`: washer and dryer share the same 'DA_WM_'
# board-family prefix there, and dishwasher's modelNum contains the
# substring 'WW', so a modelNum-only rule misroutes both.
_CONSUMER_PREFIX_TO_KEY: dict[str, str] = {
"WW": "washer",
"WD": "washer",
@@ -79,48 +79,39 @@ _CONSUMER_PREFIX_TO_KEY: dict[str, str] = {
# Board-family token -> registry key, matched against whole tokens of
# `modelNum`/`description` (see `_board_tokens`).
#
# Tokenizing instead of substring-matching is what keeps this a table rather
# than a ladder of hand-written rules. Samsung spells the same board family
# with either delimiter -- 'TP1X_DA-AC-RAC-01001' and 'TP2X_RAC_20K' are the
# same RAC family -- so a substring rule has to be written once per spelling
# ('_RAC_' *and* '-RAC-'), and a token that lands at the end of the
# pipe-prefix with no trailing delimiter ('ARTIK051_DONGLE_REF', issues #77
# and #83) matches no '_TOKEN_' spelling at all. Whole-token matching sees
# every one of those as a single entry.
# Tokenizing instead of substring-matching keeps this a table rather than a
# ladder of hand-written rules: Samsung spells the same board family with
# either delimiter ('TP1X_DA-AC-RAC-01001' vs 'TP2X_RAC_20K', both RAC), so
# a substring rule would need writing once per spelling, and a token with
# no trailing delimiter ('ARTIK051_DONGLE_REF') would match neither.
#
# Entries must name the *specific* device type, never the board family that
# Entries must name the specific device type, never the board family that
# contains it: 'DA-AC-' prefixes RAC/WAC/DHM/AIR alike, so a bare 'AC' entry
# would swallow the dehumidifier and the air purifier. Where two families
# genuinely share a resource surface they share a registry (all the
# air-conditioner spellings below), which is a statement about the hardware,
# not a shortcut.
# genuinely share a resource surface they share a registry (the
# air-conditioner spellings below), which is a statement about the
# hardware, not a shortcut.
_BOARD_TOKEN_TO_KEY: dict[str, str] = {
"REF": "refrigerator",
# Air conditioners. Every one of these is a distinct board family with
# the same resource surface: room (issues #37, #91), package, Korean
# (#136), window (#87), 2-in-1 floor+wall (#150, #153), system/commercial
# (#52), cassette (#191), and ARA-WW wall-mount (#115, #116, #117, #120).
# Air conditioners: distinct board families sharing one resource
# surface -- room, package, Korean (#136), window (#87), 2-in-1
# floor+wall (#150/#153), system/commercial (#52), cassette (#191), and
# ARA-WW wall-mount (#115-120).
"RAC": "airconditioner",
"PRAC": "airconditioner",
"KRAC": "airconditioner",
"WAC": "airconditioner",
"FAC": "airconditioner",
"CAWW": "airconditioner",
"CAC": "airconditioner", # issue #191 -- TP1X_DA-AC-CAC-01001_0000
"CAC": "airconditioner", # issue #191
"ARA": "airconditioner",
"DHM": "dehumidifier", # issue #88 -- target humidity, no climate
"EHS": "ehs", # Eco Heating System air-to-water heat pump --
# zone1 space heating/cooling + dhw domestic
# hot water, its own /mode/*/vs/0 and
# /temperatures/*/vs/0 resource shapes
"EHS": "ehs", # heat pump: zone1 heating/cooling + domestic hot water
"TVTL": "air_purifier", # issue #56 (ARTIK051)
"VTWW": "air_purifier", # issue #151 (BESPOKE Cube Air)
"AVT": "air_purifier", # issue #190 -- AVT-WW-TP1-23-AXX500, a
# next-gen BESPOKE Cube Air board; same
# lineage as VTWW above but the '-WW-'
# delimiter now falls one letter to the
# left ('A-VTWW-' -> 'AVT-WW-'), splitting
# into a token the existing entry can't see
# issue #190: same lineage as VTWW, but the '-WW-' delimiter falls one
# letter left ('A-VTWW-' -> 'AVT-WW-'), splitting into a different token.
"AVT": "air_purifier",
"AIR": "air_purifier", # issue #130 (TP1X_DA-AC-AIR)
"WATERPURIFIER": "water_purifier", # issue #90
"ADW": "dishwasher",
@@ -129,13 +120,12 @@ _BOARD_TOKEN_TO_KEY: dict[str, str] = {
"OVEN": "oven", # issue #55 -- wall oven, no burners
"MICROWAVE": "microwave", # issues #66, #121
"COOKTOP": "induction_cooktop", # issue #86 -- standalone, no oven
# Legacy ARTIK051 gas cooktops ('ARTIK051_GB_CT_001'), whose burner state
# lives in /mode/vs/0's options array. Deliberately a bare two-letter
# token, and so the loosest entry in this table -- it is only ever
# reached by a device that matched nothing more specific, and its
# `description` ('ARTIK051_GLOBAL_COOKTOP') would otherwise read as an
# induction cooktop via the COOKTOP entry above. See `for_device_by_model`
# for the field ordering that makes that resolve correctly.
# Legacy ARTIK051 gas cooktops ('ARTIK051_GB_CT_001'): burner state
# lives in /mode/vs/0's options array. Deliberately the loosest entry
# here -- reached only when nothing more specific matched, since its
# description ('ARTIK051_GLOBAL_COOKTOP') would otherwise read as an
# induction cooktop via COOKTOP above (see for_device_by_model's field
# ordering).
"CT": "cooktop",
"VSKR": "vacuum_station", # issue #131 -- stick-vacuum clean station
"DF": "air_dresser", # issue #162
@@ -161,20 +151,16 @@ def _board_tokens(value: str, cut_at: str) -> list[str]:
def _board_family_key(value: str, cut_at: str) -> str | None:
"""First `_BOARD_TOKEN_TO_KEY` hit among `value`'s tokens, or None.
No known modelNum or description yields two *conflicting* board keys, so
which token is found first doesn't matter within one field -- the table is
a flat lookup, not a priority list. Adding an entry that could co-occur
with another (a family token, or one short enough to collide by accident)
would break that property; see this table's comment.
No known modelNum or description yields two conflicting board keys, so
which token is found first doesn't matter within one field -- the
table is a flat lookup, not a priority list.
One documented exception (issue #196): AILITE water-purifier boards
spell their modelNum '...-REF-WATERPURIFIER-...', where 'REF' names the
shared cooling-subsystem board, not the refrigerator device type --
'WATERPURIFIER' is the actual, more specific type here. Rather than drop
or rename either entry (both are correct on their own for the model
strings that exist today), this one known co-occurrence resolves to
'water_purifier'; TestBoardTokenAmbiguity's blanket check carries a
matching carve-out for this exact pair.
spell their modelNum '...-REF-WATERPURIFIER-...', where 'REF' names
the shared cooling-subsystem board, not the refrigerator type --
'WATERPURIFIER' is the actual, more specific type. This one known
co-occurrence resolves to 'water_purifier'; TestBoardTokenAmbiguity
carries a matching carve-out for this exact pair.
"""
tokens = _board_tokens(value, cut_at)
if "REF" in tokens and "WATERPURIFIER" in tokens:
@@ -191,25 +177,19 @@ def _consumer_model_key(description: str) -> str | None:
Usually that token is the last '_'-delimited segment before any
'/board-info' suffix (e.g. '..._WW90DG6U25LEU4' -> 'WW90DG6U25LEU4').
But issue #79's dryer pairs two model numbers in one description --
'..._DVE50A8800_8600/DC92-...' -- so the true consumer token
('DVE50A8800') sits one segment *before* the actual last segment
('8600', a bare second model number with no recognizable prefix). Scan
segments from the end and take the first one that resolves, rather
than assuming the last segment is always it.
But issue #79's dryer pairs two model numbers in one description, so
the true consumer token sits one segment before the actual last
segment -- scan from the end and take the first segment that resolves.
Splits on '_' only, unlike `_board_tokens` above: these are two-letter
prefixes matched against the *start* of a segment, so widening the split
to '-' as well would start reading board-family segments as consumer
models -- the dishwasher's 'ADW-WW-RTL-24-AILITE' would offer up a bare
'WW' segment and route to washer.
Splits on '_' only, unlike `_board_tokens` above: widening the split to
'-' would start reading board-family segments as consumer models (the
dishwasher's 'ADW-WW-RTL-24-AILITE' would offer up a bare 'WW' and
route to washer).
Only a 2-letter *prefix* match -- e.g. 'WAC' (the Window Air Conditioner
board-family token, issue #87) also starts with 'WA' (the top-load-washer
prefix, issue #106) at this granularity. for_device_by_model() consults
the board-family table first and this function only as a fallback, so
that ambiguity resolves correctly without this function needing to know
about unrelated device families.
Only a 2-letter prefix match, so e.g. 'WAC' (Window AC, issue #87) also
matches 'WA' (top-load washer, issue #106) at this granularity --
for_device_by_model() consults the board-family table first and this
only as a fallback, so that ambiguity resolves correctly.
"""
segments = (description or "").split("/", 1)[0].split("_")
for segment in reversed(segments):
@@ -220,36 +200,25 @@ def _consumer_model_key(description: str) -> str | None:
# /oic/d's `rt` (OCF's own device-type declaration, see registry/identity.py)
# -> registry key. This is the device naming its own type -- no board-part
# guessing involved -- so it's consulted before modelNum/description at all.
# -> registry key. The device naming its own type, no board-part guessing --
# consulted before modelNum/description.
#
# Every value must already be a key in `_REGISTRY_BY_KEY` (checked by
# `test_every_oic_type_resolves_to_a_real_registry`). That's why this list
# stops well short of the full OCF/SmartThings device-type vocabulary: a
# compiled list of `x.com.st.d.*` types will include plenty of device
# categories (lights, switches, sensors, locks, cameras, TVs, generic energy
# meters, ...) no Samsung DA appliance dump could ever report and this
# integration has no registry for -- and 'oic.d.robotcleaner' names an
# actual robot vacuum, a different product from the clean/auto-empty
# *station* `vacuum_station` covers (see that registry's own module
# docstring); mapping it there would misroute a genuine robot-vacuum dump
# into a registry with no vacuum-body capabilities at all. Add a row only
# once there's a real registry key on the right-hand side to point at.
# `test_every_oic_type_resolves_to_a_real_registry`) -- this deliberately
# stops short of the full OCF/SmartThings vocabulary, since most of it (lights,
# locks, cameras, TVs, ...) has no registry here to point at, and
# 'oic.d.robotcleaner' names an actual robot vacuum, a different product from
# the clean/auto-empty *station* `vacuum_station` covers.
#
# `x.com.st.d.*` entries are SmartThings' own vendor extension to the OCF
# device-type vocabulary (used for categories with no `oic.d.*` equivalent),
# same prefix convention as the `x.com.samsung.da.*` resource fields
# elsewhere in this codebase.
# device-type vocabulary, for categories with no `oic.d.*` equivalent.
#
# `oic.d.cooktop` is deliberately absent, and is the one measured type left out.
# A TP1X_DA-KS-COOKTOP induction reports it, but `cooktop` and
# `induction_cooktop` are two unrelated registries that happen to share the
# English word (see by_type/cooktop.py's docstring: the NA9300K gas family keeps
# burner state in /mode/vs/0's options array, a completely different OCF
# surface). The OCF type does not distinguish them, so mapping it to either key
# would silently misroute the other -- and as the *primary* signal it would
# override a `COOKTOP`/`CT` board token that had it right. Same reasoning as
# `oic.d.robotcleaner` above: no unambiguous key to point at, so no row.
# `oic.d.cooktop` is deliberately absent: a TP1X_DA-KS-COOKTOP induction
# reports it, but `cooktop` and `induction_cooktop` are unrelated registries
# sharing the English word (see by_type/cooktop.py's docstring) -- the OCF
# type doesn't distinguish them, and as the primary signal it would override
# a correct `COOKTOP`/`CT` board token. No unambiguous key to point at, so no
# row.
_OIC_TYPE_TO_KEY: dict[str, str] = {
"oic.d.airconditioner": "airconditioner",
"oic.d.airpurifier": "air_purifier",
@@ -268,13 +237,10 @@ _OIC_TYPE_TO_KEY: dict[str, str] = {
def for_device_by_oic_type(device_types: Sequence[str]) -> DeviceRegistry | None:
"""Device-type detection from /oic/d's `rt` -- OCF's own device-type
declaration.
The primary path when a dump carries it: the device names its own type,
so there's nothing to infer from board part numbers. Most hardware still
doesn't populate `/oic/d` usefully -- see `resolve()`'s docstring -- so
this only ever helps a minority of dumps, and `for_device_by_model`/
`for_device_by_resources` remain load-bearing for everything else.
declaration. The primary path when a dump carries it, since the device
names its own type. Most hardware still doesn't populate `/oic/d`
usefully, so `for_device_by_model`/`for_device_by_resources` remain
load-bearing for everything else.
"""
for device_type in device_types:
key = _OIC_TYPE_TO_KEY.get(device_type)
@@ -323,15 +289,15 @@ def for_device_by_model(model_num: str, description: str) -> DeviceRegistry | No
def for_device_by_resources(resources: dict[str, dict]) -> DeviceRegistry | None:
"""Detect a device family from a distinctive local-resource signature.
This runs first as an override path for non-standard devices, not because
resource signatures are inherently more trustworthy than OIC/model
metadata. It also types boards that ship no ``/information/vs/0`` at all,
leaving `for_device_by_model` nothing to read. Some newer cooktops are the
original case: their mode resource still identifies them, carrying a
DeviceType option and multiple per-burner OperationState options.
Runs first as an override path for non-standard devices -- not because
resource signatures are more trustworthy than OIC/model metadata, but
because it also types boards with no ``/information/vs/0`` at all.
Some newer cooktops were the original case: their mode resource still
identifies them via a DeviceType option and multiple per-burner
OperationState options.
Require two independent shapes for every signature here, never one, so
putting this ahead of OIC/model metadata cannot let a common resource
Every signature here requires two independent shapes, never one, so
running this ahead of OIC/model metadata can't let a common resource
misclassify an unrelated family.
"""
mode = resources.get("/mode/vs/0", {})
@@ -347,12 +313,10 @@ def for_device_by_resources(resources: dict[str, dict]) -> DeviceRegistry | None
if "/hood/fanspeed/vs/0" in resources and "/hood/lamp/vs/0" in resources:
return _REGISTRY_BY_KEY["range_hood"]
# Oven/range/microwave boards that report no /information/vs/0 at all
# (issue #74's NE63B8411SS, issue #172's ME8000T -- the resource is simply
# absent from the dump, not just empty) can't be matched via
# for_device_by_model's modelNum tokens either. Mode vocabulary alongside
# the oven cavity resource (/oven/vs/0) is a safe two-resource signature;
# it also corrects Qooker's generic oic.d.oven / OVEN metadata (issue
# PR #225) when resource detection runs before metadata.
# (issues #74, #172) can't be matched via modelNum tokens either. Mode
# vocabulary alongside the oven cavity resource (/oven/vs/0) is a safe
# two-resource signature; it also corrects Qooker's generic oic.d.oven
# metadata (PR #225) since resource detection runs before it.
supported_modes = mode.get("x.com.samsung.da.supportedModes") or ()
if not isinstance(supported_modes, (list, tuple)):
supported_modes = ()
@@ -379,20 +343,18 @@ def resolve(
flow's probe and the golden-regression harness all call this, so the
order can't drift between what ships and what the tests assert.
Distinctive resource signatures run first because they describe the live
capability surface a registry must bind. They are deliberately strict in
`for_device_by_resources`: each requires multiple independent details, so
this can correct misleading metadata (Qooker's generic ``oic.d.oven``)
without a common href overriding an unrelated family. When no signature
matches, `/oic/d`'s `rt` (read separately from the /device/0 dump -- see
registry/identity.py) wins over model-string parsing.
Distinctive resource signatures run first, since they describe the
live capability surface a registry must bind; `for_device_by_resources`
is deliberately strict (multiple independent details required) so this
can correct misleading metadata without a common href overriding an
unrelated family. When no signature matches, `/oic/d`'s `rt` wins over
model-string parsing.
`/otninformation/vs/0`'s oneUiVersion is deliberately not consulted. It
reads like the obvious signal -- the device naming its own type, e.g.
'7.0 Dishwasher' -- but only a minority of hardware populates it, every
device that does is already typed by its modelNum board token, and no
device-support issue has ever been fixed by adding a mapping for it. It
is still reported in diagnostics as a firmware-generation marker.
`/otninformation/vs/0`'s oneUiVersion is deliberately not consulted:
only a minority of hardware populates it, every device that does is
already typed by its modelNum board token, and no device-support issue
has ever needed it. Still reported in diagnostics as a firmware
marker.
"""
info = resources.get("/information/vs/0", {})
return (
@@ -22,6 +22,12 @@ match_fn discriminators that keep them from colliding):
resource surface as A-VTWW-TP2-21-COMMON above; no new capabilities
needed.
AIR_LEVEL_CHECK ("AI Purify" -- the periodic air-quality sensing engine on
/airlevelcheck/vs/0) is shared by the last three of those: their dumps all
carry the resource with the same field names, and only the TVTL family has no
such href. It was covered as opaque plumbing until two AVT-WW-TP1 dumps
(issues #84 and #190) showed it drives a real user-facing feature.
Reuses dishwasher.DIAGNOSIS for /diagnosis/vs/0 (identical field/write
contract).
"""
@@ -38,6 +44,7 @@ REGISTRY = DeviceRegistry(
*common.POWER,
dishwasher.DIAGNOSIS,
air_purifier.AIR_QUALITY,
air_purifier.AIR_LEVEL_CHECK,
air_purifier.FILTER,
air_purifier.DEVICE_ACTIVE,
air_purifier.AIRFLOW_GENERIC,
@@ -17,7 +17,7 @@ uses unconditionally.
Reuses dishwasher.DIAGNOSIS for /diagnosis/vs/0.
"""
from ..capabilities import airconditioner, common, dishwasher, ignored
from ..capabilities import air_purifier, airconditioner, common, dishwasher, ignored
from ._base import DeviceRegistry, _build
REGISTRY = DeviceRegistry(
@@ -46,6 +46,28 @@ REGISTRY = DeviceRegistry(
airconditioner.CURRENT_TEMPERATURE,
airconditioner.CURRENT_TEMPERATURE_VS,
airconditioner.HUMIDITY,
# TP1X_DA-AC-FAC-class (issue #319): shares its /display/vs/0,
# /settings/sound/output/vs/0 and /settings/sound/volume/vs/0
# shape with the sibling TP1X_DA-AC-AIR board in air_purifier.py.
air_purifier.DISPLAY,
air_purifier.SOUND_OUTPUT,
air_purifier.SOUND_VOLUME,
airconditioner.SOUND_MODE,
airconditioner.ABSENCE_CLEAN,
airconditioner.MDS_ABSENCE_CLEAN,
airconditioner.ENERGY_SAVING,
airconditioner.EDGE_LIGHTING,
airconditioner.LIGHT_STATEFUL,
# System Fresh Air Ventilator (PR #316, ACA-KR-TP2-21-AN9000):
# WINDFREE/WINDSLEEP are this device's own hrefs; HEPA_FILTER/
# DEVICE_ACTIVE reuse air_purifier.py's identical shapes.
# AIR_LEVEL_CHECK is not this-device-specific -- see its
# removal from _AC_IGNORED above.
airconditioner.WINDFREE,
airconditioner.WINDSLEEP,
air_purifier.HEPA_FILTER,
air_purifier.DEVICE_ACTIVE,
air_purifier.AIR_LEVEL_CHECK,
*airconditioner.COVERAGE,
]
),
@@ -22,6 +22,12 @@ REGISTRY = DeviceRegistry(
cooktop.COOKTOP_CONNECTED,
cooktop.PAIRED_HOOD_STATUS,
common.FIRMWARE_UPDATE,
# issue #314: /alarms/vs/0 and /kidslock/vs/0 are the same
# generic shapes common.UNIVERSAL already models elsewhere --
# picked individually rather than pulling in all of UNIVERSAL,
# matching this registry's existing hand-picked-common style.
common.ALARMS,
common.KIDS_LOCK_VS_FALLBACK,
]
),
)
@@ -1,6 +1,6 @@
"""Oven device registry."""
from ..capabilities import common, ignored, oven
from ..capabilities import common, dishwasher, ignored, oven
from ._base import DeviceRegistry, _build
REGISTRY = DeviceRegistry(
@@ -18,6 +18,9 @@ REGISTRY = DeviceRegistry(
oven.OVEN_CONNECTED,
oven.OVEN_SPEC,
oven.OVEN_RECIPE_COOK,
# issue #300: /diagnosis/vs/0 is the same diagnosisStart shape
# dishwasher.py and airconditioner.py already reuse.
dishwasher.DIAGNOSIS,
]
),
)
@@ -13,6 +13,7 @@ REGISTRY = DeviceRegistry(
fridge.STATUS_LOCK,
fridge.DOOR_ALERT,
common.WATER_FILTER,
fridge.AIR_FILTER,
dishwasher.DIAGNOSIS,
fridge.ICEMAKER_NIGHTTIME,
fridge.FLEX_ZONE,
@@ -12,24 +12,16 @@ reports a CO2 reading the other two families don't.
A second `value` list element on the particulate-matter types (e.g. Dust's
`['31', '2']`) reads like a coarse quality-grade code, but nothing on this
board (no `supportedGrades`/similar field, no repeated dump to compare
against) confirms what its scale means -- left unbound rather than guessed,
per the adding-device-support skill's "still never invent... from nothing"
rule. Same reasoning `air_purifier.AIR_QUALITY` already applies to this
shape; index 0 is the only slot any family has ever read.
board confirms what its scale means -- left unbound rather than guessed;
index 0 is the only slot any family has ever read.
Dust/FineDust/SuperFineDust aren't assigned an HA `device_class`
(pm10/pm25/pm1) or `unit` despite the values reading like plausible
ug/m3 particulate readings in a physically consistent order (coarser
>= finer): Samsung's own two-tier Korean convention (i.e. "fine dust"/
"ultra-fine dust") maps only to a PM10/PM2.5 pair, and this board's
three-tier naming doesn't confirm where the extra tier or a PM1 reading
actually fits. The adding-device-support skill's read-side rule says
leave unit/device_class unset when the dump gives no field that
nominates one -- a wrong guess would silently mislabel every reading
forever, and the write-side rejection safety net doesn't cover reads.
Exposed as plain `measurement` sensors named after the device's own
field instead (matching air_purifier.AIR_QUALITY's existing precedent).
(pm10/pm25/pm1) or `unit` despite reading like plausible ug/m3 particulate
values: Samsung's own two-tier Korean convention maps only to a PM10/PM2.5
pair, and this board's three-tier naming doesn't confirm where the extra
tier or a PM1 reading fits. A wrong guess would silently mislabel every
reading forever, so they're plain `measurement` sensors named after the
device's own field instead, matching air_purifier.AIR_QUALITY's precedent.
"""
from datetime import time as dt_time
@@ -39,6 +31,12 @@ from ..entities import BinarySensorDesc, SensorDesc, SwitchDesc, TimeDesc
from .air_purifier import _AIR_QUALITY_SENSORS
from .common import int_or_none, sensor_item_value
# _AIR_QUALITY_SENSORS' fourth column (state_class) is deliberately discarded
# here: air_purifier leaves Odor/CleanLevel unstamped because they read as
# graded indices on that family, while this board has stamped all five as
# `measurement` since it was added (issue #210). Consuming the column would
# silently drop long-term statistics for two sensors on shipped devices, so
# the shared rows supply only the key/icon/type here.
SENSORS = Capability(
href="/sensors/vs/0",
poll_tier="warm",
@@ -51,7 +49,7 @@ SENSORS = Capability(
state_class="measurement",
value_fn=lambda items, t=sensor_type: sensor_item_value(items, t),
)
for key, icon, sensor_type in _AIR_QUALITY_SENSORS
for key, icon, sensor_type, _ in _AIR_QUALITY_SENSORS
),
SensorDesc(
key="co2",
@@ -134,13 +132,10 @@ def _dnd_time_write(field):
return _write
# Issue #210: no idle-vs-active dump pair exists for this href (only one
# dump total, DND never toggled in it), so this write contract is an
# educated guess, not a confirmed one -- symmetric with the read side
# (writing the same 'true'/'false' string shape and 'HH:MM:SS' format the
# device itself reports back) rather than invented from nothing, but still
# needs a reporter to actually flip it on real hardware and confirm. See
# the adding-device-support skill's "Educated guesses are fine" section.
# Issue #210: only one dump exists (DND never toggled in it), so this write
# contract is an educated guess -- symmetric with the read side's own
# 'true'/'false' and 'HH:MM:SS' formats, but still needs a reporter to
# confirm it on real hardware.
DND = Capability(
href="/dnd/vs/0",
poll_tier="cold",
@@ -1,63 +1,29 @@
"""Capabilities for the Samsung ARTIK051_TVTL-class air purifier family
(model AX60R5080WD/SE, issue #56).
Power, kids-lock, remote-control, alarms, and the energy meter are the shared
common.py capabilities (this family exposes the standard /power/0+/power/vs/0
pair and /alarms/vs/0, /energy/consumption/vs/0). /diagnosis/vs/0 reuses
dishwasher.DIAGNOSIS -- identical field/write contract
(x.com.samsung.da.diagnosisStart, 'Ready' on both dumps).
Power, kids-lock, remote-control, alarms, and the energy meter are the
shared common.py capabilities; /diagnosis/vs/0 reuses dishwasher.DIAGNOSIS
(identical field/write contract).
/mode/vs/0's x.com.samsung.da.options array packs multiple independent
'<Prefix>_<value>' flags into one list -- the same packed-list contract
laundry.py's option_value/option_write already model for /course/vs/0's
options[] (reused directly below, just against this family's own href). Per
issue #56's follow-up (five diagnostics dumps captured with the physical unit
set to Auto/Sleep/Low/Medium/High):
Light_On / Light_Off -- a plain on/off flag; MODE below models it as a
real switch, RMW-replacing just that one entry.
NOT the same polarity as the AC family's own
Light_On/Light_Off token on its own /mode/vs/0
(airconditioner._display_light_on) -- that one is
confirmed inverted (Light_Off means the panel is
lit) on live hardware. Same token name, same
resource name, different device type and
opposite meaning -- don't unify them.
Comode_Off -- read 'Off' on *every* one of the five dumps,
including High/Low/Medium/Auto -- confirms this
is NOT the fan-speed selector (ruling out the
original guess); exposed read-only since its
actual purpose is still unconfirmed.
OptionCode_60282 -- confirmed opaque/not user-facing in the
SmartThings app; not modeled (same treatment as
range_hood's OptionCode_* token on the same
href).
Blooming_* -- confirmed to have no corresponding SmartThings
app setting; dropped entirely rather than kept
as an unexplained diagnostic (it did track 1:1
with Sleep mode across the five dumps -- 0 in
Sleep, 6 otherwise -- so it's plausibly an
automatic side effect of sleep mode, e.g. a
display-dimming level, but that's still a guess).
/mode/vs/0's options[] packs several '<Prefix>_<value>' flags, the same
packed-list contract as laundry.py's option_value/option_write. Light_On/
Light_Off is a real on/off switch here -- NOT the same polarity as the AC
family's own Light_On/Light_Off token on its own /mode/vs/0, which is
inverted (airconditioner._display_light_on). Comode_Off reads 'Off' on
every setting (Auto/Sleep/Low/Medium/High), ruling out the original
"fan speed selector" guess; exposed read-only. OptionCode_* and Blooming_*
are unmodeled: confirmed opaque / not app-facing.
/airflow/0's `speed` is now a real fan-speed control (issue #56 follow-up).
The first round of five dumps above wasn't conclusive -- it read 0 for both
Auto *and* High, and 3 for Low/Medium *and* Sleep, likely because all five
were captured within about a minute of each other, faster than this
integration's own ~30s poll cycle could settle each change. A second round,
captured 60-90s apart per setting on two independent units, confirmed a
clean monotonic mapping instead: Auto=0, Sleep=1, Low=2, Medium=3, High=4.
AIRFLOW_GENERIC below builds an ordered-speed fan off that confirmed 0-4
range -- same SET_SPEED shape as range_hood.py's fan, mapping HA's
percentage steps straight onto the raw code, no named-preset table needed
(unlike the TP1X family's FAN, which exposes real named modes because its
board actually reports a supportedModes list to hang names off of).
/airflow/vs/0's vendor `speedLevel` is NOT used for the same purpose -- it
was unreliable on both units in that second round (Low/Medium collided on
one unit, stuck at 0 throughout on the other), so AIRFLOW_VS_FALLBACK below
stays a plain read-only diagnostic even after this change.
/airflow/0's `speed` is a real fan-speed control: two independent units,
sampled 60-90s apart per setting, confirmed a clean monotonic 0-4 mapping
across Auto/Sleep/Low/Medium/High. AIRFLOW_GENERIC below builds an
ordered-speed fan off that range. /airflow/vs/0's vendor `speedLevel` is
NOT used for the same purpose -- unreliable on both units in the same
round (collided Low/Medium on one, stuck at 0 on the other).
"""
import datetime
from ..capability import Capability
from ..entities import (
BinarySensorDesc,
@@ -66,18 +32,16 @@ from ..entities import (
SelectDesc,
SensorDesc,
SwitchDesc,
TimeDesc,
)
from .common import filter_usage_percent, int_or_none, sensor_item_value
from .common import epoch_to_utc, filter_usage_percent, int_or_none, sensor_item_value
from .laundry import bool_option_exists, bool_option_value, option_value, option_write
# Newer TP1X_DA-AC-AIR-class boards (e.g. TP1X_DA-AC-AIR-01031_0000, issue
# #130) report fan modes directly on /mode/vs/0's top-level `modes`/
# `supportedModes` fields (Smart/Max/Mid/WindFree/Sleep) instead of packing
# everything into the options[] array the way the older ARTIK051_TVTL
# family above does -- that older family's /mode/vs/0 has no top-level
# supportedModes at all (see the module docstring's Comode_Off finding).
# Both board generations share the /mode/vs/0 href, so FAN and MODE below
# are mutually exclusive via this presence check rather than colliding.
# Newer TP1X_DA-AC-AIR-class boards (issue #130) report fan modes directly
# on /mode/vs/0's top-level modes/supportedModes instead of packing
# everything into options[] like the older ARTIK051_TVTL family. Both
# generations share this href; FAN and MODE below are mutually exclusive
# via presence of supportedModes.
HREF_MODE = "/mode/vs/0"
HREF_AIRFLOW = "/airflow/0"
HREF_WIND_STRENGTH = "/wind/strength/vs/0"
@@ -87,12 +51,31 @@ def _has_top_level_modes(rep, resources):
return isinstance(rep.get("x.com.samsung.da.supportedModes"), (list, tuple))
# The fourth column is state_class, which is what makes Home Assistant keep
# long-term statistics for a sensor -- without one, a reading is only in the
# short-term recorder history and disappears with the next purge (10 days by
# default), so it can't back a long-range air-quality graph. The values are
# already numeric (sensor_item_value returns int), so nothing else was in the
# way; three sensors in this same module (filter_progress, fan_speed_level,
# hepa_filter_usage) already declare one.
#
# Only the three particulate readings get it. They fall monotonically with
# particle size on three independent board families -- 11/9/5 on ARTIK051_TVTL
# (issue #56), 10/9/6 on AVT-WW-TP1 (issue #190), 18/14/9 on the range hood --
# which is concentration behaviour, and an average over time is meaningful for
# it. Odor and CleanLevel read 0-2 on every fixture and look like graded
# indices instead, where the mean of a grade isn't obviously meaningful; left
# without a state_class rather than guessing.
#
# Deliberately no device_class/unit here: pm1/pm25/pm10 would assert the
# reading is a µg/m³ concentration, and the dumps never say so. That's a
# separate call from making the series recordable at all.
_AIR_QUALITY_SENSORS = (
("dust", "mdi:blur", "Dust"),
("fine_dust", "mdi:blur", "FineDust"),
("super_fine_dust", "mdi:blur", "SuperFineDust"),
("odor", "mdi:scent", "Odor"),
("clean_level", "mdi:air-filter", "CleanLevel"),
("dust", "mdi:blur", "Dust", "measurement"),
("fine_dust", "mdi:blur", "FineDust", "measurement"),
("super_fine_dust", "mdi:blur", "SuperFineDust", "measurement"),
("odor", "mdi:scent", "Odor", None),
("clean_level", "mdi:air-filter", "CleanLevel", None),
)
AIR_QUALITY = Capability(
@@ -103,9 +86,10 @@ AIR_QUALITY = Capability(
key=key,
field="x.com.samsung.da.items",
icon=icon,
state_class=state_class,
value_fn=lambda items, t=sensor_type: sensor_item_value(items, t),
)
for key, icon, sensor_type in _AIR_QUALITY_SENSORS
for key, icon, sensor_type, state_class in _AIR_QUALITY_SENSORS
),
)
@@ -119,12 +103,9 @@ def _consumable_state(items, name):
return None
# FilterProgress is a 0-100 percentage counting up as the filter wears --
# confirmed via issue #56: the SmartThings app shows "Filter needs changing"
# once this reaches 100, so 100 means fully used, not "brand new." Named
# after the raw field (matching the AC/range_hood filterUsage convention,
# which counts the same direction) rather than "filter life," which would
# imply the opposite direction.
# FilterProgress counts UP as the filter wears (100 = "needs changing",
# confirmed via the SmartThings app) -- named after the raw field rather
# than "filter life," which would imply the opposite direction.
FILTER = Capability(
href="/consumable/vs/0",
poll_tier="cold",
@@ -157,11 +138,9 @@ DEVICE_ACTIVE = Capability(
def _power_write(power_href, value):
"""Shared 'power' payload handling for this family's three FanDesc write
functions -- targets whichever power href fan.py's _power_payload picked
(the board may only report /power/0); a hardcoded vendor href here would
silently no-op on such a board even though the entity's own is_on
already falls back to reading it correctly."""
"""Shared 'power' payload handling for this family's FanDescs -- targets
whichever power href fan.py picked (the board may only report
/power/0)."""
if power_href == "/power/0":
return ["power", "0"], {"value": bool(value)}
return (["power", "vs", "0"], {"x.com.samsung.da.power": "On" if value else "Off"})
@@ -176,24 +155,14 @@ def _airflow_fan_write(payload, rep, href=None):
return None
# Confirmed via issue #56's second, properly-spaced round of diagnostics
# (two independent units, 60-90s apart per setting): /airflow/0's `speed` is
# a clean, monotonic 0-4 code across Auto/Sleep/Low/Medium/High, so it now
# backs a real ordered-speed fan (fan.py's LocalThingsAirflowFan, same
# SET_SPEED shape as the range hood's) instead of a read-only sensor --
# no named-preset table needed, since HA's percentage steps map onto the
# raw 0-4 code directly, the same way the range hood's numeric levels do.
# `direction` stays a plain diagnostic: every dump seen (both rounds, both
# units) reads 'Off' for it regardless of fan setting, so there's nothing
# confirmed to control there yet.
# Confirmed monotonic 0-4 speed code (see module docstring) backs a real
# ordered-speed fan, same SET_SPEED shape as the range hood's. `direction`
# stays a diagnostic: every dump reads 'Off' regardless of fan setting.
#
# Keyed 'airflow_fan', not 'fan' -- FAN below (bound to the shared
# /mode/vs/0 href) also uses 'fan', and BoundEntity's unique_id is built
# from key alone (entity.py's _key), not href. FAN and AIRFLOW_GENERIC are
# only *empirically* mutually exclusive (every dump seen has one board
# generation's shape or the other, never both), not architecturally
# enforced the way same-href caps are by _build()'s match_fn check -- a
# same key would collide if a future board ever reported both.
# Keyed 'airflow_fan', not 'fan' -- FAN below shares this registry and also
# uses key 'fan'; unique_id is built from key alone, so a shared key would
# collide if a board ever reported both (empirically mutually exclusive,
# not architecturally enforced the way same-href caps are).
AIRFLOW_GENERIC = Capability(
href=HREF_AIRFLOW,
poll_tier="warm",
@@ -208,10 +177,8 @@ AIRFLOW_GENERIC = Capability(
),
)
# Left exactly as a read-only fallback -- speedLevel is NOT the same
# confirmed-reliable field as /airflow/0's speed above (see module
# docstring): it collided Low/Medium on one unit and stuck at 0 throughout
# on the other in the same properly-spaced round.
# Read-only fallback: speedLevel is unreliable (see module docstring),
# unlike /airflow/0's speed.
AIRFLOW_VS_FALLBACK = Capability(
href="/airflow/vs/0",
match_fn=lambda rep, resources: "/airflow/0" not in resources,
@@ -236,12 +203,9 @@ AIRFLOW_VS_FALLBACK = Capability(
def _light_write(payload, rep, href=None):
# option_write's single-token write is confirmed on a washer's
# /course/vs/0 (issue #54), NOT independently on this family's
# /mode/vs/0 -- extrapolated on the assumption the same vendor field
# merges the same way everywhere. If some unit replaces the field
# outright instead, this would drop Comode/OptionCode alongside it on
# the next light toggle; revisit if a real device report surfaces that.
# option_write's single-token merge is confirmed on a washer's
# /course/vs/0 (issue #54); extrapolated here on the assumption the
# same vendor field merges the same way on this family's /mode/vs/0.
return ["mode", "vs", "0"], {
"x.com.samsung.da.options": option_write("Light", payload),
}
@@ -283,9 +247,8 @@ def _fan_write(payload, rep, href=None):
def _first_fan_mode(rep):
"""Representative scalar for the fan entity in the flattened state
(golden/regression), mirroring airconditioner.py's own _first_mode --
the real entity computes its state from live coordinator reads."""
"""Representative scalar for the flattened golden state; the real
entity reads live coordinator state instead."""
modes = rep.get("x.com.samsung.da.modes")
if isinstance(modes, (list, tuple)):
return modes[0] if modes else None
@@ -293,10 +256,8 @@ def _first_fan_mode(rep):
# Named preset modes (Smart/Max/Mid/WindFree/Sleep), not an ordered
# percentage -- WindFree/Smart/Sleep are named behaviors, not
# "faster/slower" positions relative to Max/Mid, so fan.py's entity for
# this only exposes PRESET_MODE, matching how the AC family's own named
# convenient modes are modeled as a preset rather than a speed number.
# percentage -- these are named behaviors, not "faster/slower" positions,
# so fan.py only exposes PRESET_MODE here.
FAN = Capability(
href=HREF_MODE,
poll_tier="warm",
@@ -321,19 +282,14 @@ def _wind_strength_fan_write(payload, rep, href=None):
return None
# A-VTWW-TP2-21-COMMON (issue #151): named preset modes like FAN above, but
# on a distinct href with numeric codes ("87"/"89"/"90"/"91") instead of
# A-VTWW-TP2-21-COMMON (issue #151): named presets like FAN above, but on a
# distinct href with numeric codes ("87"/"89"/"90"/"91") instead of
# self-describing supportedModes -- x.com.samsung.da.modesName gives the
# actual names (SMART/MAX/WINDFREE/Sleep), read live by fan.py's
# LocalThingsAirPurifierFan._label_for_code rather than a hardcoded
# per-model map. modes here is a bare string ('87'), not a single-element
# list like HREF_MODE's -- _wind_strength_fan_write writes it back as-is.
# real names, read live by fan.py rather than a hardcoded map. `modes` is a
# bare string here, not a single-element list like HREF_MODE's.
#
# key is 'wind_strength_fan', NOT 'fan' -- FAN above shares this registry
# and also uses a FanDesc; BoundEntity's unique_id is built from key alone
# (entity.py's _key), not href, so two same-key FanDescs in one registry
# would collide if a board ever bound both (see AIRFLOW_GENERIC's own
# comment on this exact hazard -- missed here in the initial cut).
# key is 'wind_strength_fan', not 'fan' -- same unique_id collision hazard
# as AIRFLOW_GENERIC above.
WIND_STRENGTH_FAN = Capability(
href=HREF_WIND_STRENGTH,
poll_tier="warm",
@@ -347,15 +303,12 @@ WIND_STRENGTH_FAN = Capability(
),
)
# ---------------------------------------------------------------------------
# TP1X_DA-AC-AIR-class additions (issue #130). This board reports several
# resources the older ARTIK051_TVTL family never did.
# ---------------------------------------------------------------------------
# TP1X_DA-AC-AIR-class additions (issue #130): resources the older
# ARTIK051_TVTL family never reported.
# Screen/indicator-panel on/off -- distinct from LIGHT below (ambient mood
# light): both report the same {mode, supportedModes: [On, Off]} shape on
# separate hrefs on this dump, so they're two independent physical controls,
# not a duplicate encoding of one.
# Screen/indicator panel on/off, distinct from the display_light switch
# above (ambient mood light) -- two independent controls on separate hrefs
# with the same {mode, supportedModes: [On, Off]} shape.
DISPLAY = Capability(
href="/display/vs/0",
poll_tier="cold",
@@ -374,10 +327,8 @@ DISPLAY = Capability(
),
)
# Same filterUsage/filterCapacity/filterStatus shape as the AC family's own
# AIR_FILTER (airconditioner.py) -- confirmed normal/wash/replace values not
# seen on this one dump, so the option list there is reused as-is rather
# than re-deriving it from a single sample.
# Same filterUsage/filterCapacity/filterStatus shape as the AC family's
# AIR_FILTER; the normal/wash/replace option list is reused as-is.
HEPA_FILTER = Capability(
href="/filter/hepafilter/vs/0",
poll_tier="cold",
@@ -403,10 +354,9 @@ HEPA_FILTER = Capability(
),
)
# Physical panel/cover status -- meaning of the one value seen ('Close') is
# plausible (the HEPA-filter access cover) but unconfirmed, and no
# supportedStatus list is present to check against -- exposed as a plain
# diagnostic sensor rather than an asserted binary_sensor polarity.
# Physical panel/cover status ('Close' seen, plausibly the HEPA-filter
# cover) -- unconfirmed, and no supportedStatus list to check against, so a
# plain diagnostic rather than an asserted binary_sensor.
PANEL_STATUS = Capability(
href="/panel/vs/0",
poll_tier="cold",
@@ -440,22 +390,18 @@ PET_FILTER_ACTIVATION = Capability(
),
)
# Sound mode/volume shapes look like laundry.py's SOUND_MODE/SOUND_VOLUME at
# a glance, but this board's actual values differ (supportedModes here is
# ['mute', 'buzzer'], not laundry's hardcoded voice/tone/mute; volume range
# is 0-3, not laundry's fixed 0-15) -- reusing those would either reject a
# valid write ('buzzer') or expose the wrong number range, so these are
# separate descriptors reading the live supported values instead of a
# hardcoded table.
# Sound mode/volume look like laundry.py's SOUND_MODE/SOUND_VOLUME but this
# board's actual values differ (supportedModes here is ['mute', 'buzzer'],
# not laundry's voice/tone/mute; volume is 0-3, not laundry's fixed 0-15) --
# separate descriptors reading live supported values instead of reusing
# laundry's hardcoded table.
SOUND_MODE = Capability(
href="/settings/sound/mode/vs/0",
poll_tier="cold",
entities=(
# Distinct translation_key from laundry.SOUND_MODE's shared
# 'sound_mode' catalog entry -- that one's state table is
# {voice, tone, mute}, but this board's supportedModes is
# {mute, buzzer}. Sharing the key would leave 'buzzer' unlabelled
# (falls through to the raw code) since the catalogs don't overlap.
# 'sound_mode' catalog ({voice, tone, mute}) -- this board's
# {mute, buzzer} doesn't overlap it.
SelectDesc(
key="sound_mode",
translation_key="air_purifier_sound_mode",
@@ -495,6 +441,10 @@ SOUND_VOLUME = Capability(
field="level",
icon="mdi:volume-medium",
entity_category="config",
# Some boards (issue #319's AC) report minLevel/resolution but no
# maxLevel -- native_max_fn would silently collapse to 0, giving a
# slider with no real range instead of no entity at all.
exists_fn=lambda rep, resources: "maxLevel" in rep,
native_min_fn=lambda rep: int_or_none(rep.get("minLevel")) or 0,
native_max_fn=lambda rep: int_or_none(rep.get("maxLevel")) or 0,
step_fn=lambda rep: int_or_none(rep.get("resolution")) or 1,
@@ -507,35 +457,229 @@ SOUND_VOLUME = Capability(
),
)
# /humidity/0 and /humidity/vs/0 are empty {} on both dumps this family has
# been verified against -- covered here (not globally, per ignored.py's
# module docstring) since those hrefs collide with fridge/AC schemas
# elsewhere. Same two hrefs and reasoning as airconditioner.py's _AC_IGNORED.
# AI Purify -- /airlevelcheck/vs/0 (issues #84, #190). Not scheduler
# plumbing: it drives the SmartThings app's "AI Purify" feature (the unit
# wakes on a timer, samples air, optionally acts). Reported with the same
# field names by three of this registry's four board families (TP1X_DA-AC-AIR
# #130, A-VTWW-TP2 #151, AVT-WW-TP1 #84/#190); ARTIK051_TVTL has no such
# href. Bound unconditionally since it's safe to no-op where absent.
#
# The next six hrefs (issue #130, TP1X_DA-AC-AIR board) are the exact same
# resources, same shapes, same reasoning as airconditioner.py's
# _AC_IGNORED on the shared DA-AC- board family -- duplicated here rather
# than promoted to the global ignored.py list, since that would require
# also removing them from _AC_IGNORED in the same change (a global entry
# colliding with a family-local bare Capability on the same href raises in
# _build()); left as a possible follow-up DRY cleanup.
# Two independent knobs, one entity each rather than folded into one
# select: periodicSensingActivationState (is it running) and autoExeState
# (what it does with a bad reading, Off/Airpurify/Alarm) -- mirrors the
# appliance's own UI. Folding them lost information: a configured action
# became invisible while off, and no option could toggle the feature
# without also overwriting the action. The two "off"s are NOT
# interchangeable: the switch's off stops sampling entirely; the select's
# "Off" keeps sampling but doesn't act on it (the app calls that
# "sensing only").
#
# range_hood.AIR_LEVEL_CHECK models the same href's read-only fields
# (reused verbatim below) but is deliberately not imported: it exposes
# periodic_air_sensing as a read-only BinarySensorDesc where this board
# needs it writable, and reusing it would migrate every hood user's entity
# to a different platform.
#
# Every write below was exercised on AVT-WW-TP1-23-AXX500 hardware and
# verified by surviving a reconnect (this board 2.04s writes it silently
# discards, so an echo proves nothing). The other two families get the same
# writes on field-shape grounds only.
#
# Deferred: startSensingOnce looks like a one-shot "sense now" trigger but
# stays unbound until its side effect (not just the echo) is confirmed.
def _interval_minutes(seconds):
"""Device stores the interval in seconds; the entity is in minutes.
Rounds up (not to nearest) so a sub-minute value can't floor to 0."""
secs = int_or_none(seconds)
if secs is None:
return None
return -(-secs // 60) if secs > 0 else 0
def _interval_write(payload, rep, href=None):
# Minutes in the UI -> seconds on the wire. Modeled as a free Number,
# not the app's three fixed choices, since the resource advertises no
# constraint for this field (unlike supportedAutoExeState beside it)
# and accepts finer values than the app offers (60s drove an observed
# ~60s sensing cycle on hardware). One-minute floor matches this
# board's own reporting resolution (lastSensingTime lands on exact
# minutes). Zero is refused: unlike a real "no timer" 0 elsewhere in
# this repo, nothing establishes what 0 does here. Silent no-op via
# None, same shape as range_hood._lamp_level_write.
minutes = round(float(payload))
if minutes < 1:
return None
return ["airlevelcheck", "vs", "0"], {
"x.com.samsung.da.periodicSensingInterval": str(minutes * 60)
}
def _periodic_sensing_write(payload, rep, href=None):
# Master on/off; leaves autoExeState alone so the configured action
# survives the feature being toggled off -- the select can't do that,
# since every option write sets an action too.
return ["airlevelcheck", "vs", "0"], {
"x.com.samsung.da.periodicSensingActivationState": ("On" if payload == "On" else "Off")
}
def _skip_status_write(payload, rep, href=None):
return ["airlevelcheck", "vs", "0"], {
"x.com.samsung.da.periodicSensingSkipStatus": ("On" if payload == "On" else "Off")
}
# Daily skip window, stored as one HHMMHHMM string
# (periodicSensingSkipTime). Cross-confirmed on two units (inert
# '00000000' vs a real '03002300'). Split into two HA time entities; each
# write reads the other half back out of the live rep so the pair
# round-trips -- confirmed in both directions on hardware.
def _skip_time_read(part):
def _read(value):
raw = str(value or "")
chunk = raw[0:4] if part == "start" else raw[4:8]
if len(chunk) == 4 and chunk.isdigit():
try:
return datetime.time(int(chunk[:2]), int(chunk[2:]))
except ValueError:
return None
return None
return _read
def _skip_half(raw, part):
"""The half this write isn't setting, normalized. An unparseable half
becomes '0000' rather than carrying a malformed value back to the
device."""
chunk = (str(raw or "") + "00000000")[:8]
other = chunk[4:8] if part == "start" else chunk[0:4]
return other if _skip_time_read("end" if part == "start" else "start")(chunk) else "0000"
def _skip_time_write(part):
def _write(value, rep, href=None):
raw = rep.get("x.com.samsung.da.periodicSensingSkipTime", "")
hhmm = f"{value.hour:02d}{value.minute:02d}"
other = _skip_half(raw, part)
new = hhmm + other if part == "start" else other + hhmm
return ["airlevelcheck", "vs", "0"], {"x.com.samsung.da.periodicSensingSkipTime": new}
return _write
AIR_LEVEL_CHECK = Capability(
href="/airlevelcheck/vs/0",
poll_tier="warm",
entities=(
SwitchDesc(
key="periodic_air_sensing",
field="x.com.samsung.da.periodicSensingActivationState",
icon="mdi:radar",
entity_category="config",
value_fn=lambda v: str(v).lower() == "on",
write_fn=_periodic_sensing_write,
),
# Options come off supportedAutoExeState rather than a typed table,
# so an unrecognized fourth value still reaches the user.
SelectDesc(
key="sensing_mode",
field="x.com.samsung.da.autoExeState",
options_field="x.com.samsung.da.supportedAutoExeState",
translation_key="sensing_mode",
icon="mdi:radar",
entity_category="config",
write_fn=lambda p, rep, href=None: (
["airlevelcheck", "vs", "0"],
{"x.com.samsung.da.autoExeState": p},
),
),
# The one field that varies across families: TP1X_DA-AC-AIR (#130)
# omits it, so that board runs sensing on a fixed, unexposed
# interval.
NumberDesc(
key="sensing_interval",
field="x.com.samsung.da.periodicSensingInterval",
icon="mdi:timer-cog",
entity_category="config",
native_min=1,
native_max=60,
step=1,
unit="min",
exists_fn=lambda rep, resources: "x.com.samsung.da.periodicSensingInterval" in rep,
value_fn=_interval_minutes,
write_fn=_interval_write,
),
SwitchDesc(
key="periodic_sensing_skip_status",
field="x.com.samsung.da.periodicSensingSkipStatus",
icon="mdi:sleep",
entity_category="config",
value_fn=lambda v: str(v).lower() == "on",
write_fn=_skip_status_write,
),
TimeDesc(
key="sensing_skip_start",
field="x.com.samsung.da.periodicSensingSkipTime",
icon="mdi:clock-start",
entity_category="config",
value_fn=_skip_time_read("start"),
write_fn=_skip_time_write("start"),
),
TimeDesc(
key="sensing_skip_end",
field="x.com.samsung.da.periodicSensingSkipTime",
icon="mdi:clock-end",
entity_category="config",
value_fn=_skip_time_read("end"),
write_fn=_skip_time_write("end"),
),
# Read-only status, same keys as range_hood.AIR_LEVEL_CHECK.
SensorDesc(
key="air_sensing_state",
field="x.com.samsung.da.sensingState",
icon="mdi:radar",
entity_category="diagnostic",
),
SensorDesc(
key="last_air_sensing_time",
field="x.com.samsung.da.lastSensingTime",
device_class="timestamp",
entity_category="diagnostic",
value_fn=epoch_to_utc,
),
# 'Kr1' on both dumps -- a region-prefixed, undocumented grade;
# stays a raw diagnostic rather than an asserted enum.
SensorDesc(
key="last_air_sensing_level",
field="x.com.samsung.da.lastSensingLevel",
icon="mdi:air-filter",
entity_category="diagnostic",
),
),
)
# /humidity/0 and /humidity/vs/0 are empty on both dumps -- covered here
# (not globally) since they collide with fridge/AC schemas elsewhere, same
# reasoning as airconditioner.py's _AC_IGNORED. The next six hrefs (issue
# #130) are the exact same DA-AC- board resources as _AC_IGNORED,
# duplicated here rather than promoted to the global list (a possible
# follow-up DRY cleanup).
COVERAGE = [
Capability(href="/humidity/0"),
Capability(href="/humidity/vs/0"),
Capability(href="/airlevelcheck/vs/0"), # periodic air-quality sensing scheduler plumbing
Capability(href="/availablecontrolsets/vs/0"), # opaque hex-encoded control-set bitmap
Capability(href="/da/softreset/vs/0"), # soft-reset trigger plumbing
Capability(href="/keepnormalstate/vs/0"), # internal keep-normal flag
Capability(href="/personality/presence/vs/0"), # presence-personalization plumbing (empty here)
Capability(href="/reserverulesets/vs/0"), # opaque hex-encoded schedule reservation blob
# Do-not-disturb/auto-sleep schedule (visible/startTime/endTime/
# useTimeSetting/functionState) -- every field reads its inert default
# on the only dump seen (times both '00:00:00', useTimeSetting/
# functionState both 'false'). Same "needs a multi-field schedule
# editor" treatment as fridge.py's /defrost/reservation/vs/0.
# Do-not-disturb/auto-sleep schedule -- every field reads its inert
# default on the only dump seen. Needs a multi-field schedule editor,
# same as fridge.py's /defrost/reservation/vs/0.
Capability(href="/dnd/autosleep/vs/0"),
# Empty ({}) on the A-VTWW-TP2-21 dump (issue #151) -- this board's
# convenient-mode-equivalent behavior lives entirely in WIND_STRENGTH_FAN
# above instead.
# Empty on the A-VTWW-TP2-21 dump (issue #151) -- this board's
# convenient-mode equivalent lives in WIND_STRENGTH_FAN instead.
Capability(href="/mode/convenient/vs/0"),
]
File diff suppressed because it is too large Load Diff
@@ -49,12 +49,10 @@ def wh_to_kwh(v):
def parse_iso_utc(raw):
"""ISO datetime defaulting to UTC when the string carries no timezone
of its own (this integration's convention for other bare ISO datetime
fields -- see washer.py's drum-clean-log comment). A few boards do
ship a 'Z'/offset suffix (fromisoformat parses that natively since
Python 3.11) -- only fill in UTC when parsing left the result naive,
rather than unconditionally overwriting whatever offset was parsed."""
"""ISO datetime defaulting to UTC when the string carries no timezone of
its own. A few boards ship a 'Z'/offset suffix already (fromisoformat
parses that natively since Python 3.11) -- only fill in UTC when parsing
left the result naive."""
if not raw:
return None
try:
@@ -64,11 +62,19 @@ def parse_iso_utc(raw):
return dt if dt.tzinfo is not None else dt.replace(tzinfo=UTC)
def epoch_to_utc(value):
"""Unix epoch seconds -> aware UTC datetime, for boards that report a
bare epoch rather than the ISO string parse_iso_utc handles."""
try:
return datetime.fromtimestamp(float(value), tz=UTC)
except (TypeError, ValueError, OSError):
return None
def filter_usage_percent(rep):
"""Filter usage as a percentage of rated capacity. Several families
(AC, air purifier) report `filterUsage` as a raw count in
`filterCapacityUnit` (Hours, e.g. 100 of a 500 capacity), so a plain
value with a '%' unit would be wrong -- normalize to used/capacity.
report `filterUsage` as a raw count in `filterCapacityUnit` (e.g. 100 of
a 500-hour capacity), so a plain value with a '%' unit would be wrong.
Returns None when capacity is missing/zero."""
used = _num(rep.get("x.com.samsung.da.filterUsage"))
cap = _num(rep.get("x.com.samsung.da.filterCapacity"))
@@ -80,8 +86,8 @@ def filter_usage_percent(rep):
def normalize_temp_unit(raw, default="°F"):
"""'C'/'Celsius' -> '°C', 'F'/'Fahrenheit' -> '°F'. Falls back to
`default` for any other/missing value. Shared by fridge.py and oven.py,
both of which read a per-device unit off a `/temperature*` resource
instead of assuming one (see fridge.py's module docstring, issue #7)."""
which both read a per-device unit off a `/temperature*` resource
instead of assuming one (issue #7)."""
raw = (raw or "").strip().upper()
if raw.startswith("C"):
return "°C"
@@ -96,25 +102,17 @@ def _ml_to_l(v):
def _active_alarm_codes(items):
"""Join active alarm codes; skip retained rows Samsung leaves as Deleted,
and any code ending in '_OFF'.
"""Join active alarm codes; skip retained rows Samsung leaves as
Deleted, and any code ending in '_OFF'.
Laundry boards keep a Deleted ErrorCode row in /alarms/vs/0 after the
condition clears (see WD7000B diagnostics). Surface only live alarms so
HA doesn't stick on a stale ErrorCode.
Samsung pre-populates this array with one row per alarm *type* the board
supports, each carrying its own '<Name>_OFF' placeholder code when that
alarm isn't firing -- confirmed across independent device families
(ErrorCode_OFF, FilterAlarm_OFF, OV_E_OFF, CT_E_OFF, WaterTankFull_OFF,
AC_V_0002_OFF all appear in fixtures with no corresponding active
condition). An alarm that's actually firing instead reports a plain,
unsuffixed code (FilterAlarm, DoorA_Opened, SNSF_Reached) -- issue #166's
AC dump has both a FilterAlarm_OFF placeholder and shows what a live
filter alert looks like: code 'FilterAlarm' (no suffix), state
'Created'. Range-hood previously special-cased only the literal
'ErrorCode_OFF' string in its own stricter helper; this generalizes
the same rule to the whole '_OFF' suffix convention.
condition clears. Samsung also pre-populates this array with one row
per alarm *type* the board supports, each carrying its own
'<Name>_OFF' placeholder when that alarm isn't firing -- confirmed
across independent families. A firing alarm instead reports a plain,
unsuffixed code (FilterAlarm, DoorA_Opened, ...); issue #166 shows both
in one dump. Generalizes what range hood used to special-case as just
the literal 'ErrorCode_OFF' string.
"""
if not items or not isinstance(items, list):
return "none"
@@ -133,13 +131,11 @@ def merge_options_field(cached, new_tokens):
x.com.samsung.da.options[]-style array the same way the device itself
merges them: match by prefix, replace if present, append if not.
Confirmed on real hardware (issue #54) that a write only needs to carry
the changed token(s), not the whole array -- see laundry.option_write /
oven._option_write for the write side. This is the read side of that
same fact: coordinator.async_send_command uses it to keep the
optimistic cache entry for the written href complete (every sibling
option still present) during the write-settle window, since the wire
body it applies straight to the cache no longer carries them."""
Confirmed on hardware (issue #54) that a write only needs to carry the
changed token(s), not the whole array -- see laundry.option_write /
oven._option_write for the write side. coordinator.async_send_command
uses this read-side counterpart to keep the optimistic cache entry
complete during the write-settle window."""
merged = list(cached or [])
for token in new_tokens or ():
if not isinstance(token, str) or "_" not in token:
@@ -157,18 +153,15 @@ def merge_options_field(cached, new_tokens):
def merge_items_field(cached, new_items):
"""Merge a partial x.com.samsung.da.items[]-style write (matched by
x.com.samsung.da.id) into a cached items array -- the read-side
counterpart of merge_options_field above, for the items[] shape instead
of the packed options[] shape.
x.com.samsung.da.id) into a cached items array -- the items[]
counterpart of merge_options_field above.
Confirmed on hardware that a write only needs to carry the array item
with the changed id plus the field(s) being changed; the device merges
the rest itself (same fact as the options[] case, different array --
see airconditioner._climate_write's vendor temperature write). Fields
Confirmed on hardware that a write only needs to carry the item with
the changed id plus the field(s) being changed (see
airconditioner._climate_write's vendor temperature write). Fields
within the matched item are merged, not replaced outright, so a
setpoint-only write doesn't wipe current/minimum/maximum/unit from the
optimistic cache entry for the settle window. An id with no match in
`cached` is appended."""
optimistic cache entry. An id with no match in `cached` is appended."""
merged = [dict(i) if isinstance(i, dict) else i for i in (cached or [])]
for new_item in new_items or ():
if not isinstance(new_item, dict):
@@ -184,22 +177,19 @@ def merge_items_field(cached, new_items):
# /wm/setinfo/vs/0 -- laundry-family firmware capability flags. Present on
# washers, dryers, and dishwashers; absent on fridge/oven/AC. Static for the
# life of a given board, so reading them from the /device/0 seed (no dedicated
# poll_tier) is enough.
# washers, dryers, and dishwashers; absent on fridge/oven/AC. Static for
# the life of a board, so reading it from the /device/0 seed is enough.
_SETINFO_HREF = "/wm/setinfo/vs/0"
_POWER_ON_OFF_FIELD = "x.com.samsung.da.isModelSettingPowerOnOff"
_WITHOUT_SC_FIELD = "x.com.samsung.da.isModelSettingWithoutSC"
def model_allows_power_on_off(resources: dict) -> bool:
"""True unless firmware explicitly declares remote power on/off unsupported.
`/wm/setinfo/vs/0`.`isModelSettingPowerOnOff` is `"false"` on many laundry
boards (washers/dryers): `/power/0` and `/power/vs/0` still report state,
but CoAP writes are ignored. Absent setinfo (non-laundry families) keeps
the writable switch -- current behavior.
"""
"""True unless firmware explicitly declares remote power on/off
unsupported. isModelSettingPowerOnOff is "false" on many laundry
boards: /power/0 and /power/vs/0 still report state, but CoAP writes
are ignored. Absent setinfo (non-laundry families) keeps the writable
switch."""
setinfo = resources.get(_SETINFO_HREF)
if setinfo is None:
return True
@@ -210,13 +200,11 @@ def model_allows_power_on_off(resources: dict) -> bool:
def model_setting_without_sc(resources: dict) -> bool:
"""True when firmware declares settings writable without Smart Control.
`/wm/setinfo/vs/0`.`isModelSettingWithoutSC` is `"true"` on washers/dryers
that accept temperature/spin/cycle-option writes while remote control is
off. Cycle start/pause/stop still need Smart Control on those boards --
the flag name is settings-specific, not a blanket remote-control bypass.
"""
"""True when firmware declares settings writable without Smart
Control. isModelSettingWithoutSC is "true" on washers/dryers that
accept temperature/spin/cycle-option writes while remote control is
off; cycle start/pause/stop still need Smart Control on those
boards."""
setinfo = resources.get(_SETINFO_HREF) or {}
return str(setinfo.get(_WITHOUT_SC_FIELD, "")).lower() == "true"
@@ -231,11 +219,10 @@ def _power_sensor_exists(rep, resources):
def sensor_item_value(items, sensor_type, index=0):
"""Pull one reading out of a `/sensors/vs/0`-style items[] list -- each
item is `{type, value: [...]}`; `index` picks which slot of a possibly
multi-value reading to read (index 0 is the raw measurement on every
family seen so far). Shared by range_hood.AIR_QUALITY,
air_purifier.AIR_QUALITY, and air_monitor.SENSORS, which all read the
same resource shape against the same {type, sensor_type} keys."""
item is `{type, value: [...]}`; `index` picks which slot to read
(index 0 is the raw measurement on every family seen so far). Shared
by range_hood.AIR_QUALITY, air_purifier.AIR_QUALITY, and
air_monitor.SENSORS, which all read the same resource shape."""
for item in items or ():
if not isinstance(item, dict):
continue
@@ -250,26 +237,18 @@ def sensor_item_value(items, sensor_type, index=0):
return None
# OCF-native / vendor '-vs' fallback pairs for power, kids-lock, remote control.
#
# These three controls exist as both a standard OCF resource (/power/0,
# oic.r.switch.binary, plain boolean 'value') and a Samsung vendor resource
# (/power/vs/0, x.com.samsung.da.power) -- Samsung advertises both as its
# firmware migrates onto the OCF standard model. Prefer the OCF-standard href
# when the device exposes it; the '-vs' href (a string-encoded duplicate for
# these three) binds only when the generic href is absent, via match_fn. Older
# firmware has only the '-vs' resource, so the pair is behaviour-identical to a
# lone '-vs' cap there. See the adding-device-support skill's "OCF-standard vs
# vendor" section for why this is preferred-non-vs-with-fallback, not a blanket
# choice. Every device registry lists both caps of each pair.
# OCF-native / vendor '-vs' fallback pairs for power, kids-lock, remote
# control: each exists as both a standard OCF resource (/power/0,
# oic.r.switch.binary, plain boolean 'value') and a Samsung vendor
# resource (/power/vs/0, x.com.samsung.da.power), since Samsung advertises
# both while its firmware migrates onto the OCF standard model. Prefer the
# OCF-standard href when present; the '-vs' href binds only when it's
# absent, via match_fn. Older firmware has only the '-vs' resource. See
# the adding-device-support skill's "OCF-standard vs vendor" section.
# Every device registry lists both caps of each pair.
POWER_GENERIC = Capability(
href="/power/0",
# Neither href of this pair carried a poll_tier before (issue #56's
# follow-up), so power state only ever refreshed on the once-per-30s
# summary poll instead of the subscribe/subpoll cadence 'warm' and 'hot'
# hrefs get -- the same "signal drives real-time state, but sat in the
# slow default tier" gap as REMOTE_CONTROL_GENERIC/VS_FALLBACK above.
poll_tier="warm",
entities=(
# Writable when firmware allows remote power; otherwise a read-only
@@ -319,16 +298,14 @@ POWER_VS_FALLBACK = Capability(
KIDS_LOCK_GENERIC = Capability(
href="/kidslock/0",
entities=(
# Read-only like KIDS_LOCK_VS_FALLBACK (issues #181/#183) -- not a
# SwitchDesc. SwitchDesc's `device_class='lock'` was never honored
# by HA (its switch platform only accepts 'outlet'/'switch'),
# leaving a plain switch whose 'On' state meant different things
# on different boards. As a BinarySensorDesc with `device_class='lock'`,
# both kids-lock surfaces read with the same polarity: 'On' means
# open/unlocked, per HA's lock device_class. The inversion in
# value_fn here (and in the fallback below) keeps the on-the-wire
# truth (value=False on /kidslock/0, kidsLock='Ready' on /kidslock/vs/0
# both mean kids lock NOT active) consistent with that polarity.
# Read-only like KIDS_LOCK_VS_FALLBACK (issues #181/#183): HA's
# switch platform never honored SwitchDesc's device_class='lock'
# ('outlet'/'switch' only), leaving a plain switch whose 'On' meant
# different things on different boards. As a BinarySensorDesc with
# device_class='lock', both surfaces read with the same polarity
# ('On' = open/unlocked, per HA convention); value_fn here inverts
# the wire value to match (value=False on /kidslock/0 means kids
# lock is NOT active).
BinarySensorDesc(
key="child_lock", field="value", device_class="lock", value_fn=lambda v: not bool(v)
),
@@ -339,16 +316,11 @@ KIDS_LOCK_VS_FALLBACK = Capability(
href="/kidslock/vs/0",
match_fn=lambda rep, resources: "/kidslock/0" not in resources,
entities=(
# Read-only, not a SwitchDesc (issues #181/#183): the write side of
# this capability wrote 'Enable', a value no dump in the fixture
# corpus has ever reported back -- every one reports either 'Ready'
# or 'Run', so it was never a confirmed contract. #181's reporter
# confirmed this directly: writing the *correct* value ('Run')
# still 4.05s, and the SmartThings app itself has no control for
# it either -- the resource is genuinely read-only on this
# hardware, not just wrong-valued. Polarity matches
# KIDS_LOCK_GENERIC above -- 'On' means open/unlocked, so
# kidsLock='Ready' (kids lock NOT active) renders as 'On'.
# Read-only, not a SwitchDesc (issues #181/#183): the old write
# side wrote 'Enable', a value no dump ever reports back (every one
# is 'Ready' or 'Run'), and #181's reporter confirmed writing the
# correct value ('Run') still 4.05s -- genuinely read-only on this
# hardware. Polarity matches KIDS_LOCK_GENERIC ('On' = unlocked).
BinarySensorDesc(
key="child_lock",
field="x.com.samsung.da.kidsLock",
@@ -361,15 +333,11 @@ KIDS_LOCK_VS_FALLBACK = Capability(
def remote_control_enabled(resources: dict) -> bool:
"""Single source of truth for the /remotectrl on/off signal, mirroring
REMOTE_CONTROL_GENERIC/_VS_FALLBACK's href/field pair and precedence
below. Used both to render the read-only Smart Control binary_sensor
(via those two descriptors) and, from coordinator.async_send_command,
to block writes outright when remote control is off. Both hrefs are
poll_tier='warm' below so that gate reads recent state (subscribed
when observe is live, subpolled every ~6s otherwise) rather than a
once-per-30s cold summary poll. True (assume enabled) when neither
href is present -- most device types don't report this capability
at all."""
REMOTE_CONTROL_GENERIC/_VS_FALLBACK's href/field precedence. Used both
to render the read-only Smart Control binary_sensor and, from
coordinator.async_send_command, to block writes when remote control is
off. True (assume enabled) when neither href is present -- most device
types don't report this capability at all."""
generic = resources.get("/remotectrl/0")
if generic is not None:
return bool(generic.get("value"))
@@ -434,26 +402,21 @@ ALARMS = Capability(
),
)
# instantaneousPower is a dead field on DA_WM_-class laundry dumps (washers and
# the issue #14 dryer) and on dishwashers too: the literal sentinel '-500',
# unchanged across off/idle/running. clamp_power floors it to a misleading
# "0 W" that reads as a real idle measurement. Gate power_watts out when the
# sentinel is seen -- but only then, so a device reporting a real value (e.g. a
# fridge's 93 W) still shows it (issue #6). cumulativePower is absent on at
# least one washer model; the exists_fn makes that explicit rather than relying
# on the generic field-presence gate.
# instantaneousPower is a dead field on DA_WM_-class laundry dumps and
# dishwashers: the literal sentinel '-500', unchanged across off/idle/
# running. clamp_power would floor it to a misleading "0 W". Gate
# power_watts out when the sentinel is seen, but only then, so a device
# reporting a real value (e.g. a fridge's 93 W) still shows it (issue #6).
_DEAD_INSTANTANEOUS_POWER = "-500"
ENERGY_METER = Capability(
href="/energy/consumption/vs/0",
entities=(
# `is_stub_rep(rep)` keeps the stub carve-out (see entity._is_included):
# an explicit exists_fn otherwise bypasses it, which would drop the
# entity when /device/0 returns a not-yet-fetched stub. A genuinely
# empty {} rep is NOT a stub -- it's the device's confirmed (if empty)
# answer, so it falls through to the normal field/sentinel checks like
# any populated rep. On a populated rep, hide power only for the dead
# sentinel or an absent field.
# is_stub_rep(rep) keeps the stub carve-out (see
# entity._is_included): an explicit exists_fn otherwise bypasses
# it and would drop the entity when /device/0 returns a
# not-yet-fetched stub. A genuinely empty {} rep is NOT a stub, so
# it still falls through to the normal field/sentinel checks.
SensorDesc(
key="power_watts",
field="x.com.samsung.da.instantaneousPower",
@@ -481,11 +444,7 @@ ENERGY_METER = Capability(
),
),
# cumulativeConsumption is a second, independently-varying running
# total alongside cumulativePower -- some fridges (issue #26) report
# both. Self-gates off where only cumulativePower is present. The
# `is_stub_rep(rep) or` keeps the same stub carve-out as power_watts/
# energy_kwh above -- without it, an exists_fn permanently drops the
# entity if setup happens to land on a not-yet-fetched stub.
# total some fridges (issue #26) report alongside cumulativePower.
SensorDesc(
key="power_energy_kwh",
field="x.com.samsung.da.cumulativeConsumption",
@@ -498,8 +457,8 @@ ENERGY_METER = Capability(
),
),
# AI Energy Mode's lifetime savings estimate vs. an unoptimized
# baseline -- present on some models (e.g. TP1X_REF_21K, issue #21/
# #27) and absent on others (issue #20/#26), unlike cumulativePower.
# baseline -- present on some models (issue #21/#27), absent on
# others (issue #20/#26).
SensorDesc(
key="energy_saved_kwh",
field="x.com.samsung.da.cumulativeSavedPower",
@@ -511,9 +470,8 @@ ENERGY_METER = Capability(
is_stub_rep(rep) or "x.com.samsung.da.cumulativeSavedPower" in rep
),
),
# Monthly billing-cycle totals -- the completed prior month and the
# in-progress current month. Not ever-increasing (each resets at
# month boundary), so no state_class.
# Monthly billing-cycle totals -- completed prior month and
# in-progress current month. Not ever-increasing, so no state_class.
SensorDesc(
key="energy_last_month_kwh",
field="x.com.samsung.da.monthlyConsumption",
@@ -574,26 +532,21 @@ WATER_FILTER = Capability(
),
)
# AI energy-saving level -- '0' is off, and supportedAiLevel lists the
# additional level(s) the device offers ('1' meaning just "on" on most
# hardware, but multi-level boards have been reported). Verified cross-family:
# fridge (issue #21) and washer (issue #40) both expose this href.
#
# supportedAiLevel is a single-entry list on most captured hardware, where a
# select would offer only one real choice against an implicit "off" -- shown
# as a switch instead. '0' itself is never in supportedAiLevel but has been
# observed live as the off value of aiLevel, so the select synthesizes it
# back in as an explicit option rather than leaving no way to turn off.
#
# No translation_key: aiLevel's values are plain digit strings, and
# select.py's _display() already renders an untranslated numeric string
# as-is -- there's nothing a catalog entry adds that's worth maintaining
# against an unknown, growing number of future levels.
# AI energy-saving level -- '0' is off, supportedAiLevel lists the
# additional level(s) offered ('1' meaning just "on" on most hardware,
# multi-level on some). Verified cross-family: fridge (issue #21) and
# washer (issue #40). Most hardware's supportedAiLevel is a single-entry
# list, so a select there would offer only one real choice against an
# implicit "off" -- shown as a switch instead; '0' is never in
# supportedAiLevel but is the observed off value, so the select
# synthesizes it back in as an explicit option. No translation_key:
# aiLevel's values are plain digit strings, and select.py already renders
# an untranslated numeric string as-is.
def _ai_energy_supported_levels(rep):
"""supportedAiLevel as a list -- a stray scalar (e.g. a string) must not
be len()-checked as if it were a list."""
"""supportedAiLevel as a list -- a stray scalar must not be
len()-checked as if it were one."""
sl = rep.get("supportedAiLevel")
return list(sl) if isinstance(sl, (list, tuple)) else []
@@ -618,21 +571,15 @@ AI_ENERGY_LEVEL = Capability(
poll_tier="cold",
entities=(
# No is_stub_rep carve-out on either side, unlike most exists_fn
# gates in this file -- entity creation only ever runs once, against
# whichever snapshot happens to be current the moment platforms are
# set up (see entity._is_included / __init__.py's
# async_config_entry_first_refresh-before-forward-entry-setups
# ordering), while flatten() re-evaluates exists_fn every poll
# against live data. Both descriptors share key='ai_energy_level',
# so if a stub carve-out let one of them win at setup time while the
# other wins once real data lands, flatten() would feed the
# instantiated entity a value shaped for the other platform (e.g. a
# bool into a Select). Requiring real, populated data on both sides
# keeps the entity-creation decision and the live-value decision in
# permanent agreement -- the cost is this entity doesn't appear
# until a reload if the device's very first poll stubs this
# cold-tier href, the same reload already required to fix which
# platform got picked in that case.
# gates in this file: entity creation runs once against whichever
# snapshot is current at platform setup, while flatten() re-checks
# exists_fn every poll against live data. Both descriptors share
# key='ai_energy_level' -- a stub carve-out could let one win at
# setup and the other win once real data lands, feeding the
# instantiated entity a value shaped for the other platform.
# Requiring populated data on both sides keeps the two decisions in
# permanent agreement, at the cost of the entity not appearing
# until a reload if the first poll stubs this cold-tier href.
SwitchDesc(
key="ai_energy_level",
field="aiLevel",
@@ -708,37 +655,27 @@ SELF_CHECK = Capability(
),
)
# ---------------------------------------------------------------------------
# Cross-family bundles, unpacked into every by_type registry's _build([...])
# call the same way ignored.IGNORED is (*common.UNIVERSAL / *common.POWER).
# discover() only binds a capability whose href is actually present in a
# given device's resource dump, so listing one here for a family that
# doesn't expose the href is a no-op, not a phantom entity -- see the
# adding-device-support skill's coverage-discipline section.
# call the same way ignored.IGNORED is. discover() only binds a capability
# whose href is actually present in a given device's dump, so listing one
# here for a family that doesn't expose the href is a no-op, not a phantom
# entity -- see the adding-device-support skill's coverage-discipline
# section.
#
# UNIVERSAL holds every capability with no known family that both (a) has
# the href and (b) needs to model it some other way -- broadening one of
# these to a new family is a safe, harmless guess (issue #40's AI energy
# level: 2 of 6 families confirmed, blanket-added everywhere else).
# UNIVERSAL holds every capability with no known family that both has the
# href and needs to model it some other way.
#
# POWER is kept separate -- airconditioner is the one family that opts out
# of it entirely. Canonical reason (see by_type/airconditioner.py and its
# test for pointers back here, not restatements): AC's climate entity
# already owns /power/0 and /power/vs/0 via bare, no-entity Capability
# objects (airconditioner.COVERAGE), and a second, real POWER_GENERIC/
# POWER_VS_FALLBACK cap on the same href would make _build() raise (a href
# with >1 cap must have every cap discriminated by rt_filter/match_fn, and
# the bare COVERAGE cap has neither). Kids-lock/remote-control don't have
# this conflict -- no AC dump has ever reported those hrefs -- so they stay
# in UNIVERSAL.
# POWER is kept separate: airconditioner opts out of it entirely, since
# its climate entity already owns /power/0 and /power/vs/0 via bare
# no-entity Capability objects (airconditioner.COVERAGE), and a second
# real cap on the same href would make _build() raise (see
# by_type/airconditioner.py). Kids-lock/remote-control have no such
# conflict, so they stay in UNIVERSAL.
#
# Airconditioner also partially opts out of UNIVERSAL itself, not just
# POWER: issue #193 needs ENERGY_METER's cumulativePower scale to differ by
# board generation, so by_type/airconditioner.py excludes just that one
# member (`*[c for c in common.UNIVERSAL if c is not common.ENERGY_METER]`)
# and substitutes airconditioner.ENERGY_METER_GENERIC/ENERGY_METER_LEGACY in
# its place -- every other registry still unpacks UNIVERSAL wholesale.
# ---------------------------------------------------------------------------
# Airconditioner also partially opts out of UNIVERSAL itself: issue #193
# needs ENERGY_METER's cumulativePower scale to differ by board
# generation, so by_type/airconditioner.py excludes just that one member
# and substitutes its own ENERGY_METER_GENERIC/ENERGY_METER_LEGACY.
UNIVERSAL = (
ALARMS,
@@ -15,8 +15,8 @@ from .common import int_or_none
def _first_mode(rep):
"""Representative scalar for the operating-mode select. `modes` is a
single-element list on every dump seen so far, mirroring
airconditioner._first_mode's handling of the same field shape."""
single-element list on every dump seen, mirroring
airconditioner._first_mode."""
modes = rep.get("x.com.samsung.da.modes")
if isinstance(modes, (list, tuple)):
return modes[0] if modes else None
@@ -40,14 +40,11 @@ MODE = Capability(
),
)
# Target humidity is this device's primary control (the issue-#88 dump's
# equivalent of a thermostat setpoint). No min/max range field is present in
# any dump seen so far -- native_min/native_max are deliberately left unset
# so the number entity falls back to HA's own 0-100 default, the natural
# bound for a percentage field, rather than a bound guessed from one unit's
# spec sheet (see the adding-device-support skill's "never hard-code the one
# dump's values" section). Step comes live from the device's own `increment`
# field.
# Target humidity is this device's primary control (issue #88's equivalent
# of a thermostat setpoint). No min/max range field is present in any dump
# seen, so native_min/native_max are left unset, falling back to HA's own
# 0-100 default rather than a bound guessed from one unit's spec sheet.
# Step comes live from the device's own `increment` field.
HUMIDITY = Capability(
href="/humidity/vs/0",
poll_tier="warm",
@@ -77,15 +74,13 @@ HUMIDITY = Capability(
),
)
# Water-tank ambient light (issues #271/#231, TP1X_DA_AC_DHM_01001_0000):
# on/off, color, and brightness are three independent controls on this one
# resource. `waterfullAlarmStatus` differs between the two dumps that
# reported this href (On vs. Off) so it's a real live flag, not a constant --
# but its exact meaning (tank actually full vs. the chime feature merely
# enabled) isn't confirmed by either dump alone, and /alarms/vs/0's
# alarm_code already surfaces a live WaterTankFull condition when one fires
# (see common._active_alarm_codes), so this is exposed read-only as a plain
# diagnostic value rather than guessed at as a binary_sensor.
# Water-tank ambient light (issues #271/#231): on/off, color, and
# brightness are three independent controls on this one resource.
# `waterfullAlarmStatus` differs between the two dumps that reported this
# href, so it's a real live flag, but its exact meaning (tank full vs. the
# chime feature merely enabled) isn't confirmed, and /alarms/vs/0 already
# surfaces a live WaterTankFull condition -- exposed read-only as a plain
# diagnostic rather than guessed at as a binary_sensor.
WATERTANK_LIGHTING = Capability(
href="/watertank/lighting/vs/0",
poll_tier="cold",
@@ -131,13 +126,10 @@ WATERTANK_LIGHTING = Capability(
),
)
# ---------------------------------------------------------------------------
# Dehumidifier-scoped coverage: vendor plumbing with no user-actionable state
# or no documented write contract, following the same 'don't guess' rule as
# airconditioner._AC_IGNORED (this is the same DA_AC_ board family). Not in
# the global ignored.IGNORED since some of these hrefs collide with other
# families' schemas.
# ---------------------------------------------------------------------------
# Dehumidifier-scoped coverage: vendor plumbing with no user-actionable
# state, following the same rule as airconditioner._AC_IGNORED (same
# DA_AC_ board family). Not in the global ignored.IGNORED since some hrefs
# collide with other families' schemas.
_DHM_IGNORED = [
"/availablecontrolsets/vs/0", # opaque hex-encoded control-set bitmap (id: DHM)
"/da/softreset/vs/0", # soft-reset trigger plumbing
@@ -41,26 +41,16 @@ DISHWASHER_SETTINGS = Capability(
),
)
# ---------------------------------------------------------------------------
# /course/vs/0 — cycle selection (shared laundry.cycle_select) plus the
# dishwasher-only StormWashZone / AutoDoorRelease toggles that ride in the
# same options array (shared laundry.bool_option_switch, same options[]
# boolean-toggle contract washer's bubble-soak/pre-wash/intensive switches
# use). Course display names live in translations under
# entity.select.dishwasher_cycle (see laundry.cycle_select).
# /course/vs/0 -- cycle selection (shared laundry.cycle_select) plus the
# dishwasher-only StormWashZone / AutoDoorRelease toggles riding in the same
# options array (shared laundry.bool_option_switch). Course display names
# live in translations under entity.select.dishwasher_cycle.
#
# '83'/'86' were transposed in that catalog until issue #226: both the
# original DW9000F-class fixture this table was built from and the issue
# #226 reporter's board report the identical DeviceType_0812 (a real
# per-board-generation id also seen on unrelated washer/dryer fixtures, so
# this is one shared course table, not a Table_02/Table_03-style generation
# split), and the original fixture's own live editCourseList
# ('EditCourseList_0E07908683848D808E8F') puts '86' and '83' back to back at
# positions 4-5 -- exactly the kind of adjacent pair a manual screenshot
# transcription slips on. The reporter's live confirmation (selecting
# 'Normal' ran the physical Express 60 program and vice versa) settles
# which way: '86' is Express 60, '83' is Normal.
# ---------------------------------------------------------------------------
# '83'/'86' were transposed in that catalog until issue #226: the original
# fixture's own live editCourseList puts them back to back, exactly the
# kind of adjacent pair a manual screenshot transcription slips on. The
# reporter's live confirmation (selecting 'Normal' ran the physical Express
# 60 program and vice versa) settled it: '86' is Express 60, '83' is Normal.
CYCLE_OPTIONS = Capability(
href="/course/vs/0",
@@ -38,27 +38,19 @@ DRYER_SETTINGS = Capability(
)
# /course/vs/0 -- cycle selection, shared with washer/dishwasher via
# laundry.cycle_select (options read live from /wm/editcourse/vs/0, written as
# an RMW on the options array). Course display names live in translations
# under entity.select.dryer_cycle (Table_03, DV5000-class, captured
# 2026-05-29). Codes '01' Normal and '06' Time dry were confirmed on a
# DVE50A8600V/A3 (also Table_03) by selecting each cycle on the physical
# appliance and reading back the raw code from the entity's state (issue
# #80). Codes '51' Eco Cotton, '53' AI Dry+, and '4e' Self Dry were
# confirmed the same way on a DV90DG6845LHU5 (issue #244). The
# /st/dryercourse/vs/0 resource re-encodes the same selected course and is
# ignored (ignored.py) -- the mirror of how /st/washercourse/vs/0 is ignored
# for washers.
# laundry.cycle_select. Course display names live in translations under
# entity.select.dryer_cycle (Table_03, DV5000-class). Codes '01' Normal and
# '06' Time dry were confirmed on a DVE50A8600V/A3 by selecting each cycle
# on the appliance and reading back the raw code (issue #80); '51' Eco
# Cotton, '53' AI Dry+, and '4e' Self Dry the same way on a DV90DG6845LHU5
# (issue #244). /st/dryercourse/vs/0 re-encodes the same selected course
# and is ignored (ignored.py), mirroring /st/washercourse/vs/0 for washers.
#
# Drum Clean+ maintenance tracking (issue #258) reuses washer.py's
# DrumCleanProposal_/WashingTimes_/DrumCleanLog_ tokens on this same
# options[] array -- see laundry.drum_clean_cycles_remaining/
# drum_clean_last_cleaned's docstrings for the field contract, including
# the dryer-specific '|'-joined multi-entry DrumCleanLog_ shape. No
# separate heat-exchanger-clean tracking was found on either dump #258
# supplied (DV90BB7445GES7, DV91T6440LE/SA) -- no HeatExchanger*-prefixed
# token, nor any other options[] entry that looks like a second maintenance
# counter -- so if the Samsung app surfaces that reminder for these units,
# drum_clean_last_cleaned. No separate heat-exchanger-clean tracking was
# found on either dump #258 supplied, so if the app surfaces that reminder,
# it isn't computed from anything this integration can read locally.
DRYER_COURSE = Capability(
href="/course/vs/0",
@@ -9,11 +9,10 @@ vocabulary with the room-AC family in airconditioner.py beyond the DA_AC_
board prefix -- EHS reports its own /mode/*/vs/0 and /temperatures/*/vs/0
shapes, not airconditioner.py's HREF_MODE/HREF_TEMP* OCF-pattern hrefs.
zone1 has no HA platform with matching semantics (it's a leaving-water-
temperature setpoint, not a thermostat with HVAC modes airconditioner.py's
climate.py would fit), so it stays switch/select/number/sensor -- same shape
as dehumidifier.py's power/mode/humidity split. dhw is a real HA
water_heater.py -- see DHW below and water_heater.py's module docstring --
zone1 has no HA platform with matching semantics (a leaving-water-
temperature setpoint, not a thermostat with HVAC modes), so it stays
switch/select/number/sensor -- same shape as dehumidifier.py's power/mode/
humidity split. dhw is a real HA water_heater.py entity (see DHW below),
following the same primary-resource-plus-sibling-reads pattern as
airconditioner.py's CLIMATE/climate.py.
@@ -35,8 +34,7 @@ def _num(v):
def _first_mode(rep):
"""Representative scalar for a mode select -- `modes` is a single-element
list on every dump seen so far, mirroring airconditioner._first_mode /
dehumidifier._first_mode's handling of the same field shape."""
list on every dump seen, mirroring airconditioner._first_mode."""
modes = rep.get("x.com.samsung.da.modes")
if isinstance(modes, (list, tuple)):
return modes[0] if modes else None
@@ -48,14 +46,9 @@ def _temp_unit(rep):
def _bounds(rep, default_min, default_max):
"""The resource's own (minimum, maximum) pair, or the defaults.
Both ends together or neither -- a board reporting only one would
otherwise pair a real device bound with an invented default, which
looks plausible and is silently wrong. Same rule as
climate._range()/water_heater._range(), and the same reason
oven._setpoint_bounds resolves its pair in one place.
"""
"""The resource's own (minimum, maximum) pair, or the defaults. Both
ends together or neither -- a board reporting only one would otherwise
pair a real bound with an invented default, silently wrong."""
lo = _num(rep.get("x.com.samsung.da.minimum"))
hi = _num(rep.get("x.com.samsung.da.maximum"))
return (lo, hi) if (lo is not None and hi is not None) else (default_min, default_max)
@@ -102,8 +95,8 @@ ZONE_MODE = Capability(
)
# type=Water/unit=Celsius on this dump names the space-heating loop's flow/
# room setpoint, not a literal water temperature -- Samsung EHS zone control
# is leaving-water-temperature-based, same convention as the dhw loop below.
# room setpoint, not a literal water temperature -- EHS zone control is
# leaving-water-temperature-based, same convention as the dhw loop below.
ZONE_TEMPERATURE = Capability(
href="/temperatures/indoor/vs/0",
poll_tier="warm",
@@ -134,12 +127,10 @@ ZONE_TEMPERATURE = Capability(
),
)
# Canonical dhw resource hrefs. water_heater.py binds the primary HREF_DHW_MODE
# via DHW below and reads the sibling power/temperature hrefs off the
# coordinator snapshot -- same primary-plus-siblings shape as
# airconditioner.py's HREF_MODE/CLIMATE_CONSUMED_HREFS. Declared once here
# and imported by water_heater.py, so a new sibling read can't drift out of
# sync with its DHW_CONSUMED_HREFS coverage entry below.
# Canonical dhw resource hrefs. water_heater.py binds HREF_DHW_MODE via DHW
# below and reads the sibling power/temperature hrefs off the coordinator
# snapshot -- same primary-plus-siblings shape as airconditioner.py's
# HREF_MODE/CLIMATE_CONSUMED_HREFS.
HREF_DHW_POWER = "/power/dhw/vs/0" # on/off
HREF_DHW_MODE = "/mode/dhw/vs/0" # primary (bound by DHW) -- current_operation
HREF_DHW_TEMPERATURE = "/temperatures/dhw/vs/0" # current/target temperature
@@ -150,8 +141,7 @@ DHW_CONSUMED_HREFS = [HREF_DHW_POWER, HREF_DHW_TEMPERATURE]
def _dhw_write(payload, rep, href=None):
"""Map a (kind, value) command from the water_heater platform to the
(path_segs, body) for that one sub-write -- same contract as
airconditioner._climate_write, just across the dhw loop's three
resources instead of the AC's power/mode/temperature/wind set."""
airconditioner._climate_write, across the dhw loop's three resources."""
kind, value = payload
if kind == "power":
return (["power", "dhw", "vs", "0"], {"x.com.samsung.da.power": "On" if value else "Off"})
@@ -174,19 +164,15 @@ DHW = Capability(
# Power and temperature are read by the composite DHW entity above, not
# given their own entities -- coverage-only caps so discover() reports no
# gap (see airconditioner.py's CLIMATE_CONSUMED_HREFS for the same pattern).
# gap (see airconditioner.py's CLIMATE_CONSUMED_HREFS).
DHW_CONSUMED = [Capability(href=h, poll_tier="warm") for h in DHW_CONSUMED_HREFS]
# Deliberately a plain config switch, not water_heater's AWAY_MODE feature.
# HA core's smartthings water_heater does wire this same Samsung capability
# (CUSTOM_OUTING_MODE) up to WaterHeaterEntityFeature.AWAY_MODE, and the DHW
# operation-mode map above is taken from that integration -- so the
# divergence is worth stating. /option/outgoing/vs/0 is device-wide: one
# `away` flag covering the whole unit, zone1 included (it has no dhw-scoped
# sibling href, unlike every other resource in this loop). Hanging it off
# the DHW card would present a device-wide setting as if it only affected
# hot water. It stays a switch until a board turns up with a per-loop away
# resource to bind instead.
# HA core's smartthings integration wires this same Samsung capability up
# to WaterHeaterEntityFeature.AWAY_MODE, so the divergence is worth
# stating: /option/outgoing/vs/0 is device-wide (one `away` flag covering
# zone1 too, with no dhw-scoped sibling href). Hanging it off the DHW card
# would present a device-wide setting as hot-water-only.
AWAY_MODE = Capability(
href="/option/outgoing/vs/0",
poll_tier="cold",
@@ -205,13 +191,9 @@ AWAY_MODE = Capability(
),
)
# ---------------------------------------------------------------------------
# EHS-scoped coverage: opaque vendor plumbing (hex-encoded factory/cycle/
# schedule blobs) or resources with no confirmed write contract on this
# dump, following the same 'don't guess' rule as dehumidifier._DHM_IGNORED.
# Not in the global ignored.IGNORED since these are EHS-only shapes that
# would need their own verification on other device families.
# ---------------------------------------------------------------------------
# EHS-scoped coverage: opaque vendor plumbing or resources with no
# confirmed write contract on this dump. Not in the global ignored.IGNORED
# since these are EHS-only shapes needing their own verification elsewhere.
_EHS_IGNORED = [
"/availablecontrolsets/vs/0", # opaque hex-encoded control-set bitmap (id: EHS)
"/da/softreset/vs/0", # soft-reset trigger plumbing
@@ -3,17 +3,15 @@
Resources verified against the dump at local-tools/dumps/10.0.0.254.json.
Temperature unit is read live from each resource, not assumed: the RF9000B
dump reports Fahrenheit ("units": "F" / "x.com.samsung.da.unit": "Fahrenheit"),
but a TP1X_REF_21K dump (issue #7) reports the same fields in Celsius for the
exact same resources — the device tells you which one it is, it's just never
been read before. See `_temp_unit`/`_temp_item_unit` below. Setpoints are
NumberDesc with direct-write write_fn — generic caps derive the CoAP PUT path
from href at write time.
dump reports Fahrenheit, but a TP1X_REF_21K dump (issue #7) reports the same
fields in Celsius for the exact same resources -- the device tells you which
one it is. See `_temp_unit`/`_temp_item_unit` below.
Multi-instance note: the two door resources (/door/cooler/0 and
/door/freezer/0) and the two ice-maker resources (/icemaker/one/vs/0 and
/icemaker/two/vs/0) use named path segments, so they are modelled via
pattern capabilities that auto-derive distinct entity keys from href segments.
Multi-instance note: the two door resources (/door/cooler/0,
/door/freezer/0) and the two ice-maker resources (/icemaker/one/vs/0,
/icemaker/two/vs/0) use named path segments, so they are modeled via
pattern capabilities that auto-derive distinct entity keys from href
segments.
"""
import datetime
@@ -27,13 +25,11 @@ from ..entities import (
SwitchDesc,
TimeDesc,
)
from .common import normalize_temp_unit
from .common import int_or_none, normalize_temp_unit
# Display names for the beverage zone, flex zone, ice type, and
# ice-making-status enums below live in translations/en.json,
# keyed by the lowercased raw device value — select.py and SensorDesc.options
# normalize to lowercase for HA's translation lookup and map back to this
# original casing before writing to the device.
# ice-making-status enums below live in translations/en.json, keyed by the
# lowercased raw device value.
def _int(v):
@@ -44,14 +40,13 @@ def _int(v):
def _temp_unit(rep):
"""'units': 'C'/'F' (or 'Celsius'/'Fahrenheit') -> '°C'/'°F'. Defaults to
°F (this module's original assumption) if the device omits the field."""
"""'units': 'C'/'F' (or 'Celsius'/'Fahrenheit') -> '°C'/'°F'. Defaults
to °F if the device omits the field."""
return normalize_temp_unit(rep.get("units"))
# ---------------------------------------------------------------------------
# Temperature (generic — covers /temperature/current/* and /temperature/desired/*)
# ---------------------------------------------------------------------------
# Temperature (generic -- covers /temperature/current/* and
# /temperature/desired/*)
TEMP_CURRENT_GENERIC = Capability(
href=None,
@@ -74,14 +69,10 @@ TEMP_CURRENT_GENERIC = Capability(
def _temp_setpoint_write(p, rep, href=None, resources=None):
"""Write temperature — prefer vendor /temperatures/vs/0 when available,
fall back to direct OCF /temperature/desired/ write otherwise.
Samsung fridges expose both OCF-standard /temperature/desired/* and vendor
/temperatures/vs/0. On some models only the vendor path commits the change;
on others both work. Using the vendor path when present is always correct.
Item IDs follow the Samsung convention: "0" = Freezer, "1" = Fridge/Cooler.
"""
"""Prefer vendor /temperatures/vs/0 when present, else the direct OCF
/temperature/desired/ write -- on some models only the vendor path
commits. Item IDs follow the Samsung convention: "0" = Freezer,
"1" = Fridge/Cooler."""
if not href:
return None
if resources and "/temperatures/vs/0" in resources:
@@ -127,18 +118,12 @@ TEMP_SETPOINT = Capability(
),
)
# ---------------------------------------------------------------------------
# Discrete cooler setpoint (issue #186) -- some single-door ("cooler only")
# fridges report no /temperature/current|desired/* pair at all (this href
# doesn't match TEMP_CURRENT_GENERIC/TEMP_SETPOINT's '/temperature/current/'
# or '/temperature/desired/' prefixes), only this one vendor resource that
# bundles the live desired value together with the *specific* values the
# unit accepts. That supportedList (e.g. ['1','2','3','4','7'] on the issue
# #186 dump) is not a contiguous range -- 5 and 6 genuinely aren't valid
# setpoints on this model -- so a NumberDesc with a min/max/step would let a
# user pick an unsupported value; modeled as a select reading its own live
# options list instead, same shape as BEVERAGE_ZONE/PANTRY_ZONE above.
# ---------------------------------------------------------------------------
# Discrete cooler setpoint (issue #186): single-door "cooler only" fridges
# report no /temperature/current|desired/* pair, only this vendor resource
# bundling the live desired value with the specific values the unit
# accepts. supportedList (e.g. ['1','2','3','4','7']) is not a contiguous
# range, so this is a select reading its own live options rather than a
# NumberDesc with min/max/step.
def _definite_cooler_write(p, rep, href=None):
@@ -171,11 +156,8 @@ def _definite_freezer_write(p, rep, href=None):
)
# Freezer half of the same discrete-setpoint pattern (issue #229): a
# fridge/freezer combo reporting no /temperature/current|desired/freezer
# pair, only this bundled vendor resource -- identical shape to
# DEFINITE_TEMPERATURE_COOLER above (down to the field names), just negative
# supportedList values (e.g. ['-23','-21','-19','-17','-15']).
# Freezer half of the same discrete-setpoint pattern (issue #229) -- same
# shape as DEFINITE_TEMPERATURE_COOLER, negative supportedList values.
DEFINITE_TEMPERATURE_FREEZER = Capability(
href="/temperature/definite/freezer/vs/0",
poll_tier="warm",
@@ -191,10 +173,6 @@ DEFINITE_TEMPERATURE_FREEZER = Capability(
),
)
# ---------------------------------------------------------------------------
# Icemaker nighttime quiet mode
# ---------------------------------------------------------------------------
ICEMAKER_NIGHTTIME = Capability(
href="/icemaker/nighttime/vs/0",
poll_tier="warm",
@@ -213,18 +191,13 @@ ICEMAKER_NIGHTTIME = Capability(
),
)
# ---------------------------------------------------------------------------
# Icemaker (generic — covers /icemaker/one/vs/0, /icemaker/two/vs/0)
# /icemaker/status/vs/0 is kept as exact-href cap and binds first.
# Icemaker (generic -- covers /icemaker/one/vs/0, /icemaker/two/vs/0).
# /icemaker/status/vs/0 is an exact-href cap and binds first;
# /icemaker/nighttime/vs/0 is excluded by match_fn (lacks iceMaker.state).
#
# Entity names interpolate x.com.samsung.da.iceMaker.name ("CUBED_ICE",
# "ICE_BITES") -- read via name_field, reaching the translated name as the
# {instance_name} placeholder -- not the href's "one"/"two" segment. These two
# ice makers are independent on/off toggles that can both be enabled at once
# (issue #27), so they stay separate entities rather than a single ice-type
# select, but users still want them labeled with the device's own names.
# ---------------------------------------------------------------------------
# "ICE_BITES") via name_field, not the href's "one"/"two" segment -- these
# two makers can both be enabled at once (issue #27), so they stay
# separate entities rather than one ice-type select.
def _icemaker_write(field):
@@ -273,10 +246,6 @@ ICEMAKER_GENERIC = Capability(
),
)
# ---------------------------------------------------------------------------
# Door alert tone
# ---------------------------------------------------------------------------
DOOR_ALERT = Capability(
href="/settings/sound/alert/door/vs/0",
poll_tier="warm",
@@ -296,9 +265,38 @@ DOOR_ALERT = Capability(
),
)
# ---------------------------------------------------------------------------
# Status/lock — auto door opener and fridge sound
# ---------------------------------------------------------------------------
# Internal deodorizing filter (issue #318, TP1X_REF_21K). Same
# filterUsage/filterStatus field pair as common.WATER_FILTER, but
# filterUsage here is already a 0-100 percentage with no filterCapacity to
# divide by (confirmed by filterStatus=="wash" at filterUsage=="100") --
# 'air_'-prefixed keys so a fridge with both a water and an air filter gets
# two distinct entities rather than a unique_id collision.
AIR_FILTER = Capability(
href="/filter/airdustfilter/vs/0",
poll_tier="cold",
entities=(
SensorDesc(
key="air_filter_usage",
field="x.com.samsung.da.filterUsage",
unit="%",
state_class="measurement",
icon="mdi:air-filter",
entity_category="diagnostic",
value_fn=int_or_none,
),
SensorDesc(
key="air_filter_status",
field="x.com.samsung.da.filterStatus",
device_class="enum",
options=("normal", "wash", "replace"),
translation_key="filter_status",
icon="mdi:air-filter",
entity_category="diagnostic",
value_fn=lambda v: v.lower() if isinstance(v, str) else v,
),
),
)
def _status_lock_write(field):
@@ -331,18 +329,11 @@ STATUS_LOCK = Capability(
),
)
# ---------------------------------------------------------------------------
# Defrost delay / active-defrost status
#
# /defrost/delay/vs/0 is the writable toggle to postpone a scheduled
# defrost. /defrost/block/vs/0 is an unrelated, independently-varying
# status: despite its "block" naming (originally assumed to mean "defrost
# is being withheld"), live dumps confirm DEFROST_BLOCK_ON means the
# defrost cycle is *actively running* right now, seen with defrost_delay
# off -- i.e. "block" refers to the evaporator/coil block being defrosted,
# not a blocking/prevention state. Exposed as a read-only diagnostic
# binary sensor.
# ---------------------------------------------------------------------------
# defrost. /defrost/block/vs/0 is unrelated: despite the "block" naming,
# live dumps confirm DEFROST_BLOCK_ON means the defrost cycle is actively
# running right now (seen with defrost_delay off) -- "block" refers to the
# evaporator/coil block being defrosted, not a prevention state.
DEFROST_DELAY = Capability(
href="/defrost/delay/vs/0",
@@ -362,10 +353,9 @@ DEFROST_DELAY = Capability(
),
)
# OCF-native boolean mirror of DEFROST_DELAY. The captured TP1X_REF_21K
# firmware publishes the same state on both hrefs, but only the vendor resource
# above has a confirmed write contract. Bind the native mirror without another
# entity so discovery records it as an intentional duplicate.
# OCF-native boolean mirror of DEFROST_DELAY -- only the vendor resource
# above has a confirmed write contract, so bind this without another
# entity to record it as an intentional duplicate.
DEFROST_DELAY_NATIVE_DUPLICATE = Capability(
href="/defrost/delay/0",
)
@@ -384,10 +374,6 @@ DEFROST_BLOCK_STATUS = Capability(
),
)
# ---------------------------------------------------------------------------
# Refrigeration modes (rapid cooling)
# ---------------------------------------------------------------------------
def _refrigeration_write(field_name):
def _write(p, rep, href=None):
@@ -421,10 +407,6 @@ REFRIGERATION = Capability(
),
)
# ---------------------------------------------------------------------------
# Autofill
# ---------------------------------------------------------------------------
def _autofill_write(p, rep, href=None):
if p not in ("On", "Off"):
@@ -447,10 +429,6 @@ AUTOFILL = Capability(
),
)
# ---------------------------------------------------------------------------
# Welcome lighting (proximity-triggered cabinet light)
# ---------------------------------------------------------------------------
WELCOME_LIGHTING = Capability(
href="/proximity/vs/0",
poll_tier="warm",
@@ -469,14 +447,11 @@ WELCOME_LIGHTING = Capability(
),
)
# ---------------------------------------------------------------------------
# Enhanced cabinet light — nighttime lighting schedule
#
# night.starttime is an ISO datetime; only the time portion is meaningful.
# night.duration.minute encodes the window length. End time is derived so
# both time entities write back to the same resource without stepping on each
# other: writing start preserves duration; writing end recalculates duration.
# ---------------------------------------------------------------------------
# Enhanced cabinet light nighttime schedule: night.starttime is an ISO
# datetime (only the time portion matters), night.duration.minute is the
# window length. End time is derived so both time entities write back to
# the same resource without stepping on each other: writing start
# preserves duration; writing end recalculates it.
_NIGHT_BRIGHTNESS_OPTIONS = ("33", "66", "100")
@@ -600,10 +575,6 @@ CABINET_LIGHT_ENHANCED = Capability(
),
)
# ---------------------------------------------------------------------------
# Cabinet light
# ---------------------------------------------------------------------------
def _cabinet_light_write(p, rep, href=None):
if p not in ("On", "Off"):
@@ -638,10 +609,6 @@ CABINET_LIGHT = Capability(
),
)
# ---------------------------------------------------------------------------
# Sabbath mode
# ---------------------------------------------------------------------------
def _sabbath_write(p, rep, href=None):
if p not in ("On", "Off"):
@@ -664,10 +631,6 @@ SABBATH = Capability(
),
)
# ---------------------------------------------------------------------------
# Beverage zone
# ---------------------------------------------------------------------------
def _bzone_write(p, rep, href=None):
return ["specialzone", "one", "vs", "0"], {"roomDesiredMode": p}
@@ -689,16 +652,11 @@ BEVERAGE_ZONE = Capability(
),
)
# ---------------------------------------------------------------------------
# Pantry / Cool Select Zone -- a convertible compartment toggled between
# wine/deli/drinks temperature presets (issue #20). Same shape as
# BEVERAGE_ZONE (a controllable named sub-zone with a mode + supported-modes
# list) but a distinct resource/field set -- x.com.samsung.da.mode /
# x.com.samsung.da.supportedOptions on /status/pantry/one/vs/0, rather than
# roomDesiredMode/roomSupportedModes on /specialzone/one/vs/0. Only a "one"
# instance has been seen; not generalized to a pattern cap until a second
# instance turns up.
# ---------------------------------------------------------------------------
# wine/deli/drinks presets (issue #20). Same shape as BEVERAGE_ZONE but a
# distinct field set (x.com.samsung.da.mode/supportedOptions vs
# roomDesiredMode/roomSupportedModes). Only a "one" instance seen; not
# generalized to a pattern cap until a second instance turns up.
def _pantry_write(p, rep, href=None):
@@ -721,18 +679,13 @@ PANTRY_ZONE = Capability(
),
)
# ---------------------------------------------------------------------------
# Flex zone (convertible drawer — /mode/vs/0 on RF9000-class fridges)
#
# x.com.samsung.da.modes holds multiple orthogonal flags in one list; the
# flex-zone entry is whichever item is also a member of supportedOptions --
# the other flags (WATERFILTER_*, DEFROST_BLOCK_*, the CVN_*_ZONE marker)
# never appear there. The prefix on that item varies by fridge family
# (CV_TTYPE_RF9000A_ on RF9000-class, CV_FDR_ on Bespoke-class -- issue #27 /
# #26, where the old CV_TTYPE_RF9000A_-only match left this entity bound but
# stuck on None), so match by list membership instead of a hardcoded prefix.
# Write replaces only that item; other flags are preserved.
# ---------------------------------------------------------------------------
# Flex zone (convertible drawer -- /mode/vs/0 on RF9000-class fridges):
# x.com.samsung.da.modes holds several orthogonal flags in one list; the
# flex-zone entry is whichever item also appears in supportedOptions (the
# other flags, WATERFILTER_*/DEFROST_BLOCK_*/CVN_*_ZONE, never do). The
# prefix on that item varies by family (CV_TTYPE_RF9000A_ vs CV_FDR_ on
# Bespoke, issues #27/#26), so match by list membership instead of a
# hardcoded prefix. Write replaces only that item.
def _flex_zone_supported(rep):
@@ -740,10 +693,9 @@ def _flex_zone_supported(rep):
def _flex_zone_current(rep):
# Every dump seen has at most one modes/supportedOptions overlap, so
# "first match" and "strip all matches" (in the write below) agree. If a
# future device ever reports two, this reads the first and the write
# would drop both -- revisit if that turns up.
# Every dump seen has at most one modes/supportedOptions overlap; a
# future device reporting two would read the first and the write below
# would drop both.
modes = rep.get("x.com.samsung.da.modes") or []
supported = _flex_zone_supported(rep)
return next((m for m in modes if m in supported), None)
@@ -767,15 +719,11 @@ FLEX_ZONE = Capability(
entity_category="config",
options_field="x.com.samsung.da.supportedOptions",
# A nonempty supportedOptions alone isn't sufficient: the
# kimchi-refrigerator family (issue #26) also populates
# /mode/vs/0's modes/supportedOptions with real data, but
# its tokens carry a "_[n]:[n]" parameter suffix on
# supportedOptions that modes never repeats, so no item
# ever overlaps -- the RF9000/Bespoke-class overlap this
# capability was built for never happens there. Require an
# actual resolvable value instead of just a populated
# list, so this stays absent on that family rather than
# showing a select permanently stuck on "unknown".
# kimchi-refrigerator family (issue #26) also populates both
# fields, but its tokens carry a "_[n]:[n]" suffix on
# supportedOptions that modes never repeats, so nothing ever
# overlaps there. Require an actual resolvable value so this
# stays absent on that family instead of stuck on "unknown".
exists_fn=lambda rep, resources: _flex_zone_current(rep) is not None,
rep_fn=_flex_zone_current,
write_fn=_flex_zone_write,
@@ -783,18 +731,13 @@ FLEX_ZONE = Capability(
),
)
# ---------------------------------------------------------------------------
# Generic door pattern capability (href=None — use as pattern_cap only)
# ---------------------------------------------------------------------------
# Generic door pattern capability (href=None -- use as pattern_cap only)
def _door_open_state(rep):
"""Most /door/* resources report bare `openState`, but the
ARTIK051_DONGLE_REF family's /door/onedoorfreezer/vs/0 (issues #77, #83)
reports the vendor-prefixed `x.com.samsung.da.openState` instead. This
capability still binds either way (href_prefix match doesn't care about
field names), but a plain `field=` lookup against the wrong key means
the entity exists and is permanently unavailable -- check both."""
ARTIK051_DONGLE_REF family's /door/onedoorfreezer/vs/0 (issues #77,
#83) reports `x.com.samsung.da.openState` instead -- check both."""
v = rep.get("openState")
if v is None:
v = rep.get("x.com.samsung.da.openState")
@@ -816,45 +759,27 @@ DOOR_GENERIC = Capability(
),
)
# ---------------------------------------------------------------------------
# Kimchi refrigerator compartments (TP2X_REF_20K-class 3-compartment kimchi
# units, issue #26) -- top/middle/bottom each report their own storage mode
# plus a ripening status/timer on /status/kimchi/<slot>/vs/0, all three in
# an identical shape; modeled as a pattern capability the same way
# DOOR_GENERIC/TEMP_CURRENT_GENERIC above are, deriving the per-compartment
# key and {instance_name} from the href's top/middle/bottom segment. Only
# the top compartment's door has been seen reported separately (kimchidoors);
# middle/bottom apparently have no contact switch of their own, so that's
# its own narrower pattern cap rather than assumed universal.
# Kimchi refrigerator compartments (TP2X_REF_20K-class 3-compartment
# units, issue #26): top/middle/bottom each report their own storage mode
# plus a ripening status/timer on /status/kimchi/<slot>/vs/0, modeled as a
# pattern capability the same way DOOR_GENERIC is. Only the top
# compartment's door is reported separately (kimchidoors); middle/bottom
# apparently have no contact switch, hence the narrower KIMCHI_DOOR_GENERIC
# below rather than assuming it's universal.
#
# The same state is also mirrored -- packed into single tokens like
# "KIMCHIT_KIMCHI_STORAGE_NORMAL" (T/M/B prefix per compartment) with
# bracketed parameters -- on /mode/vs/0, the same resource FLEX_ZONE reads
# for RF9000-class fridges. /status/kimchi/<slot>/vs/0's plain currentMode/
# supportMode fields are unpacked and self-describing, so that's what this
# binds to instead.
# The same state is also packed into single tokens (e.g.
# "KIMCHIT_KIMCHI_STORAGE_NORMAL") on /mode/vs/0, the resource FLEX_ZONE
# reads for RF9000-class fridges -- this binds to /status/kimchi/<slot>/
# vs/0's plain, self-describing currentMode/supportMode instead.
#
# Write path is unconfirmed (no live write against a real unit) -- same
# "write the same field back to the entity's own href" convention as
# PANTRY_ZONE/BEVERAGE_ZONE above, first real-world write is also the test.
# Write path is unconfirmed on real hardware; same "write the field back to
# the entity's own href" convention as PANTRY_ZONE/BEVERAGE_ZONE.
#
# translations/en.json's kimchi_zone_mode state labels were translated
# directly from the reporter's own (Korean-language) SmartThings app
# screenshots, not guessed from the codes or from their English paraphrase.
# Cross-checking the screenshots against supportMode confirms the on-screen
# option order matches the array order everywhere it's verifiable: the top
# compartment's freezer triplet (표준/강냉/약냉 = Standard/Strong/Weak, at
# -19/-21/-17°C) lines up 1:1 with STORAGE_FREEZER_NORMAL/COLD/WARM, and the
# middle/bottom compartments' full 8-entry kimchi-storage list, 2-entry
# ripening list, and 4-entry custom-storage list each line up 1:1 with their
# supportMode order too -- so COLD/WARM consistently means Strong/Weak (a
# colder or warmer preset around the NORMAL setpoint) everywhere that suffix
# appears, including on STORAGE_FRIDGE_* and the low-salt kimchi variants,
# which weren't directly screenshotted but share the same NORMAL/COLD/WARM
# vocabulary as the two confirmed triplets. CRUNFCH (아삭, "crisp/crunchy")
# and BUY (구입, "purchased") are also confirmed exact matches, not
# abbreviation guesses.
# ---------------------------------------------------------------------------
# translations/en.json's kimchi_zone_mode labels were translated directly
# from the reporter's own Korean SmartThings app screenshots (not guessed),
# and cross-checked against supportMode order to confirm the on-screen
# option order matches the array order throughout -- so COLD/WARM
# consistently means Strong/Weak everywhere that suffix appears.
def _kimchi_mode_write(p, rep, href=None):
@@ -896,9 +821,8 @@ KIMCHI_ZONE = Capability(
icon="mdi:timer-sand",
translation_key="kimchi_ripening_remaining",
entity_category="diagnostic",
# No dump has this nonzero (ripeStatus is always "Off" so
# far) -- device-reported unit unconfirmed, so this stays
# a bare number rather than asserting minutes or hours.
# No dump has this nonzero (ripeStatus is always "Off" so far)
# -- unit unconfirmed, so this stays a bare number.
value_fn=_int,
),
SensorDesc(
@@ -921,12 +845,11 @@ KIMCHI_DOOR_GENERIC = Capability(
poll_tier="hot",
entities=(
# Not deduped against DOORS_FALLBACK below: on the one reporter
# (refrigerator_tp2x_ref_20k_kimchi) this binds alongside, the
# /doors/vs/0 aggregate carries a single generic item (id "4", no
# /door/<instance> siblings for DOORS_FALLBACK's match_fn to see)
# that doesn't share this compartment's "top" instance numbering --
# a distinct main-cabinet door, not this kimchi drawer's own contact
# switch reported twice.
# this binds alongside, /doors/vs/0's aggregate carries a single
# generic item (id "4", no /door/<instance> siblings) that doesn't
# share this compartment's "top" numbering -- a distinct
# main-cabinet door, not this drawer's contact switch reported
# twice.
BinarySensorDesc(
key="open",
rep_fn=_door_open_state,
@@ -937,19 +860,12 @@ KIMCHI_DOOR_GENERIC = Capability(
),
)
# ---------------------------------------------------------------------------
# Aggregate-resource fallbacks
#
# /doors/vs/0, /temperatures/vs/0, and /icemaker/status/vs/0 each duplicate
# information exposed more precisely by per-instance hrefs (DOOR_GENERIC,
# TEMP_CURRENT_GENERIC/TEMP_SETPOINT_GENERIC, ICEMAKER_GENERIC) on hardware
# that has them. Not every fridge does — a simpler model may only ever
# advertise the aggregate resource. Each fallback's match_fn checks the
# full resource set for the richer sibling hrefs and only binds when
# they're absent, so it's a no-op (not a gap — see discovery.py) wherever
# the richer hrefs exist, and a real (if coarser) source of the same data
# where they don't.
# ---------------------------------------------------------------------------
# Aggregate-resource fallbacks: /doors/vs/0, /temperatures/vs/0, and
# /icemaker/status/vs/0 each duplicate information the per-instance hrefs
# above expose more precisely, on hardware that has them -- not every
# fridge does. Each fallback's match_fn checks for the richer sibling
# hrefs and only binds when they're absent, so it's a no-op wherever the
# richer hrefs exist and a real (coarser) source where they don't.
def _any_door_generic(resources):
@@ -1045,23 +961,19 @@ ICEMAKER_STATUS_FALLBACK = Capability(
),
)
# OCF-native aggregate mirror of ICEMAKER_STATUS_FALLBACK. On the captured
# TP1X_REF_21K it duplicates both the vendor aggregate and the richer per-unit
# /icemaker/one|two/vs/0 resources. Its write contract is not advertised, so
# keep the proven per-unit/vendor controls and bind this as a duplicate only.
# OCF-native aggregate mirror of ICEMAKER_STATUS_FALLBACK. On the captured
# TP1X_REF_21K it duplicates both the vendor aggregate and the richer
# per-unit hrefs; its write contract isn't advertised, so bind it as a
# duplicate only.
ICEMAKER_STATUS_NATIVE_DUPLICATE = Capability(
href="/icemaker/status/0",
)
# OCF-native /refrigeration/0 (issue #7's unbound_hrefs) -- the odd one out
# in this section: its three fields duplicate two *different* richer
# hrefs (REFRIGERATION's rapidFridge/rapidFreezing and
# DEFROST_BLOCK_STATUS's defrost_active), each absent independently, so a
# single capability-level match_fn can't express it. Gated per-entity
# (exists_fn) instead: rapid_fridge/rapid_freezing back off only when
# REFRIGERATION's href is present; defrost_active only when
# DEFROST_BLOCK_STATUS's is. No write path confirmed for this href, so
# these are read-only, unlike REFRIGERATION's switches.
# OCF-native /refrigeration/0 (issue #7): its three fields duplicate two
# different richer hrefs (REFRIGERATION's rapidFridge/rapidFreezing,
# DEFROST_BLOCK_STATUS's defrost_active), each absent independently, so
# gating is per-entity (exists_fn) rather than one capability-level
# match_fn. No write path confirmed, so these stay read-only.
REFRIGERATION_FALLBACK = Capability(
href="/refrigeration/0",
poll_tier="warm",
@@ -1078,7 +990,7 @@ REFRIGERATION_FALLBACK = Capability(
key="rapid_fridge",
field="rapidCool",
icon="mdi:fridge-industrial",
entity_category="config",
entity_category="diagnostic",
value_fn=lambda v: bool(v),
exists_fn=lambda rep, resources: "/refrigeration/vs/0" not in resources,
),
@@ -1086,7 +998,7 @@ REFRIGERATION_FALLBACK = Capability(
key="rapid_freezing",
field="rapidFreeze",
icon="mdi:snowflake",
entity_category="config",
entity_category="diagnostic",
value_fn=lambda v: bool(v),
exists_fn=lambda rep, resources: "/refrigeration/vs/0" not in resources,
),
@@ -19,9 +19,9 @@ here would silently do nothing on that path. Enumerate each known href
instead; it's a short, stable list.
This list is maintainer-curated only; there is no per-installation
override. Grow it as real /device/0 dumps surface more universal noise —
do not add a href here on a guess. If a href's relevance is unclear, leave
it unbound so it surfaces as a gap for a human to look at.
override. Grow it as real /device/0 dumps surface more universal noise --
never on a guess. If a href's relevance is unclear, leave it unbound so it
surfaces as a gap for a human to look at.
"""
from ..capability import Capability
@@ -61,12 +61,9 @@ IGNORED: list[Capability] = [
# Redundant with capabilities already declared elsewhere.
# /speakersound/vs/0 duplicates /settings/sound/volume/vs/0 (laundry.SOUND_VOLUME).
Capability(href="/speakersound/vs/0"),
# /wm/editcourse/vs/0 has no entities of its own -- x.com.samsung.da.
# editCourseList is read directly out of the resource snapshot by
# dishwasher.CYCLE_OPTIONS's and washer.WASHER_COURSE's cycle select
# (options=_cycle_options) to build that device's actual supported
# course list, rather than exposing this href's raw byte string
# through its own entity.
# No entities of its own -- editCourseList is read directly out of the
# resource snapshot by dishwasher.CYCLE_OPTIONS/washer.WASHER_COURSE's
# cycle selects to build the device's supported course list.
Capability(href="/wm/editcourse/vs/0"),
# Bixby audio feedback (chime + volume played when Bixby starts/stops
# listening) — only meaningful with Bixby enabled, which this
@@ -96,17 +93,13 @@ IGNORED: list[Capability] = [
# Temperature-unit display preference, redundant with HA's own units.
Capability(href="/wm/submode/vs/0"),
# Read-only re-encoding of the course already exposed by
# washer.WASHER_COURSE at /course/vs/0 (x.com.samsung.da.st.washerMode
# is literally "Table_02_Course_<same hex code>").
# washer.WASHER_COURSE at /course/vs/0 (same hex code, just prefixed
# "Table_02_Course_").
Capability(href="/st/washercourse/vs/0"),
# Dryer counterpart of the above: re-encoding of the course already
# exposed by dryer.DRYER_COURSE at /course/vs/0
# (x.com.samsung.da.st.dryerMode is "Table_03_Course_<same hex code>").
# Dryer counterpart: re-encodes dryer.DRYER_COURSE's /course/vs/0.
Capability(href="/st/dryercourse/vs/0"),
# AirDresser counterpart of the above (issue #157): read only for its
# courseTable id (air_dresser.AIR_DRESSER_COURSE's table_href), no
# entity of its own -- same "no entity, just the table id" role as
# /st/washercourse/vs/0 and /st/dryercourse/vs/0.
# AirDresser counterpart (issue #157): read only for its courseTable id
# (air_dresser.AIR_DRESSER_COURSE's table_href), no entity of its own.
Capability(href="/st/airdressercourse/vs/0"),
# Empty on every washer dump seen so far.
Capability(href="/wm/welcomemsg/vs/0"),
@@ -114,29 +107,21 @@ IGNORED: list[Capability] = [
# state without a multi-slot editor; revisit if that becomes valuable.
Capability(href="/wm/personalcourse/vs/0"),
# OCF-native energy resource is empty ({}) on washer hardware seen so
# far, unlike /power/0, /kidslock/0, /remotectrl/0 which do carry real
# data -- common.ENERGY_METER on /energy/consumption/vs/0 is the only
# real source for this control.
# far -- common.ENERGY_METER on /energy/consumption/vs/0 is the only
# real source.
Capability(href="/energy/consumption/0"),
# Empty ({}) on every washer dump seen so far -- nothing to expose.
Capability(href="/cycleinterface/vs/0"),
# OCF-native duplicate of /drlc/vs/0 above -- same utility-program
# dependency this integration doesn't support locally.
Capability(href="/drlc/0"),
# OCF-native duplicate of /operational/state/vs/0, which is already
# modeled by operational.OPERATIONAL_STATE (a richer, write-capable
# capability with start/pause/stop buttons and a delay-start control)
# used by washer, dishwasher, dryer, and oven. This generic href only
# carries read-only overlapping data (current job state, remaining
# time, progress percentage) with no write path -- not worth building a
# parallel write-capable capability around an unverified generic OCF
# write contract.
# OCF-native duplicate of /operational/state/vs/0, already modeled by
# operational.OPERATIONAL_STATE (richer, write-capable, used by washer,
# dishwasher, dryer, oven). This generic href is read-only overlapping
# data with no verified write contract worth building around.
Capability(href="/operational/state/0"),
# Cooktop guided-cooking/recipe status (issue #86, TP1X_DA-KS-COOKTOP
# family): sequenceNumber, operationBurnerNumber, a stageInfo block, and
# a textData.menu string -- every field empty/zero on the only dump
# seen so far (device idle, no guided-cooking program active). Same
# "don't guess" treatment as the microwave family's /recipe/cook/vs/0.
# Revisit if a dump with an active recipe surfaces.
# Cooktop guided-cooking/recipe status (issue #86): every field
# empty/zero on the only dump seen (device idle). Same "don't guess"
# treatment as the microwave family's /recipe/cook/vs/0.
Capability(href="/cooktop/recipe/status/vs/0"),
]
@@ -178,33 +178,24 @@ BUZZER_SOUND = Capability(
),
)
# ---------------------------------------------------------------------------
# Cycle selection over /course/vs/0.
#
# The selected course and every other user-tunable option ride in the
# x.com.samsung.da.options array on /course/vs/0 as `<Prefix>_<value>` tokens.
# Confirmed on real hardware (issue #54): a write only needs to carry the one
# changed token -- `{'x.com.samsung.da.options': ['SoftenerLevelCtrl_2']}` --
# the device matches by prefix, evicts the stale token, and merges the result
# into the array itself. No read-modify-write of the whole array needed (see
# option_write). The set of *selectable* courses is not hardcoded -- it's read
# live from
# x.com.samsung.da.editCourseList on /wm/editcourse/vs/0 (cycle_options), so we
# never show a course a given model doesn't have or hide one it does. Course
# codes are uppercase hex; display names live in translations under
# entity.select.<translation_key>.state.<id lowercased> so they can be
# localized -- every device-enum select in this integration works this way.
# washer.py's course comment has the byte-level evidence for why the options[]
# MostUsed_* entry is *not* a trustworthy second source.
# x.com.samsung.da.options array as `<Prefix>_<value>` tokens. Confirmed on
# real hardware (issue #54): a write only needs to carry the one changed
# token -- the device matches by prefix, evicts the stale token, and merges
# the result itself (see option_write). The set of selectable courses is
# read live from editCourseList on /wm/editcourse/vs/0 (cycle_options), not
# hardcoded. Course codes are uppercase hex; display names live in
# translations under entity.select.<translation_key>.state.<id lowercased>.
#
# Some boards populate /wm/editcourse/vs/0 without ever filling in
# editCourseList itself (issue #1) -- cycle_options() falls back to deriving
# the same list from /course/vs/0's own supportedOptions in that case; see
# _course_codes_from_supported_options for the byte-level evidence.
# editCourseList itself (issue #1) -- cycle_options() falls back to
# deriving the list from /course/vs/0's own supportedOptions in that case;
# see _course_codes_from_supported_options.
#
# Shared verbatim by washer, dishwasher, and dryer -- all DA_WM_-family boards
# expose the same /course/vs/0 options contract.
# ---------------------------------------------------------------------------
# Shared verbatim by washer, dishwasher, and dryer -- all DA_WM_-family
# boards expose the same /course/vs/0 options contract.
def hex_pairs(codes):
@@ -237,13 +228,11 @@ def option_value(options, prefix):
# Drum Clean+ maintenance tracking, from the same options[] array as the
# selected course -- shared by washer.py (issue #9) and dryer.py (issue
# #258); both families use identical DrumCleanProposal_/WashingTimes_/
# DrumCleanLog_ tokens. DrumCleanProposal_<N> is the wash/dry-cycle interval
# between recommended cleans; WashingTimes_<N> is the count since the last
# one -- their difference is exactly the "N cycles until due" figure the
# Samsung app shows (verified on a washer: DrumCleanProposal_40 -
# WashingTimes_3 == 37, matching a live app screenshot's "Potreba cistenia
# po 37 cykloch").
# #258), identical DrumCleanProposal_/WashingTimes_/DrumCleanLog_ tokens.
# DrumCleanProposal_<N> is the cycle interval between recommended cleans;
# WashingTimes_<N> is the count since the last one -- their difference is
# the "N cycles until due" figure the app shows (verified: 40 - 3 == 37,
# matching a live app screenshot).
def drum_clean_cycles_remaining(rep):
opts = rep.get("x.com.samsung.da.options") or []
proposal = option_value(opts, "DrumCleanProposal")
@@ -257,14 +246,10 @@ def drum_clean_cycles_remaining(rep):
# DrumCleanLog_ is the clean-history field: a washer reports one bare ISO
# datetime (the last clean, verified against the same app screenshot's "10
# days ago"); a dryer (issue #258's Dillton-reported dump) instead reports a
# '|'-joined history of every past clean, ten deep on that dump, in
# strictly increasing order. Splitting on '|' and taking the last element
# handles both shapes identically -- a no-'|' value is unaffected. No
# explicit timezone field accompanies either shape, so it's treated as UTC,
# matching this integration's convention for other bare ISO datetime fields
# (see fridge.py's night-light schedule comment).
# datetime (the last clean); a dryer (issue #258) instead reports a
# '|'-joined history of every past clean in increasing order. Splitting on
# '|' and taking the last element handles both shapes identically. No
# timezone accompanies either shape, so it's treated as UTC.
def drum_clean_last_cleaned(rep):
raw = option_value(rep.get("x.com.samsung.da.options"), "DrumCleanLog")
if not raw:
@@ -278,41 +263,27 @@ def drum_clean_last_cleaned(rep):
def _course_codes_from_supported_options(course_rep):
"""Fallback for an empty/missing editCourseList: derive the selectable
course list from /course/vs/0's own x.com.samsung.da.supportedOptions
instead (issue #1: some DA_WM_TP1/TP2-class boards populate the
/wm/editcourse/vs/0 href but never fill in editCourseList itself).
course list from /course/vs/0's own supportedOptions instead (issue #1:
some boards populate /wm/editcourse/vs/0 but never fill in
editCourseList itself).
supportedOptions is a 1-hex-nibble header followed by one fixed-width
record per selectable course, self-indexed rather than positional --
the first byte of every record is that course's own hex code, just in
the firmware's own internal order, not editCourseList's. Confirmed
against six independent real-world washer/dryer/dishwasher dumps: every
one divides evenly into `header + N * K bytes` with fully unique first
bytes across all N records, at the record's true byte width. (What the
rest of each record encodes is still unconfirmed -- this only uses the
course-code byte.)
the first byte of every record is that course's own hex code.
Confirmed against six independent real-world dumps: every one divides
evenly into `header + N * K bytes` with fully unique first bytes across
all N records, at the record's true byte width.
Two guards, deliberately conservative rather than guessing further: the
derived codes must (a) all be distinct -- a real course table, not
noise -- and (b) include whatever course is currently selected
(x.com.samsung.da.options' Course_<code> token), which must always be a
member of its own device's valid list. If no split satisfies both, this
returns [] rather than guess.
Two conservative guards rather than guessing further: the derived codes
must all be distinct, and must include whatever course is currently
selected. If no split satisfies both, this returns [].
Among splits that satisfy both, the *smallest* passing K wins, rather
than requiring a single unambiguous one -- more than one K reliably
does pass on real data (e.g. the shipped dishwasher fixture: true
K=7 passes, but so do 10, 14, and 35, none of which are multiples of
7 -- position 0 always lands on the same real course code regardless
of K, which is enough on its own to satisfy the current-course guard
for several unrelated splits). Smallest-K-wins is a heuristic, not a
proof: it matches the confirmed answer on every one of six independent
real-world dumps this was checked against, but a coincidentally
unique, current-course-inclusive *smaller* K is not mathematically
impossible on some future device, and would be picked silently. Not
guarded against further here, since course tables are typically large
enough (double digits) that colliding by chance on both checks is
unlikely, and no device seen so far actually needs it.
Among splits that satisfy both, the smallest passing K wins -- more
than one K reliably passes on real data, and smallest-K-wins matches
the confirmed answer on all six dumps checked, though it's a heuristic
rather than a proof. Not guarded further: course tables are typically
large enough that colliding by chance on both checks is unlikely, and
no device seen so far needs it.
"""
raw = course_rep.get("x.com.samsung.da.supportedOptions")
hexstr = raw[0] if isinstance(raw, list) and raw else raw
@@ -340,7 +311,7 @@ def _course_codes_from_supported_options(course_rep):
def option_write(prefix, new_value):
"""A one-token x.com.samsung.da.options write -- see the module comment
above cycle_options for why this doesn't read/rewrite the whole array."""
above for why this doesn't read/rewrite the whole array."""
return [f"{prefix}_{new_value}"]
@@ -360,35 +331,24 @@ def _table_id(resources, table_href):
def cycle_select(*, translation_key, icon, table_href=None):
"""A 'Cycle' select over /course/vs/0, labelled from `translation_key`.
The option list, current value, and write path are all shared across
washer/dryer/dishwasher; only the translation is family- (and, for
washer/dryer, board-) specific.
The option list, current value, and write path are shared across
washer/dryer/dishwasher; only the translation is family/board-specific.
table_href (washer/dryer only -- see washer.py/dryer.py's call sites)
suffixes translation_key with the device's own course-table id, read
from /st/washercourse/vs/0 or /st/dryercourse/vs/0's
x.com.samsung.da.st.courseTable (e.g. 'washer_cycle' + 'Table_02' ->
'washer_cycle_table_02'). An absent or unrecognized table id gets the
name-only ``cycle`` translation key while the raw course code remains
visible and writable.
This matters because course codes are NOT guaranteed consistent across
board generations sharing the same /course/vs/0 contract: every code in
washer_cycle_table_02 was confirmed against Table_02-reporting devices
(DA_WM_TP1/TP2 boards); FlexWash's older DA_WM_A51 board reports
Table_00 instead, so the same hex code could mean a different course
there for all we've verified. So a table-specific key is used only when
the shipped catalog actually has one; any other table (Table_00 today,
whatever ships next) falls back to the name-only ``cycle`` key, which
shows the raw course code rather than a label borrowed from another
board generation. Translating a new table is therefore a
translations-only change -- add the ``<family>_cycle_<table>`` entry and
this resolver picks it up.
table_href (washer/dryer only) suffixes translation_key with the
device's own course-table id, read from /st/washercourse/vs/0 or
/st/dryercourse/vs/0's courseTable (e.g. 'washer_cycle' + 'Table_02' ->
'washer_cycle_table_02'). This matters because course codes are NOT
guaranteed consistent across board generations sharing the same
/course/vs/0 contract: washer_cycle_table_02 was confirmed against
Table_02 devices, but FlexWash's older board reports Table_00, where
the same hex code could mean a different course. An absent or
unrecognized table id falls back to the name-only ``cycle`` key
instead of borrowing a label from another board generation --
translating a new table is a translations-only change.
Left at its default for dishwasher, which has no equivalent table-id
resource in any dump seen and no evidence its course codes vary by
table the way washer/dryer's do -- there's nothing to build a
table-specific key from.
resource and no evidence its codes vary by table the way washer/
dryer's do.
"""
key = translation_key
if table_href is not None:
@@ -411,14 +371,11 @@ def cycle_select(*, translation_key, icon, table_href=None):
)
# ---------------------------------------------------------------------------
# Plain boolean toggles over /course/vs/0's options[] array: a
# '<prefix>_On'/'<prefix>_Off' token, read-modify-written the same way as
# the 'Course' token above. Shared by washer (bubble soak, pre-wash,
# intensive -- issue #22) and dishwasher (storm wash, auto release dry) --
# both families ride this exact contract, just with different prefixes and
# different presence/validation needs on top.
# ---------------------------------------------------------------------------
# '<prefix>_On'/'<prefix>_Off' token, merged the same way as the 'Course'
# token above. Shared by washer (bubble soak, pre-wash, intensive -- issue
# #22) and dishwasher (storm wash, auto release dry), just with different
# prefixes and presence/validation needs on top.
def bool_option_write(prefix):
@@ -450,12 +407,11 @@ def bool_option_switch(
"""A SwitchDesc over a '<prefix>_On'/'<prefix>_Off' options[] token.
gate_on_presence self-gates the entity off on models that never report
the token at all (washer's bubble soak/pre-wash/intensive); leave False
for a toggle every device in the family reports (dishwasher's storm
wash). validate_fn is passed straight through to SwitchDesc for callers
that need to reject a write against live device state (e.g. washer's
per-course availability check) -- this factory has no opinion on it and
building one, if needed, is the caller's job.
the token (washer's bubble soak/pre-wash/intensive); leave False for a
toggle every device in the family reports (dishwasher's storm wash).
validate_fn passes straight through to SwitchDesc for callers that need
to reject a write against live state -- this factory has no opinion on
it.
"""
return SwitchDesc(
key=key,
@@ -468,14 +424,11 @@ def bool_option_switch(
)
# ---------------------------------------------------------------------------
# /wm/jobbeginingstatus/vs/0 -- the "why did the cycle not start" reason
# (e.g. door open, no water). The vendor field is x.com.samsung.da.currentStatus
# on every laundry dump that populates it (washer + DA_WM_TP1 dryer). An
# earlier dryer descriptor read x.com.samsung.da.jobBeginingStatus, but no dump
# ever carried that field, so the dryer sensor was always blank -- fixed by
# sharing this one reader.
# ---------------------------------------------------------------------------
# (e.g. door open, no water), x.com.samsung.da.currentStatus on every dump
# that populates it. An earlier dryer descriptor read
# x.com.samsung.da.jobBeginingStatus instead, which no dump ever carried,
# so the dryer sensor was always blank -- fixed by sharing this one reader.
JOB_BEGINNING_STATUS = Capability(
href="/wm/jobbeginingstatus/vs/0",
@@ -8,33 +8,25 @@ oven.py in by_type/microwave.py rather than duplicated. What's genuinely
different from an oven, and defined fresh here:
* Cooking-mode vocabulary: MicroWave/MicroWaveGrill/MicroWaveConvection/
KeepWarm never appear on an oven's /mode/vs/0, and this family spells
some shared-sounding modes differently than oven.py's own constants
(e.g. 'AirFryer', not oven.py's 'AirFry') -- a distinct SelectDesc and
mode list, not oven.OVEN_MODE.
KeepWarm never appear on an oven's /mode/vs/0, and some shared-sounding
modes are spelled differently (e.g. 'AirFryer', not oven.py's
'AirFry') -- a distinct SelectDesc and mode list, not oven.OVEN_MODE.
* Setpoint bounds: this family's Convection/MicroWaveConvection modeSpec
(issue #121's MW7300B dump) reports 40-200 C / step 5, not oven.py's
30-270 C range (verified against a different, bake-oven-class board).
* Cavity: /oven/vs/0 here also carries a `powerLevel` field (100W-900W
on the MicroWave mode's powerListData) that plain ovens don't report --
exposed as its own sensor.
* Lamp: this family's option-array token is bare 'Lamp' (issue #137's
'Lamp_Off'), not oven.py's 'UpperLamp' -- and it's genuinely absent on
the combi dump (issue #121), so it's gated with exists_fn rather than
assumed universal like oven.py's lamp switch. Issue #137's dump only
ever showed 'Off', so 'On' was a guess at the paired value; issue #152's
ME7500D dump is the first to show a real non-Off value, and it's 'High'
(a brightness level, not literally 'On') -- the switch now treats any
non-Off/non-None value as "on" for reads, and writes back 'High'/'Off'
(the two confirmed tokens) rather than the never-confirmed 'On'.
(issue #121) reports 40-200°C / step 5, not oven.py's 30-270°C range.
* Cavity: /oven/vs/0 here also carries a `powerLevel` field (100W-900W)
that plain ovens don't report -- exposed as its own sensor.
* Lamp: this family's option-array token is bare 'Lamp' (issue #137), not
oven.py's 'UpperLamp', and genuinely absent on the combi dump (issue
#121), so it's exists_fn-gated rather than assumed universal. 'On' has
never been observed as a value; the only confirmed non-Off token is
'High' (issue #152) -- the switch treats any non-Off/non-None value as
"on" for reads and writes back 'High'/'Off'.
* Filter reminder / end signal reminder: bare 'FilterRemind'/'RemindBeep'
option-array tokens (issue #181), both with On and Off observed live
(issue #152's ME7500D fixtures) -- gated with exists_fn like Lamp since
option-array tokens (issue #181), gated with exists_fn like Lamp since
the MW7300B combi dump has neither.
Note: cooking-mode writes are unproven here, same caveat as oven.py's
OVEN_MODE -- exposed as a SelectDesc for fidelity, first real-world write
is also the test.
Cooking-mode writes are unproven here, same caveat as oven.py's OVEN_MODE
-- exposed as a SelectDesc for fidelity, first real-world write is the test.
"""
from ..capability import Capability
@@ -46,13 +38,10 @@ from .laundry import option_value, option_write
# Constants
# ---------------------------------------------------------------------------
# Union of every mode seen across the two known dumps: issue #121's combi
# MW7300B (NoOperation/Autocook/AutocookCustom/Convection/AirFryer/Grill/
# MicroWave/MicroWaveGrill/MicroWaveConvection/Deodorization) and issue #137's
# plain ME7500D (NoOperation/MicroWave/Autocook/KeepWarm). No dump has shown
# every mode below on one device -- the select surfaces whatever a given
# board's own /mode/vs/0 supportedModes reports; an entry here that a device
# never sends just never gets picked.
# Union of every mode seen across the two known dumps (issues #121, #137).
# No dump has shown every mode below on one device -- the select surfaces
# whatever a given board's own supportedModes reports; an entry here a
# device never sends just never gets picked.
_MICROWAVE_MODES = (
"NoOperation",
"MicroWave",
@@ -67,22 +56,18 @@ _MICROWAVE_MODES = (
"KeepWarm",
)
# Convection/MicroWaveConvection modeSpec on issue #121's dump: tempMinC 40,
# tempMaxC 200, tempIntervalC 5. No Fahrenheit dump exists for this family;
# unlike oven.py's own SETPOINT_MIN_F/MAX_F/STEP_F (independently verified
# against issue #44's range dump), there's nothing to verify a microwave's
# Fahrenheit bounds against, so this module only exposes the setpoint
# control when the live unit is Celsius (see _microwave_temp_unit below).
# Convection/MicroWaveConvection modeSpec on issue #121's dump: 40-200°C,
# step 5. No Fahrenheit dump exists for this family, unlike oven.py's own
# independently-verified F bounds, so this module only exposes the
# setpoint control when the live unit is Celsius (see _microwave_temp_unit).
SETPOINT_MIN_C = 40
SETPOINT_MAX_C = 200
SETPOINT_STEP_C = 5
def _microwave_temp_unit(rep):
"""Same shape as oven.py's _oven_temp_unit: /temperatures/vs/0 items[]
carries a per-item x.com.samsung.da.unit field. Both known dumps for
this family report 'Celsius'; kept live rather than hardcoded per the
fridge/oven convention (issue #7)."""
"""Same shape as oven.py's _oven_temp_unit. Both known dumps report
'Celsius'; kept live rather than hardcoded (issue #7)."""
items = rep.get("x.com.samsung.da.items") or []
unit = items[0].get("x.com.samsung.da.unit") if items else None
return normalize_temp_unit(unit, default="°C")
@@ -90,8 +75,7 @@ def _microwave_temp_unit(rep):
def _setpoint_write(p, rep, href=None):
"""RMW write to /temperatures/vs/0 items array -- unproven for this
family (no live write confirmed against a real unit), same "exposed for
fidelity" caveat as the mode select."""
family, same "exposed for fidelity" caveat as the mode select."""
try:
temp = float(p)
except (TypeError, ValueError):
@@ -118,12 +102,11 @@ def _power_level_watts(v):
def _cooking_mode_options(resources):
"""Live mode list from the device's own /mode/vs/0 supportedModes when
it reports one (both known dumps do); the union-of-all-dumps
_MICROWAVE_MODES guess otherwise. Same live-first, static-fallback
pattern as oven._oven_mode_options -- a fixed list here would offer
users modes their own unit doesn't have (issue #152's ME7500D reports
only 4 of _MICROWAVE_MODES' 11)."""
"""Live mode list from the device's own supportedModes when reported
(both known dumps do); the union-of-all-dumps _MICROWAVE_MODES guess
otherwise. Same live-first, static-fallback pattern as
oven._oven_mode_options -- a fixed list would offer modes a unit
doesn't have (issue #152 reports only 4 of _MICROWAVE_MODES' 11)."""
rep = resources.get("/mode/vs/0") or {}
live = rep.get("x.com.samsung.da.supportedModes")
return list(live) if live else list(_MICROWAVE_MODES)
@@ -163,9 +146,8 @@ def _lamp_write(p, rep, href=None):
return None
if not rep.get("x.com.samsung.da.options"):
return None
# 'High' and 'Off' are the two tokens actually confirmed on live dumps
# (issues #137/#152) -- 'On' has never been observed and the device
# likely doesn't recognize it (see module docstring).
# 'High'/'Off' are the two confirmed tokens (see module docstring);
# 'On' has never been observed and likely isn't recognized.
token = "High" if p == "On" else "Off"
return ["mode", "vs", "0"], {
"x.com.samsung.da.options": option_write("Lamp", token),
@@ -271,11 +253,9 @@ MICROWAVE_MODE = Capability(
value_fn=lambda opts: option_value(opts, "Lamp") not in (None, "Off"),
write_fn=_lamp_write,
),
# issue #181: Filter Reminder / End Signal Reminder toggles,
# confirmed present (both On and Off observed across dumps -- see
# issue #152's ME7500D fixtures) but only on boards that carry the
# FilterRemind_*/RemindBeep_* tokens; gated off elsewhere (e.g. the
# MW7300B combi dump has neither) rather than assumed universal.
# issue #181: Filter Reminder / End Signal Reminder toggles, only on
# boards carrying the FilterRemind_*/RemindBeep_* tokens; gated off
# elsewhere (the MW7300B combi dump has neither).
SwitchDesc(
key="filter_remind",
field="x.com.samsung.da.options",
@@ -98,11 +98,9 @@ def _finish_time(rep):
if not total_s:
return None
# Round to whole minutes -- remainingTime itself only has minute
# resolution, but datetime.now() always carries fresh seconds/
# microseconds, so an unrounded result changes on nearly every poll
# even when the device-reported remaining time hasn't. That floods
# the recorder history/logbook with values that look identical once
# the UI rounds them down for display.
# resolution, but datetime.now()'s fresh seconds/microseconds would
# otherwise change the result on nearly every poll, flooding the
# recorder with values that look identical once the UI rounds them.
finish = datetime.now(UTC) + timedelta(seconds=total_s)
return finish.replace(second=0, microsecond=0)
@@ -147,15 +145,11 @@ OPERATIONAL_STATE = Capability(
translation_key="machine_state",
value_fn=_to_ocf,
),
# cycle_active is a bool derived from machine_state; used by the
# adapter to gate oven writes (cycle_active_field='cycle_active').
# Harmless for non-oven appliances — just an extra bool in state.
# Samsung firmware keeps state='Run' after progress reaches 'Finish',
# so we also gate on progress to avoid a stuck 'Running' indication.
# Named 'Running' in the catalog rather than 'Cycle active' -- this href (and the
# start/pause/stop buttons below) is shared across the dryer/
# dishwasher/oven/washer families, and 'cycle' is laundry-specific
# vocabulary that doesn't fit an oven's bake/roast/etc.
# cycle_active is a bool derived from machine_state, gated on
# progress too since firmware keeps state='Run' after progress
# reaches 'Finish' (a stuck 'Running' indication otherwise). Named
# 'Running' in the catalog, not 'Cycle active' -- this href is
# shared with oven, and 'cycle' is laundry-specific vocabulary.
BinarySensorDesc(
key="cycle_active",
device_class="running",
@@ -183,9 +177,8 @@ OPERATIONAL_STATE = Capability(
else _int(rep.get("x.com.samsung.da.progressPercentage"))
),
),
# Only show finish time when machine is actively running. Samsung
# firmware leaves a stale remainingTime after a cycle ends, and
# freezes it at '00:01:00' when progress reaches 'Finish'.
# Only show finish time while actively running -- firmware leaves a
# stale remainingTime after a cycle ends, frozen at '00:01:00'.
SensorDesc(
key="finish_time", device_class="timestamp", hysteresis=True, rep_fn=_finish_time
),
@@ -1,26 +1,19 @@
"""Capabilities for the oven family (Samsung NV7000BS-class).
Resources verified against the live device via DTLS-CoAP.
See `local-tools/comparisons/oven-tree.md` for the full field reference.
Resources verified against the live device via DTLS-CoAP. See
`local-tools/comparisons/oven-tree.md` for the full field reference.
Write surfaces this module exposes:
Proven write: lamp, via /mode/vs/0 options RMW, works even with Remote
Control off. Unproven (first HA use is also the test): sound/fastPreheat/
naturalSteam (same RMW pattern), setpoint via /temperatures/vs/0 items RMW,
cook time via /operational/state/vs/0's operationTime/remainingTime, mode
select via /mode/vs/0.modes (mid-cook acceptance unknown), stop via
state='Ready'.
proven:
* Lamp via /mode/vs/0 options RMW (probe_oven_lamp_toggle.py)
— works even with Remote Control off.
unproven (first HA use is also the test):
* Sound, FastPreheat, NaturalSteam — same RMW pattern as lamp.
* Setpoint via /temperatures/vs/0 items RMW.
* Cook time via /operational/state/vs/0 operationTime/remainingTime.
* Mode select via /mode/vs/0 .modes — mid-cook acceptance unknown.
* Stop via /operational/state/vs/0 state='Ready'.
Note: Cycle start is not implemented. Reverse-engineering shows local-OCF
cycle start is not reproducible on this firmware (see project_oven_remote
_start_open.md). Mode writes are also unreliable — the oven rolls them back
once a cycle is active. OVEN_MODE is provided as a SelectDesc for fidelity
but is effectively read-only in practice.
Cycle start is not implemented: local-OCF cycle start isn't reproducible on
this firmware. Mode writes are also unreliable -- the oven rolls them back
once a cycle is active, so OVEN_MODE's SelectDesc is effectively read-only
in practice.
"""
from datetime import UTC, datetime, timedelta
@@ -45,26 +38,18 @@ SETPOINT_MIN_C = 30
SETPOINT_MAX_C = 270
SETPOINT_STEP_C = 5
# Verified against issue #44's range dump (NSI6DG9100SRAA, unit reported as
# "Fahrenheit" on /temperatures/vs/0): Bake mode's modeSpec on /mode/vs/0
# reports tempMinF/tempMaxF/tempIntervalF = 175/550/5. Kept as a separate
# constant set rather than converted from the Celsius bounds above, which
# are themselves unverified (no live dump; see module docstring).
# Verified against issue #44's range dump: Bake mode's modeSpec reports
# tempMinF/tempMaxF/tempIntervalF = 175/550/5. Kept separate rather than
# converted from the Celsius bounds above, which are themselves unverified.
SETPOINT_MIN_F = 175
SETPOINT_MAX_F = 550
SETPOINT_STEP_F = 5
# Mode options seen on NV7000BS-class. No dump exists so this list is inferred
# from Samsung documentation and firmware observations. The firmware will
# reject unknown modes; missing entries here are a coverage gap, not a bug.
#
# This is a fallback only, used when a device's own /mode/vs/0 doesn't report
# x.com.samsung.da.supportedModes at all -- see _oven_mode_options/
# _oven_mode_write below. issue #138's range dump (NE63A6511SS/AA) reports
# ConvectionRoast/KeepWarm/BreadProof/AirFryer/Dehydrate/SelfClean/SteamClean
# in its own supportedModes; those are read live rather than added here, per
# the adding-device-support skill's preference for device-reported option
# lists over hardcoded ones.
# Mode options seen on NV7000BS-class. No dump exists so this list is
# inferred from Samsung documentation and firmware observations; the
# firmware rejects unknown modes, so a missing entry is a coverage gap, not
# a bug. Fallback only, used when a device's own /mode/vs/0 doesn't report
# supportedModes at all -- see _oven_mode_options/_oven_mode_write below.
_OVEN_MODES = (
"NoOperation",
"Bake",
@@ -138,22 +123,18 @@ def _option_value(options, prefix):
def _has_option(prefix):
"""exists_fn for an options-array switch: bind only when the device's own
options[] actually carries a `<prefix>_<value>` token.
"""exists_fn for an options-array switch: bind only when the device's
own options[] actually carries a `<prefix>_<value>` token.
fast_preheat/natural_steam were shipped unconditionally (no exists_fn) as
an unverified guess (see module docstring) -- issue #183's dump (model
NE6516A) reports neither `fastpreheat_*` nor `NaturalSteam_*` in its
options[] at all, so both switches were phantom controls: always read as
off, and toggling them wrote a token the firmware never recognized in
the first place, hence "does not appear to do anything."
fast_preheat/natural_steam were shipped unconditionally (no exists_fn)
as an unverified guess -- issue #183's dump reports neither token in
its options[] at all, so both switches were phantom controls that
"don't appear to do anything."
`is_stub_rep(rep) or` keeps the same stub carve-out as cooktop.py's
identical per-token exists_fn on its own options[]-array href: a stub
/device/0 seed rep (not yet sub-polled) has no options[] at all, and
without this an entity whose token is genuinely present would never get
a first chance to bind, since exists_fn runs before that first real
fetch lands.
identical exists_fn: a stub /device/0 seed rep has no options[] at all,
and without this a genuinely-present token would never get a first
chance to bind.
"""
return lambda rep, resources: (
is_stub_rep(rep) or _option_value(rep.get("x.com.samsung.da.options"), prefix) is not None
@@ -163,13 +144,10 @@ def _has_option(prefix):
def _option_write(prefix, new_value):
"""A one-token x.com.samsung.da.options write, mirroring
laundry.option_write. NOT independently confirmed on an oven -- issue
#54 only confirmed prefix-merge-on-write for a washer's /course/vs/0.
This extrapolates that same vendor field/contract to the oven's
/mode/vs/0, on the assumption the firmware handles the array the same
way there. If that assumption is wrong for some oven, a device that
replaces the field outright instead of merging would drop every other
option in it (Sound/fastpreheat/etc.) on the next write -- revisit if a
real device report surfaces that."""
#54 only confirmed prefix-merge-on-write for a washer's /course/vs/0;
this extrapolates the same contract here. If some oven replaces the
field outright instead of merging, this would drop every other option
on the next write -- revisit if a real device report surfaces that."""
return [f"{prefix}_{new_value}"]
@@ -318,13 +296,11 @@ OVEN_CAVITY = Capability(
def _oven_temp_unit(rep):
"""Same shape/risk as fridge.py's TEMPERATURES_FALLBACK: this is the
same aggregate `/temperatures/vs/0` items[] resource type, which on
fridge hardware carries a per-item `x.com.samsung.da.unit` field
('Celsius'/'Fahrenheit') that was previously hardcoded away (issue #7).
Keeps the verified '°C' default when the field is absent (the original
NV7000BS-class dump this module was written against), but reads it live
-- issue #44's range dump is the first to report 'Fahrenheit' here."""
"""Same shape/risk as fridge.py's TEMPERATURES_FALLBACK: this aggregate
`/temperatures/vs/0` items[] resource carries a per-item `unit` field
that was previously hardcoded away (issue #7). Keeps the verified '°C'
default when the field is absent, but reads it live -- issue #44's
range dump is the first to report 'Fahrenheit' here."""
items = rep.get("x.com.samsung.da.items") or []
unit = items[0].get("x.com.samsung.da.unit") if items else None
return normalize_temp_unit(unit, default="°C")
@@ -404,17 +380,12 @@ OVEN_CONNECTED = Capability(
),
)
# Static cavity capability metadata (count/type/supported features) -- no
# per-cavity data varies at runtime on any dump seen so far (issue #44's
# range: single cavity, no supportedFeatureList entries). Bound with no
# entities purely for coverage; revisit if a multi-cavity dump surfaces
# fields worth exposing.
# Static cavity capability metadata -- no per-cavity data varies at runtime
# on any dump seen so far. Bound with no entities purely for coverage.
OVEN_SPEC = Capability(href="/oven/spec/vs/0")
# Quick-recipe display blob (combi microwave, issue #121) -- a JSON-encoded
# string (language/menu/servingSize/option) with every field blank on the
# only dump seen, and no documented write contract. No entity to bind per
# the 'don't guess' rule; a bare Capability still marks the href covered.
# Quick-recipe display blob (combi microwave, issue #121) -- every field
# blank on the only dump seen, no documented write contract.
OVEN_RECIPE_COOK = Capability(href="/recipe/cook/vs/0")
OVEN_MODE = Capability(
@@ -430,10 +401,17 @@ OVEN_MODE = Capability(
value_fn=lambda v: v[0] if v else None,
write_fn=_oven_mode_write,
),
# No exists_fn on the NV7000BS-class board this was proven against
# (UpperLamp_ is always in its options[]) -- but issue #300's
# steam-oven-class WALLOVEN board's options[] has no UpperLamp_
# token at all, so this was a phantom, always-off, write-does-
# nothing switch there. Same fastpreheat/NaturalSteam-class gap
# issue #183 already fixed on the other switches below.
SwitchDesc(
key="lamp",
field="x.com.samsung.da.options",
icon="mdi:track-light",
exists_fn=_has_option("UpperLamp"),
value_fn=lambda opts: _option_value(opts, "UpperLamp") == "On",
write_fn=_option_switch_write("UpperLamp"),
),
@@ -462,9 +440,8 @@ OVEN_MODE = Capability(
write_fn=_option_switch_write("NaturalSteam"),
),
# 120-hour energy-saving standby (issue #183): confirmed present in
# this unit's options[] (EnergySaving_On) and directly requested --
# unlike fast_preheat/natural_steam above, this token is real on this
# hardware, just previously unbound entirely.
# this unit's options[] -- unlike fast_preheat/natural_steam above,
# this token is real on this hardware, just previously unbound.
SwitchDesc(
key="energy_saving",
field="x.com.samsung.da.options",
@@ -1,36 +1,32 @@
"""Capabilities for the cooktop half of range/combo appliances (issue #44,
model TP1X_DA-KS-RANGE-0102X).
Not to be confused with PR #23's registry/capabilities/cooktop.py, which
covers an unrelated standalone-cooktop product (NA9300K-class) that encodes
burner state as strings inside /mode/vs/0's options array instead of the
structured /cooktop/status/vs/0 resource this module reads -- two different
OCF surfaces that happen to share the English word "cooktop".
Not to be confused with registry/capabilities/cooktop.py, which covers an
unrelated standalone-cooktop product (NA9300K-class) that encodes burner
state as strings inside /mode/vs/0's options array instead of the
structured /cooktop/status/vs/0 resource this module reads -- two
different OCF surfaces that happen to share the English word "cooktop".
Unlike the rest of the OCF surface, these hrefs use plain camelCase field
names (no `x.com.samsung.da.` prefix) -- `/cooktop/status/vs/0` already
looks like a vendor resource migrated onto OCF-standard-shaped field naming.
names (no `x.com.samsung.da.` prefix).
`/cooktop/status/vs/0` carries every burner's live state in one `burnerList`
array (indexed by `burnerNumber`, not by a separate href per burner like
fridge ice makers), so per-burner entities are hardcoded up to MAX_BURNERS
and gated by exists_fn against whichever indices the device actually
reports -- harmless over-declaration, per common.py's UNIVERSAL note, since
an index absent from burnerList just never binds.
`/cooktop/status/vs/0` carries every burner's live state in one
`burnerList` array (indexed by `burnerNumber`), so per-burner entities are
hardcoded up to MAX_BURNERS and gated by exists_fn against whichever
indices the device actually reports -- an index absent from burnerList
just never binds.
Write surfaces here are unproven (no live device to verify against, same
caveat as oven.py's RMW writes) -- power level uses the same read-modify-
write pattern already proven safe elsewhere in this codebase (oven setpoint,
icemaker toggles).
caveat as oven.py's RMW writes) -- power level uses the same
read-modify-write pattern already proven safe elsewhere in this codebase.
"""
from ..capability import Capability
from ..entities import BinarySensorDesc, SelectDesc, SensorDesc, SwitchDesc
from .common import normalize_temp_unit
# Observed as high as 4 (this issue's dump); user-reported hardware with 5
# burners exists. Kept a little above both since exists_fn gates unused
# slots out -- see module docstring.
# Observed as high as 4; user-reported hardware with 5 burners exists.
# Kept a little above both since exists_fn gates unused slots out.
MAX_BURNERS = 6
@@ -140,11 +136,10 @@ COOKTOP_STATUS = Capability(
poll_tier="hot",
entities=(
SensorDesc(key="cooktop_state", field="operationState", icon="mdi:pot-steam"),
# The cooktop section's own on/off (issue #86) -- distinct from
# common.POWER's /power/0 or /power/vs/0, which some boards in this
# family (the range combo) additionally carry for the whole
# appliance. Read-only: no live device to confirm remotely turning
# a cooktop on wouldn't leave a burner active unattended.
# The cooktop section's own on/off (issue #86), distinct from
# common.POWER's whole-appliance switch. Read-only: no live device
# to confirm remotely turning it on wouldn't leave a burner active
# unattended.
BinarySensorDesc(
key="cooktop_power",
field="power",
@@ -153,8 +148,7 @@ COOKTOP_STATUS = Capability(
value_fn=lambda v: str(v).lower() == "on",
),
# Safe to write -- a lock toggle, not a heat control -- via a
# direct single-field PUT (no RMW needed; unlike burnerList this
# is a lone scalar, not an array of siblings to preserve).
# direct single-field PUT, no RMW needed.
SwitchDesc(
key="cooktop_child_lock",
field="childLock",
@@ -169,16 +163,14 @@ COOKTOP_STATUS = Capability(
)
# Static burner-count/power-level-list metadata, read directly by
# COOKTOP_STATUS's power-level select (options=_power_level_options) rather
# than exposed through its own entity -- same "informs another capability,
# no entity of its own" pattern as /wm/editcourse/vs/0 (ignored.py).
# COOKTOP_STATUS's power-level select (options=_power_level_options)
# rather than exposed through its own entity.
COOKTOP_SPEC = Capability(href="/cooktop/spec/vs/0")
# settingTime (seconds) is the hot-surface auto-shutoff timer's configured
# duration (1200s = 20 min in issue #44's dump); state on/off is whether the
# feature itself is enabled -- not a live "surface is hot right now" alert
# (that's COOKTOP_STATUS's per-burner hot_surface). No write contract
# verified, so read-only for now.
# duration; state on/off is whether the feature itself is enabled -- not a
# live "surface is hot right now" alert (that's COOKTOP_STATUS's per-burner
# hot_surface). No write contract verified, so read-only for now.
COOKTOP_SAFETY = Capability(
href="/cooktop/settings/status/vs/0",
poll_tier="warm",
@@ -186,7 +178,7 @@ COOKTOP_SAFETY = Capability(
BinarySensorDesc(
key="cooktop_safety_shutoff_enabled",
field="safetyAlert",
entity_category="config",
entity_category="diagnostic",
value_fn=lambda v: (v or {}).get("state") == "on",
),
),
@@ -194,9 +186,8 @@ COOKTOP_SAFETY = Capability(
# Bluetooth meat probe (issue #86). All-idle sentinel values when
# disconnected (operationBurnerNumber -1, temperatures 0) -- no special
# gating on those, matching cooktop.PAIRED_HOOD_STATUS's own precedent of
# showing a disconnected accessory's fields plainly rather than hiding the
# whole capability.
# gating, matching cooktop.PAIRED_HOOD_STATUS's precedent of showing a
# disconnected accessory's fields plainly rather than hiding the capability.
PROBE_STATUS = Capability(
href="/bluetooth/probe/status/vs/0",
poll_tier="warm",
@@ -232,14 +223,12 @@ PROBE_STATUS = Capability(
),
)
# Some range boards (issue #74's NE63B8411SS) report no /cooktop/status/vs/0
# burner array at all -- their local API only exposes this coarse
# monitoring resource for the cooktop half, with no per-burner detail.
# Meaning of `cooktopMonitoring` (a bare "0" on the only dump seen) and
# `warmingCenterState`'s full value set aren't confirmed, so both are
# exposed as plain sensors rather than guessed at as a switch/select --
# `supportedHoodLampStateList` has no corresponding live-state field on
# this resource, so nothing to bind it to yet.
# Some range boards (issue #74) report no /cooktop/status/vs/0 burner
# array at all -- their local API only exposes this coarse monitoring
# resource, with no per-burner detail. Meaning of `cooktopMonitoring`
# (bare "0" on the only dump seen) and `warmingCenterState`'s full value
# set aren't confirmed, so both are plain sensors rather than a guessed
# switch/select.
COOKTOP_MONITORING = Capability(
href="/cooktopmonitoring/vs/0",
poll_tier="warm",
@@ -7,8 +7,6 @@ brightness remain separate controls because the device advertises them as two
independent fields.
"""
from datetime import UTC, datetime
from ..batch import is_stub_rep
from ..capability import Capability
from ..entities import (
@@ -19,14 +17,7 @@ from ..entities import (
SensorDesc,
SwitchDesc,
)
from .common import int_or_none, sensor_item_value
def _timestamp(value):
try:
return datetime.fromtimestamp(float(value), tz=UTC)
except (TypeError, ValueError, OSError):
return None
from .common import epoch_to_utc, int_or_none, sensor_item_value
def _active_alarm_codes(items):
@@ -191,18 +182,13 @@ HOOD_FILTER = Capability(
)
# After Run (issue #147): the hood keeps the fan running at low speed for a
# while after it's switched off, to clear residual cooking smoke -- a
# feature a user actively watches and cancels, not passive diagnostics, so
# none of the three entities below carry entity_category. No
# supported-values list is advertised for activationState, so it's modeled
# read-only (monitoring, not an invented "enable" write) per the 'don't
# guess' rule; runningCancel's only observed value is the command name
# itself ('Cancel'), the same self-describing command-field shape as
# operational.STOP_BUTTON. runningProgress's own name states its domain
# (a percentage of the cycle completed), so it's modeled as one rather than
# left an opaque passthrough -- unlike activationState/runningCancel, there's
# no ambiguous field name or missing-write-contract question here to hedge on.
# After Run (issue #147): the hood keeps the fan running at low speed after
# it's switched off, to clear residual cooking smoke -- a feature a user
# actively watches and cancels, so none of the three entities below carry
# entity_category. No supported-values list is advertised for
# activationState, so it's read-only monitoring rather than an invented
# "enable" write; runningCancel's only observed value is the command name
# itself ('Cancel'), the same shape as operational.STOP_BUTTON.
AFTER_RUN = Capability(
href="/afterrun/vs/0",
poll_tier="warm",
@@ -286,7 +272,7 @@ AIR_LEVEL_CHECK = Capability(
field="x.com.samsung.da.lastSensingTime",
device_class="timestamp",
entity_category="diagnostic",
value_fn=_timestamp,
value_fn=epoch_to_utc,
),
SensorDesc(
key="last_air_sensing_level",
@@ -29,62 +29,33 @@ from .laundry import (
option_write,
)
# ---------------------------------------------------------------------------
# Course_XX hex codes. 23 of the codes named in translations/en.json
# under entity.select.washer_cycle_table_02.state.<id, lowercased> were captured
# from a live WW90DG6U25LEU4's x.com.samsung.da.editCourseList
# (EditCourseList_1C1D211B1E29243328262722202325322F2E30662D8F96), matched
# positionally against a Slovak-UI user's screenshots of their app's course
# list (same order, same count -- see issue #2) and cross-checked against
# the printed user manual's course table (confirming e.g. '8F' as 'Intense
# Cold', not the position-adjacent-looking but distinct 'Mixed Load', a
# cycle the manual marks "applicable models only" and that does not appear
# in this device's editCourseList -- nor does 'AI Wash', also "applicable
# models only"). FixedCourseList_1C29 (the two courses always pinned in the
# app) maps to '1C'/'29' = Eco 40-60 and Drum Clean+, which matches what
# you'd expect to be pinned (default cycle + maintenance cycle),
# corroborating the positional match.
# Course_XX hex code labels (translations/en.json,
# washer_cycle_table_02.state.<id>) come from several devices, cross-checked
# rather than guessed: 23 codes from a live WW90DG6U25LEU4's editCourseList,
# matched positionally against a user's app screenshots and the printed
# manual (issue #2); 5 more (Wash+Dry, Air Wash, Cotton Dry, Synthetics Dry,
# a second distinct '1F' Intense Cold) from a WD90T654DBN/S1 combo's own
# editCourseList and screenshots (issue #22, a combo's own course set, not
# implying anything about a plain washer's '1F'); 3 more (Eco Cold, Towels,
# Self Clean+) verified directly on a WF50A8600AV/US by reading back the raw
# code after selecting each cycle on the appliance (issue #80). Two code
# pairs ('21'/'65' Colors, '27'/'5E' Rinse+Spin, and '24'/'54' Towels)
# legitimately share a label across different course tables -- not typos.
#
# A further 5 codes -- '36' Wash+Dry, '37' Air Wash, '38' Cotton Dry,
# '39' Synthetics Dry, and a second, distinct '1F' Intense Cold (not the
# same code as '8F' above) -- came from a WD90T654DBN/S1 washer/dryer
# combo's editCourseList and were named from that user's app screenshot
# (issue #22). Combo units carry their own course set, so these codes
# don't imply anything about '1F' on a plain washer.
#
# Three more -- '52' Eco Cold, '54' Towels, '60' Self Clean+ -- came from a
# WF50A8600AV/US, verified directly rather than by inference: the reporter
# selected each cycle on the physical appliance and read back the resulting
# raw code from the cycle_select entity's state (issue #80). '54' shares a
# display name with the existing '24' Towels -- a different code on a
# different course table legitimately landing on the same label, not a typo
# (same pattern as '21'/'65' Colors and '27'/'5E' Rinse+Spin above).
#
# No static fallback list of those codes is kept here, deliberately: other
# washer models have a different actual course set (a second dump's active
# course, '65', isn't even in the list above; models with 'AI Wash'/'Mixed
# Load' -- both "applicable models only" per the manual -- would have yet
# another set), so hardcoding one device's list would show/hide the wrong
# options on a different model. laundry.cycle_options() reads only the live
# x.com.samsung.da.editCourseList; if a device doesn't populate that
# resource, the cycle select isn't created at all (see cycle_select's
# exists_fn). x.com.samsung.da.options' MostUsed_* entry was considered as a
# fallback source (its first byte reliably equals the currently-selected
# Course_XX on both dumps we have), but the bytes after that don't
# correspond to any confirmed course code on either device -- e.g. dump 1's
# MostUsed_1C8410923FA67F00000000000000 decodes to
# ['1C','84','10','92','3F','A6','7F',...] and only '1C' is a real code --
# so it isn't trustworthy as a list of selectable courses and isn't used.
# ---------------------------------------------------------------------------
# No static fallback list is kept here: other models have different actual
# course sets, so hardcoding one device's list would show/hide the wrong
# options elsewhere. laundry.cycle_options() reads only the live
# x.com.samsung.da.editCourseList; a device that doesn't populate it gets no
# cycle select at all (see cycle_select's exists_fn). x.com.samsung.da.
# options' MostUsed_* entry was considered as a fallback source (its first
# byte matches the selected Course_XX on both dumps), but the remaining
# bytes don't decode to any confirmed course code, so it isn't used.
# ---------------------------------------------------------------------------
# /washer/vs/0 -- wash temperature, spin speed, rinse cycle count
#
# /washer/vs/0 -- wash temperature, spin speed, rinse cycle count.
# Despite the shared href, this is unrelated to dryer.DRYER_SETTINGS (also
# bound to '/washer/vs/0') -- an artifact of Samsung reusing the same OCF
# path for different device families. Only one of the two ever binds for a
# given device, since dryer and washer are separate by_type registries.
# ---------------------------------------------------------------------------
WASHER_SETTINGS = Capability(
href="/washer/vs/0",
@@ -123,9 +94,8 @@ WASHER_SETTINGS = Capability(
),
),
# Washer/dryer combo units carry a dryLevel field on the wash
# resource itself (no separate dryer device/course) -- see issue
# #22. Self-gates off on plain washers, which never report
# supportedDryLevel.
# resource itself (issue #22). Self-gates off on plain washers,
# which never report supportedDryLevel.
SelectDesc(
key="dry_level",
field="x.com.samsung.da.dryLevel",
@@ -142,12 +112,9 @@ WASHER_SETTINGS = Capability(
),
)
# ---------------------------------------------------------------------------
# /course/vs/0 -- the cycle select is the shared laundry.cycle_select; the
# drum-clean and dispenser-dosing entities below are washer-specific reads off
# the same options array.
# ---------------------------------------------------------------------------
# drum-clean and dispenser-dosing entities below are washer-specific reads
# off the same options array.
# Drum Clean+ maintenance tracking (issue #9): drum_clean_cycles_remaining/
# drum_clean_last_cleaned live in laundry.py, shared with dryer.py (issue
@@ -157,30 +124,17 @@ WASHER_SETTINGS = Capability(
# Detergent/softener auto-dispense dosing, from the same options[] array
# (issue #9). '<Prefix>LevelCtrl_<code>' is the selected dose quantity;
# '<Prefix>Level2Ctrl_<code>' is a second dial -- water hardness for
# detergent, concentration for softener -- matching the SmartThings app's
# two-field dispenser screens ("Distributeur de lessive": Quantité + Dureté
# de l'eau; "Distributeur d'adoucissant": Quantité + Concentration, per
# issue #9's screenshots). 'Supported<Prefix>Ctrl_<hexpairs>' lists the
# valid raw codes for its field, same hex-pair shape as EditCourseList.
# '<Prefix>Alarm_<On/Off>' is a low-reservoir warning flag.
# '<Prefix>Level2Ctrl_<code>' is a second dial (water hardness for
# detergent, concentration for softener), matching the app's two-field
# dispenser screens. 'Supported<Prefix>Ctrl_<hexpairs>' lists the valid raw
# codes, same hex-pair shape as EditCourseList. '<Prefix>Alarm_<On/Off>' is
# a low-reservoir warning flag.
#
# Label mapping (entity.select.{detergent,softener}_quantity /
# detergent_water_hardness / softener_concentration in translations/en.json) is an
# assumed, not cross-device-verified, reading of the single issue #9 dump +
# screenshots: LevelCtrl's 4 codes as None/Low/Medium/High (00 has no
# on-screen equivalent -- the app's Quantité picker only offers
# Faible/Moyen/Élevé, i.e. codes 01-03; 00 is assumed to be what
# "Activation" off collapses to) matches DetergentLevelCtrl_3/
# SoftenerLevelCtrl_3 = "Élevé" on both dispensers. Level2Ctrl's 3 codes as
# Soft/Medium/Hard for detergent (Dureté de l'eau: Douce/Moyenne/Dure)
# matches DetergentLevel2Ctrl_2 = "Moyenne". The same 3-code shape as
# 1x/2x/3x for softener concentration does *not* cleanly match
# SoftenerLevel2Ctrl_2 against the screenshot's "3x" -- assumed to be a
# setting the user changed in the app between the dump (issue body) and the
# screenshots (a later comment), not a different code scheme, since it's
# otherwise identical in shape to the detergent side. Revisit if a second
# device's dump contradicts this.
# Label mapping (translations/en.json's {detergent,softener}_quantity /
# detergent_water_hardness / softener_concentration) is an assumed reading
# of the single issue #9 dump + screenshots, cross-checked against the
# selected value on both dispensers, not independently verified per code --
# revisit if a second device's dump contradicts it.
def _supported_level_options(resources, prefix):
rep = resources.get("/course/vs/0") or {}
raw = option_value(rep.get("x.com.samsung.da.options"), f"Supported{prefix}")
@@ -192,15 +146,13 @@ def _level_options(prefix):
def _dosing_level(prefix):
"""Current dose code, normalized to the `Supported<prefix>` code format.
The device reports the selected level as `<prefix>_<code>` with the code
un-padded (e.g. '3'), but the valid codes -- which are also this select's
options and its translation keys -- come from `Supported<prefix>_<hexpairs>`
as zero-padded hex pairs (e.g. '03'). Left as '3', the current value sits
outside the select's own option list, so HA renders it 'unknown' (issue #9).
Resolve it to the supported code with the same integer value so
current_option matches an option (and its translation)."""
"""Current dose code, normalized to the `Supported<prefix>` code
format. The device reports the selected level as `<prefix>_<code>`
un-padded (e.g. '3'), but the select's own options come from
`Supported<prefix>_<hexpairs>` as zero-padded hex pairs (e.g. '03').
Left as '3', the value sits outside the select's own option list and
HA renders it 'unknown' (issue #9) -- resolve it to the matching
zero-padded code instead."""
def fn(rep):
opts = rep.get("x.com.samsung.da.options")
@@ -227,9 +179,8 @@ def _level_write(prefix):
def write(p, rep, href=None):
if not rep.get("x.com.samsung.da.options"):
return None
# `p` is the zero-padded supported code the UI selected (e.g. '03');
# the device stores the level un-padded (e.g. '3'), matching how it
# reports it, so write it back in that native shape.
# `p` is the zero-padded supported code (e.g. '03'); the device
# stores it un-padded (e.g. '3'), matching how it's reported.
try:
native = format(int(p, 16), "X")
except (TypeError, ValueError):
@@ -248,37 +199,28 @@ def _dosing_low(prefix):
# Bubble soak / pre-wash / intensive-wash toggles, from the same options[]
# array (issue #22 follow-up on a WD90T654DBN/S1 combo). Each rides as a
# plain '<Prefix>_On'/'<Prefix>_Off' token, confirmed by a dump taken with
# Bubble Soak switched on in the app (BubbleSoak_On) -- the same On/Off shape
# already used by AiOption and KidsLockBypass in this same array, so
# PreWashSetting/IntensiveSetting are assumed to follow suit.
# array (issue #22 follow-up). Each rides as a plain '<Prefix>_On'/'_Off'
# token, confirmed against a dump taken with Bubble Soak switched on in the
# app -- the same shape as AiOption/KidsLockBypass in this array.
#
# Each also has a differently-named hex-pair availability field that lines up
# positionally with editCourseList: BubbleSoakSet, PreWashAvailableSet,
# IntensiveAvailableSet. On the reporter's dump (course '30' at position 1 of
# 24), all three read 'F0' at that position and the toggle was writable --
# and the same dump's earlier state (course '1C' at position 0, 'BubbleSoak
# Off') decodes to '00' for that course, matching the app graying the
# control out there. 'F0'/'00' is treated as available/unavailable on that
# evidence. exists_fn (device-level presence) still only runs once, against
# the setup-time snapshot, so it isn't a fit for this per-course check --
# validate_fn runs on every write attempt instead (dispatched from
# coordinator.async_send_command, ahead of write_fn), rejecting an on-write
# for a course whose byte isn't 'F0' with a user-facing error rather than
# silently no-opping against the device. The read/write/presence machinery
# itself is laundry.bool_option_switch, shared with dishwasher's storm-wash/
# auto-release-dry toggles -- only this per-course gating is washer-only, so
# it stays here rather than in laundry.py (see laundry.bool_option_switch's
# docstring: it takes a prebuilt validate_fn and has no opinion on it).
# Each also has a hex-pair availability field positional with
# editCourseList (BubbleSoakSet, PreWashAvailableSet,
# IntensiveAvailableSet): on the reporter's dump 'F0' at a course's
# position matched the app enabling the control there, '00' matched it
# grayed out. exists_fn only runs once at setup, so it can't do this
# per-course check -- validate_fn runs on every write attempt instead,
# rejecting an on-write for a course whose byte isn't 'F0' with a
# user-facing error rather than silently no-opping. The read/write/
# presence machinery is laundry.bool_option_switch, shared with
# dishwasher's storm-wash/auto-release-dry toggles; only this per-course
# gating is washer-only.
def _bool_option_switch(key, icon, prefix, availability_field):
def validate(p, rep, resources):
"""Reject turning on when the selected course's byte in
`availability_field` isn't 'F0'. Turning off is never blocked. Falls
back to allowing the write whenever the availability data can't be
resolved (unrecognized course, missing/mismatched-length bitmap)
rather than guessing -- a false rejection is worse than an
occasional no-op write."""
`availability_field` isn't 'F0'. Turning off is never blocked.
Falls back to allowing the write whenever the availability data
can't be resolved (unrecognized course, missing/mismatched-length
bitmap) -- a false rejection is worse than an occasional no-op."""
if p != "On":
return None
opts = rep.get("x.com.samsung.da.options") or []
@@ -25,19 +25,13 @@ DISPENSE = Capability(
{"x.com.samsung.da.desiredType": p},
),
),
# Only a handful of discrete temperatures are selectable (not a
# continuous range) -- a select over the live-reported set, not a
# number with invented bounds.
#
# Newer boards (issue #196, RWP70F15ANW) don't populate
# supportedHotTemperatures at all -- they report a hotwaterRange
# (min/max) and a hotwaterLevel (step count?) instead, with no
# confirmed write contract for values off the old preset list. With
# an empty options_field result, HA's current_option still returns
# the live tempDesiredHotWater, which isn't in the (empty) options
# list and renders as "unknown" -- the exact symptom reported. Gate
# the entity off entirely when the board doesn't report a supported
# list, rather than guess at hotwaterRange/hotwaterLevel's meaning.
# Only a handful of discrete temperatures are selectable -- a select
# over the live-reported set, not a number with invented bounds.
# Newer boards (issue #196) don't populate supportedHotTemperatures
# at all, reporting a hotwaterRange/hotwaterLevel pair instead with
# no confirmed write contract -- gate the entity off entirely there
# rather than guess at that pair's meaning (an empty options list
# otherwise left current_option rendering "unknown").
SelectDesc(
key="hot_water_temperature",
field="x.com.samsung.da.tempDesiredHotWater",
@@ -53,12 +47,10 @@ DISPENSE = Capability(
),
),
# Bounds and step come live from the device's own
# desiredCapacityRange/capacityResolution fields, not a hardcoded
# constant -- see the adding-device-support skill's "never hard-code
# the one dump's values" section. No unit is set: capacityUnit reads
# "C" on this dump, which can't be right for a volume field, so per
# the 'don't guess' rule the unit is left unset rather than assumed
# to be mL.
# desiredCapacityRange/capacityResolution, not a hardcoded constant.
# No unit is set: capacityUnit reads "C" on this dump, which can't
# be right for a volume field, so it's left unset rather than
# assumed to be mL.
NumberDesc(
key="dispense_capacity",
field="x.com.samsung.da.desiredCapacity",
@@ -159,24 +151,16 @@ FAVORITE_CAPACITY = Capability(
),
)
# Coffee-capable variant (issue #107) -- a "favorite" supported-list select
# for the hot water dispensed alongside brewing, same shape as
# FAVORITE_CAPACITY above.
def _status_lock_definitely_lacks_hotwater_field(resources: dict) -> bool:
"""Three-way read of /status/lock/vs/0's hotwaterLock field, favouring
"""Three-way read of /status/lock/vs/0's hotwaterLock field, favoring
LOCK.hotwater_lock (the primary descriptor) whenever the outcome is
still ambiguous:
- href entirely absent from this device -> definitely no clash, the
switchHotwater fallback below may claim the entity.
- href present but an unfetched stub ({}) -> outcome pending, *not* a
confirmed absence. LOCK's own exists_fn optimistically includes itself
through a stub (matching entity.py's default), so returning True here
too would register both descriptors -- as SwitchDescs sharing one key,
with identical unique_ids -- until the next poll resolves it.
- href present and fetched -> the real answer."""
still ambiguous: href absent -> True (fallback may claim the entity);
href present but an unfetched stub ({}) -> False (pending, not
confirmed absence -- LOCK's own exists_fn optimistically includes
itself through a stub too, so returning True would register both
descriptors under one key until the next poll); href present and
fetched -> the real answer."""
rep = resources.get("/status/lock/vs/0")
if rep is None:
return True
@@ -189,24 +173,15 @@ FAVORITE_HOTWATER = Capability(
href="/favorite/hotwater/vs/0",
poll_tier="cold",
entities=(
# Despite the resource/field naming, switchHotwater's value domain is
# Locked/Unlocked, not an enable flag (issue #144) -- it's the same
# hot-water lock as LOCK.hotwater_lock below, just surfaced through
# this href on boards that don't populate /status/lock/vs/0's
# hotwaterLock field. Shares that descriptor's key so only one "Hot
# water lock" entity ever appears.
#
# Both halves of this fallback pair need an exists_fn, not just this
# one: adapter.flatten() (the coordinator.data source every entity's
# is_on reads) only ever honours exists_fn, never entity.py's
# implicit "require own field present" default that gates plain
# registration. Two same-keyed descriptors with only one of them
# gated still both land in flatten()'s output dict -- whichever is
# processed last silently wins, decided by device-reported href
# order, not by which one is actually correct. So this exists_fn
# also re-asserts its own field's presence (switchHotwater), the
# gate a bare `field=` used to get for free before it had to share a
# key with LOCK's descriptor.
# Despite the naming, switchHotwater's value domain is
# Locked/Unlocked, not an enable flag (issue #144) -- the same
# hot-water lock as LOCK.hotwater_lock below, surfaced through this
# href on boards that don't populate /status/lock/vs/0's
# hotwaterLock. Shares that descriptor's key so only one "Hot water
# lock" entity appears; both halves need an exists_fn since
# adapter.flatten() only ever honors exists_fn, not entity.py's
# implicit field-presence default -- without it, whichever
# same-keyed descriptor is processed last would silently win.
SwitchDesc(
key="hotwater_lock",
field="x.com.samsung.da.switchHotwater",
@@ -222,18 +197,12 @@ FAVORITE_HOTWATER = Capability(
{"x.com.samsung.da.switchHotwater": "Locked" if p == "On" else "Unlocked"},
),
),
# Issue #196: `supportedList` is only the four *fixed* presets
# (e.g. ['40', '75', '85', '90']) -- the SmartThings app also lets
# the user add one custom value to their own display list via its
# "temperatures to display" editor (a wheel picker bounded by
# /setting/waterpurifier/vs/0's hotwaterRange, separate resource),
# and that custom value shows up in `showList`
# (['40', '50', '75', '85', '90'] here) but never in
# `supportedList`. Reading options from `supportedList` meant a
# unit whose current default *was* that custom value rendered as
# "unknown" -- not a coverage gap, just the wrong field. `showList`
# is a superset of `supportedList` that always includes whatever
# the current default actually is, custom or not.
# Issue #196: `supportedList` is only the four fixed presets -- the
# app also lets the user add one custom value to their own display
# list, which shows up in `showList` but never in `supportedList`.
# Reading from `supportedList` meant a unit whose current default
# was that custom value rendered as "unknown"; `showList` is a
# superset that always includes the actual current default.
SelectDesc(
key="favorite_hotwater_temperature",
field="x.com.samsung.da.favorite.defaultTemperature",
@@ -291,11 +260,9 @@ CUP_STATE = Capability(
)
# Sound mode/output/volume (issue #196). Shapes echo laundry.py/
# air_purifier.py's same-named hrefs, but this board's own values differ
# from both (supportedModes here is voice/fixedTone/mute, not laundry's
# voice/tone/mute nor air_purifier's mute/buzzer) -- reusing either would
# reject a live-supported value, so these read the device's own supported
# list/range like air_purifier's versions do.
# air_purifier.py's same-named hrefs, but this board's own supportedModes
# (voice/fixedTone/mute) differs from both, so these read the device's own
# supported list/range rather than reusing either.
SOUND_MODE = Capability(
href="/settings/sound/mode/vs/0",
poll_tier="cold",
@@ -359,9 +326,8 @@ SOUND_VOLUME = Capability(
)
# Last-pour statistics (issue #196). last.capacity's unit isn't confirmed
# (no sibling unit field on this resource, unlike DISPENSE.dispense_capacity
# which at least has an -- albeit suspect -- capacityUnit) so it's left
# unitless rather than assumed to be mL.
# (no sibling unit field on this resource) so it's left unitless rather
# than assumed to be mL.
STATISTIC_POUR = Capability(
href="/statistic/pour/vs/0",
poll_tier="cold",
@@ -387,12 +353,8 @@ LOCK = Capability(
poll_tier="warm",
entities=(
# Shares its key with FAVORITE_HOTWATER's switchHotwater fallback
# above (issue #144); see the comment there for why this half also
# needs an explicit exists_fn now that the two share a key in
# adapter.flatten()'s output. A stub rep ({}) still counts as
# "present" here (matches entity.py's own default for a field-less
# gate) since the alternative -- treating an unfetched resource as
# confirmed-absent -- is what let both descriptors register at once.
# above (issue #144); see the comment there. A stub rep ({}) still
# counts as "present" here, matching entity.py's own default.
SwitchDesc(
key="hotwater_lock",
field="x.com.samsung.da.hotwaterLock",
@@ -430,29 +392,21 @@ LOCK = Capability(
),
)
# ---------------------------------------------------------------------------
# Water-purifier-scoped coverage: hrefs with no user-actionable state or no
# confirmed contract, following the 'don't guess' rule.
# ---------------------------------------------------------------------------
_WP_IGNORED = [
# supportedModes carries a single opaque wizard-workflow token
# ('HOMECARE_WIZARD_V2') and modes reports a completely different,
# unrelated value ('WATERFILTER_DISABLE') not even present in
# supportedModes -- internal plumbing, not a real user-facing mode
# select. OCF-standard /mode/0 mirrors the same vendor resource but is
# already covered by the global ignored.IGNORED (fridge's OCF-native
# vacation-mode flag shares that href).
# supportedModes carries a single opaque wizard-workflow token and
# modes reports an unrelated value not even in supportedModes --
# internal plumbing, not a real mode select.
"/mode/vs/0",
# Static support-flags blob (automation.supported.modes/options) -- no
# live "current automation setting" field to expose.
# Static support-flags blob -- no live "current setting" field.
"/automation/waterpurifier/vs/0",
# Coffee-capable variant (issue #107). All four are static
# capability-advertisement blobs or empty -- no live "current recipe" /
# "current custom slot" field to expose, unlike /favorite/coffee/vs/0
# (COFFEE above), which does carry live brew status.
# Coffee-capable variant (issue #107): static capability-advertisement
# blobs or empty, unlike /favorite/coffee/vs/0 (COFFEE above) which
# does carry live brew status.
"/brand/recipe/info/vs/0", # revision + max-brand-count metadata
"/coffee/custom/recipe/vs/0", # publisher.support: allowed custom-recipe slot IDs
"/recipe/coffee/vs/0", # same publisher.support shape, no per-recipe content
"/coffee/custom/recipe/vs/0", # allowed custom-recipe slot IDs
"/recipe/coffee/vs/0", # same shape, no per-recipe content
"/recipe/coffee/deletion/vs/0", # empty {} on this dump
]
@@ -31,10 +31,9 @@ class BoundEntity:
key_override: str | None = None
instance_name: str | None = None
# Which logical indoor subdevice (issue #177) this entity belongs to.
# `href` above is always the *actual*, on-the-wire href for that
# subdevice -- MAIN's
# to_actual is the identity transform, so every device with no subdevices
# behaves exactly as before this field existed.
# `href` above is always the actual, on-the-wire href for that
# subdevice -- MAIN's to_actual is the identity transform, so a device
# with no subdevices is unaffected.
subdevice: Subdevice = MAIN
@@ -101,24 +100,19 @@ def discover(
tier_log: Callable[[str, str], None] | None = None,
subdevice: Subdevice = MAIN,
) -> list[BoundEntity]:
"""`tier_log(href, poll_tier)` fires for every href a capability actually
matches, even a no-entity "coverage-only" capability (see COVERAGE lists
in capabilities/*.py) that `_bind()` turns into zero `BoundEntity` rows.
Callers that need a href's poll cadence (the coordinator's hot/warm
sub-poll and OBSERVE-attempt lists) must use this, not `bound` -- a
coverage-only capability's `poll_tier` would otherwise be silently
dropped since it never appears in `bound`.
"""`tier_log(href, poll_tier)` fires for every href a capability
actually matches, even a no-entity "coverage-only" capability that
`_bind()` turns into zero `BoundEntity` rows. Callers that need a
href's poll cadence must use this, not `bound` -- a coverage-only
capability's `poll_tier` would otherwise never appear in `bound`.
`resources` is always keyed by *canonical* hrefs -- for a subdevice
(issue #177) that means its own canonical view (see
subdevices.canonical_view), the same shape as a plain single-subdevice
device's resources dict, so registry lookups/rt_filter/match_fn/
instance_suffix all behave identically regardless of which subdevice is
being discovered.
`subdevice` only affects the *href* stamped onto each BoundEntity (via
`_bind`, see above) and the href `log`/`tier_log` report -- both the
real, subscribable/pollable path, not the canonical one the registry is
keyed on.
`resources` is always keyed by canonical hrefs -- for a subdevice
(issue #177), its own canonical view (see subdevices.canonical_view),
the same shape as a single-subdevice device's resources dict, so
registry lookups behave identically regardless of which subdevice is
being discovered. `subdevice` only affects the href stamped onto each
BoundEntity and the href `log`/`tier_log` report -- the real,
subscribable/pollable path, not the canonical one.
"""
out: list[BoundEntity] = []
@@ -33,10 +33,10 @@ class SamsungEntityDescription:
# here, so a descriptor only sets this to share one catalog entry across
# several descriptors, or to point at a differently-named one.
translation_key: Any = None # str | Callable[[dict[str, dict]], Optional[str]]
# callable form receives the coordinator's full href->rep resource
# snapshot and returns the key to use -- for a descriptor shared across
# board generations whose state-code meaning isn't guaranteed consistent
# between them; see laundry.cycle_select's table-id-gated resolver.
# callable form receives the full href->rep snapshot and returns the key
# to use -- for a descriptor shared across board generations whose
# state-code meaning isn't consistent between them; see
# laundry.cycle_select's table-id-gated resolver.
translation_placeholders: Mapping[str, str] | None = None
# Dynamic resources such as fridge compartments and ice makers use a
# device-provided or href-derived instance label inside a translated name.
@@ -59,10 +59,9 @@ class SensorDesc(SamsungEntityDescription):
unit: str | None = None
unit_fn: Callable[[dict], str] | None = None # overrides `unit` from the live rep, when set
options: tuple | None = None # required by HA when device_class == 'enum'
# Opt-in: gate this sensor's reported value behind the user-configurable
# CONF_FINISH_TIME_HYSTERESIS_MINUTES threshold (see sensor.py). Only for
# values that are expected to jitter around their "true" value between
# device-side revisions -- not a general-purpose flag every sensor should set.
# Opt-in: gate this value behind CONF_FINISH_TIME_HYSTERESIS_MINUTES
# (see sensor.py). Only for values expected to jitter between
# device-side revisions -- not a general-purpose flag.
hysteresis: bool = False
@@ -102,10 +101,9 @@ class NumberDesc(SamsungEntityDescription):
native_min: float | None = None
native_max: float | None = None
step: float | None = None
# Override native_min/native_max/step from the live rep, when set --
# same "static default, live override" shape as unit_fn, for resources
# whose sane bounds depend on a per-device value (e.g. a temperature
# setpoint reported in Celsius on one device, Fahrenheit on another).
# Override native_min/max/step from the live rep, when set -- same
# "static default, live override" shape as unit_fn, for resources whose
# bounds depend on a per-device value (e.g. Celsius vs. Fahrenheit).
native_min_fn: Callable[[dict], float] | None = None
native_max_fn: Callable[[dict], float] | None = None
step_fn: Callable[[dict], float] | None = None
@@ -120,27 +118,23 @@ class TimeDesc(SamsungEntityDescription):
@dataclass(frozen=True, kw_only=True)
class ClimateDesc(SamsungEntityDescription):
# A composite entity: it binds one *primary* resource (its href) but the
# climate platform reads sibling resources (power, temperature, wind) from
# the coordinator snapshot and writes to several of them. write_fn takes a
# (kind, value) payload from the platform and returns the (path_segs, body)
# for that one sub-write, so a single desc drives multi-resource writes.
# Composite entity: binds one primary resource (its href) but the
# climate platform reads sibling resources from the coordinator
# snapshot and writes to several of them. write_fn takes a (kind,
# value) payload and returns the (path_segs, body) for that sub-write.
write_fn: WriteFn = None
@dataclass(frozen=True, kw_only=True)
class FanDesc(SamsungEntityDescription):
# Composite fan entity: reads power from /power/0 and speed/support data
# from its bound href. Payloads are (kind, value), like ClimateDesc.
# from its bound href. Payloads are (kind, value), like ClimateDesc.
write_fn: WriteFn = None
@dataclass(frozen=True, kw_only=True)
class WaterHeaterDesc(SamsungEntityDescription):
# Composite water_heater entity: binds one primary resource (its href,
# typically an operation-mode resource) but the water_heater platform
# reads sibling resources (power, temperature) from the coordinator
# snapshot and writes to several of them. Same (kind, value) -> (path_segs,
# Composite water_heater entity, same (kind, value) -> (path_segs,
# body) write_fn shape as ClimateDesc/FanDesc.
write_fn: WriteFn = None
@@ -17,6 +17,71 @@ 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 two such units on the same install silently
collide, dropping the second one's entities (issue #83).
Issue #189: the DA_WM_A51_20_COMMON (ARTIK051) laundry family reports a
flash-unset sentinel instead -- every character the same repeated hex
digit -- which the 'nothing' check doesn't catch either, aborting the
second unit's config flow as already configured.
Lives here rather than duplicated in config_flow.py/coordinator.py: the
config flow resolves the serial once and persists it for the
coordinator to seed its registry keys from (issue #236), so two copies
of this rule could let the two sides disagree and orphan 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 resolve_model(model_num: str, identity: DeviceIdentity | None) -> str:
"""The model string to name and register a device under.
`model_num` is /information/vs/0's modelNum, which many boards report
as `<model>|<board>` -- only the part before the pipe is recognizable.
A board reporting no modelNum falls back to /oic/p's mnmo. Shared with
resolve_serial's motivation: two copies of this split rule could let
the config flow and the coordinator's post-poll recompute disagree, and
a device renaming itself after the first poll is the visible symptom.
"""
if model_num:
return model_num.split("|", 1)[0]
return identity.model if identity else ""
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 and the coordinator's post-discovery rebuild, so the name a
device is first registered under matches what discovery produces 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)
@@ -45,15 +110,13 @@ def _get_links(sess, path) -> list:
def _device_types(d: dict) -> tuple[str, ...]:
"""/oic/d's `rt` -- the device's own OCF device-type declaration.
In OCF this is the one standardized "what am I" field: alongside the
generic 'oic.wk.d' it carries a concrete type such as 'oic.d.airconditioner'
or a SmartThings 'x.com.st.d.*' equivalent. `registry/by_type/resolve()`
now consults this first, ahead of board-part-number parsing, via
`for_device_by_oic_type` and its `_OIC_TYPE_TO_KEY` table -- but only a
minority of dumps populate it, so the modelNum/description path stays
load-bearing for everything else. It's also kept whole in diagnostics
(see `raw` below) so incoming issue reports keep surfacing types that
table doesn't know about yet.
The one standardized "what am I" field in OCF: alongside the generic
'oic.wk.d' it carries a concrete type like 'oic.d.airconditioner' or a
SmartThings 'x.com.st.d.*' equivalent. `registry/by_type/resolve()`
consults this first, via `for_device_by_oic_type`, but only a minority
of dumps populate it, so the modelNum/description path stays
load-bearing. Kept whole in diagnostics (see `raw` below) so issue
reports keep surfacing types the table doesn't know about yet.
"""
rt = d.get("rt")
if isinstance(rt, str):
@@ -67,17 +130,13 @@ def read_identity(sess, serial: str | None) -> DeviceIdentity:
p = _get(sess, ["oic", "p"])
d = _get(sess, ["oic", "d"])
# /oic/res is OCF's baseline resource-discovery endpoint: a unicast
# RETRIEVE on it returns every Resource/Collection href this endpoint
# hosts, not just the one /device/0 seed path the coordinator polls.
# Relevant for the OCF "Composite Device" model (issue #177: a single
# physical device -- one IP, one /oic/p -- exposing more than one logical
# subdevice, each as its own Collection resource, same rt shape as our own
# /device/0). This is what registry.subdevices.enumerate_subdevices reads
# to find a board's `/device/<n>` siblings (Pattern A -- the reporter's
# ARTIK051_DONGLE_FAC_18K) -- that probing, plus the /device/1 and
# /device/2 speculative fallback it used to run right here on every
# _connect_session (including every reconnect), moved to that module so
# it only runs once, at first discovery, instead of on every reconnect.
# RETRIEVE returns every Resource/Collection href this endpoint hosts,
# not just /device/0. Relevant for the "Composite Device" model (issue
# #177: one physical device exposing more than one logical subdevice,
# each its own Collection). registry.subdevices.enumerate_subdevices
# reads this to find a board's `/device/<n>` siblings -- that probing
# used to run right here on every _connect_session/reconnect and moved
# to that module so it only runs once, at first discovery.
res = _get_links(sess, ["oic", "res"])
return DeviceIdentity(
manufacturer=p.get("mnmn") or "Samsung",
@@ -85,8 +144,8 @@ def read_identity(sess, serial: str | None) -> DeviceIdentity:
name=d.get("n") or "",
serial=serial,
device_types=_device_types(d),
# Kept whole rather than field-by-field: these resources are outside
# the /device/0 dump diagnostics already captures, and we don't yet
# know which of their fields will turn out to identify a device type.
# Kept whole rather than field-by-field: outside the /device/0 dump
# diagnostics already captures, and we don't yet know which fields
# will turn out to identify a device type.
raw={"/oic/p": p, "/oic/d": d, "/oic/res": res},
)
@@ -30,19 +30,12 @@ _SENSITIVE_SUBSTRINGS = (
"secret",
)
# Matched whole, not as substrings. OCF's /oic/d and /oic/p identify the unit
# with bare one- and two-letter keys that the rules above cannot see, being
# far too short to match on -- 'di' alone is a substring of 'condition',
# 'display', 'dispenser' and plenty of other ordinary appliance fields:
#
# 'di' -- device UUID, 'pi' -- platform UUID. As identifying as the serial
# number above.
# 'n' -- /oic/d's device name. Free text the owner can set from the
# SmartThings app, so it may well carry a person's name. Nothing
# in the /device/0 dump has ever exposed it; it only became
# reachable when diagnostics started reporting /oic/d, and the
# device-type signal we actually want from that resource is `rt`,
# which is not redacted.
# Matched whole, not as substrings: OCF's /oic/d and /oic/p identify the
# unit with bare one/two-letter keys too short for the substring rules above
# ('di' is a substring of 'condition', 'display', ...). 'di'/'pi' are the
# device/platform UUIDs; 'n' is /oic/d's free-text device name, which may
# carry a person's name -- the device-type signal we actually want from
# that resource is `rt`, which is not redacted.
_SENSITIVE_EXACT = frozenset({"di", "pi", "n"})
@@ -1,90 +1,36 @@
"""Subdevice ("composite device") support for one physical connection exposing
more than one logical indoor subdevice -- issue #177.
"""Subdevice ("composite device") support for one physical connection
exposing more than one logical indoor subdevice -- issue #177.
Two reporters, two different board families, two genuinely different
mechanisms for exposing a second indoor subdevice over one IP / one DTLS
session (see DESIGN-177.md section 1 for the full evidence trail; the two
diagnostics dumps this was built against come from the Pattern A and
Pattern B reporters, respectively -- they each filed one of the two
reports this module unifies):
Three discovery patterns, unified by the same shape: a logical subdevice is
a seed collection path to poll, plus an href transform between the
canonical href the registry knows (e.g. `/mode/vs/0`) and the actual
on-the-wire href.
Pattern A -- indexed siblings (`ARTIK051_DONGLE_FAC_18K`, that reporter's
board). `/oic/res` lists three complete parallel resource sets whose
trailing path segment is the index (`/mode/vs/0`, `/mode/vs/1`,
`/mode/vs/2`, ... on both OCF-standard and vendor hrefs), and `/device/0`'s
batch carries only the index-0 hrefs -- the sibling subdevices are
reachable only via their own `/device/<n>` collection.
- **Pattern A -- indexed siblings** (`ARTIK051_DONGLE_FAC_18K`). `/oic/res`
lists parallel resource sets by trailing index (`/mode/vs/0`,
`/mode/vs/1`, ...); each sibling has its own `/device/<n>` Collection.
- **Pattern B -- UUID-prefixed tree** (`TP2X_FAC_BORA_21K`). `/oic/res`
hides the tree; `/subdevices/vs/0`'s `subdeviceIdList` gives the UUID.
`GET /<uuid>/device/0` is tried first; when it comes back empty (issue
#205 -- not even the reference board always exposes it), this falls back
to probing every href the master answered this cycle individually under
the UUID prefix (see `Subdevice.flat_hrefs`).
- **Pattern C -- UUID prefix via `/oic/res` only** (`AWM-WW-AID-26-ONEBODY`
washer+dryer combo, issue #241). No `subdeviceIdList`, `/device/<n>`
404s; the sibling's UUID only appears as a link prefix in `/oic/res`
(e.g. the `x.com.samsung.da.multidevice` link) -- treated as Pattern B's
transform with the UUID sourced from there instead.
Pattern B -- UUID-prefixed tree (`TP2X_FAC_BORA_21K`, that reporter's board).
`/oic/res` hides the whole appliance tree; `/device/0`'s batch instead
carries `x.com.samsung.da.subdeviceIdList` on `/subdevices/vs/0`, and that
same UUID appears as a literal href prefix in `/oic/res`
(`/<uuid>/file/list/vs/0`, ...). What's actually been confirmed live on
that reporter's unit is narrower than early issue #177 writeups suggested: a
single individual `GET /<uuid>/information/vs/0` was read by hand through
the debug panel and came back carrying a different model/serial than the
master (`TP2X_FAC_BORA_RAC_21K`, the wall-mounted subdevice, vs. the
master's `TP2X_FAC_BORA_21K`, the floor subdevice) -- real evidence a
second subdevice exists at that prefix, but not evidence that `GET
/<uuid>/device/0` (the Collection batch PR #199 built this pattern's seed
around) itself returns anything. Issue #205, the same unit on a later
version, is that assumption failing: `/<uuid>/device/0` comes back empty.
So `enumerate_subdevices` tries it first (a future board might genuinely
expose it) and falls back, when it's empty, to probing every href the
master itself answered this cycle individually under the UUID prefix --
the only thing ever actually confirmed to work for this pattern -- on the
assumption that a composite device's siblings share the master's resource
surface. See `Subdevice.flat_hrefs`.
Pattern C -- UUID prefix advertised only via `/oic/res`
(`AWM-WW-AID-26-ONEBODY` washer+dryer combo, issue #241). The board answers
`numofsubdevice='2'` on `/multidevice/vs/0` but has no `/subdevices/vs/0`
(no `subdeviceIdList`) and 4.04s `/device/1`/`/device/2`; the washer
subdevice's UUID appears nowhere except as the path prefix of the
`x.com.samsung.da.multidevice` link in `/oic/res`, and
`GET /<uuid>/device/0` answers the washer's own full Collection batch
(model `..._WF80H` vs. the master's `..._DV80H27H`) -- Pattern B's
transform with the UUID sourced from the link prefix instead of
`subdeviceIdList`.
All of these are "the same thing wearing different clothes": a logical subdevice is a
seed collection path to poll, plus an href transform between the canonical
href the registry knows (`/mode/vs/0`) and the actual on-the-wire href. The
detection signals don't overlap on either captured board (the Pattern A
reporter's has no `/subdevices/vs/0` at all; the Pattern B reporter's has
no `/device/1`), so no disambiguation logic is needed --
`enumerate_subdevices` checks both and materializes any candidate whose
seed answers with a non-empty batch.
A non-empty seed batch is necessary but not sufficient for the *candidate*
to actually be a live second subdevice, though: the Pattern A reporter's
own board also has a `/device/2` -- a third, unused SmartThings slot --
that answers with the exact same 14-href shape as the real `/device/1`
sibling, populated with three constant/echoed/shape-only reps (a region
code identical to every other subdevice's, an /information rep echoing the
*same* model string as subdevice 1, and a /temperatures items[] entry with
an id/description but no current/desired/minimum/maximum reading) and
nothing resembling live climate state. Gating on *resource* shape/hrefs
turned out to be the wrong layer -- it would need per-family domain
knowledge (which hrefs mean "in use" for a washer's second drum, a
fridge's second compartment, ...) baked into a registry field before any
of those families could use this module at all. `discover_partitioned`
instead gates at the *entity* layer, after discovery+flattening: a
candidate is only kept if it produced at least one *primary* (no
`entity_category`), non-meter bound entity whose flattened value isn't
`None` -- e.g. the Pattern A reporter's /device/2 does flatten to an
`alarm_code` value, but that entity is diagnostic-category and derived from
an empty /alarms/vs/2, so it doesn't count. This reuses the same
primary/config/diagnostic taxonomy every registry already declares (see the
adding-device-support skill's entity-taxonomy section) instead of adding a
second, parallel domain-knowledge mechanism.
The meter carve-out is issue #214, and it's the same "an unused slot still
answers *something*" problem one layer further in: that reporter's
single-split ARTIK051_KRAC_18K has a /device/1 whose operational reps are
all empty {} -- the /device/2 shape above -- but which also reports a
populated /energy/consumption/vs/1, a whole-appliance lifetime kWh counter
that materialized the slot as a phantom second air conditioner. See
A non-empty seed batch is necessary but not sufficient for a candidate to
be a real second subdevice: an unused SmartThings slot (e.g. the Pattern A
reporter's own `/device/2`) answers the same shape with constant/echoed
reps and no live state. Gating on resource shape would need per-family
domain knowledge, so `discover_partitioned` instead gates at the *entity*
layer: a candidate is only materialized if it produces at least one live,
non-`None`, primary (no `entity_category`), non-meter bound entity. The
meter exclusion (issue #214) covers a second failure mode: an unused slot
reporting a populated whole-appliance energy counter, which is the
appliance's own bookkeeping, not evidence of a second indoor unit -- see
`_has_live_primary_entity`.
"""
@@ -102,18 +48,15 @@ from .by_type._base import DeviceRegistry
_INDEXED_HREF_RE = re.compile(r"^/device/(\d+)$")
# A UUID as the first path segment of an /oic/res link href -- Pattern C's
# discovery signal (issue #241): a subdevice tree whose UUID is advertised
# nowhere except as this prefix (no subdeviceIdList, no /device/<n>).
# discovery signal (issue #241).
_UUID_PREFIX_RE = re.compile(r"^/([0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})/")
# Speculative /device/<n> siblings probed when /oic/res doesn't reveal a
# second logical subdevice's Collection on this board (moved here from
# identity.py, issue #177 -- see enumerate_subdevices' docstring for why: the
# old read_identity fired these two extra RETRIEVEs on *every* _connect_session,
# including every reconnect, for information enumeration only needs once).
# Same bound as before: a plain, tolerated-404 RETRIEVE, not the kind of
# guess the write-contract 'don't guess' rule is about. Widen only if a real
# board ever turns out to need more than two siblings.
# second subdevice's Collection (moved here from identity.py, issue #177,
# since the old read_identity fired these on every _connect_session
# including reconnects, when enumeration only needs to run once). A plain
# tolerated-404 RETRIEVE, not the kind of guess the write-contract
# 'don't guess' rule is about. Widen only if a board needs more siblings.
_SPECULATIVE_DEVICE_INDICES = (1, 2)
@@ -122,22 +65,20 @@ class Subdevice:
"""One logical indoor subdevice reachable over a single physical
connection.
`kind='main'` is the subdevice this config entry actually connects to and
always exists (see MAIN below) -- its `to_actual`/`to_canonical` are the
identity transform, so every existing single-subdevice device keeps
behaving exactly as it did before this module existed. `'indexed'`/
`'prefixed'` are Pattern A/B above; `key` is the trailing index string
('1', '2', ...) or the full subdevice UUID, and `seed_path` is the
Collection href (as path segments) whose batch response
enumerates/refreshes that subdevice.
`kind='main'` is the subdevice this config entry actually connects to
and always exists (see MAIN below) -- its `to_actual`/`to_canonical`
are the identity transform, so a single-subdevice device behaves
exactly as before this module existed. `'indexed'`/`'prefixed'` are
Pattern A/B above; `key` is the trailing index string ('1', '2', ...)
or the full subdevice UUID, and `seed_path` is the Collection href (as
path segments) whose batch enumerates/refreshes that subdevice.
`flat_hrefs` is non-empty only for a 'prefixed' subdevice that doesn't
expose its own Collection at `seed_path` (issue #205 -- not even
TP2X_FAC_BORA_21K, the board this pattern was built against, always
does). When set, `seed_path` is meaningless (left as `()`) and this
subdevice's state comes from GETting each of these canonical hrefs
individually under its prefix instead of one Collection batch -- see
enumerate_subdevices' fallback and coordinator._poll_subdevice_seed.
`flat_hrefs` is non-empty only for a 'prefixed' subdevice with no
Collection at `seed_path` (issue #205). When set, `seed_path` is
meaningless (left as `()`) and this subdevice's state comes from
GETting each of these canonical hrefs individually under its prefix
instead -- see enumerate_subdevices' fallback and
coordinator._poll_subdevice_seed.
"""
kind: str # 'main' | 'indexed' | 'prefixed'
@@ -150,13 +91,11 @@ class Subdevice:
on-the-wire href for this subdevice."""
if self.kind == "indexed":
head, sep, tail = canonical.rpartition("/")
# Only the index-0 trailing segment is ours to rewrite --
# deliberately not a "replace any trailing digit" rule, which
# would misread a genuine multi-instance resource (the fridge's
# pattern-cap hrefs, e.g. '/door/vs/1') as a subdevice's. No
# registry declares a non-zero trailing index today and no
# fixture in the corpus contains one (verified across the whole
# corpus), so the strict rule costs nothing.
# Only the index-0 trailing segment is ours to rewrite -- not a
# "replace any trailing digit" rule, which would misread a
# genuine multi-instance resource (e.g. the fridge's
# '/door/vs/1') as a subdevice's. No registry declares a
# non-zero trailing index today.
if tail == "0":
return f"{head}{sep}{self.key}"
return canonical
@@ -179,25 +118,24 @@ class Subdevice:
return actual
def owns(self, actual: str) -> bool:
"""True if `actual` belongs to this subdevice's namespace. MAIN never
"owns" anything by this definition -- it gets whatever's left after
every other subdevice's hrefs are excluded (see canonical_view)."""
"""True if `actual` belongs to this subdevice's namespace. MAIN
never "owns" anything by this definition -- it gets whatever's
left after every other subdevice's hrefs are excluded (see
canonical_view)."""
if self.kind == "main":
return False
return self.to_canonical(actual) is not None
@property
def key_prefix(self) -> str:
"""Prefix that guarantees a unique entity key/unique_id (see
adapter._key). '' for MAIN -- the master's flattened state
keys must stay byte-identical to every device this integration
shipped before issue #177, so no golden file changes. The full
subdevice UUID is used verbatim (non-alphanumerics stripped, not
truncated or replaced with an ordinal) because it's device-reported
and stable across reconnects/restarts, unlike an ordinal assigned by
enumeration order -- and it never appears in a user-visible string
(see DESIGN-177.md section 6): HA derives the visible entity_id from
the device name + entity name, not from unique_id.
"""Prefix guaranteeing a unique entity key/unique_id (see
adapter._key). '' for MAIN, so the master's flattened state keys
stay byte-identical to every device shipped before issue #177. The
full subdevice UUID is used verbatim (non-alphanumerics stripped)
rather than an enumeration-order ordinal, since it's device-reported
and stable across reconnects; it never appears in a user-visible
string, since HA derives entity_id from device+entity name, not
unique_id.
"""
if self.kind == "indexed":
return f"subdevice{self.key}_"
@@ -219,16 +157,15 @@ def canonical_view(
canonical namespace -- what discover()/exists_fn/rep_fn/is_legacy_board
and friends are written against.
For MAIN this is the snapshot *minus* every href owned by one of the
other subdevices in `subdevices` -- otherwise a sibling's own `/mode/vs/1`
would leak into the master's view under the same canonical key
('/mode/vs/0') that the master's actual `/mode/vs/0` also maps to,
silently mixing two subdevices' state together. For an indexed/prefixed
subdevice it's the reverse: only the hrefs that subdevice owns, rewritten
back through `to_canonical`.
For MAIN this is the snapshot minus every href owned by one of the
other subdevices in `subdevices` -- otherwise a sibling's own
`/mode/vs/1` would leak into the master's view under the canonical key
('/mode/vs/0') the master's own resource also maps to. For an
indexed/prefixed subdevice it's the reverse: only the hrefs that
subdevice owns, rewritten back through `to_canonical`.
`subdevices` may or may not include MAIN itself -- MAIN.owns() is always
False, so including it is harmless.
`subdevices` may or may not include MAIN itself -- MAIN.owns() is
always False, so including it is harmless.
"""
if subdevice.kind == "main":
owned_elsewhere = {href for href in resources if any(su.owns(href) for su in subdevices)}
@@ -245,11 +182,9 @@ def normalize_seed_batch(subdevice: Subdevice, batch: dict[str, dict]) -> dict[s
normalized so every href actually carries this subdevice's prefix/index.
Indexed subdevices need no change -- the device echoes the real `/x/<n>`
href in its own `/device/<n>` batch (confirmed against the Pattern A
reporter's dump). A prefixed subdevice's batch entries may or may not
already carry the `/<id>` prefix (unconfirmed which -- the Pattern B
reporter's board was never probed live before the subdevice id was
known), so it's added when missing.
href in its own `/device/<n>` batch. A prefixed subdevice's batch
entries may or may not already carry the `/<id>` prefix (unconfirmed),
so it's added when missing.
"""
if subdevice.kind != "prefixed":
return batch
@@ -265,9 +200,8 @@ def _iter_oic_res_hrefs(oic_res):
Both captured dumps group links by `di` (`[{'di': ..., 'links': [...]}]`
-- see identity.py's read_identity/_get_links), so that's the shape
handled here. Tolerant of a flat link-list too (nothing in the OCF spec
rules it out, and _get_links' own posture already treats any list-shaped
body as possible) and of anything else by yielding nothing.
handled here. Tolerant of a flat link-list too, and of anything else by
yielding nothing.
"""
for entry in oic_res or []:
if not isinstance(entry, dict):
@@ -290,8 +224,7 @@ def _seed_href(path_segs: tuple[str, ...]) -> str:
def _get_raw(sess, path_segs: tuple[str, ...]):
"""GET `path_segs` and CBOR-decode the payload, or None on any
missing/malformed response (a 4.04, a timeout, an empty payload) --
shared tolerated-absence posture for both callers below, which differ
only in which body shape they accept."""
shared tolerated-absence posture for both callers below."""
try:
code, pl = sess.get(list(path_segs), timeout=10.0)
if code == 0x45 and pl:
@@ -311,10 +244,8 @@ def _get_batch(sess, path_segs: tuple[str, ...]) -> dict[str, dict]:
def _get_property(sess, path_segs: tuple[str, ...]) -> dict:
"""GET a plain OCF Property-map resource (a bare dict, not a Collection
batch). Used for `/multidevice/vs/0` (issue #177 follow-up): listed in
`/oic/res` on the Pattern A reporter's board but absent from
`/device/0`'s batch, so it needs its own RETRIEVE, and it answers a
single Property map, not a [devcol-rep, ...] list."""
batch). Used for `/multidevice/vs/0`: listed in `/oic/res` but absent
from `/device/0`'s batch, so it needs its own RETRIEVE."""
body = _get_raw(sess, path_segs)
return body if isinstance(body, dict) else {}
@@ -329,34 +260,27 @@ def enumerate_subdevices(
connection.
Runs once, at first discovery, in an executor, under the coordinator's
session lock -- every GET here is a plain RETRIEVE (the write-contract
'don't guess' rule doesn't apply to reading an extra resource to find
out whether it's there). Returns the *candidate* subdevices and the resources
already fetched while probing them (already normalized to real hrefs),
so the coordinator's first discovery poll doesn't need to re-poll them.
session lock -- every GET here is a plain RETRIEVE. Returns the
*candidate* subdevices and the resources already fetched while probing
them (normalized to real hrefs), so the coordinator's first discovery
poll doesn't need to re-poll them.
`probe_log(seed_href, found)` fires for every seed attempted, whether or
not it answered -- so diagnostics (see diagnostics.py's subdevice_probes)
can tell "checked, nothing there" apart from "never checked", the same
posture the speculative-probe code this replaces used to document in
identity.py.
`probe_log(seed_href, found)` fires for every seed attempted, whether
or not it answered, so diagnostics can tell "checked, nothing there"
apart from "never checked".
Every candidate whose seed answers with a non-empty batch is returned
here -- this function has no way to tell a real sibling from an unused
SmartThings slot that merely answers the same shape (the Pattern A
reporter's `/device/2`); that requires discovering+flattening the
candidate's own entities first, which is `discover_partitioned`'s job,
not this one's.
See this module's docstring.
here -- this function can't tell a real sibling from an unused
SmartThings slot that answers the same shape; that requires
discovering+flattening the candidate's own entities first, which is
`discover_partitioned`'s job. See this module's docstring.
"""
subdevices: list[Subdevice] = []
fetched: dict[str, dict] = {}
# Case-insensitive -- the same UUID can reach here once from
# subdeviceIdList and once from an /oic/res link prefix with different
# casing (Samsung's own fields disagree on this elsewhere too, e.g. the
# redaction-prone subdeviceIdList handling below), and probing it twice
# would materialize the same physical subdevice as two Subdevice
# candidates under two different keys.
# casing, and probing it twice would materialize the same physical
# subdevice as two Subdevice candidates.
probed_ids: set[str] = set()
def _probed(seed_href: str, batch: dict) -> None:
@@ -379,29 +303,22 @@ def enumerate_subdevices(
fetched.update(normalize_seed_batch(subdevice, batch))
subdevices.append(subdevice)
return
# Fallback (issue #205): TP2X_FAC_BORA_21K itself -- the board this
# pattern was built against -- turns out not to always expose its own
# `/<uuid>/device/0` Collection either, so "every prefixed subdevice
# has one" doesn't hold even on the reference hardware. With no
# Collection to seed from and no per-UUID entry in `/oic/res` to
# Fallback (issue #205): even the reference TP2X_FAC_BORA_21K board
# doesn't always expose its own `/<uuid>/device/0` Collection. With
# no Collection to seed from and no per-UUID entry in /oic/res to
# enumerate hrefs from, the only signal left is that a composite
# device's siblings are the same physical board family as the
# subdevice this config entry already talks to -- so probe every
# href the master itself answered this cycle, individually, under
# this UUID's prefix, and keep whichever ones answer. Each is a
# plain tolerated-404 RETRIEVE, same posture as every other probe in
# this function.
# device's siblings share the master's own resource surface -- so
# probe every href the master answered this cycle, individually,
# under this UUID's prefix, and keep whichever answer. Each is a
# plain tolerated-404 RETRIEVE.
#
# Known gap, not yet guarded against: a firmware that answers *any*
# request under an unrecognized prefix (echoing the master's own
# state back rather than 4.04ing) would pass every one of these
# probes and, if the echoed state also clears discover_partitioned's
# liveness gate, materialize a phantom duplicate of the master
# rather than a real sibling. Every board seen so far genuinely
# 4.04s on paths it doesn't own (issue #205's own unit answered only
# 1 of 31 probes), so this hasn't been built -- the one place it
# could hook in later is comparing a candidate's confirmed reps
# against the master's own values for those same canonical hrefs.
# Known gap: a firmware that echoes the master's own state back
# under an unrecognized prefix, rather than 4.04ing, would pass
# every probe here and could materialize a phantom duplicate. Every
# board seen so far genuinely 4.04s on paths it doesn't own (issue
# #205's unit answered only 1 of 31 probes), so this hasn't been
# guarded against -- the fix would compare a candidate's confirmed
# reps against the master's own values for the same hrefs.
flat_hrefs = []
first = True
for href in sorted(resources):
@@ -427,35 +344,26 @@ def enumerate_subdevices(
# --- Pattern B: UUID-prefixed tree (TP2X_FAC_BORA_21K) ------------------
raw_ids = (resources.get("/subdevices/vs/0") or {}).get("x.com.samsung.da.subdeviceIdList")
# Tolerate anything but a list of strings -- this field is redaction-prone
# (it matches the 'deviceid' substring rule in redact.py) and the existing
# airconditioner_fac_bora fixture carries the literal string
# '**REDACTED**'/'REDACTED' there. That must yield zero subdevices, not a
# crash -- issue #177 is additive, it must never break an already-working
# single-climate-entity device.
# Tolerate anything but a list of strings -- this field is
# redaction-prone (matches redact.py's 'deviceid' rule) and a shipped
# fixture carries the literal string 'REDACTED' there. That must yield
# zero subdevices, not a crash -- issue #177 is additive and must never
# break an already-working single-climate-entity device.
ids = raw_ids if isinstance(raw_ids, list) else []
listed = sorted(i for i in ids if isinstance(i, str) and i)
for sub_id in listed:
_probe_prefixed(sub_id)
# --- Pattern C: UUID prefix advertised only via /oic/res ----------------
# (AWM-WW-AID-26-ONEBODY washer+dryer combo, issue #241.) A third
# multidevice shape: the board answers numofsubdevice='2' on
# /multidevice/vs/0, but carries no /subdevices/vs/0 (no subdeviceIdList
# -- Pattern B's signal) and 4.04s /device/1 and /device/2 (Pattern A's).
# The only trace of the sibling is a UUID-prefixed link in /oic/res
# itself: the x.com.samsung.da.multidevice link,
# '/<uuid>/multidevice/vs/0' on the reporting board. Its washer tree
# answers a full Collection at /<uuid>/device/0, exactly Pattern B's
# transform -- so treat every UUID path prefix seen in /oic/res as a
# prefixed-subdevice candidate. Probing is the same tolerated-404
# RETRIEVE as everything else here, and discover_partitioned's
# entity-level liveness gate still decides materialization, so a board
# that advertises a UUID link without a live sibling behind it
# contributes nothing. _probe_prefixed's probed_ids guard -- not a set
# difference against `listed` here -- is what keeps an id already named
# by subdeviceIdList from being probed and materialized a second time,
# since the two sources can disagree on that UUID's case.
# (AWM-WW-AID-26-ONEBODY washer+dryer combo, issue #241.) No
# /subdevices/vs/0 and /device/<n> 404s; the only trace of the sibling
# is a UUID-prefixed link in /oic/res (the x.com.samsung.da.multidevice
# link). Its own tree answers a full Collection at /<uuid>/device/0,
# exactly Pattern B's transform, so every UUID path prefix seen in
# /oic/res is treated as a candidate. _probe_prefixed's probed_ids
# guard (not a set difference against `listed`) is what keeps an id
# already named by subdeviceIdList from being probed twice, since the
# two sources can disagree on case.
linked = sorted(
{
m.group(1)
@@ -477,10 +385,9 @@ def enumerate_subdevices(
}
)
if not indices:
# A board that hides its whole tree from /oic/res (Pattern B's
# reporter board does this too, but it has no /device/<n> to find
# regardless) gives us nothing to enumerate from -- fall back to the
# bounded speculative probe this replaces from identity.py.
# A board that hides its whole tree from /oic/res gives us nothing
# to enumerate from -- fall back to the bounded speculative probe
# this replaces from identity.py.
indices = list(_SPECULATIVE_DEVICE_INDICES)
for n in indices:
seed = ("device", str(n))
@@ -492,19 +399,13 @@ def enumerate_subdevices(
fetched.update(batch) # already real /x/<n> hrefs, no normalization needed
subdevices.append(subdevice)
# /multidevice/vs/0 (issue #177 follow-up): the Pattern A reporter's
# board lists it in /oic/res but it never appears in /device/0's batch,
# so it needs its own RETRIEVE. It's a plain corroborating count
# (x.com.samsung.da.numofsubdevice), confirmed read-only (a write
# attempt returned CoAP 4.00) -- captured for diagnostics only, folded
# into the merged resources dict like any other href (see
# airconditioner._AC_IGNORED, which is what keeps it from surfacing as
# an unbound-href gap). NOT a gate: discover_partitioned's entity-level
# liveness check decides materialization correctly without it, and only
# this one board family is known to expose it at all. Whether it agrees
# with the number of subdevices actually materialized is the
# coordinator's call to log (it owns the logger; this module doesn't),
# not this function's.
# /multidevice/vs/0: listed in /oic/res on some boards but never in
# /device/0's batch, so it needs its own RETRIEVE. A plain corroborating
# count (numofsubdevice), confirmed read-only -- captured for
# diagnostics only, folded into the merged resources dict like any
# other href (see airconditioner._AC_IGNORED). Not a gate:
# discover_partitioned's entity-level liveness check decides
# materialization without it.
multidevice_seed = ("multidevice", "vs", "0")
multidevice = _get_property(sess, multidevice_seed)
_probed(_seed_href(multidevice_seed), multidevice)
@@ -516,23 +417,21 @@ def enumerate_subdevices(
@dataclass(frozen=True)
class SkippedSubdevice:
"""A candidate `enumerate_subdevices` found whose seed answered, but that
`discover_partitioned`'s entity-level liveness gate rejected -- an
unused SmartThings slot (the Pattern A reporter's `/device/2`), not a
real second subdevice. Kept around (rather than silently dropped) so a
"""A candidate `enumerate_subdevices` found whose seed answered, but
that `discover_partitioned`'s entity-level liveness gate rejected -- an
unused SmartThings slot, not a real second subdevice. Kept around so a
caller can log/report what was skipped and why."""
subdevice: Subdevice
hrefs: tuple[str, ...]
# Sensor kinds whose value is a running total the *appliance* keeps rather
# Sensor kinds whose value is a running total the appliance keeps rather
# than a reading of the subdevice's own hardware -- excluded from the
# liveness gate below (issue #214). HA's own running-total state classes
# cover most of them; the consumption device classes catch the rest, since a
# descriptor may deliberately declare no state_class (common.ENERGY_METER's
# monthly totals reset at each billing boundary, so they aren't
# `total_increasing`).
# liveness gate below (issue #214). HA's running-total state classes cover
# most of them; the consumption device classes catch the rest (a descriptor
# may deliberately declare no state_class, e.g. common.ENERGY_METER's
# monthly totals that reset at each billing boundary).
_METER_STATE_CLASSES = frozenset({"total", "total_increasing"})
_METER_DEVICE_CLASSES = frozenset({"energy", "water", "gas"})
@@ -549,35 +448,26 @@ def _is_meter(desc) -> bool:
def _has_live_primary_entity(bound, state: dict) -> bool:
"""True if flattening `bound` (one candidate subdevice's BoundEntity
list) produced at least one non-`None` value for a *primary* entity --
`entity_category` unset, HA's own "the user acts on or watches this"
tier (see the adding-device-support skill's entity-taxonomy section) --
that isn't a cumulative meter (`_is_meter`).
list) produced at least one non-`None` value for a primary entity
(`entity_category` unset) that isn't a cumulative meter (`_is_meter`).
This is the materialization gate itself (see this module's docstring).
Two exclusions, both for the same reason -- the question this answers is
"is a physical subdevice installed at this slot?", and neither kind of
value can speak to it:
Two exclusions, both because the question this answers is "is a
physical subdevice installed at this slot?", and neither kind of value
can speak to it:
- **Non-primary entities.** The Pattern A reporter's `/device/2` does
flatten to one non-`None` value (`alarm_code`), but that entity is
`diagnostic`-category and derived from an empty `/alarms/vs/2` -- a
config/diagnostic entity reading "something" proves nothing about
whether hardware is there.
- **Cumulative meters** (issue #214). An unused slot on the issue #214
reporter's ARTIK051_KRAC_18K reports `/energy/consumption/vs/1` with a
populated `cumulativePower` while every operational rep on it
(`/power/1`, `/mode/1`, `/mode/vs/1`, `/temperature/current/1`,
`/temperature/desired/1`, `/airflow/1`, `/humidity/1`) is empty `{}` --
i.e. exactly the Pattern A `/device/2` shape plus a lifetime kWh
counter. That counter got the slot materialized as a phantom second
air conditioner. A single-split AC has one compressor and one energy
meter, so a whole-appliance total showing up under a second index is
the appliance's own bookkeeping, not evidence of a second indoor unit.
A genuinely installed subdevice reports its own operational state too
(the Pattern A reporter's real `/device/1` reports power, mode, both
temperatures and airflow), and that state is what still passes this
gate.
- **Non-primary entities.** An unused slot can still flatten to a
diagnostic-category value derived from an empty resource (e.g. a
formatted `alarm_code` off an empty `/alarms/vs/2`) -- that proves
nothing about whether hardware is there.
- **Cumulative meters** (issue #214). An unused slot has been seen
reporting a populated whole-appliance `cumulativePower` while every
operational rep on it is empty `{}`. A single-split AC has one
compressor and one energy meter, so a whole-appliance total showing
up under a second index is the appliance's own bookkeeping, not
evidence of a second indoor unit. A genuinely installed subdevice
reports its own operational state too, and that is what still passes
this gate.
"""
from .adapter import _key # see discover_partitioned's deferred-import note
@@ -596,64 +486,53 @@ def discover_partitioned(
tier_log: Callable[[str, str], None] | None = None,
oic_device_types: Sequence[str] = (),
):
"""Bind every href in `resources` (the merged, real-href snapshot -- main
plus every enumerated subdevice's seed) to entities, partitioned by which
subdevice owns it.
"""Bind every href in `resources` (the merged, real-href snapshot --
main plus every enumerated subdevice's seed) to entities, partitioned
by which subdevice owns it.
Main pass runs over hrefs owned by no subdevice -- otherwise every
`/mode/vs/1` would land in `unbound_hrefs` too (nothing in the main
device's registry claims that literal href) and raise a spurious
coverage-gap repair. Then one pass per *candidate* subdevice over its own
`/mode/vs/1` would land in `unbound_hrefs` too and raise a spurious
coverage-gap repair. Then one pass per candidate subdevice over its own
canonical view, resolving that subdevice's own device type from its own
`/information/vs/0` when it reports one (e.g. the Pattern B reporter's
wall subdevice reports `TP2X_FAC_BORA_RAC_21K` -> the 'RAC' board token ->
airconditioner), falling back to the master's registry otherwise --
every AC family shares the same resource surface, and a sibling that
fails to answer its own identity resource is still the same appliance
type as the subdevice this config entry was set up against.
`/information/vs/0` when it reports one, falling back to the master's
registry otherwise -- a sibling that fails to answer its own identity
resource is still treated as the same appliance type as the master.
Each candidate is discovered and flattened *twice*: once silently to
evaluate `_has_live_primary_entity` (this module's materialization
gate -- see its docstring and this module's own), and, only if that
passes, a second time with `log`/`tier_log` wired so its coverage gaps
and poll tiers actually count. A candidate that fails the gate
contributes nothing at all -- no bound entities, no unbound-href
report, no hot/warm href -- as if it had never answered its seed.
Discovering an unused slot's small, fixed resource set twice at
first-discovery time only is a non-issue; getting a phantom subdevice
silently counted into unbound_hrefs or hot/warm tiers is not.
Each candidate is discovered and flattened twice: once silently to
evaluate `_has_live_primary_entity`, and, only if that passes, a second
time with `log`/`tier_log` wired so its coverage gaps and poll tiers
actually count. A candidate that fails the gate contributes nothing at
all, as if it had never answered its seed.
`oic_device_types` (from the master's own `/oic/d`, see
registry/identity.py) is passed only to the *master's* resolution --
subdevices have no `/oic/d` of their own read today (they resolve from
their own `/information/vs/0` or fall back to the master's whole
registry, as documented above), and blindly applying the master's OCF
device type to every subdevice's own model-based resolution would be
wrong the moment a composite appliance ever pairs two genuinely
different device types under one connection.
`oic_device_types` (from the master's own `/oic/d`) is passed only to
the master's resolution -- subdevices resolve from their own
`/information/vs/0` or fall back to the master's whole registry, and
blindly applying the master's OCF device type to every subdevice would
be wrong the moment a composite appliance pairs two different device
types under one connection.
Returns `(bound, device_type_name, materialized, skipped)`:
- `bound`: the concatenated BoundEntity list (main + every materialized
subdevice).
- `device_type_name`: the *master's* resolved device type (used for
logging/device naming; each subdevice's own resolved type only affects
which capabilities bind its hrefs, not this).
- `materialized`: the subset of `subdevices` that passed the gate, in the
same order -- what the caller should keep as its live subdevice roster
going forward (poll seeds, canonical_resources, device_info_for, ...).
- `device_type_name`: the master's resolved device type (used for
logging/device naming; each subdevice's own resolved type only
affects which capabilities bind its hrefs).
- `materialized`: the subset of `subdevices` that passed the gate, in
the same order -- what the caller should keep as its live subdevice
roster going forward (poll seeds, canonical_resources,
device_info_for, ...).
- `skipped`: `SkippedSubdevice` entries for every candidate that didn't.
"""
# Deferred import: discovery.py imports Subdevice/MAIN from this module at
# module scope, so importing discover() back here at module scope would
# be a circular import. By the time this function actually runs both
# modules are fully loaded. adapter.py imports discovery.py, so the same
# applies to flatten()/_key().
# Deferred import: discovery.py imports Subdevice/MAIN from this module
# at module scope, so importing discover() back here at module scope
# would be circular. By the time this function runs both modules are
# fully loaded; adapter.py imports discovery.py, so the same applies to
# flatten()/_key().
from .adapter import flatten
from .discovery import discover
# Same computation canonical_view does for MAIN (snapshot minus every
# other subdevice's owned hrefs) -- reuse it rather than re-deriving
# owned_elsewhere here too.
# Same computation canonical_view does for MAIN -- reuse it rather than
# re-deriving owned_elsewhere here too.
main_view = canonical_view(MAIN, resources, subdevices)
reg = resolve_registry(main_view, device_types=oic_device_types)
+17 -26
View File
@@ -52,34 +52,26 @@ def _translation_state(value: str, known: frozenset[str]) -> str | None:
def _display(value, translation_key: str | None):
"""Turn a raw device option/state value into what's shown in the UI.
`translation_key` is the entity's already-resolved key (SelectDesc.
translation_key can itself be a callable -- see entities.py -- so
callers pass the resolved value, e.g. self.translation_key, not
the raw descriptor field).
`translation_key` is the entity's already-resolved key (it can itself
be a callable -- see entities.py -- so callers pass the resolved
value, not the raw descriptor field).
An entity with a translation_key looks its state up in the shipped
translation catalog, whose state keys are lowercase -- so those values
must be lowercased exactly to match, and the device still expects
that same raw casing back on write (callers map the displayed value
back to raw via _raw_options()).
Everything else has no catalog lookup, so there's no reason to
destroy the device's own casing. Only two cosmetic fixups apply: a
fully lowercase device-native token (e.g. "voice") is title-cased,
and a PascalCase token (e.g. "ExtraHigh") gets a space inserted at
the case boundary ("Extra High"). A value that's already
human-friendly (e.g. "AI Wash") matches neither pattern and passes
through unchanged.
translation catalog, whose state keys are lowercase, and the device
still expects that same raw casing back on write (mapped back via
_raw_options()). Everything else has no catalog lookup, so there's no
reason to destroy the device's own casing: only two cosmetic fixups
apply, title-casing a fully lowercase token ("voice") and spacing a
PascalCase one ("ExtraHigh" -> "Extra High"); an already-friendly value
("AI Wash") matches neither and passes through unchanged.
"""
if not isinstance(value, str):
return value
if translation_key:
known = translated_states("select", translation_key)
if not known:
# No state table for this key: either the entity isn't translated
# at all, or its name is translated but its options deliberately
# aren't (an unrecognized course table, say). Either way the
# opaque device value is the best thing to show.
# No state table for this key: either untranslated, or its
# options deliberately aren't (an unrecognized course table).
return value
if translated := _translation_state(value, known):
return translated
@@ -99,12 +91,11 @@ class LocalThingsSelect(LocalThingsEntity, SelectEntity):
desc = cast(SelectDesc, self._bound.desc)
if callable(desc.options):
# Per-device option list computed from the full resource
# snapshot (not just this entity's own href) -- e.g. a course
# list decoded from a sibling resource. There is no static
# fallback: when that resource isn't populated the callable
# returns [] and the entity's exists_fn suppresses it entirely.
# This entity's own subdevice's canonical view (issue #177), not
# the raw actual-href snapshot -- see LocalThingsEntity._resources.
# snapshot -- e.g. a course list decoded from a sibling
# resource. No static fallback: when unpopulated, the callable
# returns [] and exists_fn suppresses the entity entirely. Uses
# this subdevice's canonical view (issue #177), not the raw
# snapshot -- see LocalThingsEntity._resources.
return list(desc.options(self._resources) or [])
if desc.options_field:
rep = self.coordinator.last_resources.get(self._bound.href) or {}
+219
View File
@@ -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:
File diff suppressed because it is too large Load Diff
@@ -117,6 +117,12 @@
"diagnosis_start": {
"name": "Start diagnosis"
},
"auto_clean_stop": {
"name": "Stop auto clean"
},
"filter_time_reset": {
"name": "Reset filter time"
},
"pause": {
"name": "Pause"
},
@@ -146,11 +152,13 @@
"smart": "Smart",
"speed": "Speed",
"nano": "WindFree",
"sleep": "Sleep",
"nanosleep": "WindFree sleep",
"longwind": "Long wind",
"motionindirect": "Motion indirect",
"motiondirect": "Motion direct",
"drycomfort": "Dry comfort",
"dlightcool": "d'light Cool",
"2step": "2-Step"
}
}
@@ -191,6 +199,9 @@
"oven_setpoint": {
"name": "Setpoint"
},
"sensing_interval": {
"name": "AI Purify interval"
},
"setpoint": {
"name": "Setpoint"
},
@@ -494,6 +505,14 @@
"rinse_cycles": {
"name": "Rinse cycles"
},
"sensing_mode": {
"name": "AI Purify action",
"state": {
"off": "Sensing only",
"airpurify": "Auto clean",
"alarm": "Get notified"
}
},
"softener_concentration": {
"name": "Softener concentration",
"state": {
@@ -519,6 +538,9 @@
"mute": "Mute"
}
},
"energy_saving_mode": {
"name": "Energy saving mode"
},
"air_purifier_sound_mode": {
"name": "Sound mode",
"state": {
@@ -646,6 +668,38 @@
},
"freezer_temperature_setpoint": {
"name": "Freezer temperature"
},
"edge_lighting_mode": {
"name": "Edge lighting mode",
"state": {
"smart": "Smart",
"high": "High",
"low": "Low"
}
},
"edge_lighting_color": {
"name": "Edge lighting color",
"state": {
"3000k": "3000 K",
"4000k": "4000 K",
"6500k": "6500 K"
}
},
"indicator_light_mode": {
"name": "Indicator light mode",
"state": {
"smart": "Smart",
"high": "High",
"low": "Low"
}
},
"ventilation_mode": {
"name": "Mode",
"state": {
"purification": "Purification",
"ventilation": "Ventilation",
"smartventilation": "Smart Ventilation"
}
}
},
"sensor": {
@@ -768,6 +822,12 @@
"indirect": "Indirect"
}
},
"energy_saving_state": {
"name": "Energy saving state"
},
"energy_saving_operating_status": {
"name": "Energy saving operating status"
},
"current_temp_c": {
"name": "Temperature"
},
@@ -1021,6 +1081,9 @@
"absence_power_saving_active": {
"name": "Absence power saving active"
},
"absence_clean": {
"name": "Absence clean"
},
"motion_detect_wind_active": {
"name": "Motion-detect wind avoidance active"
},
@@ -1030,6 +1093,12 @@
"display": {
"name": "Display"
},
"periodic_air_sensing": {
"name": "AI Purify"
},
"periodic_sensing_skip_status": {
"name": "AI Purify sensing skip"
},
"pet_filter_activation": {
"name": "Pet filter activation"
},
@@ -1179,6 +1248,18 @@
},
"ventilation_alarm": {
"name": "Ventilation alarm"
},
"edge_lighting": {
"name": "Edge lighting"
},
"indicator_light": {
"name": "Indicator light"
},
"windfree": {
"name": "Wind-Free mode"
},
"windsleep": {
"name": "Sleep mode"
}
},
"time": {
@@ -1199,6 +1280,12 @@
},
"night_start": {
"name": "Night light start"
},
"sensing_skip_end": {
"name": "AI Purify sensing skip end"
},
"sensing_skip_start": {
"name": "AI Purify sensing skip start"
}
},
"water_heater": {
@@ -1235,10 +1322,18 @@
},
"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": {
"no_response": "No response from that IP address — nothing came back on any port in the appliance's local API range (UDP 49152-49160). Check the IP address is correct, the appliance is powered on and on the same network as Home Assistant, and that no firewall is dropping UDP traffic to it.",
"ports_closed": "That IP address is reachable, but it actively refused every port in the local API range (UDP 49152-49160). Either it isn't a Samsung appliance, or it's on older firmware that only talks to Samsung's cloud over TCP 8888, which this integration can't use.",
"no_dtls_server": "Ports in the local API range are reachable at that address, but nothing there answered a DTLS handshake. Check that the IP address belongs to the appliance and not another device on your network.",
"handshake_timeout": "The appliance answered on its local API port but never finished the DTLS handshake. It is usually still holding the session from a previous attempt — wait about a minute and try again.",
"cert_rejected": "The appliance rejected the certificate. The CA certificate and key are most likely not the AC14K_M CA this appliance trusts, or they don't pair. The Home Assistant log records the exact alert the appliance sent.",
"handshake_failed": "The appliance refused the DTLS handshake for a reason unrelated to the certificate, most likely a protocol or cipher mismatch. The Home Assistant log records the exact alert it sent.",
"cloud_unreachable": "Couldn't reach Samsung's cloud gateway to fetch the UUID needed to mint this device's certificate. Check Home Assistant's internet access and try again.",
"unexpected_response": "Connected to the device successfully, but it didn't return a usable device description. It may not be an appliance this integration supports. The Home Assistant log records what it sent.",
"cannot_connect": "Cannot connect to the device. Verify the IP address is reachable and the CA credentials are correct.",
"invalid_ca": "The CA certificate or private key could not be loaded. Verify the PEM contents are correct and the key matches the certificate.",
"unknown": "Unexpected error. Check the Home Assistant logs for details."
@@ -1319,6 +1414,27 @@
},
"intensive_unavailable_for_cycle": {
"message": "Intensive isn't available on the selected cycle."
},
"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."
}
}
}
@@ -27,10 +27,18 @@
},
"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": {
"no_response": "No hubo respuesta de esa dirección IP: no llegó nada por ningún puerto del rango de la API local del electrodoméstico (UDP 49152-49160). Comprueba que la dirección IP sea correcta, que el electrodoméstico esté encendido y en la misma red que Home Assistant, y que ningún cortafuegos esté descartando el tráfico UDP hacia él.",
"ports_closed": "Esa dirección IP es accesible, pero rechazó activamente todos los puertos del rango de la API local (UDP 49152-49160). O no es un electrodoméstico Samsung, o tiene un firmware antiguo que solo se comunica con la nube de Samsung por TCP 8888, que esta integración no puede usar.",
"no_dtls_server": "Los puertos del rango de la API local son accesibles en esa dirección, pero nada respondió a un saludo DTLS. Comprueba que la dirección IP pertenezca al electrodoméstico y no a otro dispositivo de tu red.",
"handshake_timeout": "El electrodoméstico respondió en su puerto de API local, pero no completó el saludo DTLS. Normalmente todavía mantiene la sesión de un intento anterior: espera alrededor de un minuto e inténtalo de nuevo.",
"cert_rejected": "El electrodoméstico rechazó el certificado. Lo más probable es que el certificado y la clave de la CA no sean los de la CA AC14K_M en la que confía este electrodoméstico, o que no se correspondan entre sí. El registro de Home Assistant recoge la alerta exacta que envió el electrodoméstico.",
"handshake_failed": "El electrodoméstico rechazó el saludo DTLS por un motivo no relacionado con el certificado, probablemente una incompatibilidad de protocolo o de cifrado. El registro de Home Assistant recoge la alerta exacta que envió.",
"cloud_unreachable": "No se pudo contactar con la pasarela en la nube de Samsung para obtener el UUID necesario para emitir el certificado de este dispositivo. Comprueba el acceso a internet de Home Assistant e inténtalo de nuevo.",
"unexpected_response": "La conexión con el dispositivo se estableció correctamente, pero no devolvió una descripción de dispositivo utilizable. Puede que no sea un electrodoméstico compatible con esta integración. El registro de Home Assistant recoge lo que envió.",
"cannot_connect": "No se puede conectar con el dispositivo. Comprueba que la dirección IP sea accesible y que las credenciales CA sean correctas.",
"invalid_ca": "No se ha podido cargar el certificado CA o la clave privada. Comprueba que el contenido PEM sea correcto y que la clave coincida con el certificado.",
"unknown": "Error inesperado. Consulta los registros de Home Assistant para más detalles."
@@ -111,6 +119,27 @@
},
"intensive_unavailable_for_cycle": {
"message": "El modo intensivo no está disponible en el ciclo seleccionado."
},
"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": {
@@ -231,6 +260,12 @@
"diagnosis_start": {
"name": "Iniciar diagnóstico"
},
"auto_clean_stop": {
"name": "Detener la autolimpieza"
},
"filter_time_reset": {
"name": "Restablecer el contador del filtro"
},
"pause": {
"name": "Pausar"
},
@@ -260,11 +295,13 @@
"smart": "Inteligente",
"speed": "Rápido",
"nano": "WindFree",
"sleep": "Sueño",
"nanosleep": "WindFree sueño",
"longwind": "Viento prolongado",
"motionindirect": "Indirecto al movimiento",
"motiondirect": "Directo al movimiento",
"drycomfort": "Confort seco",
"dlightcool": "d'light Cool",
"2step": "2 pasos"
}
}
@@ -305,6 +342,9 @@
"oven_setpoint": {
"name": "Punto de ajuste"
},
"sensing_interval": {
"name": "Intervalo de AI Purify"
},
"setpoint": {
"name": "Punto de ajuste"
},
@@ -608,6 +648,14 @@
"rinse_cycles": {
"name": "Aclarados"
},
"sensing_mode": {
"name": "Acción de AI Purify",
"state": {
"off": "Solo medición",
"airpurify": "Limpieza automática",
"alarm": "Recibir notificación"
}
},
"softener_concentration": {
"name": "Concentración del suavizante",
"state": {
@@ -633,6 +681,9 @@
"mute": "Silencio"
}
},
"energy_saving_mode": {
"name": "Modo de ahorro de energía"
},
"air_purifier_sound_mode": {
"name": "Modo de sonido",
"state": {
@@ -760,6 +811,38 @@
},
"freezer_temperature_setpoint": {
"name": "Temperatura del congelador"
},
"edge_lighting_mode": {
"name": "Modo de iluminación perimetral",
"state": {
"smart": "Inteligente",
"high": "Alto",
"low": "Bajo"
}
},
"edge_lighting_color": {
"name": "Color de iluminación perimetral",
"state": {
"3000k": "3000 K",
"4000k": "4000 K",
"6500k": "6500 K"
}
},
"indicator_light_mode": {
"name": "Modo de luz indicadora",
"state": {
"smart": "Inteligente",
"high": "Alto",
"low": "Bajo"
}
},
"ventilation_mode": {
"name": "Modo",
"state": {
"purification": "Purificación",
"ventilation": "Ventilación",
"smartventilation": "Ventilación inteligente"
}
}
},
"sensor": {
@@ -879,6 +962,12 @@
"indirect": "Indirecto"
}
},
"energy_saving_state": {
"name": "Estado de ahorro de energía"
},
"energy_saving_operating_status": {
"name": "Estado de funcionamiento del ahorro de energía"
},
"current_temp_c": {
"name": "Temperatura"
},
@@ -1135,6 +1224,9 @@
"absence_power_saving_active": {
"name": "Ahorro por ausencia activo"
},
"absence_clean": {
"name": "Limpieza por ausencia"
},
"motion_detect_wind_active": {
"name": "Evitación de viento por detección de movimiento activa"
},
@@ -1144,6 +1236,12 @@
"display": {
"name": "Pantalla"
},
"periodic_air_sensing": {
"name": "AI Purify"
},
"periodic_sensing_skip_status": {
"name": "Omisión de medición de AI Purify"
},
"pet_filter_activation": {
"name": "Activación de filtro para mascotas"
},
@@ -1293,6 +1391,18 @@
},
"ventilation_alarm": {
"name": "Alarma de ventilación"
},
"edge_lighting": {
"name": "Iluminación perimetral"
},
"indicator_light": {
"name": "Luz indicadora"
},
"windfree": {
"name": "Modo Wind-Free"
},
"windsleep": {
"name": "Modo nocturno"
}
},
"time": {
@@ -1313,6 +1423,12 @@
},
"night_start": {
"name": "Inicio de la luz nocturna"
},
"sensing_skip_end": {
"name": "Fin de la omisión de medición de AI Purify"
},
"sensing_skip_start": {
"name": "Inicio de la omisión de medición de AI Purify"
}
},
"water_heater": {
@@ -117,6 +117,12 @@
"diagnosis_start": {
"name": "Avvia diagnosi"
},
"auto_clean_stop": {
"name": "Arresta autopulizia"
},
"filter_time_reset": {
"name": "Azzera il contatore del filtro"
},
"pause": {
"name": "Pausa"
},
@@ -146,11 +152,13 @@
"smart": "Smart",
"speed": "Veloce",
"nano": "WindFree",
"sleep": "Sonno",
"nanosleep": "WindFree sonno",
"longwind": "Vento prolungato",
"motionindirect": "Indiretto al movimento",
"motiondirect": "Diretto al movimento",
"drycomfort": "Comfort asciugatura",
"dlightcool": "d'light Cool",
"2step": "2 fasi"
}
}
@@ -191,6 +199,9 @@
"oven_setpoint": {
"name": "Valore impostato"
},
"sensing_interval": {
"name": "Intervallo AI Purify"
},
"setpoint": {
"name": "Valore impostato"
},
@@ -494,6 +505,14 @@
"rinse_cycles": {
"name": "Risciacquo"
},
"sensing_mode": {
"name": "Azione AI Purify",
"state": {
"off": "Solo rilevamento",
"airpurify": "Pulizia automatica",
"alarm": "Ricevi notifica"
}
},
"softener_concentration": {
"name": "Concentrazione ammorbidente",
"state": {
@@ -519,6 +538,9 @@
"mute": "Muto"
}
},
"energy_saving_mode": {
"name": "Modalità risparmio energetico"
},
"air_purifier_sound_mode": {
"name": "Modalità audio",
"state": {
@@ -565,7 +587,7 @@
"1c": "Eco 40-60",
"1d": "Super Speed",
"1e": "Rapido 15'",
"1f": "Intenseo a freddo",
"1f": "Intenso a freddo",
"20": "Vapore igienizzante",
"21": "Colorati",
"22": "Lana",
@@ -646,6 +668,38 @@
},
"freezer_temperature_setpoint": {
"name": "Temperatura freezer"
},
"edge_lighting_mode": {
"name": "Modalità illuminazione perimetrale",
"state": {
"smart": "Smart",
"high": "Alta",
"low": "Bassa"
}
},
"edge_lighting_color": {
"name": "Colore illuminazione perimetrale",
"state": {
"3000k": "3000 K",
"4000k": "4000 K",
"6500k": "6500 K"
}
},
"indicator_light_mode": {
"name": "Modalità spia luminosa",
"state": {
"smart": "Smart",
"high": "Alta",
"low": "Bassa"
}
},
"ventilation_mode": {
"name": "Modalità",
"state": {
"purification": "Purificazione",
"ventilation": "Ventilazione",
"smartventilation": "Ventilazione intelligente"
}
}
},
"sensor": {
@@ -768,6 +822,12 @@
"indirect": "Indiretto"
}
},
"energy_saving_state": {
"name": "Stato risparmio energetico"
},
"energy_saving_operating_status": {
"name": "Stato di funzionamento del risparmio energetico"
},
"current_temp_c": {
"name": "Temperatura"
},
@@ -1021,6 +1081,9 @@
"absence_power_saving_active": {
"name": "Risparmio energetico in assenza attivo"
},
"absence_clean": {
"name": "Pulizia in assenza"
},
"motion_detect_wind_active": {
"name": "Elusione flusso d'aria a rilevamento movimento attiva"
},
@@ -1030,6 +1093,12 @@
"display": {
"name": "Display"
},
"periodic_air_sensing": {
"name": "AI Purify"
},
"periodic_sensing_skip_status": {
"name": "Esclusione rilevamento AI Purify"
},
"pet_filter_activation": {
"name": "Attivazione filtro animali"
},
@@ -1179,6 +1248,18 @@
},
"ventilation_alarm": {
"name": "Allarme ventilazione"
},
"edge_lighting": {
"name": "Illuminazione perimetrale"
},
"indicator_light": {
"name": "Spia luminosa"
},
"windfree": {
"name": "Modalità Wind-Free"
},
"windsleep": {
"name": "Modalità notte"
}
},
"time": {
@@ -1199,6 +1280,12 @@
},
"night_start": {
"name": "Inizio luce notturna"
},
"sensing_skip_end": {
"name": "Fine esclusione rilevamento AI Purify"
},
"sensing_skip_start": {
"name": "Inizio esclusione rilevamento AI Purify"
}
},
"water_heater": {
@@ -1235,10 +1322,18 @@
},
"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": {
"no_response": "Nessuna risposta da quell'indirizzo IP: non è arrivato nulla su nessuna porta dell'intervallo dell'API locale dell'apparecchio (UDP 49152-49160). Verifica che l'indirizzo IP sia corretto, che l'apparecchio sia acceso e sulla stessa rete di Home Assistant e che nessun firewall stia scartando il traffico UDP diretto a esso.",
"ports_closed": "Quell'indirizzo IP è raggiungibile, ma ha rifiutato attivamente tutte le porte dell'intervallo dell'API locale (UDP 49152-49160). O non è un apparecchio Samsung, oppure ha un firmware più vecchio che comunica solo con il cloud Samsung su TCP 8888, che questa integrazione non può usare.",
"no_dtls_server": "Le porte dell'intervallo dell'API locale sono raggiungibili a quell'indirizzo, ma nulla ha risposto a un handshake DTLS. Verifica che l'indirizzo IP appartenga all'apparecchio e non a un altro dispositivo della rete.",
"handshake_timeout": "L'apparecchio ha risposto sulla sua porta dell'API locale ma non ha completato l'handshake DTLS. Di solito sta ancora mantenendo la sessione di un tentativo precedente: attendi circa un minuto e riprova.",
"cert_rejected": "L'apparecchio ha rifiutato il certificato. Con ogni probabilità il certificato e la chiave della CA non sono quelli della CA AC14K_M di cui questo apparecchio si fida, oppure non corrispondono tra loro. Il log di Home Assistant riporta l'alert esatto inviato dall'apparecchio.",
"handshake_failed": "L'apparecchio ha rifiutato l'handshake DTLS per un motivo non legato al certificato, molto probabilmente un'incompatibilità di protocollo o di cifratura. Il log di Home Assistant riporta l'alert esatto inviato.",
"cloud_unreachable": "Impossibile raggiungere il gateway cloud di Samsung per ottenere l'UUID necessario a emettere il certificato di questo dispositivo. Verifica l'accesso a internet di Home Assistant e riprova.",
"unexpected_response": "Connessione al dispositivo riuscita, ma non ha restituito una descrizione del dispositivo utilizzabile. Potrebbe non essere un apparecchio supportato da questa integrazione. Il log di Home Assistant riporta ciò che ha inviato.",
"cannot_connect": "Impossibile connettersi al dispositivo. Verificare che l'indirizzo IP sia raggiungibile e che le credenziali CA siano corrette.",
"invalid_ca": "Impossibile caricare il certificato CA o la chiave privata. Verificare che il contenuto del file PEM sia corretto e che la chiave corrisponda al certificato.",
"unknown": "Errore imprevisto. Controlla i registri di Home Assistant per i dettagli."
@@ -1319,6 +1414,27 @@
},
"intensive_unavailable_for_cycle": {
"message": "Intensivo non è disponibile per il ciclo selezionato."
},
"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."
}
}
}
File diff suppressed because it is too large Load Diff
@@ -117,6 +117,12 @@
"diagnosis_start": {
"name": "Diagnose starten"
},
"auto_clean_stop": {
"name": "Zelfreiniging stoppen"
},
"filter_time_reset": {
"name": "Filterteller op nul zetten"
},
"pause": {
"name": "Pauzeren"
},
@@ -146,11 +152,13 @@
"smart": "Slim",
"speed": "Snel",
"nano": "WindFree",
"sleep": "Slaap",
"nanosleep": "WindFree-slaap",
"longwind": "Lange wind",
"motionindirect": "Beweging indirect",
"motiondirect": "Beweging direct",
"drycomfort": "Droog comfort",
"dlightcool": "d'light Cool",
"2step": "2-Step"
}
}
@@ -191,6 +199,9 @@
"oven_setpoint": {
"name": "Instelpunt"
},
"sensing_interval": {
"name": "AI Purify-interval"
},
"setpoint": {
"name": "Instelpunt"
},
@@ -494,6 +505,14 @@
"rinse_cycles": {
"name": "Spoelcycli"
},
"sensing_mode": {
"name": "AI Purify-actie",
"state": {
"off": "Alleen meten",
"airpurify": "Automatisch reinigen",
"alarm": "Melding ontvangen"
}
},
"softener_concentration": {
"name": "Concentratie wasverzachter",
"state": {
@@ -519,6 +538,9 @@
"mute": "Stil"
}
},
"energy_saving_mode": {
"name": "Energiebesparingsmodus"
},
"air_purifier_sound_mode": {
"name": "Geluidsmodus",
"state": {
@@ -646,6 +668,38 @@
},
"freezer_temperature_setpoint": {
"name": "Temperatuur vriesgedeelte"
},
"edge_lighting_mode": {
"name": "Randverlichtingsmodus",
"state": {
"smart": "Slim",
"high": "Hoog",
"low": "Laag"
}
},
"edge_lighting_color": {
"name": "Randverlichtingskleur",
"state": {
"3000k": "3000 K",
"4000k": "4000 K",
"6500k": "6500 K"
}
},
"indicator_light_mode": {
"name": "Indicatorlampjemodus",
"state": {
"smart": "Slim",
"high": "Hoog",
"low": "Laag"
}
},
"ventilation_mode": {
"name": "Modus",
"state": {
"purification": "Zuivering",
"ventilation": "Ventilatie",
"smartventilation": "Slimme ventilatie"
}
}
},
"sensor": {
@@ -768,6 +822,12 @@
"indirect": "Indirect"
}
},
"energy_saving_state": {
"name": "Energiebesparing status"
},
"energy_saving_operating_status": {
"name": "Bedrijfsstatus energiebesparing"
},
"current_temp_c": {
"name": "Temperatuur"
},
@@ -1021,6 +1081,9 @@
"absence_power_saving_active": {
"name": "Energiebesparing bij afwezigheid actief"
},
"absence_clean": {
"name": "Reiniging bij afwezigheid"
},
"motion_detect_wind_active": {
"name": "Bewegingsdetectie luchtstroomvermijding actief"
},
@@ -1030,6 +1093,12 @@
"display": {
"name": "Display"
},
"periodic_air_sensing": {
"name": "AI Purify"
},
"periodic_sensing_skip_status": {
"name": "AI Purify meting overslaan"
},
"pet_filter_activation": {
"name": "Huisdierfilter actief"
},
@@ -1179,6 +1248,18 @@
},
"ventilation_alarm": {
"name": "Ventilatiealarm"
},
"edge_lighting": {
"name": "Randverlichting"
},
"indicator_light": {
"name": "Indicatorlampje"
},
"windfree": {
"name": "Wind-Free modus"
},
"windsleep": {
"name": "Slaapmodus"
}
},
"time": {
@@ -1199,6 +1280,12 @@
},
"night_start": {
"name": "Start nachtverlichting"
},
"sensing_skip_end": {
"name": "Einde AI Purify meting overslaan"
},
"sensing_skip_start": {
"name": "Start AI Purify meting overslaan"
}
},
"water_heater": {
@@ -1235,10 +1322,18 @@
},
"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": {
"no_response": "Geen reactie van dat IP-adres — er kwam niets terug op enige poort in het bereik van de lokale API van het apparaat (UDP 49152-49160). Controleer of het IP-adres klopt, of het apparaat aanstaat en op hetzelfde netwerk zit als Home Assistant, en of geen firewall het UDP-verkeer ernaartoe blokkeert.",
"ports_closed": "Dat IP-adres is bereikbaar, maar weigerde actief elke poort in het bereik van de lokale API (UDP 49152-49160). Het is óf geen Samsung-apparaat, óf het draait oudere firmware die alleen via TCP 8888 met de cloud van Samsung praat, wat deze integratie niet kan gebruiken.",
"no_dtls_server": "De poorten in het bereik van de lokale API zijn bereikbaar op dat adres, maar niets daar beantwoordde een DTLS-handshake. Controleer of het IP-adres bij het apparaat hoort en niet bij een ander apparaat in je netwerk.",
"handshake_timeout": "Het apparaat antwoordde op zijn lokale API-poort, maar voltooide de DTLS-handshake niet. Meestal houdt het de sessie van een eerdere poging nog vast — wacht ongeveer een minuut en probeer het opnieuw.",
"cert_rejected": "Het apparaat heeft het certificaat geweigerd. Het CA-certificaat en de sleutel zijn waarschijnlijk niet van de AC14K_M-CA die dit apparaat vertrouwt, of ze horen niet bij elkaar. Het Home Assistant-logboek bevat de precieze alert die het apparaat stuurde.",
"handshake_failed": "Het apparaat weigerde de DTLS-handshake om een reden die niets met het certificaat te maken heeft, hoogstwaarschijnlijk een protocol- of cipher-mismatch. Het Home Assistant-logboek bevat de precieze alert die het stuurde.",
"cloud_unreachable": "Kon de cloudgateway van Samsung niet bereiken om de UUID op te halen die nodig is om het certificaat van dit apparaat aan te maken. Controleer de internettoegang van Home Assistant en probeer het opnieuw.",
"unexpected_response": "Verbinding met het apparaat is gelukt, maar het gaf geen bruikbare apparaatbeschrijving terug. Mogelijk is het geen apparaat dat deze integratie ondersteunt. Het Home Assistant-logboek bevat wat het stuurde.",
"cannot_connect": "Kan geen verbinding maken met het apparaat. Controleer of het IP-adres bereikbaar is en de CA-inloggegevens juist zijn.",
"invalid_ca": "Het CA-certificaat of de privésleutel kon niet worden geladen. Controleer of de PEM-inhoud juist is en of de sleutel bij het certificaat hoort.",
"unknown": "Onverwachte fout. Raadpleeg de Home Assistant-logboeken voor meer informatie."
@@ -1319,6 +1414,27 @@
},
"intensive_unavailable_for_cycle": {
"message": "Intensief is niet beschikbaar voor het geselecteerde programma."
},
"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."
}
}
}
+38 -60
View File
@@ -1,38 +1,29 @@
"""Water heater platform for Local Things.
Second composite entity in this integration (see climate.py's module
docstring for the general pattern this follows): a single HA water_heater
card for a Samsung EHS heat pump's domestic hot water (DHW) loop. It binds
the primary `WaterHeaterDesc` (the `/mode/dhw/vs/0` capability, DHW.entities
in registry/capabilities/ehs.py) so the registry still tracks it, and reads
the sibling `/power/dhw/vs/0` and `/temperatures/dhw/vs/0` resources straight
from the coordinator snapshot -- the same cross-resource read climate.py uses
for the AC's power/temperature/wind siblings.
docstring for the general pattern): a single HA water_heater card for a
Samsung EHS heat pump's domestic hot water (DHW) loop. It binds the primary
`WaterHeaterDesc` (the `/mode/dhw/vs/0` capability, DHW.entities in
registry/capabilities/ehs.py) and reads the sibling `/power/dhw/vs/0` and
`/temperatures/dhw/vs/0` resources straight from the coordinator snapshot,
the same cross-resource read climate.py uses.
Writes go through `coordinator.async_send_command(bound, (kind, value))`:
DHW's `write_fn` (ehs._dhw_write) maps each `(kind, value)` payload to the
right `(path_segs, body)`, and `async_send_command` POSTs to those path_segs
and applies the optimistic value/settle guard to that same href -- not the
bound `/mode/dhw/vs/0` href -- so one descriptor drives writes to, and gets
fresh state back for, power, mode and temperature alike.
Writes go through `coordinator.async_send_command`: DHW's `write_fn`
(ehs._dhw_write) maps each `(kind, value)` payload to the right
`(path_segs, body)`, applying the optimistic value/settle guard to that
resource's own href rather than the bound `/mode/dhw/vs/0` href.
Operation-mode vocabulary: the DHW loop's four device modes (Eco/Std/Force/
Power) map onto HA's own standard water_heater states -- the same mapping
Home Assistant's core `smartthings` integration uses for this exact Samsung
capability over the cloud API (`samsungce.ehsThermostat` /
`airConditionerMode`: eco/std/force/power -> STATE_ECO/STATE_HEAT_PUMP/
STATE_HIGH_DEMAND/STATE_PERFORMANCE), just title-cased to match this OCF
resource's own code spelling. Reusing HA's standard states means no *state*
translation catalog entry is needed for them (see the entity_component
fallback in homeassistant.components.water_heater.strings.json).
Power) map onto HA's own standard water_heater states, the same mapping
HA core's `smartthings` integration uses for this exact Samsung capability
(`samsungce.ehsThermostat`), just title-cased to match this OCF resource's
spelling. Reusing HA's standard states means no state translation catalog
entry is needed for them.
Naming is a separate question from that, and the answer here differs from
climate.py's: the AC *is* the device, so its climate card takes the bare
device name (`_attr_name = None`). An EHS unit has two loops, and the DHW
one is not "the device" -- its siblings are named "Zone Mode"/"Zone Target
Temperature", so a card labelled just "EHS" would misrepresent which loop
it drives. This entity is named through the catalog like every other
descriptor here, via the DHW descriptor's `translation_key='dhw'`
Naming differs from climate.py's: the AC *is* the device, so its card takes
the bare device name. An EHS unit has two loops, and DHW isn't "the
device" (siblings are named "Zone Mode"/"Zone Target Temperature"), so this
entity is named through the catalog via `translation_key='dhw'`
(entity.water_heater.dhw.name -> "Hot water").
"""
@@ -73,8 +64,7 @@ _LOGGER = logging.getLogger(__name__)
_MODES_FIELD = "x.com.samsung.da.modes"
_SUPPORTED_FIELD = "x.com.samsung.da.supportedModes"
# Device mode <-> HA water_heater operation state -- see the module
# docstring above for the SmartThings-cloud precedent this mirrors.
# Device mode <-> HA water_heater operation state -- see module docstring.
_DEVICE_TO_STATE: dict[str, str] = {
"Eco": STATE_ECO,
"Std": STATE_HEAT_PUMP,
@@ -83,12 +73,10 @@ _DEVICE_TO_STATE: dict[str, str] = {
}
_STATE_TO_DEVICE = {v: k for k, v in _DEVICE_TO_STATE.items()}
# Read-side lookup, case-folded. climate.py resolves write codes from the
# unit's own supportedModes because two spellings there mean one HA value
# ('Wind'/'Fan' -> FAN_ONLY); this map is bijective, so the write side can
# use _STATE_TO_DEVICE directly. Only the read side is exposed to a board
# spelling the same code differently ('eco'/'ECO'), and case is the one
# variation worth absorbing rather than warning about.
# Read-side lookup, case-folded: this map is bijective (unlike climate.py's
# 'Wind'/'Fan' -> FAN_ONLY), so the write side uses _STATE_TO_DEVICE
# directly; only the read side needs to absorb a board spelling the same
# code differently ('eco'/'ECO').
_DEVICE_TO_STATE_CI = {k.lower(): v for k, v in _DEVICE_TO_STATE.items()}
@@ -132,21 +120,18 @@ class LocalThingsWaterHeater(LocalThingsEntity, WaterHeaterEntity):
def __init__(self, coordinator: LocalThingsCoordinator, bound) -> None:
super().__init__(coordinator, bound)
# No _attr_name here: unlike climate.py's AC, this is one loop of a
# two-loop device and takes a catalog name ("Hot water") through the
# descriptor's translation_key -- see the module docstring.
# two-loop device and takes a catalog name through translation_key.
self._attr_supported_features = (
WaterHeaterEntityFeature.TARGET_TEMPERATURE
| WaterHeaterEntityFeature.OPERATION_MODE
| WaterHeaterEntityFeature.ON_OFF
)
# Raw device codes already logged by _warn_unmapped -- these
# properties are read on every coordinator refresh, so an un-deduped
# warning would spam the log for any unit reporting a genuinely
# unrecognized code.
# Raw device codes already logged by _warn_unmapped -- read on every
# refresh, so un-deduped would spam the log for an unrecognized code.
self._warned_unmapped: set[str] = set()
def _rep(self, href: str) -> dict:
"""`href` is one of this module's canonical HREF_* constants --
"""`href` is one of this module's canonical HREF_* constants,
translated through this bound entity's own subdevice (issue #177),
same as climate.py's identical helper."""
return self.coordinator.resource(self._bound.subdevice.to_actual(href)) or {}
@@ -188,14 +173,10 @@ class LocalThingsWaterHeater(LocalThingsEntity, WaterHeaterEntity):
return _num(self._rep(TEMPERATURE_HREF).get("x.com.samsung.da.desired"))
def _range(self) -> list | None:
"""The device's own (minimum, maximum) pair, or None.
Both ends together or neither, deliberately -- same rule as
climate._range(). A board reporting minimum but not maximum would
otherwise pair a device minimum (40) with HA's own default maximum
(140 °F), which looks plausible and is silently wrong on a unit
that really allows 62.
"""
"""The device's own (minimum, maximum) pair, or None. Both ends
together or neither -- same rule as climate._range(); a board
reporting only minimum would otherwise pair it with HA's own
default maximum, silently wrong."""
rep = self._rep(TEMPERATURE_HREF)
lo = _num(rep.get("x.com.samsung.da.minimum"))
hi = _num(rep.get("x.com.samsung.da.maximum"))
@@ -213,8 +194,7 @@ class LocalThingsWaterHeater(LocalThingsEntity, WaterHeaterEntity):
@property
def target_temperature_step(self) -> float:
# `is None`, not `or` -- see issue #160: `or` collapses a genuine 0
# into the fallback.
# `is None`, not `or` -- `or` would collapse a genuine 0 (issue #160).
step = _num(self._rep(TEMPERATURE_HREF).get("x.com.samsung.da.increment"))
return 0.5 if step is None else step
@@ -245,13 +225,11 @@ class LocalThingsWaterHeater(LocalThingsEntity, WaterHeaterEntity):
# -- writes ---------------------------------------------------------------
async def async_set_temperature(self, **kwargs) -> None:
# HA's water_heater.set_temperature service takes an optional
# operation_mode and forwards it here (SET_TEMPERATURE_SCHEMA), same
# as climate.set_temperature does with hvac_mode. Honour it, and set
# it first -- that also powers the loop on when it was off -- so a
# dashboard "boost to 55" button that carries a mode actually changes
# mode, instead of only moving the setpoint. Same fix as the AC's
# (see climate.async_set_temperature).
# HA's water_heater.set_temperature service can carry an optional
# operation_mode; honor it, setting the mode first (which also
# powers the loop on) so a dashboard "boost to 55" button that
# carries a mode actually changes mode, not just the setpoint. Same
# fix as climate.async_set_temperature.
operation_mode = kwargs.get("operation_mode")
if operation_mode is not None:
await self.async_set_operation_mode(operation_mode)
+94
View File
@@ -0,0 +1,94 @@
# AC filter-time counter reset: solved
`registry/capabilities/airconditioner.py`'s `filter_time` sensor
(`FilterTime_<N>` option token, tenths of an hour) has a reset entity now
(`filter_time_reset`, issue-tracked as PR #289): a single-token options write
of `FilterCleanAlarm_Clear` to `/mode/vs/0`, the same merge every other
setting on that href uses. Measured on an ARTIK051_KRAC_18K: `FilterTime_95`
(9h30m) → `FilterTime_0`, still zero on a fresh DTLS session and every poll
after; none of the other 17 tokens moved and the `/alarms/vs/0` entries
stayed `Deleted`.
The rest of this file is kept as-is: the failed attempts below are still the
best record of what *doesn't* work on this generation, and the reasoning
that follows them explains why the reset looked cloud-only for as long as it
did — a genuine trap worth knowing about before the next reset-adjacent
mystery on this board family.
## What the reset actually is
A **command**, not a value write. Samsung's cloud models it as capability
`custom.dustFilter`, command `resetDustFilter`, no arguments (implemented in
several SmartThings HA forks; not in the core integration) — that command
name is real, but see below for why POSTing it directly went nowhere.
## Tried, all against a live unit, all failed (before the token above was found)
- `FilterTime_0` via the single-token options merge that works for every
other setting on this href — accepted with no error, then discarded. Tried
on two units in opposite power states to rule out the obvious confound:
5595 → back to 5595 after 69s (powered off, alarm active), 1925 → back to
1925 after 65s (actively cooling).
- A full `options[]` read-modify-write with `FilterTime_0` substituted,
instead of the single-token merge — zero fields changed anywhere.
- A write to `/consumable/vs/0`, the board's own filter resource
(`items[{name: FilterProgress, state: N}]`) — discarded. `/oic/res`
declares that resource `oic.if.s` (read-only), which fits.
- `/actions/vs/0` (`x.com.samsung.da.actions`, `oic.if.a`) is the obvious
local command channel but publishes no schema: GET returns `{}` on
baseline and on `oic.if.a`, and five POSTs probing the shape (empty map,
empty string, empty array, invalid value, items shape) all returned 4.00
with an empty body — no echo of accepted field names, unlike the laundry
firmware's `"Control fail, <...>"`. Guessed action names were deliberately
not enumerated against a live appliance: an unknown vocabulary on a
channel called "actions" can hold a factory reset next to the one we want.
- `/hass/state/vs/0` and `/hass/command/vs/0` (advertised in `/oic/res`, and
`/opt/data/hass.db` exists in `/file/list`) → 4.04 on every interface, so
unimplemented scaffolding on this firmware.
- `/file/transfer/vs/0` serves only `/mnt/usage.db`; selecting another path
returns 4.05/4.00, so the firmware can't be pulled that way to read the
action vocabulary out of it.
- `/rm/micomdata/vs/0` (channel toward the MICOM board the physical panel
talks to) stays empty even after successfully enabling remote management.
## What the failures are not
Not a transport, permission, or cert problem: a control write of `rmState`
on `/rm/state/vs/0` was accepted (2.04 Changed, value held, restored
afterwards), and `FilterAlarmTime_` is written through the very same options
merge and kept. Writes work; this one value just isn't driven that way.
## The token, and why the dead ends below missed it
`FilterCleanAlarm_Clear` is not derived from anything in this file's earlier
attempts — how it was originally identified isn't recorded here. What is
recorded is why the standard technique (diff the appliance's reported state
before/after triggering the action in Samsung's app) couldn't have found it
on its own: the token is a trigger, never stored and never echoed back in
`x.com.samsung.da.options`, so a before/after diff of stored state shows
only the *effects* (counter zeroing, alarm clearing) and never the token
that caused them.
## Dead ends tried before the token was known (kept for the next unrelated mystery)
- The `/actions/vs/0` action vocabulary from an independent source (a
firmware image, or a capture of what the cloud sends the device).
- The IR path — the physical remote has a filter reset (Options → Filter
Reset → SET), and IRremoteESP8266 decodes this AC family, though issue
#1277's dump doesn't include that button.
## Evidence for the counter's direction and scale
Confirmed counting *up* (running time since last reset, not remaining time):
token 1710 matched the Samsung app's "171 hours 0 minutes" for the same
filter (pins the tenths-of-an-hour scale); seen rising while the unit ran
(171.0 → 171.5); and across two units on one site the `/alarms/vs/0` filter
alarm tracks the counter in the right direction — live (`FilterAlarm`,
`Created`) at `FilterTime_5595`, still the `FilterAlarm_OFF`/`Deleted`
placeholder at `FilterTime_1915`, matching the app's own 500-hour threshold
behavior. `FilterAlarmTime_` in the same options blob is that threshold (500
on every unit on record).
The entity key stays `filter_time` rather than `filter_time_elapsed`:
renaming it would change every existing unit's `entity_id`/`unique_id` for a
wording improvement only.
+1 -1
View File
@@ -6,7 +6,7 @@ pytest-homeassistant-custom-component>=0.13.316
# Integration runtime deps, needed to import the component under test
# (also declared in custom_components/localthings/manifest.json).
smartthings-local>=0.1.0
smartthings-local>=0.1.2
cbor2>=5.4.6
pyOpenSSL>=23.0
cryptography>=41.0
File diff suppressed because it is too large Load Diff
+138
View File
@@ -0,0 +1,138 @@
{
"device0": [
{
"rt": [
"x.com.samsung.devcol",
"oic.wk.col"
],
"if": [
"oic.if.baseline",
"oic.if.ll",
"oic.if.b"
]
},
{
"href": "/alarms/vs/0",
"rep": {
"rt": [
"x.com.samsung.da.alarms"
],
"if": [
"oic.if.baseline",
"oic.if.a"
],
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "0",
"x.com.samsung.da.description": "Alarm",
"x.com.samsung.da.alarmType": "Device",
"x.com.samsung.da.code": "CT_E",
"x.com.samsung.da.triggeredTime": "2026-08-06T14:24:02"
}
]
}
},
{
"href": "/bluetooth/hood/status/vs/0",
"rep": {
"connectionState": "disconnected",
"micomModelId": "",
"firmwareVersion": "",
"power": "off",
"fanSpeed": 0,
"lampState": "off",
"timer": {},
"rt": [
"bluetoothHoodStatus"
],
"if": [
"oic.if.baseline",
"oic.if.s"
]
}
},
{
"href": "/configuration/vs/0",
"rep": {}
},
{
"href": "/connected/vs/0",
"rep": {
"x.com.samsung.da.connected": "On",
"rt": [
"x.com.samsung.da.connected"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/kidslock/vs/0",
"rep": {
"x.com.samsung.da.kidsLock": "Ready"
}
},
{
"href": "/mode/vs/0",
"rep": {
"x.com.samsung.da.options": [
"DeviceType_NV8000T-/KO0",
"Pause_Off",
"SyncFlex_Off",
"FlexCoil_0",
"MainTimerCurrent_0",
"MainTimerSet_0",
"MainTimerState_Ready",
"IndependentTimerCheck_Enable",
"OperationState0_Ready",
"HotSurface0_Normal",
"PowerLevel0_0",
"OperationState1_Ready",
"HotSurface1_Normal",
"PowerLevel1_0",
"OperationState2_Ready",
"HotSurface2_Normal",
"PowerLevel2_0",
"OperationState3_Ready",
"HotSurface3_Normal",
"PowerLevel3_0",
"OperationState4_Ready",
"HotSurface4_Normal",
"PowerLevel4_0",
"OperationState5_Ready",
"HotSurface5_Normal",
"PowerLevel5_0"
],
"rt": [
"x.com.samsung.da.mode"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/otninformation/vs/0",
"rep": {
"x.com.samsung.da.target": "",
"x.com.samsung.da.newVersionAvailable": "false"
}
},
{
"href": "/power/vs/0",
"rep": {
"x.com.samsung.da.power": "Off",
"rt": [
"x.com.samsung.da.operation"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
}
]
}
+9
View File
@@ -1,5 +1,6 @@
{
"state_keys": [
"air_sensing_state",
"alarm_code",
"clean_level",
"device_active",
@@ -10,9 +11,17 @@
"firmware_update",
"hepa_filter_status",
"hepa_filter_usage",
"last_air_sensing_level",
"last_air_sensing_time",
"mute_once",
"odor",
"periodic_air_sensing",
"periodic_sensing_skip_status",
"power_switch",
"sensing_interval",
"sensing_mode",
"sensing_skip_end",
"sensing_skip_start",
"super_fine_dust",
"wind_strength_fan"
]
@@ -1,5 +1,6 @@
{
"state_keys": [
"air_sensing_state",
"alarm_code",
"child_lock",
"clean_level",
@@ -14,11 +15,18 @@
"firmware_update",
"hepa_filter_status",
"hepa_filter_usage",
"last_air_sensing_level",
"last_air_sensing_time",
"mute_once",
"odor",
"panel_status",
"periodic_air_sensing",
"periodic_sensing_skip_status",
"pet_filter_activation",
"power_switch",
"sensing_mode",
"sensing_skip_end",
"sensing_skip_start",
"sound_mode",
"sound_output",
"sound_volume",
+9
View File
@@ -1,5 +1,6 @@
{
"state_keys": [
"air_sensing_state",
"alarm_code",
"clean_level",
"device_active",
@@ -9,8 +10,16 @@
"firmware_update",
"hepa_filter_status",
"hepa_filter_usage",
"last_air_sensing_level",
"last_air_sensing_time",
"odor",
"periodic_air_sensing",
"periodic_sensing_skip_status",
"power_switch",
"sensing_interval",
"sensing_mode",
"sensing_skip_end",
"sensing_skip_start",
"super_fine_dust",
"wind_strength_fan"
]
+39
View File
@@ -0,0 +1,39 @@
{
"state_keys": [
"absence_clean",
"ai_energy_level",
"air_filter_status",
"air_filter_threshold",
"air_filter_usage",
"air_filter_usage_hours",
"air_purify",
"alarm_code",
"auto_clean",
"auto_clean_progress",
"auto_clean_running",
"beep",
"climate",
"current_temperature_c",
"display",
"energy_kwh",
"energy_saved_kwh",
"energy_saving_mode",
"energy_saving_operating_status",
"energy_saving_state",
"firmware_update",
"humidity",
"mute_once",
"odor_controller_active",
"odor_controller_progress",
"power_energy_kwh",
"power_watts",
"selfcheck_error",
"selfcheck_result",
"selfcheck_status",
"sound_mode",
"sound_output",
"tropical_night_mode",
"uv_led",
"ventilation_alarm"
]
}
@@ -2,6 +2,7 @@
"state_keys": [
"alarm_code",
"auto_clean_legacy",
"auto_clean_progress_legacy",
"beep",
"clean_level",
"climate",
@@ -18,6 +19,7 @@
"super_fine_dust",
"subdevice1_alarm_code",
"subdevice1_auto_clean_legacy",
"subdevice1_auto_clean_progress_legacy",
"subdevice1_beep",
"subdevice1_climate",
"subdevice1_current_temperature_c",
@@ -3,6 +3,7 @@
"air_monitoring",
"alarm_code",
"auto_clean_legacy",
"auto_clean_progress_legacy",
"beep",
"climate",
"current_temperature_c",
@@ -3,6 +3,7 @@
"air_monitoring",
"alarm_code",
"auto_clean_legacy",
"auto_clean_progress_legacy",
"beep",
"climate",
"current_temperature_c",
@@ -3,6 +3,7 @@
"air_monitoring",
"alarm_code",
"auto_clean_legacy",
"auto_clean_progress_legacy",
"beep",
"climate",
"current_temperature_c",
+18
View File
@@ -1,5 +1,6 @@
{
"state_keys": [
"absence_clean",
"absence_power_saving_active",
"absence_power_saving_mode",
"air_filter_pm1_status",
@@ -9,6 +10,7 @@
"air_filter_usage",
"air_filter_usage_hours",
"air_purify",
"air_sensing_state",
"alarm_code",
"auto_clean",
"auto_clean_progress",
@@ -17,20 +19,36 @@
"climate",
"current_temperature_c",
"dust",
"edge_lighting",
"edge_lighting_color",
"edge_lighting_mode",
"energy_kwh",
"energy_saved_kwh",
"fine_dust",
"firmware_update",
"humidity",
"indicator_light",
"indicator_light_mode",
"last_air_sensing_level",
"last_air_sensing_time",
"motion_detect_wind_active",
"motion_detect_wind_mode",
"mute_once",
"odor_controller_active",
"odor_controller_progress",
"periodic_air_sensing",
"periodic_sensing_skip_status",
"power_watts",
"selfcheck_error",
"selfcheck_result",
"selfcheck_status",
"sensing_interval",
"sensing_mode",
"sensing_skip_end",
"sensing_skip_start",
"sound_mode",
"sound_output",
"sound_volume",
"super_fine_dust",
"tropical_night_mode",
"uv_led"
@@ -5,6 +5,7 @@
"air_filter_usage",
"air_filter_usage_hours",
"air_purify",
"air_sensing_state",
"alarm_code",
"auto_clean",
"auto_clean_progress",
@@ -19,10 +20,18 @@
"fine_dust",
"firmware_update",
"humidity",
"last_air_sensing_level",
"last_air_sensing_time",
"mute_once",
"periodic_air_sensing",
"periodic_sensing_skip_status",
"selfcheck_error",
"selfcheck_result",
"selfcheck_status",
"sensing_interval",
"sensing_mode",
"sensing_skip_end",
"sensing_skip_start",
"super_fine_dust",
"tropical_night_mode"
]
+24
View File
@@ -0,0 +1,24 @@
{
"state_keys": [
"alarm_code",
"any_burner_active",
"burner_0_state",
"burner_1_state",
"burner_2_state",
"burner_3_state",
"burner_4_state",
"burner_5_state",
"child_lock",
"cloud_connected",
"firmware_update",
"main_timer_current",
"main_timer_state",
"paired_hood_connected",
"paired_hood_fan_speed",
"paired_hood_firmware",
"paired_hood_light",
"paired_hood_model",
"paired_hood_power",
"power_state"
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"state_keys": [
"alarm_code",
"burner_0_hot_surface",
"burner_0_pan_detected",
"burner_0_power_level",
"burner_0_state",
"burner_1_hot_surface",
"burner_1_pan_detected",
"burner_1_power_level",
"burner_1_state",
"burner_2_hot_surface",
"burner_2_pan_detected",
"burner_2_power_level",
"burner_2_state",
"cooktop_child_lock",
"cooktop_power",
"cooktop_safety_shutoff_enabled",
"cooktop_state",
"energy_kwh",
"firmware_update"
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"state_keys": [
"alarm_code",
"child_lock",
"cloud_connected",
"cook_time",
"current_temp_c",
"cycle_active",
"diagnosis_status",
"door_open",
"energy_saving",
"finish_time",
"firmware_update",
"machine_state",
"operation_time_minutes",
"oven_mode",
"oven_setpoint",
"oven_state",
"power_switch",
"progress_percentage",
"remote_control",
"sound"
]
}
@@ -0,0 +1,36 @@
{
"state_keys": [
"ai_energy_level",
"air_filter_status",
"air_filter_usage",
"alarm_code",
"auto_door_opener",
"brightness_level",
"cabinet_light_dim",
"cabinet_light_switch",
"cooler_setpoint",
"cooler_temperature",
"day_brightness",
"door_alert",
"door_cooler_open",
"door_freezer_open",
"energy_kwh",
"energy_saved_kwh",
"firmware_update",
"freezer_setpoint",
"freezer_temperature",
"fridge_sound",
"ice_night_mode",
"icemaker_one_enabled",
"icemaker_one_making_status",
"night_end",
"night_start",
"power_energy_kwh",
"power_watts",
"rapid_freezing",
"rapid_fridge",
"selfcheck_error",
"selfcheck_result",
"selfcheck_status"
]
}
+240
View File
@@ -0,0 +1,240 @@
{
"meta": {
"note": "Samsung NV9000D induction cooktop (NV9000D-/KO2). Scrubbed real /device/0 dump captured for compatibility regression coverage. This firmware starts directly with /connectionconfig/vs/0 instead of a device-level collection representation.",
"model": "TP1X_DA-KS-COOKTOP-01011",
"product": "NV9000D-/KO2"
},
"device0": [
{
"href": "/connectionconfig/vs/0",
"rep": {
"autoReconnectionMinVersion": "1.0",
"autoReconnection": "true",
"autoReconnectionProtocolType": [
"helper_hotspot",
"ble_ocf"
],
"supportedWiFiAuthType": [
"OPEN",
"WEP",
"WPA-PSK",
"WPA2-PSK",
"SAE"
],
"supportedWiFiCryptoType": [
"TKIP",
"AES",
"WEP-64",
"WEP-128"
],
"supportedWiFiFreq": [
"2.4G"
],
"calmConnectionCare": {
"version": "1.0",
"role": [
"things"
]
}
}
},
{
"href": "/otninformation/vs/0",
"rep": {
"x.com.samsung.da.target": "",
"x.com.samsung.da.newVersionAvailable": "false",
"x.com.samsung.da.newVersionNo": "00000000",
"x.com.samsung.da.currentVersionInfo": "00000000",
"flashingProgress": "",
"otnTarget": "main",
"otnStatus": "None",
"otnCompleteDate": "noHistory",
"otnList": [
{
"type": "WIFI",
"modelId": "AKS-WW-TP1-21-COOKTOP-2",
"versions": [
"40260330"
],
"visVersion": "260330"
},
{
"type": "Micom",
"modelId": "051140474341FFFFFFFF",
"versions": [
"26032400",
"FFFFFFFF"
],
"visVersion": "260324"
}
]
}
},
{
"href": "/alarms/vs/0",
"rep": {
"rt": [
"x.com.samsung.da.alarms"
],
"if": [
"oic.if.baseline",
"oic.if.s"
],
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "0",
"x.com.samsung.da.description": "Alarm",
"x.com.samsung.da.alarmType": "Device",
"x.com.samsung.da.code": "CT_E_OFF",
"x.com.samsung.da.triggeredTime": "**REDACTED**"
}
]
}
},
{
"href": "/cooktop/spec/vs/0",
"rep": {
"deviceType": "cooktop",
"micomModelId": "NV9000D-/KO2",
"supportedFeatureList": [
""
],
"numberOfBurners": 3,
"supportedBurnerList": [
0,
1,
2
],
"supportedPowerLevelList": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"boost",
"0"
]
}
},
{
"href": "/cooktop/status/vs/0",
"rep": {
"sequenceNumber": 485,
"power": "off",
"childLock": "off",
"operationState": "ready",
"additionalStateList": [
""
],
"burnerList": [
{
"burnerNumber": 0,
"mode": "normal",
"operationState": "ready",
"powerLevel": "0",
"hotSurfaceState": "normal",
"panDetection": true,
"timer": {
"operationState": "ready",
"cookingTime": 0,
"remainingTime": 0
}
},
{
"burnerNumber": 1,
"mode": "normal",
"operationState": "ready",
"powerLevel": "0",
"hotSurfaceState": "normal",
"panDetection": true,
"timer": {
"operationState": "ready",
"cookingTime": 0,
"remainingTime": 0
}
},
{
"burnerNumber": 2,
"mode": "normal",
"operationState": "ready",
"powerLevel": "0",
"hotSurfaceState": "normal",
"panDetection": true,
"timer": {
"operationState": "ready",
"cookingTime": 0,
"remainingTime": 0
}
}
]
}
},
{
"href": "/information/vs/0",
"rep": {
"x.com.samsung.da.modelNum": "TP1X_DA-KS-COOKTOP-01011|40474341|50000203001811000A00000000000000",
"x.com.samsung.da.description": "NV9000D-/KO2",
"x.com.samsung.da.serialNum": "**REDACTED**",
"x.com.samsung.da.otnDUID": "**REDACTED**",
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "0",
"x.com.samsung.da.description": "Version",
"x.com.samsung.da.type": "Software",
"x.com.samsung.da.number": "26033000",
"x.com.samsung.da.newVersionAvailable": "0"
},
{
"x.com.samsung.da.id": "1",
"x.com.samsung.da.description": "Version",
"x.com.samsung.da.type": "Firmware",
"x.com.samsung.da.number": "04743A26032400",
"x.com.samsung.da.newVersionAvailable": "0"
}
],
"x.com.samsung.da.diagProtocolType": "BLE_OCF",
"x.com.samsung.da.diagMinVersion": "3.0",
"x.com.samsung.da.diagLogType": [
"errCode",
"dump"
],
"x.com.samsung.da.diagDumpType": "file",
"x.com.samsung.da.diagEndPoint": "SSM",
"x.com.samsung.da.diagMnid": "0AJT",
"x.com.samsung.da.diagSetupid": "KC2",
"x.com.samsung.da.diagTsId": "DA01"
}
},
{
"href": "/timezone/vs/0",
"rep": {
"timezoneid": "Asia/Seoul",
"offset": "+09:00",
"DST": "OFF"
}
},
{
"href": "/cooktop/settings/status/vs/0",
"rep": {
"sequenceNumber": 104,
"safetyAlert": {
"state": "on",
"settingTime": 3600
}
}
},
{
"href": "/energy/consumption/vs/0",
"rep": {
"x.com.samsung.da.instantaneousPower": "-500",
"x.com.samsung.da.instantaneousPowerUnit": "W",
"x.com.samsung.da.cumulativePower": "218600",
"x.com.samsung.da.cumulativeUnit": "Wh"
}
}
]
}
+260
View File
@@ -0,0 +1,260 @@
{
"device0": [
{
"rt": [
"x.com.samsung.devcol",
"oic.wk.col"
],
"if": [
"oic.if.baseline",
"oic.if.ll",
"oic.if.b"
]
},
{
"href": "/alarms/vs/0",
"rep": {
"rt": [
"x.com.samsung.da.alarms"
],
"if": [
"oic.if.baseline",
"oic.if.s"
],
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "0",
"x.com.samsung.da.description": "Alarm",
"x.com.samsung.da.alarmType": "Device",
"x.com.samsung.da.code": "OV_E_OFF",
"x.com.samsung.da.triggeredTime": "2026-08-05T14:20:14"
}
]
}
},
{
"href": "/connected/vs/0",
"rep": {
"x.com.samsung.da.connected": "On",
"rt": [
"x.com.samsung.da.connected"
],
"if": [
"oic.if.baseline",
"oic.if.s"
]
}
},
{
"href": "/diagnosis/vs/0",
"rep": {
"x.com.samsung.da.diagnosisStart": "Ready"
}
},
{
"href": "/doors/vs/0",
"rep": {
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "0",
"x.com.samsung.da.description": "Door",
"x.com.samsung.da.openState": "Close",
"x.com.samsung.da.lock": "Unlock"
}
],
"rt": [
"x.com.samsung.da.doors"
],
"if": [
"oic.if.baseline",
"oic.if.s"
]
}
},
{
"href": "/information/vs/0",
"rep": {
"x.com.samsung.da.modelNum": "TP2X_DA-KS-WALLOVEN-000002|40441841|5002011E021011150100000000000000",
"x.com.samsung.da.description": "NW9000KD/AA1",
"x.com.samsung.da.serialNum": "**REDACTED**",
"x.com.samsung.da.otnDUID": "**REDACTED**",
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "0",
"x.com.samsung.da.description": "Version",
"x.com.samsung.da.type": "Software",
"x.com.samsung.da.number": "240205",
"x.com.samsung.da.newVersionAvailable": "0"
},
{
"x.com.samsung.da.id": "1",
"x.com.samsung.da.description": "Version",
"x.com.samsung.da.type": "Firmware",
"x.com.samsung.da.number": "DE92-04418A_20062500, DE92-04011A_17041300",
"x.com.samsung.da.newVersionAvailable": "0"
}
],
"x.com.samsung.da.diagProtocolType": "WIFI_HTTPS",
"x.com.samsung.da.diagLogType": [
"errCode",
"dump"
],
"x.com.samsung.da.diagDumpType": "file",
"x.com.samsung.da.diagEndPoint": "SSM",
"x.com.samsung.da.diagMnid": "0AJT",
"x.com.samsung.da.diagSetupid": "610",
"x.com.samsung.da.diagMinVersion": "1.0"
}
},
{
"href": "/kidslock/vs/0",
"rep": {
"x.com.samsung.da.kidsLock": "Ready"
}
},
{
"href": "/mode/vs/0",
"rep": {
"x.com.samsung.da.supportedModes": [
"ConvectionBake",
"ConvectionRoast",
"Bake",
"Broil",
"SteamBake",
"SteamRoast",
"Easycook3",
"Descale",
"PyroFree",
"Drain",
"SelfClean",
"NoOperation"
],
"x.com.samsung.da.modes": [
"NoOperation"
],
"x.com.samsung.da.options": [
"DeviceType_NW9000KD/AA1",
"keepWarmReservation_Off",
"meatprobe_disconnected",
"NoPreheat_Off",
"waterInlet_Closed",
"steamAddLevel_0",
"descaleAlarm_Normal",
"descaleNewWaterAlarm_Off",
"descaleEmptyWaterAlarm_Off",
"steamGeneratorLevel_Empty",
"steamUsingTime_66",
"drainRequired_00",
"steamState_Standby",
"descaleState_Standby",
"waterTankInSwitch_On",
"pyroFreeState_Standby",
"waterTankOutSwitch_Off",
"Sound_On",
"AdjustingTemp_0",
"Sabbath_Off",
"EnergySaving_On"
],
"rt": [
"x.com.samsung.da.mode"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/operational/state/vs/0",
"rep": {
"x.com.samsung.da.state": "Ready",
"x.com.samsung.da.operationTime": "00:00:00",
"x.com.samsung.da.remainingTime": "00:00:00",
"x.com.samsung.da.progressPercentage": "1",
"rt": [
"x.com.samsung.da.operation"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/otninformation/vs/0",
"rep": {
"x.com.samsung.da.target": "",
"x.com.samsung.da.newVersionAvailable": "false"
}
},
{
"href": "/oven/vs/0",
"rep": {
"x.com.samsung.da.state": "Ready",
"rt": [
"x.com.samsung.da.oven"
],
"if": [
"oic.if.baseline",
"oic.if.s"
]
}
},
{
"href": "/power/vs/0",
"rep": {
"x.com.samsung.da.power": "On",
"rt": [
"x.com.samsung.da.operation"
],
"if": [
"oic.if.baseline",
"oic.if.s"
]
}
},
{
"href": "/remotectrl/vs/0",
"rep": {
"x.com.samsung.da.remoteControlEnabled": "false",
"rt": [
"x.com.samsung.da.configuration"
],
"if": [
"oic.if.baseline",
"oic.if.s"
]
}
},
{
"href": "/temperatures/vs/0",
"rep": {
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "0",
"x.com.samsung.da.description": "Temperature",
"x.com.samsung.da.desired": "0",
"x.com.samsung.da.current": "0",
"x.com.samsung.da.increment": "0",
"x.com.samsung.da.unit": "Fahrenheit"
},
{
"x.com.samsung.da.id": "1",
"x.com.samsung.da.description": "Temperature",
"x.com.samsung.da.desired": "0",
"x.com.samsung.da.current": "0",
"x.com.samsung.da.increment": "0",
"x.com.samsung.da.unit": "Fahrenheit"
}
],
"rt": [
"x.com.samsung.da.temperatures"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
}
]
}
@@ -0,0 +1,623 @@
{
"device0": [
{
"rt": [
"x.com.samsung.devcol",
"oic.wk.col"
],
"if": [
"oic.if.baseline",
"oic.if.ll",
"oic.if.b"
]
},
{
"href": "/alarms/vs/0",
"rep": {
"href": "/alarms/vs/0",
"rt": [
"x.com.samsung.da.alarms"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/bespoke/vs/0",
"rep": {
"x.com.samsung.da.BespokeProduct": "On",
"href": "/bespoke/vs/0"
}
},
{
"href": "/cabinet/light/enhanced/vs/0",
"rep": {
"light.control.status": "On",
"level.brightness.daytime": "100",
"level.brightness.nighttime": "33",
"night.starttime": "2026-08-07T12:00:00",
"night.duration.minute": "540",
"timezone.offset": "+09:00",
"href": "/cabinet/light/enhanced/vs/0",
"rt": [
"x.com.samsung.da.light.enhanced"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/cabinet/light/total/vs/0",
"rep": {
"x.com.samsung.da.lightLevel": "100",
"x.com.samsung.da.lightResolution": "3",
"x.com.samsung.da.lightControl.off.include": "Off",
"x.com.samsung.da.lightControl": "Off",
"x.com.samsung.da.lightControl.hide": "true",
"light.dimming.status": "On",
"href": "/cabinet/light/total/vs/0",
"rt": [
"x.com.samsung.da.cabinetlight"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/configuration/vs/0",
"rep": {
"x.com.samsung.da.region": "",
"x.com.samsung.da.countryCode": "",
"href": "/configuration/vs/0"
}
},
{
"href": "/connectionconfig/vs/0",
"rep": {
"autoReconnectionMinVersion": "1.0",
"autoReconnection": "true",
"autoReconnectionProtocolType": [
"helper_hotspot",
"ble_ocf"
],
"supportedWiFiAuthType": [
"OPEN",
"WEP",
"WPA-PSK",
"WPA2-PSK",
"SAE"
],
"supportedWiFiCryptoType": [
"TKIP",
"AES",
"WEP-64",
"WEP-128"
],
"supportedWiFiFreq": [
"2.4G"
],
"calmConnectionCare": {
"version": "1.0",
"role": [
"things"
]
}
}
},
{
"href": "/defrost/prediction/vs/0",
"rep": {
"ai.cooling.care": "Off",
"href": "/defrost/prediction/vs/0"
}
},
{
"href": "/dginformation/vs/0",
"rep": {
"enrolmentstatus": "Unknown",
"devicestate": "Unknown",
"lockstatus": "Normal",
"nextduedate": "",
"workingminutes": 0,
"paymentinfo": {
"emiplan": "Unknown",
"currency": "Unknown",
"totalemi": 0,
"totalemipaid": 0
}
}
},
{
"href": "/door/cooler/0",
"rep": {
"openState": "Close",
"href": "/door/cooler/0",
"rt": [
"oic.r.door"
],
"if": [
"oic.if.baseline",
"oic.if.s"
]
}
},
{
"href": "/door/freezer/0",
"rep": {
"openState": "Close",
"href": "/door/freezer/0",
"rt": [
"oic.r.door"
],
"if": [
"oic.if.baseline",
"oic.if.s"
]
}
},
{
"href": "/doors/vs/0",
"rep": {
"x.com.samsung.da.items": [
{
"x.com.samsung.da.openState": "Close",
"x.com.samsung.da.id": "0",
"x.com.samsung.da.description": "Door"
},
{
"x.com.samsung.da.openState": "Close",
"x.com.samsung.da.id": "1",
"x.com.samsung.da.description": "Door"
}
],
"href": "/doors/vs/0"
}
},
{
"href": "/drlc/vs/0",
"rep": {
"x.com.samsung.da.drlcLevel": "2",
"x.com.samsung.da.override": "Not_Supported",
"x.com.samsung.da.durationminutes": "1441",
"x.com.samsung.da.start": "2026-08-07T00:00:41Z",
"x.com.samsung.da.realSaving": "On",
"href": "/drlc/vs/0"
}
},
{
"href": "/energy/ailevel/vs/0",
"rep": {
"aiLevel": "1",
"supportedAiLevel": [
"1",
"2"
],
"href": "/energy/ailevel/vs/0"
}
},
{
"href": "/energy/consumption/vs/0",
"rep": {
"x.com.samsung.da.cumulativeConsumption": "25344",
"x.com.samsung.da.instantaneousPower": "48",
"x.com.samsung.da.cumulativePower": "413385",
"x.com.samsung.da.cumulativeSavedPower": "50694",
"x.com.samsung.da.cumulativeUnit": "Wh",
"x.com.samsung.da.instantaneousPowerUnit": "W",
"href": "/energy/consumption/vs/0",
"x.com.samsung.da.cumulativeDateUTC": "1786020360"
}
},
{
"href": "/file/information/vs/0",
"rep": {
"x.com.samsung.timeoffset": "+09:00",
"x.com.samsung.supprtedtype": 1,
"href": "/file/information/vs/0"
}
},
{
"href": "/filter/airdustfilter/vs/0",
"rep": {
"x.com.samsung.da.filterUsage": "100",
"x.com.samsung.da.filterUsageResolution": "1",
"x.com.samsung.da.filterResetType": [
"washable"
],
"x.com.samsung.da.filterStatus": "wash",
"href": "/filter/airdustfilter/vs/0"
}
},
{
"href": "/icemaker/nighttime/vs/0",
"rep": {
"ice.night.status": "On",
"ice.night.starttime": "2026-08-07T12:00:00",
"ice.night.duration": "540",
"ice.night.timezone": "+09:00",
"href": "/icemaker/nighttime/vs/0",
"rt": [
"x.com.samsung.da.ice.night"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/icemaker/one/vs/0",
"rep": {
"x.com.samsung.da.iceMaker.name": "ICE_MAKER",
"x.com.samsung.da.iceMaker.state": "On",
"x.com.samsung.da.iceType.desired": "NORMAL",
"x.com.samsung.da.iceMaker.iceMakingStatus": "ICESTATUS_STOP",
"x.com.samsung.da.iceMaker.type": "toggle",
"href": "/icemaker/one/vs/0",
"rt": [
"x.com.samsung.da.icemaker"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/icemaker/status/vs/0",
"rep": {
"x.com.samsung.da.iceMaker": "On",
"href": "/icemaker/status/vs/0"
}
},
{
"href": "/information/vs/0",
"rep": {
"x.com.samsung.da.modelNum": "TP1X_REF_21K|70664141|0000033C011913114100000041FB5F00",
"x.com.samsung.da.description": "TP1X_REF_21K",
"x.com.samsung.da.serialNum": "**REDACTED**",
"x.com.samsung.da.otnDUID": "**REDACTED**",
"x.com.samsung.da.diagDumpType": "file",
"x.com.samsung.da.diagEndPoint": "SSM",
"x.com.samsung.da.diagLogType": [
"errCode",
"dump"
],
"x.com.samsung.da.diagMnid": "0AJT",
"x.com.samsung.da.diagSetupid": "RR7",
"x.com.samsung.da.diagProtocolType": "BLE_OCF",
"x.com.samsung.da.diagMinVersion": "3.0",
"x.com.samsung.da.diagTsId": "DA01",
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "0",
"x.com.samsung.da.description": "WiFi Module",
"x.com.samsung.da.type": "Software",
"x.com.samsung.da.number": "260618",
"x.com.samsung.da.newVersionAvailable": "0"
},
{
"x.com.samsung.da.id": "1",
"x.com.samsung.da.description": "Micom",
"x.com.samsung.da.type": "Firmware",
"x.com.samsung.da.number": "2605071D, 24120906, 26040701, FFFFFFFF, 25082208, FFFFFFFF",
"x.com.samsung.da.newVersionAvailable": "0"
}
],
"href": "/information/vs/0"
}
},
{
"href": "/mode/vs/0",
"rep": {
"x.com.samsung.da.supportedModes": [
"HOMECARE_WIZARD_V2",
"ENERGY_REPORT_MODEL",
"18K_REF_OUTDOOR_CONTROL_V2"
],
"href": "/mode/vs/0",
"rt": [
"x.com.samsung.da.mode"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/otninformation/vs/0",
"rep": {
"x.com.samsung.da.target": "Micom",
"x.com.samsung.da.newVersionAvailable": "false",
"x.com.samsung.da.newVersionNo": "26040701",
"x.com.samsung.da.currentVersionInfo": "10000000",
"otnStatus": "None",
"flashingProgress": "0",
"otnTarget": "inverter",
"otnCompleteDate": "noHistory",
"scheduledTime": "None",
"swVersionInfo": {
"platform": "Tizen Lite",
"oneUiVersion": "7.0 Refrigerator",
"osVersion": "4.0"
},
"otnList": [
{
"type": "WIFI",
"modelId": "A-RFWW-TP1-24-T4-RE1",
"versions": [
"20260618"
],
"visVersion": "260618"
},
{
"type": "Micom",
"modelId": "823070664141FFFFFFFF",
"versions": [
"2605071D",
"FFFFFFFF"
],
"visVersion": "260507"
},
{
"type": "Micom",
"modelId": "823070664041FFFFFFFF",
"versions": [
"24120906",
"FFFFFFFF"
],
"visVersion": "241209"
},
{
"type": "Micom",
"modelId": "02307066414170664041",
"versions": [
"2605071D",
"24120906"
],
"visVersion": "260507"
},
{
"type": "Micom",
"modelId": "023070680641FFFFFFFF",
"versions": [
"26040701",
"FFFFFFFF"
],
"visVersion": "260407"
},
{
"type": "Micom",
"modelId": "023070668841FFFFFFFF",
"versions": [
"25082208",
"FFFFFFFF"
],
"visVersion": "250822"
}
]
}
},
{
"href": "/quickcontrol/info/vs/0",
"rep": {
"supportedVersion": "1.0"
}
},
{
"href": "/realtimenotiforclient/vs/0",
"rep": {
"x.com.samsung.da.timeforshortnoti": "0",
"x.com.samsung.da.periodicnotisubscription": "true",
"href": "/realtimenotiforclient/vs/0"
}
},
{
"href": "/refrigeration/vs/0",
"rep": {
"x.com.samsung.da.rapidFridge": "Off",
"x.com.samsung.da.rapidFreezing": "Off",
"href": "/refrigeration/vs/0",
"rt": [
"x.com.samsung.da.fridge"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/rm/control/vs/0",
"rep": {
"minPeriod": "9000",
"href": "/rm/control/vs/0"
}
},
{
"href": "/runningmode/vs/0",
"rep": {
"x.com.samsung.da.runningMode": 0,
"href": "/runningmode/vs/0"
}
},
{
"href": "/selfcheck/vs/0",
"rep": {
"x.com.samsung.da.supportedActions": [
"Start"
],
"x.com.samsung.da.status": "Ready",
"x.com.samsung.da.result": "Success",
"x.com.samsung.da.error": [
"ErrorCode_None"
],
"href": "/selfcheck/vs/0"
}
},
{
"href": "/settings/sound/alert/door/vs/0",
"rep": {
"alert.door": "1",
"supportedAlert.door": [
"1",
"2",
"3",
"4"
],
"href": "/settings/sound/alert/door/vs/0",
"rt": [
"x.com.samsung.alert.door"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/status/lock/vs/0",
"rep": {
"x.com.samsung.da.device.sound": "On",
"x.com.samsung.da.preciseCooling": "On",
"x.com.samsung.da.doorAlarmSound": "On",
"cleaning.status": "On",
"cleaning.type": "SPI_AND_UV",
"href": "/status/lock/vs/0",
"rt": [
"x.com.samsung.da.lockstatus"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/temperature/current/cooler/0",
"rep": {
"temperature": 2.0,
"range": [
1.0,
7.0
],
"units": "C",
"href": "/temperature/current/cooler/0",
"rt": [
"oic.r.temperature"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/temperature/current/freezer/0",
"rep": {
"temperature": -19.0,
"range": [
-23.0,
-15.0
],
"units": "C",
"href": "/temperature/current/freezer/0",
"rt": [
"oic.r.temperature"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/temperature/desired/cooler/0",
"rep": {
"temperature": 2.0,
"range": [
1.0,
7.0
],
"units": "C",
"href": "/temperature/desired/cooler/0",
"rt": [
"oic.r.temperature"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/temperature/desired/freezer/0",
"rep": {
"temperature": -19.0,
"range": [
-23.0,
-15.0
],
"units": "C",
"href": "/temperature/desired/freezer/0",
"rt": [
"oic.r.temperature"
],
"if": [
"oic.if.baseline",
"oic.if.a"
]
}
},
{
"href": "/temperatures/vs/0",
"rep": {
"temperature.unit.control": "true",
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "0",
"x.com.samsung.da.description": "Freezer",
"x.com.samsung.da.desired": "-19",
"x.com.samsung.da.current": "-19",
"x.com.samsung.da.maximum": "-15",
"x.com.samsung.da.minimum": "-23",
"x.com.samsung.da.unit": "Celsius"
},
{
"x.com.samsung.da.id": "1",
"x.com.samsung.da.description": "Fridge",
"x.com.samsung.da.desired": "2",
"x.com.samsung.da.current": "2",
"x.com.samsung.da.maximum": "7",
"x.com.samsung.da.minimum": "1",
"x.com.samsung.da.unit": "Celsius"
}
],
"href": "/temperatures/vs/0"
}
},
{
"href": "/timezone/vs/0",
"rep": {
"timezoneid": "Asia/Seoul",
"offset": "+09:00",
"DST": "OFF"
}
},
{
"href": "/wirelessinfo/vs/0",
"rep": {
"macaddressWiFi": "**REDACTED**",
"macaddressBLE": "**REDACTED**",
"connectedApSsid": "eomkim_IoT"
}
}
]
}
+60 -15
View File
@@ -14,10 +14,14 @@ from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.localthings.const import (
CONF_CA_CERT_PEM,
CONF_CA_KEY_PEM,
CONF_DEVICE_TYPE,
CONF_HOST,
CONF_LEAF_CERT_PEM,
CONF_LEAF_KEY_PEM,
CONF_MANUFACTURER,
CONF_MODEL,
CONF_PORT,
CONF_SERIAL,
DOMAIN,
)
from custom_components.localthings.coordinator import LocalThingsCoordinator
@@ -74,7 +78,12 @@ FIXTURES = Path(__file__).resolve().parent.parent / "fixtures"
MOCK_HOST = "10.0.0.254"
MOCK_PORT = 49154
MOCK_SERIAL = "TEST-SERIAL-001"
# Matches the identity in tests/fixtures/refrigerator_device.json, which is
# what mock_coordinator_session polls -- so an entry built from ENTRY_DATA and
# the device it "reaches" agree on who they are, the same as in production.
MOCK_SERIAL = "TEST-SERIAL-0000"
MOCK_MODEL = "TEST-MODEL"
MOCK_DEVICE_TYPE = "refrigerator"
MOCK_CA_CERT_PEM = "-----BEGIN CERTIFICATE-----\nTEST-CA\n-----END CERTIFICATE-----"
MOCK_CA_KEY_PEM = "-----BEGIN PRIVATE KEY-----\nTEST-CA-KEY\n-----END PRIVATE KEY-----"
MOCK_LEAF_CERT_PEM = "-----BEGIN CERTIFICATE-----\nTEST-LEAF\n-----END CERTIFICATE-----"
@@ -87,6 +96,23 @@ ENTRY_DATA = {
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
CONF_LEAF_CERT_PEM: MOCK_LEAF_CERT_PEM,
CONF_LEAF_KEY_PEM: MOCK_LEAF_KEY_PEM,
# Identity the config flow's probe resolved (issue #236) -- what the
# coordinator keys its devices and entities on from construction.
CONF_SERIAL: MOCK_SERIAL,
CONF_MODEL: MOCK_MODEL,
CONF_MANUFACTURER: "Samsung",
CONF_DEVICE_TYPE: MOCK_DEVICE_TYPE,
}
# A pre-identity entry, as a real install upgrading through the v1 -> v2
# migration still has it on disk.
LEGACY_ENTRY_DATA = {
CONF_HOST: MOCK_HOST,
CONF_PORT: MOCK_PORT,
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
CONF_LEAF_CERT_PEM: MOCK_LEAF_CERT_PEM,
CONF_LEAF_KEY_PEM: MOCK_LEAF_KEY_PEM,
}
@@ -102,18 +128,25 @@ def fridge_resources():
return _load_fridge_resources()
def _probe_result(*, recognized: bool) -> dict:
return {
"port": MOCK_PORT,
"serial": MOCK_SERIAL,
"model": MOCK_MODEL,
"manufacturer": "Samsung",
"device_type_name": MOCK_DEVICE_TYPE if recognized else None,
"device_type_recognized": recognized,
"leaf_cert_pem": MOCK_LEAF_CERT_PEM,
"leaf_key_pem": MOCK_LEAF_KEY_PEM,
}
@pytest.fixture
def mock_probe():
"""Patch _probe_and_validate to succeed (recognized type) without a real DTLS connection."""
with patch(
"custom_components.localthings.config_flow._probe_and_validate",
return_value={
"port": MOCK_PORT,
"serial": MOCK_SERIAL,
"leaf_cert_pem": MOCK_LEAF_CERT_PEM,
"leaf_key_pem": MOCK_LEAF_KEY_PEM,
"device_type_recognized": True,
},
return_value=_probe_result(recognized=True),
) as m:
yield m
@@ -123,13 +156,7 @@ def mock_probe_unknown_type():
"""Patch _probe_and_validate to succeed, but with an unrecognized device type."""
with patch(
"custom_components.localthings.config_flow._probe_and_validate",
return_value={
"port": MOCK_PORT,
"serial": MOCK_SERIAL,
"leaf_cert_pem": MOCK_LEAF_CERT_PEM,
"leaf_key_pem": MOCK_LEAF_KEY_PEM,
"device_type_recognized": False,
},
return_value=_probe_result(recognized=False),
) as m:
yield m
@@ -218,6 +245,24 @@ def mock_entry(hass):
domain=DOMAIN,
data=ENTRY_DATA,
unique_id=f"localthings_{MOCK_SERIAL}",
version=2,
)
entry.add_to_hass(hass)
return entry
@pytest.fixture
def legacy_entry(hass):
"""A v1 entry with no stored identity, as an upgrading install has it.
Its device identity is only knowable from the first poll, which is the
one case where _run_discovery still adopts what the device reports.
"""
entry = MockConfigEntry(
domain=DOMAIN,
data=LEGACY_ENTRY_DATA,
unique_id=f"localthings_{MOCK_SERIAL}",
version=1,
)
entry.add_to_hass(hass)
return entry
+664 -66
View File
@@ -3,9 +3,10 @@
from __future__ import annotations
from collections.abc import Iterable
from typing import cast
from typing import ClassVar, cast
from unittest.mock import patch
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from pytest_homeassistant_custom_component.common import MockConfigEntry
@@ -15,6 +16,7 @@ from custom_components.localthings.const import (
CONF_CA_CERT_PEM,
CONF_CA_KEY_PEM,
CONF_HOST,
CONF_LEAF_CERT_PEM,
CONF_PORT,
DOMAIN,
)
@@ -24,6 +26,8 @@ from .conftest import (
MOCK_CA_CERT_PEM,
MOCK_CA_KEY_PEM,
MOCK_HOST,
MOCK_LEAF_CERT_PEM,
MOCK_MODEL,
MOCK_PORT,
MOCK_SERIAL,
)
@@ -71,6 +75,41 @@ async def test_successful_setup(hass: HomeAssistant, mock_probe) -> None:
assert result["data"][CONF_CA_CERT_PEM] == MOCK_CA_CERT_PEM
async def test_setup_normalizes_messy_pasted_pem(hass: HomeAssistant, mock_probe) -> None:
"""A PEM with a leading UTF-8 BOM, CRLF line endings, and a stray blank
line -- the kind a Windows text editor's copy produces, as opposed to a
`type` dump (issue #291) -- must still be accepted and stored in its
normalized form, not rejected with an opaque InvalidHeader."""
messy_cert = "\ufeff" + MOCK_CA_CERT_PEM.replace("\n", "\r\n") + "\r\n\r\n"
messy_key = "\ufeff" + MOCK_CA_KEY_PEM.replace("\n", "\r\n")
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: MOCK_HOST,
CONF_CA_CERT_PEM: messy_cert,
CONF_CA_KEY_PEM: messy_key,
},
)
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["data"][CONF_CA_CERT_PEM] == MOCK_CA_CERT_PEM
assert result["data"][CONF_CA_KEY_PEM] == MOCK_CA_KEY_PEM
def test_normalize_pem_strips_bom_crlf_and_blank_lines() -> None:
"""Unit-level check of the helper itself, isolated from the flow."""
from custom_components.localthings.config_flow import _normalize_pem
messy = "\ufeff-----BEGIN CERTIFICATE-----\r\nTEST-CA\r\n\r\n-----END CERTIFICATE-----\r\n"
assert _normalize_pem(messy) == (
"-----BEGIN CERTIFICATE-----\nTEST-CA\n-----END CERTIFICATE-----"
)
# A clean PEM (the `type`-dump case) passes through unchanged.
clean = "-----BEGIN CERTIFICATE-----\nTEST-CA\n-----END CERTIFICATE-----"
assert _normalize_pem(clean) == clean
def test_order_candidates_prefers_known_ports() -> None:
"""Live ports are ordered with the historically known DTLS ports first,
then the rest ascending."""
@@ -120,10 +159,15 @@ def test_find_live_ports_detects_silent_port(socket_enabled) -> None:
finally:
live_sock.close()
assert result == [live_port]
assert result.live == [live_port]
# Refused, not unreachable: loopback is up and answered. That distinction
# is what stops a wrong-but-live IP and an address with nothing on it
# producing the same message.
assert result.refused == sorted(closed_ports)
assert result.unreachable == []
def test_find_live_ports_rescues_preferred_ports_the_sweep_missed(
def test_sweep_ports_rescues_preferred_ports_the_sweep_missed(
socket_enabled,
monkeypatch,
) -> None:
@@ -141,7 +185,7 @@ def test_find_live_ports_rescues_preferred_ports_the_sweep_missed(
import socket
from custom_components.localthings import config_flow
from custom_components.localthings.config_flow import _find_live_ports
from custom_components.localthings.config_flow import _sweep_ports
# Bind an OS-assigned port and immediately close it, same technique
# test_find_live_ports_detects_silent_port uses for its "closed" ports --
@@ -158,64 +202,155 @@ def test_find_live_ports_rescues_preferred_ports_the_sweep_missed(
live_port = live_sock.getsockname()[1]
try:
result = _find_live_ports("127.0.0.1", [preferred_port, live_port], 0.8)
sweep, candidates = _sweep_ports("127.0.0.1", [preferred_port, live_port], 0.8)
finally:
live_sock.close()
assert set(result) == {preferred_port, live_port}
# The sweep's own verdict stays honest -- it really didn't see the
# preferred port -- and the rescue shows up only in the candidate list.
assert sweep.live == [live_port]
assert set(candidates) == {preferred_port, live_port}
async def test_probe_uses_discovered_low_port(hass: HomeAssistant, monkeypatch) -> None:
"""A device that only answers on 49153 — outside the historical
49154/49155 pair — is found by the liveness sweep and its port is stored
on the config entry (issue #13)."""
import cbor2
WASHER_DEVICE0 = [
{"rt": ["x.com.samsung.devcol"]},
{
"href": "/information/vs/0",
"rep": {
"x.com.samsung.da.modelNum": "DA_WM_TP1_21_COMMON|20375141|20010002001811424AA30217008A0000", # noqa: E501
"x.com.samsung.da.description": "DA_WM_TP1_21_COMMON_WW5000C/DC92-03495A_B048",
"x.com.samsung.da.serialNum": "DISHWASHER-49153",
},
},
{"href": "/otninformation/vs/0", "rep": {"otnStatus": "None"}},
]
class FakeSession:
"""Stand-in for DtlsCoapSession that answers /device/0 for any path.
`reject_certs` models a device whose DTLS stack breaks the handshake off
itself -- the library raises ConnectionError for that, as opposed to the
TimeoutError it raises when nothing answers at all.
"""
instances: ClassVar[list[FakeSession]] = []
reject_certs: ClassVar[set[str]] = set()
def __init__(self, host, port, cert_pem=None, key_pem=None, **kwargs):
self.host, self.port, self.cert_pem = host, port, cert_pem
FakeSession.instances.append(self)
def connect(self):
if self.cert_pem in FakeSession.reject_certs:
raise ConnectionError(
"DTLS handshake error: [('SSL routines', '', 'sslv3 alert bad certificate')]"
)
def start_reader(self):
pass
def get(self, path, timeout=15.0):
import cbor2
return 0x45, cbor2.dumps(WASHER_DEVICE0)
def close(self):
pass
@pytest.fixture
def fake_dtls(monkeypatch):
"""Wire the probe path up to FakeSession with no real network anywhere."""
from custom_components.localthings import config_flow
device0 = [
{"rt": ["x.com.samsung.devcol"]},
{
"href": "/information/vs/0",
"rep": {
"x.com.samsung.da.modelNum": "DA_WM_TP1_21_COMMON|20375141|20010002001811424AA30217008A0000", # noqa: E501
"x.com.samsung.da.description": "DA_WM_TP1_21_COMMON_WW5000C/DC92-03495A_B048",
"x.com.samsung.da.serialNum": "DISHWASHER-49153",
},
},
{"href": "/otninformation/vs/0", "rep": {"otnStatus": "None"}},
]
class _FakeSession:
def __init__(self, host, port, cert_pem=None, key_pem=None):
self.host, self.port = host, port
def connect(self):
pass
def start_reader(self):
pass
def get(self, path, timeout=15.0):
return 0x45, cbor2.dumps(device0)
def close(self):
pass
FakeSession.instances = []
FakeSession.reject_certs = set()
monkeypatch.setattr(config_flow, "_fetch_samsung_uuid", lambda: "test-uuid")
monkeypatch.setattr(
config_flow,
"_mint_leaf_cert",
lambda ca_cert, ca_key, uuid: ("FULLCHAIN", "LEAFKEY"),
)
monkeypatch.setattr(
config_flow,
"_find_live_ports",
lambda host, ports, timeout: [49153],
)
monkeypatch.setattr(
"smartthings_local.protocol.dtls_session.DtlsCoapSession",
_FakeSession,
FakeSession,
)
return FakeSession
class _FakeProbeResult:
def __init__(self, port, live):
self.port, self.outcome = port, "live" if live else "dead"
self.is_dtls_server = live
def __repr__(self):
return f"<ProbeResult {self.port} {self.outcome}>"
def _patch_clienthello(monkeypatch, live_ports):
"""Patch the library's ClientHello probe to report `live_ports` as DTLS."""
from custom_components.localthings import config_flow
calls: list[int] = []
def _probe(host, port, **kwargs):
calls.append(port)
return _FakeProbeResult(port, port in live_ports)
monkeypatch.setattr(config_flow, "_clienthello_probe", _probe)
return calls
async def test_clienthello_probe_picks_the_confirmed_port(
hass: HomeAssistant, monkeypatch, fake_dtls
) -> None:
"""Issue #211: the stateless ClientHello probe identifies the real DTLS
port, so exactly one port gets a full certificate handshake -- not every
port the UDP sweep couldn't rule out, each costing 12s to time out."""
from custom_components.localthings import config_flow
probed = _patch_clienthello(monkeypatch, {49153})
def _no_sweep(host, ports, timeout):
raise AssertionError("UDP sweep must not run once a port is confirmed")
monkeypatch.setattr(config_flow, "_find_live_ports", _no_sweep)
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: MOCK_HOST,
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
},
)
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["data"][CONF_PORT] == 49153
# The whole range is probed (cheaply, in parallel) but only the confirmed
# port is handed a handshake.
assert set(probed) == set(config_flow.PROBE_PORT_RANGE)
assert [s.port for s in FakeSession.instances] == [49153]
async def test_probe_uses_discovered_low_port(hass: HomeAssistant, monkeypatch, fake_dtls) -> None:
"""A device that only answers on 49153 — outside the historical
49154/49155 pair — is found by the liveness sweep and its port is stored
on the config entry (issue #13).
The sweep is the fallback now: it runs when the ClientHello probe confirms
nothing, which covers both a path that eats our ClientHello and an install
still on smartthings-local < 0.1.2.
"""
from custom_components.localthings import config_flow
_patch_clienthello(monkeypatch, set())
monkeypatch.setattr(
config_flow,
"_sweep_ports",
lambda host, ports, timeout: (_sweep_result(live=[49153]), [49153]),
)
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
@@ -231,6 +366,412 @@ async def test_probe_uses_discovered_low_port(hass: HomeAssistant, monkeypatch)
assert result["data"][CONF_PORT] == 49153
async def test_probe_falls_back_when_library_lacks_the_clienthello_probe(
hass: HomeAssistant, monkeypatch, fake_dtls
) -> None:
"""An install whose smartthings-local predates the probe still adds
devices -- port detection degrades to the UDP sweep rather than failing."""
from custom_components.localthings import config_flow
def _missing(host, port, **kwargs):
raise ImportError("no module named dtls_probe")
monkeypatch.setattr(config_flow, "_clienthello_probe", _missing)
monkeypatch.setattr(
config_flow,
"_sweep_ports",
lambda host, ports, timeout: (_sweep_result(live=[49154]), [49154]),
)
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: MOCK_HOST,
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
},
)
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["data"][CONF_PORT] == 49154
async def test_entry_stores_resolved_identity(hass: HomeAssistant, monkeypatch, fake_dtls) -> None:
"""The probe's identity lands on the entry (issue #236), so the
coordinator can key its device and entities before the first poll."""
from custom_components.localthings import config_flow
from custom_components.localthings.const import (
CONF_DEVICE_TYPE,
CONF_MANUFACTURER,
CONF_MODEL,
CONF_SERIAL,
)
_patch_clienthello(monkeypatch, {49154})
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: MOCK_HOST,
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
},
)
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["data"][CONF_SERIAL] == "DISHWASHER-49153"
assert result["data"][CONF_MODEL] == "DA_WM_TP1_21_COMMON"
assert result["data"][CONF_MANUFACTURER] == "Samsung"
assert result["data"][CONF_DEVICE_TYPE] == "washer"
assert result["title"] == f"Samsung Washer ({MOCK_HOST})"
assert result["result"].version == config_flow.LocalThingsConfigFlow.VERSION
async def test_second_device_reuses_the_existing_leaf(
hass: HomeAssistant, monkeypatch, fake_dtls
) -> None:
"""Adding a second appliance skips the Samsung-cloud round trip: every
device accepts the same leaf, and the existing entry already has one
(issue #211). That makes the add independent of cloud reachability, not
just faster."""
from custom_components.localthings import config_flow
existing = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id="localthings_other")
existing.add_to_hass(hass)
_patch_clienthello(monkeypatch, {49154})
def _no_cloud():
raise AssertionError("must not contact Samsung's cloud when a leaf is available")
monkeypatch.setattr(config_flow, "_fetch_samsung_uuid", _no_cloud)
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: MOCK_HOST}
)
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["data"][CONF_LEAF_CERT_PEM] == MOCK_LEAF_CERT_PEM
assert FakeSession.instances[0].cert_pem == MOCK_LEAF_CERT_PEM
async def test_rejected_reused_leaf_is_reminted(
hass: HomeAssistant, monkeypatch, fake_dtls
) -> None:
"""The UUID behind the shared leaf does rotate. A confirmed-live device
rejecting the reused one is unambiguous enough to mint a fresh cert and
try again, so credential reuse stays self-correcting."""
existing = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id="localthings_other")
existing.add_to_hass(hass)
_patch_clienthello(monkeypatch, {49154})
FakeSession.reject_certs = {MOCK_LEAF_CERT_PEM}
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: MOCK_HOST}
)
assert result["type"] == FlowResultType.CREATE_ENTRY
# Freshly minted, and it's the fresh one that got stored.
assert result["data"][CONF_LEAF_CERT_PEM] == "FULLCHAIN"
assert [s.cert_pem for s in FakeSession.instances] == [MOCK_LEAF_CERT_PEM, "FULLCHAIN"]
async def test_unconfirmed_port_failure_is_not_reminted(
hass: HomeAssistant, monkeypatch, fake_dtls
) -> None:
"""A timeout means nothing answered, which a fresh certificate can't fix
-- so the re-mint retry stays scoped to a device that proved it is there
and broke the handshake off itself."""
from custom_components.localthings import config_flow
existing = MockConfigEntry(domain=DOMAIN, data=ENTRY_DATA, unique_id="localthings_other")
existing.add_to_hass(hass)
_patch_clienthello(monkeypatch, set())
monkeypatch.setattr(
config_flow,
"_sweep_ports",
lambda host, ports, timeout: (_sweep_result(live=[49154]), [49154]),
)
def _timeout(self):
raise TimeoutError("DTLS handshake timeout")
monkeypatch.setattr(FakeSession, "connect", _timeout)
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: MOCK_HOST}
)
assert result["type"] == FlowResultType.FORM
errors = result["errors"]
assert errors is not None
assert errors["base"] == "no_dtls_server"
assert len(FakeSession.instances) == 1
# ---------------------------------------------------------------------------
# Failure classification: one "cannot connect" used to cover all of these
# ---------------------------------------------------------------------------
def _sweep_result(live=(), refused=(), unreachable=()):
from custom_components.localthings.config_flow import _SweepResult
return _SweepResult(list(live), list(refused), list(unreachable))
def _scan(confirmed=(), swept=None, candidates=(49154,)):
from custom_components.localthings.config_flow import _PortScan
return _PortScan(list(candidates), list(confirmed), swept)
def _openssl_alert(name: str) -> ConnectionError:
"""How the library surfaces a fatal alert received from the appliance."""
return ConnectionError(f"DTLS handshake error: [('SSL routines', '', '{name}')]")
def test_cert_alert_is_reported_as_a_certificate_problem() -> None:
"""The single most common real setup mistake -- CA credentials that
aren't the AC14K_M CA the appliance trusts -- used to render as "check
the IP address is reachable and the CA credentials are correct", which
is half wrong and gives no way to tell which half."""
from custom_components.localthings.config_flow import (
CertRejected,
_classify_handshake_failure,
)
for alert in ("tlsv1 alert unknown ca", "sslv3 alert bad certificate"):
err = _classify_handshake_failure(
MOCK_HOST, _scan(confirmed=[49154]), [(49154, _openssl_alert(alert))]
)
assert isinstance(err, CertRejected), alert
assert err.error_key == "cert_rejected"
def test_non_cert_alert_is_kept_distinct_from_a_cert_problem() -> None:
"""A cipher or version mismatch is also a deliberate refusal, but no
amount of fiddling with CA credentials will fix it."""
from custom_components.localthings.config_flow import (
HandshakeFailed,
_classify_handshake_failure,
)
err = _classify_handshake_failure(
MOCK_HOST,
_scan(confirmed=[49154]),
[(49154, _openssl_alert("tlsv1 alert protocol version"))],
)
assert isinstance(err, HandshakeFailed)
assert err.error_key == "handshake_failed"
def test_confirmed_port_that_times_out_is_reported_as_a_stuck_session() -> None:
"""The ClientHello probe proved a DTLS server is right there, so this is
not a connectivity or credentials problem -- it's the appliance still
holding the association from the last attempt, which clears itself."""
from custom_components.localthings.config_flow import (
HandshakeTimeout,
_classify_handshake_failure,
)
err = _classify_handshake_failure(
MOCK_HOST, _scan(confirmed=[49154]), [(49154, TimeoutError("handshake timeout"))]
)
assert isinstance(err, HandshakeTimeout)
assert err.error_key == "handshake_timeout"
def test_every_port_refused_is_reported_as_closed_ports() -> None:
"""ICMP port-unreachable on the whole range means the host is up and
answering -- it just isn't exposing a local API. Cloud-only firmware and
a wrong-but-live IP both land here."""
from custom_components.localthings.config_flow import (
PROBE_PORT_RANGE,
PortsClosed,
_classify_handshake_failure,
)
err = _classify_handshake_failure(
MOCK_HOST,
_scan(swept=_sweep_result(refused=PROBE_PORT_RANGE)),
[(49154, TimeoutError("handshake timeout"))],
)
assert isinstance(err, PortsClosed)
assert err.error_key == "ports_closed"
def test_unreachable_host_is_not_reported_as_closed_ports() -> None:
"""A wrong IP on the local subnet never answers ARP, so the kernel fails
every send with EHOSTUNREACH -- no port is "live", but nothing refused
us either. Lumping that in with a genuine refusal would tell the user
their appliance is on cloud-only firmware when in fact there is nothing
at that address at all."""
from custom_components.localthings.config_flow import (
PROBE_PORT_RANGE,
NoResponse,
_classify_handshake_failure,
)
err = _classify_handshake_failure(
MOCK_HOST,
_scan(swept=_sweep_result(unreachable=PROBE_PORT_RANGE)),
[(49154, TimeoutError("handshake timeout"))],
)
assert isinstance(err, NoResponse)
assert err.error_key == "no_response"
def test_total_silence_is_reported_as_no_response() -> None:
"""Not one ICMP refusal across a nine-port ephemeral range: a host that
is really there answers for at least some of it, so this reads as
nothing at that address rather than as a device that won't talk."""
from custom_components.localthings.config_flow import (
PROBE_PORT_RANGE,
NoResponse,
_classify_handshake_failure,
)
err = _classify_handshake_failure(
MOCK_HOST,
_scan(swept=_sweep_result(live=PROBE_PORT_RANGE)),
[(49154, TimeoutError("handshake timeout"))],
)
assert isinstance(err, NoResponse)
assert err.error_key == "no_response"
def test_partially_open_range_is_reported_as_no_dtls_server() -> None:
"""Some ports answered, some refused -- something is listening at that
address, it just isn't a DTLS appliance."""
from custom_components.localthings.config_flow import (
NoDtlsServer,
_classify_handshake_failure,
)
err = _classify_handshake_failure(
MOCK_HOST,
_scan(swept=_sweep_result(live=[49154, 49155], refused=[49153])),
[(49154, TimeoutError("timeout"))],
)
assert isinstance(err, NoDtlsServer)
assert err.error_key == "no_dtls_server"
async def test_cert_rejection_surfaces_its_own_error_in_the_form(
hass: HomeAssistant, monkeypatch, fake_dtls
) -> None:
"""End to end: an appliance that rejects the certificate tells the user
that, rather than the blanket connectivity message."""
_patch_clienthello(monkeypatch, {49154})
FakeSession.reject_certs = {"FULLCHAIN"}
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: MOCK_HOST,
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
},
)
assert result["type"] == FlowResultType.FORM
errors = result["errors"]
assert errors is not None
assert errors["base"] == "cert_rejected"
async def test_unreachable_cloud_gateway_is_reported_separately(
hass: HomeAssistant, monkeypatch, fake_dtls
) -> None:
"""Minting a certificate needs Samsung's cloud once, for the UUID. Losing
that is an internet problem on Home Assistant's side, not anything about
the appliance or the CA credentials the old message pointed at."""
from custom_components.localthings import config_flow
_patch_clienthello(monkeypatch, {49154})
def _no_cloud():
raise OSError("Name or service not known")
monkeypatch.setattr(config_flow, "_fetch_samsung_uuid", _no_cloud)
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: MOCK_HOST,
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
},
)
assert result["type"] == FlowResultType.FORM
errors = result["errors"]
assert errors is not None
assert errors["base"] == "cloud_unreachable"
async def test_unusable_device0_is_reported_separately(
hass: HomeAssistant, monkeypatch, fake_dtls
) -> None:
"""Authenticating fine and then getting something we can't read is
neither a connectivity nor a credentials problem, and saying so saves a
user checking both."""
_patch_clienthello(monkeypatch, {49154})
monkeypatch.setattr(FakeSession, "get", lambda self, path, timeout=15.0: (0x84, b""))
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: MOCK_HOST,
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
},
)
assert result["type"] == FlowResultType.FORM
errors = result["errors"]
assert errors is not None
assert errors["base"] == "unexpected_response"
def test_every_error_key_the_flow_can_raise_has_a_message() -> None:
"""A key with no catalog entry renders as the bare key in the UI, so the
taxonomy and the strings have to stay in step."""
import json
from pathlib import Path
from custom_components.localthings import config_flow
keys = {
cls.error_key
for cls in vars(config_flow).values()
if isinstance(cls, type)
and issubclass(cls, (config_flow.CannotConnect, config_flow.InvalidCA))
}
keys.add("unknown")
catalog = json.loads(
(
Path(__file__).parents[2]
/ "custom_components"
/ "localthings"
/ "translations"
/ "en.json"
).read_text()
)["config"]["error"]
assert keys <= set(catalog)
# And nothing unreachable left behind in the catalog either.
assert set(catalog) == keys
async def test_cannot_connect(hass: HomeAssistant) -> None:
"""Failed probe: form re-shown with cannot_connect error."""
from custom_components.localthings.config_flow import CannotConnect
@@ -299,8 +840,20 @@ async def test_unknown_type_step_description_makes_no_version_claim(
two, differing only in whether they blamed a missing oneUiVersion -- a
distinction that stopped existing when detection stopped reading it."""
import json
import re
from pathlib import Path
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: MOCK_HOST,
CONF_CA_CERT_PEM: MOCK_CA_CERT_PEM,
CONF_CA_KEY_PEM: MOCK_CA_KEY_PEM,
},
)
assert result["step_id"] == "confirm_unknown_type"
steps = json.loads(
(
Path(__file__).parents[2]
@@ -314,7 +867,13 @@ async def test_unknown_type_step_description_makes_no_version_claim(
assert "confirm_unknown_type_no_version" not in steps
description = steps["confirm_unknown_type"]["description"]
assert "oneUiVersion" not in description
assert "{" not in description # no unfilled placeholder
# {model} is the only placeholder, and the step must supply it -- an
# unfilled one renders as literal braces to the user.
placeholders = re.findall(r"{(\w+)}", description)
assert placeholders == ["model"]
supplied = result["description_placeholders"]
assert supplied is not None
assert supplied["model"] == MOCK_MODEL
async def test_duplicate_device_aborted(hass: HomeAssistant, mock_probe) -> None:
@@ -477,9 +1036,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)
@@ -497,8 +1057,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"],
@@ -564,8 +1136,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"],
@@ -586,18 +1170,18 @@ def test_is_placeholder_serial_catches_nothing_svc():
"""Issue #83: the ARTIK051_DONGLE_REF firmware family reports the
literal string 'Nothing(SVC)' as serialNum on every unit -- non-empty,
so it must be caught by name, not by the plain `if not serial` check."""
from custom_components.localthings.config_flow import _is_placeholder_serial
from custom_components.localthings.registry.identity import is_placeholder_serial
assert _is_placeholder_serial("Nothing(SVC)") is True
assert _is_placeholder_serial("nothing(svc)") is True
assert _is_placeholder_serial(" Nothing(SVC) ") is True
assert is_placeholder_serial("Nothing(SVC)") is True
assert is_placeholder_serial("nothing(svc)") is True
assert is_placeholder_serial(" Nothing(SVC) ") is True
def test_is_placeholder_serial_accepts_real_serials():
from custom_components.localthings.config_flow import _is_placeholder_serial
from custom_components.localthings.registry.identity import is_placeholder_serial
assert _is_placeholder_serial("0A1B2C3D4E5F") is False
assert _is_placeholder_serial("") is False
assert is_placeholder_serial("0A1B2C3D4E5F") is False
assert is_placeholder_serial("") is False
def test_is_placeholder_serial_catches_all_same_hex_digit():
@@ -606,11 +1190,25 @@ def test_is_placeholder_serial_catches_all_same_hex_digit():
character the same repeated hex digit. A washer and a dryer, two
different physical units, both reported the literal serialNum
'FFFFFFFFFFFFFFF', colliding on the config-entry unique_id."""
from custom_components.localthings.config_flow import _is_placeholder_serial
from custom_components.localthings.registry.identity import is_placeholder_serial
assert _is_placeholder_serial("FFFFFFFFFFFFFFF") is True
assert _is_placeholder_serial("ffffffffffffffff") is True
assert _is_placeholder_serial("00000000") is True
assert is_placeholder_serial("FFFFFFFFFFFFFFF") is True
assert is_placeholder_serial("ffffffffffffffff") is True
assert is_placeholder_serial("00000000") is True
# Too short to be the flash-unset sentinel -- a real serial could
# plausibly repeat one hex digit seven times by chance.
assert _is_placeholder_serial("FFFFFFF") is False
assert is_placeholder_serial("FFFFFFF") is False
def test_resolve_serial_falls_back_to_host():
"""Both sides of the identity -- the config flow's probe and the
coordinator's first poll -- now resolve a serial through one function, so
they cannot disagree about what a device is called. They used to: the
flow fell back to `host:port` and the coordinator to `host`."""
from custom_components.localthings.registry.identity import resolve_serial
assert resolve_serial("REAL-SERIAL", "10.0.0.5") == "REAL-SERIAL"
assert resolve_serial(" REAL-SERIAL ", "10.0.0.5") == "REAL-SERIAL"
assert resolve_serial("Nothing(SVC)", "10.0.0.5") == "10.0.0.5"
assert resolve_serial("", "10.0.0.5") == "10.0.0.5"
assert resolve_serial(None, "10.0.0.5") == "10.0.0.5"
+452 -17
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import time
from datetime import timedelta
from unittest.mock import AsyncMock, patch
@@ -21,8 +22,8 @@ from custom_components.localthings.const import (
SUMMARY_INTERVAL_S,
)
from custom_components.localthings.coordinator import (
_RECOVERY_RETRY_S,
LocalThingsCoordinator,
_is_placeholder_serial,
_local_source_port,
)
from custom_components.localthings.observe import MODE_OBSERVE, MODE_POLL, PUSH_HEALTH_WINDOW_S
@@ -31,7 +32,8 @@ from custom_components.localthings.registry.capabilities.common import (
remote_control_required_for_write,
)
from .conftest import ENTRY_DATA, MOCK_SERIAL
from .conftest import ENTRY_DATA, MOCK_MODEL, MOCK_SERIAL, FakeObserveSession
from .conftest import _load_fridge_resources as _load_fridge
async def test_first_refresh_runs_discovery(
@@ -138,7 +140,7 @@ def test_run_discovery_detects_washer_via_model_fallback(hass: HomeAssistant, mo
def test_run_discovery_falls_back_to_host_for_placeholder_serial(
hass: HomeAssistant, mock_entry
hass: HomeAssistant, legacy_entry
) -> None:
"""Issue #83: the ARTIK051_DONGLE_REF firmware family reports the
literal string 'Nothing(SVC)' as serialNum on every unit. Left as-is,
@@ -154,13 +156,13 @@ def test_run_discovery_falls_back_to_host_for_placeholder_serial(
},
"/otninformation/vs/0": {},
}
coordinator = LocalThingsCoordinator(hass, mock_entry)
coordinator = LocalThingsCoordinator(hass, legacy_entry)
coordinator._run_discovery(resources)
assert coordinator.device_serial == mock_entry.data[CONF_HOST]
assert coordinator.device_serial == legacy_entry.data[CONF_HOST]
def test_run_discovery_falls_back_to_host_for_all_f_placeholder_serial(
hass: HomeAssistant, mock_entry
hass: HomeAssistant, legacy_entry
) -> None:
"""Issue #189: the DA_WM_A51_20_COMMON (ARTIK051) laundry board family
reports a flash-unset sentinel instead of 'Nothing(SVC)' -- every
@@ -176,23 +178,76 @@ def test_run_discovery_falls_back_to_host_for_all_f_placeholder_serial(
},
"/otninformation/vs/0": {},
}
coordinator = LocalThingsCoordinator(hass, legacy_entry)
coordinator._run_discovery(resources)
assert coordinator.device_serial == legacy_entry.data[CONF_HOST]
# ---------------------------------------------------------------------------
# Identity is known before the first poll (issue #236)
# ---------------------------------------------------------------------------
def test_identity_is_resolved_before_any_poll(hass: HomeAssistant, mock_entry) -> None:
"""The coordinator mints registry keys from the entry's stored identity at
construction time.
`device_serial` is what entity unique_ids and device identifiers are built
from, and those are permanent. Seeding it with the host meant anything that
registered before the first poll returned -- the connection-mode sensor
especially, added unconditionally rather than from `bound` -- was written
into the registry keyed on the IP address forever, then orphaned when the
real identity showed up moments later.
"""
coordinator = LocalThingsCoordinator(hass, mock_entry)
assert coordinator.device_serial == MOCK_SERIAL
assert coordinator.device_info["identifiers"] == {(DOMAIN, MOCK_SERIAL)}
assert coordinator.device_info["model"] == MOCK_MODEL
assert coordinator.device_info["name"] == f"Samsung Refrigerator ({MOCK_MODEL})"
assert mock_entry.data[CONF_HOST] not in str(coordinator.device_info["identifiers"])
def test_identity_survives_a_first_poll_that_never_happens(hass: HomeAssistant, mock_entry) -> None:
"""A device that is slow or unreachable at startup no longer changes what
its entities are called -- there is no placeholder left to correct."""
coordinator = LocalThingsCoordinator(hass, mock_entry)
before = coordinator.device_info["identifiers"]
coordinator._run_discovery(_load_fridge())
assert coordinator.device_info["identifiers"] == before
def test_discovery_keeps_the_registered_identity(hass: HomeAssistant, mock_entry) -> None:
"""A different appliance answering on the same IP does not silently re-key
the entry's existing devices and entities out from under the registry."""
resources = {
"/information/vs/0": {
"x.com.samsung.da.modelNum": "DA_WM_TP1_21_COMMON|20375141|20010002001811424AA30217008A0000", # noqa: E501
"x.com.samsung.da.description": "DA_WM_TP1_21_COMMON_WW5000C/DC92-03495A_B048",
"x.com.samsung.da.serialNum": "SOME-OTHER-APPLIANCE",
},
"/otninformation/vs/0": {},
}
coordinator = LocalThingsCoordinator(hass, mock_entry)
coordinator._run_discovery(resources)
assert coordinator.device_serial == mock_entry.data[CONF_HOST]
assert coordinator.device_serial == MOCK_SERIAL
def test_is_placeholder_serial_catches_all_same_hex_digit():
assert _is_placeholder_serial("FFFFFFFFFFFFFFF") is True
assert _is_placeholder_serial("ffffffffffffffff") is True
assert _is_placeholder_serial("00000000") is True
def test_discovery_backfills_a_legacy_entry_identity(hass: HomeAssistant, legacy_entry) -> None:
"""An entry migrated from before identity was stored learns it on its
first poll and keeps it, so the *next* restart registers the device fully
named before any entity exists instead of renaming it a second time."""
from custom_components.localthings.const import CONF_DEVICE_TYPE, CONF_MODEL, CONF_SERIAL
coordinator = LocalThingsCoordinator(hass, legacy_entry)
coordinator._run_discovery(_load_fridge())
def test_is_placeholder_serial_accepts_real_serials_and_short_runs():
assert _is_placeholder_serial("0A1B2C3D4E5F") is False
assert _is_placeholder_serial("") is False
# Too short to be the flash-unset sentinel -- a real serial could
# plausibly repeat one hex digit seven times by chance.
assert _is_placeholder_serial("FFFFFFF") is False
assert legacy_entry.data[CONF_SERIAL] == MOCK_SERIAL
assert legacy_entry.data[CONF_MODEL] == MOCK_MODEL
assert legacy_entry.data[CONF_DEVICE_TYPE] == "refrigerator"
def test_run_discovery_detects_cooktop_via_resource_signature(
@@ -425,6 +480,57 @@ async def test_reconnect_while_observe_mode_downgrades_to_poll(
assert coordinator._observe.mode == MODE_POLL
async def test_total_poll_failure_downgrades_observe_mode_to_poll(
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session, fridge_resources
) -> None:
"""A device that drops off the network entirely -- both the poll and its
reconnect retry fail -- must not leave the connection-mode sensor
reporting 'Push' forever (issue #287). Only the *successful* reconnect
branch used to touch observe mode (see
test_reconnect_while_observe_mode_downgrades_to_poll); this covers the
branch where the device stays unreachable."""
fake = mock_coordinator_observe_session
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
hrefs = coordinator._hot_hrefs + coordinator._warm_hrefs
fake.notify_on_subscribe = {"notified": True}
entered = await hass.async_add_executor_job(
coordinator._observe.try_enter_observe_mode,
fake,
hrefs,
0.02,
0.8,
)
assert entered is True
assert coordinator.observe_mode == MODE_OBSERVE
last_notify_ts = coordinator._observe._last_notify_ts
assert last_notify_ts is not None
coordinator._observe._last_notify_ts = last_notify_ts - (PUSH_HEALTH_WINDOW_S + 1)
with (
patch(
"custom_components.localthings.coordinator.LocalThingsCoordinator._poll_once",
side_effect=[RuntimeError("connection lost"), RuntimeError("still lost")],
),
patch(
"custom_components.localthings.coordinator.asyncio.sleep",
new=AsyncMock(),
),
):
await coordinator.async_request_refresh()
await hass.async_block_till_done()
# The update still "succeeds" with the last-known snapshot (issue #254's
# degraded-data path) -- but the connection mode must reflect reality
# now, not the stale OBSERVE state from before the outage.
assert coordinator.observe_mode == MODE_POLL
assert coordinator.last_update_success is True
async def test_poll_timeout_skips_reconnect_when_push_is_healthy(
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
) -> None:
@@ -638,6 +744,149 @@ async def test_reconnect_from_observe_mode_resubscribes_immediately(
assert coordinator.observe_mode == MODE_OBSERVE
async def test_attempt_observe_mode_discards_stale_commit_after_session_swap(
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
) -> None:
"""A reconnect (the poll path's own, or a command's retry) can swap
self._session while this attempt's grace wait is in flight -- it runs
without holding _session_lock precisely so a write isn't blocked behind
it (issue #294). Committing observe mode against the now-stale local
`sess` reference would claim "Push" on a session that's already gone,
with nothing left to notice -- the identity re-check under the lock
right before committing must catch this and abandon instead.
The new session is never-tried, though, not just abandoned: it must
flag an immediate resubscribe rather than let _last_observe_attempt_ts
(stamped for the now-abandoned attempt) throttle it for up to
_RECOVERY_RETRY_S.
Simulates the swap from inside await_observe_notifies itself rather
than via real concurrency: subscribe_hrefs (and its lock) has already
returned by the time that call runs, so this lands exactly in the
window the identity check exists to cover, deterministically."""
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
assert coordinator._resubscribe_due is False
other = FakeObserveSession()
def _swap_session_mid_wait(subscribed, grace_period_s, success_fraction=None):
coordinator._session = other # ty: ignore[invalid-assignment]
return True
with patch.object(
coordinator._observe, "await_observe_notifies", side_effect=_swap_session_mid_wait
):
await coordinator._attempt_observe_mode()
assert coordinator.observe_mode == MODE_POLL
assert coordinator._observe.subscribed_hrefs == set()
assert coordinator._observe._refresh_thread is None
assert coordinator._resubscribe_due is True
async def test_maybe_retry_observe_mode_uses_most_recent_attempt_not_just_mode_change(
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
) -> None:
"""_set_mode only stamps last_mode_change_ts on an actual transition,
so a device that never successfully enters observe mode leaves that
timestamp stuck at construction time forever -- a failed attempt keeps
calling _set_mode(MODE_POLL) while already in MODE_POLL, a no-op.
Gating solely on that timestamp would make the 600s throttle open once
and then never close again, re-attempting (and paying the subscribe
burst) on every single poll cycle instead of every _RECOVERY_RETRY_S."""
fake = mock_coordinator_observe_session
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
assert coordinator.observe_mode == MODE_POLL # never notified during setup
# Simulate exactly the scenario above: mode_change_ts is old (as it
# would be forever, for a device that never gets push), but an attempt
# really did just run.
coordinator._observe.last_mode_change_ts = time.monotonic() - _RECOVERY_RETRY_S - 1
coordinator._last_observe_attempt_ts = time.monotonic()
with patch.object(fake, "subscribe") as mock_subscribe:
await coordinator._maybe_retry_observe_mode()
mock_subscribe.assert_not_called()
async def test_maybe_retry_observe_mode_also_respects_a_mode_change_outside_an_attempt(
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
) -> None:
"""The mirror of the case above: last_mode_change_ts can be the more
recent of the two as well, e.g. right after the poll or command path's
own downgrade (neither goes through _attempt_observe_mode, so neither
stamps _last_observe_attempt_ts). Dropping last_mode_change_ts from the
max() would let a device that was *just* downgraded get re-attempted
immediately instead of respecting _RECOVERY_RETRY_S."""
fake = mock_coordinator_observe_session
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
assert coordinator.observe_mode == MODE_POLL
coordinator._last_observe_attempt_ts = time.monotonic() - _RECOVERY_RETRY_S - 1
coordinator._observe.last_mode_change_ts = time.monotonic()
with patch.object(fake, "subscribe") as mock_subscribe:
await coordinator._maybe_retry_observe_mode()
mock_subscribe.assert_not_called()
async def test_attempt_observe_mode_releases_lock_before_the_grace_wait(
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
) -> None:
"""The subscribe burst holds _session_lock (it touches the session);
the grace wait after it must not, or a command write could stall
behind up to _OBSERVE_GRACE_PERIOD_S of an unrelated observe-mode-entry
attempt (issue #294). By construction, subscribe_hrefs's own
`async with self._session_lock:` has already exited by the time
await_observe_notifies is even called -- checked here rather than
inferred from timing."""
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
locked_during_wait = {"value": None}
def _check_lock(subscribed, grace_period_s, success_fraction=None):
locked_during_wait["value"] = coordinator._session_lock.locked()
return True
with patch.object(coordinator._observe, "await_observe_notifies", side_effect=_check_lock):
await coordinator._attempt_observe_mode()
assert locked_during_wait["value"] is False
async def test_attempt_observe_mode_holds_lock_during_the_subscribe_burst(
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
) -> None:
"""The other half of the split above: the subscribe burst does touch
the session, so it must hold _session_lock -- that's what actually
stops a concurrent close from landing mid-subscribe (issue #294)."""
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
locked_during_subscribe = {"value": None}
real_subscribe_hrefs = coordinator._observe.subscribe_hrefs
def _check_lock(session, hrefs):
locked_during_subscribe["value"] = coordinator._session_lock.locked()
return real_subscribe_hrefs(session, hrefs)
with patch.object(coordinator._observe, "subscribe_hrefs", side_effect=_check_lock):
await coordinator._attempt_observe_mode()
assert locked_during_subscribe["value"] is True
async def test_sweep_mismatch_never_downgrades_a_live_observe_session(
hass: HomeAssistant, mock_entry, mock_coordinator_observe_session
) -> None:
@@ -903,6 +1152,192 @@ async def test_send_command_survives_stale_confirm_poll(
assert coordinator._cache.get("/test/vs/0") == {"value": 5}
async def test_send_command_reconnects_and_retries_after_socket_closed(
hass: HomeAssistant,
mock_entry,
mock_coordinator_observe_session,
) -> None:
"""A command lost to a session Samsung's firmware closed between polls
must not just vanish (issue #294): `_do_put` failing once is now
followed by a reconnect and a single retry, mirroring the poll path's
own recovery in `_async_update_data`.
`mock_coordinator_observe_session` patches `_close_session` to a no-op,
which would leave `self._session` never actually going `None` -- and
with it, `_do_put`'s own `if self._session is None: self._connect_session()`
guard never exercised, so a broken reconnect could still pass. Overridden
here to actually drop the session, so the retry only succeeds if that
guard really rebuilds it."""
from custom_components.localthings.registry.discovery import BoundEntity
from custom_components.localthings.registry.entities import NumberDesc
fake = mock_coordinator_observe_session
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
def _write_fn(payload, rep, href=None):
return (["test", "vs", "0"], {"value": payload})
desc = NumberDesc(key="test", field="value", write_fn=_write_fn)
bound = BoundEntity(href="/test/vs/0", capability=coordinator.bound[0].capability, desc=desc)
calls = {"n": 0}
def _post(*args, **kwargs):
calls["n"] += 1
if calls["n"] == 1:
raise ConnectionError("socket closed")
return (0x44, b"")
def _drop_session():
coordinator._session = None
reconnects = {"n": 0}
def _reconnect():
reconnects["n"] += 1
coordinator._session = fake
with (
patch.object(fake, "subscribe"),
patch.object(coordinator, "_close_session", side_effect=_drop_session),
patch.object(coordinator, "_connect_session", side_effect=_reconnect),
patch(
"custom_components.localthings.coordinator.asyncio.sleep",
new=AsyncMock(),
),
):
fake.post = _post
await coordinator.async_send_command(bound, 5)
assert reconnects["n"] == 1
assert calls["n"] == 2
assert coordinator._cache.get("/test/vs/0") == {"value": 5}
async def test_send_command_raises_after_reconnect_retry_also_fails(
hass: HomeAssistant,
mock_entry,
mock_coordinator_observe_session,
) -> None:
"""If the command still fails on the reconnected session, the user must
see it -- previously this was swallowed into a log line with no
feedback at all (issue #294).
Also covers a sibling bug the fix for that same issue introduced: the
session is closed the moment the first attempt fails, so any OBSERVE
subscriptions on it are already dead regardless of whether the retry
that follows succeeds -- a failed retry must still downgrade mode, or
it's left claiming "Push" on a session that no longer exists."""
from homeassistant.exceptions import HomeAssistantError
from custom_components.localthings.registry.discovery import BoundEntity
from custom_components.localthings.registry.entities import NumberDesc
fake = mock_coordinator_observe_session
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
hrefs = coordinator._hot_hrefs + coordinator._warm_hrefs
fake.notify_on_subscribe = {"notified": True}
entered = await hass.async_add_executor_job(
coordinator._observe.try_enter_observe_mode,
fake,
hrefs,
0.02,
0.8,
)
assert entered is True
assert coordinator.observe_mode == MODE_OBSERVE
def _write_fn(payload, rep, href=None):
return (["test", "vs", "0"], {"value": payload})
desc = NumberDesc(key="test", field="value", write_fn=_write_fn)
bound = BoundEntity(href="/test/vs/0", capability=coordinator.bound[0].capability, desc=desc)
def _post(*args, **kwargs):
raise ConnectionError("socket closed")
with (
patch(
"custom_components.localthings.coordinator.asyncio.sleep",
new=AsyncMock(),
),
pytest.raises(HomeAssistantError),
):
fake.post = _post
await coordinator.async_send_command(bound, 5)
assert coordinator.observe_mode == MODE_POLL
async def test_send_command_reconnect_downgrades_observe_mode(
hass: HomeAssistant,
mock_entry,
mock_coordinator_observe_session,
) -> None:
"""A command's own successful reconnect hands back a session with zero
OBSERVE registrations too, same as the poll path's reconnect -- must
downgrade the same way and flag a resubscribe, or observe mode stays
claimed against a session the write just replaced underneath it
(issue #294)."""
from custom_components.localthings.registry.discovery import BoundEntity
from custom_components.localthings.registry.entities import NumberDesc
fake = mock_coordinator_observe_session
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
coordinator: LocalThingsCoordinator = hass.data[DOMAIN][mock_entry.entry_id]
hrefs = coordinator._hot_hrefs + coordinator._warm_hrefs
fake.notify_on_subscribe = {"notified": True}
entered = await hass.async_add_executor_job(
coordinator._observe.try_enter_observe_mode,
fake,
hrefs,
0.02,
0.8,
)
assert entered is True
assert coordinator.observe_mode == MODE_OBSERVE
def _write_fn(payload, rep, href=None):
return (["test", "vs", "0"], {"value": payload})
desc = NumberDesc(key="test", field="value", write_fn=_write_fn)
bound = BoundEntity(href="/test/vs/0", capability=coordinator.bound[0].capability, desc=desc)
calls = {"n": 0}
def _post(*args, **kwargs):
calls["n"] += 1
if calls["n"] == 1:
raise ConnectionError("socket closed")
return (0x44, b"")
with (
patch.object(fake, "subscribe") as mock_subscribe,
patch(
"custom_components.localthings.coordinator.asyncio.sleep",
new=AsyncMock(),
),
):
fake.post = _post
await coordinator.async_send_command(bound, 5)
# _resubscribe_due is consumed by this same call's own trailing
# refresh (async_request_refresh is awaited, not fire-and-forget),
# so the visible effect is a resubscribe attempt, not a lingering
# flag value to assert on afterward.
assert mock_subscribe.called
assert coordinator.observe_mode == MODE_POLL
async def test_second_write_to_same_href_lands_during_first_writes_settle_window(
hass: HomeAssistant,
mock_entry,
+277
View File
@@ -0,0 +1,277 @@
"""Config-entry migration and the placeholder-identity repair (issue #236)."""
from __future__ import annotations
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers import entity_registry as er
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.localthings.const import (
CONF_HOST,
CONF_SERIAL,
DOMAIN,
)
from .conftest import LEGACY_ENTRY_DATA, MOCK_HOST, MOCK_PORT, MOCK_SERIAL
def _legacy_entry(hass: HomeAssistant, unique_id: str) -> MockConfigEntry:
entry = MockConfigEntry(
domain=DOMAIN,
data=LEGACY_ENTRY_DATA,
unique_id=unique_id,
version=1,
)
entry.add_to_hass(hass)
return entry
async def test_migration_recovers_serial_from_unique_id(
hass: HomeAssistant, mock_coordinator_session
) -> None:
"""A v1 entry's identity is recoverable without reaching the device: the
config flow has always keyed the entry's unique_id on the serial its probe
read."""
entry = _legacy_entry(hass, f"{DOMAIN}_{MOCK_SERIAL}")
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.version == 2
assert entry.data[CONF_SERIAL] == MOCK_SERIAL
async def test_migration_collapses_the_host_port_unique_id(
hass: HomeAssistant, mock_coordinator_session
) -> None:
"""A board with no usable serial (issues #83/#189) used to be keyed two
different ways at once: `host:port` on the config entry, `host` in the
device and entity registries. Migration collapses the entry onto the
registry's form, so the two finally name the same thing."""
entry = _legacy_entry(hass, f"{DOMAIN}_{MOCK_HOST}:{MOCK_PORT}")
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.data[CONF_SERIAL] == MOCK_HOST
assert entry.unique_id == f"{DOMAIN}_{MOCK_HOST}"
async def test_migration_resolves_a_placeholder_serial_unique_id(
hass: HomeAssistant, mock_coordinator_session
) -> None:
"""An entry created before the placeholder rules landed was keyed on the
placeholder itself (issues #83/#189), while the coordinator has been
resolving those boards to the host ever since. The unique_id records what
the flow believed then, not what the registry holds -- taking it at face
value would re-key working devices back onto a string every unit of the
family reports, which is the collision those issues are about."""
entry = _legacy_entry(hass, f"{DOMAIN}_Nothing(SVC)")
dev_reg = dr.async_get(hass)
device = dev_reg.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, MOCK_HOST)},
)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.data[CONF_SERIAL] == MOCK_HOST
assert entry.unique_id == f"{DOMAIN}_{MOCK_HOST}"
unchanged = dev_reg.async_get(device.id)
assert unchanged is not None
assert unchanged.identifiers == {(DOMAIN, MOCK_HOST)}
async def test_migration_resolves_an_all_hex_placeholder_unique_id(
hass: HomeAssistant, mock_coordinator_session
) -> None:
"""The issue #189 flash-unset sentinel, same reasoning."""
entry = _legacy_entry(hass, f"{DOMAIN}_FFFFFFFFFFFFFFF")
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.data[CONF_SERIAL] == MOCK_HOST
async def test_migration_keeps_a_survivor_off_a_removed_duplicate_device(
hass: HomeAssistant,
) -> None:
"""Removing a device takes its entities with it (entity_registry's
async_device_modified), so an entity that came through the pass above
re-keyed rather than removed has to move to the surviving device first --
otherwise the rewrite that exists to preserve an entity_id, name and area
destroys all three a few lines later.
Migration is called directly here: what the repair leaves behind is the
contract, and going through async_setup would let the platform re-adding
its entities hide a row that had in fact been deleted."""
from custom_components.localthings import async_migrate_entry
entry = _legacy_entry(hass, f"{DOMAIN}_{MOCK_SERIAL}")
dev_reg = dr.async_get(hass)
ent_reg = er.async_get(hass)
real_device = dev_reg.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, MOCK_SERIAL)},
)
orphan_device = dev_reg.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, MOCK_HOST)},
)
# The serial-keyed device exists, but this entity's serial-keyed *key* is
# free -- e.g. the user deleted the visible duplicate by hand -- so the
# entity pass rewrites it instead of removing it.
survivor = ent_reg.async_get_or_create(
"sensor",
DOMAIN,
f"{DOMAIN}_{MOCK_HOST}_connection_mode",
config_entry=entry,
device_id=orphan_device.id,
suggested_object_id="kitchen_fridge_connection",
)
assert await async_migrate_entry(hass, entry) is True
await hass.async_block_till_done()
assert dev_reg.async_get(orphan_device.id) is None
kept = ent_reg.async_get(survivor.entity_id)
assert kept is not None
assert kept.entity_id == "sensor.kitchen_fridge_connection"
assert kept.unique_id == f"{DOMAIN}_{MOCK_SERIAL}_connection_mode"
assert kept.device_id == real_device.id
async def test_migration_rekeys_an_ip_keyed_device_and_entity(
hass: HomeAssistant, mock_coordinator_session
) -> None:
"""The registry entries the old placeholder identity minted are rewritten
in place, so an orphan keeps its entity_id, name, area and every
automation that referenced it -- rather than being replaced by a
serial-keyed duplicate with a `_2` suffix while it sits permanently
unavailable (issue #236)."""
entry = _legacy_entry(hass, f"{DOMAIN}_{MOCK_SERIAL}")
dev_reg = dr.async_get(hass)
ent_reg = er.async_get(hass)
orphan_device = dev_reg.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, MOCK_HOST)},
name=f"Samsung Appliance ({MOCK_HOST})",
)
orphan_entity = ent_reg.async_get_or_create(
"sensor",
DOMAIN,
f"{DOMAIN}_{MOCK_HOST}_connection_mode",
config_entry=entry,
device_id=orphan_device.id,
)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Same registry rows, now keyed on the real identity.
rekeyed_device = dev_reg.async_get(orphan_device.id)
assert rekeyed_device is not None
assert rekeyed_device.identifiers == {(DOMAIN, MOCK_SERIAL)}
rekeyed = ent_reg.async_get(orphan_entity.entity_id)
assert rekeyed is not None
assert rekeyed.unique_id == f"{DOMAIN}_{MOCK_SERIAL}_connection_mode"
# And nothing is left keyed on the IP.
assert dev_reg.async_get_device(identifiers={(DOMAIN, MOCK_HOST)}) is None
async def test_migration_removes_an_orphan_that_is_already_duplicated(
hass: HomeAssistant, mock_coordinator_session
) -> None:
"""Where the serial-keyed entry already exists, the IP-keyed one is the
dead duplicate the race left behind -- it has been unavailable since the
restart that created it and nothing will ever update it, so it goes
rather than being rewritten onto a key that is taken."""
entry = _legacy_entry(hass, f"{DOMAIN}_{MOCK_SERIAL}")
dev_reg = dr.async_get(hass)
ent_reg = er.async_get(hass)
real_device = dev_reg.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, MOCK_SERIAL)},
)
real_entity = ent_reg.async_get_or_create(
"sensor",
DOMAIN,
f"{DOMAIN}_{MOCK_SERIAL}_connection_mode",
config_entry=entry,
device_id=real_device.id,
)
orphan_device = dev_reg.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, MOCK_HOST)},
)
orphan_entity = ent_reg.async_get_or_create(
"sensor",
DOMAIN,
f"{DOMAIN}_{MOCK_HOST}_connection_mode",
config_entry=entry,
device_id=orphan_device.id,
)
assert orphan_entity.entity_id != real_entity.entity_id
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert ent_reg.async_get(orphan_entity.entity_id) is None
assert dev_reg.async_get(orphan_device.id) is None
# The working pair is untouched.
assert ent_reg.async_get(real_entity.entity_id) is not None
assert dev_reg.async_get(real_device.id) is not None
async def test_migration_leaves_a_host_identity_device_alone(
hass: HomeAssistant, mock_coordinator_session
) -> None:
"""A board whose serial resolves *to* the host was never keyed on a
placeholder -- its host-keyed device is the real one, and re-keying or
removing it would orphan a working device to fix a problem it doesn't
have."""
entry = _legacy_entry(hass, f"{DOMAIN}_{MOCK_HOST}")
dev_reg = dr.async_get(hass)
device = dev_reg.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, MOCK_HOST)},
)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.data[CONF_SERIAL] == MOCK_HOST
unchanged = dev_reg.async_get(device.id)
assert unchanged is not None
assert unchanged.identifiers == {(DOMAIN, MOCK_HOST)}
async def test_migration_rejects_a_future_entry_version(hass: HomeAssistant) -> None:
"""A downgrade must fail the entry rather than silently mangling data
written by a newer release."""
from custom_components.localthings import async_migrate_entry
entry = MockConfigEntry(domain=DOMAIN, data=LEGACY_ENTRY_DATA, version=3)
entry.add_to_hass(hass)
assert await async_migrate_entry(hass, entry) is False
async def test_migration_without_a_unique_id_falls_back_to_host(hass: HomeAssistant) -> None:
"""Nothing to recover the identity from means the host, which is exactly
what the coordinator used to seed -- so the registry keys such an entry
already holds stay valid."""
from custom_components.localthings import async_migrate_entry
entry = MockConfigEntry(domain=DOMAIN, data=LEGACY_ENTRY_DATA, version=1)
entry.add_to_hass(hass)
assert await async_migrate_entry(hass, entry) is True
assert entry.data[CONF_SERIAL] == entry.data[CONF_HOST]
assert entry.unique_id == f"{DOMAIN}_{MOCK_HOST}"
@@ -0,0 +1,76 @@
"""The particulate sensors must declare a state_class so Home Assistant keeps
long-term statistics for them; the graded readings must not.
Without a state_class a sensor only lives in the short-term recorder history
and is dropped at the next purge, so a long-range air-quality graph is not
possible -- that is the bug this guards against reappearing.
"""
from custom_components.localthings.registry.capabilities import air_purifier
from custom_components.localthings.registry.entities import SensorDesc
PARTICULATE = ("dust", "fine_dust", "super_fine_dust")
GRADED = ("odor", "clean_level")
def _desc(key):
return next(d for d in air_purifier.AIR_QUALITY.entities if d.key == key)
def test_particulate_sensors_record_long_term_statistics():
for key in PARTICULATE:
assert _desc(key).state_class == "measurement", key
def test_graded_sensors_are_left_without_a_state_class():
"""Odor and CleanLevel read 0-2 on every fixture -- graded indices, not
concentrations. Whether averaging a grade is meaningful is a separate
call, so they stay unstamped rather than being guessed into statistics."""
for key in GRADED:
assert _desc(key).state_class is None, key
def test_no_unit_or_device_class_is_asserted():
"""state_class alone makes the series recordable. pm1/pm25/pm10 with
µg/m³ would additionally assert the reading is a mass concentration,
which no dump states."""
for key in PARTICULATE + GRADED:
desc = _desc(key)
assert desc.unit is None, key
assert desc.device_class is None, key
def test_state_class_comes_from_the_shared_tuples_fourth_column():
"""The rows carry their own state_class rather than a parallel lookup, so
a new sensor can't be added here without deciding the question."""
for row in air_purifier._AIR_QUALITY_SENSORS:
assert len(row) == 4, row
assert row[3] in ("measurement", None), row
def test_air_monitor_keeps_stamping_every_shared_sensor():
"""air_monitor imports _AIR_QUALITY_SENSORS and discards the fourth column
on purpose: that board (issue #210) has stamped all five as `measurement`
since it was added, and consuming the column would silently drop long-term
statistics for Odor/CleanLevel there. Guards the import end to end and the
deliberate divergence together."""
from custom_components.localthings.registry.capabilities import air_monitor
assert air_monitor.SENSORS.href == "/sensors/vs/0"
for key in PARTICULATE + GRADED:
desc = next(
d for d in air_monitor.SENSORS.entities if d.key == key and isinstance(d, SensorDesc)
)
assert desc.state_class == "measurement", key
def test_every_air_quality_sensor_still_reads_a_plain_int():
"""A state_class is only honoured for a numeric state, so the value
contract this depends on is asserted here too."""
from tests.conftest import _load_device
resources = _load_device("air_purifier")
rep = resources["/sensors/vs/0"]
for key in PARTICULATE + GRADED:
value = _desc(key).value_fn(rep["x.com.samsung.da.items"])
assert isinstance(value, int), (key, value)
+263
View File
@@ -0,0 +1,263 @@
"""Tests for /airlevelcheck/vs/0 -- the "AI Purify" periodic air-quality
sensing engine (issues #84 and #190).
The resource is reported by three of this registry's four board families, so
the read assertions run against each family's own fixture; the write contracts
were exercised on AVT-WW-TP1-23-AXX500 hardware and are asserted here through
the descriptors that carry them.
"""
import datetime
from custom_components.localthings.registry.adapter import flatten
from custom_components.localthings.registry.by_type import resolve
from custom_components.localthings.registry.capabilities import air_purifier
from custom_components.localthings.registry.discovery import discover
from tests.conftest import _load_device
# The three fixtures whose dumps carry this resource. air_purifier (the
# ARTIK051_TVTL family, issue #56) has no such href and is deliberately absent.
FAMILIES = ("air_purifier_avt_ww", "air_purifier_vtww", "air_purifier_tp1x_da_ac_air")
HREF = ["airlevelcheck", "vs", "0"]
def _rep(fixture):
return _load_device(fixture)["/airlevelcheck/vs/0"]
def _state(fixture):
resources = _load_device(fixture)
reg = resolve(resources)
assert reg is not None and reg.name == "air_purifier", fixture
return flatten(discover(resources, reg.capabilities, reg.pattern_capabilities), resources)
def _desc(key):
return next(d for d in air_purifier.AIR_LEVEL_CHECK.entities if d.key == key)
def test_air_level_check_is_bound_not_covered():
"""The href used to sit in COVERAGE as opaque scheduler plumbing. Guard
against it being covered again, which would silently drop every entity
below while still reporting zero unbound hrefs."""
covered = {cap.href for cap in air_purifier.COVERAGE}
assert "/airlevelcheck/vs/0" not in covered
def test_every_reporting_family_binds_the_cluster():
for fixture in FAMILIES:
state = _state(fixture)
for key in (
"sensing_mode",
"periodic_air_sensing",
"periodic_sensing_skip_status",
"sensing_skip_start",
"sensing_skip_end",
"air_sensing_state",
"last_air_sensing_time",
"last_air_sensing_level",
):
assert key in state, f"{fixture}: {key}"
def test_tvtl_family_is_untouched():
"""Issue #56's board has no /airlevelcheck href at all -- nothing this
change adds may appear on it."""
state = _state("air_purifier")
for key in ("sensing_mode", "periodic_air_sensing", "sensing_interval", "sensing_skip_start"):
assert key not in state, key
def test_no_unbound_hrefs_on_any_reporting_family():
for fixture in FAMILIES:
resources = _load_device(fixture)
reg = resolve(resources)
assert reg is not None, fixture
unbound = []
discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
assert unbound == [], f"{fixture}: {unbound}"
# --- the two knobs are separate entities, not one folded control -------------
def test_activation_and_action_are_separate_entities():
"""The resource carries an on/off and an action as independent fields, and
the appliance's own UI presents them that way. Folding them into one
control would make a configured action invisible while the feature is off,
and would leave no way to toggle the feature without overwriting it."""
assert _desc("periodic_air_sensing").field == (
"x.com.samsung.da.periodicSensingActivationState"
)
assert _desc("sensing_mode").field == "x.com.samsung.da.autoExeState"
def test_action_options_come_from_the_device_not_a_table():
"""supportedAutoExeState is advertised on every reporting fixture, so the
select reads it rather than carrying a typed-in tuple -- a board adding a
fourth action is then accepted rather than rejected."""
desc = _desc("sensing_mode")
assert desc.options_field == "x.com.samsung.da.supportedAutoExeState"
assert not desc.options, "options must come from the device, not a static tuple"
for fixture in FAMILIES:
assert _rep(fixture)["x.com.samsung.da.supportedAutoExeState"] == [
"Off",
"Airpurify",
"Alarm",
], fixture
def test_action_write_sends_the_raw_advertised_value():
"""select.py maps the chosen option back to the device's own casing before
calling write_fn, so the body is the advertised token verbatim."""
for raw in ("Off", "Airpurify", "Alarm"):
href, body = _desc("sensing_mode").write_fn(raw, {})
assert href == HREF
assert body == {"x.com.samsung.da.autoExeState": raw}
def test_activation_write_leaves_the_action_alone():
"""Toggling the feature must not disturb autoExeState -- that's what makes
the switch able to do something the action select can't."""
for payload, expected in (("On", "On"), ("Off", "Off")):
href, body = _desc("periodic_air_sensing").write_fn(payload, {})
assert href == HREF
assert body == {"x.com.samsung.da.periodicSensingActivationState": expected}
assert "x.com.samsung.da.autoExeState" not in body
# --- interval ----------------------------------------------------------------
def test_sensing_interval_only_where_the_field_exists():
"""TP1X_DA-AC-AIR (issue #130) omits periodicSensingInterval; the other two
report it. The entity must follow the field, not the href."""
assert "sensing_interval" in _state("air_purifier_avt_ww")
assert "sensing_interval" in _state("air_purifier_vtww")
assert "sensing_interval" not in _state("air_purifier_tp1x_da_ac_air")
def test_interval_is_minutes_in_the_ui_and_seconds_on_the_wire():
desc = _desc("sensing_interval")
assert desc.value_fn("600") == 10
assert desc.write_fn(10, {})[1] == {"x.com.samsung.da.periodicSensingInterval": "600"}
def test_interval_keeps_zero_distinct_from_unknown():
"""`if secs` would fold a reported 0 into None. Anything else nonzero
rounds up, so a sub-minute reading can't render as 0 and fall below the
entity's own floor."""
desc = _desc("sensing_interval")
assert desc.value_fn("0") == 0
assert desc.value_fn("20") == 1
assert desc.value_fn("61") == 2
assert desc.value_fn(None) is None
def test_interval_floor_is_one_minute():
"""lastSensingTime lands on an exact minute on this board family, so a
sub-minute interval is unobservable; and 0 has no established meaning
here, unlike the zero floors on oven.cook_time / delay_start_hours."""
desc = _desc("sensing_interval")
assert desc.native_min == 1
assert desc.write_fn(0, {}) is None
assert desc.write_fn(0.4, {}) is None
assert desc.write_fn(1, {})[1] == {"x.com.samsung.da.periodicSensingInterval": "60"}
# --- skip window -------------------------------------------------------------
def test_skip_time_splits_the_hhmmhhmm_window():
read_start = _desc("sensing_skip_start").value_fn
read_end = _desc("sensing_skip_end").value_fn
# Issue #190's unit ships a real window: 03:00-23:00.
assert read_start("03002300") == datetime.time(3, 0)
assert read_end("03002300") == datetime.time(23, 0)
# Issue #84's unit sits at the inert default.
assert read_start("00000000") == datetime.time(0, 0)
# Junk and short strings read as unknown rather than raising.
assert read_start("") is None
assert read_start("99999999") is None
assert read_end("0300") is None
def test_skip_time_write_preserves_the_other_half():
rep = {"x.com.samsung.da.periodicSensingSkipTime": "03002300"}
_, body = _desc("sensing_skip_start").write_fn(datetime.time(7, 30), rep)
assert body == {"x.com.samsung.da.periodicSensingSkipTime": "07302300"}
_, body = _desc("sensing_skip_end").write_fn(datetime.time(22, 5), rep)
assert body == {"x.com.samsung.da.periodicSensingSkipTime": "03002205"}
# A board that has never had a window set still round-trips.
_, body = _desc("sensing_skip_end").write_fn(datetime.time(1, 2), {})
assert body == {"x.com.samsung.da.periodicSensingSkipTime": "00000102"}
def test_skip_time_write_normalizes_a_half_it_cannot_parse():
"""Padding alone would splice a malformed half straight back onto the wire.
The read side already refuses one, so the write side zeroes it instead of
echoing junk to the device."""
junk = {"x.com.samsung.da.periodicSensingSkipTime": "0730zzzz"}
_, body = _desc("sensing_skip_start").write_fn(datetime.time(8, 0), junk)
assert body == {"x.com.samsung.da.periodicSensingSkipTime": "08000000"}
junk = {"x.com.samsung.da.periodicSensingSkipTime": "zzzz2200"}
_, body = _desc("sensing_skip_end").write_fn(datetime.time(23, 0), junk)
assert body == {"x.com.samsung.da.periodicSensingSkipTime": "00002300"}
def test_skip_status_switch_body():
assert _desc("periodic_sensing_skip_status").write_fn("On", {})[1] == {
"x.com.samsung.da.periodicSensingSkipStatus": "On"
}
# --- read-only diagnostics ---------------------------------------------------
def test_last_sensing_time_reads_as_utc():
state = _state("air_purifier_avt_ww")
assert state["last_air_sensing_time"].tzinfo is not None
assert state["last_air_sensing_time"].year >= 2020
def test_read_only_keys_match_the_range_hood_capability():
"""The three read-only sensor keys are shared with the hood deliberately,
so both families read from one translation catalog entry each. If either
side renames one, this catches the drift.
periodic_air_sensing is excluded: it's a SwitchDesc here and a
BinarySensorDesc on the hood, so the two sit in different platform
catalogs and are worded differently -- see the next test.
"""
from custom_components.localthings.registry.capabilities import range_hood
hood = {d.key for d in range_hood.AIR_LEVEL_CHECK.entities}
ours = {d.key for d in air_purifier.AIR_LEVEL_CHECK.entities}
assert {
"air_sensing_state",
"last_air_sensing_time",
"last_air_sensing_level",
} <= hood & ours
def test_periodic_air_sensing_is_writable_here_and_read_only_on_hoods():
"""The reason range_hood.AIR_LEVEL_CHECK is not imported directly: the hood
models this key as a read-only BinarySensorDesc, this board needs a
writable SwitchDesc. Reusing the hood's capability would migrate every hood
user's entity to a different platform."""
from custom_components.localthings.registry.capabilities import range_hood
from custom_components.localthings.registry.entities import BinarySensorDesc, SwitchDesc
hood = next(d for d in range_hood.AIR_LEVEL_CHECK.entities if d.key == "periodic_air_sensing")
assert isinstance(hood, BinarySensorDesc)
ours = _desc("periodic_air_sensing")
assert isinstance(ours, SwitchDesc)
assert ours.write_fn is not None
def test_read_only_diagnostics_match_the_hood_on_visibility():
"""The hood leaves all three enabled; asserting key parity with it while
hiding two of them would be a quiet divergence."""
for key in ("air_sensing_state", "last_air_sensing_time", "last_air_sensing_level"):
assert _desc(key).enabled_default is True, key
@@ -0,0 +1,109 @@
"""Tests for the AILP_DA-AC-FAC-02011_0000 air conditioner (issue #319).
This board resolves to the airconditioner registry two independent ways --
modelNum's 'FAC' board token (for_device_by_model) and /oic/d's
oic.d.airconditioner type (for_device_by_oic_type) agree -- and reports
several resources the sibling TP1X_DA-AC-CAC-01001 board (issue #191) left
as a documented gap: /display/vs/0 and the /settings/sound/* trio (now
shared with air_purifier.py's identical shapes), plus two genuinely new
hrefs (/csi/absenceclean/vs/0, /csi/energysaving/vs/0).
"""
from typing import cast
from custom_components.localthings.coordinator import LocalThingsCoordinator
from custom_components.localthings.entity import _is_included
from custom_components.localthings.registry.adapter import flatten
from custom_components.localthings.registry.by_type import (
for_device_by_model,
for_device_by_oic_type,
resolve,
)
from custom_components.localthings.registry.discovery import discover
from tests.conftest import _load_device
_DEVICE_TYPES = ("oic.wk.d", "oic.d.airconditioner")
class _FakeCoordinator:
"""Minimal stand-in for entity._is_included's coordinator dependency --
same shape as test_entity.py's own fake, kept local rather than shared
across test modules."""
def __init__(self, last_resources):
self.last_resources = last_resources
def canonical_resources(self, subdevice):
return self.last_resources
def _resources():
return _load_device("airconditioner_ailp_fac")
def _bound():
resources = _resources()
reg = resolve(resources, device_types=_DEVICE_TYPES)
assert reg is not None
return discover(resources, reg.capabilities, reg.pattern_capabilities), resources
def test_oic_device_type_resolves_to_airconditioner_registry():
reg = for_device_by_oic_type(_DEVICE_TYPES)
assert reg is not None and reg.name == "airconditioner"
def test_board_token_resolves_to_airconditioner_registry():
"""'FAC' is a real _BOARD_TOKEN_TO_KEY entry -- for_device_by_model
alone (no device_types) already resolves this board correctly, same as
for_device_by_oic_type above; resolve()'s device_types-agreement isn't
covering an otherwise-unreachable path."""
resources = _resources()
info = resources["/information/vs/0"]
reg = for_device_by_model(
info["x.com.samsung.da.modelNum"], info["x.com.samsung.da.description"]
)
assert reg is not None and reg.name == "airconditioner"
def test_no_unbound_hrefs():
resources = _resources()
reg = resolve(resources, device_types=_DEVICE_TYPES)
assert reg is not None
unbound = []
discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
assert unbound == []
def test_sound_mode_registers_despite_no_live_mode_value():
"""This dump has no current `mode` value yet, only supportedModes
(mute/tone/voice). entity.py's default field-presence gate would
otherwise keep the select from ever being created in HA even though
adapter.flatten() (checked below) has no such gate and would look
bound regardless -- exercise the real _is_included gate, not just
flatten(), so a regression here can't hide behind that gap again."""
bound, resources = _bound()
entity = next(b for b in bound if b.desc.key == "sound_mode")
assert entity.desc.options_field == "supportedModes"
coord = cast(LocalThingsCoordinator, _FakeCoordinator(resources))
assert _is_included(entity, coord) is True
state = flatten(bound, resources)
assert "sound_mode" in state
assert state["sound_mode"] is None
def test_absence_clean_and_energy_saving_bound():
bound, resources = _bound()
state = flatten(bound, resources)
assert state["absence_clean"] is True
assert state["energy_saving_mode"] == "Off_100"
assert state["energy_saving_state"] == "Off"
def test_sound_volume_self_gates_off_without_max_level():
"""This board's /settings/sound/volume/vs/0 reports minLevel/resolution
but no maxLevel -- air_purifier.SOUND_VOLUME's exists_fn should keep it
unbound-but-covered rather than shipping a min=0/max=0 slider."""
bound, resources = _bound()
state = flatten(bound, resources)
assert "sound_volume" not in state
+369 -6
View File
@@ -217,6 +217,70 @@ def _desc(resources, key):
return None
def test_good_sleep_is_hours_while_the_token_counts_half_hours():
"""The appliance's own app pairs its duration picker with the values it sends
one to one -- 0:30 -> 1, 1:00 -> 2, 3:00 -> 6, 12:00 -> 24 -- so the token is
half hours and the entity, which is in hours, has to halve and double. The
fixture's own Sleep_0 is the one value that reads the same either way, hence
the injected token here."""
resources = _load_device(FIXTURE)
mode = resources["/mode/vs/0"]
mode["x.com.samsung.da.options"] = [
option for option in mode["x.com.samsung.da.options"] if option != "Sleep_0"
] + ["Sleep_5"]
bound, _ = _discover(resources)
assert flatten(bound, resources)["good_sleep"] == 2.5
desc = _desc(resources, "good_sleep")
assert (desc.native_max, desc.step) == (12, 0.5)
assert desc.write_fn(2.5, {}) == (
["mode", "vs", "0"],
{"x.com.samsung.da.options": ["Comode_Sleep", "Sleep_5"]},
)
# 12 hours is the app's maximum and has to be reachable -- it was not while
# the token was published as hours.
assert desc.write_fn(12, {})[1]["x.com.samsung.da.options"] == ["Comode_Sleep", "Sleep_24"]
def _options(rep_options):
return {"x.com.samsung.da.options": list(rep_options)}
def test_good_sleep_write_carries_the_mode_token_the_duration_belongs_to():
"""`Sleep_<n>` on its own does nothing. Measured on an ARTIK051_KRAC_18K:
writing `["Sleep_4"]` was answered 2.04 Changed and the token still read
`Sleep_0` at +8s and +45s, while `["Comode_Sleep", "Sleep_4"]` held. The
duration is a parameter of the mode, so both go in one write -- which is
also the only form the appliance's own app sends."""
desc = _desc(_load_device(FIXTURE), "good_sleep")
assert desc.write_fn(2, _options(["Comode_Off", "Sleep_0"])) == (
["mode", "vs", "0"],
{"x.com.samsung.da.options": ["Comode_Sleep", "Sleep_4"]},
)
# Off means leaving the mode as well as zeroing the duration.
assert desc.write_fn(0, _options(["Comode_Sleep", "Sleep_4"]))[1] == _options(
["Comode_Off", "Sleep_0"]
)
def test_good_sleep_and_nano_wind_share_one_token():
"""Nano wind and Good Sleep are one Comode_ slot, so running both is
Comode_NanoSleep -- the board produces that code by itself when nano is
asked for while the timer runs. Turning the timer off then has to leave nano
running rather than switching the mode off entirely, which is how the app
reads it back."""
desc = _desc(_load_device(FIXTURE), "good_sleep")
for comode in ("Comode_Nano", "Comode_NanoSleep"):
assert desc.write_fn(2, _options([comode, "Sleep_0"]))[1] == _options(
["Comode_NanoSleep", "Sleep_4"]
)
assert desc.write_fn(0, _options(["Comode_NanoSleep", "Sleep_4"]))[1] == _options(
["Comode_Nano", "Sleep_0"]
)
def test_filter_alarm_time_reads_the_threshold_and_writes_one_token():
"""The interval FilterTime_ is measured against, offered by the app as a
180/300/500/700 hour radio. All four were walked on hardware while watching
@@ -235,6 +299,54 @@ def test_filter_alarm_time_reads_the_threshold_and_writes_one_token():
)
def test_auto_clean_progress_and_stop_come_off_their_own_tokens():
"""Three tokens describe the drying cycle and the switch only covered the
first. AutocleanProgress_ is a percentage -- the app renders it into a
`<progress max="100">` beside a "{{value}}%" label -- and StopAutoClean_ is
the channel for ending a cycle early, whose presence is what says the
appliance accepts that at all (the fixture reports Idle, this unit's
resting value)."""
assert _state()["auto_clean_progress_legacy"] == 1.0 # the fixture's own value
desc = _desc(_load_device(FIXTURE), "auto_clean_stop")
assert desc is not None
assert desc.write_fn(desc.payload, {}) == (
["mode", "vs", "0"],
{"x.com.samsung.da.options": ["StopAutoClean_Set"]},
)
def test_auto_clean_stop_stays_off_boards_without_the_token():
"""Newer boards run the same cycle off /option/autoclean/vs/0 and say
nothing about stopping it, so writing a legacy token there would be a
guess."""
newer = _load_device("airconditioner_tp1x_rac")
assert _desc(newer, "auto_clean_stop") is None
assert "auto_clean_progress_legacy" not in _state("airconditioner_tp1x_rac")
def test_filter_time_reset_writes_the_appliance_s_own_trigger_token():
"""FilterCleanAlarm_Clear, measured on hardware: 2.04 Changed and
FilterTime_95 -> FilterTime_0, still zero on a fresh session and every poll
after. The token is a trigger the board acts on rather than a value it
stores -- it never appears in options[] -- so the button is gated on the
counter's own token being present, which is what says this board has a
filter timer at all."""
desc = _desc(_load_device(FIXTURE), "filter_time_reset")
assert desc is not None
assert desc.write_fn(desc.payload, {}) == (
["mode", "vs", "0"],
{"x.com.samsung.da.options": ["FilterCleanAlarm_Clear"]},
)
def test_filter_time_reset_stays_off_boards_without_the_counter():
"""No FilterTime_ token, no counter to reset. Newer boards report filter
usage through their own resource and would need a different mechanism, so
offering a button that writes a legacy token there would be a guess."""
assert _desc(_load_device("airconditioner_tp1x_rac"), "filter_time_reset") is None
def test_filter_alarm_time_stays_off_boards_with_a_real_threshold_resource():
"""Newer boards carry air_filter_threshold off supportedFilterDesiredUsage;
two thresholds on one device would be a coin flip for the user.
@@ -313,17 +425,22 @@ def test_preset_comes_from_the_comode_token():
resources = _load_device(FIXTURE)
entity = _climate(resources)
assert entity.preset_mode == "none" # Comode_Off in the fixture
# Codes learned by driving this unit through its cloud integration and
# reading the token back. They go through the same dynamic resolver as a
# real convenient resource's supportedModes, so 'Nano' resolves to the
# existing 'nano' preset -- already labelled WindFree in the catalog.
# The codes go through the same dynamic resolver as a real convenient
# resource's supportedModes, so 'Nano' resolves to the existing 'nano' preset
# -- already labelled WindFree in the catalog. Which of them are offered
# depends on the HVAC mode and on the unit's own capability bits; the fixture
# is in Cool, and test_presets_follow_the_hvac_mode_and_the_capability_bits
# covers every mode.
assert entity.preset_modes == [
"none",
"nano",
"speed",
"2step",
"quiet",
"comfort",
"2step",
"speed",
"smart",
"sleep",
"nanosleep",
]
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
@@ -343,6 +460,252 @@ async def test_preset_write_uses_the_token_path():
assert coordinator.commands[-1][1] == ("preset_legacy", "Nano")
def test_the_sleep_modes_are_presets_too():
"""Good Sleep lives in the same Comode_ slot as the presets, so a unit
running it reports a code that was not in the list -- and a preset_mode
outside preset_modes is not a state HA allows. Verified against a live unit:
with the board on Comode_Sleep, the entity reported preset_mode 'sleep'
while preset_modes offered only none/nano/quiet/comfort/2step/speed."""
resources = _load_device(FIXTURE)
assert _climate(resources).preset_modes[-2:] == ["sleep", "nanosleep"]
for token, preset in (("Comode_Sleep", "sleep"), ("Comode_NanoSleep", "nanosleep")):
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
resources["/mode/vs/0"]["x.com.samsung.da.options"] = [
token if option.startswith("Comode_") else option for option in options
]
entity = _climate(resources)
assert entity.preset_mode == preset
assert preset in entity.preset_modes
def test_boards_without_the_sleep_token_do_not_get_the_sleep_presets():
"""The codes come with the Sleep_ token; a unit that has no such token has
nothing to report them from."""
resources = _load_device(FIXTURE)
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
resources["/mode/vs/0"]["x.com.samsung.da.options"] = [
option for option in options if not option.startswith("Sleep_")
]
presets = _climate(resources).preset_modes
assert "sleep" not in presets and "nanosleep" not in presets
def _in_mode(mode, fixture=FIXTURE):
resources = _load_device(fixture)
resources["/mode/vs/0"]["x.com.samsung.da.modes"] = [mode]
return _climate(resources).preset_modes
def test_presets_follow_the_hvac_mode_and_the_capability_bits():
"""The fixture's own OptionCode_35882 / ExtendOptionCode_7 say: WindFree yes
(eoc[31]), 18K yes (eoc[30]), Quiet yes (oc[10]), Turbo/Comfort in Heat yes
(oc[12]), d'light no (oc[2]), Single User no (oc[3], oc[11]).
Its owner read the same lists off the remote and the appliance's app --
2-Step/Fast Turbo/Comfort/Quiet/WindFree in Cool, Fast Turbo/Comfort/Quiet in
Heat with WindFree impossible, WindFree alone in Dry and Fan, nothing in Auto
beyond WindFree (which the app reaches by switching to Cool) -- and the
appliance itself refused Comode_Nano in Auto and accepted it in Cool.
"""
assert _in_mode("Cool") == [
"none",
"nano",
"speed",
"2step",
"quiet",
"comfort",
"smart",
"sleep",
"nanosleep",
]
# Heat: no WindFree at all, and no Smart Saver (Cool-only).
heat = _in_mode("Heat")
assert "nano" not in heat
assert "smart" not in heat
assert [c for c in ("speed", "comfort", "quiet") if c in heat] == ["speed", "comfort", "quiet"]
# Dry and Fan: WindFree is the only one, and it keeps the mode.
for mode in ("Dry", "Wind"):
assert _in_mode(mode) == ["none", "nano"]
# Auto: WindFree only because this is an 18K model.
assert _in_mode("Auto") == ["none", "nano"]
# d'light Cool is a live rule and this unit's oc[2] denies it everywhere.
for mode in ("Cool", "Heat", "Dry", "Wind", "Auto"):
assert "dlightcool" not in _in_mode(mode), mode
def test_a_board_with_only_the_old_map_keeps_the_unconditional_list():
"""One map is not enough to judge by. `airconditioner_artik051_dongle_fac_18k`
is a legacy board that publishes OptionCode and no ExtendOptionCode, so every
eoc-gated rule would read None -- and None means "this board does not publish
the map", not "the feature is absent". Deriving from it would have cost that
unit WindFree in every mode, and left it with ['none'] alone in its own
fixture mode.
Its OptionCode is also 521, three orders of magnitude below the RAC-class
values these bit positions were read from, which is the second reason not to
interpret it: the FAC and CAC families use the field differently.
"""
resources = _load_device("airconditioner_artik051_dongle_fac_18k")
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
assert any(o.startswith("OptionCode_") for o in options)
assert not any(o.startswith("ExtendOptionCode_") for o in options)
baseline = ["none", "nano", "quiet", "comfort", "2step", "speed"]
for mode in ("Auto", "Cool", "Heat", "Dry", "Wind"):
resources["/mode/vs/0"]["x.com.samsung.da.modes"] = [mode]
assert _climate(resources).preset_modes == baseline, mode
def test_the_other_board_with_both_maps_still_derives():
"""`airconditioner_artik051_krac_energy` is the same model as the fixture
above with a different OptionCode (56378), and carries both maps -- so it
stays on the derived path rather than the fallback."""
presets = _in_mode("Cool", fixture="airconditioner_artik051_krac_energy")
assert presets[:1] == ["none"]
assert "nano" in presets and "smart" in presets
assert presets != ["none", "nano", "quiet", "comfort", "2step", "speed"]
def test_an_unknown_hvac_mode_falls_back_instead_of_deriving():
"""An HVAC mode these rules have never seen is the same "cannot judge" case
as an absent map, so it gets the same answer rather than a derived-but-wrong
one. Reachable with a partial or malformed rep, where `modes` is missing."""
resources = _load_device(FIXTURE)
for modes in ([], ["CoolClean"]):
resources["/mode/vs/0"]["x.com.samsung.da.modes"] = modes
assert _climate(resources).preset_modes == [
"none",
"nano",
"quiet",
"comfort",
"2step",
"speed",
], modes
async def test_aicomfort_neither_offers_nano_nor_switches_the_mode():
"""The app disables WindFree in AIComfort, so it is not offered -- and the
Cool-first write is therefore Auto-only, with no unreachable branch for a
mode that can never ask for it."""
resources = _load_device(FIXTURE)
resources["/mode/vs/0"]["x.com.samsung.da.modes"] = ["AIComfort"]
coordinator = _FakeCoordinator(resources)
entity = _climate(resources, coordinator)
assert "nano" not in entity.preset_modes
await entity.async_set_preset_mode("quiet")
assert [payload for _, payload in coordinator.commands] == [("preset_legacy", "Quiet")]
def test_a_bit_that_is_zero_removes_its_preset():
"""oc[12] is what puts Fast Turbo and Comfort in Heat; without it the app
hides both, and so does this."""
resources = _load_device(FIXTURE)
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
# 35882 with oc[12] cleared, everything else untouched.
assert format(35882, "016b")[12] == "1"
cleared = int(format(35882, "016b")[:12] + "0" + format(35882, "016b")[13:], 2)
resources["/mode/vs/0"]["x.com.samsung.da.options"] = [
f"OptionCode_{cleared}" if option.startswith("OptionCode_") else option
for option in options
]
resources["/mode/vs/0"]["x.com.samsung.da.modes"] = ["Heat"]
presets = _climate(resources).preset_modes
assert "speed" not in presets and "comfort" not in presets
assert "quiet" in presets # oc[10], untouched
def test_a_board_without_the_bit_maps_keeps_the_unconditional_list():
"""An absent map is not a claim that nothing is supported -- issue #136's unit
of this same model publishes a different token set, and a board that omits
OptionCode entirely must not lose every preset."""
resources = _load_device(FIXTURE)
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
resources["/mode/vs/0"]["x.com.samsung.da.options"] = [
option for option in options if not option.startswith(("OptionCode_", "ExtendOptionCode_"))
]
resources["/mode/vs/0"]["x.com.samsung.da.modes"] = ["Auto"]
assert _climate(resources).preset_modes == [
"none",
"nano",
"quiet",
"comfort",
"2step",
"speed",
]
def test_the_active_code_is_always_listed_even_where_the_rules_deny_it():
"""A remote can put the unit in a mode these rules would not offer -- and a
preset_mode outside preset_modes is not a state HA allows, so the appliance
has the last word. Measured: Comode_2Step was accepted and held while the
unit was in Auto, where neither the remote nor the app offers it."""
resources = _load_device(FIXTURE)
options = resources["/mode/vs/0"]["x.com.samsung.da.options"]
resources["/mode/vs/0"]["x.com.samsung.da.options"] = [
"Comode_2Step" if option.startswith("Comode_") else option for option in options
]
resources["/mode/vs/0"]["x.com.samsung.da.modes"] = ["Auto"]
entity = _climate(resources)
assert entity.preset_mode == "2step"
assert "2step" in entity.preset_modes
async def test_nano_in_auto_switches_the_board_to_cool_first():
"""Comode_Nano written while the unit is in Auto is answered 2.04 Changed and
dropped; the same token after a separate mode write holds. Putting modes and
options in one POST does not work either, so the mode goes first, on its own.
"""
resources = _load_device(FIXTURE)
resources["/mode/vs/0"]["x.com.samsung.da.modes"] = ["Auto"]
coordinator = _FakeCoordinator(resources)
entity = _climate(resources, coordinator)
await entity.async_set_preset_mode("nano")
assert [payload for _, payload in coordinator.commands] == [
("mode", "Cool"),
("preset_legacy", "Nano"),
]
async def test_nano_outside_auto_writes_only_the_preset():
"""In Cool the token holds on its own, so nothing else is sent -- and in Dry
the mode must be left alone, since WindFree keeps it."""
for mode in ("Cool", "Dry"):
resources = _load_device(FIXTURE)
resources["/mode/vs/0"]["x.com.samsung.da.modes"] = [mode]
coordinator = _FakeCoordinator(resources)
await _climate(resources, coordinator).async_set_preset_mode("nano")
assert [payload for _, payload in coordinator.commands] == [("preset_legacy", "Nano")], mode
def test_nano_preset_keeps_a_running_good_sleep_at_its_own_duration():
"""Writing a bare Comode_Nano over a live Comode_Sleep/Sleep_4 came back as
Comode_NanoSleep/Sleep_16 -- the board upgrades the code by itself and then
supplies a duration of its own, turning two hours into eight without anyone
asking. Sending the pair keeps the user's value."""
from custom_components.localthings.registry.capabilities.airconditioner import _climate_write
assert _climate_write(("preset_legacy", "Nano"), _options(["Comode_Sleep", "Sleep_4"]))[
1
] == _options(["Comode_NanoSleep", "Sleep_4"])
# Idle timer: nano is just nano, exactly as before.
assert _climate_write(("preset_legacy", "Nano"), _options(["Comode_Off", "Sleep_0"]))[
1
] == _options(["Comode_Nano"])
# A sleep preset selected outright has no duration to reuse, so it takes the
# one the appliance itself falls back to (Sleep_16, eight hours).
assert _climate_write(("preset_legacy", "Sleep"), _options(["Comode_Off", "Sleep_0"]))[
1
] == _options(["Comode_Sleep", "Sleep_16"])
# Any other preset is untouched by all of this.
assert _climate_write(("preset_legacy", "Quiet"), _options(["Comode_Sleep", "Sleep_4"]))[
1
] == _options(["Comode_Quiet"])
async def test_newer_boards_keep_the_resource_paths():
"""The legacy fallbacks are gated on this board's resource shape, so a
board with /wind/* and /mode/convenient/vs/0 must be untouched by them."""
+54 -12
View File
@@ -6,18 +6,40 @@ token -- this board was the one exception (its oneUiVersion self-reports
"7.0 Air conditioner", but 'CAC' had never been added to the board-token
table), so it silently fell back to common caps and lost its climate entity.
This dump is NOT fully covered yet -- eight hrefs remain unbound (edge
lighting, a second stateful light resource, absence-clean, four
`/settings/sound/*` resources, smart-sensing-cooling), all genuinely new to
this board generation. That's a real device-support gap, left documented
here rather than guessed at, per the 'don't guess' rule -- fixing the
routing regression was the scope of #191.
This dump is NOT fully covered yet -- two hrefs remain unbound
(`/settings/sound/optimization/vs/0`, smart-sensing-cooling), both
genuinely new to this board generation. That's a real device-support gap,
left documented here rather than guessed at, per the 'don't guess' rule --
fixing the routing regression was the scope of #191.
/settings/sound/mode/vs/0, /settings/sound/output/vs/0 and
/settings/sound/volume/vs/0 used to be on this list too, until issue #319
(a sibling TP1X_DA-AC-FAC-class board) supplied a live dump for them --
airconditioner.SOUND_MODE and the reused air_purifier.SOUND_OUTPUT/
SOUND_VOLUME now cover all three here as well.
/edgelighting/vs/0 and /light/stateful/vs/0 used to be on this list too,
until issue #288 (six System A/C cassette units on this same board) gave
real dump evidence for both -- airconditioner.EDGE_LIGHTING and
LIGHT_STATEFUL now cover them.
/mds/absenceclean/vs/0 used to be on this list too -- its {mode,
supportedModes: [On, Off]} shape is byte-identical to issue #319's
/csi/absenceclean/vs/0, confirmed on that sibling board rather than
guessed, so airconditioner.MDS_ABSENCE_CLEAN now covers it too.
/uvled/vs/0 and /filter/airdustPM1filter/vs/0 used to be on this list too,
until issue #270 (TP1X_FAC_TIME_23K) added real capabilities for both --
this board's own live filterUsage/filterStatus data on the PM1 filter binds
through the same exists_fn-gated entities #270's dump (which has neither
field) leaves empty.
/airlevelcheck/vs/0 was never on this unbound list (this fixture's rep
already carried a full set of periodicSensing*/autoExeState fields), but
until PR #316 it was globally ignored by airconditioner.py's own
_AC_IGNORED as "scheduler plumbing" -- this fixture's own populated values
were the proof that description was wrong. air_purifier.AIR_LEVEL_CHECK
now covers it (see test_airlevelcheck_binds_real_ai_purify_state below).
"""
from custom_components.localthings.registry.adapter import flatten
@@ -27,13 +49,7 @@ from tests.conftest import _load_device
_STILL_UNBOUND = frozenset(
{
"/edgelighting/vs/0",
"/light/stateful/vs/0",
"/mds/absenceclean/vs/0",
"/settings/sound/mode/vs/0",
"/settings/sound/optimization/vs/0",
"/settings/sound/output/vs/0",
"/settings/sound/volume/vs/0",
"/smartsensingcooling/vs/0",
}
)
@@ -65,6 +81,32 @@ def test_documented_coverage_gap_is_exactly_this_set():
assert set(unbound) == _STILL_UNBOUND
def test_mds_absenceclean_shares_csi_absenceclean_key():
"""/mds/absenceclean/vs/0's mode=='Off' on this dump -- confirms
MDS_ABSENCE_CLEAN actually binds (not just that the href stops
reporting as unbound)."""
resources = _resources()
reg = _reg(resources)
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
state = flatten(bound, resources)
assert state["absence_clean"] is False
def test_airlevelcheck_binds_real_ai_purify_state():
"""This fixture's /airlevelcheck/vs/0 has real, populated values --
periodic_air_sensing on, sensing_mode 'Alarm' -- confirming
air_purifier.AIR_LEVEL_CHECK binds real AI-Purify state here rather
than the inert plumbing _AC_IGNORED used to describe."""
resources = _resources()
reg = _reg(resources)
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
state = flatten(bound, resources)
assert state["periodic_air_sensing"] is True
assert state["sensing_mode"] == "Alarm"
assert state["sensing_interval"] == 30 # 1800s
assert state["air_sensing_state"] == "NonProcessing"
def test_non_legacy_board_uses_the_generic_energy_scale():
"""This board reports /wind/strength/vs/0 (not /airflow/vs/0), so
is_legacy_board() is False and it must use the plain wh_to_kwh scale,
+13
View File
@@ -221,6 +221,19 @@ def test_tp1x_climate_entity_is_bound():
assert len(climate) == 1 and climate[0].href == "/mode/vs/0"
def test_tp1x_airlevelcheck_binds_real_ai_purify_state():
"""This fixture's /airlevelcheck/vs/0 has real, populated
periodicSensing*/autoExeState values too (PR #316's finding that
_AC_IGNORED's old "scheduler plumbing" description was wrong wasn't
specific to one board) -- air_purifier.AIR_LEVEL_CHECK now covers it."""
reg, resources = _ac_tp1x()
state = flatten(discover(resources, reg.capabilities, reg.pattern_capabilities), resources)
assert state["periodic_air_sensing"] is True
assert state["sensing_mode"] == "Alarm"
assert state["sensing_interval"] == 30 # 1800s
assert state["air_sensing_state"] == "NonProcessing"
def test_tp2x_rac_20k_model_resolves_via_model_fallback():
"""TP2X_RAC_20K (issue #37) reports no oneUiVersion and no '_PRAC_' token
-- resolved via the '_RAC_' modelNum fallback added for this device."""
@@ -0,0 +1,113 @@
"""Tests for the ventilation-mode/Wind-Free/Wind-Sleep additions extracted
from PR #316 (Samsung "System Fresh Air Ventilator", model
ACA-KR-TP2-21-AN9000, vid DA-AC-DIFFUSER-01001).
No raw diagnostics dump for this model was available -- PR #316 never
attached one, only Korean code comments describing field shapes the
contributor said they observed. Per this project's fixture-integrity rule
(a fixture must record what hardware actually did, not a third party's
prose about it), there's no `airconditioner_*_device.json` fixture for
this model here. These tests instead exercise the gating logic directly
against hand-built reps matching those quoted shapes, clearly distinct
from this suite's fixture-backed tests, and check the new gate doesn't
false-positive against every real AC fixture already in the corpus.
If a real diagnostics dump for this model ever surfaces (tracked as a
follow-up device-support issue), replace this file with a proper
fixture + golden + capability test per the usual workflow, and drop the
disclaimer above.
"""
import glob
import json
import os
from custom_components.localthings.registry.adapter import flatten
from custom_components.localthings.registry.by_type import for_device_by_model
from custom_components.localthings.registry.capabilities.airconditioner import (
WINDFREE,
WINDSLEEP,
_is_ventilation_mode_device,
)
from custom_components.localthings.registry.discovery import discover
from tests.conftest import _load_device
_FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures")
def _all_airconditioner_fixture_names():
names = []
for path in glob.glob(os.path.join(_FIXTURES_DIR, "airconditioner*_device.json")):
name = os.path.basename(path)[: -len("_device.json")]
with open(path) as f:
info = json.load(f)
rep = next(
(e["rep"] for e in info.get("device0", []) if e.get("href") == "/information/vs/0"),
None,
)
if rep is not None: # for_device_by_model needs /information/vs/0
names.append(name)
return names
def test_ventilation_mode_gate_never_false_positives_on_real_ac_fixtures():
"""None of the real air-conditioner fixtures in this corpus use the
Purification/Ventilation/SmartVentilation vocabulary -- confirms
_is_ventilation_mode_device can't turn a real AC's climate card into
this select."""
for name in _all_airconditioner_fixture_names():
resources = _load_device(name)
reg = for_device_by_model(
resources["/information/vs/0"]["x.com.samsung.da.modelNum"],
resources["/information/vs/0"]["x.com.samsung.da.description"],
)
if reg is None or reg.name != "airconditioner":
continue
mode_rep = resources.get("/mode/vs/0")
if not mode_rep:
continue
assert _is_ventilation_mode_device(mode_rep, resources) is False, name
def test_ventilation_mode_gate_matches_diffuser_shape():
"""PR #316: supportedModes exactly {Purification, Ventilation,
SmartVentilation} -- the vocabulary that makes climate.py's hvac_mode
collapse to one stuck value with no way to tell the three apart."""
rep = {
"x.com.samsung.da.modes": ["Purification"],
"x.com.samsung.da.supportedModes": ["Purification", "Ventilation", "SmartVentilation"],
}
assert _is_ventilation_mode_device(rep, {}) is True
def test_ventilation_mode_gate_rejects_partial_overlap():
"""A real AC reporting an unrelated mode alongside one of these three
words (coincidence, not this device) must not gate in -- the check is
'subset of', not 'intersects'."""
rep = {"x.com.samsung.da.supportedModes": ["Ventilation", "Cool", "Heat"]}
assert _is_ventilation_mode_device(rep, {}) is False
def _bind(capability, href, rep):
resources = {href: rep}
bound = discover(resources, {href: [capability]}, [])
return flatten(bound, resources)
def test_windfree_and_windsleep_read_their_own_hrefs():
"""PR #316's quoted rep shape: {'x.com.samsung.da.windfree': 'On'/'Off',
'x.com.samsung.da.displaycondition': 'normal'} (displaycondition is a
read-only UI-visibility flag, deliberately not modeled)."""
windfree_state = _bind(
WINDFREE,
"/modeoption/windfree/vs/0",
{"x.com.samsung.da.windfree": "On", "x.com.samsung.da.displaycondition": "normal"},
)
assert windfree_state["windfree"] is True
windsleep_state = _bind(
WINDSLEEP,
"/modeoption/windsleep/vs/0",
{"x.com.samsung.da.windsleep": "Off", "x.com.samsung.da.displaycondition": "normal"},
)
assert windsleep_state["windsleep"] is False
+13
View File
@@ -29,6 +29,19 @@ class TestIsStubRep:
class TestParseDevice0Batch:
def test_keeps_first_resource_when_collection_rep_is_absent(self):
"""Some firmware starts directly with resource entries instead of a
device-level collection representation."""
device0 = [
{"href": "/connectionconfig/vs/0", "rep": {"autoReconnection": "true"}},
{"href": "/power/vs/0", "rep": {"power": "Off"}},
]
assert parse_device0_batch(device0) == {
"/connectionconfig/vs/0": {"autoReconnection": "true"},
"/power/vs/0": {"power": "Off"},
}
def test_stub_rep_kept_distinct_from_genuine_empty(self):
device0 = [
{},
+28
View File
@@ -1,3 +1,4 @@
from custom_components.localthings.registry.by_type import _REGISTRY_BY_KEY
from custom_components.localthings.registry.entities import (
PLATFORM_OF,
BinarySensorDesc,
@@ -54,3 +55,30 @@ def test_select_carries_options_and_write_fn():
)
assert d.write_fn is not None
assert d.write_fn("tone", {}) == (["settings", "sound", "mode", "vs", "0"], {"mode": "tone"})
def test_read_only_sensor_platforms_do_not_use_config_category():
"""Home Assistant rejects config-category Sensor/BinarySensor entities.
Traverse device registries rather than the smaller global capability set
so device-specific and pattern capabilities stay covered as the registry
grows.
"""
violations = set()
for registry in _REGISTRY_BY_KEY.values():
capabilities = [
capability for group in registry.capabilities.values() for capability in group
]
capabilities.extend(registry.pattern_capabilities)
for capability in capabilities:
href = capability.href or capability.href_prefix or "<pattern>"
for desc in capability.entities:
if (
isinstance(desc, (SensorDesc, BinarySensorDesc))
and desc.entity_category == "config"
):
violations.add((registry.name, href, desc.key))
assert violations == set()
@@ -0,0 +1,58 @@
"""Tests for the TP2X_DA-KS-COOKTOP-000001 gas cooktop (issue #314).
The reporter's actual complaint (six advertised burner slots when only
three are physically present) is expected: the registry declares a
generous static superset of slots and gates each on the live options array
per cooktop.py's own comment; there's no per-device signal that
distinguishes an advertised-but-nonexistent slot from a real one, so the
extra entities are disabled by the user, not filtered by the integration.
This file locks in the actual gap from that issue -- /alarms/vs/0 and
/kidslock/vs/0 -- now bound via common.ALARMS/KIDS_LOCK_VS_FALLBACK.
"""
from custom_components.localthings.registry.adapter import flatten
from custom_components.localthings.registry.by_type import resolve
from custom_components.localthings.registry.discovery import discover
from tests.conftest import _load_device
def _bound():
resources = _load_device("gas_cooktop_tp2x_ks")
reg = resolve(resources)
assert reg is not None
return discover(resources, reg.capabilities, reg.pattern_capabilities), resources
def test_resolves_to_gas_cooktop_registry():
resources = _load_device("gas_cooktop_tp2x_ks")
reg = resolve(resources)
assert reg is not None and reg.name == "gas_cooktop"
def test_no_unbound_hrefs():
_, resources = _bound()
reg = resolve(resources)
assert reg is not None
unbound = []
discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
assert unbound == []
def test_alarm_code_and_child_lock_bound():
bound, resources = _bound()
state = flatten(bound, resources)
assert state["alarm_code"] == "CT_E"
# x.com.samsung.da.kidsLock == "Ready" reads as unlocked, same polarity
# as every other board KIDS_LOCK_VS_FALLBACK covers.
assert state["child_lock"] is True
# The reporter's original complaint -- six advertised burner slots when
# only three are physically present -- isn't tested here beyond what the
# golden regression test already locks in (burner_0_state..burner_5_state
# all present). It's expected, not a bug: the registry declares a generous
# static superset of slots per cooktop.py's own comment, and this board's
# /mode/vs/0 rep carries no field distinguishing a real slot from an
# advertised-but-nonexistent one for a test to assert against -- the user
# disabling the three extra entities is the correct fix, not something the
# integration can filter automatically.
+100 -6
View File
@@ -6,12 +6,12 @@ import pytest
GOLDEN = Path(__file__).parent / "fixtures" / "golden"
def _new_state_keys(name, resources):
def _new_state_keys(name, resources, device_types=()):
from custom_components.localthings.registry.adapter import flatten
from custom_components.localthings.registry.by_type import resolve
from custom_components.localthings.registry.discovery import discover
reg = resolve(resources)
reg = resolve(resources, device_types=device_types)
if reg is None:
from custom_components.localthings.registry.registry import CAPABILITIES
@@ -134,6 +134,49 @@ def test_registry_reproduces_golden_state_keys_for_airconditioner():
)
def test_registry_reproduces_golden_state_keys_for_airconditioner_ailp_fac():
"""AILP_DA-AC-FAC-02011_0000 (issue #319) resolves both ways --
modelNum's 'FAC' board token and /oic/d's oic.d.airconditioner type
independently agree on the airconditioner registry. Passes
device_types through resolve() to exercise that agreement, not because
the board token is absent."""
from tests.conftest import _load_device
resources = _load_device("airconditioner_ailp_fac")
golden = json.loads((GOLDEN / "airconditioner_ailp_fac.json").read_text())
state_keys = _new_state_keys(
"airconditioner_ailp_fac", resources, device_types=("oic.wk.d", "oic.d.airconditioner")
)
assert set(state_keys) == set(golden["state_keys"]), (
f"state_keys mismatch:\n"
f" extra: {sorted(set(state_keys) - set(golden['state_keys']))}\n"
f" missing: {sorted(set(golden['state_keys']) - set(state_keys))}"
)
def test_registry_reproduces_golden_state_keys_for_oven_tp2x_ks_walloven():
"""TP2X_DA-KS-WALLOVEN-000002 (issue #300), a steam-oven-class board
(water tank, descale, pyro-free) quite unlike the NV7000BS-class board
oven.py's write comments were written against. /diagnosis/vs/0 was the
dump's only unbound href, now covered via dishwasher.DIAGNOSIS. The
board's options[] also has no UpperLamp_ token at all -- confirms
LAMP's new exists_fn keeps it from registering a phantom switch here,
same fastpreheat/NaturalSteam-class gap issue #183 fixed on its
siblings."""
from tests.conftest import _load_device
resources = _load_device("oven_tp2x_ks_walloven")
golden = json.loads((GOLDEN / "oven_tp2x_ks_walloven.json").read_text())
state_keys = _new_state_keys(
"oven_tp2x_ks_walloven", resources, device_types=("oic.wk.d", "oic.d.oven")
)
assert set(state_keys) == set(golden["state_keys"]), (
f"state_keys mismatch:\n"
f" extra: {sorted(set(state_keys) - set(golden['state_keys']))}\n"
f" missing: {sorted(set(golden['state_keys']) - set(state_keys))}"
)
def test_registry_reproduces_golden_state_keys_for_dehumidifier():
"""TP1X_DA_AC_DHM_01001_0000 (issue #88, AY18CG7500GED) shares the DA_AC_
board family with the room-AC models but carries the '_DHM_' token;
@@ -213,6 +256,25 @@ def test_registry_reproduces_golden_state_keys_for_water_purifier_coffee():
)
def test_registry_reproduces_golden_state_keys_for_gas_cooktop_tp2x_ks():
"""TP2X_DA-KS-COOKTOP-000001 (issue #314) -- routes via
for_device_by_resources' DeviceType_/OperationState signature, same as
the original cooktop fixture. /alarms/vs/0 and /kidslock/vs/0 were the
dump's only unbound hrefs; both are common.UNIVERSAL shapes this
registry now picks up individually (common.ALARMS,
common.KIDS_LOCK_VS_FALLBACK)."""
from tests.conftest import _load_device
resources = _load_device("gas_cooktop_tp2x_ks")
golden = json.loads((GOLDEN / "gas_cooktop_tp2x_ks.json").read_text())
state_keys = _new_state_keys("gas_cooktop_tp2x_ks", resources)
assert set(state_keys) == set(golden["state_keys"]), (
f"state_keys mismatch:\n"
f" extra: {sorted(set(state_keys) - set(golden['state_keys']))}\n"
f" missing: {sorted(set(golden['state_keys']) - set(state_keys))}"
)
def test_registry_reproduces_golden_state_keys_for_cooktop():
from tests.conftest import _load_device
@@ -259,6 +321,24 @@ def test_registry_reproduces_golden_state_keys_for_tp1x_ref_21k_eu():
)
def test_registry_reproduces_golden_state_keys_for_tp1x_ref_21k_airfilter():
"""TP1X_REF_21K, air-filter-equipped variant (issue #318) -- reports
/filter/airdustfilter/vs/0 (internal deodorizing filter), the one
unbound href on this dump. Unlike airconditioner.AIR_FILTER's
filterUsage/filterCapacity pair, this board's filterUsage is already a
0-100 percentage with no filterCapacity to divide by."""
from tests.conftest import _load_device
resources = _load_device("refrigerator_tp1x_ref_21k_airfilter")
golden = json.loads((GOLDEN / "refrigerator_tp1x_ref_21k_airfilter.json").read_text())
state_keys = _new_state_keys("refrigerator_tp1x_ref_21k_airfilter", resources)
assert set(state_keys) == set(golden["state_keys"]), (
f"state_keys mismatch:\n"
f" extra: {sorted(set(state_keys) - set(golden['state_keys']))}\n"
f" missing: {sorted(set(golden['state_keys']) - set(state_keys))}"
)
def test_registry_reproduces_golden_state_keys_for_range_hood():
from tests.conftest import _load_device
@@ -573,6 +653,21 @@ def test_registry_reproduces_golden_state_keys_for_induction_cooktop():
)
def test_registry_reproduces_golden_state_keys_for_induction_cooktop_nv9000d():
"""NV9000D-/KO2 compatibility fixture: the same three-burner registry,
with the safety-shutoff status but without optional probe/hood resources."""
from tests.conftest import _load_device
resources = _load_device("induction_cooktop_nv9000d")
golden = json.loads((GOLDEN / "induction_cooktop_nv9000d.json").read_text())
state_keys = _new_state_keys("induction_cooktop_nv9000d", resources)
assert set(state_keys) == set(golden["state_keys"]), (
f"state_keys mismatch:\n"
f" extra: {sorted(set(state_keys) - set(golden['state_keys']))}\n"
f" missing: {sorted(set(golden['state_keys']) - set(state_keys))}"
)
def test_registry_reproduces_golden_state_keys_for_range_no_info():
"""NE63B8411SS (issue #74) -- reports no oneUiVersion *and* no
/information/vs/0 at all, so neither for_device nor
@@ -1080,10 +1175,9 @@ def test_registry_reproduces_golden_state_keys_for_airconditioner_cac():
0.16.0 when oneUiVersion detection was dropped, since 'CAC' had never
been added to the modelNum board-token table. Resolved via the new 'CAC'
token onto the existing airconditioner registry. Not fully covered yet --
ten hrefs remain unbound (edge lighting, PM1 filter, stateful light,
absence-clean, four sound-settings resources, smart-sensing-cooling, UV
LED), all genuinely new to this board generation and out of scope for
the routing fix; see test_airconditioner_cac.py for the documented gap."""
two hrefs remain unbound (sound-optimization, smart-sensing-cooling),
both genuinely new to this board generation and out of scope for the
routing fix; see test_airconditioner_cac.py for the documented gap."""
from tests.conftest import _load_device
resources = _load_device("airconditioner_cac")
+25 -4
View File
@@ -6,8 +6,8 @@ from custom_components.localthings.registry.discovery import discover
from tests.conftest import _load_device
def _cooktop():
resources = _load_device("induction_cooktop")
def _cooktop(name="induction_cooktop"):
resources = _load_device(name)
info = resources["/information/vs/0"]
reg = for_device_by_model(
info["x.com.samsung.da.modelNum"],
@@ -16,8 +16,8 @@ def _cooktop():
return reg, resources
def _state():
reg, resources = _cooktop()
def _state(name="induction_cooktop"):
reg, resources = _cooktop(name)
bound = discover(resources, reg.capabilities, reg.pattern_capabilities)
return flatten(bound, resources)
@@ -73,3 +73,24 @@ def test_recipe_status_href_is_ignored_not_unbound():
cap.href for caps in reg.capabilities.values() for cap in caps if cap.entities == ()
}
assert "/cooktop/recipe/status/vs/0" in ignored_hrefs
def test_nv9000d_resolves_with_complete_coverage():
"""NV9000D-/KO2 reuses the standalone induction-cooktop surface but
omits the optional Bluetooth probe and paired-hood resources while adding
the read-only hot-surface auto-shutoff status."""
reg, resources = _cooktop("induction_cooktop_nv9000d")
assert reg is induction_cooktop.REGISTRY
unbound = []
discover(
resources,
reg.capabilities,
reg.pattern_capabilities,
log=unbound.append,
)
assert unbound == []
state = _state("induction_cooktop_nv9000d")
assert state["cooktop_safety_shutoff_enabled"] is True
assert not any(key.startswith(("probe_", "paired_hood_")) for key in state)
@@ -0,0 +1,56 @@
"""Tests for the TP2X_DA-KS-WALLOVEN-000002 steam oven (issue #300).
The reporter's "not fully supported" notification was /diagnosis/vs/0,
now covered via dishwasher.DIAGNOSIS. Their "doesn't respond to commands"
complaint is broader: oven.py's own module docstring already documents
setpoint/cook-time/mode writes as unproven on this local-OCF firmware, and
this board's options[] carries no UpperLamp_ token at all -- confirming
`lamp` was previously a phantom, write-does-nothing switch here (same gap
issue #183 fixed for fast_preheat/natural_steam on a different board).
"""
from custom_components.localthings.registry.adapter import flatten
from custom_components.localthings.registry.by_type import for_device_by_oic_type, resolve
from custom_components.localthings.registry.discovery import discover
from tests.conftest import _load_device
_DEVICE_TYPES = ("oic.wk.d", "oic.d.oven")
def _bound():
resources = _load_device("oven_tp2x_ks_walloven")
reg = resolve(resources, device_types=_DEVICE_TYPES)
assert reg is not None
return discover(resources, reg.capabilities, reg.pattern_capabilities), resources
def test_oic_device_type_resolves_to_oven_registry():
reg = for_device_by_oic_type(_DEVICE_TYPES)
assert reg is not None and reg.name == "oven"
def test_no_unbound_hrefs():
resources = _load_device("oven_tp2x_ks_walloven")
reg = resolve(resources, device_types=_DEVICE_TYPES)
assert reg is not None
unbound = []
discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
assert unbound == []
def test_lamp_not_bound_without_an_upperlamp_token():
"""This board's options[] has no UpperLamp_ entry -- confirms the new
exists_fn keeps `lamp` from registering a switch that would always
read Off and never actually do anything on write."""
bound, resources = _bound()
state = flatten(bound, resources)
assert "lamp" not in state
def test_sound_and_energy_saving_bound_from_real_options_tokens():
"""Unlike lamp, this board's options[] does carry Sound_On and
EnergySaving_On -- these switches should reflect real state."""
bound, resources = _bound()
state = flatten(bound, resources)
assert state["sound"] is True
assert state["energy_saving"] is True
@@ -0,0 +1,35 @@
"""Tests for the TP1X_REF_21K air-filter-equipped variant (issue #318).
The dump's only unbound href was /filter/airdustfilter/vs/0, this board's
internal deodorizing filter -- same filterUsage/filterStatus field pair as
common.WATER_FILTER, but filterUsage here is already a 0-100 percentage
(no filterCapacity to divide by, unlike airconditioner.AIR_FILTER).
"""
from custom_components.localthings.registry.adapter import flatten
from custom_components.localthings.registry.by_type import resolve
from custom_components.localthings.registry.discovery import discover
from tests.conftest import _load_device
def _bound():
resources = _load_device("refrigerator_tp1x_ref_21k_airfilter")
reg = resolve(resources)
assert reg is not None
return discover(resources, reg.capabilities, reg.pattern_capabilities), resources
def test_no_unbound_hrefs():
_, resources = _bound()
unbound = []
reg = resolve(resources)
assert reg is not None
discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
assert unbound == []
def test_air_filter_usage_and_status():
bound, resources = _bound()
state = flatten(bound, resources)
assert state["air_filter_usage"] == 100
assert state["air_filter_status"] == "wash"
+636
View File
@@ -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"}