chegewara / EspTinyUSB

ESP32S2 native USB library. Implemented few common classes, like MIDI, CDC, HID or DFU (update).
MIT License
473 stars 70 forks source link

How to make buffered serial input for CDC device? #112

Closed krisik70 closed 1 year ago

krisik70 commented 1 year ago

CDC example shows how to process Serial input: void onData() {       int len = USBSerial.available();       Serial.printf("\nnew data, len %d\n", len);       uint8_t buf[len] = {};       USBSerial.read(buf, len);       Serial.write(buf, len);   } It is working great, but it always gets 1 char no matter what. I can do buffering later but it will be great to have it in the callback. Is it possible? The sample code below is not working as expected, it is still getting only 1 char:  void onData() {         uint8_t buf[32] = {};         int cur = 0; int len;         while ((len = USBSerial.available()) > 0) { if ((cur + len) > 32) {               break;          }           USBSerial.read(&buf[cur], len);           cur += len;           delay(10);         }         Serial.printf("\nnew data, len %d\n", cur);         Serial.write(buf, cur);     }

Steffen-W commented 1 year ago

Maybe the following will help you: USBSerial.setWantedChar('\n');

void onWantedChar(char c)
{
// your code
}
chegewara commented 1 year ago

It is working great, but it always gets 1 char no matter what.

It depends what/how the host is sending data. If is sending data with multiple bytes, then you will receive that amount of bytes, but when data are sent 1 byte per bulk message, then you receive only 1 byte.

krisik70 commented 1 year ago

@Steffen-W : Thanks! I used this. According to the code it can be only one "wanted char", right? @chegewara : Thanks! You are totally right, my bad. Did I miss this, or there is no way to buffer data from host in OnData() till let's say '\r' and then make some magic so Serial.available() will report the whole buffer size and Serial.read() (or USBSerial.read()) will return in?

chegewara commented 1 year ago

It is something you have to implement in your app. From CDC protocol point of view its just a bunch of bytes, so there is no reason to wait till \nor \r. I think the easiest way is to copy bytes to some buffer and check if last byte is or not is what you want to signal EOL, especially that it is possible host may split sent message.

krisik70 commented 1 year ago

Yes, this is what I've done. I just hoped that I missed a better way. Thanks!