running uasyncio in main thread plus in a 2nd thread also with uasyncios ?

All ESP32 boards running MicroPython.
Target audience: MicroPython users with an ESP32 board.
Post Reply
kindmartin
Posts: 20
Joined: Sun Apr 26, 2020 7:30 am

running uasyncio in main thread plus in a 2nd thread also with uasyncios ?

Post by kindmartin » Fri May 20, 2022 6:44 am

HI all here, I m trying to make some multi threading code and Im stuck getting errors and rebooting due to Guru panics .

The actual code is like running in a thread a main program path with uasyncio coroutines that works ok alone, and also if an issue a new thread from there to check every second if touch is touched for example.

Code: Select all

def PowerOn():  # entry function to enter first asyncio one
    try:
        print('--->> init PowerOn')
        lib._thread.stack_size(10*1024)
        lib._thread.start_new_thread(thread_touch, ())
        print(' now usyncio uasyncio.run(makeAsyncioLoop())')
        lib.uasyncio.run(makeAsyncioLoop())
    except Exception as err:
        print(err)

async def makeAsyncioLoop():
    try:
          main code using uasyncios courotines etc


...
def thread_touch():
    try:
        print('--->> def thread_touch')
        touchSensibility = int(bkw.config['hardwareSettings']['touchSensibility'])
        while True:
            if bkw.touch.read() < touchSensibility: 
                touchActioned(bkw.config['Timers']['timer0_m'])
            lib.time.sleep_ms(300)

    except Exception as ex:

        print("==>>>")
        print(ex)




Due to many reasons I would like to add more complexity to the new thread to manage some led blinking status as messages. 

so I Im trying like:

def PowerOn():  # entry function (no asyncio) to enter first asyncio one
    try:
        print('--->> init PowerOn')
        print('')

        bkw.memory["statusLed_Blinks"] = 1
        bkw.memory["statusLed_Duration_ms"] = 10000
        bkw.memory["statusLed_waits_ms"] = 60000
        lib._thread.stack_size(10*1024)
        lib._thread.start_new_thread(thread_2background, ())

        print('now usyncio uasyncio.run(makeAsyncioLoop())')
        lib.uasyncio.run(makeAsyncioLoop())
    except Exception as err:
        print(err)

async def makeAsyncioLoop():
    try:
        print('--->> makeAsyncioLoop')
        print('--->>look for home networks for Blynk monitoring, clock sync and check updates')

        bkw.memory["statusLed_Blinks"] = 1
        bkw.memory["statusLed_Duration_ms"] = 500
        bkw.memory["statusLed_waits_ms"] = 9500    

        lib.uasyncio.create_task(loopBlynkMonitor(checkEach_s=20))
        lib.uasyncio.create_task(loop_garbageC(each_s=300))
        
        print(' Now running background tasks')



def thread_2background():
    lib.uasyncio.run(makeAsyncioLoop2bck())
        
    
async def makeAsyncioLoop2bck():
    try:
        print('Running makeAsyncioLoop2bck loop')
        lib.uasyncio.create_task(thread_statusLed_white())
        lib.uasyncio.create_task(thread_statusLed_green())
        await thread_touch1() 

    except Exception as error:
        print(error)


async def thread_statusLed_white():
    try:
        while True:
            if bkw.memory["statusLed_on"] == True:
                halfBlinkOnTime_ms = int( (bkw.memory["statusLed_Duration_ms"])/(3*bkw.memory["statusLed_Blinks"]) )
                for b in range(0, bkw.memory["statusLed_Blinks"]):
                    bkw.led_white(1)
                    await lib.uasyncio.sleep_ms(halfBlinkOnTime_ms)
                    bkw.led_white(0)
                    await lib.uasyncio.sleep_ms(2*halfBlinkOnTime_ms)
                await lib.uasyncio.sleep_ms(bkw.memory["statusLed_waits_ms"])   
    
    except Exception as ex:
        print("==>>>")
        print(ex)


async def thread_touch1():
    try:
         ...



