mirror of
https://github.com/esphome/esphome.git
synced 2025-11-14 05:45:48 +00:00
Compare commits
42 Commits
controller
...
ethernet_m
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d87063865c | ||
|
|
7a700ca077 | ||
|
|
1539b43074 | ||
|
|
463a00b1ac | ||
|
|
82692d7053 | ||
|
|
1cccfdd2b9 | ||
|
|
855aa32f54 | ||
|
|
0f8332fe3c | ||
|
|
40e2976ba2 | ||
|
|
e46300828e | ||
|
|
8c5b964722 | ||
|
|
43eafbccb3 | ||
|
|
f32b69b8f1 | ||
|
|
2a16653642 | ||
|
|
b47e89a7d5 | ||
|
|
c17a31a8f8 | ||
|
|
fbbdad75f6 | ||
|
|
7abb6d4998 | ||
|
|
1dabe83d04 | ||
|
|
0d735dc259 | ||
|
|
7b86e1feb0 | ||
|
|
d516627957 | ||
|
|
fb1c67490a | ||
|
|
8b9600b930 | ||
|
|
cbb98c4050 | ||
|
|
e7ff56f1cd | ||
|
|
7705a5de06 | ||
|
|
77ab096b59 | ||
|
|
26a3ec41d6 | ||
|
|
3bcbfe8d97 | ||
|
|
870b2c4f84 | ||
|
|
5f9c7a70ff | ||
|
|
f7179d4255 | ||
|
|
eb0558ca3f | ||
|
|
5585355263 | ||
|
|
e468ca4881 | ||
|
|
4c078dea2c | ||
|
|
783dbd1e6b | ||
|
|
b49619d9bf | ||
|
|
a290b88cd6 | ||
|
|
b61027607f | ||
|
|
f55c872180 |
@@ -172,8 +172,7 @@ This document provides essential context for AI models interacting with this pro
|
||||
|
||||
* **C++ Class Pattern:**
|
||||
```cpp
|
||||
namespace esphome {
|
||||
namespace my_component {
|
||||
namespace esphome::my_component {
|
||||
|
||||
class MyComponent : public Component {
|
||||
public:
|
||||
@@ -189,8 +188,7 @@ This document provides essential context for AI models interacting with this pro
|
||||
int param_{0};
|
||||
};
|
||||
|
||||
} // namespace my_component
|
||||
} // namespace esphome
|
||||
} // namespace esphome::my_component
|
||||
```
|
||||
|
||||
* **Common Component Examples:**
|
||||
|
||||
@@ -21,7 +21,7 @@ permissions:
|
||||
jobs:
|
||||
request-codeowner-reviews:
|
||||
name: Run
|
||||
if: ${{ !github.event.pull_request.draft }}
|
||||
if: ${{ github.repository == 'esphome/esphome' && !github.event.pull_request.draft }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Request reviews from component codeowners
|
||||
|
||||
@@ -206,6 +206,7 @@ esphome/components/hdc2010/* @optimusprimespace @ssieb
|
||||
esphome/components/he60r/* @clydebarrow
|
||||
esphome/components/heatpumpir/* @rob-deutsch
|
||||
esphome/components/hitachi_ac424/* @sourabhjaiswal
|
||||
esphome/components/hlk_fm22x/* @OnFreund
|
||||
esphome/components/hm3301/* @freekode
|
||||
esphome/components/hmac_md5/* @dwmw2
|
||||
esphome/components/homeassistant/* @esphome/core @OttoWinter
|
||||
@@ -395,6 +396,7 @@ esphome/components/rpi_dpi_rgb/* @clydebarrow
|
||||
esphome/components/rtl87xx/* @kuba2k2
|
||||
esphome/components/rtttl/* @glmnet
|
||||
esphome/components/runtime_stats/* @bdraco
|
||||
esphome/components/rx8130/* @beormund
|
||||
esphome/components/safe_mode/* @jsuanet @kbx81 @paulmonigatti
|
||||
esphome/components/scd4x/* @martgras @sjtrny
|
||||
esphome/components/script/* @esphome/core
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#include <utility>
|
||||
|
||||
#include "alarm_control_panel.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
@@ -34,6 +36,9 @@ void AlarmControlPanel::publish_state(AlarmControlPanelState state) {
|
||||
LOG_STR_ARG(alarm_control_panel_state_to_string(prev_state)));
|
||||
this->current_state_ = state;
|
||||
this->state_callback_.call();
|
||||
#if defined(USE_ALARM_CONTROL_PANEL) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_alarm_control_panel_update(this);
|
||||
#endif
|
||||
if (state == ACP_STATE_TRIGGERED) {
|
||||
this->triggered_callback_.call();
|
||||
} else if (state == ACP_STATE_ARMING) {
|
||||
|
||||
@@ -227,6 +227,7 @@ CONFIG_SCHEMA = cv.All(
|
||||
esp32=8, # More RAM, can buffer more
|
||||
rp2040=5, # Limited RAM
|
||||
bk72xx=8, # Moderate RAM
|
||||
nrf52=8, # Moderate RAM
|
||||
rtl87xx=8, # Moderate RAM
|
||||
host=16, # Abundant resources
|
||||
ln882x=8, # Moderate RAM
|
||||
@@ -244,6 +245,9 @@ async def to_code(config):
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
|
||||
# Track controller registration for StaticVector sizing
|
||||
CORE.register_controller()
|
||||
|
||||
cg.add(var.set_port(config[CONF_PORT]))
|
||||
if config[CONF_PASSWORD]:
|
||||
cg.add_define("USE_API_PASSWORD")
|
||||
|
||||
@@ -1467,6 +1467,8 @@ bool APIConnection::send_device_info_response(const DeviceInfoRequest &msg) {
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Beken");
|
||||
#elif defined(USE_LN882X)
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Lightning");
|
||||
#elif defined(USE_NRF52)
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Nordic Semiconductor");
|
||||
#elif defined(USE_RTL87XX)
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Realtek");
|
||||
#elif defined(USE_HOST)
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "esphome/components/network/util.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/util.h"
|
||||
@@ -34,7 +35,7 @@ APIServer::APIServer() {
|
||||
}
|
||||
|
||||
void APIServer::setup() {
|
||||
this->setup_controller();
|
||||
ControllerRegistry::register_controller(this);
|
||||
|
||||
#ifdef USE_API_NOISE
|
||||
uint32_t hash = 88491486UL;
|
||||
@@ -269,7 +270,7 @@ bool APIServer::check_password(const uint8_t *password_data, size_t password_len
|
||||
|
||||
void APIServer::handle_disconnect(APIConnection *conn) {}
|
||||
|
||||
// Macro for entities without extra parameters
|
||||
// Macro for controller update dispatch
|
||||
#define API_DISPATCH_UPDATE(entity_type, entity_name) \
|
||||
void APIServer::on_##entity_name##_update(entity_type *obj) { /* NOLINT(bugprone-macro-parentheses) */ \
|
||||
if (obj->is_internal()) \
|
||||
@@ -278,15 +279,6 @@ void APIServer::handle_disconnect(APIConnection *conn) {}
|
||||
c->send_##entity_name##_state(obj); \
|
||||
}
|
||||
|
||||
// Macro for entities with extra parameters (but parameters not used in send)
|
||||
#define API_DISPATCH_UPDATE_IGNORE_PARAMS(entity_type, entity_name, ...) \
|
||||
void APIServer::on_##entity_name##_update(entity_type *obj, __VA_ARGS__) { /* NOLINT(bugprone-macro-parentheses) */ \
|
||||
if (obj->is_internal()) \
|
||||
return; \
|
||||
for (auto &c : this->clients_) \
|
||||
c->send_##entity_name##_state(obj); \
|
||||
}
|
||||
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
API_DISPATCH_UPDATE(binary_sensor::BinarySensor, binary_sensor)
|
||||
#endif
|
||||
@@ -304,15 +296,15 @@ API_DISPATCH_UPDATE(light::LightState, light)
|
||||
#endif
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
API_DISPATCH_UPDATE_IGNORE_PARAMS(sensor::Sensor, sensor, float state)
|
||||
API_DISPATCH_UPDATE(sensor::Sensor, sensor)
|
||||
#endif
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
API_DISPATCH_UPDATE_IGNORE_PARAMS(switch_::Switch, switch, bool state)
|
||||
API_DISPATCH_UPDATE(switch_::Switch, switch)
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
API_DISPATCH_UPDATE_IGNORE_PARAMS(text_sensor::TextSensor, text_sensor, const std::string &state)
|
||||
API_DISPATCH_UPDATE(text_sensor::TextSensor, text_sensor)
|
||||
#endif
|
||||
|
||||
#ifdef USE_CLIMATE
|
||||
@@ -320,7 +312,7 @@ API_DISPATCH_UPDATE(climate::Climate, climate)
|
||||
#endif
|
||||
|
||||
#ifdef USE_NUMBER
|
||||
API_DISPATCH_UPDATE_IGNORE_PARAMS(number::Number, number, float state)
|
||||
API_DISPATCH_UPDATE(number::Number, number)
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_DATE
|
||||
@@ -336,11 +328,11 @@ API_DISPATCH_UPDATE(datetime::DateTimeEntity, datetime)
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT
|
||||
API_DISPATCH_UPDATE_IGNORE_PARAMS(text::Text, text, const std::string &state)
|
||||
API_DISPATCH_UPDATE(text::Text, text)
|
||||
#endif
|
||||
|
||||
#ifdef USE_SELECT
|
||||
API_DISPATCH_UPDATE_IGNORE_PARAMS(select::Select, select, const std::string &state, size_t index)
|
||||
API_DISPATCH_UPDATE(select::Select, select)
|
||||
#endif
|
||||
|
||||
#ifdef USE_LOCK
|
||||
@@ -356,12 +348,13 @@ API_DISPATCH_UPDATE(media_player::MediaPlayer, media_player)
|
||||
#endif
|
||||
|
||||
#ifdef USE_EVENT
|
||||
// Event is a special case - it's the only entity that passes extra parameters to the send method
|
||||
void APIServer::on_event(event::Event *obj, const std::string &event_type) {
|
||||
// Event is a special case - unlike other entities with simple state fields,
|
||||
// events store their state in a member accessed via obj->get_last_event_type()
|
||||
void APIServer::on_event(event::Event *obj) {
|
||||
if (obj->is_internal())
|
||||
return;
|
||||
for (auto &c : this->clients_)
|
||||
c->send_event(obj, event_type);
|
||||
c->send_event(obj, obj->get_last_event_type());
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -72,19 +72,19 @@ class APIServer : public Component, public Controller {
|
||||
void on_light_update(light::LightState *obj) override;
|
||||
#endif
|
||||
#ifdef USE_SENSOR
|
||||
void on_sensor_update(sensor::Sensor *obj, float state) override;
|
||||
void on_sensor_update(sensor::Sensor *obj) override;
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
void on_switch_update(switch_::Switch *obj, bool state) override;
|
||||
void on_switch_update(switch_::Switch *obj) override;
|
||||
#endif
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
void on_text_sensor_update(text_sensor::TextSensor *obj, const std::string &state) override;
|
||||
void on_text_sensor_update(text_sensor::TextSensor *obj) override;
|
||||
#endif
|
||||
#ifdef USE_CLIMATE
|
||||
void on_climate_update(climate::Climate *obj) override;
|
||||
#endif
|
||||
#ifdef USE_NUMBER
|
||||
void on_number_update(number::Number *obj, float state) override;
|
||||
void on_number_update(number::Number *obj) override;
|
||||
#endif
|
||||
#ifdef USE_DATETIME_DATE
|
||||
void on_date_update(datetime::DateEntity *obj) override;
|
||||
@@ -96,10 +96,10 @@ class APIServer : public Component, public Controller {
|
||||
void on_datetime_update(datetime::DateTimeEntity *obj) override;
|
||||
#endif
|
||||
#ifdef USE_TEXT
|
||||
void on_text_update(text::Text *obj, const std::string &state) override;
|
||||
void on_text_update(text::Text *obj) override;
|
||||
#endif
|
||||
#ifdef USE_SELECT
|
||||
void on_select_update(select::Select *obj, const std::string &state, size_t index) override;
|
||||
void on_select_update(select::Select *obj) override;
|
||||
#endif
|
||||
#ifdef USE_LOCK
|
||||
void on_lock_update(lock::Lock *obj) override;
|
||||
@@ -141,7 +141,7 @@ class APIServer : public Component, public Controller {
|
||||
void on_alarm_control_panel_update(alarm_control_panel::AlarmControlPanel *obj) override;
|
||||
#endif
|
||||
#ifdef USE_EVENT
|
||||
void on_event(event::Event *obj, const std::string &event_type) override;
|
||||
void on_event(event::Event *obj) override;
|
||||
#endif
|
||||
#ifdef USE_UPDATE
|
||||
void on_update(update::UpdateEntity *obj) override;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "binary_sensor.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -37,6 +39,9 @@ void BinarySensor::send_state_internal(bool new_state) {
|
||||
// Note that set_state_ de-dups and will only trigger callbacks if the state has actually changed
|
||||
if (this->set_state_(new_state)) {
|
||||
ESP_LOGD(TAG, "'%s': New state is %s", this->get_name().c_str(), ONOFF(new_state));
|
||||
#if defined(USE_BINARY_SENSOR) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_binary_sensor_update(this);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ static const char *const TAG = "bl0940.number";
|
||||
void CalibrationNumber::setup() {
|
||||
float value = 0.0f;
|
||||
if (this->restore_value_) {
|
||||
this->pref_ = global_preferences->make_preference<float>(this->get_object_id_hash());
|
||||
this->pref_ = global_preferences->make_preference<float>(this->get_preference_hash());
|
||||
if (!this->pref_.load(&value)) {
|
||||
value = 0.0f;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ from esphome.const import (
|
||||
CONF_TRIGGER_ID,
|
||||
CONF_VALUE,
|
||||
)
|
||||
from esphome.core import ID
|
||||
|
||||
AUTO_LOAD = ["esp32_ble_client"]
|
||||
CODEOWNERS = ["@buxtronix", "@clydebarrow"]
|
||||
@@ -198,7 +199,12 @@ async def ble_write_to_code(config, action_id, template_arg, args):
|
||||
templ = await cg.templatable(value, args, cg.std_vector.template(cg.uint8))
|
||||
cg.add(var.set_value_template(templ))
|
||||
else:
|
||||
cg.add(var.set_value_simple(value))
|
||||
# Generate static array in flash to avoid RAM copy
|
||||
if isinstance(value, bytes):
|
||||
value = list(value)
|
||||
arr_id = ID(f"{action_id}_data", is_declaration=True, type=cg.uint8)
|
||||
arr = cg.static_const_array(arr_id, cg.ArrayInitializer(*value))
|
||||
cg.add(var.set_value_simple(arr, len(value)))
|
||||
|
||||
if len(config[CONF_SERVICE_UUID]) == len(esp32_ble_tracker.bt_uuid16_format):
|
||||
cg.add(
|
||||
|
||||
@@ -96,11 +96,8 @@ template<typename... Ts> class BLEClientWriteAction : public Action<Ts...>, publ
|
||||
BLEClientWriteAction(BLEClient *ble_client) {
|
||||
ble_client->register_ble_node(this);
|
||||
ble_client_ = ble_client;
|
||||
this->construct_simple_value_();
|
||||
}
|
||||
|
||||
~BLEClientWriteAction() { this->destroy_simple_value_(); }
|
||||
|
||||
void set_service_uuid16(uint16_t uuid) { this->service_uuid_ = espbt::ESPBTUUID::from_uint16(uuid); }
|
||||
void set_service_uuid32(uint32_t uuid) { this->service_uuid_ = espbt::ESPBTUUID::from_uint32(uuid); }
|
||||
void set_service_uuid128(uint8_t *uuid) { this->service_uuid_ = espbt::ESPBTUUID::from_raw(uuid); }
|
||||
@@ -110,17 +107,14 @@ template<typename... Ts> class BLEClientWriteAction : public Action<Ts...>, publ
|
||||
void set_char_uuid128(uint8_t *uuid) { this->char_uuid_ = espbt::ESPBTUUID::from_raw(uuid); }
|
||||
|
||||
void set_value_template(std::vector<uint8_t> (*func)(Ts...)) {
|
||||
this->destroy_simple_value_();
|
||||
this->value_.template_func = func;
|
||||
this->has_simple_value_ = false;
|
||||
this->value_.func = func;
|
||||
this->len_ = -1; // Sentinel value indicates template mode
|
||||
}
|
||||
|
||||
void set_value_simple(const std::vector<uint8_t> &value) {
|
||||
if (!this->has_simple_value_) {
|
||||
this->construct_simple_value_();
|
||||
}
|
||||
this->value_.simple = value;
|
||||
this->has_simple_value_ = true;
|
||||
// Store pointer to static data in flash (no RAM copy)
|
||||
void set_value_simple(const uint8_t *data, size_t len) {
|
||||
this->value_.data = data;
|
||||
this->len_ = len; // Length >= 0 indicates static mode
|
||||
}
|
||||
|
||||
void play(const Ts &...x) override {}
|
||||
@@ -128,7 +122,14 @@ template<typename... Ts> class BLEClientWriteAction : public Action<Ts...>, publ
|
||||
void play_complex(const Ts &...x) override {
|
||||
this->num_running_++;
|
||||
this->var_ = std::make_tuple(x...);
|
||||
auto value = this->has_simple_value_ ? this->value_.simple : this->value_.template_func(x...);
|
||||
std::vector<uint8_t> value;
|
||||
if (this->len_ >= 0) {
|
||||
// Static mode: copy from flash to vector
|
||||
value.assign(this->value_.data, this->value_.data + this->len_);
|
||||
} else {
|
||||
// Template mode: call function
|
||||
value = this->value_.func(x...);
|
||||
}
|
||||
// on write failure, continue the automation chain rather than stopping so that e.g. disconnect can work.
|
||||
if (!write(value))
|
||||
this->play_next_(x...);
|
||||
@@ -201,21 +202,11 @@ template<typename... Ts> class BLEClientWriteAction : public Action<Ts...>, publ
|
||||
}
|
||||
|
||||
private:
|
||||
void construct_simple_value_() { new (&this->value_.simple) std::vector<uint8_t>(); }
|
||||
|
||||
void destroy_simple_value_() {
|
||||
if (this->has_simple_value_) {
|
||||
this->value_.simple.~vector();
|
||||
}
|
||||
}
|
||||
|
||||
BLEClient *ble_client_;
|
||||
bool has_simple_value_ = true;
|
||||
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
|
||||
union Value {
|
||||
std::vector<uint8_t> simple;
|
||||
std::vector<uint8_t> (*template_func)(Ts...);
|
||||
Value() {} // trivial constructor
|
||||
~Value() {} // trivial destructor - we manage lifetime via discriminator
|
||||
std::vector<uint8_t> (*func)(Ts...); // Function pointer (stateless lambdas)
|
||||
const uint8_t *data; // Pointer to static data in flash
|
||||
} value_;
|
||||
espbt::ESPBTUUID service_uuid_;
|
||||
espbt::ESPBTUUID char_uuid_;
|
||||
|
||||
@@ -4,7 +4,7 @@ from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DATA, CONF_ID, CONF_TRIGGER_ID
|
||||
from esphome.core import CORE
|
||||
from esphome.core import CORE, ID
|
||||
|
||||
CODEOWNERS = ["@mvturnho", "@danielschramm"]
|
||||
IS_PLATFORM_COMPONENT = True
|
||||
@@ -176,5 +176,8 @@ async def canbus_action_to_code(config, action_id, template_arg, args):
|
||||
else:
|
||||
if isinstance(data, bytes):
|
||||
data = [int(x) for x in data]
|
||||
cg.add(var.set_data_static(data))
|
||||
# Generate static array in flash to avoid RAM copy
|
||||
arr_id = ID(f"{action_id}_data", is_declaration=True, type=cg.uint8)
|
||||
arr = cg.static_const_array(arr_id, cg.ArrayInitializer(*data))
|
||||
cg.add(var.set_data_static(arr, len(data)))
|
||||
return var
|
||||
|
||||
@@ -112,13 +112,16 @@ class Canbus : public Component {
|
||||
|
||||
template<typename... Ts> class CanbusSendAction : public Action<Ts...>, public Parented<Canbus> {
|
||||
public:
|
||||
void set_data_template(const std::function<std::vector<uint8_t>(Ts...)> func) {
|
||||
this->data_func_ = func;
|
||||
this->static_ = false;
|
||||
void set_data_template(std::vector<uint8_t> (*func)(Ts...)) {
|
||||
// Stateless lambdas (generated by ESPHome) implicitly convert to function pointers
|
||||
this->data_.func = func;
|
||||
this->len_ = -1; // Sentinel value indicates template mode
|
||||
}
|
||||
void set_data_static(const std::vector<uint8_t> &data) {
|
||||
this->data_static_ = data;
|
||||
this->static_ = true;
|
||||
|
||||
// Store pointer to static data in flash (no RAM copy)
|
||||
void set_data_static(const uint8_t *data, size_t len) {
|
||||
this->data_.data = data;
|
||||
this->len_ = len; // Length >= 0 indicates static mode
|
||||
}
|
||||
|
||||
void set_can_id(uint32_t can_id) { this->can_id_ = can_id; }
|
||||
@@ -133,21 +136,26 @@ template<typename... Ts> class CanbusSendAction : public Action<Ts...>, public P
|
||||
auto can_id = this->can_id_.has_value() ? *this->can_id_ : this->parent_->can_id_;
|
||||
auto use_extended_id =
|
||||
this->use_extended_id_.has_value() ? *this->use_extended_id_ : this->parent_->use_extended_id_;
|
||||
if (this->static_) {
|
||||
this->parent_->send_data(can_id, use_extended_id, this->remote_transmission_request_, this->data_static_);
|
||||
std::vector<uint8_t> data;
|
||||
if (this->len_ >= 0) {
|
||||
// Static mode: copy from flash to vector
|
||||
data.assign(this->data_.data, this->data_.data + this->len_);
|
||||
} else {
|
||||
auto val = this->data_func_(x...);
|
||||
this->parent_->send_data(can_id, use_extended_id, this->remote_transmission_request_, val);
|
||||
// Template mode: call function
|
||||
data = this->data_.func(x...);
|
||||
}
|
||||
this->parent_->send_data(can_id, use_extended_id, this->remote_transmission_request_, data);
|
||||
}
|
||||
|
||||
protected:
|
||||
optional<uint32_t> can_id_{};
|
||||
optional<bool> use_extended_id_{};
|
||||
bool remote_transmission_request_{false};
|
||||
bool static_{false};
|
||||
std::function<std::vector<uint8_t>(Ts...)> data_func_{};
|
||||
std::vector<uint8_t> data_static_{};
|
||||
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
|
||||
union Data {
|
||||
std::vector<uint8_t> (*func)(Ts...); // Function pointer (stateless lambdas)
|
||||
const uint8_t *data; // Pointer to static data in flash
|
||||
} data_;
|
||||
};
|
||||
|
||||
class CanbusTrigger : public Trigger<std::vector<uint8_t>, uint32_t, bool>, public Component {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "climate.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/macros.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -463,6 +465,9 @@ void Climate::publish_state() {
|
||||
|
||||
// Send state to frontend
|
||||
this->state_callback_.call(*this);
|
||||
#if defined(USE_CLIMATE) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_climate_update(this);
|
||||
#endif
|
||||
// Save state
|
||||
this->save_state_();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#include "cover.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
|
||||
#include <strings.h>
|
||||
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -169,6 +173,9 @@ void Cover::publish_state(bool save) {
|
||||
ESP_LOGD(TAG, " Current Operation: %s", cover_operation_to_str(this->current_operation));
|
||||
|
||||
this->state_callback_.call();
|
||||
#if defined(USE_COVER) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_cover_update(this);
|
||||
#endif
|
||||
|
||||
if (save) {
|
||||
CoverRestoreState restore{};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "date_entity.h"
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#ifdef USE_DATETIME_DATE
|
||||
|
||||
#include "esphome/core/log.h"
|
||||
@@ -32,6 +33,9 @@ void DateEntity::publish_state() {
|
||||
this->set_has_state(true);
|
||||
ESP_LOGD(TAG, "'%s': Sending date %d-%d-%d", this->get_name().c_str(), this->year_, this->month_, this->day_);
|
||||
this->state_callback_.call();
|
||||
#if defined(USE_DATETIME_DATE) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_date_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
DateCall DateEntity::make_call() { return DateCall(this); }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "datetime_entity.h"
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#ifdef USE_DATETIME_DATETIME
|
||||
|
||||
#include "esphome/core/log.h"
|
||||
@@ -48,6 +49,9 @@ void DateTimeEntity::publish_state() {
|
||||
ESP_LOGD(TAG, "'%s': Sending datetime %04u-%02u-%02u %02d:%02d:%02d", this->get_name().c_str(), this->year_,
|
||||
this->month_, this->day_, this->hour_, this->minute_, this->second_);
|
||||
this->state_callback_.call();
|
||||
#if defined(USE_DATETIME_DATETIME) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_datetime_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
DateTimeCall DateTimeEntity::make_call() { return DateTimeCall(this); }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "time_entity.h"
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#ifdef USE_DATETIME_TIME
|
||||
|
||||
#include "esphome/core/log.h"
|
||||
@@ -29,6 +30,9 @@ void TimeEntity::publish_state() {
|
||||
ESP_LOGD(TAG, "'%s': Sending time %02d:%02d:%02d", this->get_name().c_str(), this->hour_, this->minute_,
|
||||
this->second_);
|
||||
this->state_callback_.call();
|
||||
#if defined(USE_DATETIME_TIME) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_time_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
TimeCall TimeEntity::make_call() { return TimeCall(this); }
|
||||
|
||||
@@ -59,6 +59,7 @@ async def to_code(config):
|
||||
zephyr_add_prj_conf("SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL", True)
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
cg.add_define("USE_DEBUG")
|
||||
|
||||
|
||||
FILTER_SOURCE_FILES = filter_source_files_from_platform(
|
||||
|
||||
@@ -383,6 +383,7 @@ async def to_code(config):
|
||||
cg.add(var.set_use_address(config[CONF_USE_ADDRESS]))
|
||||
|
||||
if CONF_MANUAL_IP in config:
|
||||
cg.add_define("USE_ETHERNET_MANUAL_IP")
|
||||
cg.add(var.set_manual_ip(manual_ip(config[CONF_MANUAL_IP])))
|
||||
|
||||
# Add compile-time define for PHY types with specific code
|
||||
|
||||
@@ -418,8 +418,6 @@ void EthernetComponent::dump_config() {
|
||||
|
||||
float EthernetComponent::get_setup_priority() const { return setup_priority::WIFI; }
|
||||
|
||||
bool EthernetComponent::can_proceed() { return this->is_connected(); }
|
||||
|
||||
network::IPAddresses EthernetComponent::get_ip_addresses() {
|
||||
network::IPAddresses addresses;
|
||||
esp_netif_ip_info_t ip;
|
||||
@@ -552,11 +550,14 @@ void EthernetComponent::start_connect_() {
|
||||
}
|
||||
|
||||
esp_netif_ip_info_t info;
|
||||
#ifdef USE_ETHERNET_MANUAL_IP
|
||||
if (this->manual_ip_.has_value()) {
|
||||
info.ip = this->manual_ip_->static_ip;
|
||||
info.gw = this->manual_ip_->gateway;
|
||||
info.netmask = this->manual_ip_->subnet;
|
||||
} else {
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
info.ip.addr = 0;
|
||||
info.gw.addr = 0;
|
||||
info.netmask.addr = 0;
|
||||
@@ -577,6 +578,7 @@ void EthernetComponent::start_connect_() {
|
||||
err = esp_netif_set_ip_info(this->eth_netif_, &info);
|
||||
ESPHL_ERROR_CHECK(err, "DHCPC set IP info error");
|
||||
|
||||
#ifdef USE_ETHERNET_MANUAL_IP
|
||||
if (this->manual_ip_.has_value()) {
|
||||
LwIPLock lock;
|
||||
if (this->manual_ip_->dns1.is_set()) {
|
||||
@@ -589,7 +591,9 @@ void EthernetComponent::start_connect_() {
|
||||
d = this->manual_ip_->dns2;
|
||||
dns_setserver(1, &d);
|
||||
}
|
||||
} else {
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
err = esp_netif_dhcpc_start(this->eth_netif_);
|
||||
if (err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED) {
|
||||
ESPHL_ERROR_CHECK(err, "DHCPC start error");
|
||||
@@ -687,7 +691,9 @@ void EthernetComponent::set_clk_mode(emac_rmii_clock_mode_t clk_mode) { this->cl
|
||||
void EthernetComponent::add_phy_register(PHYRegister register_value) { this->phy_registers_.push_back(register_value); }
|
||||
#endif
|
||||
void EthernetComponent::set_type(EthernetType type) { this->type_ = type; }
|
||||
#ifdef USE_ETHERNET_MANUAL_IP
|
||||
void EthernetComponent::set_manual_ip(const ManualIP &manual_ip) { this->manual_ip_ = manual_ip; }
|
||||
#endif
|
||||
|
||||
// set_use_address() is guaranteed to be called during component setup by Python code generation,
|
||||
// so use_address_ will always be valid when get_use_address() is called - no fallback needed.
|
||||
|
||||
@@ -58,7 +58,6 @@ class EthernetComponent : public Component {
|
||||
void loop() override;
|
||||
void dump_config() override;
|
||||
float get_setup_priority() const override;
|
||||
bool can_proceed() override;
|
||||
void on_powerdown() override { powerdown(); }
|
||||
bool is_connected();
|
||||
|
||||
@@ -83,7 +82,9 @@ class EthernetComponent : public Component {
|
||||
void add_phy_register(PHYRegister register_value);
|
||||
#endif
|
||||
void set_type(EthernetType type);
|
||||
#ifdef USE_ETHERNET_MANUAL_IP
|
||||
void set_manual_ip(const ManualIP &manual_ip);
|
||||
#endif
|
||||
void set_fixed_mac(const std::array<uint8_t, 6> &mac) { this->fixed_mac_ = mac; }
|
||||
|
||||
network::IPAddresses get_ip_addresses();
|
||||
@@ -138,7 +139,9 @@ class EthernetComponent : public Component {
|
||||
uint8_t mdc_pin_{23};
|
||||
uint8_t mdio_pin_{18};
|
||||
#endif
|
||||
#ifdef USE_ETHERNET_MANUAL_IP
|
||||
optional<ManualIP> manual_ip_{};
|
||||
#endif
|
||||
uint32_t connect_begin_;
|
||||
|
||||
// Group all uint8_t types together (enums and bools)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "event.h"
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -23,6 +24,9 @@ void Event::trigger(const std::string &event_type) {
|
||||
this->last_event_type_ = found;
|
||||
ESP_LOGD(TAG, "'%s' Triggered event '%s'", this->get_name().c_str(), this->last_event_type_);
|
||||
this->event_callback_.call(event_type);
|
||||
#if defined(USE_EVENT) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_event(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
void Event::set_event_types(const FixedVector<const char *> &event_types) {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "fan.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -181,6 +183,9 @@ void Fan::publish_state() {
|
||||
ESP_LOGD(TAG, " Preset Mode: %s", preset);
|
||||
}
|
||||
this->state_callback_.call();
|
||||
#if defined(USE_FAN) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_fan_update(this);
|
||||
#endif
|
||||
this->save_state_();
|
||||
}
|
||||
|
||||
|
||||
247
esphome/components/hlk_fm22x/__init__.py
Normal file
247
esphome/components/hlk_fm22x/__init__.py
Normal file
@@ -0,0 +1,247 @@
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import uart
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_DIRECTION,
|
||||
CONF_ID,
|
||||
CONF_NAME,
|
||||
CONF_ON_ENROLLMENT_DONE,
|
||||
CONF_ON_ENROLLMENT_FAILED,
|
||||
CONF_TRIGGER_ID,
|
||||
)
|
||||
|
||||
CODEOWNERS = ["@OnFreund"]
|
||||
DEPENDENCIES = ["uart"]
|
||||
AUTO_LOAD = ["binary_sensor", "sensor", "text_sensor"]
|
||||
MULTI_CONF = True
|
||||
|
||||
CONF_HLK_FM22X_ID = "hlk_fm22x_id"
|
||||
CONF_FACE_ID = "face_id"
|
||||
CONF_ON_FACE_SCAN_MATCHED = "on_face_scan_matched"
|
||||
CONF_ON_FACE_SCAN_UNMATCHED = "on_face_scan_unmatched"
|
||||
CONF_ON_FACE_SCAN_INVALID = "on_face_scan_invalid"
|
||||
CONF_ON_FACE_INFO = "on_face_info"
|
||||
|
||||
hlk_fm22x_ns = cg.esphome_ns.namespace("hlk_fm22x")
|
||||
HlkFm22xComponent = hlk_fm22x_ns.class_(
|
||||
"HlkFm22xComponent", cg.PollingComponent, uart.UARTDevice
|
||||
)
|
||||
|
||||
FaceScanMatchedTrigger = hlk_fm22x_ns.class_(
|
||||
"FaceScanMatchedTrigger", automation.Trigger.template(cg.int16, cg.std_string)
|
||||
)
|
||||
|
||||
FaceScanUnmatchedTrigger = hlk_fm22x_ns.class_(
|
||||
"FaceScanUnmatchedTrigger", automation.Trigger.template()
|
||||
)
|
||||
|
||||
FaceScanInvalidTrigger = hlk_fm22x_ns.class_(
|
||||
"FaceScanInvalidTrigger", automation.Trigger.template(cg.uint8)
|
||||
)
|
||||
|
||||
FaceInfoTrigger = hlk_fm22x_ns.class_(
|
||||
"FaceInfoTrigger",
|
||||
automation.Trigger.template(
|
||||
cg.int16, cg.int16, cg.int16, cg.int16, cg.int16, cg.int16, cg.int16, cg.int16
|
||||
),
|
||||
)
|
||||
|
||||
EnrollmentDoneTrigger = hlk_fm22x_ns.class_(
|
||||
"EnrollmentDoneTrigger", automation.Trigger.template(cg.int16, cg.uint8)
|
||||
)
|
||||
|
||||
EnrollmentFailedTrigger = hlk_fm22x_ns.class_(
|
||||
"EnrollmentFailedTrigger", automation.Trigger.template(cg.uint8)
|
||||
)
|
||||
|
||||
EnrollmentAction = hlk_fm22x_ns.class_("EnrollmentAction", automation.Action)
|
||||
DeleteAction = hlk_fm22x_ns.class_("DeleteAction", automation.Action)
|
||||
DeleteAllAction = hlk_fm22x_ns.class_("DeleteAllAction", automation.Action)
|
||||
ScanAction = hlk_fm22x_ns.class_("ScanAction", automation.Action)
|
||||
ResetAction = hlk_fm22x_ns.class_("ResetAction", automation.Action)
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(HlkFm22xComponent),
|
||||
cv.Optional(CONF_ON_FACE_SCAN_MATCHED): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(
|
||||
FaceScanMatchedTrigger
|
||||
),
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_ON_FACE_SCAN_UNMATCHED): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(
|
||||
FaceScanUnmatchedTrigger
|
||||
),
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_ON_FACE_SCAN_INVALID): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(
|
||||
FaceScanInvalidTrigger
|
||||
),
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_ON_FACE_INFO): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(FaceInfoTrigger),
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_ON_ENROLLMENT_DONE): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(
|
||||
EnrollmentDoneTrigger
|
||||
),
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_ON_ENROLLMENT_FAILED): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(
|
||||
EnrollmentFailedTrigger
|
||||
),
|
||||
}
|
||||
),
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("50ms"))
|
||||
.extend(uart.UART_DEVICE_SCHEMA),
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
await uart.register_uart_device(var, config)
|
||||
|
||||
for conf in config.get(CONF_ON_FACE_SCAN_MATCHED, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(
|
||||
trigger, [(cg.int16, "face_id"), (cg.std_string, "name")], conf
|
||||
)
|
||||
|
||||
for conf in config.get(CONF_ON_FACE_SCAN_UNMATCHED, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [], conf)
|
||||
|
||||
for conf in config.get(CONF_ON_FACE_SCAN_INVALID, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [(cg.uint8, "error")], conf)
|
||||
|
||||
for conf in config.get(CONF_ON_FACE_INFO, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(
|
||||
trigger,
|
||||
[
|
||||
(cg.int16, "status"),
|
||||
(cg.int16, "left"),
|
||||
(cg.int16, "top"),
|
||||
(cg.int16, "right"),
|
||||
(cg.int16, "bottom"),
|
||||
(cg.int16, "yaw"),
|
||||
(cg.int16, "pitch"),
|
||||
(cg.int16, "roll"),
|
||||
],
|
||||
conf,
|
||||
)
|
||||
|
||||
for conf in config.get(CONF_ON_ENROLLMENT_DONE, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(
|
||||
trigger, [(cg.int16, "face_id"), (cg.uint8, "direction")], conf
|
||||
)
|
||||
|
||||
for conf in config.get(CONF_ON_ENROLLMENT_FAILED, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [(cg.uint8, "error")], conf)
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
"hlk_fm22x.enroll",
|
||||
EnrollmentAction,
|
||||
cv.maybe_simple_value(
|
||||
{
|
||||
cv.GenerateID(): cv.use_id(HlkFm22xComponent),
|
||||
cv.Required(CONF_NAME): cv.templatable(cv.string),
|
||||
cv.Required(CONF_DIRECTION): cv.templatable(cv.uint8_t),
|
||||
},
|
||||
key=CONF_NAME,
|
||||
),
|
||||
)
|
||||
async def hlk_fm22x_enroll_to_code(config, action_id, template_arg, args):
|
||||
var = cg.new_Pvariable(action_id, template_arg)
|
||||
await cg.register_parented(var, config[CONF_ID])
|
||||
|
||||
template_ = await cg.templatable(config[CONF_NAME], args, cg.std_string)
|
||||
cg.add(var.set_name(template_))
|
||||
template_ = await cg.templatable(config[CONF_DIRECTION], args, cg.uint8)
|
||||
cg.add(var.set_direction(template_))
|
||||
return var
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
"hlk_fm22x.delete",
|
||||
DeleteAction,
|
||||
cv.maybe_simple_value(
|
||||
{
|
||||
cv.GenerateID(): cv.use_id(HlkFm22xComponent),
|
||||
cv.Required(CONF_FACE_ID): cv.templatable(cv.uint16_t),
|
||||
},
|
||||
key=CONF_FACE_ID,
|
||||
),
|
||||
)
|
||||
async def hlk_fm22x_delete_to_code(config, action_id, template_arg, args):
|
||||
var = cg.new_Pvariable(action_id, template_arg)
|
||||
await cg.register_parented(var, config[CONF_ID])
|
||||
|
||||
template_ = await cg.templatable(config[CONF_FACE_ID], args, cg.int16)
|
||||
cg.add(var.set_face_id(template_))
|
||||
return var
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
"hlk_fm22x.delete_all",
|
||||
DeleteAllAction,
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.use_id(HlkFm22xComponent),
|
||||
}
|
||||
),
|
||||
)
|
||||
async def hlk_fm22x_delete_all_to_code(config, action_id, template_arg, args):
|
||||
var = cg.new_Pvariable(action_id, template_arg)
|
||||
await cg.register_parented(var, config[CONF_ID])
|
||||
return var
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
"hlk_fm22x.scan",
|
||||
ScanAction,
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.use_id(HlkFm22xComponent),
|
||||
}
|
||||
),
|
||||
)
|
||||
async def hlk_fm22x_scan_to_code(config, action_id, template_arg, args):
|
||||
var = cg.new_Pvariable(action_id, template_arg)
|
||||
await cg.register_parented(var, config[CONF_ID])
|
||||
return var
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
"hlk_fm22x.reset",
|
||||
ResetAction,
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.use_id(HlkFm22xComponent),
|
||||
}
|
||||
),
|
||||
)
|
||||
async def hlk_fm22x_reset_to_code(config, action_id, template_arg, args):
|
||||
var = cg.new_Pvariable(action_id, template_arg)
|
||||
await cg.register_parented(var, config[CONF_ID])
|
||||
return var
|
||||
21
esphome/components/hlk_fm22x/binary_sensor.py
Normal file
21
esphome/components/hlk_fm22x/binary_sensor.py
Normal file
@@ -0,0 +1,21 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import binary_sensor
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ICON, ICON_KEY_PLUS
|
||||
|
||||
from . import CONF_HLK_FM22X_ID, HlkFm22xComponent
|
||||
|
||||
DEPENDENCIES = ["hlk_fm22x"]
|
||||
|
||||
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
|
||||
{
|
||||
cv.GenerateID(CONF_HLK_FM22X_ID): cv.use_id(HlkFm22xComponent),
|
||||
cv.Optional(CONF_ICON, default=ICON_KEY_PLUS): cv.icon,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
hub = await cg.get_variable(config[CONF_HLK_FM22X_ID])
|
||||
var = await binary_sensor.new_binary_sensor(config)
|
||||
cg.add(hub.set_enrolling_binary_sensor(var))
|
||||
325
esphome/components/hlk_fm22x/hlk_fm22x.cpp
Normal file
325
esphome/components/hlk_fm22x/hlk_fm22x.cpp
Normal file
@@ -0,0 +1,325 @@
|
||||
#include "hlk_fm22x.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include <array>
|
||||
#include <cinttypes>
|
||||
|
||||
namespace esphome::hlk_fm22x {
|
||||
|
||||
static const char *const TAG = "hlk_fm22x";
|
||||
|
||||
void HlkFm22xComponent::setup() {
|
||||
ESP_LOGCONFIG(TAG, "Setting up HLK-FM22X...");
|
||||
this->set_enrolling_(false);
|
||||
while (this->available()) {
|
||||
this->read();
|
||||
}
|
||||
this->defer([this]() { this->send_command_(HlkFm22xCommand::GET_STATUS); });
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::update() {
|
||||
if (this->active_command_ != HlkFm22xCommand::NONE) {
|
||||
if (this->wait_cycles_ > 600) {
|
||||
ESP_LOGE(TAG, "Command 0x%.2X timed out", this->active_command_);
|
||||
if (HlkFm22xCommand::RESET == this->active_command_) {
|
||||
this->mark_failed();
|
||||
} else {
|
||||
this->reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
this->recv_command_();
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::enroll_face(const std::string &name, HlkFm22xFaceDirection direction) {
|
||||
if (name.length() > 31) {
|
||||
ESP_LOGE(TAG, "enroll_face(): name too long '%s'", name.c_str());
|
||||
return;
|
||||
}
|
||||
ESP_LOGI(TAG, "Starting enrollment for %s", name.c_str());
|
||||
std::array<uint8_t, 35> data{};
|
||||
data[0] = 0; // admin
|
||||
std::copy(name.begin(), name.end(), data.begin() + 1);
|
||||
// Remaining bytes are already zero-initialized
|
||||
data[33] = (uint8_t) direction;
|
||||
data[34] = 10; // timeout
|
||||
this->send_command_(HlkFm22xCommand::ENROLL, data.data(), data.size());
|
||||
this->set_enrolling_(true);
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::scan_face() {
|
||||
ESP_LOGI(TAG, "Verify face");
|
||||
static const uint8_t DATA[] = {0, 0};
|
||||
this->send_command_(HlkFm22xCommand::VERIFY, DATA, sizeof(DATA));
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::delete_face(int16_t face_id) {
|
||||
ESP_LOGI(TAG, "Deleting face in slot %d", face_id);
|
||||
const uint8_t data[] = {(uint8_t) (face_id >> 8), (uint8_t) (face_id & 0xFF)};
|
||||
this->send_command_(HlkFm22xCommand::DELETE_FACE, data, sizeof(data));
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::delete_all_faces() {
|
||||
ESP_LOGI(TAG, "Deleting all stored faces");
|
||||
this->send_command_(HlkFm22xCommand::DELETE_ALL_FACES);
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::get_face_count_() {
|
||||
ESP_LOGD(TAG, "Getting face count");
|
||||
this->send_command_(HlkFm22xCommand::GET_ALL_FACE_IDS);
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::reset() {
|
||||
ESP_LOGI(TAG, "Resetting module");
|
||||
this->active_command_ = HlkFm22xCommand::NONE;
|
||||
this->wait_cycles_ = 0;
|
||||
this->set_enrolling_(false);
|
||||
this->send_command_(HlkFm22xCommand::RESET);
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::send_command_(HlkFm22xCommand command, const uint8_t *data, size_t size) {
|
||||
ESP_LOGV(TAG, "Send command: 0x%.2X", command);
|
||||
if (this->active_command_ != HlkFm22xCommand::NONE) {
|
||||
ESP_LOGW(TAG, "Command 0x%.2X already active", this->active_command_);
|
||||
return;
|
||||
}
|
||||
this->wait_cycles_ = 0;
|
||||
this->active_command_ = command;
|
||||
while (this->available())
|
||||
this->read();
|
||||
this->write((uint8_t) (START_CODE >> 8));
|
||||
this->write((uint8_t) (START_CODE & 0xFF));
|
||||
this->write((uint8_t) command);
|
||||
uint16_t data_size = size;
|
||||
this->write((uint8_t) (data_size >> 8));
|
||||
this->write((uint8_t) (data_size & 0xFF));
|
||||
|
||||
uint8_t checksum = 0;
|
||||
checksum ^= (uint8_t) command;
|
||||
checksum ^= (data_size >> 8);
|
||||
checksum ^= (data_size & 0xFF);
|
||||
for (size_t i = 0; i < size; i++) {
|
||||
this->write(data[i]);
|
||||
checksum ^= data[i];
|
||||
}
|
||||
|
||||
this->write(checksum);
|
||||
this->active_command_ = command;
|
||||
this->wait_cycles_ = 0;
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::recv_command_() {
|
||||
uint8_t byte, checksum = 0;
|
||||
uint16_t length = 0;
|
||||
|
||||
if (this->available() < 7) {
|
||||
++this->wait_cycles_;
|
||||
return;
|
||||
}
|
||||
this->wait_cycles_ = 0;
|
||||
|
||||
if ((this->read() != (uint8_t) (START_CODE >> 8)) || (this->read() != (uint8_t) (START_CODE & 0xFF))) {
|
||||
ESP_LOGE(TAG, "Invalid start code");
|
||||
return;
|
||||
}
|
||||
|
||||
byte = this->read();
|
||||
checksum ^= byte;
|
||||
HlkFm22xResponseType response_type = (HlkFm22xResponseType) byte;
|
||||
|
||||
byte = this->read();
|
||||
checksum ^= byte;
|
||||
length = byte << 8;
|
||||
byte = this->read();
|
||||
checksum ^= byte;
|
||||
length |= byte;
|
||||
|
||||
std::vector<uint8_t> data;
|
||||
data.reserve(length);
|
||||
for (uint16_t idx = 0; idx < length; ++idx) {
|
||||
byte = this->read();
|
||||
checksum ^= byte;
|
||||
data.push_back(byte);
|
||||
}
|
||||
|
||||
ESP_LOGV(TAG, "Recv type: 0x%.2X, data: %s", response_type, format_hex_pretty(data).c_str());
|
||||
|
||||
byte = this->read();
|
||||
if (byte != checksum) {
|
||||
ESP_LOGE(TAG, "Invalid checksum for data. Calculated: 0x%.2X, Received: 0x%.2X", checksum, byte);
|
||||
return;
|
||||
}
|
||||
switch (response_type) {
|
||||
case HlkFm22xResponseType::NOTE:
|
||||
this->handle_note_(data);
|
||||
break;
|
||||
case HlkFm22xResponseType::REPLY:
|
||||
this->handle_reply_(data);
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW(TAG, "Unexpected response type: 0x%.2X", response_type);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::handle_note_(const std::vector<uint8_t> &data) {
|
||||
switch (data[0]) {
|
||||
case HlkFm22xNoteType::FACE_STATE:
|
||||
if (data.size() < 17) {
|
||||
ESP_LOGE(TAG, "Invalid face note data size: %u", data.size());
|
||||
break;
|
||||
}
|
||||
{
|
||||
int16_t info[8];
|
||||
uint8_t offset = 1;
|
||||
for (int16_t &i : info) {
|
||||
i = ((int16_t) data[offset + 1] << 8) | data[offset];
|
||||
offset += 2;
|
||||
}
|
||||
ESP_LOGV(TAG, "Face state: status: %d, left: %d, top: %d, right: %d, bottom: %d, yaw: %d, pitch: %d, roll: %d",
|
||||
info[0], info[1], info[2], info[3], info[4], info[5], info[6], info[7]);
|
||||
this->face_info_callback_.call(info[0], info[1], info[2], info[3], info[4], info[5], info[6], info[7]);
|
||||
}
|
||||
break;
|
||||
case HlkFm22xNoteType::READY:
|
||||
ESP_LOGE(TAG, "Command 0x%.2X timed out", this->active_command_);
|
||||
switch (this->active_command_) {
|
||||
case HlkFm22xCommand::ENROLL:
|
||||
this->set_enrolling_(false);
|
||||
this->enrollment_failed_callback_.call(HlkFm22xResult::FAILED4_TIMEOUT);
|
||||
break;
|
||||
case HlkFm22xCommand::VERIFY:
|
||||
this->face_scan_invalid_callback_.call(HlkFm22xResult::FAILED4_TIMEOUT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
this->active_command_ = HlkFm22xCommand::NONE;
|
||||
this->wait_cycles_ = 0;
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW(TAG, "Unhandled note: 0x%.2X", data[0]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::handle_reply_(const std::vector<uint8_t> &data) {
|
||||
auto expected = this->active_command_;
|
||||
this->active_command_ = HlkFm22xCommand::NONE;
|
||||
if (data[0] != (uint8_t) expected) {
|
||||
ESP_LOGE(TAG, "Unexpected response command. Expected: 0x%.2X, Received: 0x%.2X", expected, data[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data[1] != HlkFm22xResult::SUCCESS) {
|
||||
ESP_LOGE(TAG, "Command <0x%.2X> failed. Error: 0x%.2X", data[0], data[1]);
|
||||
switch (expected) {
|
||||
case HlkFm22xCommand::ENROLL:
|
||||
this->set_enrolling_(false);
|
||||
this->enrollment_failed_callback_.call(data[1]);
|
||||
break;
|
||||
case HlkFm22xCommand::VERIFY:
|
||||
if (data[1] == HlkFm22xResult::REJECTED) {
|
||||
this->face_scan_unmatched_callback_.call();
|
||||
} else {
|
||||
this->face_scan_invalid_callback_.call(data[1]);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
switch (expected) {
|
||||
case HlkFm22xCommand::VERIFY: {
|
||||
int16_t face_id = ((int16_t) data[2] << 8) | data[3];
|
||||
std::string name(data.begin() + 4, data.begin() + 36);
|
||||
ESP_LOGD(TAG, "Face verified. ID: %d, name: %s", face_id, name.c_str());
|
||||
if (this->last_face_id_sensor_ != nullptr) {
|
||||
this->last_face_id_sensor_->publish_state(face_id);
|
||||
}
|
||||
if (this->last_face_name_text_sensor_ != nullptr) {
|
||||
this->last_face_name_text_sensor_->publish_state(name);
|
||||
}
|
||||
this->face_scan_matched_callback_.call(face_id, name);
|
||||
break;
|
||||
}
|
||||
case HlkFm22xCommand::ENROLL: {
|
||||
int16_t face_id = ((int16_t) data[2] << 8) | data[3];
|
||||
HlkFm22xFaceDirection direction = (HlkFm22xFaceDirection) data[4];
|
||||
ESP_LOGI(TAG, "Face enrolled. ID: %d, Direction: 0x%.2X", face_id, direction);
|
||||
this->enrollment_done_callback_.call(face_id, (uint8_t) direction);
|
||||
this->set_enrolling_(false);
|
||||
this->defer([this]() { this->get_face_count_(); });
|
||||
break;
|
||||
}
|
||||
case HlkFm22xCommand::GET_STATUS:
|
||||
if (this->status_sensor_ != nullptr) {
|
||||
this->status_sensor_->publish_state(data[2]);
|
||||
}
|
||||
this->defer([this]() { this->send_command_(HlkFm22xCommand::GET_VERSION); });
|
||||
break;
|
||||
case HlkFm22xCommand::GET_VERSION:
|
||||
if (this->version_text_sensor_ != nullptr) {
|
||||
std::string version(data.begin() + 2, data.end());
|
||||
this->version_text_sensor_->publish_state(version);
|
||||
}
|
||||
this->defer([this]() { this->get_face_count_(); });
|
||||
break;
|
||||
case HlkFm22xCommand::GET_ALL_FACE_IDS:
|
||||
if (this->face_count_sensor_ != nullptr) {
|
||||
this->face_count_sensor_->publish_state(data[2]);
|
||||
}
|
||||
break;
|
||||
case HlkFm22xCommand::DELETE_FACE:
|
||||
ESP_LOGI(TAG, "Deleted face");
|
||||
break;
|
||||
case HlkFm22xCommand::DELETE_ALL_FACES:
|
||||
ESP_LOGI(TAG, "Deleted all faces");
|
||||
break;
|
||||
case HlkFm22xCommand::RESET:
|
||||
ESP_LOGI(TAG, "Module reset");
|
||||
this->defer([this]() { this->send_command_(HlkFm22xCommand::GET_STATUS); });
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW(TAG, "Unhandled command: 0x%.2X", this->active_command_);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::set_enrolling_(bool enrolling) {
|
||||
if (this->enrolling_binary_sensor_ != nullptr) {
|
||||
this->enrolling_binary_sensor_->publish_state(enrolling);
|
||||
}
|
||||
}
|
||||
|
||||
void HlkFm22xComponent::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "HLK_FM22X:");
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
if (this->version_text_sensor_) {
|
||||
LOG_TEXT_SENSOR(" ", "Version", this->version_text_sensor_);
|
||||
ESP_LOGCONFIG(TAG, " Current Value: %s", this->version_text_sensor_->get_state().c_str());
|
||||
}
|
||||
if (this->enrolling_binary_sensor_) {
|
||||
LOG_BINARY_SENSOR(" ", "Enrolling", this->enrolling_binary_sensor_);
|
||||
ESP_LOGCONFIG(TAG, " Current Value: %s", this->enrolling_binary_sensor_->state ? "ON" : "OFF");
|
||||
}
|
||||
if (this->face_count_sensor_) {
|
||||
LOG_SENSOR(" ", "Face Count", this->face_count_sensor_);
|
||||
ESP_LOGCONFIG(TAG, " Current Value: %u", (uint16_t) this->face_count_sensor_->get_state());
|
||||
}
|
||||
if (this->status_sensor_) {
|
||||
LOG_SENSOR(" ", "Status", this->status_sensor_);
|
||||
ESP_LOGCONFIG(TAG, " Current Value: %u", (uint8_t) this->status_sensor_->get_state());
|
||||
}
|
||||
if (this->last_face_id_sensor_) {
|
||||
LOG_SENSOR(" ", "Last Face ID", this->last_face_id_sensor_);
|
||||
ESP_LOGCONFIG(TAG, " Current Value: %u", (int16_t) this->last_face_id_sensor_->get_state());
|
||||
}
|
||||
if (this->last_face_name_text_sensor_) {
|
||||
LOG_TEXT_SENSOR(" ", "Last Face Name", this->last_face_name_text_sensor_);
|
||||
ESP_LOGCONFIG(TAG, " Current Value: %s", this->last_face_name_text_sensor_->get_state().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace esphome::hlk_fm22x
|
||||
224
esphome/components/hlk_fm22x/hlk_fm22x.h
Normal file
224
esphome/components/hlk_fm22x/hlk_fm22x.h
Normal file
@@ -0,0 +1,224 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
#include "esphome/components/binary_sensor/binary_sensor.h"
|
||||
#include "esphome/components/text_sensor/text_sensor.h"
|
||||
#include "esphome/components/uart/uart.h"
|
||||
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace esphome::hlk_fm22x {
|
||||
|
||||
static const uint16_t START_CODE = 0xEFAA;
|
||||
enum HlkFm22xCommand {
|
||||
NONE = 0x00,
|
||||
RESET = 0x10,
|
||||
GET_STATUS = 0x11,
|
||||
VERIFY = 0x12,
|
||||
ENROLL = 0x13,
|
||||
DELETE_FACE = 0x20,
|
||||
DELETE_ALL_FACES = 0x21,
|
||||
GET_ALL_FACE_IDS = 0x24,
|
||||
GET_VERSION = 0x30,
|
||||
GET_SERIAL_NUMBER = 0x93,
|
||||
};
|
||||
|
||||
enum HlkFm22xResponseType {
|
||||
REPLY = 0x00,
|
||||
NOTE = 0x01,
|
||||
IMAGE = 0x02,
|
||||
};
|
||||
|
||||
enum HlkFm22xNoteType {
|
||||
READY = 0x00,
|
||||
FACE_STATE = 0x01,
|
||||
};
|
||||
|
||||
enum HlkFm22xResult {
|
||||
SUCCESS = 0x00,
|
||||
REJECTED = 0x01,
|
||||
ABORTED = 0x02,
|
||||
FAILED4_CAMERA = 0x04,
|
||||
FAILED4_UNKNOWNREASON = 0x05,
|
||||
FAILED4_INVALIDPARAM = 0x06,
|
||||
FAILED4_NOMEMORY = 0x07,
|
||||
FAILED4_UNKNOWNUSER = 0x08,
|
||||
FAILED4_MAXUSER = 0x09,
|
||||
FAILED4_FACEENROLLED = 0x0A,
|
||||
FAILED4_LIVENESSCHECK = 0x0C,
|
||||
FAILED4_TIMEOUT = 0x0D,
|
||||
FAILED4_AUTHORIZATION = 0x0E,
|
||||
FAILED4_READ_FILE = 0x13,
|
||||
FAILED4_WRITE_FILE = 0x14,
|
||||
FAILED4_NO_ENCRYPT = 0x15,
|
||||
FAILED4_NO_RGBIMAGE = 0x17,
|
||||
FAILED4_JPGPHOTO_LARGE = 0x18,
|
||||
FAILED4_JPGPHOTO_SMALL = 0x19,
|
||||
};
|
||||
|
||||
enum HlkFm22xFaceDirection {
|
||||
FACE_DIRECTION_UNDEFINED = 0x00,
|
||||
FACE_DIRECTION_MIDDLE = 0x01,
|
||||
FACE_DIRECTION_RIGHT = 0x02,
|
||||
FACE_DIRECTION_LEFT = 0x04,
|
||||
FACE_DIRECTION_DOWN = 0x08,
|
||||
FACE_DIRECTION_UP = 0x10,
|
||||
};
|
||||
|
||||
class HlkFm22xComponent : public PollingComponent, public uart::UARTDevice {
|
||||
public:
|
||||
void setup() override;
|
||||
void update() override;
|
||||
void dump_config() override;
|
||||
|
||||
void set_face_count_sensor(sensor::Sensor *face_count_sensor) { this->face_count_sensor_ = face_count_sensor; }
|
||||
void set_status_sensor(sensor::Sensor *status_sensor) { this->status_sensor_ = status_sensor; }
|
||||
void set_last_face_id_sensor(sensor::Sensor *last_face_id_sensor) {
|
||||
this->last_face_id_sensor_ = last_face_id_sensor;
|
||||
}
|
||||
void set_last_face_name_text_sensor(text_sensor::TextSensor *last_face_name_text_sensor) {
|
||||
this->last_face_name_text_sensor_ = last_face_name_text_sensor;
|
||||
}
|
||||
void set_enrolling_binary_sensor(binary_sensor::BinarySensor *enrolling_binary_sensor) {
|
||||
this->enrolling_binary_sensor_ = enrolling_binary_sensor;
|
||||
}
|
||||
void set_version_text_sensor(text_sensor::TextSensor *version_text_sensor) {
|
||||
this->version_text_sensor_ = version_text_sensor;
|
||||
}
|
||||
void add_on_face_scan_matched_callback(std::function<void(int16_t, std::string)> callback) {
|
||||
this->face_scan_matched_callback_.add(std::move(callback));
|
||||
}
|
||||
void add_on_face_scan_unmatched_callback(std::function<void()> callback) {
|
||||
this->face_scan_unmatched_callback_.add(std::move(callback));
|
||||
}
|
||||
void add_on_face_scan_invalid_callback(std::function<void(uint8_t)> callback) {
|
||||
this->face_scan_invalid_callback_.add(std::move(callback));
|
||||
}
|
||||
void add_on_face_info_callback(
|
||||
std::function<void(int16_t, int16_t, int16_t, int16_t, int16_t, int16_t, int16_t, int16_t)> callback) {
|
||||
this->face_info_callback_.add(std::move(callback));
|
||||
}
|
||||
void add_on_enrollment_done_callback(std::function<void(int16_t, uint8_t)> callback) {
|
||||
this->enrollment_done_callback_.add(std::move(callback));
|
||||
}
|
||||
void add_on_enrollment_failed_callback(std::function<void(uint8_t)> callback) {
|
||||
this->enrollment_failed_callback_.add(std::move(callback));
|
||||
}
|
||||
|
||||
void enroll_face(const std::string &name, HlkFm22xFaceDirection direction);
|
||||
void scan_face();
|
||||
void delete_face(int16_t face_id);
|
||||
void delete_all_faces();
|
||||
void reset();
|
||||
|
||||
protected:
|
||||
void get_face_count_();
|
||||
void send_command_(HlkFm22xCommand command, const uint8_t *data = nullptr, size_t size = 0);
|
||||
void recv_command_();
|
||||
void handle_note_(const std::vector<uint8_t> &data);
|
||||
void handle_reply_(const std::vector<uint8_t> &data);
|
||||
void set_enrolling_(bool enrolling);
|
||||
|
||||
HlkFm22xCommand active_command_ = HlkFm22xCommand::NONE;
|
||||
uint16_t wait_cycles_ = 0;
|
||||
sensor::Sensor *face_count_sensor_{nullptr};
|
||||
sensor::Sensor *status_sensor_{nullptr};
|
||||
sensor::Sensor *last_face_id_sensor_{nullptr};
|
||||
binary_sensor::BinarySensor *enrolling_binary_sensor_{nullptr};
|
||||
text_sensor::TextSensor *last_face_name_text_sensor_{nullptr};
|
||||
text_sensor::TextSensor *version_text_sensor_{nullptr};
|
||||
CallbackManager<void(uint8_t)> face_scan_invalid_callback_;
|
||||
CallbackManager<void(int16_t, std::string)> face_scan_matched_callback_;
|
||||
CallbackManager<void()> face_scan_unmatched_callback_;
|
||||
CallbackManager<void(int16_t, int16_t, int16_t, int16_t, int16_t, int16_t, int16_t, int16_t)> face_info_callback_;
|
||||
CallbackManager<void(int16_t, uint8_t)> enrollment_done_callback_;
|
||||
CallbackManager<void(uint8_t)> enrollment_failed_callback_;
|
||||
};
|
||||
|
||||
class FaceScanMatchedTrigger : public Trigger<int16_t, std::string> {
|
||||
public:
|
||||
explicit FaceScanMatchedTrigger(HlkFm22xComponent *parent) {
|
||||
parent->add_on_face_scan_matched_callback(
|
||||
[this](int16_t face_id, const std::string &name) { this->trigger(face_id, name); });
|
||||
}
|
||||
};
|
||||
|
||||
class FaceScanUnmatchedTrigger : public Trigger<> {
|
||||
public:
|
||||
explicit FaceScanUnmatchedTrigger(HlkFm22xComponent *parent) {
|
||||
parent->add_on_face_scan_unmatched_callback([this]() { this->trigger(); });
|
||||
}
|
||||
};
|
||||
|
||||
class FaceScanInvalidTrigger : public Trigger<uint8_t> {
|
||||
public:
|
||||
explicit FaceScanInvalidTrigger(HlkFm22xComponent *parent) {
|
||||
parent->add_on_face_scan_invalid_callback([this](uint8_t error) { this->trigger(error); });
|
||||
}
|
||||
};
|
||||
|
||||
class FaceInfoTrigger : public Trigger<int16_t, int16_t, int16_t, int16_t, int16_t, int16_t, int16_t, int16_t> {
|
||||
public:
|
||||
explicit FaceInfoTrigger(HlkFm22xComponent *parent) {
|
||||
parent->add_on_face_info_callback(
|
||||
[this](int16_t status, int16_t left, int16_t top, int16_t right, int16_t bottom, int16_t yaw, int16_t pitch,
|
||||
int16_t roll) { this->trigger(status, left, top, right, bottom, yaw, pitch, roll); });
|
||||
}
|
||||
};
|
||||
|
||||
class EnrollmentDoneTrigger : public Trigger<int16_t, uint8_t> {
|
||||
public:
|
||||
explicit EnrollmentDoneTrigger(HlkFm22xComponent *parent) {
|
||||
parent->add_on_enrollment_done_callback(
|
||||
[this](int16_t face_id, uint8_t direction) { this->trigger(face_id, direction); });
|
||||
}
|
||||
};
|
||||
|
||||
class EnrollmentFailedTrigger : public Trigger<uint8_t> {
|
||||
public:
|
||||
explicit EnrollmentFailedTrigger(HlkFm22xComponent *parent) {
|
||||
parent->add_on_enrollment_failed_callback([this](uint8_t error) { this->trigger(error); });
|
||||
}
|
||||
};
|
||||
|
||||
template<typename... Ts> class EnrollmentAction : public Action<Ts...>, public Parented<HlkFm22xComponent> {
|
||||
public:
|
||||
TEMPLATABLE_VALUE(std::string, name)
|
||||
TEMPLATABLE_VALUE(uint8_t, direction)
|
||||
|
||||
void play(Ts... x) override {
|
||||
auto name = this->name_.value(x...);
|
||||
auto direction = (HlkFm22xFaceDirection) this->direction_.value(x...);
|
||||
this->parent_->enroll_face(name, direction);
|
||||
}
|
||||
};
|
||||
|
||||
template<typename... Ts> class DeleteAction : public Action<Ts...>, public Parented<HlkFm22xComponent> {
|
||||
public:
|
||||
TEMPLATABLE_VALUE(int16_t, face_id)
|
||||
|
||||
void play(Ts... x) override {
|
||||
auto face_id = this->face_id_.value(x...);
|
||||
this->parent_->delete_face(face_id);
|
||||
}
|
||||
};
|
||||
|
||||
template<typename... Ts> class DeleteAllAction : public Action<Ts...>, public Parented<HlkFm22xComponent> {
|
||||
public:
|
||||
void play(Ts... x) override { this->parent_->delete_all_faces(); }
|
||||
};
|
||||
|
||||
template<typename... Ts> class ScanAction : public Action<Ts...>, public Parented<HlkFm22xComponent> {
|
||||
public:
|
||||
void play(Ts... x) override { this->parent_->scan_face(); }
|
||||
};
|
||||
|
||||
template<typename... Ts> class ResetAction : public Action<Ts...>, public Parented<HlkFm22xComponent> {
|
||||
public:
|
||||
void play(Ts... x) override { this->parent_->reset(); }
|
||||
};
|
||||
|
||||
} // namespace esphome::hlk_fm22x
|
||||
47
esphome/components/hlk_fm22x/sensor.py
Normal file
47
esphome/components/hlk_fm22x/sensor.py
Normal file
@@ -0,0 +1,47 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import sensor
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_STATUS, ENTITY_CATEGORY_DIAGNOSTIC, ICON_ACCOUNT
|
||||
|
||||
from . import CONF_HLK_FM22X_ID, HlkFm22xComponent
|
||||
|
||||
DEPENDENCIES = ["hlk_fm22x"]
|
||||
|
||||
CONF_FACE_COUNT = "face_count"
|
||||
CONF_LAST_FACE_ID = "last_face_id"
|
||||
ICON_FACE = "mdi:face-recognition"
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(CONF_HLK_FM22X_ID): cv.use_id(HlkFm22xComponent),
|
||||
cv.Optional(CONF_FACE_COUNT): sensor.sensor_schema(
|
||||
icon=ICON_FACE,
|
||||
accuracy_decimals=0,
|
||||
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
),
|
||||
cv.Optional(CONF_STATUS): sensor.sensor_schema(
|
||||
accuracy_decimals=0,
|
||||
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
),
|
||||
cv.Optional(CONF_LAST_FACE_ID): sensor.sensor_schema(
|
||||
icon=ICON_ACCOUNT,
|
||||
accuracy_decimals=0,
|
||||
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
hub = await cg.get_variable(config[CONF_HLK_FM22X_ID])
|
||||
|
||||
for key in [
|
||||
CONF_FACE_COUNT,
|
||||
CONF_STATUS,
|
||||
CONF_LAST_FACE_ID,
|
||||
]:
|
||||
if key not in config:
|
||||
continue
|
||||
conf = config[key]
|
||||
sens = await sensor.new_sensor(conf)
|
||||
cg.add(getattr(hub, f"set_{key}_sensor")(sens))
|
||||
42
esphome/components/hlk_fm22x/text_sensor.py
Normal file
42
esphome/components/hlk_fm22x/text_sensor.py
Normal file
@@ -0,0 +1,42 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import text_sensor
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_VERSION,
|
||||
ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
ICON_ACCOUNT,
|
||||
ICON_RESTART,
|
||||
)
|
||||
|
||||
from . import CONF_HLK_FM22X_ID, HlkFm22xComponent
|
||||
|
||||
DEPENDENCIES = ["hlk_fm22x"]
|
||||
|
||||
CONF_LAST_FACE_NAME = "last_face_name"
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(CONF_HLK_FM22X_ID): cv.use_id(HlkFm22xComponent),
|
||||
cv.Optional(CONF_VERSION): text_sensor.text_sensor_schema(
|
||||
icon=ICON_RESTART,
|
||||
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
),
|
||||
cv.Optional(CONF_LAST_FACE_NAME): text_sensor.text_sensor_schema(
|
||||
icon=ICON_ACCOUNT,
|
||||
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
hub = await cg.get_variable(config[CONF_HLK_FM22X_ID])
|
||||
for key in [
|
||||
CONF_VERSION,
|
||||
CONF_LAST_FACE_NAME,
|
||||
]:
|
||||
if key not in config:
|
||||
continue
|
||||
conf = config[key]
|
||||
sens = await text_sensor.new_text_sensor(conf)
|
||||
cg.add(getattr(hub, f"set_{key}_text_sensor")(sens))
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <climits>
|
||||
#include "abstract_aqi_calculator.h"
|
||||
// https://www.airnow.gov/sites/default/files/2020-05/aqi-technical-assistance-document-sept2018.pdf
|
||||
// https://document.airnow.gov/technical-assistance-document-for-the-reporting-of-daily-air-quailty.pdf
|
||||
|
||||
namespace esphome {
|
||||
namespace hm3301 {
|
||||
@@ -16,16 +16,15 @@ class AQICalculator : public AbstractAQICalculator {
|
||||
}
|
||||
|
||||
protected:
|
||||
static const int AMOUNT_OF_LEVELS = 7;
|
||||
static const int AMOUNT_OF_LEVELS = 6;
|
||||
|
||||
int index_grid_[AMOUNT_OF_LEVELS][2] = {{0, 50}, {51, 100}, {101, 150}, {151, 200},
|
||||
{201, 300}, {301, 400}, {401, 500}};
|
||||
int index_grid_[AMOUNT_OF_LEVELS][2] = {{0, 50}, {51, 100}, {101, 150}, {151, 200}, {201, 300}, {301, 500}};
|
||||
|
||||
int pm2_5_calculation_grid_[AMOUNT_OF_LEVELS][2] = {{0, 12}, {13, 35}, {36, 55}, {56, 150},
|
||||
{151, 250}, {251, 350}, {351, 500}};
|
||||
int pm2_5_calculation_grid_[AMOUNT_OF_LEVELS][2] = {{0, 9}, {10, 35}, {36, 55},
|
||||
{56, 125}, {126, 225}, {226, INT_MAX}};
|
||||
|
||||
int pm10_0_calculation_grid_[AMOUNT_OF_LEVELS][2] = {{0, 54}, {55, 154}, {155, 254}, {255, 354},
|
||||
{355, 424}, {425, 504}, {505, 604}};
|
||||
int pm10_0_calculation_grid_[AMOUNT_OF_LEVELS][2] = {{0, 54}, {55, 154}, {155, 254},
|
||||
{255, 354}, {355, 424}, {425, INT_MAX}};
|
||||
|
||||
int calculate_index_(uint16_t value, int array[AMOUNT_OF_LEVELS][2]) {
|
||||
int grid_index = get_grid_index_(value, array);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
#include "light_output.h"
|
||||
#include "light_state.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "light_output.h"
|
||||
#include "transformers.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -137,7 +138,12 @@ void LightState::loop() {
|
||||
|
||||
float LightState::get_setup_priority() const { return setup_priority::HARDWARE - 1.0f; }
|
||||
|
||||
void LightState::publish_state() { this->remote_values_callback_.call(); }
|
||||
void LightState::publish_state() {
|
||||
this->remote_values_callback_.call();
|
||||
#if defined(USE_LIGHT) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_light_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
LightOutput *LightState::get_output() const { return this->output_; }
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "lock.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -53,6 +55,9 @@ void Lock::publish_state(LockState state) {
|
||||
this->rtc_.save(&this->state);
|
||||
ESP_LOGD(TAG, "'%s': Sending state %s", this->name_.c_str(), lock_state_to_string(state));
|
||||
this->state_callback_.call();
|
||||
#if defined(USE_LOCK) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_lock_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
void Lock::add_on_state_callback(std::function<void()> &&callback) { this->state_callback_.add(std::move(callback)); }
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import importlib
|
||||
import logging
|
||||
import pkgutil
|
||||
|
||||
from esphome.automation import build_automation, register_action, validate_automation
|
||||
from esphome.automation import build_automation, validate_automation
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.const import CONF_COLOR_DEPTH, CONF_DRAW_ROUNDING
|
||||
from esphome.components.display import Display
|
||||
@@ -25,8 +27,8 @@ from esphome.cpp_generator import MockObj
|
||||
from esphome.final_validate import full_config
|
||||
from esphome.helpers import write_file_if_changed
|
||||
|
||||
from . import defines as df, helpers, lv_validation as lvalid
|
||||
from .automation import disp_update, focused_widgets, refreshed_widgets, update_to_code
|
||||
from . import defines as df, helpers, lv_validation as lvalid, widgets
|
||||
from .automation import disp_update, focused_widgets, refreshed_widgets
|
||||
from .defines import add_define
|
||||
from .encoders import (
|
||||
ENCODERS_CONFIG,
|
||||
@@ -45,7 +47,6 @@ from .schemas import (
|
||||
WIDGET_TYPES,
|
||||
any_widget_schema,
|
||||
container_schema,
|
||||
create_modify_schema,
|
||||
obj_schema,
|
||||
)
|
||||
from .styles import add_top_layer, styles_to_code, theme_to_code
|
||||
@@ -54,7 +55,6 @@ from .trigger import add_on_boot_triggers, generate_triggers
|
||||
from .types import (
|
||||
FontEngine,
|
||||
IdleTrigger,
|
||||
ObjUpdateAction,
|
||||
PlainTrigger,
|
||||
lv_font_t,
|
||||
lv_group_t,
|
||||
@@ -69,33 +69,23 @@ from .widgets import (
|
||||
set_obj_properties,
|
||||
styles_used,
|
||||
)
|
||||
from .widgets.animimg import animimg_spec
|
||||
from .widgets.arc import arc_spec
|
||||
from .widgets.button import button_spec
|
||||
from .widgets.buttonmatrix import buttonmatrix_spec
|
||||
from .widgets.canvas import canvas_spec
|
||||
from .widgets.checkbox import checkbox_spec
|
||||
from .widgets.container import container_spec
|
||||
from .widgets.dropdown import dropdown_spec
|
||||
from .widgets.img import img_spec
|
||||
from .widgets.keyboard import keyboard_spec
|
||||
from .widgets.label import label_spec
|
||||
from .widgets.led import led_spec
|
||||
from .widgets.line import line_spec
|
||||
from .widgets.lv_bar import bar_spec
|
||||
from .widgets.meter import meter_spec
|
||||
|
||||
# Import only what we actually use directly in this file
|
||||
from .widgets.msgbox import MSGBOX_SCHEMA, msgboxes_to_code
|
||||
from .widgets.obj import obj_spec
|
||||
from .widgets.page import add_pages, generate_page_triggers, page_spec
|
||||
from .widgets.qrcode import qr_code_spec
|
||||
from .widgets.roller import roller_spec
|
||||
from .widgets.slider import slider_spec
|
||||
from .widgets.spinbox import spinbox_spec
|
||||
from .widgets.spinner import spinner_spec
|
||||
from .widgets.switch import switch_spec
|
||||
from .widgets.tabview import tabview_spec
|
||||
from .widgets.textarea import textarea_spec
|
||||
from .widgets.tileview import tileview_spec
|
||||
from .widgets.obj import obj_spec # Used in LVGL_SCHEMA
|
||||
from .widgets.page import ( # page_spec used in LVGL_SCHEMA
|
||||
add_pages,
|
||||
generate_page_triggers,
|
||||
page_spec,
|
||||
)
|
||||
|
||||
# Widget registration happens via WidgetType.__init__ in individual widget files
|
||||
# The imports below trigger creation of the widget types
|
||||
# Action registration (lvgl.{widget}.update) happens automatically
|
||||
# in the WidgetType.__init__ method
|
||||
|
||||
for module_info in pkgutil.iter_modules(widgets.__path__):
|
||||
importlib.import_module(f".widgets.{module_info.name}", package=__package__)
|
||||
|
||||
DOMAIN = "lvgl"
|
||||
DEPENDENCIES = ["display"]
|
||||
@@ -103,41 +93,6 @@ AUTO_LOAD = ["key_provider"]
|
||||
CODEOWNERS = ["@clydebarrow"]
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
for w_type in (
|
||||
label_spec,
|
||||
obj_spec,
|
||||
button_spec,
|
||||
bar_spec,
|
||||
slider_spec,
|
||||
arc_spec,
|
||||
line_spec,
|
||||
spinner_spec,
|
||||
led_spec,
|
||||
animimg_spec,
|
||||
checkbox_spec,
|
||||
img_spec,
|
||||
switch_spec,
|
||||
tabview_spec,
|
||||
buttonmatrix_spec,
|
||||
meter_spec,
|
||||
dropdown_spec,
|
||||
roller_spec,
|
||||
textarea_spec,
|
||||
spinbox_spec,
|
||||
keyboard_spec,
|
||||
tileview_spec,
|
||||
qr_code_spec,
|
||||
canvas_spec,
|
||||
container_spec,
|
||||
):
|
||||
WIDGET_TYPES[w_type.name] = w_type
|
||||
|
||||
for w_type in WIDGET_TYPES.values():
|
||||
register_action(
|
||||
f"lvgl.{w_type.name}.update",
|
||||
ObjUpdateAction,
|
||||
create_modify_schema(w_type),
|
||||
)(update_to_code)
|
||||
|
||||
SIMPLE_TRIGGERS = (
|
||||
df.CONF_ON_PAUSE,
|
||||
@@ -402,6 +357,15 @@ def add_hello_world(config):
|
||||
return config
|
||||
|
||||
|
||||
def _theme_schema(value):
|
||||
return cv.Schema(
|
||||
{
|
||||
cv.Optional(name): obj_schema(w).extend(FULL_STYLE_SCHEMA)
|
||||
for name, w in WIDGET_TYPES.items()
|
||||
}
|
||||
)(value)
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = final_validation
|
||||
|
||||
LVGL_SCHEMA = cv.All(
|
||||
@@ -454,12 +418,7 @@ LVGL_SCHEMA = cv.All(
|
||||
cv.Optional(
|
||||
df.CONF_TRANSPARENCY_KEY, default=0x000400
|
||||
): lvalid.lv_color,
|
||||
cv.Optional(df.CONF_THEME): cv.Schema(
|
||||
{
|
||||
cv.Optional(name): obj_schema(w).extend(FULL_STYLE_SCHEMA)
|
||||
for name, w in WIDGET_TYPES.items()
|
||||
}
|
||||
),
|
||||
cv.Optional(df.CONF_THEME): _theme_schema,
|
||||
cv.Optional(df.CONF_GRADIENTS): GRADIENT_SCHEMA,
|
||||
cv.Optional(df.CONF_TOUCHSCREENS, default=None): touchscreen_schema,
|
||||
cv.Optional(df.CONF_ENCODERS, default=None): ENCODERS_CONFIG,
|
||||
|
||||
@@ -411,6 +411,10 @@ def any_widget_schema(extras=None):
|
||||
Dynamically generate schemas for all possible LVGL widgets. This is what implements the ability to have a list of any kind of
|
||||
widget under the widgets: key.
|
||||
|
||||
This uses lazy evaluation - the schema is built when called during validation,
|
||||
not at import time. This allows external components to register widgets
|
||||
before schema validation begins.
|
||||
|
||||
:param extras: Additional schema to be applied to each generated one
|
||||
:return: A validator for the Widgets key
|
||||
"""
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import sys
|
||||
|
||||
from esphome import automation, codegen as cg
|
||||
from esphome.automation import register_action
|
||||
from esphome.config_validation import Schema
|
||||
from esphome.const import CONF_MAX_VALUE, CONF_MIN_VALUE, CONF_TEXT, CONF_VALUE
|
||||
from esphome.core import EsphomeError
|
||||
from esphome.cpp_generator import MockObj, MockObjClass
|
||||
from esphome.cpp_types import esphome_ns
|
||||
|
||||
@@ -124,13 +126,16 @@ class WidgetType:
|
||||
schema=None,
|
||||
modify_schema=None,
|
||||
lv_name=None,
|
||||
is_mock: bool = False,
|
||||
):
|
||||
"""
|
||||
:param name: The widget name, e.g. "bar"
|
||||
:param w_type: The C type of the widget
|
||||
:param parts: What parts this widget supports
|
||||
:param schema: The config schema for defining a widget
|
||||
:param modify_schema: A schema to update the widget
|
||||
:param modify_schema: A schema to update the widget, defaults to the same as the schema
|
||||
:param lv_name: The name of the LVGL widget in the LVGL library, if different from the name
|
||||
:param is_mock: Whether this widget is a mock widget, i.e. not a real LVGL widget
|
||||
"""
|
||||
self.name = name
|
||||
self.lv_name = lv_name or name
|
||||
@@ -146,6 +151,22 @@ class WidgetType:
|
||||
self.modify_schema = modify_schema
|
||||
self.mock_obj = MockObj(f"lv_{self.lv_name}", "_")
|
||||
|
||||
# Local import to avoid circular import
|
||||
from .automation import update_to_code
|
||||
from .schemas import WIDGET_TYPES, create_modify_schema
|
||||
|
||||
if not is_mock:
|
||||
if self.name in WIDGET_TYPES:
|
||||
raise EsphomeError(f"Duplicate definition of widget type '{self.name}'")
|
||||
WIDGET_TYPES[self.name] = self
|
||||
|
||||
# Register the update action automatically
|
||||
register_action(
|
||||
f"lvgl.{self.name}.update",
|
||||
ObjUpdateAction,
|
||||
create_modify_schema(self),
|
||||
)(update_to_code)
|
||||
|
||||
@property
|
||||
def animated(self):
|
||||
return False
|
||||
|
||||
@@ -213,17 +213,14 @@ class LvScrActType(WidgetType):
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__("lv_scr_act()", lv_obj_t, ())
|
||||
super().__init__("lv_scr_act()", lv_obj_t, (), is_mock=True)
|
||||
|
||||
async def to_code(self, w, config: dict):
|
||||
return []
|
||||
|
||||
|
||||
lv_scr_act_spec = LvScrActType()
|
||||
|
||||
|
||||
def get_scr_act(lv_comp: MockObj) -> Widget:
|
||||
return Widget.create(None, lv_comp.get_scr_act(), lv_scr_act_spec, {})
|
||||
return Widget.create(None, lv_comp.get_scr_act(), LvScrActType(), {})
|
||||
|
||||
|
||||
def get_widget_generator(wid):
|
||||
|
||||
@@ -2,7 +2,7 @@ from esphome import automation
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_RANGE_FROM, CONF_RANGE_TO, CONF_STEP, CONF_VALUE
|
||||
|
||||
from ..automation import action_to_code, update_to_code
|
||||
from ..automation import action_to_code
|
||||
from ..defines import (
|
||||
CONF_CURSOR,
|
||||
CONF_DECIMAL_PLACES,
|
||||
@@ -171,17 +171,3 @@ async def spinbox_decrement(config, action_id, template_arg, args):
|
||||
lv.spinbox_decrement(w.obj)
|
||||
|
||||
return await action_to_code(widgets, do_increment, action_id, template_arg, args)
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
"lvgl.spinbox.update",
|
||||
ObjUpdateAction,
|
||||
cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_ID): cv.use_id(lv_spinbox_t),
|
||||
cv.Required(CONF_VALUE): lv_float,
|
||||
}
|
||||
),
|
||||
)
|
||||
async def spinbox_update_to_code(config, action_id, template_arg, args):
|
||||
return await update_to_code(config, action_id, template_arg, args)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "media_player.h"
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -148,7 +149,12 @@ void MediaPlayer::add_on_state_callback(std::function<void()> &&callback) {
|
||||
this->state_callback_.add(std::move(callback));
|
||||
}
|
||||
|
||||
void MediaPlayer::publish_state() { this->state_callback_.call(); }
|
||||
void MediaPlayer::publish_state() {
|
||||
this->state_callback_.call();
|
||||
#if defined(USE_MEDIA_PLAYER) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_media_player_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace media_player
|
||||
} // namespace esphome
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "number.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -32,6 +34,9 @@ void Number::publish_state(float state) {
|
||||
this->state = state;
|
||||
ESP_LOGD(TAG, "'%s': Sending state %f", this->get_name().c_str(), state);
|
||||
this->state_callback_.call(state);
|
||||
#if defined(USE_NUMBER) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_number_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
void Number::add_on_state_callback(std::function<void(float)> &&callback) {
|
||||
|
||||
@@ -39,7 +39,7 @@ from esphome.const import (
|
||||
CONF_WAND_ID,
|
||||
CONF_ZERO,
|
||||
)
|
||||
from esphome.core import coroutine
|
||||
from esphome.core import ID, coroutine
|
||||
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor
|
||||
from esphome.util import Registry, SimpleRegistry
|
||||
|
||||
@@ -2104,7 +2104,9 @@ async def abbwelcome_action(var, config, args):
|
||||
)
|
||||
cg.add(var.set_data_template(template_))
|
||||
else:
|
||||
cg.add(var.set_data_static(data_))
|
||||
arr_id = ID(f"{var.base}_data", is_declaration=True, type=cg.uint8)
|
||||
arr = cg.static_const_array(arr_id, cg.ArrayInitializer(*data_))
|
||||
cg.add(var.set_data_static(arr, len(data_)))
|
||||
|
||||
|
||||
# Mirage
|
||||
|
||||
@@ -214,10 +214,13 @@ template<typename... Ts> class ABBWelcomeAction : public RemoteTransmitterAction
|
||||
TEMPLATABLE_VALUE(uint8_t, message_type)
|
||||
TEMPLATABLE_VALUE(uint8_t, message_id)
|
||||
TEMPLATABLE_VALUE(bool, auto_message_id)
|
||||
void set_data_static(std::vector<uint8_t> data) { data_static_ = std::move(data); }
|
||||
void set_data_template(std::function<std::vector<uint8_t>(Ts...)> func) {
|
||||
this->data_func_ = func;
|
||||
has_data_func_ = true;
|
||||
void set_data_template(std::vector<uint8_t> (*func)(Ts...)) {
|
||||
this->data_.func = func;
|
||||
this->len_ = -1; // Sentinel value indicates template mode
|
||||
}
|
||||
void set_data_static(const uint8_t *data, size_t len) {
|
||||
this->data_.data = data;
|
||||
this->len_ = len; // Length >= 0 indicates static mode
|
||||
}
|
||||
void encode(RemoteTransmitData *dst, Ts... x) override {
|
||||
ABBWelcomeData data;
|
||||
@@ -228,19 +231,25 @@ template<typename... Ts> class ABBWelcomeAction : public RemoteTransmitterAction
|
||||
data.set_message_type(this->message_type_.value(x...));
|
||||
data.set_message_id(this->message_id_.value(x...));
|
||||
data.auto_message_id = this->auto_message_id_.value(x...);
|
||||
if (has_data_func_) {
|
||||
data.set_data(this->data_func_(x...));
|
||||
std::vector<uint8_t> data_vec;
|
||||
if (this->len_ >= 0) {
|
||||
// Static mode: copy from flash to vector
|
||||
data_vec.assign(this->data_.data, this->data_.data + this->len_);
|
||||
} else {
|
||||
data.set_data(this->data_static_);
|
||||
// Template mode: call function
|
||||
data_vec = this->data_.func(x...);
|
||||
}
|
||||
data.set_data(data_vec);
|
||||
data.finalize();
|
||||
ABBWelcomeProtocol().encode(dst, data);
|
||||
}
|
||||
|
||||
protected:
|
||||
std::function<std::vector<uint8_t>(Ts...)> data_func_{};
|
||||
std::vector<uint8_t> data_static_{};
|
||||
bool has_data_func_{false};
|
||||
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
|
||||
union Data {
|
||||
std::vector<uint8_t> (*func)(Ts...); // Function pointer (stateless lambdas)
|
||||
const uint8_t *data; // Pointer to static data in flash
|
||||
} data_;
|
||||
};
|
||||
|
||||
} // namespace remote_base
|
||||
|
||||
@@ -71,6 +71,7 @@ static const uint16_t FALLBACK_FREQUENCY = 64767U; // To use with frequency = 0
|
||||
static const uint32_t MICROSECONDS_IN_SECONDS = 1000000UL;
|
||||
static const uint16_t PRONTO_DEFAULT_GAP = 45000;
|
||||
static const uint16_t MARK_EXCESS_MICROS = 20;
|
||||
static constexpr size_t PRONTO_LOG_CHUNK_SIZE = 230;
|
||||
|
||||
static uint16_t to_frequency_k_hz(uint16_t code) {
|
||||
if (code == 0)
|
||||
@@ -225,18 +226,18 @@ optional<ProntoData> ProntoProtocol::decode(RemoteReceiveData src) {
|
||||
}
|
||||
|
||||
void ProntoProtocol::dump(const ProntoData &data) {
|
||||
std::string rest;
|
||||
|
||||
rest = data.data;
|
||||
ESP_LOGI(TAG, "Received Pronto: data=");
|
||||
while (true) {
|
||||
ESP_LOGI(TAG, "%s", rest.substr(0, 230).c_str());
|
||||
if (rest.size() > 230) {
|
||||
rest = rest.substr(230);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const char *ptr = data.data.c_str();
|
||||
size_t remaining = data.data.size();
|
||||
|
||||
// Log in chunks, always logging at least once (even for empty string)
|
||||
do {
|
||||
size_t chunk_size = remaining < PRONTO_LOG_CHUNK_SIZE ? remaining : PRONTO_LOG_CHUNK_SIZE;
|
||||
ESP_LOGI(TAG, "%.*s", (int) chunk_size, ptr);
|
||||
ptr += chunk_size;
|
||||
remaining -= chunk_size;
|
||||
} while (remaining > 0);
|
||||
}
|
||||
|
||||
} // namespace remote_base
|
||||
|
||||
@@ -42,17 +42,20 @@ class RawTrigger : public Trigger<RawTimings>, public Component, public RemoteRe
|
||||
|
||||
template<typename... Ts> class RawAction : public RemoteTransmitterActionBase<Ts...> {
|
||||
public:
|
||||
void set_code_template(std::function<RawTimings(Ts...)> func) { this->code_func_ = func; }
|
||||
void set_code_template(RawTimings (*func)(Ts...)) {
|
||||
this->code_.func = func;
|
||||
this->len_ = -1; // Sentinel value indicates template mode
|
||||
}
|
||||
void set_code_static(const int32_t *code, size_t len) {
|
||||
this->code_static_ = code;
|
||||
this->code_static_len_ = len;
|
||||
this->code_.data = code;
|
||||
this->len_ = len; // Length >= 0 indicates static mode
|
||||
}
|
||||
TEMPLATABLE_VALUE(uint32_t, carrier_frequency);
|
||||
|
||||
void encode(RemoteTransmitData *dst, Ts... x) override {
|
||||
if (this->code_static_ != nullptr) {
|
||||
for (size_t i = 0; i < this->code_static_len_; i++) {
|
||||
auto val = this->code_static_[i];
|
||||
if (this->len_ >= 0) {
|
||||
for (size_t i = 0; i < static_cast<size_t>(this->len_); i++) {
|
||||
auto val = this->code_.data[i];
|
||||
if (val < 0) {
|
||||
dst->space(static_cast<uint32_t>(-val));
|
||||
} else {
|
||||
@@ -60,15 +63,17 @@ template<typename... Ts> class RawAction : public RemoteTransmitterActionBase<Ts
|
||||
}
|
||||
}
|
||||
} else {
|
||||
dst->set_data(this->code_func_(x...));
|
||||
dst->set_data(this->code_.func(x...));
|
||||
}
|
||||
dst->set_carrier_frequency(this->carrier_frequency_.value(x...));
|
||||
}
|
||||
|
||||
protected:
|
||||
std::function<RawTimings(Ts...)> code_func_{nullptr};
|
||||
const int32_t *code_static_{nullptr};
|
||||
int32_t code_static_len_{0};
|
||||
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
|
||||
union Code {
|
||||
RawTimings (*func)(Ts...);
|
||||
const int32_t *data;
|
||||
} code_;
|
||||
};
|
||||
|
||||
class RawDumper : public RemoteReceiverDumperBase {
|
||||
|
||||
0
esphome/components/rx8130/__init__.py
Normal file
0
esphome/components/rx8130/__init__.py
Normal file
127
esphome/components/rx8130/rx8130.cpp
Normal file
127
esphome/components/rx8130/rx8130.cpp
Normal file
@@ -0,0 +1,127 @@
|
||||
#include "rx8130.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
// https://download.epsondevice.com/td/pdf/app/RX8130CE_en.pdf
|
||||
|
||||
namespace esphome {
|
||||
namespace rx8130 {
|
||||
|
||||
static const uint8_t RX8130_REG_SEC = 0x10;
|
||||
static const uint8_t RX8130_REG_MIN = 0x11;
|
||||
static const uint8_t RX8130_REG_HOUR = 0x12;
|
||||
static const uint8_t RX8130_REG_WDAY = 0x13;
|
||||
static const uint8_t RX8130_REG_MDAY = 0x14;
|
||||
static const uint8_t RX8130_REG_MONTH = 0x15;
|
||||
static const uint8_t RX8130_REG_YEAR = 0x16;
|
||||
static const uint8_t RX8130_REG_EXTEN = 0x1C;
|
||||
static const uint8_t RX8130_REG_FLAG = 0x1D;
|
||||
static const uint8_t RX8130_REG_CTRL0 = 0x1E;
|
||||
static const uint8_t RX8130_REG_CTRL1 = 0x1F;
|
||||
static const uint8_t RX8130_REG_DIG_OFFSET = 0x30;
|
||||
static const uint8_t RX8130_BIT_CTRL_STOP = 0x40;
|
||||
static const uint8_t RX8130_BAT_FLAGS = 0x30;
|
||||
static const uint8_t RX8130_CLEAR_FLAGS = 0x00;
|
||||
|
||||
static const char *const TAG = "rx8130";
|
||||
|
||||
constexpr uint8_t bcd2dec(uint8_t val) { return (val >> 4) * 10 + (val & 0x0f); }
|
||||
constexpr uint8_t dec2bcd(uint8_t val) { return ((val / 10) << 4) + (val % 10); }
|
||||
|
||||
void RX8130Component::setup() {
|
||||
// Set digital offset to disabled with no offset
|
||||
if (this->write_register(RX8130_REG_DIG_OFFSET, &RX8130_CLEAR_FLAGS, 1) != i2c::ERROR_OK) {
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
// Disable wakeup timers
|
||||
if (this->write_register(RX8130_REG_EXTEN, &RX8130_CLEAR_FLAGS, 1) != i2c::ERROR_OK) {
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
// Clear VLF flag in case there has been data loss
|
||||
if (this->write_register(RX8130_REG_FLAG, &RX8130_CLEAR_FLAGS, 1) != i2c::ERROR_OK) {
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
// Clear test flag and disable interrupts
|
||||
if (this->write_register(RX8130_REG_CTRL0, &RX8130_CLEAR_FLAGS, 1) != i2c::ERROR_OK) {
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
// Enable battery charging and switching
|
||||
if (this->write_register(RX8130_REG_CTRL1, &RX8130_BAT_FLAGS, 1) != i2c::ERROR_OK) {
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
// Clear STOP bit
|
||||
this->stop_(false);
|
||||
}
|
||||
|
||||
void RX8130Component::update() { this->read_time(); }
|
||||
|
||||
void RX8130Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "RX8130:");
|
||||
LOG_I2C_DEVICE(this);
|
||||
}
|
||||
|
||||
void RX8130Component::read_time() {
|
||||
uint8_t date[7];
|
||||
if (this->read_register(RX8130_REG_SEC, date, 7) != i2c::ERROR_OK) {
|
||||
this->status_set_warning(ESP_LOG_MSG_COMM_FAIL);
|
||||
return;
|
||||
}
|
||||
ESPTime rtc_time{
|
||||
.second = bcd2dec(date[0] & 0x7f),
|
||||
.minute = bcd2dec(date[1] & 0x7f),
|
||||
.hour = bcd2dec(date[2] & 0x3f),
|
||||
.day_of_week = bcd2dec(date[3] & 0x7f),
|
||||
.day_of_month = bcd2dec(date[4] & 0x3f),
|
||||
.day_of_year = 1, // ignored by recalc_timestamp_utc(false)
|
||||
.month = bcd2dec(date[5] & 0x1f),
|
||||
.year = static_cast<uint16_t>(bcd2dec(date[6]) + 2000),
|
||||
.is_dst = false, // not used
|
||||
.timestamp = 0 // overwritten by recalc_timestamp_utc(false)
|
||||
};
|
||||
rtc_time.recalc_timestamp_utc(false);
|
||||
if (!rtc_time.is_valid()) {
|
||||
ESP_LOGE(TAG, "Invalid RTC time, not syncing to system clock.");
|
||||
return;
|
||||
}
|
||||
ESP_LOGD(TAG, "Read UTC time: %04d-%02d-%02d %02d:%02d:%02d", rtc_time.year, rtc_time.month, rtc_time.day_of_month,
|
||||
rtc_time.hour, rtc_time.minute, rtc_time.second);
|
||||
time::RealTimeClock::synchronize_epoch_(rtc_time.timestamp);
|
||||
}
|
||||
|
||||
void RX8130Component::write_time() {
|
||||
auto now = time::RealTimeClock::utcnow();
|
||||
if (!now.is_valid()) {
|
||||
ESP_LOGE(TAG, "Invalid system time, not syncing to RTC.");
|
||||
return;
|
||||
}
|
||||
uint8_t buff[7];
|
||||
buff[0] = dec2bcd(now.second);
|
||||
buff[1] = dec2bcd(now.minute);
|
||||
buff[2] = dec2bcd(now.hour);
|
||||
buff[3] = dec2bcd(now.day_of_week);
|
||||
buff[4] = dec2bcd(now.day_of_month);
|
||||
buff[5] = dec2bcd(now.month);
|
||||
buff[6] = dec2bcd(now.year % 100);
|
||||
this->stop_(true);
|
||||
if (this->write_register(RX8130_REG_SEC, buff, 7) != i2c::ERROR_OK) {
|
||||
this->status_set_warning(ESP_LOG_MSG_COMM_FAIL);
|
||||
} else {
|
||||
ESP_LOGD(TAG, "Wrote UTC time: %04d-%02d-%02d %02d:%02d:%02d", now.year, now.month, now.day_of_month, now.hour,
|
||||
now.minute, now.second);
|
||||
}
|
||||
this->stop_(false);
|
||||
}
|
||||
|
||||
void RX8130Component::stop_(bool stop) {
|
||||
const uint8_t data = stop ? RX8130_BIT_CTRL_STOP : RX8130_CLEAR_FLAGS;
|
||||
if (this->write_register(RX8130_REG_CTRL0, &data, 1) != i2c::ERROR_OK) {
|
||||
this->status_set_warning(ESP_LOG_MSG_COMM_FAIL);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace rx8130
|
||||
} // namespace esphome
|
||||
35
esphome/components/rx8130/rx8130.h
Normal file
35
esphome/components/rx8130/rx8130.h
Normal file
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/time/real_time_clock.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace rx8130 {
|
||||
|
||||
class RX8130Component : public time::RealTimeClock, public i2c::I2CDevice {
|
||||
public:
|
||||
void setup() override;
|
||||
void update() override;
|
||||
void dump_config() override;
|
||||
void read_time();
|
||||
void write_time();
|
||||
/// Ensure RTC is initialized at the correct time in the setup sequence
|
||||
float get_setup_priority() const override { return setup_priority::DATA; }
|
||||
|
||||
protected:
|
||||
void stop_(bool stop);
|
||||
};
|
||||
|
||||
template<typename... Ts> class WriteAction : public Action<Ts...>, public Parented<RX8130Component> {
|
||||
public:
|
||||
void play(const Ts... x) override { this->parent_->write_time(); }
|
||||
};
|
||||
|
||||
template<typename... Ts> class ReadAction : public Action<Ts...>, public Parented<RX8130Component> {
|
||||
public:
|
||||
void play(const Ts... x) override { this->parent_->read_time(); }
|
||||
};
|
||||
|
||||
} // namespace rx8130
|
||||
} // namespace esphome
|
||||
56
esphome/components/rx8130/time.py
Normal file
56
esphome/components/rx8130/time.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c, time
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID
|
||||
|
||||
CODEOWNERS = ["@beormund"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
rx8130_ns = cg.esphome_ns.namespace("rx8130")
|
||||
RX8130Component = rx8130_ns.class_("RX8130Component", time.RealTimeClock, i2c.I2CDevice)
|
||||
WriteAction = rx8130_ns.class_("WriteAction", automation.Action)
|
||||
ReadAction = rx8130_ns.class_("ReadAction", automation.Action)
|
||||
|
||||
|
||||
CONFIG_SCHEMA = time.TIME_SCHEMA.extend(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(RX8130Component),
|
||||
}
|
||||
).extend(i2c.i2c_device_schema(0x32))
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
"rx8130.write_time",
|
||||
WriteAction,
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.use_id(RX8130Component),
|
||||
}
|
||||
),
|
||||
)
|
||||
async def rx8130_write_time_to_code(config, action_id, template_arg, args):
|
||||
var = cg.new_Pvariable(action_id, template_arg)
|
||||
await cg.register_parented(var, config[CONF_ID])
|
||||
return var
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
"rx8130.read_time",
|
||||
ReadAction,
|
||||
automation.maybe_simple_id(
|
||||
{
|
||||
cv.GenerateID(): cv.use_id(RX8130Component),
|
||||
}
|
||||
),
|
||||
)
|
||||
async def rx8130_read_time_to_code(config, action_id, template_arg, args):
|
||||
var = cg.new_Pvariable(action_id, template_arg)
|
||||
await cg.register_parented(var, config[CONF_ID])
|
||||
return var
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
await i2c.register_i2c_device(var, config)
|
||||
await time.register_time(var, config)
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "select.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include <cstring>
|
||||
|
||||
@@ -33,6 +35,9 @@ void Select::publish_state(size_t index) {
|
||||
ESP_LOGD(TAG, "'%s': Sending state %s (index %zu)", this->get_name().c_str(), option, index);
|
||||
// Callback signature requires std::string, create temporary for compatibility
|
||||
this->state_callback_.call(std::string(option), index);
|
||||
#if defined(USE_SELECT) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_select_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
const char *Select::current_option() const { return this->has_state() ? this->option_at(this->active_index_) : ""; }
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "sensor.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -131,6 +133,9 @@ void Sensor::internal_send_state_to_frontend(float state) {
|
||||
ESP_LOGD(TAG, "'%s': Sending state %.5f %s with %d decimals of accuracy", this->get_name().c_str(), state,
|
||||
this->get_unit_of_measurement_ref().c_str(), this->get_accuracy_decimals());
|
||||
this->callback_.call(state);
|
||||
#if defined(USE_SENSOR) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_sensor_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace sensor
|
||||
|
||||
@@ -3,7 +3,7 @@ import esphome.codegen as cg
|
||||
from esphome.components import audio, audio_dac
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DATA, CONF_ID, CONF_VOLUME
|
||||
from esphome.core import CORE
|
||||
from esphome.core import CORE, ID
|
||||
from esphome.coroutine import CoroPriority, coroutine_with_priority
|
||||
|
||||
AUTO_LOAD = ["audio"]
|
||||
@@ -90,7 +90,10 @@ async def speaker_play_action(config, action_id, template_arg, args):
|
||||
templ = await cg.templatable(data, args, cg.std_vector.template(cg.uint8))
|
||||
cg.add(var.set_data_template(templ))
|
||||
else:
|
||||
cg.add(var.set_data_static(data))
|
||||
# Generate static array in flash to avoid RAM copy
|
||||
arr_id = ID(f"{action_id}_data", is_declaration=True, type=cg.uint8)
|
||||
arr = cg.static_const_array(arr_id, cg.ArrayInitializer(*data))
|
||||
cg.add(var.set_data_static(arr, len(data)))
|
||||
return var
|
||||
|
||||
|
||||
|
||||
@@ -10,28 +10,33 @@ namespace speaker {
|
||||
|
||||
template<typename... Ts> class PlayAction : public Action<Ts...>, public Parented<Speaker> {
|
||||
public:
|
||||
void set_data_template(std::function<std::vector<uint8_t>(Ts...)> func) {
|
||||
this->data_func_ = func;
|
||||
this->static_ = false;
|
||||
void set_data_template(std::vector<uint8_t> (*func)(Ts...)) {
|
||||
this->data_.func = func;
|
||||
this->len_ = -1; // Sentinel value indicates template mode
|
||||
}
|
||||
void set_data_static(const std::vector<uint8_t> &data) {
|
||||
this->data_static_ = data;
|
||||
this->static_ = true;
|
||||
|
||||
void set_data_static(const uint8_t *data, size_t len) {
|
||||
this->data_.data = data;
|
||||
this->len_ = len; // Length >= 0 indicates static mode
|
||||
}
|
||||
|
||||
void play(const Ts &...x) override {
|
||||
if (this->static_) {
|
||||
this->parent_->play(this->data_static_);
|
||||
if (this->len_ >= 0) {
|
||||
// Static mode: pass pointer directly to play(const uint8_t *, size_t)
|
||||
this->parent_->play(this->data_.data, static_cast<size_t>(this->len_));
|
||||
} else {
|
||||
auto val = this->data_func_(x...);
|
||||
// Template mode: call function and pass vector to play(const std::vector<uint8_t> &)
|
||||
auto val = this->data_.func(x...);
|
||||
this->parent_->play(val);
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
bool static_{false};
|
||||
std::function<std::vector<uint8_t>(Ts...)> data_func_{};
|
||||
std::vector<uint8_t> data_static_{};
|
||||
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
|
||||
union Data {
|
||||
std::vector<uint8_t> (*func)(Ts...); // Function pointer (stateless lambdas)
|
||||
const uint8_t *data; // Pointer to static data in flash
|
||||
} data_;
|
||||
};
|
||||
|
||||
template<typename... Ts> class VolumeSetAction : public Action<Ts...>, public Parented<Speaker> {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "switch.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -62,6 +64,9 @@ void Switch::publish_state(bool state) {
|
||||
|
||||
ESP_LOGD(TAG, "'%s': Sending state %s", this->name_.c_str(), ONOFF(this->state));
|
||||
this->state_callback_.call(this->state);
|
||||
#if defined(USE_SWITCH) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_switch_update(this);
|
||||
#endif
|
||||
}
|
||||
bool Switch::assumed_state() { return false; }
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import esphome.codegen as cg
|
||||
from esphome.components import spi
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_BUSY_PIN, CONF_DATA, CONF_FREQUENCY, CONF_ID
|
||||
from esphome.core import TimePeriod
|
||||
from esphome.core import ID, TimePeriod
|
||||
|
||||
MULTI_CONF = True
|
||||
CODEOWNERS = ["@swoboda1337"]
|
||||
@@ -189,7 +189,7 @@ CONFIG_SCHEMA = (
|
||||
cv.GenerateID(): cv.declare_id(SX126x),
|
||||
cv.Optional(CONF_BANDWIDTH, default="125_0kHz"): cv.enum(BW),
|
||||
cv.Optional(CONF_BITRATE, default=4800): cv.int_range(min=600, max=300000),
|
||||
cv.Required(CONF_BUSY_PIN): pins.internal_gpio_input_pin_schema,
|
||||
cv.Required(CONF_BUSY_PIN): pins.gpio_input_pin_schema,
|
||||
cv.Optional(CONF_CODING_RATE, default="CR_4_5"): cv.enum(CODING_RATE),
|
||||
cv.Optional(CONF_CRC_ENABLE, default=False): cv.boolean,
|
||||
cv.Optional(CONF_CRC_INVERTED, default=True): cv.boolean,
|
||||
@@ -201,7 +201,7 @@ CONFIG_SCHEMA = (
|
||||
cv.hex_int, cv.Range(min=0, max=0xFFFF)
|
||||
),
|
||||
cv.Optional(CONF_DEVIATION, default=5000): cv.int_range(min=0, max=100000),
|
||||
cv.Required(CONF_DIO1_PIN): pins.internal_gpio_input_pin_schema,
|
||||
cv.Required(CONF_DIO1_PIN): pins.gpio_input_pin_schema,
|
||||
cv.Required(CONF_FREQUENCY): cv.int_range(min=137000000, max=1020000000),
|
||||
cv.Required(CONF_HW_VERSION): cv.one_of(
|
||||
"sx1261", "sx1262", "sx1268", "llcc68", lower=True
|
||||
@@ -213,7 +213,7 @@ CONFIG_SCHEMA = (
|
||||
cv.Optional(CONF_PAYLOAD_LENGTH, default=0): cv.int_range(min=0, max=256),
|
||||
cv.Optional(CONF_PREAMBLE_DETECT, default=2): cv.int_range(min=0, max=4),
|
||||
cv.Optional(CONF_PREAMBLE_SIZE, default=8): cv.int_range(min=1, max=65535),
|
||||
cv.Required(CONF_RST_PIN): pins.internal_gpio_output_pin_schema,
|
||||
cv.Required(CONF_RST_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_RX_START, default=True): cv.boolean,
|
||||
cv.Required(CONF_RF_SWITCH): cv.boolean,
|
||||
cv.Optional(CONF_SHAPING, default="NONE"): cv.enum(SHAPING),
|
||||
@@ -329,5 +329,8 @@ async def send_packet_action_to_code(config, action_id, template_arg, args):
|
||||
templ = await cg.templatable(data, args, cg.std_vector.template(cg.uint8))
|
||||
cg.add(var.set_data_template(templ))
|
||||
else:
|
||||
cg.add(var.set_data_static(data))
|
||||
# Generate static array in flash to avoid RAM copy
|
||||
arr_id = ID(f"{action_id}_data", is_declaration=True, type=cg.uint8)
|
||||
arr = cg.static_const_array(arr_id, cg.ArrayInitializer(*data))
|
||||
cg.add(var.set_data_static(arr, len(data)))
|
||||
return var
|
||||
|
||||
@@ -14,28 +14,34 @@ template<typename... Ts> class RunImageCalAction : public Action<Ts...>, public
|
||||
|
||||
template<typename... Ts> class SendPacketAction : public Action<Ts...>, public Parented<SX126x> {
|
||||
public:
|
||||
void set_data_template(std::function<std::vector<uint8_t>(Ts...)> func) {
|
||||
this->data_func_ = func;
|
||||
this->static_ = false;
|
||||
void set_data_template(std::vector<uint8_t> (*func)(Ts...)) {
|
||||
this->data_.func = func;
|
||||
this->len_ = -1; // Sentinel value indicates template mode
|
||||
}
|
||||
|
||||
void set_data_static(const std::vector<uint8_t> &data) {
|
||||
this->data_static_ = data;
|
||||
this->static_ = true;
|
||||
void set_data_static(const uint8_t *data, size_t len) {
|
||||
this->data_.data = data;
|
||||
this->len_ = len; // Length >= 0 indicates static mode
|
||||
}
|
||||
|
||||
void play(const Ts &...x) override {
|
||||
if (this->static_) {
|
||||
this->parent_->transmit_packet(this->data_static_);
|
||||
std::vector<uint8_t> data;
|
||||
if (this->len_ >= 0) {
|
||||
// Static mode: copy from flash to vector
|
||||
data.assign(this->data_.data, this->data_.data + this->len_);
|
||||
} else {
|
||||
this->parent_->transmit_packet(this->data_func_(x...));
|
||||
// Template mode: call function
|
||||
data = this->data_.func(x...);
|
||||
}
|
||||
this->parent_->transmit_packet(data);
|
||||
}
|
||||
|
||||
protected:
|
||||
bool static_{false};
|
||||
std::function<std::vector<uint8_t>(Ts...)> data_func_{};
|
||||
std::vector<uint8_t> data_static_{};
|
||||
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
|
||||
union Data {
|
||||
std::vector<uint8_t> (*func)(Ts...); // Function pointer (stateless lambdas)
|
||||
const uint8_t *data; // Pointer to static data in flash
|
||||
} data_;
|
||||
};
|
||||
|
||||
template<typename... Ts> class SetModeTxAction : public Action<Ts...>, public Parented<SX126x> {
|
||||
|
||||
@@ -64,7 +64,7 @@ class SX126x : public Component,
|
||||
void dump_config() override;
|
||||
void set_bandwidth(SX126xBw bandwidth) { this->bandwidth_ = bandwidth; }
|
||||
void set_bitrate(uint32_t bitrate) { this->bitrate_ = bitrate; }
|
||||
void set_busy_pin(InternalGPIOPin *busy_pin) { this->busy_pin_ = busy_pin; }
|
||||
void set_busy_pin(GPIOPin *busy_pin) { this->busy_pin_ = busy_pin; }
|
||||
void set_coding_rate(uint8_t coding_rate) { this->coding_rate_ = coding_rate; }
|
||||
void set_crc_enable(bool crc_enable) { this->crc_enable_ = crc_enable; }
|
||||
void set_crc_inverted(bool crc_inverted) { this->crc_inverted_ = crc_inverted; }
|
||||
@@ -72,7 +72,7 @@ class SX126x : public Component,
|
||||
void set_crc_polynomial(uint16_t crc_polynomial) { this->crc_polynomial_ = crc_polynomial; }
|
||||
void set_crc_initial(uint16_t crc_initial) { this->crc_initial_ = crc_initial; }
|
||||
void set_deviation(uint32_t deviation) { this->deviation_ = deviation; }
|
||||
void set_dio1_pin(InternalGPIOPin *dio1_pin) { this->dio1_pin_ = dio1_pin; }
|
||||
void set_dio1_pin(GPIOPin *dio1_pin) { this->dio1_pin_ = dio1_pin; }
|
||||
void set_frequency(uint32_t frequency) { this->frequency_ = frequency; }
|
||||
void set_hw_version(const std::string &hw_version) { this->hw_version_ = hw_version; }
|
||||
void set_mode_rx();
|
||||
@@ -85,7 +85,7 @@ class SX126x : public Component,
|
||||
void set_payload_length(uint8_t payload_length) { this->payload_length_ = payload_length; }
|
||||
void set_preamble_detect(uint16_t preamble_detect) { this->preamble_detect_ = preamble_detect; }
|
||||
void set_preamble_size(uint16_t preamble_size) { this->preamble_size_ = preamble_size; }
|
||||
void set_rst_pin(InternalGPIOPin *rst_pin) { this->rst_pin_ = rst_pin; }
|
||||
void set_rst_pin(GPIOPin *rst_pin) { this->rst_pin_ = rst_pin; }
|
||||
void set_rx_start(bool rx_start) { this->rx_start_ = rx_start; }
|
||||
void set_rf_switch(bool rf_switch) { this->rf_switch_ = rf_switch; }
|
||||
void set_shaping(uint8_t shaping) { this->shaping_ = shaping; }
|
||||
@@ -115,9 +115,9 @@ class SX126x : public Component,
|
||||
std::vector<SX126xListener *> listeners_;
|
||||
std::vector<uint8_t> packet_;
|
||||
std::vector<uint8_t> sync_value_;
|
||||
InternalGPIOPin *busy_pin_{nullptr};
|
||||
InternalGPIOPin *dio1_pin_{nullptr};
|
||||
InternalGPIOPin *rst_pin_{nullptr};
|
||||
GPIOPin *busy_pin_{nullptr};
|
||||
GPIOPin *dio1_pin_{nullptr};
|
||||
GPIOPin *rst_pin_{nullptr};
|
||||
std::string hw_version_;
|
||||
char version_[16];
|
||||
SX126xBw bandwidth_{SX126X_BW_125000};
|
||||
|
||||
@@ -3,6 +3,7 @@ import esphome.codegen as cg
|
||||
from esphome.components import spi
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DATA, CONF_FREQUENCY, CONF_ID
|
||||
from esphome.core import ID
|
||||
|
||||
MULTI_CONF = True
|
||||
CODEOWNERS = ["@swoboda1337"]
|
||||
@@ -321,5 +322,8 @@ async def send_packet_action_to_code(config, action_id, template_arg, args):
|
||||
templ = await cg.templatable(data, args, cg.std_vector.template(cg.uint8))
|
||||
cg.add(var.set_data_template(templ))
|
||||
else:
|
||||
cg.add(var.set_data_static(data))
|
||||
# Generate static array in flash to avoid RAM copy
|
||||
arr_id = ID(f"{action_id}_data", is_declaration=True, type=cg.uint8)
|
||||
arr = cg.static_const_array(arr_id, cg.ArrayInitializer(*data))
|
||||
cg.add(var.set_data_static(arr, len(data)))
|
||||
return var
|
||||
|
||||
@@ -14,28 +14,34 @@ template<typename... Ts> class RunImageCalAction : public Action<Ts...>, public
|
||||
|
||||
template<typename... Ts> class SendPacketAction : public Action<Ts...>, public Parented<SX127x> {
|
||||
public:
|
||||
void set_data_template(std::function<std::vector<uint8_t>(Ts...)> func) {
|
||||
this->data_func_ = func;
|
||||
this->static_ = false;
|
||||
void set_data_template(std::vector<uint8_t> (*func)(Ts...)) {
|
||||
this->data_.func = func;
|
||||
this->len_ = -1; // Sentinel value indicates template mode
|
||||
}
|
||||
|
||||
void set_data_static(const std::vector<uint8_t> &data) {
|
||||
this->data_static_ = data;
|
||||
this->static_ = true;
|
||||
void set_data_static(const uint8_t *data, size_t len) {
|
||||
this->data_.data = data;
|
||||
this->len_ = len; // Length >= 0 indicates static mode
|
||||
}
|
||||
|
||||
void play(const Ts &...x) override {
|
||||
if (this->static_) {
|
||||
this->parent_->transmit_packet(this->data_static_);
|
||||
std::vector<uint8_t> data;
|
||||
if (this->len_ >= 0) {
|
||||
// Static mode: copy from flash to vector
|
||||
data.assign(this->data_.data, this->data_.data + this->len_);
|
||||
} else {
|
||||
this->parent_->transmit_packet(this->data_func_(x...));
|
||||
// Template mode: call function
|
||||
data = this->data_.func(x...);
|
||||
}
|
||||
this->parent_->transmit_packet(data);
|
||||
}
|
||||
|
||||
protected:
|
||||
bool static_{false};
|
||||
std::function<std::vector<uint8_t>(Ts...)> data_func_{};
|
||||
std::vector<uint8_t> data_static_{};
|
||||
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
|
||||
union Data {
|
||||
std::vector<uint8_t> (*func)(Ts...); // Function pointer (stateless lambdas)
|
||||
const uint8_t *data; // Pointer to static data in flash
|
||||
} data_;
|
||||
};
|
||||
|
||||
template<typename... Ts> class SetModeTxAction : public Action<Ts...>, public Parented<SX127x> {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "text.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -16,6 +18,9 @@ void Text::publish_state(const std::string &state) {
|
||||
ESP_LOGD(TAG, "'%s': Sending state %s", this->get_name().c_str(), state.c_str());
|
||||
}
|
||||
this->state_callback_.call(state);
|
||||
#if defined(USE_TEXT) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_text_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
void Text::add_on_state_callback(std::function<void(std::string)> &&callback) {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "text_sensor.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -84,6 +86,9 @@ void TextSensor::internal_send_state_to_frontend(const std::string &state) {
|
||||
this->set_has_state(true);
|
||||
ESP_LOGD(TAG, "'%s': Sending state '%s'", this->name_.c_str(), state.c_str());
|
||||
this->callback_.call(state);
|
||||
#if defined(USE_TEXT_SENSOR) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_text_sensor_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace text_sensor
|
||||
|
||||
@@ -31,7 +31,7 @@ from esphome.const import (
|
||||
PLATFORM_HOST,
|
||||
PlatformFramework,
|
||||
)
|
||||
from esphome.core import CORE
|
||||
from esphome.core import CORE, ID
|
||||
import esphome.final_validate as fv
|
||||
from esphome.yaml_util import make_data_base
|
||||
|
||||
@@ -446,7 +446,10 @@ async def uart_write_to_code(config, action_id, template_arg, args):
|
||||
templ = await cg.templatable(data, args, cg.std_vector.template(cg.uint8))
|
||||
cg.add(var.set_data_template(templ))
|
||||
else:
|
||||
cg.add(var.set_data_static(cg.ArrayInitializer(*data)))
|
||||
# Generate static array in flash to avoid RAM copy
|
||||
arr_id = ID(f"{action_id}_data", is_declaration=True, type=cg.uint8)
|
||||
arr = cg.static_const_array(arr_id, cg.ArrayInitializer(*data))
|
||||
cg.add(var.set_data_static(arr, len(data)))
|
||||
return var
|
||||
|
||||
|
||||
|
||||
@@ -10,32 +10,35 @@ namespace uart {
|
||||
|
||||
template<typename... Ts> class UARTWriteAction : public Action<Ts...>, public Parented<UARTComponent> {
|
||||
public:
|
||||
void set_data_template(std::function<std::vector<uint8_t>(Ts...)> func) {
|
||||
this->data_func_ = func;
|
||||
this->static_ = false;
|
||||
void set_data_template(std::vector<uint8_t> (*func)(Ts...)) {
|
||||
// Stateless lambdas (generated by ESPHome) implicitly convert to function pointers
|
||||
this->code_.func = func;
|
||||
this->len_ = -1; // Sentinel value indicates template mode
|
||||
}
|
||||
void set_data_static(std::vector<uint8_t> &&data) {
|
||||
this->data_static_ = std::move(data);
|
||||
this->static_ = true;
|
||||
}
|
||||
void set_data_static(std::initializer_list<uint8_t> data) {
|
||||
this->data_static_ = std::vector<uint8_t>(data);
|
||||
this->static_ = true;
|
||||
|
||||
// Store pointer to static data in flash (no RAM copy)
|
||||
void set_data_static(const uint8_t *data, size_t len) {
|
||||
this->code_.data = data;
|
||||
this->len_ = len; // Length >= 0 indicates static mode
|
||||
}
|
||||
|
||||
void play(const Ts &...x) override {
|
||||
if (this->static_) {
|
||||
this->parent_->write_array(this->data_static_);
|
||||
if (this->len_ >= 0) {
|
||||
// Static mode: use pointer and length
|
||||
this->parent_->write_array(this->code_.data, static_cast<size_t>(this->len_));
|
||||
} else {
|
||||
auto val = this->data_func_(x...);
|
||||
// Template mode: call function
|
||||
auto val = this->code_.func(x...);
|
||||
this->parent_->write_array(val);
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
bool static_{false};
|
||||
std::function<std::vector<uint8_t>(Ts...)> data_func_{};
|
||||
std::vector<uint8_t> data_static_{};
|
||||
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
|
||||
union Code {
|
||||
std::vector<uint8_t> (*func)(Ts...); // Function pointer (stateless lambdas)
|
||||
const uint8_t *data; // Pointer to static data in flash
|
||||
} code_;
|
||||
};
|
||||
|
||||
} // namespace uart
|
||||
|
||||
@@ -12,7 +12,7 @@ from esphome.components.packet_transport import (
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DATA, CONF_ID, CONF_PORT, CONF_TRIGGER_ID
|
||||
from esphome.core import Lambda
|
||||
from esphome.core import ID, Lambda
|
||||
from esphome.cpp_generator import ExpressionStatement, MockObj
|
||||
|
||||
CODEOWNERS = ["@clydebarrow"]
|
||||
@@ -158,5 +158,8 @@ async def udp_write_to_code(config, action_id, template_arg, args):
|
||||
templ = await cg.templatable(data, args, cg.std_vector.template(cg.uint8))
|
||||
cg.add(var.set_data_template(templ))
|
||||
else:
|
||||
cg.add(var.set_data_static(data))
|
||||
# Generate static array in flash to avoid RAM copy
|
||||
arr_id = ID(f"{action_id}_data", is_declaration=True, type=cg.uint8)
|
||||
arr = cg.static_const_array(arr_id, cg.ArrayInitializer(*data))
|
||||
cg.add(var.set_data_static(arr, len(data)))
|
||||
return var
|
||||
|
||||
@@ -11,28 +11,33 @@ namespace udp {
|
||||
|
||||
template<typename... Ts> class UDPWriteAction : public Action<Ts...>, public Parented<UDPComponent> {
|
||||
public:
|
||||
void set_data_template(std::function<std::vector<uint8_t>(Ts...)> func) {
|
||||
this->data_func_ = func;
|
||||
this->static_ = false;
|
||||
void set_data_template(std::vector<uint8_t> (*func)(Ts...)) {
|
||||
this->data_.func = func;
|
||||
this->len_ = -1; // Sentinel value indicates template mode
|
||||
}
|
||||
void set_data_static(const std::vector<uint8_t> &data) {
|
||||
this->data_static_ = data;
|
||||
this->static_ = true;
|
||||
|
||||
void set_data_static(const uint8_t *data, size_t len) {
|
||||
this->data_.data = data;
|
||||
this->len_ = len; // Length >= 0 indicates static mode
|
||||
}
|
||||
|
||||
void play(const Ts &...x) override {
|
||||
if (this->static_) {
|
||||
this->parent_->send_packet(this->data_static_);
|
||||
if (this->len_ >= 0) {
|
||||
// Static mode: pass pointer directly to send_packet(const uint8_t *, size_t)
|
||||
this->parent_->send_packet(this->data_.data, static_cast<size_t>(this->len_));
|
||||
} else {
|
||||
auto val = this->data_func_(x...);
|
||||
// Template mode: call function and pass vector to send_packet(const std::vector<uint8_t> &)
|
||||
auto val = this->data_.func(x...);
|
||||
this->parent_->send_packet(val);
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
bool static_{false};
|
||||
std::function<std::vector<uint8_t>(Ts...)> data_func_{};
|
||||
std::vector<uint8_t> data_static_{};
|
||||
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
|
||||
union Data {
|
||||
std::vector<uint8_t> (*func)(Ts...); // Function pointer (stateless lambdas)
|
||||
const uint8_t *data; // Pointer to static data in flash
|
||||
} data_;
|
||||
};
|
||||
|
||||
} // namespace udp
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "update_entity.h"
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -32,6 +33,9 @@ void UpdateEntity::publish_state() {
|
||||
|
||||
this->set_has_state(true);
|
||||
this->state_callback_.call();
|
||||
#if defined(USE_UPDATE) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_update(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace update
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "valve.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include <strings.h>
|
||||
|
||||
@@ -147,6 +149,9 @@ void Valve::publish_state(bool save) {
|
||||
ESP_LOGD(TAG, " Current Operation: %s", valve_operation_to_str(this->current_operation));
|
||||
|
||||
this->state_callback_.call();
|
||||
#if defined(USE_VALVE) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_valve_update(this);
|
||||
#endif
|
||||
|
||||
if (save) {
|
||||
ValveRestoreState restore{};
|
||||
|
||||
@@ -289,6 +289,9 @@ async def to_code(config):
|
||||
var = cg.new_Pvariable(config[CONF_ID], paren)
|
||||
await cg.register_component(var, config)
|
||||
|
||||
# Track controller registration for StaticVector sizing
|
||||
CORE.register_controller()
|
||||
|
||||
version = config[CONF_VERSION]
|
||||
|
||||
cg.add(paren.set_port(config[CONF_PORT]))
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
#include "esphome/components/json/json_util.h"
|
||||
#include "esphome/components/network/util.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/entity_base.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
@@ -294,7 +296,7 @@ std::string WebServer::get_config_json() {
|
||||
}
|
||||
|
||||
void WebServer::setup() {
|
||||
this->setup_controller(this->include_internal_);
|
||||
ControllerRegistry::register_controller(this);
|
||||
this->base_->init();
|
||||
|
||||
#ifdef USE_LOGGER
|
||||
@@ -430,7 +432,9 @@ static JsonDetail get_request_detail(AsyncWebServerRequest *request) {
|
||||
}
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
void WebServer::on_sensor_update(sensor::Sensor *obj, float state) {
|
||||
void WebServer::on_sensor_update(sensor::Sensor *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", sensor_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -473,7 +477,9 @@ std::string WebServer::sensor_json(sensor::Sensor *obj, float value, JsonDetail
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
void WebServer::on_text_sensor_update(text_sensor::TextSensor *obj, const std::string &state) {
|
||||
void WebServer::on_text_sensor_update(text_sensor::TextSensor *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", text_sensor_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_text_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -513,7 +519,9 @@ std::string WebServer::text_sensor_json(text_sensor::TextSensor *obj, const std:
|
||||
#endif
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
void WebServer::on_switch_update(switch_::Switch *obj, bool state) {
|
||||
void WebServer::on_switch_update(switch_::Switch *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", switch_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_switch_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -625,6 +633,8 @@ std::string WebServer::button_json(button::Button *obj, JsonDetail start_config)
|
||||
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
void WebServer::on_binary_sensor_update(binary_sensor::BinarySensor *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", binary_sensor_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_binary_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -664,6 +674,8 @@ std::string WebServer::binary_sensor_json(binary_sensor::BinarySensor *obj, bool
|
||||
|
||||
#ifdef USE_FAN
|
||||
void WebServer::on_fan_update(fan::Fan *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", fan_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_fan_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -738,6 +750,8 @@ std::string WebServer::fan_json(fan::Fan *obj, JsonDetail start_config) {
|
||||
|
||||
#ifdef USE_LIGHT
|
||||
void WebServer::on_light_update(light::LightState *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", light_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_light_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -811,6 +825,8 @@ std::string WebServer::light_json(light::LightState *obj, JsonDetail start_confi
|
||||
|
||||
#ifdef USE_COVER
|
||||
void WebServer::on_cover_update(cover::Cover *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", cover_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_cover_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -895,7 +911,9 @@ std::string WebServer::cover_json(cover::Cover *obj, JsonDetail start_config) {
|
||||
#endif
|
||||
|
||||
#ifdef USE_NUMBER
|
||||
void WebServer::on_number_update(number::Number *obj, float state) {
|
||||
void WebServer::on_number_update(number::Number *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", number_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_number_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -961,6 +979,8 @@ std::string WebServer::number_json(number::Number *obj, float value, JsonDetail
|
||||
|
||||
#ifdef USE_DATETIME_DATE
|
||||
void WebServer::on_date_update(datetime::DateEntity *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", date_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_date_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -1016,6 +1036,8 @@ std::string WebServer::date_json(datetime::DateEntity *obj, JsonDetail start_con
|
||||
|
||||
#ifdef USE_DATETIME_TIME
|
||||
void WebServer::on_time_update(datetime::TimeEntity *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", time_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_time_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -1070,6 +1092,8 @@ std::string WebServer::time_json(datetime::TimeEntity *obj, JsonDetail start_con
|
||||
|
||||
#ifdef USE_DATETIME_DATETIME
|
||||
void WebServer::on_datetime_update(datetime::DateTimeEntity *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", datetime_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_datetime_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -1124,7 +1148,9 @@ std::string WebServer::datetime_json(datetime::DateTimeEntity *obj, JsonDetail s
|
||||
#endif // USE_DATETIME_DATETIME
|
||||
|
||||
#ifdef USE_TEXT
|
||||
void WebServer::on_text_update(text::Text *obj, const std::string &state) {
|
||||
void WebServer::on_text_update(text::Text *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", text_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_text_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -1178,7 +1204,9 @@ std::string WebServer::text_json(text::Text *obj, const std::string &value, Json
|
||||
#endif
|
||||
|
||||
#ifdef USE_SELECT
|
||||
void WebServer::on_select_update(select::Select *obj, const std::string &state, size_t index) {
|
||||
void WebServer::on_select_update(select::Select *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", select_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_select_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -1237,6 +1265,8 @@ std::string WebServer::select_json(select::Select *obj, const char *value, JsonD
|
||||
|
||||
#ifdef USE_CLIMATE
|
||||
void WebServer::on_climate_update(climate::Climate *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", climate_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_climate_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -1378,6 +1408,8 @@ std::string WebServer::climate_json(climate::Climate *obj, JsonDetail start_conf
|
||||
|
||||
#ifdef USE_LOCK
|
||||
void WebServer::on_lock_update(lock::Lock *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", lock_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_lock_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -1449,6 +1481,8 @@ std::string WebServer::lock_json(lock::Lock *obj, lock::LockState value, JsonDet
|
||||
|
||||
#ifdef USE_VALVE
|
||||
void WebServer::on_valve_update(valve::Valve *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", valve_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_valve_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -1530,6 +1564,8 @@ std::string WebServer::valve_json(valve::Valve *obj, JsonDetail start_config) {
|
||||
|
||||
#ifdef USE_ALARM_CONTROL_PANEL
|
||||
void WebServer::on_alarm_control_panel_update(alarm_control_panel::AlarmControlPanel *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", alarm_control_panel_state_json_generator);
|
||||
}
|
||||
void WebServer::handle_alarm_control_panel_request(AsyncWebServerRequest *request, const UrlMatch &match) {
|
||||
@@ -1607,7 +1643,9 @@ std::string WebServer::alarm_control_panel_json(alarm_control_panel::AlarmContro
|
||||
#endif
|
||||
|
||||
#ifdef USE_EVENT
|
||||
void WebServer::on_event(event::Event *obj, const std::string &event_type) {
|
||||
void WebServer::on_event(event::Event *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
this->events_.deferrable_send_state(obj, "state", event_state_json_generator);
|
||||
}
|
||||
|
||||
|
||||
@@ -255,7 +255,7 @@ class WebServer : public Controller, public Component, public AsyncWebHandler {
|
||||
#endif
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
void on_sensor_update(sensor::Sensor *obj, float state) override;
|
||||
void on_sensor_update(sensor::Sensor *obj) override;
|
||||
/// Handle a sensor request under '/sensor/<id>'.
|
||||
void handle_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match);
|
||||
|
||||
@@ -266,7 +266,7 @@ class WebServer : public Controller, public Component, public AsyncWebHandler {
|
||||
#endif
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
void on_switch_update(switch_::Switch *obj, bool state) override;
|
||||
void on_switch_update(switch_::Switch *obj) override;
|
||||
|
||||
/// Handle a switch request under '/switch/<id>/</turn_on/turn_off/toggle>'.
|
||||
void handle_switch_request(AsyncWebServerRequest *request, const UrlMatch &match);
|
||||
@@ -324,7 +324,7 @@ class WebServer : public Controller, public Component, public AsyncWebHandler {
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
void on_text_sensor_update(text_sensor::TextSensor *obj, const std::string &state) override;
|
||||
void on_text_sensor_update(text_sensor::TextSensor *obj) override;
|
||||
|
||||
/// Handle a text sensor request under '/text_sensor/<id>'.
|
||||
void handle_text_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match);
|
||||
@@ -348,7 +348,7 @@ class WebServer : public Controller, public Component, public AsyncWebHandler {
|
||||
#endif
|
||||
|
||||
#ifdef USE_NUMBER
|
||||
void on_number_update(number::Number *obj, float state) override;
|
||||
void on_number_update(number::Number *obj) override;
|
||||
/// Handle a number request under '/number/<id>'.
|
||||
void handle_number_request(AsyncWebServerRequest *request, const UrlMatch &match);
|
||||
|
||||
@@ -392,7 +392,7 @@ class WebServer : public Controller, public Component, public AsyncWebHandler {
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT
|
||||
void on_text_update(text::Text *obj, const std::string &state) override;
|
||||
void on_text_update(text::Text *obj) override;
|
||||
/// Handle a text input request under '/text/<id>'.
|
||||
void handle_text_request(AsyncWebServerRequest *request, const UrlMatch &match);
|
||||
|
||||
@@ -403,7 +403,7 @@ class WebServer : public Controller, public Component, public AsyncWebHandler {
|
||||
#endif
|
||||
|
||||
#ifdef USE_SELECT
|
||||
void on_select_update(select::Select *obj, const std::string &state, size_t index) override;
|
||||
void on_select_update(select::Select *obj) override;
|
||||
/// Handle a select request under '/select/<id>'.
|
||||
void handle_select_request(AsyncWebServerRequest *request, const UrlMatch &match);
|
||||
|
||||
@@ -462,7 +462,7 @@ class WebServer : public Controller, public Component, public AsyncWebHandler {
|
||||
#endif
|
||||
|
||||
#ifdef USE_EVENT
|
||||
void on_event(event::Event *obj, const std::string &event_type) override;
|
||||
void on_event(event::Event *obj) override;
|
||||
|
||||
static std::string event_state_json_generator(WebServer *web_server, void *source);
|
||||
static std::string event_all_json_generator(WebServer *web_server, void *source);
|
||||
|
||||
@@ -42,6 +42,258 @@ namespace wifi {
|
||||
|
||||
static const char *const TAG = "wifi";
|
||||
|
||||
/// WiFi Retry Logic - Priority-Based BSSID Selection
|
||||
///
|
||||
/// The WiFi component uses a state machine with priority degradation to handle connection failures
|
||||
/// and automatically cycle through different BSSIDs in mesh networks or multiple configured networks.
|
||||
///
|
||||
/// Connection Flow:
|
||||
/// ┌──────────────────────────────────────────────────────────────────────┐
|
||||
/// │ Fast Connect Path (Optional) │
|
||||
/// ├──────────────────────────────────────────────────────────────────────┤
|
||||
/// │ Entered if: configuration has 'fast_connect: true' │
|
||||
/// │ Optimization to skip scanning when possible: │
|
||||
/// │ │
|
||||
/// │ 1. INITIAL_CONNECT → Try one of: │
|
||||
/// │ a) Saved BSSID+channel (from previous boot) │
|
||||
/// │ b) First configured non-hidden network (any BSSID) │
|
||||
/// │ ↓ │
|
||||
/// │ [FAILED] → Check if more configured networks available │
|
||||
/// │ ↓ │
|
||||
/// │ 2. FAST_CONNECT_CYCLING_APS → Try remaining configured networks │
|
||||
/// │ (1 attempt each, any BSSID) │
|
||||
/// │ ↓ │
|
||||
/// │ [All Failed] → Fall through to explicit hidden or scanning │
|
||||
/// │ │
|
||||
/// │ Note: Fast connect data saved from previous successful connection │
|
||||
/// └──────────────────────────────────────────────────────────────────────┘
|
||||
/// ↓
|
||||
/// ┌──────────────────────────────────────────────────────────────────────┐
|
||||
/// │ Explicit Hidden Networks Path (Optional) │
|
||||
/// ├──────────────────────────────────────────────────────────────────────┤
|
||||
/// │ Entered if: first configured network has 'hidden: true' │
|
||||
/// │ │
|
||||
/// │ 1. EXPLICIT_HIDDEN → Try consecutive hidden networks (1 attempt) │
|
||||
/// │ Stop when visible network reached │
|
||||
/// │ ↓ │
|
||||
/// │ Example: Hidden1, Hidden2, Visible1, Hidden3, Visible2 │
|
||||
/// │ Try: Hidden1, Hidden2 (stop at Visible1) │
|
||||
/// │ ↓ │
|
||||
/// │ [All Failed] → Fall back to scan-based connection │
|
||||
/// │ │
|
||||
/// │ Note: Fast connect saves BSSID after first successful connection, │
|
||||
/// │ so subsequent boots use fast path instead of hidden mode │
|
||||
/// └──────────────────────────────────────────────────────────────────────┘
|
||||
/// ↓
|
||||
/// ┌──────────────────────────────────────────────────────────────────────┐
|
||||
/// │ Scan-Based Connection Path │
|
||||
/// ├──────────────────────────────────────────────────────────────────────┤
|
||||
/// │ │
|
||||
/// │ 1. SCAN → Sort by priority (highest first), then RSSI │
|
||||
/// │ ┌─────────────────────────────────────────────────┐ │
|
||||
/// │ │ scan_result_[0] = Best BSSID (highest priority) │ │
|
||||
/// │ │ scan_result_[1] = Second best │ │
|
||||
/// │ │ scan_result_[2] = Third best │ │
|
||||
/// │ └─────────────────────────────────────────────────┘ │
|
||||
/// │ ↓ │
|
||||
/// │ 2. SCAN_CONNECTING → Try scan_result_[0] (2 attempts) │
|
||||
/// │ (Visible1, Visible2 from example above) │
|
||||
/// │ ↓ │
|
||||
/// │ 3. FAILED → Decrease priority: 0.0 → -1.0 → -2.0 │
|
||||
/// │ (stored in persistent sta_priorities_) │
|
||||
/// │ ↓ │
|
||||
/// │ 4. Check for hidden networks: │
|
||||
/// │ - If found → RETRY_HIDDEN (try SSIDs not in scan, 1 attempt) │
|
||||
/// │ Skip hidden networks before first visible one │
|
||||
/// │ (Skip Hidden1/Hidden2, try Hidden3 from example) │
|
||||
/// │ - If none → Skip RETRY_HIDDEN, go to step 5 │
|
||||
/// │ ↓ │
|
||||
/// │ 5. FAILED → RESTARTING_ADAPTER (skipped if AP/improv active) │
|
||||
/// │ ↓ │
|
||||
/// │ 6. Loop back to start: │
|
||||
/// │ - If first network is hidden → EXPLICIT_HIDDEN (retry cycle) │
|
||||
/// │ - Otherwise → SCAN_CONNECTING (rescan) │
|
||||
/// │ ↓ │
|
||||
/// │ 7. RESCAN → Apply stored priorities, sort again │
|
||||
/// │ ┌─────────────────────────────────────────────────┐ │
|
||||
/// │ │ scan_result_[0] = BSSID B (priority 0.0) ← NEW │ │
|
||||
/// │ │ scan_result_[1] = BSSID C (priority 0.0) │ │
|
||||
/// │ │ scan_result_[2] = BSSID A (priority -2.0) ← OLD │ │
|
||||
/// │ └─────────────────────────────────────────────────┘ │
|
||||
/// │ ↓ │
|
||||
/// │ 8. SCAN_CONNECTING → Try scan_result_[0] (next best) │
|
||||
/// │ │
|
||||
/// │ Key: Priority system cycles through BSSIDs ACROSS scan cycles │
|
||||
/// │ Full retry cycle: EXPLICIT_HIDDEN → SCAN → RETRY_HIDDEN │
|
||||
/// │ Always try best available BSSID (scan_result_[0]) │
|
||||
/// └──────────────────────────────────────────────────────────────────────┘
|
||||
///
|
||||
/// Retry Phases:
|
||||
/// - INITIAL_CONNECT: Try saved BSSID+channel (fast_connect), or fall back to normal flow
|
||||
/// - FAST_CONNECT_CYCLING_APS: Cycle through remaining configured networks (1 attempt each, fast_connect only)
|
||||
/// - EXPLICIT_HIDDEN: Try consecutive networks marked hidden:true before scanning (1 attempt per SSID)
|
||||
/// - SCAN_CONNECTING: Connect using scan results (2 attempts per BSSID)
|
||||
/// - RETRY_HIDDEN: Try networks not found in scan (1 attempt per SSID, skipped if none found)
|
||||
/// - RESTARTING_ADAPTER: Restart WiFi adapter to clear stuck state
|
||||
///
|
||||
/// Hidden Network Handling:
|
||||
/// - Networks marked 'hidden: true' before first non-hidden → Tried in EXPLICIT_HIDDEN phase
|
||||
/// - Networks marked 'hidden: true' after first non-hidden → Tried in RETRY_HIDDEN phase
|
||||
/// - After successful connection, fast_connect saves BSSID → subsequent boots use fast path
|
||||
/// - Networks not in scan results → Tried in RETRY_HIDDEN phase
|
||||
/// - Networks visible in scan + not marked hidden → Skipped in RETRY_HIDDEN phase
|
||||
/// - Networks marked 'hidden: true' always use hidden mode, even if broadcasting SSID
|
||||
|
||||
static const LogString *retry_phase_to_log_string(WiFiRetryPhase phase) {
|
||||
switch (phase) {
|
||||
case WiFiRetryPhase::INITIAL_CONNECT:
|
||||
return LOG_STR("INITIAL_CONNECT");
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
case WiFiRetryPhase::FAST_CONNECT_CYCLING_APS:
|
||||
return LOG_STR("FAST_CONNECT_CYCLING");
|
||||
#endif
|
||||
case WiFiRetryPhase::EXPLICIT_HIDDEN:
|
||||
return LOG_STR("EXPLICIT_HIDDEN");
|
||||
case WiFiRetryPhase::SCAN_CONNECTING:
|
||||
return LOG_STR("SCAN_CONNECTING");
|
||||
case WiFiRetryPhase::RETRY_HIDDEN:
|
||||
return LOG_STR("RETRY_HIDDEN");
|
||||
case WiFiRetryPhase::RESTARTING_ADAPTER:
|
||||
return LOG_STR("RESTARTING");
|
||||
default:
|
||||
return LOG_STR("UNKNOWN");
|
||||
}
|
||||
}
|
||||
|
||||
bool WiFiComponent::went_through_explicit_hidden_phase_() const {
|
||||
// If first configured network is marked hidden, we went through EXPLICIT_HIDDEN phase
|
||||
// This means those networks were already tried and should be skipped in RETRY_HIDDEN
|
||||
return !this->sta_.empty() && this->sta_[0].get_hidden();
|
||||
}
|
||||
|
||||
int8_t WiFiComponent::find_first_non_hidden_index_() const {
|
||||
// Find the first network that is NOT marked hidden:true
|
||||
// This is where EXPLICIT_HIDDEN phase would have stopped
|
||||
for (size_t i = 0; i < this->sta_.size(); i++) {
|
||||
if (!this->sta_[i].get_hidden()) {
|
||||
return static_cast<int8_t>(i);
|
||||
}
|
||||
}
|
||||
return -1; // All networks are hidden
|
||||
}
|
||||
|
||||
// 2 attempts per BSSID in SCAN_CONNECTING phase
|
||||
// Rationale: This is the ONLY phase where we decrease BSSID priority, so we must be very sure.
|
||||
// Auth failures are common immediately after scan due to WiFi stack state transitions.
|
||||
// Trying twice filters out false positives and prevents unnecessarily marking a good BSSID as bad.
|
||||
// After 2 genuine failures, priority degradation ensures we skip this BSSID on subsequent scans.
|
||||
static constexpr uint8_t WIFI_RETRY_COUNT_PER_BSSID = 2;
|
||||
|
||||
// 1 attempt per SSID in RETRY_HIDDEN phase
|
||||
// Rationale: Try hidden mode once, then rescan to get next best BSSID via priority system
|
||||
static constexpr uint8_t WIFI_RETRY_COUNT_PER_SSID = 1;
|
||||
|
||||
// 1 attempt per AP in fast_connect mode (INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS)
|
||||
// Rationale: Fast connect prioritizes speed - try each AP once to find a working one quickly
|
||||
static constexpr uint8_t WIFI_RETRY_COUNT_PER_AP = 1;
|
||||
|
||||
static constexpr uint8_t get_max_retries_for_phase(WiFiRetryPhase phase) {
|
||||
switch (phase) {
|
||||
case WiFiRetryPhase::INITIAL_CONNECT:
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
case WiFiRetryPhase::FAST_CONNECT_CYCLING_APS:
|
||||
#endif
|
||||
// INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS both use 1 attempt per AP (fast_connect mode)
|
||||
return WIFI_RETRY_COUNT_PER_AP;
|
||||
case WiFiRetryPhase::EXPLICIT_HIDDEN:
|
||||
// Explicitly hidden network: 1 attempt (user marked as hidden, try once then scan)
|
||||
return WIFI_RETRY_COUNT_PER_SSID;
|
||||
case WiFiRetryPhase::SCAN_CONNECTING:
|
||||
// Scan-based phase: 2 attempts per BSSID (handles transient auth failures after scan)
|
||||
return WIFI_RETRY_COUNT_PER_BSSID;
|
||||
case WiFiRetryPhase::RETRY_HIDDEN:
|
||||
// Hidden network mode: 1 attempt per SSID
|
||||
return WIFI_RETRY_COUNT_PER_SSID;
|
||||
default:
|
||||
return WIFI_RETRY_COUNT_PER_BSSID;
|
||||
}
|
||||
}
|
||||
|
||||
static void apply_scan_result_to_params(WiFiAP ¶ms, const WiFiScanResult &scan) {
|
||||
params.set_hidden(false);
|
||||
params.set_ssid(scan.get_ssid());
|
||||
params.set_bssid(scan.get_bssid());
|
||||
params.set_channel(scan.get_channel());
|
||||
}
|
||||
|
||||
bool WiFiComponent::needs_scan_results_() const {
|
||||
// Only SCAN_CONNECTING phase needs scan results
|
||||
if (this->retry_phase_ != WiFiRetryPhase::SCAN_CONNECTING) {
|
||||
return false;
|
||||
}
|
||||
// Need scan if we have no results or no matching networks
|
||||
return this->scan_result_.empty() || !this->scan_result_[0].get_matches();
|
||||
}
|
||||
|
||||
bool WiFiComponent::ssid_was_seen_in_scan_(const std::string &ssid) const {
|
||||
// Check if this SSID is configured as hidden
|
||||
// If explicitly marked hidden, we should always try hidden mode regardless of scan results
|
||||
for (const auto &conf : this->sta_) {
|
||||
if (conf.get_ssid() == ssid && conf.get_hidden()) {
|
||||
return false; // Treat as not seen - force hidden mode attempt
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, check if we saw it in scan results
|
||||
for (const auto &scan : this->scan_result_) {
|
||||
if (scan.get_ssid() == ssid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int8_t WiFiComponent::find_next_hidden_sta_(int8_t start_index, bool include_explicit_hidden) {
|
||||
// Find next SSID that wasn't in scan results (might be hidden)
|
||||
// Start searching from start_index + 1
|
||||
for (size_t i = start_index + 1; i < this->sta_.size(); i++) {
|
||||
const auto &sta = this->sta_[i];
|
||||
|
||||
// Skip networks that were already tried in EXPLICIT_HIDDEN phase
|
||||
// Those are: networks marked hidden:true that appear before the first non-hidden network
|
||||
if (!include_explicit_hidden && sta.get_hidden()) {
|
||||
int8_t first_non_hidden_idx = this->find_first_non_hidden_index_();
|
||||
if (first_non_hidden_idx >= 0 && static_cast<int8_t>(i) < first_non_hidden_idx) {
|
||||
ESP_LOGD(TAG, "Skipping " LOG_SECRET("'%s'") " (explicit hidden, already tried)", sta.get_ssid().c_str());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this->ssid_was_seen_in_scan_(sta.get_ssid())) {
|
||||
ESP_LOGD(TAG, "Hidden candidate " LOG_SECRET("'%s'") " at index %d", sta.get_ssid().c_str(), static_cast<int>(i));
|
||||
return static_cast<int8_t>(i);
|
||||
}
|
||||
ESP_LOGD(TAG, "Skipping " LOG_SECRET("'%s'") " (visible in scan)", sta.get_ssid().c_str());
|
||||
}
|
||||
// No hidden SSIDs found
|
||||
return -1;
|
||||
}
|
||||
|
||||
void WiFiComponent::start_initial_connection_() {
|
||||
// If first network (highest priority) is explicitly marked hidden, try it first before scanning
|
||||
// This respects user's priority order when they explicitly configure hidden networks
|
||||
if (!this->sta_.empty() && this->sta_[0].get_hidden()) {
|
||||
ESP_LOGI(TAG, "Starting with explicit hidden network (highest priority)");
|
||||
this->selected_sta_index_ = 0;
|
||||
this->retry_phase_ = WiFiRetryPhase::EXPLICIT_HIDDEN;
|
||||
WiFiAP params = this->build_params_for_current_phase_();
|
||||
this->start_connecting(params, false);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "Starting scan");
|
||||
this->start_scanning();
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP) && ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
|
||||
static const char *eap_phase2_to_str(esp_eap_ttls_phase2_types type) {
|
||||
switch (type) {
|
||||
@@ -109,18 +361,28 @@ void WiFiComponent::start() {
|
||||
ESP_LOGV(TAG, "Setting Power Save Option failed");
|
||||
}
|
||||
|
||||
this->transition_to_phase_(WiFiRetryPhase::INITIAL_CONNECT);
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
WiFiAP params;
|
||||
this->trying_loaded_ap_ = this->load_fast_connect_settings_(params);
|
||||
if (!this->trying_loaded_ap_) {
|
||||
// FAST CONNECT FALLBACK: No saved settings available
|
||||
// Use first config (will use SSID from config)
|
||||
bool loaded_fast_connect = this->load_fast_connect_settings_(params);
|
||||
// Fast connect optimization: only use when we have saved BSSID+channel data
|
||||
// Without saved data, try first configured network or use normal flow
|
||||
if (loaded_fast_connect) {
|
||||
ESP_LOGI(TAG, "Starting fast_connect (saved) " LOG_SECRET("'%s'"), params.get_ssid().c_str());
|
||||
this->start_connecting(params, false);
|
||||
} else if (!this->sta_.empty() && !this->sta_[0].get_hidden()) {
|
||||
// No saved data, but have configured networks - try first non-hidden network
|
||||
ESP_LOGI(TAG, "Starting fast_connect (config) " LOG_SECRET("'%s'"), this->sta_[0].get_ssid().c_str());
|
||||
this->selected_sta_index_ = 0;
|
||||
params = this->build_wifi_ap_from_selected_();
|
||||
params = this->build_params_for_current_phase_();
|
||||
this->start_connecting(params, false);
|
||||
} else {
|
||||
// No saved data and (no networks OR first is hidden) - use normal flow
|
||||
this->start_initial_connection_();
|
||||
}
|
||||
this->start_connecting(params, false);
|
||||
#else
|
||||
this->start_scanning();
|
||||
// Without fast_connect: go straight to scanning (or hidden mode if all networks are hidden)
|
||||
this->start_initial_connection_();
|
||||
#endif
|
||||
#ifdef USE_WIFI_AP
|
||||
} else if (this->has_ap()) {
|
||||
@@ -150,8 +412,7 @@ void WiFiComponent::restart_adapter() {
|
||||
ESP_LOGW(TAG, "Restarting adapter");
|
||||
this->wifi_mode_(false, {});
|
||||
delay(100); // NOLINT
|
||||
this->num_retried_ = 0;
|
||||
this->retry_hidden_ = false;
|
||||
// Don't set retry_phase_ or num_retried_ here - state machine handles transitions
|
||||
}
|
||||
|
||||
void WiFiComponent::loop() {
|
||||
@@ -172,21 +433,19 @@ void WiFiComponent::loop() {
|
||||
case WIFI_COMPONENT_STATE_COOLDOWN: {
|
||||
this->status_set_warning(LOG_STR("waiting to reconnect"));
|
||||
if (millis() - this->action_started_ > 5000) {
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
// Safety check: Ensure selected_sta_index_ is valid before retrying
|
||||
// (should already be set by retry_connect(), but check for robustness)
|
||||
// After cooldown, connect based on current retry phase
|
||||
this->reset_selected_ap_to_first_if_invalid_();
|
||||
WiFiAP params = this->build_wifi_ap_from_selected_();
|
||||
this->start_connecting(params, false);
|
||||
#else
|
||||
if (this->retry_hidden_) {
|
||||
this->reset_selected_ap_to_first_if_invalid_();
|
||||
WiFiAP params = this->build_wifi_ap_from_selected_();
|
||||
this->start_connecting(params, false);
|
||||
} else {
|
||||
|
||||
// Check if we need to trigger a scan first
|
||||
if (this->needs_scan_results_() && !this->all_networks_hidden_()) {
|
||||
// Need scan results or no matching networks found - scan/rescan
|
||||
ESP_LOGD(TAG, "Scanning required for phase %s", LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
|
||||
this->start_scanning();
|
||||
} else {
|
||||
// Have everything we need to connect (or all networks are hidden, skip scanning)
|
||||
WiFiAP params = this->build_params_for_current_phase_();
|
||||
this->start_connecting(params, false);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -344,30 +603,44 @@ void WiFiComponent::set_sta(const WiFiAP &ap) {
|
||||
this->selected_sta_index_ = 0;
|
||||
}
|
||||
|
||||
WiFiAP WiFiComponent::build_wifi_ap_from_selected_() const {
|
||||
// PRECONDITION: selected_sta_index_ must be valid (ensured by all callers)
|
||||
WiFiAP WiFiComponent::build_params_for_current_phase_() {
|
||||
const WiFiAP *config = this->get_selected_sta_();
|
||||
assert(config != nullptr);
|
||||
if (config == nullptr) {
|
||||
ESP_LOGE(TAG, "No valid network config (selected_sta_index_=%d, sta_.size()=%zu)",
|
||||
static_cast<int>(this->selected_sta_index_), this->sta_.size());
|
||||
// Return empty params - caller should handle this gracefully
|
||||
return WiFiAP();
|
||||
}
|
||||
|
||||
WiFiAP params = *config;
|
||||
|
||||
// SYNCHRONIZATION: selected_sta_index_ and scan_result_[0] are kept in sync after wifi_scan_done():
|
||||
// - wifi_scan_done() sorts all scan results by priority/RSSI (best first)
|
||||
// - It then finds which sta_[i] config matches scan_result_[0]
|
||||
// - Sets selected_sta_index_ = i to record that matching config
|
||||
// This sync holds until scan_result_ is cleared (e.g., after connection or in reset_for_next_ap_attempt_())
|
||||
if (!this->scan_result_.empty()) {
|
||||
// Override with scan data - network is visible
|
||||
const WiFiScanResult &scan = this->scan_result_[0];
|
||||
params.set_hidden(false);
|
||||
params.set_ssid(scan.get_ssid());
|
||||
params.set_bssid(scan.get_bssid());
|
||||
params.set_channel(scan.get_channel());
|
||||
} else if (params.get_hidden()) {
|
||||
// Hidden network - clear BSSID and channel even if set in config
|
||||
// There might be multiple hidden networks with same SSID but we can't know which is correct
|
||||
// Rely on probe-req with just SSID. Empty channel triggers ALL_CHANNEL_SCAN.
|
||||
params.set_bssid(optional<bssid_t>{});
|
||||
params.set_channel(optional<uint8_t>{});
|
||||
switch (this->retry_phase_) {
|
||||
case WiFiRetryPhase::INITIAL_CONNECT:
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
case WiFiRetryPhase::FAST_CONNECT_CYCLING_APS:
|
||||
#endif
|
||||
// Fast connect phases: use config-only (no scan results)
|
||||
// BSSID/channel from config if user specified them, otherwise empty
|
||||
break;
|
||||
|
||||
case WiFiRetryPhase::EXPLICIT_HIDDEN:
|
||||
case WiFiRetryPhase::RETRY_HIDDEN:
|
||||
// Hidden network mode: clear BSSID/channel to trigger probe request
|
||||
// (both explicit hidden and retry hidden use same behavior)
|
||||
params.set_bssid(optional<bssid_t>{});
|
||||
params.set_channel(optional<uint8_t>{});
|
||||
break;
|
||||
|
||||
case WiFiRetryPhase::SCAN_CONNECTING:
|
||||
// Scan-based phase: always use best scan result (index 0 - highest priority after sorting)
|
||||
if (!this->scan_result_.empty()) {
|
||||
apply_scan_result_to_params(params, this->scan_result_[0]);
|
||||
}
|
||||
break;
|
||||
|
||||
case WiFiRetryPhase::RESTARTING_ADAPTER:
|
||||
// Should not be building params during restart
|
||||
break;
|
||||
}
|
||||
|
||||
return params;
|
||||
@@ -392,7 +665,21 @@ void WiFiComponent::save_wifi_sta(const std::string &ssid, const std::string &pa
|
||||
}
|
||||
|
||||
void WiFiComponent::start_connecting(const WiFiAP &ap, bool two) {
|
||||
ESP_LOGI(TAG, "Connecting to '%s'", ap.get_ssid().c_str());
|
||||
// Log connection attempt at INFO level with priority
|
||||
std::string bssid_formatted;
|
||||
float priority = 0.0f;
|
||||
|
||||
if (ap.get_bssid().has_value()) {
|
||||
bssid_formatted = format_mac_address_pretty(ap.get_bssid().value().data());
|
||||
priority = this->get_sta_priority(ap.get_bssid().value());
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG,
|
||||
"Connecting to " LOG_SECRET("'%s'") " " LOG_SECRET("(%s)") " (priority %.1f, attempt %u/%u in phase %s)...",
|
||||
ap.get_ssid().c_str(), ap.get_bssid().has_value() ? bssid_formatted.c_str() : LOG_STR_LITERAL("any"),
|
||||
priority, this->num_retried_ + 1, get_max_retries_for_phase(this->retry_phase_),
|
||||
LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
|
||||
|
||||
#ifdef ESPHOME_LOG_HAS_VERBOSE
|
||||
ESP_LOGV(TAG, "Connection Params:");
|
||||
ESP_LOGV(TAG, " SSID: '%s'", ap.get_ssid().c_str());
|
||||
@@ -565,8 +852,39 @@ void WiFiComponent::start_scanning() {
|
||||
this->state_ = WIFI_COMPONENT_STATE_STA_SCANNING;
|
||||
}
|
||||
|
||||
// Helper function for WiFi scan result comparison
|
||||
// Returns true if 'a' should be placed before 'b' in the sorted order
|
||||
/// Comparator for WiFi scan result sorting - determines which network should be tried first
|
||||
/// Returns true if 'a' should be placed before 'b' in the sorted order (a is "better" than b)
|
||||
///
|
||||
/// Sorting logic (in priority order):
|
||||
/// 1. Matching networks always ranked before non-matching networks
|
||||
/// 2. For matching networks: Priority first (CRITICAL - tracks failure history)
|
||||
/// 3. RSSI as tiebreaker for equal priority or non-matching networks
|
||||
///
|
||||
/// WHY PRIORITY MUST BE CHECKED FIRST:
|
||||
/// The priority field tracks connection failure history via priority degradation:
|
||||
/// - Initial priority: 0.0 (from config or default)
|
||||
/// - Each connection failure: priority -= 1.0 (becomes -1.0, -2.0, -3.0, etc.)
|
||||
/// - Failed BSSIDs sorted lower → naturally try different BSSID on next scan
|
||||
///
|
||||
/// This enables automatic BSSID cycling for various real-world failure scenarios:
|
||||
/// - Crashed/hung AP (visible but not responding)
|
||||
/// - Misconfigured mesh node (accepts auth but no DHCP/routing)
|
||||
/// - Capacity limits (AP refuses new clients)
|
||||
/// - Rogue AP (same SSID, wrong password or malicious)
|
||||
/// - Intermittent hardware issues (flaky radio, overheating)
|
||||
///
|
||||
/// Example mesh network: 3 APs with same SSID "home", all at priority 0.0 initially
|
||||
/// - Try strongest BSSID A (sorted by RSSI) → fails → priority A becomes -1.0
|
||||
/// - Next scan: BSSID B and C (priority 0.0) sorted BEFORE A (priority -1.0)
|
||||
/// - Try next strongest BSSID B → succeeds or fails and gets deprioritized
|
||||
/// - System naturally cycles through all BSSIDs via priority degradation
|
||||
/// - Eventually finds working AP or tries all options before restarting adapter
|
||||
///
|
||||
/// If we checked RSSI first (Bug in PR #9963):
|
||||
/// - Same failed BSSID would keep being selected if it has strongest signal
|
||||
/// - Device stuck connecting to crashed AP with -30dBm while working AP at -50dBm ignored
|
||||
/// - Priority degradation would be useless
|
||||
/// - Mesh networks would never recover from single AP failure
|
||||
[[nodiscard]] inline static bool wifi_scan_result_is_better(const WiFiScanResult &a, const WiFiScanResult &b) {
|
||||
// Matching networks always come before non-matching
|
||||
if (a.get_matches() && !b.get_matches())
|
||||
@@ -574,21 +892,13 @@ void WiFiComponent::start_scanning() {
|
||||
if (!a.get_matches() && b.get_matches())
|
||||
return false;
|
||||
|
||||
if (a.get_matches() && b.get_matches()) {
|
||||
// For APs with the same SSID, always prefer stronger signal
|
||||
// This helps with mesh networks and multiple APs
|
||||
if (a.get_ssid() == b.get_ssid()) {
|
||||
return a.get_rssi() > b.get_rssi();
|
||||
}
|
||||
|
||||
// For different SSIDs, check priority first
|
||||
if (a.get_priority() != b.get_priority())
|
||||
return a.get_priority() > b.get_priority();
|
||||
// If priorities are equal, prefer stronger signal
|
||||
return a.get_rssi() > b.get_rssi();
|
||||
// Both matching: check priority first (tracks connection failures via priority degradation)
|
||||
// Priority is decreased when a BSSID fails to connect, so lower priority = previously failed
|
||||
if (a.get_matches() && b.get_matches() && a.get_priority() != b.get_priority()) {
|
||||
return a.get_priority() > b.get_priority();
|
||||
}
|
||||
|
||||
// Both don't match - sort by signal strength
|
||||
// Use RSSI as tiebreaker (for equal-priority matching networks or all non-matching networks)
|
||||
return a.get_rssi() > b.get_rssi();
|
||||
}
|
||||
|
||||
@@ -623,10 +933,8 @@ __attribute__((noinline)) static void log_scan_result(const WiFiScanResult &res)
|
||||
ESP_LOGI(TAG, "- '%s' %s" LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(),
|
||||
res.get_is_hidden() ? LOG_STR_LITERAL("(HIDDEN) ") : LOG_STR_LITERAL(""), bssid_s,
|
||||
LOG_STR_ARG(get_signal_bars(res.get_rssi())));
|
||||
ESP_LOGD(TAG,
|
||||
" Channel: %u\n"
|
||||
" RSSI: %d dB",
|
||||
res.get_channel(), res.get_rssi());
|
||||
ESP_LOGD(TAG, " Channel: %2u, RSSI: %3d dB, Priority: %4.1f", res.get_channel(), res.get_rssi(),
|
||||
res.get_priority());
|
||||
} else {
|
||||
ESP_LOGD(TAG, "- " LOG_SECRET("'%s'") " " LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(), bssid_s,
|
||||
LOG_STR_ARG(get_signal_bars(res.get_rssi())));
|
||||
@@ -675,34 +983,36 @@ void WiFiComponent::check_scanning_finished() {
|
||||
// SYNCHRONIZATION POINT: Establish link between scan_result_[0] and selected_sta_index_
|
||||
// After sorting, scan_result_[0] contains the best network. Now find which sta_[i] config
|
||||
// matches that network and record it in selected_sta_index_. This keeps the two indices
|
||||
// synchronized so build_wifi_ap_from_selected_() can safely use both to build connection parameters.
|
||||
// synchronized so build_params_for_current_phase_() can safely use both to build connection parameters.
|
||||
const WiFiScanResult &scan_res = this->scan_result_[0];
|
||||
if (!scan_res.get_matches()) {
|
||||
ESP_LOGW(TAG, "No matching network found");
|
||||
this->retry_connect();
|
||||
return;
|
||||
}
|
||||
|
||||
bool found_match = false;
|
||||
for (size_t i = 0; i < this->sta_.size(); i++) {
|
||||
if (scan_res.matches(this->sta_[i])) {
|
||||
// Safe cast: sta_.size() limited to MAX_WIFI_NETWORKS (127) in __init__.py validation
|
||||
// No overflow check needed - YAML validation prevents >127 networks
|
||||
this->selected_sta_index_ = static_cast<int8_t>(i); // Links scan_result_[0] with sta_[i]
|
||||
found_match = true;
|
||||
break;
|
||||
if (scan_res.get_matches()) {
|
||||
for (size_t i = 0; i < this->sta_.size(); i++) {
|
||||
if (scan_res.matches(this->sta_[i])) {
|
||||
// Safe cast: sta_.size() limited to MAX_WIFI_NETWORKS (127) in __init__.py validation
|
||||
// No overflow check needed - YAML validation prevents >127 networks
|
||||
this->selected_sta_index_ = static_cast<int8_t>(i); // Links scan_result_[0] with sta_[i]
|
||||
found_match = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!found_match) {
|
||||
ESP_LOGW(TAG, "No matching network found");
|
||||
this->retry_connect();
|
||||
return;
|
||||
// No scan results matched our configured networks - transition directly to hidden mode
|
||||
// Don't call retry_connect() since we never attempted a connection (no BSSID to penalize)
|
||||
this->transition_to_phase_(WiFiRetryPhase::RETRY_HIDDEN);
|
||||
// Now start connection attempt in hidden mode
|
||||
} else if (this->transition_to_phase_(WiFiRetryPhase::SCAN_CONNECTING)) {
|
||||
return; // scan started, wait for next loop iteration
|
||||
}
|
||||
|
||||
yield();
|
||||
|
||||
WiFiAP params = this->build_wifi_ap_from_selected_();
|
||||
WiFiAP params = this->build_params_for_current_phase_();
|
||||
// Ensure we're in SCAN_CONNECTING phase when connecting with scan results
|
||||
// (needed when scan was started directly without transition_to_phase_, e.g., initial scan)
|
||||
this->start_connecting(params, false);
|
||||
}
|
||||
|
||||
@@ -724,11 +1034,14 @@ void WiFiComponent::check_connecting_finished() {
|
||||
ESP_LOGI(TAG, "Connected");
|
||||
// Warn if we had to retry with hidden network mode for a network that's not marked hidden
|
||||
// Only warn if we actually connected without scan data (SSID only), not if scan succeeded on retry
|
||||
if (const WiFiAP *config = this->get_selected_sta_();
|
||||
this->retry_hidden_ && config && !config->get_hidden() && this->scan_result_.empty()) {
|
||||
ESP_LOGW(TAG, "Network '%s' should be marked as hidden", config->get_ssid().c_str());
|
||||
if (const WiFiAP *config = this->get_selected_sta_(); this->retry_phase_ == WiFiRetryPhase::RETRY_HIDDEN &&
|
||||
config && !config->get_hidden() &&
|
||||
this->scan_result_.empty()) {
|
||||
ESP_LOGW(TAG, LOG_SECRET("'%s'") " should be marked hidden", config->get_ssid().c_str());
|
||||
}
|
||||
this->retry_hidden_ = false;
|
||||
// Reset to initial phase on successful connection (don't log transition, just reset state)
|
||||
this->retry_phase_ = WiFiRetryPhase::INITIAL_CONNECT;
|
||||
this->num_retried_ = 0;
|
||||
|
||||
this->print_connect_params_();
|
||||
|
||||
@@ -796,70 +1109,340 @@ void WiFiComponent::check_connecting_finished() {
|
||||
this->retry_connect();
|
||||
}
|
||||
|
||||
void WiFiComponent::retry_connect() {
|
||||
if (const WiFiAP *config = this->get_selected_sta_(); config && config->get_bssid()) {
|
||||
auto bssid = *config->get_bssid();
|
||||
float priority = this->get_sta_priority(bssid);
|
||||
this->set_sta_priority(bssid, priority - 1.0f);
|
||||
/// Determine the next retry phase based on current state and failure conditions
|
||||
/// This function examines the current retry phase, number of retries, and failure reasons
|
||||
/// to decide what phase to move to next. It does not modify any state - it only returns
|
||||
/// the recommended next phase.
|
||||
///
|
||||
/// @return The next WiFiRetryPhase to transition to (may be same as current phase if should retry)
|
||||
WiFiRetryPhase WiFiComponent::determine_next_phase_() {
|
||||
switch (this->retry_phase_) {
|
||||
case WiFiRetryPhase::INITIAL_CONNECT:
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
case WiFiRetryPhase::FAST_CONNECT_CYCLING_APS:
|
||||
// INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS: no retries, try next AP or fall back to scan
|
||||
if (this->selected_sta_index_ < static_cast<int8_t>(this->sta_.size()) - 1) {
|
||||
return WiFiRetryPhase::FAST_CONNECT_CYCLING_APS; // Move to next AP
|
||||
}
|
||||
#endif
|
||||
// No more APs to try, fall back to scan
|
||||
return WiFiRetryPhase::SCAN_CONNECTING;
|
||||
|
||||
case WiFiRetryPhase::EXPLICIT_HIDDEN: {
|
||||
// Try all explicitly hidden networks before scanning
|
||||
if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_SSID) {
|
||||
return WiFiRetryPhase::EXPLICIT_HIDDEN; // Keep retrying same SSID
|
||||
}
|
||||
|
||||
// Exhausted retries on current SSID - check for more explicitly hidden networks
|
||||
// Stop when we reach a visible network (proceed to scanning)
|
||||
size_t next_index = this->selected_sta_index_ + 1;
|
||||
if (next_index < this->sta_.size() && this->sta_[next_index].get_hidden()) {
|
||||
// Found another explicitly hidden network
|
||||
return WiFiRetryPhase::EXPLICIT_HIDDEN;
|
||||
}
|
||||
|
||||
// No more consecutive explicitly hidden networks - proceed to scanning
|
||||
return WiFiRetryPhase::SCAN_CONNECTING;
|
||||
}
|
||||
|
||||
case WiFiRetryPhase::SCAN_CONNECTING:
|
||||
// If scan found no matching networks, skip to hidden network mode
|
||||
if (!this->scan_result_.empty() && !this->scan_result_[0].get_matches()) {
|
||||
return WiFiRetryPhase::RETRY_HIDDEN;
|
||||
}
|
||||
|
||||
if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_BSSID) {
|
||||
return WiFiRetryPhase::SCAN_CONNECTING; // Keep retrying same BSSID
|
||||
}
|
||||
|
||||
// Exhausted retries on current BSSID (scan_result_[0])
|
||||
// Its priority has been decreased, so on next scan it will be sorted lower
|
||||
// and we'll try the next best BSSID.
|
||||
// Check if there are any potentially hidden networks to try
|
||||
if (this->find_next_hidden_sta_(-1, !this->went_through_explicit_hidden_phase_()) >= 0) {
|
||||
return WiFiRetryPhase::RETRY_HIDDEN; // Found hidden networks to try
|
||||
}
|
||||
// No hidden networks - skip directly to restart/rescan
|
||||
if (this->is_captive_portal_active_() || this->is_esp32_improv_active_()) {
|
||||
return this->went_through_explicit_hidden_phase_() ? WiFiRetryPhase::EXPLICIT_HIDDEN
|
||||
: WiFiRetryPhase::SCAN_CONNECTING;
|
||||
}
|
||||
return WiFiRetryPhase::RESTARTING_ADAPTER;
|
||||
|
||||
case WiFiRetryPhase::RETRY_HIDDEN:
|
||||
// If no hidden SSIDs to try (selected_sta_index_ == -1), skip directly to rescan
|
||||
if (this->selected_sta_index_ >= 0) {
|
||||
if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_SSID) {
|
||||
return WiFiRetryPhase::RETRY_HIDDEN; // Keep retrying same SSID
|
||||
}
|
||||
|
||||
// Exhausted retries on current SSID - check if there are more potentially hidden SSIDs to try
|
||||
if (this->selected_sta_index_ < static_cast<int8_t>(this->sta_.size()) - 1) {
|
||||
// More SSIDs available - stay in RETRY_HIDDEN, advance will happen in retry_connect()
|
||||
return WiFiRetryPhase::RETRY_HIDDEN;
|
||||
}
|
||||
}
|
||||
// Exhausted all potentially hidden SSIDs - rescan to try next BSSID
|
||||
// If captive portal/improv is active, skip adapter restart and go back to start
|
||||
// Otherwise restart adapter to clear any stuck state
|
||||
if (this->is_captive_portal_active_() || this->is_esp32_improv_active_()) {
|
||||
// Go back to explicit hidden if we went through it initially, otherwise scan
|
||||
return this->went_through_explicit_hidden_phase_() ? WiFiRetryPhase::EXPLICIT_HIDDEN
|
||||
: WiFiRetryPhase::SCAN_CONNECTING;
|
||||
}
|
||||
|
||||
// Restart adapter
|
||||
return WiFiRetryPhase::RESTARTING_ADAPTER;
|
||||
|
||||
case WiFiRetryPhase::RESTARTING_ADAPTER:
|
||||
// After restart, go back to explicit hidden if we went through it initially, otherwise scan
|
||||
return this->went_through_explicit_hidden_phase_() ? WiFiRetryPhase::EXPLICIT_HIDDEN
|
||||
: WiFiRetryPhase::SCAN_CONNECTING;
|
||||
}
|
||||
|
||||
delay(10);
|
||||
if (!this->is_captive_portal_active_() && !this->is_esp32_improv_active_() &&
|
||||
(this->num_retried_ > 3 || this->error_from_callback_)) {
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
// No empty check needed - YAML validation requires at least one network for fast_connect
|
||||
if (this->trying_loaded_ap_) {
|
||||
this->trying_loaded_ap_ = false;
|
||||
this->selected_sta_index_ = 0; // Retry from the first configured AP
|
||||
this->reset_for_next_ap_attempt_();
|
||||
} else if (this->selected_sta_index_ >= static_cast<int8_t>(this->sta_.size()) - 1) {
|
||||
// Safe cast: sta_.size() limited to MAX_WIFI_NETWORKS (127) in __init__.py validation
|
||||
// Exhausted all configured APs, restart adapter and cycle back to first
|
||||
// Restart clears any stuck WiFi driver state
|
||||
// Each AP is tried with config data only (SSID + optional BSSID/channel if user configured them)
|
||||
// Typically SSID only, which triggers ESP-IDF internal scanning
|
||||
ESP_LOGW(TAG, "No more APs to try");
|
||||
this->selected_sta_index_ = 0;
|
||||
this->reset_for_next_ap_attempt_();
|
||||
this->restart_adapter();
|
||||
} else {
|
||||
// Try next AP
|
||||
this->selected_sta_index_++;
|
||||
this->reset_for_next_ap_attempt_();
|
||||
}
|
||||
#else
|
||||
if (this->num_retried_ > 5) {
|
||||
// If retry failed for more than 5 times, let's restart STA
|
||||
this->restart_adapter();
|
||||
} else {
|
||||
// Try hidden networks after 3 failed retries
|
||||
ESP_LOGD(TAG, "Retrying with hidden networks");
|
||||
this->retry_hidden_ = true;
|
||||
this->num_retried_++;
|
||||
}
|
||||
#endif
|
||||
} else {
|
||||
this->num_retried_++;
|
||||
// Should never reach here
|
||||
return WiFiRetryPhase::SCAN_CONNECTING;
|
||||
}
|
||||
|
||||
/// Transition from current retry phase to a new phase with logging and phase-specific setup
|
||||
/// This function handles the actual state change, including:
|
||||
/// - Logging the phase transition
|
||||
/// - Resetting the retry counter
|
||||
/// - Performing phase-specific initialization (e.g., advancing AP index, starting scans)
|
||||
///
|
||||
/// @param new_phase The phase we're transitioning TO
|
||||
/// @return true if an async scan was started (caller should wait for completion)
|
||||
/// false if no scan started (caller can proceed with connection attempt)
|
||||
bool WiFiComponent::transition_to_phase_(WiFiRetryPhase new_phase) {
|
||||
WiFiRetryPhase old_phase = this->retry_phase_;
|
||||
|
||||
// No-op if staying in same phase
|
||||
if (old_phase == new_phase) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, "Retry phase: %s → %s", LOG_STR_ARG(retry_phase_to_log_string(old_phase)),
|
||||
LOG_STR_ARG(retry_phase_to_log_string(new_phase)));
|
||||
|
||||
this->retry_phase_ = new_phase;
|
||||
this->num_retried_ = 0; // Reset retry counter on phase change
|
||||
|
||||
// Phase-specific setup
|
||||
switch (new_phase) {
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
case WiFiRetryPhase::FAST_CONNECT_CYCLING_APS:
|
||||
// Move to next configured AP - clear old scan data so new AP is tried with config only
|
||||
this->selected_sta_index_++;
|
||||
this->scan_result_.clear();
|
||||
break;
|
||||
#endif
|
||||
|
||||
case WiFiRetryPhase::EXPLICIT_HIDDEN:
|
||||
// Starting explicit hidden phase - reset to first network
|
||||
this->selected_sta_index_ = 0;
|
||||
break;
|
||||
|
||||
case WiFiRetryPhase::SCAN_CONNECTING:
|
||||
// Transitioning to scan-based connection
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
if (old_phase == WiFiRetryPhase::FAST_CONNECT_CYCLING_APS) {
|
||||
ESP_LOGI(TAG, "Fast connect exhausted, falling back to scan");
|
||||
}
|
||||
#endif
|
||||
// Trigger scan if we don't have scan results OR if transitioning from phases that need fresh scan
|
||||
if (this->scan_result_.empty() || old_phase == WiFiRetryPhase::EXPLICIT_HIDDEN ||
|
||||
old_phase == WiFiRetryPhase::RETRY_HIDDEN || old_phase == WiFiRetryPhase::RESTARTING_ADAPTER) {
|
||||
this->selected_sta_index_ = -1; // Will be set after scan completes
|
||||
this->start_scanning();
|
||||
return true; // Started scan, wait for completion
|
||||
}
|
||||
// Already have scan results - selected_sta_index_ should already be synchronized
|
||||
// (set in check_scanning_finished() when scan completed)
|
||||
// No need to reset it here
|
||||
break;
|
||||
|
||||
case WiFiRetryPhase::RETRY_HIDDEN:
|
||||
// Starting hidden mode - find first SSID that wasn't in scan results
|
||||
if (old_phase == WiFiRetryPhase::SCAN_CONNECTING) {
|
||||
// Keep scan results so we can skip SSIDs that were visible in the scan
|
||||
// Don't clear scan_result_ - we need it to know which SSIDs are NOT hidden
|
||||
|
||||
// If first network is marked hidden, we went through EXPLICIT_HIDDEN phase
|
||||
// In that case, skip networks marked hidden:true (already tried)
|
||||
// Otherwise, include them (they haven't been tried yet)
|
||||
this->selected_sta_index_ = this->find_next_hidden_sta_(-1, !this->went_through_explicit_hidden_phase_());
|
||||
|
||||
if (this->selected_sta_index_ == -1) {
|
||||
ESP_LOGD(TAG, "All SSIDs visible or already tried, skipping hidden mode");
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case WiFiRetryPhase::RESTARTING_ADAPTER:
|
||||
this->restart_adapter();
|
||||
// Return true to indicate we should wait (go to COOLDOWN) instead of immediately connecting
|
||||
return true;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return false; // Did not start scan, can proceed with connection
|
||||
}
|
||||
|
||||
/// Log failed connection attempt and decrease BSSID priority to avoid repeated failures
|
||||
/// This function identifies which BSSID was attempted (from scan results or config),
|
||||
/// decreases its priority by 1.0 to discourage future attempts, and logs the change.
|
||||
///
|
||||
/// The priority degradation system ensures that failed BSSIDs are automatically sorted
|
||||
/// lower in subsequent scans, naturally cycling through different APs without explicit
|
||||
/// BSSID tracking within a scan cycle.
|
||||
///
|
||||
/// Priority sources:
|
||||
/// - SCAN_CONNECTING phase: Uses BSSID from scan_result_[0] (best match after sorting)
|
||||
/// - Other phases: Uses BSSID from config if explicitly specified by user or fast_connect
|
||||
///
|
||||
/// If no BSSID is available (SSID-only connection), priority adjustment is skipped.
|
||||
void WiFiComponent::log_and_adjust_priority_for_failed_connect_() {
|
||||
// Determine which BSSID we tried to connect to
|
||||
optional<bssid_t> failed_bssid;
|
||||
|
||||
if (this->retry_phase_ == WiFiRetryPhase::SCAN_CONNECTING && !this->scan_result_.empty()) {
|
||||
// Scan-based phase: always use best result (index 0)
|
||||
failed_bssid = this->scan_result_[0].get_bssid();
|
||||
} else if (const WiFiAP *config = this->get_selected_sta_(); config && config->get_bssid()) {
|
||||
// Config has specific BSSID (fast_connect or user-specified)
|
||||
failed_bssid = *config->get_bssid();
|
||||
}
|
||||
|
||||
if (!failed_bssid.has_value()) {
|
||||
return; // No BSSID to penalize
|
||||
}
|
||||
|
||||
// Decrease priority to avoid repeatedly trying the same failed BSSID
|
||||
float old_priority = this->get_sta_priority(failed_bssid.value());
|
||||
float new_priority = old_priority - 1.0f;
|
||||
this->set_sta_priority(failed_bssid.value(), new_priority);
|
||||
|
||||
// Get SSID for logging
|
||||
std::string ssid;
|
||||
if (this->retry_phase_ == WiFiRetryPhase::SCAN_CONNECTING && !this->scan_result_.empty()) {
|
||||
ssid = this->scan_result_[0].get_ssid();
|
||||
} else if (const WiFiAP *config = this->get_selected_sta_()) {
|
||||
ssid = config->get_ssid();
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, "Failed " LOG_SECRET("'%s'") " " LOG_SECRET("(%s)") ", priority %.1f → %.1f", ssid.c_str(),
|
||||
format_mac_address_pretty(failed_bssid.value().data()).c_str(), old_priority, new_priority);
|
||||
}
|
||||
|
||||
/// Handle target advancement or retry counter increment when staying in the same phase
|
||||
/// This function is called when a connection attempt fails and determine_next_phase_() indicates
|
||||
/// we should stay in the current phase. It decides whether to:
|
||||
/// - Advance to the next target (AP in fast_connect, SSID in hidden mode)
|
||||
/// - Or increment the retry counter to try the same target again
|
||||
///
|
||||
/// Phase-specific behavior:
|
||||
/// - FAST_CONNECT_CYCLING_APS: Always advance to next AP (no retries per AP)
|
||||
/// - RETRY_HIDDEN: Advance to next SSID after exhausting retries on current SSID
|
||||
/// - Other phases: Increment retry counter (will retry same target)
|
||||
void WiFiComponent::advance_to_next_target_or_increment_retry_() {
|
||||
WiFiRetryPhase current_phase = this->retry_phase_;
|
||||
|
||||
// Check if we need to advance to next AP/SSID within the same phase
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
if (current_phase == WiFiRetryPhase::FAST_CONNECT_CYCLING_APS) {
|
||||
// Fast connect: always advance to next AP (no retries per AP)
|
||||
this->selected_sta_index_++;
|
||||
this->num_retried_ = 0;
|
||||
ESP_LOGD(TAG, "Next AP in %s", LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (current_phase == WiFiRetryPhase::EXPLICIT_HIDDEN && this->num_retried_ + 1 >= WIFI_RETRY_COUNT_PER_SSID) {
|
||||
// Explicit hidden: exhausted retries on current SSID, find next explicitly hidden network
|
||||
// Stop when we reach a visible network (proceed to scanning)
|
||||
size_t next_index = this->selected_sta_index_ + 1;
|
||||
if (next_index < this->sta_.size() && this->sta_[next_index].get_hidden()) {
|
||||
this->selected_sta_index_ = static_cast<int8_t>(next_index);
|
||||
this->num_retried_ = 0;
|
||||
ESP_LOGD(TAG, "Next explicit hidden network at index %d", static_cast<int>(next_index));
|
||||
return;
|
||||
}
|
||||
// No more consecutive explicit hidden networks found - fall through to trigger phase change
|
||||
}
|
||||
|
||||
if (current_phase == WiFiRetryPhase::RETRY_HIDDEN && this->num_retried_ + 1 >= WIFI_RETRY_COUNT_PER_SSID) {
|
||||
// Hidden mode: exhausted retries on current SSID, find next potentially hidden SSID
|
||||
// If first network is marked hidden, we went through EXPLICIT_HIDDEN phase
|
||||
// In that case, skip networks marked hidden:true (already tried)
|
||||
// Otherwise, include them (they haven't been tried yet)
|
||||
int8_t next_index =
|
||||
this->find_next_hidden_sta_(this->selected_sta_index_, !this->went_through_explicit_hidden_phase_());
|
||||
if (next_index != -1) {
|
||||
// Found another potentially hidden SSID
|
||||
this->selected_sta_index_ = next_index;
|
||||
this->num_retried_ = 0;
|
||||
return;
|
||||
}
|
||||
// No more potentially hidden SSIDs - set selected_sta_index_ to -1 to trigger phase change
|
||||
// This ensures determine_next_phase_() will skip the RETRY_HIDDEN logic and transition out
|
||||
this->selected_sta_index_ = -1;
|
||||
// Return early - phase change will happen on next wifi_loop() iteration
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't increment retry counter if we're in a scan phase with no valid targets
|
||||
if (this->needs_scan_results_()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Increment retry counter to try the same target again
|
||||
this->num_retried_++;
|
||||
ESP_LOGD(TAG, "Retry attempt %u/%u in phase %s", this->num_retried_ + 1,
|
||||
get_max_retries_for_phase(this->retry_phase_), LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
|
||||
}
|
||||
|
||||
void WiFiComponent::retry_connect() {
|
||||
this->log_and_adjust_priority_for_failed_connect_();
|
||||
|
||||
delay(10);
|
||||
|
||||
// Determine next retry phase based on current state
|
||||
WiFiRetryPhase current_phase = this->retry_phase_;
|
||||
WiFiRetryPhase next_phase = this->determine_next_phase_();
|
||||
|
||||
// Handle phase transitions (transition_to_phase_ handles same-phase no-op internally)
|
||||
if (this->transition_to_phase_(next_phase)) {
|
||||
return; // Wait for scan to complete
|
||||
}
|
||||
|
||||
if (next_phase == current_phase) {
|
||||
this->advance_to_next_target_or_increment_retry_();
|
||||
}
|
||||
|
||||
this->error_from_callback_ = false;
|
||||
|
||||
if (this->state_ == WIFI_COMPONENT_STATE_STA_CONNECTING) {
|
||||
yield();
|
||||
this->state_ = WIFI_COMPONENT_STATE_STA_CONNECTING_2;
|
||||
WiFiAP params = this->build_wifi_ap_from_selected_();
|
||||
this->start_connecting(params, true);
|
||||
return;
|
||||
// Check if we have a valid target before building params
|
||||
// After exhausting all networks in a phase, selected_sta_index_ may be -1
|
||||
// In that case, skip connection and let next wifi_loop() handle phase transition
|
||||
if (this->selected_sta_index_ >= 0) {
|
||||
this->state_ = WIFI_COMPONENT_STATE_STA_CONNECTING_2;
|
||||
WiFiAP params = this->build_params_for_current_phase_();
|
||||
this->start_connecting(params, true);
|
||||
return;
|
||||
}
|
||||
// No valid target - fall through to set state to allow phase transition
|
||||
}
|
||||
|
||||
this->state_ = WIFI_COMPONENT_STATE_COOLDOWN;
|
||||
this->action_started_ = millis();
|
||||
}
|
||||
|
||||
bool WiFiComponent::can_proceed() {
|
||||
if (!this->has_sta() || this->state_ == WIFI_COMPONENT_STATE_DISABLED || this->ap_setup_) {
|
||||
return true;
|
||||
}
|
||||
return this->is_connected();
|
||||
}
|
||||
void WiFiComponent::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
|
||||
bool WiFiComponent::is_connected() {
|
||||
return this->state_ == WIFI_COMPONENT_STATE_STA_CONNECTED &&
|
||||
|
||||
@@ -94,6 +94,24 @@ enum class WiFiSTAConnectStatus : int {
|
||||
ERROR_CONNECT_FAILED,
|
||||
};
|
||||
|
||||
/// Tracks the current retry strategy/phase for WiFi connection attempts
|
||||
enum class WiFiRetryPhase : uint8_t {
|
||||
/// Initial connection attempt (varies based on fast_connect setting)
|
||||
INITIAL_CONNECT,
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
/// Fast connect mode: cycling through configured APs (config-only, no scan)
|
||||
FAST_CONNECT_CYCLING_APS,
|
||||
#endif
|
||||
/// Explicitly hidden networks (user marked as hidden, try before scanning)
|
||||
EXPLICIT_HIDDEN,
|
||||
/// Scan-based: connecting to best AP from scan results
|
||||
SCAN_CONNECTING,
|
||||
/// Retry networks not found in scan (might be hidden)
|
||||
RETRY_HIDDEN,
|
||||
/// Restarting WiFi adapter to clear stuck state
|
||||
RESTARTING_ADAPTER,
|
||||
};
|
||||
|
||||
/// Struct for setting static IPs in WiFiComponent.
|
||||
struct ManualIP {
|
||||
network::IPAddress static_ip;
|
||||
@@ -251,8 +269,6 @@ class WiFiComponent : public Component {
|
||||
|
||||
void retry_connect();
|
||||
|
||||
bool can_proceed() override;
|
||||
|
||||
void set_reboot_timeout(uint32_t reboot_timeout);
|
||||
|
||||
bool is_connected();
|
||||
@@ -341,8 +357,37 @@ class WiFiComponent : public Component {
|
||||
#endif // USE_WIFI_AP
|
||||
|
||||
void print_connect_params_();
|
||||
WiFiAP build_wifi_ap_from_selected_() const;
|
||||
WiFiAP build_params_for_current_phase_();
|
||||
|
||||
/// Determine next retry phase based on current state and failure conditions
|
||||
WiFiRetryPhase determine_next_phase_();
|
||||
/// Transition to a new retry phase with logging
|
||||
/// Returns true if a scan was started (caller should wait), false otherwise
|
||||
bool transition_to_phase_(WiFiRetryPhase new_phase);
|
||||
/// Check if we need valid scan results for the current phase but don't have any
|
||||
/// Returns true if the phase requires scan results but they're missing or don't match
|
||||
bool needs_scan_results_() const;
|
||||
/// Check if we went through EXPLICIT_HIDDEN phase (first network is marked hidden)
|
||||
/// Used in RETRY_HIDDEN to determine whether to skip explicitly hidden networks
|
||||
bool went_through_explicit_hidden_phase_() const;
|
||||
/// Find the index of the first non-hidden network
|
||||
/// Returns where EXPLICIT_HIDDEN phase would have stopped, or -1 if all networks are hidden
|
||||
int8_t find_first_non_hidden_index_() const;
|
||||
/// Check if an SSID was seen in the most recent scan results
|
||||
/// Used to skip hidden mode for SSIDs we know are visible
|
||||
bool ssid_was_seen_in_scan_(const std::string &ssid) const;
|
||||
/// Find next SSID that wasn't in scan results (might be hidden)
|
||||
/// Returns index of next potentially hidden SSID, or -1 if none found
|
||||
/// @param start_index Start searching from index after this (-1 to start from beginning)
|
||||
/// @param include_explicit_hidden If true, include SSIDs marked hidden:true. If false, only find truly hidden SSIDs.
|
||||
int8_t find_next_hidden_sta_(int8_t start_index, bool include_explicit_hidden = true);
|
||||
/// Log failed connection and decrease BSSID priority to avoid repeated attempts
|
||||
void log_and_adjust_priority_for_failed_connect_();
|
||||
/// Advance to next target (AP/SSID) within current phase, or increment retry counter
|
||||
/// Called when staying in the same phase after a failed connection attempt
|
||||
void advance_to_next_target_or_increment_retry_();
|
||||
/// Start initial connection - either scan or connect directly to hidden networks
|
||||
void start_initial_connection_();
|
||||
const WiFiAP *get_selected_sta_() const {
|
||||
if (this->selected_sta_index_ >= 0 && static_cast<size_t>(this->selected_sta_index_) < this->sta_.size()) {
|
||||
return &this->sta_[this->selected_sta_index_];
|
||||
@@ -356,14 +401,15 @@ class WiFiComponent : public Component {
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
// Reset state for next fast connect AP attempt
|
||||
// Clears old scan data so the new AP is tried with config only (SSID without specific BSSID/channel)
|
||||
void reset_for_next_ap_attempt_() {
|
||||
this->num_retried_ = 0;
|
||||
this->scan_result_.clear();
|
||||
bool all_networks_hidden_() const {
|
||||
if (this->sta_.empty())
|
||||
return false;
|
||||
for (const auto &ap : this->sta_) {
|
||||
if (!ap.get_hidden())
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
void wifi_loop_();
|
||||
bool wifi_mode_(optional<bool> sta, optional<bool> ap);
|
||||
@@ -443,20 +489,18 @@ class WiFiComponent : public Component {
|
||||
// Group all 8-bit values together
|
||||
WiFiComponentState state_{WIFI_COMPONENT_STATE_OFF};
|
||||
WiFiPowerSaveMode power_save_{WIFI_POWER_SAVE_NONE};
|
||||
WiFiRetryPhase retry_phase_{WiFiRetryPhase::INITIAL_CONNECT};
|
||||
uint8_t num_retried_{0};
|
||||
// Index into sta_ array for the currently selected AP configuration (-1 = none selected)
|
||||
// Used to access password, manual_ip, priority, EAP settings, and hidden flag
|
||||
// int8_t limits to 127 APs (enforced in __init__.py via MAX_WIFI_NETWORKS)
|
||||
int8_t selected_sta_index_{-1};
|
||||
|
||||
#if USE_NETWORK_IPV6
|
||||
uint8_t num_ipv6_addresses_{0};
|
||||
#endif /* USE_NETWORK_IPV6 */
|
||||
|
||||
// Group all boolean values together
|
||||
#ifdef USE_WIFI_FAST_CONNECT
|
||||
bool trying_loaded_ap_{false};
|
||||
#endif
|
||||
bool retry_hidden_{false};
|
||||
bool has_ap_{false};
|
||||
bool handled_connected_state_{false};
|
||||
bool error_from_callback_{false};
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <zephyr/random/random.h>
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/defines.h"
|
||||
|
||||
namespace esphome {
|
||||
|
||||
@@ -25,7 +26,14 @@ void arch_init() {
|
||||
wdt_config.window.max = 2000;
|
||||
wdt_channel_id = wdt_install_timeout(WDT, &wdt_config);
|
||||
if (wdt_channel_id >= 0) {
|
||||
wdt_setup(WDT, WDT_OPT_PAUSE_HALTED_BY_DBG | WDT_OPT_PAUSE_IN_SLEEP);
|
||||
uint8_t options = 0;
|
||||
#ifdef USE_DEBUG
|
||||
options |= WDT_OPT_PAUSE_HALTED_BY_DBG;
|
||||
#endif
|
||||
#ifdef USE_DEEP_SLEEP
|
||||
options |= WDT_OPT_PAUSE_IN_SLEEP;
|
||||
#endif
|
||||
wdt_setup(WDT, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,9 @@ if TYPE_CHECKING:
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# Key for tracking controller count in CORE.data for ControllerRegistry StaticVector sizing
|
||||
KEY_CONTROLLER_REGISTRY_COUNT = "controller_registry_count"
|
||||
|
||||
|
||||
class EsphomeError(Exception):
|
||||
"""General ESPHome exception occurred."""
|
||||
@@ -910,6 +913,11 @@ class EsphomeCore:
|
||||
"""
|
||||
self.platform_counts[platform_name] += 1
|
||||
|
||||
def register_controller(self) -> None:
|
||||
"""Track registration of a Controller for ControllerRegistry StaticVector sizing."""
|
||||
controller_count = self.data.setdefault(KEY_CONTROLLER_REGISTRY_COUNT, 0)
|
||||
self.data[KEY_CONTROLLER_REGISTRY_COUNT] = controller_count + 1
|
||||
|
||||
@property
|
||||
def cpp_main_section(self):
|
||||
from esphome.cpp_generator import statement
|
||||
|
||||
@@ -40,7 +40,12 @@ from esphome.const import (
|
||||
PlatformFramework,
|
||||
__version__ as ESPHOME_VERSION,
|
||||
)
|
||||
from esphome.core import CORE, CoroPriority, coroutine_with_priority
|
||||
from esphome.core import (
|
||||
CORE,
|
||||
KEY_CONTROLLER_REGISTRY_COUNT,
|
||||
CoroPriority,
|
||||
coroutine_with_priority,
|
||||
)
|
||||
from esphome.helpers import (
|
||||
copy_file_if_changed,
|
||||
fnv1a_32bit_hash,
|
||||
@@ -462,6 +467,15 @@ async def _add_platform_defines() -> None:
|
||||
cg.add_define(f"USE_{platform_name.upper()}")
|
||||
|
||||
|
||||
@coroutine_with_priority(CoroPriority.FINAL)
|
||||
async def _add_controller_registry_define() -> None:
|
||||
# Generate StaticVector size for ControllerRegistry
|
||||
controller_count = CORE.data.get(KEY_CONTROLLER_REGISTRY_COUNT, 0)
|
||||
if controller_count > 0:
|
||||
cg.add_define("USE_CONTROLLER_REGISTRY")
|
||||
cg.add_define("CONTROLLER_REGISTRY_MAX", controller_count)
|
||||
|
||||
|
||||
@coroutine_with_priority(CoroPriority.CORE)
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
cg.add_global(cg.global_ns.namespace("esphome").using)
|
||||
@@ -483,6 +497,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
cg.add_define("ESPHOME_COMPONENT_COUNT", len(CORE.component_ids))
|
||||
|
||||
CORE.add_job(_add_platform_defines)
|
||||
CORE.add_job(_add_controller_registry_define)
|
||||
|
||||
CORE.add_job(_add_automations, config)
|
||||
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
#include "controller.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
|
||||
void Controller::setup_controller(bool include_internal) {
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
for (auto *obj : App.get_binary_sensors()) {
|
||||
if (include_internal || !obj->is_internal()) {
|
||||
obj->add_full_state_callback(
|
||||
[this, obj](optional<bool> previous, optional<bool> state) { this->on_binary_sensor_update(obj); });
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_FAN
|
||||
for (auto *obj : App.get_fans()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj]() { this->on_fan_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_LIGHT
|
||||
for (auto *obj : App.get_lights()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_new_remote_values_callback([this, obj]() { this->on_light_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_SENSOR
|
||||
for (auto *obj : App.get_sensors()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj](float state) { this->on_sensor_update(obj, state); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
for (auto *obj : App.get_switches()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj](bool state) { this->on_switch_update(obj, state); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_COVER
|
||||
for (auto *obj : App.get_covers()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj]() { this->on_cover_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
for (auto *obj : App.get_text_sensors()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj](const std::string &state) { this->on_text_sensor_update(obj, state); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_CLIMATE
|
||||
for (auto *obj : App.get_climates()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj](climate::Climate & /*unused*/) { this->on_climate_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_NUMBER
|
||||
for (auto *obj : App.get_numbers()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj](float state) { this->on_number_update(obj, state); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_DATETIME_DATE
|
||||
for (auto *obj : App.get_dates()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj]() { this->on_date_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_DATETIME_TIME
|
||||
for (auto *obj : App.get_times()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj]() { this->on_time_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_DATETIME_DATETIME
|
||||
for (auto *obj : App.get_datetimes()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj]() { this->on_datetime_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_TEXT
|
||||
for (auto *obj : App.get_texts()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj](const std::string &state) { this->on_text_update(obj, state); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_SELECT
|
||||
for (auto *obj : App.get_selects()) {
|
||||
if (include_internal || !obj->is_internal()) {
|
||||
obj->add_on_state_callback(
|
||||
[this, obj](const std::string &state, size_t index) { this->on_select_update(obj, state, index); });
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_LOCK
|
||||
for (auto *obj : App.get_locks()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj]() { this->on_lock_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_VALVE
|
||||
for (auto *obj : App.get_valves()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj]() { this->on_valve_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
for (auto *obj : App.get_media_players()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj]() { this->on_media_player_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_ALARM_CONTROL_PANEL
|
||||
for (auto *obj : App.get_alarm_control_panels()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj]() { this->on_alarm_control_panel_update(obj); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_EVENT
|
||||
for (auto *obj : App.get_events()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_event_callback([this, obj](const std::string &event_type) { this->on_event(obj, event_type); });
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_UPDATE
|
||||
for (auto *obj : App.get_updates()) {
|
||||
if (include_internal || !obj->is_internal())
|
||||
obj->add_on_state_callback([this, obj]() { this->on_update(obj); });
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace esphome
|
||||
@@ -69,7 +69,6 @@ namespace esphome {
|
||||
|
||||
class Controller {
|
||||
public:
|
||||
void setup_controller(bool include_internal = false);
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
virtual void on_binary_sensor_update(binary_sensor::BinarySensor *obj){};
|
||||
#endif
|
||||
@@ -80,22 +79,22 @@ class Controller {
|
||||
virtual void on_light_update(light::LightState *obj){};
|
||||
#endif
|
||||
#ifdef USE_SENSOR
|
||||
virtual void on_sensor_update(sensor::Sensor *obj, float state){};
|
||||
virtual void on_sensor_update(sensor::Sensor *obj){};
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
virtual void on_switch_update(switch_::Switch *obj, bool state){};
|
||||
virtual void on_switch_update(switch_::Switch *obj){};
|
||||
#endif
|
||||
#ifdef USE_COVER
|
||||
virtual void on_cover_update(cover::Cover *obj){};
|
||||
#endif
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
virtual void on_text_sensor_update(text_sensor::TextSensor *obj, const std::string &state){};
|
||||
virtual void on_text_sensor_update(text_sensor::TextSensor *obj){};
|
||||
#endif
|
||||
#ifdef USE_CLIMATE
|
||||
virtual void on_climate_update(climate::Climate *obj){};
|
||||
#endif
|
||||
#ifdef USE_NUMBER
|
||||
virtual void on_number_update(number::Number *obj, float state){};
|
||||
virtual void on_number_update(number::Number *obj){};
|
||||
#endif
|
||||
#ifdef USE_DATETIME_DATE
|
||||
virtual void on_date_update(datetime::DateEntity *obj){};
|
||||
@@ -107,10 +106,10 @@ class Controller {
|
||||
virtual void on_datetime_update(datetime::DateTimeEntity *obj){};
|
||||
#endif
|
||||
#ifdef USE_TEXT
|
||||
virtual void on_text_update(text::Text *obj, const std::string &state){};
|
||||
virtual void on_text_update(text::Text *obj){};
|
||||
#endif
|
||||
#ifdef USE_SELECT
|
||||
virtual void on_select_update(select::Select *obj, const std::string &state, size_t index){};
|
||||
virtual void on_select_update(select::Select *obj){};
|
||||
#endif
|
||||
#ifdef USE_LOCK
|
||||
virtual void on_lock_update(lock::Lock *obj){};
|
||||
@@ -125,7 +124,7 @@ class Controller {
|
||||
virtual void on_alarm_control_panel_update(alarm_control_panel::AlarmControlPanel *obj){};
|
||||
#endif
|
||||
#ifdef USE_EVENT
|
||||
virtual void on_event(event::Event *obj, const std::string &event_type){};
|
||||
virtual void on_event(event::Event *obj){};
|
||||
#endif
|
||||
#ifdef USE_UPDATE
|
||||
virtual void on_update(update::UpdateEntity *obj){};
|
||||
|
||||
114
esphome/core/controller_registry.cpp
Normal file
114
esphome/core/controller_registry.cpp
Normal file
@@ -0,0 +1,114 @@
|
||||
#include "esphome/core/controller_registry.h"
|
||||
|
||||
#ifdef USE_CONTROLLER_REGISTRY
|
||||
|
||||
#include "esphome/core/controller.h"
|
||||
|
||||
namespace esphome {
|
||||
|
||||
StaticVector<Controller *, CONTROLLER_REGISTRY_MAX> ControllerRegistry::controllers;
|
||||
|
||||
void ControllerRegistry::register_controller(Controller *controller) { controllers.push_back(controller); }
|
||||
|
||||
// Macro for standard registry notification dispatch - calls on_<entity_name>_update()
|
||||
#define CONTROLLER_REGISTRY_NOTIFY(entity_type, entity_name) \
|
||||
void ControllerRegistry::notify_##entity_name##_update(entity_type *obj) { /* NOLINT(bugprone-macro-parentheses) */ \
|
||||
for (auto *controller : controllers) { \
|
||||
controller->on_##entity_name##_update(obj); \
|
||||
} \
|
||||
}
|
||||
|
||||
// Macro for entities where controller method has no "_update" suffix (Event, Update)
|
||||
#define CONTROLLER_REGISTRY_NOTIFY_NO_UPDATE_SUFFIX(entity_type, entity_name) \
|
||||
void ControllerRegistry::notify_##entity_name(entity_type *obj) { /* NOLINT(bugprone-macro-parentheses) */ \
|
||||
for (auto *controller : controllers) { \
|
||||
controller->on_##entity_name(obj); \
|
||||
} \
|
||||
}
|
||||
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
CONTROLLER_REGISTRY_NOTIFY(binary_sensor::BinarySensor, binary_sensor)
|
||||
#endif
|
||||
|
||||
#ifdef USE_FAN
|
||||
CONTROLLER_REGISTRY_NOTIFY(fan::Fan, fan)
|
||||
#endif
|
||||
|
||||
#ifdef USE_LIGHT
|
||||
CONTROLLER_REGISTRY_NOTIFY(light::LightState, light)
|
||||
#endif
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
CONTROLLER_REGISTRY_NOTIFY(sensor::Sensor, sensor)
|
||||
#endif
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
CONTROLLER_REGISTRY_NOTIFY(switch_::Switch, switch)
|
||||
#endif
|
||||
|
||||
#ifdef USE_COVER
|
||||
CONTROLLER_REGISTRY_NOTIFY(cover::Cover, cover)
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
CONTROLLER_REGISTRY_NOTIFY(text_sensor::TextSensor, text_sensor)
|
||||
#endif
|
||||
|
||||
#ifdef USE_CLIMATE
|
||||
CONTROLLER_REGISTRY_NOTIFY(climate::Climate, climate)
|
||||
#endif
|
||||
|
||||
#ifdef USE_NUMBER
|
||||
CONTROLLER_REGISTRY_NOTIFY(number::Number, number)
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_DATE
|
||||
CONTROLLER_REGISTRY_NOTIFY(datetime::DateEntity, date)
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_TIME
|
||||
CONTROLLER_REGISTRY_NOTIFY(datetime::TimeEntity, time)
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_DATETIME
|
||||
CONTROLLER_REGISTRY_NOTIFY(datetime::DateTimeEntity, datetime)
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT
|
||||
CONTROLLER_REGISTRY_NOTIFY(text::Text, text)
|
||||
#endif
|
||||
|
||||
#ifdef USE_SELECT
|
||||
CONTROLLER_REGISTRY_NOTIFY(select::Select, select)
|
||||
#endif
|
||||
|
||||
#ifdef USE_LOCK
|
||||
CONTROLLER_REGISTRY_NOTIFY(lock::Lock, lock)
|
||||
#endif
|
||||
|
||||
#ifdef USE_VALVE
|
||||
CONTROLLER_REGISTRY_NOTIFY(valve::Valve, valve)
|
||||
#endif
|
||||
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
CONTROLLER_REGISTRY_NOTIFY(media_player::MediaPlayer, media_player)
|
||||
#endif
|
||||
|
||||
#ifdef USE_ALARM_CONTROL_PANEL
|
||||
CONTROLLER_REGISTRY_NOTIFY(alarm_control_panel::AlarmControlPanel, alarm_control_panel)
|
||||
#endif
|
||||
|
||||
#ifdef USE_EVENT
|
||||
CONTROLLER_REGISTRY_NOTIFY_NO_UPDATE_SUFFIX(event::Event, event)
|
||||
#endif
|
||||
|
||||
#ifdef USE_UPDATE
|
||||
CONTROLLER_REGISTRY_NOTIFY_NO_UPDATE_SUFFIX(update::UpdateEntity, update)
|
||||
#endif
|
||||
|
||||
#undef CONTROLLER_REGISTRY_NOTIFY
|
||||
#undef CONTROLLER_REGISTRY_NOTIFY_NO_UPDATE_SUFFIX
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
#endif // USE_CONTROLLER_REGISTRY
|
||||
245
esphome/core/controller_registry.h
Normal file
245
esphome/core/controller_registry.h
Normal file
@@ -0,0 +1,245 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
|
||||
#ifdef USE_CONTROLLER_REGISTRY
|
||||
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
// Forward declarations
|
||||
namespace esphome {
|
||||
|
||||
class Controller;
|
||||
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
namespace binary_sensor {
|
||||
class BinarySensor;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_FAN
|
||||
namespace fan {
|
||||
class Fan;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_LIGHT
|
||||
namespace light {
|
||||
class LightState;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
namespace sensor {
|
||||
class Sensor;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
namespace switch_ {
|
||||
class Switch;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_COVER
|
||||
namespace cover {
|
||||
class Cover;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
namespace text_sensor {
|
||||
class TextSensor;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_CLIMATE
|
||||
namespace climate {
|
||||
class Climate;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_NUMBER
|
||||
namespace number {
|
||||
class Number;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_DATE
|
||||
namespace datetime {
|
||||
class DateEntity;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_TIME
|
||||
namespace datetime {
|
||||
class TimeEntity;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_DATETIME
|
||||
namespace datetime {
|
||||
class DateTimeEntity;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT
|
||||
namespace text {
|
||||
class Text;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_SELECT
|
||||
namespace select {
|
||||
class Select;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_LOCK
|
||||
namespace lock {
|
||||
class Lock;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_VALVE
|
||||
namespace valve {
|
||||
class Valve;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
namespace media_player {
|
||||
class MediaPlayer;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_ALARM_CONTROL_PANEL
|
||||
namespace alarm_control_panel {
|
||||
class AlarmControlPanel;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_EVENT
|
||||
namespace event {
|
||||
class Event;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_UPDATE
|
||||
namespace update {
|
||||
class UpdateEntity;
|
||||
}
|
||||
#endif
|
||||
|
||||
/** Global registry for Controllers to receive entity state updates.
|
||||
*
|
||||
* This singleton registry allows Controllers (APIServer, WebServer) to receive
|
||||
* entity state change notifications without storing per-entity callbacks.
|
||||
*
|
||||
* Instead of each entity maintaining controller callbacks (32 bytes overhead per entity),
|
||||
* entities call ControllerRegistry::notify_*_update() which iterates the small list
|
||||
* of registered controllers (typically 2: API and WebServer).
|
||||
*
|
||||
* Controllers read state directly from entities using existing accessors (obj->state, etc.)
|
||||
* rather than receiving it as callback parameters that were being ignored anyway.
|
||||
*
|
||||
* Memory savings: 32 bytes per entity (2 controllers × 16 bytes std::function overhead)
|
||||
* Typical config (25 entities): ~780 bytes saved
|
||||
* Large config (80 entities): ~2,540 bytes saved
|
||||
*/
|
||||
class ControllerRegistry {
|
||||
public:
|
||||
/** Register a controller to receive entity state updates.
|
||||
*
|
||||
* Controllers should call this in their setup() method.
|
||||
* Typically only APIServer and WebServer register.
|
||||
*/
|
||||
static void register_controller(Controller *controller);
|
||||
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
static void notify_binary_sensor_update(binary_sensor::BinarySensor *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_FAN
|
||||
static void notify_fan_update(fan::Fan *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_LIGHT
|
||||
static void notify_light_update(light::LightState *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
static void notify_sensor_update(sensor::Sensor *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
static void notify_switch_update(switch_::Switch *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_COVER
|
||||
static void notify_cover_update(cover::Cover *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
static void notify_text_sensor_update(text_sensor::TextSensor *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_CLIMATE
|
||||
static void notify_climate_update(climate::Climate *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_NUMBER
|
||||
static void notify_number_update(number::Number *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_DATE
|
||||
static void notify_date_update(datetime::DateEntity *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_TIME
|
||||
static void notify_time_update(datetime::TimeEntity *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_DATETIME
|
||||
static void notify_datetime_update(datetime::DateTimeEntity *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT
|
||||
static void notify_text_update(text::Text *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_SELECT
|
||||
static void notify_select_update(select::Select *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_LOCK
|
||||
static void notify_lock_update(lock::Lock *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_VALVE
|
||||
static void notify_valve_update(valve::Valve *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
static void notify_media_player_update(media_player::MediaPlayer *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_ALARM_CONTROL_PANEL
|
||||
static void notify_alarm_control_panel_update(alarm_control_panel::AlarmControlPanel *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_EVENT
|
||||
static void notify_event(event::Event *obj);
|
||||
#endif
|
||||
|
||||
#ifdef USE_UPDATE
|
||||
static void notify_update(update::UpdateEntity *obj);
|
||||
#endif
|
||||
|
||||
protected:
|
||||
static StaticVector<Controller *, CONTROLLER_REGISTRY_MAX> controllers;
|
||||
};
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
#endif // USE_CONTROLLER_REGISTRY
|
||||
@@ -28,11 +28,13 @@
|
||||
#define USE_BUTTON
|
||||
#define USE_CAMERA
|
||||
#define USE_CLIMATE
|
||||
#define USE_CONTROLLER_REGISTRY
|
||||
#define USE_COVER
|
||||
#define USE_DATETIME
|
||||
#define USE_DATETIME_DATE
|
||||
#define USE_DATETIME_DATETIME
|
||||
#define USE_DATETIME_TIME
|
||||
#define USE_DEBUG
|
||||
#define USE_DEEP_SLEEP
|
||||
#define USE_DEVICES
|
||||
#define USE_DISPLAY
|
||||
@@ -213,6 +215,7 @@
|
||||
#define USE_ARDUINO_VERSION_CODE VERSION_CODE(3, 3, 2)
|
||||
#define USE_ETHERNET
|
||||
#define USE_ETHERNET_KSZ8081
|
||||
#define USE_ETHERNET_MANUAL_IP
|
||||
#endif
|
||||
|
||||
#ifdef USE_ESP_IDF
|
||||
@@ -296,6 +299,7 @@
|
||||
#define USE_DASHBOARD_IMPORT
|
||||
|
||||
// Default counts for static analysis
|
||||
#define CONTROLLER_REGISTRY_MAX 2
|
||||
#define ESPHOME_COMPONENT_COUNT 50
|
||||
#define ESPHOME_DEVICE_COUNT 10
|
||||
#define ESPHOME_AREA_COUNT 10
|
||||
|
||||
@@ -129,9 +129,6 @@ class EntityBase {
|
||||
// Returns empty StringRef if object_id is dynamic (needs allocation)
|
||||
StringRef get_object_id_ref_for_api_() const;
|
||||
|
||||
/// The hash_base() function has been deprecated. It is kept in this
|
||||
/// class for now, to prevent external components from not compiling.
|
||||
virtual uint32_t hash_base() { return 0L; }
|
||||
void calc_object_id_();
|
||||
|
||||
/// Check if the object_id is dynamic (changes with MAC suffix)
|
||||
|
||||
@@ -1174,12 +1174,18 @@ template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
|
||||
* Functions to constrain the range of arithmetic values.
|
||||
*/
|
||||
|
||||
template<std::totally_ordered T> T clamp_at_least(T value, T min) {
|
||||
template<typename T, typename U>
|
||||
concept comparable_with = requires(T a, U b) {
|
||||
{ a > b } -> std::convertible_to<bool>;
|
||||
{ a < b } -> std::convertible_to<bool>;
|
||||
};
|
||||
|
||||
template<std::totally_ordered T, comparable_with<T> U> T clamp_at_least(T value, U min) {
|
||||
if (value < min)
|
||||
return min;
|
||||
return value;
|
||||
}
|
||||
template<std::totally_ordered T> T clamp_at_most(T value, T max) {
|
||||
template<std::totally_ordered T, comparable_with<T> U> T clamp_at_most(T value, U max) {
|
||||
if (value > max)
|
||||
return max;
|
||||
return value;
|
||||
|
||||
@@ -12,7 +12,7 @@ platformio==6.1.18 # When updating platformio, also update /docker/Dockerfile
|
||||
esptool==5.1.0
|
||||
click==8.1.7
|
||||
esphome-dashboard==20251013.0
|
||||
aioesphomeapi==42.6.0
|
||||
aioesphomeapi==42.7.0
|
||||
zeroconf==0.148.0
|
||||
puremagic==1.30
|
||||
ruamel.yaml==0.18.16 # dashboard_import
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
pylint==4.0.2
|
||||
flake8==7.3.0 # also change in .pre-commit-config.yaml when updating
|
||||
ruff==0.14.4 # also change in .pre-commit-config.yaml when updating
|
||||
pyupgrade==3.21.0 # also change in .pre-commit-config.yaml when updating
|
||||
pyupgrade==3.21.1 # also change in .pre-commit-config.yaml when updating
|
||||
pre-commit
|
||||
|
||||
# Unit tests
|
||||
pytest==8.4.2
|
||||
pytest==9.0.0
|
||||
pytest-cov==7.0.0
|
||||
pytest-mock==3.15.1
|
||||
pytest-asyncio==1.2.0
|
||||
pytest-asyncio==1.3.0
|
||||
pytest-xdist==3.8.0
|
||||
asyncmock==0.4.2
|
||||
hypothesis==6.92.1
|
||||
|
||||
@@ -86,6 +86,7 @@ ISOLATED_COMPONENTS = {
|
||||
"modbus_controller": "Defines multiple modbus buses for testing client/server functionality - conflicts with package modbus bus",
|
||||
"neopixelbus": "RMT type conflict with ESP32 Arduino/ESP-IDF headers (enum vs struct rmt_channel_t)",
|
||||
"packages": "cannot merge packages",
|
||||
"tinyusb": "Conflicts with usb_host component - cannot be used together",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -178,6 +178,14 @@ api:
|
||||
- logger.log: "Skipped loops"
|
||||
- logger.log: "After combined test"
|
||||
|
||||
event:
|
||||
- platform: template
|
||||
name: Test Event
|
||||
id: test_event
|
||||
event_types:
|
||||
- single_click
|
||||
- double_click
|
||||
|
||||
globals:
|
||||
- id: api_continuation_test_counter
|
||||
type: int
|
||||
|
||||
@@ -52,3 +52,25 @@ sensor:
|
||||
name: "BLE Sensor without Lambda"
|
||||
service_uuid: "abcd1234-abcd-1234-abcd-abcd12345678"
|
||||
characteristic_uuid: "abcd1237-abcd-1234-abcd-abcd12345678"
|
||||
|
||||
number:
|
||||
- platform: template
|
||||
name: "Test Number"
|
||||
id: test_number
|
||||
optimistic: true
|
||||
min_value: 0
|
||||
max_value: 255
|
||||
step: 1
|
||||
|
||||
button:
|
||||
# Test ble_write with lambda that references a component (function pointer)
|
||||
- platform: template
|
||||
name: "BLE Write Lambda Test"
|
||||
on_press:
|
||||
- ble_client.ble_write:
|
||||
id: test_blec
|
||||
service_uuid: "abcd1234-abcd-1234-abcd-abcd12345678"
|
||||
characteristic_uuid: "abcd1235-abcd-1234-abcd-abcd12345678"
|
||||
value: !lambda |-
|
||||
uint8_t val = (uint8_t)id(test_number).state;
|
||||
return std::vector<uint8_t>{0xAA, val, 0xBB};
|
||||
|
||||
@@ -37,6 +37,15 @@ canbus:
|
||||
break;
|
||||
}
|
||||
|
||||
number:
|
||||
- platform: template
|
||||
name: "Test Number"
|
||||
id: test_number
|
||||
optimistic: true
|
||||
min_value: 0
|
||||
max_value: 255
|
||||
step: 1
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
name: Canbus Actions
|
||||
@@ -44,3 +53,7 @@ button:
|
||||
- canbus.send: "abc"
|
||||
- canbus.send: [0, 1, 2]
|
||||
- canbus.send: !lambda return {0, 1, 2};
|
||||
# Test canbus.send with lambda that references a component (function pointer)
|
||||
- canbus.send: !lambda |-
|
||||
uint8_t val = (uint8_t)id(test_number).state;
|
||||
return std::vector<uint8_t>{0xAA, val, 0xBB};
|
||||
|
||||
@@ -16,5 +16,6 @@ display:
|
||||
|
||||
touchscreen:
|
||||
- platform: chsc6x
|
||||
i2c_id: i2c_bus
|
||||
display: ili9xxx_display
|
||||
interrupt_pin: 22
|
||||
|
||||
41
tests/components/hlk_fm22x/common.yaml
Normal file
41
tests/components/hlk_fm22x/common.yaml
Normal file
@@ -0,0 +1,41 @@
|
||||
esphome:
|
||||
on_boot:
|
||||
then:
|
||||
- hlk_fm22x.enroll:
|
||||
name: "Test"
|
||||
direction: 1
|
||||
- hlk_fm22x.delete_all:
|
||||
|
||||
hlk_fm22x:
|
||||
on_face_scan_matched:
|
||||
- logger.log: test_hlk_22x_face_scan_matched
|
||||
on_face_scan_unmatched:
|
||||
- logger.log: test_hlk_22x_face_scan_unmatched
|
||||
on_face_scan_invalid:
|
||||
- logger.log: test_hlk_22x_face_scan_invalid
|
||||
on_face_info:
|
||||
- logger.log: test_hlk_22x_face_info
|
||||
on_enrollment_done:
|
||||
- logger.log: test_hlk_22x_enrollment_done
|
||||
on_enrollment_failed:
|
||||
- logger.log: test_hlk_22x_enrollment_failed
|
||||
|
||||
sensor:
|
||||
- platform: hlk_fm22x
|
||||
face_count:
|
||||
name: "Face Count"
|
||||
last_face_id:
|
||||
name: "Last Face ID"
|
||||
status:
|
||||
name: "Face Status"
|
||||
|
||||
binary_sensor:
|
||||
- platform: hlk_fm22x
|
||||
name: "Face Enrolling"
|
||||
|
||||
text_sensor:
|
||||
- platform: hlk_fm22x
|
||||
version:
|
||||
name: "HLK Version"
|
||||
last_face_name:
|
||||
name: "Last Face Name"
|
||||
4
tests/components/hlk_fm22x/test.esp32-idf.yaml
Normal file
4
tests/components/hlk_fm22x/test.esp32-idf.yaml
Normal file
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
uart: !include ../../test_build_components/common/uart/esp32-idf.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
4
tests/components/hlk_fm22x/test.esp8266-ard.yaml
Normal file
4
tests/components/hlk_fm22x/test.esp8266-ard.yaml
Normal file
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
uart: !include ../../test_build_components/common/uart/esp8266-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
4
tests/components/hlk_fm22x/test.rp2040-ard.yaml
Normal file
4
tests/components/hlk_fm22x/test.rp2040-ard.yaml
Normal file
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
uart: !include ../../test_build_components/common/uart/rp2040-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -700,6 +700,10 @@ lvgl:
|
||||
width: 100%
|
||||
height: 10%
|
||||
align: top_mid
|
||||
on_value:
|
||||
- lvgl.spinbox.update:
|
||||
id: spinbox_id
|
||||
value: !lambda return x;
|
||||
- button:
|
||||
styles: spin_button
|
||||
id: spin_up
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
number:
|
||||
- platform: template
|
||||
id: test_number
|
||||
optimistic: true
|
||||
min_value: 0
|
||||
max_value: 255
|
||||
step: 1
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
name: Beo4 audio mute
|
||||
@@ -128,10 +136,16 @@ button:
|
||||
address: 0x00
|
||||
command: 0x0B
|
||||
- platform: template
|
||||
name: RC5 Raw
|
||||
name: RC5 Raw static
|
||||
on_press:
|
||||
remote_transmitter.transmit_raw:
|
||||
code: [1000, -1000]
|
||||
- platform: template
|
||||
name: RC5 Raw lambda
|
||||
on_press:
|
||||
remote_transmitter.transmit_raw:
|
||||
code: !lambda |-
|
||||
return {(int32_t)id(test_number).state * 100, -1000};
|
||||
- platform: template
|
||||
name: AEHA
|
||||
id: eaha_hitachi_climate_power_on
|
||||
@@ -217,6 +231,23 @@ button:
|
||||
command: 0xEC
|
||||
rc_code_1: 0x0D
|
||||
rc_code_2: 0x0D
|
||||
- platform: template
|
||||
name: ABBWelcome static
|
||||
on_press:
|
||||
remote_transmitter.transmit_abbwelcome:
|
||||
source_address: 0x1234
|
||||
destination_address: 0x5678
|
||||
message_type: 0x01
|
||||
data: [0x10, 0x20, 0x30]
|
||||
- platform: template
|
||||
name: ABBWelcome lambda
|
||||
on_press:
|
||||
remote_transmitter.transmit_abbwelcome:
|
||||
source_address: 0x1234
|
||||
destination_address: 0x5678
|
||||
message_type: 0x01
|
||||
data: !lambda |-
|
||||
return {(uint8_t)id(test_number).state, 0x20, 0x30};
|
||||
- platform: template
|
||||
name: Digital Write
|
||||
on_press:
|
||||
|
||||
8
tests/components/rx8130/common.yaml
Normal file
8
tests/components/rx8130/common.yaml
Normal file
@@ -0,0 +1,8 @@
|
||||
esphome:
|
||||
on_boot:
|
||||
- rx8130.read_time
|
||||
- rx8130.write_time
|
||||
|
||||
time:
|
||||
- platform: rx8130
|
||||
i2c_id: i2c_bus
|
||||
4
tests/components/rx8130/test.esp32-idf.yaml
Normal file
4
tests/components/rx8130/test.esp32-idf.yaml
Normal file
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
4
tests/components/rx8130/test.esp8266-ard.yaml
Normal file
4
tests/components/rx8130/test.esp8266-ard.yaml
Normal file
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp8266-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
4
tests/components/rx8130/test.rp2040-ard.yaml
Normal file
4
tests/components/rx8130/test.rp2040-ard.yaml
Normal file
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/rp2040-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -1,18 +1,52 @@
|
||||
number:
|
||||
- platform: template
|
||||
name: "Speaker Number"
|
||||
id: my_number
|
||||
optimistic: true
|
||||
min_value: 0
|
||||
max_value: 100
|
||||
step: 1
|
||||
|
||||
esphome:
|
||||
on_boot:
|
||||
then:
|
||||
- speaker.mute_on:
|
||||
id: speaker_id
|
||||
- speaker.mute_off:
|
||||
id: speaker_id
|
||||
- if:
|
||||
condition: speaker.is_stopped
|
||||
condition:
|
||||
speaker.is_stopped:
|
||||
id: speaker_id
|
||||
then:
|
||||
- speaker.play: [0, 1, 2, 3]
|
||||
- speaker.volume_set: 0.9
|
||||
- speaker.play:
|
||||
id: speaker_id
|
||||
data: [0, 1, 2, 3]
|
||||
- speaker.volume_set:
|
||||
id: speaker_id
|
||||
volume: 0.9
|
||||
- if:
|
||||
condition: speaker.is_playing
|
||||
condition:
|
||||
speaker.is_playing:
|
||||
id: speaker_id
|
||||
then:
|
||||
- speaker.finish:
|
||||
id: speaker_id
|
||||
- speaker.stop:
|
||||
id: speaker_id
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
name: "Speaker Button"
|
||||
on_press:
|
||||
then:
|
||||
- speaker.play:
|
||||
id: speaker_id
|
||||
data: [0x10, 0x20, 0x30, 0x40]
|
||||
- speaker.play:
|
||||
id: speaker_id
|
||||
data: !lambda |-
|
||||
return {0x01, 0x02, (uint8_t)id(my_number).state};
|
||||
|
||||
i2s_audio:
|
||||
i2s_lrclk_pin: ${i2s_bclk_pin}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user