Thursday, May 8, 2025

IoT (Internet of Things) Automation - MQTT Sensor Data Logger

 


Notes:

  • Problem Solved: Collects real-time data from IoT sensors via MQTT and stores it locally.

  • Customization Benefits: Add support for multiple topics or cloud sync.

  • Further Adoption: Integrate with InfluxDB, Grafana, or AWS IoT.

Python Code:


import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
    with open('sensor_log.csv', 'a') as f:
        f.write(f"{msg.topic},{msg.payload.decode()}\n")
    print(f"Logged: {msg.topic} -> {msg.payload.decode()}")

client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883)
client.subscribe("iot/temperature")

print("Listening for sensor data...")
client.loop_forever()

No comments:

Post a Comment

IoT (Internet of Things) Automation - Smart Energy Usage Tracker

  Notes: Problem Solved: Logs and analyzes power usage from smart meters. Customization Benefits: Track per-device energy and set ale...