-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlc.py
executable file
·487 lines (400 loc) · 14.1 KB
/
lc.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#!/usr/bin/python
import requests
try:
import simplejson as json
except ImportError:
import json
import sys
import time
import getopt
from pathlib import Path
from os.path import exists
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qsl, parse_qs
import webbrowser
import keyring
import warnings
warnings.filterwarnings("ignore")
lightstat = None
interactive = False
config_path = str(Path.home()) + '/.config/LightControl/'
topology_path = config_path + 'topology.json'
token_path = config_path + 'token.json'
app_params_path = config_path + 'app_params.json'
token_service = "LightControl"
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>Authentication successfull</title></head>", "utf-8"))
self.wfile.write(bytes("<body><p>Authentication successfull.</p>", "utf-8"))
self.wfile.write(bytes("<p>You can now close this page.</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
res = parse_qs(urlparse(self.path).query)
code = res['code'][0]
#app_params = json.loads(open(app_param_path, "r").read())
files = {
'grant_type': (None, 'authorization_code'),
'client_secret': (None, app_params['client_secret']),
'client_id': (None, app_params['client_id']),
'code': (None, code),
'redirect_uri': (None, app_params['redirect_uri']),
'scope': (None, 'read_magellan write_magellan read_thermostat write_thermostat'),
}
response = requests.post('https://api.netatmo.com/oauth2/token', files=files)
token=json.loads(response.text)
token_str=json.dumps(token, indent = 4, sort_keys=True)
if token_in_keyring:
keyring.set_password(token_service, "access_token", token["access_token"])
keyring.set_password(token_service, "refresh_token", token["refresh_token"])
else:
token_str=json.dumps(token, indent = 4, sort_keys=True)
f = open(token_path, "w")
f.write(token_str)
f.close()
def log_into_netatmo():
hostName=app_params['host_name']
hostPort=app_params['host_port']
myServer = HTTPServer((hostName, hostPort), MyServer)
print(time.asctime(), "Server Starts - %s:%s" % (hostName, hostPort))
# Display login page in a browser
authorize_url="https://api.netatmo.com/oauth2/authorize"
authorize_url+="?client_id="+app_params['client_id']
authorize_url+="&redirect_uri="+app_params['redirect_uri']
authorize_url+="&scope=read_magellan%20write_magellan%20read_thermostat%20write_thermostat"
webbrowser.open(authorize_url, new=2)
print("Browser should open, if not go to " + authorize_url)
try:
# Handle one request then exit
myServer.handle_request()
except KeyboardInterrupt:
print("Exit via keyboard interrupt");
pass
myServer.server_close()
def renew_token():
global token
files = {
'client_id': (None, app_params['client_id']),
'client_secret': (None, app_params['client_secret']),
'grant_type': (None, 'refresh_token'),
'refresh_token': (None, token['refresh_token']),
}
response = requests.post('https://api.netatmo.com/oauth2/token', files=files)
token=json.loads(response.text)
token_str=json.dumps(token, indent = 4, sort_keys=True)
if token_in_keyring:
keyring.set_password(token_service, "access_token", token["access_token"])
keyring.set_password(token_service, "refresh_token", token["refresh_token"])
else:
token_str=json.dumps(token, indent = 4, sort_keys=True)
f = open(token_path, "w")
f.write(token_str)
f.close()
def get_topology():
global topology
global id_home
authorization="Bearer " + token['access_token']
headers = {
'Authorization': authorization,
}
url = 'https://api.netatmo.com/api/homesdata'
response = requests.get(url, headers=headers)
if not response.ok:
# maybe token has expired
renew_token()
headers['Authorization'] = "Bearer " + token['access_token']
response = requests.get(url, headers=headers)
if not response.ok:
sys.exit(-1)
topology=json.loads(response.text)["body"]["homes"][0]
id_home=topology["id"]
def print_topology():
global topology
print(json.dumps(topology, indent = 4))
def write_topology():
global topology
f=open(topology_path, "w")
f.write(json.dumps(topology, indent = 4))
f.close()
def get_plant():
global token
global roomstemp
authorization="Bearer " + token['access_token']
url="https://api.netatmo.com/api/homestatus?home_id="+id_home#+"&device_types=NLG"
headers = {
'Content-Type': 'application/json',
'Authorization': authorization,
}
response = requests.get(url, headers=headers)
if not response.ok:
if interactive:
rewind(1)
print("Getting new token ...")
renew_token()
headers['Authorization'] = "Bearer " + token['access_token']
response = requests.get(url, headers=headers)
if not response.ok:
return None
p = json.loads(response.text)["body"]["home"]
roomstemp = {}
for r in p["rooms"]:
roomstemp[r["id"]] = r
return p
def set_light(light_id, new_status):
authorization="Bearer " + token['access_token']
headers = {
'Content-Type': 'application/json',
'Authorization': authorization,
}
url="https://api.netatmo.com/api/setstate"
data = '{"home": {"id": "' + id_home + '",'
data += '"modules": [ {'
data += '"id":"' + light_id + '",'
data += '"on":' + new_status + ','
data += '"bridge":"' + lights[light_id]["bridge"] + '"'
data += '} ]' # end modules
data += '} }' # end home
response = requests.post(url, headers=headers, data=data)
if not response.ok:
if interactive :
rewind(1)
print("Getting new token ...")
renew_token()
headers['Authorization'] = "Bearer " + token['access_token']
response = requests.post(url, headers=headers, data=data)
def set_light_level(light_id, new_level):
authorization="Bearer " + token['access_token']
headers = {
'Content-Type': 'application/json',
'Authorization': authorization,
}
url="https://api.netatmo.com/api/setstate"
data = '{"home": {"id": "' + id_home + '",'
data += '"modules": [ {'
data += '"id":"' + light_id + '",'
data += '"brightness":' + new_level + ','
data += '"bridge":"' + lights[light_id]["bridge"] + '"'
data += '} ]' # end modules
data += '} }' # end home
response = requests.post(url, headers=headers, data=data)
if not response.ok:
if interactive :
rewind(1)
print("Getting new token ...")
renew_token()
headers['Authorization'] = "Bearer " + token['access_token']
response = requests.post(url, headers=headers, data=data)
def build_lightstat():
lightstat = {}
for module in plant["modules"]:
if module["id"] in lights:
id = module['id']
lightstat[id] = {}
lightstat[id]["status"] = module['on']
if "brightness" in module:
lightstat[id]["level"] = module["brightness"]
return lightstat
def build_lightlist():
lights={}
for module in topology['modules']:
if module['type'] == "NLM":
lights[module["id"]] = module
elif module['type'] == "NLF":
lights[module["id"]] = module
return lights
def build_ambientlist():
amb=[]
for ambient in topology["rooms"]:
if "module_ids" in ambient:
amb.append(ambient)
return amb
def build_lightmap():
lightno = 0
lightmap = {}
for ambient in topology["rooms"]:
if "module_ids" in ambient:
for mid in ambient["module_ids"]:
if mid in lights:
lightchar = chr(ord('a') + lightno)
lightmap[lightchar]=mid
lightno+=1
return lightmap
def print_status():
global lightstat
global roomstemp
lightno = 0
for ambient in topology["rooms"]:
if "module_ids" in ambient:
n = ambient["name"]
if ambient["id"] in roomstemp :
r = roomstemp[ambient["id"]]
if interactive :
n += "\033[32m"
n += " ["
n += str(r["therm_measured_temperature"])
n += " / "
n += str(r["therm_setpoint_temperature"])
n += "]"
if interactive :
n += "\033[0m "
print (n)
for mid in ambient["module_ids"]:
if mid in lights:
lightchar = chr(ord('a') + lightno)
dispstr = " " + lightchar + " "
lightno += 1
if not lightstat is None:
l = lightstat[mid]
if l["status"] :
if interactive :
dispstr += "\033[33m#\033[0m "
else :
dispstr += "# "
else:
if interactive :
dispstr += "\033[34m-\033[0m "
else :
dispstr += "- "
else:
dispstr += "- "
dispstr += lights[mid]["name"]
if (not lightstat is None) and "level" in l:
if interactive :
dispstr += "\033[36m (" + str(l["level"]) + ")\033[0m"
else :
dispstr += " (" + str(l["level"]) +")"
print (dispstr)
def clear_line():
sys.stdout.write(u"\u001b[0K")
def rewind(steps):
for i in range(steps):
sys.stdout.write(u"\u001b[0K\033[F")
def process_cmd(cmd):
global lightmap
if cmd[0] >= 'A' and cmd[0] <= 'Z':
c = chr (ord(cmd[0]) - ord('A') + ord('a'))
set_light_level(lightmap[c], cmd[1:])
else:
# toggle each light in the string
for c in cmd:
if c >= 'a' and c <= 'z':
light_id = lightmap[c]
if lightstat[light_id]["status"]:
set_light(light_id, "false")
else:
set_light(light_id, "true")
def cmd_loop():
global lightstat
global plant
while True:
rewind(len(lights) + len(ambients) + 1)
print_status()
clear_line()
cmd = input("cmd> ");
if len(cmd) > 0:
process_cmd(cmd)
time.sleep(0.5) # status update is not instantaneous
plant=get_plant()
lightstat=build_lightstat()
else:
break
def tui():
global token
global app_params
global plant
global lightstat
# print topology to user
print_status()
print("Initializing ... ");
plant = get_plant()
if plant is None:
sys.exit(-1)
lightstat = build_lightstat()
cmd_loop()
# opening app parameters
# if params file does not exists, exit
if not exists(app_params_path):
print("No application parameters ... exiting")
quit()
f=open(app_params_path, "r")
app_params = json.loads(f.read())
f.close()
# reading token
# if token does not exists, login into netatmo server
if "token_in_keyring" in app_params :
token_in_keyring = app_params["token_in_keyring"]
else :
token_in_keyring = False
if token_in_keyring :
token = {}
token["access_token"] = keyring.get_password(token_service, "access_token")
if token["access_token"] == None :
print("Login in Netatmo ...");
log_into_netatmo()
token["access_token"] = keyring.get_password(token_service, "access_token")
token["refresh_token"] = keyring.get_password(token_service, "refresh_token")
else :
if not exists(token_path):
print("Login in Netatmo ...");
log_into_netatmo()
f=open(token_path, "r")
token = json.loads(f.read())
f.close()
# if topology does not exists, get and store it
if not exists(topology_path):
print("No topology file, getting it from server")
get_topology()
write_topology()
else:
f=open(topology_path, "r")
topology = json.loads(f.read())
f.close()
id_home=topology["id"]
lights=build_lightlist()
ambients=build_ambientlist()
lightmap = build_lightmap()
roomstemp = {}
if len(sys.argv) == 1:
interactive = True
tui()
else:
opts, args = getopt.getopt(sys.argv[1:],"stgpwrv")
for opt, arg in opts:
if opt == '-t':
print_status()
elif opt == '-v':
plant = get_plant()
print(json.dumps(plant))
elif opt == '-g':
get_topology()
elif opt == '-p':
print_topology()
elif opt == '-w':
write_topology()
elif opt == '-r':
plant = get_plant()
if plant is None:
sys.exit(-1)
lightstat = build_lightstat()
lights=build_lightlist()
ambient=build_ambientlist()
print_status()
elif opt == '-s':
interactive = True
print_status()
print ("Initializing ... ")
plant = get_plant()
if plant is None:
sys.exit(-1)
lightstat = build_lightstat()
lights=build_lightlist()
ambients=build_ambientlist()
rewind(len(lights) + len(ambients) + 1)
print_status()
clear_line()
if len(args) > 0:
plant = get_plant()
lightstat = build_lightstat()
for i in args:
process_cmd(i)