forked from guiguitt/gateway_ttn-thingsboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.py
124 lines (102 loc) · 4.12 KB
/
library.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
import json
import requests
from datetime import datetime
import sys
import os
def udpateFileNum(i):
global fileNum
fileNum = i
def getIniParameters(sFile):
"""
Read parameters in ini file
@param sFile Path to the ini file to read
@return Dictionary with sections and parameters contained in the INI file
"""
import os,sys
sCurrentPath = os.path.abspath(os.path.dirname(sys.argv[0]))
os.chdir(sCurrentPath)
sIniFile = sFile
import configparser as cp
cfg = cp.ConfigParser()
with open(sIniFile) as f:
cfg.read_file(f)
# https://stackoverflow.com/a/28990982
return {s:dict(cfg.items(s)) for s in cfg.sections()}
def printlog(s, sep = ": "):
"""
Print message with date and time and flush the console
@see https://www.turnkeylinux.org/blog/unix-buffering
"""
sDateTime = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
print(sDateTime + sep + s)
sys.stdout.flush()
def PostThingsboard(JsDATA, DeviceId):
dPrm = getIniParameters("commissioning.ini")
headers_AccessT = {
'content-type': "application/json",
'accept': "application/json"
}
printlog("1/6 - Send request to Access Token")
#print(dPrm['THINGS']['url']+'/api/auth/login/public')
try:
ResponseAccessToken = requests.post(dPrm['THINGS']['url']+'/api/auth/login', headers=headers_AccessT, data='{"username":"' + dPrm['THINGS']['username'] + '", "password":"' + dPrm['THINGS']['password'] + '"}')
except requests.exceptions.RequestException as e:
printlog("Error " + e)
return
if 'status' in ResponseAccessToken.text:
printlog(ResponseAccessToken.text)
return
else:
printlog("2/6 - Request response ok")
try:
AccessToken=eval(ResponseAccessToken.text)['token']
except:
printlog("Error retrieving token in " + ResponseAccessToken.text)
return
headers_DeviceT = {
'Accept': 'application/json',
'X-Authorization': "Bearer " +AccessToken
}
printlog("3/6 - Send request to Device token")
try:
ResponseDeviceToken = requests.get(dPrm['THINGS']['url']+'/api/device/'+DeviceId+'/credentials', headers=headers_DeviceT)
except requests.exceptions.RequestException as e:
printlog("Error " + e)
return
if 'status' in ResponseDeviceToken.text:
printlog(ResponseAccessToken.text)
return
else:
printlog("4/6 - Request response ok")
null = None
try:
DeviceToken=str(eval(ResponseDeviceToken.text)['credentialsId'])
except:
printlog("Error retrieving credentials Id")
printlog("5/6 - Send request telemetry")
try:
r = requests.post(dPrm['THINGS']['url']+'/api/v1/'+DeviceToken+'/telemetry', json=JsDATA)
except requests.exceptions.RequestException as e:
printlog("Error " + e)
printlog("6/6 - Request code response "+ ("ok" if r.status_code == 200 else str(r.text)))
def on_log( client, userdata, level, buf ):
printlog( "log: "+ buf)
def on_connect( client, userdata, flags, rc ):
printlog( "Connexion MQTT: code retour= "+ str(rc) )
printlog( "Connexion MQTT: Statut= " +("OK" if rc==0 else "echec") + "\n" )
#print("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n")
def on_message(client, userdata, message):
"""
application that processes data when a message is
received and starts the post procedure on ThingsBoard
"""
msg = json.loads(message.payload.decode("utf-8" ))
printlog( "Receipt message MQTT... (application : " + msg["end_device_ids"]["application_ids"]["application_id"] + ", pid : "+ str(os.getpid()) + ")" )
printlog( "Topic : "+ str(message.topic) )
#printlog("dev_if : " +y["dev_id"])
#printlog("Latitude: " +y["payload_fields"]["latitude"])
#printlog("Longitude: " +y["payload_fields"]["longitude"])
#printlog("detection: %s" +y["payload_fields"]["detection"])
#printlog("data: "+str(msg["payload_fields"]))
printlog("data: "+str(msg["uplink_message"]["decoded_payload"]))
PostThingsboard(msg["uplink_message"]["decoded_payload"], msg["end_device_ids"]["device_id"])