arduino / arduino/ArduinoCore-API

Add (nonblocking) read(buf, len) to Stream class

Ouverte
#54 9 commentaires 0 réactions 1 personne assignée Réclamée par @cmaglie Voir sur GitHub
enhancement
Langage dominant
C++
Étoiles
306
Forks
150
Métriques de merge des PR
Aucune PR mergée en 30 j

Description

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?

Guide de contribution

Aucun guide de contribution indexé pour ce dépôt

Évaluation

Cette issue n'a pas encore été évaluée.

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.