Sound Byte Libs 1ee2ca6
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
cdc.cpp
Go to the documentation of this file.
1/*
2 * cdc.cpp - USB CDC Serial implementation
3 *
4 * Wraps TinyUSB CDC functions with SBL API.
5 */
6
7#include "cdc.hpp"
8#include "tusb.h"
9#include <cstring>
10
11namespace sbl::usb {
12
13size_t CdcSerial::write(const uint8_t* data, size_t len) {
14 if (!tud_cdc_connected()) {
15 return 0;
16 }
17
18 size_t written = 0;
19 while (written < len) {
20 size_t avail = tud_cdc_write_available();
21 if (avail == 0) {
22 // Buffer full, flush and retry
23 tud_cdc_write_flush();
24 tud_task(); // Process USB to make room
25 avail = tud_cdc_write_available();
26 if (avail == 0) {
27 break; // Still full, return what we wrote
28 }
29 }
30
31 size_t to_write = (len - written) < avail ? (len - written) : avail;
32 size_t n = tud_cdc_write(data + written, to_write);
33 written += n;
34
35 if (n == 0) {
36 break; // Write failed
37 }
38 }
39
40 tud_cdc_write_flush();
41 return written;
42}
43
44size_t CdcSerial::puts(const char* str) {
45 if (!str) return 0;
46 return write(reinterpret_cast<const uint8_t*>(str), strlen(str));
47}
48
49bool CdcSerial::write_byte(uint8_t byte) {
50 if (!tud_cdc_connected()) {
51 return false;
52 }
53
54 if (tud_cdc_write_available() == 0) {
55 tud_cdc_write_flush();
56 tud_task();
57 if (tud_cdc_write_available() == 0) {
58 return false;
59 }
60 }
61
62 return tud_cdc_write_char(byte) == 1;
63}
64
65size_t CdcSerial::read(uint8_t* data, size_t max_len) {
66 if (!tud_cdc_available()) {
67 return 0;
68 }
69 return tud_cdc_read(data, max_len);
70}
71
73 if (!tud_cdc_available()) {
74 return -1;
75 }
76 return tud_cdc_read_char();
77}
78
80 return tud_cdc_available();
81}
82
84 return tud_cdc_connected();
85}
86
88 tud_cdc_write_flush();
89
90 // Wait for TX complete with timeout
91 for (int i = 0; i < 1000; i++) {
92 tud_task();
93 if (tud_cdc_write_available() == CFG_TUD_CDC_TX_BUFSIZE) {
94 break; // Buffer empty, all sent
95 }
96 // Small delay - could use Timer::delay_us() but keep it simple
97 for (volatile int j = 0; j < 1000; j++) {}
98 }
99}
100
101} // namespace sbl::usb
USB CDC (Virtual COM Port) interface.
static size_t write(const uint8_t *data, size_t len)
Write data to USB serial (non-blocking)
Definition cdc.cpp:13
static size_t puts(const char *str)
Write null-terminated string.
Definition cdc.cpp:44
static void flush()
Flush TX buffer.
Definition cdc.cpp:87
static size_t available()
Get number of bytes available to read.
Definition cdc.cpp:79
static size_t read(uint8_t *data, size_t max_len)
Read data from USB serial (non-blocking)
Definition cdc.cpp:65
static bool write_byte(uint8_t byte)
Write single byte.
Definition cdc.cpp:49
static bool connected()
Check if host has terminal connected (DTR set)
Definition cdc.cpp:83
static int read_byte()
Read single byte.
Definition cdc.cpp:72