Despite the fact that I have been programming in Python for several years, I am a beginner in using async and mqtt and have problems that I cannot understand.
I have taken an original program by Peter Hinch (thanks!), with very small modifications called “range” (name of the topics, qos and some print in the code to visualize what happens).
The result is unpredictable: sometimes it connects and sometimes it doesn't.
I enclose the program and the results, using Thonny IDE, running it several times in succession without modifying anything
Program
Code: Select all
# range.py Test of asynchronous mqtt client with clean session False.
# (C) Copyright Peter Hinch 2017-2019.
# Released under the MIT licence.
# Public brokers https://github.com/mqtt/mqtt.github.io/wiki/public_brokers
# This demo is for wireless range tests. If OOR the red LED will light.
# In range the blue LED will pulse for each received message.
# Uses clean sessions to avoid backlog when OOR.
# red LED: ON == WiFi fail
# blue LED pulse == message received
# Publishes connection statistics.
from mqtt_as import MQTTClient, config
from config import wifi_led, blue_led
import uasyncio as asyncio
from sys import platform
TOPIC = 'CO2' # For demo publication and last will use same topic
outages = 0
async def pulse(): # This demo pulses blue LED each time a subscribed msg arrives.
blue_led(True)
await asyncio.sleep(1)
blue_led(False)
def sub_cb(topic, msg, retained):
print((topic, msg))
asyncio.create_task(pulse())
async def wifi_han(state):
global outages
wifi_led(not state) # Light LED when WiFi down
if state:
print('We are connected to broker.')
else:
outages += 1
print('WiFi or broker is down.')
await asyncio.sleep(1)
async def conn_han(client):
await client.subscribe('MONITOR', 1)
async def main(client):
try:
await client.connect()
except OSError:
print('Connection failed.')
return
n = 0
while True:
await asyncio.sleep(5)
print('publish', n)
# If WiFi is down the following will pause for the duration.
await client.publish(TOPIC, '{} repubs: {} outages: {}'.format(n, client.REPUB_COUNT, outages), qos = 1)
n += 1
# Define configuration
config['server'] = '192.168.1.32' # Change to suit
config['ssid'] = 'MIWIFI_2G_kYXg'
config['wifi_pw'] = 'XX'
config['subs_cb'] = sub_cb
config['wifi_coro'] = wifi_han
config['will'] = (TOPIC, 'Goodbye cruel world!', False, 0)
config['connect_coro'] = conn_han
config['keepalive'] = 120
print (config)
# Set up client. Enable optional debug statements.
MQTTClient.DEBUG = True
client = MQTTClient(config)
try:
asyncio.run(main(client))
finally: # Prevent LmacRxBlk:1 errors.
client.close()
blue_led(True)
asyncio.new_event_loop()
Code: Select all
>>> %Run -c $EDITOR_CONTENT
{'wifi_coro': <generator>, 'server': '192.168.1.32', 'ssl': False, 'port': 0, 'ssl_params': {}, 'response_time': 10, 'will': ('CO2', 'Goodbye cruel world!', False, 0), 'subs_cb': <function sub_cb at 0x3ffe77a0>, 'ssid': 'MIWIFI_2G_kYXg', 'wifi_pw': 'XX', 'clean_init': True, 'user': '', 'max_repubs': 4, 'password': '', 'ping_interval': 0, 'connect_coro': <generator>, 'clean': True, 'keepalive': 120, 'client_id': b'240ac4efb324'}
Checking WiFi integrity.
Got reliable connection
Connecting to broker.
Connected to broker.
We are connected to broker.
publish 0
publish 1
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
MicroPython v1.14 on 2021-02-02; ESP32 module with ESP32
Type "help()" for more information.
>>> %Run -c $EDITOR_CONTENT
{'wifi_coro': <generator>, 'server': '192.168.1.32', 'ssl': False, 'port': 0, 'ssl_params': {}, 'response_time': 10, 'will': ('CO2', 'Goodbye cruel world!', False, 0), 'subs_cb': <function sub_cb at 0x3ffeb190>, 'ssid': 'MIWIFI_2G_kYXg', 'wifi_pw': 'XX', 'clean_init': True, 'user': '', 'max_repubs': 4, 'password': '', 'ping_interval': 0, 'connect_coro': <generator>, 'clean': True, 'keepalive': 120, 'client_id': b'240ac4efb324'}
Checking WiFi integrity.
Got reliable connection
Connecting to broker.
Connection failed.
>>> %Run -c $EDITOR_CONTENT
{'wifi_coro': <generator>, 'server': '192.168.1.32', 'ssl': False, 'port': 0, 'ssl_params': {}, 'response_time': 10, 'will': ('CO2', 'Goodbye cruel world!', False, 0), 'subs_cb': <function sub_cb at 0x3ffeb300>, 'ssid': 'MIWIFI_2G_kYXg', 'wifi_pw': 'XX', 'clean_init': True, 'user': '', 'max_repubs': 4, 'password': '', 'ping_interval': 0, 'connect_coro': <generator>, 'clean': True, 'keepalive': 120, 'client_id': b'240ac4efb324'}
Checking WiFi integrity.
Got reliable connection
Connecting to broker.
Connection failed.
>>> %Run -c $EDITOR_CONTENT
{'wifi_coro': <generator>, 'server': '192.168.1.32', 'ssl': False, 'port': 0, 'ssl_params': {}, 'response_time': 10, 'will': ('CO2', 'Goodbye cruel world!', False, 0), 'subs_cb': <function sub_cb at 0x3ffef8f0>, 'ssid': 'MIWIFI_2G_kYXg', 'wifi_pw': 'XX', 'clean_init': True, 'user': '', 'max_repubs': 4, 'password': '', 'ping_interval': 0, 'connect_coro': <generator>, 'clean': True, 'keepalive': 120, 'client_id': b'240ac4efb324'}
Checking WiFi integrity.
Got reliable connection
Connecting to broker.
Connected to broker.
We are connected to broker.
publish 0
publish 1
A solution would be to try the connection several times, until the result is obtained. But that is not a deterministic or elegant solution.
Processor: Dev. Kit ESP32 WROOM 32
Broker: Raspberry Pi with Mosquitto
Distance to Access Point: 4 m aprox
Can someone give me an idea to help me determine what happens?