diff --git a/broadlink/purifier.py b/broadlink/purifier.py index f7e5721..f0c3db5 100644 --- a/broadlink/purifier.py +++ b/broadlink/purifier.py @@ -25,8 +25,12 @@ class lifaair(Device): TYPE = "LIFAAIR" - # Fan state byte values reported by the device. 0x01 means the main unit - # is offline / unpaired; temperature and humidity are then unavailable. + # Fan state byte (payload[55]). 0x01 is the purifier offline or unpaired. + # On this unit (fw 10026) that is flags 0xC0 and temperature/humidity + # bytes 00 00 00. Another LM05 instead kept raw 25 and 45 (decoded + # 2.5 deg C / 45 %) with no purifier paired (mjg59/python-broadlink#807); + # that is not special-cased. A restart or re-pair returns the purifier + # itself to AUTO. FAN_STATE_TO_MODE = { 0x81: FanMode.OFF, 0xA5: FanMode.AUTO, @@ -55,24 +59,39 @@ class _Action(enum.IntEnum): } def set_fan_mode(self, fan_mode: FanMode) -> dict: - """Set mode of the fan. Returns updated state.""" - if fan_mode == FanMode.MANUAL: - return self.set_fan_speed(50) - + """Set the fan mode. Returns the decoded response. + + In OFF only OFF and AUTO are accepted; NIGHT, TURBO and + ANTI_ALLERGY raise the device error -5 (reported as StorageError) + and nothing changes. AUTO from OFF reports speed 30 and may drop + to 0 a few seconds later. NIGHT starts at 10, TURBO at 121, + ANTI_ALLERGY at 60. There is no MANUAL command; use set_fan_speed(). + While the purifier main unit is offline the station rejects mode + commands with the device error -5 (StorageError); the mode is not + applied after the unit reconnects either. + """ action_arg = self.FAN_MODE_TO_ACTION_ARG.get(fan_mode) - if action_arg is not None: - data = self._send( - self._Operation.SET_STATE, self._Action.SET_FAN_MODE, action_arg - ) - return self._decode_state(data) - - return self.get_state() + if action_arg is None: + raise ValueError(f"{fan_mode!r} has no mode command") + data = self._send( + self._Operation.SET_STATE, self._Action.SET_FAN_MODE, action_arg + ) + return self._decode_state(data) def set_fan_speed(self, fan_speed: int) -> dict: - """Set fan speed (0-121). Returns updated state. - - Note that fan mode will be changed to MANUAL by the device. + """Set fan speed (0-121). Returns the decoded response. + + Any mode except OFF reports MANUAL with the new speed (0 included). + In OFF the speed is applied and the fan spins, but the device keeps + reporting OFF. While the purifier main unit is offline the station + answers with success but returns the offline state (purifier_online + False) and the speed is not applied, neither then nor after the unit + reconnects. """ + if not isinstance(fan_speed, int) or isinstance(fan_speed, bool): + raise ValueError("fan_speed must be an int in 0..121") + if not 0 <= fan_speed <= 121: + raise ValueError("fan_speed must be an int in 0..121") data = self._send( self._Operation.SET_STATE, self._Action.SET_FAN_SPEED, fan_speed ) @@ -81,9 +100,14 @@ def set_fan_speed(self, fan_speed: int) -> dict: def get_state(self) -> dict: """Return the current state of the purifier as a dict. - The smart remote contains CO2, TVOC, formaldehyde and PM sensors. - Temperature, humidity and fan state are fetched from the main unit, - which can be offline (unplugged or unpaired); those keys are then None. + CO2, TVOC, formaldehyde and PM come from the station. Temperature, + humidity, fan mode and fan speed come from the purifier. They are + None when it is offline (purifier_online is False); the speed byte + is then 0, a placeholder. Temperature and humidity are also None + when bytes 27-29 are placeholder zeros on the first poll after it + reconnects. Fan mode and fan speed are otherwise the values the + device reports, including AUTO at speed 0 and OFF with a non-zero + speed. Format:: @@ -93,11 +117,12 @@ def get_state(self) -> dict: "co2": 425, # int, ppm "formaldehyde": 0.03, # float, mg/m3 "tvoc": 150, # int, ug/m3 - "pm1": 5, # int, ug/m3 (PM1.0) - "pm2_5": 7, # int, ug/m3 (PM2.5) - "pm10": 9, # int, ug/m3 (PM10) - "fan_mode": FanMode.AUTO, # FanMode enum, or None - "fan_speed": 50, # int, 0-121 + "pm1": 5, # int, ug/m3 + "pm2_5": 7, # int, ug/m3 + "pm10": 9, # int, ug/m3 + "fan_mode": FanMode.AUTO, # FanMode, or None + "fan_speed": 50, # int 0-121, or None + "purifier_online": True, # bool, bit 7 of byte 55 } """ data = self._send(self._Operation.GET_STATE) @@ -105,11 +130,24 @@ def get_state(self) -> dict: def _decode_state(self, data: bytes) -> dict: raw = self._decode_state_raw(data) + # Bit 7 of the fan-state byte is set whenever the purifier is online. + purifier_online = bool(raw["fan_state"] & 0x80) fan_mode = self._decode_fan_mode(raw["fan_state"], raw["fan_flags"]) - is_offline = fan_mode is None + # Bytes 27-29 are 00 00 00 when the purifier has no climate reading: + # it is offline, or this is the first poll after it reconnects + # (fan_state is already online). Not a real 0.0 deg C / 0 %. + if not purifier_online or (raw["temperature"] == 0 and raw["humidity"] == 0): + temperature = None + humidity = None + else: + temperature = raw["temperature"] / 10.0 + humidity = raw["humidity"] + # Mode and speed are reported independently: AUTO can report speed 0 + # (seen with clean air), and OFF reported speed 50 after set_fan_speed(50). + # Offline frames carry speed 0 as a placeholder. return { - "temperature": None if is_offline else raw["temperature"] / 10.0, - "humidity": None if is_offline else raw["humidity"], + "temperature": temperature, + "humidity": humidity, "co2": raw["co2"], "formaldehyde": raw["formaldehyde"] / 100.0, "tvoc": raw["tvoc"] * 10, @@ -117,11 +155,16 @@ def _decode_state(self, data: bytes) -> dict: "pm2_5": raw["pm2_5"], "pm10": raw["pm10"], "fan_mode": fan_mode, - "fan_speed": raw["fan_speed"], + "fan_speed": raw["fan_speed"] if purifier_online else None, + "purifier_online": purifier_online, } def _decode_state_raw(self, data: bytes) -> dict: # PM field order verified against LAM01/LM05 display (PM1 <= PM2.5 <= PM10). + # Byte 30 is always 0x02. Meaning unknown; not decoded. + # CO2 reads exactly 400 for up to ~10 s after the station starts (5/5) + # and was also seen once when the main unit dropped out. 400 ppm can + # be real, so it is kept. return { "temperature": data[27] + 256 * data[28], "humidity": data[29], @@ -137,13 +180,15 @@ def _decode_state_raw(self, data: bytes) -> dict: } def _decode_fan_mode(self, fan_state: int, fan_flags: int): - # Check offline before anti-allergy: unpaired units can clear bit 0x40 - # while still reporting fan_state 0x01 and stale temp/humidity defaults. - if fan_state == 0x01: + # Bit 7 clear: purifier offline or unpaired (observed as 0x01, flags 0xC0). + if fan_state & 0x80 == 0: return None + # Anti-allergy is 0x85 with bit 0x40 of the flags clear. if fan_flags & 0x40 == 0: return FanMode.ANTI_ALLERGY - return self.FAN_STATE_TO_MODE.get(fan_state, FanMode.UNKNOWN) + # Mode arguments 9 and 10 clear and set bit 0 of this byte without + # changing mode or speed; meaning unknown. + return self.FAN_STATE_TO_MODE.get(fan_state | 0x01, FanMode.UNKNOWN) def _send(self, operation: int, action: int = 0, action_arg: int = 0) -> bytes: """Send a command to the device.""" @@ -166,5 +211,6 @@ def _send(self, operation: int, action: int = 0, action_arg: int = 0) -> bytes: packet[0x01] = packet_len >> 8 resp = self.send_packet(0x6A, packet) + # Seen returning -5 sporadically during power-cycling and pairing; cause unknown. e.check_error(resp[0x22:0x24]) return self.decrypt(resp[0x38:]) diff --git a/cli/test_lifaair b/cli/test_lifaair index 0abfb1b..a5c8ab7 100755 --- a/cli/test_lifaair +++ b/cli/test_lifaair @@ -8,9 +8,10 @@ from broadlink import FanMode, lifaair def print_state(state: dict): temperature = state["temperature"] humidity = state["humidity"] + fan_speed = state["fan_speed"] print( "-> Temperature=%s Humidity=%s CO2=%4dppm HCHO=%4.2fmg/m3 " - "TVOC=%4dug/m3 PM1=%2d PM2.5=%2d PM10=%2d FanSpeed=%d (%s)" + "TVOC=%4dug/m3 PM1=%2d PM2.5=%2d PM10=%2d FanSpeed=%s (%s) online=%s" % ( "%2.1fC" % temperature if temperature is not None else "-----", "%2d%%" % humidity if humidity is not None else "---", @@ -20,8 +21,9 @@ def print_state(state: dict): state["pm1"], state["pm2_5"], state["pm10"], - state["fan_speed"], + "%d" % fan_speed if fan_speed is not None else "---", state["fan_mode"], + state["purifier_online"], ) ) @@ -40,8 +42,12 @@ print(dev.get_fwversion()) print("Getting state...") print_state(dev.get_state()) +print( + "While OFF, modes other than OFF and AUTO are rejected with " + "error -5 and nothing changes." +) for mode in FanMode: - if mode == FanMode.UNKNOWN: + if mode in (FanMode.MANUAL, FanMode.UNKNOWN): continue print("Setting fan mode to %s" % mode) print_state(dev.set_fan_mode(mode)) diff --git a/tests/test_lifaair.py b/tests/test_lifaair.py new file mode 100644 index 0000000..f9c42ab --- /dev/null +++ b/tests/test_lifaair.py @@ -0,0 +1,349 @@ +"""Decode LIFAair LM05 frames captured from a real device. + +Bytes are payload offsets 27..57 from firmware 10026, polled on 2026-11-17. +""" + +import unittest + +from broadlink.exceptions import StorageError +from broadlink.purifier import FanMode, lifaair + + +def payload(raw_hex): + """Return a GET_STATE body with captured bytes placed at offset 27.""" + data = bytearray(58) + data[27:] = bytes.fromhex(raw_hex) + return bytes(data) + + +def device(): + """Return a lifaair instance that does not touch the network.""" + return lifaair(("127.0.0.1", 80), b"\x00" * 6, 0x4EC2) + + +# Station up, purifier not yet online. 14:31:15. +OFFLINE_BOOT = ( + "00 00 00 02 90 01 00 00 09 00 02 00 02 00 03 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 01 00 c0" +) +# Unpaired after the pairing window. 15:11:10. +OFFLINE_UNPAIRED = ( + "00 00 00 02 ab 03 00 00 09 00 01 00 00 00 01 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 01 00 c0" +) +# First online frame after each reconnection: fan_state 0xA5, climate 00 00 00. +RECONNECT_ZEROS = ( + ( + "00 00 00 02 b5 03 00 00 0a 00 01 00 00 00 02 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 a5 2b c0", + 949, + 43, + ), + ( + "00 00 00 02 ee 03 00 00 0a 00 00 00 00 00 01 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 a5 2b c0", + 1006, + 43, + ), + ( + "00 00 00 02 90 01 00 00 0a 00 00 00 01 00 02 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 a5 14 c0", + 400, + 20, + ), + ( + "00 00 00 02 a8 03 00 00 0a 00 00 00 00 00 01 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 a5 2b c0", + 936, + 43, + ), +) +# Next frame after the 14:44:57 placeholder. 14:45:01. +AFTER_RECONNECT = ( + "08 01 16 02 be 03 00 00 09 00 01 00 00 00 01 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 a5 2b c0" +) +# CO2 still 400, climate already valid. 15:01:50. +CO2_WARMUP = ( + "0a 01 16 02 90 01 00 00 09 00 00 00 02 00 03 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 a5 14 c0" +) +# Spray peak. 14:33:05. +SPRAY = ( + "0a 01 16 02 9f 03 00 00 09 00 0c 00 27 00 80 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 a5 0d c0" +) + + +class LifaairDecodeTest(unittest.TestCase): + """State decoded from captured frames.""" + + def decode(self, raw_hex): + """Decode one captured frame.""" + return device()._decode_state(payload(raw_hex)) + + def test_offline_purifier_climate_and_mode_are_none(self): + """Unplugged and unpaired both report 0x01 with zero climate bytes.""" + for raw_hex, co2 in ((OFFLINE_BOOT, 400), (OFFLINE_UNPAIRED, 939)): + state = self.decode(raw_hex) + self.assertIsNone(state["temperature"]) + self.assertIsNone(state["humidity"]) + self.assertIsNone(state["fan_mode"]) + self.assertIsNone(state["fan_speed"]) + self.assertFalse(state["purifier_online"]) + self.assertEqual(state["co2"], co2) + self.assertEqual(state["formaldehyde"], 0.0) + self.assertIsNotNone(state["pm2_5"]) + + def test_reconnect_placeholder_zeros_are_none(self): + """Online fan_state with 00 00 00 climate is not 0.0 deg C / 0 %.""" + for raw_hex, co2, speed in RECONNECT_ZEROS: + state = self.decode(raw_hex) + self.assertIsNone(state["temperature"]) + self.assertIsNone(state["humidity"]) + self.assertEqual(state["fan_mode"], FanMode.AUTO) + self.assertEqual(state["fan_speed"], speed) + self.assertTrue(state["purifier_online"]) + self.assertEqual(state["co2"], co2) + self.assertEqual(state["formaldehyde"], 0.0) + + def test_real_climate_after_placeholder(self): + """The frame after the placeholder carries the real reading.""" + state = self.decode(AFTER_RECONNECT) + self.assertEqual(state["temperature"], 26.4) + self.assertEqual(state["humidity"], 22) + self.assertEqual(state["co2"], 958) + self.assertEqual(state["fan_mode"], FanMode.AUTO) + self.assertEqual(state["fan_speed"], 43) + self.assertTrue(state["purifier_online"]) + + def test_co2_warmup_placeholder_is_kept(self): + """400 ppm has no separate marker, so it is returned as 400.""" + state = self.decode(CO2_WARMUP) + self.assertEqual(state["co2"], 400) + self.assertEqual(state["temperature"], 26.6) + self.assertEqual(state["humidity"], 22) + self.assertEqual(state["tvoc"], 90) + self.assertEqual(state["pm1"], 0) + self.assertEqual(state["pm2_5"], 2) + self.assertEqual(state["pm10"], 3) + self.assertEqual(state["fan_mode"], FanMode.AUTO) + self.assertEqual(state["fan_speed"], 20) + self.assertTrue(state["purifier_online"]) + + def test_spray_frame_keeps_pm_order_and_zero_formaldehyde(self): + """PM offsets stay as verified, and a zero HCHO reading stays 0.0.""" + state = self.decode(SPRAY) + self.assertEqual(state["temperature"], 26.6) + self.assertEqual(state["humidity"], 22) + self.assertEqual(state["co2"], 927) + self.assertEqual(state["formaldehyde"], 0.0) + self.assertEqual(state["tvoc"], 90) + self.assertEqual(state["pm1"], 12) + self.assertEqual(state["pm2_5"], 39) + self.assertEqual(state["pm10"], 128) + self.assertEqual(state["fan_mode"], FanMode.AUTO) + self.assertEqual(state["fan_speed"], 13) + self.assertTrue(state["purifier_online"]) + + def test_fan_mode_and_speed_are_reported_independently(self): + """Reported mode and speed are not rewritten.""" + cases = ( + # AUTO speed 0, clean air. 14:46:10. + ( + "09 01 16 02 dc 03 00 00 0a 00 01 00 00 00 01 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 a5 00 c0", + FanMode.AUTO, + 0, + ), + # OFF reported speed 50 after set_fan_speed(50). 14:50:25. + ( + "0b 01 16 02 8f 03 00 00 0a 00 00 00 00 00 01 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 81 32 c0", + FanMode.OFF, + 50, + ), + # NIGHT. 14:50:48. + ( + "0b 01 16 02 8d 03 00 00 0a 00 01 00 00 00 01 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 95 0a c0", + FanMode.NIGHT, + 10, + ), + # TURBO. 14:50:58. + ( + "0b 01 16 02 8b 03 00 00 09 00 01 00 00 00 01 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 8d 79 c0", + FanMode.TURBO, + 121, + ), + # ANTI_ALLERGY is 0x85 with flags 0x80. 14:50:04. + ( + "0b 01 16 02 90 03 00 00 09 00 00 00 00 00 02 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 85 3c 80", + FanMode.ANTI_ALLERGY, + 60, + ), + # MANUAL reported at speed 0. 14:51:18. + ( + "0b 01 16 02 88 03 00 00 09 00 01 00 00 00 02 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 85 00 c0", + FanMode.MANUAL, + 0, + ), + # MANUAL speed 50. 14:51:28. + ( + "0b 01 16 02 89 03 00 00 0a 00 02 00 00 00 02 00 " + "00 00 00 00 00 00 00 00 00 00 00 00 85 32 c0", + FanMode.MANUAL, + 50, + ), + ) + for raw_hex, mode, speed in cases: + state = self.decode(raw_hex) + self.assertEqual(state["fan_mode"], mode) + self.assertEqual(state["fan_speed"], speed) + self.assertTrue(state["purifier_online"]) + self.assertIsNotNone(state["temperature"]) + self.assertEqual(state["humidity"], 22) + + +def response(fan, speed, flags): + """Return a state payload with a real climate reading and one fan triple.""" + data = bytearray(58) + data[27:30] = b"\x0b\x01\x16" # 26.7 C, 22 % + data[55] = fan + data[56] = speed + data[57] = flags + return bytes(data) + + +class LifaairCommandTest(unittest.TestCase): + """Setters send one encoded argument and decode that response.""" + + def setUp(self): + self.dev = device() + self.calls = [] + + def script(self, payload): + """Replace _send with a recorder that returns payload.""" + + def send(operation, action=0, action_arg=0): + self.calls.append((operation, action, action_arg)) + return payload + + self.dev._send = send + + def test_set_fan_mode_sends_one_mode_argument(self): + """Each mode command is one SET_FAN_MODE packet.""" + cases = ( + (FanMode.OFF, 1, 0x81, 0x00, 0xC0, FanMode.OFF, 0), + (FanMode.AUTO, 2, 0xA5, 0x1E, 0xC0, FanMode.AUTO, 30), + (FanMode.NIGHT, 6, 0x95, 0x0A, 0xC0, FanMode.NIGHT, 10), + (FanMode.TURBO, 7, 0x8D, 0x79, 0xC0, FanMode.TURBO, 121), + (FanMode.ANTI_ALLERGY, 11, 0x85, 0x3C, 0x80, FanMode.ANTI_ALLERGY, 60), + ) + for mode, arg, fan, speed, flags, expect_mode, expect_speed in cases: + self.calls.clear() + self.script(response(fan, speed, flags)) + state = self.dev.set_fan_mode(mode) + self.assertEqual( + self.calls, + [ + ( + lifaair._Operation.SET_STATE, + lifaair._Action.SET_FAN_MODE, + arg, + ) + ], + ) + self.assertEqual(state["fan_mode"], expect_mode) + self.assertEqual(state["fan_speed"], expect_speed) + self.assertTrue(state["purifier_online"]) + + def test_set_fan_mode_without_a_command_sends_nothing(self): + """MANUAL, UNKNOWN and None have no mode argument.""" + self.script(response(0x85, 50, 0xC0)) + for mode in (FanMode.MANUAL, FanMode.UNKNOWN, None): + with self.assertRaises(ValueError): + self.dev.set_fan_mode(mode) + self.assertEqual(self.calls, []) + + def test_set_fan_mode_device_error_is_not_retried(self): + """Error -5 from the device is StorageError, raised once.""" + + def send(operation, action=0, action_arg=0): + self.calls.append((operation, action, action_arg)) + raise StorageError(-5, "The device storage is full") + + self.dev._send = send + with self.assertRaises(StorageError): + self.dev.set_fan_mode(FanMode.TURBO) + self.assertEqual( + self.calls, + [ + ( + lifaair._Operation.SET_STATE, + lifaair._Action.SET_FAN_MODE, + 7, + ) + ], + ) + + def test_set_fan_speed_sends_one_speed_argument(self): + """Speed is one SET_FAN_SPEED packet, including 0 and OFF.""" + cases = ( + (70, 0x85, 0x46, 0xC0, FanMode.MANUAL, 70), + (0, 0x85, 0x00, 0xC0, FanMode.MANUAL, 0), + (121, 0x85, 0x79, 0xC0, FanMode.MANUAL, 121), + (50, 0x81, 0x32, 0xC0, FanMode.OFF, 50), + ) + for speed, fan, raw_speed, flags, mode, expect_speed in cases: + self.calls.clear() + self.script(response(fan, raw_speed, flags)) + state = self.dev.set_fan_speed(speed) + self.assertEqual( + self.calls, + [ + ( + lifaair._Operation.SET_STATE, + lifaair._Action.SET_FAN_SPEED, + speed, + ) + ], + ) + self.assertEqual(state["fan_mode"], mode) + self.assertEqual(state["fan_speed"], expect_speed) + self.assertTrue(state["purifier_online"]) + + def test_set_fan_speed_rejects_values_that_cannot_be_encoded(self): + """Only ints in 0..121 are sent.""" + self.script(response(0x85, 50, 0xC0)) + for speed in (-1, 122, True, "50"): + with self.assertRaises(ValueError): + self.dev.set_fan_speed(speed) + self.assertEqual(self.calls, []) + + +class LifaairBit0Test(unittest.TestCase): + """Bit 0 of the fan-state byte does not change the mode.""" + + def test_bit0_clear_decodes_as_the_same_mode(self): + """0x84, 0xA4 and 0x80 are MANUAL, AUTO and OFF.""" + cases = ( + (0x84, 0x32, 0xC0, FanMode.MANUAL, 50), + (0xA4, 0x1E, 0xC0, FanMode.AUTO, 30), + (0x80, 0x00, 0xC0, FanMode.OFF, 0), + ) + dev = device() + for fan, speed, flags, mode, expect_speed in cases: + state = dev._decode_state(response(fan, speed, flags)) + self.assertEqual(state["fan_mode"], mode) + self.assertEqual(state["fan_speed"], expect_speed) + self.assertTrue(state["purifier_online"]) + self.assertEqual(state["temperature"], 26.7) + self.assertEqual(state["humidity"], 22) + + +if __name__ == "__main__": + unittest.main()