-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtriones2mqtt.py
executable file
·110 lines (83 loc) · 2.6 KB
/
triones2mqtt.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
#!/bin/python3
import sys
import json
import yaml
import paho.mqtt.client as mqtt
import lightbulb
def log(msg):
print(msg)
sys.stdout.flush()
def mqtt_message(client, userdata, message):
msg = str(message.payload.decode("utf-8"))
if message.topic == "homeassistant/status":
if msg != "online": return
elif not message.topic.endswith("/get") :
log("Received SET " + msg)
data = json.loads(msg)
if "color" in data:
rgb = data["color"]
light.setRGB(rgb["r"],rgb["g"],rgb["b"])
elif "white_value" in data:
light.setWhite(data["white_value"])
elif "effect" in data:
light.setEffect(data["effect"])
if "brightness" in data:
light.setBrightness(data["brightness"])
if "effect_speed" in data:
light.setEffectSpeed(data["effect_speed"])
if "state" in data:
if data["state"] == "ON":
light.turnOn()
elif data["state"] == "OFF":
light.turnOff()
elif data["state"] == "TOGGLE":
light.toggle()
msg = light.getStateJSON()
client.publish(light.getStateTopic(),msg)
log("Sent " + msg)
def mqtt_disconnect(client, userdata, rc):
if rc != 0:
log ("MQTT unexpected disconnect. Reconnecting...")
####Read Config
with open("config.yaml","r") as stream:
try:
config = yaml.load(stream, Loader=yaml.SafeLoader)
except:
log("malformed config file")
sys.exit()
availability_topic = "triones2mqtt/availability"
light = None
#/while light is None:
#try:
log("Connecting to lightbulb")
light = lightbulb.Lightbulb(config["light"])
log ("Lightbulb connected")
#except Exception as e:
# log ("Error connecting")
# log (str(e))
# exit
#else:
try:
log ("Connecting to MQTT")
client = mqtt.Client()
client.will_set(availability_topic, "offline", 0, True)
if config["mqtt"]["username"] != None and config["mqtt"]["password"] != None:
client.username_pw_set(config["mqtt"]["username"],config["mqtt"]["password"])
client.connect(config["mqtt"]["server"])
log ("MQTT Connected")
msg = light.getStateJSON()
client.publish(light.getStateTopic(),msg)
log("Sent " + msg)
client.subscribe(light.getCommandTopic())
client.subscribe(light.getGetTopic())
client.publish(availability_topic, "online", 0, True)
if "homeassistant" in config:
client.publish(light.getHAConfigPath(),light.getHAConfigJSON(availability_topic),0,True)
client.subscribe("homeassistant/status")
client.on_message=mqtt_message
client.on_disconnect=mqtt_disconnect
client.loop_forever()
finally:
light.disconnect()
client.publish(availability_topic, "offline", 0, True)
client.disconnect()