Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
7
Indexable
Never
# Define MQTT callback funcitons
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT broker")
        client.subscribe("FancyPants/#")
    else:
        print("Connection to MTQTT broker failed")

def on_message(client, userdata, msg):
    message = msg.payload.decode("utf-8")
    print("Received message:", message)
    mqtt_messages.append(message)
    try:
            # Parse the JSON message
            parsed_message = json.loads(message)
            # Update the latest MQTT message
            global latest_mqtt_message
            latest_mqtt_message = parsed_message
            for key, value in parsed_message.items():
                latest_mqtt_message[key] = value

            socketio.emit('update', latest_mqtt_message)
            
    except json.JSONDecodeError as e:
        print("Error decoding JSON message:", str(e))


# start MQTT client loop
mqtt_client = mqtt.Client()
mqtt_client.username_pw_set(mqtt_username, mqtt_password)
mqtt_client.tls_set(tls_version=ssl.PROTOCOL_TLSv1_2)

mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message

try:
    mqtt_client.connect(mqtt_broker_address, mqtt_broker_port, keepalive=60)
except Exception as e:
    print("Error connecting to MQTT broker:", str(e))
mqtt_client.loop_start()