mirror of
https://github.com/esphome/esphome.git
synced 2025-09-27 15:42:22 +01:00
Improv - BLE WiFi provisioning (#1807)
Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
69
esphome/components/esp32_improv/__init__.py
Normal file
69
esphome/components/esp32_improv/__init__.py
Normal file
@@ -0,0 +1,69 @@
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome.components import binary_sensor, output, esp32_ble
|
||||
from esphome.const import CONF_ID, ESP_PLATFORM_ESP32
|
||||
|
||||
|
||||
AUTO_LOAD = ["binary_sensor", "output", "improv"]
|
||||
CODEOWNERS = ["@jesserockz"]
|
||||
DEPENDENCIES = ["esp32_ble", "wifi"]
|
||||
ESP_PLATFORMS = [ESP_PLATFORM_ESP32]
|
||||
|
||||
CONF_AUTHORIZED_DURATION = "authorized_duration"
|
||||
CONF_AUTHORIZER = "authorizer"
|
||||
CONF_BLE_SERVER_ID = "ble_server_id"
|
||||
CONF_IDENTIFY_DURATION = "identify_duration"
|
||||
CONF_STATUS_INDICATOR = "status_indicator"
|
||||
CONF_WIFI_TIMEOUT = "wifi_timeout"
|
||||
|
||||
esp32_improv_ns = cg.esphome_ns.namespace("esp32_improv")
|
||||
ESP32ImprovComponent = esp32_improv_ns.class_(
|
||||
"ESP32ImprovComponent", cg.Component, esp32_ble.BLEServiceComponent
|
||||
)
|
||||
|
||||
|
||||
def validate_none_(value):
|
||||
if value in ("none", "None"):
|
||||
return None
|
||||
if cv.boolean(value) is False:
|
||||
return None
|
||||
raise cv.Invalid("Must be none")
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(ESP32ImprovComponent),
|
||||
cv.GenerateID(CONF_BLE_SERVER_ID): cv.use_id(esp32_ble.BLEServer),
|
||||
cv.Required(CONF_AUTHORIZER): cv.Any(
|
||||
validate_none_, cv.use_id(binary_sensor.BinarySensor)
|
||||
),
|
||||
cv.Optional(CONF_STATUS_INDICATOR): cv.use_id(output.BinaryOutput),
|
||||
cv.Optional(
|
||||
CONF_IDENTIFY_DURATION, default="10s"
|
||||
): cv.positive_time_period_milliseconds,
|
||||
cv.Optional(
|
||||
CONF_AUTHORIZED_DURATION, default="1min"
|
||||
): cv.positive_time_period_milliseconds,
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
|
||||
ble_server = await cg.get_variable(config[CONF_BLE_SERVER_ID])
|
||||
cg.add(ble_server.register_service_component(var))
|
||||
|
||||
cg.add_define("USE_IMPROV")
|
||||
|
||||
cg.add(var.set_identify_duration(config[CONF_IDENTIFY_DURATION]))
|
||||
cg.add(var.set_authorized_duration(config[CONF_AUTHORIZED_DURATION]))
|
||||
|
||||
if CONF_AUTHORIZER in config and config[CONF_AUTHORIZER] is not None:
|
||||
activator = await cg.get_variable(config[CONF_AUTHORIZER])
|
||||
cg.add(var.set_authorizer(activator))
|
||||
|
||||
if CONF_STATUS_INDICATOR in config:
|
||||
status_indicator = await cg.get_variable(config[CONF_STATUS_INDICATOR])
|
||||
cg.add(var.set_status_indicator(status_indicator))
|
275
esphome/components/esp32_improv/esp32_improv_component.cpp
Normal file
275
esphome/components/esp32_improv/esp32_improv_component.cpp
Normal file
@@ -0,0 +1,275 @@
|
||||
#include "esp32_improv_component.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/components/esp32_ble/ble_2902.h"
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
|
||||
namespace esphome {
|
||||
namespace esp32_improv {
|
||||
|
||||
static const char *TAG = "esp32_improv.component";
|
||||
|
||||
ESP32ImprovComponent::ESP32ImprovComponent() { global_improv_component = this; }
|
||||
|
||||
void ESP32ImprovComponent::setup_service() {
|
||||
this->service_ = esp32_ble::global_ble_server->create_service(improv::SERVICE_UUID, true);
|
||||
|
||||
this->status_ = this->service_->create_characteristic(
|
||||
improv::STATUS_UUID, esp32_ble::BLECharacteristic::PROPERTY_READ | esp32_ble::BLECharacteristic::PROPERTY_NOTIFY);
|
||||
esp32_ble::BLEDescriptor *status_descriptor = new esp32_ble::BLE2902();
|
||||
this->status_->add_descriptor(status_descriptor);
|
||||
|
||||
this->error_ = this->service_->create_characteristic(
|
||||
improv::ERROR_UUID, esp32_ble::BLECharacteristic::PROPERTY_READ | esp32_ble::BLECharacteristic::PROPERTY_NOTIFY);
|
||||
esp32_ble::BLEDescriptor *error_descriptor = new esp32_ble::BLE2902();
|
||||
this->error_->add_descriptor(error_descriptor);
|
||||
|
||||
this->rpc_ =
|
||||
this->service_->create_characteristic(improv::RPC_COMMAND_UUID, esp32_ble::BLECharacteristic::PROPERTY_WRITE);
|
||||
this->rpc_->on_write([this](std::vector<uint8_t> &data) {
|
||||
if (data.size() > 0) {
|
||||
this->incoming_data_.insert(this->incoming_data_.end(), data.begin(), data.end());
|
||||
}
|
||||
});
|
||||
esp32_ble::BLEDescriptor *rpc_descriptor = new esp32_ble::BLE2902();
|
||||
this->rpc_->add_descriptor(rpc_descriptor);
|
||||
|
||||
this->rpc_response_ =
|
||||
this->service_->create_characteristic(improv::RPC_RESULT_UUID, esp32_ble::BLECharacteristic::PROPERTY_READ |
|
||||
esp32_ble::BLECharacteristic::PROPERTY_NOTIFY);
|
||||
esp32_ble::BLEDescriptor *rpc_response_descriptor = new esp32_ble::BLE2902();
|
||||
this->rpc_response_->add_descriptor(rpc_response_descriptor);
|
||||
|
||||
this->capabilities_ =
|
||||
this->service_->create_characteristic(improv::CAPABILITIES_UUID, esp32_ble::BLECharacteristic::PROPERTY_READ);
|
||||
esp32_ble::BLEDescriptor *capabilities_descriptor = new esp32_ble::BLE2902();
|
||||
this->capabilities_->add_descriptor(capabilities_descriptor);
|
||||
uint8_t capabilities = 0x00;
|
||||
if (this->status_indicator_ != nullptr)
|
||||
capabilities |= improv::CAPABILITY_IDENTIFY;
|
||||
this->capabilities_->set_value(capabilities);
|
||||
this->setup_complete_ = true;
|
||||
}
|
||||
|
||||
void ESP32ImprovComponent::loop() {
|
||||
if (this->incoming_data_.size() > 0)
|
||||
this->process_incoming_data_();
|
||||
uint32_t now = millis();
|
||||
|
||||
switch (this->state_) {
|
||||
case improv::STATE_STOPPED:
|
||||
if (this->status_indicator_ != nullptr)
|
||||
this->status_indicator_->turn_off();
|
||||
|
||||
if (this->should_start_ && this->setup_complete_) {
|
||||
ESP_LOGD(TAG, "Starting Improv service...");
|
||||
|
||||
this->service_->start();
|
||||
this->service_->get_server()->get_advertising()->start();
|
||||
|
||||
this->set_state_(improv::STATE_AWAITING_AUTHORIZATION);
|
||||
this->set_error_(improv::ERROR_NONE);
|
||||
this->should_start_ = false;
|
||||
ESP_LOGD(TAG, "Service started!");
|
||||
}
|
||||
break;
|
||||
case improv::STATE_AWAITING_AUTHORIZATION: {
|
||||
if (this->authorizer_ == nullptr || this->authorizer_->state) {
|
||||
this->set_state_(improv::STATE_AUTHORIZED);
|
||||
this->authorized_start_ = now;
|
||||
} else {
|
||||
if (this->status_indicator_ != nullptr) {
|
||||
if (!this->check_identify_())
|
||||
this->status_indicator_->turn_on();
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case improv::STATE_AUTHORIZED: {
|
||||
if (this->authorizer_ != nullptr) {
|
||||
if (now - this->authorized_start_ > this->authorized_duration_) {
|
||||
ESP_LOGD(TAG, "Authorization timeout");
|
||||
this->set_state_(improv::STATE_AWAITING_AUTHORIZATION);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (this->status_indicator_ != nullptr) {
|
||||
if (!this->check_identify_()) {
|
||||
if ((now % 1000) < 500) {
|
||||
this->status_indicator_->turn_on();
|
||||
} else {
|
||||
this->status_indicator_->turn_off();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case improv::STATE_PROVISIONING: {
|
||||
if (this->status_indicator_ != nullptr) {
|
||||
if ((now % 200) < 100) {
|
||||
this->status_indicator_->turn_on();
|
||||
} else {
|
||||
this->status_indicator_->turn_off();
|
||||
}
|
||||
}
|
||||
if (wifi::global_wifi_component->is_connected()) {
|
||||
wifi::global_wifi_component->save_wifi_sta(this->connecting_sta_.get_ssid(),
|
||||
this->connecting_sta_.get_password());
|
||||
this->connecting_sta_ = {};
|
||||
this->cancel_timeout("wifi-connect-timeout");
|
||||
this->set_state_(improv::STATE_PROVISIONED);
|
||||
|
||||
std::string url = "https://my.home-assistant.io/redirect/config_flow_start?domain=esphome";
|
||||
std::vector<uint8_t> data = improv::build_rpc_response(improv::WIFI_SETTINGS, {url});
|
||||
this->send_response(data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case improv::STATE_PROVISIONED: {
|
||||
this->incoming_data_.clear();
|
||||
if (this->status_indicator_ != nullptr)
|
||||
this->status_indicator_->turn_on();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool ESP32ImprovComponent::check_identify_() {
|
||||
uint32_t now = millis();
|
||||
|
||||
bool identify = this->identify_start_ != 0 && now - this->identify_start_ <= this->identify_duration_;
|
||||
|
||||
if (identify) {
|
||||
uint32_t time = now % 1000;
|
||||
if (time < 600 && time % 200 < 100) {
|
||||
this->status_indicator_->turn_on();
|
||||
} else {
|
||||
this->status_indicator_->turn_off();
|
||||
}
|
||||
}
|
||||
return identify;
|
||||
}
|
||||
|
||||
void ESP32ImprovComponent::set_state_(improv::State state) {
|
||||
ESP_LOGV(TAG, "Setting state: %d", state);
|
||||
this->state_ = state;
|
||||
if (this->status_->get_value().size() == 0 || this->status_->get_value()[0] != state) {
|
||||
uint8_t data[1]{state};
|
||||
this->status_->set_value(data, 1);
|
||||
if (state != improv::STATE_STOPPED)
|
||||
this->status_->notify();
|
||||
}
|
||||
}
|
||||
|
||||
void ESP32ImprovComponent::set_error_(improv::Error error) {
|
||||
if (error != improv::ERROR_NONE)
|
||||
ESP_LOGE(TAG, "Error: %d", error);
|
||||
if (this->error_->get_value().size() == 0 || this->error_->get_value()[0] != error) {
|
||||
uint8_t data[1]{error};
|
||||
this->error_->set_value(data, 1);
|
||||
if (this->state_ != improv::STATE_STOPPED)
|
||||
this->error_->notify();
|
||||
}
|
||||
}
|
||||
|
||||
void ESP32ImprovComponent::send_response(std::vector<uint8_t> &response) {
|
||||
this->rpc_response_->set_value(response);
|
||||
if (this->state_ != improv::STATE_STOPPED)
|
||||
this->rpc_response_->notify();
|
||||
}
|
||||
|
||||
void ESP32ImprovComponent::start() {
|
||||
if (this->state_ != improv::STATE_STOPPED)
|
||||
return;
|
||||
|
||||
ESP_LOGD(TAG, "Setting Improv to start");
|
||||
this->should_start_ = true;
|
||||
}
|
||||
|
||||
void ESP32ImprovComponent::end() {
|
||||
this->set_state_(improv::STATE_STOPPED);
|
||||
this->service_->stop();
|
||||
}
|
||||
|
||||
float ESP32ImprovComponent::get_setup_priority() const {
|
||||
// Before WiFi
|
||||
return setup_priority::AFTER_BLUETOOTH;
|
||||
}
|
||||
|
||||
void ESP32ImprovComponent::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "ESP32 Improv:");
|
||||
LOG_BINARY_SENSOR(" ", "Authorizer", this->authorizer_);
|
||||
ESP_LOGCONFIG(TAG, " Status Indicator: '%s'", YESNO(this->status_indicator_ != nullptr));
|
||||
}
|
||||
|
||||
void ESP32ImprovComponent::process_incoming_data_() {
|
||||
uint8_t length = this->incoming_data_[1];
|
||||
|
||||
ESP_LOGD(TAG, "Processing bytes - %s", hexencode(this->incoming_data_).c_str());
|
||||
if (this->incoming_data_.size() - 3 == length) {
|
||||
this->set_error_(improv::ERROR_NONE);
|
||||
improv::ImprovCommand command = improv::parse_improv_data(this->incoming_data_);
|
||||
switch (command.command) {
|
||||
case improv::BAD_CHECKSUM:
|
||||
ESP_LOGW(TAG, "Error decoding Improv payload");
|
||||
this->set_error_(improv::ERROR_INVALID_RPC);
|
||||
this->incoming_data_.clear();
|
||||
break;
|
||||
case improv::WIFI_SETTINGS: {
|
||||
if (this->state_ != improv::STATE_AUTHORIZED) {
|
||||
ESP_LOGW(TAG, "Settings received, but not authorized");
|
||||
this->set_error_(improv::ERROR_NOT_AUTHORIZED);
|
||||
this->incoming_data_.clear();
|
||||
return;
|
||||
}
|
||||
wifi::WiFiAP sta{};
|
||||
sta.set_ssid(command.ssid);
|
||||
sta.set_password(command.password);
|
||||
this->connecting_sta_ = sta;
|
||||
|
||||
wifi::global_wifi_component->set_sta(sta);
|
||||
wifi::global_wifi_component->start_scanning();
|
||||
this->set_state_(improv::STATE_PROVISIONING);
|
||||
ESP_LOGD(TAG, "Received Improv wifi settings ssid=%s, password=" LOG_SECRET("%s"), command.ssid.c_str(),
|
||||
command.password.c_str());
|
||||
|
||||
auto f = std::bind(&ESP32ImprovComponent::on_wifi_connect_timeout_, this);
|
||||
this->set_timeout("wifi-connect-timeout", 30000, f);
|
||||
this->incoming_data_.clear();
|
||||
break;
|
||||
}
|
||||
case improv::IDENTIFY:
|
||||
this->incoming_data_.clear();
|
||||
this->identify_start_ = millis();
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW(TAG, "Unknown Improv payload");
|
||||
this->set_error_(improv::ERROR_UNKNOWN_RPC);
|
||||
this->incoming_data_.clear();
|
||||
}
|
||||
} else if (this->incoming_data_.size() - 2 > length) {
|
||||
ESP_LOGV(TAG, "Too much data came in, or malformed resetting buffer...");
|
||||
this->incoming_data_.clear();
|
||||
} else {
|
||||
ESP_LOGV(TAG, "Waiting for split data packets...");
|
||||
}
|
||||
}
|
||||
|
||||
void ESP32ImprovComponent::on_wifi_connect_timeout_() {
|
||||
this->set_error_(improv::ERROR_UNABLE_TO_CONNECT);
|
||||
this->set_state_(improv::STATE_AUTHORIZED);
|
||||
if (this->authorizer_ != nullptr)
|
||||
this->authorized_start_ = millis();
|
||||
ESP_LOGW(TAG, "Timed out trying to connect to given WiFi network");
|
||||
wifi::global_wifi_component->clear_sta();
|
||||
}
|
||||
|
||||
void ESP32ImprovComponent::on_client_disconnect() { this->set_error_(improv::ERROR_NONE); };
|
||||
|
||||
ESP32ImprovComponent *global_improv_component = nullptr;
|
||||
|
||||
} // namespace esp32_improv
|
||||
} // namespace esphome
|
||||
|
||||
#endif
|
74
esphome/components/esp32_improv/esp32_improv_component.h
Normal file
74
esphome/components/esp32_improv/esp32_improv_component.h
Normal file
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/preferences.h"
|
||||
#include "esphome/components/binary_sensor/binary_sensor.h"
|
||||
#include "esphome/components/esp32_ble/ble_server.h"
|
||||
#include "esphome/components/esp32_ble/ble_characteristic.h"
|
||||
#include "esphome/components/output/binary_output.h"
|
||||
#include "esphome/components/wifi/wifi_component.h"
|
||||
#include "esphome/components/improv/improv.h"
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
|
||||
namespace esphome {
|
||||
namespace esp32_improv {
|
||||
|
||||
class ESP32ImprovComponent : public Component, public esp32_ble::BLEServiceComponent {
|
||||
public:
|
||||
ESP32ImprovComponent();
|
||||
void dump_config() override;
|
||||
void loop() override;
|
||||
void setup_service() override;
|
||||
void on_client_disconnect() override;
|
||||
|
||||
float get_setup_priority() const override;
|
||||
void start();
|
||||
void end();
|
||||
bool is_active() const { return this->state_ == improv::STATE_AUTHORIZED; }
|
||||
|
||||
void set_authorizer(binary_sensor::BinarySensor *authorizer) { this->authorizer_ = authorizer; }
|
||||
void set_status_indicator(output::BinaryOutput *status_indicator) { this->status_indicator_ = status_indicator; }
|
||||
void set_identify_duration(uint32_t identify_duration) { this->identify_duration_ = identify_duration; }
|
||||
void set_authorized_duration(uint32_t authorized_duration) { this->authorized_duration_ = authorized_duration; }
|
||||
|
||||
protected:
|
||||
bool should_start_{false};
|
||||
bool setup_complete_{false};
|
||||
|
||||
uint32_t identify_start_{0};
|
||||
uint32_t identify_duration_;
|
||||
uint32_t authorized_start_{0};
|
||||
uint32_t authorized_duration_;
|
||||
|
||||
std::vector<uint8_t> incoming_data_;
|
||||
wifi::WiFiAP connecting_sta_;
|
||||
|
||||
esp32_ble::BLEService *service_;
|
||||
esp32_ble::BLECharacteristic *status_;
|
||||
esp32_ble::BLECharacteristic *error_;
|
||||
esp32_ble::BLECharacteristic *rpc_;
|
||||
esp32_ble::BLECharacteristic *rpc_response_;
|
||||
esp32_ble::BLECharacteristic *capabilities_;
|
||||
|
||||
binary_sensor::BinarySensor *authorizer_{nullptr};
|
||||
output::BinaryOutput *status_indicator_{nullptr};
|
||||
|
||||
improv::State state_{improv::STATE_STOPPED};
|
||||
improv::Error error_state_{improv::ERROR_NONE};
|
||||
|
||||
void set_state_(improv::State state);
|
||||
void set_error_(improv::Error error);
|
||||
void send_response(std::vector<uint8_t> &response);
|
||||
void process_incoming_data_();
|
||||
void on_wifi_connect_timeout_();
|
||||
bool check_identify_();
|
||||
};
|
||||
|
||||
extern ESP32ImprovComponent *global_improv_component;
|
||||
|
||||
} // namespace esp32_improv
|
||||
} // namespace esphome
|
||||
|
||||
#endif
|
Reference in New Issue
Block a user