Merge main into ac-additive-entities, resolve conflicts with #146

Both PRs independently modeled the same /mode/vs/0 Volume_*/Sleep_*
option tokens: #129 as beep/tropical_night_mode, #146 (already merged)
as buzzer_volume/good_sleep gated to the legacy ARTIK051 board
generation. They also each defined a helper named _option_token with
different return semantics (full token vs. value half) in
non-overlapping parts of the file, so git didn't flag it as a
conflict even though the second definition silently shadowed the
first.

Keep a single _option_token (value-half, the one already used by
buzzer_volume/good_sleep/spi/etc.), adjust beep's read/write to that
convention, and gate beep/tropical_night_mode off the legacy board so
they don't duplicate buzzer_volume/good_sleep on ARTIK051_KRAC-class
devices. Added a regression test locking in the gate.
This commit is contained in:
Marc Billow committed 2026-07-28 13:28:20 +00:00
commit 00c1d78373
52 files changed
+3286 -170

No files matched your search

@@ -0,0 +1,232 @@
{
"device0": [
{
"rt": [
"x.com.samsung.devcol",
"oic.wk.col"
],
"if": [
"oic.if.baseline",
"oic.if.ll",
"oic.if.b"
]
},
{
"href": "/airflow/0",
"rep": {
"speed": 3,
"direction": "Fix"
}
},
{
"href": "/airflow/vs/0",
"rep": {
"x.com.samsung.da.speedLevel": "3",
"x.com.samsung.da.direction": "Fix"
}
},
{
"href": "/alarms/vs/0",
"rep": {
"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": "ErrorCode_OFF",
"x.com.samsung.da.triggeredTime": "2026-07-28T00:18:15",
"x.com.samsung.da.state": "Deleted"
},
{
"x.com.samsung.da.id": "1",
"x.com.samsung.da.description": "Alarm",
"x.com.samsung.da.alarmType": "Device",
"x.com.samsung.da.code": "FilterAlarm_OFF",
"x.com.samsung.da.triggeredTime": "2026-07-28T00:18:15",
"x.com.samsung.da.state": "Deleted"
}
]
}
},
{
"href": "/configuration/vs/0",
"rep": {
"x.com.samsung.da.region": "0000000000"
}
},
{
"href": "/diagnosis/vs/0",
"rep": {
"x.com.samsung.da.diagnosisStart": "Ready"
}
},
{
"href": "/energy/consumption/0",
"rep": {}
},
{
"href": "/energy/consumption/vs/0",
"rep": {
"x.com.samsung.da.cumulativePower": "0"
}
},
{
"href": "/file/information/vs/0",
"rep": {
"x.com.samsung.timeoffset": "+01:00",
"x.com.samsung.supprtedtype": 1
}
},
{
"href": "/humidity/0",
"rep": {
"humidity": 0
}
},
{
"href": "/humidity/vs/0",
"rep": {
"x.com.samsung.da.humidity": "0"
}
},
{
"href": "/information/vs/0",
"rep": {
"x.com.samsung.da.modelNum": "ARTIK051_KRAC_18K|10193441|60010119001111110200000000000000",
"x.com.samsung.da.description": "ARTIK051_KRAC_18K",
"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": "02016A200825",
"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": "18020800,17120500",
"x.com.samsung.da.newVersionAvailable": "0"
}
]
}
},
{
"href": "/mode/0",
"rep": {
"supportedModes": [
"Cool",
"Dry",
"Wind",
"Auto",
"Heat",
"HOMECARE_WIZARD_V2"
],
"modes": [
"Cool"
]
}
},
{
"href": "/mode/vs/0",
"rep": {
"x.com.samsung.da.supportedModes": [
"Cool",
"Dry",
"Wind",
"Auto",
"Heat",
"HOMECARE_WIZARD_V2"
],
"x.com.samsung.da.modes": [
"Cool"
],
"x.com.samsung.da.options": [
"Comode_Off",
"Sleep_0",
"OutdoorTemp_74",
"CoolCapa_25",
"WarmCapa_32",
"Spi_Off",
"Autoclean_Off",
"Light_Off",
"Volume_100",
"AirMonitoring_Off",
"AutocleanProgress_1",
"StopAutoClean_Idle",
"FilterTime_1715",
"FilterAlarmTime_500",
"OptionCode_35882",
"ExtendOptionCode_7",
"RacInfo_None",
"UpdateAllow_NotAllowed"
]
}
},
{
"href": "/personality/presence/vs/0",
"rep": {
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "",
"x.com.samsung.da.deviceId": "**REDACTED**",
"x.com.samsung.da.value": ""
}
]
}
},
{
"href": "/power/0",
"rep": {
"value": false
}
},
{
"href": "/power/vs/0",
"rep": {
"x.com.samsung.da.power": "Off"
}
},
{
"href": "/temperature/current/0",
"rep": {
"range": [
16.0,
30.0
],
"units": "C",
"temperature": 21.0
}
},
{
"href": "/temperature/desired/0",
"rep": {
"range": [
16.0,
30.0
],
"units": "C",
"temperature": 20.0
}
},
{
"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": "20",
"x.com.samsung.da.current": "21",
"x.com.samsung.da.maximum": "30",
"x.com.samsung.da.minimum": "16",
"x.com.samsung.da.unit": "Celsius"
}
]
}
}
]
}
+1 -7
View File
@@ -1,24 +1,18 @@
{
"state_keys": [
"airflow_fan",
"alarm_code",
"clean_level",
"device_active",
"diagnosis_status",
"display_light",
"dust",
"energy_kwh",
"energy_last_month_kwh",
"energy_saved_kwh",
"energy_this_month_kwh",
"fan_direction",
"fan_speed_level",
"filter_progress",
"fine_dust",
"odor",
"operating_mode",
"power_energy_kwh",
"power_switch",
"power_watts",
"super_fine_dust"
]
}
@@ -0,0 +1,18 @@
{
"state_keys": [
"air_monitoring",
"alarm_code",
"auto_clean_legacy",
"buzzer_volume",
"climate",
"current_temperature_c",
"diagnosis_status",
"display_light",
"energy_kwh",
"filter_time",
"good_sleep",
"humidity",
"outdoor_temperature",
"spi"
]
}
+22
View File
@@ -0,0 +1,22 @@
{
"state_keys": [
"alarm_code",
"cavity_state",
"child_lock",
"cloud_connected",
"cook_time",
"cooking_mode",
"cycle_active",
"door_open",
"energy_kwh",
"fan",
"finish_time",
"firmware_update",
"lamp",
"machine_state",
"operation_time_minutes",
"power_level",
"progress_percentage",
"sound"
]
}
@@ -1,25 +1,23 @@
{
"state_keys": [
"alarm_code",
"cavity_state",
"child_lock",
"cloud_connected",
"cook_time",
"cooking_mode",
"current_temp_c",
"cycle_active",
"door_open",
"energy_kwh",
"fast_preheat",
"finish_time",
"firmware_update",
"lamp",
"machine_state",
"natural_steam",
"operation_time_minutes",
"oven_mode",
"oven_setpoint",
"oven_state",
"power_level",
"progress_percentage",
"remote_control",
"setpoint",
"sound"
]
}
}
+2
View File
@@ -1,5 +1,7 @@
{
"state_keys": [
"after_run_active",
"after_run_progress",
"air_sensing_state",
"alarm_code",
"auto_ventilation_action",
@@ -5,16 +5,10 @@
"defrost_delay",
"diagnosis_status",
"door_onedoorfreezer_open",
"energy_kwh",
"energy_last_month_kwh",
"energy_saved_kwh",
"energy_this_month_kwh",
"firmware_update",
"freezer_setpoint",
"freezer_temperature",
"ice_maker_enabled",
"power_energy_kwh",
"power_watts",
"rapid_freezing",
"rapid_fridge",
"sabbath_mode"
@@ -8,14 +8,8 @@
"diagnosis_status",
"door_cooler_open",
"door_onedoorfreezer_open",
"energy_kwh",
"energy_last_month_kwh",
"energy_saved_kwh",
"energy_this_month_kwh",
"firmware_update",
"ice_maker_enabled",
"power_energy_kwh",
"power_watts",
"rapid_freezing",
"rapid_fridge",
"sabbath_mode"
@@ -0,0 +1,24 @@
{
"state_keys": [
"alarm_code",
"bottom_mode",
"bottom_rack_count",
"bottom_ripening_remaining",
"bottom_ripening_status",
"diagnosis_status",
"door_open",
"energy_kwh",
"firmware_update",
"middle_mode",
"middle_rack_count",
"middle_ripening_remaining",
"middle_ripening_status",
"power_energy_kwh",
"power_watts",
"top_mode",
"top_open",
"top_rack_count",
"top_ripening_remaining",
"top_ripening_status"
]
}
-1
View File
@@ -9,7 +9,6 @@
"favorite_capacity",
"favorite_capacity_enabled",
"favorite_coffee_enabled",
"favorite_hotwater_enabled",
"favorite_hotwater_temperature",
"filter_clean_remain_time",
"filter_door_status",
+201
View File
@@ -0,0 +1,201 @@
{
"device0": [
{
"rt": ["x.com.samsung.devcol", "oic.wk.col"],
"if": ["oic.if.baseline", "oic.if.ll", "oic.if.b"]
},
{
"href": "/otninformation/vs/0",
"rep": {
"x.com.samsung.da.target": "",
"x.com.samsung.da.newVersionAvailable": "false",
"flashingProgress": "",
"otnStatus": "None",
"otnList": [
{
"type": "WIFI",
"modelId": "AKS-WW-TP1-23-MICROWAVE-OTR",
"versions": ["40241114"],
"visVersion": "241114"
},
{
"type": "Micom",
"modelId": "07424047334140473241",
"versions": ["24071000", "23120700"],
"visVersion": "240710"
},
{
"type": "Micom",
"modelId": "074240475443FFFFFFFF",
"versions": ["23120800", "FFFFFFFF"],
"visVersion": "231208"
}
]
}
},
{
"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": "/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"
}
],
"rt": ["x.com.samsung.da.doors"],
"if": ["oic.if.baseline", "oic.if.s"]
}
},
{
"href": "/information/vs/0",
"rep": {
"x.com.samsung.da.modelNum": "TP1X_DA-KS-MICROWAVE-01051|40473341|50040000011811000A00000000000000",
"x.com.samsung.da.description": "ME7500D-/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": "24111400",
"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": "04733A24071000, 04732A23120700",
"x.com.samsung.da.newVersionAvailable": "0"
},
{
"x.com.samsung.da.id": "2",
"x.com.samsung.da.description": "Version",
"x.com.samsung.da.type": "Firmware",
"x.com.samsung.da.number": "04754C23120800",
"x.com.samsung.da.newVersionAvailable": "0"
}
],
"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": "KM5",
"x.com.samsung.da.diagMinVersion": "3.0",
"x.com.samsung.da.diagTsId": "DA01"
}
},
{
"href": "/mode/vs/0",
"rep": {
"x.com.samsung.da.supportedModes": ["NoOperation", "MicroWave", "Autocook", "KeepWarm"],
"x.com.samsung.da.modes": ["NoOperation"],
"x.com.samsung.da.options": [
"DeviceType_ME7500D-/AA1",
"TimeAutoSync_On",
"weight_LBS",
"TimeSystem_12",
"Sound_On",
"RemindBeep_On",
"FilterRemind_Off",
"Lamp_Off"
],
"x.com.samsung.da.defaultMode": "MicroWave",
"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": "0",
"rt": ["x.com.samsung.da.operation"],
"if": ["oic.if.baseline", "oic.if.a"]
}
},
{
"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-07-27T20:03:10"
}
]
}
},
{
"href": "/oven/vs/0",
"rep": {
"x.com.samsung.da.state": "Ready",
"x.com.samsung.da.recipe": "00000000000000",
"x.com.samsung.da.powerLevel": "0",
"rt": ["x.com.samsung.da.oven"],
"if": ["oic.if.baseline", "oic.if.s"]
}
},
{
"href": "/timezone/vs/0",
"rep": {
"timezoneid": "America/New_York",
"offset": "-04:00",
"DST": "ON"
}
},
{
"href": "/energy/consumption/vs/0",
"rep": {
"x.com.samsung.da.instantaneousPower": "-500",
"x.com.samsung.da.instantaneousPowerUnit": "W",
"x.com.samsung.da.cumulativePower": "3400",
"x.com.samsung.da.cumulativeUnit": "Wh"
}
},
{
"href": "/hood/fanspeed/vs/0",
"rep": {
"x.com.samsung.da.hood.fanSpeed": "0",
"x.com.samsung.da.hood.supportedFanSpeed": ["0", "1", "2", "3", "4"],
"x.com.samsung.da.hood.settableMaxFanSpeed": "4",
"x.com.samsung.da.hood.settableMinFanSpeed": "0"
}
},
{
"href": "/kidslock/vs/0",
"rep": {
"x.com.samsung.da.kidsLock": "Ready"
}
},
{
"href": "/wirelessinfo/vs/0",
"rep": {
"macaddressWiFi": "**REDACTED**",
"macaddressBLE": "**REDACTED**"
}
},
{
"href": "/quickcontrol/info/vs/0",
"rep": {
"supportedVersion": "1.0"
}
}
]
}
File renamed without changes.
+8
View File
@@ -160,6 +160,14 @@
"href": "/da/softreset/vs/0",
"rep": {"x.com.samsung.da.softwarereset": "false"}
},
{
"href": "/afterrun/vs/0",
"rep": {
"x.com.samsung.da.runningProgress": "0",
"x.com.samsung.da.runningCancel": "Cancel",
"x.com.samsung.da.activationState": "Off"
}
},
{
"href": "/filter/hoodfilter/vs/0",
"rep": {
@@ -0,0 +1,274 @@
{
"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": "/diagnosis/vs/0",
"rep": {
"x.com.samsung.da.diagnosisStart": "Ready"
}
},
{
"href": "/energy/consumption/vs/0",
"rep": {
"x.com.samsung.da.cumulativeConsumption": "5",
"x.com.samsung.da.cumulativePower": "1733313",
"x.com.samsung.da.cumulativeUnit": "Wh",
"x.com.samsung.da.instantaneousPower": "61",
"x.com.samsung.da.instantaneousPowerUnit": "W"
}
},
{
"href": "/mode/vs/0",
"rep": {
"x.com.samsung.da.supportedModes": [
"HOMECARE_WIZARD_V2",
"ENERGY_REPORT_MODEL",
"18K_KIMCHI_OUTDOOR_CONTROL"
],
"x.com.samsung.da.modes": [
"KIMCHIT_STORAGE_FREEZER_NORMAL",
"KIMCHIT_RIPE_REMAIN_[0]:[0]",
"KIMCHIM_KIMCHI_STORAGE_NORMAL",
"KIMCHIM_RIPE_REMAIN_[0]:[0]",
"KIMCHIB_KIMCHI_STORAGE_NORMAL",
"KIMCHIB_RIPE_REMAIN_[0]:[0]",
"KIMCHIT_BOX_COUNT_[6]",
"KIMCHIM_BOX_COUNT_[4]",
"KIMCHIB_BOX_COUNT_[2]",
"KIMCHI_BOX_COUNT_[0]"
],
"x.com.samsung.da.supportedOptions": [
"KIMCHIT_KIMCHI_STORAGE_NORMAL_[0]:[0]",
"KIMCHIT_KIMCHI_STORAGE_COLD_[0]:[0]",
"KIMCHIT_KIMCHI_STORAGE_WARM_[0]:[0]",
"KIMCHIT_KIMCHI_STORAGE_LOW_SALT_NORMAL_[0]:[0]",
"KIMCHIT_KIMCHI_STORAGE_LOW_SALT_COLD_[0]:[0]",
"KIMCHIT_KIMCHI_STORAGE_LOW_SALT_WARM_[0]:[0]",
"KIMCHIT_STORAGE_FRIDGE_NORMAL_[0]:[0]",
"KIMCHIT_STORAGE_FRIDGE_COLD_[0]:[0]",
"KIMCHIT_STORAGE_FRIDGE_WARM_[0]:[0]",
"KIMCHIT_STORAGE_FREEZER_NORMAL_[0]:[0]",
"KIMCHIT_STORAGE_FREEZER_COLD_[0]:[0]",
"KIMCHIT_STORAGE_FREEZER_WARM_[0]:[0]",
"KIMCHIT_OFF_[0]:[0]",
"KIMCHIT_KIMCHI_RIPE_LOW_TEMP_[5]:[17]",
"KIMCHIT_KIMCHI_RIPE_NORMAL_TEMP_[2]:[12]",
"KIMCHIM_KIMCHI_STORAGE_NORMAL_[0]:[0]",
"KIMCHIM_KIMCHI_STORAGE_COLD_[0]:[0]",
"KIMCHIM_KIMCHI_STORAGE_WARM_[0]:[0]",
"KIMCHIM_KIMCHI_STORAGE_LOW_SALT_NORMAL_[0]:[0]",
"KIMCHIM_KIMCHI_STORAGE_LOW_SALT_COLD_[0]:[0]",
"KIMCHIM_KIMCHI_STORAGE_LOW_SALT_WARM_[0]:[0]",
"KIMCHIM_KIMCHI_STORAGE_CRUNFCH_[0]:[0]",
"KIMCHIM_KIMCHI_STORAGE_BUY_[0]:[0]",
"KIMCHIM_MEAT_RIPE_NORMAL_[3]:[0]",
"KIMCHIM_STORAGE_MEAT_[0]:[0]",
"KIMCHIM_STORAGE_FRIDGE_VEGETABLES_FRUIT_[0]:[0]",
"KIMCHIM_STORAGE_FRESH_CEREAL_[0]:[0]",
"KIMCHIM_OFF_[0]:[0]",
"KIMCHIM_KIMCHI_RIPE_LOW_TEMP_[5]:[17]",
"KIMCHIM_KIMCHI_RIPE_NORMAL_TEMP_[2]:[12]",
"KIMCHIB_KIMCHI_STORAGE_NORMAL_[0]:[0]",
"KIMCHIB_KIMCHI_STORAGE_COLD_[0]:[0]",
"KIMCHIB_KIMCHI_STORAGE_WARM_[0]:[0]",
"KIMCHIB_KIMCHI_STORAGE_LOW_SALT_NORMAL_[0]:[0]",
"KIMCHIB_KIMCHI_STORAGE_LOW_SALT_COLD_[0]:[0]",
"KIMCHIB_KIMCHI_STORAGE_LOW_SALT_WARM_[0]:[0]",
"KIMCHIB_KIMCHI_STORAGE_CRUNFCH_[0]:[0]",
"KIMCHIB_KIMCHI_STORAGE_BUY_[0]:[0]",
"KIMCHIB_STORAGE_FRIDGE_VEGETABLES_FRUIT_[0]:[0]",
"KIMCHIB_STORAGE_FRIDGE_DRINK_[0]:[0]",
"KIMCHIB_STORAGE_FRESH_WINE_[0]:[0]",
"KIMCHIB_STORAGE_FRESH_POTATO_BANANA_[0]:[0]",
"KIMCHIB_OFF_[0]:[0]",
"KIMCHIB_KIMCHI_RIPE_KKAKDUGI_[4]:[5]",
"KIMCHIB_KIMCHI_RIPE_DONGCHIMI_[7]:[6]"
]
}
},
{
"href": "/mode/0",
"rep": {
"supportedModes": [
"HOMECARE_WIZARD_V2",
"ENERGY_REPORT_MODEL",
"18K_KIMCHI_OUTDOOR_CONTROL"
],
"modes": [
"KIMCHIT_STORAGE_FREEZER_NORMAL",
"KIMCHIT_RIPE_REMAIN_[0]:[0]",
"KIMCHIM_KIMCHI_STORAGE_NORMAL",
"KIMCHIM_RIPE_REMAIN_[0]:[0]",
"KIMCHIB_KIMCHI_STORAGE_NORMAL",
"KIMCHIB_RIPE_REMAIN_[0]:[0]",
"KIMCHIT_BOX_COUNT_[6]",
"KIMCHIM_BOX_COUNT_[4]",
"KIMCHIB_BOX_COUNT_[2]",
"KIMCHI_BOX_COUNT_[0]"
]
}
},
{
"href": "/realtimenotiforclient/vs/0",
"rep": {
"x.com.samsung.da.timeforshortnoti": "0",
"x.com.samsung.da.periodicnotisubscription": "true"
}
},
{
"href": "/information/vs/0",
"rep": {
"x.com.samsung.da.modelNum": "TP2X_REF_20K|00135941|10010221011411010103642021000000",
"x.com.samsung.da.description": "TP2X_REF_20K",
"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": "WiFi Module",
"x.com.samsung.da.type": "Software",
"x.com.samsung.da.number": "02144A220110",
"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": "20082109,FFFFFFFF",
"x.com.samsung.da.newVersionAvailable": "0"
}
]
}
},
{
"href": "/file/information/vs/0",
"rep": {
"x.com.samsung.timeoffset": "+09:00",
"x.com.samsung.supprtedtype": 1
}
},
{
"href": "/doors/vs/0",
"rep": {
"x.com.samsung.da.items": [
{
"x.com.samsung.da.id": "4",
"x.com.samsung.da.description": "Door",
"x.com.samsung.da.openState": "Close"
}
]
}
},
{
"href": "/kimchidoors/top/vs/0",
"rep": {
"x.com.samsung.da.openState": "Close"
}
},
{
"href": "/configuration/vs/0",
"rep": {
"x.com.samsung.da.countryCode": "",
"x.com.samsung.da.region": ""
}
},
{
"href": "/bespoke/vs/0",
"rep": {
"x.com.samsung.da.BespokeProduct": "On"
}
},
{
"href": "/otninformation/vs/0",
"rep": {
"x.com.samsung.da.target": "Micom",
"x.com.samsung.da.newVersionAvailable": "false"
}
},
{
"href": "/status/kimchi/top/vs/0",
"rep": {
"x.com.samsung.da.currentMode": "STORAGE_FREEZER_NORMAL",
"x.com.samsung.da.ripeStatus": "Off",
"x.com.samsung.da.ripeRemaintime": "0",
"x.com.samsung.da.rackCount": "6",
"x.com.samsung.da.supportMode": [
"KIMCHI_STORAGE_NORMAL",
"KIMCHI_STORAGE_COLD",
"KIMCHI_STORAGE_WARM",
"KIMCHI_STORAGE_LOW_SALT_NORMAL",
"KIMCHI_STORAGE_LOW_SALT_COLD",
"KIMCHI_STORAGE_LOW_SALT_WARM",
"STORAGE_FRIDGE_NORMAL",
"STORAGE_FRIDGE_COLD",
"STORAGE_FRIDGE_WARM",
"STORAGE_FREEZER_NORMAL",
"STORAGE_FREEZER_COLD",
"STORAGE_FREEZER_WARM",
"OFF",
"KIMCHI_RIPE_LOW_TEMP",
"KIMCHI_RIPE_NORMAL_TEMP"
]
}
},
{
"href": "/status/kimchi/middle/vs/0",
"rep": {
"x.com.samsung.da.currentMode": "KIMCHI_STORAGE_NORMAL",
"x.com.samsung.da.ripeStatus": "Off",
"x.com.samsung.da.ripeRemaintime": "0",
"x.com.samsung.da.rackCount": "4",
"x.com.samsung.da.supportMode": [
"KIMCHI_STORAGE_NORMAL",
"KIMCHI_STORAGE_COLD",
"KIMCHI_STORAGE_WARM",
"KIMCHI_STORAGE_LOW_SALT_NORMAL",
"KIMCHI_STORAGE_LOW_SALT_COLD",
"KIMCHI_STORAGE_LOW_SALT_WARM",
"KIMCHI_STORAGE_CRUNFCH",
"KIMCHI_STORAGE_BUY",
"MEAT_RIPE_NORMAL",
"STORAGE_MEAT",
"STORAGE_FRIDGE_VEGETABLES_FRUIT",
"STORAGE_FRESH_CEREAL",
"OFF",
"KIMCHI_RIPE_LOW_TEMP",
"KIMCHI_RIPE_NORMAL_TEMP"
]
}
},
{
"href": "/status/kimchi/bottom/vs/0",
"rep": {
"x.com.samsung.da.currentMode": "KIMCHI_STORAGE_NORMAL",
"x.com.samsung.da.ripeStatus": "Off",
"x.com.samsung.da.ripeRemaintime": "0",
"x.com.samsung.da.rackCount": "2",
"x.com.samsung.da.supportMode": [
"KIMCHI_STORAGE_NORMAL",
"KIMCHI_STORAGE_COLD",
"KIMCHI_STORAGE_WARM",
"KIMCHI_STORAGE_LOW_SALT_NORMAL",
"KIMCHI_STORAGE_LOW_SALT_COLD",
"KIMCHI_STORAGE_LOW_SALT_WARM",
"KIMCHI_STORAGE_CRUNFCH",
"KIMCHI_STORAGE_BUY",
"STORAGE_FRIDGE_VEGETABLES_FRUIT",
"STORAGE_FRIDGE_DRINK",
"STORAGE_FRESH_WINE",
"STORAGE_FRESH_POTATO_BANANA",
"OFF",
"KIMCHI_RIPE_KKAKDUGI",
"KIMCHI_RIPE_DONGCHIMI"
]
}
}
]
}
+34 -2
View File
@@ -11,9 +11,12 @@ from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import issue_registry as ir
from custom_components.localthings.const import (
CONF_BYPASS_REMOTE_CONTROL, CONF_HOST, DOMAIN, SUMMARY_INTERVAL_S,
CONF_BYPASS_REMOTE_CONTROL, CONF_HOST, DOMAIN, DTLS_LOCAL_PORT_BASE,
SUMMARY_INTERVAL_S,
)
from custom_components.localthings.coordinator import (
LocalThingsCoordinator, _local_source_port,
)
from custom_components.localthings.coordinator import LocalThingsCoordinator
from custom_components.localthings.registry.capabilities.common import (
remote_control_enabled,
remote_control_required_for_write,
@@ -1174,3 +1177,32 @@ async def test_send_command_operational_still_blocked_when_without_sc(
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == 'remote_control_disabled'
assert posted is False
def test_local_source_port_stable_and_in_range() -> None:
"""Same host always maps to the same port (stability is the whole point:
a reconnect must reuse the 5-tuple), and it stays in the documented window."""
for host in ('192.168.1.217', '10.0.0.42', 'fridge.local'):
port = _local_source_port(host)
assert port == _local_source_port(host)
assert DTLS_LOCAL_PORT_BASE <= port <= DTLS_LOCAL_PORT_BASE + 0xFF
def test_local_source_port_unique_per_host_on_a_24() -> None:
"""Distinct last octets -> distinct ports, so two devices on the same HA
host never share a source port (the lib's socket is unconnected, so a
shared port would cross-deliver datagrams)."""
ports = {_local_source_port(f'192.168.1.{n}') for n in range(1, 255)}
assert len(ports) == 254
def test_local_source_port_ipv4_uses_last_octet() -> None:
"""The IPv4 fast path is the last octet, not a hash."""
assert _local_source_port('192.168.1.217') == DTLS_LOCAL_PORT_BASE + 217
def test_local_source_port_non_ipv4_falls_back_to_hash() -> None:
"""A non-IPv4 host still yields a deterministic in-range port."""
port = _local_source_port('some-hostname')
assert port == _local_source_port('some-hostname')
assert DTLS_LOCAL_PORT_BASE <= port <= DTLS_LOCAL_PORT_BASE + 0xFF
+105
View File
@@ -0,0 +1,105 @@
"""HA fan-entity mapping tests for the ARTIK051_TVTL air purifier (issue #56)."""
from custom_components.localthings.fan import LocalThingsAirflowFan
from custom_components.localthings.registry.by_type import air_purifier
from custom_components.localthings.registry.capabilities.air_purifier import HREF_AIRFLOW
from custom_components.localthings.registry.discovery import discover
from custom_components.localthings.registry.entities import FanDesc
from tests.conftest import _load_device
class _FakeCoordinator:
device_serial = 'TEST-AIRFLOW-SERIAL'
device_info = {}
data = {}
def __init__(self, resources):
self.last_resources = resources
self.commands = []
def resource(self, href):
return self.last_resources.get(href, {})
async def async_send_command(self, bound, payload):
self.commands.append((bound, payload))
def _entity(resources, coordinator=None):
bound = discover(
resources,
air_purifier.REGISTRY.capabilities,
air_purifier.REGISTRY.pattern_capabilities,
)
fan_bound = next(
item for item in bound
if isinstance(item.desc, FanDesc) and item.href == HREF_AIRFLOW
)
return LocalThingsAirflowFan(
coordinator or _FakeCoordinator(resources), fan_bound,
)
def test_power_off_maps_to_zero_percent_and_five_retained_speeds():
entity = _entity(_load_device('air_purifier'))
assert entity.is_on is False
assert entity.speed_count == 5
assert entity.percentage == 0
def test_active_codes_map_to_ordered_percentages():
"""Confirmed via issue #56's second, properly-spaced diagnostics round:
/airflow/0's speed is a clean 0-4 code across Auto/Sleep/Low/Medium/High."""
resources = _load_device('air_purifier')
resources['/power/0']['value'] = True
for code, expected_percentage in ((0, 20), (1, 40), (2, 60), (3, 80), (4, 100)):
resources['/airflow/0']['speed'] = code
assert _entity(resources).percentage == expected_percentage
async def test_power_write_prefers_standard_resource_when_both_exist():
"""Both /power/0 and /power/vs/0 are present on this family's dumps --
/power/0 must win, matching common.POWER_GENERIC's own preference (the
power_switch entity is unconditionally bound to /power/0 whenever it's
present, so writing here to /power/vs/0 first would leave the two
entities disagreeing until the next poll)."""
resources = _load_device('air_purifier')
coordinator = _FakeCoordinator(resources)
entity = _entity(resources, coordinator)
await entity.async_turn_on()
assert coordinator.commands[-1][1] == ('power', True, '/power/0')
async def test_power_write_falls_back_to_vendor_resource():
resources = _load_device('air_purifier')
resources.pop('/power/0')
coordinator = _FakeCoordinator(resources)
entity = _entity(resources, coordinator)
await entity.async_turn_off()
assert coordinator.commands[-1][1] == ('power', False, '/power/vs/0')
async def test_set_percentage_writes_raw_speed_code():
resources = _load_device('air_purifier')
resources['/power/0']['value'] = True
coordinator = _FakeCoordinator(resources)
entity = _entity(resources, coordinator)
await entity.async_set_percentage(60)
assert coordinator.commands[-1][1] == ('speed', 2)
async def test_set_percentage_zero_turns_off():
resources = _load_device('air_purifier')
resources['/power/0']['value'] = True
coordinator = _FakeCoordinator(resources)
entity = _entity(resources, coordinator)
await entity.async_set_percentage(0)
assert coordinator.commands[-1][1] == ('power', False, '/power/0')
+25 -1
View File
@@ -41,7 +41,7 @@ def test_expected_entities_present():
for key in (
'power_switch', 'alarm_code', 'dust', 'fine_dust', 'super_fine_dust',
'odor', 'clean_level', 'filter_progress', 'device_active',
'diagnosis_status', 'fan_speed_level', 'fan_direction',
'diagnosis_status', 'airflow_fan', 'fan_direction',
'display_light', 'operating_mode',
):
assert key in state, key
@@ -114,3 +114,27 @@ def test_airflow_vs_fallback_only_binds_without_generic():
{}, {'/airflow/0': {'speed': 0, 'direction': 'Off'}},
) is False
assert air_purifier.AIRFLOW_VS_FALLBACK.match_fn({}, {}) is True
def test_airflow_fan_write_contract():
"""Confirmed via issue #56's second, properly-spaced diagnostics round
(two independent units, 60-90s apart per setting): /airflow/0's `speed`
is a clean, monotonic 0-4 code, so the write is a plain int passthrough
-- no named-preset table needed (see fan.py's LocalThingsAirflowFan)."""
fan_desc = next(e for e in air_purifier.AIRFLOW_GENERIC.entities if e.key == 'airflow_fan')
assert fan_desc.write_fn(('speed', 3), {}) == (['airflow', '0'], {'speed': 3})
assert fan_desc.write_fn(('power', True, '/power/vs/0'), {}) == (
['power', 'vs', '0'], {'x.com.samsung.da.power': 'On'},
)
assert fan_desc.write_fn(('power', False, '/power/0'), {}) == (
['power', '0'], {'value': False},
)
def test_airflow_speed_reads_from_dump():
"""The fixture's /airflow/0 (power-off snapshot) reads speed=0, and
fan_direction stays a plain diagnostic (every dump seen reads 'Off'
regardless of fan setting)."""
state = _state()
assert state['airflow_fan'] == 0
assert state['fan_direction'] == 'Off'
+234
View File
@@ -0,0 +1,234 @@
"""ARTIK051_KRAC_18K room air conditioner (issue #136).
This board generation predates every AC dump the registry was built from and
differs from all of them in three ways, each covered below:
* No ``/wind/*`` resources at all -- fan speed and vane direction share one
``/airflow/vs/0`` resource (``speedLevel`` on the same 0-4 scale as
``_DEVICE_TO_FAN``, ``direction`` with the same codes as ``_DEVICE_TO_SWING``).
* No ``/mode/convenient/vs/0`` -- the convenient-mode preset is a ``Comode_*``
token in ``/mode/vs/0``'s ``options`` array.
* Several settings (SPI, auto clean, air monitoring, beep volume, Good Sleep,
outdoor temperature, filter time) are ``options`` tokens too, where newer
boards have dedicated resources.
Fan, swing, preset, SPI and beep-volume writes were all confirmed on hardware
by read-back on the unit this fixture is dumped from. The issue #136 unit is
the same model with a slightly different token set (no ``Spi``,
``FilterTime_5460``, ``OutdoorTemp_81``), which the token entities' presence
gating handles the same way it handles newer boards.
"""
from custom_components.localthings.climate import LocalThingsClimate
from custom_components.localthings.registry.adapter import flatten
from custom_components.localthings.registry.by_type import (
airconditioner, for_device_by_model,
)
from custom_components.localthings.registry.capabilities.airconditioner import (
HREF_AIRFLOW, _option_number_write, _option_switch_write,
)
from custom_components.localthings.registry.discovery import discover
from custom_components.localthings.registry.entities import ClimateDesc
from tests.conftest import _load_device
FIXTURE = 'airconditioner_artik051_krac_18k'
MODEL = 'ARTIK051_KRAC_18K|10193441|60010119001111010100000000000000'
class _FakeCoordinator:
device_serial = 'TEST-KRAC-SERIAL'
device_info = {}
data = {}
def __init__(self, resources):
self.last_resources = resources
self.commands = []
def resource(self, href):
return self.last_resources.get(href, {})
async def async_send_command(self, bound, payload):
self.commands.append((bound, payload))
def _discover(resources, registry=airconditioner.REGISTRY):
unbound = []
bound = discover(resources, registry.capabilities,
registry.pattern_capabilities, log=unbound.append)
return bound, unbound
def _state(fixture=FIXTURE):
resources = _load_device(fixture)
bound, _ = _discover(resources)
return flatten(bound, resources)
def _climate(resources, coordinator=None):
bound, _ = _discover(resources)
climate_bound = next(
item for item in bound if isinstance(item.desc, ClimateDesc)
)
return LocalThingsClimate(
coordinator or _FakeCoordinator(resources), climate_bound,
)
# -- device type --------------------------------------------------------------
def test_krac_model_resolves_to_the_airconditioner_registry():
"""The '_RAC_' token check can't see '_KRAC_' -- the 'K' sits between the
underscore and 'RAC' -- and the consumer-prefix fallback only covers
washers/dryers/dishwashers, so this model resolved to 'unknown' and
exposed nothing but power."""
registry = for_device_by_model(MODEL, 'ARTIK051_KRAC_18K')
assert registry is not None
assert registry.name == 'airconditioner'
def test_no_unbound_hrefs():
_, unbound = _discover(_load_device(FIXTURE))
assert unbound == []
# -- option-token entities ----------------------------------------------------
def test_token_entities_present_with_calibrated_values():
state = _state()
# token/10 hours: 1715 displayed as "171 hours 0 minutes"... at 1710 in the
# official app on this unit, which pins the scale (the .5 here is a later
# reading). Whether it counts up or down is deliberately not asserted --
# see the descriptor comment.
assert state['filter_time'] == 171.5
# token - 55 == 19 C, against a 19.4 C forecast at the time of the dump.
assert state['outdoor_temperature'] == 19.0
assert state['buzzer_volume'] == 100.0
assert state['good_sleep'] == 0.0
assert state['spi'] is False
assert state['auto_clean_legacy'] is False
assert state['air_monitoring'] is False
def test_token_entities_stay_off_newer_boards():
"""Newer families carry Volume/Sleep/OutdoorTemp/Autoclean tokens too,
while also exposing those settings as dedicated resources -- ungated, the
token entities would duplicate them (auto clean) or apply a scale
calibrated on another board generation (outdoor temperature)."""
state = _state('airconditioner_tp1x_rac')
for key in ('spi', 'auto_clean_legacy', 'air_monitoring', 'buzzer_volume',
'good_sleep', 'outdoor_temperature', 'filter_time'):
assert key not in state, key
def test_absent_token_yields_no_entity():
"""The issue #136 unit of this same model reports no Spi token."""
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('Spi_')
]
bound, _ = _discover(resources)
assert 'spi' not in flatten(bound, resources)
def test_humidity_reads_the_vendor_field_and_treats_zero_as_unknown():
"""This board has no fivepercentHumidity field; the plain humidity field
only carries a reading while Air monitoring is on, and the unit switches
that back off by itself after about a minute."""
resources = _load_device(FIXTURE)
assert resources['/humidity/vs/0']['x.com.samsung.da.humidity'] == '0'
bound, _ = _discover(resources)
assert flatten(bound, resources)['humidity'] is None
resources['/humidity/vs/0']['x.com.samsung.da.humidity'] = '51'
bound, _ = _discover(resources)
assert flatten(bound, resources)['humidity'] == 51.0
def test_option_writes_carry_one_token():
"""Both go through option_write's single-token merge, the same mechanism
the display light already uses on this href. Confirmed on hardware by
read-back: Spi_On/Spi_Off, and the volume token surviving a write."""
assert _option_switch_write('Spi')('On', {}) == (
['mode', 'vs', '0'], {'x.com.samsung.da.options': ['Spi_On']},
)
# The number platform hands over a float; the device wants an integer token.
assert _option_number_write('Volume')(70.0, {}) == (
['mode', 'vs', '0'], {'x.com.samsung.da.options': ['Volume_70']},
)
# -- climate entity: fan, swing and preset off /airflow/vs/0 ------------------
def test_fan_mode_reads_the_airflow_speed_level():
entity = _climate(_load_device(FIXTURE))
assert entity.fan_mode == 'high' # speedLevel 3 in the fixture
# No supportedModes on this resource, so the full 0-4 scale is offered.
assert entity.fan_modes == ['auto', 'low', 'medium', 'high', 'turbo']
def test_swing_mode_reads_the_airflow_direction():
resources = _load_device(FIXTURE)
entity = _climate(resources)
assert entity.swing_mode == 'off' # 'Fix' in the fixture
resources[HREF_AIRFLOW]['x.com.samsung.da.direction'] = 'All'
assert _climate(resources).swing_mode == 'both'
assert 'both' in _climate(resources).swing_modes
async def test_fan_and_swing_writes_target_the_airflow_resource():
resources = _load_device(FIXTURE)
coordinator = _FakeCoordinator(resources)
entity = _climate(resources, coordinator)
await entity.async_set_fan_mode('turbo')
await entity.async_set_swing_mode('both')
assert [payload for _, payload in coordinator.commands] == [
('fan_legacy', '4'), ('swing_legacy', 'All'),
]
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.
assert entity.preset_modes == [
'none', 'nano', 'quiet', 'comfort', '2step', 'speed',
]
options = resources['/mode/vs/0']['x.com.samsung.da.options']
resources['/mode/vs/0']['x.com.samsung.da.options'] = [
'Comode_Nano' if option.startswith('Comode_') else option
for option in options
]
assert _climate(resources).preset_mode == 'nano'
async def test_preset_write_uses_the_token_path():
resources = _load_device(FIXTURE)
coordinator = _FakeCoordinator(resources)
entity = _climate(resources, coordinator)
await entity.async_set_preset_mode('nano')
assert coordinator.commands[-1][1] == ('preset_legacy', 'Nano')
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."""
resources = _load_device('airconditioner_tp1x_rac')
coordinator = _FakeCoordinator(resources)
entity = _climate(resources, coordinator)
await entity.async_set_fan_mode('high')
await entity.async_set_swing_mode('off')
await entity.async_set_preset_mode('quiet') # from its own supportedModes
kinds = [payload[0] for _, payload in coordinator.commands]
assert kinds == ['fan', 'swing', 'preset']
+25 -1
View File
@@ -405,7 +405,17 @@ def test_current_temperature_vs_only_binds_when_ocf_href_absent():
def test_humidity_reads_five_percent_field_not_stuck_humidity_field():
desc = airconditioner.HUMIDITY.entities[0]
rep = {'x.com.samsung.da.humidity': '0', 'x.com.samsung.da.fivepercentHumidity': '42'}
assert desc.value_fn(rep.get(desc.field)) == 42.0
assert desc.rep_fn(rep) == 42.0
def test_humidity_falls_back_to_the_plain_field_where_five_percent_is_absent():
"""ARTIK051 boards (issue #136) have no fivepercentHumidity field at all.
Their plain field is not stuck -- it carries a reading while Air monitoring
is on -- so 0 means "not measuring" on both generations, not 0% humidity."""
desc = airconditioner.HUMIDITY.entities[0]
assert desc.rep_fn({'x.com.samsung.da.humidity': '51'}) == 51.0
assert desc.rep_fn({'x.com.samsung.da.humidity': '0'}) is None
assert desc.rep_fn({}) is None
# ---------------------------------------------------------------------------
@@ -634,3 +644,17 @@ def test_sensor_item_value_picks_first_value():
assert airconditioner._sensor_item_value(items, 'Odor') is None
assert airconditioner._sensor_item_value(items, 'Missing') is None
assert airconditioner._sensor_item_value(None, 'Dust') is None
def test_beep_and_tropical_night_stay_off_legacy_krac_board():
"""ARTIK051_KRAC_18K (issue #136) reports both a Volume_ and a Sleep_
option token, but they're already modeled as buzzer_volume/good_sleep
(see airconditioner.CLIMATE) -- beep/tropical_night_mode must not also
bind there, or the same options[] slot would surface as two entities."""
reg, resources = _resolve('airconditioner_artik051_krac_18k')
state = flatten(
discover(resources, reg.capabilities, reg.pattern_capabilities), resources)
assert 'beep' not in state
assert 'tropical_night_mode' not in state
assert state['buzzer_volume'] == 100.0
assert state['good_sleep'] == 0.0
+56
View File
@@ -0,0 +1,56 @@
"""Tests for registry.batch — the /device/0 sweep parser and its stub marker.
issue #127: a device whose /energy/consumption/vs/0 is permanently
unsupported reports a genuinely empty {} rep for it. The previous parser
collapsed /device/0's own {"href": "..."} "not fetched yet" marker to that
same {} shape, so downstream exists_fn checks couldn't tell "confirmed
empty" apart from "haven't polled it yet" and created phantom always-
"unknown" entities either way. is_stub_rep/parse_device0_batch now keep the
two shapes distinct.
"""
from custom_components.localthings.registry.batch import is_stub_rep, parse_device0_batch
class TestIsStubRep:
def test_true_for_bare_href_marker(self):
assert is_stub_rep({'href': '/energy/consumption/vs/0'}) is True
def test_false_for_genuinely_empty_rep(self):
assert is_stub_rep({}) is False
def test_false_for_populated_rep(self):
assert is_stub_rep({'x.com.samsung.da.cumulativePower': '58900'}) is False
def test_false_for_href_plus_data(self):
"""A real, populated rep may legitimately echo 'href' alongside
actual fields -- only a rep with *no other keys* is the stub."""
assert is_stub_rep({'href': '/x/0', 'value': True}) is False
class TestParseDevice0Batch:
def test_stub_rep_kept_distinct_from_genuine_empty(self):
device0 = [
{},
{'href': '/energy/consumption/vs/0', 'rep': {'href': '/energy/consumption/vs/0'}},
{'href': '/sabbath/vs/0', 'rep': {}},
]
resources = parse_device0_batch(device0)
assert is_stub_rep(resources['/energy/consumption/vs/0']) is True
assert is_stub_rep(resources['/sabbath/vs/0']) is False
assert resources['/sabbath/vs/0'] == {}
def test_populated_rep_passes_through_unchanged(self):
device0 = [
{},
{'href': '/door/cooler/0', 'rep': {'openState': 'Close'}},
]
resources = parse_device0_batch(device0)
assert resources['/door/cooler/0'] == {'openState': 'Close'}
def test_skips_entries_without_href(self):
device0 = [{}, {'rep': {'a': 1}}]
assert parse_device0_batch(device0) == {}
def test_skips_non_dict_rep(self):
device0 = [{}, {'href': '/x/0', 'rep': 'not-a-dict'}]
assert parse_device0_batch(device0) == {}
+6 -6
View File
@@ -329,19 +329,19 @@ class TestForDeviceByModel:
assert reg is not None
assert reg.name == 'airconditioner'
def test_oven_via_microwave_token(self):
"""Issue #121: a combi microwave (MW7300B-/EU1) reports no
def test_microwave_via_microwave_token(self):
"""Issue #121/#66: a combi microwave (MW7300B-/EU1) reports no
oneUiVersion and an unrecognized consumer token; falls back to the
'-MICROWAVE-' token in modelNum onto the *existing* oven registry
(same '/oven/vs/0' cavity + cook-mode shape), not a new device
type."""
'-MICROWAVE-' token in modelNum onto its own microwave registry
(initially folded into 'oven' for issue #121, split out into a
distinct device type per user feedback)."""
from custom_components.localthings.registry.by_type import for_device_by_model
reg = for_device_by_model(
'TP1X_DA-KS-MICROWAVE-01041|40475341|50040100021811000A00000000000000',
'MW7300B-/EU1',
)
assert reg is not None
assert reg.name == 'oven'
assert reg.name == 'microwave'
def test_vacuum_station_via_vskr_token(self):
"""Issue #131: a stick-vacuum clean/auto-empty station
+36 -12
View File
@@ -253,13 +253,24 @@ class TestEnergyMeter:
kwh = next(e for e in common.ENERGY_METER.entities if e.key == 'energy_kwh')
assert kwh.exists_fn({'x.com.samsung.da.cumulativePower': '58900'}, {}) is True
def test_both_entities_included_on_empty_stub(self):
"""An empty {} rep means the resource exists but data isn't fetched yet
(see entity._is_included) -- include both so sub-polls populate them."""
def test_both_entities_included_on_true_stub(self):
"""A true stub -- /device/0's {"href": "..."} "not fetched yet"
marker (see registry.batch.is_stub_rep) -- means the resource exists
but data isn't fetched yet; include both so sub-polls populate them."""
pw = next(e for e in common.ENERGY_METER.entities if e.key == 'power_watts')
kwh = next(e for e in common.ENERGY_METER.entities if e.key == 'energy_kwh')
assert pw.exists_fn({}, {}) is True
assert kwh.exists_fn({}, {}) is True
stub = {'href': '/energy/consumption/vs/0'}
assert pw.exists_fn(stub, {}) is True
assert kwh.exists_fn(stub, {}) is True
def test_both_entities_hidden_on_genuinely_empty_rep(self):
"""A real {} rep (no 'href' key) is the device's confirmed -- if
empty -- answer, not a stub, so a model that never populates this
resource doesn't get a phantom always-"unknown" entity (issue #127)."""
pw = next(e for e in common.ENERGY_METER.entities if e.key == 'power_watts')
kwh = next(e for e in common.ENERGY_METER.entities if e.key == 'energy_kwh')
assert pw.exists_fn({}, {}) is False
assert kwh.exists_fn({}, {}) is False
def test_power_watts_hidden_when_field_absent_in_populated_rep(self):
"""A populated rep that lacks instantaneousPower must not spawn a
@@ -388,13 +399,20 @@ class TestAiEnergyLevelStubDoesNotDecideThePlatform:
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 already-instantiated
entity a value shaped for the other platform (e.g. a bool into a Select
expecting a string option). Neither side gets a `not rep` carve-out, so
an unfetched stub can never win entity creation for either platform --
expecting a string option). Neither side gets an is_stub_rep carve-out,
so an unfetched stub can never win entity creation for either platform --
the entity simply doesn't appear until a reload happens with real data,
same as any other exists_fn-gated entity in this codebase that's unlucky
on first-poll timing, instead of appearing as the wrong widget type."""
def test_neither_widget_exists_on_empty_stub_rep(self):
def test_neither_widget_exists_on_true_stub_rep(self):
switch = _ai_energy_level_desc('SwitchDesc')
select = _ai_energy_level_desc('SelectDesc')
stub = {'href': '/energy/ailevel/vs/0'}
assert switch.exists_fn(stub, {}) is False
assert select.exists_fn(stub, {}) is False
def test_neither_widget_exists_on_genuinely_empty_rep(self):
switch = _ai_energy_level_desc('SwitchDesc')
select = _ai_energy_level_desc('SelectDesc')
assert switch.exists_fn({}, {}) is False
@@ -416,11 +434,17 @@ class TestSelfCheckError:
desc = self._desc()
assert desc.exists_fn({'x.com.samsung.da.status': 'Ready'}, {}) is False
def test_exists_for_empty_stub_rep(self):
"""An empty {} rep is /device/0's not-yet-fetched-stub carve-out --
must be included-for-now, same as ENERGY_METER's fields."""
def test_exists_for_true_stub_rep(self):
"""A true stub ({"href": "..."}) is /device/0's not-yet-fetched
marker -- must be included-for-now, same as ENERGY_METER's fields."""
desc = self._desc()
assert desc.exists_fn({}, {}) is True
assert desc.exists_fn({'href': '/selfcheck/vs/0'}, {}) is True
def test_hidden_for_genuinely_empty_rep(self):
"""A real {} rep is the device's confirmed empty answer, not a stub --
must NOT be force-included (issue #127's phantom-entity pattern)."""
desc = self._desc()
assert desc.exists_fn({}, {}) is False
def test_value_joins_list(self):
desc = self._desc()
+79
View File
@@ -0,0 +1,79 @@
"""Tests for entity._is_included -- the one-time entity-creation gate run
per platform at async_setup_entry (see sensor.py etc.), separate from
adapter.flatten()'s per-poll state values. issue #127 review: this default
gate has to stay permissive on a genuinely empty {} rep, not just a true
is_stub_rep stub -- a resource like /alarms/vs/0 is validly empty in its
normal, no-alarm state (fridge._active_alarm_codes), so excluding the
entity there would silently drop working sensors on first-poll timing,
not just fix phantom ones.
"""
from custom_components.localthings.entity import _is_included
from custom_components.localthings.registry.capability import Capability
from custom_components.localthings.registry.discovery import BoundEntity
from custom_components.localthings.registry.entities import SensorDesc
class _FakeCoordinator:
def __init__(self, last_resources):
self.last_resources = last_resources
def _bound(desc, href):
capability = Capability(href=href, entities=(desc,))
return BoundEntity(href=href, capability=capability, desc=desc)
class TestDefaultFieldGate:
"""No explicit exists_fn -- the field-presence default in entity.py."""
def _bound(self):
return _bound(SensorDesc(key='x', field='x.com.samsung.da.value'), '/x/vs/0')
def test_included_when_field_present(self):
bound = self._bound()
coord = _FakeCoordinator({'/x/vs/0': {'x.com.samsung.da.value': '1'}})
assert _is_included(bound, coord) is True
def test_excluded_when_field_absent_from_populated_rep(self):
bound = self._bound()
coord = _FakeCoordinator({'/x/vs/0': {'x.com.samsung.da.other': '1'}})
assert _is_included(bound, coord) is False
def test_included_on_true_stub(self):
bound = self._bound()
coord = _FakeCoordinator({'/x/vs/0': {'href': '/x/vs/0'}})
assert _is_included(bound, coord) is True
def test_included_on_genuinely_empty_rep(self):
"""The default gate stays permissive on a real {} -- see
/alarms/vs/0, whose empty rep is the normal no-alarm state, not a
signal the hardware is unsupported. Only a capability-specific
exists_fn (e.g. common.ENERGY_METER) opts into excluding on
confirmed-empty, after verifying that's actually safe for its field."""
bound = self._bound()
coord = _FakeCoordinator({'/x/vs/0': {}})
assert _is_included(bound, coord) is True
def test_excluded_when_href_missing_from_resources(self):
bound = self._bound()
coord = _FakeCoordinator({})
assert _is_included(bound, coord) is False
class TestExplicitExistsFnGate:
def test_explicit_exists_fn_overrides_default_field_gate(self):
desc = SensorDesc(key='x', field='x.com.samsung.da.value',
exists_fn=lambda rep, resources: rep.get('flag') is True)
bound = _bound(desc, '/x/vs/0')
coord = _FakeCoordinator({'/x/vs/0': {'flag': True}})
assert _is_included(bound, coord) is True
coord = _FakeCoordinator({'/x/vs/0': {'flag': False, 'x.com.samsung.da.value': '1'}})
assert _is_included(bound, coord) is False
class TestNoFieldEntities:
def test_rep_fn_entity_always_included(self):
desc = SensorDesc(key='x', rep_fn=lambda rep: rep.get('x.com.samsung.da.value'))
bound = _bound(desc, '/x/vs/0')
coord = _FakeCoordinator({'/x/vs/0': {}})
assert _is_included(bound, coord) is True
+138
View File
@@ -163,6 +163,26 @@ class TestFlexZone:
assert 'CV_FDR_MEAT' not in modes
assert 'CVN_CONVERTIBLE_ZONE' in modes and 'WATERFILTER_ENABLE' in modes
def test_exists_only_when_a_current_value_resolves(self):
"""Issue #26's kimchi-refrigerator family also populates /mode/vs/0's
modes/supportedOptions, but its supportedOptions tokens carry a
"_[n]:[n]" suffix modes never repeats, so no item ever overlaps --
the entity used to bind anyway (supportedOptions is nonempty) and
get stuck on "unknown" forever."""
no_overlap_rep = {
'x.com.samsung.da.modes': ['KIMCHIT_STORAGE_FREEZER_NORMAL'],
'x.com.samsung.da.supportedOptions': [
'KIMCHIT_STORAGE_FREEZER_NORMAL_[0]:[0]'],
}
desc = fridge.FLEX_ZONE.entities[0]
assert desc.exists_fn(no_overlap_rep, {}) is False
overlap_rep = {
'x.com.samsung.da.modes': ['CV_FDR_MEAT'],
'x.com.samsung.da.supportedOptions': ['CV_FDR_WINE', 'CV_FDR_MEAT'],
}
assert desc.exists_fn(overlap_rep, {}) is True
class TestTp1xNativeDuplicateResources:
"""The US TP1X_REF_21K publishes two native mirrors in addition to the
@@ -210,6 +230,97 @@ class TestPantryZone:
assert body == {'x.com.samsung.da.mode': 'FDR_WINE'}
class TestKimchiZone:
"""Kimchi-refrigerator compartments (TP2X_REF_20K-class, issue #26) --
top/middle/bottom each report an identically-shaped currentMode/
supportMode resource under /status/kimchi/<slot>/vs/0."""
def test_href_prefix(self):
assert fridge.KIMCHI_ZONE.href_prefix == '/status/kimchi/'
assert fridge.KIMCHI_DOOR_GENERIC.href_prefix == '/kimchidoors/'
def test_write_derives_path_from_href(self):
desc = fridge.KIMCHI_ZONE.entities[0]
rep = {'x.com.samsung.da.supportMode': ['KIMCHI_STORAGE_COLD']}
path, body = desc.write_fn(
'KIMCHI_STORAGE_COLD', rep, href='/status/kimchi/middle/vs/0')
assert path == ['status', 'kimchi', 'middle', 'vs', '0']
assert body == {'x.com.samsung.da.currentMode': 'KIMCHI_STORAGE_COLD'}
def test_write_without_href_is_rejected(self):
desc = fridge.KIMCHI_ZONE.entities[0]
rep = {'x.com.samsung.da.supportMode': ['KIMCHI_STORAGE_COLD']}
assert desc.write_fn('KIMCHI_STORAGE_COLD', rep) is None
def test_write_rejects_value_outside_supportmode(self):
"""A value the compartment never advertised is rejected rather than
written blind -- this write path is unconfirmed against real
hardware (module docstring above KIMCHI_ZONE), so a bad value here
is a food-safety-adjacent outcome, not just a cosmetic one."""
desc = fridge.KIMCHI_ZONE.entities[0]
rep = {'x.com.samsung.da.supportMode': ['KIMCHI_STORAGE_COLD']}
assert desc.write_fn(
'KIMCHI_STORAGE_WARM', rep, href='/status/kimchi/middle/vs/0',
) is None
def test_ripening_status_passes_through_device_value(self):
"""No device_class='enum' catalog entry exists for this sensor, so
lowercasing it would only make the raw device token un-translatable
by HA -- pass the device's own casing straight through instead."""
desc = next(e for e in fridge.KIMCHI_ZONE.entities if e.key == 'ripening_status')
assert desc.value_fn('Off') == 'Off'
def test_door_reuses_open_state_helper(self):
desc = fridge.KIMCHI_DOOR_GENERIC.entities[0]
assert desc.rep_fn({'x.com.samsung.da.openState': 'Open'}) is True
assert desc.rep_fn({'x.com.samsung.da.openState': 'Close'}) is False
async def test_zone_mode_select_round_trips_through_display_casing(self):
"""kimchi_zone_mode's displayed value (lowercase, catalog-translated)
and the raw device code it writes back can silently drift apart --
this is the one place that casing conversion could break. Runs
through the real discovery/select pipeline against the tp2x_ref_20k
kimchi fixture rather than a hand-built descriptor, so it also
catches use_instance_name key derivation going wrong."""
from custom_components.localthings.registry.adapter import flatten
from custom_components.localthings.registry.by_type import refrigerator
from custom_components.localthings.registry.discovery import discover
from custom_components.localthings.registry.entities import SelectDesc
from custom_components.localthings.select import LocalThingsSelect
from tests.conftest import _load_device
resources = _load_device('refrigerator_tp2x_ref_20k_kimchi')
bound = discover(
resources, refrigerator.REGISTRY.capabilities,
refrigerator.REGISTRY.pattern_capabilities,
)
mode_bound = next(
b for b in bound
if isinstance(b.desc, SelectDesc) and b.href == '/status/kimchi/middle/vs/0'
)
class _FakeCoordinator:
device_serial = 'TEST-SERIAL'
def __init__(self, resources, data):
self.last_resources = resources
self.data = data
self.commands = []
async def async_send_command(self, bound, value):
self.commands.append(value)
coordinator = _FakeCoordinator(resources, flatten(bound, resources))
entity = LocalThingsSelect(coordinator, mode_bound)
assert entity.current_option == 'kimchi_storage_normal'
assert 'kimchi_storage_cold' in entity.options
await entity.async_select_option('kimchi_storage_cold')
assert coordinator.commands == ['KIMCHI_STORAGE_COLD']
class TestArtik051AndTp2xFixturesHaveCompleteCoverage:
"""issue #20 (ARTIK051_REF_17K) and #26 (TP2X_REF_20K) both triggered
the incomplete-capability-coverage repair; both must resolve to zero
@@ -253,6 +364,33 @@ class TestArtik051AndTp2xFixturesHaveCompleteCoverage:
state = flatten(bound, resources)
assert state['flex_zone_mode'] == 'CV_FDR_BEVERAGE'
def test_tp2x_ref_20k_kimchi(self):
"""A different physical unit sharing the same modelNum string (issue
#26, second reporter) -- a 3-compartment kimchi refrigerator instead
of the flex-zone fridge above. /kimchidoors/top/vs/0 and
/status/kimchi/{top,middle,bottom}/vs/0 were previously unbound."""
from custom_components.localthings.registry.adapter import flatten
from custom_components.localthings.registry.by_type import refrigerator
from custom_components.localthings.registry.discovery import discover
from tests.conftest import _load_device
resources = _load_device('refrigerator_tp2x_ref_20k_kimchi')
unbound = []
bound = discover(
resources,
refrigerator.REGISTRY.capabilities,
refrigerator.REGISTRY.pattern_capabilities,
log=unbound.append,
)
assert unbound == []
state = flatten(bound, resources)
assert state['top_mode'] == 'STORAGE_FREEZER_NORMAL'
assert state['middle_mode'] == 'KIMCHI_STORAGE_NORMAL'
assert state['bottom_mode'] == 'KIMCHI_STORAGE_NORMAL'
assert state['top_open'] is False
assert 'middle_open' not in state # no /kimchidoors/middle/vs/0 reported
assert 'flex_zone_mode' not in state # no resolvable overlap on this family
class TestArtik051DongleRefFixtureCoverage:
"""Issues #77/#83: the ARTIK051_DONGLE_REF standalone freezer resolves
+73 -10
View File
@@ -300,6 +300,23 @@ def test_registry_reproduces_golden_state_keys_for_tp2x_ref_20k():
)
def test_registry_reproduces_golden_state_keys_for_tp2x_ref_20k_kimchi():
"""A different physical unit reporting the same "TP2X_REF_20K" modelNum
string as the fixture above (issue #26's second reporter) -- a
3-compartment kimchi refrigerator with no flex zone, doors/icemaker, or
freezer/cooler split, but its own /status/kimchi/<slot>/vs/0 and
/kimchidoors/top/vs/0 resources (fridge.KIMCHI_ZONE/KIMCHI_DOOR_GENERIC)."""
from tests.conftest import _load_device
resources = _load_device('refrigerator_tp2x_ref_20k_kimchi')
golden = json.loads((GOLDEN / 'refrigerator_tp2x_ref_20k_kimchi.json').read_text())
state_keys = _new_state_keys('refrigerator_tp2x_ref_20k_kimchi', 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_ac_tp1x_da_ac_rac_01011():
"""Newer AC firmware (Tizen Lite, oneUiVersion "7.0 Air conditioner"; model
TP1X_DA-AC-RAC-01011) reports temperature via the vendor /temperatures/vs/0
@@ -568,19 +585,44 @@ def test_registry_reproduces_golden_state_keys_for_airconditioner_windfree_oscil
)
def test_registry_reproduces_golden_state_keys_for_oven_mw7300b():
def test_registry_reproduces_golden_state_keys_for_microwave_mw7300b():
"""TP1X_DA-KS-MICROWAVE-01041 combi microwave (model MW7300B, issue
#121) -- reports no oneUiVersion; resolved via the '-MICROWAVE-'
modelNum token fallback onto the *existing* oven registry rather than
a new device type, since it shares the same '/oven/vs/0' cavity and
'/mode/vs/0' cook-mode shape (Convection/AirFryer/Grill/MicroWave*).
The only href the oven registry didn't already cover was
/recipe/cook/vs/0 (oven.OVEN_RECIPE_COOK, an empty quick-recipe-display
blob with no entity)."""
modelNum token fallback onto its own microwave registry. Shares the
oven board family's operational-state/door/connected/recipe-cook
Capability objects (reused directly from oven.py), but has its own
cooking-mode vocabulary, setpoint bounds, and cavity power-level sensor
(capabilities/microwave.py) -- this device's initial routing folded it
into the oven registry (issue #121); split into its own device type per
user feedback that microwaves shouldn't show up as ovens."""
from tests.conftest import _load_device
resources = _load_device('oven_mw7300b')
golden = json.loads((GOLDEN / 'oven_mw7300b.json').read_text())
state_keys = _new_state_keys('oven_mw7300b', resources)
resources = _load_device('microwave_mw7300b')
golden = json.loads((GOLDEN / 'microwave_mw7300b.json').read_text())
state_keys = _new_state_keys('microwave_mw7300b', 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_microwave_me7500d():
"""TP1X_DA-KS-MICROWAVE-01051 plain microwave (model ME7500D, issues
#137/#142) -- the same microwave registry as MW7300B above, but this
board also reports the built-in vent fan's `/hood/fanspeed/vs/0`
resource, previously unbound. Bound via range_hood.HOOD_FAN (reused
directly, same resource shape a standalone range hood reports); unlike
a standalone hood this board has no sibling `/power/0` or
`/power/vs/0` resource, so fan.py's LocalThingsRangeHoodFan treats
fan speed 0 as the off state instead of writing a separate power
resource -- see its `_speed_zero_is_off` check. This board also has
no `/temperatures/vs/0` or `x.com.samsung.da.hood.autoOperation`
field, unlike MW7300B, so `setpoint`/`current_temp_c` and
`automatic_operation` are correctly absent here."""
from tests.conftest import _load_device
resources = _load_device('microwave_me7500d')
golden = json.loads((GOLDEN / 'microwave_me7500d.json').read_text())
state_keys = _new_state_keys('microwave_me7500d', 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"
@@ -629,6 +671,27 @@ def test_registry_reproduces_golden_state_keys_for_vacuum_station():
)
def test_registry_reproduces_golden_state_keys_for_artik051_krac_18k():
"""ARTIK051_KRAC_18K (issue #136) -- reports no oneUiVersion, and its
'_KRAC_' token was invisible to for_device_by_model's '_RAC_' check (the
'K' sits between the underscore and 'RAC'), so it fell back to 'unknown'
and exposed nothing but power. Same ARTIK051 board generation as the
'_TVTL_' air purifier: no /wind/* resources at all (fan and vane live in
/airflow/vs/0), no /mode/convenient/vs/0 (the preset is a Comode_* token),
and several settings carried as /mode/vs/0 options[] tokens."""
from tests.conftest import _load_device
resources = _load_device('airconditioner_artik051_krac_18k')
golden = json.loads(
(GOLDEN / 'airconditioner_artik051_krac_18k.json').read_text()
)
state_keys = _new_state_keys('airconditioner_artik051_krac_18k', 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_resources_from_batch_preferred_over_flat():
from tests.conftest import _resources_from_dump
dump = {
+177
View File
@@ -0,0 +1,177 @@
"""Unit tests for the microwave-family capabilities (issue #121/#66 split
into their own device type instead of being folded into oven.py)."""
from custom_components.localthings.registry.by_type import for_device_by_model
from custom_components.localthings.registry.capabilities import microwave
from custom_components.localthings.registry.discovery import discover
# ---------------------------------------------------------------------------
# Device-type detection + full-dump coverage
# ---------------------------------------------------------------------------
def test_microwave_fixture_resolves_and_has_no_unbound_hrefs():
from tests.conftest import _load_device
resources = _load_device('microwave_mw7300b')
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
assert reg.name == 'microwave'
unbound = []
discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
assert unbound == []
def test_microwave_hood_fan_fixture_resolves_and_has_no_unbound_hrefs():
"""Issues #137/#142: `/hood/fanspeed/vs/0` (the combi unit's built-in
vent fan) was previously unbound on this family."""
from tests.conftest import _load_device
resources = _load_device('microwave_me7500d')
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
assert reg.name == 'microwave'
unbound = []
discover(resources, reg.capabilities, reg.pattern_capabilities, log=unbound.append)
assert unbound == []
# ---------------------------------------------------------------------------
# MICROWAVE_SETPOINT — NumberDesc with RMW write semantics
# ---------------------------------------------------------------------------
def test_microwave_setpoint_write_is_read_modify_write():
desc = microwave.MICROWAVE_SETPOINT.entities[0]
rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.desired': '0'}]}
path, body = desc.write_fn(180, rep)
assert path == ['temperatures', 'vs', '0']
assert body['x.com.samsung.da.items'][0]['x.com.samsung.da.desired'] == '180'
def test_microwave_setpoint_rmw_preserves_other_item_fields():
desc = microwave.MICROWAVE_SETPOINT.entities[0]
rep = {'x.com.samsung.da.items': [{
'x.com.samsung.da.current': '150',
'x.com.samsung.da.desired': '150',
}]}
path, body = desc.write_fn(180, rep)
item = body['x.com.samsung.da.items'][0]
assert item['x.com.samsung.da.desired'] == '180'
assert item['x.com.samsung.da.current'] == '150'
def test_microwave_setpoint_clamps_to_step():
desc = microwave.MICROWAVE_SETPOINT.entities[0]
rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.desired': '0'}]}
_, body = desc.write_fn(182, rep) # nearest 5 = 180
assert body['x.com.samsung.da.items'][0]['x.com.samsung.da.desired'] == '180'
def test_microwave_setpoint_rejects_out_of_range():
desc = microwave.MICROWAVE_SETPOINT.entities[0]
rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.desired': '100'}]}
assert desc.write_fn(20, rep) is None # below min (40)
assert desc.write_fn(210, rep) is None # above max (200)
def test_microwave_setpoint_rejects_missing_items():
desc = microwave.MICROWAVE_SETPOINT.entities[0]
assert desc.write_fn(180, {}) is None
def test_microwave_setpoint_exists_only_for_celsius():
"""No Fahrenheit dump exists for this family (unlike oven.py's, verified
against issue #44) -- the writable setpoint stays hidden rather than
showing unverified bounds under the wrong unit."""
desc = microwave.MICROWAVE_SETPOINT.entities[0]
celsius_rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.unit': 'Celsius'}]}
fahrenheit_rep = {'x.com.samsung.da.items': [{'x.com.samsung.da.unit': 'Fahrenheit'}]}
assert desc.exists_fn(celsius_rep, {}) is True
assert desc.exists_fn(fahrenheit_rep, {}) is False
# ---------------------------------------------------------------------------
# MICROWAVE_CAVITY — power_level sensor
# ---------------------------------------------------------------------------
def test_power_level_parses_watt_suffix():
"""Issue #121's combi dump reports e.g. '0W'."""
desc = next(e for e in microwave.MICROWAVE_CAVITY.entities if e.key == 'power_level')
assert desc.value_fn('900W') == 900
def test_power_level_parses_bare_number():
"""Issue #137's plain microwave reports the bare number, no 'W' suffix."""
desc = next(e for e in microwave.MICROWAVE_CAVITY.entities if e.key == 'power_level')
assert desc.value_fn('0') == 0
def test_power_level_handles_missing_value():
desc = next(e for e in microwave.MICROWAVE_CAVITY.entities if e.key == 'power_level')
assert desc.value_fn(None) is None
# ---------------------------------------------------------------------------
# MICROWAVE_MODE — SelectDesc with non-empty, family-specific options
# ---------------------------------------------------------------------------
def test_microwave_mode_options_nonempty():
desc = microwave.MICROWAVE_MODE.entities[0]
assert len(desc.options) > 0
assert 'MicroWave' in desc.options
assert 'AirFryer' in desc.options # distinct spelling from oven.py's 'AirFry'
def test_microwave_mode_write_round_trips():
desc = microwave.MICROWAVE_MODE.entities[0]
path, body = desc.write_fn('MicroWave', {})
assert path == ['mode', 'vs', '0']
assert body['x.com.samsung.da.modes'] == ['MicroWave']
def test_microwave_mode_rejects_unknown():
desc = microwave.MICROWAVE_MODE.entities[0]
assert desc.write_fn('SpaghettiMode', {}) is None
# ---------------------------------------------------------------------------
# MICROWAVE_MODE — lamp/sound options-array writes
# ---------------------------------------------------------------------------
def test_sound_write_is_single_token():
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'sound')
rep = {'x.com.samsung.da.options': ['Sound_On']}
path, body = desc.write_fn('Off', rep)
assert path == ['mode', 'vs', '0']
assert body == {'x.com.samsung.da.options': ['Sound_Off']}
def test_lamp_gated_absent_when_no_lamp_option():
"""Issue #121's combi dump has no 'Lamp_*' token at all -- unlike
oven.py's lamp switch (assumed universal), this one self-gates off."""
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'lamp')
rep = {'x.com.samsung.da.options': ['DeviceType_MW7300B-/EU1', 'Sound_Off']}
assert desc.exists_fn(rep, {}) is False
def test_lamp_gated_present_when_lamp_option_reported():
"""Issue #137's plain microwave reports 'Lamp_Off'."""
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'lamp')
rep = {'x.com.samsung.da.options': ['Lamp_Off', 'Sound_On']}
assert desc.exists_fn(rep, {}) is True
def test_lamp_write_is_single_token():
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'lamp')
rep = {'x.com.samsung.da.options': ['Lamp_Off']}
path, body = desc.write_fn('On', rep)
assert path == ['mode', 'vs', '0']
assert body == {'x.com.samsung.da.options': ['Lamp_On']}
def test_lamp_write_requires_existing_options():
desc = next(e for e in microwave.MICROWAVE_MODE.entities if e.key == 'lamp')
assert desc.write_fn('On', {}) is None
+18
View File
@@ -61,6 +61,8 @@ def test_range_hood_fixture_values():
assert state['periodic_air_sensing'] is False
assert state['air_sensing_state'] == 'NonProcessing'
assert state['last_air_sensing_level'] == 'Kr2'
assert state['after_run_active'] is False
assert state['after_run_progress'] == 0
def test_one_composite_fan_is_bound():
@@ -114,3 +116,19 @@ def test_lamp_write_contract():
['hood', 'lamp', 'vs', '0'], {'x.com.samsung.lamp.current': '2'},
)
assert brightness.write_fn('Unsupported', rep) is None
def test_after_run_cancel_write_contract():
"""issue #147: /afterrun/vs/0 was previously unbound. runningCancel's
only observed value is the command name itself, so cancel is modeled as
a ButtonDesc that writes that value back."""
active, progress, cancel = range_hood.AFTER_RUN.entities
assert cancel.write_fn('Cancel', {}) == (
['afterrun', 'vs', '0'], {'x.com.samsung.da.runningCancel': 'Cancel'},
)
def test_after_run_active_reads_on_off():
active, progress, cancel = range_hood.AFTER_RUN.entities
assert active.value_fn('On') is True
assert active.value_fn('Off') is False
+136 -4
View File
@@ -1,7 +1,7 @@
"""HA fan-entity mapping tests for the range hood."""
from custom_components.localthings.fan import LocalThingsRangeHoodFan
from custom_components.localthings.registry.by_type import range_hood
from custom_components.localthings.registry.by_type import microwave, range_hood
from custom_components.localthings.registry.discovery import discover
from custom_components.localthings.registry.entities import FanDesc
from tests.conftest import _load_device
@@ -23,11 +23,11 @@ class _FakeCoordinator:
self.commands.append((bound, payload))
def _entity(resources, coordinator=None):
def _entity(resources, coordinator=None, registry=range_hood.REGISTRY):
bound = discover(
resources,
range_hood.REGISTRY.capabilities,
range_hood.REGISTRY.pattern_capabilities,
registry.capabilities,
registry.pattern_capabilities,
)
fan_bound = next(item for item in bound if isinstance(item.desc, FanDesc))
return LocalThingsRangeHoodFan(
@@ -35,6 +35,10 @@ def _entity(resources, coordinator=None):
)
def _microwave_entity(resources, coordinator=None):
return _entity(resources, coordinator, registry=microwave.REGISTRY)
def test_power_off_maps_to_zero_percent_and_four_retained_speeds():
entity = _entity(_load_device('range_hood'))
assert entity.is_on is False
@@ -86,3 +90,131 @@ async def test_power_write_falls_back_to_vendor_resource():
await entity.async_turn_off()
assert coordinator.commands[-1][1] == ('power', False, '/power/vs/0')
# ---------------------------------------------------------------------------
# Microwave built-in vent fan (issues #137/#142): reuses HOOD_FAN, but this
# board has no sibling /power/0 or /power/vs/0 resource -- fan speed 0 is
# itself the off state.
# ---------------------------------------------------------------------------
def test_standalone_hood_has_separate_power():
"""Explicit converse of the microwave case below: guards the
discriminator itself, not just its downstream effects, so a future
change to it fails loudly here instead of only via behavioral drift."""
entity = _entity(_load_device('range_hood'))
assert entity._has_separate_power() is True
assert entity._speed_zero_is_off() is False
def test_microwave_vent_fan_has_no_separate_power_resource():
resources = _load_device('microwave_me7500d')
assert '/power/0' not in resources
assert '/power/vs/0' not in resources
entity = _microwave_entity(resources)
assert entity._has_separate_power() is False
assert entity._speed_zero_is_off() is True
async def test_combi_microwave_with_cavity_power_still_treats_zero_speed_as_fan_off():
"""A combi over-the-range microwave can report a /power/0 resource for
the cavity while the vent fan still has no power resource of its own
(settableMinFanSpeed '0' -- same board shape as microwave_me7500d).
_speed_zero_is_off must key off the hood resource itself, not merely
"some power resource exists on this device", so turning the fan off
writes fan speed rather than the shared cavity power resource."""
resources = _load_device('microwave_me7500d')
resources['/power/0'] = {'value': True}
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.fanSpeed'] = '2'
coordinator = _FakeCoordinator(resources)
entity = _microwave_entity(resources, coordinator)
assert entity._has_separate_power() is True
assert entity._speed_zero_is_off() is True
await entity.async_turn_off()
assert coordinator.commands[-1][1] == ('speed', '0')
def test_microwave_vent_fan_off_state_excludes_zero_from_speed_codes():
"""supportedFanSpeed reports ['0'..'4'] with 0 meaning off -- unlike the
standalone hood's codes, which never include an off entry."""
resources = _load_device('microwave_me7500d')
entity = _microwave_entity(resources)
assert entity.is_on is False
assert entity.percentage == 0
assert entity.speed_count == 4 # ['1', '2', '3', '4'], '0' excluded
def test_microwave_vent_fan_nonzero_speed_reads_as_on():
resources = _load_device('microwave_me7500d')
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.fanSpeed'] = '2'
entity = _microwave_entity(resources)
assert entity.is_on is True
assert entity.percentage == 50 # 2nd of ['1', '2', '3', '4']
async def test_microwave_vent_fan_turn_off_writes_zero_speed_not_power():
resources = _load_device('microwave_me7500d')
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.fanSpeed'] = '2'
coordinator = _FakeCoordinator(resources)
entity = _microwave_entity(resources, coordinator)
await entity.async_turn_off()
assert coordinator.commands[-1][1] == ('speed', '0')
async def test_microwave_vent_fan_turn_on_without_percentage_picks_lowest_speed():
resources = _load_device('microwave_me7500d')
coordinator = _FakeCoordinator(resources)
entity = _microwave_entity(resources, coordinator)
await entity.async_turn_on()
assert coordinator.commands[-1][1] == ('speed', '1')
async def test_microwave_vent_fan_set_percentage_writes_speed_only():
resources = _load_device('microwave_me7500d')
coordinator = _FakeCoordinator(resources)
entity = _microwave_entity(resources, coordinator)
await entity.async_set_percentage(100)
assert coordinator.commands == [(entity._bound, ('speed', '4'))]
async def test_microwave_vent_fan_turn_on_with_percentage_writes_speed_directly():
resources = _load_device('microwave_me7500d')
coordinator = _FakeCoordinator(resources)
entity = _microwave_entity(resources, coordinator)
await entity.async_turn_on(percentage=75)
assert coordinator.commands == [(entity._bound, ('speed', '3'))]
async def test_microwave_vent_fan_turn_on_without_percentage_when_already_on_is_a_noop():
"""A scene or automation calling fan.turn_on on an already-running vent
fan must not reset it to the lowest speed."""
resources = _load_device('microwave_me7500d')
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.fanSpeed'] = '3'
coordinator = _FakeCoordinator(resources)
entity = _microwave_entity(resources, coordinator)
await entity.async_turn_on()
assert coordinator.commands == []
async def test_microwave_vent_fan_set_percentage_zero_turns_off():
resources = _load_device('microwave_me7500d')
resources['/hood/fanspeed/vs/0']['x.com.samsung.da.hood.fanSpeed'] = '2'
coordinator = _FakeCoordinator(resources)
entity = _microwave_entity(resources, coordinator)
await entity.async_set_percentage(0)
assert coordinator.commands[-1][1] == ('speed', '0')
+28 -2
View File
@@ -126,8 +126,10 @@ def test_no_catalog_carries_unresolved_core_references():
# The hood fan is its device's primary feature: fan.py sets _attr_name = None
# so it presents as the device itself, and never reads a catalog name.
UNNAMED_DESCRIPTORS = {("fan", "fan")}
# so it presents as the device itself, and never reads a catalog name. Same
# for the ARTIK051 air-purifier's airflow_fan (issue #56) -- ordered speed
# levels, no presets, same _attr_name = None treatment.
UNNAMED_DESCRIPTORS = {("fan", "fan"), ("fan", "airflow_fan")}
def test_every_descriptor_has_an_entity_catalog_entry():
@@ -208,3 +210,27 @@ def test_every_ac_convenient_mode_code_has_a_preset_label():
missing.append((path.name, code))
assert missing == []
def test_every_kimchi_zone_supportmode_code_has_a_state_label():
"""Same guard as the AC preset one above, for KIMCHI_ZONE's
kimchi_zone_mode select (fridge.py, issue #26): the write path resolved
from options_field is fully dynamic too, so an unlabelled supportMode
code across any /status/kimchi/<slot>/vs/0 resource would silently
render as its raw device token instead of the translated state.
"""
state_labels = set(
_load("en")["entity"]["select"]["kimchi_zone_mode"]["state"]
)
fixtures_dir = Path(__file__).parent / "fixtures"
missing = []
for path in sorted(fixtures_dir.glob("*_device.json")):
dump = json.loads(path.read_text())
for item in dump.get("device0", []):
href = item.get("href", "")
if not (href.startswith("/status/kimchi/") and href.endswith("/vs/0")):
continue
for code in item["rep"].get("x.com.samsung.da.supportMode", []):
if code.lower() not in state_labels:
missing.append((path.name, href, code))
assert missing == []
+86 -6
View File
@@ -169,6 +169,14 @@ def _desc_coffee(key):
return next(b.desc for b in bound if b.desc.key == key)
def _desc_coffee_by_href(key, href):
"""Like _desc_coffee, but disambiguates descriptors that share a key
across hrefs (hotwater_lock: LOCK's hotwaterLock field and
FAVORITE_HOTWATER's switchHotwater fallback, issue #144)."""
bound, _ = _bound_coffee()
return next(b.desc for b in bound if b.desc.key == key and b.href == href)
def test_coffee_variant_no_unbound_hrefs():
"""Every resource in the issue #107 dump binds or is covered, including
the four coffee-recipe hrefs not present in issue #90's dump."""
@@ -181,7 +189,7 @@ def test_coffee_variant_no_unbound_hrefs():
def test_coffee_variant_expected_state_keys_present():
state = _state_coffee()
for key in ('favorite_coffee_enabled', 'coffee_brew_status',
'favorite_hotwater_enabled', 'favorite_hotwater_temperature'):
'hotwater_lock', 'favorite_hotwater_temperature'):
assert key in state, key
@@ -193,12 +201,84 @@ def test_favorite_coffee_write_contract():
['favorite', 'coffee', 'vs', '0'], {'favorite.activate': 'Off'})
def test_favorite_hotwater_write_contract():
enabled = _desc_coffee('favorite_hotwater_enabled')
assert enabled.write_fn('On', {}) == (
['favorite', 'hotwater', 'vs', '0'], {'x.com.samsung.da.switchHotwater': 'Unlocked'})
assert enabled.write_fn('Off', {}) == (
def test_favorite_hotwater_switch_is_a_lock_not_an_enable_flag():
"""issue #144: switchHotwater's value domain is Locked/Unlocked, not an
enable flag, and it's misspelled as "Favorite hot water" -- it's the same
hot-water lock as LOCK.hotwater_lock, just surfaced through this href on
boards (like this fixture's) that don't populate /status/lock/vs/0's
hotwaterLock field."""
lock = _desc_coffee_by_href('hotwater_lock', '/favorite/hotwater/vs/0')
assert lock.write_fn('On', {}) == (
['favorite', 'hotwater', 'vs', '0'], {'x.com.samsung.da.switchHotwater': 'Locked'})
assert lock.write_fn('Off', {}) == (
['favorite', 'hotwater', 'vs', '0'], {'x.com.samsung.da.switchHotwater': 'Unlocked'})
assert lock.value_fn('Unlocked') is False
assert lock.value_fn('Locked') is True
def test_favorite_hotwater_lock_wins_in_flattened_state():
"""adapter.flatten() -- the actual source of coordinator.data every
switch's is_on reads -- only honours exists_fn, never entity.py's
implicit own-field-presence default. So it's not enough for the
*registered* entity to resolve correctly (test_expected_state_keys_present
territory); the shared 'hotwater_lock' key in the flattened dict itself
must reflect the live switchHotwater value, not a stale phantom from
LOCK's ungated hotwaterLock read (issue #144). This fixture's
switchHotwater reads 'Unlocked'; without exists_fn on *both* sides of the
pair, LOCK's descriptor computes None != 'Unlocked' == True regardless,
and flatten() would pick whichever of the two entities happens to be
processed last."""
state = _state_coffee()
assert state['hotwater_lock'] is False
def test_exactly_one_hotwater_lock_descriptor_exists_per_resource_state():
"""Both LOCK.hotwater_lock and FAVORITE_HOTWATER's switchHotwater
fallback are always bound on this fixture (their hrefs are both always
present) -- discrimination happens entirely in exists_fn. Exactly one of
the two must ever pass, regardless of iteration order, or two switch
entities would be registered with the same unique_id."""
bound, resources = _bound_coffee()
candidates = [b for b in bound if b.desc.key == 'hotwater_lock']
assert len(candidates) == 2
included = [b for b in candidates
if b.desc.exists_fn(resources.get(b.href) or {}, resources)]
assert len(included) == 1
assert included[0].href == '/favorite/hotwater/vs/0'
def test_hotwater_lock_fallback_gating_across_status_lock_states():
"""The fallback (FAVORITE_HOTWATER's switchHotwater descriptor) must
activate only once /status/lock/vs/0 is confirmed to lack hotwaterLock --
never while that resource is an unfetched stub ({}), and never when it
does carry the field. LOCK's own descriptor is the mirror image."""
fallback = _desc_coffee_by_href('hotwater_lock', '/favorite/hotwater/vs/0')
primary = _desc_coffee_by_href('hotwater_lock', '/status/lock/vs/0')
own_rep = {'x.com.samsung.da.switchHotwater': 'Unlocked'}
# /status/lock/vs/0 absent entirely -- device genuinely lacks it.
assert fallback.exists_fn(own_rep, {}) is True
# /status/lock/vs/0 present but not yet fetched (a stub): outcome
# pending, so the fallback must defer to LOCK rather than assume absence.
stub_resources = {'/status/lock/vs/0': {}}
assert fallback.exists_fn(own_rep, stub_resources) is False
assert primary.exists_fn({}, stub_resources) is True
# /status/lock/vs/0 fetched and confirmed to lack hotwaterLock (this
# fixture's actual shape) -- the fallback wins.
absent_resources = {'/status/lock/vs/0': {'x.com.samsung.da.coldwaterLock': 'Unlocked'}}
assert fallback.exists_fn(own_rep, absent_resources) is True
assert primary.exists_fn(absent_resources['/status/lock/vs/0'], absent_resources) is False
# /status/lock/vs/0 fetched and does carry hotwaterLock -- primary wins.
present_resources = {'/status/lock/vs/0': {'x.com.samsung.da.hotwaterLock': 'Unlocked'}}
assert fallback.exists_fn(own_rep, present_resources) is False
assert primary.exists_fn(present_resources['/status/lock/vs/0'], present_resources) is True
# The fallback also re-asserts its own field, since it no longer gets
# that check for free once it shares LOCK's key (issue #144 review).
assert fallback.exists_fn({}, {}) is False
def test_favorite_hotwater_temperature_options_come_from_live_supported_list():