Skip to content

Commit 76f03a2

Browse files
committed
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.
1 parent f1826b0 commit 76f03a2

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

shared-bindings/keypad/EventQueue.c

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,11 @@
2424
* THE SOFTWARE.
2525
*/
2626

27+
#include "py/ioctl.h"
28+
#include "py/mperrno.h"
2729
#include "py/objproperty.h"
2830
#include "py/runtime.h"
31+
#include "py/stream.h"
2932
#include "shared-bindings/keypad/Event.h"
3033
#include "shared-bindings/keypad/EventQueue.h"
3134

@@ -141,12 +144,41 @@ STATIC const mp_rom_map_elem_t keypad_eventqueue_locals_dict_table[] = {
141144

142145
STATIC MP_DEFINE_CONST_DICT(keypad_eventqueue_locals_dict, keypad_eventqueue_locals_dict_table);
143146

147+
#if MICROPY_PY_USELECT
148+
STATIC mp_uint_t eventqueue_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
149+
(void)errcode;
150+
keypad_eventqueue_obj_t *self = MP_OBJ_TO_PTR(self_in);
151+
switch (request) {
152+
case MP_STREAM_POLL: {
153+
mp_uint_t flags = arg;
154+
mp_uint_t ret = 0;
155+
if ((flags & MP_IOCTL_POLL_RD) && common_hal_keypad_eventqueue_get_length(self)) {
156+
ret |= MP_IOCTL_POLL_RD;
157+
}
158+
return ret;
159+
}
160+
default:
161+
*errcode = MP_EINVAL;
162+
return MP_STREAM_ERROR;
163+
}
164+
}
165+
166+
STATIC const mp_stream_p_t eventqueue_p = {
167+
MP_PROTO_IMPLEMENT(MP_QSTR_protocol_stream)
168+
.ioctl = eventqueue_ioctl,
169+
};
170+
#endif
171+
172+
144173
const mp_obj_type_t keypad_eventqueue_type = {
145174
{ &mp_type_type },
146175
.flags = MP_TYPE_FLAG_EXTENDED,
147176
.name = MP_QSTR_EventQueue,
148177
MP_TYPE_EXTENDED_FIELDS(
149178
.unary_op = keypad_eventqueue_unary_op,
179+
#if MICROPY_PY_USELECT
180+
.protocol = &eventqueue_p,
181+
#endif
150182
),
151183
.locals_dict = (mp_obj_t)&keypad_eventqueue_locals_dict,
152184
};

0 commit comments

Comments
 (0)