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 actual ThingsBoard device access token
ACCESS_TOKEN = "YOUR_DEVICE_ACCESS_TOKEN"

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

# Connection status
connected = False


# Callback when connected to ThingsBoard
def on_connect(client, userdata, flags, reason_code, properties):
    global connected

    if reason_code.is_failure:
        connected = False
        print("Connection failed:", reason_code)
    else:
        connected = True
        print("Connected to ThingsBoard successfully!")


# Callback when disconnected
def on_disconnect(client, userdata, disconnect_flags, reason_code, properties):
    global connected
    connected = False
    print("Disconnected from ThingsBoard:", reason_code)


# Create MQTT client using Paho MQTT 2.x
client = mqtt.Client(
    callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
    client_id="temperature_sensor",
    protocol=mqtt.MQTTv311
)

# Set callbacks
client.on_connect = on_connect
client.on_disconnect = on_disconnect

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

try:
    # Connect to ThingsBoard
    print("Connecting to ThingsBoard...")
    client.connect(BROKER, PORT, 60)

    # Start MQTT network loop
    client.loop_start()

    print("Publishing sensor data...")

    while True:
        if not connected:
            print("Waiting for ThingsBoard connection...")
            time.sleep(2)
            continue

        # 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, qos=1)

        if result.rc == mqtt.MQTT_ERR_SUCCESS:
            result.wait_for_publish(timeout=10)

            if result.is_published():
                print("Published successfully:", payload)
            else:
                print("Message publishing timed out")
        else:
            print("Publish failed:", mqtt.error_string(result.rc))

        time.sleep(5)

except KeyboardInterrupt:
    print("\nStopping sensor...")

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

finally:
    client.loop_stop()
    client.disconnect()
    print("Disconnected from ThingsBoard")

