arduino / arduino/ArduinoCore-API
Add (nonblocking) read(buf, len) to Stream class
- Vorherrschende Sprache
- C++
- Sterne
- 306
- Forks
- 150
- PR-Merge-Kennzahlen
- Keine gemergten PRs in 30 T.
Beschreibung
Currently, the Stream class only has a (virtual) `read()` method to read one character at a time. It does have a `readBytes()` method to read multiple bytes at a time, but hat one blocks (with a timeout) and is not virtual, so it resorts to single-character reads.
It would be good to have a virtual multiple-byte reading method, which allows:
- Callers to easily read multiple bytes into a buffer
- Stream implementations to do efficient multiple-byte reads (e.g. prevent one SPI transfer per byte)
The Client class already has exactly this method, probably for the above reasons. Adding a virtual version of it to Stream means that Client implementations will support it out of the box.
We can also add a default implementation to the Stream class (using the existing `read()` method), that should keep all existing Stream implementations working. The default implementation would be something like:
Something like this (untested):
```
int read(uint8_t *buf, size_t size) {
if (!available())
return -1;
int res = 0;
while((int c = read()) >= 0 && size--)
buf[res] = c;
return res;
}
```
Note that this has a slightly peculiar return value: it returns -1 when
there is no data, to match the (Ethernet)Client implementation (which
returns 0 when the connection is closed). I guess it would make sense
swapping these, but that would break backward compatibility for the
Ethernet and (to a lesser degree, see arduino/Arduino#2251) the Wifi library.
How does all this sound?
Beitragsleitfaden
Für dieses Repository ist kein Beitragsleitfaden indexiert
Bewertung
Dieses Issue wurde noch nicht bewertet.