From 8dd03a3dac480e8eda0c8d8e31d1bf62ae23efae Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 6 May 2024 19:04:52 -0500 Subject: [PATCH] Manage global pointer better --- .../esp32_ble_tracker/esp32_ble_tracker.cpp | 2 +- esphome/components/esphome/ota/ota_esphome.cpp | 2 +- esphome/components/ota/ota_backend.cpp | 11 ++++++++++- esphome/components/ota/ota_backend.h | 3 ++- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp b/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp index 6b2a1caa13..82855b2038 100644 --- a/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp +++ b/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp @@ -58,7 +58,7 @@ void ESP32BLETracker::setup() { this->scanner_idle_ = true; #ifdef USE_OTA - ota::global_ota_component->add_on_state_callback( + ota::get_global_ota_callback()->add_on_state_callback( [this](ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) { if (state == ota::OTA_STARTED) { this->stop_scan(); diff --git a/esphome/components/esphome/ota/ota_esphome.cpp b/esphome/components/esphome/ota/ota_esphome.cpp index 26bc6b82f9..9ce4c8fe27 100644 --- a/esphome/components/esphome/ota/ota_esphome.cpp +++ b/esphome/components/esphome/ota/ota_esphome.cpp @@ -23,7 +23,7 @@ static constexpr u_int16_t OTA_BLOCK_SIZE = 8192; void ESPHomeOTAComponent::setup() { #ifdef USE_OTA_STATE_CALLBACK - ota::global_ota_component->register_ota(this); + ota::register_ota_platform(this); #endif server_ = socket::socket_ip(SOCK_STREAM, 0); diff --git a/esphome/components/ota/ota_backend.cpp b/esphome/components/ota/ota_backend.cpp index 32b9c19164..5e459aa034 100644 --- a/esphome/components/ota/ota_backend.cpp +++ b/esphome/components/ota/ota_backend.cpp @@ -4,7 +4,16 @@ namespace esphome { namespace ota { #ifdef USE_OTA_STATE_CALLBACK -OTAGlobalCallback *global_ota_component = new OTAGlobalCallback(); // NOLINT +OTAGlobalCallback *global_ota_callback{nullptr}; + +OTAGlobalCallback *get_global_ota_callback() { + if (global_ota_callback == nullptr) { + global_ota_callback = new OTAGlobalCallback(); + } + return global_ota_callback; +} + +void register_ota_platform(OTAComponent *ota_caller) { get_global_ota_callback()->register_ota(ota_caller); } #endif } // namespace ota diff --git a/esphome/components/ota/ota_backend.h b/esphome/components/ota/ota_backend.h index b76883df74..2537cdb67a 100644 --- a/esphome/components/ota/ota_backend.h +++ b/esphome/components/ota/ota_backend.h @@ -81,7 +81,8 @@ class OTAGlobalCallback { CallbackManager state_callback_{}; }; -extern OTAGlobalCallback *global_ota_component; // NOLINT +OTAGlobalCallback *get_global_ota_callback(); +void register_ota_platform(OTAComponent *ota_caller); #endif std::unique_ptr make_ota_backend();