[esp32_ble_server] Optimize notification and action managers for typical use cases (#10897)

This commit is contained in:
J. Nick Koston authored and GitHub committed 2025-09-29 11:32:16 +13:00
1 parent ef73ae2116
commit ab79e596b5
4 files changed
+88 -22

No files matched your search

@@ -45,17 +45,16 @@ Trigger<uint16_t> *BLETriggers::create_server_on_disconnect_trigger(BLEServer *s
void BLECharacteristicSetValueActionManager::set_listener(BLECharacteristic *characteristic,
EventEmitterListenerID listener_id,
const std::function<void()> &pre_notify_listener) {
// Check if there is already a listener for this characteristic
if (this->listeners_.count(characteristic) > 0) {
// Unpack the pair listener_id, pre_notify_listener_id
auto listener_pairs = this->listeners_[characteristic];
EventEmitterListenerID old_listener_id = listener_pairs.first;
EventEmitterListenerID old_pre_notify_listener_id = listener_pairs.second;
// Find and remove existing listener for this characteristic
auto *existing = this->find_listener_(characteristic);
if (existing != nullptr) {
// Remove the previous listener
characteristic->EventEmitter<BLECharacteristicEvt::EmptyEvt, uint16_t>::off(BLECharacteristicEvt::EmptyEvt::ON_READ,
old_listener_id);
existing->listener_id);
// Remove the pre-notify listener
this->off(BLECharacteristicSetValueActionEvt::PRE_NOTIFY, old_pre_notify_listener_id);
this->off(BLECharacteristicSetValueActionEvt::PRE_NOTIFY, existing->pre_notify_listener_id);
// Remove from vector
this->remove_listener_(characteristic);
}
// Create a new listener for the pre-notify event
EventEmitterListenerID pre_notify_listener_id =
@@ -66,8 +65,30 @@ void BLECharacteristicSetValueActionManager::set_listener(BLECharacteristic *cha
pre_notify_listener();
}
});
// Save the pair listener_id, pre_notify_listener_id to the map
this->listeners_[characteristic] = std::make_pair(listener_id, pre_notify_listener_id);
// Save the entry to the vector
this->listeners_.push_back({characteristic, listener_id, pre_notify_listener_id});
}
BLECharacteristicSetValueActionManager::ListenerEntry *BLECharacteristicSetValueActionManager::find_listener_(
BLECharacteristic *characteristic) {
for (auto &entry : this->listeners_) {
if (entry.characteristic == characteristic) {
return &entry;
}
}
return nullptr;
}
void BLECharacteristicSetValueActionManager::remove_listener_(BLECharacteristic *characteristic) {
// Since we typically have very few listeners, optimize by swapping with back and popping
for (size_t i = 0; i < this->listeners_.size(); i++) {
if (this->listeners_[i].characteristic == characteristic) {
// Swap with last element and pop (safe even when i is the last element)
this->listeners_[i] = this->listeners_.back();
this->listeners_.pop_back();
return;
}
}
}
} // namespace esp32_ble_server_automations