-
Notifications
You must be signed in to change notification settings - Fork 0
/
uart_read_line_sensor.h
57 lines (51 loc) · 1.43 KB
/
uart_read_line_sensor.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "esphome.h"
class UartReadLineSensor : public Component, public UARTDevice, public TextSensor {
public:
TextSensor *volume = new TextSensor();
TextSensor *input = new TextSensor();
TextSensor *raw_data = new TextSensor();
UartReadLineSensor(UARTComponent *parent) : UARTDevice(parent) {}
void setup() override {
// Nothing here
}
int readline(int readch, char *buffer, int len)
{
static int pos = 0;
int rpos;
if (readch > 0) {
switch (readch) {
case '\n': // Ignore new-lines
break;
case '$': // Return on $ sign
rpos = pos;
pos = 0; // Reset position index ready for next time
return rpos;
default:
if (pos < len-1) {
buffer[pos++] = readch;
buffer[pos] = 0;
}
}
}
// No end of line has been found, so return -1.
return -1;
}
void loop() override {
const int max_line_length = 80;
static char buffer[max_line_length];
char *property;
char *value;
while (available()) {
if(readline(read(), buffer, max_line_length) > 0) {
raw_data->publish_state(buffer);
property = strtok(buffer, "=");
value = strtok(NULL, "=");
if (strcmp(property,"volume") == 0) {
volume->publish_state(value);
} else if (strcmp(property,"source") == 0) {
input->publish_state(value);
}
}
}
}
};