[03:15:55:496] >>> Task exception wasn't retrieved␍␊
[03:15:55:496] future: <Task> coro= <generator object 'updateBlynkStatusA9G' at 3f82acf0>␍␊
[03:15:55:496] Traceback (most recent call last):␍␊
[03:15:55:496] File "uasyncio/core.py", line 1, in run_until_complete␍␊
[03:15:55:496] ValueError: generator already executing␍␊
[03:15:58:589] >>> ---> network register not ok due no answer␍␊
[03:16:03:391] Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled.␍␊
[03:16:03:403] ␍␊
[03:16:03:403] Core 1 register dump:␍␊
[03:16:03:403] PC : 0x4010d870 PS : 0x00060b30 A0 : 0x800ebfd8 A1 : 0x3ffed4d0 ␍␊
[03:16:03:444] A2 : 0x400ebfe0 A3 : 0x00000000 A4 : 0x3f82add0 A5 : 0x00000000 ␍␊
[03:16:03:444] A6 : 0x000041b2 A7 : 0x00000002 A8 : 0x00000000 A9 : 0x3ffed4b0 ␍␊
[03:16:03:444] A10 : 0x00000000 A11 : 0x3f82add0 A12 : 0x3f82add0 A13 : 0x00000080 ␍␊
[03:16:03:444] A14 : 0x00000000 A15 : 0x00000005 SAR : 0x00000000 EXCCAUSE: 0x0000001c ␍␊
[03:16:03:444] EXCVADDR: 0x0000000c LBEG : 0x4008394d LEND : 0x40083955 LCOUNT : 0x00000027 ␍␊
[03:16:03:489] ␍␊
[03:16:03:489] Backtrace:0x4010d86d:0x3ffed4d0 0x400ebfd5:0x3ffed4f0 0x400e0a95:0x3ffed510 0x400e6b99:0x3ffed530 0x400e6cea:0x3ffed550 0x40085b91:0x3ffed570 0x400e0bb4:0x3ffed610 0x400e6b99:0x3ffed640 0x40085ae1:0x3ffed660 0x400e0bb4:0x3ffed700 0x400e6b99:0x3ffed760 0x400e6cea:0x3ffed780 0x40085b91:0x3ffed7a0 0x400e0bb4:0x3ffed840 0x400e6b99:0x3ffed890 0x4010adb3:0x3ffed8b0 0x400dc99d:0x3ffed950␍␊
[03:16:03:489] ␍␊
[03:16:03:489] ␍␊
[03:16:03:489] ELF file SHA256: a7479aa71ff6406c␍␊
[03:16:03:489] ␍␊
[03:16:03:489] Rebooting...␍␊
[03:16:03:489] ets Jul 29 2019 12:21:46␍␊

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

Re: running uasyncio in main thread plus in a 2nd thread also with uasyncios ?

Post by pythoncoder » Fri May 20, 2022 9:11 am

Running uasyncio in multiple threads is not supported: see this issue.

Why do you believe that uasyncio in a single thread cannot solve your problem?
Peter Hinch
Index to my micropython libraries.

kindmartin
Posts: 20
Joined: Sun Apr 26, 2020 7:30 am

Re: running uasyncio in main thread plus in a 2nd thread also with uasyncios ?

Post by kindmartin » Mon May 23, 2022 2:14 pm

pythoncoder wrote:
Fri May 20, 2022 9:11 am
Running uasyncio in multiple threads is not supported: see this issue.

Why do you believe that uasyncio in a single thread cannot solve your problem?
Thanks Pete, you make me think on how one can retribute your kind attention.

Ok with those issues running a separate instance ok uasyncio. I will need to think of another way to solve my needs.
the project I'm working on for months, also you helped me with the first uasyncio demo code in an mp message, which is related to an esp32 talking with an A9G ( btw module is also running mpy, but AT could be the same) wherein the main thread I often query that module via ESP32 UART 2 and sometimes I have to wait for responses due to those serial related time outs ( like bkw.A9G_uart.init(115200,rx=rx, tx=tx, bits=8, parity=None, stop=1, timeout=1000) )
I could bring down that UART timeout lets say to 100ms, and change all individually current functions not using uasyncio to use it so I will not have any time.sleep() waits. I will think in that, I would need to rewrite all to get all time.sleep and time.sleep_ms out.
Code_Q233qpesnN.png
Code_Q233qpesnN.png (115.14 KiB) Viewed 2770 times
any other hint ? thanks in advance, have an excellent week

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

Re: running uasyncio in main thread plus in a 2nd thread also with uasyncios ?

Post by pythoncoder » Tue May 24, 2022 12:02 pm

I suggest you write this as a uasyncio application. Look at StreamReader and StreamWriter classes. These allow access to a UART in asynchronous code: one task can be waiting on UART data while other tasks continue to run. You don't need to think about UART timeouts. The official documentation isn't too clear on this usage: see this tutorial section which I hope clarifies its use.
Peter Hinch
Index to my micropython libraries.

kindmartin
Posts: 20
Joined: Sun Apr 26, 2020 7:30 am

Re: running uasyncio in main thread plus in a 2nd thread also with uasyncios ?

Post by kindmartin » Mon Jul 18, 2022 12:12 pm

Thanks Peter. I finished to rewrite all now only using uasyncios sleeps. works greats.
/M

Post Reply