ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
basic_session.cpp
Go to the documentation of this file.
1#include "basic_session.h"
2#ifdef USE_PACKET_INTERFACE_BASIC_SESSION
5#include "esphome/core/log.h"
6
8
9ESPHOME_LOG_TAG(TAG, "packet_interface.session");
10
11static constexpr uint8_t PACKET_TYPE_DATA = 0x00;
12static constexpr uint8_t PACKET_TYPE_KEEP_ALIVE = 0x01;
13// Type byte and the 32-bit boot id, little endian
14static constexpr size_t KEEP_ALIVE_SIZE = 5;
15
16BasicSession::BasicSession(PacketInterface *lower)
17 : PacketInterface(remaining_packet_size(lower->get_max_packet_size(), HEADER_SIZE)), lower_(lower) {
18 this->stack_on_(lower, CAPABILITY_SESSION);
19 // Data lost by a reliability layer below must be sent again, as after a restart of the peer
21 lower->add_on_session_state_callback([this](bool connected) {
22 if (!connected && this->connected_)
23 this->set_connected_(false);
24 });
25 }
26}
27
28void BasicSession::setup() {
29 if (this->lower_->get_max_packet_size() < KEEP_ALIVE_SIZE) {
30 this->mark_failed(LOG_STR("max_packet_size too small for the configured layers"));
31 return;
32 }
33 this->boot_id_ = random_uint32();
34#ifdef USE_BINARY_SENSOR
35 if (this->connected_binary_sensor_ != nullptr)
36 this->connected_binary_sensor_->publish_initial_state(false);
37#endif
38 this->lower_->add_packet_interface_listener(
39 [this](const PacketBuffer &data, const PacketMetaData &meta_data) { this->receive_(data, meta_data); });
40 // A reliability layer below queues this until its link is up, so the peer hears of a restart straight away
41 this->send_keep_alive_();
42 this->set_interval(this->keep_alive_ms_, [this] { this->on_interval_(); });
43}
44
45void BasicSession::dump_config() {
46 ESP_LOGCONFIG(TAG,
47 "Basic Session on '%s':\n"
48 " Max Packet Size: %zu\n"
49 " Keep Alive: %" PRIu32 "ms\n"
50 " Timeout: %" PRIu32 "ms",
51 this->name_, this->max_packet_size_, this->keep_alive_ms_, this->timeout_ms_);
52#ifdef USE_BINARY_SENSOR
53 LOG_BINARY_SENSOR(" ", "Connected", this->connected_binary_sensor_);
54#endif
55}
56
57bool BasicSession::send_to_interface(const PacketBuffer &data, const PacketMetaData &meta_data) {
58 if (this->is_failed())
59 return false;
60 uint8_t header = PACKET_TYPE_DATA;
61 PacketBuffer packet(&header, HEADER_SIZE, &data, nullptr, 0);
62 return this->lower_->send_to_interface(packet, meta_data);
63}
64
65void BasicSession::send_keep_alive_() {
66 uint8_t packet[KEEP_ALIVE_SIZE] = {
67 PACKET_TYPE_KEEP_ALIVE, static_cast<uint8_t>(this->boot_id_), static_cast<uint8_t>(this->boot_id_ >> 8),
68 static_cast<uint8_t>(this->boot_id_ >> 16), static_cast<uint8_t>(this->boot_id_ >> 24)};
69 if (!this->lower_->send_to_interface(PacketBuffer(packet, sizeof(packet)), {}))
70 ESP_LOGV(TAG, "%s: Lower layer did not accept keep-alive", this->name_);
71}
72
73void BasicSession::on_interval_() {
74 this->send_keep_alive_();
75 if (this->connected_ && App.get_loop_component_start_time() - this->last_receive_ms_ > this->timeout_ms_) {
76 ESP_LOGW(TAG, "%s: Peer not heard for %" PRIu32 "ms", this->name_, this->timeout_ms_);
77 this->set_connected_(false);
78 }
79}
80
81void BasicSession::set_connected_(bool connected) {
82 this->connected_ = connected;
83 ESP_LOGD(TAG, "%s: Session %s", this->name_, connected ? LOG_STR_LITERAL("connected") : LOG_STR_LITERAL("lost"));
84#ifdef USE_BINARY_SENSOR
85 PUBLISH_STATE(this->connected_binary_sensor_, connected);
86#endif
87 this->session_callback_.call(connected);
88}
89
90void BasicSession::receive_(const PacketBuffer &data, const PacketMetaData &meta_data) {
91 // Lower layers deliver packets in one piece; the payload is passed up without copying
92 if (!data.is_contiguous()) {
93 ESP_LOGW(TAG, "%s: Packet split across buffers is not supported", this->name_);
94 return;
95 }
96 auto packet = data.as_span();
97 if (packet.empty()) {
98 this->note_received_(false);
99 return;
100 }
101 uint8_t type = packet[0];
102 if (type == PACKET_TYPE_KEEP_ALIVE) {
103 if (packet.size() != KEEP_ALIVE_SIZE) {
104 ESP_LOGV(TAG, "%s: Keep-alive of %zu bytes dropped", this->name_, packet.size());
105 this->note_received_(false);
106 return;
107 }
108 uint32_t boot_id = encode_uint32(packet[4], packet[3], packet[2], packet[1]);
109 if (!this->peer_known_ || boot_id != this->peer_boot_id_) {
110 // Data may arrive before the first keep-alive, so only a changed id means a restart
111 if (this->connected_ && this->peer_known_) {
112 ESP_LOGD(TAG, "%s: Peer has restarted", this->name_);
113 this->set_connected_(false);
114 }
115 this->peer_boot_id_ = boot_id;
116 this->peer_known_ = true;
117 // Answer a new peer at once; it answers only if our id is new to it, so this cannot repeat
118 this->send_keep_alive_();
119 }
120 } else if (type != PACKET_TYPE_DATA) {
121 ESP_LOGV(TAG, "%s: Unknown packet type 0x%02X dropped", this->name_, type);
122 this->note_received_(false);
123 return;
124 }
125 this->note_received_(true);
126 this->last_receive_ms_ = App.get_loop_component_start_time();
127 if (!this->connected_)
128 this->set_connected_(true);
129 if (type == PACKET_TYPE_DATA)
130 this->on_receive_from_interface_(PacketBuffer(packet.data() + HEADER_SIZE, packet.size() - HEADER_SIZE), meta_data);
131}
132
133} // namespace esphome::packet_interface
134#endif
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.
A buffer class that efficiently represents a composite buffer with three sections:
A class that will transport data to and from an abstract channel.
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,...
A struct to hold metadata about a packet.
uint8_t type
constexpr size_t remaining_packet_size(size_t size, size_t used)
The room left for a packet of size bytes after used bytes, or 0 if it is too small.
ESPHOME_LOG_TAG(TAG, "packet_interface.session")
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:10
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:1051
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t