forked from eschava/broadlink-mqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt.py
executable file
·703 lines (583 loc) · 28.4 KB
/
mqtt.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
#!/usr/bin/env python
import paho.mqtt.client as paho # pip install paho-mqtt
import broadlink # pip install broadlink
import os
import sys
import time
import logging
import logging.config
import socket
import sched
import json
import binascii
import types
from threading import Thread
from test import TestDevice
HAVE_TLS = True
try:
import ssl
except ImportError:
HAVE_TLS = False
# read initial config files
dirname = os.path.dirname(os.path.abspath(__file__)) + '/'
logging.config.fileConfig(dirname + 'logging.conf')
CONFIG = os.getenv('BROADLINKMQTTCONFIG', dirname + 'mqtt.conf')
CONFIG_CUSTOM = os.getenv('BROADLINKMQTTCONFIGCUSTOM', dirname + 'custom.conf')
class Config(object):
def __init__(self, filename=CONFIG, custom_filename=CONFIG_CUSTOM):
self.config = {}
exec(compile(open(filename, "rb").read(), filename, 'exec'), self.config)
if os.path.isfile(custom_filename):
exec(compile(open(custom_filename, "rb").read(), custom_filename, 'exec'), self.config)
if self.config.get('ca_certs', None) is not None:
self.config['tls'] = True
tls_version = self.config.get('tls_version', None)
if tls_version is not None:
if not HAVE_TLS:
logging.error("TLS parameters set but no TLS available (SSL)")
sys.exit(2)
if tls_version == 'tlsv1':
self.config['tls_version'] = ssl.PROTOCOL_TLSv1
if tls_version == 'tlsv1.2':
# TLS v1.2 is available starting from python 2.7.9 and requires openssl version 1.0.1+.
if sys.version_info >= (2, 7, 9):
self.config['tls_version'] = ssl.PROTOCOL_TLSv1_2
else:
logging.error("TLS version 1.2 not available but 'tlsv1.2' is set.")
sys.exit(2)
if tls_version == 'sslv3':
self.config['tls_version'] = ssl.PROTOCOL_SSLv3
def get(self, key, default='special empty value'):
v = self.config.get(key, default)
if v == 'special empty value':
logging.error("Configuration parameter '%s' should be specified" % key)
sys.exit(2)
return v
try:
cf = Config()
except Exception as e:
print("Cannot load configuration from file %s: %s" % (CONFIG, str(e)))
sys.exit(2)
qos = cf.get('mqtt_qos', 0)
retain = cf.get('mqtt_retain', False)
topic_prefix = cf.get('mqtt_topic_prefix', 'broadlink/')
device_accessories_dict = {}
# noinspection PyUnusedLocal
def on_message(client, device, msg):
command = msg.topic[len(topic_prefix):].lower()
if isinstance(device, dict):
for subprefix in device:
if command.startswith(subprefix):
#example broadlink/rm.../fan/alkova/state
device = device[subprefix]
device_id = subprefix
command_accessory = command.split("/")[-1]
accessory = command[len(subprefix):-len(command_accessory)-1]
command = command[len(subprefix):]
break
else:
logging.error("MQTT topic %s has no recognized device reference, expected one of %s" %
(msg.topic, ','.join(device.keys())))
return
# internal notification
if command == 'temperature' or \
command == 'humidity' or \
command == 'energy' or \
command == 'sensors' or \
command == 'position' or \
command == 'state' or \
command.startswith('state/') or \
command.startswith('sensor/'):
return
try:
action = msg.payload.decode('utf-8')
logging.debug("Received MQTT message " + msg.topic + " " + action + " type "+device.type)
unique_id = device_id + accessory
# # RM2/RM4 record/replay control
# if device.type == 'RM2' or device.type == 'RM4':
# file = dirname + "commands/" + command
# handy_file = file + '/' + action
# if action == '' or action == 'auto':
# record_or_replay(device, file)
# return
# elif action == 'autorf':
# record_or_replay_rf(device, file)
# return
# elif os.path.isfile(handy_file):
# replay(device, handy_file)
# return
# elif action == 'record':
# record(device, file)
# return
# elif action == 'recordrf':
# record_rf(device, file)
# return
# elif action == 'replay':
# replay(device, file)
# mqttc.publish(msg.topic, "executed", qos=0, retain=False)
# return
# elif action == 'macro':
# file = dirname + "macros/" + command
# macro(device, file)
# return
# elif action == 'executed':
# return
if device.type == 'RM2' or device.type == 'RM4':
logging.debug("Received accessory command " + accessory + " command "+command_accessory + " action "+action)
#find accessory
#check if accessory in list
if unique_id in device_accessories_dict:
logging.debug("Found accessory " + unique_id)
else:
if(command_accessory == 'status'): #take last status from mqtt
logging.debug("Found last accessory status on mqtt")
device_accessories_dict[unique_id] = json.loads(action)
else:
logging.debug("Accessory " + unique_id + " not found...creating")
if accessory.find('fan/') != -1: #is fan
device_accessories_dict[unique_id] = { "on": False, "rotationSpeed": 50, "rotationDirection": 0 }
elif accessory.find('ac/') != -1: #is ac
device_accessories_dict[unique_id] = { "on": False, "targetTemperature": 25 }
action = action.lower()
if command_accessory[0:3] == 'get':
mqttc.publish(topic_prefix+unique_id+"/status", json.dumps(device_accessories_dict[unique_id]), qos=0, retain=True)
elif command_accessory[0:3] == 'set':
subcommand = command_accessory[3:]
speedmultiplier = 10
if accessory.find('fan/alpha') != -1: #is alpha, only 5 speeds
#logging.debug("Is Alpha fan")
speedmultiplier = 100 / 5
subdir = "commands/fan/alpha"
elif accessory.find('fan/alkova') != -1: #is alkova, only 8 speeds
speedmultiplier = 100 / 8
subdir = "commands/fan/alkova"
elif accessory.find('fan/daikin') != -1: #is alkova, only 8 speeds
speedmultiplier = 100 / 5
subdir = "commands/fan/daikin"
elif accessory.find('ac/daikin') != -1: #is alkova, only 8 speeds
#speedmultiplier = 100 / 5
subdir = "commands/ac/daikin"
else:
logging.debug("Device type not identified")
return
if subcommand == 'on':
if action == 'true':
targetstate = 'on'
targetstate_b = True
elif action == 'false':
targetstate = 'off'
targetstate_b = False
else:
return
file = dirname + subdir + "/" + targetstate
if targetstate == 'off' or device_accessories_dict[unique_id]['on'] != targetstate_b: #always play when to be turned off. On only if in different states
replay(device, file)
device_accessories_dict[unique_id]['on'] = targetstate_b
if targetstate_b == False:
if accessory.find('fan/') != -1:
device_accessories_dict[unique_id]['rotationDirection'] = 0 #reset rotationdirection
if targetstate_b == True:
if accessory.find('ac/') != -1:
device_accessories_dict[unique_id]['targetTemperature'] = 25 #reset targetTemperature
time.sleep(0.5) #wait x second with response
mqttc.publish(topic_prefix+unique_id+"/status", json.dumps(device_accessories_dict[unique_id]), qos=0, retain=True)
return
if subcommand == 'rotationspeed':
target_speed = int( action )
fanspeed = round( target_speed / speedmultiplier )
file = dirname + subdir + "/fan" + str(fanspeed)
if 'rotationSpeed' in device_accessories_dict[unique_id] and device_accessories_dict[unique_id]['rotationSpeed'] != round(fanspeed * speedmultiplier): #only replay if different state
replay(device, file)
device_accessories_dict[unique_id]['rotationSpeed'] = round(fanspeed * speedmultiplier)
time.sleep(0.5) #wait x second with response
mqttc.publish(topic_prefix+unique_id+"/status", json.dumps(device_accessories_dict[unique_id]), qos=0, retain=True)
return
if subcommand == 'rotationdirection':
file = dirname + subdir + "/toggleclockwise"
if 'rotationDirection' in device_accessories_dict[unique_id] and device_accessories_dict[unique_id]['rotationDirection'] != int(action): #only replay if different state
replay(device, file)
device_accessories_dict[unique_id]['rotationDirection'] = int(action)
time.sleep(0.5) #wait x second with response
mqttc.publish(topic_prefix+unique_id+"/status", json.dumps(device_accessories_dict[unique_id]), qos=0, retain=True)
return
if subcommand == 'targettemperature':
target_temperature = round( float( action ))
file = dirname + subdir + "/cool" + str(target_temperature)
if 'targetTemperature' in device_accessories_dict[unique_id] and device_accessories_dict[unique_id]['targetTemperature'] != target_temperature: #only replay if different state
replay(device, file)
device_accessories_dict[unique_id]['targetTemperature'] = target_temperature
time.sleep(0.5) #wait x second with response
mqttc.publish(topic_prefix+unique_id+"/status", json.dumps(device_accessories_dict[unique_id]), qos=0, retain=True)
return
return
logging.warning("Unrecognized MQTT message " + action)
except Exception:
logging.exception("Error")
# noinspection PyUnusedLocal
def on_connect(client, device, flags, result_code):
if cf.get('mqtt_birth_payload', False):
mqttc.publish(cf.get('mqtt_birth_topic', 'clients/broadlink'), payload=cf.get('mqtt_birth_payload'), qos=0, retain=True)
topic = topic_prefix + '#'
logging.debug("Connected to MQTT broker, subscribing to topic " + topic)
mqttc.subscribe(topic, qos)
# noinspection PyUnusedLocal
def on_disconnect(client, device, rc):
logging.warning("OOOOPS! MQTT disconnection")
time.sleep(10)
def record_or_replay(device, file):
if os.path.isfile(file):
replay(device, file)
else:
record(device, file)
def record_or_replay_rf(device, file):
if os.path.isfile(file):
replay(device, file)
else:
record_rf(device, file)
def record(device, file):
logging.debug("Recording command to file " + file)
# receive packet
device.enter_learning()
ir_packet = None
attempt = 0
while ir_packet is None and attempt < 6:
time.sleep(5)
ir_packet = device.check_data()
attempt = attempt + 1
if ir_packet is not None:
# write to file
directory = os.path.dirname(file)
if not os.path.exists(directory):
os.makedirs(directory)
with open(file, 'wb') as f:
f.write(binascii.hexlify(ir_packet))
logging.debug("Done")
else:
logging.warn("No command received")
def record_rf(device, file):
logging.debug("Recording RF command to file " + file)
logging.debug("Learning RF Frequency, press and hold the button to learn...")
device.sweep_frequency()
timeout = 20
while (not device.check_frequency()) and (timeout > 0):
time.sleep(1)
timeout -= 1
if timeout <= 0:
logging.warn("RF Frequency not found")
device.cancel_sweep_frequency()
return
logging.debug("Found RF Frequency - 1 of 2!")
time.sleep(5)
logging.debug("To complete learning, single press the button you want to learn")
# receive packet
device.find_rf_packet()
rf_packet = None
attempt = 0
while rf_packet is None and attempt < 6:
time.sleep(5)
rf_packet = device.check_data()
attempt = attempt + 1
if rf_packet is not None:
# write to file
directory = os.path.dirname(file)
if not os.path.exists(directory):
os.makedirs(directory)
with open(file, 'wb') as f:
f.write(binascii.hexlify(rf_packet))
logging.debug("Done")
else:
logging.warn("No command received")
def replay(device, file):
logging.debug("Replaying command from file " + file)
with open(file, 'rb') as f:
ir_packet = f.read()
device.send_data(binascii.unhexlify(ir_packet.strip()))
def macro(device, file):
logging.debug("Replaying macro from file " + file)
with open(file, 'r') as f:
for line in f:
line = line.strip(' \n\r\t')
if len(line) == 0 or line.startswith("#"):
continue
if line.startswith("pause "):
pause = int(line[6:].strip())
logging.debug("Pause for " + str(pause) + " milliseconds")
time.sleep(pause / 1000.0)
else:
command_file = dirname + "commands/" + line
replay(device, command_file)
def get_device(cf):
device_type = cf.get('device_type', 'lookup')
if device_type == 'lookup':
local_address = cf.get('local_address', None)
lookup_timeout = cf.get('lookup_timeout', 20)
devices = broadlink.discover(timeout=lookup_timeout) if local_address is None else \
broadlink.discover(timeout=lookup_timeout, local_ip_address=local_address)
if len(devices) == 0:
logging.error('No Broadlink device found')
sys.exit(2)
if len(devices) > 1:
logging.error('More than one Broadlink device found (' +
', '.join([d.type + '/' + d.host[0] + '/' + ':'.join(format(s, '02x') for s in d.mac[::-1]) for d in devices]) +
')')
sys.exit(2)
return configure_device(devices[0], topic_prefix)
elif device_type == 'multiple_lookup':
local_address = cf.get('local_address', None)
lookup_timeout = cf.get('lookup_timeout', 20)
devices = broadlink.discover(timeout=lookup_timeout) if local_address is None else \
broadlink.discover(timeout=lookup_timeout, local_ip_address=local_address)
if len(devices) == 0:
logging.error('No Broadlink devices found')
sys.exit(2)
mqtt_multiple_prefix_format = cf.get('mqtt_multiple_subprefix_format', None)
devices_dict = {}
for device in devices:
mqtt_subprefix = mqtt_multiple_prefix_format.format(
type=device.type,
host=device.host[0],
mac='_'.join(format(s, '02x') for s in device.mac[::-1]),
mac_nic='_'.join(format(s, '02x') for s in device.mac[2::-1]))
device = configure_device(device, topic_prefix + mqtt_subprefix)
devices_dict[mqtt_subprefix] = device
return devices_dict
elif device_type == 'multiple_devices':
devices_dict = {}
mqtt_multiple_prefix_format = cf.get('mqtt_multiple_subprefix_format', None)
x = 0
while (x < 5):
x = x + 1
device_host = cf.get('device_host_'+str(x),'none')
if device_host == 'none':
break
device_host = (device_host,80)
device_mac = cf.get('device_mac_'+str(x),'none')
if device_mac == 'none':
break
device_mac = bytearray.fromhex(device_mac.replace(':', ' '))
mqtt_subprefix = mqtt_multiple_prefix_format.format(
type='rm',
host=device_host,
mac='_'.join(format(s, '02x') for s in device_mac[::-1]),
mac_nic='_'.join(format(s, '02x') for s in device_mac[2::-1]))
device = broadlink.rm(host=device_host, mac=device_mac, devtype=0x2712)
device = configure_device(device, topic_prefix + mqtt_subprefix)
devices_dict[mqtt_subprefix] = device
return devices_dict
elif device_type == 'test':
return configure_device(TestDevice(cf), topic_prefix)
else:
host = (cf.get('device_host'), 80)
mac = bytearray.fromhex(cf.get('device_mac').replace(':', ' '))
if device_type == 'rm':
device = broadlink.rm(host=host, mac=mac, devtype=0x2712)
elif device_type == 'rm4':
device = broadlink.rm4(host=host, mac=mac, devtype=0x51da)
elif device_type == 'sp1':
device = broadlink.sp1(host=host, mac=mac, devtype=0)
elif device_type == 'sp2':
device = broadlink.sp2(host=host, mac=mac, devtype=0x2711)
elif device_type == 'a1':
device = broadlink.a1(host=host, mac=mac, devtype=0x2714)
elif device_type == 'mp1':
device = broadlink.mp1(host=host, mac=mac, devtype=0x4EB5)
elif device_type == 'dooya':
device = broadlink.dooya(host=host, mac=mac, devtype=0x4E4D)
elif device_type == 'bg1':
device = broadlink.bg1(host=host, mac=mac, devtype=0x51E3)
else:
logging.error('Incorrect device configured: ' + device_type)
sys.exit(2)
return configure_device(device, topic_prefix)
def configure_device(device, mqtt_prefix):
device.auth()
logging.debug('Connected to \'%s\' Broadlink device at \'%s\' (MAC %s) and started listening for commands at MQTT topic having prefix \'%s\' '
% (device.type, device.host[0], ':'.join(format(s, '02x') for s in device.mac[::-1]), mqtt_prefix))
broadlink_rm_temperature_interval = cf.get('broadlink_rm_temperature_interval', 0)
if (device.type == 'RM2' or device.type == 'RM4') and broadlink_rm_temperature_interval > 0:
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(broadlink_rm_temperature_interval, 1, broadlink_rm_temperature_timer,
[scheduler, broadlink_rm_temperature_interval, device, mqtt_prefix])
# scheduler.run()
tt = SchedulerThread(scheduler)
tt.daemon = True
tt.start()
broadlink_sp_energy_interval = cf.get('broadlink_sp_energy_interval', 0)
if device.type == 'SP2' and broadlink_sp_energy_interval > 0:
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(broadlink_sp_energy_interval, 1, broadlink_sp_energy_timer,
[scheduler, broadlink_sp_energy_interval, device, mqtt_prefix])
# scheduler.run()
tt = SchedulerThread(scheduler)
tt.daemon = True
tt.start()
broadlink_a1_sensors_interval = cf.get('broadlink_a1_sensors_interval', 0)
if device.type == 'A1' and broadlink_a1_sensors_interval > 0:
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(broadlink_a1_sensors_interval, 1, broadlink_a1_sensors_timer,
[scheduler, broadlink_a1_sensors_interval, device, mqtt_prefix])
# scheduler.run()
tt = SchedulerThread(scheduler)
tt.daemon = True
tt.start()
broadlink_mp1_state_interval = cf.get('broadlink_mp1_state_interval', 0)
if device.type == 'MP1' and broadlink_mp1_state_interval > 0:
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(broadlink_mp1_state_interval, 1, broadlink_mp1_state_timer,
[scheduler, broadlink_mp1_state_interval, device, mqtt_prefix])
# scheduler.run()
tt = SchedulerThread(scheduler)
tt.daemon = True
tt.start()
if device.type == 'Dooya DT360E':
# noinspection PyUnusedLocal
def publish(dev, percentage):
try:
percentage = str(percentage)
topic = mqtt_prefix + "position"
logging.debug("Sending Dooya position " + percentage + " to topic " + topic)
mqttc.publish(topic, percentage, qos=qos, retain=retain)
except:
logging.exception("Error")
device.publish = types.MethodType(publish, device)
broadlink_dooya_position_interval = cf.get('broadlink_dooya_position_interval', 0)
if broadlink_dooya_position_interval > 0:
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(broadlink_dooya_position_interval, 1, broadlink_dooya_position_timer,
[scheduler, broadlink_dooya_position_interval, device])
# scheduler.run()
tt = SchedulerThread(scheduler)
tt.daemon = True
tt.start()
broadlink_bg1_state_interval = cf.get('broadlink_bg1_state_interval', 0)
if device.type == 'BG1' and broadlink_bg1_state_interval > 0:
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(broadlink_bg1_state_interval, 1, broadlink_bg1_state_timer,
[scheduler, broadlink_bg1_state_interval, device, mqtt_prefix])
# scheduler.run()
tt = SchedulerThread(scheduler)
tt.daemon = True
tt.start()
return device
def broadlink_rm_temperature_timer(scheduler, delay, device, mqtt_prefix):
scheduler.enter(delay, 1, broadlink_rm_temperature_timer, [scheduler, delay, device, mqtt_prefix])
try:
temperature = str(device.check_temperature())
topic = mqtt_prefix + "temperature"
logging.debug("Sending RM temperature " + temperature + " to topic " + topic)
mqttc.publish(topic, temperature, qos=qos, retain=retain)
if device.type == 'RM4':
humidity = str(device.check_humidity())
topic = mqtt_prefix + "humidity"
logging.debug("Sending RM humidity " + humidity + " to topic " + topic)
mqttc.publish(topic, humidity, qos=qos, retain=retain)
except:
logging.exception("Error")
def broadlink_sp_energy_timer(scheduler, delay, device, mqtt_prefix):
scheduler.enter(delay, 1, broadlink_sp_energy_timer, [scheduler, delay, device, mqtt_prefix])
try:
energy = str(device.get_energy())
topic = mqtt_prefix + "energy"
logging.debug("Sending SP energy " + energy + " to topic " + topic)
mqttc.publish(topic, energy, qos=qos, retain=retain)
except:
logging.exception("Error")
def broadlink_a1_sensors_timer(scheduler, delay, device, mqtt_prefix):
scheduler.enter(delay, 1, broadlink_a1_sensors_timer, [scheduler, delay, device, mqtt_prefix])
try:
text_values = cf.get('broadlink_a1_sensors_text_values', False)
is_json = cf.get('broadlink_a1_sensors_json', False)
sensors = device.check_sensors() if text_values else device.check_sensors_raw()
if is_json:
topic = mqtt_prefix + "sensors"
value = json.dumps(sensors)
logging.debug("Sending A1 sensors '%s' to topic '%s'" % (value, topic))
mqttc.publish(topic, value, qos=qos, retain=retain)
else:
for name in sensors:
topic = mqtt_prefix + "sensor/" + name
value = str(sensors[name])
logging.debug("Sending A1 %s '%s' to topic '%s'" % (name, value, topic))
mqttc.publish(topic, value, qos=qos, retain=retain)
except:
logging.exception("Error")
def broadlink_mp1_state_timer(scheduler, delay, device, mqtt_prefix):
scheduler.enter(delay, 1, broadlink_mp1_state_timer, [scheduler, delay, device, mqtt_prefix])
try:
is_json = cf.get('broadlink_mp1_state_json', False)
state = device.check_power()
if is_json:
topic = mqtt_prefix + "state"
value = json.dumps(state)
logging.debug("Sending MP1 state '%s' to topic '%s'" % (value, topic))
mqttc.publish(topic, value, qos=qos, retain=retain)
elif state is not None:
for name in state:
topic = mqtt_prefix + "state/" + name
value = str(state[name])
logging.debug("Sending MP1 %s '%s' to topic '%s'" % (name, value, topic))
mqttc.publish(topic, value, qos=qos, retain=retain)
except:
logging.exception("Error")
def broadlink_dooya_position_timer(scheduler, delay, device):
scheduler.enter(delay, 1, broadlink_dooya_position_timer, [scheduler, delay, device])
device.publish(device.get_percentage())
def broadlink_bg1_state_timer(scheduler, delay, device, mqtt_prefix):
scheduler.enter(delay, 1, broadlink_bg1_state_timer, [scheduler, delay, device, mqtt_prefix])
try:
is_json = cf.get('broadlink_bg1_state_json', False)
state = device.get_state()
if is_json:
topic = mqtt_prefix + "state"
value = json.dumps(state)
logging.debug("Sending BG1 state '%s' to topic '%s'" % (value, topic))
mqttc.publish(topic, value, qos=qos, retain=retain)
elif state is not None:
for name in state:
topic = mqtt_prefix + "state/" + name
value = str(state[name])
logging.debug("Sending BG1 %s '%s' to topic '%s'" % (name, value, topic))
mqttc.publish(topic, value, qos=qos, retain=retain)
except:
logging.exception("Error")
class SchedulerThread(Thread):
def __init__(self, scheduler):
Thread.__init__(self)
self.scheduler = scheduler
def run(self):
try:
self.scheduler.run()
except:
logging.exception("Error")
if __name__ == '__main__':
devices = get_device(cf)
clientid = cf.get('mqtt_clientid', 'broadlink-%s' % os.getpid())
# initialise MQTT broker connection
mqttc = paho.Client(clientid, clean_session=cf.get('mqtt_clean_session', False), userdata=devices)
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
#if isinstance(devices, dict):
# for subprefix in devices:
# logging.debug("Subprefix: "+subprefix)
if cf.get('mqtt_will_payload', False):
mqttc.will_set(cf.get('mqtt_will_topic', 'clients/broadlink'), payload=cf.get('mqtt_will_payload'), qos=0, retain=True)
# Delays will be: 3, 6, 12, 24, 30, 30, ...
# mqttc.reconnect_delay_set(delay=3, delay_max=30, exponential_backoff=True)
if cf.get('tls', False):
mqttc.tls_set(cf.get('ca_certs', None), cf.get('certfile', None), cf.get('keyfile', None),
tls_version=cf.get('tls_version', None), ciphers=None)
if cf.get('tls_insecure', False):
mqttc.tls_insecure_set(True)
mqttc.username_pw_set(cf.get('mqtt_username'), cf.get('mqtt_password'))
while True:
try:
mqttc.connect(cf.get('mqtt_broker', 'localhost'), int(cf.get('mqtt_port', '1883')), 60)
mqttc.loop_forever()
except socket.error:
logging.warn("Cannot connect to MQTT server, will try to reconnect in 5 seconds")
time.sleep(5)
except KeyboardInterrupt:
sys.exit(0)
except:
logging.exception("Error")