Anvil.pico.connect freezes all functions

Today I finally managed to run the server function from within Micropython.

At the moment, I just don’t know how to handle one thing. Below is an excerpt from my main.py file:

async def main():
     uasyncio.create_task(check_temps())
     uasyncio.create_task(knob_operation())
     uasyncio.create_task(anvil.pico.connect(UPLINK_KEY))
     await uasyncio.create_task(daemons.daemons())

uasyncio.run(main())

What I don’t like is that until I see an Anvil message in the console saying “Connected/Authenticated…” none of the functions work. Anvil freezes all functions while connecting. I also checked anvil.pico.connect_async but the result was the same. If there’s no workaround, maybe there’s a way to run my own function when authentication happens?

You can certainly run your own functions when authentication happens! See on_first_connect and on_every_connect in the docs: Anvil Docs | Uplink for Pico W

I checked on_first_connect before creating this thread. It fires before, not after the connection is made:

uasyncio.create_task(anvil.pico.connect_async(UPLINK_KEY, on_first_connect=print('on_first_connect')))
>>>
MPY: soft reboot
<CYW43 STA up 192.168.0.164>
<CYW43 STA up 192.168.0.164>
on_first_connect
Connecting to Anvil...
Connected
Authenticated to app XXXXXXXXXXX

Here you are calling print('on_first_connect'), which returns None, and then you’re passing that None to the connect_async function. Try passing an ordinary function to on_first_connect, and that should work just fine!

Like this?

def ofc():
    print('on_first_connect')
    return True
uasyncio.create_task(anvil.pico.connect_async(UPLINK_KEY, on_first_connect=ofc()))

Same result.

As you can see in the example in the docs, the function you pass needs to be a coroutine:

async def ofc():
    print('on_first_connect')
    return True

That should work!

Ahh I missed async! Now it is working. Thanks for the help!

You’re very welcome!