-
Notifications
You must be signed in to change notification settings - Fork 0
/
broadlink
3767 lines (3074 loc) · 113 KB
/
broadlink
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
Repository: mjg59/python-broadlink
File: .github/PULL_REQUEST_TEMPLATE.md
<!--
You are amazing! Thanks for contributing to our project!
Please fill the template to help maintainers processing your PR.
Don't forget to create the PR against the correct branch:
- new product id -> new_product_ids
- anything else -> dev
-->
## Context
<!--
Summarize the motivation and context of the change.
Which issue are you dealing with?
-->
## Proposed change
<!--
Describe the change. How are you fixing the issue?
-->
## Type of change
<!--
What type of change does your PR introduce?
Please, check only 1 box!
-->
- [ ] Dependency upgrade
- [ ] Bugfix (non-breaking change which fixes an issue)
- [ ] New device
- [ ] New product id (the device is already supported with a different id)
- [ ] New feature (which adds functionality to an existing device)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests
- [ ] Documentation
## Additional information
<!--
Link docs and related issues, when applicable.
-->
- This PR fixes issue: fixes #
- This PR is related to:
- Link to documentation pull request:
## Checklist
<!--
Please do your best to check these boxes.
-->
- [ ] The code change is tested and works locally.
- [ ] The code has been formatted using Black.
- [ ] The code follows the [Zen of Python](https://www.python.org/dev/peps/pep-0020/).
- [ ] I am creating the Pull Request against the correct branch.
- [ ] Documentation added/updated.
Repository: mjg59/python-broadlink
File: .github/workflows/flake8.yaml
name: Python flake8
on:
push:
branches: [ master, dev ]
pull_request:
branches: [ master, dev ]
jobs:
test:
runs-on: ubuntu-20.04
strategy:
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install wheel
pip install flake8 flake8-quotes
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. ignore magic numbers and use double quotes and ignore numbers with zeroes before them.
# and ignore lowercase hex numbers and ignore isort incorrect imports
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=90 --ignore=WPS432,WPS339,WPS341,I --inline-quotes double --statistics
Repository: mjg59/python-broadlink
File: .gitignore
*.pyc
Repository: mjg59/python-broadlink
File: LICENSE
The MIT License (MIT)
Copyright (c) 2014 Mike Ryan
Copyright (c) 2016 Matthew Garrett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Repository: mjg59/python-broadlink
File: README.md
# python-broadlink
A Python module and CLI for controlling Broadlink devices locally. The following devices are supported:
- **Universal remotes**: RM home, RM mini 3, RM plus, RM pro, RM pro+, RM4 mini, RM4 pro, RM4C mini, RM4S, RM4 TV mate
- **Smart plugs**: SP mini, SP mini 3, SP mini+, SP1, SP2, SP2-BR, SP2-CL, SP2-IN, SP2-UK, SP3, SP3-EU, SP3S-EU, SP3S-US, SP4L-AU, SP4L-EU, SP4L-UK, SP4M, SP4M-US, Ankuoo NEO, Ankuoo NEO PRO, Efergy Ego, BG AHC/U-01
- **Switches**: MCB1, SC1, SCB1E, SCB2
- **Outlets**: BG 800, BG 900
- **Power strips**: MP1-1K3S2U, MP1-1K4S, MP2
- **Environment sensors**: A1
- **Alarm kits**: S1C, S2KIT
- **Light bulbs**: LB1, LB26 R1, LB27 R1, SB800TD
- **Curtain motors**: Dooya DT360E-45/20
- **Thermostats**: Hysen HY02B05H
- **Hubs**: S3
## Installation
Use pip3 to install the latest version of this module.
```
pip3 install broadlink
```
## Basic functions
First, open Python 3 and import this module.
```
python3
```
```python3
import broadlink
```
Now let's try some functions...
### Setup
In order to control the device, you need to connect it to your local network. If you have already configured the device with the Broadlink app, this step is not necessary.
1. Put the device into AP Mode.
- Long press the reset button until the blue LED is blinking quickly.
- Long press again until blue LED is blinking slowly.
- Manually connect to the WiFi SSID named BroadlinkProv.
2. Connect the device to your local network with the setup function.
```python3
broadlink.setup('myssid', 'mynetworkpass', 3)
```
Security mode options are (0 = none, 1 = WEP, 2 = WPA1, 3 = WPA2, 4 = WPA1/2)
#### Advanced options
You may need to specify a broadcast address if setup is not working.
```python3
broadlink.setup('myssid', 'mynetworkpass', 3, ip_address='192.168.0.255')
```
### Discovery
Use this function to discover devices:
```python3
devices = broadlink.discover()
```
#### Advanced options
You may need to specify `local_ip_address` or `discover_ip_address` if discovery does not return any devices.
Using the IP address of your local machine:
```python3
devices = broadlink.discover(local_ip_address='192.168.0.100')
```
Using the broadcast address of your subnet:
```python3
devices = broadlink.discover(discover_ip_address='192.168.0.255')
```
If the device is locked, it may not be discoverable with broadcast. In such cases, you can use the unicast version `broadlink.hello()` for direct discovery:
```python3
device = broadlink.hello('192.168.0.16')
```
If you are a perfomance freak, use `broadlink.xdiscover()` to create devices instantly:
```python3
for device in broadlink.xdiscover():
print(device) # Example action. Do whatever you want here.
```
### Authentication
After discovering the device, call the `auth()` method to obtain the authentication key required for further communication:
```python3
device.auth()
```
The next steps depend on the type of device you want to control.
## Universal remotes
### Learning IR codes
Learning IR codes takes place in three steps.
1. Enter learning mode:
```python3
device.enter_learning()
```
2. When the LED blinks, point the remote at the Broadlink device and press the button you want to learn.
3. Get the IR packet.
```python3
packet = device.check_data()
```
### Learning RF codes
Learning RF codes takes place in six steps.
1. Sweep the frequency:
```python3
device.sweep_frequency()
```
2. When the LED blinks, point the remote at the Broadlink device for the first time and long press the button you want to learn.
3. Check if the frequency was successfully identified:
```python3
ok = device.check_frequency()
if ok:
print('Frequency found!')
```
4. Enter learning mode:
```python3
device.find_rf_packet()
```
5. When the LED blinks, point the remote at the Broadlink device for the second time and short press the button you want to learn.
6. Get the RF packet:
```python3
packet = device.check_data()
```
#### Notes
Universal remotes with product id 0x2712 use the same method for learning IR and RF codes. They don't need to sweep frequency. Just call `device.enter_learning()` and `device.check_data()`.
### Canceling learning
You can exit the learning mode in the middle of the process by calling this method:
```python3
device.cancel_sweep_frequency()
```
### Sending IR/RF packets
```python3
device.send_data(packet)
```
### Fetching sensor data
```python3
data = device.check_sensors()
```
## Switches
### Setting power state
```python3
device.set_power(True)
device.set_power(False)
```
### Checking power state
```python3
state = device.check_power()
```
### Checking energy consumption
```python3
state = device.get_energy()
```
## Power strips
### Setting power state
```python3
device.set_power(1, True) # Example socket. It could be 2 or 3.
device.set_power(1, False)
```
### Checking power state
```python3
state = device.check_power()
```
## Light bulbs
### Fetching data
```python3
state = device.get_state()
```
### Setting state attributes
```python3
devices[0].set_state(pwr=0)
devices[0].set_state(pwr=1)
devices[0].set_state(brightness=75)
devices[0].set_state(bulb_colormode=0)
devices[0].set_state(blue=255)
devices[0].set_state(red=0)
devices[0].set_state(green=128)
devices[0].set_state(bulb_colormode=1)
```
## Environment sensors
### Fetching sensor data
```python3
data = device.check_sensors()
```
## Hubs
### Discovering subdevices
```python3
device.get_subdevices()
```
### Fetching data
Use the DID obtained from get_subdevices() for the input parameter to query specific sub-device.
```python3
device.get_state(did="00000000000000000000a043b0d06963")
```
### Setting state attributes
The parameters depend on the type of subdevice that is being controlled. In this example, we are controlling LC-1 switches:
#### Turn on
```python3
device.set_state(did="00000000000000000000a043b0d0783a", pwr=1)
device.set_state(did="00000000000000000000a043b0d0783a", pwr1=1)
device.set_state(did="00000000000000000000a043b0d0783a", pwr2=1)
```
#### Turn off
```python3
device.set_state(did="00000000000000000000a043b0d0783a", pwr=0)
device.set_state(did="00000000000000000000a043b0d0783a", pwr1=0)
device.set_state(did="00000000000000000000a043b0d0783a", pwr2=0)
```
Repository: mjg59/python-broadlink
File: TROUBLESHOOTING.md
# Troubleshooting
## Firmware issues
### AP setup fails with non-alphanumeric passwords
Some devices ship with firmware that cannot connect to WLANs with non-alphanumeric passwords. To fix this, update the firmware to the latest version. You can also change the password to one with just letters and numbers or create a separate guest network with a simpler password.
_First seen on Broadlink RM4 pro 0x6026. Already fixed in firmware v52079._
Repository: mjg59/python-broadlink
File: broadlink/__init__.py
#!/usr/bin/env python3
"""The python-broadlink library."""
import socket
from typing import Generator, List, Optional, Tuple, Union
from . import exceptions as e
from .const import DEFAULT_BCAST_ADDR, DEFAULT_PORT, DEFAULT_TIMEOUT
from .alarm import S1C
from .climate import hvac, hysen
from .cover import dooya, dooya2, wser
from .device import Device, ping, scan
from .hub import s3
from .light import lb1, lb2
from .remote import rm, rm4, rm4mini, rm4pro, rmmini, rmminib, rmpro
from .sensor import a1, a2
from .switch import bg1, ehc31, mp1, mp1s, sp1, sp2, sp2s, sp3, sp3s, sp4, sp4b
SUPPORTED_TYPES = {
sp1: {
0x0000: ("SP1", "Broadlink"),
},
sp2: {
0x2717: ("NEO", "Ankuoo"),
0x2719: ("SP2-compatible", "Honeywell"),
0x271A: ("SP2-compatible", "Honeywell"),
0x2720: ("SP mini", "Broadlink"),
0x2728: ("SP2-compatible", "URANT"),
0x273E: ("SP mini", "Broadlink"),
0x7530: ("SP2", "Broadlink (OEM)"),
0x7539: ("SP2-IL", "Broadlink (OEM)"),
0x753E: ("SP mini 3", "Broadlink"),
0x7540: ("MP2", "Broadlink"),
0x7544: ("SP2-CL", "Broadlink"),
0x7546: ("SP2-UK/BR/IN", "Broadlink (OEM)"),
0x7547: ("SC1", "Broadlink"),
0x7549: ("SP mini 3", "Broadlink (OEM)"),
0x7918: ("SP2", "Broadlink (OEM)"),
0x7919: ("SP2-compatible", "Honeywell"),
0x791A: ("SP2-compatible", "Honeywell"),
0x7D0D: ("SP mini 3", "Broadlink (OEM)"),
},
sp2s: {
0x2711: ("SP2", "Broadlink"),
0x2716: ("NEO PRO", "Ankuoo"),
0x271D: ("Ego", "Efergy"),
0x2736: ("SP mini+", "Broadlink"),
},
sp3: {
0x2733: ("SP3", "Broadlink"),
0x7D00: ("SP3-EU", "Broadlink (OEM)"),
},
sp3s: {
0x9479: ("SP3S-US", "Broadlink"),
0x947A: ("SP3S-EU", "Broadlink"),
},
sp4: {
0x7568: ("SP4L-CN", "Broadlink"),
0x756B: ("SP4M-JP", "Broadlink"),
0x756C: ("SP4M", "Broadlink"),
0x756F: ("MCB1", "Broadlink"),
0x7579: ("SP4L-EU", "Broadlink"),
0x757B: ("SP4L-AU", "Broadlink"),
0x7583: ("SP mini 3", "Broadlink"),
0x7587: ("SP4L-UK", "Broadlink"),
0x7D11: ("SP mini 3", "Broadlink"),
0xA4F9: ("WS4", "Broadlink (OEM)"),
0xA569: ("SP4L-UK", "Broadlink"),
0xA56A: ("MCB1", "Broadlink"),
0xA56B: ("SCB1E", "Broadlink"),
0xA56C: ("SP4L-EU", "Broadlink"),
0xA576: ("SP4L-AU", "Broadlink"),
0xA589: ("SP4L-UK", "Broadlink"),
0xA5D3: ("SP4L-EU", "Broadlink"),
0xA6F4: ("SP4D-US", "Broadlink"),
},
sp4b: {
0x5115: ("SCB1E", "Broadlink"),
0x51E2: ("AHC/U-01", "BG Electrical"),
0x6111: ("MCB1", "Broadlink"),
0x6113: ("SCB1E", "Broadlink"),
0x618B: ("SP4L-EU", "Broadlink"),
0x6489: ("SP4L-AU", "Broadlink"),
0x648B: ("SP4M-US", "Broadlink"),
0x648C: ("SP4L-US", "Broadlink"),
0x6494: ("SCB2", "Broadlink"),
},
rmmini: {
0x2737: ("RM mini 3", "Broadlink"),
0x278F: ("RM mini", "Broadlink"),
0x27B7: ("RM mini 3", "Broadlink"),
0x27C2: ("RM mini 3", "Broadlink"),
0x27C7: ("RM mini 3", "Broadlink"),
0x27CC: ("RM mini 3", "Broadlink"),
0x27CD: ("RM mini 3", "Broadlink"),
0x27D0: ("RM mini 3", "Broadlink"),
0x27D1: ("RM mini 3", "Broadlink"),
0x27D3: ("RM mini 3", "Broadlink"),
0x27DC: ("RM mini 3", "Broadlink"),
0x27DE: ("RM mini 3", "Broadlink"),
},
rmpro: {
0x2712: ("RM pro/pro+", "Broadlink"),
0x272A: ("RM pro", "Broadlink"),
0x273D: ("RM pro", "Broadlink"),
0x277C: ("RM home", "Broadlink"),
0x2783: ("RM home", "Broadlink"),
0x2787: ("RM pro", "Broadlink"),
0x278B: ("RM plus", "Broadlink"),
0x2797: ("RM pro+", "Broadlink"),
0x279D: ("RM pro+", "Broadlink"),
0x27A1: ("RM plus", "Broadlink"),
0x27A6: ("RM plus", "Broadlink"),
0x27A9: ("RM pro+", "Broadlink"),
0x27C3: ("RM pro+", "Broadlink"),
},
rmminib: {
0x5F36: ("RM mini 3", "Broadlink"),
0x6507: ("RM mini 3", "Broadlink"),
0x6508: ("RM mini 3", "Broadlink"),
},
rm4mini: {
0x51DA: ("RM4 mini", "Broadlink"),
0x5209: ("RM4 TV mate", "Broadlink"),
0x520C: ("RM4 mini", "Broadlink"),
0x520D: ("RM4C mini", "Broadlink"),
0x5211: ("RM4C mate", "Broadlink"),
0x5212: ("RM4 TV mate", "Broadlink"),
0x5216: ("RM4 mini", "Broadlink"),
0x521C: ("RM4 mini", "Broadlink"),
0x6070: ("RM4C mini", "Broadlink"),
0x610E: ("RM4 mini", "Broadlink"),
0x610F: ("RM4C mini", "Broadlink"),
0x62BC: ("RM4 mini", "Broadlink"),
0x62BE: ("RM4C mini", "Broadlink"),
0x6364: ("RM4S", "Broadlink"),
0x648D: ("RM4 mini", "Broadlink"),
0x6539: ("RM4C mini", "Broadlink"),
0x653A: ("RM4 mini", "Broadlink"),
},
rm4pro: {
0x520B: ("RM4 pro", "Broadlink"),
0x5213: ("RM4 pro", "Broadlink"),
0x5218: ("RM4C pro", "Broadlink"),
0x6026: ("RM4 pro", "Broadlink"),
0x6184: ("RM4C pro", "Broadlink"),
0x61A2: ("RM4 pro", "Broadlink"),
0x649B: ("RM4 pro", "Broadlink"),
0x653C: ("RM4 pro", "Broadlink"),
},
a1: {
0x2714: ("A1", "Broadlink"),
},
a2: {
0x4F60: ("A2", "Broadlink"),
},
mp1: {
0x4EB5: ("MP1-1K4S", "Broadlink"),
0x4F1B: ("MP1-1K3S2U", "Broadlink (OEM)"),
0x4F65: ("MP1-1K3S2U", "Broadlink"),
},
mp1s: {
0x4EF7: ("MP1-1K4S", "Broadlink (OEM)"),
},
lb1: {
0x5043: ("SB800TD", "Broadlink (OEM)"),
0x504E: ("LB1", "Broadlink"),
0x606D: ("SLA22RGB9W81/SLA27RGB9W81", "Luceco"),
0x606E: ("SB500TD", "Broadlink (OEM)"),
0x60C7: ("LB1", "Broadlink"),
0x60C8: ("LB1", "Broadlink"),
0x6112: ("LB1", "Broadlink"),
0x644B: ("LB1", "Broadlink"),
0x644C: ("LB27 R1", "Broadlink"),
0x644E: ("LB26 R1", "Broadlink"),
0x6488: ("LB27 C1", "Broadlink"),
},
lb2: {
0xA4F4: ("LB27 R1", "Broadlink"),
0xA5F7: ("LB27 R1", "Broadlink"),
0xA6EF: ("EFCF60WSMT", "Luceco"),
},
S1C: {
0x2722: ("S2KIT", "Broadlink"),
},
s3: {
0xA59C: ("S3", "Broadlink"),
0xA64D: ("S3", "Broadlink"),
},
hvac: {
0x4E2A: ("HVAC", "Licensed manufacturer"),
},
hysen: {
0x4EAD: ("HY02/HY03", "Hysen"),
},
dooya: {
0x4E4D: ("DT360E-45/20", "Dooya"),
},
dooya2: {
0x4F6E: ("DT360E-45/20", "Dooya"),
},
wser: {
0x4F6C: ("WSER", "Wistar"),
},
bg1: {
0x51E3: ("BG800/BG900", "BG Electrical"),
},
ehc31: {
0x6480: ("EHC31", "BG Electrical"),
},
}
def gendevice(
dev_type: int,
host: Tuple[str, int],
mac: Union[bytes, str],
name: str = "",
is_locked: bool = False,
) -> Device:
"""Generate a device."""
for dev_cls, products in SUPPORTED_TYPES.items():
try:
model, manufacturer = products[dev_type]
except KeyError:
continue
return dev_cls(
host,
mac,
dev_type,
name=name,
model=model,
manufacturer=manufacturer,
is_locked=is_locked,
)
return Device(host, mac, dev_type, name=name, is_locked=is_locked)
def hello(
ip_address: str,
port: int = DEFAULT_PORT,
timeout: int = DEFAULT_TIMEOUT,
) -> Device:
"""Direct device discovery.
Useful if the device is locked.
"""
try:
return next(
xdiscover(
timeout=timeout,
discover_ip_address=ip_address,
discover_ip_port=port,
)
)
except StopIteration as err:
raise e.NetworkTimeoutError(
-4000,
"Network timeout",
f"No response received within {timeout}s",
) from err
def discover(
timeout: int = DEFAULT_TIMEOUT,
local_ip_address: Optional[str] = None,
discover_ip_address: str = DEFAULT_BCAST_ADDR,
discover_ip_port: int = DEFAULT_PORT,
) -> List[Device]:
"""Discover devices connected to the local network."""
responses = scan(
timeout, local_ip_address, discover_ip_address, discover_ip_port
)
return [gendevice(*resp) for resp in responses]
def xdiscover(
timeout: int = DEFAULT_TIMEOUT,
local_ip_address: Optional[str] = None,
discover_ip_address: str = DEFAULT_BCAST_ADDR,
discover_ip_port: int = DEFAULT_PORT,
) -> Generator[Device, None, None]:
"""Discover devices connected to the local network.
This function returns a generator that yields devices instantly.
"""
responses = scan(
timeout, local_ip_address, discover_ip_address, discover_ip_port
)
for resp in responses:
yield gendevice(*resp)
# Setup a new Broadlink device via AP Mode. Review the README to see how to enter AP Mode.
# Only tested with Broadlink RM3 Mini (Blackbean)
def setup(
ssid: str,
password: str,
security_mode: int,
ip_address: str = DEFAULT_BCAST_ADDR,
) -> None:
"""Set up a new Broadlink device via AP mode."""
# Security mode options are (0 - none, 1 = WEP, 2 = WPA1, 3 = WPA2, 4 = WPA1/2)
payload = bytearray(0x88)
payload[0x26] = 0x14 # This seems to always be set to 14
# Add the SSID to the payload
ssid_start = 68
ssid_length = 0
for letter in ssid:
payload[(ssid_start + ssid_length)] = ord(letter)
ssid_length += 1
# Add the WiFi password to the payload
pass_start = 100
pass_length = 0
for letter in password:
payload[(pass_start + pass_length)] = ord(letter)
pass_length += 1
payload[0x84] = ssid_length # Character length of SSID
payload[0x85] = pass_length # Character length of password
payload[0x86] = security_mode # Type of encryption
checksum = sum(payload, 0xBEAF) & 0xFFFF
payload[0x20] = checksum & 0xFF # Checksum 1 position
payload[0x21] = checksum >> 8 # Checksum 2 position
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet # UDP
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(payload, (ip_address, DEFAULT_PORT))
sock.close()
Repository: mjg59/python-broadlink
File: broadlink/alarm.py
"""Support for alarm kits."""
from . import exceptions as e
from .device import Device
class S1C(Device):
"""Controls a Broadlink S1C."""
TYPE = "S1C"
_SENSORS_TYPES = {
0x31: "Door Sensor",
0x91: "Key Fob",
0x21: "Motion Sensor",
}
def get_sensors_status(self) -> dict:
"""Return the state of the sensors."""
packet = bytearray(16)
packet[0] = 0x06
response = self.send_packet(0x6A, packet)
e.check_error(response[0x22:0x24])
payload = self.decrypt(response[0x38:])
count = payload[0x4]
sensor_data = payload[0x6:]
sensors = [
bytearray(sensor_data[i * 83 : (i + 1) * 83])
for i in range(len(sensor_data) // 83)
]
return {
"count": count,
"sensors": [
{
"status": sensor[0],
"name": sensor[4:26].decode().strip("\x00"),
"type": self._SENSORS_TYPES.get(sensor[3], "Unknown"),
"order": sensor[1],
"serial": sensor[26:30].hex(),
}
for sensor in sensors
if any(sensor[26:30])
],
}
Repository: mjg59/python-broadlink
File: broadlink/climate.py
"""Support for climate control."""
import enum
import struct
from typing import List, Sequence
from . import exceptions as e
from .device import Device
from .helpers import CRC16
class hysen(Device):
"""Controls a Hysen heating thermostat.
This device is manufactured by Hysen and sold under different
brands, including Floureon, Beca Energy, Beok and Decdeal.
Supported models:
- HY02B05H
- HY03WE
"""
TYPE = "HYS"
def send_request(self, request: Sequence[int]) -> bytes:
"""Send a request to the device."""
packet = bytearray()
packet.extend((len(request) + 2).to_bytes(2, "little"))
packet.extend(request)
packet.extend(CRC16.calculate(request).to_bytes(2, "little"))
response = self.send_packet(0x6A, packet)
e.check_error(response[0x22:0x24])
payload = self.decrypt(response[0x38:])
p_len = int.from_bytes(payload[:0x02], "little")
nom_crc = int.from_bytes(payload[p_len:p_len+2], "little")
real_crc = CRC16.calculate(payload[0x02:p_len])
if nom_crc != real_crc:
raise e.DataValidationError(
-4008,
"Received data packet check error",
f"Expected a checksum of {nom_crc} and received {real_crc}",
)
return payload[0x02:p_len]
def _decode_temp(self, payload, base_index):
base_temp = payload[base_index] / 2.0
add_offset = (payload[4] >> 3) & 1 # should offset be added?
offset_raw_value = (payload[17] >> 4) & 3 # offset value
offset = (offset_raw_value + 1) / 10 if add_offset else 0.0
return base_temp + offset
def get_temp(self) -> float:
"""Return the room temperature in degrees celsius."""
payload = self.send_request([0x01, 0x03, 0x00, 0x00, 0x00, 0x08])
return self._decode_temp(payload, 5)
def get_external_temp(self) -> float:
"""Return the external temperature in degrees celsius."""
payload = self.send_request([0x01, 0x03, 0x00, 0x00, 0x00, 0x08])
return self._decode_temp(payload, 18)
def get_full_status(self) -> dict:
"""Return the state of the device.
Timer schedule included.
"""
payload = self.send_request([0x01, 0x03, 0x00, 0x00, 0x00, 0x16])
data = {}
data["remote_lock"] = payload[3] & 1
data["power"] = payload[4] & 1
data["active"] = (payload[4] >> 4) & 1
data["temp_manual"] = (payload[4] >> 6) & 1
data["heating_cooling"] = (payload[4] >> 7) & 1
data["room_temp"] = self._decode_temp(payload, 5)
data["thermostat_temp"] = payload[6] / 2.0
data["auto_mode"] = payload[7] & 0x0F
data["loop_mode"] = payload[7] >> 4
data["sensor"] = payload[8]
data["osv"] = payload[9]
data["dif"] = payload[10]
data["svh"] = payload[11]
data["svl"] = payload[12]
data["room_temp_adj"] = (
int.from_bytes(payload[13:15], "big", signed=True) / 10.0
)
data["fre"] = payload[15]
data["poweron"] = payload[16]
data["unknown"] = payload[17]
data["external_temp"] = self._decode_temp(payload, 18)
data["hour"] = payload[19]
data["min"] = payload[20]
data["sec"] = payload[21]
data["dayofweek"] = payload[22]
weekday = []
for i in range(0, 6):
weekday.append(
{
"start_hour": payload[2 * i + 23],
"start_minute": payload[2 * i + 24],
"temp": payload[i + 39] / 2.0,
}
)
data["weekday"] = weekday
weekend = []
for i in range(6, 8):
weekend.append(
{
"start_hour": payload[2 * i + 23],
"start_minute": payload[2 * i + 24],
"temp": payload[i + 39] / 2.0,
}
)
data["weekend"] = weekend
return data
# Change controller mode
# auto_mode = 1 for auto (scheduled/timed) mode, 0 for manual mode.
# Manual mode will activate last used temperature.
# In typical usage call set_temp to activate manual control and set temp.
# loop_mode refers to index in [ "12345,67", "123456,7", "1234567" ]
# E.g. loop_mode = 0 ("12345,67") means Saturday and Sunday (weekend schedule)
# loop_mode = 2 ("1234567") means every day, including Saturday and Sunday (weekday schedule)
# The sensor command is currently experimental
def set_mode(
self, auto_mode: int, loop_mode: int, sensor: int = 0
) -> None:
"""Set the mode of the device."""
mode_byte = ((loop_mode + 1) << 4) + auto_mode
self.send_request([0x01, 0x06, 0x00, 0x02, mode_byte, sensor])
# Advanced settings
# Sensor mode (SEN) sensor = 0 for internal sensor, 1 for external sensor,
# 2 for internal control temperature, external limit temperature. Factory default: 0.
# Set temperature range for external sensor (OSV) osv = 5..99. Factory default: 42C
# Deadzone for floor temprature (dIF) dif = 1..9. Factory default: 2C
# Upper temperature limit for internal sensor (SVH) svh = 5..99. Factory default: 35C
# Lower temperature limit for internal sensor (SVL) svl = 5..99. Factory default: 5C
# Actual temperature calibration (AdJ) adj = -0.5. Precision 0.1C
# Anti-freezing function (FrE) fre = 0 for anti-freezing function shut down,
# 1 for anti-freezing function open. Factory default: 0
# Power on memory (POn) poweron = 0 for off, 1 for on. Default: 0
def set_advanced(
self,
loop_mode: int,
sensor: int,
osv: int,
dif: int,
svh: int,
svl: int,
adj: float,
fre: int,
poweron: int,
) -> None:
"""Set advanced options."""
self.send_request(
[
0x01,
0x10,
0x00,
0x02,
0x00,
0x05,
0x0A,
loop_mode,
sensor,
osv,
dif,
svh,
svl,
int(adj * 10) >> 8 & 0xFF,
int(adj * 10) & 0xFF,
fre,
poweron,
]
)
# For backwards compatibility only. Prefer calling set_mode directly.
# Note this function invokes loop_mode=0 and sensor=0.
def switch_to_auto(self) -> None:
"""Switch mode to auto."""
self.set_mode(auto_mode=1, loop_mode=0)
def switch_to_manual(self) -> None:
"""Switch mode to manual."""
self.set_mode(auto_mode=0, loop_mode=0)
# Set temperature for manual mode (also activates manual mode if currently in automatic)
def set_temp(self, temp: float) -> None:
"""Set the target temperature."""
self.send_request([0x01, 0x06, 0x00, 0x01, 0x00, int(temp * 2)])
# Set device on(1) or off(0), does not deactivate Wifi connectivity.
# Remote lock disables control by buttons on thermostat.
# heating_cooling: heating(0) cooling(1)
def set_power(
self, power: int = 1, remote_lock: int = 0, heating_cooling: int = 0
) -> None:
"""Set the power state of the device."""
state = (heating_cooling << 7) + power
self.send_request([0x01, 0x06, 0x00, 0x00, remote_lock, state])
# set time on device
# n.b. day=1 is Monday, ..., day=7 is Sunday
def set_time(self, hour: int, minute: int, second: int, day: int) -> None:
"""Set the time."""
self.send_request(
[
0x01,