]> the.earth.li Git - energenie-attiny.git/blob - mqtt-power
Add mqtt-power showing integration with MQTT via Python
[energenie-attiny.git] / mqtt-power
1 #!/usr/bin/python3
2 #
3 # Copyright 2018 Jonathan McDowell <noodles@earth.li>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 import glob
19 import time
20 import sys
21
22 import hid
23 import paho.mqtt.client as mqtt
24
25 debug = False
26 Broker = 'mqtt.host'
27 prefix = 'relay-{}/cmnd/#'
28 auth = {
29     'username': 'mqttuser',
30     'password': 'mqttpass',
31 }
32
33
34 def control_relay(device, relay=0, power=False):
35     cmnd = [0] * 8
36     if power:
37         cmnd[1] = 0xFF
38     else:
39         cmnd[1] = 0xFD
40     cmnd[2] = relay
41     device.write(cmnd)
42     time.sleep(1)
43
44
45 def mqtt_message(client, device, message):
46     if debug:
47         print("message received :", str(message.payload.decode("utf-8")))
48         print("           topic :", message.topic)
49
50     relay = int(message.topic[-1])
51
52     cmnd = message.payload.decode("utf-8").lower()
53     if cmnd in ["on", "1", "true"]:
54         state = True
55     elif cmnd in ["off", "0", "false"]:
56         state = False
57     else:
58         print("Unknown command value: %s" % cmnd)
59         return
60
61     control_relay(device, relay, state)
62
63
64 relay = None
65 for dev in hid.enumerate(0x16c0, 0x05df):
66     if dev['manufacturer_string'] == 'www.dcttech.com':
67         relay = hid.device()
68         relay.open_path(dev['path'])
69         break
70
71 if relay is None:
72     raise ValueError('Relay device not found')
73
74 relay.set_nonblocking(1)
75 serno = relay.get_feature_report(1, 9)
76 serno_str = bytes(serno[0:5]).decode('ascii')
77
78 client = mqtt.Client("P1Client")
79 client.tls_set(ca_certs='/etc/ssl/certs/ca-certificates.crt')
80 client.username_pw_set(auth['username'], auth['password'])
81 client.user_data_set(relay)
82 client.on_message = mqtt_message
83 client.connect(Broker, port=8883)
84 print("Subscribing to %s" % prefix.format(serno_str))
85 client.subscribe(prefix.format(serno_str))
86 client.loop_start()
87
88 while True:
89     time.sleep(60)