Compare commits

..
27 changed files with 81 additions and 517 deletions

No files matched your search

-45
View File
@@ -128,51 +128,6 @@ helper; `AGENTS.md` section 4 and the `component-codegen` skill have the detail.
| action or condition class that only forwards to the parent | `register_apply_action` / `register_apply_condition` |
| enum-to-string `switch` returning literals | `PROGMEM_STRING_TABLE` with `get_log_str` / `get_progmem_str` |
| `if (x := config.get(CONF_X)) is not None: cg.add(var.set_x(x))` | `cg.add_optional(var.set_x, config.get(CONF_X))`, when the setter takes the value unchanged |
| `x = (x & ~mask) \| (on ? mask : 0)` or a bit-reversal loop | `assign_bits(x, mask, on)`, `reverse_bits(x)` (`esphome/core/helpers.h`) |
| `x < lo ? lo : (x > hi ? hi : x)` | `std::clamp(x, lo, hi)` |
| I2C read, mask, write by hand; private 16-bit register byte helpers | `update_register`, `update_register16`, `read_byte_reg16`, `write_byte_reg16` |
| custom validator that checks which keys are set, or one schema with model checks | `cv.has_exactly_one_key`, `cv.has_at_most_one_key`, `cv.Inclusive`/`cv.Exclusive`, `cv.typed_schema` per model |
## Cleanups automated reviews keep missing
Multi-pass cleanup reviews of contributor PRs find these again and again, and single-pass reviews
almost never flag them. Look for each one explicitly; the matching `AGENTS.md` section 4 entry has the
detail.
- **Copies within the PR** (the most common finding): two functions, branches, platform files or tests
that differ in a constant or two. Ask for one helper, loop or table.
- **State that copies other state:** a `write_pending_` bool beside a timer (use the return value of
`cancel_timeout(ID)`), a `has_x_` bool beside `x_` (use `NAN` or a sentinel), an enum that can be worked
out from stored fields.
- **Dead guards:** null checks on members codegen always sets, `is_failed()` checks in `loop()`, range
checks the schema already enforces, `default:` in a `switch` over every value of an `enum class` the
component sets itself (not one cast from bus data), calls that set a member to its default
(`set_cs_pin(nullptr)`).
- **Member layout:** field order that leaves padding, `int`/`uint32_t` for values that fit a `uint8_t`,
an `enum class` without `: uint8_t`, several `bool` members that could share a byte. Each costs RAM per
instance.
- **C++ work that belongs in codegen:** scaling, clamping, checksums or register bytes computed at boot
from config values; ask for the plain value from `to_code`.
- **Two `switch` ladders for one mapping:** encode and decode of the same value pairs should share one
`static constexpr` table (`PROGMEM` on ESP8266).
- **Compile-time constants:** `static const` or `#define` with a constant value (use `static constexpr`),
constant tables not in `PROGMEM`, unused constants.
- **Code for one model or feature compiled into every build:** ask for a `cg.add_define()` emitted only
when the config uses it, with the runtime check inside the `#ifdef`.
- **Failure handling:** `mark_failed()` outside `setup()` (runtime failures set a warning that the next
success clears), an error enum that only picks a log message.
- **Logging** that does not follow https://developers.esphome.io/architecture/logging/: `ESP_LOGD` on every
reading, "Setting up" or "initialized" lines in `setup()`, a `dump_config()` made of single-line
`ESP_LOGCONFIG` calls where related lines fit one call, a name helper that returns `const char *` instead
of `const LogString *`.
- **Leaf classes** that are not `final`.
- **Unused helpers, includes and imports** left behind; lint does not catch most of them.
- **Comments that restate the code** or tell its history: a block comment that walks through the next
ten lines, a docstring that repeats the signature, a derivation that a one-line note plus a datasheet
section would cover.
- **Tests:** near-identical test functions that differ only in inputs (ask for `pytest.mark.parametrize`
or a table-driven gtest), tests that repeat another test, test YAML that sets options to their defaults.
## Python conventions
+1 -24
View File
@@ -247,7 +247,6 @@ file does, and it is the authority when they disagree. The most useful starting
`DS_BCD_CALENDAR` or `PCF_BCD_CALENDAR`.
* **Bus helpers:** UART drains with `read_available(on_byte)` and `discard_available()`, text lines with
`LineReader<N>`, fixed-length binary frames with `FrameReader<N, HEADER...>`; I2C has `update_register`,
`update_register16`, `read_byte_reg16` and `write_byte_reg16` for 16-bit register addresses,
`write_registers` (PROGMEM `I2CRegValue` table), `check_chip_id` and `read_bytes_16_le`.
`if (!this->status_comm_result(ok)) return;` sets or clears the warning; an earlier step of a multi-step
poll uses `status_comm_check(ok)`, which only sets it, so the last step must clear it; in `setup()`,
@@ -312,27 +311,6 @@ file does, and it is the authority when they disagree. The most useful starting
text::Text *source_{nullptr};
};
```
* **No state that copies other state:** a flag that mirrors a timer, a `has_x_` bool beside `x_`, or an enum
that can be worked out from fields already stored is a second source of truth. Use the source:
`pending = this->cancel_timeout(ID)`, an unset value of `NAN` or an out-of-range sentinel.
* **No dead guards:** do not check what the caller or core already guarantees: a member that codegen always
sets, `is_failed()` in `loop()` (core stops calling it), a value the config validation already limits, a
`default:` in a `switch` over every value of an `enum class` the component sets itself (keep it when the
value is cast from bus data).
* **Member layout:** order fields so the compiler adds no padding (usually largest first), store small codes
as `uint8_t`, declare `enum class X : uint8_t`, and pack flags into one byte.
* **Work out constants in Python:** math that only depends on the configuration (register bytes, scale
factors, thresholds, checksums) is done in `to_code` and passed as a plain value, not done in C++ at
boot.
* **One table for both directions:** a value that is encoded and decoded through the same mapping uses one
`static constexpr` (`PROGMEM` on ESP8266) table of `{value, code}` pairs, not two `switch` ladders.
* **Logging:** follow https://developers.esphome.io/architecture/logging/ for log levels and `dump_config()`.
In short: a reading is logged with `ESP_LOGV`, not `ESP_LOGD` on every update; `setup()` logs no
"Setting up" or "initialized" line (core logs setup); `dump_config()` combines related lines into one
`ESP_LOGCONFIG` call, within the 512-byte log buffer.
* **Leaf classes are `final`:** a component or entity class nothing derives from is declared `final`.
* **No copies within the PR:** two functions, branches or platform files that differ in a constant or two
become one helper, loop or table; helpers, includes and imports nothing uses are deleted.
* **Component Code Generation:** every component's `__init__.py` defines `DOMAIN` (its own name, checked by
CI). Hub entities go in platform files (`sensor.py`, ...) that take the hub's id, not under the hub's own
@@ -379,8 +357,7 @@ file does, and it is the authority when they disagree. The most useful starting
`script/test_build_components -c <component>`. Never define buses directly in test YAML: include the
shared packages from `tests/test_build_components/common/` with dict-style `packages:`. Test file naming,
`validate.*.yaml` config-only tests, CI grouping, C++ unit tests and integration tests are in the
`component-tests` skill. Tests that differ only in their inputs are one `pytest.mark.parametrize` test
or a table-driven gtest.
`component-tests` skill.
* **Debugging and Troubleshooting:**
* **Debug Tools:**
+1 -1
View File
@@ -385,7 +385,7 @@ async def to_code(config: ConfigType) -> None:
# Adds a define and IDF component for legacy `audio_decoder.cpp`.
if data.flac_support:
cg.add_define("USE_AUDIO_FLAC_SUPPORT")
add_idf_component(name="esphome/micro-flac", ref="0.3.1")
add_idf_component(name="esphome/micro-flac", ref="0.3.0")
_emit_memory_pair(
data.flac.buffer_memory,
"CONFIG_MICRO_FLAC_PREFER_PSRAM",
+14 -13
View File
@@ -41,7 +41,7 @@ from esphome.const import (
__version__ as ESPHOME_VERSION,
)
from esphome.core import CORE, ID, MACAddress
from esphome.cpp_generator import MockObj, StaticCastExpression, UnaryOpExpression
from esphome.cpp_generator import MockObj, StaticCastExpression
import esphome.final_validate as fv
from esphome.schema_extractors import SCHEMA_EXTRACT
from esphome.types import ConfigType, TemplateArgsType
@@ -704,21 +704,21 @@ async def to_code_descriptor(descriptor_conf, char_conf, char_var):
descriptor_conf[CONF_MAX_LENGTH],
descriptor_permissions(descriptor_conf, char_conf),
)
# Static storage, so the characteristic must not free it
cg.add(char_var.add_descriptor(UnaryOpExpression("*", desc_var)))
cg.add(char_var.add_descriptor(desc_var))
cg.add(desc_var.set_value(value))
if (on_write_conf := descriptor_conf.get(CONF_ON_WRITE)) is not None:
await _build_on_write_automation(desc_var, on_write_conf)
async def to_code_characteristic(service_var, char_conf):
char_var = cg.new_Pvariable(
char_var = cg.Pvariable(
char_conf[CONF_ID],
parse_uuid(char_conf[CONF_UUID]),
parse_properties(char_conf),
characteristic_permissions(char_conf),
service_var.create_characteristic(
parse_uuid(char_conf[CONF_UUID]),
parse_properties(char_conf),
characteristic_permissions(char_conf),
),
)
cg.add(service_var.add_characteristic(UnaryOpExpression("*", char_var)))
if (on_write_conf := char_conf.get(CONF_ON_WRITE)) is not None:
await _build_on_write_automation(char_var, on_write_conf)
if CONF_VALUE in char_conf:
@@ -823,13 +823,14 @@ async def to_code(config):
for service_config in config[CONF_SERVICES]:
# Calculate the optimal number of handles based on the number of characteristics and descriptors
num_handles = calculate_num_handles(service_config)
service_var = cg.new_Pvariable(
service_var = cg.Pvariable(
service_config[CONF_ID],
parse_uuid(service_config[CONF_UUID]),
num_handles,
service_config[CONF_ADVERTISE],
var.create_service(
parse_uuid(service_config[CONF_UUID]),
service_config[CONF_ADVERTISE],
num_handles,
),
)
cg.add(var.add_service(UnaryOpExpression("*", service_var)))
for char_conf in service_config[CONF_CHARACTERISTICS]:
await to_code_characteristic(service_var, char_conf)
if uuid_is(service_config[CONF_UUID], DEVICE_INFORMATION_SERVICE_UUID):
@@ -2,8 +2,6 @@
#include "ble_server.h"
#include "ble_service.h"
#include <vector>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
@@ -15,12 +13,7 @@ ESPHOME_LOG_TAG(TAG, "esp32_ble_server.characteristic");
BLECharacteristic::~BLECharacteristic() {
for (auto *descriptor : this->descriptors_) {
if (descriptor->owned_) {
delete descriptor; // NOLINT(cppcoreguidelines-owning-memory)
} else if (descriptor->characteristic_ == this) {
// A caller-owned descriptor outlives this characteristic, and may already belong to another one
descriptor->characteristic_ = nullptr;
}
delete descriptor; // NOLINT(cppcoreguidelines-owning-memory)
}
}
@@ -86,27 +79,10 @@ void BLECharacteristic::notify() {
}
}
void BLECharacteristic::do_delete() {
this->clients_to_notify_.clear();
// The stack may reuse the handles, so a deleted characteristic must not match events until it is created again
this->handle_ = 0xFFFF;
this->state_ = INIT;
for (auto *descriptor : this->descriptors_) {
descriptor->handle_ = 0xFFFF;
descriptor->state_ = BLEDescriptor::INIT;
}
}
bool BLECharacteristic::add_descriptor(BLEDescriptor &descriptor) {
// Bound until removed or the parent is destroyed
if (descriptor.characteristic_ != nullptr) {
ESP_LOGE(TAG, "Already added");
return false;
}
descriptor.characteristic_ = this;
void BLECharacteristic::add_descriptor(BLEDescriptor *descriptor) {
// If the descriptor is the CCCD descriptor, listen to its write event to know if the client wants to be notified
if (descriptor.get_uuid() == ESPBTUUID::from_uint16(ESP_GATT_UUID_CHAR_CLIENT_CONFIG)) {
descriptor.on_write([this](std::span<const uint8_t> value, uint16_t conn_id) {
if (descriptor->get_uuid() == ESPBTUUID::from_uint16(ESP_GATT_UUID_CHAR_CLIENT_CONFIG)) {
descriptor->on_write([this](std::span<const uint8_t> value, uint16_t conn_id) {
if (value.size() != 2)
return;
uint16_t cccd = encode_uint16(value[1], value[0]);
@@ -120,18 +96,16 @@ bool BLECharacteristic::add_descriptor(BLEDescriptor &descriptor) {
}
});
}
this->descriptors_.push_back(&descriptor);
return true;
this->descriptors_.push_back(descriptor);
}
void BLECharacteristic::remove_descriptor(BLEDescriptor *descriptor) {
if (std::erase(this->descriptors_, descriptor) == 0)
return;
descriptor->owned_ = false; // the caller owns it again
descriptor->characteristic_ = nullptr;
this->descriptors_.erase(std::remove(this->descriptors_.begin(), this->descriptors_.end(), descriptor),
this->descriptors_.end());
}
void BLECharacteristic::do_create() {
void BLECharacteristic::do_create(BLEService *service) {
this->service_ = service;
esp_attr_control_t control;
control.auto_rsp = ESP_GATT_RSP_BY_APP;
@@ -142,9 +116,8 @@ void BLECharacteristic::do_create() {
#endif
esp_bt_uuid_t uuid = this->uuid_.get_uuid();
esp_err_t err =
esp_ble_gatts_add_char(this->service_->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
this->properties_, nullptr, &control);
esp_err_t err = esp_ble_gatts_add_char(service->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
this->properties_, nullptr, &control);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_add_char failed: %d", err);
@@ -215,15 +188,11 @@ void BLECharacteristic::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt
break;
}
case ESP_GATTS_ADD_CHAR_EVT: {
// Only while creating, in its own service: a late event for a removed service or a same-UUID
// characteristic elsewhere must not set the handle or start the descriptors
if (this->state_ == CREATING && this->service_ != nullptr &&
this->service_->get_handle() == param->add_char.service_handle &&
this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
if (this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
this->handle_ = param->add_char.attr_handle;
for (auto *descriptor : this->descriptors_) {
descriptor->do_create();
descriptor->do_create(this);
}
this->state_ = CREATING_DEPENDENTS;
@@ -25,8 +25,6 @@ using namespace bytebuffer;
class BLEService;
class BLECharacteristic final {
friend class BLEService;
public:
BLECharacteristic(ESPBTUUID uuid, uint32_t properties, esp_gatt_perm_t permissions);
~BLECharacteristic();
@@ -46,18 +44,11 @@ class BLECharacteristic final {
void notify();
void do_create();
void do_delete();
void do_create(BLEService *service);
void do_delete() { this->clients_to_notify_.clear(); }
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
/// Takes ownership of a heap-allocated descriptor and frees it with this characteristic.
void add_descriptor(BLEDescriptor *descriptor) {
if (this->add_descriptor(*descriptor))
descriptor->owned_ = true;
}
/// Adds a descriptor the caller keeps alive (such as a component member); it is never freed here.
/// False when it already belongs to a characteristic.
bool add_descriptor(BLEDescriptor &descriptor);
void add_descriptor(BLEDescriptor *descriptor);
void remove_descriptor(BLEDescriptor *descriptor);
BLEService *get_service() { return this->service_; }
@@ -115,8 +106,6 @@ class BLECharacteristic final {
CREATING_DEPENDENTS,
CREATED,
} state_{INIT};
// Set by BLEService::create_characteristic(), which allocates it; the service frees it
bool owned_{false};
};
} // namespace esphome::esp32_ble_server
@@ -27,7 +27,8 @@ BLEDescriptor::BLEDescriptor(ESPBTUUID uuid, uint16_t max_len, esp_gatt_perm_t p
BLEDescriptor::~BLEDescriptor() { free(this->value_.attr_value); } // NOLINT
void BLEDescriptor::do_create() {
void BLEDescriptor::do_create(BLECharacteristic *characteristic) {
this->characteristic_ = characteristic;
esp_attr_control_t control;
control.auto_rsp = ESP_GATT_AUTO_RSP;
@@ -65,8 +66,7 @@ void BLEDescriptor::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_
esp_ble_gatts_cb_param_t *param) {
switch (event) {
case ESP_GATTS_ADD_CHAR_DESCR_EVT: {
// Bound by add_descriptor(), so only a descriptor do_create() is creating may claim the event
if (this->state_ == CREATING && this->uuid_ == ESPBTUUID::from_uuid(param->add_char_descr.descr_uuid) &&
if (this->characteristic_ != nullptr && this->uuid_ == ESPBTUUID::from_uuid(param->add_char_descr.descr_uuid) &&
this->characteristic_->get_service()->get_handle() == param->add_char_descr.service_handle &&
this->characteristic_ == this->characteristic_->get_service()->get_last_created_characteristic()) {
this->handle_ = param->add_char_descr.attr_handle;
@@ -20,13 +20,11 @@ class BLECharacteristic;
// Base class for BLE descriptors
class BLEDescriptor {
friend class BLECharacteristic;
public:
BLEDescriptor(ESPBTUUID uuid, uint16_t max_len = 100, bool read = true, bool write = true);
BLEDescriptor(ESPBTUUID uuid, uint16_t max_len, esp_gatt_perm_t permissions);
virtual ~BLEDescriptor();
void do_create();
void do_create(BLECharacteristic *characteristic);
ESPBTUUID get_uuid() const { return this->uuid_; }
void set_value(const uint8_t *data, size_t length);
@@ -62,8 +60,6 @@ class BLEDescriptor {
CREATING,
CREATED,
} state_{INIT};
// Set when the characteristic took ownership through add_descriptor(BLEDescriptor *) and frees it
bool owned_{false};
};
} // namespace esphome::esp32_ble_server
@@ -1,7 +1,5 @@
#include "ble_server.h"
#include <vector>
#include "esphome/components/ble_device_base/ble_device.h"
#include "esphome/components/esp32_ble/ble.h"
#include "esphome/core/log.h"
@@ -125,52 +123,31 @@ void BLEServer::release_advertising_() {
}
BLEService *BLEServer::create_service(ESPBTUUID uuid, bool advertise, uint16_t num_handles) {
// Checked before allocating, so a failure never deletes a service and pulls in its destructor
const uint8_t inst_id = this->free_inst_id_(uuid);
if (inst_id == INVALID_INST_ID)
return nullptr;
auto *service = new BLEService(uuid, num_handles, advertise); // NOLINT(cppcoreguidelines-owning-memory)
this->register_service_(*service, inst_id, true);
return service;
}
bool BLEServer::add_service(BLEService &service) {
// Adding it twice would free or start it twice
for (auto &entry : this->services_) {
if (entry.service == &service) {
ESP_LOGE(TAG, "Already added");
return false;
}
}
const uint8_t inst_id = this->free_inst_id_(service.get_uuid());
if (inst_id == INVALID_INST_ID)
return false;
this->register_service_(service, inst_id, false);
return true;
}
uint8_t BLEServer::free_inst_id_(const ESPBTUUID &uuid) {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char uuid_buf[esp32_ble::UUID_STR_LEN];
uuid.to_str(uuid_buf);
ESP_LOGV(TAG, "Adding BLE service - %s", uuid_buf);
ESP_LOGV(TAG, "Creating BLE service - %s", uuid_buf);
#endif
for (uint8_t inst_id = 0; inst_id < INVALID_INST_ID; inst_id++) {
if (this->get_service(uuid, inst_id) == nullptr)
return inst_id;
// Calculate the inst_id for the service
uint8_t inst_id = 0;
for (; inst_id < 0xFF; inst_id++) {
if (this->get_service(uuid, inst_id) == nullptr) {
break;
}
}
char warn_uuid_buf[esp32_ble::UUID_STR_LEN];
uuid.to_str(warn_uuid_buf);
ESP_LOGW(TAG, "Could not create BLE service %s, too many instances", warn_uuid_buf);
return INVALID_INST_ID;
}
void BLEServer::register_service_(BLEService &service, uint8_t inst_id, bool owned) {
service.inst_id_ = inst_id;
this->services_.push_back({service.get_uuid(), inst_id, owned, &service});
if (inst_id == 0xFF) {
char warn_uuid_buf[esp32_ble::UUID_STR_LEN];
uuid.to_str(warn_uuid_buf);
ESP_LOGW(TAG, "Could not create BLE service %s, too many instances", warn_uuid_buf);
return nullptr;
}
BLEService *service = // NOLINT(cppcoreguidelines-owning-memory)
new BLEService(uuid, num_handles, inst_id, advertise);
this->services_.push_back({uuid, inst_id, service});
if (this->parent_->is_active() && this->registered_) {
service.do_create(this);
service->do_create(this);
}
return service;
}
void BLEServer::remove_service(ESPBTUUID uuid, uint8_t inst_id) {
@@ -182,10 +159,7 @@ void BLEServer::remove_service(ESPBTUUID uuid, uint8_t inst_id) {
for (auto it = this->services_.begin(); it != this->services_.end(); ++it) {
if (it->uuid == uuid && it->inst_id == inst_id) {
it->service->do_delete();
// A service still waiting to start must not stay queued once it is unregistered or freed
std::erase(this->services_to_start_, it->service);
if (it->owned)
delete it->service; // NOLINT(cppcoreguidelines-owning-memory)
delete it->service; // NOLINT(cppcoreguidelines-owning-memory)
this->services_.erase(it);
return;
}
@@ -241,18 +215,8 @@ void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t ga
break;
}
// Indexed: a handler (an on_write lambda) can create a service, and push_back may move the vector.
for (size_t i = 0; i < this->services_.size(); i++) { // NOLINT(modernize-loop-convert)
this->services_[i].service->gatts_event_handler(event, gatts_if, param);
}
// A service this server asked for but removed while the stack was still creating it is deleted once its handle
// arrives; services of other GATT applications are left alone
if (event == ESP_GATTS_CREATE_EVT && gatts_if == this->gatts_if_ && param->create.status == ESP_GATT_OK) {
for (auto &entry : this->services_) {
if (entry.service->get_handle() == param->create.service_handle)
return;
}
esp_ble_gatts_delete_service(param->create.service_handle);
for (auto &entry : this->services_) {
entry.service->gatts_event_handler(event, gatts_if, param);
}
}
@@ -49,10 +49,6 @@ class BLEServer final : public Component, public Parented<ESP32BLE> {
uint8_t get_max_clients() const { return this->max_clients_; }
BLEService *create_service(ESPBTUUID uuid, bool advertise = false, uint16_t num_handles = 15);
/// Adds a service the caller keeps alive (such as a component member); remove_service() never frees it.
/// Do not add it again after remove_service(). Returns false when it is already added or the UUID already has
/// 255 instances.
bool add_service(BLEService &service);
void remove_service(ESPBTUUID uuid, uint8_t inst_id = 0);
BLEService *get_service(ESPBTUUID uuid, uint8_t inst_id = 0);
void enqueue_start_service(BLEService *service) { this->services_to_start_.push_back(service); }
@@ -118,13 +114,9 @@ class BLEServer final : public Component, public Parented<ESP32BLE> {
struct ServiceEntry {
ESPBTUUID uuid;
uint8_t inst_id;
bool owned; // allocated by create_service(), freed by remove_service()
BLEService *service;
};
static constexpr uint8_t INVALID_INST_ID = 0xFF;
uint8_t free_inst_id_(const ESPBTUUID &uuid);
void register_service_(BLEService &service, uint8_t inst_id, bool owned);
void restart_advertising_();
void request_advertising_();
void release_advertising_();
@@ -12,25 +12,8 @@ BLEService::BLEService(ESPBTUUID uuid, uint16_t num_handles, uint8_t inst_id, bo
: uuid_(uuid), num_handles_(num_handles), inst_id_(inst_id), advertise_(advertise) {}
BLEService::~BLEService() {
for (auto *chr : this->characteristics_) {
if (chr->owned_) {
delete chr; // NOLINT(cppcoreguidelines-owning-memory)
} else if (chr->service_ == this) {
// A caller-owned characteristic outlives this service, and may already belong to another one
chr->service_ = nullptr;
}
}
}
bool BLEService::add_characteristic(BLECharacteristic &characteristic) {
// Bound until the parent is destroyed
if (characteristic.service_ != nullptr) {
ESP_LOGE(TAG, "Already added");
return false;
}
characteristic.service_ = this;
this->characteristics_.push_back(&characteristic);
return true;
for (auto &chr : this->characteristics_)
delete chr; // NOLINT(cppcoreguidelines-owning-memory)
}
BLECharacteristic *BLEService::get_characteristic(ESPBTUUID uuid) {
@@ -56,8 +39,7 @@ BLECharacteristic *BLEService::create_characteristic(ESPBTUUID uuid, esp_gatt_ch
esp_gatt_perm_t permissions) {
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
BLECharacteristic *characteristic = new BLECharacteristic(uuid, properties, permissions);
characteristic->owned_ = true;
this->add_characteristic(*characteristic);
this->characteristics_.push_back(characteristic);
return characteristic;
}
@@ -87,14 +69,8 @@ void BLEService::do_delete() {
// Call all characteristics to delete
for (auto *characteristic : this->characteristics_)
characteristic->do_delete();
// Not created on the stack yet; if a create is in flight, the server deletes it when its handle arrives
if (this->handle_ == 0xFFFF) {
this->state_ = DELETED;
return;
}
this->stop_();
esp_err_t err = esp_ble_gatts_delete_service(this->handle_);
this->handle_ = 0xFFFF; // a later add creates it again with a new handle
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_delete_service failed: %d", err);
return;
@@ -111,7 +87,7 @@ bool BLEService::do_create_characteristics_() {
auto *characteristic = this->characteristics_[this->created_characteristic_count_++];
this->last_created_characteristic_ = characteristic;
characteristic->do_create();
characteristic->do_create(this);
return true;
}
@@ -164,7 +140,7 @@ void BLEService::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t g
esp_ble_gatts_cb_param_t *param) {
switch (event) {
case ESP_GATTS_CREATE_EVT: {
if (this->state_ == CREATING && this->uuid_ == ESPBTUUID::from_uuid(param->create.service_id.id.uuid) &&
if (this->uuid_ == ESPBTUUID::from_uuid(param->create.service_id.id.uuid) &&
this->inst_id_ == param->create.service_id.id.inst_id) {
this->handle_ = param->create.service_handle;
this->state_ = CREATED;
@@ -20,12 +20,8 @@ class BLEServer;
using namespace esp32_ble;
class BLEService final {
friend class BLEServer;
public:
BLEService(ESPBTUUID uuid, uint16_t num_handles, uint8_t inst_id, bool advertise);
/// The server picks the instance id when the service is added.
BLEService(ESPBTUUID uuid, uint16_t num_handles, bool advertise) : BLEService(uuid, num_handles, 0, advertise) {}
~BLEService();
BLECharacteristic *get_characteristic(ESPBTUUID uuid);
BLECharacteristic *get_characteristic(uint16_t uuid);
@@ -36,8 +32,6 @@ class BLEService final {
esp_gatt_perm_t permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE);
BLECharacteristic *create_characteristic(ESPBTUUID uuid, esp_gatt_char_prop_t properties,
esp_gatt_perm_t permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE);
/// Adds a characteristic the caller keeps alive; it is never freed here. False when it already belongs to a service.
bool add_characteristic(BLECharacteristic &characteristic);
ESPBTUUID get_uuid() { return this->uuid_; }
uint8_t get_inst_id() { return this->inst_id_; }
@@ -151,8 +151,7 @@ Color color_from_light_color_values(LightColorValues val) {
auto r = to_uint8_scale(val.get_color_brightness() * val.get_red());
auto g = to_uint8_scale(val.get_color_brightness() * val.get_green());
auto b = to_uint8_scale(val.get_color_brightness() * val.get_blue());
// White keeps its default of 100% in RGB mode, where it must not count as the strongest channel
uint8_t w = val.get_color_mode() == ColorMode::RGB ? 0 : to_uint8_scale(val.get_white());
auto w = to_uint8_scale(val.get_white());
return Color(r, g, b, w);
}
@@ -12,45 +12,6 @@ uint8_t ESPColorCorrection::gamma_correct_(uint8_t value) const {
return result;
}
uint16_t ESPColorCorrection::gamma_level_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value * 257;
return progmem_read_uint16(&this->gamma_table_[value]);
}
uint8_t ESPColorCorrection::gamma_round_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value;
return (progmem_read_uint16(&this->gamma_table_[value]) + 128) / 257;
}
// Lighting every non-zero channel instead would turn a dim red with a trace of green into yellow
Color ESPColorCorrection::correct_dark_pixel_(Color color) const {
// Compared without the local brightness, which is the same for every channel: the scaled 8-bit
// values are too coarse to compare at the lowest brightness
uint16_t strengths[4];
uint16_t max_strength = 0;
bool lit = false;
for (uint8_t i = 0; i < 4; i++) {
strengths[i] = color[i] * this->max_brightness_[i];
max_strength = std::max(max_strength, strengths[i]);
lit |= esp_scale8_twice(color[i], this->max_brightness_[i], this->local_brightness_) != 0;
}
Color res;
if (!lit)
return res;
// Stretch the strongest channel to full scale and round the others against it; the table is too
// coarse to compare its lowest levels
for (uint8_t i = 0; i < 4; i++) {
if (strengths[i] == max_strength) {
res[i] = 1;
} else if (strengths[i] != 0) {
res[i] = this->gamma_level_(strengths[i] * 255 / max_strength) >= 0x8000 ? 1 : 0;
}
}
return res;
}
uint8_t ESPColorCorrection::gamma_uncorrect_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value;
@@ -40,13 +40,10 @@ class ESPColorCorrection {
#endif
void set_gamma_table(const uint16_t *table) { this->gamma_table_ = table; }
/// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma, keeping a lit pixel lit
inline Color color_correct(Color color) const ESPHOME_ALWAYS_INLINE {
Color res(this->round_channel_(COLOR_CHANNEL_R, color.red), this->round_channel_(COLOR_CHANNEL_G, color.green),
this->round_channel_(COLOR_CHANNEL_B, color.blue), this->round_channel_(COLOR_CHANNEL_W, color.white));
if (res.raw_32 == 0 && color.raw_32 != 0)
res = this->correct_dark_pixel_(color);
return Color(this->limit_(res.red), this->limit_(res.green), this->limit_(res.blue), this->limit_(res.white));
// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma
return Color(this->color_correct_red(color.red), this->color_correct_green(color.green),
this->color_correct_blue(color.blue), this->color_correct_white(color.white));
}
inline uint8_t color_correct_red(uint8_t red) const ESPHOME_ALWAYS_INLINE {
return this->color_correct_channel(COLOR_CHANNEL_R, red);
@@ -93,15 +90,6 @@ class ESPColorCorrection {
#endif
return res;
}
inline uint8_t round_channel_(uint8_t channel, uint8_t value) const ESPHOME_ALWAYS_INLINE {
return this->gamma_round_(esp_scale8_twice(value, this->max_brightness_[channel], this->local_brightness_));
}
/// Forward gamma as the table's 16-bit level
uint16_t gamma_level_(uint8_t value) const;
/// Forward gamma rounded to uint8, where a low level becomes 0
uint8_t gamma_round_(uint8_t value) const;
/// The levels of a pixel whose channels all round to 0: 1 for its strongest channels, unless it is black
Color correct_dark_pixel_(Color color) const;
/// Forward gamma: read uint16 PROGMEM table, convert to uint8
uint8_t gamma_correct_(uint8_t value) const;
/// Reverse gamma and limit for one stored level
+1 -18
View File
@@ -36,10 +36,6 @@ class ESPColorAccessor {
#if defined(USE_LIGHT_PARTITION) && defined(USE_LIGHT_POWER_ESTIMATION)
virtual const ESPColorCorrection *get_color_correction_internal(int32_t index) const { return nullptr; }
#endif
#ifdef USE_LIGHT_PARTITION
// For internal use only: whether the LED at `index` stores a white level.
virtual bool has_white_internal(int32_t index) const { return true; }
#endif
};
/// Color accessor that is completely at peace with the void of nothingness.
@@ -82,10 +78,6 @@ class BufferColorAccessor : public ESPColorAccessor {
}
void set_effect_data(int32_t index, uint8_t value) override { this->effect_data[index] = value; }
#ifdef USE_LIGHT_PARTITION
bool has_white_internal(int32_t index) const override { return this->channel_colors.has_white(); }
#endif
/// Allocate a zeroed block of buffer_bytes() plus `extra_bytes` for the caller, which start at
/// `effect_data + num_leds`, and pass it to set_buffer(). Returns false if it failed.
bool allocate(RAMAllocator<uint8_t> &allocator, size_t num_leds, size_t extra_bytes = 0) {
@@ -159,12 +151,7 @@ class CorrectedBufferColorAccessor final : public BufferColorAccessor {
return this->color_correction->color_uncorrect_channel(channel, this->get_channel_raw(index, channel));
}
void set(int32_t index, Color color) override {
// A white level the strip cannot show must not count as the pixel's strongest channel
if (!this->channel_colors.has_white())
color.white = 0;
this->set_raw(index, this->color_correction->color_correct(color));
}
void set(int32_t index, Color color) override { this->set_raw(index, this->color_correction->color_correct(color)); }
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
this->set_channel_raw(index, channel, this->color_correction->color_correct_channel(channel, value));
}
@@ -286,10 +273,6 @@ class ESPColorView final : public ESPColorSettable {
return this->accessor_->get_color_correction_internal(this->index_);
}
#endif
#ifdef USE_LIGHT_PARTITION
// This method is for internal use only.
bool has_white_internal() const { return this->accessor_->has_white_internal(this->index_); }
#endif
protected:
ESPColorAccessor *const accessor_;
@@ -83,9 +83,6 @@ class PartitionLightOutput final : public light::AddressableLight {
void set(int32_t index, Color color) override {
light::ESPColorView color_view = this->parent_->get_color_view_(index);
// A white level the LED cannot show must not count as the pixel's strongest channel
if (!color_view.has_white_internal()) // NOLINT
color.white = 0;
color_view.set_raw(this->parent_->get_color_correction_(color_view)->color_correct(color));
}
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
@@ -101,10 +98,6 @@ class PartitionLightOutput final : public light::AddressableLight {
this->parent_->get_color_view_(index).set_effect_data(value);
}
bool has_white_internal(int32_t index) const override { // NOLINT
return this->parent_->get_color_view_(index).has_white_internal();
}
#ifdef USE_LIGHT_POWER_ESTIMATION
const light::ESPColorCorrection *get_color_correction_internal(int32_t index) const override { // NOLINT
return this->parent_->get_color_correction_(this->parent_->get_color_view_(index));
@@ -98,7 +98,7 @@ CONFIG_SCHEMA = cv.All(
cv.positive_time_period_milliseconds,
cv.Range(max=cv.TimePeriod(milliseconds=5000)),
),
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=True): cv.boolean,
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=False): cv.boolean,
cv.Optional(CONF_FIXED_DELAY, default="0us"): cv.All(
cv.positive_time_period_microseconds,
cv.Range(max=cv.TimePeriod(microseconds=10000)),
@@ -61,7 +61,7 @@ class SendspinMediaSource final : public SendspinChild,
bool cached_muted_{false};
bool pending_start_{false};
bool static_delay_adjustable_{true};
bool static_delay_adjustable_{false};
};
} // namespace esphome::sendspin_
+6
View File
@@ -20,6 +20,7 @@ from esphome.const import (
CONF_WEB_SERVER,
CONF_WIFI,
KEY_CORE,
KEY_FRAMEWORK_VERSION,
KEY_TARGET_FRAMEWORK,
KEY_TARGET_PLATFORM,
NATIVE_TOOLCHAINS,
@@ -1035,6 +1036,11 @@ class EsphomeCore:
def target_framework(self):
return self.data[KEY_CORE][KEY_TARGET_FRAMEWORK]
@property
def framework_version(self) -> Version:
"""The version of the target platform's framework, set by the platform component."""
return self.data[KEY_CORE][KEY_FRAMEWORK_VERSION]
@property
def using_arduino(self):
return self.target_framework == "arduino"
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies:
esphome/micro-decoder:
version: 0.4.0
esphome/micro-flac:
version: 0.3.1
version: 0.3.0
esphome/micro-mp3:
version: 0.4.0
esphome/micro-opus:
@@ -4,7 +4,6 @@ from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
import re
import pytest
@@ -148,42 +147,6 @@ def test_set_value_constants_share_a_flash_table(
assert "ByteBuffer::wrap" not in main_cpp
def test_yaml_services_and_characteristics_are_static(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
main_cpp = generate_main(component_config_path("own_service.yaml"))
# Placement new into static storage, with handle count then advertise
service = re.search(
r"new\((\w+)\) esp32_ble_server::BLEService\("
r'esp32_ble::ESPBTUUID::from_raw\("2A24B789-7AAB-4535-AF3E-EE76A35CC12D"\), \d+, (?:true|false)\);',
main_cpp,
)
assert service is not None
assert f"ble_server->add_service((*{service[1]}));" in main_cpp
characteristic = re.search(
r"new\((\w+)\) esp32_ble_server::BLECharacteristic\("
r'esp32_ble::ESPBTUUID::from_raw\("CAD48E28-7FBE-41CF-BAE9-D77A6C233423"\)',
main_cpp,
)
assert characteristic is not None
assert f"{service[1]}->add_characteristic((*{characteristic[1]}));" in main_cpp
assert "create_service(" not in main_cpp
assert "create_characteristic(" not in main_cpp
def test_yaml_descriptors_are_added_by_reference(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
main_cpp = generate_main(component_config_path("set_value.yaml"))
# Descriptors live in static storage, so the characteristic must not take ownership
assert "->add_descriptor((*test_descriptor));" in main_cpp
assert "->add_descriptor(test_descriptor);" not in main_cpp
def test_float32_rejects_out_of_range() -> None:
for value in (1e40, -1e40):
with pytest.raises(cv.Invalid, match="out of range for a float"):
@@ -1,18 +1,3 @@
esphome:
on_boot:
- lambda: |-
// Objects the caller keeps alive, registered without heap allocation
static esp32_ble_server::BLEService battery(esp32_ble::ESPBTUUID::from_uint16(0x180F), 6, false);
static esp32_ble_server::BLECharacteristic level(
esp32_ble::ESPBTUUID::from_uint16(0x2A19),
esp32_ble_server::BLECharacteristic::PROPERTY_READ | esp32_ble_server::BLECharacteristic::PROPERTY_NOTIFY,
ESP_GATT_PERM_READ);
static esp32_ble_server::BLE2902 level_cccd;
level.add_descriptor(level_cccd);
battery.add_characteristic(level);
if (id(ble_server).add_service(battery))
id(ble_server).enqueue_start_service(&battery);
esp32_ble_server:
id: ble_server
manufacturer_data: [0x72, 0x4, 0x00, 0x23]
@@ -6,7 +6,6 @@
#include <cstdint>
#include "esphome/components/light/esp_color_correction.h"
#include "esphome/components/light/esp_color_view.h"
namespace esphome::light::testing {
@@ -68,69 +67,6 @@ TEST(GammaCorrection, DeadZoneFixedAtGamma28) {
}
}
// A whole pixel keeps its colour when dim: only the strongest channel is lifted to 1.
TEST(GammaCorrection, DimPixelKeepsDominantChannel) {
GammaFixture fixture(2.8);
fixture.correction.set_local_brightness(13);
EXPECT_EQ(fixture.correction.color_correct(Color(255, 30, 0, 0)), Color(1, 0, 0, 0));
EXPECT_EQ(fixture.correction.color_correct(Color(0, 0, 255, 30)), Color(0, 0, 1, 0));
}
// Orange at 2% brightness and below: the table reads 1 for both channels there, and at the lowest
// step both scale to the same 8-bit value, so neither can be used to compare them.
TEST(GammaCorrection, VeryDimPixelKeepsDominantChannel) {
GammaFixture fixture(2.8);
for (uint8_t brightness : {1, 2, 3, 4, 5, 6}) {
fixture.correction.set_local_brightness(brightness);
EXPECT_EQ(fixture.correction.color_correct(Color(255, 130, 0, 0)), Color(1, 0, 0, 0))
<< "brightness=" << int(brightness);
}
}
TEST(GammaCorrection, DimPixelKeepsSimilarChannels) {
GammaFixture fixture(2.8);
fixture.correction.set_local_brightness(13);
EXPECT_EQ(fixture.correction.color_correct(Color(255, 255, 255, 0)), Color(1, 1, 1, 0));
EXPECT_EQ(fixture.correction.color_correct(Color(255, 230, 0, 0)), Color(1, 1, 0, 0));
fixture.correction.set_local_brightness(1);
EXPECT_EQ(fixture.correction.color_correct(Color(255, 250, 250, 0)), Color(1, 1, 1, 0));
}
// A channel that color_correct sets to 0% stays dark even when it is the strongest in the pixel.
TEST(GammaCorrection, DimPixelLeavesDisabledChannelDark) {
GammaFixture fixture(2.8);
fixture.correction.set_max_brightness(Color(255, 0, 255, 255));
EXPECT_EQ(fixture.correction.color_correct(Color(1, 255, 0, 0)), Color(1, 0, 0, 0));
}
// A strip without white drops the white level before the pixel is rounded, so it cannot outrank red.
TEST(GammaCorrection, UnusedWhiteDoesNotDarkenRgbStrip) {
GammaFixture fixture(2.8);
fixture.correction.set_local_brightness(13);
std::array<uint8_t, 3> color_data{};
std::array<uint8_t, 1> effect_data{};
CorrectedBufferColorAccessor accessor(color_data.data(), effect_data.data(), ChannelColors{0, 1, 2},
&fixture.correction);
accessor.set(0, Color(128, 0, 0, 255));
EXPECT_EQ(color_data, (std::array<uint8_t, 3>{1, 0, 0}));
}
TEST(GammaCorrection, LitPixelDropsChannelThatRoundsToZero) {
GammaFixture fixture(2.8);
EXPECT_EQ(fixture.correction.color_correct(Color(255, 5, 0, 0)), Color(255, 0, 0, 0));
}
// The pixel-level form of esphome/esphome#18842: a non-zero pixel never goes fully dark.
TEST(GammaCorrection, NonZeroPixelStaysLit) {
for (double gamma : {1.0, 2.2, 2.8, 4.0}) {
GammaFixture fixture(gamma);
for (int i = 1; i < 256; i++) {
EXPECT_GE(fixture.correction.color_correct(Color(i, 0, 0, 0)).red, 1) << "gamma=" << gamma << " index=" << i;
}
EXPECT_EQ(fixture.correction.color_correct(Color(0, 0, 0, 0)), Color(0, 0, 0, 0)) << "gamma=" << gamma;
}
}
TEST(GammaCorrection, ReverseSearchFindsLargestIndexLessEqualTarget) {
auto table = build_gamma_table(2.8);
for (uint16_t target : {0, 128, 129, 135, 1000, 32768, 65535}) {
-12
View File
@@ -1,12 +0,0 @@
import esphome.codegen as cg
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
async def to_code_testing(config):
# The accessor hooks that partitions use, and the gamma table of the light under test
cg.add_define("USE_LIGHT_PARTITION")
cg.add_define("USE_LIGHT_GAMMA_LUT")
manifest.to_code = to_code_testing
manifest.dependencies = manifest.dependencies + ["light"]
@@ -1,56 +0,0 @@
#include <gtest/gtest.h>
#include <array>
#include <cmath>
#include <cstdint>
#include "esphome/components/light/addressable_light.h"
#include "esphome/components/light/light_state.h"
#include "esphome/components/partition/light_partition.h"
namespace esphome::partition::testing {
namespace {
// One RGB pixel in memory
class RgbStrip : public light::AddressableLight {
public:
RgbStrip()
: internal_accessor_(this->buffer_.data(), this->buffer_.data() + 3, light::ChannelColors{0, 1, 2},
&this->correction_) {
this->accessor_ = &this->internal_accessor_;
}
int32_t size() const override { return 1; }
void clear_effect_data() override {}
light::LightTraits get_traits() override { return {}; }
void write_state(light::LightState *state) override {}
protected:
std::array<uint8_t, 4> buffer_{};
light::CorrectedBufferColorAccessor internal_accessor_;
};
} // namespace
// The partition corrects a pixel before the strip drops its white level, so it has to drop it first.
TEST(PartitionWhite, UnusedWhiteDoesNotDarkenRgbSegment) {
light::GammaTable table{};
for (int i = 1; i < 256; i++)
table.lut[i] = std::max(1.0, std::round(std::pow(i / 255.0, 2.8) * 65535.0));
table.gamma_x100 = 280;
RgbStrip strip;
light::LightState strip_state(&strip);
PartitionLightOutput partition({AddressableSegment(&strip_state, 0, 1, false)});
light::LightState partition_state(&partition);
partition_state.set_gamma_table(&table);
partition.setup_state(&partition_state);
partition_state.current_values.set_state(1.0f);
partition_state.current_values.set_brightness(13 / 255.0f);
partition.update_state(&partition_state);
partition[0] = Color(128, 0, 0, 255);
EXPECT_EQ(strip[0].get_raw(), Color(1, 0, 0, 0));
}
} // namespace esphome::partition::testing
+5
View File
@@ -582,6 +582,11 @@ class TestEsphomeCore:
assert t == other
def test_framework_version(self, target: core.EsphomeCore) -> None:
version = core.Version(1, 12, 0)
target.data[const.KEY_CORE] = {const.KEY_FRAMEWORK_VERSION: version}
assert target.framework_version is version
def test_address__none(self, target):
target.config = {}
assert target.address is None