To jest stara wersja strony!
MQTT w Python
Instalacja biblioteki: pip install paho-mqtt
Połączenie
import random from paho.mqtt import client as mqtt_client 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: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) # client.username_pw_set(username, password) client.on_connect = on_connect client.connect(broker, port) return client
Subskrypcja
def subscribe(client: mqtt_client): def on_message(client, userdata, msg): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") client.subscribe('topic/topic') client.on_message = on_message
Publikacja
msg = f"message" topic = 'topic/topic' result = client.publish(topic, msg) status = result[0] if status == 0: print(f"Send `{msg}` to topic `{topic}`") else: print(f"Failed to send message to topic {topic}")
Pętla obsługująca MQTT
W pętli działania programu trzeba podtrzymywać połączenie MQTT:
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