-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
executable file
·244 lines (198 loc) · 9.37 KB
/
app.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#!/usr/bin/python3
# tado_aa.py (Tado Auto-Assist for Geofencing and Open Window Detection)
# Created by Adrian Slabu <[email protected]> on 11.02.2021
#
# Adjusted for Docker usage
import sys
import time
import inspect
import os
import logging
import socketserver
from http.server import BaseHTTPRequestHandler
from datetime import datetime
from PyTado.interface import Tado
from threading import Thread
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("OK\n".encode("utf-8"))
def log_message(self, format, *args):
return
def demonized():
port = int(os.getenv("TADO_HEALTHCHECK_PORT", default = 8080 )) # Healthcheck port for Cloud Run (GCP)
print(f"Starting status server on port {port}")
httpd = socketserver.TCPServer(("0.0.0.0", port), MyHandler)
httpd.serve_forever()
def main():
global lastMessage
global username
global password
global checkingInterval
global errorRetringInterval
global enableLog
global logFile
lastMessage = ""
username = os.getenv("USERNAME")
password = os.getenv("PASSWORD")
# Convertion to float is needed as the environment variable is treated as string
checkingInterval = float(os.getenv("TADO_CHECK_INTERVAL",default = 10.0 )) # checking interval (in seconds)
errorRetringInterval = 30.0 # retrying interval (in seconds), in case of an error
enableLog = os.getenv("TADO_ENABLE_LOG", default = False) # activate the log with "True" or disable it with "False"
logFile = os.getenv("TADO_LOG_FILE", default = "/var/log/tado.log") # log file location
# To change status port , set TADO_HEALTHCHECK_PORT to a valid tcp port
httpd = Thread(target=demonized)
httpd.daemon = True
httpd.start()
login()
homeStatus()
def login():
global t
try:
t = Tado(username, password)
if (lastMessage.find("Connection Error") != -1):
printm ("Connection established, everything looks good now, continuing..\n")
except KeyboardInterrupt:
printm ("Interrupted by user.")
sys.exit(0)
except Exception as e:
if (str(e).find("access_token") != -1):
printm ("Login error, check the username / password !")
sys.exit(0)
else:
printm (str(e) + "\nConnection Error, retrying in " + str(errorRetringInterval) + " sec..")
time.sleep(errorRetringInterval)
login()
def homeStatus():
global devicesHome
try:
homeState = t.get_home_state()["presence"]
devicesHome = []
for mobileDevice in t.get_mobile_devices():
if (mobileDevice["settings"]["geoTrackingEnabled"] == True):
if (mobileDevice["location"] != None):
if (mobileDevice["location"]["atHome"] == True):
devicesHome.append(mobileDevice["name"])
if (lastMessage.find("Connection Error") != -1 or lastMessage.find("Waiting for the device location") != -1):
printm ("Successfully got the location, everything looks good now, continuing..\n")
if (len(devicesHome) > 0 and homeState == "HOME"):
if (len(devicesHome) == 1):
printm ("Your home is in HOME Mode, the device " + devicesHome[0] + " is at home.")
else:
devices = ""
for i in range(len(devicesHome)):
if (i != len(devicesHome) - 1):
devices += devicesHome[i] + ", "
else:
devices += devicesHome[i]
printm ("Your home is in HOME Mode, the devices " + devices + " are at home.")
elif (len(devicesHome) == 0 and homeState == "AWAY"):
printm ("Your home is in AWAY Mode and are no devices at home.")
elif (len(devicesHome) == 0 and homeState == "HOME"):
printm ("Your home is in HOME Mode but are no devices at home.")
printm ("Activating AWAY mode.")
t.set_away()
printm ("Done!")
elif (len(devicesHome) > 0 and homeState == "AWAY"):
if (len(devicesHome) == 1):
printm ("Your home is in AWAY Mode but the device " + devicesHome[0] + " is at home.")
else:
devices = ""
for i in range(len(devicesHome)):
if (i != len(devicesHome) - 1):
devices += devicesHome[i] + ", "
else:
devices += devicesHome[i]
printm ("Your home is in AWAY Mode but the devices " + devices + " are at home.")
printm ("Activating HOME mode.")
t.set_home()
printm ("Done!")
devicesHome.clear()
printm ("Waiting for a change in devices location or for an open window..")
time.sleep(1)
engine()
except KeyboardInterrupt:
printm ("Interrupted by user.")
sys.exit(0)
except Exception as e:
if (str(e).find("location") != -1):
printm ("I cannot get the location of one of the devices because the Geofencing is off or the user signed out from tado app.\nWaiting for the device location, until then the Geofencing Assist is NOT active.\nWaiting for an open window..")
time.sleep(1)
engine()
elif (str(e).find("NoneType") != -1):
time.sleep(1)
engine()
else:
printm (str(e) + "\nConnection Error, retrying in " + str(errorRetringInterval) + " sec..")
time.sleep(errorRetringInterval)
homeStatus()
def engine():
i = 0
while(True): # My solution to fix the "stack depth"
try:
#Open Window Detection
for z in t.get_zones():
zoneID = z["id"]
zoneName = z["name"]
if (t.get_open_window_detected(zoneID)["openWindowDetected"] == True):
printm (zoneName + ": open window detected, activating the OpenWindow mode.")
t.set_open_window(zoneID)
printm ("Done!")
printm ("Waiting for a change in devices location or for an open window..")
#Geofencing
homeState = t.get_home_state()["presence"]
devicesHome.clear()
for mobileDevice in t.get_mobile_devices():
if (mobileDevice["settings"]["geoTrackingEnabled"] == True):
if (mobileDevice["location"] != None):
if (mobileDevice["location"]["atHome"] == True):
devicesHome.append(mobileDevice["name"])
if (lastMessage.find("Connection Error") != -1 or lastMessage.find("Waiting for the device location") != -1):
printm ("Successfully got the location, everything looks good now, continuing..\n")
printm ("Waiting for a change in devices location or for an open window..")
if (len(devicesHome) > 0 and homeState == "AWAY"):
if (len(devicesHome) == 1):
printm (devicesHome[0] + " is at home, activating HOME mode.")
else:
devices = ""
for i in range(len(devicesHome)):
if (i != len(devicesHome) - 1):
devices += devicesHome[i] + ", "
else:
devices += devicesHome[i]
printm (devices + " are at home, activating HOME mode.")
t.set_home()
printm ("Done!")
printm ("Waiting for a change in devices location or for an open window..")
elif (len(devicesHome) == 0 and homeState == "HOME"):
printm ("Are no devices at home, activating AWAY mode.")
t.set_away()
printm ("Done!")
printm ("Waiting for a change in devices location or for an open window..")
devicesHome.clear()
time.sleep(checkingInterval)
except KeyboardInterrupt:
printm ("Interrupted by user.")
sys.exit(0)
except Exception as e:
if (str(e).find("location") != -1 or str(e).find("NoneType") != -1):
printm ("I cannot get the location of one of the devices because the Geofencing is off or the user signed out from tado app.\nWaiting for the device location, until then the Geofencing Assist is NOT active.\nWaiting for an open window..")
time.sleep(checkingInterval)
else:
printm (str(e) + "\nConnection Error, retrying in " + str(errorRetringInterval) + " sec..")
time.sleep(errorRetringInterval)
def printm(message):
global lastMessage
if (enableLog == True and message != lastMessage):
try:
with open(logFile, "a") as log:
log.write(datetime.now().strftime('%d-%m-%Y %H:%M:%S') + " # " + message + "\n")
log.close()
except Exception as e:
sys.stdout.write(datetime.now().strftime('%d-%m-%Y %H:%M:%S') + " # " + str(e) + "\n")
if (message != lastMessage):
lastMessage = message
sys.stdout.write(datetime.now().strftime('%d-%m-%Y %H:%M:%S') + " # " + message + "\n")
main()