Skip to content

Commit 5466f1b

Browse files
robert-hhdpgeorge
authored andcommitted
esp32/machine_uart: Implement uart.flush() and uart.txdone().
uart.flush() flush() will wait until all characters have been sent.To avoid a permanent lock, a timeout applies depending on the size of txbuf and the baud rate. ret = uart.txdone() ret is True if no transfer is in progress. ret is False otherwise.
1 parent 2488311 commit 5466f1b

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

ports/esp32/machine_uart.c

+25
Original file line numberDiff line numberDiff line change
@@ -417,15 +417,28 @@ STATIC mp_obj_t machine_uart_sendbreak(mp_obj_t self_in) {
417417
}
418418
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_sendbreak_obj, machine_uart_sendbreak);
419419

420+
STATIC mp_obj_t machine_uart_txdone(mp_obj_t self_in) {
421+
machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
422+
423+
if (uart_wait_tx_done(self->uart_num, 0) == ESP_OK) {
424+
return mp_const_true;
425+
} else {
426+
return mp_const_false;
427+
}
428+
}
429+
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_txdone_obj, machine_uart_txdone);
430+
420431
STATIC const mp_rom_map_elem_t machine_uart_locals_dict_table[] = {
421432
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_uart_init_obj) },
422433
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_uart_deinit_obj) },
423434
{ MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&machine_uart_any_obj) },
435+
{ MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) },
424436
{ MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
425437
{ MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
426438
{ MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
427439
{ MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
428440
{ MP_ROM_QSTR(MP_QSTR_sendbreak), MP_ROM_PTR(&machine_uart_sendbreak_obj) },
441+
{ MP_ROM_QSTR(MP_QSTR_txdone), MP_ROM_PTR(&machine_uart_txdone_obj) },
429442

430443
{ MP_ROM_QSTR(MP_QSTR_INV_TX), MP_ROM_INT(UART_INV_TX) },
431444
{ MP_ROM_QSTR(MP_QSTR_INV_RX), MP_ROM_INT(UART_INV_RX) },
@@ -491,6 +504,18 @@ STATIC mp_uint_t machine_uart_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr
491504
if ((flags & MP_STREAM_POLL_WR) && 1) { // FIXME: uart_tx_any_room(self->uart_num)
492505
ret |= MP_STREAM_POLL_WR;
493506
}
507+
} else if (request == MP_STREAM_FLUSH) {
508+
// The timeout is estimated using the buffer size and the baudrate.
509+
// Take the worst case assumptions at 13 bit symbol size times 2.
510+
uint32_t baudrate;
511+
uart_get_baudrate(self->uart_num, &baudrate);
512+
uint32_t timeout = (3 + self->txbuf) * 13000 * 2 / baudrate;
513+
if (uart_wait_tx_done(self->uart_num, timeout) == ESP_OK) {
514+
ret = 0;
515+
} else {
516+
*errcode = MP_ETIMEDOUT;
517+
ret = MP_STREAM_ERROR;
518+
}
494519
} else {
495520
*errcode = MP_EINVAL;
496521
ret = MP_STREAM_ERROR;

0 commit comments

Comments
 (0)