MQTT breaks infinite loop

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
dnoha
Posts: 7
Joined: Sat Jan 11, 2020 11:43 am

Re: MQTT breaks infinite loop

Post by dnoha » Sun Nov 07, 2021 6:23 pm

Ok, I have done it with .create_task.

Now I have transfered everything as coro routines :D .
I works reliabliy (tested for hours in good wifi, still need to test in bad wifi).

Code: Select all

# STARTING CORO ROUTINES
print('STARTING CORO ROUTINES')
event_loop = asyncio.get_event_loop()
event_loop.create_task(blink())
event_loop.create_task(publish())
event_loop.create_task(controller())
event_loop.create_task(read_temp())
event_loop.create_task(connect_mqtt())   # ONE TIME RUN !!!
event_loop.run_forever()


# MAIN LOOP
print('STARTING MAIN LOOP')
try: 
    while True:
        pass
    
finally:
    machine.reset()
    client.close()  # Prevent LmacRxBlk:1 errors

For enyone with possibly similar "issue", I was confused a bit with "start coro routine and it runs forever". That's true, only if routine has inifinte loop built in, like this:

Code: Select all

# CORO ROUTINE TO READ TEMPERATURE FROM SENSOR
async def read_temp():
    global temp_current
    while True:
        #print('start temp reading..')
        sensor_DS18X20.get_temp()
        await asyncio.sleep(1)
        sensor_DS18X20.read_temp()
        temp_current = sensor_DS18X20.temperature
        #print('temp:' + str(temp_current))
        await asyncio.sleep(1) 
If there is no infinite loop (while true), it will run only once:

Code: Select all

# CORO ROUTINE FOR NON-BLOCKING SUBSCRIBE TO MQTT
async def connect_coro(client):
    print("SUBSCRIBE to MQTT")
    await client.subscribe(COMMAND_TOPIC, 1)
    print("SUBSCRIBED to MQTT")
Last edited by dnoha on Mon Nov 08, 2021 2:48 pm, edited 2 times in total.

dnoha
Posts: 7
Joined: Sat Jan 11, 2020 11:43 am

Re: MQTT breaks infinite loop

Post by dnoha » Sun Nov 07, 2021 6:28 pm

Only not sure why mqtt_as client receives only messages with "/set" section.
Clipboard02.jpg
Clipboard02.jpg (10.33 KiB) Viewed 1062 times
Anything else is not received by my app?

Post Reply