21using namespace bytebuffer;
25static constexpr uint32_t STOP_SERVICE_TIMEOUT_ID = 0;
26static constexpr uint32_t WIFI_CONNECT_TIMEOUT_ID = 1;
28static constexpr size_t IMPROV_MAX_LOG_BYTES = 128;
29static constexpr char ESPHOME_MY_LINK[] =
"https://my.home-assistant.io/redirect/config_flow_start?domain=esphome";
31static constexpr size_t RPC_RESPONSE_OVERHEAD = 3;
34static constexpr size_t MAX_NEXT_URL_LEN =
35 improv::RPC_RESPONSE_MAX_SIZE - RPC_RESPONSE_OVERHEAD - 1 -
sizeof(ESPHOME_MY_LINK);
36static constexpr uint16_t STOP_ADVERTISING_DELAY =
38static constexpr uint16_t NAME_ADVERTISING_INTERVAL = 60000;
39static constexpr uint16_t NAME_ADVERTISING_DURATION = 1000;
42static constexpr uint8_t IMPROV_SERVICE_DATA_SIZE = 8;
43static constexpr uint8_t IMPROV_PROTOCOL_ID_1 = 0x77;
44static constexpr uint8_t IMPROV_PROTOCOL_ID_2 = 0x46;
48static bool provisioning_closed() {
49#ifdef USE_PROVISIONING
56void ImprovBLEComponent::setup() {
57#ifdef USE_BINARY_SENSOR
58 if (this->authorizer_binary_sensor_ !=
nullptr) {
59 this->authorizer_binary_sensor_->add_on_state_callback([
this](
bool state) {
69#ifdef USE_PROVISIONING
72 ESP_LOGD(TAG,
"Provisioning window closed; stopping Improv");
82void ImprovBLEComponent::setup_characteristics() {
85 BLEDescriptor *status_descriptor =
new BLE2902();
90 BLEDescriptor *error_descriptor =
new BLE2902();
94 rpc->
on_write([
this](std::span<const uint8_t> data, uint16_t
id) {
99 BLEDescriptor *rpc_descriptor =
new BLE2902();
100 rpc->add_descriptor(rpc_descriptor);
104 BLEDescriptor *rpc_response_descriptor =
new BLE2902();
107 auto *capabilities_chr =
109 BLEDescriptor *capabilities_descriptor =
new BLE2902();
110 capabilities_chr->add_descriptor(capabilities_descriptor);
111 uint8_t capabilities = 0x00;
114 capabilities |= improv::CAPABILITY_IDENTIFY;
119void ImprovBLEComponent::loop() {
123 if (this->
state_ != improv::STATE_STOPPED) {
127 this->
state_ = improv::STATE_STOPPED;
130#ifdef USE_IMPROV_BLE_STATE_CALLBACK
143 ESP_LOGD(TAG,
"Creating Improv service");
145 this->setup_characteristics();
153 if (this->
state_ != improv::STATE_STOPPED && this->
state_ != improv::STATE_PROVISIONED) {
158 case improv::STATE_STOPPED:
169 ESP_LOGV(TAG,
"Starting with device name advertising");
180 ESP_LOGD(TAG,
"Service started!");
186 case improv::STATE_AWAITING_AUTHORIZATION: {
187#ifdef USE_BINARY_SENSOR
188 if (this->authorizer_binary_sensor_ ==
nullptr ||
201 case improv::STATE_AUTHORIZED: {
202#ifdef USE_BINARY_SENSOR
204 ESP_LOGD(TAG,
"Authorization timeout");
205 this->
set_state_(improv::STATE_AWAITING_AUTHORIZATION);
215 case improv::STATE_PROVISIONING: {
220 case improv::STATE_PROVISIONED: {
241#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
244 case improv::STATE_STOPPED:
246 case improv::STATE_AWAITING_AUTHORIZATION:
247 return "AWAITING_AUTHORIZATION";
248 case improv::STATE_AUTHORIZED:
250 case improv::STATE_PROVISIONING:
251 return "PROVISIONING";
252 case improv::STATE_PROVISIONED:
253 return "PROVISIONED";
274 if (this->
state_ == state) {
278#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
285 if (
state != improv::STATE_STOPPED)
292 if (state != improv::STATE_STOPPED && update_advertising) {
300#ifdef USE_IMPROV_BLE_STATE_CALLBACK
306 if (error != improv::ERROR_NONE) {
307 ESP_LOGE(TAG,
"Error: %d", error);
310 if (this->
error_ !=
nullptr && (this->
error_->
get_value().empty() || this->error_->get_value()[0] != error)) {
312 if (this->
state_ != improv::STATE_STOPPED)
320 if (this->
state_ != improv::STATE_STOPPED)
324void ImprovBLEComponent::start() {
330 if (provisioning_closed()) {
331 ESP_LOGD(TAG,
"Provisioning window closed; not starting Improv");
335 ESP_LOGD(TAG,
"Setting Improv to start");
340void ImprovBLEComponent::stop() {
345 if (this->
state_ == improv::STATE_STOPPED) {
353 this->
set_timeout(STOP_SERVICE_TIMEOUT_ID, STOP_ADVERTISING_DELAY, [
this] {
387void ImprovBLEComponent::dump_config() {
388 ESP_LOGCONFIG(TAG,
"Improv BLE:");
389#ifdef USE_BINARY_SENSOR
390 LOG_BINARY_SENSOR(
" ",
"Authorizer", this->authorizer_binary_sensor_);
393 ESP_LOGCONFIG(TAG,
" Status Indicator: '%s'", YESNO(this->
status_indicator_ !=
nullptr));
402 ESP_LOGV_HEX(TAG, this->
incoming_data_.data(), this->incoming_data_.size(), IMPROV_MAX_LOG_BYTES,
403 "Processing bytes - %s");
406 improv::ImprovCommand command = improv::parse_improv_data(this->
incoming_data_);
407 switch (command.command) {
408 case improv::BAD_CHECKSUM:
409 ESP_LOGW(TAG,
"Error decoding Improv payload");
413 case improv::WIFI_SETTINGS: {
414 if (this->
state_ != improv::STATE_AUTHORIZED) {
415 ESP_LOGW(TAG,
"Settings received, but not authorized");
416 this->
set_error_(improv::ERROR_NOT_AUTHORIZED);
420 if (provisioning_closed()) {
421 ESP_LOGW(TAG,
"Provisioning window closed; refusing settings");
422 this->
set_error_(improv::ERROR_NOT_AUTHORIZED);
429 ESP_LOGW(TAG,
"Wi-Fi is disabled; cannot provision");
430 this->
set_error_(improv::ERROR_UNABLE_TO_CONNECT);
436 sta.set_password(command.password.c_str());
442 ESP_LOGD(TAG,
"Received Improv Wi-Fi settings ssid=%s, password=" LOG_SECRET(
"%s"), command.ssid.c_str(),
443 command.password.c_str());
449 case improv::IDENTIFY:
454 ESP_LOGW(TAG,
"Unknown Improv payload");
459 ESP_LOGV(TAG,
"Too much data received or data malformed; resetting buffer");
462 ESP_LOGV(TAG,
"Waiting for split data packets");
468 if (this->
state_ != improv::STATE_PROVISIONING)
471 this->
set_error_(improv::ERROR_UNABLE_TO_CONNECT);
473#ifdef USE_BINARY_SENSOR
474 if (this->authorizer_binary_sensor_ !=
nullptr)
477 ESP_LOGW(TAG,
"Timed out while connecting to Wi-Fi network");
487 if (this->
state_ == improv::STATE_PROVISIONING) {
491 std::array<uint8_t, improv::RPC_RESPONSE_MAX_SIZE> buf;
492 improv::RpcResponseBuilder builder(buf, improv::WIFI_SETTINGS);
494#ifdef USE_IMPROV_NEXT_URL
501 builder.add_string(ESPHOME_MY_LINK,
sizeof(ESPHOME_MY_LINK) - 1);
511 }
else if (this->is_active() && this->
state_ != improv::STATE_PROVISIONED) {
512 ESP_LOGD(TAG,
"WiFi provisioned externally");
522 std::array<char, wifi::SSID_BUFFER_SIZE> ssid;
525 if (joined[0] ==
'\0')
534 uint8_t service_data[IMPROV_SERVICE_DATA_SIZE] = {};
535 service_data[0] = IMPROV_PROTOCOL_ID_1;
536 service_data[1] = IMPROV_PROTOCOL_ID_2;
537 service_data[2] =
static_cast<uint8_t
>(this->
state_);
539 uint8_t capabilities = 0x00;
542 capabilities |= improv::CAPABILITY_IDENTIFY;
545 service_data[3] = capabilities;
558 ESP_LOGV(TAG,
"Switching back to service data advertising");
568 ESP_LOGV(TAG,
"Switching to device name advertising");
595#ifdef USE_BINARY_SENSOR
597 return this->authorizer_binary_sensor_ ==
nullptr ? improv::STATE_AUTHORIZED : improv::STATE_AWAITING_AUTHORIZATION;
600 return improv::STATE_AUTHORIZED;
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 char *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 char *name, uint32_t timeout, SchedulerCallback &&f)
Set a timeout function with a const char* name.
constexpr bool empty() const
static constexpr ESPBTUUID from_raw(const uint8_t *data)
Construct from raw 16-byte little-endian UUID.
static ByteBuffer wrap(T value, Endian endianness=LITTLE)
void advertising_start()
Request advertising on behalf of a component.
void advertising_set_service_data_and_name(std::span< const uint8_t > data, bool include_name)
void advertising_clear_priority_uuid()
void advertising_set_priority_uuid(ESPBTUUID uuid)
Keep uuid and the service data alone in the advertising packet; applies on the next refresh.
void advertising_stop()
Release a request made with advertising_start(); advertising stops at the last release.
static constexpr uint32_t PROPERTY_WRITE
void set_value(ByteBuffer buffer)
void on_write(std::function< void(std::span< const uint8_t >, uint16_t)> &&callback)
static constexpr uint32_t PROPERTY_NOTIFY
static constexpr uint32_t PROPERTY_READ
void add_descriptor(BLEDescriptor *descriptor)
std::vector< uint8_t > & get_value()
ESPHOME_ALWAYS_INLINE bool is_running()
BLEService * create_service(ESPBTUUID uuid, bool advertise=false, uint16_t num_handles=15)
void remove_service(ESPBTUUID uuid, uint8_t inst_id=0)
void on_disconnect(std::function< void(uint16_t)> &&callback)
const ESPBTUUID & get_uuid() const
BLECharacteristic * create_characteristic(const std::string &uuid, esp_gatt_char_prop_t properties, esp_gatt_perm_t permissions=ESP_GATT_PERM_READ|ESP_GATT_PERM_WRITE)
bool should_start() const
void set_should_start(bool should_start)
Started by the server once created, and again after ble.enable.
void add_webserver_url_(improv::RpcResponseBuilder &builder, const network::IPAddress &ip)
Append "http://<ip>:<port>" to the response, warning if it does not fit.
void add_next_url_(improv::RpcResponseBuilder &builder, size_t max_len)
Append the formatted next_url to the RPC response, warning if it does not fit.
void check_wifi_connection_()
std::vector< uint8_t > incoming_data_
uint32_t authorized_start_
void request_advertising_()
void set_state_(improv::State state, bool update_advertising=true)
bool status_indicator_state_
const char * state_to_string_(improv::State state)
CallbackManager< void(improv::State, improv::Error)> state_callback_
void release_advertising_()
BLECharacteristic * rpc_response_
uint32_t last_name_adv_time_
BLECharacteristic * status_
void set_status_indicator_state_(bool state)
void update_advertising_type_()
uint32_t identify_duration_
output::BinaryOutput * status_indicator_
BLECharacteristic * error_
wifi::WiFiAP connecting_sta_
improv::Error error_state_
uint32_t authorized_duration_
improv::State get_initial_state_() const
bool advertising_requested_
void save_connecting_sta_()
void advertise_service_data_()
void on_wifi_connect_timeout_()
bool advertising_device_name_
void set_error_(improv::Error error)
void process_incoming_data_()
void send_response_(std::span< const uint8_t > response)
virtual void set_state(bool state)
Enable or disable this binary output.
void add_on_closed_callback(F &&callback)
StringRef 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)
const char * wifi_ssid_to(std::span< char, SSID_BUFFER_SIZE > buffer)
Write SSID to buffer without heap allocation.
bool is_connected() const
BLEServer * global_ble_server
ESPHOME_LOG_TAG(TAG, "esp32_ble")
ImprovBLEComponent * global_improv_component
std::span< const uint8_t > data
ProvisioningManager * global_provisioning_manager
constexpr float AFTER_BLUETOOTH
WiFiComponent * global_wifi_component
uint32_t IRAM_ATTR HOT millis()
Application App
Global storage of Application pointer - only one Application can exist.