Skip to content

Commit f82e7dd

Browse files
authored
Merge pull request #292 from rygwdn/printf-reliability
make dh_debug_printf more reliable.
2 parents 4d2fc6d + 45e7dd0 commit f82e7dd

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/utils.c

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,14 +215,47 @@ bool validate_packet(uart_packet_t *packet) {
215215
* ================================================== */
216216
#ifdef DH_DEBUG
217217

218+
// Based on: https://github.com/raspberrypi/pico-sdk/blob/a1438dff1d38bd9c65dbd693f0e5db4b9ae91779/src/rp2_common/pico_stdio_usb/stdio_usb.c#L100-L130
219+
static void cdc_write_str(const char *str) {
220+
int str_len = strlen(str);
221+
222+
if (!tud_cdc_connected())
223+
return;
224+
225+
uint64_t last_write_time = time_us_64();
226+
227+
for (int bytes_written = 0; bytes_written < str_len;) {
228+
int bytes_remaining = str_len - bytes_written;
229+
int available_space = (int)tud_cdc_write_available();
230+
int chunk_size = (bytes_remaining < available_space) ? bytes_remaining : available_space;
231+
232+
if (chunk_size > 0) {
233+
int written = (int)tud_cdc_write(str + bytes_written, (uint32_t)chunk_size);
234+
tud_task();
235+
tud_cdc_write_flush();
236+
237+
bytes_written += written;
238+
last_write_time = time_us_64();
239+
} else {
240+
tud_task();
241+
tud_cdc_write_flush();
242+
243+
/* Timeout after 1ms if buffer stays full or connection lost */
244+
if (!tud_cdc_connected() || (time_us_64() > last_write_time + 1000))
245+
break;
246+
}
247+
}
248+
}
249+
250+
218251
int dh_debug_printf(const char *format, ...) {
219252
va_list args;
220253
va_start(args, format);
221254
char buffer[512];
222255

223256
int string_len = vsnprintf(buffer, 512, format, args);
224257

225-
tud_cdc_n_write(0, buffer, string_len);
258+
cdc_write_str(buffer);
226259
tud_cdc_write_flush();
227260

228261
va_end(args);

0 commit comments

Comments
 (0)