1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-02 20:48:30 +00:00
trezor-firmware/src/trezor/loop.py

101 lines
2.4 KiB
Python
Raw Normal View History

import utime
2016-04-29 19:19:25 +00:00
from uheapq import heappop, heappush
from .utils import type_gen
2016-04-29 12:49:47 +00:00
from . import msg
2016-04-29 15:58:57 +00:00
from . import ui
2016-04-29 17:54:54 +00:00
import log
2016-04-29 19:19:25 +00:00
EVT_TSTART = const(-1)
EVT_TMOVE = const(-2)
EVT_TEND = const(-3)
EVT_MSG = const(-4)
evt_handlers = { EVT_TSTART: None,
EVT_TMOVE: None,
EVT_TEND: None,
EVT_MSG: None, }
time_queue = []
def run_forever():
delay_max = const(1000000)
while True:
if time_queue:
t, _, _ = time_queue[0]
delay = t - utime.ticks_us()
else:
delay = delay_max
event = wait_for_event(delay)
if event:
# run interrupt handler
raise NotImplementedError()
else:
# run something from the time queue
_, gen, args = heappop(time_queue)
try:
if not args:
args = (None,)
ret = gen.send(*args)
except StopIteration as e:
# gen ended, forget it and go on
continue
if isinstance(ret, type_gen):
# generator, run it and call us asap
call_at(None, ret)
call_at(None, gen, *args)
elif isinstance(ret, int):
if ret >= 0:
# sleep in microseconds, call us later
call_at(utime.ticks_us() + ret, gen, *args)
else:
# wait for event
raise NotImplementedError()
elif ret is None:
# just call us asap
call_at(None, gen, *args)
def call_at(time, gen, *args):
if __debug__:
log.debug("Scheduling %s", (time, gen, args))
if not time:
time = utime.ticks_us()
heappush(time_queue, (time, gen, args))
if __debug__:
# For performance stats
import array
log_delay_pos = 0
log_delay_rb_len = const(10)
log_delay_rb = array.array('i', [0] * log_delay_rb_len)
2016-04-29 19:19:25 +00:00
def wait_for_event(timeout_us):
if __debug__:
# Adding delay to ring buffer for performance stats
global log_delay_pos
global log_delay_rb
global log_delay_rb_len
2016-04-29 19:19:25 +00:00
log_delay_rb[log_delay_pos] = timeout_us
log_delay_pos = (log_delay_pos + 1) % log_delay_rb_len
2016-04-29 19:19:25 +00:00
event = msg.select(timeout_us)
if event:
2016-04-29 15:58:57 +00:00
# print('msg:', m)
# utime.sleep_us(10000)
2016-04-29 19:19:25 +00:00
if event[0] == 2:
ui.display.bar(event[1], event[2], 2, 2, ui.BLACK)
return event