mirror of
https://github.com/esphome/esphome.git
synced 2026-11-19 11:35:57 +00:00
Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8c95ace2d | ||
|
|
ec04273cb9 | ||
|
|
8b744ca59c | ||
|
|
590ed71434 | ||
|
|
19d2f90a2a | ||
|
|
bee80eef56 | ||
|
|
04bb736511 | ||
|
|
94e670de12 | ||
|
|
03990bf424 | ||
|
|
d3dd1b27da | ||
|
|
05436f0b15 | ||
|
|
c90cf2c987 | ||
|
|
87be3320a3 | ||
|
|
39fa5b1dd6 | ||
|
|
d983659f32 | ||
|
|
837f2706b4 | ||
|
|
d01835e824 | ||
|
|
0b0bb23517 | ||
|
|
4f8ca50ffe | ||
|
|
e009b526aa | ||
|
|
29f751a8aa | ||
|
|
c1b0e3b7b6 | ||
|
|
5a46ae13d8 | ||
|
|
b338e0a2e3 | ||
|
|
fd330d8e23 | ||
|
|
3d067b9484 | ||
|
|
4d28203063 | ||
|
|
f72ba983e9 | ||
|
|
dcda93d7ca | ||
|
|
0436eda0f8 | ||
|
|
3c0905fb03 | ||
|
|
bf79439362 | ||
|
|
a460fb50b4 | ||
|
|
06ac99fe7b | ||
|
|
61b99d91bf | ||
|
|
69a7f7a408 | ||
|
|
9fb6cb4867 | ||
|
|
e0a5fad2de | ||
|
|
d76c655553 | ||
|
|
9bdd466e51 | ||
|
|
03880d5ea6 | ||
|
|
4a04c61ab5 | ||
|
|
2cd9ddf246 |
No files matched your search
@@ -120,7 +120,7 @@ helper; `AGENTS.md` section 4 and the `component-codegen` skill have the detail.
|
||||
| hand-written `set_x_sensor()` plus `x_sensor_` member | `SUB_SENSOR(x)`, `SUB_BINARY_SENSOR`, `SUB_TEXT_SENSOR`, `SUB_SWITCH`, ... |
|
||||
| `if CONF_X in config: s = await sensor.new_sensor(config[CONF_X])` plus setter | `sensors = sensor.sub_sensors(config)` then `await sensors(CONF_X, hub.set_x_sensor)` |
|
||||
| hand-written `{"a": MyEnum.MY_ENUM_A, ...}` dict | `MyEnum.options("a", "b", prefix="MY_ENUM_")` |
|
||||
| loops on `available()` / `read_byte()` | UART `read_available(on_byte)`, `discard_available()`, `LineReader<N>`, `FrameReader<N, HEADER...>` |
|
||||
| loops on `available()` / `read_byte()` | UART `read_available(on_byte)`, `discard_available()`, `LineReader<N>`, `FrameReader<N, HEADER...>`, `LengthFrameReader<N, FrameFormat<...>...>` |
|
||||
| hand-rolled CRC, checksum or bit loop | `crc8`, `crc16`, `xor_bytes`, `sum16_bytes`, `encode_uint16`, ... (`esphome/core/helpers.h`) |
|
||||
| integer split into buffer bytes by hand (`buf[0] = v >> 8; buf[1] = v;`) | `put_be16`/`24`/`32`, `put_le16`, `put_le32` (`esphome/core/helpers.h`) |
|
||||
| bare `mark_failed()`, or `ESP_LOGE` then `mark_failed()` | `this->mark_failed(LOG_STR("reason"))` or `LOG_STR(ESP_LOG_MSG_COMM_FAIL)` |
|
||||
|
||||
@@ -246,7 +246,9 @@ file does, and it is the authority when they disagree. The most useful starting
|
||||
`time::decode_bcd_calendar<LAYOUT>` and `encode_bcd_calendar<LAYOUT>` with `EPSON_BCD_CALENDAR`,
|
||||
`DS_BCD_CALENDAR` or `PCF_BCD_CALENDAR`.
|
||||
* **Bus helpers:** UART drains with `read_available(on_byte)` and `discard_available()`, text lines with
|
||||
`LineReader<N>`, fixed-length binary frames with `FrameReader<N, HEADER...>`; I2C has `update_register`,
|
||||
`LineReader<N>`, fixed-length binary frames with `FrameReader<N, HEADER...>`, frames that give their own length
|
||||
with `LengthFrameReader<N, FrameFormat<FrameHeader<...>, PayloadLengthU16LE<LengthField{...}>>...>` fed by
|
||||
`read_frames(reader, handler, now, last_rx)`, which frees frames a bad length holds; I2C has `update_register`,
|
||||
`update_register16`, `read_byte_reg16` and `write_byte_reg16` for 16-bit register addresses,
|
||||
`write_registers` (PROGMEM `I2CRegValue` table), `check_chip_id` and `read_bytes_16_le`.
|
||||
`if (!this->status_comm_result(ok)) return;` sets or clears the warning; an earlier step of a multi-step
|
||||
|
||||
@@ -701,6 +701,7 @@ esphome/components/toshiba/* @kbx81
|
||||
esphome/components/touchscreen/* @jesserockz @nielsnl68
|
||||
esphome/components/tsl2591/* @wjcarpenter
|
||||
esphome/components/tt21100/* @kroimon
|
||||
esphome/components/tuya/* @dwmw2 @ssieb
|
||||
esphome/components/tuya/binary_sensor/* @jesserockz
|
||||
esphome/components/tuya/climate/* @jesserockz
|
||||
esphome/components/tuya/number/* @frankiboy1
|
||||
|
||||
@@ -41,7 +41,7 @@ from esphome.const import (
|
||||
__version__ as ESPHOME_VERSION,
|
||||
)
|
||||
from esphome.core import CORE, ID, MACAddress
|
||||
from esphome.cpp_generator import MockObj, StaticCastExpression, UnaryOpExpression
|
||||
from esphome.cpp_generator import MockObj, StaticCastExpression
|
||||
import esphome.final_validate as fv
|
||||
from esphome.schema_extractors import SCHEMA_EXTRACT
|
||||
from esphome.types import ConfigType, TemplateArgsType
|
||||
@@ -704,21 +704,21 @@ async def to_code_descriptor(descriptor_conf, char_conf, char_var):
|
||||
descriptor_conf[CONF_MAX_LENGTH],
|
||||
descriptor_permissions(descriptor_conf, char_conf),
|
||||
)
|
||||
# Static storage, so the characteristic must not free it
|
||||
cg.add(char_var.add_descriptor(UnaryOpExpression("*", desc_var)))
|
||||
cg.add(char_var.add_descriptor(desc_var))
|
||||
cg.add(desc_var.set_value(value))
|
||||
if (on_write_conf := descriptor_conf.get(CONF_ON_WRITE)) is not None:
|
||||
await _build_on_write_automation(desc_var, on_write_conf)
|
||||
|
||||
|
||||
async def to_code_characteristic(service_var, char_conf):
|
||||
char_var = cg.new_Pvariable(
|
||||
char_var = cg.Pvariable(
|
||||
char_conf[CONF_ID],
|
||||
parse_uuid(char_conf[CONF_UUID]),
|
||||
parse_properties(char_conf),
|
||||
characteristic_permissions(char_conf),
|
||||
service_var.create_characteristic(
|
||||
parse_uuid(char_conf[CONF_UUID]),
|
||||
parse_properties(char_conf),
|
||||
characteristic_permissions(char_conf),
|
||||
),
|
||||
)
|
||||
cg.add(service_var.add_characteristic(UnaryOpExpression("*", char_var)))
|
||||
if (on_write_conf := char_conf.get(CONF_ON_WRITE)) is not None:
|
||||
await _build_on_write_automation(char_var, on_write_conf)
|
||||
if CONF_VALUE in char_conf:
|
||||
@@ -823,13 +823,14 @@ async def to_code(config):
|
||||
for service_config in config[CONF_SERVICES]:
|
||||
# Calculate the optimal number of handles based on the number of characteristics and descriptors
|
||||
num_handles = calculate_num_handles(service_config)
|
||||
service_var = cg.new_Pvariable(
|
||||
service_var = cg.Pvariable(
|
||||
service_config[CONF_ID],
|
||||
parse_uuid(service_config[CONF_UUID]),
|
||||
num_handles,
|
||||
service_config[CONF_ADVERTISE],
|
||||
var.create_service(
|
||||
parse_uuid(service_config[CONF_UUID]),
|
||||
service_config[CONF_ADVERTISE],
|
||||
num_handles,
|
||||
),
|
||||
)
|
||||
cg.add(var.add_service(UnaryOpExpression("*", service_var)))
|
||||
for char_conf in service_config[CONF_CHARACTERISTICS]:
|
||||
await to_code_characteristic(service_var, char_conf)
|
||||
if uuid_is(service_config[CONF_UUID], DEVICE_INFORMATION_SERVICE_UUID):
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
#include "ble_server.h"
|
||||
#include "ble_service.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
@@ -15,12 +13,7 @@ ESPHOME_LOG_TAG(TAG, "esp32_ble_server.characteristic");
|
||||
|
||||
BLECharacteristic::~BLECharacteristic() {
|
||||
for (auto *descriptor : this->descriptors_) {
|
||||
if (descriptor->owned_) {
|
||||
delete descriptor; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
} else if (descriptor->characteristic_ == this) {
|
||||
// A caller-owned descriptor outlives this characteristic, and may already belong to another one
|
||||
descriptor->characteristic_ = nullptr;
|
||||
}
|
||||
delete descriptor; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,27 +79,10 @@ void BLECharacteristic::notify() {
|
||||
}
|
||||
}
|
||||
|
||||
void BLECharacteristic::do_delete() {
|
||||
this->clients_to_notify_.clear();
|
||||
// The stack may reuse the handles, so a deleted characteristic must not match events until it is created again
|
||||
this->handle_ = 0xFFFF;
|
||||
this->state_ = INIT;
|
||||
for (auto *descriptor : this->descriptors_) {
|
||||
descriptor->handle_ = 0xFFFF;
|
||||
descriptor->state_ = BLEDescriptor::INIT;
|
||||
}
|
||||
}
|
||||
|
||||
bool BLECharacteristic::add_descriptor(BLEDescriptor &descriptor) {
|
||||
// Bound until removed or the parent is destroyed
|
||||
if (descriptor.characteristic_ != nullptr) {
|
||||
ESP_LOGE(TAG, "Already added");
|
||||
return false;
|
||||
}
|
||||
descriptor.characteristic_ = this;
|
||||
void BLECharacteristic::add_descriptor(BLEDescriptor *descriptor) {
|
||||
// If the descriptor is the CCCD descriptor, listen to its write event to know if the client wants to be notified
|
||||
if (descriptor.get_uuid() == ESPBTUUID::from_uint16(ESP_GATT_UUID_CHAR_CLIENT_CONFIG)) {
|
||||
descriptor.on_write([this](std::span<const uint8_t> value, uint16_t conn_id) {
|
||||
if (descriptor->get_uuid() == ESPBTUUID::from_uint16(ESP_GATT_UUID_CHAR_CLIENT_CONFIG)) {
|
||||
descriptor->on_write([this](std::span<const uint8_t> value, uint16_t conn_id) {
|
||||
if (value.size() != 2)
|
||||
return;
|
||||
uint16_t cccd = encode_uint16(value[1], value[0]);
|
||||
@@ -120,18 +96,16 @@ bool BLECharacteristic::add_descriptor(BLEDescriptor &descriptor) {
|
||||
}
|
||||
});
|
||||
}
|
||||
this->descriptors_.push_back(&descriptor);
|
||||
return true;
|
||||
this->descriptors_.push_back(descriptor);
|
||||
}
|
||||
|
||||
void BLECharacteristic::remove_descriptor(BLEDescriptor *descriptor) {
|
||||
if (std::erase(this->descriptors_, descriptor) == 0)
|
||||
return;
|
||||
descriptor->owned_ = false; // the caller owns it again
|
||||
descriptor->characteristic_ = nullptr;
|
||||
this->descriptors_.erase(std::remove(this->descriptors_.begin(), this->descriptors_.end(), descriptor),
|
||||
this->descriptors_.end());
|
||||
}
|
||||
|
||||
void BLECharacteristic::do_create() {
|
||||
void BLECharacteristic::do_create(BLEService *service) {
|
||||
this->service_ = service;
|
||||
esp_attr_control_t control;
|
||||
control.auto_rsp = ESP_GATT_RSP_BY_APP;
|
||||
|
||||
@@ -142,9 +116,8 @@ void BLECharacteristic::do_create() {
|
||||
#endif
|
||||
|
||||
esp_bt_uuid_t uuid = this->uuid_.get_uuid();
|
||||
esp_err_t err =
|
||||
esp_ble_gatts_add_char(this->service_->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
|
||||
this->properties_, nullptr, &control);
|
||||
esp_err_t err = esp_ble_gatts_add_char(service->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
|
||||
this->properties_, nullptr, &control);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "esp_ble_gatts_add_char failed: %d", err);
|
||||
@@ -215,15 +188,11 @@ void BLECharacteristic::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt
|
||||
break;
|
||||
}
|
||||
case ESP_GATTS_ADD_CHAR_EVT: {
|
||||
// Only while creating, in its own service: a late event for a removed service or a same-UUID
|
||||
// characteristic elsewhere must not set the handle or start the descriptors
|
||||
if (this->state_ == CREATING && this->service_ != nullptr &&
|
||||
this->service_->get_handle() == param->add_char.service_handle &&
|
||||
this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
|
||||
if (this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
|
||||
this->handle_ = param->add_char.attr_handle;
|
||||
|
||||
for (auto *descriptor : this->descriptors_) {
|
||||
descriptor->do_create();
|
||||
descriptor->do_create(this);
|
||||
}
|
||||
|
||||
this->state_ = CREATING_DEPENDENTS;
|
||||
|
||||
@@ -25,8 +25,6 @@ using namespace bytebuffer;
|
||||
class BLEService;
|
||||
|
||||
class BLECharacteristic final {
|
||||
friend class BLEService;
|
||||
|
||||
public:
|
||||
BLECharacteristic(ESPBTUUID uuid, uint32_t properties, esp_gatt_perm_t permissions);
|
||||
~BLECharacteristic();
|
||||
@@ -46,18 +44,11 @@ class BLECharacteristic final {
|
||||
|
||||
void notify();
|
||||
|
||||
void do_create();
|
||||
void do_delete();
|
||||
void do_create(BLEService *service);
|
||||
void do_delete() { this->clients_to_notify_.clear(); }
|
||||
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
|
||||
|
||||
/// Takes ownership of a heap-allocated descriptor and frees it with this characteristic.
|
||||
void add_descriptor(BLEDescriptor *descriptor) {
|
||||
if (this->add_descriptor(*descriptor))
|
||||
descriptor->owned_ = true;
|
||||
}
|
||||
/// Adds a descriptor the caller keeps alive (such as a component member); it is never freed here.
|
||||
/// False when it already belongs to a characteristic.
|
||||
bool add_descriptor(BLEDescriptor &descriptor);
|
||||
void add_descriptor(BLEDescriptor *descriptor);
|
||||
void remove_descriptor(BLEDescriptor *descriptor);
|
||||
|
||||
BLEService *get_service() { return this->service_; }
|
||||
@@ -115,8 +106,6 @@ class BLECharacteristic final {
|
||||
CREATING_DEPENDENTS,
|
||||
CREATED,
|
||||
} state_{INIT};
|
||||
// Set by BLEService::create_characteristic(), which allocates it; the service frees it
|
||||
bool owned_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::esp32_ble_server
|
||||
|
||||
@@ -27,7 +27,8 @@ BLEDescriptor::BLEDescriptor(ESPBTUUID uuid, uint16_t max_len, esp_gatt_perm_t p
|
||||
|
||||
BLEDescriptor::~BLEDescriptor() { free(this->value_.attr_value); } // NOLINT
|
||||
|
||||
void BLEDescriptor::do_create() {
|
||||
void BLEDescriptor::do_create(BLECharacteristic *characteristic) {
|
||||
this->characteristic_ = characteristic;
|
||||
esp_attr_control_t control;
|
||||
control.auto_rsp = ESP_GATT_AUTO_RSP;
|
||||
|
||||
@@ -65,8 +66,7 @@ void BLEDescriptor::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_
|
||||
esp_ble_gatts_cb_param_t *param) {
|
||||
switch (event) {
|
||||
case ESP_GATTS_ADD_CHAR_DESCR_EVT: {
|
||||
// Bound by add_descriptor(), so only a descriptor do_create() is creating may claim the event
|
||||
if (this->state_ == CREATING && this->uuid_ == ESPBTUUID::from_uuid(param->add_char_descr.descr_uuid) &&
|
||||
if (this->characteristic_ != nullptr && this->uuid_ == ESPBTUUID::from_uuid(param->add_char_descr.descr_uuid) &&
|
||||
this->characteristic_->get_service()->get_handle() == param->add_char_descr.service_handle &&
|
||||
this->characteristic_ == this->characteristic_->get_service()->get_last_created_characteristic()) {
|
||||
this->handle_ = param->add_char_descr.attr_handle;
|
||||
|
||||
@@ -20,13 +20,11 @@ class BLECharacteristic;
|
||||
|
||||
// Base class for BLE descriptors
|
||||
class BLEDescriptor {
|
||||
friend class BLECharacteristic;
|
||||
|
||||
public:
|
||||
BLEDescriptor(ESPBTUUID uuid, uint16_t max_len = 100, bool read = true, bool write = true);
|
||||
BLEDescriptor(ESPBTUUID uuid, uint16_t max_len, esp_gatt_perm_t permissions);
|
||||
virtual ~BLEDescriptor();
|
||||
void do_create();
|
||||
void do_create(BLECharacteristic *characteristic);
|
||||
ESPBTUUID get_uuid() const { return this->uuid_; }
|
||||
|
||||
void set_value(const uint8_t *data, size_t length);
|
||||
@@ -62,8 +60,6 @@ class BLEDescriptor {
|
||||
CREATING,
|
||||
CREATED,
|
||||
} state_{INIT};
|
||||
// Set when the characteristic took ownership through add_descriptor(BLEDescriptor *) and frees it
|
||||
bool owned_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::esp32_ble_server
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
#include "ble_server.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/components/ble_device_base/ble_device.h"
|
||||
#include "esphome/components/esp32_ble/ble.h"
|
||||
#include "esphome/core/log.h"
|
||||
@@ -125,52 +123,31 @@ void BLEServer::release_advertising_() {
|
||||
}
|
||||
|
||||
BLEService *BLEServer::create_service(ESPBTUUID uuid, bool advertise, uint16_t num_handles) {
|
||||
// Checked before allocating, so a failure never deletes a service and pulls in its destructor
|
||||
const uint8_t inst_id = this->free_inst_id_(uuid);
|
||||
if (inst_id == INVALID_INST_ID)
|
||||
return nullptr;
|
||||
auto *service = new BLEService(uuid, num_handles, advertise); // NOLINT(cppcoreguidelines-owning-memory)
|
||||
this->register_service_(*service, inst_id, true);
|
||||
return service;
|
||||
}
|
||||
|
||||
bool BLEServer::add_service(BLEService &service) {
|
||||
// Adding it twice would free or start it twice
|
||||
for (auto &entry : this->services_) {
|
||||
if (entry.service == &service) {
|
||||
ESP_LOGE(TAG, "Already added");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const uint8_t inst_id = this->free_inst_id_(service.get_uuid());
|
||||
if (inst_id == INVALID_INST_ID)
|
||||
return false;
|
||||
this->register_service_(service, inst_id, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
uint8_t BLEServer::free_inst_id_(const ESPBTUUID &uuid) {
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
|
||||
char uuid_buf[esp32_ble::UUID_STR_LEN];
|
||||
uuid.to_str(uuid_buf);
|
||||
ESP_LOGV(TAG, "Adding BLE service - %s", uuid_buf);
|
||||
ESP_LOGV(TAG, "Creating BLE service - %s", uuid_buf);
|
||||
#endif
|
||||
for (uint8_t inst_id = 0; inst_id < INVALID_INST_ID; inst_id++) {
|
||||
if (this->get_service(uuid, inst_id) == nullptr)
|
||||
return inst_id;
|
||||
// Calculate the inst_id for the service
|
||||
uint8_t inst_id = 0;
|
||||
for (; inst_id < 0xFF; inst_id++) {
|
||||
if (this->get_service(uuid, inst_id) == nullptr) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
char warn_uuid_buf[esp32_ble::UUID_STR_LEN];
|
||||
uuid.to_str(warn_uuid_buf);
|
||||
ESP_LOGW(TAG, "Could not create BLE service %s, too many instances", warn_uuid_buf);
|
||||
return INVALID_INST_ID;
|
||||
}
|
||||
|
||||
void BLEServer::register_service_(BLEService &service, uint8_t inst_id, bool owned) {
|
||||
service.inst_id_ = inst_id;
|
||||
this->services_.push_back({service.get_uuid(), inst_id, owned, &service});
|
||||
if (inst_id == 0xFF) {
|
||||
char warn_uuid_buf[esp32_ble::UUID_STR_LEN];
|
||||
uuid.to_str(warn_uuid_buf);
|
||||
ESP_LOGW(TAG, "Could not create BLE service %s, too many instances", warn_uuid_buf);
|
||||
return nullptr;
|
||||
}
|
||||
BLEService *service = // NOLINT(cppcoreguidelines-owning-memory)
|
||||
new BLEService(uuid, num_handles, inst_id, advertise);
|
||||
this->services_.push_back({uuid, inst_id, service});
|
||||
if (this->parent_->is_active() && this->registered_) {
|
||||
service.do_create(this);
|
||||
service->do_create(this);
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
void BLEServer::remove_service(ESPBTUUID uuid, uint8_t inst_id) {
|
||||
@@ -182,10 +159,7 @@ void BLEServer::remove_service(ESPBTUUID uuid, uint8_t inst_id) {
|
||||
for (auto it = this->services_.begin(); it != this->services_.end(); ++it) {
|
||||
if (it->uuid == uuid && it->inst_id == inst_id) {
|
||||
it->service->do_delete();
|
||||
// A service still waiting to start must not stay queued once it is unregistered or freed
|
||||
std::erase(this->services_to_start_, it->service);
|
||||
if (it->owned)
|
||||
delete it->service; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
delete it->service; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
this->services_.erase(it);
|
||||
return;
|
||||
}
|
||||
@@ -245,15 +219,6 @@ void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t ga
|
||||
for (size_t i = 0; i < this->services_.size(); i++) { // NOLINT(modernize-loop-convert)
|
||||
this->services_[i].service->gatts_event_handler(event, gatts_if, param);
|
||||
}
|
||||
// A service this server asked for but removed while the stack was still creating it is deleted once its handle
|
||||
// arrives; services of other GATT applications are left alone
|
||||
if (event == ESP_GATTS_CREATE_EVT && gatts_if == this->gatts_if_ && param->create.status == ESP_GATT_OK) {
|
||||
for (auto &entry : this->services_) {
|
||||
if (entry.service->get_handle() == param->create.service_handle)
|
||||
return;
|
||||
}
|
||||
esp_ble_gatts_delete_service(param->create.service_handle);
|
||||
}
|
||||
}
|
||||
|
||||
int8_t BLEServer::find_client_index_(uint16_t conn_id) const {
|
||||
|
||||
@@ -49,10 +49,6 @@ class BLEServer final : public Component, public Parented<ESP32BLE> {
|
||||
uint8_t get_max_clients() const { return this->max_clients_; }
|
||||
|
||||
BLEService *create_service(ESPBTUUID uuid, bool advertise = false, uint16_t num_handles = 15);
|
||||
/// Adds a service the caller keeps alive (such as a component member); remove_service() never frees it.
|
||||
/// Do not add it again after remove_service(). Returns false when it is already added or the UUID already has
|
||||
/// 255 instances.
|
||||
bool add_service(BLEService &service);
|
||||
void remove_service(ESPBTUUID uuid, uint8_t inst_id = 0);
|
||||
BLEService *get_service(ESPBTUUID uuid, uint8_t inst_id = 0);
|
||||
void enqueue_start_service(BLEService *service) { this->services_to_start_.push_back(service); }
|
||||
@@ -118,13 +114,9 @@ class BLEServer final : public Component, public Parented<ESP32BLE> {
|
||||
struct ServiceEntry {
|
||||
ESPBTUUID uuid;
|
||||
uint8_t inst_id;
|
||||
bool owned; // allocated by create_service(), freed by remove_service()
|
||||
BLEService *service;
|
||||
};
|
||||
|
||||
static constexpr uint8_t INVALID_INST_ID = 0xFF;
|
||||
uint8_t free_inst_id_(const ESPBTUUID &uuid);
|
||||
void register_service_(BLEService &service, uint8_t inst_id, bool owned);
|
||||
void restart_advertising_();
|
||||
void request_advertising_();
|
||||
void release_advertising_();
|
||||
|
||||
@@ -12,25 +12,8 @@ BLEService::BLEService(ESPBTUUID uuid, uint16_t num_handles, uint8_t inst_id, bo
|
||||
: uuid_(uuid), num_handles_(num_handles), inst_id_(inst_id), advertise_(advertise) {}
|
||||
|
||||
BLEService::~BLEService() {
|
||||
for (auto *chr : this->characteristics_) {
|
||||
if (chr->owned_) {
|
||||
delete chr; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
} else if (chr->service_ == this) {
|
||||
// A caller-owned characteristic outlives this service, and may already belong to another one
|
||||
chr->service_ = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool BLEService::add_characteristic(BLECharacteristic &characteristic) {
|
||||
// Bound until the parent is destroyed
|
||||
if (characteristic.service_ != nullptr) {
|
||||
ESP_LOGE(TAG, "Already added");
|
||||
return false;
|
||||
}
|
||||
characteristic.service_ = this;
|
||||
this->characteristics_.push_back(&characteristic);
|
||||
return true;
|
||||
for (auto &chr : this->characteristics_)
|
||||
delete chr; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
}
|
||||
|
||||
BLECharacteristic *BLEService::get_characteristic(ESPBTUUID uuid) {
|
||||
@@ -56,8 +39,7 @@ BLECharacteristic *BLEService::create_characteristic(ESPBTUUID uuid, esp_gatt_ch
|
||||
esp_gatt_perm_t permissions) {
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
|
||||
BLECharacteristic *characteristic = new BLECharacteristic(uuid, properties, permissions);
|
||||
characteristic->owned_ = true;
|
||||
this->add_characteristic(*characteristic);
|
||||
this->characteristics_.push_back(characteristic);
|
||||
return characteristic;
|
||||
}
|
||||
|
||||
@@ -87,14 +69,8 @@ void BLEService::do_delete() {
|
||||
// Call all characteristics to delete
|
||||
for (auto *characteristic : this->characteristics_)
|
||||
characteristic->do_delete();
|
||||
// Not created on the stack yet; if a create is in flight, the server deletes it when its handle arrives
|
||||
if (this->handle_ == 0xFFFF) {
|
||||
this->state_ = DELETED;
|
||||
return;
|
||||
}
|
||||
this->stop_();
|
||||
esp_err_t err = esp_ble_gatts_delete_service(this->handle_);
|
||||
this->handle_ = 0xFFFF; // a later add creates it again with a new handle
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "esp_ble_gatts_delete_service failed: %d", err);
|
||||
return;
|
||||
@@ -111,7 +87,7 @@ bool BLEService::do_create_characteristics_() {
|
||||
|
||||
auto *characteristic = this->characteristics_[this->created_characteristic_count_++];
|
||||
this->last_created_characteristic_ = characteristic;
|
||||
characteristic->do_create();
|
||||
characteristic->do_create(this);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -164,7 +140,7 @@ void BLEService::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t g
|
||||
esp_ble_gatts_cb_param_t *param) {
|
||||
switch (event) {
|
||||
case ESP_GATTS_CREATE_EVT: {
|
||||
if (this->state_ == CREATING && this->uuid_ == ESPBTUUID::from_uuid(param->create.service_id.id.uuid) &&
|
||||
if (this->uuid_ == ESPBTUUID::from_uuid(param->create.service_id.id.uuid) &&
|
||||
this->inst_id_ == param->create.service_id.id.inst_id) {
|
||||
this->handle_ = param->create.service_handle;
|
||||
this->state_ = CREATED;
|
||||
|
||||
@@ -20,12 +20,8 @@ class BLEServer;
|
||||
using namespace esp32_ble;
|
||||
|
||||
class BLEService final {
|
||||
friend class BLEServer;
|
||||
|
||||
public:
|
||||
BLEService(ESPBTUUID uuid, uint16_t num_handles, uint8_t inst_id, bool advertise);
|
||||
/// The server picks the instance id when the service is added.
|
||||
BLEService(ESPBTUUID uuid, uint16_t num_handles, bool advertise) : BLEService(uuid, num_handles, 0, advertise) {}
|
||||
~BLEService();
|
||||
BLECharacteristic *get_characteristic(ESPBTUUID uuid);
|
||||
BLECharacteristic *get_characteristic(uint16_t uuid);
|
||||
@@ -36,8 +32,6 @@ class BLEService final {
|
||||
esp_gatt_perm_t permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE);
|
||||
BLECharacteristic *create_characteristic(ESPBTUUID uuid, esp_gatt_char_prop_t properties,
|
||||
esp_gatt_perm_t permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE);
|
||||
/// Adds a characteristic the caller keeps alive; it is never freed here. False when it already belongs to a service.
|
||||
bool add_characteristic(BLECharacteristic &characteristic);
|
||||
|
||||
ESPBTUUID get_uuid() { return this->uuid_; }
|
||||
uint8_t get_inst_id() { return this->inst_id_; }
|
||||
|
||||
@@ -4,13 +4,22 @@ import esphome.codegen as cg
|
||||
from esphome.components import time, uart
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_SENSOR_DATAPOINT, CONF_TIME_ID
|
||||
from esphome.core import CORE, CoroPriority, coroutine_with_priority
|
||||
from esphome.core import CORE, AutoLoad, CoroPriority, coroutine_with_priority
|
||||
from esphome.cpp_generator import MockObj
|
||||
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor
|
||||
from esphome.types import ConfigType
|
||||
|
||||
DEPENDENCIES = ["uart"]
|
||||
CODEOWNERS = ["@dwmw2", "@ssieb"]
|
||||
DOMAIN = "tuya"
|
||||
|
||||
|
||||
# AutoLoad: another transport pulled in only the base class. None: CI dependency probe.
|
||||
def AUTO_LOAD(config: ConfigType | AutoLoad | None) -> list[str]:
|
||||
if isinstance(config, AutoLoad):
|
||||
return []
|
||||
return ["uart"]
|
||||
|
||||
|
||||
CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS = "ignore_mcu_update_on_datapoints"
|
||||
|
||||
CONF_ON_DATAPOINT_UPDATE = "on_datapoint_update"
|
||||
@@ -20,7 +29,8 @@ CONF_FORCE_TIME_SYNC = "force_time_sync"
|
||||
|
||||
tuya_ns = cg.esphome_ns.namespace("tuya")
|
||||
TuyaDatapointType = tuya_ns.enum("TuyaDatapointType", is_class=True)
|
||||
Tuya = tuya_ns.class_("Tuya", cg.Component, uart.UARTDevice)
|
||||
Tuya = tuya_ns.class_("Tuya", cg.Component)
|
||||
TuyaUART = tuya_ns.class_("TuyaUART", Tuya, uart.UARTDevice)
|
||||
|
||||
TuyaDatapoint = tuya_ns.struct("TuyaDatapoint")
|
||||
|
||||
@@ -72,42 +82,50 @@ def _validate_time_options(config: ConfigType) -> ConfigType:
|
||||
return config
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
TUYA_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.Optional(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS): cv.ensure_list(cv.uint8_t),
|
||||
cv.Optional(CONF_ON_DATAPOINT_UPDATE): automation.validate_automation(
|
||||
{
|
||||
cv.Required(CONF_SENSOR_DATAPOINT): cv.uint8_t,
|
||||
cv.Optional(CONF_DATAPOINT_TYPE, default=DPTYPE_ANY): cv.one_of(
|
||||
*DATAPOINT_TYPES, lower=True
|
||||
),
|
||||
}
|
||||
),
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA)
|
||||
|
||||
UART_SCHEMA = cv.All(
|
||||
TUYA_SCHEMA.extend(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(Tuya),
|
||||
cv.GenerateID(): cv.declare_id(TuyaUART),
|
||||
cv.Optional(CONF_TIME_ID): cv.use_id(time.RealTimeClock),
|
||||
cv.Optional(CONF_FORCE_TIME_SYNC, default=False): cv.boolean,
|
||||
cv.Optional(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS): cv.ensure_list(
|
||||
cv.uint8_t
|
||||
),
|
||||
cv.Optional(CONF_STATUS_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_ON_DATAPOINT_UPDATE): automation.validate_automation(
|
||||
{
|
||||
cv.Required(CONF_SENSOR_DATAPOINT): cv.uint8_t,
|
||||
cv.Optional(CONF_DATAPOINT_TYPE, default=DPTYPE_ANY): cv.one_of(
|
||||
*DATAPOINT_TYPES, lower=True
|
||||
),
|
||||
}
|
||||
),
|
||||
}
|
||||
)
|
||||
.extend(cv.COMPONENT_SCHEMA)
|
||||
.extend(uart.UART_DEVICE_SCHEMA),
|
||||
).extend(uart.UART_DEVICE_SCHEMA),
|
||||
_validate_time_options,
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
var = await uart.new_uart_component(config)
|
||||
if (time_id := config.get(CONF_TIME_ID)) is not None:
|
||||
await cg.add_variable(var.set_time_id, time_id)
|
||||
if config[CONF_FORCE_TIME_SYNC]:
|
||||
cg.add(var.set_force_time_sync(True))
|
||||
await cg.add_pin(var.set_status_pin, config.get(CONF_STATUS_PIN))
|
||||
if CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS in config:
|
||||
for dp in config[CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS]:
|
||||
cg.add(var.add_ignore_mcu_update_on_datapoints(dp))
|
||||
@schema_extractor("schema")
|
||||
def _validate_config(value: ConfigType | AutoLoad) -> ConfigType | AutoLoad | cv.Schema:
|
||||
if value is SCHEMA_EXTRACT:
|
||||
# Expose the UART schema to the language-schema dumper
|
||||
return UART_SCHEMA
|
||||
if isinstance(value, AutoLoad):
|
||||
return value
|
||||
return UART_SCHEMA(value)
|
||||
|
||||
|
||||
CONFIG_SCHEMA = _validate_config
|
||||
|
||||
|
||||
async def setup_tuya(var: MockObj, config: ConfigType) -> None:
|
||||
"""Apply the base-class options; called from a transport's to_code()."""
|
||||
for dp in config.get(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS, []):
|
||||
cg.add(var.add_ignore_mcu_update_on_datapoints(dp))
|
||||
for conf in config.get(CONF_ON_DATAPOINT_UPDATE, []):
|
||||
type_, expected, field = DATAPOINT_TYPES[conf[CONF_DATAPOINT_TYPE]]
|
||||
forward = None
|
||||
@@ -117,3 +135,23 @@ async def to_code(config):
|
||||
[(type_, "x")], conf, params=[(TuyaDatapoint, "x")], forward=forward
|
||||
)
|
||||
cg.add(var.register_listener(conf[CONF_SENSOR_DATAPOINT], callback))
|
||||
|
||||
|
||||
async def to_code(config: ConfigType | AutoLoad) -> None:
|
||||
if isinstance(config, AutoLoad):
|
||||
return
|
||||
|
||||
var = await uart.new_uart_component(config)
|
||||
if (time_id := config.get(CONF_TIME_ID)) is not None:
|
||||
await cg.add_variable(var.set_time_id, time_id)
|
||||
if config[CONF_FORCE_TIME_SYNC]:
|
||||
cg.add(var.set_force_time_sync(True))
|
||||
await cg.add_pin(var.set_status_pin, config.get(CONF_STATUS_PIN))
|
||||
await setup_tuya(var, config)
|
||||
|
||||
|
||||
def FILTER_SOURCE_FILES() -> list[str]:
|
||||
# When only auto-loaded as a base class, the UART implementation is unused
|
||||
if isinstance(CORE.config.get(DOMAIN), AutoLoad):
|
||||
return ["tuya_uart.cpp", "tuya_uart.h"]
|
||||
return []
|
||||
@@ -1,85 +1,13 @@
|
||||
#include "tuya.h"
|
||||
#include <cstring>
|
||||
#include "esphome/core/gpio.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/util.h"
|
||||
|
||||
#ifdef USE_NETWORK
|
||||
#include "esphome/components/network/util.h"
|
||||
#endif
|
||||
|
||||
#ifdef USE_WIFI
|
||||
#include "esphome/components/wifi/wifi_component.h"
|
||||
#endif
|
||||
|
||||
#ifdef USE_CAPTIVE_PORTAL
|
||||
#include "esphome/components/captive_portal/captive_portal.h"
|
||||
#endif
|
||||
|
||||
namespace esphome::tuya {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "tuya");
|
||||
|
||||
static constexpr uint32_t HEARTBEAT_INTERVAL_ID = 0;
|
||||
static constexpr uint32_t WIFI_STATUS_INTERVAL_ID = 1;
|
||||
static constexpr uint32_t DATAPOINT_DUMP_TIMEOUT_ID = 2;
|
||||
static constexpr uint32_t FORCE_TIME_SYNC_INTERVAL_ID = 3;
|
||||
static const int COMMAND_DELAY = 10;
|
||||
static const int RECEIVE_TIMEOUT = 300;
|
||||
static const int MAX_RETRIES = 5;
|
||||
// Max bytes to log for datapoint values (larger values are truncated)
|
||||
static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
|
||||
static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
|
||||
|
||||
static bool network_is_connected() {
|
||||
#ifdef USE_NETWORK
|
||||
return network::is_connected();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void Tuya::setup() {
|
||||
this->set_interval(HEARTBEAT_INTERVAL_ID, 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
|
||||
#ifdef USE_TIME
|
||||
if (this->force_time_sync_) {
|
||||
this->register_local_time_sync_callback_();
|
||||
this->set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
|
||||
[this] { this->check_force_time_sync_(); });
|
||||
}
|
||||
#endif
|
||||
if (this->status_pin_ != nullptr) {
|
||||
this->status_pin_->digital_write(false);
|
||||
}
|
||||
}
|
||||
|
||||
void Tuya::loop() {
|
||||
this->read_available([this](uint8_t b) { this->handle_char_(b); });
|
||||
process_command_queue_();
|
||||
}
|
||||
|
||||
void Tuya::dump_config() {
|
||||
this->dump_mcu_config_();
|
||||
#ifdef USE_TUYA_DUMP_PUBLISHER
|
||||
if (this->dump_publisher_ != nullptr)
|
||||
this->dump_publisher_();
|
||||
#endif
|
||||
}
|
||||
|
||||
// Also logged again once the MCU reports its datapoints
|
||||
void Tuya::dump_mcu_config_() {
|
||||
ESP_LOGCONFIG(TAG, "Tuya:");
|
||||
if (this->init_state_ != TuyaInitState::INIT_DONE) {
|
||||
if (this->init_failed_) {
|
||||
ESP_LOGCONFIG(TAG, " Initialization failed. Current init_state: %u", static_cast<uint8_t>(this->init_state_));
|
||||
} else {
|
||||
ESP_LOGCONFIG(TAG, " Configuration will be reported when setup is complete. Current init_state: %u",
|
||||
static_cast<uint8_t>(this->init_state_));
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " If no further output is received, confirm that this is a supported Tuya device.");
|
||||
return;
|
||||
}
|
||||
void Tuya::dump_datapoints_() {
|
||||
for (auto &info : this->datapoints_) {
|
||||
if (info.type == TuyaDatapointType::RAW) {
|
||||
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
|
||||
@@ -99,595 +27,36 @@ void Tuya::dump_mcu_config_() {
|
||||
ESP_LOGCONFIG(TAG, " Datapoint %u: unknown", info.id);
|
||||
}
|
||||
}
|
||||
if ((this->status_pin_reported_ != -1) || (this->reset_pin_reported_ != -1)) {
|
||||
ESP_LOGCONFIG(TAG, " GPIO Configuration: status: pin %d, reset: pin %d", this->status_pin_reported_,
|
||||
this->reset_pin_reported_);
|
||||
}
|
||||
LOG_PIN(" Status Pin: ", this->status_pin_);
|
||||
ESP_LOGCONFIG(TAG, " Product: '%s'",
|
||||
this->product_invalid_ ? LOG_STR_LITERAL(R"({"p":"INVALID"})")
|
||||
: (this->product_ ? this->product_.get() : LOG_STR_LITERAL("")));
|
||||
#ifdef USE_TIME
|
||||
if (this->time_id_ != nullptr) {
|
||||
ESP_LOGCONFIG(TAG, " Force time sync: %s", YESNO(this->force_time_sync_));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool Tuya::validate_message_() {
|
||||
uint32_t at = this->rx_message_.size() - 1;
|
||||
auto *data = &this->rx_message_[0];
|
||||
uint8_t new_byte = data[at];
|
||||
|
||||
// Byte 0: HEADER1 (always 0x55)
|
||||
if (at == 0)
|
||||
return new_byte == 0x55;
|
||||
// Byte 1: HEADER2 (always 0xAA)
|
||||
if (at == 1)
|
||||
return new_byte == 0xAA;
|
||||
|
||||
// Byte 2: VERSION
|
||||
// no validation for the following fields:
|
||||
uint8_t version = data[2];
|
||||
if (at == 2)
|
||||
return true;
|
||||
// Byte 3: COMMAND
|
||||
uint8_t command = data[3];
|
||||
if (at == 3)
|
||||
return true;
|
||||
|
||||
// Byte 4: LENGTH1
|
||||
// Byte 5: LENGTH2
|
||||
if (at <= 5) {
|
||||
// no validation for these fields
|
||||
return true;
|
||||
}
|
||||
|
||||
uint16_t length = encode_uint16(data[4], data[5]);
|
||||
|
||||
// wait until all data is read
|
||||
if (at - 6 < length)
|
||||
return true;
|
||||
|
||||
// Byte 6+LEN: CHECKSUM - sum of all bytes (including header) modulo 256
|
||||
uint8_t rx_checksum = new_byte;
|
||||
const uint8_t calc_checksum = sum_bytes(data, 6 + length);
|
||||
|
||||
if (rx_checksum != calc_checksum) {
|
||||
ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
|
||||
return false;
|
||||
}
|
||||
|
||||
// valid message
|
||||
const uint8_t *message_data = data + 6;
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
|
||||
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
|
||||
ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
|
||||
format_hex_pretty_to(hex_buf, message_data, length), static_cast<uint8_t>(this->init_state_));
|
||||
#endif
|
||||
this->handle_command_(command, version, message_data, length);
|
||||
|
||||
// return false to reset rx buffer
|
||||
return false;
|
||||
}
|
||||
|
||||
void Tuya::handle_char_(uint8_t c) {
|
||||
this->rx_message_.push_back(c);
|
||||
if (!this->validate_message_()) {
|
||||
this->rx_message_.clear();
|
||||
} else {
|
||||
this->last_rx_char_timestamp_ = millis();
|
||||
}
|
||||
}
|
||||
|
||||
void Tuya::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
|
||||
TuyaCommandType command_type = (TuyaCommandType) command;
|
||||
|
||||
if (this->expected_response_.has_value() && this->expected_response_ == command_type) {
|
||||
this->expected_response_.reset();
|
||||
this->command_queue_.erase(command_queue_.begin());
|
||||
this->init_retries_ = 0;
|
||||
}
|
||||
|
||||
switch (command_type) {
|
||||
case TuyaCommandType::HEARTBEAT:
|
||||
ESP_LOGV(TAG, "MCU Heartbeat (0x%02X)", buffer[0]);
|
||||
this->protocol_version_ = version;
|
||||
if (buffer[0] == 0) {
|
||||
ESP_LOGI(TAG, "MCU restarted");
|
||||
this->init_state_ = TuyaInitState::INIT_HEARTBEAT;
|
||||
}
|
||||
if (this->init_state_ == TuyaInitState::INIT_HEARTBEAT) {
|
||||
this->init_state_ = TuyaInitState::INIT_PRODUCT;
|
||||
this->send_empty_command_(TuyaCommandType::PRODUCT_QUERY);
|
||||
}
|
||||
break;
|
||||
case TuyaCommandType::PRODUCT_QUERY: {
|
||||
// check it is a valid string made up of printable characters
|
||||
bool valid = true;
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
if (!std::isprint(buffer[i])) {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (valid) {
|
||||
this->product_ = std::make_unique<char[]>(len + 1);
|
||||
memcpy(this->product_.get(), buffer, len);
|
||||
} else {
|
||||
this->product_.reset();
|
||||
}
|
||||
this->product_invalid_ = !valid;
|
||||
if (this->init_state_ == TuyaInitState::INIT_PRODUCT) {
|
||||
this->init_state_ = TuyaInitState::INIT_CONF;
|
||||
this->send_empty_command_(TuyaCommandType::CONF_QUERY);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case TuyaCommandType::CONF_QUERY: {
|
||||
if (len >= 2) {
|
||||
this->status_pin_reported_ = buffer[0];
|
||||
this->reset_pin_reported_ = buffer[1];
|
||||
}
|
||||
if (this->init_state_ == TuyaInitState::INIT_CONF) {
|
||||
// If mcu returned status gpio, then we can omit sending wifi state
|
||||
if (this->status_pin_reported_ != -1) {
|
||||
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
|
||||
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
|
||||
if (this->status_pin_ != nullptr) {
|
||||
if (this->status_pin_->get_pin() != this->status_pin_reported_) {
|
||||
ESP_LOGW(TAG, "Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
|
||||
this->status_pin_reported_);
|
||||
}
|
||||
ESP_LOGV(TAG, "Configured status pin %i", this->status_pin_->get_pin());
|
||||
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->set_status_pin_(); });
|
||||
} else {
|
||||
ESP_LOGW(TAG, "MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
|
||||
this->status_pin_reported_);
|
||||
}
|
||||
} else {
|
||||
this->init_state_ = TuyaInitState::INIT_WIFI;
|
||||
ESP_LOGV(TAG, "Configured WIFI_STATE periodic send");
|
||||
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->send_wifi_status_(); });
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case TuyaCommandType::WIFI_STATE:
|
||||
if (this->init_state_ == TuyaInitState::INIT_WIFI) {
|
||||
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
|
||||
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
|
||||
}
|
||||
break;
|
||||
case TuyaCommandType::WIFI_SELECT:
|
||||
case TuyaCommandType::WIFI_RESET: {
|
||||
const bool is_select = (len >= 1);
|
||||
// Send WIFI_SELECT ACK
|
||||
TuyaCommand ack;
|
||||
ack.cmd = is_select ? TuyaCommandType::WIFI_SELECT : TuyaCommandType::WIFI_RESET;
|
||||
ack.payload.clear();
|
||||
this->send_command_(ack);
|
||||
// Establish pairing mode for correct first WIFI_STATE byte, EZ (0x00) default
|
||||
uint8_t first = 0x00;
|
||||
const char *mode_str = "EZ";
|
||||
if (is_select && buffer[0] == 0x01) {
|
||||
first = 0x01;
|
||||
mode_str = "AP";
|
||||
}
|
||||
// Send WIFI_STATE response, MCU exits pairing mode
|
||||
TuyaCommand st;
|
||||
st.cmd = TuyaCommandType::WIFI_STATE;
|
||||
st.payload.resize(1);
|
||||
st.payload[0] = first;
|
||||
this->send_command_(st);
|
||||
st.payload[0] = 0x02;
|
||||
this->send_command_(st);
|
||||
st.payload[0] = 0x03;
|
||||
this->send_command_(st);
|
||||
st.payload[0] = 0x04;
|
||||
this->send_command_(st);
|
||||
ESP_LOGI(TAG, "%s received (%s), replied with WIFI_STATE confirming connection established",
|
||||
is_select ? LOG_STR_LITERAL("WIFI_SELECT") : LOG_STR_LITERAL("WIFI_RESET"), mode_str);
|
||||
break;
|
||||
}
|
||||
case TuyaCommandType::DATAPOINT_DELIVER:
|
||||
break;
|
||||
case TuyaCommandType::DATAPOINT_REPORT_ASYNC:
|
||||
case TuyaCommandType::DATAPOINT_REPORT_SYNC:
|
||||
if (this->init_state_ == TuyaInitState::INIT_DATAPOINT) {
|
||||
this->init_state_ = TuyaInitState::INIT_DONE;
|
||||
this->set_timeout(DATAPOINT_DUMP_TIMEOUT_ID, 1000, [this] { this->dump_mcu_config_(); });
|
||||
this->initialized_callback_.call();
|
||||
}
|
||||
this->handle_datapoints_(buffer, len);
|
||||
|
||||
if (command_type == TuyaCommandType::DATAPOINT_REPORT_SYNC) {
|
||||
this->send_command_(
|
||||
TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_REPORT_ACK, .payload = std::vector<uint8_t>{0x01}});
|
||||
}
|
||||
break;
|
||||
case TuyaCommandType::DATAPOINT_QUERY:
|
||||
break;
|
||||
case TuyaCommandType::WIFI_TEST:
|
||||
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_TEST, .payload = std::vector<uint8_t>{0x00, 0x00}});
|
||||
break;
|
||||
case TuyaCommandType::WIFI_RSSI:
|
||||
this->send_command_(
|
||||
TuyaCommand{.cmd = TuyaCommandType::WIFI_RSSI, .payload = std::vector<uint8_t>{get_wifi_rssi_()}});
|
||||
break;
|
||||
case TuyaCommandType::LOCAL_TIME_QUERY:
|
||||
#ifdef USE_TIME
|
||||
if (this->time_id_ != nullptr) {
|
||||
this->send_local_time_();
|
||||
this->register_local_time_sync_callback_();
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured");
|
||||
}
|
||||
break;
|
||||
case TuyaCommandType::GMT_TIME_QUERY:
|
||||
#ifdef USE_TIME
|
||||
if (this->time_id_ != nullptr) {
|
||||
this->send_gmt_time_();
|
||||
|
||||
if (!this->gmt_time_sync_callback_registered_) {
|
||||
// tuya mcu supports time, so we let them know when our time changed
|
||||
this->time_id_->add_on_time_sync_callback([this] { this->send_gmt_time_(); });
|
||||
this->gmt_time_sync_callback_registered_ = true;
|
||||
}
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
ESP_LOGW(TAG, "GMT_TIME_QUERY is not handled because time is not configured");
|
||||
}
|
||||
break;
|
||||
case TuyaCommandType::VACUUM_MAP_UPLOAD:
|
||||
this->send_command_(
|
||||
TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector<uint8_t>{0x01}});
|
||||
ESP_LOGW(TAG, "Vacuum map upload requested, responding that it is not enabled.");
|
||||
break;
|
||||
case TuyaCommandType::GET_NETWORK_STATUS: {
|
||||
uint8_t wifi_status = this->get_wifi_status_code_();
|
||||
|
||||
this->send_command_(
|
||||
TuyaCommand{.cmd = TuyaCommandType::GET_NETWORK_STATUS, .payload = std::vector<uint8_t>{wifi_status}});
|
||||
ESP_LOGV(TAG, "Network status requested, reported as %i", wifi_status);
|
||||
break;
|
||||
}
|
||||
case TuyaCommandType::EXTENDED_SERVICES: {
|
||||
uint8_t subcommand = buffer[0];
|
||||
switch ((TuyaExtendedServicesCommandType) subcommand) {
|
||||
case TuyaExtendedServicesCommandType::RESET_NOTIFICATION: {
|
||||
this->send_command_(
|
||||
TuyaCommand{.cmd = TuyaCommandType::EXTENDED_SERVICES,
|
||||
.payload = std::vector<uint8_t>{
|
||||
static_cast<uint8_t>(TuyaExtendedServicesCommandType::RESET_NOTIFICATION), 0x00}});
|
||||
ESP_LOGV(TAG, "Reset status notification enabled");
|
||||
break;
|
||||
}
|
||||
case TuyaExtendedServicesCommandType::MODULE_RESET: {
|
||||
ESP_LOGE(TAG, "EXTENDED_SERVICES::MODULE_RESET is not handled");
|
||||
break;
|
||||
}
|
||||
case TuyaExtendedServicesCommandType::UPDATE_IN_PROGRESS: {
|
||||
ESP_LOGE(TAG, "EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ESP_LOGE(TAG, "Invalid extended services subcommand (0x%02X) received", subcommand);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
|
||||
}
|
||||
}
|
||||
|
||||
void Tuya::handle_datapoints_(const uint8_t *buffer, size_t len) {
|
||||
while (len >= 4) {
|
||||
TuyaDatapoint datapoint{};
|
||||
datapoint.id = buffer[0];
|
||||
datapoint.type = (TuyaDatapointType) buffer[1];
|
||||
datapoint.value_uint = 0;
|
||||
|
||||
size_t data_size = encode_uint16(buffer[2], buffer[3]);
|
||||
const uint8_t *data = buffer + 4;
|
||||
size_t data_len = len - 4;
|
||||
if (data_size > data_len) {
|
||||
ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
|
||||
void Tuya::handle_datapoint_(const TuyaDatapoint &datapoint) {
|
||||
// drop update if datapoint is in ignore_mcu_datapoint_update list
|
||||
for (auto i : this->ignore_mcu_update_on_datapoints_) {
|
||||
if (datapoint.id == i) {
|
||||
ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
|
||||
return;
|
||||
}
|
||||
|
||||
datapoint.len = data_size;
|
||||
|
||||
switch (datapoint.type) {
|
||||
case TuyaDatapointType::RAW:
|
||||
datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
|
||||
{
|
||||
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id,
|
||||
format_hex_pretty_to(hex_buf, datapoint.value_raw.data(), datapoint.value_raw.size()));
|
||||
}
|
||||
break;
|
||||
case TuyaDatapointType::BOOLEAN:
|
||||
if (data_size != 1) {
|
||||
ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
|
||||
return;
|
||||
}
|
||||
datapoint.value_bool = data[0];
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
|
||||
break;
|
||||
case TuyaDatapointType::INTEGER:
|
||||
if (data_size != 4) {
|
||||
ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
|
||||
return;
|
||||
}
|
||||
datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
|
||||
break;
|
||||
case TuyaDatapointType::STRING:
|
||||
datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
|
||||
break;
|
||||
case TuyaDatapointType::ENUM:
|
||||
if (data_size != 1) {
|
||||
ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
|
||||
return;
|
||||
}
|
||||
datapoint.value_enum = data[0];
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
|
||||
break;
|
||||
case TuyaDatapointType::BITMASK:
|
||||
switch (data_size) {
|
||||
case 1:
|
||||
datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
|
||||
break;
|
||||
case 2:
|
||||
datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
|
||||
break;
|
||||
case 4:
|
||||
datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
|
||||
return;
|
||||
}
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
|
||||
return;
|
||||
}
|
||||
|
||||
len -= data_size + 4;
|
||||
buffer = data + data_size;
|
||||
|
||||
// drop update if datapoint is in ignore_mcu_datapoint_update list
|
||||
bool skip = false;
|
||||
for (auto i : this->ignore_mcu_update_on_datapoints_) {
|
||||
if (datapoint.id == i) {
|
||||
ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
|
||||
skip = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (skip)
|
||||
continue;
|
||||
|
||||
// Update internal datapoints
|
||||
bool found = false;
|
||||
for (auto &other : this->datapoints_) {
|
||||
if (other.id == datapoint.id) {
|
||||
other = datapoint;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
this->datapoints_.push_back(datapoint);
|
||||
}
|
||||
|
||||
// Run through listeners
|
||||
for (auto &listener : this->listeners_) {
|
||||
if (listener.datapoint_id == datapoint.id)
|
||||
listener.on_datapoint.call(datapoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Tuya::send_raw_command_(TuyaCommand command) {
|
||||
uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
|
||||
uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
|
||||
uint8_t version = 0;
|
||||
|
||||
this->last_command_timestamp_ = millis();
|
||||
switch (command.cmd) {
|
||||
case TuyaCommandType::HEARTBEAT:
|
||||
this->expected_response_ = TuyaCommandType::HEARTBEAT;
|
||||
break;
|
||||
case TuyaCommandType::PRODUCT_QUERY:
|
||||
this->expected_response_ = TuyaCommandType::PRODUCT_QUERY;
|
||||
break;
|
||||
case TuyaCommandType::CONF_QUERY:
|
||||
this->expected_response_ = TuyaCommandType::CONF_QUERY;
|
||||
break;
|
||||
case TuyaCommandType::DATAPOINT_DELIVER:
|
||||
case TuyaCommandType::DATAPOINT_QUERY:
|
||||
this->expected_response_ = TuyaCommandType::DATAPOINT_REPORT_ASYNC;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
|
||||
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
|
||||
ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
|
||||
version, format_hex_pretty_to(hex_buf, command.payload.data(), command.payload.size()),
|
||||
static_cast<uint8_t>(this->init_state_));
|
||||
#endif
|
||||
|
||||
this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
|
||||
if (!command.payload.empty())
|
||||
this->write_array(command.payload.data(), command.payload.size());
|
||||
|
||||
const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
|
||||
this->write_byte(sum_bytes(command.payload.data(), command.payload.size(), header_sum));
|
||||
}
|
||||
|
||||
void Tuya::process_command_queue_() {
|
||||
uint32_t now = millis();
|
||||
uint32_t delay = now - this->last_command_timestamp_;
|
||||
|
||||
if (now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
|
||||
this->rx_message_.clear();
|
||||
}
|
||||
|
||||
if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
|
||||
this->expected_response_.reset();
|
||||
if (init_state_ != TuyaInitState::INIT_DONE) {
|
||||
if (++this->init_retries_ >= MAX_RETRIES) {
|
||||
this->init_failed_ = true;
|
||||
ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
|
||||
this->command_queue_.erase(command_queue_.begin());
|
||||
this->init_retries_ = 0;
|
||||
}
|
||||
} else {
|
||||
this->command_queue_.erase(command_queue_.begin());
|
||||
// Update internal datapoints
|
||||
bool found = false;
|
||||
for (auto &other : this->datapoints_) {
|
||||
if (other.id == datapoint.id) {
|
||||
other = datapoint;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
|
||||
if (delay > COMMAND_DELAY && !this->command_queue_.empty() && this->rx_message_.empty() &&
|
||||
!this->expected_response_.has_value()) {
|
||||
this->send_raw_command_(command_queue_.front());
|
||||
if (!this->expected_response_.has_value())
|
||||
this->command_queue_.erase(command_queue_.begin());
|
||||
}
|
||||
}
|
||||
|
||||
void Tuya::send_command_(const TuyaCommand &command) {
|
||||
command_queue_.push_back(command);
|
||||
process_command_queue_();
|
||||
}
|
||||
|
||||
void Tuya::send_empty_command_(TuyaCommandType command) {
|
||||
send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
|
||||
}
|
||||
|
||||
void Tuya::set_status_pin_() {
|
||||
bool is_network_ready = network_is_connected() && remote_is_connected();
|
||||
this->status_pin_->digital_write(is_network_ready);
|
||||
}
|
||||
|
||||
uint8_t Tuya::get_wifi_status_code_() {
|
||||
uint8_t status = 0x02;
|
||||
|
||||
if (network_is_connected()) {
|
||||
status = 0x03;
|
||||
|
||||
// Protocol version 3 also supports specifying when connected to "the cloud"
|
||||
if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
|
||||
status = 0x04;
|
||||
}
|
||||
} else {
|
||||
#ifdef USE_CAPTIVE_PORTAL
|
||||
if (captive_portal::global_captive_portal != nullptr && captive_portal::global_captive_portal->is_active()) {
|
||||
status = 0x01;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
uint8_t Tuya::get_wifi_rssi_() {
|
||||
#ifdef USE_WIFI
|
||||
if (wifi::global_wifi_component != nullptr)
|
||||
return wifi::global_wifi_component->wifi_rssi();
|
||||
#endif
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void Tuya::send_wifi_status_() {
|
||||
uint8_t status = this->get_wifi_status_code_();
|
||||
|
||||
if (status == this->wifi_status_) {
|
||||
return;
|
||||
if (!found) {
|
||||
this->datapoints_.push_back(datapoint);
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, "Sending WiFi Status");
|
||||
this->wifi_status_ = status;
|
||||
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
|
||||
}
|
||||
|
||||
#ifdef USE_TIME
|
||||
void Tuya::register_local_time_sync_callback_() {
|
||||
if (this->time_sync_callback_registered_) {
|
||||
return;
|
||||
// Run through listeners
|
||||
for (auto &listener : this->listeners_) {
|
||||
if (listener.datapoint_id == datapoint.id)
|
||||
listener.on_datapoint.call(datapoint);
|
||||
}
|
||||
this->time_id_->add_on_time_sync_callback([this] { this->send_local_time_(); });
|
||||
this->time_sync_callback_registered_ = true;
|
||||
}
|
||||
|
||||
void Tuya::check_force_time_sync_() {
|
||||
ESPTime now = this->time_id_->now();
|
||||
if (!now.is_valid() || now.minute == this->last_force_time_sync_minute_)
|
||||
return;
|
||||
this->last_force_time_sync_minute_ = now.minute;
|
||||
this->send_local_time_(true);
|
||||
}
|
||||
|
||||
void Tuya::send_local_time_(bool periodic) {
|
||||
std::vector<uint8_t> payload;
|
||||
ESPTime now = this->time_id_->now();
|
||||
if (now.is_valid()) {
|
||||
uint8_t year = now.year - 2000;
|
||||
uint8_t month = now.month;
|
||||
uint8_t day_of_month = now.day_of_month;
|
||||
uint8_t hour = now.hour;
|
||||
uint8_t minute = now.minute;
|
||||
uint8_t second = now.second;
|
||||
// Tuya days starts from Monday, esphome uses Sunday as day 1
|
||||
uint8_t day_of_week = now.day_of_week - 1;
|
||||
if (day_of_week == 0) {
|
||||
day_of_week = 7;
|
||||
}
|
||||
// The forced send repeats every minute, so it stays out of the debug log
|
||||
if (periodic) {
|
||||
ESP_LOGV(TAG, "Sending local time");
|
||||
} else {
|
||||
ESP_LOGD(TAG, "Sending local time");
|
||||
}
|
||||
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
|
||||
} else {
|
||||
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
|
||||
ESP_LOGW(TAG, "Sending missing local time");
|
||||
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||
}
|
||||
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
|
||||
}
|
||||
void Tuya::send_gmt_time_() {
|
||||
std::vector<uint8_t> payload;
|
||||
ESPTime now = this->time_id_->utcnow();
|
||||
if (now.is_valid()) {
|
||||
uint8_t year = now.year - 2000;
|
||||
uint8_t month = now.month;
|
||||
uint8_t day_of_month = now.day_of_month;
|
||||
uint8_t hour = now.hour;
|
||||
uint8_t minute = now.minute;
|
||||
uint8_t second = now.second;
|
||||
ESP_LOGD(TAG, "Sending gmt time");
|
||||
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second};
|
||||
} else {
|
||||
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
|
||||
ESP_LOGW(TAG, "Sending missing gmt time");
|
||||
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||
}
|
||||
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::GMT_TIME_QUERY, .payload = payload});
|
||||
}
|
||||
#endif
|
||||
|
||||
void Tuya::set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value) {
|
||||
this->set_raw_datapoint_value_(datapoint_id, value, false);
|
||||
}
|
||||
@@ -744,19 +113,19 @@ void Tuya::force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t valu
|
||||
this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BITMASK, value, length, true);
|
||||
}
|
||||
|
||||
optional<TuyaDatapoint> Tuya::get_datapoint_(uint8_t datapoint_id) {
|
||||
for (auto &datapoint : this->datapoints_) {
|
||||
const TuyaDatapoint *Tuya::get_datapoint_(uint8_t datapoint_id) const {
|
||||
for (const auto &datapoint : this->datapoints_) {
|
||||
if (datapoint.id == datapoint_id)
|
||||
return datapoint;
|
||||
return &datapoint;
|
||||
}
|
||||
return {};
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint32_t value,
|
||||
uint8_t length, bool forced) {
|
||||
ESP_LOGD(TAG, "Setting datapoint %u to %" PRIu32, datapoint_id, value);
|
||||
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
|
||||
if (!datapoint.has_value()) {
|
||||
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
|
||||
if (datapoint == nullptr) {
|
||||
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
|
||||
} else if (datapoint->type != datapoint_type) {
|
||||
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
|
||||
@@ -766,30 +135,29 @@ void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> data;
|
||||
uint8_t data[4];
|
||||
switch (length) {
|
||||
case 4:
|
||||
data.push_back(value >> 24);
|
||||
data.push_back(value >> 16);
|
||||
[[fallthrough]];
|
||||
put_be32(data, value);
|
||||
break;
|
||||
case 2:
|
||||
data.push_back(value >> 8);
|
||||
[[fallthrough]];
|
||||
put_be16(data, value);
|
||||
break;
|
||||
case 1:
|
||||
data.push_back(value >> 0);
|
||||
data[0] = value;
|
||||
break;
|
||||
default:
|
||||
ESP_LOGE(TAG, "Unexpected datapoint length %u", length);
|
||||
return;
|
||||
}
|
||||
this->send_datapoint_command_(datapoint_id, datapoint_type, data);
|
||||
this->send_datapoint_command(datapoint_id, datapoint_type, data, length);
|
||||
}
|
||||
|
||||
void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced) {
|
||||
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
|
||||
ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, format_hex_pretty_to(hex_buf, value.data(), value.size()));
|
||||
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
|
||||
if (!datapoint.has_value()) {
|
||||
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
|
||||
if (datapoint == nullptr) {
|
||||
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
|
||||
} else if (datapoint->type != TuyaDatapointType::RAW) {
|
||||
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
|
||||
@@ -798,13 +166,13 @@ void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint
|
||||
ESP_LOGV(TAG, "Not sending unchanged value");
|
||||
return;
|
||||
}
|
||||
this->send_datapoint_command_(datapoint_id, TuyaDatapointType::RAW, value);
|
||||
this->send_datapoint_command(datapoint_id, TuyaDatapointType::RAW, value.data(), value.size());
|
||||
}
|
||||
|
||||
void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const char *value, size_t len, bool forced) {
|
||||
ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, value);
|
||||
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
|
||||
if (!datapoint.has_value()) {
|
||||
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
|
||||
if (datapoint == nullptr) {
|
||||
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
|
||||
} else if (datapoint->type != TuyaDatapointType::STRING) {
|
||||
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
|
||||
@@ -814,19 +182,7 @@ void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const char *value,
|
||||
ESP_LOGV(TAG, "Not sending unchanged value");
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> data(value, value + len);
|
||||
this->send_datapoint_command_(datapoint_id, TuyaDatapointType::STRING, data);
|
||||
}
|
||||
|
||||
void Tuya::send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data) {
|
||||
std::vector<uint8_t> buffer;
|
||||
buffer.push_back(datapoint_id);
|
||||
buffer.push_back(static_cast<uint8_t>(datapoint_type));
|
||||
buffer.push_back(data.size() >> 8);
|
||||
buffer.push_back(data.size() >> 0);
|
||||
buffer.insert(buffer.end(), data.begin(), data.end());
|
||||
|
||||
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_DELIVER, .payload = buffer});
|
||||
this->send_datapoint_command(datapoint_id, TuyaDatapointType::STRING, reinterpret_cast<const uint8_t *>(value), len);
|
||||
}
|
||||
|
||||
void Tuya::register_listener_(uint8_t datapoint_id, Callback<void(const TuyaDatapoint &)> func) {
|
||||
@@ -850,6 +206,4 @@ const TuyaDatapoint &TuyaDatapoint::expect_type(TuyaDatapointType expected) cons
|
||||
return *this;
|
||||
}
|
||||
|
||||
TuyaInitState Tuya::get_init_state() { return this->init_state_; }
|
||||
|
||||
} // namespace esphome::tuya
|
||||
+24
-100
@@ -1,21 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <cinttypes>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/components/uart/uart.h"
|
||||
|
||||
#ifdef USE_TIME
|
||||
#include "esphome/components/time/real_time_clock.h"
|
||||
#include "esphome/core/time.h"
|
||||
#endif
|
||||
|
||||
namespace esphome::tuya {
|
||||
|
||||
// Max bytes to log for datapoint values (larger values are truncated)
|
||||
static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
|
||||
|
||||
enum class TuyaDatapointType : uint8_t {
|
||||
RAW = 0x00, // variable length
|
||||
BOOLEAN = 0x01, // 1 byte (0/1)
|
||||
@@ -48,53 +44,18 @@ struct TuyaDatapointListener {
|
||||
Callback<void(const TuyaDatapoint &)> on_datapoint;
|
||||
};
|
||||
|
||||
enum class TuyaCommandType : uint8_t {
|
||||
HEARTBEAT = 0x00,
|
||||
PRODUCT_QUERY = 0x01,
|
||||
CONF_QUERY = 0x02,
|
||||
WIFI_STATE = 0x03,
|
||||
WIFI_RESET = 0x04,
|
||||
WIFI_SELECT = 0x05,
|
||||
DATAPOINT_DELIVER = 0x06,
|
||||
DATAPOINT_REPORT_ASYNC = 0x07,
|
||||
DATAPOINT_QUERY = 0x08,
|
||||
GMT_TIME_QUERY = 0x0C,
|
||||
WIFI_TEST = 0x0E,
|
||||
LOCAL_TIME_QUERY = 0x1C,
|
||||
DATAPOINT_REPORT_SYNC = 0x22,
|
||||
DATAPOINT_REPORT_ACK = 0x23,
|
||||
WIFI_RSSI = 0x24,
|
||||
VACUUM_MAP_UPLOAD = 0x28,
|
||||
GET_NETWORK_STATUS = 0x2B,
|
||||
EXTENDED_SERVICES = 0x34,
|
||||
};
|
||||
|
||||
enum class TuyaExtendedServicesCommandType : uint8_t {
|
||||
RESET_NOTIFICATION = 0x04,
|
||||
MODULE_RESET = 0x05,
|
||||
UPDATE_IN_PROGRESS = 0x0A,
|
||||
};
|
||||
|
||||
enum class TuyaInitState : uint8_t {
|
||||
INIT_HEARTBEAT = 0x00,
|
||||
INIT_PRODUCT,
|
||||
INIT_CONF,
|
||||
INIT_WIFI,
|
||||
INIT_DATAPOINT,
|
||||
INIT_DONE,
|
||||
};
|
||||
|
||||
struct TuyaCommand {
|
||||
TuyaCommandType cmd;
|
||||
std::vector<uint8_t> payload;
|
||||
};
|
||||
|
||||
class Tuya final : public Component, public uart::UARTDevice {
|
||||
/// Transport-agnostic Tuya controller. Subclasses implement send_datapoint_command(), feed received datapoints
|
||||
/// to handle_datapoint_(), and call mark_initialized_() once the MCU has reported.
|
||||
class Tuya : public Component {
|
||||
public:
|
||||
float get_setup_priority() const override { return setup_priority::LATE; }
|
||||
void setup() override;
|
||||
void loop() override;
|
||||
void dump_config() override;
|
||||
/// Prints each child entity's dump; a transport that overrides it prints its own block first, then calls this
|
||||
void dump_config() override {
|
||||
#ifdef USE_TUYA_DUMP_PUBLISHER
|
||||
if (this->dump_publisher_ != nullptr)
|
||||
this->dump_publisher_();
|
||||
#endif
|
||||
}
|
||||
#ifdef USE_TUYA_DUMP_PUBLISHER
|
||||
HUB_PUBLISHER(dump)
|
||||
#endif
|
||||
@@ -104,7 +65,6 @@ class Tuya final : public Component, public uart::UARTDevice {
|
||||
void set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value);
|
||||
void set_boolean_datapoint_value(uint8_t datapoint_id, bool value);
|
||||
void set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value);
|
||||
void set_status_pin(InternalGPIOPin *status_pin) { this->status_pin_ = status_pin; }
|
||||
void set_string_datapoint_value(uint8_t datapoint_id, const std::string &value);
|
||||
void set_string_datapoint_value(uint8_t datapoint_id, const char *value);
|
||||
void set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value);
|
||||
@@ -116,11 +76,6 @@ class Tuya final : public Component, public uart::UARTDevice {
|
||||
void force_set_string_datapoint_value(uint8_t datapoint_id, const char *value);
|
||||
void force_set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value);
|
||||
void force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length);
|
||||
TuyaInitState get_init_state();
|
||||
#ifdef USE_TIME
|
||||
void set_time_id(time::RealTimeClock *time_id) { this->time_id_ = time_id; }
|
||||
void set_force_time_sync(bool force_time_sync) { this->force_time_sync_ = force_time_sync; }
|
||||
#endif
|
||||
void add_ignore_mcu_update_on_datapoints(uint8_t ignore_mcu_update_on_datapoints) {
|
||||
this->ignore_mcu_update_on_datapoints_.push_back(ignore_mcu_update_on_datapoints);
|
||||
}
|
||||
@@ -130,56 +85,25 @@ class Tuya final : public Component, public uart::UARTDevice {
|
||||
|
||||
protected:
|
||||
void register_listener_(uint8_t datapoint_id, Callback<void(const TuyaDatapoint &)> func);
|
||||
void dump_mcu_config_();
|
||||
void handle_char_(uint8_t c);
|
||||
void handle_datapoints_(const uint8_t *buffer, size_t len);
|
||||
optional<TuyaDatapoint> get_datapoint_(uint8_t datapoint_id);
|
||||
bool validate_message_();
|
||||
|
||||
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len);
|
||||
void send_raw_command_(TuyaCommand command);
|
||||
void process_command_queue_();
|
||||
void send_command_(const TuyaCommand &command);
|
||||
void send_empty_command_(TuyaCommandType command);
|
||||
/// Store a datapoint received from the MCU and notify listeners.
|
||||
void handle_datapoint_(const TuyaDatapoint &datapoint);
|
||||
void mark_initialized_() { this->initialized_callback_.call(); }
|
||||
const TuyaDatapoint *get_datapoint_(uint8_t datapoint_id) const;
|
||||
void dump_datapoints_();
|
||||
void set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, uint32_t value,
|
||||
uint8_t length, bool forced);
|
||||
void set_string_datapoint_value_(uint8_t datapoint_id, const char *value, size_t len, bool forced);
|
||||
void set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced);
|
||||
void send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data);
|
||||
void set_status_pin_();
|
||||
void send_wifi_status_();
|
||||
uint8_t get_wifi_status_code_();
|
||||
uint8_t get_wifi_rssi_();
|
||||
/// Deliver a datapoint value to the MCU over the subclass's transport.
|
||||
/// The payload is borrowed for the duration of the call only.
|
||||
virtual void send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
|
||||
size_t len) = 0;
|
||||
|
||||
#ifdef USE_TIME
|
||||
void register_local_time_sync_callback_();
|
||||
void check_force_time_sync_();
|
||||
void send_local_time_(bool periodic = false);
|
||||
void send_gmt_time_();
|
||||
time::RealTimeClock *time_id_{nullptr};
|
||||
bool force_time_sync_{false};
|
||||
uint8_t last_force_time_sync_minute_{0xFF}; // 0xFF: no minute seen yet
|
||||
bool time_sync_callback_registered_{false};
|
||||
bool gmt_time_sync_callback_registered_{false};
|
||||
#endif
|
||||
TuyaInitState init_state_ = TuyaInitState::INIT_HEARTBEAT;
|
||||
bool init_failed_{false};
|
||||
int init_retries_{0};
|
||||
uint8_t protocol_version_ = -1;
|
||||
InternalGPIOPin *status_pin_{nullptr};
|
||||
int status_pin_reported_ = -1;
|
||||
int reset_pin_reported_ = -1;
|
||||
uint32_t last_command_timestamp_ = 0;
|
||||
uint32_t last_rx_char_timestamp_ = 0;
|
||||
std::unique_ptr<char[]> product_;
|
||||
std::vector<TuyaDatapointListener> listeners_;
|
||||
std::vector<TuyaDatapoint> datapoints_;
|
||||
std::vector<uint8_t> rx_message_;
|
||||
std::vector<uint8_t> ignore_mcu_update_on_datapoints_{};
|
||||
std::vector<TuyaCommand> command_queue_;
|
||||
optional<TuyaCommandType> expected_response_{};
|
||||
uint8_t wifi_status_ = -1;
|
||||
bool product_invalid_{false};
|
||||
|
||||
private:
|
||||
CallbackManager<void()> initialized_callback_{};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,656 @@
|
||||
#include "tuya_uart.h"
|
||||
#include "esphome/core/gpio.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/util.h"
|
||||
#include <cctype>
|
||||
#include <cstring>
|
||||
|
||||
#ifdef USE_NETWORK
|
||||
#include "esphome/components/network/util.h"
|
||||
#endif
|
||||
|
||||
#ifdef USE_WIFI
|
||||
#include "esphome/components/wifi/wifi_component.h"
|
||||
#endif
|
||||
|
||||
#ifdef USE_CAPTIVE_PORTAL
|
||||
#include "esphome/components/captive_portal/captive_portal.h"
|
||||
#endif
|
||||
|
||||
namespace esphome::tuya {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "tuya");
|
||||
|
||||
static constexpr uint32_t HEARTBEAT_INTERVAL_ID = 0;
|
||||
static constexpr uint32_t WIFI_STATUS_INTERVAL_ID = 1;
|
||||
static constexpr uint32_t DATAPOINT_DUMP_TIMEOUT_ID = 2;
|
||||
static constexpr uint32_t FORCE_TIME_SYNC_INTERVAL_ID = 3;
|
||||
static const int COMMAND_DELAY = 10;
|
||||
static const int RECEIVE_TIMEOUT = 300;
|
||||
static const int MAX_RETRIES = 5;
|
||||
static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
|
||||
|
||||
static bool network_is_connected() {
|
||||
#ifdef USE_NETWORK
|
||||
return network::is_connected();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void TuyaUART::setup() {
|
||||
this->set_interval(HEARTBEAT_INTERVAL_ID, 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
|
||||
#ifdef USE_TIME
|
||||
if (this->force_time_sync_) {
|
||||
this->register_local_time_sync_callback_();
|
||||
this->set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
|
||||
[this] { this->check_force_time_sync_(); });
|
||||
}
|
||||
#endif
|
||||
if (this->status_pin_ != nullptr) {
|
||||
this->status_pin_->digital_write(false);
|
||||
}
|
||||
}
|
||||
|
||||
void TuyaUART::loop() {
|
||||
this->read_available([this](uint8_t b) { this->handle_char_(b); });
|
||||
process_command_queue_();
|
||||
}
|
||||
|
||||
void TuyaUART::dump_config() {
|
||||
this->dump_mcu_config_();
|
||||
Tuya::dump_config();
|
||||
}
|
||||
|
||||
// Also logged again once the MCU reports its datapoints
|
||||
void TuyaUART::dump_mcu_config_() {
|
||||
ESP_LOGCONFIG(TAG, "Tuya:");
|
||||
if (this->init_state_ != TuyaInitState::INIT_DONE) {
|
||||
if (this->init_failed_) {
|
||||
ESP_LOGCONFIG(TAG, " Initialization failed. Current init_state: %u", static_cast<uint8_t>(this->init_state_));
|
||||
} else {
|
||||
ESP_LOGCONFIG(TAG, " Configuration will be reported when setup is complete. Current init_state: %u",
|
||||
static_cast<uint8_t>(this->init_state_));
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " If no further output is received, confirm that this is a supported Tuya device.");
|
||||
return;
|
||||
}
|
||||
this->dump_datapoints_();
|
||||
if ((this->status_pin_reported_ != -1) || (this->reset_pin_reported_ != -1)) {
|
||||
ESP_LOGCONFIG(TAG, " GPIO Configuration: status: pin %d, reset: pin %d", this->status_pin_reported_,
|
||||
this->reset_pin_reported_);
|
||||
}
|
||||
LOG_PIN(" Status Pin: ", this->status_pin_);
|
||||
ESP_LOGCONFIG(TAG, " Product: '%s'",
|
||||
this->product_invalid_ ? LOG_STR_LITERAL(R"({"p":"INVALID"})")
|
||||
: (this->product_ ? this->product_.get() : LOG_STR_LITERAL("")));
|
||||
#ifdef USE_TIME
|
||||
if (this->time_id_ != nullptr) {
|
||||
ESP_LOGCONFIG(TAG, " Force time sync: %s", YESNO(this->force_time_sync_));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool TuyaUART::validate_message_() {
|
||||
uint32_t at = this->rx_message_.size() - 1;
|
||||
auto *data = &this->rx_message_[0];
|
||||
uint8_t new_byte = data[at];
|
||||
|
||||
// Byte 0: HEADER1 (always 0x55)
|
||||
if (at == 0)
|
||||
return new_byte == 0x55;
|
||||
// Byte 1: HEADER2 (always 0xAA)
|
||||
if (at == 1)
|
||||
return new_byte == 0xAA;
|
||||
|
||||
// Byte 2: VERSION
|
||||
// no validation for the following fields:
|
||||
uint8_t version = data[2];
|
||||
if (at == 2)
|
||||
return true;
|
||||
// Byte 3: COMMAND
|
||||
uint8_t command = data[3];
|
||||
if (at == 3)
|
||||
return true;
|
||||
|
||||
// Byte 4: LENGTH1
|
||||
// Byte 5: LENGTH2
|
||||
if (at <= 5) {
|
||||
// no validation for these fields
|
||||
return true;
|
||||
}
|
||||
|
||||
uint16_t length = encode_uint16(data[4], data[5]);
|
||||
|
||||
// wait until all data is read
|
||||
if (at - 6 < length)
|
||||
return true;
|
||||
|
||||
// Byte 6+LEN: CHECKSUM - sum of all bytes (including header) modulo 256
|
||||
uint8_t rx_checksum = new_byte;
|
||||
const uint8_t calc_checksum = sum_bytes(data, 6 + length);
|
||||
|
||||
if (rx_checksum != calc_checksum) {
|
||||
ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
|
||||
return false;
|
||||
}
|
||||
|
||||
// valid message
|
||||
const uint8_t *message_data = data + 6;
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
|
||||
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
|
||||
ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
|
||||
format_hex_pretty_to(hex_buf, message_data, length), static_cast<uint8_t>(this->init_state_));
|
||||
#endif
|
||||
this->handle_command_(command, version, message_data, length);
|
||||
|
||||
// return false to reset rx buffer
|
||||
return false;
|
||||
}
|
||||
|
||||
void TuyaUART::handle_char_(uint8_t c) {
|
||||
this->rx_message_.push_back(c);
|
||||
if (!this->validate_message_()) {
|
||||
this->rx_message_.clear();
|
||||
} else {
|
||||
this->last_rx_char_timestamp_ = millis();
|
||||
}
|
||||
}
|
||||
|
||||
void TuyaUART::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
|
||||
TuyaCommandType command_type = (TuyaCommandType) command;
|
||||
|
||||
if (this->expected_response_.has_value() && this->expected_response_ == command_type) {
|
||||
this->expected_response_.reset();
|
||||
this->command_queue_.erase(command_queue_.begin());
|
||||
this->init_retries_ = 0;
|
||||
}
|
||||
|
||||
switch (command_type) {
|
||||
case TuyaCommandType::HEARTBEAT:
|
||||
ESP_LOGV(TAG, "MCU Heartbeat (0x%02X)", buffer[0]);
|
||||
this->protocol_version_ = version;
|
||||
if (buffer[0] == 0) {
|
||||
ESP_LOGI(TAG, "MCU restarted");
|
||||
this->init_state_ = TuyaInitState::INIT_HEARTBEAT;
|
||||
}
|
||||
if (this->init_state_ == TuyaInitState::INIT_HEARTBEAT) {
|
||||
this->init_state_ = TuyaInitState::INIT_PRODUCT;
|
||||
this->send_empty_command_(TuyaCommandType::PRODUCT_QUERY);
|
||||
}
|
||||
break;
|
||||
case TuyaCommandType::PRODUCT_QUERY: {
|
||||
// check it is a valid string made up of printable characters
|
||||
bool valid = true;
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
if (!std::isprint(buffer[i])) {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (valid) {
|
||||
this->product_ = std::make_unique<char[]>(len + 1);
|
||||
memcpy(this->product_.get(), buffer, len);
|
||||
} else {
|
||||
this->product_.reset();
|
||||
}
|
||||
this->product_invalid_ = !valid;
|
||||
if (this->init_state_ == TuyaInitState::INIT_PRODUCT) {
|
||||
this->init_state_ = TuyaInitState::INIT_CONF;
|
||||
this->send_empty_command_(TuyaCommandType::CONF_QUERY);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case TuyaCommandType::CONF_QUERY: {
|
||||
if (len >= 2) {
|
||||
this->status_pin_reported_ = buffer[0];
|
||||
this->reset_pin_reported_ = buffer[1];
|
||||
}
|
||||
if (this->init_state_ == TuyaInitState::INIT_CONF) {
|
||||
// If mcu returned status gpio, then we can omit sending wifi state
|
||||
if (this->status_pin_reported_ != -1) {
|
||||
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
|
||||
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
|
||||
if (this->status_pin_ != nullptr) {
|
||||
if (this->status_pin_->get_pin() != this->status_pin_reported_) {
|
||||
ESP_LOGW(TAG, "Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
|
||||
this->status_pin_reported_);
|
||||
}
|
||||
ESP_LOGV(TAG, "Configured status pin %i", this->status_pin_->get_pin());
|
||||
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->set_status_pin_(); });
|
||||
} else {
|
||||
ESP_LOGW(TAG, "MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
|
||||
this->status_pin_reported_);
|
||||
}
|
||||
} else {
|
||||
this->init_state_ = TuyaInitState::INIT_WIFI;
|
||||
ESP_LOGV(TAG, "Configured WIFI_STATE periodic send");
|
||||
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->send_wifi_status_(); });
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case TuyaCommandType::WIFI_STATE:
|
||||
if (this->init_state_ == TuyaInitState::INIT_WIFI) {
|
||||
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
|
||||
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
|
||||
}
|
||||
break;
|
||||
case TuyaCommandType::WIFI_SELECT:
|
||||
case TuyaCommandType::WIFI_RESET: {
|
||||
const bool is_select = (len >= 1);
|
||||
// Send WIFI_SELECT ACK
|
||||
TuyaCommand ack;
|
||||
ack.cmd = is_select ? TuyaCommandType::WIFI_SELECT : TuyaCommandType::WIFI_RESET;
|
||||
ack.payload.clear();
|
||||
this->send_command_(ack);
|
||||
// Establish pairing mode for correct first WIFI_STATE byte, EZ (0x00) default
|
||||
uint8_t first = 0x00;
|
||||
const char *mode_str = "EZ";
|
||||
if (is_select && buffer[0] == 0x01) {
|
||||
first = 0x01;
|
||||
mode_str = "AP";
|
||||
}
|
||||
// Send WIFI_STATE response, MCU exits pairing mode
|
||||
TuyaCommand st;
|
||||
st.cmd = TuyaCommandType::WIFI_STATE;
|
||||
st.payload.resize(1);
|
||||
st.payload[0] = first;
|
||||
this->send_command_(st);
|
||||
st.payload[0] = 0x02;
|
||||
this->send_command_(st);
|
||||
st.payload[0] = 0x03;
|
||||
this->send_command_(st);
|
||||
st.payload[0] = 0x04;
|
||||
this->send_command_(st);
|
||||
ESP_LOGI(TAG, "%s received (%s), replied with WIFI_STATE confirming connection established",
|
||||
is_select ? LOG_STR_LITERAL("WIFI_SELECT") : LOG_STR_LITERAL("WIFI_RESET"), mode_str);
|
||||
break;
|
||||
}
|
||||
case TuyaCommandType::DATAPOINT_DELIVER:
|
||||
break;
|
||||
case TuyaCommandType::DATAPOINT_REPORT_ASYNC:
|
||||
case TuyaCommandType::DATAPOINT_REPORT_SYNC:
|
||||
if (this->init_state_ == TuyaInitState::INIT_DATAPOINT) {
|
||||
this->init_state_ = TuyaInitState::INIT_DONE;
|
||||
this->set_timeout(DATAPOINT_DUMP_TIMEOUT_ID, 1000, [this] { this->dump_mcu_config_(); });
|
||||
this->mark_initialized_();
|
||||
}
|
||||
this->handle_datapoints_(buffer, len);
|
||||
|
||||
if (command_type == TuyaCommandType::DATAPOINT_REPORT_SYNC) {
|
||||
this->send_command_(
|
||||
TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_REPORT_ACK, .payload = std::vector<uint8_t>{0x01}});
|
||||
}
|
||||
break;
|
||||
case TuyaCommandType::DATAPOINT_QUERY:
|
||||
break;
|
||||
case TuyaCommandType::WIFI_TEST:
|
||||
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_TEST, .payload = std::vector<uint8_t>{0x00, 0x00}});
|
||||
break;
|
||||
case TuyaCommandType::WIFI_RSSI:
|
||||
this->send_command_(
|
||||
TuyaCommand{.cmd = TuyaCommandType::WIFI_RSSI, .payload = std::vector<uint8_t>{get_wifi_rssi_()}});
|
||||
break;
|
||||
case TuyaCommandType::LOCAL_TIME_QUERY:
|
||||
#ifdef USE_TIME
|
||||
if (this->time_id_ != nullptr) {
|
||||
this->send_local_time_();
|
||||
this->register_local_time_sync_callback_();
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured");
|
||||
}
|
||||
break;
|
||||
case TuyaCommandType::GMT_TIME_QUERY:
|
||||
#ifdef USE_TIME
|
||||
if (this->time_id_ != nullptr) {
|
||||
this->send_gmt_time_();
|
||||
|
||||
if (!this->gmt_time_sync_callback_registered_) {
|
||||
// tuya mcu supports time, so we let them know when our time changed
|
||||
this->time_id_->add_on_time_sync_callback([this] { this->send_gmt_time_(); });
|
||||
this->gmt_time_sync_callback_registered_ = true;
|
||||
}
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
ESP_LOGW(TAG, "GMT_TIME_QUERY is not handled because time is not configured");
|
||||
}
|
||||
break;
|
||||
case TuyaCommandType::VACUUM_MAP_UPLOAD:
|
||||
this->send_command_(
|
||||
TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector<uint8_t>{0x01}});
|
||||
ESP_LOGW(TAG, "Vacuum map upload requested, responding that it is not enabled.");
|
||||
break;
|
||||
case TuyaCommandType::GET_NETWORK_STATUS: {
|
||||
uint8_t wifi_status = this->get_wifi_status_code_();
|
||||
|
||||
this->send_command_(
|
||||
TuyaCommand{.cmd = TuyaCommandType::GET_NETWORK_STATUS, .payload = std::vector<uint8_t>{wifi_status}});
|
||||
ESP_LOGV(TAG, "Network status requested, reported as %i", wifi_status);
|
||||
break;
|
||||
}
|
||||
case TuyaCommandType::EXTENDED_SERVICES: {
|
||||
uint8_t subcommand = buffer[0];
|
||||
switch ((TuyaExtendedServicesCommandType) subcommand) {
|
||||
case TuyaExtendedServicesCommandType::RESET_NOTIFICATION: {
|
||||
this->send_command_(
|
||||
TuyaCommand{.cmd = TuyaCommandType::EXTENDED_SERVICES,
|
||||
.payload = std::vector<uint8_t>{
|
||||
static_cast<uint8_t>(TuyaExtendedServicesCommandType::RESET_NOTIFICATION), 0x00}});
|
||||
ESP_LOGV(TAG, "Reset status notification enabled");
|
||||
break;
|
||||
}
|
||||
case TuyaExtendedServicesCommandType::MODULE_RESET: {
|
||||
ESP_LOGE(TAG, "EXTENDED_SERVICES::MODULE_RESET is not handled");
|
||||
break;
|
||||
}
|
||||
case TuyaExtendedServicesCommandType::UPDATE_IN_PROGRESS: {
|
||||
ESP_LOGE(TAG, "EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ESP_LOGE(TAG, "Invalid extended services subcommand (0x%02X) received", subcommand);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
|
||||
}
|
||||
}
|
||||
|
||||
void TuyaUART::handle_datapoints_(const uint8_t *buffer, size_t len) {
|
||||
while (len >= 4) {
|
||||
TuyaDatapoint datapoint{};
|
||||
datapoint.id = buffer[0];
|
||||
datapoint.type = (TuyaDatapointType) buffer[1];
|
||||
datapoint.value_uint = 0;
|
||||
|
||||
size_t data_size = encode_uint16(buffer[2], buffer[3]);
|
||||
const uint8_t *data = buffer + 4;
|
||||
size_t data_len = len - 4;
|
||||
if (data_size > data_len) {
|
||||
ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
|
||||
return;
|
||||
}
|
||||
|
||||
datapoint.len = data_size;
|
||||
|
||||
switch (datapoint.type) {
|
||||
case TuyaDatapointType::RAW:
|
||||
datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
|
||||
{
|
||||
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id,
|
||||
format_hex_pretty_to(hex_buf, datapoint.value_raw.data(), datapoint.value_raw.size()));
|
||||
}
|
||||
break;
|
||||
case TuyaDatapointType::BOOLEAN:
|
||||
if (data_size != 1) {
|
||||
ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
|
||||
return;
|
||||
}
|
||||
datapoint.value_bool = data[0];
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
|
||||
break;
|
||||
case TuyaDatapointType::INTEGER:
|
||||
if (data_size != 4) {
|
||||
ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
|
||||
return;
|
||||
}
|
||||
datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
|
||||
break;
|
||||
case TuyaDatapointType::STRING:
|
||||
datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
|
||||
break;
|
||||
case TuyaDatapointType::ENUM:
|
||||
if (data_size != 1) {
|
||||
ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
|
||||
return;
|
||||
}
|
||||
datapoint.value_enum = data[0];
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
|
||||
break;
|
||||
case TuyaDatapointType::BITMASK:
|
||||
switch (data_size) {
|
||||
case 1:
|
||||
datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
|
||||
break;
|
||||
case 2:
|
||||
datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
|
||||
break;
|
||||
case 4:
|
||||
datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
|
||||
return;
|
||||
}
|
||||
ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
|
||||
return;
|
||||
}
|
||||
|
||||
len -= data_size + 4;
|
||||
buffer = data + data_size;
|
||||
|
||||
this->handle_datapoint_(datapoint);
|
||||
}
|
||||
}
|
||||
|
||||
void TuyaUART::send_raw_command_(TuyaCommand command) {
|
||||
uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
|
||||
uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
|
||||
uint8_t version = 0;
|
||||
|
||||
this->last_command_timestamp_ = millis();
|
||||
switch (command.cmd) {
|
||||
case TuyaCommandType::HEARTBEAT:
|
||||
this->expected_response_ = TuyaCommandType::HEARTBEAT;
|
||||
break;
|
||||
case TuyaCommandType::PRODUCT_QUERY:
|
||||
this->expected_response_ = TuyaCommandType::PRODUCT_QUERY;
|
||||
break;
|
||||
case TuyaCommandType::CONF_QUERY:
|
||||
this->expected_response_ = TuyaCommandType::CONF_QUERY;
|
||||
break;
|
||||
case TuyaCommandType::DATAPOINT_DELIVER:
|
||||
case TuyaCommandType::DATAPOINT_QUERY:
|
||||
this->expected_response_ = TuyaCommandType::DATAPOINT_REPORT_ASYNC;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
|
||||
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
|
||||
ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
|
||||
version, format_hex_pretty_to(hex_buf, command.payload.data(), command.payload.size()),
|
||||
static_cast<uint8_t>(this->init_state_));
|
||||
#endif
|
||||
|
||||
this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
|
||||
if (!command.payload.empty())
|
||||
this->write_array(command.payload.data(), command.payload.size());
|
||||
|
||||
const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
|
||||
this->write_byte(sum_bytes(command.payload.data(), command.payload.size(), header_sum));
|
||||
}
|
||||
|
||||
void TuyaUART::process_command_queue_() {
|
||||
uint32_t now = millis();
|
||||
uint32_t delay = now - this->last_command_timestamp_;
|
||||
|
||||
if (now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
|
||||
this->rx_message_.clear();
|
||||
}
|
||||
|
||||
if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
|
||||
this->expected_response_.reset();
|
||||
if (init_state_ != TuyaInitState::INIT_DONE) {
|
||||
if (++this->init_retries_ >= MAX_RETRIES) {
|
||||
this->init_failed_ = true;
|
||||
ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
|
||||
this->command_queue_.erase(command_queue_.begin());
|
||||
this->init_retries_ = 0;
|
||||
}
|
||||
} else {
|
||||
this->command_queue_.erase(command_queue_.begin());
|
||||
}
|
||||
}
|
||||
|
||||
// Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
|
||||
if (delay > COMMAND_DELAY && !this->command_queue_.empty() && this->rx_message_.empty() &&
|
||||
!this->expected_response_.has_value()) {
|
||||
this->send_raw_command_(command_queue_.front());
|
||||
if (!this->expected_response_.has_value())
|
||||
this->command_queue_.erase(command_queue_.begin());
|
||||
}
|
||||
}
|
||||
|
||||
void TuyaUART::send_command_(TuyaCommand command) {
|
||||
command_queue_.push_back(std::move(command));
|
||||
process_command_queue_();
|
||||
}
|
||||
|
||||
void TuyaUART::send_empty_command_(TuyaCommandType command) {
|
||||
send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
|
||||
}
|
||||
|
||||
void TuyaUART::send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
|
||||
size_t len) {
|
||||
std::vector<uint8_t> buffer;
|
||||
buffer.reserve(4 + len);
|
||||
buffer.push_back(datapoint_id);
|
||||
buffer.push_back(static_cast<uint8_t>(datapoint_type));
|
||||
buffer.push_back(len >> 8);
|
||||
buffer.push_back(len >> 0);
|
||||
buffer.insert(buffer.end(), data, data + len);
|
||||
|
||||
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_DELIVER, .payload = std::move(buffer)});
|
||||
}
|
||||
|
||||
void TuyaUART::set_status_pin_() {
|
||||
bool is_network_ready = network_is_connected() && remote_is_connected();
|
||||
this->status_pin_->digital_write(is_network_ready);
|
||||
}
|
||||
|
||||
uint8_t TuyaUART::get_wifi_status_code_() {
|
||||
uint8_t status = 0x02;
|
||||
|
||||
if (network_is_connected()) {
|
||||
status = 0x03;
|
||||
|
||||
// Protocol version 3 also supports specifying when connected to "the cloud"
|
||||
if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
|
||||
status = 0x04;
|
||||
}
|
||||
} else {
|
||||
#ifdef USE_CAPTIVE_PORTAL
|
||||
if (captive_portal::global_captive_portal != nullptr && captive_portal::global_captive_portal->is_active()) {
|
||||
status = 0x01;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
uint8_t TuyaUART::get_wifi_rssi_() {
|
||||
#ifdef USE_WIFI
|
||||
if (wifi::global_wifi_component != nullptr)
|
||||
return wifi::global_wifi_component->wifi_rssi();
|
||||
#endif
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void TuyaUART::send_wifi_status_() {
|
||||
uint8_t status = this->get_wifi_status_code_();
|
||||
|
||||
if (status == this->wifi_status_) {
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, "Sending WiFi Status");
|
||||
this->wifi_status_ = status;
|
||||
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
|
||||
}
|
||||
|
||||
#ifdef USE_TIME
|
||||
void TuyaUART::register_local_time_sync_callback_() {
|
||||
if (this->time_sync_callback_registered_) {
|
||||
return;
|
||||
}
|
||||
this->time_id_->add_on_time_sync_callback([this] { this->send_local_time_(); });
|
||||
this->time_sync_callback_registered_ = true;
|
||||
}
|
||||
|
||||
void TuyaUART::check_force_time_sync_() {
|
||||
ESPTime now = this->time_id_->now();
|
||||
if (!now.is_valid() || now.minute == this->last_force_time_sync_minute_)
|
||||
return;
|
||||
this->last_force_time_sync_minute_ = now.minute;
|
||||
this->send_local_time_(true);
|
||||
}
|
||||
|
||||
void TuyaUART::send_local_time_(bool periodic) {
|
||||
std::vector<uint8_t> payload;
|
||||
ESPTime now = this->time_id_->now();
|
||||
if (now.is_valid()) {
|
||||
uint8_t year = now.year - 2000;
|
||||
uint8_t month = now.month;
|
||||
uint8_t day_of_month = now.day_of_month;
|
||||
uint8_t hour = now.hour;
|
||||
uint8_t minute = now.minute;
|
||||
uint8_t second = now.second;
|
||||
// Tuya days starts from Monday, esphome uses Sunday as day 1
|
||||
uint8_t day_of_week = now.day_of_week - 1;
|
||||
if (day_of_week == 0) {
|
||||
day_of_week = 7;
|
||||
}
|
||||
// The forced send repeats every minute, so it stays out of the debug log
|
||||
if (periodic) {
|
||||
ESP_LOGV(TAG, "Sending local time");
|
||||
} else {
|
||||
ESP_LOGD(TAG, "Sending local time");
|
||||
}
|
||||
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
|
||||
} else {
|
||||
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
|
||||
ESP_LOGW(TAG, "Sending missing local time");
|
||||
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||
}
|
||||
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
|
||||
}
|
||||
void TuyaUART::send_gmt_time_() {
|
||||
std::vector<uint8_t> payload;
|
||||
ESPTime now = this->time_id_->utcnow();
|
||||
if (now.is_valid()) {
|
||||
uint8_t year = now.year - 2000;
|
||||
uint8_t month = now.month;
|
||||
uint8_t day_of_month = now.day_of_month;
|
||||
uint8_t hour = now.hour;
|
||||
uint8_t minute = now.minute;
|
||||
uint8_t second = now.second;
|
||||
ESP_LOGD(TAG, "Sending gmt time");
|
||||
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second};
|
||||
} else {
|
||||
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
|
||||
ESP_LOGW(TAG, "Sending missing gmt time");
|
||||
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||
}
|
||||
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::GMT_TIME_QUERY, .payload = payload});
|
||||
}
|
||||
#endif
|
||||
|
||||
TuyaInitState TuyaUART::get_init_state() { return this->init_state_; }
|
||||
|
||||
} // namespace esphome::tuya
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
|
||||
#include <cinttypes>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "tuya.h"
|
||||
#include "esphome/components/uart/uart.h"
|
||||
|
||||
#ifdef USE_TIME
|
||||
#include "esphome/components/time/real_time_clock.h"
|
||||
#include "esphome/core/time.h"
|
||||
#endif
|
||||
|
||||
namespace esphome::tuya {
|
||||
|
||||
enum class TuyaCommandType : uint8_t {
|
||||
HEARTBEAT = 0x00,
|
||||
PRODUCT_QUERY = 0x01,
|
||||
CONF_QUERY = 0x02,
|
||||
WIFI_STATE = 0x03,
|
||||
WIFI_RESET = 0x04,
|
||||
WIFI_SELECT = 0x05,
|
||||
DATAPOINT_DELIVER = 0x06,
|
||||
DATAPOINT_REPORT_ASYNC = 0x07,
|
||||
DATAPOINT_QUERY = 0x08,
|
||||
GMT_TIME_QUERY = 0x0C,
|
||||
WIFI_TEST = 0x0E,
|
||||
LOCAL_TIME_QUERY = 0x1C,
|
||||
DATAPOINT_REPORT_SYNC = 0x22,
|
||||
DATAPOINT_REPORT_ACK = 0x23,
|
||||
WIFI_RSSI = 0x24,
|
||||
VACUUM_MAP_UPLOAD = 0x28,
|
||||
GET_NETWORK_STATUS = 0x2B,
|
||||
EXTENDED_SERVICES = 0x34,
|
||||
};
|
||||
|
||||
enum class TuyaExtendedServicesCommandType : uint8_t {
|
||||
RESET_NOTIFICATION = 0x04,
|
||||
MODULE_RESET = 0x05,
|
||||
UPDATE_IN_PROGRESS = 0x0A,
|
||||
};
|
||||
|
||||
enum class TuyaInitState : uint8_t {
|
||||
INIT_HEARTBEAT = 0x00,
|
||||
INIT_PRODUCT,
|
||||
INIT_CONF,
|
||||
INIT_WIFI,
|
||||
INIT_DATAPOINT,
|
||||
INIT_DONE,
|
||||
};
|
||||
|
||||
struct TuyaCommand {
|
||||
TuyaCommandType cmd;
|
||||
std::vector<uint8_t> payload;
|
||||
};
|
||||
|
||||
/// Tuya MCU controller connected over UART (the standard Tuya serial protocol).
|
||||
class TuyaUART final : public Tuya, public uart::UARTDevice {
|
||||
public:
|
||||
void setup() override;
|
||||
void loop() override;
|
||||
void dump_config() override;
|
||||
void set_status_pin(InternalGPIOPin *status_pin) { this->status_pin_ = status_pin; }
|
||||
TuyaInitState get_init_state();
|
||||
#ifdef USE_TIME
|
||||
void set_time_id(time::RealTimeClock *time_id) { this->time_id_ = time_id; }
|
||||
void set_force_time_sync(bool force_time_sync) { this->force_time_sync_ = force_time_sync; }
|
||||
#endif
|
||||
|
||||
protected:
|
||||
void dump_mcu_config_();
|
||||
void handle_char_(uint8_t c);
|
||||
void handle_datapoints_(const uint8_t *buffer, size_t len);
|
||||
bool validate_message_();
|
||||
|
||||
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len);
|
||||
void send_raw_command_(TuyaCommand command);
|
||||
void process_command_queue_();
|
||||
void send_command_(TuyaCommand command);
|
||||
void send_empty_command_(TuyaCommandType command);
|
||||
void send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
|
||||
size_t len) override;
|
||||
void set_status_pin_();
|
||||
void send_wifi_status_();
|
||||
uint8_t get_wifi_status_code_();
|
||||
uint8_t get_wifi_rssi_();
|
||||
|
||||
#ifdef USE_TIME
|
||||
void register_local_time_sync_callback_();
|
||||
void check_force_time_sync_();
|
||||
void send_local_time_(bool periodic = false);
|
||||
void send_gmt_time_();
|
||||
time::RealTimeClock *time_id_{nullptr};
|
||||
bool force_time_sync_{false};
|
||||
uint8_t last_force_time_sync_minute_{0xFF}; // 0xFF: no minute seen yet
|
||||
bool time_sync_callback_registered_{false};
|
||||
bool gmt_time_sync_callback_registered_{false};
|
||||
#endif
|
||||
TuyaInitState init_state_ = TuyaInitState::INIT_HEARTBEAT;
|
||||
bool init_failed_{false};
|
||||
int init_retries_{0};
|
||||
uint8_t protocol_version_ = -1;
|
||||
InternalGPIOPin *status_pin_{nullptr};
|
||||
int status_pin_reported_ = -1;
|
||||
int reset_pin_reported_ = -1;
|
||||
uint32_t last_command_timestamp_ = 0;
|
||||
uint32_t last_rx_char_timestamp_ = 0;
|
||||
std::unique_ptr<char[]> product_;
|
||||
std::vector<uint8_t> rx_message_;
|
||||
std::vector<TuyaCommand> command_queue_;
|
||||
optional<TuyaCommandType> expected_response_{};
|
||||
uint8_t wifi_status_ = -1;
|
||||
bool product_invalid_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::tuya
|
||||
@@ -90,6 +90,19 @@ class UARTDevice {
|
||||
count);
|
||||
}
|
||||
|
||||
/// Feed the waiting bytes to a LengthFrameReader; on a pass with none, gap_ms after last_rx, flush a stalled frame.
|
||||
/// Returns false when a UART read failed.
|
||||
template<size_t N = 64, typename R, typename F>
|
||||
bool read_frames(R &reader, F &&handle, uint32_t now, uint32_t &last_rx, uint32_t gap_ms = 250) {
|
||||
if (const size_t count = this->available()) {
|
||||
last_rx = now;
|
||||
return this->read_available<N>([&reader, &handle](uint8_t c) { reader.feed(c, handle); }, count);
|
||||
}
|
||||
if (reader.length() != 0 && now - last_rx >= gap_ms)
|
||||
reader.flush(handle);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Read and drop every byte waiting in the receive buffer.
|
||||
void discard_available();
|
||||
|
||||
|
||||
+320
-13
@@ -1,11 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <type_traits>
|
||||
|
||||
// Out of line, one copy: the frame readers' rare paths call each other, and GCC would add specialised clones
|
||||
#if defined(__clang__)
|
||||
#define ESPHOME_FRAME_READER_COLD __attribute__((noinline))
|
||||
#else
|
||||
#define ESPHOME_FRAME_READER_COLD __attribute__((noinline, noclone))
|
||||
#endif
|
||||
|
||||
namespace esphome {
|
||||
|
||||
namespace frame_reader_detail {
|
||||
// A fold, not an array, so no header table lands in RAM on ESP8266
|
||||
template<uint8_t... HEADER> constexpr uint8_t header_byte(size_t i) {
|
||||
size_t j = 0;
|
||||
uint8_t r = 0;
|
||||
((r = (j++ == i) ? HEADER : r), ...);
|
||||
return r;
|
||||
}
|
||||
} // namespace frame_reader_detail
|
||||
|
||||
/// Collects fixed length binary frames of N bytes that start with the header bytes HEADER...; the binary twin of
|
||||
/// LineReader. Bytes before a header are skipped; checksums are left to the caller.
|
||||
template<size_t N, uint8_t... HEADER> class FrameReader {
|
||||
@@ -18,11 +37,12 @@ template<size_t N, uint8_t... HEADER> class FrameReader {
|
||||
/// Feed one byte; returns the completed frame, header included, valid until the next call, or nullptr.
|
||||
const uint8_t *feed(uint8_t c) {
|
||||
pos_t pos = this->pos_;
|
||||
if (pos < HEADER_LEN && c != header_byte(pos)) {
|
||||
if (pos < HEADER_LEN && c != frame_reader_detail::header_byte<HEADER...>(pos)) {
|
||||
// A later byte of the broken header, or c, may start the real one
|
||||
if (pos == 0)
|
||||
return nullptr;
|
||||
this->buf_[pos] = c;
|
||||
this->replay_(pos);
|
||||
return nullptr;
|
||||
return this->replay_(pos);
|
||||
}
|
||||
this->buf_[pos++] = c;
|
||||
if (pos < N) {
|
||||
@@ -44,24 +64,311 @@ template<size_t N, uint8_t... HEADER> class FrameReader {
|
||||
void resync() { this->replay_(N - 1); }
|
||||
|
||||
protected:
|
||||
// A fold, not an array, so no header table lands in RAM on ESP8266
|
||||
static constexpr uint8_t header_byte(size_t i) {
|
||||
size_t j = 0;
|
||||
uint8_t r = 0;
|
||||
((r = (j++ == i) ? HEADER : r), ...);
|
||||
return r;
|
||||
}
|
||||
|
||||
// Start over and feed buf_[1..last] again; never completes a frame as last < N
|
||||
void replay_(size_t last) {
|
||||
// Start over and feed buf_[1..last] again; never completes a frame as last < N, so it returns nullptr, which lets
|
||||
// feed() end in a tail call. Out of line, as feed() and replay_() call each other.
|
||||
const uint8_t *ESPHOME_FRAME_READER_COLD replay_(size_t last) {
|
||||
this->pos_ = 0;
|
||||
for (size_t i = 1; i <= last; i++) {
|
||||
this->feed(this->buf_[i]);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
uint8_t buf_[N];
|
||||
pos_t pos_{0};
|
||||
};
|
||||
|
||||
// Length rules: get() gives the whole frame length once KNOWN_AT bytes are in, or 0 to reject the header.
|
||||
|
||||
/// offset: where the length field starts, counted from the first header byte; trailer: the bytes after the payload
|
||||
/// (checksum, footer), for a payload length only.
|
||||
struct LengthField {
|
||||
size_t offset;
|
||||
size_t trailer = 0;
|
||||
};
|
||||
|
||||
/// Whole-frame length: the field counts every byte of the frame, header included.
|
||||
template<LengthField F> struct FrameLengthU8 {
|
||||
static_assert(F.trailer == 0, "A whole-frame length has no trailer");
|
||||
static constexpr size_t KNOWN_AT = F.offset + 1;
|
||||
static constexpr size_t get(const uint8_t *buf) { return buf[F.offset]; }
|
||||
};
|
||||
template<LengthField F> struct FrameLengthU16BE {
|
||||
static_assert(F.trailer == 0, "A whole-frame length has no trailer");
|
||||
static constexpr size_t KNOWN_AT = F.offset + 2;
|
||||
static constexpr size_t get(const uint8_t *buf) { return (size_t(buf[F.offset]) << 8) | buf[F.offset + 1]; }
|
||||
};
|
||||
template<LengthField F> struct FrameLengthU16LE {
|
||||
static_assert(F.trailer == 0, "A whole-frame length has no trailer");
|
||||
static constexpr size_t KNOWN_AT = F.offset + 2;
|
||||
static constexpr size_t get(const uint8_t *buf) { return buf[F.offset] | (size_t(buf[F.offset + 1]) << 8); }
|
||||
};
|
||||
/// Payload length: the field counts the payload right after it.
|
||||
template<LengthField F> struct PayloadLengthU8 {
|
||||
static constexpr size_t KNOWN_AT = F.offset + 1;
|
||||
static constexpr size_t get(const uint8_t *buf) { return KNOWN_AT + buf[F.offset] + F.trailer; }
|
||||
};
|
||||
template<LengthField F> struct PayloadLengthU16BE {
|
||||
static constexpr size_t KNOWN_AT = F.offset + 2;
|
||||
static constexpr size_t get(const uint8_t *buf) {
|
||||
return KNOWN_AT + FrameLengthU16BE<LengthField{.offset = F.offset}>::get(buf) + F.trailer;
|
||||
}
|
||||
};
|
||||
template<LengthField F> struct PayloadLengthU16LE {
|
||||
static constexpr size_t KNOWN_AT = F.offset + 2;
|
||||
static constexpr size_t get(const uint8_t *buf) {
|
||||
return KNOWN_AT + FrameLengthU16LE<LengthField{.offset = F.offset}>::get(buf) + F.trailer;
|
||||
}
|
||||
};
|
||||
/// A frame type that always has LEN bytes.
|
||||
template<size_t LEN> struct FrameFixedLength {
|
||||
static_assert(LEN >= 2, "A fixed length frame has at least 2 bytes");
|
||||
static constexpr size_t KNOWN_AT = 1;
|
||||
static constexpr size_t get(const uint8_t * /*buf*/) { return LEN; }
|
||||
};
|
||||
|
||||
/// Wraps a length rule: CHECK(buf) runs once AT bytes are in, and a header it fails gives length 0 (rejected).
|
||||
template<class LENGTH, size_t AT, bool (*CHECK)(const uint8_t *)> struct CheckedLength {
|
||||
static_assert(AT >= LENGTH::KNOWN_AT, "AT must cover the length field");
|
||||
static constexpr size_t KNOWN_AT = AT;
|
||||
static size_t get(const uint8_t *buf) { return CHECK(buf) ? LENGTH::get(buf) : 0; }
|
||||
};
|
||||
|
||||
/// Wraps a length rule: a frame longer than MAX calls WARN(length) and is rejected; a replay can warn again.
|
||||
template<class LENGTH, size_t MAX, void (*WARN)(size_t)> struct WarnIfLonger {
|
||||
static constexpr size_t KNOWN_AT = LENGTH::KNOWN_AT;
|
||||
static size_t get(const uint8_t *buf) {
|
||||
const size_t len = LENGTH::get(buf);
|
||||
if (len <= MAX)
|
||||
return len;
|
||||
WARN(len);
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
/// The shortest frame of a FrameFormat, when that is more than its header and length field.
|
||||
template<size_t LEN> struct FrameMinLength {
|
||||
static constexpr size_t VALUE = LEN;
|
||||
};
|
||||
|
||||
namespace frame_reader_detail {
|
||||
// The length of a FrameFixedLength rule, 0 for every other rule
|
||||
template<class LENGTH> constexpr size_t FIXED_LENGTH = 0;
|
||||
template<size_t LEN> constexpr size_t FIXED_LENGTH<FrameFixedLength<LEN>> = LEN;
|
||||
template<class LENGTH, size_t AT, bool (*CHECK)(const uint8_t *)>
|
||||
constexpr size_t FIXED_LENGTH<CheckedLength<LENGTH, AT, CHECK>> = FIXED_LENGTH<LENGTH>;
|
||||
template<class LENGTH, size_t MAX, void (*WARN)(size_t)>
|
||||
constexpr size_t FIXED_LENGTH<WarnIfLonger<LENGTH, MAX, WARN>> = FIXED_LENGTH<LENGTH>;
|
||||
// The MAX of a WarnIfLonger rule, 0 for every other rule
|
||||
template<class LENGTH> constexpr size_t WARN_MAX = 0;
|
||||
template<class LENGTH, size_t MAX, void (*WARN)(size_t)>
|
||||
constexpr size_t WARN_MAX<WarnIfLonger<LENGTH, MAX, WARN>> = MAX;
|
||||
template<class LENGTH, size_t AT, bool (*CHECK)(const uint8_t *)>
|
||||
constexpr size_t WARN_MAX<CheckedLength<LENGTH, AT, CHECK>> = WARN_MAX<LENGTH>;
|
||||
} // namespace frame_reader_detail
|
||||
|
||||
/// The bytes every frame of a FrameFormat starts with.
|
||||
template<uint8_t... BYTES> struct FrameHeader {
|
||||
static constexpr size_t LEN = sizeof...(BYTES);
|
||||
static_assert(LEN >= 1 && LEN <= 8, "A FrameHeader has 1 to 8 bytes");
|
||||
static constexpr uint8_t byte(size_t i) { return frame_reader_detail::header_byte<BYTES...>(i); }
|
||||
};
|
||||
|
||||
/// One frame type for LengthFrameReader: a FrameHeader, a length rule from above and an optional FrameMinLength.
|
||||
template<class HEADER, class LENGTH, class MIN = FrameMinLength<0>> struct FrameFormat {
|
||||
using Length = LENGTH;
|
||||
static constexpr size_t HEADER_LEN = HEADER::LEN;
|
||||
static constexpr uint8_t FIRST = HEADER::byte(0);
|
||||
// Bytes collected when the length is checked
|
||||
static constexpr size_t MIN_LEN = std::max<size_t>({LENGTH::KNOWN_AT, HEADER_LEN, 2});
|
||||
// A shorter length is not a frame
|
||||
static constexpr size_t SHORTEST = std::max(MIN_LEN, MIN::VALUE);
|
||||
static_assert(LENGTH::KNOWN_AT == 1 || LENGTH::KNOWN_AT > HEADER_LEN, "The length field must follow the header");
|
||||
static constexpr uint8_t header_byte(size_t i) { return HEADER::byte(i); }
|
||||
};
|
||||
|
||||
/// Collects binary frames that give their own length, of up to N bytes, in one or more FrameFormats; the first byte
|
||||
/// picks the format, so each format needs a different first header byte. Bytes before a header are skipped. A length
|
||||
/// that ends the frame before its length field, or is longer than N, is not a frame, and the reader looks for a
|
||||
/// header after its first byte. Checksums and footers are left to the caller, which passes a handler that returns
|
||||
/// false for a frame it rejects:
|
||||
///
|
||||
/// this->reader_.feed(c, [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); });
|
||||
///
|
||||
/// For frames of one fixed size, FrameReader is smaller.
|
||||
template<size_t N, class... FORMATS> class LengthFrameReader {
|
||||
using pos_t = std::conditional_t<(N <= 0xFF), uint8_t, uint16_t>;
|
||||
static_assert(sizeof...(FORMATS) >= 1, "LengthFrameReader takes at least one FrameFormat");
|
||||
// flush_() copies a partial frame on the stack
|
||||
static_assert(N >= 2 && N <= 1024, "LengthFrameReader size out of range");
|
||||
static constexpr bool distinct_first() {
|
||||
const uint8_t first[] = {FORMATS::FIRST...};
|
||||
for (size_t i = 0; i < sizeof...(FORMATS); i++) {
|
||||
for (size_t j = i + 1; j < sizeof...(FORMATS); j++) {
|
||||
if (first[i] == first[j])
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
static_assert(distinct_first(), "Each FrameFormat needs a different first header byte");
|
||||
static_assert(((FORMATS::SHORTEST <= N) && ...), "N must hold the shortest frame of every FrameFormat");
|
||||
static_assert(((frame_reader_detail::FIXED_LENGTH<typename FORMATS::Length> == 0 ||
|
||||
(frame_reader_detail::FIXED_LENGTH<typename FORMATS::Length> >= FORMATS::SHORTEST &&
|
||||
frame_reader_detail::FIXED_LENGTH<typename FORMATS::Length> <= N)) &&
|
||||
...),
|
||||
"A fixed length must hold the header and fit in N");
|
||||
static_assert(((frame_reader_detail::WARN_MAX<typename FORMATS::Length> <= N) && ...),
|
||||
"A WarnIfLonger MAX above N lets longer frames be skipped without a warning");
|
||||
|
||||
public:
|
||||
/// Feed one byte; calls handle(frame, length) for each frame it completes, header included. A rejected frame
|
||||
/// (handle returns false) is searched for frames inside it and after it, which go to handle the same way.
|
||||
/// handle must not feed this reader again: the frame and the bytes held behind it live in its buffer.
|
||||
template<class F> void __attribute__((always_inline)) feed(uint8_t c, F &&handle) {
|
||||
// Most bytes are in the middle of a frame whose length is known, and not its last byte
|
||||
const pos_t pos = this->pos_;
|
||||
if (pos + 1u < this->end_) {
|
||||
this->buf_[pos] = c;
|
||||
this->pos_ = pos + 1;
|
||||
} else if (const size_t len = this->feed_edge_(c)) {
|
||||
this->drain_(len, handle);
|
||||
}
|
||||
}
|
||||
|
||||
/// For a partial frame idle too long: hands over the frames a corrupt length holds back inside it, else keeps it for
|
||||
/// a slow UART. UARTDevice::read_frames() calls this.
|
||||
template<class F> void flush(F &&handle) {
|
||||
// held_end_ marks a partial frame already searched; new bytes move pos_ past it
|
||||
if (this->pos_ != 0 && this->held_end_ != this->pos_)
|
||||
this->flush_(handle);
|
||||
}
|
||||
|
||||
/// Number of bytes of the partial frame; 0 after a frame is returned and while looking for a header.
|
||||
size_t length() const { return this->pos_; }
|
||||
|
||||
/// Whether a frame is coming in: a partial frame that an idle flush has not searched and kept.
|
||||
bool receiving() const { return this->pos_ != 0 && this->held_end_ != this->pos_; }
|
||||
|
||||
/// Forget a partial frame an idle flush kept, before a request starts a new exchange; safe inside a frame handler.
|
||||
void drop_kept() {
|
||||
if (this->pos_ != 0 && this->held_end_ == this->pos_)
|
||||
this->reset();
|
||||
}
|
||||
|
||||
/// Forget the partial frame, for a request/response protocol starting a new exchange.
|
||||
void reset() {
|
||||
this->pos_ = 0;
|
||||
this->end_ = 0;
|
||||
this->held_end_ = 0;
|
||||
}
|
||||
|
||||
protected:
|
||||
// Hands each frame (len bytes at buf_) to handle, then goes on after a handled frame or from the second byte of a
|
||||
// rejected one
|
||||
template<class F> bool ESPHOME_FRAME_READER_COLD drain_(size_t len, F &handle) {
|
||||
bool handled = false;
|
||||
while (len != 0) {
|
||||
const bool ok = handle(this->buf_, len);
|
||||
handled |= ok;
|
||||
len = this->replay_(ok ? len : 1, this->held_end_);
|
||||
}
|
||||
this->held_end_ = 0;
|
||||
return handled;
|
||||
}
|
||||
|
||||
// Searches the partial frame for frames; when handle takes none, puts the partial frame back and marks it searched
|
||||
template<class F> void ESPHOME_FRAME_READER_COLD flush_(F &handle) {
|
||||
const pos_t pos = this->pos_;
|
||||
const pos_t end = this->end_;
|
||||
uint8_t saved[N];
|
||||
std::memcpy(saved, this->buf_, pos);
|
||||
while (this->pos_ != 0) {
|
||||
// A partial frame left behind the handed over ones is searched on the next idle pass
|
||||
if (this->drain_(this->replay_(1, this->pos_), handle))
|
||||
return;
|
||||
}
|
||||
std::memcpy(this->buf_, saved, pos);
|
||||
this->pos_ = pos;
|
||||
this->end_ = end;
|
||||
this->held_end_ = pos;
|
||||
}
|
||||
|
||||
// Every byte but the middle of a frame; returns the length of a completed frame, or 0
|
||||
size_t ESPHOME_FRAME_READER_COLD feed_edge_(uint8_t c) {
|
||||
// A byte that starts or ends a frame clears the searched mark, so it cannot match a later partial frame
|
||||
this->held_end_ = 0;
|
||||
const pos_t pos = this->pos_;
|
||||
if (pos == 0) {
|
||||
const bool header = ((c == FORMATS::FIRST) || ...);
|
||||
if (header) {
|
||||
this->buf_[0] = c;
|
||||
this->pos_ = 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if constexpr (sizeof...(FORMATS) == 1) {
|
||||
return this->feed_as_<FORMATS...>(pos, c);
|
||||
} else {
|
||||
const uint8_t first = this->buf_[0];
|
||||
size_t len = 0;
|
||||
(void) ((first == FORMATS::FIRST && ((len = this->feed_as_<FORMATS>(pos, c)), true)) || ...);
|
||||
return len;
|
||||
}
|
||||
}
|
||||
|
||||
template<class F> size_t feed_as_(pos_t pos, uint8_t c) {
|
||||
if (pos < F::HEADER_LEN && c != F::header_byte(pos)) {
|
||||
// A later byte of the broken header, or c, may start the real one
|
||||
this->buf_[pos] = c;
|
||||
return this->replay_(1, pos + 1);
|
||||
}
|
||||
this->buf_[pos++] = c;
|
||||
if (pos == F::MIN_LEN) {
|
||||
const size_t len = F::Length::get(this->buf_);
|
||||
if (len < F::SHORTEST || len > N)
|
||||
return this->replay_(1, pos);
|
||||
this->end_ = len;
|
||||
}
|
||||
if (pos == this->end_) {
|
||||
this->pos_ = 0;
|
||||
this->end_ = 0;
|
||||
this->held_end_ = pos;
|
||||
return pos;
|
||||
}
|
||||
this->pos_ = pos;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Start over and feed buf_[from..to) again; writes stay behind the read position. On a completed frame, moves the
|
||||
// bytes not fed yet right behind it, for drain_(), and returns its length; 0 otherwise.
|
||||
size_t ESPHOME_FRAME_READER_COLD replay_(size_t from, size_t to) {
|
||||
this->pos_ = 0;
|
||||
this->end_ = 0;
|
||||
for (size_t i = from; i < to; i++) {
|
||||
const size_t len = this->feed_edge_(this->buf_[i]);
|
||||
if (len == 0)
|
||||
continue;
|
||||
// A nested replay may already have put bytes of its own behind the frame
|
||||
const size_t held = this->held_end_;
|
||||
const size_t rest = to - i - 1;
|
||||
std::memmove(this->buf_ + held, this->buf_ + i + 1, rest);
|
||||
this->held_end_ = held + rest;
|
||||
return len;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Before buf_, so they stay within a short load offset of the reader when N is large
|
||||
pos_t pos_{0};
|
||||
// Length of the frame being collected once its length is known; 0 otherwise
|
||||
pos_t end_{0};
|
||||
// End of a held frame plus the bytes after it not fed yet; or, after flush() kept a partial frame, the pos_ it
|
||||
// searched
|
||||
pos_t held_end_{0};
|
||||
uint8_t buf_[N];
|
||||
};
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
#undef ESPHOME_FRAME_READER_COLD
|
||||
@@ -20,6 +20,12 @@ static constexpr uint8_t FRAME_30[30] = {0xAA, 0xFF, 0x03, 0x00, 0x0E, 0x03, 0xB
|
||||
static constexpr uint8_t ULTRASONIC_NOISY[] = {0x12, 0xFF, 0x07, 0xA1, 0xA7, 0x34, 0xFF, 0xFF, 0x07, 0xA1, 0xA7,
|
||||
0x00, 0xFF, 0x07, 0xA1, 0xA7, 0x56, 0xFF, 0x07, 0xA1, 0xA7};
|
||||
|
||||
// Pioneer WT shaped frames (A5 01 header, whole-frame length at byte 7) of 12, 20 and 12 bytes among noise
|
||||
static constexpr uint8_t LENGTH_FRAMES[] = {0x00, 0xA5, 0x01, 0x01, 0x23, 0x00, 0xA5, 0x00, 0x0C, 0x11, 0x22, 0x33,
|
||||
0x44, 0xA5, 0x01, 0x01, 0x23, 0x00, 0xA5, 0x00, 0x14, 0x11, 0x22, 0x33,
|
||||
0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0x7E, 0xA5, 0x01,
|
||||
0x01, 0x23, 0x00, 0xA5, 0x00, 0x0C, 0x11, 0x22, 0x33, 0x44};
|
||||
|
||||
// --- LineReader: one GGA sentence fed byte by byte ---
|
||||
|
||||
static void LineReader_NmeaLine(benchmark::State &state) {
|
||||
@@ -93,4 +99,32 @@ static void FrameReader_UltrasonicNoisy(benchmark::State &state) {
|
||||
}
|
||||
BENCHMARK(FrameReader_UltrasonicNoisy);
|
||||
|
||||
// --- LengthFrameReader: frames of different lengths among noise ---
|
||||
|
||||
// A5 01, whole-frame length at 7
|
||||
using PioneerFormat = FrameFormat<FrameHeader<0xA5, 0x01>, FrameLengthU8<LengthField{.offset = 7}>>;
|
||||
|
||||
static void LengthFrameReader_MixedFrames(benchmark::State &state) {
|
||||
LengthFrameReader<255, PioneerFormat> reader;
|
||||
const uint8_t *bytes = LENGTH_FRAMES;
|
||||
uint32_t frames = 0;
|
||||
|
||||
auto handle = [&frames](const uint8_t *frame, size_t /*len*/) {
|
||||
benchmark::DoNotOptimize(frame);
|
||||
frames++;
|
||||
return true;
|
||||
};
|
||||
|
||||
for (auto _ : state) {
|
||||
benchmark::DoNotOptimize(bytes);
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
for (size_t j = 0; j < sizeof(LENGTH_FRAMES); j++)
|
||||
reader.feed(bytes[j], handle);
|
||||
}
|
||||
benchmark::DoNotOptimize(frames);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LengthFrameReader_MixedFrames);
|
||||
|
||||
} // namespace esphome::benchmarks
|
||||
@@ -4,7 +4,6 @@ from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -148,42 +147,6 @@ def test_set_value_constants_share_a_flash_table(
|
||||
assert "ByteBuffer::wrap" not in main_cpp
|
||||
|
||||
|
||||
def test_yaml_services_and_characteristics_are_static(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
main_cpp = generate_main(component_config_path("own_service.yaml"))
|
||||
|
||||
# Placement new into static storage, with handle count then advertise
|
||||
service = re.search(
|
||||
r"new\((\w+)\) esp32_ble_server::BLEService\("
|
||||
r'esp32_ble::ESPBTUUID::from_raw\("2A24B789-7AAB-4535-AF3E-EE76A35CC12D"\), \d+, (?:true|false)\);',
|
||||
main_cpp,
|
||||
)
|
||||
assert service is not None
|
||||
assert f"ble_server->add_service((*{service[1]}));" in main_cpp
|
||||
characteristic = re.search(
|
||||
r"new\((\w+)\) esp32_ble_server::BLECharacteristic\("
|
||||
r'esp32_ble::ESPBTUUID::from_raw\("CAD48E28-7FBE-41CF-BAE9-D77A6C233423"\)',
|
||||
main_cpp,
|
||||
)
|
||||
assert characteristic is not None
|
||||
assert f"{service[1]}->add_characteristic((*{characteristic[1]}));" in main_cpp
|
||||
assert "create_service(" not in main_cpp
|
||||
assert "create_characteristic(" not in main_cpp
|
||||
|
||||
|
||||
def test_yaml_descriptors_are_added_by_reference(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
main_cpp = generate_main(component_config_path("set_value.yaml"))
|
||||
|
||||
# Descriptors live in static storage, so the characteristic must not take ownership
|
||||
assert "->add_descriptor((*test_descriptor));" in main_cpp
|
||||
assert "->add_descriptor(test_descriptor);" not in main_cpp
|
||||
|
||||
|
||||
def test_float32_rejects_out_of_range() -> None:
|
||||
for value in (1e40, -1e40):
|
||||
with pytest.raises(cv.Invalid, match="out of range for a float"):
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
|
||||
external_components:
|
||||
- source:
|
||||
type: local
|
||||
path: ../../../components/tuya/components
|
||||
|
||||
fake_tuya_transport:
|
||||
id: my_tuya
|
||||
|
||||
switch:
|
||||
- platform: tuya
|
||||
tuya_id: my_tuya
|
||||
name: Fake Switch
|
||||
switch_datapoint: 1
|
||||
@@ -0,0 +1,25 @@
|
||||
"""End-to-end test of the base-class split through the config pipeline."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from esphome.components.tuya import FILTER_SOURCE_FILES
|
||||
from esphome.core import CORE
|
||||
|
||||
|
||||
def test_non_uart_transport_loads_base_only(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
main_cpp = generate_main(component_config_path("fake_transport.yaml"))
|
||||
|
||||
# The fake transport and the tuya switch resolve through the base class
|
||||
assert "fake_tuya_transport::FakeTuyaTransport" in main_cpp
|
||||
assert "tuya::TuyaSwitch" in main_cpp
|
||||
|
||||
# The UART transport is neither loaded nor instantiated...
|
||||
assert "uart" not in CORE.loaded_integrations
|
||||
assert "TuyaUART" not in main_cpp
|
||||
|
||||
# ...and its sources are excluded from the build
|
||||
assert sorted(FILTER_SOURCE_FILES()) == ["tuya_uart.cpp", "tuya_uart.h"]
|
||||
@@ -3,7 +3,7 @@
|
||||
import pytest
|
||||
|
||||
from esphome import config_validation as cv
|
||||
from esphome.components.tuya import CONF_FORCE_TIME_SYNC, CONFIG_SCHEMA
|
||||
from esphome.components.tuya import AUTO_LOAD, CONF_FORCE_TIME_SYNC, CONFIG_SCHEMA
|
||||
from esphome.const import CONF_TIME_ID
|
||||
|
||||
|
||||
@@ -21,3 +21,8 @@ def test_force_time_sync_accepts_time_id() -> None:
|
||||
def test_force_time_sync_requires_time_id() -> None:
|
||||
with pytest.raises(cv.Invalid, match="force_time_sync requires time_id"):
|
||||
CONFIG_SCHEMA({CONF_FORCE_TIME_SYNC: True})
|
||||
|
||||
|
||||
def test_auto_load_requests_uart_for_probe_and_config() -> None:
|
||||
assert AUTO_LOAD(None) == ["uart"]
|
||||
assert AUTO_LOAD({"id": "x"}) == ["uart"]
|
||||
@@ -140,4 +140,372 @@ TEST(FrameReaderTest, SixteenBitIndex) {
|
||||
EXPECT_EQ(frames[0][299], 0x42);
|
||||
}
|
||||
|
||||
// Feeds bytes and collects every frame the reader hands over, rejecting those reject() picks.
|
||||
template<size_t N, class... F, class R>
|
||||
static Frames feed_all(LengthFrameReader<N, F...> &reader, const Bytes &input, R reject) {
|
||||
Frames frames;
|
||||
auto handle = [&](const uint8_t *frame, size_t len) {
|
||||
frames.emplace_back(frame, frame + len);
|
||||
return !reject(frames.back());
|
||||
};
|
||||
for (uint8_t c : input)
|
||||
reader.feed(c, handle);
|
||||
return frames;
|
||||
}
|
||||
template<size_t N, class... F> static Frames feed_all(LengthFrameReader<N, F...> &reader, const Bytes &input) {
|
||||
return feed_all(reader, input, [](const Bytes & /*frame*/) { return false; });
|
||||
}
|
||||
|
||||
// Takes every frame and keeps a copy
|
||||
struct Collect {
|
||||
Frames seen;
|
||||
bool operator()(const uint8_t *frame, size_t len) {
|
||||
this->seen.emplace_back(frame, frame + len);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// pioneer_wt: A5 01, one byte at 7 holds the whole length
|
||||
using OneByte = FrameFormat<FrameHeader<0xA5, 0x01>, FrameLengthU8<LengthField{.offset = 7}>>;
|
||||
// tuya: 55 AA, version, command, payload length (2, BE), payload, checksum
|
||||
using TwoByteBE = FrameFormat<FrameHeader<0x55, 0xAA>, PayloadLengthU16BE<LengthField{.offset = 4, .trailer = 1}>>;
|
||||
// ld24xx command and data frames: header (4), payload length (2, LE), payload, footer (4)
|
||||
using LdCmd =
|
||||
FrameFormat<FrameHeader<0xFD, 0xFC, 0xFB, 0xFA>, PayloadLengthU16LE<LengthField{.offset = 4, .trailer = 4}>>;
|
||||
using LdData =
|
||||
FrameFormat<FrameHeader<0xF4, 0xF3, 0xF2, 0xF1>, PayloadLengthU16LE<LengthField{.offset = 4, .trailer = 4}>>;
|
||||
// ld2410s short frame: 6E, always 5 bytes
|
||||
using LdShort = FrameFormat<FrameHeader<0x6E>, FrameFixedLength<5>>;
|
||||
// Small format for the recovery tests: A5, one byte at 1 holds the whole length
|
||||
using Small = FrameFormat<FrameHeader<0xA5>, FrameLengthU8<LengthField{.offset = 1}>>;
|
||||
|
||||
static_assert(sizeof(LengthFrameReader<255, OneByte>) == 258);
|
||||
static_assert(sizeof(LengthFrameReader<300, TwoByteBE>) == 306);
|
||||
|
||||
TEST(LengthFrameReaderTest, OneByteLength) {
|
||||
LengthFrameReader<16, OneByte> reader;
|
||||
EXPECT_EQ(feed_all(reader, {0x00, 0xA5, 0x01, 0x10, 0x11, 0x12, 0x13, 0x00, 0x09, 0x42}),
|
||||
(Frames{{0xA5, 0x01, 0x10, 0x11, 0x12, 0x13, 0x00, 0x09, 0x42}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, TwoByteBigEndianPayloadLength) {
|
||||
LengthFrameReader<300, TwoByteBE> reader;
|
||||
// Payload of 0x0102 = 258 bytes: 265 in all, past an 8-bit index
|
||||
Bytes input{0x55, 0xAA, 0x03, 0x07, 0x01, 0x02};
|
||||
input.resize(265, 0x33);
|
||||
Frames frames = feed_all(reader, input);
|
||||
ASSERT_EQ(frames.size(), 1u);
|
||||
EXPECT_EQ(frames[0].size(), 265u);
|
||||
// Too long for N: not a frame
|
||||
EXPECT_EQ(feed_all(reader, {0x55, 0xAA, 0x03, 0x07, 0x01, 0x30}), Frames{});
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, LittleEndianLengthsAboveAByte) {
|
||||
// Whole-frame length 0x0102 = 258, low byte first
|
||||
LengthFrameReader<300, FrameFormat<FrameHeader<0xA5>, FrameLengthU16LE<LengthField{.offset = 1}>>> whole;
|
||||
Bytes input{0xA5, 0x02, 0x01};
|
||||
input.resize(258, 0x33);
|
||||
Frames frames = feed_all(whole, input);
|
||||
ASSERT_EQ(frames.size(), 1u);
|
||||
EXPECT_EQ(frames[0].size(), 258u);
|
||||
// Payload length 0x0100 = 256 after the field, then a 1 byte trailer: 260 in all
|
||||
LengthFrameReader<300, FrameFormat<FrameHeader<0xA5>, PayloadLengthU16LE<LengthField{.offset = 1, .trailer = 1}>>>
|
||||
payload;
|
||||
input = {0xA5, 0x00, 0x01};
|
||||
input.resize(260, 0x44);
|
||||
frames = feed_all(payload, input);
|
||||
ASSERT_EQ(frames.size(), 1u);
|
||||
EXPECT_EQ(frames[0].size(), 260u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, TwoFormatsPickedByFirstByte) {
|
||||
LengthFrameReader<32, LdCmd, LdData> reader;
|
||||
const Bytes cmd{0xFD, 0xFC, 0xFB, 0xFA, 0x02, 0x00, 0xA0, 0x01, 0x04, 0x03, 0x02, 0x01};
|
||||
const Bytes data{0xF4, 0xF3, 0xF2, 0xF1, 0x01, 0x00, 0x55, 0xF8, 0xF7, 0xF6, 0xF5};
|
||||
Bytes input{0x00};
|
||||
input.insert(input.end(), data.begin(), data.end());
|
||||
input.insert(input.end(), cmd.begin(), cmd.end());
|
||||
EXPECT_EQ(feed_all(reader, input), (Frames{data, cmd}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, FixedAndLengthFormatsTogether) {
|
||||
LengthFrameReader<32, LdShort, LdData> reader;
|
||||
const Bytes small{0x6E, 0x01, 0x02, 0x03, 0x62};
|
||||
const Bytes data{0xF4, 0xF3, 0xF2, 0xF1, 0x00, 0x00, 0xF8, 0xF7, 0xF6, 0xF5};
|
||||
Bytes input = small;
|
||||
input.insert(input.end(), data.begin(), data.end());
|
||||
input.insert(input.end(), small.begin(), small.end());
|
||||
EXPECT_EQ(feed_all(reader, input), (Frames{small, data, small}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, BrokenHeaderRealigns) {
|
||||
LengthFrameReader<32, LdCmd, LdData> reader;
|
||||
// FD FC then F4 breaks the command header and starts a data header
|
||||
const Bytes data{0xF4, 0xF3, 0xF2, 0xF1, 0x00, 0x00, 0xF8, 0xF7, 0xF6, 0xF5};
|
||||
Bytes input{0xFD, 0xFC};
|
||||
input.insert(input.end(), data.begin(), data.end());
|
||||
EXPECT_EQ(feed_all(reader, input), (Frames{data}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, BrokenHeaderHoldsAShorterFrameOfAnotherFormat) {
|
||||
// FD FC FB then 77 breaks the command header; its replay finds a whole 2 byte FC frame and keeps the 77 behind it
|
||||
LengthFrameReader<32, LdCmd, FrameFormat<FrameHeader<0xFC>, FrameFixedLength<2>>> reader;
|
||||
EXPECT_EQ(feed_all(reader, {0xFD, 0xFC, 0xFB, 0x77}), (Frames{{0xFC, 0xFB}}));
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
// The held 77 was noise, so the next frame is found normally
|
||||
EXPECT_EQ(feed_all(reader, {0xFC, 0x01}), (Frames{{0xFC, 0x01}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, RejectedFrameHoldsFramesOfBothFormats) {
|
||||
LengthFrameReader<32, LdShort, Small> reader;
|
||||
// A rejected 12 byte A5 frame holds a whole short frame, a whole A5 frame and the start of another
|
||||
auto reject_12 = [](const Bytes &frame) { return frame.size() == 12; };
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x0C, 0x6E, 0x01, 0x02, 0x03, 0x62, 0xA5, 0x03, 0x09, 0xA5, 0x05}, reject_12),
|
||||
(Frames{{0xA5, 0x0C, 0x6E, 0x01, 0x02, 0x03, 0x62, 0xA5, 0x03, 0x09, 0xA5, 0x05},
|
||||
{0x6E, 0x01, 0x02, 0x03, 0x62},
|
||||
{0xA5, 0x03, 0x09}}));
|
||||
EXPECT_EQ(reader.length(), 2u);
|
||||
EXPECT_EQ(feed_all(reader, {0x11, 0x22, 0x33}), (Frames{{0xA5, 0x05, 0x11, 0x22, 0x33}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, BadLengthRealignsAfterFirstByte) {
|
||||
LengthFrameReader<8, Small> reader;
|
||||
// 0x01 ends the frame before its length byte and 0x09 is longer than 8: neither is a frame.
|
||||
// The second A5 inside the bad one starts the real frame.
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x01, 0xA5, 0x09, 0xA5, 0x04, 0x01, 0x02}), (Frames{{0xA5, 0x04, 0x01, 0x02}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, LengthByteCanStartHeader) {
|
||||
LengthFrameReader<8, FrameFormat<FrameHeader<0x09>, FrameLengthU8<LengthField{.offset = 1}>>> reader;
|
||||
// Length 9 is longer than 8, so the length byte becomes the next header
|
||||
EXPECT_EQ(feed_all(reader, {0x09, 0x09, 0x03, 0x07}), (Frames{{0x09, 0x03, 0x07}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, LengthTracksPartialFrame) {
|
||||
LengthFrameReader<8, Small> reader;
|
||||
EXPECT_EQ(feed_all(reader, {0x01, 0xA5, 0x05}), Frames{});
|
||||
EXPECT_EQ(reader.length(), 2u);
|
||||
EXPECT_EQ(feed_all(reader, {0x10, 0x20, 0x30}), (Frames{{0xA5, 0x05, 0x10, 0x20, 0x30}}));
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, RejectedFrameIsSearchedForAHeader) {
|
||||
LengthFrameReader<8, Small> reader;
|
||||
// The A5 taken as a header was payload; the real frame starts at the second A5
|
||||
auto reject_long = [](const Bytes &frame) { return frame.size() == 5; };
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x05, 0x00, 0xA5, 0x04}, reject_long), (Frames{{0xA5, 0x05, 0x00, 0xA5, 0x04}}));
|
||||
EXPECT_EQ(reader.length(), 2u);
|
||||
EXPECT_EQ(feed_all(reader, {0x10, 0x20}, reject_long), (Frames{{0xA5, 0x04, 0x10, 0x20}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, RejectionRecoversEveryFrameInside) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
// The 9 byte frame is rejected; the two frames inside it are handed over too, and a partial one is kept
|
||||
auto reject_9 = [](const Bytes &frame) { return frame.size() == 9; };
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x02, 0xA5, 0x04}, reject_9),
|
||||
(Frames{{0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x02, 0xA5, 0x04}, {0xA5, 0x03, 0x01}, {0xA5, 0x02}}));
|
||||
EXPECT_EQ(reader.length(), 2u);
|
||||
EXPECT_EQ(feed_all(reader, {0x01, 0x02}), (Frames{{0xA5, 0x04, 0x01, 0x02}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, RecoveredFrameRejectedTooIsSearched) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
// The 9 byte frame holds a 4 byte candidate, which holds a 3 byte one; both outer ones are rejected
|
||||
auto reject_outer = [](const Bytes &frame) { return frame.size() != 3; };
|
||||
EXPECT_EQ(
|
||||
feed_all(reader, {0xA5, 0x09, 0xA5, 0x04, 0xA5, 0x03, 0x01, 0x02, 0x03}, reject_outer),
|
||||
(Frames{{0xA5, 0x09, 0xA5, 0x04, 0xA5, 0x03, 0x01, 0x02, 0x03}, {0xA5, 0x04, 0xA5, 0x03}, {0xA5, 0x03, 0x01}}));
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, FlushHandsOverFramesHeldBack) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
// A corrupt length of 15 holds back two complete frames until flush()
|
||||
for (uint8_t c : {0xA5, 0x0F, 0xA5, 0x04, 0x01, 0x02, 0xA5, 0x03, 0x09})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_EQ(handle.seen, Frames{});
|
||||
EXPECT_EQ(reader.length(), 9u);
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0xA5, 0x04, 0x01, 0x02}, {0xA5, 0x03, 0x09}}));
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
reader.flush(handle); // nothing collected: nothing to do
|
||||
EXPECT_EQ(handle.seen.size(), 2u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, FlushKeepsASlowFrameUntilTheRestArrives) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
for (uint8_t c : {0xA5, 0x06, 0xA5, 0x03})
|
||||
reader.feed(c, handle);
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(handle.seen, Frames{});
|
||||
EXPECT_EQ(reader.length(), 4u);
|
||||
for (uint8_t c : {0x01, 0x02})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0xA5, 0x06, 0xA5, 0x03, 0x01, 0x02}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, FlushKeepsASlowFrameBehindTheFramesItHandsOver) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
// A corrupt length holds a whole frame, then the start of a slow one
|
||||
for (uint8_t c : {0xA5, 0x0F, 0xA5, 0x04, 0x01, 0x02, 0xA5, 0x05, 0x11})
|
||||
reader.feed(c, handle);
|
||||
reader.flush(handle);
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0xA5, 0x04, 0x01, 0x02}}));
|
||||
EXPECT_EQ(reader.length(), 3u);
|
||||
for (uint8_t c : {0x22, 0x33})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0xA5, 0x04, 0x01, 0x02}, {0xA5, 0x05, 0x11, 0x22, 0x33}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, ReceivingUntilAnIdleFlushKeepsTheFrame) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
EXPECT_FALSE(reader.receiving());
|
||||
for (uint8_t c : {0xA5, 0x06, 0x01})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_TRUE(reader.receiving());
|
||||
reader.flush(handle);
|
||||
EXPECT_FALSE(reader.receiving());
|
||||
reader.feed(0x02, handle);
|
||||
EXPECT_TRUE(reader.receiving());
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, NewBytesAtTheSearchedLengthAreSearchedAgain) {
|
||||
// A5 with a whole-frame length at 5, and a fixed two-byte 6E frame
|
||||
LengthFrameReader<16, FrameFormat<FrameHeader<0xA5>, FrameLengthU8<LengthField{.offset = 5}>>,
|
||||
FrameFormat<FrameHeader<0x6E>, FrameFixedLength<2>>>
|
||||
reader;
|
||||
Collect handle;
|
||||
for (uint8_t c : {0xA5, 0xA5, 0x00, 0x00, 0x6E})
|
||||
reader.feed(c, handle);
|
||||
reader.flush(handle);
|
||||
reader.feed(0x01, handle);
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0x6E, 0x01}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, ResyncAfterASearchedFrameIsSearchedAgain) {
|
||||
// A5 with a whole-frame length at 3, and a fixed two-byte AA frame
|
||||
LengthFrameReader<6, FrameFormat<FrameHeader<0xA5>, FrameLengthU8<LengthField{.offset = 3}>>,
|
||||
FrameFormat<FrameHeader<0xAA>, FrameFixedLength<2>>>
|
||||
reader;
|
||||
Collect handle;
|
||||
for (uint8_t c : {0xA5, 0xA5, 0xAA})
|
||||
reader.feed(c, handle);
|
||||
reader.flush(handle);
|
||||
reader.feed(0x07, handle);
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0xAA, 0x07}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, FlushKeepsTheFrameWhenEveryFrameInsideIsRejected) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
size_t calls = 0;
|
||||
auto reject = [&calls](const uint8_t *, size_t) {
|
||||
calls++;
|
||||
return false;
|
||||
};
|
||||
for (uint8_t c : {0xA5, 0x0F, 0xA5, 0x03, 0x09})
|
||||
reader.feed(c, reject);
|
||||
reader.flush(reject);
|
||||
EXPECT_EQ(calls, 1u);
|
||||
EXPECT_EQ(reader.length(), 5u);
|
||||
// Searched once until a new byte comes
|
||||
reader.flush(reject);
|
||||
EXPECT_EQ(calls, 1u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, ResetForgetsThePartialFrame) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x05, 0x11}), Frames{});
|
||||
reader.reset();
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x03, 0x22}), (Frames{{0xA5, 0x03, 0x22}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, DropKeptLeavesAFrameStillComingIn) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
for (uint8_t c : {0xA5, 0x06, 0x01})
|
||||
reader.feed(c, handle);
|
||||
reader.drop_kept();
|
||||
EXPECT_EQ(reader.length(), 3u);
|
||||
reader.flush(handle);
|
||||
reader.drop_kept();
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, DropKeptInsideAHandlerKeepsTheHeldFrames) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Frames seen;
|
||||
auto handle = [&reader, &seen](const uint8_t *frame, size_t len) {
|
||||
seen.emplace_back(frame, frame + len);
|
||||
reader.drop_kept();
|
||||
return frame[1] != 0x09;
|
||||
};
|
||||
for (uint8_t c : {0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x03, 0x02, 0x00})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_EQ(seen,
|
||||
(Frames{{0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x03, 0x02, 0x00}, {0xA5, 0x03, 0x01}, {0xA5, 0x03, 0x02}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, IdleAfterHandledFrameFindsNothingInIt) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Collect handle;
|
||||
// A handled frame whose payload looks like a frame of its own, then noise
|
||||
for (uint8_t c : {0xA5, 0x06, 0xA5, 0x03, 0x01, 0x02, 0x00})
|
||||
reader.feed(c, handle);
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(handle.seen, (Frames{{0xA5, 0x06, 0xA5, 0x03, 0x01, 0x02}}));
|
||||
}
|
||||
|
||||
// A custom rule known at the first byte that reads the buffer builds (only FrameFixedLength is checked up front)
|
||||
struct FirstByteLength {
|
||||
static constexpr size_t KNOWN_AT = 1;
|
||||
static constexpr size_t get(const uint8_t *buf) { return buf[0]; }
|
||||
};
|
||||
|
||||
TEST(LengthFrameReaderTest, CustomRuleKnownAtTheFirstByte) {
|
||||
LengthFrameReader<8, FrameFormat<FrameHeader<0x03>, FirstByteLength>> reader;
|
||||
EXPECT_EQ(feed_all(reader, {0x03, 0x01, 0x02, 0x03}), (Frames{{0x03, 0x01, 0x02}}));
|
||||
}
|
||||
|
||||
// A5, payload length at 1, payload, checksum; a frame has at least 2 payload bytes
|
||||
using MinTwo =
|
||||
FrameFormat<FrameHeader<0xA5>, PayloadLengthU8<LengthField{.offset = 1, .trailer = 1}>, FrameMinLength<5>>;
|
||||
|
||||
TEST(LengthFrameReaderTest, LengthBelowTheMinimumIsRejectedAtTheHeader) {
|
||||
LengthFrameReader<16, MinTwo> reader;
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x00, 0xA5, 0x02, 0x10, 0x20, 0x30}), (Frames{{0xA5, 0x02, 0x10, 0x20, 0x30}}));
|
||||
}
|
||||
|
||||
static bool second_byte_not_ff(const uint8_t *buf) { return buf[1] != 0xFF; }
|
||||
// A5, a byte that must not be FF, payload length at 2, payload
|
||||
using Checked =
|
||||
FrameFormat<FrameHeader<0xA5>, CheckedLength<PayloadLengthU8<LengthField{.offset = 2}>, 3, second_byte_not_ff>>;
|
||||
|
||||
static size_t &warned_len() {
|
||||
static size_t len = 0;
|
||||
return len;
|
||||
}
|
||||
static void note_too_long(size_t len) { warned_len() = len; }
|
||||
|
||||
TEST(LengthFrameReaderTest, WarnIfLongerRejectsAndReports) {
|
||||
LengthFrameReader<
|
||||
8, FrameFormat<FrameHeader<0xA5>, WarnIfLonger<FrameLengthU8<LengthField{.offset = 1}>, 8, note_too_long>>>
|
||||
reader;
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x09, 0xA5, 0x03, 0x42}), (Frames{{0xA5, 0x03, 0x42}}));
|
||||
EXPECT_EQ(warned_len(), 9u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, CheckedLengthRejectsABadHeader) {
|
||||
LengthFrameReader<16, Checked> reader;
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0xFF, 0x01, 0xA5, 0x00, 0x01, 0x42}), (Frames{{0xA5, 0x00, 0x01, 0x42}}));
|
||||
}
|
||||
|
||||
} // namespace esphome::core::testing
|
||||
@@ -1,18 +1,3 @@
|
||||
esphome:
|
||||
on_boot:
|
||||
- lambda: |-
|
||||
// Objects the caller keeps alive, registered without heap allocation
|
||||
static esp32_ble_server::BLEService battery(esp32_ble::ESPBTUUID::from_uint16(0x180F), 6, false);
|
||||
static esp32_ble_server::BLECharacteristic level(
|
||||
esp32_ble::ESPBTUUID::from_uint16(0x2A19),
|
||||
esp32_ble_server::BLECharacteristic::PROPERTY_READ | esp32_ble_server::BLECharacteristic::PROPERTY_NOTIFY,
|
||||
ESP_GATT_PERM_READ);
|
||||
static esp32_ble_server::BLE2902 level_cccd;
|
||||
level.add_descriptor(level_cccd);
|
||||
battery.add_characteristic(level);
|
||||
if (id(ble_server).add_service(battery))
|
||||
id(ble_server).enqueue_start_service(&battery);
|
||||
|
||||
esp32_ble_server:
|
||||
id: ble_server
|
||||
manufacturer_data: [0x72, 0x4, 0x00, 0x23]
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import tuya
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID
|
||||
from esphome.types import ConfigType
|
||||
|
||||
AUTO_LOAD = ["tuya"]
|
||||
|
||||
ns = cg.esphome_ns.namespace("fake_tuya_transport")
|
||||
FakeTuyaTransport = ns.class_("FakeTuyaTransport", tuya.Tuya)
|
||||
|
||||
CONFIG_SCHEMA = tuya.TUYA_SCHEMA.extend(
|
||||
{cv.GenerateID(): cv.declare_id(FakeTuyaTransport)}
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
await tuya.setup_tuya(var, config)
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/tuya/tuya.h"
|
||||
|
||||
namespace esphome::fake_tuya_transport {
|
||||
|
||||
/// A Tuya controller with no transport: datapoint writes are dropped, and
|
||||
/// initialization completes immediately in setup() so entities receive
|
||||
/// their initial-state callbacks.
|
||||
class FakeTuyaTransport : public tuya::Tuya {
|
||||
public:
|
||||
void setup() override { this->mark_initialized_(); }
|
||||
|
||||
protected:
|
||||
void send_datapoint_command(uint8_t datapoint_id, tuya::TuyaDatapointType datapoint_type, const uint8_t *data,
|
||||
size_t len) override {}
|
||||
};
|
||||
|
||||
} // namespace esphome::fake_tuya_transport
|
||||
@@ -0,0 +1,14 @@
|
||||
# Compile the tuya base class with a non-UART transport: no uart bus anywhere,
|
||||
# and the UART implementation filtered from the build.
|
||||
external_components:
|
||||
- source: ../../components/tuya/components
|
||||
components: [fake_tuya_transport]
|
||||
|
||||
fake_tuya_transport:
|
||||
id: fake_tuya
|
||||
|
||||
switch:
|
||||
- platform: tuya
|
||||
tuya_id: fake_tuya
|
||||
name: Fake Switch
|
||||
switch_datapoint: 1
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <algorithm>
|
||||
#include "common.h"
|
||||
#include "esphome/components/uart/uart.h"
|
||||
#include "esphome/core/frame_reader.h"
|
||||
|
||||
namespace esphome::uart::testing {
|
||||
|
||||
@@ -179,4 +180,66 @@ TEST(UARTReadAvailableTest, DiscardStopsOnReadFailure) {
|
||||
EXPECT_EQ(uart.read_sizes.size(), 3u);
|
||||
}
|
||||
|
||||
// Keeps a copy of each frame; takes every frame except those whose length byte is reject_len
|
||||
struct Collect {
|
||||
std::vector<std::vector<uint8_t>> frames;
|
||||
uint8_t reject_len{0};
|
||||
bool operator()(const uint8_t *f, size_t len) {
|
||||
this->frames.emplace_back(f, f + len);
|
||||
return f[1] != this->reject_len;
|
||||
}
|
||||
};
|
||||
|
||||
// AA, length byte, then that many bytes
|
||||
using GapReader = LengthFrameReader<16, FrameFormat<FrameHeader<0xAA>, PayloadLengthU8<LengthField{.offset = 1}>>>;
|
||||
|
||||
TEST(UARTReadFramesTest, FeedsTheReaderAndStampsTheTime) {
|
||||
::testing::NiceMock<FakeRxUART> uart(std::vector<uint8_t>{0xAA, 0x01, 0x07});
|
||||
UARTDevice dev(&uart);
|
||||
GapReader reader;
|
||||
Collect handle;
|
||||
uint32_t last_rx = 0;
|
||||
EXPECT_TRUE(dev.read_frames(reader, handle, 500, last_rx));
|
||||
EXPECT_EQ(last_rx, 500u);
|
||||
EXPECT_EQ(handle.frames, (std::vector<std::vector<uint8_t>>{{0xAA, 0x01, 0x07}}));
|
||||
}
|
||||
|
||||
TEST(UARTReadFramesTest, IdlePassAfterTheGapFlushesAStalledFrame) {
|
||||
// A corrupt length of 9 holds the whole frame AA 01 07 behind it
|
||||
::testing::NiceMock<FakeRxUART> uart(std::vector<uint8_t>{0xAA, 0x09, 0xAA, 0x01, 0x07});
|
||||
UARTDevice dev(&uart);
|
||||
GapReader reader;
|
||||
Collect handle{.reject_len = 0x09};
|
||||
uint32_t last_rx = 0;
|
||||
dev.read_frames(reader, handle, 1000, last_rx, 100);
|
||||
dev.read_frames(reader, handle, 1099, last_rx, 100);
|
||||
EXPECT_TRUE(handle.frames.empty());
|
||||
dev.read_frames(reader, handle, 1100, last_rx, 100);
|
||||
EXPECT_EQ(handle.frames, (std::vector<std::vector<uint8_t>>{{0xAA, 0x01, 0x07}}));
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
}
|
||||
|
||||
TEST(UARTReadFramesTest, BytesAfterASlowLoopAreFedNotFlushed) {
|
||||
::testing::NiceMock<FakeRxUART> uart(std::vector<uint8_t>{0xAA, 0x02, 0x01});
|
||||
UARTDevice dev(&uart);
|
||||
GapReader reader;
|
||||
Collect handle;
|
||||
uint32_t last_rx = 0;
|
||||
dev.read_frames(reader, handle, 1000, last_rx, 100);
|
||||
// The rest of the frame waited out a 500 ms loop
|
||||
uart.append({0x02});
|
||||
dev.read_frames(reader, handle, 1500, last_rx, 100);
|
||||
EXPECT_EQ(handle.frames, (std::vector<std::vector<uint8_t>>{{0xAA, 0x02, 0x01, 0x02}}));
|
||||
}
|
||||
|
||||
TEST(UARTReadFramesTest, ReportsAFailedRead) {
|
||||
::testing::NiceMock<FakeRxUART> uart(std::vector<uint8_t>{0xAA, 0x01, 0x07});
|
||||
uart.fail_after_reads = 0;
|
||||
UARTDevice dev(&uart);
|
||||
GapReader reader;
|
||||
Collect handle;
|
||||
uint32_t last_rx = 0;
|
||||
EXPECT_FALSE(dev.read_frames(reader, handle, 500, last_rx));
|
||||
}
|
||||
|
||||
} // namespace esphome::uart::testing
|
||||
Reference in new issue
Block a user