-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathtb_device_http.py
465 lines (393 loc) · 18.2 KB
/
tb_device_http.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
# Copyright 2024. ThingsBoard
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ThingsBoard HTTP API device module."""
import threading
import logging
import queue
import time
import typing
from datetime import datetime, timezone
from sdk_utils import verify_checksum
import requests
from math import ceil
FW_CHECKSUM_ATTR = "fw_checksum"
FW_CHECKSUM_ALG_ATTR = "fw_checksum_algorithm"
FW_SIZE_ATTR = "fw_size"
FW_TITLE_ATTR = "fw_title"
FW_VERSION_ATTR = "fw_version"
FW_STATE_ATTR = "fw_state"
REQUIRED_SHARED_KEYS = [FW_CHECKSUM_ATTR, FW_CHECKSUM_ALG_ATTR, FW_SIZE_ATTR, FW_TITLE_ATTR, FW_VERSION_ATTR]
class TBHTTPAPIException(Exception):
"""ThingsBoard HTTP Device API Exception class."""
class TBProvisionFailure(TBHTTPAPIException):
"""Exception raised if device provisioning failed."""
class TBHTTPDevice:
"""ThingsBoard HTTP Device API class.
:param host: The ThingsBoard hostname.
:param token: The device token.
:param name: A name for this device. The name is only set locally.
"""
def __init__(self, host: str, token: str, name: str = None, chunk_size: int = 0):
self.__session = requests.Session()
self.__session.headers.update({'Content-Type': 'application/json'})
self.__config = {
'host': host, 'token': token, 'name': name, 'timeout': 30
}
self.__worker = {
'publish': {
'queue': queue.Queue(),
'thread': threading.Thread(target=self.__publish_worker, daemon=True),
'stop_event': threading.Event()
},
'attributes': {
'thread': threading.Thread(target=self.__subscription_worker,
daemon=True,
kwargs={'endpoint': 'attributes'}),
'stop_event': threading.Event(),
},
'rpc': {
'thread': threading.Thread(target=self.__subscription_worker,
daemon=True,
kwargs={'endpoint': 'rpc'}),
'stop_event': threading.Event(),
}
}
self.current_firmware_info = {
"current_fw_title": None,
"current_fw_version": None
}
self.chunk_size = chunk_size
def __repr__(self):
return f'<ThingsBoard ({self.host}) HTTP device {self.name}>'
@property
def host(self) -> str:
"""Get the ThingsBoard hostname."""
return self.__config['host']
@property
def name(self) -> str:
"""Get the device name."""
return self.__config['name']
@property
def timeout(self) -> int:
"""Get the connection timeout."""
return self.__config['timeout']
@property
def api_base_url(self) -> str:
"""Get the ThingsBoard API base URL."""
return f'{self.host}/api/v1/{self.token}'
@property
def token(self) -> str:
"""Get the device token."""
return self.__config['token']
@property
def logger(self) -> logging.Logger:
"""Get the logger instance."""
return logging.getLogger('TBHTTPDevice')
@property
def log_level(self) -> str:
"""Get the log level."""
levels = {0: 'NOTSET', 10: 'DEBUG', 20: 'INFO', 30: 'WARNING', 40: 'ERROR', 50: 'CRITICAL'}
return levels.get(self.logger.level)
@log_level.setter
def log_level(self, value: typing.Union[int, str]):
self.logger.setLevel(value)
self.logger.critical('Log level set to %s', self.log_level)
def __get_firmware_info(self):
response = self.__session.get(
f"{self.__config['host']}/api/v1/{self.__config['token']}/attributes",
params={"sharedKeys": REQUIRED_SHARED_KEYS}).json()
return response.get("shared", {})
def __get_firmware(self, fw_info):
chunk_count = ceil(fw_info.get(FW_SIZE_ATTR, 0) / self.chunk_size) if self.chunk_size > 0 else 0
firmware_data = b''
for chunk_number in range(chunk_count + 1):
params = {"title": fw_info.get(FW_TITLE_ATTR),
"version": fw_info.get(FW_VERSION_ATTR),
"size": self.chunk_size if self.chunk_size < fw_info.get(FW_SIZE_ATTR,
0) else fw_info.get(
FW_SIZE_ATTR, 0),
"chunk": chunk_number
}
self.logger.debug(params)
self.logger.debug(
'Getting chunk with number: %s. Chunk size is : %r byte(s).' % (chunk_number + 1, self.chunk_size))
response = self.__session.get(
f"{self.__config['host']}/api/v1/{self.__config['token']}/firmware",
params=params)
if response.status_code != 200:
self.logger.error('Received error:')
response.raise_for_status()
return
firmware_data = firmware_data + response.content
return firmware_data
def __on_firmware_received(self, firmware_info, firmware_data):
with open(firmware_info.get(FW_TITLE_ATTR), "wb") as firmware_file:
firmware_file.write(firmware_data)
self.logger.info('Firmware is updated!\n Current firmware version is: %s' % firmware_info.get(FW_VERSION_ATTR))
def get_firmware_update(self):
self.send_telemetry(self.current_firmware_info)
self.logger.info('Getting firmware info from %s' % self.__config['host'])
firmware_info = self.__get_firmware_info()
if (firmware_info.get(FW_VERSION_ATTR) is not None and firmware_info.get(
FW_VERSION_ATTR) != self.current_firmware_info.get("current_" + FW_VERSION_ATTR)) \
or (firmware_info.get(FW_TITLE_ATTR) is not None and firmware_info.get(
FW_TITLE_ATTR) != self.current_firmware_info.get("current_" + FW_TITLE_ATTR)):
self.logger.info('New firmware available!')
self.current_firmware_info[FW_STATE_ATTR] = "DOWNLOADING"
time.sleep(1)
self.send_telemetry(self.current_firmware_info)
firmware_data = self.__get_firmware(firmware_info)
self.current_firmware_info[FW_STATE_ATTR] = "DOWNLOADED"
time.sleep(1)
self.send_telemetry(self.current_firmware_info)
verification_result = verify_checksum(firmware_data, firmware_info.get(FW_CHECKSUM_ALG_ATTR),
firmware_info.get(FW_CHECKSUM_ATTR))
if verification_result:
self.logger.debug('Checksum verified!')
self.current_firmware_info[FW_STATE_ATTR] = "VERIFIED"
time.sleep(1)
self.send_telemetry(self.current_firmware_info)
else:
self.logger.debug('Checksum verification failed!')
self.current_firmware_info[FW_STATE_ATTR] = "FAILED"
time.sleep(1)
self.send_telemetry(self.current_firmware_info)
firmware_data = self.__get_firmware(firmware_info)
return
self.current_firmware_info[FW_STATE_ATTR] = "UPDATING"
time.sleep(1)
self.send_telemetry(self.current_firmware_info)
self.__on_firmware_received(firmware_info, firmware_data)
current_firmware_info = {
"current_" + FW_TITLE_ATTR: firmware_info.get(FW_TITLE_ATTR),
"current_" + FW_VERSION_ATTR: firmware_info.get(FW_VERSION_ATTR),
FW_STATE_ATTR: "UPDATED"
}
time.sleep(1)
self.send_telemetry(current_firmware_info)
def start_publish_worker(self):
"""Start the publish worker thread."""
self.__worker['publish']['stop_event'].clear()
self.__worker['publish']['thread'].start()
def stop_publish_worker(self):
"""Stop the publish worker thread."""
self.__worker['publish']['stop_event'].set()
def __publish_worker(self):
"""Publish telemetry data from the queue."""
logger = self.logger.getChild('worker.publish')
logger.info('Start publisher thread')
logger.debug('Perform connection test before entering worker loop')
if not self.test_connection():
logger.error('Connection test failed, exit publisher thread')
return
logger.debug('Connection test successful')
while True:
if not self.__worker['publish']['queue'].empty():
try:
task = self.__worker['publish']['queue'].get(timeout=1)
except queue.Empty:
if self.__worker['publish']['stop_event'].is_set():
break
continue
endpoint = task.pop('endpoint')
try:
self._publish_data(task, endpoint)
except Exception as error:
# ToDo: More precise exception catching
logger.error(error)
task.update({'endpoint': endpoint})
self.__worker['publish']['queue'].put(task)
time.sleep(1)
else:
logger.debug('Published %s to %s', task, endpoint)
self.__worker['publish']['queue'].task_done()
time.sleep(.2)
logger.info('Stop publisher thread.')
def test_connection(self) -> bool:
"""Test connection to the API.
:return: True if no errors occurred, False otherwise.
"""
self.logger.debug('Start connection test')
success = False
try:
self._publish_data(data={}, endpoint='telemetry')
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as error:
self.logger.debug(error)
except requests.exceptions.HTTPError as error:
self.logger.debug(error)
status_code = error.response.status_code
if status_code == 401:
self.logger.error('Error 401: Unauthorized. Check if token is correct.')
else:
self.logger.error('Error %s', status_code)
else:
self.logger.debug('Connection test successful')
success = True
finally:
self.logger.debug('End connection test')
return success
def connect(self) -> bool:
"""Publish an empty telemetry data to ThingsBoard to test the connection.
:return: True if connected, false otherwise.
"""
if self.test_connection():
self.logger.info('Connected to ThingsBoard')
self.start_publish_worker()
return True
return False
def _publish_data(self, data: dict, endpoint: str, timeout: int = None) -> dict:
"""Send POST data to ThingsBoard.
:param data: The data dictionary to send.
:param endpoint: The receiving API endpoint.
:param timeout: Override the instance timeout for this request.
"""
response = self.__session.post(
url=f'{self.api_base_url}/{endpoint}',
json=data,
timeout=timeout or self.timeout)
response.raise_for_status()
return response.json() if response.content else {}
def _get_data(self, params: dict, endpoint: str, timeout: int = None) -> dict:
"""Retrieve data with GET from ThingsBoard.
:param params: A dictionary with the parameters for the request.
:param endpoint: The receiving API endpoint.
:param timeout: Override the instance timeout for this request.
:return: A dictionary with the response from the ThingsBoard instance.
"""
response = self.__session.get(
url=f'{self.api_base_url}/{endpoint}',
params=params,
timeout=timeout or self.timeout)
response.raise_for_status()
return response.json()
def send_telemetry(self, telemetry: dict, timestamp: datetime = None, queued: bool = True):
"""Publish telemetry to ThingsBoard.
:param telemetry: A dictionary with the telemetry data to send.
:param timestamp: Timestamp to set for the values. If not set the ThingsBoard server uses
the time of reception as timestamp.
:param queued: Add the telemetry to the queue. If False, the data is send immediately.
"""
timestamp = datetime.now() if timestamp is None else timestamp
payload = {
'ts': int(timestamp.replace(tzinfo=timezone.utc).timestamp() * 1000),
'values': telemetry,
}
if queued:
payload.update({'endpoint': 'telemetry'})
self.__worker['publish']['queue'].put(payload)
else:
self._publish_data(payload, 'telemetry')
def send_attributes(self, attributes: dict):
"""Send attributes to ThingsBoard.
:param attributes: Attributes to send.
"""
self._publish_data(attributes, 'attributes')
def send_rpc(self, name: str, params: dict = None, rpc_id: int = None) -> dict:
"""Send RPC to ThingsBoard and return response.
:param name: Name of the RPC method.
:param params: Parameter for the RPC.
:param rpc_id: Specify an Id for this RPC.
:return: A dictionary with the response.
"""
endpoint = f'rpc/{rpc_id}' if rpc_id else 'rpc'
return self._publish_data({'method': name, 'params': params or {}}, endpoint)
def request_attributes(self, client_keys: list = None, shared_keys: list = None) -> dict:
"""Request attributes from ThingsBoard.
:param client_keys: A list of keys for client attributes.
:param shared_keys: A list of keys for shared attributes.
:return: A dictionary with the request attributes.
"""
params = {'client_keys': client_keys, 'shared_keys': shared_keys}
return self._get_data(params=params, endpoint='attributes')
def __subscription_worker(self, endpoint: str, timeout: int = None):
"""Worker thread for subscription to HTTP API endpoints.
:param endpoint: The endpoint name.
:param timeout: Timeout value in seconds.
"""
logger = self.logger.getChild(f'worker.subscription.{endpoint}')
stop_event = self.__worker[endpoint]['stop_event']
logger.info('Start subscription to %s updates', endpoint)
if not self.__worker[endpoint].get('callback'):
logger.warning('No callback set for %s subscription', endpoint)
stop_event.set()
callback = self.__worker[endpoint].get('callback', lambda data: None)
params = {
'timeout': (timeout or self.timeout) * 1000
}
url = {
'attributes': f'{self.api_base_url}/attributes/updates',
'rpc': f'{self.api_base_url}/rpc'
}
logger.debug('Timeout set to %ss', params['timeout'] / 1000)
while not stop_event.is_set():
response = self.__session.get(url=url[endpoint],
params=params,
timeout=params['timeout'])
if stop_event.is_set():
break
if response.status_code == 408: # Request timeout
continue
if response.status_code == 504: # Gateway Timeout
continue # Reconnect
response.raise_for_status()
callback(response.json())
time.sleep(.1)
stop_event.clear()
logger.info('Stop subscription to %s updates', endpoint)
def subscribe(self, endpoint: str, callback: typing.Callable[[dict], None] = None):
"""Subscribe to updates from a given endpoint.
:param endpoint: The endpoint to subscribe.
:param callback: Callback to execute on an update. Takes a dict as only argument.
"""
if endpoint not in ['attributes', 'rpc']:
raise ValueError
if callback:
if not callable(callback):
raise TypeError
self.__worker[endpoint]['callback'] = callback
self.__worker[endpoint]['stop_event'].clear()
self.__worker[endpoint]['thread'].start()
def unsubscribe(self, endpoint: str):
"""Unsubscribe from a given endpoint.
:param endpoint: The endpoint to unsubscribe.
"""
if endpoint not in ['attributes', 'rpc']:
raise ValueError
self.logger.debug('Set stop event for %s subscription', endpoint)
self.__worker[endpoint]['stop_event'].set()
@classmethod
def provision(cls, host: str, device_name: str, device_key: str, device_secret: str):
"""Initiate device provisioning and return a device instance.
:param host: The root URL to the ThingsBoard instance.
:param device_name: Name of the device to provision.
:param device_key: Provisioning device key from ThingsBoard.
:param device_secret: Provisioning secret from ThingsBoard.
:return: Instance of :class:`TBHTTPClient`
"""
data = {
'deviceName': device_name,
'provisionDeviceKey': device_key,
'provisionDeviceSecret': device_secret
}
response = requests.post(f'{host}/api/v1/provision', json=data)
response.raise_for_status()
device = response.json()
if device['status'] == 'SUCCESS' and device['credentialsType'] == 'ACCESS_TOKEN':
return cls(host=host, token=device['credentialsValue'], name=device_name)
raise TBProvisionFailure(device)
class TBHTTPClient(TBHTTPDevice):
"""Legacy class name."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.logger.critical('TBHTTPClient class is deprecated, please use TBHTTPDevice')