SensESP 3.0.1
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
stream_producer.h
Go to the documentation of this file.
1#ifndef SENSESP_SYSTEM_STREAM_PRODUCER_H
2#define SENSESP_SYSTEM_STREAM_PRODUCER_H
3
4#include "sensesp.h"
5
6#include <memory>
7
8#include "ReactESP.h"
10#include "sensesp_base_app.h"
11
12namespace sensesp {
13
17class StreamCharProducer : public ValueProducer<char> {
18 public:
19 StreamCharProducer(Stream* stream) : stream_{stream} {
20 read_event_ = event_loop()->onAvailable(*stream_, [this]() {
21 while (stream_->available()) {
22 char c = stream_->read();
23 this->emit(c);
24 }
25 });
26 }
27
28 protected:
29 Stream* stream_;
30 reactesp::StreamEvent* read_event_;
31};
32
36class StreamLineProducer : public ValueProducer<String> {
37 public:
39 Stream* stream,
40 std::shared_ptr<reactesp::EventLoop> event_loop = event_loop(),
41 int max_line_length = 256)
42 : stream_{stream}, max_line_length_{max_line_length} {
43 buf_ = new char[max_line_length_ + 1];
45 event_loop->onAvailable(*stream_, [this]() { this->receive_line(); });
46 }
47
48 protected:
50 int buf_pos = 0;
51 char* buf_;
52 Stream* stream_;
53 reactesp::StreamEvent* read_event_;
54
55 void receive_line() {
56 while (stream_->available()) {
57 char c = stream_->read();
58 if (c == '\n') {
59 // Include the newline character in the output
60 buf_[buf_pos++] = c;
61 buf_[buf_pos] = '\0';
62 this->emit(buf_);
63 buf_pos = 0;
64 } else {
65 buf_[buf_pos++] = c;
66 if (buf_pos >= max_line_length_ - 1) {
67 buf_pos = 0;
68 }
69 }
70 }
71 }
72};
73
74} // namespace sensesp
75
76#endif // SENSESP_SRC_SENSESP_SYSTEM_STREAM_PRODUCER_H_
ValueProducer that reads from a Stream and produces each character.
reactesp::StreamEvent * read_event_
StreamCharProducer(Stream *stream)
ValueProducer that reads from a Stream and produces a full line.
reactesp::StreamEvent * read_event_
StreamLineProducer(Stream *stream, std::shared_ptr< reactesp::EventLoop > event_loop=event_loop(), int max_line_length=256)
A base class for any sensor or piece of code that outputs a value for consumption elsewhere.
void emit(const char &new_value)
std::shared_ptr< reactesp::EventLoop > event_loop()
Definition sensesp.cpp:9