-
Notifications
You must be signed in to change notification settings - Fork 1
/
nuki2influxdb.py
executable file
·353 lines (287 loc) · 10 KB
/
nuki2influxdb.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
#!/usr/bin/env python3
# encoding=utf-8
from pytz import timezone
from datetime import datetime
from influxdb_client import InfluxDBClient, Point, WriteOptions
from influxdb_client.client.write_api import SYNCHRONOUS
import json
import os
import sys
import requests
import subprocess
import platform
# function ping test
def pingTest(pingHost):
try:
output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', pingHost), shell=True)# except Exception as e:
except Exception as e:
return False
return True
# debug enviroment variables
showraw = False
debug_str=os.getenv("DEBUG", None)
if debug_str is not None:
debug = debug_str.lower() == "true"
else:
debug = False
# Nuki envionment variables
nuki_api_token=os.getenv('NUKI_WEB_API_TOKEN', "")
nuki_bridge_ip=os.getenv('NUKI_BRIDGE_IP', "")
nuki_bridge_token=os.getenv('NUKI_BRIDGE_TOKEN', "")
# influxDBv2 envionment variables
influxdb2_host=os.getenv('INFLUXDB2_HOST', "localhost")
influxdb2_port=int(os.getenv('INFLUXDB2_PORT', "8086"))
influxdb2_org=os.getenv('INFLUXDB2_ORG', "Home")
influxdb2_token=os.getenv('INFLUXDB2_TOKEN', "")
influxdb2_bucket=os.getenv('INFLUXDB2_BUCKET', "DEV")
influxdb2_ssl_str=os.getenv('INFLUXDB2_SSL', "False")
if influxdb2_ssl_str is not None:
influxdb2_ssl = influxdb2_ssl_str.lower() == "true"
else:
influxdb2_ssl = False
influxdb2_ssl_verify_str=os.getenv('INFLUXDB2_SSL_VERIFY', "True")
if influxdb2_ssl_verify_str is not None:
influxdb2_ssl_verify = influxdb2_ssl_verify_str.lower() == "true"
else:
influxdb2_ssl_verify = False
# hard encoded envionment varables for testing
if os.path.exists('private-nuki.py'):
print(" incl: private-nuki.py")
exec(compile(source=open('private-nuki.py').read(), filename='private-nuki.py', mode='exec'))
debug = False
# report debug status
if debug:
print ( " debug: TRUE" )
if influxdb2_ssl:
print ( " SSL: TRUE" )
else:
print ( " SSL: FALSE" )
if influxdb2_ssl_verify:
print ( "verify: TRUE" )
else:
print ( "verify: FALSE" )
else:
print ( " debug: FALSE" )
# influxDBv2
if influxdb2_ssl_str:
influxdb2_url="https://" + influxdb2_host + ":" + str(influxdb2_port)
else:
influxdb2_url="http://" + influxdb2_host + ":" + str(influxdb2_port)
if debug:
print ( "influx"+influxdb2_url+"\nbucket: "+influxdb2_bucket )
if influxdb2_ssl_verify:
if debug:
print ( "verify: True" )
client = InfluxDBClient(url=influxdb2_url, token=influxdb2_token, org=influxdb2_org, verify_ssl=True)
else:
if debug:
print ( "verify: False" )
client = InfluxDBClient(url=influxdb2_url, token=influxdb2_token, org=influxdb2_org, verify_ssl=False)
write_api = client.write_api(write_options=SYNCHRONOUS)
def write_influxdb():
if debug:
print ("INFLUX: "+influxdb2_bucket)
print (json.dumps(senddata,indent=4))
write_api.write(bucket=influxdb2_bucket, org=influxdb2_org, record=[senddata])
# test for Nuki Bridge
if not nuki_bridge_ip and not nuki_bridge_token:
nukiBridge = False
if debug:
print ("bridge: FALSE")
else:
nukiBridge = True
if debug:
print ("bridge: TRUE ", end='')
if pingTest( nuki_bridge_ip ):
if debug:
print ("ping OK")
else:
if debug:
print ("ping NOK")
# get Nuki Bridge API
if nukiBridge:
url="http://"+nuki_bridge_ip+":8080/list&token="+nuki_bridge_token
try:
raw = requests.get(url, timeout=4)
except requests.exceptions.Timeout as e:
if debug:
print ("BL API:",e)
if raw.status_code == requests.codes.ok:
if debug:
print ("BL API: OK ["+str(raw.status_code)+"]")
dsList = raw.json()
if debug and showraw:
print ("BL RAW:")
print (json.dumps(dsList,indent=4))
else:
if debug:
print ("BL API: NOK")
url="http://"+nuki_bridge_ip+":8080/info&token="+nuki_bridge_token
try:
raw = requests.get(url, timeout=4)
except requests.exceptions.Timeout as e:
if debug:
print ("BI API:",e)
if raw.status_code == requests.codes.ok:
if debug:
print ("BI API: OK ["+str(raw.status_code)+"]")
dsInfo = raw.json()
if debug and showraw:
print ("BI RAW:")
print (json.dumps(dsInfo,indent=4))
else:
if debug:
print ("BI API: NOK")
senddata={}
senddata["measurement"]="signal"
senddata["tags"]={}
senddata["tags"]["origin"]="Nuki"
senddata["tags"]["source"]="docker nuki-influxdb2"
senddata["fields"]={}
# pass info
for key in dsList:
name=key['name']
nukiID=key['nukiId']
senddata["tags"]["host"]=name
for key2 in dsInfo['scanResults']:
if key2['nukiId'] == nukiID:
rssi=key2['rssi']
signal=( rssi + 100 )*2.0
senddata["fields"]["percent"]=signal
senddata["fields"]["rssi"]=rssi
write_influxdb()
# get Nuki Web API
baseURL="https://api.nuki.io"
pathURL="smartlock"
url=baseURL+"/"+pathURL
try:
devJ = requests.get(url, timeout=4, headers = {"Authorization": "Bearer "+nuki_api_token} )
except requests.exceptions.Timeout as e:
if debug:
print ("WD API:",e)
# continue
if devJ.status_code == requests.codes.ok:
if debug:
print ("WD API: OK ["+str(devJ.status_code)+"]")
devList = devJ.json()
if debug and showraw:
print ("WD RAW:")
print (json.dumps(devList,indent=4))
else:
if debug:
print ("WD API: NOK")
# continue
pathURL="smartlock/log"
optionURL="?limit=25"
url=baseURL+"/"+pathURL+optionURL
try:
logJ = requests.get(url, timeout=4, headers = {"Authorization": "Bearer "+nuki_api_token} )
except requests.exceptions.Timeout as e:
if debug:
print ("WL API:",e)
# continue
if logJ.status_code == requests.codes.ok:
if debug:
print ("WL API: OK ["+str(logJ.status_code)+"]")
logList = logJ.json()
if debug and showraw:
print ("WL RAW:")
print (json.dumps(logList,indent=4))
else:
if debug:
print ("WL API: NOK")
# continue
# pass smartlock devices
for key in devList:
name=key['name']
smartlockID=key['smartlockId']
stateID=key['state']['state']
triggerID=key['state']['trigger']
if triggerID == 0: trigger="proximity"
elif triggerID == 1: trigger="manual"
elif triggerID == 2: trigger="button"
elif triggerID == 3: trigger="automatic"
elif triggerID == 6: trigger="continious"
else: trigger="other"
if key['type'] == 2:
if stateID == 1: state="online"
elif stateID == 3: state="ring-to-open"
elif stateID == 5: state="open"
elif stateID == 7: state="opening"
else: state="other"
else:
if stateID == 1: state="locked"
elif stateID == 2: state="unlocking"
elif stateID == 3: state="unlocked"
elif stateID == 4: state="locking"
elif stateID == 5: state="unlatched"
elif stateID == 6: state="lock-n-go"
elif stateID == 7: state="unlatching"
else: state="other"
senddata={}
senddata["measurement"]="lock"
senddata["tags"]={}
senddata["tags"]["origin"]="Nuki"
senddata["tags"]["source"]="docker nuki-influxdb2"
senddata["tags"]["host"]=name
senddata["fields"]={}
senddata["fields"]["trigger"]=trigger
senddata["fields"]["state"]=state
write_influxdb()
del senddata["fields"]["trigger"]
del senddata["fields"]["state"]
if key['type'] == 2:
if key['state']['batteryCritical'] == "true":
battery=20
else:
battery=100
battery=float(round(battery,2))
senddata["measurement"]="battery"
senddata["fields"]["percent"]=battery
write_influxdb()
else:
if 'batteryCharge' in key['state']:
battery=key['state']['batteryCharge']
battery=float(round(battery,2))
senddata["measurement"]="battery"
senddata["fields"]["percent"]=battery
write_influxdb()
if 'percent' in senddata["fields"]:
del senddata["fields"]["percent"]
for logEntry in logList:
if logEntry['smartlockId'] == smartlockID:
senddata["measurement"]="lock"
senddata["time"]=logEntry['date']
stateID=logEntry['state']
if logEntry['deviceType'] == 2:
if stateID == 1: state="online"
elif stateID == 3: state="ring-to-open"
elif stateID == 5: state="open"
elif stateID == 7: state="opening"
else: state="other"
else:
if stateID == 1: state="locked"
elif stateID == 2: state="unlocking"
elif stateID == 3: state="unlocked"
elif stateID == 4: state="locking"
elif stateID == 5: state="unlatched"
elif stateID == 6: state="lock-n-go"
elif stateID == 7: state="unlatching"
else: state="other"
triggerID=logEntry['trigger']
if triggerID == 0: trigger="proximity"
elif triggerID == 1: trigger="manual"
elif triggerID == 2: trigger="button"
elif triggerID == 3: trigger="automatic"
elif triggerID == 6: trigger="continious"
else: trigger="other"
print ( name.rjust(10,' ')+" - TR: "+str(triggerID)+"-"+trigger.ljust(12,' ')+"ST: "+str(stateID)+"-"+state.ljust(12,' ')+" TM: "+logEntry['date'])
who=logEntry['name']
if not who:
who="other"
senddata["tags"]["who"]=who
senddata["fields"]["trigger"]=trigger
senddata["fields"]["state"]=state
# senddata["tags"]["triggerID"]=triggerID
# senddata["tags"]["stateID"]=stateID
write_influxdb()