SensESP 3.3.0
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_param = event_loop(),
41 int max_line_length = 256)
42 : stream_{stream},
43 max_line_length_{max_line_length},
44 buf_(new char[max_line_length_ + 1]) {
46 event_loop_param->onAvailable(*stream_, [this]() { this->receive_line(); });
47 }
48
49 protected:
51 int buf_pos = 0;
52 std::unique_ptr<char[]> buf_;
53 Stream* stream_;
54 reactesp::StreamEvent* read_event_;
55
56 void receive_line() {
57 while (stream_->available()) {
58 char c = stream_->read();
59 if (c == '\n') {
60 // Include the newline character in the output
61 buf_[buf_pos++] = c;
62 buf_[buf_pos] = '\0';
63 this->emit(buf_);
64 buf_pos = 0;
65 } else {
66 buf_[buf_pos++] = c;
67 if (buf_pos >= max_line_length_ - 1) {
68 buf_pos = 0;
69 }
70 }
71 }
72 }
73};
74
75} // namespace sensesp
76
77#endif // SENSESP_SRC_SENSESP_SYSTEM_STREAM_PRODUCER_H_
reactesp::StreamEvent * read_event_
StreamCharProducer(Stream *stream)
std::unique_ptr< char[]> buf_
reactesp::StreamEvent * read_event_
StreamLineProducer(Stream *stream, std::shared_ptr< reactesp::EventLoop > event_loop_param=event_loop(), int max_line_length=256)
void emit(const char &new_value)
std::shared_ptr< reactesp::EventLoop > event_loop()
Definition sensesp.cpp:9