1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-13 18:08:10 +00:00
trezor-firmware/core/src/trezor/loop.py

346 lines
10 KiB
Python
Raw Normal View History

2018-07-03 14:20:58 +00:00
"""
Implements an event loop with cooperative multitasking and async I/O. Tasks in
the form of python coroutines (either plain generators or `async` functions) are
stepped through until completion, and can get asynchronously blocked by
`yield`ing or `await`ing a syscall.
See `schedule`, `run`, and syscalls `sleep`, `wait`, `signal` and `spawn`.
2018-07-03 14:20:58 +00:00
"""
import utime
import utimeq
from micropython import const
2018-07-03 14:20:26 +00:00
from trezor import io, log
2019-07-03 13:07:04 +00:00
if False:
from typing import (
Any,
Awaitable,
Callable,
Coroutine,
Dict,
Generator,
List,
Optional,
Set,
)
Task = Coroutine
Finalizer = Callable[[Task, Any], None]
# function to call after every task step
after_step_hook = None # type: Optional[Callable[[], None]]
# tasks scheduled for execution in the future
_queue = utimeq.utimeq(64)
# tasks paused on I/O
_paused = {} # type: Dict[int, Set[Task]]
# functions to execute after a task is finished
_finalizers = {} # type: Dict[int, Finalizer]
if __debug__:
# for performance stats
import array
2018-07-03 14:20:58 +00:00
log_delay_pos = 0
log_delay_rb_len = const(10)
2018-07-03 14:20:58 +00:00
log_delay_rb = array.array("i", [0] * log_delay_rb_len)
2019-07-03 13:07:04 +00:00
def schedule(
task: Task, value: Any = None, deadline: int = None, finalizer: Finalizer = None
) -> None:
2018-07-03 14:20:58 +00:00
"""
Schedule task to be executed with `value` on given `deadline` (in
microseconds). Does not start the event loop itself, see `run`.
2018-07-03 14:20:58 +00:00
"""
2016-11-12 11:22:05 +00:00
if deadline is None:
deadline = utime.ticks_us()
2019-05-13 13:06:34 +00:00
if finalizer is not None:
_finalizers[id(task)] = finalizer
2017-09-16 13:00:31 +00:00
_queue.push(deadline, task, value)
2019-07-03 13:07:04 +00:00
def pause(task: Task, iface: int) -> None:
tasks = _paused.get(iface, None)
if tasks is None:
2018-01-22 12:07:12 +00:00
tasks = _paused[iface] = set()
tasks.add(task)
2016-05-16 15:10:12 +00:00
2019-07-03 13:07:04 +00:00
def finalize(task: Task, value: Any) -> None:
2019-05-13 13:06:34 +00:00
fn = _finalizers.pop(id(task), None)
if fn is not None:
fn(task, value)
2019-07-03 13:07:04 +00:00
def close(task: Task) -> None:
2018-01-22 12:07:12 +00:00
for iface in _paused:
_paused[iface].discard(task)
_queue.discard(task)
2017-10-10 13:32:43 +00:00
task.close()
2019-05-13 13:06:34 +00:00
finalize(task, GeneratorExit())
2017-10-10 13:32:43 +00:00
2019-07-03 13:07:04 +00:00
def run() -> None:
2018-07-03 14:20:58 +00:00
"""
Loop forever, stepping through scheduled tasks and awaiting I/O events
2017-09-16 13:00:31 +00:00
inbetween. Use `schedule` first to add a coroutine to the task queue.
Tasks yield back to the scheduler on any I/O, usually by calling `await` on
a `Syscall`.
2018-07-03 14:20:58 +00:00
"""
2016-05-16 15:10:12 +00:00
if __debug__:
global log_delay_pos
2017-09-16 13:00:31 +00:00
max_delay = const(1000000) # usec delay if queue is empty
task_entry = [0, 0, 0] # deadline, task, value
msg_entry = [0, 0] # iface | flags, value
2017-10-24 11:59:09 +00:00
while _queue or _paused:
# compute the maximum amount of time we can wait for a message
2017-09-16 13:00:31 +00:00
if _queue:
delay = utime.ticks_diff(_queue.peektime(), utime.ticks_us())
else:
2017-09-16 13:00:31 +00:00
delay = max_delay
if __debug__:
# add current delay to ring buffer for performance stats
log_delay_rb[log_delay_pos] = delay
log_delay_pos = (log_delay_pos + 1) % log_delay_rb_len
2017-09-16 13:00:31 +00:00
if io.poll(_paused, msg_entry, delay):
# message received, run tasks paused on the interface
msg_tasks = _paused.pop(msg_entry[0], ())
for task in msg_tasks:
_step(task, msg_entry[1])
else:
# timeout occurred, run the first scheduled task
2017-09-16 13:00:31 +00:00
if _queue:
_queue.pop(task_entry)
2019-07-03 13:07:04 +00:00
_step(task_entry[1], task_entry[2]) # type: ignore
# error: Argument 1 to "_step" has incompatible type "int"; expected "Coroutine[Any, Any, Any]"
# rationale: We use untyped lists here, because that is what the C API supports.
def clear() -> None:
2019-07-11 14:52:25 +00:00
"""Clear all queue state. Any scheduled or paused tasks will be forgotten."""
_ = [0, 0, 0]
while _queue:
_queue.pop(_)
_paused.clear()
_finalizers.clear()
2019-07-03 13:07:04 +00:00
def _step(task: Task, value: Any) -> None:
try:
2019-05-13 13:06:34 +00:00
if isinstance(value, BaseException):
2019-07-03 13:07:04 +00:00
result = task.throw(value) # type: ignore
# error: Argument 1 to "throw" of "Coroutine" has incompatible type "Exception"; expected "Type[BaseException]"
# rationale: In micropython, generator.throw() accepts the exception object directly.
else:
result = task.send(value)
2019-05-13 13:06:34 +00:00
except StopIteration as e: # as e:
2017-08-21 11:22:35 +00:00
if __debug__:
2018-07-03 14:20:58 +00:00
log.debug(__name__, "finish: %s", task)
2019-05-13 13:06:34 +00:00
finalize(task, e.value)
except Exception as e:
2017-08-21 11:22:35 +00:00
if __debug__:
log.exception(__name__, e)
2019-05-13 13:06:34 +00:00
finalize(task, e)
else:
if isinstance(result, Syscall):
result.handle(task)
elif result is None:
2017-09-16 13:00:31 +00:00
schedule(task)
else:
2017-08-21 11:22:35 +00:00
if __debug__:
2018-07-03 14:20:58 +00:00
log.error(__name__, "unknown syscall: %s", result)
if after_step_hook:
after_step_hook()
class Syscall:
2018-07-03 14:20:58 +00:00
"""
When tasks want to perform any I/O, or do any sort of communication with the
scheduler, they do so through instances of a class derived from `Syscall`.
2018-07-03 14:20:58 +00:00
"""
2019-07-03 13:07:04 +00:00
def __iter__(self) -> Task: # type: ignore
# support `yield from` or `await` on syscalls
return (yield self)
2019-07-03 13:07:04 +00:00
def __await__(self) -> Generator:
return self.__iter__() # type: ignore
def handle(self, task: Task) -> None:
pass
2017-09-16 13:00:31 +00:00
class sleep(Syscall):
2018-07-03 14:20:58 +00:00
"""
Pause current task and resume it after given delay. Although the delay is
given in microseconds, sub-millisecond precision is not guaranteed. Result
value is the calculated deadline.
Example:
2017-09-16 13:00:31 +00:00
>>> planned = await loop.sleep(1000 * 1000) # sleep for 1ms
>>> print('missed by %d us', utime.ticks_diff(utime.ticks_us(), planned))
2018-07-03 14:20:58 +00:00
"""
2019-07-03 13:07:04 +00:00
def __init__(self, delay_us: int) -> None:
self.delay_us = delay_us
2019-07-03 13:07:04 +00:00
def handle(self, task: Task) -> None:
deadline = utime.ticks_add(utime.ticks_us(), self.delay_us)
2017-09-16 13:00:31 +00:00
schedule(task, deadline, deadline)
class wait(Syscall):
2018-07-03 14:20:58 +00:00
"""
Pause current task, and resume only after a message on `msg_iface` is
received. Messages are received either from an USB interface, or the
touch display. Result value a tuple of message values.
Example:
2017-09-16 13:00:31 +00:00
>>> hid_report, = await loop.wait(0xABCD) # await USB HID report
>>> event, x, y = await loop.wait(io.TOUCH) # await touch event
2018-07-03 14:20:58 +00:00
"""
2019-07-03 13:07:04 +00:00
def __init__(self, msg_iface: int) -> None:
self.msg_iface = msg_iface
2016-04-29 23:20:57 +00:00
2019-07-03 13:07:04 +00:00
def handle(self, task: Task) -> None:
2017-09-16 13:00:31 +00:00
pause(task, self.msg_iface)
2019-07-03 13:07:04 +00:00
_NO_VALUE = object()
2017-09-16 13:00:31 +00:00
class signal(Syscall):
2018-07-03 14:20:58 +00:00
"""
Pause current task, and let other running task to resume it later with a
result value or an exception.
Example:
2017-09-16 13:00:31 +00:00
>>> # in task #1:
>>> signal = loop.signal()
>>> result = await signal
>>> print('awaited result:', result)
>>> # in task #2:
>>> signal.send('hello from task #2')
>>> # prints in the next iteration of the event loop
2018-07-03 14:20:58 +00:00
"""
2019-07-03 13:07:04 +00:00
def __init__(self) -> None:
self.reset()
2019-07-03 13:07:04 +00:00
def reset(self) -> None:
self.value = _NO_VALUE
2019-07-03 13:07:04 +00:00
self.task = None # type: Optional[Task]
2019-07-03 13:07:04 +00:00
def handle(self, task: Task) -> None:
self.task = task
self._deliver()
2019-07-03 13:07:04 +00:00
def send(self, value: Any) -> None:
self.value = value
self._deliver()
2019-07-03 13:07:04 +00:00
def _deliver(self) -> None:
if self.task is not None and self.value is not _NO_VALUE:
2017-09-16 13:00:31 +00:00
schedule(self.task, self.value)
self.task = None
self.value = _NO_VALUE
2016-05-16 15:10:12 +00:00
2019-07-03 13:07:04 +00:00
def __iter__(self) -> Task: # type: ignore
try:
return (yield self)
2018-04-03 23:22:40 +00:00
except: # noqa: E722
self.task = None
raise
2019-05-13 13:06:34 +00:00
_type_gen = type((lambda: (yield))())
class spawn(Syscall):
2018-07-03 14:20:58 +00:00
"""
Execute one or more children tasks and wait until one of them exits.
Return value of `spawn` is the return value of task that triggered the
completion. By default, `spawn` returns after the first child completes, and
other running children are killed (by cancelling any pending schedules and
calling `close()`).
Example:
2017-09-16 13:00:31 +00:00
>>> # async def wait_for_touch(): ...
>>> # async def animate_logo(): ...
>>> touch_task = wait_for_touch()
>>> animation_task = animate_logo()
>>> waiter = loop.spawn(touch_task, animation_task)
2017-09-16 13:00:31 +00:00
>>> result = await waiter
>>> if animation_task in waiter.finished:
>>> print('animation task returned', result)
>>> else:
>>> print('touch task returned', result)
Note: You should not directly `yield` a `spawn` instance, see logic in
`spawn.__iter__` for explanation. Always use `await`.
2018-07-03 14:20:58 +00:00
"""
2019-07-03 13:07:04 +00:00
def __init__(self, *children: Awaitable, exit_others: bool = True) -> None:
self.children = children
2016-05-02 14:06:08 +00:00
self.exit_others = exit_others
2019-07-03 13:07:04 +00:00
self.finished = [] # type: List[Awaitable] # children that finished
self.scheduled = [] # type: List[Task] # scheduled wrapper tasks
2016-05-02 14:06:08 +00:00
2019-07-03 13:07:04 +00:00
def handle(self, task: Task) -> None:
2019-05-13 13:06:34 +00:00
finalizer = self._finish
scheduled = self.scheduled
finished = self.finished
2016-04-29 23:20:57 +00:00
2019-05-13 13:06:34 +00:00
self.callback = task
scheduled.clear()
finished.clear()
for child in self.children:
if isinstance(child, _type_gen):
child_task = child
else:
2019-07-03 13:07:04 +00:00
child_task = iter(child) # type: ignore
schedule(child_task, None, None, finalizer) # type: ignore
scheduled.append(child_task) # type: ignore
# TODO: document the types here
2019-05-13 13:06:34 +00:00
2019-07-03 13:07:04 +00:00
def exit(self, except_for: Task = None) -> None:
2019-05-13 13:06:34 +00:00
for task in self.scheduled:
if task != except_for:
close(task)
2019-07-03 13:07:04 +00:00
def _finish(self, task: Task, result: Any) -> None:
if not self.finished:
2019-05-13 13:06:34 +00:00
for index, child_task in enumerate(self.scheduled):
if child_task is task:
child = self.children[index]
break
self.finished.append(child)
2016-05-02 14:06:08 +00:00
if self.exit_others:
2019-05-13 13:06:34 +00:00
self.exit(task)
schedule(self.callback, result)
2019-07-03 13:07:04 +00:00
def __iter__(self) -> Task: # type: ignore
try:
return (yield self)
except: # noqa: E722
2016-10-06 12:41:50 +00:00
# exception was raised on the waiting task externally with
# close() or throw(), kill the children tasks and re-raise
self.exit()
raise