ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
entity_transport.cpp
Go to the documentation of this file.
1#include "entity_transport.h"
2#include <algorithm>
3#include <cmath>
4#include <cstring>
6#include "esphome/core/log.h"
8
10
13
14ESPHOME_LOG_TAG(TAG, "entity_transport");
15
16// The packet type byte holds the format version in its high nibble
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;
21// Entity types, in dictionary sections and data records; 0 is not used
22static constexpr uint8_t TYPE_SENSOR = 1;
23static constexpr uint8_t TYPE_BINARY_SENSOR = 2;
24static constexpr uint8_t MAX_TYPE = 31;
25// Packet type and dictionary id
26static constexpr size_t HEADER_SIZE = 5;
27// A dictionary packet's part byte follows the header: the part's index in bits 0-6, and on the last part, bit 7
28static constexpr uint8_t PART_INDEX_MASK = 0x7F;
29static constexpr uint8_t PART_LAST = 0x80;
30static constexpr uint8_t PART_NONE = 0xFF; // no dictionary is being received in order
31// A data record starts with a 16-bit tag: the entity's number in bits 0-7, its type in bits 8-12, the payload form in
32// bits 13-14, and with PAYLOAD_NONE, the state in bit 15. Any record can be skipped without knowing its type.
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; // the state is in the tag's value bit
38static constexpr uint8_t PAYLOAD_WORD = 1; // 4 bytes follow
39static constexpr uint8_t PAYLOAD_LENGTH = 2; // a length byte follows, then that many bytes
40static constexpr uint8_t PAYLOAD_NO_STATE = 3; // the entity has no state
41static constexpr size_t WORD_SIZE = 4;
42static constexpr size_t MAX_RECORD_SIZE = TAG_SIZE + WORD_SIZE;
43// A dictionary section starts with the entity type, first number and count
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;
52// How long the interface may refuse every packet before it is reported
53static constexpr uint32_t REFUSED_WARNING_MS = 60000;
54
55static void put_uint32(uint8_t *buf, uint32_t value) {
56 for (size_t i = 0; i != 4; i++)
57 buf[i] = value >> (i * 8);
58}
59
60// True if the NUL terminated str is the same as the len bytes at data
61static bool matches(const char *str, const char *data, size_t len) {
62 return strlen(str) == len && memcmp(str, data, len) == 0;
63}
64
65struct Record {
66 uint8_t number;
67 uint8_t type;
68 uint8_t payload;
69 bool value;
70 const uint8_t *data; // what follows the tag
71};
72
73static Record parse_record(std::span<const uint8_t> packet, size_t pos) {
74 uint16_t tag = encode_uint16(packet[pos + 1], packet[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};
78}
79
80// The size of the data record at pos, or 0 if it does not fit in the packet
81static size_t record_size(std::span<const uint8_t> packet, size_t pos) {
82 if (pos + TAG_SIZE > packet.size())
83 return 0;
84 size_t size = TAG_SIZE;
85 uint8_t payload = parse_record(packet, pos).payload;
86 if (payload == PAYLOAD_WORD) {
87 size += WORD_SIZE;
88 } else if (payload == PAYLOAD_LENGTH) {
89 if (pos + TAG_SIZE == packet.size())
90 return 0;
91 size += 1 + packet[pos + TAG_SIZE];
92 }
93 return pos + size <= packet.size() ? size : 0;
94}
95
96// Checks every record of a data packet, so that a damaged or forged packet changes no state at all
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);
100 if (size == 0)
101 return false;
102 Record record = parse_record(packet, pos);
103 if (record.type == 0 || (record.value && record.payload != PAYLOAD_NONE))
104 return false;
105 // Types this device knows must use their own payload form; others are skipped
106 if (record.type == TYPE_SENSOR && record.payload != PAYLOAD_WORD && record.payload != PAYLOAD_NO_STATE)
107 return false;
108 if (record.type == TYPE_BINARY_SENSOR && record.payload != PAYLOAD_NONE && record.payload != PAYLOAD_NO_STATE)
109 return false;
110 pos += size;
111 }
112 return true;
113}
114
115// Checks the device name and every section of a dictionary packet before anything is learnt from it
116static bool dictionary_well_formed(std::span<const uint8_t> packet) {
117 size_t pos = HEADER_SIZE + 1;
118 if (pos >= packet.size())
119 return false;
120 pos += 1 + packet[pos];
121 if (pos > packet.size())
122 return false;
123 while (pos != packet.size()) {
124 if (pos + SECTION_HEADER_SIZE > packet.size())
125 return false;
126 uint8_t type = packet[pos];
127 size_t first = packet[pos + 1];
128 size_t count = packet[pos + 2];
129 pos += SECTION_HEADER_SIZE;
130 // Numbers are one byte, and a data record can name types up to MAX_TYPE only
131 if (type == 0 || type > MAX_TYPE || count == 0 || first + count > 256)
132 return false;
133 for (size_t i = 0; i != count; i++) {
134 if (pos == packet.size())
135 return false;
136 pos += 1 + packet[pos];
137 if (pos > packet.size())
138 return false;
139 }
140 }
141 return true;
142}
143
145 this->interface_ = this->interface_->top();
146 if (!this->setup_check(this->buffer_ != nullptr, LOG_STR("Not enough memory for the packet buffer")))
147 return;
148 // Code generation sizes the buffer from the configured layers, which must give the same size as the C++ ones
149 if (!this->setup_check(this->interface_->get_max_packet_size() <= this->max_packet_size_,
150 LOG_STR("Packet buffer smaller than the interface's packets")))
151 return;
153 const auto &name = App.get_name();
154 size_t longest_id = 0;
155 for (const auto &entity : this->entities_)
156 longest_id = std::max(longest_id, strlen(entity.id));
157 // A dictionary packet must hold the device name and any one id, which also leaves room for a data record
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"));
161 return;
162 }
163 // The dictionary id changes when the device name or any entity changes
164 uint32_t hash = fnv1a_hash(name.c_str());
165 for (const auto &entity : this->entities_) {
166 hash = fnv1a_hash_extend(hash, entity.is_sensor ? TYPE_SENSOR : TYPE_BINARY_SENSOR);
167 hash = fnv1a_hash_extend(hash, entity.id);
168 }
169 this->dictionary_id_ = hash;
170
171 // [&entity] is safe: FixedVector never reallocates, and the parent pointer keeps the capture to one pointer
172 for (auto &entity : this->entities_) {
173#ifdef USE_SENSOR
174 if (entity.is_sensor) {
175 static_cast<sensor::Sensor *>(entity.entity)->add_on_state_callback([&entity](float) {
176 entity.parent->mark_updated_(entity);
177 });
178 }
179#endif
180#ifdef USE_BINARY_SENSOR
181 if (!entity.is_sensor) {
182 // The full state callback also fires for the first state
183 static_cast<binary_sensor::BinarySensor *>(entity.entity)
184 ->add_full_state_callback(
185 [&entity](optional<bool>, optional<bool>) { entity.parent->mark_updated_(entity); });
186 }
187#endif
188 }
190 [this](const PacketBuffer &data, const PacketMetaData &) { this->receive_(data); });
191
193 if (session)
194 this->interface_->add_on_session_state_callback([this](bool connected) { this->on_session_(connected); });
195 // Without a session and reliable delivery, a lost dictionary or state is only replaced by a periodic resend
196 if (this->update_interval_ms_ == 0) {
199 : DEFAULT_UPDATE_INTERVAL_MS;
200 }
202 this->set_interval(this->update_interval_ms_, [this] { this->send_all_(); });
203 if (this->remote_timeout_ms_ != 0)
204 this->set_interval(TIMEOUT_CHECK_INTERVAL_MS, [this] { this->clear_remote_states_(true); });
205 this->send_all_();
206}
207
209 ESP_LOGCONFIG(TAG,
210 "Entity Transport:\n"
211 " Packet Interface: %s\n"
212 " Max Packet Size: %zu\n"
213 " Encryption: %s\n"
214 " Reliability: %s\n"
215 " Session: %s\n"
216 " Dictionary ID: %08" PRIX32,
217 this->interface_->get_name(), this->max_packet_size_,
220 YESNO(this->interface_->has_capability(packet_interface::CAPABILITY_SESSION)), this->dictionary_id_);
222 ESP_LOGCONFIG(TAG, " Update Interval: never");
223 } else {
224 ESP_LOGCONFIG(TAG, " Update Interval: %" PRIu32 "ms", this->update_interval_ms_);
225 }
226 if (this->remote_timeout_ms_ != 0) {
227 ESP_LOGCONFIG(TAG, " Remote Timeout: %" PRIu32 "ms", this->remote_timeout_ms_);
228 }
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);
232 }
233#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
234 for (const auto &remote : this->remote_sensors_) {
235 ESP_LOGCONFIG(TAG, " Remote Sensor: %s from %s", remote.remote_id, remote.provider);
236 }
237#endif
238#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
239 for (const auto &remote : this->remote_binary_sensors_) {
240 ESP_LOGCONFIG(TAG, " Remote Binary Sensor: %s from %s", remote.remote_id, remote.provider);
241 }
242#endif
243}
244
246 this->dictionary_pending_ = true;
247 this->dictionary_next_ = 0;
248 this->dictionary_part_ = 0;
249 for (auto &entity : this->entities_)
250 entity.updated = true;
251 this->enable_loop();
252}
253
255 entity.updated = true;
256 this->enable_loop();
257}
258
260 this->disable_loop();
261 // States are only sent once the dictionary that names them has been accepted
262 if ((this->dictionary_pending_ && !this->send_dictionary_()) || !this->send_updated_()) {
263 this->sending_refused_();
264 this->set_timeout(RETRY_TIMER_ID, RETRY_DELAY_MS, [this] { this->enable_loop(); });
265 return;
266 }
267 this->refusing_ = false;
268 if (this->status_has_warning()) {
269 ESP_LOGI(TAG, "Packets are accepted again");
270 this->status_clear_warning();
271 }
272}
273
274// A link that is down or full refuses packets for a while; one that refuses them for long sends nothing at all
277 if (!this->refusing_) {
278 this->refusing_ = true;
279 this->refused_since_ms_ = now;
280 return;
281 }
282 if (!this->status_has_warning() && now - this->refused_since_ms_ >= REFUSED_WARNING_MS) {
283 ESP_LOGW(TAG, "The packet interface has accepted no packets for %" PRIu32 "s, so no states are sent",
284 (now - this->refused_since_ms_) / 1000);
285 this->status_set_warning();
286 }
287}
288
290 this->buffer_[0] = type;
291 put_uint32(this->buffer_ + 1, this->dictionary_id_);
292 return HEADER_SIZE;
293}
294
296 uint8_t *buf = this->buffer_;
297 const auto &name = App.get_name();
298 size_t header = this->write_header_(PACKET_DICTIONARY);
299 size_t part_offset = header++;
300 buf[header++] = name.size();
301 memcpy(buf + header, name.c_str(), name.size());
302 header += name.size();
303 size_t length = header;
304 size_t count_offset = 0;
305 uint8_t section_type = 0; // none
306 // A dictionary in several packets resumes after the last packet accepted, so a refused one does not resend the rest
307 for (size_t i = this->dictionary_next_; i != this->entities_.size(); i++) {
308 const auto &entity = this->entities_[i];
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;
312 if (length + (new_section ? SECTION_HEADER_SIZE : 0) + 1 + id_length > this->max_packet_size_) {
313 buf[part_offset] = this->dictionary_part_ & PART_INDEX_MASK;
314 if (!this->interface_->send_to_interface(PacketBuffer(buf, length), {})) {
315 ESP_LOGV(TAG, "Dictionary packet of %zu bytes not accepted, will retry", length);
316 return false;
317 }
318 this->dictionary_next_ = i;
319 this->dictionary_part_++;
320 length = header;
321 new_section = true;
322 }
323 if (new_section) {
324 buf[length++] = type;
325 buf[length++] = entity.number;
326 count_offset = length;
327 buf[length++] = 0;
328 section_type = type;
329 }
330 buf[count_offset]++;
331 buf[length++] = id_length;
332 memcpy(buf + length, entity.id, id_length);
333 length += id_length;
334 }
335 if (length != header) {
336 buf[part_offset] = (this->dictionary_part_ & PART_INDEX_MASK) | PART_LAST;
337 if (!this->interface_->send_to_interface(PacketBuffer(buf, length), {})) {
338 ESP_LOGV(TAG, "Dictionary packet of %zu bytes not accepted, will retry", length);
339 return false;
340 }
341 }
342 this->dictionary_pending_ = false;
343 this->dictionary_next_ = 0;
344 this->dictionary_part_ = 0;
345 return true;
346}
347
348// Writes the entity's data record, and returns its size
349size_t EntityTransport::write_record_(const LocalEntity &entity, uint8_t *record) const {
350 uint8_t type = entity.is_sensor ? TYPE_SENSOR : TYPE_BINARY_SENSOR;
351 uint8_t payload = PAYLOAD_NO_STATE;
352 bool value = false;
353 size_t size = TAG_SIZE;
354#ifdef USE_SENSOR
355 if (entity.is_sensor) {
356 float state = static_cast<sensor::Sensor *>(entity.entity)->get_state();
357 if (!std::isnan(state)) {
358 payload = PAYLOAD_WORD;
359 uint32_t bits;
360 memcpy(&bits, &state, sizeof(bits));
361 put_uint32(record + TAG_SIZE, bits);
362 size += WORD_SIZE;
363 }
364 }
365#endif
366#ifdef USE_BINARY_SENSOR
367 if (!entity.is_sensor) {
368 auto *sensor = static_cast<binary_sensor::BinarySensor *>(entity.entity);
369 if (sensor->has_state()) {
370 payload = PAYLOAD_NONE;
371 value = sensor->state;
372 }
373 }
374#endif
375 uint16_t tag =
376 entity.number | (type << TAG_TYPE_SHIFT) | (payload << TAG_PAYLOAD_SHIFT) | (value ? TAG_VALUE_BIT : 0);
377 put_le16(record, tag);
378 return size;
379}
380
381// Sends every updated entity, in as few packets as fit; returns false if a packet was refused
383 size_t length = this->write_header_(PACKET_DATA);
384 size_t first = 0;
385 for (size_t i = 0; i != this->entities_.size(); i++) {
386 auto &entity = this->entities_[i];
387 if (!entity.updated)
388 continue;
389 uint8_t record[MAX_RECORD_SIZE];
390 size_t size = this->write_record_(entity, record);
391 if (length + size > this->max_packet_size_) {
392 if (!this->flush_(length, first, i))
393 return false;
394 length = HEADER_SIZE;
395 first = i;
396 }
397 memcpy(this->buffer_ + length, record, size);
398 length += size;
399 }
400 return this->flush_(length, first, this->entities_.size());
401}
402
403// Sends the packet holding the updated entities from first up to last, and clears their flags if it was accepted
404bool EntityTransport::flush_(size_t length, size_t first, size_t last) {
405 if (length == HEADER_SIZE)
406 return true;
407 if (!this->interface_->send_to_interface(PacketBuffer(this->buffer_, length), {})) {
408 ESP_LOGV(TAG, "Packet of %zu bytes not accepted, will retry", length);
409 return false;
410 }
411 for (size_t i = first; i != last; i++)
412 this->entities_[i].updated = false;
413 return true;
414}
415
417 // Packet interface layers deliver packets in one piece
418 if (!data.is_contiguous()) {
419 ESP_LOGW(TAG, "Packet split across buffers is not supported");
420 return;
421 }
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());
426 }
427 return;
428 }
429 if (packet[0] >> 4 != FORMAT_VERSION) {
431 ESP_LOGW(TAG, "Packet format version %u not supported; the sender may run another ESPHome version",
432 packet[0] >> 4);
433 }
434 return;
435 }
436 uint32_t dictionary_id = encode_uint32(packet[4], packet[3], packet[2], packet[1]);
437 if (dictionary_id == this->dictionary_id_) {
438 // Either a request for our dictionary, or our own packet heard on a broadcast channel
439 if (packet[0] == PACKET_REQUEST && packet.size() == HEADER_SIZE) {
440 ESP_LOGD(TAG, "Dictionary requested");
441 this->send_all_();
442 } else {
443 ESP_LOGV(TAG, "Packet with our own dictionary id dropped; another device may have the same name and entities");
444 }
445 return;
446 }
447 if (packet[0] == PACKET_DICTIONARY) {
448 this->receive_dictionary_(packet, dictionary_id);
449 } else if (packet[0] == PACKET_DATA) {
450 this->receive_data_(packet, dictionary_id);
451 } else if (packet[0] != PACKET_REQUEST) {
452 ESP_LOGV(TAG, "Unknown packet type 0x%02X", packet[0]);
453 }
454}
455
456void EntityTransport::receive_dictionary_(std::span<const uint8_t> packet, uint32_t dictionary_id) {
457 if (!dictionary_well_formed(packet)) {
459 ESP_LOGW(TAG, "Dictionary packet of %zu bytes is malformed", packet.size());
460 }
461 return;
462 }
463 size_t pos = HEADER_SIZE;
464 uint8_t part = packet[pos++];
465 uint8_t index = part & PART_INDEX_MASK;
466 // The dictionary is complete, and need not be asked for again, once its last part follows all the others in order
467 bool in_order = index == 0 || (this->rx_dictionary_id_ == dictionary_id && index == this->rx_next_part_);
468 this->rx_dictionary_id_ = dictionary_id;
469 this->rx_next_part_ = in_order ? (index + 1) & PART_INDEX_MASK : PART_NONE;
470 bool completed = in_order && (part & PART_LAST) != 0;
471 bool first_time = completed && !this->dictionary_seen_(dictionary_id);
472 if (first_time) {
473 this->seen_dictionaries_[this->seen_next_] = dictionary_id;
474 this->seen_next_ = (this->seen_next_ + 1) % this->seen_dictionaries_.size();
475 }
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()) {
480 uint8_t type = packet[pos];
481 uint8_t number = packet[pos + 1];
482 uint8_t count = packet[pos + 2];
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);
488 pos += id_length;
489 }
490 }
491 // Names each device heard, so a provider that matches none of them is easy to spot
492 if (first_time) {
493 ESP_LOGD(TAG, "Dictionary %08" PRIX32 " received from '%.*s'", dictionary_id, static_cast<int>(provider_length),
494 provider);
495 }
496 // A provider may go back to a dictionary already seen, so every complete one is checked
497 if (completed)
498 this->forget_unnamed_(provider, provider_length, dictionary_id, first_time);
499}
500
501void EntityTransport::forget_unnamed_(const char *provider, size_t provider_length, uint32_t dictionary_id,
502 bool first_time) {
503 // A remote entity that its provider's whole dictionary does not name would otherwise keep no or a stale state
504 // silently
505#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
506 for (auto &remote : this->remote_sensors_) {
507 if (!matches(remote.provider, provider, provider_length) || (remote.known && remote.dictionary_id == dictionary_id))
508 continue;
509 if (remote.known || first_time) {
510 ESP_LOGW(TAG, "'%s' does not send '%s'", remote.provider, remote.remote_id);
511 }
512 remote.known = false;
513 if (remote.has_state) {
514 remote.has_state = false;
515 remote.entity->publish_state(NAN);
516 }
517 }
518#endif
519#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
520 for (auto &remote : this->remote_binary_sensors_) {
521 if (!matches(remote.provider, provider, provider_length) || (remote.known && remote.dictionary_id == dictionary_id))
522 continue;
523 if (remote.known || first_time) {
524 ESP_LOGW(TAG, "'%s' does not send '%s'", remote.provider, remote.remote_id);
525 }
526 remote.known = false;
527 if (remote.has_state) {
528 remote.has_state = false;
529 remote.entity->invalidate_state();
530 }
531 }
532#endif
533}
534
535void EntityTransport::learn_(const char *provider, size_t provider_length, uint8_t type, uint8_t number, const char *id,
536 size_t id_length, uint32_t dictionary_id) {
537#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
538 if (type == TYPE_SENSOR) {
539 for (auto &remote : this->remote_sensors_) {
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;
543 remote.known = true;
544 }
545 }
546 }
547#endif
548#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
549 if (type == TYPE_BINARY_SENSOR) {
550 for (auto &remote : this->remote_binary_sensors_) {
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;
554 remote.known = true;
555 }
556 }
557 }
558#endif
559}
560
562 return std::find(this->seen_dictionaries_.begin(), this->seen_dictionaries_.end(), dictionary_id) !=
563 this->seen_dictionaries_.end();
564}
565
566void EntityTransport::receive_data_(std::span<const uint8_t> packet, uint32_t dictionary_id) {
567 bool known = false;
568 bool has_remotes = false;
569#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
570 for (const auto &remote : this->remote_sensors_) {
571 known |= remote.known && remote.dictionary_id == dictionary_id;
572 has_remotes = true;
573 }
574#endif
575#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
576 for (const auto &remote : this->remote_binary_sensors_) {
577 known |= remote.known && remote.dictionary_id == dictionary_id;
578 has_remotes = true;
579 }
580#endif
581 if (!has_remotes)
582 return;
583 // Checked first, so a damaged packet does not make the provider resend everything
584 if (!data_well_formed(packet)) {
586 ESP_LOGW(TAG, "Data packet of %zu bytes is malformed", packet.size());
587 }
588 return;
589 }
590 // A dictionary not yet received in full may name our entities, or be a provider's new one; one received in full
591 // named all of them it could, so asking again would only make that provider resend everything
592 if (!this->dictionary_seen_(dictionary_id))
593 this->request_dictionary_(dictionary_id);
594 if (!known)
595 return;
596 [[maybe_unused]] uint32_t now = App.get_loop_component_start_time();
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) {
601 float value = NAN;
602 if (record.payload == PAYLOAD_WORD) {
603 uint32_t bits = encode_uint32(record.data[3], record.data[2], record.data[1], record.data[0]);
604 memcpy(&value, &bits, sizeof(value));
605 }
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);
611 }
612 }
613 }
614#endif
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)
619 continue;
620 remote.last_state_ms = now;
621 remote.has_state = true;
622 if (record.payload == PAYLOAD_NO_STATE) {
623 remote.entity->invalidate_state();
624 } else {
625 remote.entity->publish_state(record.value);
626 }
627 }
628 }
629#endif
630 }
631}
632
635 if (this->request_sent_ && now - this->last_request_ms_ < REQUEST_INTERVAL_MS)
636 return;
637 uint8_t packet[HEADER_SIZE] = {PACKET_REQUEST};
638 put_uint32(packet + 1, dictionary_id);
639 // A refused request is tried again with the next data packet under that dictionary id
640 if (!this->interface_->send_to_interface(PacketBuffer(packet, sizeof(packet)), {})) {
641 ESP_LOGV(TAG, "Request for dictionary %08" PRIX32 " not accepted", dictionary_id);
642 return;
643 }
644 this->request_sent_ = true;
645 this->last_request_ms_ = now;
646 ESP_LOGD(TAG, "Requested dictionary %08" PRIX32, dictionary_id);
647}
648
649// Dropped packets point to a device with other firmware or a fault, and may arrive steadily, so warn only now and then
652 auto index = static_cast<uint8_t>(reason);
653 uint8_t bit = 1 << index;
654 if ((this->warned_ & bit) != 0 && now - this->last_warning_ms_[index] < WARNING_INTERVAL_MS)
655 return false;
656 this->warned_ |= bit;
657 this->last_warning_ms_[index] = now;
658 return true;
659}
660
661// A newly connected or restarted peer needs the dictionary and every state; while it is lost, its entities have no
662// state
663void EntityTransport::on_session_(bool connected) {
664 if (connected) {
665 this->send_all_();
666 return;
667 }
668 this->clear_remote_states_(false);
669}
670
671// Clears the state of every remote entity, or with timed_out_only, of those whose state is older than the timeout
672void EntityTransport::clear_remote_states_(bool timed_out_only) {
673 [[maybe_unused]] uint32_t now = App.get_loop_component_start_time();
674#ifdef ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT
675 for (auto &remote : this->remote_sensors_) {
676 if (timed_out_only && (!remote.has_state || now - remote.last_state_ms <= this->remote_timeout_ms_))
677 continue;
678 remote.has_state = false;
679 remote.entity->publish_state(NAN);
680 }
681#endif
682#ifdef ENTITY_TRANSPORT_REMOTE_BINARY_SENSOR_COUNT
683 for (auto &remote : this->remote_binary_sensors_) {
684 if (timed_out_only && (!remote.has_state || now - remote.last_state_ms <= this->remote_timeout_ms_))
685 continue;
686 remote.has_state = false;
687 remote.entity->invalidate_state();
688 }
689#endif
690}
691
692} // namespace esphome::entity_transport
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 enable_loop()
Enable this component's loop.
Definition component.h:261
bool ESPHOME_ALWAYS_INLINE setup_check(bool ok)
Marks the component failed with message (default "Communication failed") unless ok; returns ok.
Definition component.h:235
bool status_has_warning() const
Definition component.h:293
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
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.
Definition component.cpp:88
void status_clear_warning()
Definition component.h:317
Base class for all binary_sensor-type classes.
void receive_dictionary_(std::span< const uint8_t > packet, uint32_t dictionary_id)
void receive_data_(std::span< const uint8_t > packet, uint32_t dictionary_id)
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)
StaticVector< RemoteEntity< sensor::Sensor >, ENTITY_TRANSPORT_REMOTE_SENSOR_COUNT > remote_sensors_
DropReason
The kinds of dropped packet, each warned about at most once a minute, so a steady stream of one kind ...
bool flush_(size_t length, size_t first, size_t last)
void request_dictionary_(uint32_t dictionary_id)
std::array< uint32_t, DROP_REASON_COUNT > last_warning_ms_
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)
size_t write_record_(const LocalEntity &entity, uint8_t *record) const
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.
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.
A struct to hold metadata about a packet.
Base-class for all sensors.
Definition sensor.h:48
uint8_t type
bool state
Definition fan.h:2
unsigned count
Definition gif.cpp:51
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.
Definition helpers.h:1141
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:44
size_t size_t pos
Definition helpers.h:1493
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.
Definition helpers.h:1207
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1199
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.
Definition helpers.h:1164
void const char * tag
Definition log.h:110
constexpr uint32_t SCHEDULER_DONT_RUN
Definition component.h:63
constexpr uint8_t * put_le16(uint8_t *dst, uint16_t value)
Definition helpers.h:1286
static void uint32_t
uint16_t length
Definition tt21100.cpp:0