Skip to content

Commit b61214d

Browse files
committed
added timeout to input()
1 parent d751740 commit b61214d

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

py/modbuiltins.c

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
#include "py/runtime.h"
3535
#include "py/builtin.h"
3636
#include "py/stream.h"
37+
#include "py/obj.h" /* For get_int */
3738

3839
#include "supervisor/shared/translate.h"
3940

@@ -233,10 +234,41 @@ MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_hex_obj, mp_builtin_hex);
233234
#define mp_hal_readline readline
234235
#endif
235236

237+
#include "usb.h"
238+
236239
STATIC mp_obj_t mp_builtin_input(size_t n_args, const mp_obj_t *args) {
237-
if (n_args == 1) {
240+
if (n_args >= 1) {
238241
mp_obj_print(args[0], PRINT_STR);
239242
}
243+
if (n_args == 2)
244+
{
245+
if (!mp_obj_is_true(args[1]))
246+
{ /* If they pass 0 or False, return immediately if there's no text available */
247+
if (!usb_bytes_available())
248+
{
249+
return mp_const_none;
250+
}
251+
}
252+
else if (MP_OBJ_IS_INT(args[1]))
253+
{
254+
/* Timeout has been sent... check for USB input for that # of millis */
255+
mp_uint_t target = mp_hal_ticks_ms() + mp_obj_get_int(args[1]);
256+
bool bytesAvaliable = false;
257+
258+
while (mp_hal_ticks_ms() < target)
259+
{
260+
if (usb_bytes_available())
261+
{
262+
bytesAvaliable = true;
263+
break;
264+
}
265+
}
266+
if (!bytesAvaliable)
267+
return mp_const_none;
268+
}
269+
}
270+
271+
240272
vstr_t line;
241273
vstr_init(&line, 16);
242274
int ret = mp_hal_readline(&line, "");
@@ -248,7 +280,7 @@ STATIC mp_obj_t mp_builtin_input(size_t n_args, const mp_obj_t *args) {
248280
}
249281
return mp_obj_new_str_from_vstr(&mp_type_str, &line);
250282
}
251-
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_input_obj, 0, 1, mp_builtin_input);
283+
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_input_obj, 0, 2, mp_builtin_input);
252284

253285
#endif
254286

0 commit comments

Comments
 (0)