Compare commits

..
Author SHA1 Message Date
J. Nick Koston 33d7629e65 Merge commit '6bb30eed5e9b3cf603ba2250a8ab66acc245d344' into HEAD
# Conflicts:
#	esphome/components/esp32_ble_server/ble_server.cpp
2026-11-18 13:40:19 -06:00
J. Nick Koston 6bb30eed5e Merge remote-tracking branch 'origin/dev' into HEAD 2026-11-18 13:39:33 -06:00
J. Nick Koston f62bc46eea [esp32_ble_server] Fix crash when an on_write lambda creates a service (#22877) 2026-11-18 13:38:24 -06:00
Jesse Hills d966ec6f71 Merge branch 'release' into dev 2026-11-19 07:43:24 +13:00
Jesse Hills 1feda1bcaa Merge pull request #22888 from esphome/bump-2026.11.0
2026.11.0
2026-11-19 07:42:57 +13:00
J. Nick Koston 00125a448d [ai] Add the cleanups reviews keep missing to AGENTS.md and the review skill (#22708) 2026-11-18 12:33:37 -06:00
Kevin Ahrendt 3fc8bcbd14 [audio] Bump microFLAC to v0.3.1 (#22878) 2026-11-18 13:10:09 -05:00
Jesse Hills 3b302d3821 Bump version to 2026.11.0 2026-11-19 07:01:16 +13:00
Keith Burzinski cd0258944d [light] Keep the colour of a dim addressable pixel (#22868) 2026-11-19 07:00:36 +13:00
Leandro 512d143a3a [mqtt] Connect as soon as the network is up, not 5 s after boot (#22871) 2026-11-19 06:59:16 +13:00
Keith Burzinski 9898eb124a [light] Keep the colour of a dim addressable pixel (#22868) 2026-11-19 06:58:14 +13:00
Kevin Ahrendt cac0e29421 [sendspin] Default static_delay_adjustable to true (#22872) 2026-11-18 11:51:00 -06:00
J. Nick Koston 4478372f11 Merge commit 'cda4d0fab7' into HEAD 2026-11-18 03:24:33 -06:00
J. Nick Koston cda4d0fab7 Merge remote-tracking branch 'origin/dev' into HEAD 2026-11-18 03:14:22 -06:00
J. Nick Koston 47f8393f68 Merge remote-tracking branch 'origin/ble-server-caller-owned' into HEAD 2026-11-14 08:39:59 -06:00
J. Nick Koston f245927b49 Merge remote-tracking branch 'origin/dev' into HEAD 2026-11-14 08:36:58 -06:00
J. Nick Koston bd0aa95dcb Merge remote-tracking branch 'origin/ble-server-caller-owned' into ble-server-service-entry
# Conflicts:
#	esphome/components/esp32_ble_server/ble_server.cpp
2026-11-12 00:31:14 -06:00
J. Nick Koston deb8ff7747 Delete only unclaimed services created through this server's GATT interface 2026-11-12 00:30:38 -06:00
J. Nick Koston a4f10e34d2 Merge remote-tracking branch 'origin/ble-server-caller-owned' into ble-server-service-entry 2026-11-12 00:15:17 -06:00
J. Nick Koston be7ebd4502 Claim ADD_CHAR_EVT only while creating, in the characteristic's own service 2026-11-12 00:14:57 -06:00
J. Nick Koston db8aabb0a5 Walk the pointer list when deleting an unclaimed service 2026-11-11 23:52:22 -06:00
J. Nick Koston 278c58acaa Merge remote-tracking branch 'origin/ble-server-caller-owned' into ble-server-service-entry 2026-11-11 23:51:42 -06:00
J. Nick Koston 8441f30da4 Delete a service whose create arrives after it was removed 2026-11-11 23:51:36 -06:00
J. Nick Koston c468be5fe6 Merge remote-tracking branch 'origin/ble-server-caller-owned' into ble-server-service-entry 2026-11-11 23:43:11 -06:00
J. Nick Koston a1ede4e5c6 Skip the stack calls when a service is removed before it was created 2026-11-11 23:42:59 -06:00
J. Nick Koston c277712e47 Merge remote-tracking branch 'origin/ble-server-caller-owned' into ble-server-service-entry 2026-11-11 23:42:25 -06:00
J. Nick Koston 93efaca879 Forget a deleted characteristic's handles until it is created again 2026-11-11 23:38:31 -06:00
J. Nick Koston b7d59ccf7d Merge branch 'dev' into ble-server-caller-owned 2026-11-11 23:24:22 -06:00
J. Nick Koston 1bf9d1a7b2 Narrow the created characteristic count so owned_ fits in BLEService's padding 2026-11-11 23:10:10 -06:00
J. Nick Koston 70ec155ea2 Merge remote-tracking branch 'origin/ble-server-caller-owned' into ble-server-service-entry
# Conflicts:
#	esphome/components/esp32_ble_server/ble_server.cpp
2026-11-11 23:10:10 -06:00
J. Nick Koston f55557f581 Bind each parent only when adding, share one error message and trim comments 2026-11-11 23:09:30 -06:00
J. Nick Koston cb17035ee4 Find an already added service in the pointer list 2026-11-11 23:07:30 -06:00
J. Nick Koston 9d30de6f8a Merge remote-tracking branch 'origin/ble-server-caller-owned' into ble-server-service-entry 2026-11-11 23:06:50 -06:00
J. Nick Koston b78f3df6c1 Refuse a service, characteristic or descriptor that is already registered
Each object is bound to its parent when added and unbound when removed or when the
parent is destroyed, so none can be in two lists, be freed twice or keep a stale parent.
2026-11-11 23:05:09 -06:00
J. Nick Koston ce9763bea5 Merge remote-tracking branch 'origin/ble-server-caller-owned' into ble-server-service-entry
# Conflicts:
#	esphome/components/esp32_ble_server/ble_server.cpp
2026-11-11 22:26:34 -06:00
J. Nick Koston 507f754c78 Use std::erase, guard the descriptor's characteristic and dereference with an expression 2026-11-11 22:25:46 -06:00
J. Nick Koston 95f297a126 Merge remote-tracking branch 'origin/ble-server-caller-owned' into ble-server-service-entry 2026-11-11 22:23:52 -06:00
J. Nick Koston e465f754c6 Remove every copy of a descriptor and clear only a characteristic's own service 2026-11-11 22:22:06 -06:00
J. Nick Koston a971115a68 Merge remote-tracking branch 'origin/ble-server-caller-owned' into ble-server-service-entry
# Conflicts:
#	esphome/components/esp32_ble_server/ble_server.cpp
2026-11-11 21:50:00 -06:00
J. Nick Koston 4e09edb59a Unqueue removed services, free only member descriptors and bind added characteristics 2026-11-11 21:48:28 -06:00
J. Nick Koston 4e6f994b7c Merge remote-tracking branch 'upstream/dev' into ble-server-caller-owned 2026-11-09 20:59:46 -08:00
J. Nick Koston ad9027207b Merge branch 'ble-server-caller-owned' into ble-server-service-entry 2026-11-09 02:23:28 -08:00
J. Nick Koston 195d16eb27 Document that a caller-owned service is added once 2026-11-09 02:23:20 -08:00
J. Nick Koston d05bea3046 Merge branch 'ble-server-caller-owned' into ble-server-service-entry 2026-11-09 02:18:56 -08:00
J. Nick Koston fab9d004cc Point the caller-owned API comments at component members 2026-11-09 02:18:41 -08:00
J. Nick Koston f976b0c89a Keep the service owned flag on the service and list plain pointers 2026-11-09 02:18:21 -08:00
J. Nick Koston 7479304f75 Merge branch 'ble-server-caller-owned' into ble-server-service-entry
# Conflicts:
#	esphome/components/esp32_ble_server/ble_server.cpp
2026-11-09 02:09:53 -08:00
J. Nick Koston d4ffa31c4a Pick the instance id before allocating so create_service never deletes 2026-11-09 02:09:13 -08:00
J. Nick Koston 93416cb81e Merge branch 'ble-server-caller-owned' into ble-server-service-entry 2026-11-09 01:52:34 -08:00
J. Nick Koston 1296f3bc63 Test caller-owned registration and YAML descriptors added by reference 2026-11-09 01:52:06 -08:00
J. Nick Koston 2b37efad87 Merge branch 'ble-server-caller-owned' into ble-server-service-entry 2026-11-09 01:43:29 -08:00
J. Nick Koston e40165dd84 Clear ownership on remove_descriptor and parent pointers of caller-owned children 2026-11-09 01:43:12 -08:00
J. Nick Koston 91996b4b7c Make the service lookup getters const and return the UUID by reference 2026-11-09 01:10:09 -08:00
J. Nick Koston 21c0d5c464 [esp32_ble_server] Keep only the service pointer in the server's service list 2026-11-09 00:51:43 -08:00
J. Nick Koston 9579244ef3 Shorten the BLEService constructor comment 2026-11-09 00:35:39 -08:00
J. Nick Koston 60812d8055 [esp32_ble_server] Accept services, characteristics and descriptors the caller keeps alive 2026-11-09 00:22:41 -08:00
27 changed files with 498 additions and 89 deletions

No files matched your search

+45
View File
@@ -128,6 +128,51 @@ 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
+24 -1
View File
@@ -247,6 +247,7 @@ 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()`,
@@ -311,6 +312,27 @@ 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
@@ -357,7 +379,8 @@ 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.
`component-tests` skill. Tests that differ only in their inputs are one `pytest.mark.parametrize` test
or a table-driven gtest.
* **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.0")
add_idf_component(name="esphome/micro-flac", ref="0.3.1")
_emit_memory_pair(
data.flac.buffer_memory,
"CONFIG_MICRO_FLAC_PREFER_PSRAM",
@@ -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
from esphome.cpp_generator import MockObj, StaticCastExpression, UnaryOpExpression
import esphome.final_validate as fv
from esphome.schema_extractors import SCHEMA_EXTRACT
from esphome.types import ConfigType, TemplateArgsType
@@ -704,7 +704,8 @@ async def to_code_descriptor(descriptor_conf, char_conf, char_var):
descriptor_conf[CONF_MAX_LENGTH],
descriptor_permissions(descriptor_conf, char_conf),
)
cg.add(char_var.add_descriptor(desc_var))
# Static storage, so the characteristic must not free it
cg.add(char_var.add_descriptor(UnaryOpExpression("*", 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)
@@ -2,6 +2,8 @@
#include "ble_server.h"
#include "ble_service.h"
#include <vector>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
@@ -13,7 +15,12 @@ ESPHOME_LOG_TAG(TAG, "esp32_ble_server.characteristic");
BLECharacteristic::~BLECharacteristic() {
for (auto *descriptor : this->descriptors_) {
delete descriptor; // NOLINT(cppcoreguidelines-owning-memory)
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;
}
}
}
@@ -79,10 +86,27 @@ void BLECharacteristic::notify() {
}
}
void BLECharacteristic::add_descriptor(BLEDescriptor *descriptor) {
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;
// 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]);
@@ -96,16 +120,18 @@ void BLECharacteristic::add_descriptor(BLEDescriptor *descriptor) {
}
});
}
this->descriptors_.push_back(descriptor);
this->descriptors_.push_back(&descriptor);
return true;
}
void BLECharacteristic::remove_descriptor(BLEDescriptor *descriptor) {
this->descriptors_.erase(std::remove(this->descriptors_.begin(), this->descriptors_.end(), descriptor),
this->descriptors_.end());
if (std::erase(this->descriptors_, descriptor) == 0)
return;
descriptor->owned_ = false; // the caller owns it again
descriptor->characteristic_ = nullptr;
}
void BLECharacteristic::do_create(BLEService *service) {
this->service_ = service;
void BLECharacteristic::do_create() {
esp_attr_control_t control;
control.auto_rsp = ESP_GATT_RSP_BY_APP;
@@ -116,8 +142,9 @@ void BLECharacteristic::do_create(BLEService *service) {
#endif
esp_bt_uuid_t uuid = this->uuid_.get_uuid();
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);
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);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_add_char failed: %d", err);
@@ -188,11 +215,15 @@ void BLECharacteristic::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt
break;
}
case ESP_GATTS_ADD_CHAR_EVT: {
if (this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
// 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)) {
this->handle_ = param->add_char.attr_handle;
for (auto *descriptor : this->descriptors_) {
descriptor->do_create(this);
descriptor->do_create();
}
this->state_ = CREATING_DEPENDENTS;
@@ -25,6 +25,8 @@ using namespace bytebuffer;
class BLEService;
class BLECharacteristic final {
friend class BLEService;
public:
BLECharacteristic(ESPBTUUID uuid, uint32_t properties, esp_gatt_perm_t permissions);
~BLECharacteristic();
@@ -44,11 +46,18 @@ class BLECharacteristic final {
void notify();
void do_create(BLEService *service);
void do_delete() { this->clients_to_notify_.clear(); }
void do_create();
void do_delete();
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
void add_descriptor(BLEDescriptor *descriptor);
/// 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 remove_descriptor(BLEDescriptor *descriptor);
BLEService *get_service() { return this->service_; }
@@ -106,6 +115,8 @@ 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,8 +27,7 @@ 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(BLECharacteristic *characteristic) {
this->characteristic_ = characteristic;
void BLEDescriptor::do_create() {
esp_attr_control_t control;
control.auto_rsp = ESP_GATT_AUTO_RSP;
@@ -66,7 +65,8 @@ 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: {
if (this->characteristic_ != nullptr && this->uuid_ == ESPBTUUID::from_uuid(param->add_char_descr.descr_uuid) &&
// 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) &&
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,11 +20,13 @@ 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(BLECharacteristic *characteristic);
void do_create();
ESPBTUUID get_uuid() const { return this->uuid_; }
void set_value(const uint8_t *data, size_t length);
@@ -60,6 +62,8 @@ 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,5 +1,8 @@
#include "ble_server.h"
#include <algorithm>
#include <vector>
#include "esphome/components/ble_device_base/ble_device.h"
#include "esphome/components/esp32_ble/ble.h"
#include "esphome/core/log.h"
@@ -76,11 +79,11 @@ void BLEServer::loop() {
// it is at the top of the GATT table
this->device_information_service_->do_create(this);
// Create all services previously created
for (auto &entry : this->services_) {
if (entry.service == this->device_information_service_) {
for (auto *service : this->services_) {
if (service == this->device_information_service_) {
continue;
}
entry.service->do_create(this);
service->do_create(this);
}
this->state_ = STARTING_SERVICE;
}
@@ -123,31 +126,52 @@ 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)
service->owned_ = true;
this->register_service_(*service, inst_id);
return service;
}
bool BLEServer::add_service(BLEService &service) {
// Adding it twice would free or start it twice
if (std::ranges::find(this->services_, &service) != this->services_.end()) {
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);
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, "Creating BLE service - %s", uuid_buf);
ESP_LOGV(TAG, "Adding BLE service - %s", uuid_buf);
#endif
// 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;
}
for (uint8_t inst_id = 0; inst_id < INVALID_INST_ID; inst_id++) {
if (this->get_service(uuid, inst_id) == nullptr)
return inst_id;
}
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});
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) {
service.inst_id_ = inst_id;
BLEService *ptr = &service; // an lvalue reuses the push_back already linked for services_to_start_
this->services_.push_back(ptr);
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) {
@@ -157,9 +181,13 @@ void BLEServer::remove_service(ESPBTUUID uuid, uint8_t inst_id) {
ESP_LOGV(TAG, "Removing BLE service - %s %d", uuid_buf, inst_id);
#endif
for (auto it = this->services_.begin(); it != this->services_.end(); ++it) {
if (it->uuid == uuid && it->inst_id == inst_id) {
it->service->do_delete();
delete it->service; // NOLINT(cppcoreguidelines-owning-memory)
BLEService *service = *it;
if (service->get_inst_id() == inst_id && service->get_uuid() == uuid) {
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_, service);
if (service->owned_)
delete service; // NOLINT(cppcoreguidelines-owning-memory)
this->services_.erase(it);
return;
}
@@ -170,9 +198,9 @@ void BLEServer::remove_service(ESPBTUUID uuid, uint8_t inst_id) {
}
BLEService *BLEServer::get_service(ESPBTUUID uuid, uint8_t inst_id) {
for (auto &entry : this->services_) {
if (entry.uuid == uuid && entry.inst_id == inst_id) {
return entry.service;
for (auto *service : this->services_) {
if (service->get_inst_id() == inst_id && service->get_uuid() == uuid) {
return service;
}
}
return nullptr;
@@ -215,8 +243,18 @@ void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t ga
break;
}
for (auto &entry : this->services_) {
entry.service->gatts_event_handler(event, gatts_if, param);
// 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]->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 *service : this->services_) {
if (service->get_handle() == param->create.service_handle)
return;
}
esp_ble_gatts_delete_service(param->create.service_handle);
}
}
@@ -278,8 +316,8 @@ void BLEServer::ble_before_disabled_event_handler() {
// Delete all clients
this->client_count_ = 0;
// Delete all services
for (auto &entry : this->services_) {
entry.service->do_delete();
for (auto *service : this->services_) {
service->do_delete();
}
this->registered_ = false;
this->state_ = INIT;
@@ -49,6 +49,10 @@ 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); }
@@ -111,12 +115,9 @@ class BLEServer final : public Component, public Parented<ESP32BLE> {
std::function<void(uint16_t)> callback;
};
struct ServiceEntry {
ESPBTUUID uuid;
uint8_t inst_id;
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);
void restart_advertising_();
void request_advertising_();
void release_advertising_();
@@ -159,7 +160,7 @@ class BLEServer final : public Component, public Parented<ESP32BLE> {
#endif
uint8_t client_count_{0};
uint8_t max_clients_{1};
std::vector<ServiceEntry> services_{};
std::vector<BLEService *> services_{};
std::vector<BLEService *> services_to_start_{};
BLEService *device_information_service_{};
@@ -12,8 +12,25 @@ 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_)
delete chr; // NOLINT(cppcoreguidelines-owning-memory)
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;
}
BLECharacteristic *BLEService::get_characteristic(ESPBTUUID uuid) {
@@ -39,7 +56,8 @@ 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);
this->characteristics_.push_back(characteristic);
characteristic->owned_ = true;
this->add_characteristic(*characteristic);
return characteristic;
}
@@ -69,8 +87,14 @@ 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;
@@ -87,7 +111,7 @@ bool BLEService::do_create_characteristics_() {
auto *characteristic = this->characteristics_[this->created_characteristic_count_++];
this->last_created_characteristic_ = characteristic;
characteristic->do_create(this);
characteristic->do_create();
return true;
}
@@ -140,7 +164,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->uuid_ == ESPBTUUID::from_uuid(param->create.service_id.id.uuid) &&
if (this->state_ == CREATING && 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,8 +20,12 @@ 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);
@@ -32,9 +36,11 @@ 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_; }
const ESPBTUUID &get_uuid() const { return this->uuid_; }
uint8_t get_inst_id() const { return this->inst_id_; }
BLECharacteristic *get_last_created_characteristic() { return this->last_created_characteristic_; }
uint16_t get_handle() { return this->handle_; }
@@ -57,7 +63,9 @@ class BLEService final {
protected:
std::vector<BLECharacteristic *> characteristics_;
BLECharacteristic *last_created_characteristic_{nullptr};
uint32_t created_characteristic_count_{0};
uint16_t created_characteristic_count_{0}; // never above num_handles_, so owned_ fits beside it
// Set by BLEServer::create_service(), which allocates it; remove_service() frees it
bool owned_{false};
BLEServer *server_ = nullptr;
ESPBTUUID uuid_;
uint16_t num_handles_;
@@ -151,7 +151,8 @@ 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());
auto w = to_uint8_scale(val.get_white());
// 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());
return Color(r, g, b, w);
}
@@ -12,6 +12,45 @@ 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,10 +40,13 @@ 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 {
// 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));
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));
}
inline uint8_t color_correct_red(uint8_t red) const ESPHOME_ALWAYS_INLINE {
return this->color_correct_channel(COLOR_CHANNEL_R, red);
@@ -90,6 +93,15 @@ 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
+18 -1
View File
@@ -36,6 +36,10 @@ 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.
@@ -78,6 +82,10 @@ 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) {
@@ -151,7 +159,12 @@ 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 { this->set_raw(index, this->color_correction->color_correct(color)); }
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_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));
}
@@ -273,6 +286,10 @@ 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,6 +83,9 @@ 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 {
@@ -98,6 +101,10 @@ 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=False): cv.boolean,
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=True): 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_{false};
bool static_delay_adjustable_{true};
};
} // namespace esphome::sendspin_
-6
View File
@@ -20,7 +20,6 @@ from esphome.const import (
CONF_WEB_SERVER,
CONF_WIFI,
KEY_CORE,
KEY_FRAMEWORK_VERSION,
KEY_TARGET_FRAMEWORK,
KEY_TARGET_PLATFORM,
NATIVE_TOOLCHAINS,
@@ -1036,11 +1035,6 @@ 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.0
version: 0.3.1
esphome/micro-mp3:
version: 0.4.0
esphome/micro-opus:
@@ -147,6 +147,17 @@ def test_set_value_constants_share_a_flash_table(
assert "ByteBuffer::wrap" 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,3 +1,18 @@
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,6 +6,7 @@
#include <cstdint>
#include "esphome/components/light/esp_color_correction.h"
#include "esphome/components/light/esp_color_view.h"
namespace esphome::light::testing {
@@ -67,6 +68,69 @@ 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
@@ -0,0 +1,12 @@
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"]
@@ -0,0 +1,56 @@
#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,11 +582,6 @@ 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