arduino / arduino/ArduinoCore-API

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

オープン
#54 コメント 9 件 リアクション 0 件 担当者 1 名 @cmaglie が担当を希望しています GitHub で見る
enhancement
主要言語
C++
スター
306
フォーク
150
PR マージ指標
30日以内にマージされた PR はありません

説明

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?

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。