@@ -114,11 +114,14 @@ void USBCDC::onEvent(arduino_usb_cdc_event_t event, esp_event_handler_t callback
114
114
}
115
115
116
116
size_t USBCDC::setRxBufferSize (size_t rx_queue_len){
117
- if (rx_queue){
118
- if (!rx_queue_len){
117
+ size_t currentQueueSize = rx_queue ?
118
+ uxQueueSpacesAvailable (rx_queue) + uxQueueMessagesWaiting (rx_queue) : 0 ;
119
+
120
+ if (rx_queue && (!rx_queue_len || rx_queue_len != currentQueueSize)) {
119
121
vQueueDelete (rx_queue);
120
122
rx_queue = NULL ;
121
- }
123
+ }
124
+ if (!rx_queue_len || rx_queue_len == currentQueueSize){
122
125
return 0 ;
123
126
}
124
127
rx_queue = xQueueCreate (rx_queue_len, sizeof (uint8_t ));
@@ -133,7 +136,8 @@ void USBCDC::begin(unsigned long baud)
133
136
if (tx_lock == NULL ) {
134
137
tx_lock = xSemaphoreCreateMutex ();
135
138
}
136
- setRxBufferSize (256 );// default if not preset
139
+ // if rx_queue was set before begin(), keep it
140
+ if (!rx_queue) setRxBufferSize (256 ); // default if not preset
137
141
devices[itf] = this ;
138
142
}
139
143
@@ -144,6 +148,7 @@ void USBCDC::end()
144
148
setRxBufferSize (0 );
145
149
if (tx_lock != NULL ) {
146
150
vSemaphoreDelete (tx_lock);
151
+ tx_lock = NULL ;
147
152
}
148
153
}
149
154
@@ -246,14 +251,27 @@ void USBCDC::_onLineCoding(uint32_t _bit_rate, uint8_t _stop_bits, uint8_t _pari
246
251
void USBCDC::_onRX (){
247
252
uint8_t buf[CONFIG_TINYUSB_CDC_RX_BUFSIZE+1 ];
248
253
uint32_t count = tud_cdc_n_read (itf, buf, CONFIG_TINYUSB_CDC_RX_BUFSIZE);
254
+
255
+ if (rx_queue == NULL ) {
256
+ return ;
257
+ }
258
+ if (uxQueueSpacesAvailable (rx_queue) < count) {
259
+ // this VTaskDelay gives, to Arduino's task, time to the CPU do its processing
260
+ // without it, data may be lost when the number of bytes received is higher than CDC buffer size
261
+ vTaskDelay (10 );
262
+ }
249
263
for (uint32_t i=0 ; i<count; i++){
250
- if (rx_queue == NULL || !xQueueSend (rx_queue, buf+i, 0 )){
251
- return ;
264
+ if (!xQueueSend (rx_queue, buf+i, 0 )){
265
+ // rx_queue overflow - data will be lost
266
+ count = i;
267
+ break ;
252
268
}
253
269
}
254
- arduino_usb_cdc_event_data_t p;
255
- p.rx .len = count;
256
- arduino_usb_event_post (ARDUINO_USB_CDC_EVENTS, ARDUINO_USB_CDC_RX_EVENT, &p, sizeof (arduino_usb_cdc_event_data_t ), portMAX_DELAY);
270
+ if (count) {
271
+ arduino_usb_cdc_event_data_t p;
272
+ p.rx .len = count;
273
+ arduino_usb_event_post (ARDUINO_USB_CDC_EVENTS, ARDUINO_USB_CDC_RX_EVENT, &p, sizeof (arduino_usb_cdc_event_data_t ), portMAX_DELAY);
274
+ }
257
275
}
258
276
259
277
void USBCDC::_onTX (){
0 commit comments