Skip to content

Commit dcc7739

Browse files
authored
Refactored MicroPython SDK (#12)
* Refactored SDK * Added submodule * Added examples * Fixed package.json
1 parent 327889b commit dcc7739

8 files changed

Lines changed: 184 additions & 414 deletions

File tree

.gitmodules

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[submodule "sdk_core"]
2+
path = sdk_core
3+
url = https://github.com/thingsboard/thingsboard-micro-sdk-core

examples/provision_device.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
This sketch demonstrates connecting and provisioning a device using ThingsBoard SDK
3+
"""
4+
5+
import network
6+
7+
from sdk_core.device_mqtt import TBDeviceMqttClientBase
8+
from thingsboard_sdk.tb_device_mqtt import TBDeviceMqttClient
9+
10+
WIFI_SSID = "YOUR_SSID"
11+
WIFI_PASSWORD = "YOUR_PASSWORD"
12+
13+
# Thingsboard we want to establish a connection to
14+
THINGSBOARD_HOST = "thingsboard.cloud"
15+
# MQTT port used to communicate with the server, 1883 is the default unencrypted MQTT port,
16+
# whereas 8883 would be the default encrypted SSL MQTT port
17+
THINGSBOARD_PORT = 1883
18+
# See
19+
# to understand how to obtain provision device key and device secret
20+
PROVISION_DEVICE_KEY = "YOUR_PROVISION_DEVICE_KEY"
21+
PROVISION_DEVICE_SECRET = "YOUR_PROVISION_DEVICE_SECRET"
22+
# Provisioned device name
23+
DEVICE_NAME = "MyDevice"
24+
25+
# Enabling WLAN interface
26+
wlan = network.WLAN(network.STA_IF)
27+
wlan.active(True)
28+
29+
# Establishing connection to the Wi-Fi
30+
if not wlan.isconnected():
31+
print('Connecting to network...')
32+
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
33+
while not wlan.isconnected():
34+
pass
35+
36+
print('Connected! Network config:', wlan.ifconfig())
37+
38+
# Form provision request using provision credentials
39+
provision_request = TBDeviceMqttClientBase.get_provision_request(provision_device_key=PROVISION_DEVICE_KEY,
40+
provision_device_secret=PROVISION_DEVICE_SECRET,
41+
device_name=DEVICE_NAME)
42+
# Send provision device request
43+
provisioned_credentials = TBDeviceMqttClient.provision(THINGSBOARD_HOST, THINGSBOARD_PORT, provision_request)
44+
print(provisioned_credentials)
45+
46+
if not provisioned_credentials:
47+
print("Provisioning failed!")
48+
raise SystemExit("Exiting: Provisioning unsuccessful.")
49+
50+
# Get provisioned credentials
51+
access_token = provisioned_credentials.get("credentialsValue")
52+
if not access_token:
53+
print("No access token found in credentials!")
54+
raise SystemExit("Exiting: Access token missing.")
55+
56+
# Telemetry message that we will send
57+
telemetry = {"temperature": 41.9, "enabled": False, "currentFirmwareVersion": "v1.2.2"}
58+
# Initialising client with provisioned credentials to communicate with ThingsBoard
59+
client = TBDeviceMqttClient(host=THINGSBOARD_HOST, port=THINGSBOARD_PORT, access_token=access_token)
60+
# Connect to ThingsBoard
61+
client.connect()
62+
# Sending telemetry without checking the delivery status
63+
client.send_telemetry(telemetry)
64+
# Disconnect from ThingsBoard
65+
client.disconnect()

examples/send_telemetry.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
This sketch demonstrates connecting and sending telemetry using ThingsBoard SDK
3+
"""
4+
5+
import network
6+
from thingsboard_sdk.tb_device_mqtt import TBDeviceMqttClient
7+
8+
9+
WIFI_SSID = "YOUR_SSID"
10+
WIFI_PASSWORD = "YOUR_PASSWORD"
11+
12+
# Thingsboard we want to establish a connection to
13+
THINGSBOARD_HOST = "thingsboard.cloud"
14+
# MQTT port used to communicate with the server, 1883 is the default unencrypted MQTT port,
15+
# whereas 8883 would be the default encrypted SSL MQTT port
16+
THINGSBOARD_PORT = 1883
17+
# See https://thingsboard.io/docs/getting-started-guides/helloworld/
18+
# to understand how to obtain an access token
19+
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"
20+
21+
# Enabling WLAN interface
22+
wlan = network.WLAN(network.STA_IF)
23+
wlan.active(True)
24+
25+
# Establishing connection to the Wi-Fi
26+
if not wlan.isconnected():
27+
print('Connecting to network...')
28+
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
29+
while not wlan.isconnected():
30+
pass
31+
32+
print('Connected! Network config:', wlan.ifconfig())
33+
34+
# Telemetry message that we will send
35+
telemetry = {"temperature": 41.9, "enabled": False, "currentFirmwareVersion": "v1.2.2"}
36+
# Initialising client to communicate with ThingsBoard
37+
client = TBDeviceMqttClient(host=THINGSBOARD_HOST, port=THINGSBOARD_PORT, access_token=ACCESS_TOKEN)
38+
# Connect to ThingsBoard
39+
client.connect()
40+
# Sending telemetry without checking the delivery status
41+
client.send_telemetry(telemetry)
42+
# Sending telemetry and checking the delivery status (QoS = 1 by default)
43+
result = client.send_telemetry(telemetry)
44+
# Disconnect from ThingsBoard
45+
client.disconnect()

package.json

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,41 @@
11
{
22
"urls": [
3-
["thingsboard_sdk/__init__.py", "thingsboard_sdk/__init__.py"],
4-
["thingsboard_sdk/manifest.py", "thingsboard_sdk/manifest.py"],
5-
["thingsboard_sdk/sdk_utils.py", "thingsboard_sdk/sdk_utils.py"],
6-
["thingsboard_sdk/umqtt.py", "thingsboard_sdk/umqtt.py"],
7-
["thingsboard_sdk/tb_device_mqtt.py", "thingsboard_sdk/tb_device_mqtt.py"],
8-
["thingsboard_sdk/provision_client.py", "thingsboard_sdk/provision_client.py"]
3+
[
4+
"sdk_core/__init__.py",
5+
"https://raw.githubusercontent.com/thingsboard/thingsboard-micro-sdk-core/main/__init__.py"
6+
],
7+
[
8+
"sdk_core/device_mqtt.py",
9+
"https://raw.githubusercontent.com/thingsboard/thingsboard-micro-sdk-core/main/device_mqtt.py"
10+
],
11+
[
12+
"sdk_core/sdk_utils.py",
13+
"https://raw.githubusercontent.com/thingsboard/thingsboard-micro-sdk-core/main/sdk_utils.py"
14+
],
15+
[
16+
"sdk_core/provision_client.py",
17+
"https://raw.githubusercontent.com/thingsboard/thingsboard-micro-sdk-core/main/provision_client.py"
18+
],
19+
[
20+
"thingsboard_sdk/__init__.py",
21+
"thingsboard_sdk/__init__.py"
22+
],
23+
[
24+
"thingsboard_sdk/manifest.py",
25+
"thingsboard_sdk/manifest.py"
26+
],
27+
[
28+
"thingsboard_sdk/umqtt.py",
29+
"thingsboard_sdk/umqtt.py"
30+
],
31+
[
32+
"thingsboard_sdk/tb_device_mqtt.py",
33+
"thingsboard_sdk/tb_device_mqtt.py"
34+
],
35+
[
36+
"thingsboard_sdk/provision_client.py",
37+
"thingsboard_sdk/provision_client.py"
38+
]
939
],
10-
"version": "0.1"
40+
"version": "0.2"
1141
}

sdk_core

Submodule sdk_core added at f69d040
Lines changed: 11 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,67 +1,24 @@
1-
# Copyright 2026. ThingsBoard
2-
# #
3-
# Licensed under the Apache License, Version 2.0 (the "License");
4-
# you may not use this file except in compliance with the License.
5-
# You may obtain a copy of the License at
6-
# #
7-
# http://www.apache.org/licenses/LICENSE-2.0
8-
# #
9-
# Unless required by applicable law or agreed to in writing, software
10-
# distributed under the License is distributed on an "AS IS" BASIS,
11-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12-
# See the License for the specific language governing permissions and
13-
# limitations under the License.
14-
#
15-
16-
from ujson import dumps, loads
171
from gc import collect
182

3+
from sdk_core.provision_client import ProvisionClientBase
194
from .umqtt import MQTTClient
205

216

22-
class ProvisionClient:
23-
PROVISION_REQUEST_TOPIC = b"/provision/request"
24-
PROVISION_RESPONSE_TOPIC = b"/provision/response"
25-
7+
class ProvisionClient(ProvisionClientBase):
268
def __init__(self, host, port, provision_request):
27-
self._host = host
28-
self._port = port
29-
self._client_id = b"provision"
30-
self._provision_request = provision_request
31-
self._credentials = None
9+
super().__init__(host, port, provision_request)
3210

33-
def _on_message(self, topic, msg):
34-
try:
35-
response = loads(msg)
36-
if response.get("status") == "SUCCESS":
37-
self._credentials = response
38-
else:
39-
print(f"Provisioning failed: {response.get('errorMsg', 'Unknown error')}")
40-
except MemoryError:
41-
print("MemoryError during message processing!")
11+
mqtt_client = MQTTClient(self._client_id, self._host, self._port, keepalive=10)
12+
mqtt_client.set_callback(self.on_message_callback)
13+
self.set_client(mqtt_client)
4214

4315
def provision(self):
44-
mqtt_client = None
4516
try:
46-
collect()
47-
48-
mqtt_client = MQTTClient(self._client_id, self._host, self._port, keepalive=10)
49-
mqtt_client.set_callback(self._on_message)
50-
mqtt_client.connect(clean_session=True)
51-
mqtt_client.subscribe(self.PROVISION_RESPONSE_TOPIC)
52-
collect()
53-
54-
provision_request_str = dumps(self._provision_request, separators=(',', ':'))
55-
mqtt_client.publish(self.PROVISION_REQUEST_TOPIC, provision_request_str)
56-
del provision_request_str
57-
collect()
17+
super().provision()
5818

59-
mqtt_client.wait_msg()
19+
self._client.wait_msg()
6020
finally:
61-
if mqtt_client:
62-
mqtt_client.disconnect()
63-
collect()
21+
if self._client:
22+
self._client.disconnect()
6423

65-
@property
66-
def credentials(self):
67-
return self._credentials
24+
collect()

thingsboard_sdk/sdk_utils.py

Lines changed: 0 additions & 35 deletions
This file was deleted.

0 commit comments

Comments
 (0)