-
Notifications
You must be signed in to change notification settings - Fork 1
/
thinq_mqtt.py
188 lines (143 loc) · 6.99 KB
/
thinq_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
#!/usr/bin/env python3
#############################################################################
# Version: 1.1
# Changes: 2020-10-23 Error handling for mqtt-connect added
#############################################################################
import os
import json
import signal
import time
import paho.mqtt.client as paho
import logging
from thinq2.controller.auth import ThinQAuth
from thinq2.controller.thinq import ThinQ
mqtt_client_name="thinq_mqtt"
mqtt_host="localhost"
mqtt_port=1883
mqtt_topic="thinq"
mqtt_user=""
mqtt_pass=""
mqtt_qos=2
LANGUAGE_CODE = os.environ.get("LANGUAGE_CODE", "ko-KR")
COUNTRY_CODE = os.environ.get("COUNTRY_CODE", "KR")
STATE_FILE = os.environ.get("STATE_FILE", "state.json")
#############################################################################
# load from existing state or create a new client #
#############################################################################
if os.path.exists(STATE_FILE):
with open(STATE_FILE, "r") as f:
thinq = ThinQ(json.load(f))
else:
auth = ThinQAuth(language_code=LANGUAGE_CODE, country_code=COUNTRY_CODE)
print("No state file found, starting new client session.\n")
print(
"Please set the following environment variables if the default is not correct:\n"
)
print("LANGUAGE_CODE={} COUNTRY_CODE={}\n".format(LANGUAGE_CODE, COUNTRY_CODE))
print("Log in here:\n")
print(auth.oauth_login_url)
print("\nThen paste the URL to which the browser is redirected:\n")
callback_url = input()
auth.set_token_from_url(callback_url)
thinq = ThinQ(auth=auth)
print("\n")
def save_state():
with open(STATE_FILE, "w") as f:
json.dump(vars(thinq), f)
save_state()
#############################################################################
# state is easily serialized in dict form, as in this shutdown handler #
#############################################################################
def shutdown(sig, frame):
print("\nCaught SIGINT, saving application state.")
exit(0)
signal.signal(signal.SIGINT, shutdown)
#############################################################################
# display some information about the user's account/devices #
#############################################################################
mqtt_client=paho.Client(mqtt_client_name)
devices = thinq.mqtt.thinq_client.get_devices()
if len(devices.items) == 0:
print("No devices found!")
print("If you are using ThinQ v1 devices, try https://github.com/sampsyo/wideq")
exit(1)
print("UserID: {}".format(thinq.auth.profile.user_id))
print("User #: {}\n".format(thinq.auth.profile.user_no))
print("Devices:\n")
try:
mqtt_client.connect(mqtt_host,mqtt_port)
mqtt_client.publish(mqtt_topic + "/user/" + "user_id",thinq.auth.profile.user_id, 0, True)
mqtt_client.publish(mqtt_topic + "/user/" + "user_no",thinq.auth.profile.user_no, 0, True)
except Exception as error:
# Will only catch any other exception
print("Error: " + str(error))
raise
for device in devices.items:
print("{}: {} (model {})".format(device.device_id, device.alias, device.model_name))
mqtt_client.publish(mqtt_topic + "/" + device.device_id + "/device_info/alias",device.alias, 0, True)
mqtt_client.publish(mqtt_topic + "/" + device.device_id + "/device_info/model",device.model_name, 0, True)
mqtt_client.disconnect()
#############################################################################
# example of raw MQTT access #
#############################################################################
#client=paho.Client("thinq_mqtt") #create client object client1.on_publish = on_publish #assign function to callback client1.connect(broker,port) #establish connection client1.publish("house/bulb1","on")
#print("Connecting to broker: " + mqtt_host + ":" + mqtt_port)
#client.connect(mqtt_host)#connect
#print("subscribing ")
#client.subscribe(mqtt_topic) #subscribe
#print("publishing ")
#client.publish(mqtt_topic + "/state","initializing_new")#publish
print("\nListening for device events. Use Ctrl-C/SIGINT to quit.\n")
def on_message(client, userdata, msg):
#print(msg.topic)
try:
node_data=str(msg.payload.decode("utf-8","ignore"))
print()
print(node_data)
json_dict = json.loads(node_data)
mqtt_client.connect(mqtt_host,mqtt_port)
# for k, v in my_dict.items():
# print(i)
# print(type(i))
# print(v)
DeviceID=json_dict["deviceId"]
def iterate_json(d):
for k, v in d.items():
if isinstance(v, dict):
iterate_json(v)
else:
try:
print("{0} : {1}".format(k, v))
mqtt_client.publish(mqtt_topic + "/" + DeviceID + "/raw_data/" + k,v, 0, True)
if str(k).lower() == "state":
mqtt_client.publish(mqtt_topic + "/" + DeviceID + "/state",str(v).lower(), 0, True)
mqtt_client.publish(mqtt_topic + "/" + DeviceID + "/data/state",str(v).lower(), 0, True)
if str(k).lower() == "error" and str(v).lower() == "error_no":
mqtt_client.publish(mqtt_topic + "/" + DeviceID + "/error","none")
if "time" in str(k).lower():
mqtt_client.publish(mqtt_topic + "/" + DeviceID + "/data/" + str(k).lower(),v, 0, True)
if str(k).lower() == "online":
mqtt_client.publish(mqtt_topic + "/" + DeviceID + "/data/" + str(k).lower(),str(v).lower(), 0, True)
if str(k).lower() == "type":
mqtt_client.publish(mqtt_topic + "/" + DeviceID + "/data/" + str(k).lower(),str(v).lower(), 0, True)
if str(k).lower() == "temp":
mqtt_client.publish(mqtt_topic + "/" + DeviceID + "/data/" + str(k).lower(),str(v).lower().replace('temp_',''), 0, True)
if str(v).lower().endswith("_on"):
mqtt_client.publish(mqtt_topic + "/" + DeviceID + "/data/" + str(k).lower(),"On", 0, True)
if str(v).lower().endswith("_off"):
mqtt_client.publish(mqtt_topic + "/" + DeviceID + "/data/" + str(k).lower(),"Off", 0, True)
time.sleep(0.05)
#print("{0} : {1}".format(k, v))
except Exception as error:
# Will only catch any other exception
print("Error: " + str(error))
raise
iterate_json(json_dict)
mqtt_client.disconnect()
except Exception as error:
# Will only catch any other exception
print("Error: " + str(error))
raise
thinq.mqtt.on_message = on_message
thinq.mqtt.connect()
thinq.mqtt.loop_forever()