-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
180 lines (131 loc) · 5.78 KB
/
main.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
#!/usr/bin/env python
import asyncio;
import json;
import paho.mqtt.client as mqtt;
import GoveeBleLight;
import sys;
import getopt;
import time;
import signal;
SERVER_ZONE_ID: int = 1;
ADAPTER: str = None;
MQTT_SERVER: str = "192.168.14.12";
MQTT_PORT: int = 1883;
MQTT_USER: str = None;
MQTT_PASS: str = None;
# ////////////////////////////////////////////////////////////////////////////
# ////////////////////////////////////////////////////////////////////////////
CLIENTS = {};
MESSAGE_QUEUE = [];
RUNNING = True;
# ////////////////////////////////////////////////////////////////////////////
# ////////////////////////////////////////////////////////////////////////////
# Entry point
async def main(argv):
global SERVER_ZONE_ID;
global ADAPTER;
global CLIENTS;
global MESSAGE_QUEUE;
global RUNNING;
l_Options, _ = getopt.getopt(argv,"hz:a:",["adapter=","zone="])
for l_Option, l_Argument in l_Options:
if l_Option == '-h':
print('main.py -a <adapter> -z <zone>');
sys.exit();
elif l_Option in ("-a", "--adapter"):
ADAPTER = l_Argument
elif l_Option in ("-z", "--zone"):
SERVER_ZONE_ID = l_Argument
print("[Main] Starting with zone " + str(SERVER_ZONE_ID));
if ADAPTER is not None:
print("[Main] Starting with adapter " + ADAPTER);
signal.signal(signal.SIGINT, Signal_OnSigInt);
l_MqttClient = mqtt.Client();
l_MqttClient.on_connect = Mqtt_OnConnect;
l_MqttClient.on_message = Mqtt_OnMessage;
if MQTT_USER != None and MQTT_PASS != None:
l_MqttClient.username_pw_set(MQTT_USER, MQTT_PASS);
l_MqttClient.connect(MQTT_SERVER, MQTT_PORT, 60);
while RUNNING:
try:
if l_MqttClient.loop() != mqtt.MQTT_ERR_SUCCESS:
print("[Main] Disconnected from Mqtt, trying to reconnect in 5 seconds...");
time.sleep(5);
if l_MqttClient.connect(MQTT_SERVER, MQTT_PORT, 60) == mqtt.MQTT_ERR_SUCCESS:
pass;
while len(MESSAGE_QUEUE) > 0:
l_Message = MESSAGE_QUEUE.pop(0);
l_Topic = l_Message.topic;
l_Prefix = "goveeblemqtt/zone" + str(SERVER_ZONE_ID) + "/light/";
l_Suffix = "/command";
if not l_Topic.startswith(l_Prefix) and not l_Topic.endwith(l_Suffix):
continue;
l_DeviceID = l_Topic[len(l_Prefix):len(l_Topic)-len(l_Suffix)];
l_Model = "generic";
l_Payload = json.loads(l_Message.payload.decode("utf-8","ignore"));
if "_" in l_DeviceID:
l_Model = l_DeviceID[l_DeviceID.find('_')+1:];
l_DeviceID = l_DeviceID[:l_DeviceID.find('_')];
OnPayloadReceived(l_MqttClient, l_Topic, l_DeviceID, l_Model, l_Payload);
except:
pass;
print("[Main] Exiting...");
for l_Client in CLIENTS:
CLIENTS[l_Client].Close();
sys.exit(0);
# ////////////////////////////////////////////////////////////////////////////
# ////////////////////////////////////////////////////////////////////////////
# On signal Int
def Signal_OnSigInt(p_Signal, p_Frame):
global RUNNING;
RUNNING = False;
print("[Signal_OnSigInt] Exiting...");
# ////////////////////////////////////////////////////////////////////////////
# ////////////////////////////////////////////////////////////////////////////
# On Mqtt connect
def Mqtt_OnConnect(p_MqttClient, _, __, ___):
l_Topic = "goveeblemqtt/zone" + str(SERVER_ZONE_ID) + "/light/+/command";
print("[Mqtt_OnConnect] Connected to Mqtt broker")
print("[Mqtt_OnConnect] Subscribing to topic: " + l_Topic);
p_MqttClient.subscribe(l_Topic)
# On Mqtt message
def Mqtt_OnMessage(p_MqttClient, _, p_Message):
global MESSAGE_QUEUE;
MESSAGE_QUEUE.append(p_Message);
# ////////////////////////////////////////////////////////////////////////////
# ////////////////////////////////////////////////////////////////////////////
def OnPayloadReceived(p_MqttClient, p_Topic, p_DeviceID, p_Model, p_Paypload):
global CLIENTS;
global MESSAGE_QUEUE;
l_RequestedDeviceID = p_DeviceID;
l_Device = None;
print(p_DeviceID + " " + str(p_Paypload));
try:
p_DeviceID = ':'.join(p_DeviceID[i:i+2] for i in range(0, len(p_DeviceID), 2));
if not p_DeviceID in CLIENTS:
l_Topic = p_Topic[0:p_Topic.rfind("/") + 1] + "state";
CLIENTS[p_DeviceID] = GoveeBleLight.Client(p_DeviceID, p_Model, p_MqttClient, l_Topic, ADAPTER);
time.sleep(2);
l_Device = CLIENTS[p_DeviceID];
if "state" in p_Paypload:
l_ExpectedState = 1 if p_Paypload["state"] == "ON" else 0;
if l_Device.State != l_ExpectedState:
l_Device.SetPower(l_ExpectedState);
if "brightness" in p_Paypload:
l_Device.SetBrightness(p_Paypload["brightness"] / 255);
if "segment" in p_Paypload:
l_Device.SetSegment(p_Paypload["segment"]);
if "color_temp" in p_Paypload:
l_Device.SetColorTempMired(p_Paypload["color_temp"]);
if "color" in p_Paypload:
l_R = p_Paypload["color"]["r"];
l_G = p_Paypload["color"]["g"];
l_B = p_Paypload["color"]["b"];
if l_Device.R != l_R or l_Device.G != l_G or l_Device.B != l_B:
l_Device.SetColorRGB(l_R, l_G, l_B);
except Exception as l_Exception:
print(f"[OnPayloadReceived] OnPayloadReceived: Something Bad happened: {l_Exception}")
# ////////////////////////////////////////////////////////////////////////////
# ////////////////////////////////////////////////////////////////////////////
if __name__ == "__main__":
asyncio.run(main(sys.argv[1:]));