ESPHome 2025.12.0-dev
Loading...
Searching...
No Matches
esp32_improv_component.cpp
Go to the documentation of this file.
2
7#include "esphome/core/log.h"
8
9#ifdef USE_ESP32
10
11namespace esphome {
12namespace esp32_improv {
13
14using namespace bytebuffer;
15
16static const char *const TAG = "esp32_improv.component";
17static const char *const ESPHOME_MY_LINK = "https://my.home-assistant.io/redirect/config_flow_start?domain=esphome";
18static constexpr uint16_t STOP_ADVERTISING_DELAY =
19 10000; // Delay (ms) before stopping service to allow BLE clients to read the final state
20static constexpr uint16_t NAME_ADVERTISING_INTERVAL = 60000; // Advertise name every 60 seconds
21static constexpr uint16_t NAME_ADVERTISING_DURATION = 1000; // Advertise name for 1 second
22
23// Improv service data constants
24static constexpr uint8_t IMPROV_SERVICE_DATA_SIZE = 8;
25static constexpr uint8_t IMPROV_PROTOCOL_ID_1 = 0x77; // 'P' << 1 | 'R' >> 7
26static constexpr uint8_t IMPROV_PROTOCOL_ID_2 = 0x46; // 'I' << 1 | 'M' >> 7
27
29
31#ifdef USE_BINARY_SENSOR
32 if (this->authorizer_ != nullptr) {
33 this->authorizer_->add_on_state_callback([this](bool state) {
34 if (state) {
35 this->authorized_start_ = millis();
36 this->identify_start_ = 0;
37 }
38 });
39 }
40#endif
41 global_ble_server->on_disconnect([this](uint16_t conn_id) { this->set_error_(improv::ERROR_NONE); });
42
43 // Start with loop disabled - will be enabled by start() when needed
44 this->disable_loop();
45}
46
50 BLEDescriptor *status_descriptor = new BLE2902();
51 this->status_->add_descriptor(status_descriptor);
52
55 BLEDescriptor *error_descriptor = new BLE2902();
56 this->error_->add_descriptor(error_descriptor);
57
58 this->rpc_ = this->service_->create_characteristic(improv::RPC_COMMAND_UUID, BLECharacteristic::PROPERTY_WRITE);
59 this->rpc_->on_write([this](std::span<const uint8_t> data, uint16_t id) {
60 if (!data.empty()) {
61 this->incoming_data_.insert(this->incoming_data_.end(), data.begin(), data.end());
62 }
63 });
64 BLEDescriptor *rpc_descriptor = new BLE2902();
65 this->rpc_->add_descriptor(rpc_descriptor);
66
69 BLEDescriptor *rpc_response_descriptor = new BLE2902();
70 this->rpc_response_->add_descriptor(rpc_response_descriptor);
71
72 this->capabilities_ =
73 this->service_->create_characteristic(improv::CAPABILITIES_UUID, BLECharacteristic::PROPERTY_READ);
74 BLEDescriptor *capabilities_descriptor = new BLE2902();
75 this->capabilities_->add_descriptor(capabilities_descriptor);
76 uint8_t capabilities = 0x00;
77#ifdef USE_OUTPUT
78 if (this->status_indicator_ != nullptr)
79 capabilities |= improv::CAPABILITY_IDENTIFY;
80#endif
81 this->capabilities_->set_value(ByteBuffer::wrap(capabilities));
82 this->setup_complete_ = true;
83}
84
87 if (this->state_ != improv::STATE_STOPPED) {
88 this->state_ = improv::STATE_STOPPED;
89#ifdef USE_ESP32_IMPROV_STATE_CALLBACK
90 this->state_callback_.call(this->state_, this->error_state_);
91#endif
92 }
93 this->incoming_data_.clear();
94 return;
95 }
96 if (this->service_ == nullptr) {
97 // Setup the service
98 ESP_LOGD(TAG, "Creating Improv service");
99 this->service_ = global_ble_server->create_service(ESPBTUUID::from_raw(improv::SERVICE_UUID), true);
100 this->setup_characteristics();
101 }
102
103 if (!this->incoming_data_.empty())
105 uint32_t now = App.get_loop_component_start_time();
106
107 // Check if we need to update advertising type
108 if (this->state_ != improv::STATE_STOPPED && this->state_ != improv::STATE_PROVISIONED) {
110 }
111
112 switch (this->state_) {
113 case improv::STATE_STOPPED:
114 this->set_status_indicator_state_(false);
115
116 if (this->should_start_ && this->setup_complete_) {
117 if (this->service_->is_created()) {
118 this->service_->start();
119 } else if (this->service_->is_running()) {
120 // Start by advertising the device name first BEFORE setting any state
121 ESP_LOGV(TAG, "Starting with device name advertising");
122 this->advertising_device_name_ = true;
124 esp32_ble::global_ble->advertising_set_service_data_and_name(std::span<const uint8_t>{}, true);
126
127 // Set initial state based on whether we have an authorizer
128 this->set_state_(this->get_initial_state_(), false);
129 this->set_error_(improv::ERROR_NONE);
130 ESP_LOGD(TAG, "Service started!");
131 }
132 }
133 break;
134 case improv::STATE_AWAITING_AUTHORIZATION: {
135#ifdef USE_BINARY_SENSOR
136 if (this->authorizer_ == nullptr ||
137 (this->authorized_start_ != 0 && ((now - this->authorized_start_) < this->authorized_duration_))) {
138 this->set_state_(improv::STATE_AUTHORIZED);
139 } else {
140 if (!this->check_identify_())
141 this->set_status_indicator_state_(true);
142 }
143#else
144 this->set_state_(improv::STATE_AUTHORIZED);
145#endif
147 break;
148 }
149 case improv::STATE_AUTHORIZED: {
150#ifdef USE_BINARY_SENSOR
151 if (this->authorizer_ != nullptr && now - this->authorized_start_ > this->authorized_duration_) {
152 ESP_LOGD(TAG, "Authorization timeout");
153 this->set_state_(improv::STATE_AWAITING_AUTHORIZATION);
154 return;
155 }
156#endif
157 if (!this->check_identify_()) {
158 this->set_status_indicator_state_((now % 1000) < 500);
159 }
161 break;
162 }
163 case improv::STATE_PROVISIONING: {
164 this->set_status_indicator_state_((now % 200) < 100);
166 break;
167 }
168 case improv::STATE_PROVISIONED: {
169 this->incoming_data_.clear();
170 this->set_status_indicator_state_(false);
171 // Provisioning complete, no further loop execution needed
172 this->disable_loop();
173 break;
174 }
175 }
176}
177
179#ifdef USE_OUTPUT
180 if (this->status_indicator_ == nullptr)
181 return;
182 if (this->status_indicator_state_ == state)
183 return;
185 if (state) {
186 this->status_indicator_->turn_on();
187 } else {
189 }
190#endif
191}
192
193#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
195 switch (state) {
196 case improv::STATE_STOPPED:
197 return "STOPPED";
198 case improv::STATE_AWAITING_AUTHORIZATION:
199 return "AWAITING_AUTHORIZATION";
200 case improv::STATE_AUTHORIZED:
201 return "AUTHORIZED";
202 case improv::STATE_PROVISIONING:
203 return "PROVISIONING";
204 case improv::STATE_PROVISIONED:
205 return "PROVISIONED";
206 default:
207 return "UNKNOWN";
208 }
209}
210#endif
211
213 uint32_t now = millis();
214
215 bool identify = this->identify_start_ != 0 && now - this->identify_start_ <= this->identify_duration_;
216
217 if (identify) {
218 uint32_t time = now % 1000;
219 this->set_status_indicator_state_(time < 600 && time % 200 < 100);
220 }
221 return identify;
222}
223
224void ESP32ImprovComponent::set_state_(improv::State state, bool update_advertising) {
225 // Skip if state hasn't changed
226 if (this->state_ == state) {
227 return;
228 }
229
230#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
231 ESP_LOGD(TAG, "State transition: %s (0x%02X) -> %s (0x%02X)", this->state_to_string_(this->state_), this->state_,
232 this->state_to_string_(state), state);
233#endif
234 this->state_ = state;
235 if (this->status_ != nullptr && (this->status_->get_value().empty() || this->status_->get_value()[0] != state)) {
236 this->status_->set_value(ByteBuffer::wrap(static_cast<uint8_t>(state)));
237 if (state != improv::STATE_STOPPED)
238 this->status_->notify();
239 }
240 // Only advertise valid Improv states (0x01-0x04).
241 // STATE_STOPPED (0x00) is internal only and not part of the Improv spec.
242 // Advertising 0x00 causes undefined behavior in some clients and makes them
243 // repeatedly connect trying to determine the actual state.
244 if (state != improv::STATE_STOPPED && update_advertising) {
245 // State change always overrides name advertising and resets the timer
246 this->advertising_device_name_ = false;
247 // Reset the timer so we wait another 60 seconds before advertising name
249 // Advertise the new state via service data
251 }
252#ifdef USE_ESP32_IMPROV_STATE_CALLBACK
253 this->state_callback_.call(this->state_, this->error_state_);
254#endif
255}
256
257void ESP32ImprovComponent::set_error_(improv::Error error) {
258 if (error != improv::ERROR_NONE) {
259 ESP_LOGE(TAG, "Error: %d", error);
260 }
261 // The error_ characteristic is initialized in setup_characteristics() which is called
262 // from the loop, while the BLE disconnect callback is registered in setup().
263 // error_ can be nullptr if:
264 // 1. A client connects/disconnects before setup_characteristics() is called
265 // 2. The device is already provisioned so the service never starts (should_start_ is false)
266 if (this->error_ != nullptr && (this->error_->get_value().empty() || this->error_->get_value()[0] != error)) {
267 this->error_->set_value(ByteBuffer::wrap(static_cast<uint8_t>(error)));
268 if (this->state_ != improv::STATE_STOPPED)
269 this->error_->notify();
270 }
271}
272
273void ESP32ImprovComponent::send_response_(std::vector<uint8_t> &&response) {
274 this->rpc_response_->set_value(std::move(response));
275 if (this->state_ != improv::STATE_STOPPED)
276 this->rpc_response_->notify();
277}
278
280 if (this->should_start_ || this->state_ != improv::STATE_STOPPED)
281 return;
282
283 ESP_LOGD(TAG, "Setting Improv to start");
284 this->should_start_ = true;
285 this->enable_loop();
286}
287
289 this->should_start_ = false;
290 // Wait before stopping the service to ensure all BLE clients see the state change.
291 // This prevents clients from repeatedly reconnecting and wasting resources by allowing
292 // them to observe that the device is provisioned before the service disappears.
293 this->set_timeout("end-service", STOP_ADVERTISING_DELAY, [this] {
294 if (this->state_ == improv::STATE_STOPPED || this->service_ == nullptr)
295 return;
296 this->service_->stop();
297 this->set_state_(improv::STATE_STOPPED);
298 });
299}
300
302
304 ESP_LOGCONFIG(TAG, "ESP32 Improv:");
305#ifdef USE_BINARY_SENSOR
306 LOG_BINARY_SENSOR(" ", "Authorizer", this->authorizer_);
307#endif
308#ifdef USE_OUTPUT
309 ESP_LOGCONFIG(TAG, " Status Indicator: '%s'", YESNO(this->status_indicator_ != nullptr));
310#endif
311}
312
314 uint8_t length = this->incoming_data_[1];
315
316 ESP_LOGV(TAG, "Processing bytes - %s", format_hex_pretty(this->incoming_data_).c_str());
317 if (this->incoming_data_.size() - 3 == length) {
318 this->set_error_(improv::ERROR_NONE);
319 improv::ImprovCommand command = improv::parse_improv_data(this->incoming_data_);
320 switch (command.command) {
321 case improv::BAD_CHECKSUM:
322 ESP_LOGW(TAG, "Error decoding Improv payload");
323 this->set_error_(improv::ERROR_INVALID_RPC);
324 this->incoming_data_.clear();
325 break;
326 case improv::WIFI_SETTINGS: {
327 if (this->state_ != improv::STATE_AUTHORIZED) {
328 ESP_LOGW(TAG, "Settings received, but not authorized");
329 this->set_error_(improv::ERROR_NOT_AUTHORIZED);
330 this->incoming_data_.clear();
331 return;
332 }
333 wifi::WiFiAP sta{};
334 sta.set_ssid(command.ssid);
335 sta.set_password(command.password);
336 this->connecting_sta_ = sta;
337
340 this->set_state_(improv::STATE_PROVISIONING);
341 ESP_LOGD(TAG, "Received Improv Wi-Fi settings ssid=%s, password=" LOG_SECRET("%s"), command.ssid.c_str(),
342 command.password.c_str());
343
344 auto f = std::bind(&ESP32ImprovComponent::on_wifi_connect_timeout_, this);
345 this->set_timeout("wifi-connect-timeout", 30000, f);
346 this->incoming_data_.clear();
347 break;
348 }
349 case improv::IDENTIFY:
350 this->incoming_data_.clear();
351 this->identify_start_ = millis();
352 break;
353 default:
354 ESP_LOGW(TAG, "Unknown Improv payload");
355 this->set_error_(improv::ERROR_UNKNOWN_RPC);
356 this->incoming_data_.clear();
357 }
358 } else if (this->incoming_data_.size() - 2 > length) {
359 ESP_LOGV(TAG, "Too much data received or data malformed; resetting buffer");
360 this->incoming_data_.clear();
361 } else {
362 ESP_LOGV(TAG, "Waiting for split data packets");
363 }
364}
365
367 this->set_error_(improv::ERROR_UNABLE_TO_CONNECT);
368 this->set_state_(improv::STATE_AUTHORIZED);
369#ifdef USE_BINARY_SENSOR
370 if (this->authorizer_ != nullptr)
371 this->authorized_start_ = millis();
372#endif
373 ESP_LOGW(TAG, "Timed out while connecting to Wi-Fi network");
375}
376
378 if (!wifi::global_wifi_component->is_connected()) {
379 return;
380 }
381
382 if (this->state_ == improv::STATE_PROVISIONING) {
383 wifi::global_wifi_component->save_wifi_sta(this->connecting_sta_.get_ssid(), this->connecting_sta_.get_password());
384 this->connecting_sta_ = {};
385 this->cancel_timeout("wifi-connect-timeout");
386
387 // Build URL list with minimal allocations
388 // Maximum 3 URLs: custom next_url + ESPHOME_MY_LINK + webserver URL
389 std::string url_strings[3];
390 size_t url_count = 0;
391
392#ifdef USE_ESP32_IMPROV_NEXT_URL
393 // Add next_url if configured (should be first per Improv BLE spec)
394 std::string next_url = this->get_formatted_next_url_();
395 if (!next_url.empty()) {
396 url_strings[url_count++] = std::move(next_url);
397 }
398#endif
399
400 // Add default URLs for backward compatibility
401 url_strings[url_count++] = ESPHOME_MY_LINK;
402#ifdef USE_WEBSERVER
403 for (auto &ip : wifi::global_wifi_component->wifi_sta_ip_addresses()) {
404 if (ip.is_ip4()) {
405 char url_buffer[64];
406 snprintf(url_buffer, sizeof(url_buffer), "http://%s:%d", ip.str().c_str(), USE_WEBSERVER_PORT);
407 url_strings[url_count++] = url_buffer;
408 break;
409 }
410 }
411#endif
412 this->send_response_(improv::build_rpc_response(improv::WIFI_SETTINGS,
413 std::vector<std::string>(url_strings, url_strings + url_count)));
414 } else if (this->is_active() && this->state_ != improv::STATE_PROVISIONED) {
415 ESP_LOGD(TAG, "WiFi provisioned externally");
416 }
417
418 this->set_state_(improv::STATE_PROVISIONED);
419 this->stop();
420}
421
423 uint8_t service_data[IMPROV_SERVICE_DATA_SIZE] = {};
424 service_data[0] = IMPROV_PROTOCOL_ID_1; // PR
425 service_data[1] = IMPROV_PROTOCOL_ID_2; // IM
426 service_data[2] = static_cast<uint8_t>(this->state_);
427
428 uint8_t capabilities = 0x00;
429#ifdef USE_OUTPUT
430 if (this->status_indicator_ != nullptr)
431 capabilities |= improv::CAPABILITY_IDENTIFY;
432#endif
433
434 service_data[3] = capabilities;
435 // service_data[4-7] are already 0 (Reserved)
436
437 // Atomically set service data and disable name in advertising
438 esp32_ble::global_ble->advertising_set_service_data_and_name(std::span<const uint8_t>(service_data), false);
439}
440
442 uint32_t now = App.get_loop_component_start_time();
443
444 // If we're advertising the device name and it's been more than NAME_ADVERTISING_DURATION, switch back to service data
445 if (this->advertising_device_name_) {
446 if (now - this->last_name_adv_time_ >= NAME_ADVERTISING_DURATION) {
447 ESP_LOGV(TAG, "Switching back to service data advertising");
448 this->advertising_device_name_ = false;
449 // Restore service data advertising
451 }
452 return;
453 }
454
455 // Check if it's time to advertise the device name (every NAME_ADVERTISING_INTERVAL)
456 if (now - this->last_name_adv_time_ >= NAME_ADVERTISING_INTERVAL) {
457 ESP_LOGV(TAG, "Switching to device name advertising");
458 this->advertising_device_name_ = true;
459 this->last_name_adv_time_ = now;
460
461 // Atomically clear service data and enable name in advertising data
462 esp32_ble::global_ble->advertising_set_service_data_and_name(std::span<const uint8_t>{}, true);
463 }
464}
465
467#ifdef USE_BINARY_SENSOR
468 // If we have an authorizer, start in awaiting authorization state
469 return this->authorizer_ == nullptr ? improv::STATE_AUTHORIZED : improv::STATE_AWAITING_AUTHORIZATION;
470#else
471 // No binary_sensor support = no authorizer possible, start as authorized
472 return improv::STATE_AUTHORIZED;
473#endif
474}
475
476ESP32ImprovComponent *global_improv_component = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
477
478} // namespace esp32_improv
479} // namespace esphome
480
481#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.
bool cancel_timeout(const std::string &name)
Cancel a timeout function.
void enable_loop()
Enable this component's loop.
void disable_loop()
Disable this component's loop.
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
void add_on_state_callback(std::function< void(T)> &&callback)
static ByteBuffer wrap(T value, Endian endianness=LITTLE)
Definition bytebuffer.h:156
void advertising_set_service_data_and_name(std::span< const uint8_t > data, bool include_name)
Definition ble.cpp:104
static ESPBTUUID from_raw(const uint8_t *data)
Definition ble_uuid.cpp:29
void on_write(std::function< void(std::span< const uint8_t >, uint16_t)> &&callback)
void add_descriptor(BLEDescriptor *descriptor)
BLEService * create_service(ESPBTUUID uuid, bool advertise=false, uint16_t num_handles=15)
void on_disconnect(std::function< void(uint16_t)> &&callback)
Definition ble_server.h:62
BLECharacteristic * create_characteristic(const std::string &uuid, esp_gatt_char_prop_t properties)
void send_response_(std::vector< uint8_t > &&response)
CallbackManager< void(improv::State, improv::Error)> state_callback_
void set_state_(improv::State state, bool update_advertising=true)
const char * state_to_string_(improv::State state)
virtual void turn_off()
Disable this binary output.
virtual void turn_on()
Enable this binary output.
const std::string & get_ssid() const
void set_ssid(const std::string &ssid)
void set_sta(const WiFiAP &ap)
void save_wifi_sta(const std::string &ssid, const std::string &password)
void start_connecting(const WiFiAP &ap)
bool state
Definition fan.h:0
ESP32BLE * global_ble
Definition ble.cpp:660
ESP32ImprovComponent * global_improv_component
const float AFTER_BLUETOOTH
Definition component.cpp:62
WiFiComponent * global_wifi_component
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
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:317
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:30
Application App
Global storage of Application pointer - only one Application can exist.
uint16_t length
Definition tt21100.cpp:0