programowanie:python:mqtt

MQTT w Python


Instalacja biblioteki: pip install paho-mqtt


import random
import logging
from paho.mqtt import client as mqtt_client
 
logging.basicConfig(level=logging.INFO)
 
broker = '127.0.0.1'
port = 1883
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 100)}'
# username = 'username'
# password = 'password'
 
def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            logging.info("Connected to MQTT Broker!")
        else:
            logging.error(f"Failed to connect, return code {rc}")
            # Attempt to reconnect
            client.reconnect()
 
    client = mqtt_client.Client(client_id)
    # client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client



def subscribe(client: mqtt_client, topics):
    def on_message(client, userdata, msg):
        logging.info(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
 
    for topic in topics:
        client.subscribe(topic)
    client.on_message = on_message



msg = f"message"
topic = 'topic/topic'
result = client.publish(topic, msg)
status = result[0]
if status == 0:
   logging.info(f"Send `{msg}` to topic `{topic}`")
else:
   logging.error(f"Failed to send message to topic {topic}")



Przykład 1:
client.loop_start()
 
while True:
   pass
 
client.loop_stop()
Przykład 2:
while True:
    rc = client.loop(timeout=1.0)
    if rc != 0:
        # need to handle error, possible reconnecting or stopping the application
  • programowanie/python/mqtt.txt
  • ostatnio zmienione: 2024/10/18 15:58
  • przez sases