Skip to content
Stand with Ukraine flag

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.

  • Python 3.7+
  • A ThingsBoard device with an Access Token — see Devices
  1. Install paho-mqtt:

    Terminal window
    pip install paho-mqtt
  2. Copy your device’s Access Token from Entities → Devices → [device] → Copy Access Token.

import paho.mqtt.client as mqtt
import json
import time
THINGSBOARD_HOST = "thingsboard.cloud" # replace with your host
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN" # replace with your device token
TELEMETRY_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.

To publish one payload and exit — useful for cron jobs or serverless functions:

import paho.mqtt.client as mqtt
import 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()

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))