ESPHome 2025.5.0
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 auto now = millis() / 1000;
318 if (this->last_key_time_ + this->ping_pong_recyle_time_ < now) {
320 this->last_key_time_ = now;
321 }
322}
323
324void PacketTransport::add_key_(const char *name, uint32_t key) {
325 if (!this->is_encrypted_())
326 return;
327 if (this->ping_keys_.count(name) == 0 && this->ping_keys_.size() == MAX_PING_KEYS) {
328 ESP_LOGW(TAG, "Ping key from %s discarded", name);
329 return;
330 }
331 this->ping_keys_[name] = key;
332 this->updated_ = true;
333 ESP_LOGV(TAG, "Ping key from %s now %X", name, (unsigned) key);
334}
335
336static bool process_rolling_code(Provider &provider, PacketDecoder &decoder) {
337 uint32_t code0, code1;
338 if (decoder.get(code0) != DECODE_OK || decoder.get(code1) != DECODE_OK) {
339 ESP_LOGW(TAG, "Rolling code requires 8 bytes");
340 return false;
341 }
342 if (code1 < provider.last_code[1] || (code1 == provider.last_code[1] && code0 <= provider.last_code[0])) {
343 ESP_LOGW(TAG, "Rolling code for %s %08lX:%08lX is old", provider.name, (unsigned long) code1,
344 (unsigned long) code0);
345 return false;
346 }
347 provider.last_code[0] = code0;
348 provider.last_code[1] = code1;
349 ESP_LOGV(TAG, "Saw new rolling code for %s %08lX:%08lX", provider.name, (unsigned long) code1, (unsigned long) code0);
350 return true;
351}
352
356void PacketTransport::process_(const std::vector<uint8_t> &data) {
357 auto ping_key_seen = !this->ping_pong_enable_;
358 PacketDecoder decoder((data.data()), data.size());
359 char namebuf[256]{};
360 uint8_t byte;
361 FuData rdata{};
362 uint16_t magic;
363 if (decoder.get(magic) != DECODE_OK) {
364 ESP_LOGD(TAG, "Short buffer");
365 return;
366 }
367 if (magic != MAGIC_NUMBER && magic != MAGIC_PING) {
368 ESP_LOGV(TAG, "Bad magic %X", magic);
369 return;
370 }
371
372 if (decoder.decode_string(namebuf, sizeof namebuf) != DECODE_OK) {
373 ESP_LOGV(TAG, "Bad hostname length");
374 return;
375 }
376 if (strcmp(this->name_, namebuf) == 0) {
377 ESP_LOGVV(TAG, "Ignoring our own data");
378 return;
379 }
380 if (magic == MAGIC_PING) {
381 uint32_t key;
382 if (decoder.get(key) != DECODE_OK) {
383 ESP_LOGW(TAG, "Bad ping request");
384 return;
385 }
386 this->add_key_(namebuf, key);
387 ESP_LOGV(TAG, "Updated ping key for %s to %08X", namebuf, (unsigned) key);
388 return;
389 }
390
391 if (this->providers_.count(namebuf) == 0) {
392 ESP_LOGVV(TAG, "Unknown hostname %s", namebuf);
393 return;
394 }
395 ESP_LOGV(TAG, "Found hostname %s", namebuf);
396
397#ifdef USE_SENSOR
398 auto &sensors = this->remote_sensors_[namebuf];
399#endif
400#ifdef USE_BINARY_SENSOR
401 auto &binary_sensors = this->remote_binary_sensors_[namebuf];
402#endif
403
404 if (!decoder.bump_to(4)) {
405 ESP_LOGW(TAG, "Bad packet length %zu", data.size());
406 }
407 auto len = decoder.get_remaining_size();
408 if (round4(len) != len) {
409 ESP_LOGW(TAG, "Bad payload length %zu", len);
410 return;
411 }
412
413 auto &provider = this->providers_[namebuf];
414 // if encryption not used with this host, ping check is pointless since it would be easily spoofed.
415 if (provider.encryption_key.empty())
416 ping_key_seen = true;
417
418 if (!provider.encryption_key.empty()) {
419 decoder.decrypt((const uint32_t *) provider.encryption_key.data());
420 }
421 if (decoder.get(byte) != DECODE_OK) {
422 ESP_LOGV(TAG, "No key byte");
423 return;
424 }
425
426 if (byte == ROLLING_CODE_KEY) {
427 if (!process_rolling_code(provider, decoder))
428 return;
429 } else if (byte != DATA_KEY) {
430 ESP_LOGV(TAG, "Expected rolling_key or data_key, got %X", byte);
431 return;
432 }
433 uint32_t key;
434 while (decoder.get_remaining_size() != 0) {
435 if (decoder.decode(ZERO_FILL_KEY) == DECODE_OK)
436 continue;
437 if (decoder.decode(PING_KEY, key) == DECODE_OK) {
438 if (key == this->ping_key_) {
439 ping_key_seen = true;
440 ESP_LOGV(TAG, "Found good ping key %X", (unsigned) key);
441 } else {
442 ESP_LOGV(TAG, "Unknown ping key %X", (unsigned) key);
443 }
444 continue;
445 }
446 if (!ping_key_seen) {
447 ESP_LOGW(TAG, "Ping key not seen");
448 this->resend_ping_key_ = true;
449 break;
450 }
451 if (decoder.decode(BINARY_SENSOR_KEY, namebuf, sizeof(namebuf), byte) == DECODE_OK) {
452 ESP_LOGV(TAG, "Got binary sensor %s %d", namebuf, byte);
453#ifdef USE_BINARY_SENSOR
454 if (binary_sensors.count(namebuf) != 0)
455 binary_sensors[namebuf]->publish_state(byte != 0);
456#endif
457 continue;
458 }
459 if (decoder.decode(SENSOR_KEY, namebuf, sizeof(namebuf), rdata.u32) == DECODE_OK) {
460 ESP_LOGV(TAG, "Got sensor %s %f", namebuf, rdata.f32);
461#ifdef USE_SENSOR
462 if (sensors.count(namebuf) != 0)
463 sensors[namebuf]->publish_state(rdata.f32);
464#endif
465 continue;
466 }
467 if (decoder.get(byte) == DECODE_OK) {
468 ESP_LOGW(TAG, "Unknown key %X", byte);
469 ESP_LOGD(TAG, "Buffer pos: %zu contents: %s", data.size() - decoder.get_remaining_size(),
470 format_hex_pretty(data).c_str());
471 }
472 break;
473 }
474}
475
477 ESP_LOGCONFIG(TAG, "Packet Transport:");
478 ESP_LOGCONFIG(TAG, " Platform: %s", this->platform_name_);
479 ESP_LOGCONFIG(TAG, " Encrypted: %s", YESNO(this->is_encrypted_()));
480 ESP_LOGCONFIG(TAG, " Ping-pong: %s", YESNO(this->ping_pong_enable_));
481#ifdef USE_SENSOR
482 for (auto sensor : this->sensors_)
483 ESP_LOGCONFIG(TAG, " Sensor: %s", sensor.id);
484#endif
485#ifdef USE_BINARY_SENSOR
486 for (auto sensor : this->binary_sensors_)
487 ESP_LOGCONFIG(TAG, " Binary Sensor: %s", sensor.id);
488#endif
489 for (const auto &host : this->providers_) {
490 ESP_LOGCONFIG(TAG, " Remote host: %s", host.first.c_str());
491 ESP_LOGCONFIG(TAG, " Encrypted: %s", YESNO(!host.second.encryption_key.empty()));
492#ifdef USE_SENSOR
493 for (const auto &sensor : this->remote_sensors_[host.first.c_str()])
494 ESP_LOGCONFIG(TAG, " Sensor: %s", sensor.first.c_str());
495#endif
496#ifdef USE_BINARY_SENSOR
497 for (const auto &sensor : this->remote_binary_sensors_[host.first.c_str()])
498 ESP_LOGCONFIG(TAG, " Binary Sensor: %s", sensor.first.c_str());
499#endif
500 }
501}
503 if (this->rolling_code_enable_) {
504 if (++this->rolling_code_[0] == 0) {
505 this->rolling_code_[1]++;
506 this->pref_.save(&this->rolling_code_[1]);
507 // must make sure it's saved immediately
509 }
510 }
511}
512
514 if (this->resend_ping_key_)
516 if (this->updated_) {
517 this->send_data_(this->resend_data_);
518 }
519}
520
522 if (!this->ping_pong_enable_ || !this->should_send())
523 return;
524 this->ping_key_ = random_uint32();
525 this->ping_header_.clear();
526 add(this->ping_header_, MAGIC_PING);
527 add(this->ping_header_, this->name_);
528 add(this->ping_header_, this->ping_key_);
529 this->send_packet(this->ping_header_);
530 this->resend_ping_key_ = false;
531 ESP_LOGV(TAG, "Sent new ping request %08X", (unsigned) this->ping_key_);
532}
533} // namespace packet_transport
534} // 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="unspecified")
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:301
ESPPreferences * global_preferences
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:196
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:27
Application App
Global storage of Application pointer - only one Application can exist.
std::string format_hex_pretty(const uint8_t *data, size_t length)
Format the byte array data of length len in pretty-printed, human-readable hex.
Definition helpers.cpp:372
std::vector< uint8_t > encryption_key
uint16_t x
Definition tt21100.cpp:5