{"id":18521449,"url":"https://github.com/thingsboard/thingsboard-micropython-client-sdk","last_synced_at":"2025-04-09T09:33:11.286Z","repository":{"id":146229437,"uuid":"605983769","full_name":"thingsboard/thingsboard-micropython-client-sdk","owner":"thingsboard","description":null,"archived":false,"fork":false,"pushed_at":"2025-01-09T10:49:51.000Z","size":26,"stargazers_count":14,"open_issues_count":4,"forks_count":6,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-03-24T04:43:23.287Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thingsboard.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-24T10:32:23.000Z","updated_at":"2025-02-10T13:28:46.000Z","dependencies_parsed_at":null,"dependency_job_id":"62af384c-c58b-4f69-ad0c-04370b299594","html_url":"https://github.com/thingsboard/thingsboard-micropython-client-sdk","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thingsboard%2Fthingsboard-micropython-client-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thingsboard%2Fthingsboard-micropython-client-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thingsboard%2Fthingsboard-micropython-client-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thingsboard%2Fthingsboard-micropython-client-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thingsboard","download_url":"https://codeload.github.com/thingsboard/thingsboard-micropython-client-sdk/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248012825,"owners_count":21033248,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-06T17:25:56.019Z","updated_at":"2025-04-09T09:33:11.281Z","avatar_url":"https://github.com/thingsboard.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ThingsBoard MQTT client MicroPython SDK\n[![Join the chat at https://gitter.im/thingsboard/chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/thingsboard/chat?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n\n\u003ca href=\"https://thingsboard.io\"\u003e\u003cimg src=\"./logo.png?raw=true\" width=\"100\" height=\"100\"\u003e\u003c/a\u003e\n\n**💡 Make the notion that it is the early alpha of MQTT client MicroPython SDK special for controllers. So we appreciate any \nhelp in improving this project and getting it growing.**\n\nThingsBoard is an open-source IoT platform for data collection, processing, visualization, and device management.\nThis project is a MicroPython library that provides convenient client SDK for Device API using MicroPython.\n\nSDK supports:\n- Provided all supported feature of umqtt library\n- Unencrypted and encrypted (TLS v1.2) connection\n- QoS 0 and 1 (MQTT only)\n- Automatic reconnect\n- [Device MQTT](https://thingsboard.io/docs/reference/mqtt-api/) API provided by ThingsBoard\n- Firmware updates\n  - Device Claiming are not supported yet \n\nThe [Device MQTT](https://thingsboard.io/docs/reference/mqtt-api/) API are based on uMQTT library.\n\n**For now library support only local install (not from package manager relates to MicroPython)**\n\n## Getting Started\n\nClient initialization and telemetry publishing\n### MQTT\n```python\nfrom tb_device_mqtt import TBDeviceMqttClient\ntelemetry = {\"temperature\": 41.9, \"enabled\": False, \"currentFirmwareVersion\": \"v1.2.2\"}\nclient = TBDeviceMqttClient(\"127.0.0.1\", \"A1_TEST_TOKEN\")\n# Connect to ThingsBoard\nclient.connect()\n# Sending telemetry without checking the delivery status\nclient.send_telemetry(telemetry) \n# Sending telemetry and checking the delivery status (QoS = 1 by default)\nresult = client.send_telemetry(telemetry)\n# Disconnect from ThingsBoard\nclient.disconnect()\n```\n\n## Using Device APIs\n\n**TBDeviceMqttClient** provides access to Device MQTT APIs of ThingsBoard platform. It allows to publish telemetry and attribute updates, subscribe to attribute changes, send and receive RPC commands, etc. Use **TBHTTPClient** for the Device HTTP API.\n#### Subscription to attributes\n##### MQTT\n```python\nimport time\nfrom tb_device_mqtt import TBDeviceMqttClient\n\ndef on_attributes_change(client, result, exception):\n    if exception is not None:\n        print(\"Exception: \" + str(exception))\n    else:\n        print(result)\n\nclient = TBDeviceMqttClient(\"127.0.0.1\", \"A1_TEST_TOKEN\")\nclient.connect()\nclient.subscribe_to_attribute(\"uploadFrequency\", on_attributes_change)\nclient.subscribe_to_all_attributes(on_attributes_change)\nwhile True:\n    client.wait_for_msg()\n    time.sleep(1)\n```\n\n#### Telemetry pack sending\n##### MQTT\n```python\nimport logging\nfrom tb_device_mqtt import TBDeviceMqttClient\nimport time\ntelemetry_with_ts = {\"ts\": int(round(time.time() * 1000)), \"values\": {\"temperature\": 42.1, \"humidity\": 70}}\nclient = TBDeviceMqttClient(\"127.0.0.1\", \"A1_TEST_TOKEN\")\nclient.connect()\nresults = []\nresult = True\nfor i in range(0, 100):\n    results.append(client.send_telemetry(telemetry_with_ts))\n\nprint(\"Result \" + str(result))\nclient.disconnect()\n```\n\n#### Request attributes from server\n##### MQTT\n```python\nimport logging\nimport time\nfrom tb_device_mqtt import TBDeviceMqttClient\n\ndef on_attributes_change(client,result, exception:\n    if exception is not None:\n        print(\"Exception: \" + str(exception))\n    else:\n        print(result)\n\nclient = TBDeviceMqttClient(\"127.0.0.1\", \"A1_TEST_TOKEN\")\nclient.connect()\nclient.request_attributes([\"configuration\",\"targetFirmwareVersion\"], callback=on_attributes_change)\nwhile True:\n    time.sleep(1)\n```\n\n#### Respond to server RPC call\n##### MQTT\n```python\nimport psutil\nimport time\nimport logging\nfrom tb_device_mqtt import TBDeviceMqttClient\n\n# dependently of request method we send different data back\ndef on_server_side_rpc_request(client, request_id, request_body):\n    print(request_id, request_body)\n    if request_body[\"method\"] == \"getCPULoad\":\n        client.send_rpc_reply(request_id, {\"CPU percent\": psutil.cpu_percent()})\n    elif request_body[\"method\"] == \"getMemoryUsage\":\n        client.send_rpc_reply(request_id, {\"Memory\": psutil.virtual_memory().percent})\n\nclient = TBDeviceMqttClient(\"127.0.0.1\", \"A1_TEST_TOKEN\")\nclient.set_server_side_rpc_request_handler(on_server_side_rpc_request)\nclient.connect()\nwhile True:\n    time.sleep(1)\n```\n## Device provisioning\n**ProvisionManager** - class created to have ability to provision device to ThingsBoard, using device provisioning feature [Provisioning devices](https://thingsboard.io/docs/paas/user-guide/device-provisioning/)   \nFirst, you need to set up and configure the `ProvisionManager`, which allows you to provision a device on the ThingsBoard server via MQTT. Below are the steps for using this class.\n\n```python\nfrom tb_device_mqtt import TBDeviceMqttClient, ProvisionManager\n\nTHINGSBOARD_HOST = \"YOUR_THINGSBOARD_HOST\"\nTHINGSBOARD_PORT = 1883\nPROVISION_DEVICE_KEY = \"YOUR_PROVISION_DEVICE_KEY\"\nPROVISION_DEVICE_SECRET = \"YOUR_PROVISION_DEVICE_SECRET\"\nDEVICE_NAME = \"MyDevice\"\n\nprovision_manager = ProvisionManager(THINGSBOARD_HOST, THINGSBOARD_PORT)\n\ncredentials = provision_manager.provision_device(\n    provision_device_key=PROVISION_DEVICE_KEY,\n    provision_device_secret=PROVISION_DEVICE_SECRET,\n    device_name=DEVICE_NAME\n\n)\nif not credentials:\n    print(\"Provisioning failed!\")\n    raise SystemExit(\"Exiting: Provisioning unsuccessful.\")\n\nprint(f\"Provisioning successful! Credentials: {credentials}\")\n\naccess_token = credentials.get(\"credentialsValue\")\nif not access_token:\n    print(\"No access token found in credentials!\")\n    raise SystemExit(\"Exiting: Access token missing.\")\n\nclient_id = f\"{DEVICE_NAME}_client\"\nmqtt_client = TBDeviceMqttClient(host=THINGSBOARD_HOST, port=THINGSBOARD_PORT, access_token=access_token)\n\ntry:\n    mqtt_client.connect()\n    print(f\"Connected to ThingsBoard server at {THINGSBOARD_HOST}:{THINGSBOARD_PORT}\")\n\n    TELEMETRY_DATA = {\n        \"temperature\": 22.5,\n        \"humidity\": 60\n    }\n\n    mqtt_client.send_telemetry(TELEMETRY_DATA)\n    print(f\"Telemetry sent: {TELEMETRY_DATA}\")\n\nexcept Exception as e:\n    print(f\"An error occurred: {e}\")\nfinally:\n    if mqtt_client.connect():\n        mqtt_client.disconnect()\n        print(\"Disconnected from ThingsBoard server.\")\n    else:\n        print(\"Client was not connected; no need to disconnect.\")\n```\n\n# Claim device\n[**Claim device**](https://thingsboard.io/docs/pe/user-guide/claiming-devices/) is a function designed to handle the device claiming feature in ThingsBoard. It enables sending device claiming requests to the ThingsBoard MQTT broker, allowing dynamic assignment of devices to users or customers.\n\n```python\nfrom tb_device_mqtt import TBDeviceMqttClient\n\nTHINGSBOARD_HOST = \"YOUR_THINGSBOARD_HOST\"\nTHINGSBOARD_PORT = 1883\nDEVICE_TOKEN = \"YOUR_DEVICE_TOKEN\"\nDURATION_MS = 30000\nSECRET_KEY = \"YOUR_SECRET_KEY\"\n\nclient = TBDeviceMqttClient(THINGSBOARD_HOST, THINGSBOARD_PORT, DEVICE_TOKEN)\n\ntry:\n    client.connect()\n\n    client.claim_device(SECRET_KEY, DURATION_MS)\n    print(f\"Claim request sent with secretKey: {SECRET_KEY} and durationMs: {DURATION_MS}\")\nexcept Exception as e:\n    print(f\"An error occurred: {e}\")\nfinally:\n    if client.connected:\n        client.disconnect()\n        print(\"Disconnected from ThingsBoard.\")\n```\n## Other Examples\n\nThere are more examples for both [device](https://github.com/thingsboard/thingsboard-python-client-sdk/tree/master/examples/device) and [gateway](https://github.com/thingsboard/thingsboard-python-client-sdk/tree/master/examples/gateway) in corresponding [folders](https://github.com/thingsboard/thingsboard-python-client-sdk/tree/master/examples).\n\n## Support\n\n - [Community chat](https://gitter.im/thingsboard/chat)\n - [Q\u0026A forum](https://groups.google.com/forum/#!forum/thingsboard)\n - [Stackoverflow](http://stackoverflow.com/questions/tagged/thingsboard)\n\n## Licenses\n\nThis project is released under [Apache 2.0 License](./LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthingsboard%2Fthingsboard-micropython-client-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthingsboard%2Fthingsboard-micropython-client-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthingsboard%2Fthingsboard-micropython-client-sdk/lists"}