1
0
mirror of https://github.com/esphome/esphome.git synced 2025-09-18 11:12:20 +01:00

Add uart.write action (#567)

* Add uart.write action

* Lint
This commit is contained in:
Otto Winter
2019-05-29 19:32:18 +02:00
committed by GitHub
parent f35f6d2348
commit 31ddd3f668
6 changed files with 85 additions and 18 deletions

View File

@@ -1,15 +1,27 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins
from esphome.const import CONF_BAUD_RATE, CONF_ID, CONF_RX_PIN, CONF_TX_PIN, CONF_UART_ID
from esphome import pins, automation
from esphome.const import CONF_BAUD_RATE, CONF_ID, CONF_RX_PIN, CONF_TX_PIN, CONF_UART_ID, CONF_DATA
from esphome.core import CORE, coroutine
from esphome.py_compat import text_type, binary_type, char_to_byte
uart_ns = cg.esphome_ns.namespace('uart')
UARTComponent = uart_ns.class_('UARTComponent', cg.Component)
UARTDevice = uart_ns.class_('UARTDevice')
UARTWriteAction = uart_ns.class_('UARTWriteAction', automation.Action)
MULTI_CONF = True
def validate_raw_data(value):
if isinstance(value, text_type):
return value.encode('utf-8')
if isinstance(value, str):
return value
if isinstance(value, list):
return cv.Schema([cv.hex_uint8_t])(value)
raise cv.Invalid("data must either be a string wrapped in quotes or a list of bytes")
def validate_rx_pin(value):
value = pins.input_pin(value)
if CORE.is_esp8266 and value >= 16:
@@ -51,3 +63,22 @@ def register_uart_device(var, config):
"""
parent = yield cg.get_variable(config[CONF_UART_ID])
cg.add(var.set_uart_parent(parent))
@automation.register_action('uart.write', UARTWriteAction, cv.maybe_simple_value({
cv.GenerateID(): cv.use_id(UARTComponent),
cv.Required(CONF_DATA): cv.templatable(validate_raw_data),
}, key=CONF_DATA))
def uart_write_to_code(config, action_id, template_arg, args):
var = cg.new_Pvariable(action_id, template_arg)
yield cg.register_parented(var, config[CONF_ID])
data = config[CONF_DATA]
if isinstance(data, binary_type):
data = [char_to_byte(x) for x in data]
if cg.is_template(data):
templ = yield cg.templatable(data, args, cg.std_vector.template(cg.uint8))
cg.add(var.set_data_template(templ))
else:
cg.add(var.set_data_static(data))
yield var