From 5d561fbb0eef74a74521fc17a14a47e5027dc368 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 10:45:05 +0000 Subject: [PATCH 1/9] Add support for the LIFAair LM05 air purifier MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the lifaair class for the LM05 (0x4EC2). get_state decodes firmware 10026 frames. set_fan_mode and set_fan_speed each send one encoded argument and return the decoded response. Fan mode, speed, temperature and humidity are None when the purifier is offline. Tested on an LM05 with firmware 10026. Co-authored-by: Piotr Paczyński --- CHANGELOG.md | 12 ++ README.md | 16 ++ broadlink_async/__init__.py | 4 + broadlink_async/purifier.py | 221 +++++++++++++++++++++ cli/test_lifaair | 71 +++++++ tests/oracle/cases.py | 53 ++++++ tests/oracle/fixtures.json | 131 +++++++++++++ tests/test_lifaair.py | 371 ++++++++++++++++++++++++++++++++++++ tests/test_transport.py | 1 + 9 files changed, 880 insertions(+) create mode 100644 broadlink_async/purifier.py create mode 100644 cli/test_lifaair create mode 100644 tests/test_lifaair.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 07a6c45..6692387 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,18 @@ All notable changes to this project are recorded here. The format follows Keep a Changelog; versions follow Semantic Versioning. +## Unreleased + +### Added + +- The LIFAair LM05 air purifier (0x4EC2) is supported as `lifaair`: + station readings (CO2, TVOC, formaldehyde, PM) and the purifier's fan + mode, speed, temperature and humidity. Fan mode, speed, temperature + and humidity are `None` when the purifier is offline. `set_fan_mode` + and `set_fan_speed` each send one encoded argument and return the + decoded response. Tested on an LM05 with firmware 10026 + (pit3k/python-broadlink#1, mjg59/python-broadlink#807). + ## 1.3.0 - 2026-11-16 ### Added diff --git a/README.md b/README.md index 068a51a..ab20805 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ The following devices are supported: - **Curtain motors**: Dooya DT360E-45/20 - **Thermostats**: Hysen HY02/HY03 - **Hubs**: S3 +- **Air purifiers**: LIFAair LM05 ## Timing @@ -428,6 +429,21 @@ await devices[0].set_state(bulb_colormode=1) data = await device.check_sensors() ``` +## Air purifiers + +### Fetching purifier state +```python3 +from broadlink_async import FanMode + +data = await device.get_state() +``` + +### Controlling purifier fan +```python3 +await device.set_fan_mode(FanMode.TURBO) +await device.set_fan_speed(50) +``` + ## Hubs ### Discovering subdevices diff --git a/broadlink_async/__init__.py b/broadlink_async/__init__.py index 6c85a85..3efe045 100644 --- a/broadlink_async/__init__.py +++ b/broadlink_async/__init__.py @@ -11,6 +11,7 @@ from .device import Device, ping, scan, send_setup_packet from .hub import s3 from .light import fl, lb1, lb2 +from .purifier import FanMode, lifaair from .remote import rm, rm4, rm4mini, rm4pro, rm5plus, rmmini, rmminib, rmpro from .sensor import a1, a2 from .switch import bg1, ehc31, mp1, mp1s, sp1, sp2, sp2s, sp3, sp3s, sp4, sp4b @@ -226,6 +227,9 @@ ehc31: { 0x6480: ("EHC31", "BG Electrical"), }, + lifaair: { + 0x4EC2: ("LM05", "LIFAair"), + }, } diff --git a/broadlink_async/purifier.py b/broadlink_async/purifier.py new file mode 100644 index 0000000..5b2e7a5 --- /dev/null +++ b/broadlink_async/purifier.py @@ -0,0 +1,221 @@ +"""Support for air purifiers.""" + +import enum + +from . import exceptions as e +from .device import Device + + +@enum.unique +class FanMode(enum.IntEnum): + """Represents mode of the fan.""" + + OFF = 0 + AUTO = 1 + NIGHT = 2 + TURBO = 3 + ANTI_ALLERGY = 4 + MANUAL = 5 + + UNKNOWN = -1 + + +class lifaair(Device): + """Controls a Broadlink-based LIFAair air purifier / monitor. + + Product id 0x4EC2 is the LM05. The layout and the commands below were + checked on firmware 10026 (pit3k/python-broadlink#1, continuing + mjg59/python-broadlink#807). + """ + + TYPE = "LIFAAIR" + + # 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, + 0x95: FanMode.NIGHT, + 0x8D: FanMode.TURBO, + 0x85: FanMode.MANUAL, + 0x01: None, # main unit offline / unpaired + } + + @enum.unique + class _Operation(enum.IntEnum): + SET_STATE = 1 + GET_STATE = 2 + + @enum.unique + class _Action(enum.IntEnum): + SET_FAN_SPEED = 1 + SET_FAN_MODE = 2 + + FAN_MODE_TO_ACTION_ARG = { + FanMode.OFF: 1, + FanMode.AUTO: 2, + FanMode.NIGHT: 6, + FanMode.TURBO: 7, + FanMode.ANTI_ALLERGY: 11, + } + + async def set_fan_mode(self, fan_mode: FanMode) -> dict: + """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 None: + raise ValueError(f"{fan_mode!r} has no mode command") + data = await self._send( + self._Operation.SET_STATE, self._Action.SET_FAN_MODE, action_arg + ) + return self._decode_state(data) + + async def set_fan_speed(self, fan_speed: int) -> dict: + """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 = await self._send( + self._Operation.SET_STATE, self._Action.SET_FAN_SPEED, fan_speed + ) + return self._decode_state(data) + + async def get_state(self) -> dict: + """Return the current state of the purifier as a dict. + + 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:: + + { + "temperature": 24.5, # float, deg C, or None + "humidity": 41, # int, %, or None + "co2": 425, # int, ppm + "formaldehyde": 0.03, # float, mg/m3 + "tvoc": 150, # int, ug/m3 + "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 = await self._send(self._Operation.GET_STATE) + return self._decode_state(data) + + 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"]) + # 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": temperature, + "humidity": humidity, + "co2": raw["co2"], + "formaldehyde": raw["formaldehyde"] / 100.0, + "tvoc": raw["tvoc"] * 10, + "pm1": raw["pm1"], + "pm2_5": raw["pm2_5"], + "pm10": raw["pm10"], + "fan_mode": fan_mode, + "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], + "co2": data[31] + 256 * data[32], + "formaldehyde": data[33] + 256 * data[34], + "tvoc": data[35] + 256 * data[36], + "pm1": data[37] + 256 * data[38], + "pm2_5": data[39] + 256 * data[40], + "pm10": data[41] + 256 * data[42], + "fan_state": data[55], + "fan_speed": data[56], + "fan_flags": data[57], + } + + def _decode_fan_mode(self, fan_state: int, fan_flags: int) -> FanMode | None: + # 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 + # 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) + + async def _send(self, operation: int, action: int = 0, action_arg: int = 0) -> bytes: + """Send a command to the device.""" + packet = bytearray(26) + packet[0x02] = 0xA5 + packet[0x03] = 0xA5 + packet[0x04] = 0x5A + packet[0x05] = 0x5A + packet[0x08] = operation & 0xFF + packet[0x0A] = 0x0C + packet[0x0E] = action & 0xFF + packet[0x0F] = action_arg & 0xFF + + checksum = sum(packet, 0xBEAF) & 0xFFFF + packet[0x06] = checksum & 0xFF + packet[0x07] = checksum >> 8 + + packet_len = len(packet) - 2 + packet[0x00] = packet_len & 0xFF + packet[0x01] = packet_len >> 8 + + resp = await 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 new file mode 100644 index 0000000..351ebb8 --- /dev/null +++ b/cli/test_lifaair @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +import asyncio + +import broadlink_async +from broadlink_async 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=%s (%s) online=%s" + % ( + "%2.1fC" % temperature if temperature is not None else "-----", + "%2d%%" % humidity if humidity is not None else "---", + state["co2"], + state["formaldehyde"], + state["tvoc"], + state["pm1"], + state["pm2_5"], + state["pm10"], + "%d" % fan_speed if fan_speed is not None else "---", + state["fan_mode"], + state["purifier_online"], + ) + ) + + +async def main(): + print("Searching for lifaair devices... ") + devices = await broadlink_async.discover() + dev: lifaair = next(d for d in devices if isinstance(d, lifaair)) + print("Found %s" % dev) + + async with dev: + print("Authenticating... ", end="") + await dev.auth() + print("OK (id=%d, key=%s)" % (dev.id, dev.aes.algorithm.key.hex())) + + print("Getting firmware version... ", end="") + print(await dev.get_fwversion()) + + print("Getting state...") + print_state(await 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 in (FanMode.MANUAL, FanMode.UNKNOWN): + continue + print("Setting fan mode to %s" % mode) + print_state(await dev.set_fan_mode(mode)) + await asyncio.sleep(5) + + for speed in (0, 60, 121): + print("Setting fan speed to %d" % speed) + print_state(await dev.set_fan_speed(speed)) + await asyncio.sleep(5) + + print("Monitoring state...") + while True: + print_state(await dev.get_state()) + await asyncio.sleep(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tests/oracle/cases.py b/tests/oracle/cases.py index 8526f09..b3d17fb 100644 --- a/tests/oracle/cases.py +++ b/tests/oracle/cases.py @@ -83,6 +83,13 @@ def a1_payload(temp=(23, 5), hum=(45, 2), light=2, air=1, noise=0) -> str: return p.hex() +def lifaair_payload(frame_from_27: str) -> str: + """LM05 state body. Captured bytes sit at offset 27; the decoder reads 27..57.""" + data = bytearray(58) + data[27:] = bytes.fromhex(frame_from_27) + return data.hex() + + def a2_payload() -> str: p = bytearray(0x18) p[0x0D:0x0F] = (12).to_bytes(2, "big") # pm10 @@ -418,6 +425,43 @@ def all_cases() -> list[dict]: add(case("a1", 0x2714, "check_sensors_raw", responses=[a1_payload()])) add(case("a2", 0x4F60, "check_sensors_raw", responses=[a2_payload()])) + # Purifiers --------------------------------------------------------- + # Firmware 10026 frames, bytes from offset 27 (pit3k/python-broadlink#1). + # 26.4 C, 22 %, CO2 958, fan AUTO at speed 43. + online = ( + "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" + ) + add(case("lifaair", 0x4EC2, "get_state", responses=[lifaair_payload(online)])) + # TURBO reports 0x8D, speed 121. + turbo = ( + "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" + ) + add( + case( + "lifaair", + 0x4EC2, + "set_fan_mode", + 3, # FanMode.TURBO + responses=[lifaair_payload(turbo)], + ) + ) + # Speed 50 reports MANUAL (0x85) at that speed. + manual = ( + "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" + ) + add( + case( + "lifaair", + 0x4EC2, + "set_fan_speed", + 50, + responses=[lifaair_payload(manual)], + ) + ) + # Lights ------------------------------------------------------------ lb_state = { "red": 128, @@ -678,4 +722,13 @@ def error_cases() -> list[dict]: "responses": [EMPTY], "error_code": 0xFFF9, }, + { + "cls": "lifaair", + "devtype": 0x4EC2, + "method": "set_fan_mode", + "args": [3], # FanMode.TURBO; the device answers -5 + "kwargs": {}, + "responses": [EMPTY], + "error_code": 0xFFFB, # -5, StorageError + }, ] diff --git a/tests/oracle/fixtures.json b/tests/oracle/fixtures.json index 80ed738..2e00e0e 100644 --- a/tests/oracle/fixtures.json +++ b/tests/oracle/fixtures.json @@ -2694,6 +2694,112 @@ "unused_responses": 0 } }, + { + "case": { + "cls": "lifaair", + "devtype": 20162, + "method": "get_state", + "args": [], + "kwargs": {}, + "responses": [ + "00000000000000000000000000000000000000000000000000000008011602be0300000900010000000100000000000000000000000000a52bc0" + ] + }, + "expect": { + "result": { + "temperature": 26.4, + "humidity": 22, + "co2": 958, + "formaldehyde": 0.0, + "tvoc": 90, + "pm1": 1, + "pm2_5": 0, + "pm10": 1, + "fan_mode": 1, + "fan_speed": 43, + "purifier_online": true + }, + "sent": [ + [ + 106, + "1800a5a55a5abbc002000c000000000000000000000000000000" + ] + ], + "unused_responses": 0 + } + }, + { + "case": { + "cls": "lifaair", + "devtype": 20162, + "method": "set_fan_mode", + "args": [ + 3 + ], + "kwargs": {}, + "responses": [ + "0000000000000000000000000000000000000000000000000000000b0116028b03000009000100000001000000000000000000000000008d79c0" + ] + }, + "expect": { + "result": { + "temperature": 26.7, + "humidity": 22, + "co2": 907, + "formaldehyde": 0.0, + "tvoc": 90, + "pm1": 1, + "pm2_5": 0, + "pm10": 1, + "fan_mode": 3, + "fan_speed": 121, + "purifier_online": true + }, + "sent": [ + [ + 106, + "1800a5a55a5ac3c001000c000000020700000000000000000000" + ] + ], + "unused_responses": 0 + } + }, + { + "case": { + "cls": "lifaair", + "devtype": 20162, + "method": "set_fan_speed", + "args": [ + 50 + ], + "kwargs": {}, + "responses": [ + "0000000000000000000000000000000000000000000000000000000b011602890300000a000200000002000000000000000000000000008532c0" + ] + }, + "expect": { + "result": { + "temperature": 26.7, + "humidity": 22, + "co2": 905, + "formaldehyde": 0.0, + "tvoc": 100, + "pm1": 2, + "pm2_5": 0, + "pm10": 2, + "fan_mode": 5, + "fan_speed": 50, + "purifier_online": true + }, + "sent": [ + [ + 106, + "1800a5a55a5aedc001000c000000013200000000000000000000" + ] + ], + "unused_responses": 0 + } + }, { "case": { "cls": "lb1", @@ -4170,5 +4276,30 @@ ], "unused_responses": 0 } + }, + { + "case": { + "cls": "lifaair", + "devtype": 20162, + "method": "set_fan_mode", + "args": [ + 3 + ], + "kwargs": {}, + "responses": [ + "00000000000000000000000000000000" + ], + "error_code": 65531 + }, + "expect": { + "error": "StorageError: [Errno -5] The device storage is full", + "sent": [ + [ + 106, + "1800a5a55a5ac3c001000c000000020700000000000000000000" + ] + ], + "unused_responses": 0 + } } ] diff --git a/tests/test_lifaair.py b/tests/test_lifaair.py new file mode 100644 index 0000000..78dadcb --- /dev/null +++ b/tests/test_lifaair.py @@ -0,0 +1,371 @@ +"""Decode LIFAair LM05 frames captured from a real device. + +Bytes are payload offsets 27..57 from firmware 10026, polled on 2026-11-17. +""" + +from __future__ import annotations + +import asyncio + +import pytest + +from broadlink_async.exceptions import StorageError +from broadlink_async.purifier import FanMode, lifaair + + +def payload(raw_hex: str) -> bytes: + """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() -> lifaair: + """Return a lifaair instance that does not touch the network.""" + return lifaair(("127.0.0.1", 80), b"\x00" * 6, 0x4EC2) + + +def run(coro): + return asyncio.run(coro) + + +# 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" +) + + +def decode(raw_hex: str) -> dict: + """Decode one captured frame.""" + return device()._decode_state(payload(raw_hex)) + + +def test_offline_purifier_climate_and_mode_are_none(): + """Unplugged and unpaired both report 0x01 with zero climate bytes.""" + for raw_hex, co2 in ((OFFLINE_BOOT, 400), (OFFLINE_UNPAIRED, 939)): + state = decode(raw_hex) + assert state["temperature"] is None + assert state["humidity"] is None + assert state["fan_mode"] is None + assert state["fan_speed"] is None + assert state["purifier_online"] is False + assert state["co2"] == co2 + assert state["formaldehyde"] == 0.0 + assert state["pm2_5"] is not None + + +def test_reconnect_placeholder_zeros_are_none(): + """Online fan_state with 00 00 00 climate is not 0.0 deg C / 0 %.""" + for raw_hex, co2, speed in RECONNECT_ZEROS: + state = decode(raw_hex) + assert state["temperature"] is None + assert state["humidity"] is None + assert state["fan_mode"] == FanMode.AUTO + assert state["fan_speed"] == speed + assert state["purifier_online"] is True + assert state["co2"] == co2 + assert state["formaldehyde"] == 0.0 + + +def test_real_climate_after_placeholder(): + """The frame after the placeholder carries the real reading.""" + state = decode(AFTER_RECONNECT) + assert state["temperature"] == 26.4 + assert state["humidity"] == 22 + assert state["co2"] == 958 + assert state["fan_mode"] == FanMode.AUTO + assert state["fan_speed"] == 43 + assert state["purifier_online"] is True + + +def test_co2_warmup_placeholder_is_kept(): + """400 ppm has no separate marker, so it is returned as 400.""" + state = decode(CO2_WARMUP) + assert state["co2"] == 400 + assert state["temperature"] == 26.6 + assert state["humidity"] == 22 + assert state["tvoc"] == 90 + assert state["pm1"] == 0 + assert state["pm2_5"] == 2 + assert state["pm10"] == 3 + assert state["fan_mode"] == FanMode.AUTO + assert state["fan_speed"] == 20 + assert state["purifier_online"] is True + + +def test_spray_frame_keeps_pm_order_and_zero_formaldehyde(): + """PM offsets stay as verified, and a zero HCHO reading stays 0.0.""" + state = decode(SPRAY) + assert state["temperature"] == 26.6 + assert state["humidity"] == 22 + assert state["co2"] == 927 + assert state["formaldehyde"] == 0.0 + assert state["tvoc"] == 90 + assert state["pm1"] == 12 + assert state["pm2_5"] == 39 + assert state["pm10"] == 128 + assert state["fan_mode"] == FanMode.AUTO + assert state["fan_speed"] == 13 + assert state["purifier_online"] is True + + +def test_fan_mode_and_speed_are_reported_independently(): + """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 = decode(raw_hex) + assert state["fan_mode"] == mode + assert state["fan_speed"] == speed + assert state["purifier_online"] is True + assert state["temperature"] is not None + assert state["humidity"] == 22 + + +def response(fan: int, speed: int, flags: int) -> bytes: + """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) + + +def script(dev: lifaair, calls: list, body: bytes) -> None: + """Replace _send with a recorder that returns body.""" + + async def send(operation, action=0, action_arg=0): + calls.append((operation, action, action_arg)) + return body + + dev._send = send + + +def test_set_fan_mode_sends_one_mode_argument(): + """Each mode command is one SET_FAN_MODE packet.""" + dev = device() + calls: list = [] + 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: + calls.clear() + script(dev, calls, response(fan, speed, flags)) + state = run(dev.set_fan_mode(mode)) + assert calls == [ + ( + lifaair._Operation.SET_STATE, + lifaair._Action.SET_FAN_MODE, + arg, + ) + ] + assert state["fan_mode"] == expect_mode + assert state["fan_speed"] == expect_speed + assert state["purifier_online"] is True + + +def test_set_fan_mode_without_a_command_sends_nothing(): + """MANUAL, UNKNOWN and None have no mode argument.""" + dev = device() + calls: list = [] + script(dev, calls, response(0x85, 50, 0xC0)) + for mode in (FanMode.MANUAL, FanMode.UNKNOWN, None): + with pytest.raises(ValueError): + run(dev.set_fan_mode(mode)) + assert calls == [] + + +def test_set_fan_mode_device_error_is_not_retried(): + """Error -5 from the device is StorageError, raised once.""" + dev = device() + calls: list = [] + + async def send(operation, action=0, action_arg=0): + calls.append((operation, action, action_arg)) + raise StorageError(-5, "The device storage is full") + + dev._send = send + with pytest.raises(StorageError): + run(dev.set_fan_mode(FanMode.TURBO)) + assert calls == [ + ( + lifaair._Operation.SET_STATE, + lifaair._Action.SET_FAN_MODE, + 7, + ) + ] + + +def test_set_fan_speed_sends_one_speed_argument(): + """Speed is one SET_FAN_SPEED packet, including 0 and OFF.""" + dev = device() + calls: list = [] + 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: + calls.clear() + script(dev, calls, response(fan, raw_speed, flags)) + state = run(dev.set_fan_speed(speed)) + assert calls == [ + ( + lifaair._Operation.SET_STATE, + lifaair._Action.SET_FAN_SPEED, + speed, + ) + ] + assert state["fan_mode"] == mode + assert state["fan_speed"] == expect_speed + assert state["purifier_online"] is True + + +def test_set_fan_speed_rejects_values_that_cannot_be_encoded(): + """Only ints in 0..121 are sent.""" + dev = device() + calls: list = [] + script(dev, calls, response(0x85, 50, 0xC0)) + for speed in (-1, 122, True, "50"): + with pytest.raises(ValueError): + run(dev.set_fan_speed(speed)) + assert calls == [] + + +def test_device_error_minus_5_is_storage_error(): + """A response error of -5 is StorageError, and the command is not resent.""" + dev = device() + calls: list = [] + + async def send_packet(packet_type, packet): + calls.append((packet_type, bytes(packet))) + frame = bytearray(0x38) + frame[0x22:0x24] = (-5 & 0xFFFF).to_bytes(2, "little") + return bytes(frame) + + dev.send_packet = send_packet + with pytest.raises(StorageError) as raised: + run(dev.set_fan_mode(FanMode.TURBO)) + assert raised.value.errno == -5 + assert len(calls) == 1 + assert calls[0][0] == 0x6A + + +def test_bit0_clear_decodes_as_the_same_mode(): + """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)) + assert state["fan_mode"] == mode + assert state["fan_speed"] == expect_speed + assert state["purifier_online"] is True + assert state["temperature"] == 26.7 + assert state["humidity"] == 22 diff --git a/tests/test_transport.py b/tests/test_transport.py index 509345a..f6ab0cf 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -988,6 +988,7 @@ def failing_sendto(data, addr=None): (0x791B, broadlink_async.sp2, "WS2-W10"), (0x791C, broadlink_async.sp2, "WS2-W16"), (0x2714, broadlink_async.a1, "A1"), + (0x4EC2, broadlink_async.lifaair, "LM05"), (0x4EAD, broadlink_async.hysen, "HY02/HY03"), (0x60C7, broadlink_async.lb1, "LB1"), (0x4EB5, broadlink_async.mp1, "MP1-1K4S"), From 382491e93940ca1d242685658fc7a3b7676083a1 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 10:56:35 +0000 Subject: [PATCH 2/9] Nest FanMode on the lifaair class MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Device enums live on the device class and are not re-exported. FanMode is now lifaair.FanMode. The two lookup tables are private, matching the other device classes. Co-authored-by: Piotr Paczyński --- README.md | 4 +-- broadlink_async/__init__.py | 2 +- broadlink_async/purifier.py | 39 ++++++++++++----------- cli/test_lifaair | 6 ++-- tests/oracle/cases.py | 4 +-- tests/test_lifaair.py | 62 +++++++++++++++++++++---------------- 6 files changed, 62 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index ab20805..64c9066 100644 --- a/README.md +++ b/README.md @@ -433,14 +433,14 @@ data = await device.check_sensors() ### Fetching purifier state ```python3 -from broadlink_async import FanMode +from broadlink_async import lifaair data = await device.get_state() ``` ### Controlling purifier fan ```python3 -await device.set_fan_mode(FanMode.TURBO) +await device.set_fan_mode(lifaair.FanMode.TURBO) await device.set_fan_speed(50) ``` diff --git a/broadlink_async/__init__.py b/broadlink_async/__init__.py index 3efe045..72b560e 100644 --- a/broadlink_async/__init__.py +++ b/broadlink_async/__init__.py @@ -11,7 +11,7 @@ from .device import Device, ping, scan, send_setup_packet from .hub import s3 from .light import fl, lb1, lb2 -from .purifier import FanMode, lifaair +from .purifier import lifaair from .remote import rm, rm4, rm4mini, rm4pro, rm5plus, rmmini, rmminib, rmpro from .sensor import a1, a2 from .switch import bg1, ehc31, mp1, mp1s, sp1, sp2, sp2s, sp3, sp3s, sp4, sp4b diff --git a/broadlink_async/purifier.py b/broadlink_async/purifier.py index 5b2e7a5..5802a0f 100644 --- a/broadlink_async/purifier.py +++ b/broadlink_async/purifier.py @@ -6,20 +6,6 @@ from .device import Device -@enum.unique -class FanMode(enum.IntEnum): - """Represents mode of the fan.""" - - OFF = 0 - AUTO = 1 - NIGHT = 2 - TURBO = 3 - ANTI_ALLERGY = 4 - MANUAL = 5 - - UNKNOWN = -1 - - class lifaair(Device): """Controls a Broadlink-based LIFAair air purifier / monitor. @@ -30,13 +16,26 @@ class lifaair(Device): TYPE = "LIFAAIR" + @enum.unique + class FanMode(enum.IntEnum): + """Enumerates fan modes.""" + + OFF = 0 + AUTO = 1 + NIGHT = 2 + TURBO = 3 + ANTI_ALLERGY = 4 + MANUAL = 5 + + UNKNOWN = -1 + # 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 = { + _FAN_STATE_TO_MODE = { 0x81: FanMode.OFF, 0xA5: FanMode.AUTO, 0x95: FanMode.NIGHT, @@ -55,7 +54,7 @@ class _Action(enum.IntEnum): SET_FAN_SPEED = 1 SET_FAN_MODE = 2 - FAN_MODE_TO_ACTION_ARG = { + _FAN_MODE_TO_ACTION_ARG = { FanMode.OFF: 1, FanMode.AUTO: 2, FanMode.NIGHT: 6, @@ -75,7 +74,7 @@ async def set_fan_mode(self, fan_mode: FanMode) -> dict: 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) + action_arg = self._FAN_MODE_TO_ACTION_ARG.get(fan_mode) if action_arg is None: raise ValueError(f"{fan_mode!r} has no mode command") data = await self._send( @@ -125,7 +124,7 @@ async def get_state(self) -> dict: "pm1": 5, # int, ug/m3 "pm2_5": 7, # int, ug/m3 "pm10": 9, # int, ug/m3 - "fan_mode": FanMode.AUTO, # FanMode, or None + "fan_mode": lifaair.FanMode.AUTO, # lifaair.FanMode, or None "fan_speed": 50, # int 0-121, or None "purifier_online": True, # bool, bit 7 of byte 55 } @@ -190,10 +189,10 @@ def _decode_fan_mode(self, fan_state: int, fan_flags: int) -> FanMode | None: return None # Anti-allergy is 0x85 with bit 0x40 of the flags clear. if fan_flags & 0x40 == 0: - return FanMode.ANTI_ALLERGY + return self.FanMode.ANTI_ALLERGY # 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) + return self._FAN_STATE_TO_MODE.get(fan_state | 0x01, self.FanMode.UNKNOWN) async def _send(self, operation: int, action: int = 0, action_arg: int = 0) -> bytes: """Send a command to the device.""" diff --git a/cli/test_lifaair b/cli/test_lifaair index 351ebb8..ef5701f 100644 --- a/cli/test_lifaair +++ b/cli/test_lifaair @@ -2,7 +2,7 @@ import asyncio import broadlink_async -from broadlink_async import FanMode, lifaair +from broadlink_async import lifaair def print_state(state: dict): @@ -49,8 +49,8 @@ async def main(): "While OFF, modes other than OFF and AUTO are rejected with " "error -5 and nothing changes." ) - for mode in FanMode: - if mode in (FanMode.MANUAL, FanMode.UNKNOWN): + for mode in lifaair.FanMode: + if mode in (lifaair.FanMode.MANUAL, lifaair.FanMode.UNKNOWN): continue print("Setting fan mode to %s" % mode) print_state(await dev.set_fan_mode(mode)) diff --git a/tests/oracle/cases.py b/tests/oracle/cases.py index b3d17fb..fe20d97 100644 --- a/tests/oracle/cases.py +++ b/tests/oracle/cases.py @@ -443,7 +443,7 @@ def all_cases() -> list[dict]: "lifaair", 0x4EC2, "set_fan_mode", - 3, # FanMode.TURBO + 3, # lifaair.FanMode.TURBO responses=[lifaair_payload(turbo)], ) ) @@ -726,7 +726,7 @@ def error_cases() -> list[dict]: "cls": "lifaair", "devtype": 0x4EC2, "method": "set_fan_mode", - "args": [3], # FanMode.TURBO; the device answers -5 + "args": [3], # lifaair.FanMode.TURBO; the device answers -5 "kwargs": {}, "responses": [EMPTY], "error_code": 0xFFFB, # -5, StorageError diff --git a/tests/test_lifaair.py b/tests/test_lifaair.py index 78dadcb..30f1869 100644 --- a/tests/test_lifaair.py +++ b/tests/test_lifaair.py @@ -10,7 +10,7 @@ import pytest from broadlink_async.exceptions import StorageError -from broadlink_async.purifier import FanMode, lifaair +from broadlink_async.purifier import lifaair def payload(raw_hex: str) -> bytes: @@ -108,7 +108,7 @@ def test_reconnect_placeholder_zeros_are_none(): state = decode(raw_hex) assert state["temperature"] is None assert state["humidity"] is None - assert state["fan_mode"] == FanMode.AUTO + assert state["fan_mode"] == lifaair.FanMode.AUTO assert state["fan_speed"] == speed assert state["purifier_online"] is True assert state["co2"] == co2 @@ -121,7 +121,7 @@ def test_real_climate_after_placeholder(): assert state["temperature"] == 26.4 assert state["humidity"] == 22 assert state["co2"] == 958 - assert state["fan_mode"] == FanMode.AUTO + assert state["fan_mode"] == lifaair.FanMode.AUTO assert state["fan_speed"] == 43 assert state["purifier_online"] is True @@ -136,7 +136,7 @@ def test_co2_warmup_placeholder_is_kept(): assert state["pm1"] == 0 assert state["pm2_5"] == 2 assert state["pm10"] == 3 - assert state["fan_mode"] == FanMode.AUTO + assert state["fan_mode"] == lifaair.FanMode.AUTO assert state["fan_speed"] == 20 assert state["purifier_online"] is True @@ -152,7 +152,7 @@ def test_spray_frame_keeps_pm_order_and_zero_formaldehyde(): assert state["pm1"] == 12 assert state["pm2_5"] == 39 assert state["pm10"] == 128 - assert state["fan_mode"] == FanMode.AUTO + assert state["fan_mode"] == lifaair.FanMode.AUTO assert state["fan_speed"] == 13 assert state["purifier_online"] is True @@ -164,49 +164,49 @@ def test_fan_mode_and_speed_are_reported_independently(): ( "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, + lifaair.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, + lifaair.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, + lifaair.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, + lifaair.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, + lifaair.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, + lifaair.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, + lifaair.FanMode.MANUAL, 50, ), ) @@ -244,11 +244,19 @@ def test_set_fan_mode_sends_one_mode_argument(): dev = device() calls: list = [] 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), + (lifaair.FanMode.OFF, 1, 0x81, 0x00, 0xC0, lifaair.FanMode.OFF, 0), + (lifaair.FanMode.AUTO, 2, 0xA5, 0x1E, 0xC0, lifaair.FanMode.AUTO, 30), + (lifaair.FanMode.NIGHT, 6, 0x95, 0x0A, 0xC0, lifaair.FanMode.NIGHT, 10), + (lifaair.FanMode.TURBO, 7, 0x8D, 0x79, 0xC0, lifaair.FanMode.TURBO, 121), + ( + lifaair.FanMode.ANTI_ALLERGY, + 11, + 0x85, + 0x3C, + 0x80, + lifaair.FanMode.ANTI_ALLERGY, + 60, + ), ) for mode, arg, fan, speed, flags, expect_mode, expect_speed in cases: calls.clear() @@ -271,7 +279,7 @@ def test_set_fan_mode_without_a_command_sends_nothing(): dev = device() calls: list = [] script(dev, calls, response(0x85, 50, 0xC0)) - for mode in (FanMode.MANUAL, FanMode.UNKNOWN, None): + for mode in (lifaair.FanMode.MANUAL, lifaair.FanMode.UNKNOWN, None): with pytest.raises(ValueError): run(dev.set_fan_mode(mode)) assert calls == [] @@ -288,7 +296,7 @@ async def send(operation, action=0, action_arg=0): dev._send = send with pytest.raises(StorageError): - run(dev.set_fan_mode(FanMode.TURBO)) + run(dev.set_fan_mode(lifaair.FanMode.TURBO)) assert calls == [ ( lifaair._Operation.SET_STATE, @@ -303,10 +311,10 @@ def test_set_fan_speed_sends_one_speed_argument(): dev = device() calls: list = [] 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), + (70, 0x85, 0x46, 0xC0, lifaair.FanMode.MANUAL, 70), + (0, 0x85, 0x00, 0xC0, lifaair.FanMode.MANUAL, 0), + (121, 0x85, 0x79, 0xC0, lifaair.FanMode.MANUAL, 121), + (50, 0x81, 0x32, 0xC0, lifaair.FanMode.OFF, 50), ) for speed, fan, raw_speed, flags, mode, expect_speed in cases: calls.clear() @@ -348,7 +356,7 @@ async def send_packet(packet_type, packet): dev.send_packet = send_packet with pytest.raises(StorageError) as raised: - run(dev.set_fan_mode(FanMode.TURBO)) + run(dev.set_fan_mode(lifaair.FanMode.TURBO)) assert raised.value.errno == -5 assert len(calls) == 1 assert calls[0][0] == 0x6A @@ -357,9 +365,9 @@ async def send_packet(packet_type, packet): def test_bit0_clear_decodes_as_the_same_mode(): """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), + (0x84, 0x32, 0xC0, lifaair.FanMode.MANUAL, 50), + (0xA4, 0x1E, 0xC0, lifaair.FanMode.AUTO, 30), + (0x80, 0x00, 0xC0, lifaair.FanMode.OFF, 0), ) dev = device() for fan, speed, flags, mode, expect_speed in cases: From 75b39db9af9b96d5b70b89e28b8fd9a7ceff52df Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 11:06:31 +0000 Subject: [PATCH 3/9] Build the LM05 oracle payloads field by field MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lifaair_state_data assigns each decoded field on its own line. The three canned frames stay the bytes captured on firmware 10026. Co-authored-by: Piotr Paczyński --- tests/oracle/cases.py | 91 ++++++++++++++++++++++++++++++++----------- 1 file changed, 68 insertions(+), 23 deletions(-) diff --git a/tests/oracle/cases.py b/tests/oracle/cases.py index fe20d97..70b4d38 100644 --- a/tests/oracle/cases.py +++ b/tests/oracle/cases.py @@ -83,11 +83,31 @@ def a1_payload(temp=(23, 5), hum=(45, 2), light=2, air=1, noise=0) -> str: return p.hex() -def lifaair_payload(frame_from_27: str) -> str: - """LM05 state body. Captured bytes sit at offset 27; the decoder reads 27..57.""" - data = bytearray(58) - data[27:] = bytes.fromhex(frame_from_27) - return data.hex() +def lifaair_state_data( + *, + temperature: int, + co2: int, + tvoc: int, + pm1: int, + pm10: int, + fan_state: int, + fan_speed: int, +) -> bytes: + """58-byte LM05 state body. The decoder reads offsets 27..57.""" + body = bytearray(58) + body[27:29] = temperature.to_bytes(2, "little") # tenths deg C + body[29] = 22 # humidity + body[30] = 0x02 # set as captured; meaning unknown + body[31:33] = co2.to_bytes(2, "little") # ppm + body[33:35] = (0).to_bytes(2, "little") # formaldehyde + body[35:37] = tvoc.to_bytes(2, "little") # tvoc + body[37:39] = pm1.to_bytes(2, "little") # pm1 + body[39:41] = (0).to_bytes(2, "little") # pm2_5 + body[41:43] = pm10.to_bytes(2, "little") # pm10 + body[55] = fan_state # fan state + body[56] = fan_speed # fan speed + body[57] = 0xC0 # fan flags + return bytes(body) def a2_payload() -> str: @@ -426,39 +446,64 @@ def all_cases() -> list[dict]: add(case("a2", 0x4F60, "check_sensors_raw", responses=[a2_payload()])) # Purifiers --------------------------------------------------------- - # Firmware 10026 frames, bytes from offset 27 (pit3k/python-broadlink#1). - # 26.4 C, 22 %, CO2 958, fan AUTO at speed 43. - online = ( - "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" - ) - add(case("lifaair", 0x4EC2, "get_state", responses=[lifaair_payload(online)])) - # TURBO reports 0x8D, speed 121. - turbo = ( - "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" + # Firmware 10026 captures (pit3k/python-broadlink#1). + # 26.4 C, 22 %, CO2 958, fan state 0xA5, speed 43. + add( + case( + "lifaair", + 0x4EC2, + "get_state", + responses=[ + lifaair_state_data( + temperature=264, + co2=958, + tvoc=9, + pm1=1, + pm10=1, + fan_state=0xA5, + fan_speed=43, + ).hex() + ], + ) ) + # TURBO: fan state 0x8D, speed 121. add( case( "lifaair", 0x4EC2, "set_fan_mode", 3, # lifaair.FanMode.TURBO - responses=[lifaair_payload(turbo)], + responses=[ + lifaair_state_data( + temperature=267, + co2=907, + tvoc=9, + pm1=1, + pm10=1, + fan_state=0x8D, + fan_speed=121, + ).hex() + ], ) ) - # Speed 50 reports MANUAL (0x85) at that speed. - manual = ( - "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" - ) + # Speed 50: fan state 0x85, speed 50. add( case( "lifaair", 0x4EC2, "set_fan_speed", 50, - responses=[lifaair_payload(manual)], + responses=[ + lifaair_state_data( + temperature=267, + co2=905, + tvoc=10, + pm1=2, + pm10=2, + fan_state=0x85, + fan_speed=50, + ).hex() + ], ) ) From 23315a04c9123dab186b9a70374c5ecb1713ab1d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 11:07:30 +0000 Subject: [PATCH 4/9] Match the LM05 changelog entry to earlier device notes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One sentence of what the class supports, the CLI script, and who contributed it. Co-authored-by: Piotr Paczyński --- CHANGELOG.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6692387..bc43aa3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,12 +8,9 @@ Keep a Changelog; versions follow Semantic Versioning. ### Added - The LIFAair LM05 air purifier (0x4EC2) is supported as `lifaair`: - station readings (CO2, TVOC, formaldehyde, PM) and the purifier's fan - mode, speed, temperature and humidity. Fan mode, speed, temperature - and humidity are `None` when the purifier is offline. `set_fan_mode` - and `set_fan_speed` each send one encoded argument and return the - decoded response. Tested on an LM05 with firmware 10026 - (pit3k/python-broadlink#1, mjg59/python-broadlink#807). + station readings (CO2, TVOC, formaldehyde, PM1, PM2.5, PM10), the + purifier's temperature and humidity, and fan mode and speed, with a + `cli/test_lifaair` script. Contributed by pit3k. ## 1.3.0 - 2026-11-16 From 02976cd16df086817ca0aa02a46205cec4e0733e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 11:18:19 +0000 Subject: [PATCH 5/9] Add LM05 fan options to the CLI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit broadlink_cli sets the fan with --fanmode and --fanspeed and prints the decoded state. --sensors prints get_state for an LM05. The per-device script is removed. Co-authored-by: Piotr Paczyński --- CHANGELOG.md | 4 +-- cli/README.md | 18 ++++++++++++ cli/broadlink_cli | 19 +++++++++++-- cli/test_lifaair | 71 ----------------------------------------------- 4 files changed, 36 insertions(+), 76 deletions(-) delete mode 100644 cli/test_lifaair diff --git a/CHANGELOG.md b/CHANGELOG.md index bc43aa3..63a93f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ Keep a Changelog; versions follow Semantic Versioning. - The LIFAair LM05 air purifier (0x4EC2) is supported as `lifaair`: station readings (CO2, TVOC, formaldehyde, PM1, PM2.5, PM10), the - purifier's temperature and humidity, and fan mode and speed, with a - `cli/test_lifaair` script. Contributed by pit3k. + purifier's temperature and humidity, and fan mode and speed, with + matching CLI options. Contributed by pit3k. ## 1.3.0 - 2026-11-16 diff --git a/cli/README.md b/cli/README.md index 0b7099b..2e919c0 100644 --- a/cli/README.md +++ b/cli/README.md @@ -154,3 +154,21 @@ broadlink_cli --device @BEDROOM.device --checknl ``` broadlink_cli --device @BEDROOM.device --energy ``` + +### Air purifiers + +#### Get state +``` +broadlink_cli --device @BEDROOM.device --getstate +``` +`--sensors` prints the same dict for an LM05. + +#### Set fan mode +``` +broadlink_cli --device @BEDROOM.device --fanmode AUTO +``` + +#### Set fan speed +``` +broadlink_cli --device @BEDROOM.device --fanspeed 50 +``` diff --git a/cli/broadlink_cli b/cli/broadlink_cli index f2223ef..dbd2351 100644 --- a/cli/broadlink_cli +++ b/cli/broadlink_cli @@ -73,6 +73,8 @@ parser.add_argument("--ontime", action="store", help="set floodlight on time (10 parser.add_argument("--sensitivity", action="store", help="set motion sensitivity (0 - 3)") parser.add_argument("--brightnesscontrol", action="store", help="set ambient light threshold (5 - 2000)") parser.add_argument("--getstate", action="store_true", help="get current state") +parser.add_argument("--fanmode", action="store", help="set fan mode (OFF, AUTO, NIGHT, TURBO, ANTI_ALLERGY)") +parser.add_argument("--fanspeed", type=int, help="set fan speed (0 - 121)") parser.add_argument("--temperature", action="store_true", help="request temperature from device") parser.add_argument("--humidity", action="store_true", help="request humidity from device") parser.add_argument("--energy", action="store_true", help="request energy consumption from device") @@ -146,6 +148,14 @@ async def run_commands(stack: AsyncExitStack): await dev.set_state(brightness_control=args.brightnesscontrol) if args.getstate: print(await dev.get_state()) + if args.fanmode: + try: + fan_mode = broadlink_async.lifaair.FanMode[args.fanmode] + except KeyError: + fan_mode = broadlink_async.lifaair.FanMode(auto_int(args.fanmode)) + print(await dev.set_fan_mode(fan_mode)) + if args.fanspeed is not None: + print(await dev.set_fan_speed(args.fanspeed)) if args.convert: data = bytearray.fromhex(''.join(args.data)) @@ -158,9 +168,12 @@ async def run_commands(stack: AsyncExitStack): if args.energy: print(await dev.get_energy()) if args.sensors: - data = await dev.check_sensors() - for key in data: - print("{} {}".format(key, data[key])) + if isinstance(dev, broadlink_async.lifaair): + print(await dev.get_state()) + else: + data = await dev.check_sensors() + for key in data: + print("{} {}".format(key, data[key])) if args.send: data = ( pulses_to_data(parse_pulses(args.data), repeat=args.repeat) diff --git a/cli/test_lifaair b/cli/test_lifaair deleted file mode 100644 index ef5701f..0000000 --- a/cli/test_lifaair +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python3 -import asyncio - -import broadlink_async -from broadlink_async import 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=%s (%s) online=%s" - % ( - "%2.1fC" % temperature if temperature is not None else "-----", - "%2d%%" % humidity if humidity is not None else "---", - state["co2"], - state["formaldehyde"], - state["tvoc"], - state["pm1"], - state["pm2_5"], - state["pm10"], - "%d" % fan_speed if fan_speed is not None else "---", - state["fan_mode"], - state["purifier_online"], - ) - ) - - -async def main(): - print("Searching for lifaair devices... ") - devices = await broadlink_async.discover() - dev: lifaair = next(d for d in devices if isinstance(d, lifaair)) - print("Found %s" % dev) - - async with dev: - print("Authenticating... ", end="") - await dev.auth() - print("OK (id=%d, key=%s)" % (dev.id, dev.aes.algorithm.key.hex())) - - print("Getting firmware version... ", end="") - print(await dev.get_fwversion()) - - print("Getting state...") - print_state(await dev.get_state()) - - print( - "While OFF, modes other than OFF and AUTO are rejected with " - "error -5 and nothing changes." - ) - for mode in lifaair.FanMode: - if mode in (lifaair.FanMode.MANUAL, lifaair.FanMode.UNKNOWN): - continue - print("Setting fan mode to %s" % mode) - print_state(await dev.set_fan_mode(mode)) - await asyncio.sleep(5) - - for speed in (0, 60, 121): - print("Setting fan speed to %d" % speed) - print_state(await dev.set_fan_speed(speed)) - await asyncio.sleep(5) - - print("Monitoring state...") - while True: - print_state(await dev.get_state()) - await asyncio.sleep(1) - - -if __name__ == "__main__": - asyncio.run(main()) From 592c59855ab91df289fbf96c190e852d7b372ae7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 11:28:06 +0000 Subject: [PATCH 6/9] Read LM05 state with the existing getstate option MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drop the lifaair branch from --sensors. --getstate already prints get_state, and --fanmode and --fanspeed stay. Co-authored-by: Piotr Paczyński --- cli/README.md | 1 - cli/broadlink_cli | 9 +++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/cli/README.md b/cli/README.md index 2e919c0..52238fe 100644 --- a/cli/README.md +++ b/cli/README.md @@ -161,7 +161,6 @@ broadlink_cli --device @BEDROOM.device --energy ``` broadlink_cli --device @BEDROOM.device --getstate ``` -`--sensors` prints the same dict for an LM05. #### Set fan mode ``` diff --git a/cli/broadlink_cli b/cli/broadlink_cli index dbd2351..38353fd 100644 --- a/cli/broadlink_cli +++ b/cli/broadlink_cli @@ -168,12 +168,9 @@ async def run_commands(stack: AsyncExitStack): if args.energy: print(await dev.get_energy()) if args.sensors: - if isinstance(dev, broadlink_async.lifaair): - print(await dev.get_state()) - else: - data = await dev.check_sensors() - for key in data: - print("{} {}".format(key, data[key])) + data = await dev.check_sensors() + for key in data: + print("{} {}".format(key, data[key])) if args.send: data = ( pulses_to_data(parse_pulses(args.data), repeat=args.repeat) From 5c6e03d2f4355a12726b22b9357884adb9284007 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 11:34:31 +0000 Subject: [PATCH 7/9] Look up fan modes by name and align the LM05 tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --fanmode uses FanMode[name] only. The LM05 tests build the device with the shared HOST and MAC and keep their helpers with the others. Co-authored-by: Piotr Paczyński --- cli/broadlink_cli | 5 +---- tests/test_lifaair.py | 47 ++++++++++++++++++++++--------------------- 2 files changed, 25 insertions(+), 27 deletions(-) diff --git a/cli/broadlink_cli b/cli/broadlink_cli index 38353fd..b922b3b 100644 --- a/cli/broadlink_cli +++ b/cli/broadlink_cli @@ -149,10 +149,7 @@ async def run_commands(stack: AsyncExitStack): if args.getstate: print(await dev.get_state()) if args.fanmode: - try: - fan_mode = broadlink_async.lifaair.FanMode[args.fanmode] - except KeyError: - fan_mode = broadlink_async.lifaair.FanMode(auto_int(args.fanmode)) + fan_mode = broadlink_async.lifaair.FanMode[args.fanmode] print(await dev.set_fan_mode(fan_mode)) if args.fanspeed is not None: print(await dev.set_fan_speed(args.fanspeed)) diff --git a/tests/test_lifaair.py b/tests/test_lifaair.py index 30f1869..06916bb 100644 --- a/tests/test_lifaair.py +++ b/tests/test_lifaair.py @@ -11,6 +11,7 @@ from broadlink_async.exceptions import StorageError from broadlink_async.purifier import lifaair +from tests.oracle.harness import HOST, MAC def payload(raw_hex: str) -> bytes: @@ -22,7 +23,7 @@ def payload(raw_hex: str) -> bytes: def device() -> lifaair: """Return a lifaair instance that does not touch the network.""" - return lifaair(("127.0.0.1", 80), b"\x00" * 6, 0x4EC2) + return lifaair(HOST, MAC, 0x4EC2) def run(coro): @@ -88,6 +89,26 @@ def decode(raw_hex: str) -> dict: return device()._decode_state(payload(raw_hex)) +def response(fan: int, speed: int, flags: int) -> bytes: + """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) + + +def script(dev: lifaair, calls: list, body: bytes) -> None: + """Replace _send with a recorder that returns body.""" + + async def send(operation, action=0, action_arg=0): + calls.append((operation, action, action_arg)) + return body + + dev._send = send + + def test_offline_purifier_climate_and_mode_are_none(): """Unplugged and unpaired both report 0x01 with zero climate bytes.""" for raw_hex, co2 in ((OFFLINE_BOOT, 400), (OFFLINE_UNPAIRED, 939)): @@ -219,26 +240,6 @@ def test_fan_mode_and_speed_are_reported_independently(): assert state["humidity"] == 22 -def response(fan: int, speed: int, flags: int) -> bytes: - """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) - - -def script(dev: lifaair, calls: list, body: bytes) -> None: - """Replace _send with a recorder that returns body.""" - - async def send(operation, action=0, action_arg=0): - calls.append((operation, action, action_arg)) - return body - - dev._send = send - - def test_set_fan_mode_sends_one_mode_argument(): """Each mode command is one SET_FAN_MODE packet.""" dev = device() @@ -355,9 +356,9 @@ async def send_packet(packet_type, packet): return bytes(frame) dev.send_packet = send_packet - with pytest.raises(StorageError) as raised: + with pytest.raises(StorageError) as err: run(dev.set_fan_mode(lifaair.FanMode.TURBO)) - assert raised.value.errno == -5 + assert err.value.errno == -5 assert len(calls) == 1 assert calls[0][0] == 0x6A From b773a648e112255d6edbc2063deebd7123967aec Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 11:45:35 +0000 Subject: [PATCH 8/9] Keep the LM05 tests on decoded frames MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drop the tests that spy on _send or repeat the oracle. ValueError cases only check the raise, and each decode test asserts its point. Co-authored-by: Piotr Paczyński --- tests/test_lifaair.py | 188 ++---------------------------------------- 1 file changed, 9 insertions(+), 179 deletions(-) diff --git a/tests/test_lifaair.py b/tests/test_lifaair.py index 06916bb..3ebe5b5 100644 --- a/tests/test_lifaair.py +++ b/tests/test_lifaair.py @@ -9,7 +9,6 @@ import pytest -from broadlink_async.exceptions import StorageError from broadlink_async.purifier import lifaair from tests.oracle.harness import HOST, MAC @@ -45,25 +44,21 @@ def run(coro): ( "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, ), ) @@ -72,11 +67,6 @@ def run(coro): "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 " @@ -99,83 +89,37 @@ def response(fan: int, speed: int, flags: int) -> bytes: return bytes(data) -def script(dev: lifaair, calls: list, body: bytes) -> None: - """Replace _send with a recorder that returns body.""" - - async def send(operation, action=0, action_arg=0): - calls.append((operation, action, action_arg)) - return body - - dev._send = send - - def test_offline_purifier_climate_and_mode_are_none(): """Unplugged and unpaired both report 0x01 with zero climate bytes.""" - for raw_hex, co2 in ((OFFLINE_BOOT, 400), (OFFLINE_UNPAIRED, 939)): + for raw_hex in (OFFLINE_BOOT, OFFLINE_UNPAIRED): state = decode(raw_hex) assert state["temperature"] is None assert state["humidity"] is None assert state["fan_mode"] is None assert state["fan_speed"] is None assert state["purifier_online"] is False - assert state["co2"] == co2 - assert state["formaldehyde"] == 0.0 - assert state["pm2_5"] is not None -def test_reconnect_placeholder_zeros_are_none(): - """Online fan_state with 00 00 00 climate is not 0.0 deg C / 0 %.""" - for raw_hex, co2, speed in RECONNECT_ZEROS: +def test_reconnect_placeholder_then_real_climate(): + """00 00 00 climate is not 0.0 deg C / 0 %; the next frame is the reading.""" + for raw_hex, speed in RECONNECT_ZEROS: state = decode(raw_hex) assert state["temperature"] is None assert state["humidity"] is None assert state["fan_mode"] == lifaair.FanMode.AUTO assert state["fan_speed"] == speed - assert state["purifier_online"] is True - assert state["co2"] == co2 - assert state["formaldehyde"] == 0.0 - - -def test_real_climate_after_placeholder(): - """The frame after the placeholder carries the real reading.""" state = decode(AFTER_RECONNECT) assert state["temperature"] == 26.4 assert state["humidity"] == 22 - assert state["co2"] == 958 - assert state["fan_mode"] == lifaair.FanMode.AUTO - assert state["fan_speed"] == 43 - assert state["purifier_online"] is True - - -def test_co2_warmup_placeholder_is_kept(): - """400 ppm has no separate marker, so it is returned as 400.""" - state = decode(CO2_WARMUP) - assert state["co2"] == 400 - assert state["temperature"] == 26.6 - assert state["humidity"] == 22 - assert state["tvoc"] == 90 - assert state["pm1"] == 0 - assert state["pm2_5"] == 2 - assert state["pm10"] == 3 - assert state["fan_mode"] == lifaair.FanMode.AUTO - assert state["fan_speed"] == 20 - assert state["purifier_online"] is True def test_spray_frame_keeps_pm_order_and_zero_formaldehyde(): """PM offsets stay as verified, and a zero HCHO reading stays 0.0.""" state = decode(SPRAY) - assert state["temperature"] == 26.6 - assert state["humidity"] == 22 - assert state["co2"] == 927 assert state["formaldehyde"] == 0.0 - assert state["tvoc"] == 90 assert state["pm1"] == 12 assert state["pm2_5"] == 39 assert state["pm10"] == 128 - assert state["fan_mode"] == lifaair.FanMode.AUTO - assert state["fan_speed"] == 13 - assert state["purifier_online"] is True def test_fan_mode_and_speed_are_reported_independently(): @@ -235,132 +179,22 @@ def test_fan_mode_and_speed_are_reported_independently(): state = decode(raw_hex) assert state["fan_mode"] == mode assert state["fan_speed"] == speed - assert state["purifier_online"] is True - assert state["temperature"] is not None - assert state["humidity"] == 22 -def test_set_fan_mode_sends_one_mode_argument(): - """Each mode command is one SET_FAN_MODE packet.""" - dev = device() - calls: list = [] - cases = ( - (lifaair.FanMode.OFF, 1, 0x81, 0x00, 0xC0, lifaair.FanMode.OFF, 0), - (lifaair.FanMode.AUTO, 2, 0xA5, 0x1E, 0xC0, lifaair.FanMode.AUTO, 30), - (lifaair.FanMode.NIGHT, 6, 0x95, 0x0A, 0xC0, lifaair.FanMode.NIGHT, 10), - (lifaair.FanMode.TURBO, 7, 0x8D, 0x79, 0xC0, lifaair.FanMode.TURBO, 121), - ( - lifaair.FanMode.ANTI_ALLERGY, - 11, - 0x85, - 0x3C, - 0x80, - lifaair.FanMode.ANTI_ALLERGY, - 60, - ), - ) - for mode, arg, fan, speed, flags, expect_mode, expect_speed in cases: - calls.clear() - script(dev, calls, response(fan, speed, flags)) - state = run(dev.set_fan_mode(mode)) - assert calls == [ - ( - lifaair._Operation.SET_STATE, - lifaair._Action.SET_FAN_MODE, - arg, - ) - ] - assert state["fan_mode"] == expect_mode - assert state["fan_speed"] == expect_speed - assert state["purifier_online"] is True - - -def test_set_fan_mode_without_a_command_sends_nothing(): +def test_set_fan_mode_without_a_command_raises(): """MANUAL, UNKNOWN and None have no mode argument.""" dev = device() - calls: list = [] - script(dev, calls, response(0x85, 50, 0xC0)) for mode in (lifaair.FanMode.MANUAL, lifaair.FanMode.UNKNOWN, None): with pytest.raises(ValueError): run(dev.set_fan_mode(mode)) - assert calls == [] - - -def test_set_fan_mode_device_error_is_not_retried(): - """Error -5 from the device is StorageError, raised once.""" - dev = device() - calls: list = [] - - async def send(operation, action=0, action_arg=0): - calls.append((operation, action, action_arg)) - raise StorageError(-5, "The device storage is full") - - dev._send = send - with pytest.raises(StorageError): - run(dev.set_fan_mode(lifaair.FanMode.TURBO)) - assert calls == [ - ( - lifaair._Operation.SET_STATE, - lifaair._Action.SET_FAN_MODE, - 7, - ) - ] - - -def test_set_fan_speed_sends_one_speed_argument(): - """Speed is one SET_FAN_SPEED packet, including 0 and OFF.""" - dev = device() - calls: list = [] - cases = ( - (70, 0x85, 0x46, 0xC0, lifaair.FanMode.MANUAL, 70), - (0, 0x85, 0x00, 0xC0, lifaair.FanMode.MANUAL, 0), - (121, 0x85, 0x79, 0xC0, lifaair.FanMode.MANUAL, 121), - (50, 0x81, 0x32, 0xC0, lifaair.FanMode.OFF, 50), - ) - for speed, fan, raw_speed, flags, mode, expect_speed in cases: - calls.clear() - script(dev, calls, response(fan, raw_speed, flags)) - state = run(dev.set_fan_speed(speed)) - assert calls == [ - ( - lifaair._Operation.SET_STATE, - lifaair._Action.SET_FAN_SPEED, - speed, - ) - ] - assert state["fan_mode"] == mode - assert state["fan_speed"] == expect_speed - assert state["purifier_online"] is True -def test_set_fan_speed_rejects_values_that_cannot_be_encoded(): - """Only ints in 0..121 are sent.""" +def test_set_fan_speed_rejects_out_of_range(): + """Speeds outside 0..121 are rejected.""" dev = device() - calls: list = [] - script(dev, calls, response(0x85, 50, 0xC0)) - for speed in (-1, 122, True, "50"): + for speed in (-1, 122): with pytest.raises(ValueError): run(dev.set_fan_speed(speed)) - assert calls == [] - - -def test_device_error_minus_5_is_storage_error(): - """A response error of -5 is StorageError, and the command is not resent.""" - dev = device() - calls: list = [] - - async def send_packet(packet_type, packet): - calls.append((packet_type, bytes(packet))) - frame = bytearray(0x38) - frame[0x22:0x24] = (-5 & 0xFFFF).to_bytes(2, "little") - return bytes(frame) - - dev.send_packet = send_packet - with pytest.raises(StorageError) as err: - run(dev.set_fan_mode(lifaair.FanMode.TURBO)) - assert err.value.errno == -5 - assert len(calls) == 1 - assert calls[0][0] == 0x6A def test_bit0_clear_decodes_as_the_same_mode(): @@ -370,11 +204,7 @@ def test_bit0_clear_decodes_as_the_same_mode(): (0xA4, 0x1E, 0xC0, lifaair.FanMode.AUTO, 30), (0x80, 0x00, 0xC0, lifaair.FanMode.OFF, 0), ) - dev = device() for fan, speed, flags, mode, expect_speed in cases: - state = dev._decode_state(response(fan, speed, flags)) + state = device()._decode_state(response(fan, speed, flags)) assert state["fan_mode"] == mode assert state["fan_speed"] == expect_speed - assert state["purifier_online"] is True - assert state["temperature"] == 26.7 - assert state["humidity"] == 22 From ce2b96d43a1238e5060efc45a6a86cbba7ab0da3 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 13:32:53 +0000 Subject: [PATCH 9/9] Give the LM05 a new UDP port for every request MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The LM05 stops answering a source port after 10 received packets, and a new port works with the same session key. lifaair drops its endpoint after each exchange; other devices keep the one they already hold. Co-authored-by: Piotr Paczyński --- CHANGELOG.md | 3 +- broadlink_async/device.py | 127 +++++++++++++++++++----------------- broadlink_async/purifier.py | 4 ++ tests/test_lifaair.py | 41 +++++++++++- 4 files changed, 114 insertions(+), 61 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63a93f7..e3cf84f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,8 @@ Keep a Changelog; versions follow Semantic Versioning. - The LIFAair LM05 air purifier (0x4EC2) is supported as `lifaair`: station readings (CO2, TVOC, formaldehyde, PM1, PM2.5, PM10), the purifier's temperature and humidity, and fan mode and speed, with - matching CLI options. Contributed by pit3k. + matching CLI options. Each request uses a new UDP source port. + Contributed by pit3k. ## 1.3.0 - 2026-11-16 diff --git a/broadlink_async/device.py b/broadlink_async/device.py index 81c0ac3..ddb7037 100644 --- a/broadlink_async/device.py +++ b/broadlink_async/device.py @@ -263,6 +263,9 @@ class Device: TYPE = "Unknown" + # Close the UDP endpoint after every request so the next one binds a new port. + _fresh_endpoint_per_request = False + __INIT_KEY = "097628343fe99e23765c1513accf8b02" __INIT_VECT = "562e17996d093d28ddb3ba695a2e6f58" @@ -562,71 +565,77 @@ async def _exchange(self, packet: bytes) -> bytes: device has not used recently is accepted, for firmware that may not echo it. """ - transport, protocol = await self._endpoint() - protocol.drain() - loop = asyncio.get_running_loop() - start = loop.time() - timeout = self.timeout - count = int.from_bytes(packet[0x28:0x2A], "little") - self._recent.append(count) - sends = 0 - - while True: - transport.sendto(packet) - sends += 1 - if sends > 1: - _LOGGER.debug("%s: no reply, resending (%d)", self.host[0], sends) - resend_at = loop.time() + DEFAULT_RETRY_INTVL + try: + transport, protocol = await self._endpoint() + protocol.drain() + loop = asyncio.get_running_loop() + start = loop.time() + timeout = self.timeout + count = int.from_bytes(packet[0x28:0x2A], "little") + self._recent.append(count) + sends = 0 + while True: - now = loop.time() - if now - start >= timeout: - break - wait = min(resend_at, start + timeout) - now - try: - resp, _ = await asyncio.wait_for(protocol.queue.get(), max(wait, 0)) - except TimeoutError: - if loop.time() - start >= timeout: + transport.sendto(packet) + sends += 1 + if sends > 1: + _LOGGER.debug("%s: no reply, resending (%d)", self.host[0], sends) + resend_at = loop.time() + DEFAULT_RETRY_INTVL + while True: + now = loop.time() + if now - start >= timeout: break - if loop.time() >= resend_at: - break # Resend. - continue - if resp is None: - raise e.EndpointClosedError( - -4013, "Endpoint closed", "The device endpoint was closed" - ) - if _is_silence(resp): - # ICMP unreachable of one kind or another: the host is up - # with nothing listening, the device is off or rebooting, - # or a router answered for it. The original library's - # unconnected socket never saw these, so keep waiting and - # let the timeout decide, as it did. + wait = min(resend_at, start + timeout) - now + try: + resp, _ = await asyncio.wait_for( + protocol.queue.get(), max(wait, 0) + ) + except TimeoutError: + if loop.time() - start >= timeout: + break + if loop.time() >= resend_at: + break # Resend. + continue + if resp is None: + raise e.EndpointClosedError( + -4013, "Endpoint closed", "The device endpoint was closed" + ) + if _is_silence(resp): + # ICMP unreachable of one kind or another: the host is up + # with nothing listening, the device is off or rebooting, + # or a router answered for it. The original library's + # unconnected socket never saw these, so keep waiting and + # let the timeout decide, as it did. + _LOGGER.debug( + "%s: unreachable (%s), still waiting", self.host[0], resp + ) + continue + if isinstance(resp, Exception): + # A send failure (no route, address gone) or a fatal + # transport error: fail now and throw the socket away. + _LOGGER.debug("%s: socket error: %s", self.host[0], resp) + self._drop_endpoint() + raise resp + resp = self._validate(resp) + reply_count = int.from_bytes(resp[0x28:0x2A], "little") + if reply_count == count or reply_count not in self._recent: + return resp _LOGGER.debug( - "%s: unreachable (%s), still waiting", self.host[0], resp + "%s: dropped a reply for an earlier request (counter 0x%04x)", + self.host[0], + reply_count, ) - continue - if isinstance(resp, Exception): - # A send failure (no route, address gone) or a fatal - # transport error: fail now and throw the socket away. - _LOGGER.debug("%s: socket error: %s", self.host[0], resp) + if loop.time() - start >= timeout: + _LOGGER.debug("%s: no reply within %ss", self.host[0], timeout) self._drop_endpoint() - raise resp - resp = self._validate(resp) - reply_count = int.from_bytes(resp[0x28:0x2A], "little") - if reply_count == count or reply_count not in self._recent: - return resp - _LOGGER.debug( - "%s: dropped a reply for an earlier request (counter 0x%04x)", - self.host[0], - reply_count, - ) - if loop.time() - start >= timeout: - _LOGGER.debug("%s: no reply within %ss", self.host[0], timeout) + raise e.NetworkTimeoutError( + -4000, + "Network timeout", + f"No response received within {timeout}s", + ) from None + finally: + if self._fresh_endpoint_per_request: self._drop_endpoint() - raise e.NetworkTimeoutError( - -4000, - "Network timeout", - f"No response received within {timeout}s", - ) from None async def send_packet(self, packet_type: int, payload: bytes | bytearray) -> bytes: """Send a packet to the device and return the raw response frame. diff --git a/broadlink_async/purifier.py b/broadlink_async/purifier.py index 5802a0f..9dda1f0 100644 --- a/broadlink_async/purifier.py +++ b/broadlink_async/purifier.py @@ -16,6 +16,10 @@ class lifaair(Device): TYPE = "LIFAAIR" + # The LM05 stops answering a source port after 10 received packets. + # A new port works without a new login. + _fresh_endpoint_per_request = True + @enum.unique class FanMode(enum.IntEnum): """Enumerates fan modes.""" diff --git a/tests/test_lifaair.py b/tests/test_lifaair.py index 3ebe5b5..02f842c 100644 --- a/tests/test_lifaair.py +++ b/tests/test_lifaair.py @@ -9,8 +9,9 @@ import pytest +from broadlink_async import device as device_module from broadlink_async.purifier import lifaair -from tests.oracle.harness import HOST, MAC +from tests.oracle.harness import HOST, MAC, make_response def payload(raw_hex: str) -> bytes: @@ -197,6 +198,44 @@ def test_set_fan_speed_rejects_out_of_range(): run(dev.set_fan_speed(speed)) +def test_each_request_opens_a_new_endpoint(monkeypatch): + """Two requests leave on two source ports, and each port is closed.""" + opened = [] + + class _Port: + def __init__(self, protocol, port): + self.protocol = protocol + self.port = port + self.closed = False + + def sendto(self, data, addr=None): + self.protocol.queue.put_nowait((make_response(dev, b""), HOST)) + + def is_closing(self): + return self.closed + + def close(self): + self.closed = True + + async def open_endpoint(local_addr=None, remote_addr=None, broadcast=False): + protocol = device_module._Protocol() + transport = _Port(protocol, 10000 + len(opened)) + protocol.connection_made(transport) + opened.append(transport) + return transport, protocol + + monkeypatch.setattr(device_module, "_open_endpoint", open_endpoint) + dev = device() + + async def go(): + await dev.send_packet(0x6A, b"") + await dev.send_packet(0x6A, b"") + + run(go()) + assert [port.port for port in opened] == [10000, 10001] + assert all(port.closed for port in opened) + + def test_bit0_clear_decodes_as_the_same_mode(): """0x84, 0xA4 and 0x80 are MANUAL, AUTO and OFF.""" cases = (