Develop an IoT application that simulates temperature and humidity sensor data, publishes the data to ThingsBoard using the MQTT protocol, and visualizes the sensor readings on the ThingsBoard dashboard.


1. Open ThingsBoard Cloud.
2. Create an account or sign in.
3. Open Entities → Devices.
4. Click + Add new device.
5. Enter the device name:
Temperature_Humidity_Sensor
6. Click Add.
7. Open the device you created.
8. Find its Credentials section.
9. Copy the Access Token.

pip install paho-mqtt

sensor_simulation.py


# Temperature and Humidity Monitoring using MQTT
# ThingsBoard Cloud

import paho.mqtt.client as mqtt
import random
import json
import time

# ThingsBoard connection details
THINGSBOARD_HOST = "mqtt.thingsboard.cloud"
PORT = 1883

# Replace with your device access token
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"

# MQTT topic
TOPIC = "v1/devices/me/telemetry"


# Callback function
def on_connect(client, userdata, flags, reason_code, properties):
    if reason_code == 0:
        print("Connected to ThingsBoard successfully!")
    else:
        print("Connection failed:", reason_code)


# Create MQTT client
client = mqtt.Client(
    callback_api_version=mqtt.CallbackAPIVersion.VERSION2
)

# Set access token as username
client.username_pw_set(ACCESS_TOKEN)

# Set callback
client.on_connect = on_connect

# Connect to ThingsBoard
print("Connecting to ThingsBoard...")

client.connect(THINGSBOARD_HOST, PORT, 60)

# Start MQTT network loop
client.loop_start()

try:
    # Wait for connection
    timeout = time.time() + 10

    while not client.is_connected():
        if time.time() > timeout:
            raise TimeoutError("Could not connect to ThingsBoard")
        time.sleep(0.1)

    while True:

        # Generate simulated sensor readings
        temperature = round(random.uniform(20, 40), 2)
        humidity = round(random.uniform(40, 90), 2)

        # Create JSON payload
        data = {
            "temperature": temperature,
            "humidity": humidity
        }

        # Publish data to ThingsBoard
        result = client.publish(
            TOPIC,
            json.dumps(data),
            qos=1
        )

        result.wait_for_publish()

        print("Data sent:", data)

        # Send readings every 5 seconds
        time.sleep(5)

except KeyboardInterrupt:
    print("\nSensor simulation stopped.")

except Exception as e:
    print("Error:", e)

finally:
    client.loop_stop()
    client.disconnect()
