-
-
Notifications
You must be signed in to change notification settings - Fork 568
/
airpurifier_miot.py
562 lines (484 loc) · 17.5 KB
/
airpurifier_miot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
import enum
import logging
from typing import Any, Dict, Optional
import click
from .airfilter_util import FilterType, FilterTypeUtil
from .click_common import EnumType, command, format_output
from .exceptions import DeviceException
from .miot_device import MiotDevice
_LOGGER = logging.getLogger(__name__)
_MAPPING = {
# Air Purifier (siid=2)
"power": {"siid": 2, "piid": 2},
"fan_level": {"siid": 2, "piid": 4},
"mode": {"siid": 2, "piid": 5},
# Environment (siid=3)
"humidity": {"siid": 3, "piid": 7},
"temperature": {"siid": 3, "piid": 8},
"aqi": {"siid": 3, "piid": 6},
# Filter (siid=4)
"filter_life_remaining": {"siid": 4, "piid": 3},
"filter_hours_used": {"siid": 4, "piid": 5},
# Alarm (siid=5)
"buzzer": {"siid": 5, "piid": 1},
"buzzer_volume": {"siid": 5, "piid": 2},
# Indicator Light (siid=6)
"led_brightness": {"siid": 6, "piid": 1},
"led": {"siid": 6, "piid": 6},
# Physical Control Locked (siid=7)
"child_lock": {"siid": 7, "piid": 1},
# Motor Speed (siid=10)
"favorite_level": {"siid": 10, "piid": 10},
"favorite_rpm": {"siid": 10, "piid": 7},
"motor_speed": {"siid": 10, "piid": 8},
# Use time (siid=12)
"use_time": {"siid": 12, "piid": 1},
# AQI (siid=13)
"purify_volume": {"siid": 13, "piid": 1},
"average_aqi": {"siid": 13, "piid": 2},
# RFID (siid=14)
"filter_rfid_tag": {"siid": 14, "piid": 1},
"filter_rfid_product_id": {"siid": 14, "piid": 3},
# Other (siid=15)
"app_extra": {"siid": 15, "piid": 1},
}
# https://miot-spec.org/miot-spec-v2/instance?type=urn:miot-spec-v2:device:air-purifier:0000A007:zhimi-mb4:2
_MODEL_AIRPURIFIER_MB4 = {
# Air Purifier
"power": {"siid": 2, "piid": 1},
"mode": {"siid": 2, "piid": 4},
# Environment
"aqi": {"siid": 3, "piid": 4},
# Filter
"filter_life_remaining": {"siid": 4, "piid": 1},
"filter_hours_used": {"siid": 4, "piid": 3},
# Alarm
"buzzer": {"siid": 6, "piid": 1},
# Screen
"led_brightness_level": {"siid": 7, "piid": 2},
# Physical Control Locked
"child_lock": {"siid": 8, "piid": 1},
# custom-service
"motor_speed": {"siid": 9, "piid": 1},
"favorite_rpm": {"siid": 9, "piid": 3},
}
class AirPurifierMiotException(DeviceException):
pass
class OperationMode(enum.Enum):
Auto = 0
Silent = 1
Favorite = 2
Fan = 3
class LedBrightness(enum.Enum):
Bright = 0
Dim = 1
Off = 2
class BasicAirPurifierMiotStatus:
"""Container for status reports from the air purifier."""
def __init__(self, data: Dict[str, Any]) -> None:
self.filter_type_util = FilterTypeUtil()
self.data = data
@property
def is_on(self) -> bool:
"""Return True if device is on."""
return self.data["power"]
@property
def power(self) -> str:
"""Power state."""
return "on" if self.is_on else "off"
@property
def aqi(self) -> int:
"""Air quality index."""
# zhimi-airpurifier-mb3 returns 1 as AQI value if the measurement was
# unsuccessful
if self.data["aqi"] == 1:
return None
return self.data["aqi"]
@property
def mode(self) -> OperationMode:
"""Current operation mode."""
return OperationMode(self.data["mode"])
@property
def buzzer(self) -> Optional[bool]:
"""Return True if buzzer is on."""
if self.data["buzzer"] is not None:
return self.data["buzzer"]
return None
@property
def child_lock(self) -> bool:
"""Return True if child lock is on."""
return self.data["child_lock"]
@property
def filter_life_remaining(self) -> int:
"""Time until the filter should be changed."""
return self.data["filter_life_remaining"]
@property
def filter_hours_used(self) -> int:
"""How long the filter has been in use."""
return self.data["filter_hours_used"]
@property
def motor_speed(self) -> int:
"""Speed of the motor."""
return self.data["motor_speed"]
class AirPurifierMiotStatus(BasicAirPurifierMiotStatus):
"""Container for status reports from the air purifier."""
@property
def average_aqi(self) -> int:
"""Average of the air quality index."""
return self.data["average_aqi"]
@property
def humidity(self) -> int:
"""Current humidity."""
return self.data["humidity"]
@property
def temperature(self) -> Optional[float]:
"""Current temperature, if available."""
if self.data["temperature"] is not None:
return round(self.data["temperature"], 1)
return None
@property
def fan_level(self) -> int:
"""Current fan level."""
return self.data["fan_level"]
@property
def led(self) -> bool:
"""Return True if LED is on."""
return self.data["led"]
@property
def led_brightness(self) -> Optional[LedBrightness]:
"""Brightness of the LED."""
if self.data["led_brightness"] is not None:
try:
return LedBrightness(self.data["led_brightness"])
except ValueError:
return None
return None
@property
def buzzer_volume(self) -> Optional[int]:
"""Return buzzer volume."""
if self.data["buzzer_volume"] is not None:
return self.data["buzzer_volume"]
return None
@property
def favorite_level(self) -> int:
"""Return favorite level, which is used if the mode is ``favorite``."""
# Favorite level used when the mode is `favorite`.
return self.data["favorite_level"]
@property
def use_time(self) -> int:
"""How long the device has been active in seconds."""
return self.data["use_time"]
@property
def purify_volume(self) -> int:
"""The volume of purified air in cubic meter."""
return self.data["purify_volume"]
@property
def filter_rfid_product_id(self) -> Optional[str]:
"""RFID product ID of installed filter."""
return self.data["filter_rfid_product_id"]
@property
def filter_rfid_tag(self) -> Optional[str]:
"""RFID tag ID of installed filter."""
return self.data["filter_rfid_tag"]
@property
def filter_type(self) -> Optional[FilterType]:
"""Type of installed filter."""
return self.filter_type_util.determine_filter_type(
self.filter_rfid_tag, self.filter_rfid_product_id
)
def __repr__(self) -> str:
s = (
"<AirPurifierMiotStatus power=%s, "
"aqi=%s, "
"average_aqi=%s, "
"temperature=%s, "
"humidity=%s%%, "
"fan_level=%s, "
"mode=%s, "
"led=%s, "
"led_brightness=%s, "
"buzzer=%s, "
"buzzer_volume=%s, "
"child_lock=%s, "
"favorite_level=%s, "
"filter_life_remaining=%s, "
"filter_hours_used=%s, "
"use_time=%s, "
"purify_volume=%s, "
"motor_speed=%s, "
"filter_rfid_product_id=%s, "
"filter_rfid_tag=%s, "
"filter_type=%s>"
% (
self.power,
self.aqi,
self.average_aqi,
self.temperature,
self.humidity,
self.fan_level,
self.mode,
self.led,
self.led_brightness,
self.buzzer,
self.buzzer_volume,
self.child_lock,
self.favorite_level,
self.filter_life_remaining,
self.filter_hours_used,
self.use_time,
self.purify_volume,
self.motor_speed,
self.filter_rfid_product_id,
self.filter_rfid_tag,
self.filter_type,
)
)
return s
class AirPurifierMB4Status(BasicAirPurifierMiotStatus):
"""
Container for status reports from the Mi Air Purifier 3C (zhimi.airpurifier.mb4).
{
'power': True,
'mode': 1,
'aqi': 2,
'filter_life_remaining': 97,
'filter_hours_used': 100,
'buzzer': True,
'led_brightness_level': 8,
'child_lock': False,
'motor_speed': 392,
'favorite_rpm': 500
}
Response (MIoT format)
[
{'did': 'power', 'siid': 2, 'piid': 1, 'code': 0, 'value': True},
{'did': 'mode', 'siid': 2, 'piid': 4, 'code': 0, 'value': 1},
{'did': 'aqi', 'siid': 3, 'piid': 4, 'code': 0, 'value': 3},
{'did': 'filter_life_remaining', 'siid': 4, 'piid': 1, 'code': 0, 'value': 97},
{'did': 'filter_hours_used', 'siid': 4, 'piid': 3, 'code': 0, 'value': 100},
{'did': 'buzzer', 'siid': 6, 'piid': 1, 'code': 0, 'value': True},
{'did': 'led_brightness_level', 'siid': 7, 'piid': 2, 'code': 0, 'value': 8},
{'did': 'child_lock', 'siid': 8, 'piid': 1, 'code': 0, 'value': False},
{'did': 'motor_speed', 'siid': 9, 'piid': 1, 'code': 0, 'value': 388},
{'did': 'favorite_rpm', 'siid': 9, 'piid': 3, 'code': 0, 'value': 500}
]
"""
@property
def led_brightness_level(self) -> int:
"""Return brightness level."""
return self.data["led_brightness_level"]
@property
def favorite_rpm(self) -> int:
"""Return favorite rpm level."""
return self.data["favorite_rpm"]
def __repr__(self) -> str:
s = (
"<AirPurifierMiotStatus power=%s, "
"aqi=%s, "
"mode=%s, "
"led_brightness_level=%s, "
"buzzer=%s, "
"child_lock=%s, "
"filter_life_remaining=%s, "
"filter_hours_used=%s, "
"motor_speed=%s, "
"favorite_rpm=%s>"
% (
self.power,
self.aqi,
self.mode,
self.led_brightness_level,
self.buzzer,
self.child_lock,
self.filter_life_remaining,
self.filter_hours_used,
self.motor_speed,
self.favorite_rpm,
)
)
return s
class BasicAirPurifierMiot(MiotDevice):
"""Main class representing the air purifier which uses MIoT protocol."""
@command(default_output=format_output("Powering on"))
def on(self):
"""Power on."""
return self.set_property("power", True)
@command(default_output=format_output("Powering off"))
def off(self):
"""Power off."""
return self.set_property("power", False)
@command(
click.argument("rpm", type=int),
default_output=format_output("Setting favorite motor speed '{rpm}' rpm"),
)
def set_favorite_rpm(self, rpm: int):
"""Set favorite motor speed."""
# Note: documentation says the maximum is 2300, however, the purifier may return an error for rpm over 2200.
if rpm < 300 or rpm > 2300 or rpm % 10 != 0:
raise AirPurifierMiotException(
"Invalid favorite motor speed: %s. Must be between 300 and 2300 and divisible by 10"
% rpm
)
return self.set_property("favorite_rpm", rpm)
@command(
click.argument("mode", type=EnumType(OperationMode)),
default_output=format_output("Setting mode to '{mode.value}'"),
)
def set_mode(self, mode: OperationMode):
"""Set mode."""
return self.set_property("mode", mode.value)
@command(
click.argument("buzzer", type=bool),
default_output=format_output(
lambda buzzer: "Turning on buzzer" if buzzer else "Turning off buzzer"
),
)
def set_buzzer(self, buzzer: bool):
"""Set buzzer on/off."""
return self.set_property("buzzer", buzzer)
@command(
click.argument("lock", type=bool),
default_output=format_output(
lambda lock: "Turning on child lock" if lock else "Turning off child lock"
),
)
def set_child_lock(self, lock: bool):
"""Set child lock on/off."""
return self.set_property("child_lock", lock)
class AirPurifierMiot(BasicAirPurifierMiot):
"""Main class representing the air purifier which uses MIoT protocol."""
def __init__(
self,
ip: str = None,
token: str = None,
start_id: int = 0,
debug: int = 0,
lazy_discover: bool = True,
) -> None:
super().__init__(_MAPPING, ip, token, start_id, debug, lazy_discover)
@command(
default_output=format_output(
"",
"Power: {result.power}\n"
"AQI: {result.aqi} μg/m³\n"
"Average AQI: {result.average_aqi} μg/m³\n"
"Humidity: {result.humidity} %\n"
"Temperature: {result.temperature} °C\n"
"Fan Level: {result.fan_level}\n"
"Mode: {result.mode}\n"
"LED: {result.led}\n"
"LED brightness: {result.led_brightness}\n"
"Buzzer: {result.buzzer}\n"
"Buzzer vol.: {result.buzzer_volume}\n"
"Child lock: {result.child_lock}\n"
"Favorite level: {result.favorite_level}\n"
"Filter life remaining: {result.filter_life_remaining} %\n"
"Filter hours used: {result.filter_hours_used}\n"
"Use time: {result.use_time} s\n"
"Purify volume: {result.purify_volume} m³\n"
"Motor speed: {result.motor_speed} rpm\n"
"Filter RFID product id: {result.filter_rfid_product_id}\n"
"Filter RFID tag: {result.filter_rfid_tag}\n"
"Filter type: {result.filter_type}\n",
)
)
def status(self) -> AirPurifierMiotStatus:
"""Retrieve properties."""
return AirPurifierMiotStatus(
{
prop["did"]: prop["value"] if prop["code"] == 0 else None
for prop in self.get_properties_for_mapping()
}
)
@command(
click.argument("level", type=int),
default_output=format_output("Setting fan level to '{level}'"),
)
def set_fan_level(self, level: int):
"""Set fan level."""
if level < 1 or level > 3:
raise AirPurifierMiotException("Invalid fan level: %s" % level)
return self.set_property("fan_level", level)
@command(
click.argument("volume", type=int),
default_output=format_output("Setting sound volume to {volume}"),
)
def set_volume(self, volume: int):
"""Set buzzer volume."""
if volume < 0 or volume > 100:
raise AirPurifierMiotException(
"Invalid volume: %s. Must be between 0 and 100" % volume
)
return self.set_property("buzzer_volume", volume)
@command(
click.argument("level", type=int),
default_output=format_output("Setting favorite level to {level}"),
)
def set_favorite_level(self, level: int):
"""Set the favorite level used when the mode is `favorite`.
Needs to be between 0 and 14.
"""
if level < 0 or level > 14:
raise AirPurifierMiotException("Invalid favorite level: %s" % level)
return self.set_property("favorite_level", level)
@command(
click.argument("brightness", type=EnumType(LedBrightness)),
default_output=format_output("Setting LED brightness to {brightness}"),
)
def set_led_brightness(self, brightness: LedBrightness):
"""Set led brightness."""
return self.set_property("led_brightness", brightness.value)
@command(
click.argument("led", type=bool),
default_output=format_output(
lambda led: "Turning on LED" if led else "Turning off LED"
),
)
def set_led(self, led: bool):
"""Turn led on/off."""
return self.set_property("led", led)
class AirPurifierMB4(BasicAirPurifierMiot):
"""Main class representing the air purifier which uses MIoT protocol."""
def __init__(
self,
ip: str = None,
token: str = None,
start_id: int = 0,
debug: int = 0,
lazy_discover: bool = True,
) -> None:
super().__init__(
_MODEL_AIRPURIFIER_MB4, ip, token, start_id, debug, lazy_discover
)
@command(
default_output=format_output(
"",
"Power: {result.power}\n"
"AQI: {result.aqi} μg/m³\n"
"Mode: {result.mode}\n"
"LED brightness level: {result.led_brightness_level}\n"
"Buzzer: {result.buzzer}\n"
"Child lock: {result.child_lock}\n"
"Filter life remaining: {result.filter_life_remaining} %\n"
"Filter hours used: {result.filter_hours_used}\n"
"Motor speed: {result.motor_speed} rpm\n"
"Favorite RPM: {result.favorite_rpm} rpm\n",
)
)
def status(self) -> AirPurifierMB4Status:
"""Retrieve properties."""
return AirPurifierMB4Status(
{
prop["did"]: prop["value"] if prop["code"] == 0 else None
for prop in self.get_properties_for_mapping()
}
)
@command(
click.argument("level", type=int),
default_output=format_output("Setting LED brightness level to {level}"),
)
def set_led_brightness_level(self, level: int):
"""Set led brightness level (0..8)."""
if level < 0 or level > 8:
raise AirPurifierMiotException("Invalid brightness level: %s" % level)
return self.set_property("led_brightness_level", level)