Spaces:
Running
Running
# mqtt_client.py | |
import paho.mqtt.client as mqtt | |
import json | |
broker = "localhost" | |
port = 1883 | |
topic = "sensor_data" | |
data_list = [] | |
def on_connect(client, userdata, flags, rc): | |
print(f"Connected with result code {rc}") | |
client.subscribe(topic) | |
def on_message(client, userdata, msg): | |
global data_list | |
data = json.loads(msg.payload) | |
data_list.append(data) | |
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1) | |
client.on_connect = on_connect | |
client.on_message = on_message | |
def start_mqtt_client(): | |
client.connect(broker, port) | |
client.loop_start() | |
if __name__ == "__main__": | |
start_mqtt_client() | |