uasyncio - How detect the end task in another task.

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Primesty
Posts: 13
Joined: Sun Jun 28, 2020 11:06 pm

Re: uasyncio - How detect the end task in another task.

Post by Primesty » Tue Jul 28, 2020 2:07 pm

Will do and re-write according to the tutorial!

Primesty
Posts: 13
Joined: Sun Jun 28, 2020 11:06 pm

Re: uasyncio - How detect the end task in another task.

Post by Primesty » Fri Jul 31, 2020 7:51 pm

Hi Peter!

I was able to re-write the code according to your tutorial so that it's not legacy anymore:

Code: Select all

from machine import Pin, Timer, I2C
import dht
import time
import uasyncio
import gc

from my_app import temp_reader

led = Pin(2, Pin.OUT)

def set_global_exception():
    def handle_exception(loop, context):
        import sys
        sys.print_exception(context["exception"])
        sys.exit()
    loop = uasyncio.get_event_loop()
    loop.set_exception_handler(handle_exception)

async def main():
    set_global_exception()  # Debug aid
    my_class = temp_reader(led)  # Constructor might create tasks
    uasyncio.create_task(my_class.blink())  # Or you might do this
    await my_class.cancel()  # Non-terminating method
try:
    uasyncio.run(main())
finally:
    uasyncio.new_event_loop()  # Clear retained state


main()

gc.collect()
gc.threshold(gc.mem_free() // 4 + gc.mem_alloc())
The led-blink example still works and the class with the blink method and the cancel method is in a file *my_app.py* .

Should I now first implement a temp_reader method or work on the encoder method? I assume both will then have to be put into **uasyncio.create_task()** above. Should the temperature measurement OR the encoder be non-terminating methods - for the last line above, e.g.

Code: Select all

await my_class.temp_measure() # Non-terminating method
? Please let me know what you think. Happy weekend!

User avatar
pythoncoder
Posts: 4335
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: uasyncio - How detect the end task in another task.

Post by pythoncoder » Sat Aug 01, 2020 7:30 am

A typical firmware application will have several non-terminating tasks. Your main() task starts all but one by issuing .create_task() and then awaits the last task: this ensures that the scheduler itself runs forever.

In many cases it doesn't matter which task you await - it's only an issue if the application logic requires the tasks to be started in a defined order.
Peter Hinch

Primesty
Posts: 13
Joined: Sun Jun 28, 2020 11:06 pm

Re: uasyncio - How detect the end task in another task.

Post by Primesty » Sat Aug 01, 2020 3:04 pm

Gotcha! Thanks for the input - once I have my drivers up and running again - I'll continue building the coros.

Post Reply