forked from Bluetooth-Devices/xiaomi-ble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.py
1996 lines (1783 loc) · 69.6 KB
/
parser.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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Parser for Xiaomi BLE advertisements.
This file is shamlessly copied from the following repository:
https://github.com/Ernst79/bleparser/blob/c42ae922e1abed2720c7fac993777e1bd59c0c93/package/bleparser/xiaomi.py
MIT License applies.
"""
from __future__ import annotations
import datetime
import logging
import math
import struct
from typing import Any
from bleak import BleakClient
from bleak.backends.device import BLEDevice
from bleak_retry_connector import establish_connection
from bluetooth_data_tools import short_address
from bluetooth_sensor_state_data import BluetoothData
from Cryptodome.Cipher import AES
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESCCM
from home_assistant_bluetooth import BluetoothServiceInfo
from sensor_state_data import (
BinarySensorDeviceClass,
SensorLibrary,
SensorUpdate,
Units,
)
from .const import (
CHARACTERISTIC_BATTERY,
SERVICE_HHCCJCY10,
SERVICE_MIBEACON,
SERVICE_SCALE1,
SERVICE_SCALE2,
TIMEOUT_1DAY,
EncryptionScheme,
ExtendedBinarySensorDeviceClass,
ExtendedSensorDeviceClass,
)
from .devices import DEVICE_TYPES, SLEEPY_DEVICE_MODELS
from .events import EventDeviceKeys
from .locks import BLE_LOCK_ACTION, BLE_LOCK_ERROR, BLE_LOCK_METHOD
_LOGGER = logging.getLogger(__name__)
def to_mac(addr: bytes) -> str:
"""Return formatted MAC address"""
return ":".join(f"{i:02X}" for i in addr)
def to_unformatted_mac(addr: str) -> str:
"""Return unformatted MAC address"""
return "".join(f"{i:02X}" for i in addr[:])
def parse_event_properties(
event_property: str | None, value: int
) -> dict[str, int | None] | None:
"""Convert event property and data to event properties."""
if event_property:
return {event_property: value}
return None
# Structured objects for data conversions
TH_STRUCT = struct.Struct("<hH")
H_STRUCT = struct.Struct("<H")
T_STRUCT = struct.Struct("<h")
TTB_STRUCT = struct.Struct("<hhB")
CND_STRUCT = struct.Struct("<H")
ILL_STRUCT = struct.Struct("<I")
LIGHT_STRUCT = struct.Struct("<I")
FMDH_STRUCT = struct.Struct("<H")
M_STRUCT = struct.Struct("<L")
P_STRUCT = struct.Struct("<H")
BUTTON_STRUCT = struct.Struct("<BBB")
FLOAT_STRUCT = struct.Struct("<f")
# Advertisement conversion of measurement data
# https://iot.mi.com/new/doc/accesses/direct-access/embedded-development/ble/object-definition
def obj0003(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Motion"""
# 0x0003 is only used by MUE4094RT, which does not send motion clear.
# This object is therefore added as event (motion detected).
device.fire_event(
key=EventDeviceKeys.MOTION,
event_type="motion_detected",
event_properties=None,
)
return {}
def obj0006(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Fingerprint"""
if len(xobj) == 5:
key_id_bytes = xobj[0:4]
match_byte = xobj[4]
if key_id_bytes == b"\x00\x00\x00\x00":
key_type = "administrator"
elif key_id_bytes == b"\xff\xff\xff\xff":
key_type = "unknown operator"
elif key_id_bytes == b"\xde\xad\xbe\xef":
key_type = "invalid operator"
else:
key_type = str(int.from_bytes(key_id_bytes, "little"))
if match_byte == 0x00:
result = "match_successful"
elif match_byte == 0x01:
result = "match_failed"
elif match_byte == 0x02:
result = "timeout"
elif match_byte == 0x033:
result = "low_quality_too_light_fuzzy"
elif match_byte == 0x04:
result = "insufficient_area"
elif match_byte == 0x05:
result = "skin_is_too_dry"
elif match_byte == 0x06:
result = "skin_is_too_wet"
else:
result = None
fingerprint = True if match_byte == 0x00 else False
# Update fingerprint binary sensor
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.FINGERPRINT,
native_value=fingerprint,
device_class=ExtendedBinarySensorDeviceClass.FINGERPRINT,
name="Fingerprint",
)
# Update key_id sensor
device.update_sensor(
key=ExtendedSensorDeviceClass.KEY_ID,
name="Key id",
device_class=ExtendedSensorDeviceClass.KEY_ID,
native_value=key_type,
native_unit_of_measurement=None,
)
# Fire Fingerprint action event
if result:
device.fire_event(
key=EventDeviceKeys.FINGERPRINT,
event_type=result,
event_properties=None,
)
return {}
def obj0007(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Door"""
door_byte = xobj[0]
if door_byte == 0x00:
# open the door
device.update_predefined_binary_sensor(BinarySensorDeviceClass.DOOR, True)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.DOOR_STUCK,
native_value=False, # reset door stuck
device_class=ExtendedBinarySensorDeviceClass.DOOR_STUCK,
name="Door stuck",
)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.KNOCK_ON_THE_DOOR,
native_value=False, # reset knock on the door
device_class=ExtendedBinarySensorDeviceClass.KNOCK_ON_THE_DOOR,
name="Knock on the door",
)
elif door_byte == 0x01:
# close the door
device.update_predefined_binary_sensor(BinarySensorDeviceClass.DOOR, False)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.DOOR_LEFT_OPEN,
native_value=False, # reset door left open
device_class=ExtendedBinarySensorDeviceClass.DOOR_LEFT_OPEN,
name="Door left open",
)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.PRY_THE_DOOR,
native_value=False, # reset pry the door
device_class=ExtendedBinarySensorDeviceClass.PRY_THE_DOOR,
name="Pry the door",
)
elif door_byte == 0x02:
# timeout, not closed
device.update_predefined_binary_sensor(BinarySensorDeviceClass.DOOR, True)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.DOOR_LEFT_OPEN,
native_value=True,
device_class=ExtendedBinarySensorDeviceClass.DOOR_LEFT_OPEN,
name="Door left open",
)
elif door_byte == 0x03:
# knock on the door
device.update_predefined_binary_sensor(BinarySensorDeviceClass.DOOR, False)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.KNOCK_ON_THE_DOOR,
native_value=True,
device_class=ExtendedBinarySensorDeviceClass.KNOCK_ON_THE_DOOR,
name="Knock on the door",
)
elif door_byte == 0x04:
# pry the door
device.update_predefined_binary_sensor(BinarySensorDeviceClass.DOOR, True)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.PRY_THE_DOOR,
native_value=True,
device_class=ExtendedBinarySensorDeviceClass.PRY_THE_DOOR,
name="Pry the door",
)
elif door_byte == 0x05:
# door stuck
device.update_predefined_binary_sensor(BinarySensorDeviceClass.DOOR, False)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.DOOR_STUCK,
native_value=True,
device_class=ExtendedBinarySensorDeviceClass.DOOR_STUCK,
name="Door stuck",
)
return {}
def obj0008(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""armed away"""
value = xobj[0] ^ 1
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.ARMED,
native_value=bool(value), # Armed away
device_class=ExtendedBinarySensorDeviceClass.ARMED,
name="Armed",
)
# Lift up door handle outside the door sends this event from DSL-C08.
if device_type == "DSL-C08":
device.update_predefined_binary_sensor(
BinarySensorDeviceClass.LOCK, bool(value)
)
# Fire Lock action event
device.fire_event(
key=EventDeviceKeys.LOCK,
event_type="lock_outside_the_door",
event_properties=None,
)
# # Update method sensor
device.update_sensor(
key=ExtendedSensorDeviceClass.LOCK_METHOD,
name="Lock method",
device_class=ExtendedSensorDeviceClass.LOCK_METHOD,
native_value="manual",
native_unit_of_measurement=None,
)
return {}
def obj0010(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Toothbrush"""
if xobj[0] == 0:
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.TOOTHBRUSH,
native_value=True, # Toothbrush On
device_class=ExtendedBinarySensorDeviceClass.TOOTHBRUSH,
name="Toothbrush",
)
else:
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.TOOTHBRUSH,
native_value=False, # Toothbrush Off
device_class=ExtendedBinarySensorDeviceClass.TOOTHBRUSH,
name="Toothbrush",
)
if len(xobj) > 1:
device.update_sensor(
key=ExtendedSensorDeviceClass.COUNTER,
name="Counter",
native_unit_of_measurement=Units.TIME_SECONDS,
device_class=ExtendedSensorDeviceClass.COUNTER,
native_value=xobj[1],
)
return {}
def obj000a(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Body Temperature"""
if len(xobj) == 2:
(temp,) = T_STRUCT.unpack(xobj)
if temp:
device.update_predefined_sensor(
SensorLibrary.TEMPERATURE__CELSIUS, temp / 100
)
return {}
def obj000b(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Lock"""
if len(xobj) == 9:
lock_action_int = xobj[0] & 0x0F
lock_method_int = xobj[0] >> 4
key_id = int.from_bytes(xobj[1:5], "little")
short_key_id = key_id & 0xFFFF
# Lock action (event) and lock method (sensor)
if (
lock_action_int not in BLE_LOCK_ACTION
or lock_method_int not in BLE_LOCK_METHOD
):
return {}
lock_action = BLE_LOCK_ACTION[lock_action_int][2]
lock_method = BLE_LOCK_METHOD[lock_method_int]
# Some specific key_ids represent an error
error = BLE_LOCK_ERROR.get(key_id)
if not error:
if key_id == 0x00000000:
key_type = "administrator"
elif key_id == 0xFFFFFFFF:
key_type = "unknown operator"
elif key_id == 0xDEADBEEF:
key_type = "invalid operator"
elif key_id <= 0x7FFFFFF:
# Bluetooth (up to 2147483647)
key_type = f"Bluetooth key {key_id}"
else:
# All other key methods have only key ids up to 65536
if key_id <= 0x8001FFFF:
key_type = f"Fingerprint key id {short_key_id}"
elif key_id <= 0x8002FFFF:
key_type = f"Password key id {short_key_id}"
elif key_id <= 0x8003FFFF:
key_type = f"Keys key id {short_key_id}"
elif key_id <= 0x8004FFFF:
key_type = f"NFC key id {short_key_id}"
elif key_id <= 0x8005FFFF:
key_type = f"Two-step verification key id {short_key_id}"
elif key_id <= 0x8006FFFF:
key_type = f"Human face key id {short_key_id}"
elif key_id <= 0x8007FFFF:
key_type = f"Finger veins key id {short_key_id}"
elif key_id <= 0x8008FFFF:
key_type = f"Palm print key id {short_key_id}"
else:
key_type = f"key id {short_key_id}"
# Lock type and state
# Lock type can be `lock` or for ZNMS17LM `lock`, `childlock` or `antilock`
if device_type == "ZNMS17LM":
# Lock type can be `lock`, `childlock` or `antilock`
lock_type = BLE_LOCK_ACTION[lock_action_int][1]
else:
# Lock type can only be `lock` for other locks
lock_type = "lock"
lock_state = BLE_LOCK_ACTION[lock_action_int][0]
# Update lock state
if lock_type == "lock":
device.update_predefined_binary_sensor(
BinarySensorDeviceClass.LOCK, lock_state
)
elif lock_type == "childlock":
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.CHILDLOCK,
native_value=lock_state,
device_class=ExtendedBinarySensorDeviceClass.CHILDLOCK,
name="Childlock",
)
elif lock_type == "antilock":
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.ANTILOCK,
native_value=lock_state,
device_class=ExtendedBinarySensorDeviceClass.ANTILOCK,
name="Antilock",
)
else:
return {}
# Update key_id sensor
device.update_sensor(
key=ExtendedSensorDeviceClass.KEY_ID,
name="Key id",
device_class=ExtendedSensorDeviceClass.KEY_ID,
native_value=key_type,
native_unit_of_measurement=None,
)
# Fire Lock action event: see BLE_LOCK_ACTTION
device.fire_event(
key=EventDeviceKeys.LOCK,
event_type=lock_action,
event_properties=None,
)
# # Update method sensor: see BLE_LOCK_METHOD
device.update_sensor(
key=ExtendedSensorDeviceClass.LOCK_METHOD,
name="Lock method",
device_class=ExtendedSensorDeviceClass.LOCK_METHOD,
native_value=lock_method.value,
native_unit_of_measurement=None,
)
if error:
# Fire event with the error: see BLE_LOCK_ERROR
device.fire_event(
key=EventDeviceKeys.ERROR,
event_type=error,
event_properties=None,
)
return {}
def obj000f(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Moving with light"""
if len(xobj) == 3:
(illum,) = LIGHT_STRUCT.unpack(xobj + b"\x00")
device.update_predefined_binary_sensor(BinarySensorDeviceClass.MOTION, True)
if device_type in ["MJYD02YL", "RTCGQ02LM"]:
# MJYD02YL: 1 - moving no light, 100 - moving with light
# RTCGQ02LM: 0 - moving no light, 256 - moving with light
device.update_predefined_binary_sensor(
BinarySensorDeviceClass.LIGHT, bool(illum >= 100)
)
elif device_type == "CGPR1":
# CGPR1: moving, value is illumination in lux
device.update_predefined_sensor(SensorLibrary.LIGHT__LIGHT_LUX, illum)
return {}
def obj1001(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""button"""
if len(xobj) != 3:
return {}
(button_type, value, press_type) = BUTTON_STRUCT.unpack(xobj)
# button_type represents the pressed button or rubiks cube rotation direction
remote_command = None
fan_remote_command = None
ven_fan_remote_command = None
bathroom_remote_command = None
cube_rotation = None
one_btn_switch = False
two_btn_switch_left = False
two_btn_switch_right = False
three_btn_switch_left = False
three_btn_switch_middle = False
three_btn_switch_right = False
if button_type == 0:
remote_command = "on"
fan_remote_command = "fan"
ven_fan_remote_command = "swing"
bathroom_remote_command = "stop"
one_btn_switch = True
two_btn_switch_left = True
three_btn_switch_left = True
cube_rotation = "rotate_right"
elif button_type == 1:
remote_command = "off"
fan_remote_command = "light"
ven_fan_remote_command = "power"
bathroom_remote_command = "air_exchange"
two_btn_switch_right = True
three_btn_switch_middle = True
cube_rotation = "rotate_left"
elif button_type == 2:
remote_command = "brightness"
fan_remote_command = "wind_speed"
ven_fan_remote_command = "timer_60_minutes"
bathroom_remote_command = "fan"
two_btn_switch_left = True
two_btn_switch_right = True
three_btn_switch_right = True
elif button_type == 3:
remote_command = "plus"
fan_remote_command = "color_temperature"
ven_fan_remote_command = "increase_wind_speed"
bathroom_remote_command = "increase_speed"
three_btn_switch_left = True
three_btn_switch_middle = True
elif button_type == 4:
remote_command = "M"
fan_remote_command = "wind_mode"
ven_fan_remote_command = "timer_30_minutes"
bathroom_remote_command = "decrease_speed"
three_btn_switch_middle = True
three_btn_switch_right = True
elif button_type == 5:
remote_command = "min"
fan_remote_command = "brightness"
ven_fan_remote_command = "decrease_wind_speed"
bathroom_remote_command = "dry"
three_btn_switch_left = True
three_btn_switch_right = True
elif button_type == 6:
bathroom_remote_command = "light"
three_btn_switch_left = True
three_btn_switch_middle = True
three_btn_switch_right = True
elif button_type == 7:
bathroom_remote_command = "swing"
elif button_type == 8:
bathroom_remote_command = "heat"
# press_type represents the type of press or rotate
# for dimmers, buton_type is used to represent the type of press
# for dimmers, value or button_type is used to represent the direction and number
# of steps, number of presses or duration of long press
button_press_type = "no_press"
btn_switch_press_type = None
dimmer_value: int = 0
if press_type == 0:
button_press_type = "press"
btn_switch_press_type = "press"
elif press_type == 1:
button_press_type = "double_press"
btn_switch_press_type = "long_press"
elif press_type == 2:
button_press_type = "long_press"
btn_switch_press_type = "double_press"
elif press_type == 3:
if button_type == 0:
button_press_type = "press"
dimmer_value = value
if button_type == 1:
button_press_type = "long_press"
dimmer_value = value
elif press_type == 4:
if button_type == 0:
if value <= 127:
button_press_type = "rotate_right"
dimmer_value = value
else:
button_press_type = "rotate_left"
dimmer_value = 256 - value
elif button_type <= 127:
button_press_type = "rotate_right_pressed"
dimmer_value = button_type
else:
button_press_type = "rotate_left_pressed"
dimmer_value = 256 - button_type
elif press_type == 5:
button_press_type = "press"
elif press_type == 6:
button_press_type = "long_press"
# return device specific output
if device_type in ["RTCGQ02LM", "YLAI003", "JTYJGD03MI", "SJWS01LM"]:
# RTCGQ02LM, JTYJGD03MI, SJWS01LM: press
# YLAI003: press, double_press or long_press
device.fire_event(
key=EventDeviceKeys.BUTTON,
event_type=button_press_type,
event_properties=None,
)
elif device_type == "XMMF01JQD":
# cube_rotation: rotate_left or rotate_right
device.fire_event(
key=EventDeviceKeys.CUBE,
event_type=cube_rotation,
event_properties=None,
)
elif device_type == "YLYK01YL":
# Buttons: on, off, brightness, plus, min, M
# Press types: press and long_press
if remote_command == "on":
device.update_predefined_binary_sensor(BinarySensorDeviceClass.POWER, True)
elif remote_command == "off":
device.update_predefined_binary_sensor(BinarySensorDeviceClass.POWER, False)
device.fire_event(
key=f"{str(EventDeviceKeys.BUTTON)}_{remote_command}",
event_type=button_press_type,
event_properties=None,
)
elif device_type == "YLYK01YL-FANRC":
# Buttons: fan, light, wind_speed, wind_mode, brightness, color_temperature
# Press types: press and long_press
device.fire_event(
key=f"{str(EventDeviceKeys.BUTTON)}_{fan_remote_command}",
event_type=button_press_type,
event_properties=None,
)
elif device_type == "YLYK01YL-VENFAN":
# Buttons: swing, power, timer_30_minutes, timer_60_minutes,
# increase_wind_speed, decrease_wind_speed
# Press types: press and long_press
device.fire_event(
key=f"{str(EventDeviceKeys.BUTTON)}_{ven_fan_remote_command}",
event_type=button_press_type,
event_properties=None,
)
elif device_type == "YLYB01YL-BHFRC":
# Buttons: heat, air_exchange, dry, fan, swing, decrease_speed, increase_speed,
# stop or light
# Press types: press and long_press
device.fire_event(
key=f"{str(EventDeviceKeys.BUTTON)}_{bathroom_remote_command}",
event_type=button_press_type,
event_properties=None,
)
elif device_type == "YLKG07YL/YLKG08YL":
# Dimmer reports: press, long_press, rotate_left, rotate_right,
# rotate_left_pressed or rotate_right_pressed
if button_press_type == "press":
# it also reports how many times you pressed the dimmer.
event_property = "number_of_presses"
elif button_press_type == "long_press":
# it also reports the duration (in seconds) you pressed the dimmer
event_property = "duration"
elif button_press_type in [
"rotate_right",
"rotate_left",
"rotate_right_pressed",
"rotate_left_pressed",
]:
# it reports how far you rotate, measured in number of `steps`.
event_property = "steps"
else:
event_property = None
event_properties = parse_event_properties(
event_property=event_property, value=dimmer_value
)
device.fire_event(
key=EventDeviceKeys.DIMMER,
event_type=button_press_type,
event_properties=event_properties,
)
elif device_type == "K9B-1BTN":
# Press types: press, double_press, long_press
if one_btn_switch:
device.fire_event(
key=EventDeviceKeys.BUTTON,
event_type=btn_switch_press_type,
event_properties=None,
)
elif device_type == "K9B-2BTN":
# Buttons: left and/or right
# Press types: press, double_press, long_press
# device can send button press of multiple buttons in one message
if two_btn_switch_left:
device.fire_event(
key=f"{str(EventDeviceKeys.BUTTON)}_left",
event_type=btn_switch_press_type,
event_properties=None,
)
if two_btn_switch_right:
device.fire_event(
key=f"{str(EventDeviceKeys.BUTTON)}_right",
event_type=btn_switch_press_type,
event_properties=None,
)
elif device_type == "K9B-3BTN":
# Buttons: left, middle and/or right
# result can be press, double_press or long_press
# device can send button press of multiple buttons in one message
if three_btn_switch_left:
device.fire_event(
key=f"{str(EventDeviceKeys.BUTTON)}_left",
event_type=btn_switch_press_type,
event_properties=None,
)
if three_btn_switch_middle:
device.fire_event(
key=f"{str(EventDeviceKeys.BUTTON)}_middle",
event_type=btn_switch_press_type,
event_properties=None,
)
if three_btn_switch_right:
device.fire_event(
key=f"{str(EventDeviceKeys.BUTTON)}_right",
event_type=btn_switch_press_type,
event_properties=None,
)
return {}
def obj1004(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Temperature"""
if len(xobj) == 2:
(temp,) = T_STRUCT.unpack(xobj)
device.update_predefined_sensor(SensorLibrary.TEMPERATURE__CELSIUS, temp / 10)
return {}
def obj1005(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Power on/off and Temperature"""
device.update_predefined_binary_sensor(BinarySensorDeviceClass.POWER, xobj[0])
device.update_predefined_sensor(SensorLibrary.TEMPERATURE__CELSIUS, xobj[1])
return {}
def obj1006(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Humidity"""
if len(xobj) == 2:
(humi,) = H_STRUCT.unpack(xobj)
if device_type in ["LYWSD03MMC", "MHO-C401"]:
# To handle jagged stair stepping readings from these sensors.
# https://github.com/custom-components/ble_monitor/blob/ef2e3944b9c1a635208390b8563710d0eec2a945/custom_components/ble_monitor/sensor.py#L752
# https://github.com/esphome/esphome/blob/c39f6d0738d97ecc11238220b493731ec70c701c/esphome/components/xiaomi_lywsd03mmc/xiaomi_lywsd03mmc.cpp#L44C14-L44C99
# https://github.com/custom-components/ble_monitor/issues/7#issuecomment-595948254
device.update_predefined_sensor(
SensorLibrary.HUMIDITY__PERCENTAGE, int(humi / 10)
)
else:
device.update_predefined_sensor(
SensorLibrary.HUMIDITY__PERCENTAGE, humi / 10
)
return {}
def obj1007(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Illuminance"""
if len(xobj) == 3:
(illum,) = ILL_STRUCT.unpack(xobj + b"\x00")
if device_type in ["MJYD02YL", "MCCGQ02HL"]:
# 100 means light, else dark (0 or 1)
# MCCGQ02HL might use obj1018 for light sensor, just added here to be sure.
device.update_predefined_binary_sensor(
BinarySensorDeviceClass.LIGHT, illum == 100
)
elif device_type in ["HHCCJCY01", "GCLS002"]:
# illumination in lux
device.update_predefined_sensor(SensorLibrary.LIGHT__LIGHT_LUX, illum)
return {}
def obj1008(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Moisture"""
device.update_predefined_sensor(SensorLibrary.MOISTURE__PERCENTAGE, xobj[0])
return {}
def obj1009(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Conductivity"""
if len(xobj) == 2:
(cond,) = CND_STRUCT.unpack(xobj)
device.update_predefined_sensor(SensorLibrary.CONDUCTIVITY__CONDUCTIVITY, cond)
return {}
def obj1010(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Formaldehyde"""
if len(xobj) == 2:
(fmdh,) = FMDH_STRUCT.unpack(xobj)
device.update_predefined_sensor(
SensorLibrary.FORMALDEHYDE__CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER,
fmdh / 100,
)
return {}
def obj1012(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Power on/off"""
device.update_predefined_binary_sensor(BinarySensorDeviceClass.POWER, xobj[0])
return {}
def obj1013(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Consumable (in percent)"""
device.update_sensor(
key=ExtendedSensorDeviceClass.CONSUMABLE,
name="Consumable",
native_unit_of_measurement=Units.PERCENTAGE,
device_class=ExtendedSensorDeviceClass.CONSUMABLE,
native_value=xobj[0],
)
return {}
def obj1014(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Moisture"""
device.update_predefined_binary_sensor(
BinarySensorDeviceClass.MOISTURE, xobj[0] > 0
)
return {}
def obj1015(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Smoke"""
device.update_predefined_binary_sensor(BinarySensorDeviceClass.SMOKE, xobj[0] > 0)
return {}
def obj1017(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Time in seconds without motion"""
if len(xobj) == 4:
(no_motion_time,) = M_STRUCT.unpack(xobj)
# seconds since last motion detected message
# 0x1017 is send 3 seconds after 0x000f, 5 seconds arter 0x1007
# and at 60, 120, 300, 600, 1200 and 1800 seconds after last motion.
# Anything <= 30 seconds is regarded motion detected in the MiHome app.
if no_motion_time <= 30:
device.update_predefined_binary_sensor(BinarySensorDeviceClass.MOTION, True)
else:
device.update_predefined_binary_sensor(
BinarySensorDeviceClass.MOTION, False
)
return {}
def obj1018(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Light intensity"""
device.update_predefined_binary_sensor(BinarySensorDeviceClass.LIGHT, bool(xobj[0]))
return {}
def obj1019(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Door/Window sensor"""
open_obj = xobj[0]
if open_obj == 0:
# opened
device.update_predefined_binary_sensor(BinarySensorDeviceClass.OPENING, True)
elif open_obj == 1:
# closed
device.update_predefined_binary_sensor(BinarySensorDeviceClass.OPENING, False)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.DOOR_LEFT_OPEN,
native_value=False, # reset door left open
device_class=ExtendedBinarySensorDeviceClass.DOOR_LEFT_OPEN,
name="Door left open",
)
elif open_obj == 2:
# closing timeout
device.update_predefined_binary_sensor(BinarySensorDeviceClass.OPENING, True)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.DOOR_LEFT_OPEN,
native_value=True,
device_class=ExtendedBinarySensorDeviceClass.DOOR_LEFT_OPEN,
name="Door left open",
)
elif open_obj == 3:
# device reset (not implemented)
return {}
else:
return {}
return {}
def obj100a(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Battery"""
batt = xobj[0]
volt = 2.2 + (3.1 - 2.2) * (batt / 100)
device.update_predefined_sensor(SensorLibrary.BATTERY__PERCENTAGE, batt)
device.update_predefined_sensor(
SensorLibrary.VOLTAGE__ELECTRIC_POTENTIAL_VOLT, volt
)
return {}
def obj100d(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Temperature and humidity"""
if len(xobj) == 4:
(temp, humi) = TH_STRUCT.unpack(xobj)
device.update_predefined_sensor(SensorLibrary.TEMPERATURE__CELSIUS, temp / 10)
device.update_predefined_sensor(SensorLibrary.HUMIDITY__PERCENTAGE, humi / 10)
return {}
def obj100e(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Lock common attribute"""
# https://iot.mi.com/new/doc/accesses/direct-access/embedded-development/ble/object-definition#%E9%94%81%E5%B1%9E%E6%80%A7
if len(xobj) == 1:
# Unlock by type on some devices
if device_type == "DSL-C08":
lock_attribute = int.from_bytes(xobj, "little")
device.update_predefined_binary_sensor(
BinarySensorDeviceClass.LOCK, bool(lock_attribute & 0x01 ^ 1)
)
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.CHILDLOCK,
native_value=bool(lock_attribute >> 3 ^ 1),
device_class=ExtendedBinarySensorDeviceClass.CHILDLOCK,
name="Childlock",
)
return {}
def obj101b(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Timeout no movement"""
# https://iot.mi.com/new/doc/accesses/direct-access/embedded-development/ble/object-definition#%E9%80%9A%E7%94%A8%E5%B1%9E%E6%80%A7
device.update_predefined_binary_sensor(BinarySensorDeviceClass.MOTION, False)
return {}
def obj2000(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Body temperature"""
if len(xobj) == 5:
(temp1, temp2, bat) = TTB_STRUCT.unpack(xobj)
# Body temperature is calculated from the two measured temperatures.
# Formula is based on approximation based on values in the app in
# the range 36.5 - 37.8.
body_temp = (
3.71934 * pow(10, -11) * math.exp(0.69314 * temp1 / 100)
- (1.02801 * pow(10, -8) * math.exp(0.53871 * temp2 / 100))
+ 36.413
)
device.update_predefined_sensor(SensorLibrary.TEMPERATURE__CELSIUS, body_temp)
device.update_predefined_sensor(SensorLibrary.BATTERY__PERCENTAGE, bat)
return {}
def obj3003(
xobj: bytes, device: XiaomiBluetoothDeviceData, device_type: str
) -> dict[str, Any]:
"""Brushing"""
result = {}
start_obj = xobj[0]
if start_obj == 0:
# Start of brushing
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.TOOTHBRUSH,
native_value=True, # Toothbrush On
device_class=ExtendedBinarySensorDeviceClass.TOOTHBRUSH,
name="Toothbrush",
)
# Start time has not been implemented
start_time = struct.unpack("<L", xobj[1:5])[0]
result["start time"] = datetime.datetime.fromtimestamp(
start_time, tz=datetime.timezone.utc
).replace(tzinfo=None)
elif start_obj == 1:
# End of brushing
device.update_binary_sensor(
key=ExtendedBinarySensorDeviceClass.TOOTHBRUSH,
native_value=False, # Toothbrush Off
device_class=ExtendedBinarySensorDeviceClass.TOOTHBRUSH,
name="Toothbrush",
)
# End time has not been implemented
end_time = struct.unpack("<L", xobj[1:5])[0]
result["end time"] = datetime.datetime.fromtimestamp(
end_time, tz=datetime.timezone.utc
).replace(tzinfo=None)
if len(xobj) == 6:
device.update_sensor(
key=ExtendedSensorDeviceClass.SCORE,
name="Score",
native_unit_of_measurement=None,
device_class=ExtendedSensorDeviceClass.SCORE,
native_value=xobj[5],
)
return result