Send Telemetry with Python
Send sensor readings from a Python script to ThingsBoard over MQTT using the paho-mqtt client. This recipe uses an Access Token for authentication — see Getting Connected for other credential types.
Prerequisites
Section titled “Prerequisites”- Python 3.7+
- A ThingsBoard device with an Access Token — see Devices
-
Install paho-mqtt:
Terminal window pip install paho-mqtt -
Copy your device’s Access Token from Entities → Devices → [device] → Copy Access Token.
Send Telemetry
Section titled “Send Telemetry”import paho.mqtt.client as mqttimport jsonimport time
THINGSBOARD_HOST = "thingsboard.cloud" # replace with your hostACCESS_TOKEN = "YOUR_ACCESS_TOKEN" # replace with your device tokenTELEMETRY_TOPIC = "v1/devices/me/telemetry"
def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to ThingsBoard") else: print(f"Connection failed: {rc}")
client = mqtt.Client()client.username_pw_set(ACCESS_TOKEN)client.on_connect = on_connect
client.connect(THINGSBOARD_HOST, 1883, 60)client.loop_start()
try: while True: payload = {"temperature": 22.5, "humidity": 61} client.publish(TELEMETRY_TOPIC, json.dumps(payload)) print(f"Sent: {payload}") time.sleep(5)except KeyboardInterrupt: pass
client.loop_stop()client.disconnect()The script connects once and publishes a reading every 5 seconds until interrupted with Ctrl+C.
Send a Single Reading
Section titled “Send a Single Reading”To publish one payload and exit — useful for cron jobs or serverless functions:
import paho.mqtt.client as mqttimport json
THINGSBOARD_HOST = "thingsboard.cloud"ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"
client = mqtt.Client()client.username_pw_set(ACCESS_TOKEN)client.connect(THINGSBOARD_HOST, 1883, 60)
payload = {"temperature": 22.5, "humidity": 61}client.publish("v1/devices/me/telemetry", json.dumps(payload))client.disconnect()Send with Client-Side Timestamp
Section titled “Send with Client-Side Timestamp”Include ts (Unix milliseconds) when the device has a reliable clock and you want the exact measurement time stored instead of the server receive time:
import time
payload = { "ts": int(time.time() * 1000), "values": {"temperature": 22.5, "humidity": 61}}client.publish("v1/devices/me/telemetry", json.dumps(payload))