From 76f03a2bee0a7d8a35fd68eb3bed1ceda3530cbd Mon Sep 17 00:00:00 2001 From: Jeff Epler Date: Mon, 8 Aug 2022 14:28:30 -0500 Subject: [PATCH] Make keypad select/poll'able for better async This allows a small wrapper class to be written ```py class AsyncEventQueue: def __init__(self, events): self._events = events async def __await__(self): yield asyncio.core._io_queue.queue_read(self._events) return self._events.get() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass ``` and used to just "await" the next event: ```py async def key_task(): print("waiting for keypresses") with keypad.KeyMatrix([board.D4], [board.D5]) as keys, AsyncEventQueue(keys.events) as ev: while True: print(await ev) ``` Because checking the empty status of the EventQueue does not enter CircuitPython bytecode, it's assumed (but not measured) that this is more efficient than an equivalent loop with an `await async.sleep(0)` yield and introduces less latency than any non-zero sleep value. --- shared-bindings/keypad/EventQueue.c | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/shared-bindings/keypad/EventQueue.c b/shared-bindings/keypad/EventQueue.c index 8e45f7ad1d..ed182033dc 100644 --- a/shared-bindings/keypad/EventQueue.c +++ b/shared-bindings/keypad/EventQueue.c @@ -24,8 +24,11 @@ * THE SOFTWARE. */ +#include "py/ioctl.h" +#include "py/mperrno.h" #include "py/objproperty.h" #include "py/runtime.h" +#include "py/stream.h" #include "shared-bindings/keypad/Event.h" #include "shared-bindings/keypad/EventQueue.h" @@ -141,12 +144,41 @@ STATIC const mp_rom_map_elem_t keypad_eventqueue_locals_dict_table[] = { STATIC MP_DEFINE_CONST_DICT(keypad_eventqueue_locals_dict, keypad_eventqueue_locals_dict_table); +#if MICROPY_PY_USELECT +STATIC mp_uint_t eventqueue_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { + (void)errcode; + keypad_eventqueue_obj_t *self = MP_OBJ_TO_PTR(self_in); + switch (request) { + case MP_STREAM_POLL: { + mp_uint_t flags = arg; + mp_uint_t ret = 0; + if ((flags & MP_IOCTL_POLL_RD) && common_hal_keypad_eventqueue_get_length(self)) { + ret |= MP_IOCTL_POLL_RD; + } + return ret; + } + default: + *errcode = MP_EINVAL; + return MP_STREAM_ERROR; + } +} + +STATIC const mp_stream_p_t eventqueue_p = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_stream) + .ioctl = eventqueue_ioctl, +}; +#endif + + const mp_obj_type_t keypad_eventqueue_type = { { &mp_type_type }, .flags = MP_TYPE_FLAG_EXTENDED, .name = MP_QSTR_EventQueue, MP_TYPE_EXTENDED_FIELDS( .unary_op = keypad_eventqueue_unary_op, + #if MICROPY_PY_USELECT + .protocol = &eventqueue_p, + #endif ), .locals_dict = (mp_obj_t)&keypad_eventqueue_locals_dict, };