diff --git a/CHANGELOG.md b/CHANGELOG.md index 07a6c45..e3cf84f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,16 @@ 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, PM1, PM2.5, PM10), the + purifier's temperature and humidity, and fan mode and speed, with + matching CLI options. Each request uses a new UDP source port. + Contributed by pit3k. + ## 1.3.0 - 2026-11-16 ### Added diff --git a/README.md b/README.md index 068a51a..64c9066 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 lifaair + +data = await device.get_state() +``` + +### Controlling purifier fan +```python3 +await device.set_fan_mode(lifaair.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..72b560e 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 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/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 new file mode 100644 index 0000000..9dda1f0 --- /dev/null +++ b/broadlink_async/purifier.py @@ -0,0 +1,224 @@ +"""Support for air purifiers.""" + +import enum + +from . import exceptions as e +from .device import Device + + +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" + + # 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.""" + + 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 = { + 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": lifaair.FanMode.AUTO, # lifaair.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 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, self.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/README.md b/cli/README.md index 0b7099b..52238fe 100644 --- a/cli/README.md +++ b/cli/README.md @@ -154,3 +154,20 @@ broadlink_cli --device @BEDROOM.device --checknl ``` broadlink_cli --device @BEDROOM.device --energy ``` + +### Air purifiers + +#### Get state +``` +broadlink_cli --device @BEDROOM.device --getstate +``` + +#### 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..b922b3b 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,11 @@ 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: + 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)) if args.convert: data = bytearray.fromhex(''.join(args.data)) diff --git a/tests/oracle/cases.py b/tests/oracle/cases.py index 8526f09..70b4d38 100644 --- a/tests/oracle/cases.py +++ b/tests/oracle/cases.py @@ -83,6 +83,33 @@ def a1_payload(temp=(23, 5), hum=(45, 2), light=2, air=1, noise=0) -> str: return p.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: p = bytearray(0x18) p[0x0D:0x0F] = (12).to_bytes(2, "big") # pm10 @@ -418,6 +445,68 @@ 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 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_state_data( + temperature=267, + co2=907, + tvoc=9, + pm1=1, + pm10=1, + fan_state=0x8D, + fan_speed=121, + ).hex() + ], + ) + ) + # Speed 50: fan state 0x85, speed 50. + add( + case( + "lifaair", + 0x4EC2, + "set_fan_speed", + 50, + responses=[ + lifaair_state_data( + temperature=267, + co2=905, + tvoc=10, + pm1=2, + pm10=2, + fan_state=0x85, + fan_speed=50, + ).hex() + ], + ) + ) + # Lights ------------------------------------------------------------ lb_state = { "red": 128, @@ -678,4 +767,13 @@ def error_cases() -> list[dict]: "responses": [EMPTY], "error_code": 0xFFF9, }, + { + "cls": "lifaair", + "devtype": 0x4EC2, + "method": "set_fan_mode", + "args": [3], # lifaair.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..02f842c --- /dev/null +++ b/tests/test_lifaair.py @@ -0,0 +1,249 @@ +"""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 import device as device_module +from broadlink_async.purifier import lifaair +from tests.oracle.harness import HOST, MAC, make_response + + +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(HOST, MAC, 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", + 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", + 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", + 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", + 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" +) +# 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 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 test_offline_purifier_climate_and_mode_are_none(): + """Unplugged and unpaired both report 0x01 with zero climate bytes.""" + 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 + + +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 + state = decode(AFTER_RECONNECT) + assert state["temperature"] == 26.4 + assert state["humidity"] == 22 + + +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["formaldehyde"] == 0.0 + assert state["pm1"] == 12 + assert state["pm2_5"] == 39 + assert state["pm10"] == 128 + + +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", + 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", + 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", + 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", + 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", + 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", + 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", + lifaair.FanMode.MANUAL, + 50, + ), + ) + for raw_hex, mode, speed in cases: + state = decode(raw_hex) + assert state["fan_mode"] == mode + assert state["fan_speed"] == speed + + +def test_set_fan_mode_without_a_command_raises(): + """MANUAL, UNKNOWN and None have no mode argument.""" + dev = device() + for mode in (lifaair.FanMode.MANUAL, lifaair.FanMode.UNKNOWN, None): + with pytest.raises(ValueError): + run(dev.set_fan_mode(mode)) + + +def test_set_fan_speed_rejects_out_of_range(): + """Speeds outside 0..121 are rejected.""" + dev = device() + for speed in (-1, 122): + with pytest.raises(ValueError): + 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 = ( + (0x84, 0x32, 0xC0, lifaair.FanMode.MANUAL, 50), + (0xA4, 0x1E, 0xC0, lifaair.FanMode.AUTO, 30), + (0x80, 0x00, 0xC0, lifaair.FanMode.OFF, 0), + ) + for fan, speed, flags, mode, expect_speed in cases: + state = device()._decode_state(response(fan, speed, flags)) + assert state["fan_mode"] == mode + assert state["fan_speed"] == expect_speed 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"),