@@ -114,11 +114,14 @@ void USBCDC::onEvent(arduino_usb_cdc_event_t event, esp_event_handler_t callback
114114}
115115
116116size_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)) {
119121 vQueueDelete (rx_queue);
120122 rx_queue = NULL ;
121- }
123+ }
124+ if (!rx_queue_len || rx_queue_len == currentQueueSize){
122125 return 0 ;
123126 }
124127 rx_queue = xQueueCreate (rx_queue_len, sizeof (uint8_t ));
@@ -133,7 +136,8 @@ void USBCDC::begin(unsigned long baud)
133136 if (tx_lock == NULL ) {
134137 tx_lock = xSemaphoreCreateMutex ();
135138 }
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
137141 devices[itf] = this ;
138142}
139143
@@ -144,6 +148,7 @@ void USBCDC::end()
144148 setRxBufferSize (0 );
145149 if (tx_lock != NULL ) {
146150 vSemaphoreDelete (tx_lock);
151+ tx_lock = NULL ;
147152 }
148153}
149154
@@ -246,14 +251,27 @@ void USBCDC::_onLineCoding(uint32_t _bit_rate, uint8_t _stop_bits, uint8_t _pari
246251void USBCDC::_onRX (){
247252 uint8_t buf[CONFIG_TINYUSB_CDC_RX_BUFSIZE+1 ];
248253 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+ }
249263 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 ;
252268 }
253269 }
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+ }
257275}
258276
259277void USBCDC::_onTX (){
0 commit comments