peterhinch / micropython-async

Application of uasyncio to hardware interfaces. Tutorial and code.
MIT License
744 stars 169 forks source link

What is an 'event-like' object ? #95

Closed obdevel closed 1 year ago

obdevel commented 1 year ago

What attribute(s) does a class require in order to be 'event-like' and waitable by WaitAny / WaitAll ? This clearly works well with asyncio.Event objects but I'd like to use it with other classes. I added a wait() method to my class but that doesn't seem to be sufficient. What else do I need to implement ? Thanks.

peterhinch commented 1 year ago

I attempt to explain this here in the first paragraph.

The .wait method must be asynchronous and it must pause until some triggering event occurs. Here the word "event" is with a small "e". In other words .wait pauses until something happens. The object behaves like an Event without actually being an instance of that class.

obdevel commented 1 year ago

Thank you. It works fine now that I have my head around the precise syntax.

--> x = await WaitAny((sn1, sn2, )).wait()
--> x is sn1
False
--> x is sn2
True

Where sn1 and sn2 are objects that have an asynchronous .wait() method, as you describe.

These classes do have an asyncio.Event() object but I wanted to see if I could hide their internal implementation.

I also now have a version with a timeout, using a simple timeout class that sleeps then sets an event. If it completes first then the call to WaitAny has timed out.

peterhinch commented 1 year ago

Glad you've got it working :)