mqtt_as
Posted: Sat May 14, 2022 11:59 pm
I'm using the excellent mqtt_as library by Peter Hinch @pythoncoder. One issue I am trying to solve is when the program running on an ESP32 automatically starts when the power returns after a power cut. My mqtt broker running on a rpi is not immediately available when the ESP bursts into life as it takes longer to fire up. In this case I get a connection failed message and the program does not appear to retry the connection if the first connection cannot be made.
I have tried the following code:
in the hope I could circle around for 10 times before giving up. However the program will only ever try to connect 2 times before then giving an error of Wifi Internal Error, as per the following:
Trying to connect for 1 time
Connection failed. -1
Trying to connect for 2 time
Connection failed. -1
Trying to connect for 3 time
Connection failed. Wifi Internal Error
Trying to connect for 4 time
Connection failed. Wifi Internal Error
Trying to connect for 5 time
Connection failed. Wifi Internal Error
Trying to connect for 6 time
Connection failed. Wifi Internal Error
Trying to connect for 7 time
Connection failed. Wifi Internal Error
Trying to connect for 8 time
Connection failed. Wifi Internal Error
Trying to connect for 9 time
Connection failed. Wifi Internal Error
Now I tried to search the mqtt_as.py to find this message but I have not located it. In any case I suspect there is a better way to proceed. Any suggestion on a better way of ensuring the mqtt connection is only made once the mqtt broker is actually up and running would be appreciated.
I have tried the following code:
Code: Select all
# main function - called by asyncio.run
async def main(client):
x = 1
async def connection(x):
try:
await client.connect()
x = 100
return x
except OSError as e:
print('Connection failed.', e)
x += 1
return x
while x < 10:
print(f'Connection tries = {x}')
x = await connection(x)
if x < 11:
globs.run_program = False
Trying to connect for 1 time
Connection failed. -1
Trying to connect for 2 time
Connection failed. -1
Trying to connect for 3 time
Connection failed. Wifi Internal Error
Trying to connect for 4 time
Connection failed. Wifi Internal Error
Trying to connect for 5 time
Connection failed. Wifi Internal Error
Trying to connect for 6 time
Connection failed. Wifi Internal Error
Trying to connect for 7 time
Connection failed. Wifi Internal Error
Trying to connect for 8 time
Connection failed. Wifi Internal Error
Trying to connect for 9 time
Connection failed. Wifi Internal Error
Now I tried to search the mqtt_as.py to find this message but I have not located it. In any case I suspect there is a better way to proceed. Any suggestion on a better way of ensuring the mqtt connection is only made once the mqtt broker is actually up and running would be appreciated.