ESPHome 2025.9.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 }
274 add(this->data_, key);
275 add(this->data_, (uint8_t) data);
276 add(this->data_, id);
277}
278void PacketTransport::add_data_(uint8_t key, const char *id, float data) {
279 FuData udata{.f32 = data};
280 this->add_data_(key, id, udata.u32);
281}
282
283void PacketTransport::add_data_(uint8_t key, const char *id, uint32_t data) {
284 auto len = 4 + 1 + 1 + strlen(id);
285 if (len + this->header_.size() + this->data_.size() > this->get_max_packet_size()) {
286 this->flush_();
287 }
288 add(this->data_, key);
289 add(this->data_, data);
290 add(this->data_, id);
291}
293 if (!this->should_send())
294 return;
295 this->init_data_();
296#ifdef USE_SENSOR
297 for (auto &sensor : this->sensors_) {
298 if (all || sensor.updated) {
299 sensor.updated = false;
300 this->add_data_(SENSOR_KEY, sensor.id, sensor.sensor->get_state());
301 }
302 }
303#endif
304#ifdef USE_BINARY_SENSOR
305 for (auto &sensor : this->binary_sensors_) {
306 if (all || sensor.updated) {
307 sensor.updated = false;
308 this->add_binary_data_(BINARY_SENSOR_KEY, sensor.id, sensor.sensor->state);
309 }
310 }
311#endif
312 this->flush_();
313 this->updated_ = false;
314}
315
317 if (!this->ping_pong_enable_) {
318 return;
319 }
320 auto now = millis() / 1000;
321 if (this->last_key_time_ + this->ping_pong_recyle_time_ < now) {
323 ESP_LOGV(TAG, "Ping request, age %u", now - this->last_key_time_);
324 this->last_key_time_ = now;
325 }
326 for (const auto &provider : this->providers_) {
327 uint32_t key_response_age = now - provider.second.last_key_response_time;
328 if (key_response_age > (this->ping_pong_recyle_time_ * 2u)) {
329#ifdef USE_STATUS_SENSOR
330 if (provider.second.status_sensor != nullptr && provider.second.status_sensor->state) {
331 ESP_LOGI(TAG, "Ping status for %s timeout at %u with age %u", provider.first.c_str(), now, key_response_age);
332 provider.second.status_sensor->publish_state(false);
333 }
334#endif
335#ifdef USE_SENSOR
336 for (auto &sensor : this->remote_sensors_[provider.first]) {
337 sensor.second->publish_state(NAN);
338 }
339#endif
340#ifdef USE_BINARY_SENSOR
341 for (auto &sensor : this->remote_binary_sensors_[provider.first]) {
342 sensor.second->invalidate_state();
343 }
344#endif
345 } else {
346#ifdef USE_STATUS_SENSOR
347 if (provider.second.status_sensor != nullptr && !provider.second.status_sensor->state) {
348 ESP_LOGI(TAG, "Ping status for %s restored at %u with age %u", provider.first.c_str(), now, key_response_age);
349 provider.second.status_sensor->publish_state(true);
350 }
351#endif
352 }
353 }
354}
355
356void PacketTransport::add_key_(const char *name, uint32_t key) {
357 if (!this->is_encrypted_())
358 return;
359 if (this->ping_keys_.count(name) == 0 && this->ping_keys_.size() == MAX_PING_KEYS) {
360 ESP_LOGW(TAG, "Ping key from %s discarded", name);
361 return;
362 }
363 this->ping_keys_[name] = key;
364 this->updated_ = true;
365 ESP_LOGV(TAG, "Ping key from %s now %X", name, (unsigned) key);
366}
367
368static bool process_rolling_code(Provider &provider, PacketDecoder &decoder) {
369 uint32_t code0, code1;
370 if (decoder.get(code0) != DECODE_OK || decoder.get(code1) != DECODE_OK) {
371 ESP_LOGW(TAG, "Rolling code requires 8 bytes");
372 return false;
373 }
374 if (code1 < provider.last_code[1] || (code1 == provider.last_code[1] && code0 <= provider.last_code[0])) {
375 ESP_LOGW(TAG, "Rolling code for %s %08lX:%08lX is old", provider.name, (unsigned long) code1,
376 (unsigned long) code0);
377 return false;
378 }
379 provider.last_code[0] = code0;
380 provider.last_code[1] = code1;
381 ESP_LOGV(TAG, "Saw new rolling code for %s %08lX:%08lX", provider.name, (unsigned long) code1, (unsigned long) code0);
382 return true;
383}
384
388void PacketTransport::process_(const std::vector<uint8_t> &data) {
389 auto ping_key_seen = !this->ping_pong_enable_;
390 PacketDecoder decoder((data.data()), data.size());
391 char namebuf[256]{};
392 uint8_t byte;
393 FuData rdata{};
394 uint16_t magic;
395 if (decoder.get(magic) != DECODE_OK) {
396 ESP_LOGD(TAG, "Short buffer");
397 return;
398 }
399 if (magic != MAGIC_NUMBER && magic != MAGIC_PING) {
400 ESP_LOGV(TAG, "Bad magic %X", magic);
401 return;
402 }
403
404 if (decoder.decode_string(namebuf, sizeof namebuf) != DECODE_OK) {
405 ESP_LOGV(TAG, "Bad hostname length");
406 return;
407 }
408 if (strcmp(this->name_, namebuf) == 0) {
409 ESP_LOGVV(TAG, "Ignoring our own data");
410 return;
411 }
412 if (magic == MAGIC_PING) {
413 uint32_t key;
414 if (decoder.get(key) != DECODE_OK) {
415 ESP_LOGW(TAG, "Bad ping request");
416 return;
417 }
418 this->add_key_(namebuf, key);
419 ESP_LOGV(TAG, "Updated ping key for %s to %08X", namebuf, (unsigned) key);
420 return;
421 }
422
423 if (this->providers_.count(namebuf) == 0) {
424 ESP_LOGVV(TAG, "Unknown hostname %s", namebuf);
425 return;
426 }
427 ESP_LOGV(TAG, "Found hostname %s", namebuf);
428
429#ifdef USE_SENSOR
430 auto &sensors = this->remote_sensors_[namebuf];
431#endif
432#ifdef USE_BINARY_SENSOR
433 auto &binary_sensors = this->remote_binary_sensors_[namebuf];
434#endif
435
436 if (!decoder.bump_to(4)) {
437 ESP_LOGW(TAG, "Bad packet length %zu", data.size());
438 }
439 auto len = decoder.get_remaining_size();
440 if (round4(len) != len) {
441 ESP_LOGW(TAG, "Bad payload length %zu", len);
442 return;
443 }
444
445 auto &provider = this->providers_[namebuf];
446 // if encryption not used with this host, ping check is pointless since it would be easily spoofed.
447 if (provider.encryption_key.empty())
448 ping_key_seen = true;
449
450 if (!provider.encryption_key.empty()) {
451 decoder.decrypt((const uint32_t *) provider.encryption_key.data());
452 }
453 if (decoder.get(byte) != DECODE_OK) {
454 ESP_LOGV(TAG, "No key byte");
455 return;
456 }
457
458 if (byte == ROLLING_CODE_KEY) {
459 if (!process_rolling_code(provider, decoder))
460 return;
461 } else if (byte != DATA_KEY) {
462 ESP_LOGV(TAG, "Expected rolling_key or data_key, got %X", byte);
463 return;
464 }
465 uint32_t key;
466 while (decoder.get_remaining_size() != 0) {
467 if (decoder.decode(ZERO_FILL_KEY) == DECODE_OK)
468 continue;
469 if (decoder.decode(PING_KEY, key) == DECODE_OK) {
470 if (key == this->ping_key_) {
471 ping_key_seen = true;
472 provider.last_key_response_time = millis() / 1000;
473 ESP_LOGV(TAG, "Found good ping key %X at timestamp %" PRIu32, (unsigned) key, provider.last_key_response_time);
474 } else {
475 ESP_LOGV(TAG, "Unknown ping key %X", (unsigned) key);
476 }
477 continue;
478 }
479 if (!ping_key_seen) {
480 ESP_LOGW(TAG, "Ping key not seen");
481 this->resend_ping_key_ = true;
482 break;
483 }
484 if (decoder.decode(BINARY_SENSOR_KEY, namebuf, sizeof(namebuf), byte) == DECODE_OK) {
485 ESP_LOGV(TAG, "Got binary sensor %s %d", namebuf, byte);
486#ifdef USE_BINARY_SENSOR
487 if (binary_sensors.count(namebuf) != 0)
488 binary_sensors[namebuf]->publish_state(byte != 0);
489#endif
490 continue;
491 }
492 if (decoder.decode(SENSOR_KEY, namebuf, sizeof(namebuf), rdata.u32) == DECODE_OK) {
493 ESP_LOGV(TAG, "Got sensor %s %f", namebuf, rdata.f32);
494#ifdef USE_SENSOR
495 if (sensors.count(namebuf) != 0)
496 sensors[namebuf]->publish_state(rdata.f32);
497#endif
498 continue;
499 }
500 if (decoder.get(byte) == DECODE_OK) {
501 ESP_LOGW(TAG, "Unknown key %X", byte);
502 ESP_LOGD(TAG, "Buffer pos: %zu contents: %s", data.size() - decoder.get_remaining_size(),
503 format_hex_pretty(data).c_str());
504 }
505 break;
506 }
507}
508
510 ESP_LOGCONFIG(TAG,
511 "Packet Transport:\n"
512 " Platform: %s\n"
513 " Encrypted: %s\n"
514 " Ping-pong: %s",
515 this->platform_name_, YESNO(this->is_encrypted_()), YESNO(this->ping_pong_enable_));
516#ifdef USE_SENSOR
517 for (auto sensor : this->sensors_)
518 ESP_LOGCONFIG(TAG, " Sensor: %s", sensor.id);
519#endif
520#ifdef USE_BINARY_SENSOR
521 for (auto sensor : this->binary_sensors_)
522 ESP_LOGCONFIG(TAG, " Binary Sensor: %s", sensor.id);
523#endif
524 for (const auto &host : this->providers_) {
525 ESP_LOGCONFIG(TAG, " Remote host: %s", host.first.c_str());
526 ESP_LOGCONFIG(TAG, " Encrypted: %s", YESNO(!host.second.encryption_key.empty()));
527#ifdef USE_SENSOR
528 for (const auto &sensor : this->remote_sensors_[host.first.c_str()])
529 ESP_LOGCONFIG(TAG, " Sensor: %s", sensor.first.c_str());
530#endif
531#ifdef USE_BINARY_SENSOR
532 for (const auto &sensor : this->remote_binary_sensors_[host.first.c_str()])
533 ESP_LOGCONFIG(TAG, " Binary Sensor: %s", sensor.first.c_str());
534#endif
535 }
536}
538 if (this->rolling_code_enable_) {
539 if (++this->rolling_code_[0] == 0) {
540 this->rolling_code_[1]++;
541 this->pref_.save(&this->rolling_code_[1]);
542 // must make sure it's saved immediately
544 }
545 }
546}
547
549 if (this->resend_ping_key_)
551 if (this->updated_) {
552 this->send_data_(this->resend_data_);
553 }
554}
555
557 if (!this->ping_pong_enable_ || !this->should_send())
558 return;
559 this->ping_key_ = random_uint32();
560 this->ping_header_.clear();
561 add(this->ping_header_, MAGIC_PING);
562 add(this->ping_header_, this->name_);
563 add(this->ping_header_, this->ping_key_);
564 this->send_packet(this->ping_header_);
565 this->resend_ping_key_ = false;
566 ESP_LOGV(TAG, "Sent new ping request %08X", (unsigned) this->ping_key_);
567}
568} // namespace packet_transport
569} // 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:279
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:280
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