-
Notifications
You must be signed in to change notification settings - Fork 84
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement stream producers that emit characters or lines
- Loading branch information
Showing
1 changed file
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
#ifndef SENSESP_SRC_SENSESP_SYSTEM_STREAM_PRODUCER_H_ | ||
#define SENSESP_SRC_SENSESP_SYSTEM_STREAM_PRODUCER_H_ | ||
|
||
#include "sensesp.h" | ||
|
||
#include "ReactESP.h" | ||
#include "sensesp/system/valueproducer.h" | ||
|
||
namespace sensesp { | ||
|
||
/** | ||
* @brief ValueProducer that reads from a Stream and produces each character. | ||
*/ | ||
class StreamCharProducer : public ValueProducer<char> { | ||
public: | ||
StreamCharProducer(Stream* stream) : stream_{stream} { | ||
read_reaction_ = ReactESP::app->onAvailable(*stream_, [this]() { | ||
while (stream_->available()) { | ||
char c = stream_->read(); | ||
this->emit(c); | ||
} | ||
}); | ||
} | ||
|
||
protected: | ||
Stream* stream_; | ||
StreamReaction* read_reaction_; | ||
}; | ||
|
||
/** | ||
* @brief ValueProducer that reads from a Stream and produces a full line. | ||
*/ | ||
class StreamLineProducer : public ValueProducer<String> { | ||
public: | ||
StreamLineProducer(Stream* stream, int max_line_length = 256) | ||
: stream_{stream}, max_line_length_{max_line_length} { | ||
static int buf_pos = 0; | ||
buf_ = new char[max_line_length_ + 1]; | ||
read_reaction_ = ReactESP::app->onAvailable(*stream_, [this]() { | ||
while (stream_->available()) { | ||
char c = stream_->read(); | ||
if (c == '\n') { | ||
// Include the newline character in the output | ||
buf_[buf_pos++] = c; | ||
buf_[buf_pos] = '\0'; | ||
this->emit(buf_); | ||
buf_pos = 0; | ||
} else { | ||
buf_[buf_pos++] = c; | ||
if (buf_pos >= max_line_length_ - 1) { | ||
buf_pos = 0; | ||
} | ||
} | ||
} | ||
}); | ||
} | ||
|
||
protected: | ||
const int max_line_length_; | ||
char *buf_; | ||
Stream* stream_; | ||
StreamReaction* read_reaction_; | ||
}; | ||
|
||
} // namespace sensesp | ||
|
||
#endif // SENSESP_SRC_SENSESP_SYSTEM_STREAM_PRODUCER_H_ |