Add support for Tuya Switches (#1074)

* Add tuya component to test4.yaml

* Add support for tuya switches

* Better config dump
This commit is contained in:
Jesse Hills 2020-07-12 08:52:29 +12:00 committed by GitHub
parent f3158c8b24
commit ef9e6e4d6e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 95 additions and 0 deletions

View file

@ -0,0 +1,28 @@
from esphome.components import switch
import esphome.config_validation as cv
import esphome.codegen as cg
from esphome.const import CONF_ID
from .. import tuya_ns, CONF_TUYA_ID, Tuya
DEPENDENCIES = ['tuya']
CONF_SWITCH_DATAPOINT = "switch_datapoint"
TuyaSwitch = tuya_ns.class_('TuyaSwitch', switch.Switch, cg.Component)
CONFIG_SCHEMA = switch.SWITCH_SCHEMA.extend({
cv.GenerateID(): cv.declare_id(TuyaSwitch),
cv.GenerateID(CONF_TUYA_ID): cv.use_id(Tuya),
cv.Required(CONF_SWITCH_DATAPOINT): cv.uint8_t,
}).extend(cv.COMPONENT_SCHEMA)
def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
yield cg.register_component(var, config)
yield switch.register_switch(var, config)
paren = yield cg.get_variable(config[CONF_TUYA_ID])
cg.add(var.set_tuya_parent(paren))
cg.add(var.set_switch_id(config[CONF_SWITCH_DATAPOINT]))

View file

@ -0,0 +1,33 @@
#include "esphome/core/log.h"
#include "tuya_switch.h"
namespace esphome {
namespace tuya {
static const char *TAG = "tuya.switch";
void TuyaSwitch::setup() {
this->parent_->register_listener(this->switch_id_, [this](TuyaDatapoint datapoint) {
this->publish_state(datapoint.value_bool);
ESP_LOGD(TAG, "MCU reported switch is: %s", ONOFF(datapoint.value_bool));
});
}
void TuyaSwitch::write_state(bool state) {
TuyaDatapoint datapoint{};
datapoint.id = this->switch_id_;
datapoint.type = TuyaDatapointType::BOOLEAN;
datapoint.value_bool = state;
this->parent_->set_datapoint_value(datapoint);
ESP_LOGD(TAG, "Setting switch: %s", ONOFF(state));
this->publish_state(state);
}
void TuyaSwitch::dump_config() {
LOG_SWITCH("", "Tuya Switch", this);
ESP_LOGCONFIG(TAG, " Switch has datapoint ID %u", this->switch_id_);
}
} // namespace tuya
} // namespace esphome

View file

@ -0,0 +1,26 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/tuya/tuya.h"
#include "esphome/components/switch/switch.h"
namespace esphome {
namespace tuya {
class TuyaSwitch : public switch_::Switch, public Component {
public:
void setup() override;
void dump_config() override;
void set_switch_id(uint8_t switch_id) { this->switch_id_ = switch_id; }
void set_tuya_parent(Tuya *parent) { this->parent_ = parent; }
protected:
void write_state(bool state) override;
Tuya *parent_;
uint8_t switch_id_{0};
};
} // namespace tuya
} // namespace esphome

View file

@ -49,6 +49,9 @@ web_server:
username: admin
password: admin
tuya:
sensor:
- platform: homeassistant
entity_id: sensor.hello_world
@ -71,3 +74,8 @@ sensor:
# - platform: apds9960
# type: blue
# name: APDS9960 Blue
switch:
- platform: tuya
id: tuya_switch
switch_datapoint: 1