-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmqtt-hue-controller.py
More file actions
110 lines (83 loc) · 2.47 KB
/
mqtt-hue-controller.py
File metadata and controls
110 lines (83 loc) · 2.47 KB
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
#!/usr/bin/env python3
import os
import sys
import time
import configparser
import paho.mqtt.client as mqtt
from phue import Bridge
CONFIG = None
BRIDGE = None
def LOG(msg):
print(msg)
def handle_config_entry(entry):
if 'light' in entry:
if 'bri' in entry:
BRIDGE.set_light(entry['light'], 'bri', int(entry['bri']))
if 'on' in entry:
BRIDGE.set_light(entry['light'], 'on', entry.getboolean('on'))
LOG("set %s" % entry['light'])
def mqtt_on_message(client, userdata, msg):
global CONFIG
topic = msg.topic
payload = msg.payload.decode()
LOG("mqtt got message: %s: %s" % (topic, payload))
if payload in CONFIG:
handle_config_entry(CONFIG[payload])
else:
LOG("no action associated with this payload")
def mqtt_on_connect(client, userdata, flags, rc):
global CONFIG
if rc == 0:
LOG("mqtt connected")
for topic in CONFIG['MQTT']['event_topics'].split():
client.subscribe(topic, qos=0)
client.publish(
CONFIG['MQTT']['status_topic'], "hue-controller up and running", qos=0, retain=True)
else:
LOG("mqtt connection failed")
sys.exit(1)
def mqtt_init():
global CONFIG
protocol = mqtt.MQTTv311
if 'protocol' in CONFIG['MQTT']:
pass
client_id = CONFIG['MQTT'].get('client_id', 'hue-controller')
client = mqtt.Client(
client_id=client_id, clean_session=False, protocol=protocol)
client.on_connect = mqtt_on_connect
client.on_message = mqtt_on_message
return client
def bridge_init():
global CONFIG
global BRIDGE
BRIDGE = Bridge(ip=CONFIG['Hue']['host'], username=CONFIG['Hue']['key'])
BRIDGE.connect()
def main():
global CONFIG
config = configparser.ConfigParser()
config.read('/etc/mqtt_hue_controller/config.ini')
CONFIG = config
client = mqtt_init()
try:
client.connect(
CONFIG['MQTT']['host'],
int(CONFIG['MQTT']['port']),
60)
except socket.error as err:
LOG(err)
sys.exit(1)
bridge_init()
client.loop_start()
try:
while True:
time.sleep(10)
except KeyboardInterrupt:
LOG("KeyboardInterrupt")
finally:
client.publish(
CONFIG['MQTT']['status_topic'], "hue-controller dead", qos=0, retain=True)
time.sleep(0.1)
client.disconnect()
sys.exit(0)
if __name__ == "__main__":
main()