2019-11-13 10:07:58 +00:00
|
|
|
# MicroPython uasyncio module
|
|
|
|
# MIT license; Copyright (c) 2019-2020 Damien P. George
|
|
|
|
|
|
|
|
from . import core
|
|
|
|
|
|
|
|
# Event class for primitive events that can be waited on, set, and cleared
|
|
|
|
class Event:
|
|
|
|
def __init__(self):
|
|
|
|
self.state = False # False=unset; True=set
|
|
|
|
self.waiting = core.TaskQueue() # Queue of Tasks waiting on completion of this event
|
|
|
|
|
|
|
|
def is_set(self):
|
|
|
|
return self.state
|
|
|
|
|
|
|
|
def set(self):
|
|
|
|
# Event becomes set, schedule any tasks waiting on it
|
2021-02-12 03:14:07 +00:00
|
|
|
# Note: This must not be called from anything except the thread running
|
|
|
|
# the asyncio loop (i.e. neither hard or soft IRQ, or a different thread).
|
2019-11-13 10:07:58 +00:00
|
|
|
while self.waiting.peek():
|
2022-04-20 08:20:07 +01:00
|
|
|
core._task_queue.push(self.waiting.pop())
|
2019-11-13 10:07:58 +00:00
|
|
|
self.state = True
|
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
self.state = False
|
|
|
|
|
|
|
|
async def wait(self):
|
|
|
|
if not self.state:
|
|
|
|
# Event not set, put the calling task on the event's waiting queue
|
2022-04-20 08:20:07 +01:00
|
|
|
self.waiting.push(core.cur_task)
|
2019-11-13 10:07:58 +00:00
|
|
|
# Set calling task's data to the event's queue so it can be removed if needed
|
|
|
|
core.cur_task.data = self.waiting
|
|
|
|
yield
|
|
|
|
return True
|
2021-02-12 03:14:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
# MicroPython-extension: This can be set from outside the asyncio event loop,
|
|
|
|
# such as other threads, IRQs or scheduler context. Implementation is a stream
|
|
|
|
# that asyncio will poll until a flag is set.
|
2021-09-01 18:48:15 +01:00
|
|
|
# Note: Unlike Event, this is self-clearing after a wait().
|
2021-02-12 03:14:07 +00:00
|
|
|
try:
|
|
|
|
import uio
|
|
|
|
|
|
|
|
class ThreadSafeFlag(uio.IOBase):
|
|
|
|
def __init__(self):
|
2022-08-12 08:03:38 +01:00
|
|
|
self.state = 0
|
2021-02-12 03:14:07 +00:00
|
|
|
|
|
|
|
def ioctl(self, req, flags):
|
|
|
|
if req == 3: # MP_STREAM_POLL
|
2022-08-12 08:03:38 +01:00
|
|
|
return self.state * flags
|
2021-02-12 03:14:07 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
def set(self):
|
2022-08-12 08:03:38 +01:00
|
|
|
self.state = 1
|
2021-02-12 03:14:07 +00:00
|
|
|
|
2021-09-01 18:48:15 +01:00
|
|
|
def clear(self):
|
2022-08-12 08:03:38 +01:00
|
|
|
self.state = 0
|
2021-09-01 18:48:15 +01:00
|
|
|
|
2021-02-12 03:14:07 +00:00
|
|
|
async def wait(self):
|
2022-08-12 08:03:38 +01:00
|
|
|
if not self.state:
|
2021-02-12 03:14:07 +00:00
|
|
|
yield core._io_queue.queue_read(self)
|
2022-08-12 08:03:38 +01:00
|
|
|
self.state = 0
|
2021-02-12 03:14:07 +00:00
|
|
|
|
|
|
|
except ImportError:
|
|
|
|
pass
|