Różnice
Różnice między wybraną wersją a wersją aktualną.
| Poprzednia rewizja po obu stronach Poprzednia wersja Nowa wersja | Poprzednia wersja | ||
| programowanie:python:mqtt [2024/08/29 08:36] – sases | programowanie:python:mqtt [2024/10/18 15:58] (aktualna) – [Publikacja] sases | ||
|---|---|---|---|
| Linia 3: | Linia 3: | ||
| Instalacja biblioteki: '' | Instalacja biblioteki: '' | ||
| + | \\ | ||
| \\ | \\ | ||
| - | === Połączenie === | + | ===== Połączenie |
| <code python> | <code python> | ||
| import random | import random | ||
| + | import logging | ||
| from paho.mqtt import client as mqtt_client | from paho.mqtt import client as mqtt_client | ||
| + | |||
| + | logging.basicConfig(level=logging.INFO) | ||
| broker = ' | broker = ' | ||
| Linia 20: | Linia 24: | ||
| def on_connect(client, | def on_connect(client, | ||
| if rc == 0: | if rc == 0: | ||
| - | | + | |
| else: | else: | ||
| - | | + | |
| + | # Attempt to reconnect | ||
| + | client.reconnect() | ||
| client = mqtt_client.Client(client_id) | client = mqtt_client.Client(client_id) | ||
| Linia 30: | Linia 36: | ||
| return client | return client | ||
| </ | </ | ||
| + | \\ | ||
| \\ | \\ | ||
| - | === Subskrypcja === | + | ===== Subskrypcja |
| <code python> | <code python> | ||
| - | def subscribe(client: | + | def subscribe(client: |
| def on_message(client, | def on_message(client, | ||
| - | | + | |
| - | client.subscribe(' | + | |
| + | | ||
| client.on_message = on_message | client.on_message = on_message | ||
| </ | </ | ||
| + | \\ | ||
| \\ | \\ | ||
| - | === Publikacja === | + | ===== Publikacja |
| <code python> | <code python> | ||
| msg = f" | msg = f" | ||
| Linia 50: | Linia 59: | ||
| status = result[0] | status = result[0] | ||
| if status == 0: | if status == 0: | ||
| - | print(f" | + | logging.info(f" |
| else: | else: | ||
| - | print(f" | + | logging.error(f" |
| </ | </ | ||
| \\ | \\ | ||
| + | \\ | ||
| + | |||
| + | ===== Pętla obsługująca MQTT ===== | ||
| - | === Pętla obsługująca MQTT === | + | == Przykład 1: == |
| - | Przykład 1: | + | |
| <code python> | <code python> | ||
| client.loop_start() | client.loop_start() | ||
| Linia 67: | Linia 78: | ||
| </ | </ | ||
| - | Przykład 2: | + | == Przykład 2: == |
| <code python> | <code python> | ||
| while True: | while True: | ||