laundry: discover and offer cloud "Download" cycles (issue #342)

A washer whose course table includes "Download"/"Downloaded" runs whichever
program the SmartThings cloud last pushed down. Those programs are now
selectable from the ordinary cycle select, so a downloaded Jeans or Sports
cycle can be started without giving the appliance internet access.

The device turns out to enumerate them itself. `CloudExtraCourse_` on
/course/vs/0 lists one byte per downloaded program, and byte 2 of a
program's payload is exactly that slot id -- verified against all nine
programs on the reporter's WW5000C and against the WA55A7700AV dump already
in the corpus. So nothing here is hardcoded: the appliance says which
programs exist, the payloads are learned by watching what it reports, and
the names come from the user.

That last part is unavoidable rather than a shortcut. A payload is only
visible while its program is loaded, and the appliance never reports a name
for one. So cloudcourse.py persists what has been seen (same rationale as
learned.py's mode store), a Repairs issue tells the owner how many programs
are still unaccounted for, and an options-flow step collects the names. A
program appears in the cycle select only once it is both learned and named.

Selecting one issues the only two-token options write in the codebase --
the course token has to switch to Download in the same write, or the
appliance accepts the program token and silently ignores it (confirmed on
hardware). The Download course code is learned by observation but never
applied until the user confirms it: tokens in this array are replaced by
prefix and never evicted, so a stale program token can appear alongside an
unrelated course, and acting on that would start the wrong wash cycle. For
the same reason a stale token is never reported as the running program.

Also of note:

- There is no single "Download" course code. The WW5000C uses 87, the
  WA55A7700AV uses 17 -- same Table_02. Any per-table lookup would have
  been wrong on one of the only two devices available to check.
- Payloads are replayed byte-for-byte and never decomposed or rebuilt.
  Bytes 5/7/9 do decode to temperature/rinse/spin on the WW5000C, 9 for 9,
  and produce nonsense on the WA55A7700AV -- so that decode is written up
  in docs/investigations/download-cycle.md and not shipped, and the
  read-only sensors it would have enabled were dropped.
- The store reaches the registry as a namespaced synthetic field merged
  onto /course/vs/0's rep at read time, so exists_fn/rep_fn/options/write_fn
  all see it through their existing signatures. It never enters the state
  cache, so it can't be polled over, written to the device, or land in a
  diagnostics dump.
- A name that would render identically to another cycle in the same
  dropdown is rejected in the flow: the select maps a chosen label back to
  a raw value by matching display text.

Non-English catalogs carry the new strings in English for now; they need
real translations.
This commit is contained in:
Marc Billow committed 2026-08-09 21:21:10 +00:00
1 parent 1424c2222e
commit f45bd6a72c
23 files changed
+2162 -32

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
{
"state_keys": [
"alarm_code",
"bubble_soak",
"buzzer_sound",
"child_lock",
"completion_minutes",
"cycle",
"cycle_active",
"delay_start_hours",
"detergent_low",
"diagnosis_status",
"drum_clean_cycles_remaining",
"drum_clean_last_cleaned",
"energy_kwh",
"energy_saved_kwh",
"finish_sound",
"finish_time",
"firmware_update",
"intensive",
"job_beginning_status",
"machine_state",
"power_switch",
"pre_wash",
"progress",
"progress_percentage",
"remote_control",
"rinse_cycles",
"softener_low",
"spin_speed",
"wash_temperature",
"water_liters"
]
}
+452
View File
@@ -0,0 +1,452 @@
{
"device0": [
{
"rt": [
"x.com.samsung.devcol",
"oic.wk.col"
],
"if": [
"oic.if.baseline",
"oic.if.ll",
"oic.if.b"
]
},
{
"href": "/realtimenotiforclient/vs/0",
"rep": {
"x.com.samsung.da.timeforshortnoti": "10",
"x.com.samsung.da.periodicnotisubscription": "true"
}
},
{
"href": "/alarms/vs/0",
"rep": {}
},
{
"href": "/diagnosis/vs/0",
"rep": {
"x.com.samsung.da.diagnosisStart": "Ready"
}
},
{
"href": "/energy/consumption/vs/0",
"rep": {
"x.com.samsung.da.instantaneousPower": "-500",
"x.com.samsung.da.instantaneousPowerUnit": "W",
"x.com.samsung.da.cumulativePower": "74800",
"x.com.samsung.da.cumulativeUnit": "Wh",
"x.com.samsung.da.cumulativeDate": "1786287600",
"x.com.samsung.da.cumulativeDateUTC": "1786280400",
"x.com.samsung.da.cumulativeSavedPower": "0"
}
},
{
"href": "/energy/consumption/0",
"rep": {}
},
{
"href": "/course/vs/0",
"rep": {
"x.com.samsung.da.supportedModes": [
"HOMECARE_WIZARD_V2"
],
"x.com.samsung.da.options": [
"DeviceType_0167",
"UpdateAllow_NotAllowed",
"Course_87",
"LaundryOutTime_0",
"SeamlessControl_Enable",
"KidsLockBypass_On",
"WashingTimes_0",
"DrumCleanProposal_40",
"DetergentOnce_0",
"DetergentLeft_0",
"DetergentBase_0",
"DetergentAlarm_Off",
"DetergentType_0",
"DetergentTotal_0",
"SoftenerOnce_0",
"SoftenerLeft_0",
"SoftenerBase_0",
"SoftenerAlarm_Off",
"SoftenerType_0",
"SoftenerTotal_0",
"SpecialFunction_4",
"AvailableDelayTime_74",
"BubbleSoak_Off",
"LaundryPlannerUserSetTime_0",
"ProgressTimeSet_421C20820437A2042C",
"SendToDevice_On",
"GMT_04",
"PreWashSetting_Off",
"IntensiveSetting_Off",
"CloudCourse_0021550449284D134AA04C0035F004F005F0AC00",
"CloudExtraCourse_0A5C286B2D0C55301A",
"OneTimeCloudCourse_001F6B0449284D134AA04C0035F004F005F0AC00",
"BubbleSoakSet_00F0F0F00000F0F000000000F000",
"EnergyLevelSet_050304040501050404030201020401",
"MostUsed_1B841E923FA67F00000000000000",
"PreWashAvailableSet_F0F0F0F00000F0F000F0F000F000",
"IntensiveAvailableSet_F0F0F0F00000F0F000F0F000F000",
"TextureLevel_None",
"SavingModeCondition_010102151C1BA0961C8F251C0A061A207F5C55656B0C2D3034030149035E2830",
"SavingMode_Off",
"WelcomeLighting_1",
"SupportedWelcomeLighting_000102",
"GeoFenceAlarm",
"UsagesDB_ok",
"EnergyKW_396",
"DrumCleanLog_2025-08-18T14:56:34|2025-11-02T21:08:39|2026-01-19T13:00:50|2026-03-23T12:10:12|2026-06-27T11:07:22|2026-08-09T10:13:44",
"TimeSync_NotSupported"
],
"x.com.samsung.da.supportedOptions": [
"31C8410923FA67F1B847E923FA67F25843E933FA57F20857E943FA67F088000913FA67F7485209204A5208780009000A00006841E930FA30F7F841E920FA30F65841E943FA57F8F8102923FA57F96841E920FA37F34841E923FA67FA0811E933FA33F"
]
}
},
{
"href": "/power/vs/0",
"rep": {
"x.com.samsung.da.power": "On"
}
},
{
"href": "/power/0",
"rep": {
"value": true
}
},
{
"href": "/cycleinterface/vs/0",
"rep": {}
},
{
"href": "/kidslock/vs/0",
"rep": {
"x.com.samsung.da.kidsLock": "Ready"
}
},
{
"href": "/kidslock/0",
"rep": {
"value": false
}
},
{
"href": "/operational/state/vs/0",
"rep": {
"x.com.samsung.da.state": "Ready",
"x.com.samsung.da.remainingTime": "01:14:00",
"x.com.samsung.da.progressPercentage": "1",
"x.com.samsung.da.progress": "None",
"x.com.samsung.da.delayEndTime": "00:00:00",
"x.com.samsung.da.supportedProgress": [
"None",
"Wash",
"Rinse",
"Spin",
"Finish"
]
}
},
{
"href": "/operational/state/0",
"rep": {
"currentMachineState": "**REDACTED**",
"machineStates": "**REDACTED**",
"jobStates": [
"None",
"Wash",
"Rinse",
"Spin",
"Finish"
],
"currentJobState": "None",
"remainingTime": "01:14:00",
"progressPercentage": "1"
}
},
{
"href": "/information/vs/0",
"rep": {
"x.com.samsung.da.modelNum": "DA_WM_TP1_21_COMMON|20348141|20010002001711124ACB020200080000",
"x.com.samsung.da.description": "DA_WM_TP1_21_COMMON_WW5000C/DC92-03495A_B06C",
"x.com.samsung.da.serialNum": "**REDACTED**",
"x.com.samsung.da.otnDUID": "**REDACTED**",
"x.com.samsung.da.diagProtocolType": "BLE_OCF",
"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": "WF1",
"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": "DA_WM_TP1_21_COMMON|20348141|20010002001711124ACB020200080000",
"x.com.samsung.da.type": "Software",
"x.com.samsung.da.number": "02986A260118(A182)",
"x.com.samsung.da.newVersionAvailable": "0"
},
{
"x.com.samsung.da.id": "1",
"x.com.samsung.da.description": "Firmware_1_DB_20348141240110090FFFFF203495412406195503FFFF(01672034814120349541_30000000)(FileDown:0)(Type:0)",
"x.com.samsung.da.type": "Firmware",
"x.com.samsung.da.number": "03481A24011009,03495A24061955",
"x.com.samsung.da.newVersionAvailable": "0"
},
{
"x.com.samsung.da.id": "2",
"x.com.samsung.da.description": "Firmware_2_DB_2025984624053003032FFFFFFFFFFFFFFFFFFFFFFFFE(016720259846FFFFFFFF_30000000)(FileDown:0)(Type:0)",
"x.com.samsung.da.type": "Firmware",
"x.com.samsung.da.number": "02598F24053003,FFFFFFFFFFFFFF"
}
]
}
},
{
"href": "/file/information/vs/0",
"rep": {
"x.com.samsung.timeoffset": "+02:00"
}
},
{
"href": "/washer/vs/0",
"rep": {
"x.com.samsung.da.waterTemperature": "30",
"x.com.samsung.da.supportedWaterTemperature": [
"None",
"Cold",
"20",
"30",
"40",
"60",
"90"
],
"x.com.samsung.da.spinLevel": "800",
"x.com.samsung.da.supportedSpinLevel": [
"RinseHold",
"NoSpin",
"400",
"800",
"1000",
"1200",
"1400"
],
"x.com.samsung.da.rinseCycles": "3",
"x.com.samsung.da.supportedRinseCycles": [
"0",
"1",
"2",
"3",
"4",
"5"
]
}
},
{
"href": "/st/washercourse/vs/0",
"rep": {
"x.com.samsung.da.st.washerMode": "Table_02_Course_87",
"x.com.samsung.da.st.courseTable": "Table_02"
}
},
{
"href": "/water/consumption/vs/0",
"rep": {
"x.com.samsung.da.cumulativeWater": "7512800"
}
},
{
"href": "/setting/vs/0",
"rep": {
"x.com.samsung.da.supportedSetLanguage": [
"ko_KR",
"en_US"
]
}
},
{
"href": "/wm/editcourse/vs/0",
"rep": {}
},
{
"href": "/wm/setinfo/vs/0",
"rep": {
"x.com.samsung.da.isModelSettingWithoutSC": "true",
"x.com.samsung.da.isModelSettingPowerOnOff": "false",
"x.com.samsung.da.modelCode": "M(None),W(WW8XCGC04AAEEG)"
}
},
{
"href": "/wm/jobbeginingstatus/vs/0",
"rep": {
"x.com.samsung.da.currentStatus": "None"
}
},
{
"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",
"otnStatus": "None",
"flashingProgress": "",
"otnTarget": "main",
"otnCompleteDate": "2026-03-04",
"otnList": [
{
"type": "WIFI",
"modelId": "DA_WM_TP1_21_COMMON",
"versions": [
"30260118"
],
"visVersion": "260118"
},
{
"type": "Micom",
"modelId": "01672034814120349541",
"versions": [
"24011009",
"24061955"
],
"visVersion": "240619"
},
{
"type": "Micom",
"modelId": "016720259846FFFFFFFF",
"versions": [
"24053003",
"FFFFFFFF"
],
"visVersion": "240530"
},
{
"type": "Micom",
"modelId": "016720259846FFFFFFFF",
"versions": [
"24053003",
"FFFFFFFF"
],
"visVersion": "240530"
}
]
}
},
{
"href": "/buzzersound/vs/0",
"rep": {
"supportedBuzzerSound": [
"Volume_Off",
"Volume_Low",
"Volume_Med",
"Volume_High"
],
"setBuzzerSound": "Volume_Low",
"supportedFinishSound": [
"FinishSound_1",
"FinishSound_2",
"FinishSound_3"
],
"setFinishSound": "FinishSound_2"
}
},
{
"href": "/remotectrl/vs/0",
"rep": {
"x.com.samsung.da.remoteControlEnabled": "false"
}
},
{
"href": "/remotectrl/0",
"rep": {
"value": false
}
},
{
"href": "/configuration/vs/0",
"rep": {
"x.com.samsung.da.region": "0000000000",
"x.com.samsung.da.countryCode": "DE"
}
},
{
"href": "/drlc/0",
"rep": {
"DRLevel": 0,
"start": "0000-00-00T00:00:00Z",
"duration": 0,
"override": false
}
},
{
"href": "/drlc/vs/0",
"rep": {
"x.com.samsung.da.drlcLevel": "0",
"x.com.samsung.da.durationminutes": "0",
"x.com.samsung.da.start": "0000-00-00T00:00:00Z",
"x.com.samsung.da.override": "Off",
"x.com.samsung.da.realSaving": "Off"
}
},
{
"href": "/timezone/vs/0",
"rep": {
"timezoneid": "Europe/Berlin",
"offset": "+02:00",
"DST": "ON"
}
},
{
"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": "/wirelessinfo/vs/0",
"rep": {
"macaddressWiFi": "**REDACTED**",
"macaddressBLE": "**REDACTED**"
}
},
{
"href": "/quickcontrol/info/vs/0",
"rep": {
"supportedVersion": "1.0"
}
}
]
}
+312
View File
@@ -0,0 +1,312 @@
"""Cloud "Download" programs on laundry devices (issue #342).
The store and blob parsing live in cloudcourse.py; how they reach the cycle
select lives in registry/capabilities/laundry.py. Both are covered here,
against the two real dumps in the corpus that carry these tokens:
washer_ww5000c_cloud the issue #342 reporter's WW5000C, sitting on
Download with a one-time Jeans override loaded over
a saved Sports default. Advertises nine programs.
washer_wa55a7700av a WA55A7700AV sitting on an ordinary local course,
with a saved program and the FFFF "none" sentinel in
the one-time slot. Advertises two programs.
"""
import pytest
from custom_components.localthings import cloudcourse
from custom_components.localthings.registry.capabilities import laundry, washer
from custom_components.localthings.registry.entities import SelectDesc
from tests.conftest import _load_device
# The reporter's nine captured programs, keyed by the slot byte the device
# itself advertises. Only used to drive the tests -- nothing in the shipped
# code carries a table of these (see cloudcourse.py's module docstring).
SPORTS = "0021550449284D134AA04C0035F004F005F0AC00"
JEANS = "001F6B0449284D134AA04C0035F004F005F0AC00"
TOWELS = "00040A0449404D134AB84C0035F004F005F0AC00"
def _cycle_desc():
return next(
e for e in washer.WASHER_COURSE.entities if e.key == "cycle" and isinstance(e, SelectDesc)
)
def _rep(options, cloud=None):
rep = {"x.com.samsung.da.options": list(options)}
if cloud is not None:
rep[cloudcourse.FIELD] = cloud
return rep
class TestBlobParsing:
def test_slot_is_byte_two(self):
"""Confirmed against every program in both dumps: byte 2 of a blob
is the slot id its own CloudExtraCourse_ token advertises."""
assert cloudcourse.slot_of(SPORTS) == "55"
assert cloudcourse.slot_of(JEANS) == "6B"
assert cloudcourse.slot_of(TOWELS) == "0A"
def test_ffff_prefix_is_not_a_program(self):
"""WA55A7700AV reports this while sitting on a local course -- it
means 'no one-time override', not a program, and its byte 2 is not
one of the slots that device advertises."""
sentinel = "FFFF010049004D004A804C0037F0AC00"
assert cloudcourse.is_loaded(sentinel) is False
assert cloudcourse.slot_of(sentinel) is None
@pytest.mark.parametrize(
"bad",
[None, "", "zz", "0021", "0021550449284D134AA04C0035F004F005F0AC0"],
)
def test_malformed_blobs_yield_no_slot(self, bad):
assert cloudcourse.slot_of(bad) is None
def test_advertised_slots_preserve_device_order(self):
rep = _rep(["CloudExtraCourse_0A5C286B2D0C55301A"])
assert cloudcourse.advertised_slots(rep) == [
"0A",
"5C",
"28",
"6B",
"2D",
"0C",
"55",
"30",
"1A",
]
def test_no_cloud_tokens_means_unsupported(self):
assert cloudcourse.supports_cloud_courses(_rep(["Course_1C"])) is False
class TestRealDumps:
def test_reporter_dump_advertises_nine_and_learns_both_loaded_blobs(self):
"""One poll teaches two programs: the saved default and the loaded
one-time override are different programs on this dump."""
rep = _load_device("washer_ww5000c_cloud")["/course/vs/0"]
assert len(cloudcourse.advertised_slots(rep)) == 9
store = cloudcourse.CloudCourses()
assert store.observe(rep) is True
assert store.blob("55") == SPORTS
assert store.blob("6B") == JEANS
# Learned but unnamed -- nothing is offerable yet.
assert store.named() == {}
assert store.view() == {}
def test_reporter_dump_proposes_its_download_course(self):
rep = _load_device("washer_ww5000c_cloud")["/course/vs/0"]
store = cloudcourse.CloudCourses()
store.observe(rep)
assert store.download_candidates() == ["87"]
# A candidate is never used until confirmed.
assert store.download_course() is None
def test_wa55_learns_its_saved_program_but_not_the_sentinel(self):
rep = _load_device("washer_wa55a7700av")["/course/vs/0"]
assert cloudcourse.advertised_slots(rep) == ["59", "58"]
store = cloudcourse.CloudCourses()
store.observe(rep)
assert store.blob("59") == "001C590549164D114A224C2037F0AC22"
assert store.blob("01") is None # the FFFF sentinel's byte 2
def test_wa55_proposes_no_download_course(self):
"""It is sitting on an ordinary local course with no override
loaded, so there is nothing to infer -- exactly the case where
guessing a code would start the wrong cycle."""
rep = _load_device("washer_wa55a7700av")["/course/vs/0"]
store = cloudcourse.CloudCourses()
store.observe(rep)
assert store.download_candidates() == []
def test_undiscovered_counts_against_what_the_device_advertises(self):
rep = _load_device("washer_ww5000c_cloud")["/course/vs/0"]
store = cloudcourse.CloudCourses()
store.observe(rep)
# Both learned slots are still unnamed, so all nine are outstanding.
assert len(cloudcourse.undiscovered(rep, store.snapshot())) == 9
store.set_name("55", "Sports")
assert "55" not in cloudcourse.undiscovered(rep, store.snapshot())
assert len(cloudcourse.undiscovered(rep, store.snapshot())) == 8
class TestStoreRules:
def test_only_advertised_slots_are_recorded(self):
"""A blob for a slot this appliance doesn't list isn't a program it
offers."""
store = cloudcourse.CloudCourses()
store.observe(_rep(["CloudExtraCourse_55", f"OneTimeCloudCourse_{JEANS}"]))
assert store.blob("6B") is None
def test_a_relearned_blob_replaces_the_old_payload(self):
store = cloudcourse.CloudCourses()
store.observe(_rep(["CloudExtraCourse_55", f"CloudCourse_{SPORTS}"]))
rewritten = SPORTS.replace("F005F0AC00", "F005F0AC11")
assert store.observe(_rep(["CloudExtraCourse_55", f"CloudCourse_{rewritten}"])) is True
assert store.blob("55") == rewritten
def test_observing_the_same_rep_twice_changes_nothing(self):
store = cloudcourse.CloudCourses()
rep = _rep(["CloudExtraCourse_55", f"CloudCourse_{SPORTS}"])
assert store.observe(rep) is True
assert store.observe(rep) is False
def test_view_is_empty_until_a_download_course_is_confirmed(self):
"""Both halves are required: without the course code there is no
write to build, so nothing should reach the select."""
store = cloudcourse.CloudCourses()
store.observe(_rep(["CloudExtraCourse_55", f"CloudCourse_{SPORTS}"]))
store.set_name("55", "Sports")
assert store.view() == {}
store.set_download_course("87")
assert store.view()["programs"] == {"55": {"blob": SPORTS, "name": "Sports"}}
def test_round_trips_through_the_entry(self):
store = cloudcourse.CloudCourses()
store.observe(_rep(["CloudExtraCourse_55", f"CloudCourse_{SPORTS}"]))
store.set_name("55", "Sports")
store.set_download_course("87")
restored = cloudcourse.CloudCourses(store.snapshot())
assert restored.snapshot() == store.snapshot()
assert restored.view() == store.view()
@pytest.mark.parametrize(
"junk",
[
"not a dict",
{"slots": "nope"},
{"slots": {"55": {"blob": "garbage", "name": "Sports"}}},
# blob's own byte 2 disagrees with the key it is filed under
{"slots": {"99": {"blob": SPORTS, "name": "Sports"}}},
],
)
def test_a_hand_edited_entry_cannot_crash_setup(self, junk):
assert cloudcourse.CloudCourses(junk).snapshot()["slots"] == {}
class TestCycleSelectIntegration:
"""The cloud programs ride in the ordinary cycle select -- on the
appliance's dial, Download is one course among the rest."""
def _cloud(self):
return {
"download_course": "87",
"programs": {"55": {"blob": SPORTS, "name": "Sports"}},
}
def test_local_courses_are_unchanged_without_cloud_data(self):
desc = _cycle_desc()
live = {"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_1C1D"}}
assert desc.options(live) == ["1C", "1D"]
def test_named_programs_join_the_option_list_after_local_courses(self):
desc = _cycle_desc()
live = {
"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_1C87"},
"/course/vs/0": _rep(["Course_87"], self._cloud()),
}
assert desc.options(live) == ["1C", "87", "cloud:55"]
def test_an_unnamed_program_is_never_offered(self):
desc = _cycle_desc()
live = {
"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_1C"},
"/course/vs/0": _rep(
["Course_87"],
{"download_course": "87", "programs": {}},
),
}
assert desc.options(live) == ["1C"]
def test_label_is_the_users_own_name(self):
desc = _cycle_desc()
resources = {"/course/vs/0": _rep(["Course_87"], self._cloud())}
assert desc.display_fn("cloud:55", resources) == "Sports"
def test_unknown_cloud_value_gets_no_invented_label(self):
desc = _cycle_desc()
resources = {"/course/vs/0": _rep(["Course_87"], self._cloud())}
assert desc.display_fn("cloud:99", resources) is None
def test_state_reports_the_loaded_program_while_on_download(self):
desc = _cycle_desc()
rep = _rep(["Course_87", f"OneTimeCloudCourse_{SPORTS}"], self._cloud())
assert desc.rep_fn(rep) == "cloud:55"
def test_state_falls_back_to_the_saved_program(self):
"""No one-time override loaded: the appliance runs the saved default,
which the reporter confirmed by leaving Download and returning."""
desc = _cycle_desc()
rep = _rep(
["Course_87", f"CloudCourse_{SPORTS}", "OneTimeCloudCourse_FFFF010049004D004A804C00"],
self._cloud(),
)
assert desc.rep_fn(rep) == "cloud:55"
def test_a_stale_program_token_is_not_reported_on_a_local_course(self):
"""Tokens are replaced by prefix and never evicted, so a one-time
program outlives its run. Reporting 'Sports' while a cotton cycle
runs would be a live lie about what the machine is doing."""
desc = _cycle_desc()
rep = _rep(["Course_1C", f"OneTimeCloudCourse_{SPORTS}"], self._cloud())
assert desc.rep_fn(rep) == "1C"
def test_selecting_a_program_switches_course_and_loads_it_in_one_write(self):
"""Confirmed on hardware: writing the program token alone while
another course is selected is silently ignored."""
desc = _cycle_desc()
rep = _rep(["Course_1C"], self._cloud())
path, body = desc.write_fn("cloud:55", rep)
assert path == ["course", "vs", "0"]
assert body == {"x.com.samsung.da.options": ["Course_87", f"OneTimeCloudCourse_{SPORTS}"]}
def test_selecting_a_local_course_still_writes_one_token(self):
desc = _cycle_desc()
rep = _rep(["Course_87"], self._cloud())
_, body = desc.write_fn("1C", rep)
assert body == {"x.com.samsung.da.options": ["Course_1C"]}
def test_no_write_without_a_confirmed_download_course(self):
desc = _cycle_desc()
rep = _rep(["Course_1C"], {"programs": {"55": {"blob": SPORTS, "name": "Sports"}}})
assert desc.write_fn("cloud:55", rep) is None
def test_no_write_for_an_unknown_program(self):
desc = _cycle_desc()
rep = _rep(["Course_1C"], self._cloud())
assert desc.write_fn("cloud:99", rep) is None
class TestOptionsMergePreservesSiblingTokens:
def test_two_token_write_merges_like_the_device_does(self):
"""The write carries only the changed tokens; merge_options_field is
what keeps the optimistic cache entry complete during the settle
window. Both tokens must land, and unrelated ones must survive."""
from custom_components.localthings.registry.capabilities.common import merge_options_field
cached = [
"DeviceType_0167",
"Course_1C",
f"CloudCourse_{SPORTS}",
"CloudExtraCourse_0A5C286B2D0C55301A",
f"OneTimeCloudCourse_{TOWELS}",
"GMT_04",
]
merged = merge_options_field(cached, ["Course_87", f"OneTimeCloudCourse_{SPORTS}"])
assert "Course_87" in merged
assert f"OneTimeCloudCourse_{SPORTS}" in merged
# The saved default and the device's own slot list are untouched.
assert f"CloudCourse_{SPORTS}" in merged
assert "CloudExtraCourse_0A5C286B2D0C55301A" in merged
assert "DeviceType_0167" in merged
def test_cloud_prefixes_do_not_poison_the_course_lookup(self):
"""'Course_' is a prefix of neither 'CloudCourse_' nor
'OneTimeCloudCourse_' only because option_value anchors at position
0 -- one character away from being wrong, so it is pinned."""
options = [f"CloudCourse_{SPORTS}", f"OneTimeCloudCourse_{JEANS}", "Course_1C"]
assert laundry.option_value(options, "Course") == "1C"
assert cloudcourse.option_value(options, "Course") == "1C"
+322
View File
@@ -0,0 +1,322 @@
"""End-to-end wiring for cloud "Download" cycles (issue #342).
The store's own rules are covered in test_cloud_courses.py. This file covers
the parts that only exist once a coordinator is running: learning from an
applied rep, persisting to the config entry, surfacing the store to entity
descriptors through the synthetic field, the Repairs nudge, and the options
flow that supplies the names.
"""
from __future__ import annotations
import asyncio
from typing import Any, cast
import cbor2
from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry as ir
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.localthings import cloudcourse
from custom_components.localthings.const import CONF_CLOUD_COURSES, DOMAIN
from custom_components.localthings.coordinator import LocalThingsCoordinator
from custom_components.localthings.registry.entities import SelectDesc
from tests.conftest import _load_device
from tests.test_subdevice_discovery import ENTRY_DATA
FIXTURE = "washer_ww5000c_cloud"
COURSE = cloudcourse.COURSE_HREF
SPORTS = "0021550449284D134AA04C0035F004F005F0AC00"
JEANS = "001F6B0449284D134AA04C0035F004F005F0AC00"
async def _flush(hass: HomeAssistant) -> None:
"""hass.add_job hops used by the persist path."""
for _ in range(3):
await asyncio.sleep(0)
await hass.async_block_till_done()
def _entry(hass: HomeAssistant, data=None) -> MockConfigEntry:
entry = MockConfigEntry(
domain=DOMAIN,
data={**ENTRY_DATA, **(data or {})},
unique_id="localthings_CLOUD-COURSE-TEST",
)
entry.add_to_hass(hass)
return entry
async def _coordinator(hass: HomeAssistant, entry=None) -> LocalThingsCoordinator:
coordinator = LocalThingsCoordinator(hass, entry or _entry(hass))
resources = _load_device(FIXTURE)
coordinator._run_discovery(resources)
for href, rep in resources.items():
coordinator._observe.apply(href, rep, source="poll")
await _flush(hass)
return coordinator
def _cycle_state(coordinator: LocalThingsCoordinator):
from custom_components.localthings.registry.adapter import flatten
return flatten(coordinator.bound, coordinator.entity_resources()).get("cycle")
def _cycle_desc(coordinator: LocalThingsCoordinator) -> SelectDesc:
return cast(SelectDesc, next(b.desc for b in coordinator.bound if b.desc.key == "cycle"))
def _cycle_options(coordinator: LocalThingsCoordinator):
from custom_components.localthings.registry.subdevices import MAIN
return _cycle_desc(coordinator).options(coordinator.canonical_resources(MAIN))
async def test_a_poll_learns_and_persists_the_loaded_programs(hass: HomeAssistant):
entry = _entry(hass)
coordinator = await _coordinator(hass, entry)
assert coordinator.cloud_courses.blob("55") == SPORTS
assert coordinator.cloud_courses.blob("6B") == JEANS
# Survives a restart -- the payload is only visible while loaded.
assert entry.data[CONF_CLOUD_COURSES]["slots"]["55"]["blob"] == SPORTS
async def test_an_optimistic_write_teaches_nothing(hass: HomeAssistant):
"""An optimistic rep is what this integration just wrote, not what the
appliance reported."""
coordinator = LocalThingsCoordinator(hass, _entry(hass))
coordinator._observe.apply(
COURSE,
{"x.com.samsung.da.options": ["CloudExtraCourse_55", f"CloudCourse_{SPORTS}"]},
source="optimistic",
)
await _flush(hass)
assert coordinator.cloud_courses.blob("55") is None
async def test_learned_but_unnamed_programs_stay_out_of_the_cycle_select(hass: HomeAssistant):
coordinator = await _coordinator(hass)
options = _cycle_options(coordinator)
assert all(not o.startswith(cloudcourse.RAW_PREFIX) for o in options)
# The local courses are untouched.
assert "87" in options
async def test_naming_a_program_puts_it_in_the_cycle_select(hass: HomeAssistant):
coordinator = await _coordinator(hass)
coordinator.set_cloud_download_course("87")
coordinator.set_cloud_course_name("55", "Sports")
await _flush(hass)
assert "cloud:55" in _cycle_options(coordinator)
# The fixture is sitting on Download with a Jeans one-time override, and
# Jeans is still unnamed -- so the state falls through to the raw course.
assert _cycle_state(coordinator) == "87"
coordinator.set_cloud_course_name("6B", "Jeans")
await _flush(hass)
assert _cycle_state(coordinator) == "cloud:6B"
async def test_the_synthetic_field_never_reaches_the_device_snapshot(hass: HomeAssistant):
"""It is merged at read time only: last_resources stays exactly what the
appliance reported, so it can't be polled over, written back, or land in
a diagnostics dump."""
coordinator = await _coordinator(hass)
coordinator.set_cloud_download_course("87")
coordinator.set_cloud_course_name("55", "Sports")
await _flush(hass)
assert cloudcourse.FIELD in coordinator.entity_resources()[COURSE]
assert cloudcourse.FIELD not in coordinator.last_resources[COURSE]
assert cloudcourse.FIELD not in coordinator.resource(COURSE)
async def test_selecting_a_named_program_writes_both_tokens(hass: HomeAssistant):
"""Driven through async_send_command rather than write_fn directly: the
command path builds its own rep, and a rep taken straight off the state
cache carries no cloud programs, so the write would silently no-op."""
coordinator = await _coordinator(hass)
coordinator.set_cloud_download_course("87")
coordinator.set_cloud_course_name("55", "Sports")
await _flush(hass)
sent: list[tuple[list[str], bytes]] = []
class _FakeSession:
def post(self, path_segs, payload, timeout=None):
sent.append((path_segs, payload))
return 0x44, b""
coordinator._session = cast(Any, _FakeSession())
bound = next(b for b in coordinator.bound if b.desc.key == "cycle")
await coordinator.async_send_command(bound, "cloud:55")
assert len(sent) == 1
path_segs, payload = sent[0]
assert path_segs == ["course", "vs", "0"]
assert cbor2.loads(payload)["x.com.samsung.da.options"] == [
"Course_87",
f"OneTimeCloudCourse_{SPORTS}",
]
# The optimistic merge keeps the rest of the array intact for the settle
# window -- including the device's own slot list and the saved default.
merged = coordinator.resource(COURSE)["x.com.samsung.da.options"]
assert "Course_87" in merged
assert f"OneTimeCloudCourse_{SPORTS}" in merged
assert "CloudExtraCourse_0A5C286B2D0C55301A" in merged
async def test_a_repair_is_raised_until_every_program_is_named(hass: HomeAssistant):
entry = _entry(hass)
coordinator = await _coordinator(hass, entry)
coordinator._refresh_cloud_course_issue()
await _flush(hass)
registry = ir.async_get(hass)
issue_id = f"cloud_courses_{entry.entry_id}"
issue = registry.async_get_issue(DOMAIN, issue_id)
assert issue is not None
assert (issue.translation_placeholders or {})["total"] == "9"
coordinator.set_cloud_download_course("87")
for slot in cloudcourse.advertised_slots(coordinator.cloud_course_rep()):
# Only two are learned; name every advertised slot to close the gap.
coordinator.cloud_courses.observe(
{
"x.com.samsung.da.options": [
"CloudExtraCourse_0A5C286B2D0C55301A",
f"CloudCourse_0000{slot}0449284D134AA04C0035F004F005F0AC00",
]
}
)
coordinator.set_cloud_course_name(slot, f"Program {slot}")
await _flush(hass)
assert registry.async_get_issue(DOMAIN, issue_id) is None
async def test_no_repair_for_a_device_without_downloaded_programs(hass: HomeAssistant):
entry = _entry(hass)
coordinator = LocalThingsCoordinator(hass, entry)
resources = _load_device("washer")
coordinator._run_discovery(resources)
for href, rep in resources.items():
coordinator._observe.apply(href, rep, source="poll")
coordinator._refresh_cloud_course_issue()
await _flush(hass)
registry = ir.async_get(hass)
assert registry.async_get_issue(DOMAIN, f"cloud_courses_{entry.entry_id}") is None
async def test_a_malformed_entry_record_does_not_block_setup(hass: HomeAssistant):
entry = _entry(hass, data={CONF_CLOUD_COURSES: {"slots": {"55": {"blob": "junk"}}}})
coordinator = await _coordinator(hass, entry)
# Dropped on restore, then relearned from the live poll.
assert coordinator.cloud_courses.blob("55") == SPORTS
# ---------------------------------------------------------------------------
# Options flow
# ---------------------------------------------------------------------------
async def _options_handler(hass: HomeAssistant, coordinator: LocalThingsCoordinator):
from custom_components.localthings.config_flow import LocalThingsOptionsFlow
entry = coordinator.config_entry
assert entry is not None
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
handler = LocalThingsOptionsFlow()
handler.hass = hass
# OptionsFlow.config_entry resolves through `handler`, which the flow
# manager normally sets when it starts the flow.
handler.handler = entry.entry_id
return handler
async def test_the_menu_offers_download_cycles_only_when_the_device_has_them(
hass: HomeAssistant,
):
coordinator = await _coordinator(hass)
handler = await _options_handler(hass, coordinator)
result = await handler.async_step_init()
assert "cloud_courses" in result["menu_options"]
async def test_naming_through_the_flow_persists(hass: HomeAssistant):
entry = _entry(hass)
coordinator = await _coordinator(hass, entry)
handler = await _options_handler(hass, coordinator)
await handler.async_step_cloud_courses()
await handler.async_step_cloud_courses(
{"name_55": "Sports", "name_6B": "Jeans", "download_course": "87"}
)
await _flush(hass)
assert coordinator.cloud_courses.named() == {"55": "Sports", "6B": "Jeans"}
assert entry.data[CONF_CLOUD_COURSES]["download_course"] == "87"
async def test_the_flow_rejects_two_programs_sharing_a_name(hass: HomeAssistant):
coordinator = await _coordinator(hass)
handler = await _options_handler(hass, coordinator)
result = await handler.async_step_cloud_courses(
{"name_55": "Sports", "name_6B": "sports", "download_course": "87"}
)
assert result["errors"] == {"base": "cloud_course_name_duplicate"}
assert coordinator.cloud_courses.named() == {}
async def test_the_flow_rejects_a_name_that_shadows_a_local_course(hass: HomeAssistant):
"""'Drum Clean' is course 74 on this appliance's own list. Two options
rendering the same label would resolve to whichever comes first."""
coordinator = await _coordinator(hass)
handler = await _options_handler(hass, coordinator)
result = await handler.async_step_cloud_courses(
{"name_55": "Drum Clean", "download_course": "87"}
)
assert result["errors"] == {"base": "cloud_course_name_duplicate"}
assert coordinator.cloud_courses.named() == {}
async def test_clearing_a_name_removes_the_program_from_the_select(hass: HomeAssistant):
coordinator = await _coordinator(hass)
handler = await _options_handler(hass, coordinator)
await handler.async_step_cloud_courses({"name_55": "Sports", "download_course": "87"})
await _flush(hass)
assert "cloud:55" in _cycle_options(coordinator)
await handler.async_step_cloud_courses({"name_55": "", "download_course": "87"})
await _flush(hass)
assert "cloud:55" not in _cycle_options(coordinator)
async def test_without_a_confirmed_download_course_nothing_is_offered(hass: HomeAssistant):
"""Names alone aren't enough -- there'd be no course code to write."""
coordinator = await _coordinator(hass)
handler = await _options_handler(hass, coordinator)
await handler.async_step_cloud_courses({"name_55": "Sports", "download_course": ""})
await _flush(hass)
assert coordinator.cloud_courses.named() == {"55": "Sports"}
assert "cloud:55" not in _cycle_options(coordinator)
async def test_the_form_proposes_the_observed_download_course(hass: HomeAssistant):
coordinator = await _coordinator(hass)
handler = await _options_handler(hass, coordinator)
result = await handler.async_step_cloud_courses()
assert result["step_id"] == "cloud_courses"
assert result["description_placeholders"]["total"] == "9"
# Two learned so far, seven still to walk through on the appliance.
assert result["description_placeholders"]["found"] == "2"
assert coordinator.cloud_courses.download_candidates() == ["87"]
+3 -2
View File
@@ -5,7 +5,7 @@ cycle_options, cycle_write) is tested in test_laundry_capabilities.py; here we
check the dishwasher wiring and its device-specific options.
"""
from custom_components.localthings.registry.capabilities import dishwasher, laundry
from custom_components.localthings.registry.capabilities import dishwasher
from custom_components.localthings.registry.entities import SwitchDesc
@@ -15,7 +15,8 @@ class TestCycleOptions:
def test_cycle_desc_uses_shared_cycle_options(self):
desc = self._cycle()
assert desc.options is laundry.cycle_options
live = {"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_0E82"}}
assert desc.options(live) == ["0E", "82"]
assert desc.translation_key == "dishwasher_cycle"
def test_exists_only_when_edit_course_list_is_live(self):
+3 -2
View File
@@ -2,7 +2,7 @@
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 import dryer, ignored, laundry
from custom_components.localthings.registry.capabilities import dryer, ignored
from custom_components.localthings.registry.discovery import discover
from custom_components.localthings.registry.entities import SelectDesc
from tests.conftest import _load_device
@@ -82,7 +82,8 @@ def test_course_bound_to_shared_course_vs_0():
table_03 = {"/st/dryercourse/vs/0": {"x.com.samsung.da.st.courseTable": "Table_03"}}
assert desc.translation_key(table_03) == "dryer_cycle_table_03"
assert desc.translation_key({}) == "cycle"
assert desc.options is laundry.cycle_options
live = {"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_1620"}}
assert desc.options(live) == ["16", "20"]
rep = {"x.com.samsung.da.options": ["Course_16", "GMT_02"]}
assert desc.rep_fn is not None
assert desc.rep_fn(rep) == "16"
+23
View File
@@ -1496,3 +1496,26 @@ def test_resources_from_batch_preferred_over_flat():
}
result = _resources_from_dump(dump)
assert result == {"/foo": {"x": 1}}
def test_registry_reproduces_golden_state_keys_for_washer_ww5000c_cloud():
"""The issue #342 reporter's WW5000C (DA_WM_TP1_21_COMMON, Table_02),
captured while sitting on its Download course with a one-time Jeans
program loaded over a saved Sports default.
The cloud "Download" programs it advertises add no entity of their own
-- they ride in the existing cycle select -- so this golden is the guard
that discovering them never grows the entity set.
Its /wm/editcourse/vs/0 is empty, so its course list comes from the
supportedOptions fallback (issue #1)."""
from tests.conftest import _load_device
resources = _load_device("washer_ww5000c_cloud")
golden = json.loads((GOLDEN / "washer_ww5000c_cloud.json").read_text())
state_keys = _new_state_keys("washer_ww5000c_cloud", 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))}"
)
+4 -1
View File
@@ -233,7 +233,10 @@ class TestCycleSelect:
assert desc.key == "cycle"
assert desc.translation_key == "dryer_cycle"
assert desc.icon == "mdi:tumble-dryer"
assert desc.options is laundry.cycle_options
# Behavior, not identity: the option list is the device's own live
# course list (plus any named cloud programs -- see cycle_select).
live = {"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_161C"}}
assert desc.options(live) == ["16", "1C"]
def test_reads_raw_course_code_from_options(self):
desc = laundry.cycle_select(translation_key="dryer_cycle", icon="x")
+15 -3
View File
@@ -7,7 +7,7 @@ fallback pairs and the energy meter in test_common_capabilities.py.
from datetime import UTC
from custom_components.localthings.registry.capabilities import laundry, washer
from custom_components.localthings.registry.capabilities import washer
from custom_components.localthings.registry.entities import SelectDesc
@@ -157,8 +157,20 @@ class TestWasherCourse:
for e in washer.WASHER_COURSE.entities
if e.key == "cycle" and isinstance(e, SelectDesc)
)
assert desc.options is laundry.cycle_options
assert desc.display_fn is laundry.washer_cycle_fallback
# Behavior, not identity: cycle_select wraps both hooks to fold in
# cloud "Download" programs (issue #342), so the plain functions are
# no longer handed through as-is.
live = {"/wm/editcourse/vs/0": {"x.com.samsung.da.editCourseList": "EditCourseList_1C1D"}}
assert desc.options(live) == ["1C", "1D"]
# display_fn still resolves a personal course name through
# washer_cycle_fallback for a non-cloud value.
assert desc.display_fn is not None
personal = {
"/wm/personalcourse/vs/0": {
"x.com.samsung.da.courses": ["A1_01044D79436F"],
}
}
assert desc.display_fn("A1", personal) == "MyCo"
def test_exists_only_when_edit_course_list_is_live(self):
"""No hardcoded course table is kept -- the selector only appears