ESPHome 2025.10.0-dev
Loading...
Searching...
No Matches
packet_transport.cpp
Go to the documentation of this file.
1#include "esphome/core/log.h"
3#include "packet_transport.h"
4
6
7namespace esphome {
8namespace packet_transport {
48static const char *const TAG = "packet_transport";
49
50static size_t round4(size_t value) { return (value + 3) & ~3; }
51
52union FuData {
53 uint32_t u32;
54 float f32;
55};
56
57static const uint16_t MAGIC_NUMBER = 0x4553;
58static const uint16_t MAGIC_PING = 0x5048;
59static const uint32_t PREF_HASH = 0x45535043;
68
75
76static const size_t MAX_PING_KEYS = 4;
77
78static inline void add(std::vector<uint8_t> &vec, uint32_t data) {
79 vec.push_back(data & 0xFF);
80 vec.push_back((data >> 8) & 0xFF);
81 vec.push_back((data >> 16) & 0xFF);
82 vec.push_back((data >> 24) & 0xFF);
83}
84
85class PacketDecoder {
86 public:
87 PacketDecoder(const uint8_t *buffer, size_t len) : buffer_(buffer), len_(len) {}
88
89 DecodeResult decode_string(char *data, size_t maxlen) {
90 if (this->position_ == this->len_)
91 return DECODE_EMPTY;
92 auto len = this->buffer_[this->position_];
93 if (len == 0 || this->position_ + 1 + len > this->len_ || len >= maxlen)
94 return DECODE_ERROR;
95 this->position_++;
96 memcpy(data, this->buffer_ + this->position_, len);
97 data[len] = 0;
98 this->position_ += len;
99 return DECODE_OK;
100 }
101
102 template<typename T> DecodeResult get(T &data) {
103 if (this->position_ + sizeof(T) > this->len_)
104 return DECODE_ERROR;
105 T value = 0;
106 for (size_t i = 0; i != sizeof(T); ++i) {
107 value += this->buffer_[this->position_++] << (i * 8);
108 }
109 data = value;
110 return DECODE_OK;
111 }
112
113 template<typename T> DecodeResult decode(uint8_t key, T &data) {
114 if (this->position_ == this->len_)
115 return DECODE_EMPTY;
116 if (this->buffer_[this->position_] != key)
117 return DECODE_UNMATCHED;
118 if (this->position_ + 1 + sizeof(T) > this->len_)
119 return DECODE_ERROR;
120 this->position_++;
121 T value = 0;
122 for (size_t i = 0; i != sizeof(T); ++i) {
123 value += this->buffer_[this->position_++] << (i * 8);
124 }
125 data = value;
126 return DECODE_OK;
127 }
128
129 template<typename T> DecodeResult decode(uint8_t key, char *buf, size_t buflen, T &data) {
130 if (this->position_ == this->len_)
131 return DECODE_EMPTY;
132 if (this->buffer_[this->position_] != key)
133 return DECODE_UNMATCHED;
134 this->position_++;
135 T value = 0;
136 for (size_t i = 0; i != sizeof(T); ++i) {
137 value += this->buffer_[this->position_++] << (i * 8);
138 }
139 data = value;
140 return this->decode_string(buf, buflen);
141 }
142
143 DecodeResult decode(uint8_t key) {
144 if (this->position_ == this->len_)
145 return DECODE_EMPTY;
146 if (this->buffer_[this->position_] != key)
147 return DECODE_UNMATCHED;
148 this->position_++;
149 return DECODE_OK;
150 }
151
152 size_t get_remaining_size() const { return this->len_ - this->position_; }
153
154 // align the pointer to the given byte boundary
155 bool bump_to(size_t boundary) {
156 auto newpos = this->position_;
157 auto offset = this->position_ % boundary;
158 if (offset != 0) {
159 newpos += boundary - offset;
160 }
161 if (newpos >= this->len_)
162 return false;
163 this->position_ = newpos;
164 return true;
165 }
166
167 bool decrypt(const uint32_t *key) {
168 if (this->get_remaining_size() % 4 != 0) {
169 return false;
170 }
171 xxtea::decrypt((uint32_t *) (this->buffer_ + this->position_), this->get_remaining_size() / 4, key);
172 return true;
173 }
174
175 protected:
176 const uint8_t *buffer_;
177 size_t len_;
178 size_t position_{};
179};
180
181static inline void add(std::vector<uint8_t> &vec, uint8_t data) { vec.push_back(data); }
182static inline void add(std::vector<uint8_t> &vec, uint16_t data) {
183 vec.push_back((uint8_t) data);
184 vec.push_back((uint8_t) (data >> 8));
185}
186static inline void add(std::vector<uint8_t> &vec, DataKey data) { vec.push_back(data); }
187static void add(std::vector<uint8_t> &vec, const char *str) {
188 auto len = strlen(str);
189 vec.push_back(len);
190 for (size_t i = 0; i != len; i++) {
191 vec.push_back(*str++);
192 }
193}
194
196 this->name_ = App.get_name().c_str();
197 if (strlen(this->name_) > 255) {
198 this->mark_failed();
199 this->status_set_error("Device name exceeds 255 chars");
200 return;
201 }
203 this->pref_ = global_preferences->make_preference<uint32_t>(PREF_HASH, true);
204 if (this->rolling_code_enable_) {
205 // restore the upper 32 bits of the rolling code, increment and save.
206 this->pref_.load(&this->rolling_code_[1]);
207 this->rolling_code_[1]++;
208 this->pref_.save(&this->rolling_code_[1]);
209 // must make sure it's saved immediately
211 this->ping_key_ = random_uint32();
212 ESP_LOGV(TAG, "Rolling code incremented, upper part now %u", (unsigned) this->rolling_code_[1]);
213 }
214#ifdef USE_SENSOR
215 for (auto &sensor : this->sensors_) {
216 sensor.sensor->add_on_state_callback([this, &sensor](float x) {
217 this->updated_ = true;
218 sensor.updated = true;
219 });
220 }
221#endif
222#ifdef USE_BINARY_SENSOR
223 for (auto &sensor : this->binary_sensors_) {
224 sensor.sensor->add_on_state_callback([this, &sensor](bool value) {
225 this->updated_ = true;
226 sensor.updated = true;
227 });
228 }
229#endif
230 // initialise the header. This is invariant.
231 add(this->header_, MAGIC_NUMBER);
232 add(this->header_, this->name_);
233 // pad to a multiple of 4 bytes
234 while (this->header_.size() & 0x3)
235 this->header_.push_back(0);
236}
237
239 this->data_.clear();
240 if (this->rolling_code_enable_) {
241 add(this->data_, ROLLING_CODE_KEY);
242 add(this->data_, this->rolling_code_[0]);
243 add(this->data_, this->rolling_code_[1]);
244 this->increment_code_();
245 } else {
246 add(this->data_, DATA_KEY);
247 }
248 for (auto pkey : this->ping_keys_) {
249 add(this->data_, PING_KEY);
250 add(this->data_, pkey.second);
251 }
252}
253
255 if (!this->should_send() || this->data_.empty())
256 return;
257 auto header_len = round4(this->header_.size());
258 auto len = round4(data_.size());
259 auto encode_buffer = std::vector<uint8_t>(round4(header_len + len));
260 memcpy(encode_buffer.data(), this->header_.data(), this->header_.size());
261 memcpy(encode_buffer.data() + header_len, this->data_.data(), this->data_.size());
262 if (this->is_encrypted_()) {
263 xxtea::encrypt((uint32_t *) (encode_buffer.data() + header_len), len / 4,
264 (uint32_t *) this->encryption_key_.data());
265 }
266 this->send_packet(encode_buffer);
267}
268
269void PacketTransport::add_binary_data_(uint8_t key, const char *id, bool data) {
270 auto len = 1 + 1 + 1 + strlen(id);
271 if (len + this->header_.size() + this->data_.size() > this->get_max_packet_size()) {
272 this->flush_();
273 this->init_data_();
274 }
275 add(this->data_, key);
276 add(this->data_, (uint8_t) data);
277 add(this->data_, id);
278}
279void PacketTransport::add_data_(uint8_t key, const char *id, float data) {
280 FuData udata{.f32 = data};
281 this->add_data_(key, id, udata.u32);
282}
283
284void PacketTransport::add_data_(uint8_t key, const char *id, uint32_t data) {
285 auto len = 4 + 1 + 1 + strlen(id);
286 if (len + this->header_.size() + this->data_.size() > this->get_max_packet_size()) {
287 this->flush_();
288 this->init_data_();
289 }
290 add(this->data_, key);
291 add(this->data_, data);
292 add(this->data_, id);
293}
295 if (!this->should_send())
296 return;
297 this->init_data_();
298#ifdef USE_SENSOR
299 for (auto &sensor : this->sensors_) {
300 if (all || sensor.updated) {
301 sensor.updated = false;
302 this->add_data_(SENSOR_KEY, sensor.id, sensor.sensor->get_state());
303 }
304 }
305#endif
306#ifdef USE_BINARY_SENSOR
307 for (auto &sensor : this->binary_sensors_) {
308 if (all || sensor.updated) {
309 sensor.updated = false;
310 this->add_binary_data_(BINARY_SENSOR_KEY, sensor.id, sensor.sensor->state);
311 }
312 }
313#endif
314 this->flush_();
315 this->updated_ = false;
316}
317
319 if (!this->ping_pong_enable_) {
320 return;
321 }
322 auto now = millis() / 1000;
323 if (this->last_key_time_ + this->ping_pong_recyle_time_ < now) {
325 ESP_LOGV(TAG, "Ping request, age %u", now - this->last_key_time_);
326 this->last_key_time_ = now;
327 }
328 for (const auto &provider : this->providers_) {
329 uint32_t key_response_age = now - provider.second.last_key_response_time;
330 if (key_response_age > (this->ping_pong_recyle_time_ * 2u)) {
331#ifdef USE_STATUS_SENSOR
332 if (provider.second.status_sensor != nullptr && provider.second.status_sensor->state) {
333 ESP_LOGI(TAG, "Ping status for %s timeout at %u with age %u", provider.first.c_str(), now, key_response_age);
334 provider.second.status_sensor->publish_state(false);
335 }
336#endif
337#ifdef USE_SENSOR
338 for (auto &sensor : this->remote_sensors_[provider.first]) {
339 sensor.second->publish_state(NAN);
340 }
341#endif
342#ifdef USE_BINARY_SENSOR
343 for (auto &sensor : this->remote_binary_sensors_[provider.first]) {
344 sensor.second->invalidate_state();
345 }
346#endif
347 } else {
348#ifdef USE_STATUS_SENSOR
349 if (provider.second.status_sensor != nullptr && !provider.second.status_sensor->state) {
350 ESP_LOGI(TAG, "Ping status for %s restored at %u with age %u", provider.first.c_str(), now, key_response_age);
351 provider.second.status_sensor->publish_state(true);
352 }
353#endif
354 }
355 }
356}
357
358void PacketTransport::add_key_(const char *name, uint32_t key) {
359 if (!this->is_encrypted_())
360 return;
361 if (this->ping_keys_.count(name) == 0 && this->ping_keys_.size() == MAX_PING_KEYS) {
362 ESP_LOGW(TAG, "Ping key from %s discarded", name);
363 return;
364 }
365 this->ping_keys_[name] = key;
366 this->updated_ = true;
367 ESP_LOGV(TAG, "Ping key from %s now %X", name, (unsigned) key);
368}
369
370static bool process_rolling_code(Provider &provider, PacketDecoder &decoder) {
371 uint32_t code0, code1;
372 if (decoder.get(code0) != DECODE_OK || decoder.get(code1) != DECODE_OK) {
373 ESP_LOGW(TAG, "Rolling code requires 8 bytes");
374 return false;
375 }
376 if (code1 < provider.last_code[1] || (code1 == provider.last_code[1] && code0 <= provider.last_code[0])) {
377 ESP_LOGW(TAG, "Rolling code for %s %08lX:%08lX is old", provider.name, (unsigned long) code1,
378 (unsigned long) code0);
379 return false;
380 }
381 provider.last_code[0] = code0;
382 provider.last_code[1] = code1;
383 ESP_LOGV(TAG, "Saw new rolling code for %s %08lX:%08lX", provider.name, (unsigned long) code1, (unsigned long) code0);
384 return true;
385}
386
390void PacketTransport::process_(const std::vector<uint8_t> &data) {
391 auto ping_key_seen = !this->ping_pong_enable_;
392 PacketDecoder decoder((data.data()), data.size());
393 char namebuf[256]{};
394 uint8_t byte;
395 FuData rdata{};
396 uint16_t magic;
397 if (decoder.get(magic) != DECODE_OK) {
398 ESP_LOGD(TAG, "Short buffer");
399 return;
400 }
401 if (magic != MAGIC_NUMBER && magic != MAGIC_PING) {
402 ESP_LOGV(TAG, "Bad magic %X", magic);
403 return;
404 }
405
406 if (decoder.decode_string(namebuf, sizeof namebuf) != DECODE_OK) {
407 ESP_LOGV(TAG, "Bad hostname length");
408 return;
409 }
410 if (strcmp(this->name_, namebuf) == 0) {
411 ESP_LOGVV(TAG, "Ignoring our own data");
412 return;
413 }
414 if (magic == MAGIC_PING) {
415 uint32_t key;
416 if (decoder.get(key) != DECODE_OK) {
417 ESP_LOGW(TAG, "Bad ping request");
418 return;
419 }
420 this->add_key_(namebuf, key);
421 ESP_LOGV(TAG, "Updated ping key for %s to %08X", namebuf, (unsigned) key);
422 return;
423 }
424
425 if (this->providers_.count(namebuf) == 0) {
426 ESP_LOGVV(TAG, "Unknown hostname %s", namebuf);
427 return;
428 }
429 ESP_LOGV(TAG, "Found hostname %s", namebuf);
430
431#ifdef USE_SENSOR
432 auto &sensors = this->remote_sensors_[namebuf];
433#endif
434#ifdef USE_BINARY_SENSOR
435 auto &binary_sensors = this->remote_binary_sensors_[namebuf];
436#endif
437
438 if (!decoder.bump_to(4)) {
439 ESP_LOGW(TAG, "Bad packet length %zu", data.size());
440 }
441 auto len = decoder.get_remaining_size();
442 if (round4(len) != len) {
443 ESP_LOGW(TAG, "Bad payload length %zu", len);
444 return;
445 }
446
447 auto &provider = this->providers_[namebuf];
448 // if encryption not used with this host, ping check is pointless since it would be easily spoofed.
449 if (provider.encryption_key.empty())
450 ping_key_seen = true;
451
452 if (!provider.encryption_key.empty()) {
453 decoder.decrypt((const uint32_t *) provider.encryption_key.data());
454 }
455 if (decoder.get(byte) != DECODE_OK) {
456 ESP_LOGV(TAG, "No key byte");
457 return;
458 }
459
460 if (byte == ROLLING_CODE_KEY) {
461 if (!process_rolling_code(provider, decoder))
462 return;
463 } else if (byte != DATA_KEY) {
464 ESP_LOGV(TAG, "Expected rolling_key or data_key, got %X", byte);
465 return;
466 }
467 uint32_t key;
468 while (decoder.get_remaining_size() != 0) {
469 if (decoder.decode(ZERO_FILL_KEY) == DECODE_OK)
470 continue;
471 if (decoder.decode(PING_KEY, key) == DECODE_OK) {
472 if (key == this->ping_key_) {
473 ping_key_seen = true;
474 provider.last_key_response_time = millis() / 1000;
475 ESP_LOGV(TAG, "Found good ping key %X at timestamp %" PRIu32, (unsigned) key, provider.last_key_response_time);
476 } else {
477 ESP_LOGV(TAG, "Unknown ping key %X", (unsigned) key);
478 }
479 continue;
480 }
481 if (!ping_key_seen) {
482 ESP_LOGW(TAG, "Ping key not seen");
483 this->resend_ping_key_ = true;
484 break;
485 }
486 if (decoder.decode(BINARY_SENSOR_KEY, namebuf, sizeof(namebuf), byte) == DECODE_OK) {
487 ESP_LOGV(TAG, "Got binary sensor %s %d", namebuf, byte);
488#ifdef USE_BINARY_SENSOR
489 if (binary_sensors.count(namebuf) != 0)
490 binary_sensors[namebuf]->publish_state(byte != 0);
491#endif
492 continue;
493 }
494 if (decoder.decode(SENSOR_KEY, namebuf, sizeof(namebuf), rdata.u32) == DECODE_OK) {
495 ESP_LOGV(TAG, "Got sensor %s %f", namebuf, rdata.f32);
496#ifdef USE_SENSOR
497 if (sensors.count(namebuf) != 0)
498 sensors[namebuf]->publish_state(rdata.f32);
499#endif
500 continue;
501 }
502 if (decoder.get(byte) == DECODE_OK) {
503 ESP_LOGW(TAG, "Unknown key %X", byte);
504 ESP_LOGD(TAG, "Buffer pos: %zu contents: %s", data.size() - decoder.get_remaining_size(),
505 format_hex_pretty(data).c_str());
506 }
507 break;
508 }
509}
510
512 ESP_LOGCONFIG(TAG,
513 "Packet Transport:\n"
514 " Platform: %s\n"
515 " Encrypted: %s\n"
516 " Ping-pong: %s",
517 this->platform_name_, YESNO(this->is_encrypted_()), YESNO(this->ping_pong_enable_));
518#ifdef USE_SENSOR
519 for (auto sensor : this->sensors_)
520 ESP_LOGCONFIG(TAG, " Sensor: %s", sensor.id);
521#endif
522#ifdef USE_BINARY_SENSOR
523 for (auto sensor : this->binary_sensors_)
524 ESP_LOGCONFIG(TAG, " Binary Sensor: %s", sensor.id);
525#endif
526 for (const auto &host : this->providers_) {
527 ESP_LOGCONFIG(TAG, " Remote host: %s", host.first.c_str());
528 ESP_LOGCONFIG(TAG, " Encrypted: %s", YESNO(!host.second.encryption_key.empty()));
529#ifdef USE_SENSOR
530 for (const auto &sensor : this->remote_sensors_[host.first.c_str()])
531 ESP_LOGCONFIG(TAG, " Sensor: %s", sensor.first.c_str());
532#endif
533#ifdef USE_BINARY_SENSOR
534 for (const auto &sensor : this->remote_binary_sensors_[host.first.c_str()])
535 ESP_LOGCONFIG(TAG, " Binary Sensor: %s", sensor.first.c_str());
536#endif
537 }
538}
540 if (this->rolling_code_enable_) {
541 if (++this->rolling_code_[0] == 0) {
542 this->rolling_code_[1]++;
543 this->pref_.save(&this->rolling_code_[1]);
544 // must make sure it's saved immediately
546 }
547 }
548}
549
551 if (this->resend_ping_key_)
553 if (this->updated_) {
554 this->send_data_(this->resend_data_);
555 }
556}
557
559 if (!this->ping_pong_enable_ || !this->should_send())
560 return;
561 this->ping_key_ = random_uint32();
562 this->ping_header_.clear();
563 add(this->ping_header_, MAGIC_PING);
564 add(this->ping_header_, this->name_);
565 add(this->ping_header_, this->ping_key_);
566 this->send_packet(this->ping_header_);
567 this->resend_ping_key_ = false;
568 ESP_LOGV(TAG, "Sent new ping request %08X", (unsigned) this->ping_key_);
569}
570} // namespace packet_transport
571} // namespace esphome
const std::string & get_name() const
Get the name of this Application set by pre_setup().
virtual void mark_failed()
Mark this component as failed.
void status_set_error(const char *message=nullptr)
bool save(const T *src)
Definition preferences.h:21
virtual bool sync()=0
Commit pending writes to flash.
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
void add_data_(uint8_t key, const char *id, float data)
std::map< std::string, std::map< std::string, binary_sensor::BinarySensor * > > remote_binary_sensors_
std::vector< BinarySensor > binary_sensors_
void add_key_(const char *name, uint32_t key)
void process_(const std::vector< uint8_t > &data)
Process a received packet.
std::map< std::string, std::map< std::string, sensor::Sensor * > > remote_sensors_
void add_binary_data_(uint8_t key, const char *id, bool data)
std::map< const char *, uint32_t > ping_keys_
virtual void send_packet(const std::vector< uint8_t > &buf) const =0
std::map< std::string, Provider > providers_
void encrypt(uint32_t *v, size_t n, const uint32_t *k)
Encrypt a block of data in-place using XXTEA algorithm with 256-bit key.
Definition xxtea.cpp:9
void decrypt(uint32_t *v, size_t n, const uint32_t *k)
Decrypt a block of data in-place using XXTEA algorithm with 256-bit key.
Definition xxtea.cpp:27
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string size_t len
Definition helpers.h:291
ESPPreferences * global_preferences
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:17
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Definition helpers.cpp:292
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
std::vector< uint8_t > encryption_key
uint16_t x
Definition tt21100.cpp:5