/* * (c)2014-2026 Forward Computing and Control Pty. Ltd. * NSW Australia, www.forward.com.au * This code is not warranted to be fit for any purpose. You may only use it at your own risk. * This code may be freely used for both private and commercial use * Provided this copyright is maintained. */ #include "target_Stream.h" #include "pico/stdio_usb.h" #include "pico/stdio/driver.h" // struct stdio_driver, for stdio_usb.out_chars() etc. /** * Constructor, only initialises member variables. * Does NOT access the hardware, call begin() from setup() for that. */ target_Stream::target_Stream() { started = false; lookAhead = -1; } /** * Start the USB CDC device. See target_Stream.h. * stdio_usb_init() initialises TinyUSB, starts its background task and adds the * USB driver to the Pico SDK stdio. * @return true if the USB device started, false if not. */ bool target_Stream::begin() { started = stdio_usb_init(); return started; } /** * Write one byte. See write(buffer, size). * @param c the byte to send * @return 1 if queued, 0 if not started or the host is not connected. */ size_t target_Stream::write(uint8_t c) { return write(&c, 1); } /** * Write a block of bytes with the stdio_usb driver's out_chars(), which waits * for tx FIFO space, queues the bytes and starts sending them. * out_chars() returns nothing, it drops the bytes if the host disconnects, or * stops reading for PICO_STDIO_USB_STDOUT_TIMEOUT_US, while it is waiting. * @param buffer the bytes to send * @param size the number of bytes * @return size if queued, 0 if not started or the host is not connected. */ size_t target_Stream::write(const uint8_t *buffer, size_t size) { if (!started || !stdio_usb_connected()) { return 0; } stdio_usb.out_chars((const char *)buffer, (int)size); return size; } /** * Wait until all bytes previously written have been passed to the USB hardware. * Does NOT discard received data. */ void target_Stream::flush() { if (!started) { return; } stdio_usb.out_flush(); } /** * If the look ahead is empty, tries to read one byte into it. * @return 1 if a byte is held in the look ahead, else 0. */ int target_Stream::available() { if (lookAhead < 0) { lookAhead = read(); } return (lookAhead >= 0) ? 1 : 0; } /** * Read and remove the next received byte, the look ahead byte first, * otherwise from the stdio_usb driver's in_chars(), which does not block. * @return the next byte (0..255) as an int, or -1 if no byte is available. */ int target_Stream::read() { if (lookAhead >= 0) { int c = lookAhead; lookAhead = -1; return c; } if (!started) { return -1; } char b; if (stdio_usb.in_chars(&b, 1) == 1) { return (int)(uint8_t)b; } return -1; // PICO_ERROR_NO_DATA } /** * Return the next received byte WITHOUT removing it. * @return the next byte (0..255) as an int, or -1 if no byte is available. */ int target_Stream::peek() { available(); return lookAhead; }