add serial text sensor
This commit is contained in:
25
serial/text_sensor/__init__.py
Normal file
25
serial/text_sensor/__init__.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome import automation
|
||||
from esphome.components import uart
|
||||
from esphome.components import text_sensor
|
||||
from esphome.const import CONF_ID, CONF_STATE
|
||||
|
||||
DEPENDENCIES = ['uart']
|
||||
|
||||
serial_ns = cg.esphome_ns.namespace('serial')
|
||||
|
||||
SerialTextSensor = serial_ns.class_('SerialTextSensor', cg.Component,
|
||||
text_sensor.TextSensor, uart.UARTDevice)
|
||||
|
||||
CONFIG_SCHEMA = text_sensor.TEXT_SENSOR_SCHEMA.extend({
|
||||
cv.GenerateID(): cv.declare_id(SerialTextSensor),
|
||||
}).extend(uart.UART_DEVICE_SCHEMA)
|
||||
|
||||
|
||||
def to_code(config):
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
yield cg.register_component(var, config)
|
||||
yield text_sensor.register_text_sensor(var, config)
|
||||
yield uart.register_uart_device(var, config)
|
||||
|
||||
32
serial/text_sensor/serial_text_sensor.cpp
Normal file
32
serial/text_sensor/serial_text_sensor.cpp
Normal file
@@ -0,0 +1,32 @@
|
||||
#include "serial_text_sensor.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace serial {
|
||||
|
||||
static const char *TAG = "serial.text_sensor";
|
||||
|
||||
void SerialTextSensor::loop() {
|
||||
while (this->available()) {
|
||||
uint8_t c;
|
||||
this->read_byte(&c);
|
||||
this->handle_char_(c);
|
||||
}
|
||||
}
|
||||
|
||||
void SerialTextSensor::handle_char_(uint8_t c) {
|
||||
if (c == '\r')
|
||||
return;
|
||||
if (c == '\n') {
|
||||
std::string s(this->rx_message_.begin(), this->rx_message_.end());
|
||||
this->publish_state(s);
|
||||
this->rx_message_.clear();
|
||||
return;
|
||||
}
|
||||
this->rx_message_.push_back(c);
|
||||
}
|
||||
|
||||
void SerialTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Serial Sensor", this); }
|
||||
|
||||
} // namespace serial
|
||||
} // namespace esphome
|
||||
22
serial/text_sensor/serial_text_sensor.h
Normal file
22
serial/text_sensor/serial_text_sensor.h
Normal file
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/components/text_sensor/text_sensor.h"
|
||||
#include "esphome/components/uart/uart.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace serial {
|
||||
|
||||
class SerialTextSensor : public Component, public text_sensor::TextSensor, public uart::UARTDevice {
|
||||
public:
|
||||
float get_setup_priority() const override { return setup_priority::LATE; }
|
||||
void loop() override;
|
||||
void dump_config() override;
|
||||
|
||||
protected:
|
||||
void handle_char_(uint8_t c);
|
||||
std::vector<uint8_t> rx_message_;
|
||||
};
|
||||
|
||||
} // namespace serial
|
||||
} // namespace esphome
|
||||
Reference in New Issue
Block a user