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

pip install paho-mqtt

thingsboard_iot/
│
└── publisher.py

publisher.py:


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

# ThingsBoard configuration
BROKER = "mqtt.thingsboard.cloud"
PORT = 1883

# Replace with your ThingsBoard device access token
ACCESS_TOKEN = "YOUR_DEVICE_ACCESS_TOKEN"

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


# Create MQTT client
client = mqtt.Client(
    client_id="temperature_sensor"
)

# Authenticate using device access token
client.username_pw_set(ACCESS_TOKEN)

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

client.connect(BROKER, PORT, 60)

client.loop_start()

print("Connected to ThingsBoard!")
print("Publishing sensor data...")


try:
    while True:

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

        # Prepare JSON telemetry
        data = {
            "temperature": temperature,
            "humidity": humidity
        }

        payload = json.dumps(data)

        # Publish telemetry
        result = client.publish(TOPIC, payload)

        result.wait_for_publish()

        print("Published:", payload)

        time.sleep(5)


except KeyboardInterrupt:
    print("Stopping sensor...")


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

    print("Disconnected from ThingsBoard")
