17static constexpr uint8_t FORMAT_VERSION = 1;
18static constexpr uint8_t PACKET_DICTIONARY = 0x11;
19static constexpr uint8_t PACKET_DATA = 0x12;
20static constexpr uint8_t PACKET_REQUEST = 0x13;
22static constexpr uint8_t TYPE_SENSOR = 1;
23static constexpr uint8_t TYPE_BINARY_SENSOR = 2;
24static constexpr uint8_t MAX_TYPE = 31;
26static constexpr size_t HEADER_SIZE = 5;
28static constexpr uint8_t PART_INDEX_MASK = 0x7F;
29static constexpr uint8_t PART_LAST = 0x80;
30static constexpr uint8_t PART_NONE = 0xFF;
33static constexpr size_t TAG_SIZE = 2;
34static constexpr uint8_t TAG_TYPE_SHIFT = 8;
35static constexpr uint8_t TAG_PAYLOAD_SHIFT = 13;
36static constexpr uint16_t TAG_VALUE_BIT = 0x8000;
37static constexpr uint8_t PAYLOAD_NONE = 0;
38static constexpr uint8_t PAYLOAD_WORD = 1;
39static constexpr uint8_t PAYLOAD_LENGTH = 2;
40static constexpr uint8_t PAYLOAD_NO_STATE = 3;
41static constexpr size_t WORD_SIZE = 4;
42static constexpr size_t MAX_RECORD_SIZE = TAG_SIZE + WORD_SIZE;
44static constexpr size_t SECTION_HEADER_SIZE = 3;
45static constexpr size_t MAX_STRING_LENGTH = 255;
46static constexpr uint32_t DEFAULT_UPDATE_INTERVAL_MS = 15000;
47static constexpr uint32_t REQUEST_INTERVAL_MS = 5000;
48static constexpr uint32_t RETRY_DELAY_MS = 1000;
49static constexpr uint32_t RETRY_TIMER_ID = 0;
50static constexpr uint32_t TIMEOUT_CHECK_INTERVAL_MS = 1000;
51static constexpr uint32_t WARNING_INTERVAL_MS = 60000;
53static constexpr uint32_t REFUSED_WARNING_MS = 60000;
56 for (
size_t i = 0; i != 4; i++)
57 buf[i] =
value >> (i * 8);
61static bool matches(
const char *str,
const char *data,
size_t len) {
62 return strlen(str) ==
len && memcmp(str, data,
len) == 0;
73static Record parse_record(std::span<const uint8_t> packet,
size_t pos) {
75 return {
static_cast<uint8_t
>(
tag),
static_cast<uint8_t
>((
tag >> TAG_TYPE_SHIFT) & MAX_TYPE),
76 static_cast<uint8_t
>((
tag >> TAG_PAYLOAD_SHIFT) & 3), (
tag & TAG_VALUE_BIT) != 0,
77 packet.data() +
pos + TAG_SIZE};
81static size_t record_size(std::span<const uint8_t> packet,
size_t pos) {
82 if (
pos + TAG_SIZE > packet.size())
84 size_t size = TAG_SIZE;
85 uint8_t payload = parse_record(packet,
pos).payload;
86 if (payload == PAYLOAD_WORD) {
88 }
else if (payload == PAYLOAD_LENGTH) {
89 if (
pos + TAG_SIZE == packet.size())
91 size += 1 + packet[
pos + TAG_SIZE];
97static bool data_well_formed(std::span<const uint8_t> packet) {
98 for (
size_t pos = HEADER_SIZE;
pos != packet.size();) {
99 size_t size = record_size(packet,
pos);
102 Record record = parse_record(packet,
pos);
103 if (record.type == 0 || (record.value && record.payload != PAYLOAD_NONE))
106 if (record.type == TYPE_SENSOR && record.payload != PAYLOAD_WORD && record.payload != PAYLOAD_NO_STATE)
108 if (record.type == TYPE_BINARY_SENSOR && record.payload != PAYLOAD_NONE && record.payload != PAYLOAD_NO_STATE)
116static bool dictionary_well_formed(std::span<const uint8_t> packet) {
117 size_t pos = HEADER_SIZE + 1;
118 if (
pos >= packet.size())
121 if (
pos > packet.size())
123 while (
pos != packet.size()) {
124 if (
pos + SECTION_HEADER_SIZE > packet.size())
127 size_t first = packet[
pos + 1];
129 pos += SECTION_HEADER_SIZE;
133 for (
size_t i = 0; i !=
count; i++) {
134 if (
pos == packet.size())
137 if (
pos > packet.size())
146 if (!this->
setup_check(this->
buffer_ !=
nullptr, LOG_STR(
"Not enough memory for the packet buffer")))
150 LOG_STR(
"Packet buffer smaller than the interface's packets")))
154 size_t longest_id = 0;
155 for (
const auto &entity : this->
entities_)
156 longest_id = std::max(longest_id, strlen(entity.id));
158 if (name.size() > MAX_STRING_LENGTH || longest_id > MAX_STRING_LENGTH ||
159 HEADER_SIZE + 2 + name.size() + SECTION_HEADER_SIZE + 1 + longest_id > this->max_packet_size_) {
160 this->
mark_failed(LOG_STR(
"max_packet_size too small for the device name and entity ids"));
165 for (
const auto &entity : this->entities_) {
166 hash =
fnv1a_hash_extend(hash, entity.is_sensor ? TYPE_SENSOR : TYPE_BINARY_SENSOR);
172 for (
auto &entity : this->entities_) {
174 if (entity.is_sensor) {
175 static_cast<sensor::Sensor *
>(entity.entity)->add_on_state_callback([&entity](
float) {
176 entity.parent->mark_updated_(entity);
180#ifdef USE_BINARY_SENSOR
181 if (!entity.is_sensor) {
184 ->add_full_state_callback(
185 [&entity](optional<bool>, optional<bool>) { entity.parent->mark_updated_(entity); });
199 : DEFAULT_UPDATE_INTERVAL_MS;
210 "Entity Transport:\n"
211 " Packet Interface: %s\n"
212 " Max Packet Size: %zu\n"
216 " Dictionary ID: %08" PRIX32,
222 ESP_LOGCONFIG(TAG,
" Update Interval: never");
229 for (
const auto &entity : this->
entities_) {
230 ESP_LOGCONFIG(TAG,
" %s %u: %s", entity.is_sensor ? LOG_STR_LITERAL(
"Sensor") : LOG_STR_LITERAL(
"Binary Sensor"),
231 entity.number, entity.id);
233#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
235 ESP_LOGCONFIG(TAG,
" Remote Sensor: %s from %s", remote.remote_id, remote.provider);
238#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
240 ESP_LOGCONFIG(TAG,
" Remote Binary Sensor: %s from %s", remote.remote_id, remote.provider);
250 entity.updated =
true;
269 ESP_LOGI(TAG,
"Packets are accepted again");
283 ESP_LOGW(TAG,
"The packet interface has accepted no packets for %" PRIu32
"s, so no states are sent",
299 size_t part_offset = header++;
300 buf[header++] = name.size();
301 memcpy(buf + header, name.c_str(), name.size());
302 header += name.size();
304 size_t count_offset = 0;
305 uint8_t section_type = 0;
309 uint8_t
type = entity.is_sensor ? TYPE_SENSOR : TYPE_BINARY_SENSOR;
310 size_t id_length = strlen(entity.id);
311 bool new_section =
type != section_type;
315 ESP_LOGV(TAG,
"Dictionary packet of %zu bytes not accepted, will retry",
length);
325 buf[
length++] = entity.number;
331 buf[
length++] = id_length;
332 memcpy(buf +
length, entity.id, id_length);
338 ESP_LOGV(TAG,
"Dictionary packet of %zu bytes not accepted, will retry",
length);
350 uint8_t
type = entity.
is_sensor ? TYPE_SENSOR : TYPE_BINARY_SENSOR;
351 uint8_t payload = PAYLOAD_NO_STATE;
353 size_t size = TAG_SIZE;
357 if (!std::isnan(
state)) {
358 payload = PAYLOAD_WORD;
360 memcpy(&bits, &
state,
sizeof(bits));
361 put_uint32(record + TAG_SIZE, bits);
366#ifdef USE_BINARY_SENSOR
369 if (sensor->has_state()) {
370 payload = PAYLOAD_NONE;
371 value = sensor->state;
376 entity.
number | (
type << TAG_TYPE_SHIFT) | (payload << TAG_PAYLOAD_SHIFT) | (
value ? TAG_VALUE_BIT : 0);
385 for (
size_t i = 0; i != this->
entities_.size(); i++) {
389 uint8_t record[MAX_RECORD_SIZE];
392 if (!this->
flush_(length, first, i))
405 if (
length == HEADER_SIZE)
408 ESP_LOGV(TAG,
"Packet of %zu bytes not accepted, will retry",
length);
411 for (
size_t i = first; i != last; i++)
418 if (!data.is_contiguous()) {
419 ESP_LOGW(TAG,
"Packet split across buffers is not supported");
422 auto packet = data.as_span();
423 if (packet.size() < HEADER_SIZE) {
425 ESP_LOGW(TAG,
"Packet of %zu bytes is too short", packet.size());
429 if (packet[0] >> 4 != FORMAT_VERSION) {
431 ESP_LOGW(TAG,
"Packet format version %u not supported; the sender may run another ESPHome version",
439 if (packet[0] == PACKET_REQUEST && packet.size() == HEADER_SIZE) {
440 ESP_LOGD(TAG,
"Dictionary requested");
443 ESP_LOGV(TAG,
"Packet with our own dictionary id dropped; another device may have the same name and entities");
447 if (packet[0] == PACKET_DICTIONARY) {
449 }
else if (packet[0] == PACKET_DATA) {
451 }
else if (packet[0] != PACKET_REQUEST) {
452 ESP_LOGV(TAG,
"Unknown packet type 0x%02X", packet[0]);
457 if (!dictionary_well_formed(packet)) {
459 ESP_LOGW(TAG,
"Dictionary packet of %zu bytes is malformed", packet.size());
463 size_t pos = HEADER_SIZE;
464 uint8_t part = packet[
pos++];
465 uint8_t index = part & PART_INDEX_MASK;
469 this->
rx_next_part_ = in_order ? (index + 1) & PART_INDEX_MASK : PART_NONE;
470 bool completed = in_order && (part & PART_LAST) != 0;
476 size_t provider_length = packet[
pos++];
477 const auto *provider =
reinterpret_cast<const char *
>(packet.data() +
pos);
478 pos += provider_length;
479 while (
pos != packet.size()) {
481 uint8_t number = packet[
pos + 1];
483 pos += SECTION_HEADER_SIZE;
484 for (uint8_t i = 0; i !=
count; i++) {
485 size_t id_length = packet[
pos++];
486 this->
learn_(provider, provider_length,
type, number + i,
reinterpret_cast<const char *
>(packet.data() +
pos),
487 id_length, dictionary_id);
493 ESP_LOGD(TAG,
"Dictionary %08" PRIX32
" received from '%.*s'", dictionary_id,
static_cast<int>(provider_length),
498 this->
forget_unnamed_(provider, provider_length, dictionary_id, first_time);
505#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
507 if (!matches(remote.provider, provider, provider_length) || (remote.known && remote.dictionary_id == dictionary_id))
509 if (remote.known || first_time) {
510 ESP_LOGW(TAG,
"'%s' does not send '%s'", remote.provider, remote.remote_id);
512 remote.known =
false;
513 if (remote.has_state) {
514 remote.has_state =
false;
515 remote.entity->publish_state(NAN);
519#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
521 if (!matches(remote.provider, provider, provider_length) || (remote.known && remote.dictionary_id == dictionary_id))
523 if (remote.known || first_time) {
524 ESP_LOGW(TAG,
"'%s' does not send '%s'", remote.provider, remote.remote_id);
526 remote.known =
false;
527 if (remote.has_state) {
528 remote.has_state =
false;
529 remote.entity->invalidate_state();
536 size_t id_length,
uint32_t dictionary_id) {
537#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
538 if (
type == TYPE_SENSOR) {
540 if (matches(remote.provider, provider, provider_length) && matches(remote.remote_id,
id, id_length)) {
541 remote.dictionary_id = dictionary_id;
542 remote.number = number;
548#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
549 if (
type == TYPE_BINARY_SENSOR) {
551 if (matches(remote.provider, provider, provider_length) && matches(remote.remote_id,
id, id_length)) {
552 remote.dictionary_id = dictionary_id;
553 remote.number = number;
562 return std::find(this->
seen_dictionaries_.begin(), this->seen_dictionaries_.end(), dictionary_id) !=
568 bool has_remotes =
false;
569#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
571 known |= remote.known && remote.dictionary_id == dictionary_id;
575#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
577 known |= remote.known && remote.dictionary_id == dictionary_id;
584 if (!data_well_formed(packet)) {
586 ESP_LOGW(TAG,
"Data packet of %zu bytes is malformed", packet.size());
597 for (
size_t pos = HEADER_SIZE;
pos != packet.size();
pos += record_size(packet,
pos)) {
598 [[maybe_unused]] Record record = parse_record(packet,
pos);
599#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
600 if (record.type == TYPE_SENSOR) {
602 if (record.payload == PAYLOAD_WORD) {
606 for (
auto &remote : this->remote_sensors_) {
607 if (remote.known && remote.dictionary_id == dictionary_id && remote.number == record.number) {
608 remote.last_state_ms = now;
609 remote.has_state =
true;
610 remote.entity->publish_state(
value);
615#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
616 if (record.type == TYPE_BINARY_SENSOR) {
617 for (
auto &remote : this->remote_binary_sensors_) {
618 if (!remote.known || remote.dictionary_id != dictionary_id || remote.number != record.number)
620 remote.last_state_ms = now;
621 remote.has_state =
true;
622 if (record.payload == PAYLOAD_NO_STATE) {
623 remote.entity->invalidate_state();
625 remote.entity->publish_state(record.value);
637 uint8_t packet[HEADER_SIZE] = {PACKET_REQUEST};
638 put_uint32(packet + 1, dictionary_id);
641 ESP_LOGV(TAG,
"Request for dictionary %08" PRIX32
" not accepted", dictionary_id);
646 ESP_LOGD(TAG,
"Requested dictionary %08" PRIX32, dictionary_id);
652 auto index =
static_cast<uint8_t
>(reason);
653 uint8_t bit = 1 << index;
674#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
676 if (timed_out_only && (!remote.has_state || now - remote.last_state_ms <= this->remote_timeout_ms_))
678 remote.has_state =
false;
679 remote.entity->publish_state(NAN);
682#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
684 if (timed_out_only && (!remote.has_state || now - remote.last_state_ms <= this->remote_timeout_ms_))
686 remote.has_state =
false;
687 remote.entity->invalidate_state();
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
void status_set_warning()
void enable_loop()
Enable this component's loop.
bool ESPHOME_ALWAYS_INLINE setup_check(bool ok)
Marks the component failed with message (default "Communication failed") unless ok; returns ok.
bool status_has_warning() const
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
void disable_loop()
Disable this component's loop.
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
void status_clear_warning()
Base class for all binary_sensor-type classes.
void receive_dictionary_(std::span< const uint8_t > packet, uint32_t dictionary_id)
void clear_remote_states_(bool timed_out_only)
void receive_data_(std::span< const uint8_t > packet, uint32_t dictionary_id)
FixedVector< LocalEntity > entities_
void forget_unnamed_(const char *provider, size_t provider_length, uint32_t dictionary_id, bool first_time)
Clears each remote entity of provider that its complete dictionary does not name, warning if the enti...
void learn_(const char *provider, size_t provider_length, uint8_t type, uint8_t number, const char *id, size_t id_length, uint32_t dictionary_id)
uint32_t last_request_ms_
StaticVector< RemoteEntity< sensor::Sensor >, ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT > remote_sensors_
std::array< uint32_t, 8 > seen_dictionaries_
DropReason
The kinds of dropped packet, each warned about at most once a minute, so a steady stream of one kind ...
@ DROP_REASON_MALFORMED_DATA
@ DROP_REASON_FORMAT_VERSION
@ DROP_REASON_MALFORMED_DICTIONARY
uint32_t remote_timeout_ms_
uint32_t update_interval_ms_
bool flush_(size_t length, size_t first, size_t last)
size_t write_header_(uint8_t type) const
void request_dictionary_(uint32_t dictionary_id)
std::array< uint32_t, DROP_REASON_COUNT > last_warning_ms_
void on_session_(bool connected)
StaticVector< RemoteEntity< binary_sensor::BinarySensor >, ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT > remote_binary_sensors_
packet_interface::PacketInterface * interface_
bool dictionary_seen_(uint32_t dictionary_id) const
void receive_(const packet_interface::PacketBuffer &data)
bool warning_due_(DropReason reason)
uint32_t refused_since_ms_
size_t write_record_(const LocalEntity &entity, uint8_t *record) const
void mark_updated_(LocalEntity &entity)
uint32_t rx_dictionary_id_
void dump_config() override
A buffer class that efficiently represents a composite buffer with three sections:
bool has_capability(Capability capability) const
void add_on_session_state_callback(F &&callback)
With CAPABILITY_SESSION, the callback is called with true when the peer can be reached,...
size_t get_max_packet_size() const
The largest packet this layer accepts; fixed when the layer is constructed.
const char * get_name() const
PacketInterface * top()
The topmost layer stacked on this one, or this one if nothing is stacked on it.
virtual bool send_to_interface(const PacketBuffer &data, const PacketMetaData &meta_data)=0
Method to be implemented by child classes to send data to the interface.
void add_packet_interface_listener(F &&callback)
Add a listener that will be called when data is received.
Base-class for all sensors.
ESPHOME_LOG_TAG(TAG, "entity_transport")
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Application App
Global storage of Application pointer - only one Application can exist.
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
constexpr uint32_t SCHEDULER_DONT_RUN
constexpr uint8_t * put_le16(uint8_t *dst, uint16_t value)