I want to read lines from the UART interface. I found the example of a custom uart text sensor:
I created the *.h-file and added the - include in the yaml-file.
Unfortunately I get a compiler error:
In file included from src/main.cpp:47:0:
src/uart_read_line_sensor.h:3:83: error: expected class-name before '{' token
class UartReadLineSensor : public Component, public UARTDevice, public TextSensor {
^
src/uart_read_line_sensor.h: In member function 'virtual void UartReadLineSensor::loop()':
src/uart_read_line_sensor.h:40:29: error: 'publish_state' was not declared in this scope
publish_state(buffer);
It seems that the class name TextSensor is not recognized. What can I do?
#include "esphome.h"
class UartReadLineSensor : public Component, public UARTDevice, public TextSensor {
public:
UartReadLineSensor(UARTComponent *parent) : UARTDevice(parent) {}
void setup() override {
// nothing to do 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 '\r': // Return on CR
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];
while (available()) {
if(readline(read(), buffer, max_line_length) > 0) {
publish_state(buffer);
}
}
}
};
Nevermind, I found the reason for the compilation error. I didn’t understand the magic of ESPHome concerning the compiling process.
As you can see in my yaml file, I included the *.h-file but didn’t define a text_sensor. This leads to a esphome.h-file without including the class definition of TextSensor. Probably to save memory. After defining a text_sensor in the yaml-file, as in the full example from above, the code compiles.
I suspect that if you don’t have a matching text sensor, it doesn’t include the libraries needed to compile the custom component. Explains why mine worked as I included the example text sensor.