{"id":863,"date":"2023-03-10T12:01:01","date_gmt":"2023-03-10T12:01:01","guid":{"rendered":"https:\/\/samndave.org.uk\/ourdoc\/?p=863"},"modified":"2025-07-10T16:11:33","modified_gmt":"2025-07-10T16:11:33","slug":"thingsboard-python-mqtt-and-gateways","status":"publish","type":"post","link":"https:\/\/samndave.org.uk\/index.php\/2023\/03\/10\/thingsboard-python-mqtt-and-gateways\/","title":{"rendered":"ThingsBoard, Python, MQTT and Gateways"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/en.wikipedia.org\/wiki\/MQTT\">MQTT<\/a> is a lightweight communication platform, ideal for messaging between servers and IoT devices. <a href=\"https:\/\/thingsboard.io\/\">ThingsBoard<\/a> is a powerful IoT platform which supports device provisioning and telemetry logging via MQTT. One very useful feature is the ability to mark a device as a gateway. Rather than having to hold credentials for individual devices, a single device acting as an IoT gateway (or a script pulling data from multiple devices) can log to multiple ThingsBoard devices by only communicating to the MQTT gateway node.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">MQTT logging to a single device<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">There are a number of MQTT libraries available for Python, the paho library from Eclipse is very popular. Although there is also a ThingsBoard specific library, the version I looked at had a bug and was not usable at the time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To post telemetry to a device, the device needs to be created in ThingsBoard, and the access token obtained. The device does not need to be set as public. The client procedure to send a single element of telemetry is:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Define a client object<\/li>\n\n\n\n<li>Set up any call back functions<\/li>\n\n\n\n<li>Set the username \/ password to be the device access token<\/li>\n\n\n\n<li>Connect to the server<\/li>\n\n\n\n<li>Start the client loop<\/li>\n\n\n\n<li>Publish telemetry<\/li>\n\n\n\n<li>Stop the client loop<\/li>\n\n\n\n<li>Disconnect<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The callback functions will execute on the specific events, connect, publish and disconnect. By setting a global variable mqtt_connected, to track connection status, we can deal with disconnects. While this is unlikely in a script which sends a single telemetry set, it is useful for long running applications where the connection may be dropped. The callback functions can be expanded for greater error handling.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The following script sends one set of dummy data to a ThingsBoard device:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/python\n\n# MQTT test, based on API code at https:\/\/thingsboard.io\/docs\/samples\/raspberry\/temperature\/\nimport paho.mqtt.client as mqtt\nimport json\nimport time\n\nTHINGSBOARD_HOST = '&lt;server>'\nACCESS_TOKEN = '&lt;token>'\n\nsensor_data = {'ultimateAnswer':42, 'pi':3.14159}\nTHINGSBOARD_PORT = 1883\nmqtt_connected = False\n\n# Functions to act on connection and check for disconnection\n# See https:\/\/stackoverflow.com\/questions\/36093078\/mqtt-is-there-a-way-to-check-if-the-client-is-still-connected\ndef on_connect(client, userdata, flags, rc):\n    global mqtt_connected\n    if(rc==0):\n        mqtt_connected = True\n        print(\"MQTT server connected successfully\")\n    else:\n        print(\"MQTT server failed to connect rc={}\".format(rc))\n\ndef on_disconnect(client, userdata, rc):\n    global mqtt_connected\n    mqtt_connected = False\n    print(\"MQTT server disconnected, rc={}\".format(rc))\n\ndef on_publish(client, userdata, mid):\n    print(\"MQTT on_publish returned {}\".format(mid))\n\ndef mqttConnect():\n    global client,mqtt_connected\n    print(\"Connecting to ThingsBoard server\")\n    client.on_connect = on_connect\n    client.on_disconnect = on_disconnect\n    client.on_publish = on_publish\n    client.username_pw_set(ACCESS_TOKEN)\n    try:\n        client.connect(THINGSBOARD_HOST, THINGSBOARD_PORT, 60)\n    except:\n        print(\"Error: exception when connecting to MQTT server\")\n    client.loop_start()\n\nclient = mqtt.Client()\nmqttConnect()\n\nprint(\"Publishing data\")\nclient.publish('v1\/devices\/me\/telemetry', json.dumps(sensor_data), 1)\nprint(\"Published\")\n\nclient.loop_stop()\nclient.disconnect()\nprint(\"Test complete\")<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Logging to multiple devices via a gateway<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If we build an object to act as a gateway (e.g. a single device in a LoRaWAN or BLE network), this can dynamically provision ThingsBoard devices and then send telemetry to them. See the <a href=\"https:\/\/thingsboard.io\/docs\/reference\/gateway-mqtt-api\/\" data-type=\"URL\" data-id=\"https:\/\/thingsboard.io\/docs\/reference\/gateway-mqtt-api\/\">ThingsBoard MQTT reference<\/a> for greater details. We can expand on the above script, but rather than publish once, we need to go through a number of steps to ensure the device exists:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Connect to the gateway via <code>v1\/gateway\/connect<\/code> API call. If this does not exist, the device in the name provided is created. By adding a &#8216;type&#8217; element, the device is created with a matching profile name. If the device already exists, this call does not create another device. However, it can not be used to create the profile.<\/li>\n\n\n\n<li>Optionally, attributes can be set via <code>v1\/gateway\/attributes<\/code>. Attributes are similar to telemetry, however where as a history of telemetry is stored, only the single value of each key->value pair is stored. In my example this is a note (you can not set a device label), but equally it could be something from the environment such as the GPS location of a fixed sensor.<\/li>\n\n\n\n<li>Telemetry can then be sent. We can send telemetry for multiple devices at one time. The data needs to be in a specific format and include the current timestamp, e.g.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n    \"testgw_rcv\": &#91;\n        {\n            \"ts\": 1678382122412,\n            \"values\": {\n                \"SeeLights\": 4,\n                \"OfNine\": 7\n            }\n        }\n    ]\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The full listing is below. From this, it should be straight forward to build a sensor loop and add other devices:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/python\n\n# MQTT test, based on API code at https:\/\/thingsboard.io\/docs\/reference\/python-client-sdk\/\nimport paho.mqtt.client as mqtt\nimport json\nimport time\nfrom pprint import pprint\n\nTHINGSBOARD_HOST = '&lt;server>'\nACCESS_TOKEN = '&lt;token>'\n\nmy_name=\"TestGateway\"\nsensor_data = {'ultimateAnswer':42, 'pi':3.14159}\nother_device_data = {'SeeLights':4, 'OfNine': 7}\nother_device_name = \"testgw_rcv\"\nother_device_profile = \"GenericTest\"\n\nTHINGSBOARD_PORT = 1883\nmqtt_connected = False\n\n# Functions to act on connection and check for disconnection\n# See https:\/\/stackoverflow.com\/questions\/36093078\/mqtt-is-there-a-way-to-check-if-the-client-is-still-connected\ndef on_connect(client, userdata, flags, rc):\n    global mqtt_connected\n    if(rc==0):\n        mqtt_connected = True\n        print(\"MQTT server connected successfully\")\n    else:\n        print(\"MQTT server failed to connect rc={}\".format(rc))\n\ndef on_disconnect(client, userdata, rc):\n    global mqtt_connected\n    mqtt_connected = False\n    print(\"MQTT server disconnected, rc={}\".format(rc))\n\ndef on_publish(client, userdata, mid):\n    print(\"MQTT on_publish returned {}\".format(mid))\n\ndef mqttConnect():\n    global client,mqtt_connected\n    print(\"Connecting to ThingsBoard server\")\n    client.on_connect = on_connect\n    client.on_disconnect = on_disconnect\n    client.on_publish = on_publish\n    client.username_pw_set(ACCESS_TOKEN)\n    try:\n        client.connect(THINGSBOARD_HOST, THINGSBOARD_PORT, 60)\n    except:\n        print(\"Error: exception when connecting to MQTT server\")\n    client.loop_start()\n\nclient = mqtt.Client()\nmqttConnect()\n\nprint(\"Publishing teletry data\")\nclient.publish('v1\/devices\/me\/telemetry', json.dumps(sensor_data), 1)\n\n# Create the device\n# If the device already exists, this is ignored and the profile does not change (if different)\nmsg=\"{{'device':'{}', 'type':'{}'}}\".format(other_device_name,other_device_profile)\nprint(\"Connecting to gateway to provision device; Message: \"+msg)\nclient.publish('v1\/gateway\/connect', msg)\n\n# Set device attributes\nmsg=\"{{'{}':{{'Note':'Created by MQTT Gateway'}}}}\".format(other_device_name)\nprint(\"Sending attributes: \"+msg)\nclient.publish('v1\/gateway\/attributes', msg)\n\n# Build data structure\ntimeSeries={\"ts\": int(time.time()*1000), \"values\": other_device_data}\nsendData={other_device_name:&#91;timeSeries]}\n#print(json.dumps(sendData, indent=4))\nmsg=json.dumps(sendData)\nprint(\"Publishing teletry: \"+msg)\nclient.publish('v1\/gateway\/telemetry', msg)\n\nclient.loop_stop()\nclient.disconnect()\nprint(\"Test complete\")<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>MQTT is a lightweight communication platform, ideal for messaging between servers and IoT devices. ThingsBoard [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[31,32],"tags":[51,52,33],"class_list":["post-863","post","type-post","status-publish","format-standard","hentry","category-iot","category-thingsboard","tag-mqtt","tag-python","tag-thingsboard"],"_links":{"self":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/863","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/comments?post=863"}],"version-history":[{"count":1,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/863\/revisions"}],"predecessor-version":[{"id":1142,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/863\/revisions\/1142"}],"wp:attachment":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/media?parent=863"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/categories?post=863"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/tags?post=863"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}