File size: 634 Bytes
767e14d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bc71f8
767e14d
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 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()