Page 1 of 1
mqtt_as library and esp8266
Posted: Fri May 29, 2020 9:37 am
by jnogues
This is a question for the mqtt
Jedi Peter Hinch.
I'm using the mqtt_as library with an esp8266. when uC starts up and the router is off, the program ends giving an error. I have added the following in the code for restarting, is OK?
Code: Select all
try:
loop.run_until_complete(main(client))
finally:
client.close() # Prevent LmacRxBlk:1 errors
print('++++++++Error connecting first time. Reseting...+++++++++++')
time.sleep(10)
machine.reset()
Regards
Re: mqtt_as library and esp8266
Posted: Fri May 29, 2020 9:50 am
by pythoncoder
The
mqtt_as library assumes that connectivity to the broker exists on initial power up. Your fix looks OK to me. Does it work in practice?
I've been called many things in my life, not all complimentary - but I'm new to being a
Jedi
Re: mqtt_as library and esp8266
Posted: Fri May 29, 2020 9:57 am
by kevinkk525
I'm just a Padawan but this is how I handle it
Code: Select all
while True:
try:
await client.connect()
return
except OSError as e:
_log.error("Error connecting to wifi or mqtt:", e)
# not connected after trying.. not much we can do without a connection except
# trying again.
# Don't like resetting the machine as components could be working without wifi.
await asyncio.sleep(10)
continue
In way older code I was resetting the device too but at some point I realized that I also had modules that should be working without a wifi connection, e.g. if you have a button that should do something on the same device or a pump that should repeatedly turn on. So I changed it to just try again until it gets a connection.
Re: mqtt_as library and esp8266
Posted: Fri May 29, 2020 10:56 am
by jnogues
It works, the last 2 days. Now I try kevinkk525 solution! But Can you share where I need put this code? I'm a beginner!I
Regards!
Re: mqtt_as library and esp8266
Posted: Fri May 29, 2020 1:09 pm
by kevinkk525
In your main code you can put this block after you have created the "client" object:
Code: Select all
async def connect():
while True:
try:
await client.connect()
return
except OSError as e:
print("Error connecting to wifi or mqtt:", e)
# not connected after trying.. not much we can do without a connection except
# trying again.
# Don't like resetting the machine as components could be working without wifi.
await asyncio.sleep(10)
continue
asyncio.create_task(connect())
after that you continue with your other code like:
Code: Select all
try:
loop.run_forever()
finally:
client.close()
machine.reset()