diff --git a/.clang-tidy b/.clang-tidy index 936100e9e6..597065d50b 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -30,7 +30,6 @@ Checks: >- -cppcoreguidelines-macro-usage, -cppcoreguidelines-narrowing-conversions, -cppcoreguidelines-non-private-member-variables-in-classes, - -cppcoreguidelines-owning-memory, -cppcoreguidelines-pro-bounds-array-to-pointer-decay, -cppcoreguidelines-pro-bounds-constant-array-index, -cppcoreguidelines-pro-bounds-pointer-arithmetic, diff --git a/esphome/components/api/api_server.cpp b/esphome/components/api/api_server.cpp index c4c193b389..70f82c59db 100644 --- a/esphome/components/api/api_server.cpp +++ b/esphome/components/api/api_server.cpp @@ -64,7 +64,7 @@ void APIServer::setup() { #ifdef USE_LOGGER if (logger::global_logger != nullptr) { logger::global_logger->add_on_log_callback([this](int level, const char *tag, const char *message) { - for (auto *c : this->clients_) { + for (auto &c : this->clients_) { if (!c->remove_) c->send_log_message(level, tag, message); } @@ -77,7 +77,7 @@ void APIServer::setup() { #ifdef USE_ESP32_CAMERA if (esp32_camera::global_esp32_camera != nullptr) { esp32_camera::global_esp32_camera->add_image_callback([this](std::shared_ptr image) { - for (auto *c : this->clients_) + for (auto &c : this->clients_) if (!c->remove_) c->send_camera_state(image); }); @@ -95,25 +95,21 @@ void APIServer::loop() { ESP_LOGD(TAG, "Accepted %s", sock->getpeername().c_str()); auto *conn = new APIConnection(std::move(sock), this); - clients_.push_back(conn); + clients_.emplace_back(conn); conn->start(); } // Partition clients into remove and active - auto new_end = - std::partition(this->clients_.begin(), this->clients_.end(), [](APIConnection *conn) { return !conn->remove_; }); + auto new_end = std::partition(this->clients_.begin(), this->clients_.end(), + [](const std::unique_ptr &conn) { return !conn->remove_; }); // print disconnection messages for (auto it = new_end; it != this->clients_.end(); ++it) { ESP_LOGD(TAG, "Disconnecting %s", (*it)->client_info_.c_str()); } - // only then delete the pointers, otherwise log routine - // would access freed memory - for (auto it = new_end; it != this->clients_.end(); ++it) - delete *it; // resize vector this->clients_.erase(new_end, this->clients_.end()); - for (auto *client : this->clients_) { + for (auto &client : this->clients_) { client->loop(); } @@ -169,7 +165,7 @@ void APIServer::handle_disconnect(APIConnection *conn) {} void APIServer::on_binary_sensor_update(binary_sensor::BinarySensor *obj, bool state) { if (obj->is_internal()) return; - for (auto *c : this->clients_) + for (auto &c : this->clients_) c->send_binary_sensor_state(obj, state); } #endif @@ -178,7 +174,7 @@ void APIServer::on_binary_sensor_update(binary_sensor::BinarySensor *obj, bool s void APIServer::on_cover_update(cover::Cover *obj) { if (obj->is_internal()) return; - for (auto *c : this->clients_) + for (auto &c : this->clients_) c->send_cover_state(obj); } #endif @@ -187,7 +183,7 @@ void APIServer::on_cover_update(cover::Cover *obj) { void APIServer::on_fan_update(fan::FanState *obj) { if (obj->is_internal()) return; - for (auto *c : this->clients_) + for (auto &c : this->clients_) c->send_fan_state(obj); } #endif @@ -196,7 +192,7 @@ void APIServer::on_fan_update(fan::FanState *obj) { void APIServer::on_light_update(light::LightState *obj) { if (obj->is_internal()) return; - for (auto *c : this->clients_) + for (auto &c : this->clients_) c->send_light_state(obj); } #endif @@ -205,7 +201,7 @@ void APIServer::on_light_update(light::LightState *obj) { void APIServer::on_sensor_update(sensor::Sensor *obj, float state) { if (obj->is_internal()) return; - for (auto *c : this->clients_) + for (auto &c : this->clients_) c->send_sensor_state(obj, state); } #endif @@ -214,7 +210,7 @@ void APIServer::on_sensor_update(sensor::Sensor *obj, float state) { void APIServer::on_switch_update(switch_::Switch *obj, bool state) { if (obj->is_internal()) return; - for (auto *c : this->clients_) + for (auto &c : this->clients_) c->send_switch_state(obj, state); } #endif @@ -223,7 +219,7 @@ void APIServer::on_switch_update(switch_::Switch *obj, bool state) { void APIServer::on_text_sensor_update(text_sensor::TextSensor *obj, const std::string &state) { if (obj->is_internal()) return; - for (auto *c : this->clients_) + for (auto &c : this->clients_) c->send_text_sensor_state(obj, state); } #endif @@ -232,7 +228,7 @@ void APIServer::on_text_sensor_update(text_sensor::TextSensor *obj, const std::s void APIServer::on_climate_update(climate::Climate *obj) { if (obj->is_internal()) return; - for (auto *c : this->clients_) + for (auto &c : this->clients_) c->send_climate_state(obj); } #endif @@ -241,7 +237,7 @@ void APIServer::on_climate_update(climate::Climate *obj) { void APIServer::on_number_update(number::Number *obj, float state) { if (obj->is_internal()) return; - for (auto *c : this->clients_) + for (auto &c : this->clients_) c->send_number_state(obj, state); } #endif @@ -250,7 +246,7 @@ void APIServer::on_number_update(number::Number *obj, float state) { void APIServer::on_select_update(select::Select *obj, const std::string &state) { if (obj->is_internal()) return; - for (auto *c : this->clients_) + for (auto &c : this->clients_) c->send_select_state(obj, state); } #endif @@ -261,7 +257,7 @@ APIServer *global_api_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-c void APIServer::set_password(const std::string &password) { this->password_ = password; } void APIServer::send_homeassistant_service_call(const HomeassistantServiceResponse &call) { - for (auto *client : this->clients_) { + for (auto &client : this->clients_) { client->send_homeassistant_service_call(call); } } @@ -281,7 +277,7 @@ uint16_t APIServer::get_port() const { return this->port_; } void APIServer::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; } #ifdef USE_HOMEASSISTANT_TIME void APIServer::request_time() { - for (auto *client : this->clients_) { + for (auto &client : this->clients_) { if (!client->remove_ && client->connection_state_ == APIConnection::ConnectionState::CONNECTED) client->send_time_request(); } @@ -289,7 +285,7 @@ void APIServer::request_time() { #endif bool APIServer::is_connected() const { return !this->clients_.empty(); } void APIServer::on_shutdown() { - for (auto *c : this->clients_) { + for (auto &c : this->clients_) { c->send_disconnect_request(DisconnectRequest()); } delay(10); diff --git a/esphome/components/api/api_server.h b/esphome/components/api/api_server.h index e3fa6b18c9..d659f24358 100644 --- a/esphome/components/api/api_server.h +++ b/esphome/components/api/api_server.h @@ -91,7 +91,7 @@ class APIServer : public Component, public Controller { uint16_t port_{6053}; uint32_t reboot_timeout_{300000}; uint32_t last_connected_{0}; - std::vector clients_; + std::vector> clients_; std::string password_; std::vector state_subs_; std::vector user_services_; diff --git a/esphome/components/api/custom_api_device.h b/esphome/components/api/custom_api_device.h index 74343904eb..9f125a6149 100644 --- a/esphome/components/api/custom_api_device.h +++ b/esphome/components/api/custom_api_device.h @@ -49,7 +49,7 @@ class CustomAPIDevice { template void register_service(void (T::*callback)(Ts...), const std::string &name, const std::array &arg_names) { - auto *service = new CustomAPIDeviceService(name, arg_names, (T *) this, callback); + auto *service = new CustomAPIDeviceService(name, arg_names, (T *) this, callback); // NOLINT global_api_server->register_user_service(service); } @@ -72,7 +72,7 @@ class CustomAPIDevice { * @param name The name of the arguments for the service, must match the arguments of the function. */ template void register_service(void (T::*callback)(), const std::string &name) { - auto *service = new CustomAPIDeviceService(name, {}, (T *) this, callback); + auto *service = new CustomAPIDeviceService(name, {}, (T *) this, callback); // NOLINT global_api_server->register_user_service(service); } diff --git a/esphome/components/captive_portal/captive_portal.cpp b/esphome/components/captive_portal/captive_portal.cpp index 746029e011..3341769956 100644 --- a/esphome/components/captive_portal/captive_portal.cpp +++ b/esphome/components/captive_portal/captive_portal.cpp @@ -76,7 +76,7 @@ void CaptivePortal::start() { this->base_->add_ota_handler(); } - this->dns_server_ = new DNSServer(); + this->dns_server_ = make_unique(); this->dns_server_->setErrorReplyCode(DNSReplyCode::NoError); IPAddress ip = wifi::global_wifi_component->wifi_soft_ap_ip(); this->dns_server_->start(53, "*", ip); diff --git a/esphome/components/captive_portal/captive_portal.h b/esphome/components/captive_portal/captive_portal.h index 44b1050f45..399ffaabd3 100644 --- a/esphome/components/captive_portal/captive_portal.h +++ b/esphome/components/captive_portal/captive_portal.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include "esphome/core/component.h" #include "esphome/core/helpers.h" @@ -26,7 +27,7 @@ class CaptivePortal : public AsyncWebHandler, public Component { this->active_ = false; this->base_->deinit(); this->dns_server_->stop(); - delete this->dns_server_; + this->dns_server_ = nullptr; } bool canHandle(AsyncWebServerRequest *request) override { @@ -65,7 +66,7 @@ class CaptivePortal : public AsyncWebHandler, public Component { web_server_base::WebServerBase *base_; bool initialized_{false}; bool active_{false}; - DNSServer *dns_server_{nullptr}; + std::unique_ptr dns_server_{nullptr}; }; extern CaptivePortal *global_captive_portal; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) diff --git a/esphome/components/dallas/dallas_component.cpp b/esphome/components/dallas/dallas_component.cpp index 7e34546078..847d630e7c 100644 --- a/esphome/components/dallas/dallas_component.cpp +++ b/esphome/components/dallas/dallas_component.cpp @@ -97,16 +97,7 @@ void DallasComponent::dump_config() { } } -DallasTemperatureSensor *DallasComponent::get_sensor_by_address(uint64_t address, uint8_t resolution) { - auto s = new DallasTemperatureSensor(address, resolution, this); - this->sensors_.push_back(s); - return s; -} -DallasTemperatureSensor *DallasComponent::get_sensor_by_index(uint8_t index, uint8_t resolution) { - auto s = this->get_sensor_by_address(0, resolution); - s->set_index(index); - return s; -} +void DallasComponent::register_sensor(DallasTemperatureSensor *sensor) { this->sensors_.push_back(sensor); } void DallasComponent::update() { this->status_clear_warning(); @@ -157,11 +148,6 @@ void DallasComponent::update() { } DallasComponent::DallasComponent(ESPOneWire *one_wire) : one_wire_(one_wire) {} -DallasTemperatureSensor::DallasTemperatureSensor(uint64_t address, uint8_t resolution, DallasComponent *parent) - : parent_(parent) { - this->set_address(address); - this->set_resolution(resolution); -} void DallasTemperatureSensor::set_address(uint64_t address) { this->address_ = address; } uint8_t DallasTemperatureSensor::get_resolution() const { return this->resolution_; } void DallasTemperatureSensor::set_resolution(uint8_t resolution) { this->resolution_ = resolution; } diff --git a/esphome/components/dallas/dallas_component.h b/esphome/components/dallas/dallas_component.h index d32aec1758..8d405f6eab 100644 --- a/esphome/components/dallas/dallas_component.h +++ b/esphome/components/dallas/dallas_component.h @@ -13,8 +13,7 @@ class DallasComponent : public PollingComponent { public: explicit DallasComponent(ESPOneWire *one_wire); - DallasTemperatureSensor *get_sensor_by_address(uint64_t address, uint8_t resolution); - DallasTemperatureSensor *get_sensor_by_index(uint8_t index, uint8_t resolution); + void register_sensor(DallasTemperatureSensor *sensor); void setup() override; void dump_config() override; @@ -33,8 +32,7 @@ class DallasComponent : public PollingComponent { /// Internal class that helps us create multiple sensors for one Dallas hub. class DallasTemperatureSensor : public sensor::Sensor { public: - DallasTemperatureSensor(uint64_t address, uint8_t resolution, DallasComponent *parent); - + void set_parent(DallasComponent *parent) { parent_ = parent; } /// Helper to get a pointer to the address as uint8_t. uint8_t *get_address8(); /// Helper to create (and cache) the name for this sensor. For example "0xfe0000031f1eaf29". diff --git a/esphome/components/dallas/sensor.py b/esphome/components/dallas/sensor.py index 5e09701bae..05c2c8b90c 100644 --- a/esphome/components/dallas/sensor.py +++ b/esphome/components/dallas/sensor.py @@ -36,10 +36,15 @@ CONFIG_SCHEMA = cv.All( async def to_code(config): hub = await cg.get_variable(config[CONF_DALLAS_ID]) + var = cg.new_Pvariable(config[CONF_ID]) + if CONF_ADDRESS in config: - address = config[CONF_ADDRESS] - rhs = hub.Pget_sensor_by_address(address, config.get(CONF_RESOLUTION)) + cg.add(var.set_address(config[CONF_ADDRESS])) else: - rhs = hub.Pget_sensor_by_index(config[CONF_INDEX], config.get(CONF_RESOLUTION)) - var = cg.Pvariable(config[CONF_ID], rhs) + cg.add(var.set_index(config[CONF_INDEX])) + + if CONF_RESOLUTION in config: + cg.add(var.set_resolution(config[CONF_RESOLUTION])) + + cg.add(hub.register_sensor(var)) await sensor.register_sensor(var, config) diff --git a/esphome/components/display/display_buffer.cpp b/esphome/components/display/display_buffer.cpp index c330d00ce5..9c4ee3189f 100644 --- a/esphome/components/display/display_buffer.cpp +++ b/esphome/components/display/display_buffer.cpp @@ -1,9 +1,9 @@ #include "display_buffer.h" +#include #include "esphome/core/application.h" #include "esphome/core/color.h" #include "esphome/core/log.h" -#include namespace esphome { namespace display { @@ -14,7 +14,7 @@ const Color COLOR_OFF(0, 0, 0, 0); const Color COLOR_ON(255, 255, 255, 255); void DisplayBuffer::init_internal_(uint32_t buffer_length) { - this->buffer_ = new (std::nothrow) uint8_t[buffer_length]; + this->buffer_ = new (std::nothrow) uint8_t[buffer_length]; // NOLINT if (this->buffer_ == nullptr) { ESP_LOGE(TAG, "Could not allocate buffer for display!"); return; diff --git a/esphome/components/dsmr/dsmr.cpp b/esphome/components/dsmr/dsmr.cpp index 9bce7a382f..39f05a28d1 100644 --- a/esphome/components/dsmr/dsmr.cpp +++ b/esphome/components/dsmr/dsmr.cpp @@ -105,7 +105,7 @@ void Dsmr::receive_encrypted_() { &buffer[18], // cipher size buffer_length - 17); - delete gcmaes128; + delete gcmaes128; // NOLINT(cppcoreguidelines-owning-memory) telegram_len_ = strnlen(this->telegram_, sizeof(this->telegram_)); ESP_LOGV(TAG, "Decrypted data length: %d", telegram_len_); diff --git a/esphome/components/e131/e131.cpp b/esphome/components/e131/e131.cpp index bd749683c5..7694d039e5 100644 --- a/esphome/components/e131/e131.cpp +++ b/esphome/components/e131/e131.cpp @@ -26,7 +26,7 @@ E131Component::~E131Component() { } void E131Component::setup() { - udp_.reset(new WiFiUDP()); + udp_ = make_unique(); if (!udp_->begin(PORT)) { ESP_LOGE(TAG, "Cannot bind E131 to %d.", PORT); diff --git a/esphome/components/fastled_base/fastled_light.cpp b/esphome/components/fastled_base/fastled_light.cpp index edfeb401f1..15a5c8984c 100644 --- a/esphome/components/fastled_base/fastled_light.cpp +++ b/esphome/components/fastled_base/fastled_light.cpp @@ -10,7 +10,7 @@ void FastLEDLightOutput::setup() { ESP_LOGCONFIG(TAG, "Setting up FastLED light..."); this->controller_->init(); this->controller_->setLeds(this->leds_, this->num_leds_); - this->effect_data_ = new uint8_t[this->num_leds_]; + this->effect_data_ = new uint8_t[this->num_leds_]; // NOLINT if (!this->max_refresh_rate_.has_value()) { this->set_max_refresh_rate(this->controller_->getMaxRefreshRate()); } diff --git a/esphome/components/fastled_base/fastled_light.h b/esphome/components/fastled_base/fastled_light.h index ee85735dea..d1c470599d 100644 --- a/esphome/components/fastled_base/fastled_light.h +++ b/esphome/components/fastled_base/fastled_light.h @@ -30,7 +30,7 @@ class FastLEDLightOutput : public light::AddressableLight { CLEDController &add_leds(CLEDController *controller, int num_leds) { this->controller_ = controller; this->num_leds_ = num_leds; - this->leds_ = new CRGB[num_leds]; + this->leds_ = new CRGB[num_leds]; // NOLINT for (int i = 0; i < this->num_leds_; i++) this->leds_[i] = CRGB::Black; diff --git a/esphome/components/hm3301/hm3301.cpp b/esphome/components/hm3301/hm3301.cpp index 5612867d1b..96c1ec0ee9 100644 --- a/esphome/components/hm3301/hm3301.cpp +++ b/esphome/components/hm3301/hm3301.cpp @@ -12,7 +12,7 @@ static const uint8_t PM_10_0_VALUE_INDEX = 7; void HM3301Component::setup() { ESP_LOGCONFIG(TAG, "Setting up HM3301..."); - hm3301_ = new HM330X(); + hm3301_ = make_unique(); error_code_ = hm3301_->init(); if (error_code_ != NO_ERROR) { this->mark_failed(); diff --git a/esphome/components/hm3301/hm3301.h b/esphome/components/hm3301/hm3301.h index 5594f1719c..b024f93719 100644 --- a/esphome/components/hm3301/hm3301.h +++ b/esphome/components/hm3301/hm3301.h @@ -27,7 +27,7 @@ class HM3301Component : public PollingComponent, public i2c::I2CDevice { void update() override; protected: - HM330X *hm3301_; + std::unique_ptr hm3301_; HM330XErrorCode error_code_{NO_ERROR}; diff --git a/esphome/components/http_request/http_request.cpp b/esphome/components/http_request/http_request.cpp index 0fafa8cd86..bf5b24c4f2 100644 --- a/esphome/components/http_request/http_request.cpp +++ b/esphome/components/http_request/http_request.cpp @@ -75,10 +75,10 @@ void HttpRequestComponent::send(const std::vector } #ifdef ARDUINO_ARCH_ESP8266 -WiFiClient *HttpRequestComponent::get_wifi_client_() { +std::shared_ptr HttpRequestComponent::get_wifi_client_() { if (this->secure_) { if (this->wifi_client_secure_ == nullptr) { - this->wifi_client_secure_ = new BearSSL::WiFiClientSecure(); + this->wifi_client_secure_ = std::make_shared(); this->wifi_client_secure_->setInsecure(); this->wifi_client_secure_->setBufferSizes(512, 512); } @@ -86,7 +86,7 @@ WiFiClient *HttpRequestComponent::get_wifi_client_() { } if (this->wifi_client_ == nullptr) { - this->wifi_client_ = new WiFiClient(); + this->wifi_client_ = std::make_shared(); } return this->wifi_client_; } diff --git a/esphome/components/http_request/http_request.h b/esphome/components/http_request/http_request.h index 27919fe75d..740a4580b4 100644 --- a/esphome/components/http_request/http_request.h +++ b/esphome/components/http_request/http_request.h @@ -6,6 +6,7 @@ #include #include #include +#include #ifdef ARDUINO_ARCH_ESP32 #include @@ -51,9 +52,9 @@ class HttpRequestComponent : public Component { std::string body_; std::list
headers_; #ifdef ARDUINO_ARCH_ESP8266 - WiFiClient *wifi_client_{nullptr}; - BearSSL::WiFiClientSecure *wifi_client_secure_{nullptr}; - WiFiClient *get_wifi_client_(); + std::shared_ptr wifi_client_; + std::shared_ptr wifi_client_secure_; + std::shared_ptr get_wifi_client_(); #endif }; diff --git a/esphome/components/json/json_util.cpp b/esphome/components/json/json_util.cpp index 4720c8f9c9..aab5b1ce9b 100644 --- a/esphome/components/json/json_util.cpp +++ b/esphome/components/json/json_util.cpp @@ -6,21 +6,7 @@ namespace json { static const char *const TAG = "json"; -static char *global_json_build_buffer = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) -static size_t global_json_build_buffer_size = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) - -void reserve_global_json_build_buffer(size_t required_size) { - if (global_json_build_buffer_size == 0 || global_json_build_buffer_size < required_size) { - delete[] global_json_build_buffer; - global_json_build_buffer_size = std::max(required_size, global_json_build_buffer_size * 2); - - size_t remainder = global_json_build_buffer_size % 16U; - if (remainder != 0) - global_json_build_buffer_size += 16 - remainder; - - global_json_build_buffer = new char[global_json_build_buffer_size]; - } -} +static std::vector global_json_build_buffer; // NOLINT const char *build_json(const json_build_t &f, size_t *length) { global_json_buffer.clear(); @@ -35,16 +21,16 @@ const char *build_json(const json_build_t &f, size_t *length) { // Discovery | 372 | 356 | // Discovery | 336 | 311 | // Discovery | 408 | 393 | - reserve_global_json_build_buffer(global_json_buffer.size()); - size_t bytes_written = root.printTo(global_json_build_buffer, global_json_build_buffer_size); + global_json_build_buffer.reserve(global_json_buffer.size() + 1); + size_t bytes_written = root.printTo(global_json_build_buffer.data(), global_json_build_buffer.capacity()); - if (bytes_written >= global_json_build_buffer_size - 1) { - reserve_global_json_build_buffer(root.measureLength() + 1); - bytes_written = root.printTo(global_json_build_buffer, global_json_build_buffer_size); + if (bytes_written >= global_json_build_buffer.capacity() - 1) { + global_json_build_buffer.reserve(root.measureLength() + 1); + bytes_written = root.printTo(global_json_build_buffer.data(), global_json_build_buffer.capacity()); } *length = bytes_written; - return global_json_build_buffer; + return global_json_build_buffer.data(); } void parse_json(const std::string &data, const json_parse_t &f) { global_json_buffer.clear(); @@ -113,7 +99,7 @@ void VectorJsonBuffer::reserve(size_t size) { // NOLINT target_capacity *= 2; char *old_buffer = this->buffer_; - this->buffer_ = new char[target_capacity]; + this->buffer_ = new char[target_capacity]; // NOLINT if (old_buffer != nullptr && this->capacity_ != 0) { this->free_blocks_.push_back(old_buffer); memcpy(this->buffer_, old_buffer, this->capacity_); diff --git a/esphome/components/json/json_util.h b/esphome/components/json/json_util.h index aafd039b9a..65b2496b85 100644 --- a/esphome/components/json/json_util.h +++ b/esphome/components/json/json_util.h @@ -1,5 +1,7 @@ #pragma once +#include + #include "esphome/core/helpers.h" #include diff --git a/esphome/components/lcd_base/lcd_display.cpp b/esphome/components/lcd_base/lcd_display.cpp index 95b349b9c1..4c0d0ab3ea 100644 --- a/esphome/components/lcd_base/lcd_display.cpp +++ b/esphome/components/lcd_base/lcd_display.cpp @@ -29,7 +29,7 @@ static const uint8_t LCD_DISPLAY_FUNCTION_2_LINE = 0x08; static const uint8_t LCD_DISPLAY_FUNCTION_5X10_DOTS = 0x04; void LCDDisplay::setup() { - this->buffer_ = new uint8_t[this->rows_ * this->columns_]; + this->buffer_ = new uint8_t[this->rows_ * this->columns_]; // NOLINT for (uint8_t i = 0; i < this->rows_ * this->columns_; i++) this->buffer_[i] = ' '; diff --git a/esphome/components/logger/logger.cpp b/esphome/components/logger/logger.cpp index 9d79037087..59dfa93429 100644 --- a/esphome/components/logger/logger.cpp +++ b/esphome/components/logger/logger.cpp @@ -123,7 +123,7 @@ void HOT Logger::log_message_(int level, const char *tag, int offset) { Logger::Logger(uint32_t baud_rate, size_t tx_buffer_size, UARTSelection uart) : baud_rate_(baud_rate), tx_buffer_size_(tx_buffer_size), uart_(uart) { // add 1 to buffer size for null terminator - this->tx_buffer_ = new char[this->tx_buffer_size_ + 1]; + this->tx_buffer_ = new char[this->tx_buffer_size_ + 1]; // NOLINT } void Logger::pre_setup() { diff --git a/esphome/components/max7219/max7219.cpp b/esphome/components/max7219/max7219.cpp index 91bea22e46..97886e53fa 100644 --- a/esphome/components/max7219/max7219.cpp +++ b/esphome/components/max7219/max7219.cpp @@ -117,7 +117,7 @@ float MAX7219Component::get_setup_priority() const { return setup_priority::PROC void MAX7219Component::setup() { ESP_LOGCONFIG(TAG, "Setting up MAX7219..."); this->spi_setup(); - this->buffer_ = new uint8_t[this->num_chips_ * 8]; + this->buffer_ = new uint8_t[this->num_chips_ * 8]; // NOLINT for (uint8_t i = 0; i < this->num_chips_ * 8; i++) this->buffer_[i] = 0; diff --git a/esphome/components/mqtt/mqtt_component.cpp b/esphome/components/mqtt/mqtt_component.cpp index 6ddc080b53..6e376d0fef 100644 --- a/esphome/components/mqtt/mqtt_component.cpp +++ b/esphome/components/mqtt/mqtt_component.cpp @@ -139,8 +139,7 @@ void MQTTComponent::set_custom_command_topic(const std::string &custom_command_t void MQTTComponent::set_availability(std::string topic, std::string payload_available, std::string payload_not_available) { - delete this->availability_; - this->availability_ = new Availability(); + this->availability_ = make_unique(); this->availability_->topic = std::move(topic); this->availability_->payload_available = std::move(payload_available); this->availability_->payload_not_available = std::move(payload_not_available); diff --git a/esphome/components/mqtt/mqtt_component.h b/esphome/components/mqtt/mqtt_component.h index 4d7a522d5f..83a0c06644 100644 --- a/esphome/components/mqtt/mqtt_component.h +++ b/esphome/components/mqtt/mqtt_component.h @@ -1,5 +1,7 @@ #pragma once +#include + #include "esphome/core/component.h" #include "mqtt_client.h" @@ -171,7 +173,7 @@ class MQTTComponent : public Component { std::string custom_command_topic_{}; bool retain_{true}; bool discovery_enabled_{true}; - Availability *availability_{nullptr}; + std::unique_ptr availability_; bool resend_state_{false}; }; diff --git a/esphome/components/neopixelbus/neopixelbus_light.h b/esphome/components/neopixelbus/neopixelbus_light.h index 6fa3fb3cd9..5359bac61b 100644 --- a/esphome/components/neopixelbus/neopixelbus_light.h +++ b/esphome/components/neopixelbus/neopixelbus_light.h @@ -79,7 +79,7 @@ class NeoPixelBusLightOutputBase : public light::AddressableLight { (*this)[i] = Color(0, 0, 0, 0); } - this->effect_data_ = new uint8_t[this->size()]; + this->effect_data_ = new uint8_t[this->size()]; // NOLINT this->controller_->Begin(); } diff --git a/esphome/components/nextion/binary_sensor/nextion_binarysensor.cpp b/esphome/components/nextion/binary_sensor/nextion_binarysensor.cpp index bf6e74cb38..c5bfa78efe 100644 --- a/esphome/components/nextion/binary_sensor/nextion_binarysensor.cpp +++ b/esphome/components/nextion/binary_sensor/nextion_binarysensor.cpp @@ -33,7 +33,7 @@ void NextionBinarySensor::update() { if (this->variable_name_.empty()) // This is a touch component return; - this->nextion_->add_to_get_queue(this); + this->nextion_->add_to_get_queue(shared_from_this()); } void NextionBinarySensor::set_state(bool state, bool publish, bool send_to_nextion) { @@ -48,7 +48,7 @@ void NextionBinarySensor::set_state(bool state, bool publish, bool send_to_nexti this->needs_to_send_update_ = true; } else { this->needs_to_send_update_ = false; - this->nextion_->add_no_result_to_queue_with_set(this, (int) state); + this->nextion_->add_no_result_to_queue_with_set(shared_from_this(), (int) state); } } diff --git a/esphome/components/nextion/binary_sensor/nextion_binarysensor.h b/esphome/components/nextion/binary_sensor/nextion_binarysensor.h index b6b23ada85..b86ee74013 100644 --- a/esphome/components/nextion/binary_sensor/nextion_binarysensor.h +++ b/esphome/components/nextion/binary_sensor/nextion_binarysensor.h @@ -10,7 +10,8 @@ class NextionBinarySensor; class NextionBinarySensor : public NextionComponent, public binary_sensor::BinarySensorInitiallyOff, - public PollingComponent { + public PollingComponent, + public std::enable_shared_from_this { public: NextionBinarySensor(NextionBase *nextion) { this->nextion_ = nextion; } diff --git a/esphome/components/nextion/nextion.cpp b/esphome/components/nextion/nextion.cpp index 3f44fe4075..d56c370412 100644 --- a/esphome/components/nextion/nextion.cpp +++ b/esphome/components/nextion/nextion.cpp @@ -196,7 +196,7 @@ void Nextion::print_queue_members_() { ESP_LOGN(TAG, "print_queue_members_ (top 10) size %zu", this->nextion_queue_.size()); ESP_LOGN(TAG, "*******************************************"); int count = 0; - for (auto *i : this->nextion_queue_) { + for (auto &i : this->nextion_queue_) { if (count++ == 10) break; @@ -257,8 +257,9 @@ bool Nextion::remove_from_q_(bool report_empty) { return false; } - NextionQueue *nb = this->nextion_queue_.front(); - NextionComponentBase *component = nb->component; + auto nb = std::move(this->nextion_queue_.front()); + this->nextion_queue_.pop_front(); + auto &component = nb->component; ESP_LOGN(TAG, "Removing %s from the queue", component->get_variable_name().c_str()); @@ -266,10 +267,8 @@ bool Nextion::remove_from_q_(bool report_empty) { if (component->get_variable_name() == "sleep_wake") { this->is_sleeping_ = false; } - delete component; } - delete nb; - this->nextion_queue_.pop_front(); + return true; } @@ -358,7 +357,7 @@ void Nextion::process_nextion_commands_() { int index = 0; int found = -1; for (auto &nb : this->nextion_queue_) { - NextionComponentBase *component = nb->component; + auto &component = nb->component; if (component->get_queue_type() == NextionQueueType::WAVEFORM_SENSOR) { ESP_LOGW(TAG, "Nextion reported invalid Waveform ID %d or Channel # %d was used!", @@ -369,9 +368,6 @@ void Nextion::process_nextion_commands_() { found = index; - delete component; - delete nb; - break; } ++index; @@ -468,8 +464,9 @@ void Nextion::process_nextion_commands_() { break; } - NextionQueue *nb = this->nextion_queue_.front(); - NextionComponentBase *component = nb->component; + auto nb = std::move(this->nextion_queue_.front()); + this->nextion_queue_.pop_front(); + auto &component = nb->component; if (component->get_queue_type() != NextionQueueType::TEXT_SENSOR) { ESP_LOGE(TAG, "ERROR: Received string return but next in queue \"%s\" is not a text sensor", @@ -480,9 +477,6 @@ void Nextion::process_nextion_commands_() { component->set_state_from_string(to_process, true, false); } - delete nb; - this->nextion_queue_.pop_front(); - break; } // 0x71 0x01 0x02 0x03 0x04 0xFF 0xFF 0xFF @@ -511,8 +505,9 @@ void Nextion::process_nextion_commands_() { ++dataindex; } - NextionQueue *nb = this->nextion_queue_.front(); - NextionComponentBase *component = nb->component; + auto nb = std::move(this->nextion_queue_.front()); + this->nextion_queue_.pop_front(); + auto &component = nb->component; if (component->get_queue_type() != NextionQueueType::SENSOR && component->get_queue_type() != NextionQueueType::BINARY_SENSOR && @@ -526,9 +521,6 @@ void Nextion::process_nextion_commands_() { component->set_state_from_int(value, true, false); } - delete nb; - this->nextion_queue_.pop_front(); - break; } @@ -690,7 +682,7 @@ void Nextion::process_nextion_commands_() { int index = 0; int found = -1; for (auto &nb : this->nextion_queue_) { - auto component = nb->component; + auto &component = nb->component; if (component->get_queue_type() == NextionQueueType::WAVEFORM_SENSOR) { size_t buffer_to_send = component->get_wave_buffer().size() < 255 ? component->get_wave_buffer().size() : 255; // ADDT command can only send 255 @@ -707,8 +699,6 @@ void Nextion::process_nextion_commands_() { component->get_wave_buffer().begin() + buffer_to_send); } found = index; - delete component; - delete nb; break; } ++index; @@ -737,7 +727,7 @@ void Nextion::process_nextion_commands_() { if (!this->nextion_queue_.empty() && this->nextion_queue_.front()->queue_time + this->max_q_age_ms_ < ms) { for (int i = 0; i < this->nextion_queue_.size(); i++) { - NextionComponentBase *component = this->nextion_queue_[i]->component; + auto &component = this->nextion_queue_[i]->component; if (this->nextion_queue_[i]->queue_time + this->max_q_age_ms_ < ms) { if (this->nextion_queue_[i]->queue_time == 0) ESP_LOGD(TAG, "Removing old queue type \"%s\" name \"%s\" queue_time 0", @@ -754,12 +744,10 @@ void Nextion::process_nextion_commands_() { if (component->get_variable_name() == "sleep_wake") { this->is_sleeping_ = false; } - delete component; } - delete this->nextion_queue_[i]; - this->nextion_queue_.erase(this->nextion_queue_.begin() + i); + i--; } else { break; @@ -911,16 +899,16 @@ uint16_t Nextion::recv_ret_string_(std::string &response, uint32_t timeout, bool * @param variable_name Name for the queue */ void Nextion::add_no_result_to_queue_(const std::string &variable_name) { - nextion::NextionQueue *nextion_queue = new nextion::NextionQueue; + auto nextion_queue = make_unique(); - nextion_queue->component = new nextion::NextionComponentBase; + nextion_queue->component = make_unique(); nextion_queue->component->set_variable_name(variable_name); nextion_queue->queue_time = millis(); - this->nextion_queue_.push_back(nextion_queue); - ESP_LOGN(TAG, "Add to queue type: NORESULT component %s", nextion_queue->component->get_variable_name().c_str()); + + this->nextion_queue_.push_back(std::move(nextion_queue)); } /** @@ -991,7 +979,7 @@ bool Nextion::add_no_result_to_queue_with_printf_(const std::string &variable_na * @param is_sleep_safe The command is safe to send when the Nextion is sleeping */ -void Nextion::add_no_result_to_queue_with_set(NextionComponentBase *component, int state_value) { +void Nextion::add_no_result_to_queue_with_set(std::shared_ptr component, int state_value) { this->add_no_result_to_queue_with_set(component->get_variable_name(), component->get_variable_name_to_send(), state_value); } @@ -1019,7 +1007,8 @@ void Nextion::add_no_result_to_queue_with_set_internal_(const std::string &varia * @param state_value String value to set * @param is_sleep_safe The command is safe to send when the Nextion is sleeping */ -void Nextion::add_no_result_to_queue_with_set(NextionComponentBase *component, const std::string &state_value) { +void Nextion::add_no_result_to_queue_with_set(std::shared_ptr component, + const std::string &state_value) { this->add_no_result_to_queue_with_set(component->get_variable_name(), component->get_variable_name_to_send(), state_value); } @@ -1039,11 +1028,11 @@ void Nextion::add_no_result_to_queue_with_set_internal_(const std::string &varia state_value.c_str()); } -void Nextion::add_to_get_queue(NextionComponentBase *component) { +void Nextion::add_to_get_queue(std::shared_ptr component) { if ((!this->is_setup() && !this->ignore_is_setup_)) return; - nextion::NextionQueue *nextion_queue = new nextion::NextionQueue; + auto nextion_queue = make_unique(); nextion_queue->component = component; nextion_queue->queue_time = millis(); @@ -1054,7 +1043,7 @@ void Nextion::add_to_get_queue(NextionComponentBase *component) { std::string command = "get " + component->get_variable_name_to_send(); if (this->send_command_(command)) { - this->nextion_queue_.push_back(nextion_queue); + this->nextion_queue_.push_back(std::move(nextion_queue)); } } @@ -1066,13 +1055,13 @@ void Nextion::add_to_get_queue(NextionComponentBase *component) { * @param buffer_to_send The buffer size * @param buffer_size The buffer data */ -void Nextion::add_addt_command_to_queue(NextionComponentBase *component) { +void Nextion::add_addt_command_to_queue(std::shared_ptr component) { if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping()) return; - nextion::NextionQueue *nextion_queue = new nextion::NextionQueue; + auto nextion_queue = make_unique(); - nextion_queue->component = new nextion::NextionComponentBase; + nextion_queue->component = std::make_shared(); nextion_queue->queue_time = millis(); size_t buffer_to_send = component->get_wave_buffer_size() < 255 ? component->get_wave_buffer_size() @@ -1081,7 +1070,7 @@ void Nextion::add_addt_command_to_queue(NextionComponentBase *component) { std::string command = "addt " + to_string(component->get_component_id()) + "," + to_string(component->get_wave_channel_id()) + "," + to_string(buffer_to_send); if (this->send_command_(command)) { - this->nextion_queue_.push_back(nextion_queue); + this->nextion_queue_.push_back(std::move(nextion_queue)); } } diff --git a/esphome/components/nextion/nextion.h b/esphome/components/nextion/nextion.h index 3a43a51975..45c4a629c4 100644 --- a/esphome/components/nextion/nextion.h +++ b/esphome/components/nextion/nextion.h @@ -707,17 +707,18 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe void set_nextion_sensor_state(NextionQueueType queue_type, const std::string &name, float state); void set_nextion_text_state(const std::string &name, const std::string &state); - void add_no_result_to_queue_with_set(NextionComponentBase *component, int state_value) override; + void add_no_result_to_queue_with_set(std::shared_ptr component, int state_value) override; void add_no_result_to_queue_with_set(const std::string &variable_name, const std::string &variable_name_to_send, int state_value) override; - void add_no_result_to_queue_with_set(NextionComponentBase *component, const std::string &state_value) override; + void add_no_result_to_queue_with_set(std::shared_ptr component, + const std::string &state_value) override; void add_no_result_to_queue_with_set(const std::string &variable_name, const std::string &variable_name_to_send, const std::string &state_value) override; - void add_to_get_queue(NextionComponentBase *component) override; + void add_to_get_queue(std::shared_ptr component) override; - void add_addt_command_to_queue(NextionComponentBase *component) override; + void add_addt_command_to_queue(std::shared_ptr component) override; void update_components_by_prefix(const std::string &prefix); @@ -728,7 +729,7 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe void set_auto_wake_on_touch_internal(bool auto_wake_on_touch) { this->auto_wake_on_touch_ = auto_wake_on_touch; } protected: - std::deque nextion_queue_; + std::deque> nextion_queue_; uint16_t recv_ret_string_(std::string &response, uint32_t timeout, bool recv_flag); void all_components_send_state_(bool force_update = false); uint64_t comok_sent_ = 0; diff --git a/esphome/components/nextion/nextion_base.h b/esphome/components/nextion/nextion_base.h index a24fd74060..d91c70c960 100644 --- a/esphome/components/nextion/nextion_base.h +++ b/esphome/components/nextion/nextion_base.h @@ -24,18 +24,19 @@ class NextionBase; class NextionBase { public: - virtual void add_no_result_to_queue_with_set(NextionComponentBase *component, int state_value) = 0; + virtual void add_no_result_to_queue_with_set(std::shared_ptr component, int state_value) = 0; virtual void add_no_result_to_queue_with_set(const std::string &variable_name, const std::string &variable_name_to_send, int state_value) = 0; - virtual void add_no_result_to_queue_with_set(NextionComponentBase *component, const std::string &state_value) = 0; + virtual void add_no_result_to_queue_with_set(std::shared_ptr component, + const std::string &state_value) = 0; virtual void add_no_result_to_queue_with_set(const std::string &variable_name, const std::string &variable_name_to_send, const std::string &state_value) = 0; - virtual void add_addt_command_to_queue(NextionComponentBase *component) = 0; + virtual void add_addt_command_to_queue(std::shared_ptr component) = 0; - virtual void add_to_get_queue(NextionComponentBase *component) = 0; + virtual void add_to_get_queue(std::shared_ptr component) = 0; virtual void set_component_background_color(const char *component, Color color) = 0; virtual void set_component_pressed_background_color(const char *component, Color color) = 0; diff --git a/esphome/components/nextion/nextion_component_base.h b/esphome/components/nextion/nextion_component_base.h index 71ad803bc4..2725d5a30c 100644 --- a/esphome/components/nextion/nextion_component_base.h +++ b/esphome/components/nextion/nextion_component_base.h @@ -1,5 +1,6 @@ #pragma once #include +#include #include "esphome/core/defines.h" namespace esphome { @@ -22,7 +23,7 @@ class NextionComponentBase; class NextionQueue { public: virtual ~NextionQueue() = default; - NextionComponentBase *component; + std::shared_ptr component; uint32_t queue_time = 0; }; diff --git a/esphome/components/nextion/nextion_upload.cpp b/esphome/components/nextion/nextion_upload.cpp index 43c8867e56..a83618e888 100644 --- a/esphome/components/nextion/nextion_upload.cpp +++ b/esphome/components/nextion/nextion_upload.cpp @@ -275,12 +275,12 @@ void Nextion::upload_tft() { } else { #endif ESP_LOGD(TAG, "Allocating buffer size %d, Heap size is %u", chunk_size, ESP.getFreeHeap()); - this->transfer_buffer_ = new (std::nothrow) uint8_t[chunk_size]; - if (this->transfer_buffer_ == nullptr) { // Try a smaller size + this->transfer_buffer_ = new (std::nothrow) uint8_t[chunk_size]; // NOLINT(cppcoreguidelines-owning-memory) + if (this->transfer_buffer_ == nullptr) { // Try a smaller size ESP_LOGD(TAG, "Could not allocate buffer size: %d trying 4096 instead", chunk_size); chunk_size = 4096; ESP_LOGD(TAG, "Allocating %d buffer", chunk_size); - this->transfer_buffer_ = new uint8_t[chunk_size]; + this->transfer_buffer_ = new (std::nothrow) uint8_t[chunk_size]; // NOLINT(cppcoreguidelines-owning-memory) if (!this->transfer_buffer_) this->upload_end_(); @@ -322,7 +322,7 @@ void Nextion::upload_end_() { WiFiClient *Nextion::get_wifi_client_() { if (this->tft_url_.compare(0, 6, "https:") == 0) { if (this->wifi_client_secure_ == nullptr) { - this->wifi_client_secure_ = new BearSSL::WiFiClientSecure(); + this->wifi_client_secure_ = new BearSSL::WiFiClientSecure(); // NOLINT(cppcoreguidelines-owning-memory) this->wifi_client_secure_->setInsecure(); this->wifi_client_secure_->setBufferSizes(512, 512); } @@ -330,7 +330,7 @@ WiFiClient *Nextion::get_wifi_client_() { } if (this->wifi_client_ == nullptr) { - this->wifi_client_ = new WiFiClient(); + this->wifi_client_ = new WiFiClient(); // NOLINT(cppcoreguidelines-owning-memory) } return this->wifi_client_; } diff --git a/esphome/components/nextion/sensor/nextion_sensor.cpp b/esphome/components/nextion/sensor/nextion_sensor.cpp index bbcb465d85..1e79164546 100644 --- a/esphome/components/nextion/sensor/nextion_sensor.cpp +++ b/esphome/components/nextion/sensor/nextion_sensor.cpp @@ -34,7 +34,7 @@ void NextionSensor::update() { return; if (this->wave_chan_id_ == UINT8_MAX) { - this->nextion_->add_to_get_queue(this); + this->nextion_->add_to_get_queue(shared_from_this()); } else { if (this->send_last_value_) { this->add_to_wave_buffer(this->last_value_); @@ -62,9 +62,9 @@ void NextionSensor::set_state(float state, bool publish, bool send_to_nextion) { double to_multiply = pow(10, this->precision_); int state_value = (int) (state * to_multiply); - this->nextion_->add_no_result_to_queue_with_set(this, (int) state_value); + this->nextion_->add_no_result_to_queue_with_set(shared_from_this(), (int) state_value); } else { - this->nextion_->add_no_result_to_queue_with_set(this, (int) state); + this->nextion_->add_no_result_to_queue_with_set(shared_from_this(), (int) state); } } } @@ -103,7 +103,7 @@ void NextionSensor::wave_update_() { buffer_to_send, this->wave_buffer_.size(), this->component_id_, this->wave_chan_id_); #endif - this->nextion_->add_addt_command_to_queue(this); + this->nextion_->add_addt_command_to_queue(shared_from_this()); } } // namespace nextion diff --git a/esphome/components/nextion/sensor/nextion_sensor.h b/esphome/components/nextion/sensor/nextion_sensor.h index e4dde9a513..068ff0451b 100644 --- a/esphome/components/nextion/sensor/nextion_sensor.h +++ b/esphome/components/nextion/sensor/nextion_sensor.h @@ -8,7 +8,10 @@ namespace esphome { namespace nextion { class NextionSensor; -class NextionSensor : public NextionComponent, public sensor::Sensor, public PollingComponent { +class NextionSensor : public NextionComponent, + public sensor::Sensor, + public PollingComponent, + public std::enable_shared_from_this { public: NextionSensor(NextionBase *nextion) { this->nextion_ = nextion; } void send_state_to_nextion() override { this->set_state(this->state, false, true); }; diff --git a/esphome/components/nextion/switch/nextion_switch.cpp b/esphome/components/nextion/switch/nextion_switch.cpp index 1f32ad3425..0bd958e0d8 100644 --- a/esphome/components/nextion/switch/nextion_switch.cpp +++ b/esphome/components/nextion/switch/nextion_switch.cpp @@ -20,7 +20,7 @@ void NextionSwitch::process_bool(const std::string &variable_name, bool on) { void NextionSwitch::update() { if (!this->nextion_->is_setup()) return; - this->nextion_->add_to_get_queue(this); + this->nextion_->add_to_get_queue(shared_from_this()); } void NextionSwitch::set_state(bool state, bool publish, bool send_to_nextion) { @@ -32,7 +32,7 @@ void NextionSwitch::set_state(bool state, bool publish, bool send_to_nextion) { this->needs_to_send_update_ = true; } else { this->needs_to_send_update_ = false; - this->nextion_->add_no_result_to_queue_with_set(this, (int) state); + this->nextion_->add_no_result_to_queue_with_set(shared_from_this(), (int) state); } } if (publish) { diff --git a/esphome/components/nextion/switch/nextion_switch.h b/esphome/components/nextion/switch/nextion_switch.h index 1548287473..d7783e5c51 100644 --- a/esphome/components/nextion/switch/nextion_switch.h +++ b/esphome/components/nextion/switch/nextion_switch.h @@ -8,7 +8,10 @@ namespace esphome { namespace nextion { class NextionSwitch; -class NextionSwitch : public NextionComponent, public switch_::Switch, public PollingComponent { +class NextionSwitch : public NextionComponent, + public switch_::Switch, + public PollingComponent, + public std::enable_shared_from_this { public: NextionSwitch(NextionBase *nextion) { this->nextion_ = nextion; } diff --git a/esphome/components/nextion/text_sensor/nextion_textsensor.cpp b/esphome/components/nextion/text_sensor/nextion_textsensor.cpp index 08f032df74..fa7cb35025 100644 --- a/esphome/components/nextion/text_sensor/nextion_textsensor.cpp +++ b/esphome/components/nextion/text_sensor/nextion_textsensor.cpp @@ -18,7 +18,7 @@ void NextionTextSensor::process_text(const std::string &variable_name, const std void NextionTextSensor::update() { if (!this->nextion_->is_setup()) return; - this->nextion_->add_to_get_queue(this); + this->nextion_->add_to_get_queue(shared_from_this()); } void NextionTextSensor::set_state(const std::string &state, bool publish, bool send_to_nextion) { @@ -29,7 +29,7 @@ void NextionTextSensor::set_state(const std::string &state, bool publish, bool s if (this->nextion_->is_sleeping() || !this->visible_) { this->needs_to_send_update_ = true; } else { - this->nextion_->add_no_result_to_queue_with_set(this, state); + this->nextion_->add_no_result_to_queue_with_set(shared_from_this(), state); } } diff --git a/esphome/components/nextion/text_sensor/nextion_textsensor.h b/esphome/components/nextion/text_sensor/nextion_textsensor.h index 5716d0a008..762797727d 100644 --- a/esphome/components/nextion/text_sensor/nextion_textsensor.h +++ b/esphome/components/nextion/text_sensor/nextion_textsensor.h @@ -8,7 +8,10 @@ namespace esphome { namespace nextion { class NextionTextSensor; -class NextionTextSensor : public NextionComponent, public text_sensor::TextSensor, public PollingComponent { +class NextionTextSensor : public NextionComponent, + public text_sensor::TextSensor, + public PollingComponent, + public std::enable_shared_from_this { public: NextionTextSensor(NextionBase *nextion) { this->nextion_ = nextion; } void update() override; diff --git a/esphome/components/nfc/ndef_message.cpp b/esphome/components/nfc/ndef_message.cpp index 4e295d4469..b1554f41ae 100644 --- a/esphome/components/nfc/ndef_message.cpp +++ b/esphome/components/nfc/ndef_message.cpp @@ -17,7 +17,7 @@ NdefMessage::NdefMessage(std::vector &data) { ESP_LOGVV(TAG, "me=%s, sr=%s, il=%s, tnf=%d", YESNO(me), YESNO(sr), YESNO(il), tnf); - auto record = new NdefRecord(); + auto record = make_unique(); record->set_tnf(tnf); uint8_t type_length = data[index++]; @@ -62,20 +62,20 @@ NdefMessage::NdefMessage(std::vector &data) { record->set_payload(payload_str); index += payload_length; - this->add_record(record); ESP_LOGV(TAG, "Adding record type %s = %s", record->get_type().c_str(), record->get_payload().c_str()); + this->add_record(std::move(record)); if (me) break; } } -bool NdefMessage::add_record(NdefRecord *record) { +bool NdefMessage::add_record(std::unique_ptr record) { if (this->records_.size() >= MAX_NDEF_RECORDS) { ESP_LOGE(TAG, "Too many records. Max: %d", MAX_NDEF_RECORDS); return false; } - this->records_.push_back(record); + this->records_.emplace_back(std::move(record)); return true; } @@ -83,13 +83,11 @@ bool NdefMessage::add_text_record(const std::string &text) { return this->add_te bool NdefMessage::add_text_record(const std::string &text, const std::string &encoding) { std::string payload = to_string(text.length()) + encoding + text; - auto r = new NdefRecord(TNF_WELL_KNOWN, "T", payload); - return this->add_record(r); + return this->add_record(make_unique(TNF_WELL_KNOWN, "T", payload)); } bool NdefMessage::add_uri_record(const std::string &uri) { - auto r = new NdefRecord(TNF_WELL_KNOWN, "U", uri); - return this->add_record(r); + return this->add_record(make_unique(TNF_WELL_KNOWN, "U", uri)); } std::vector NdefMessage::encode() { diff --git a/esphome/components/nfc/ndef_message.h b/esphome/components/nfc/ndef_message.h index e47a7b992a..d2ffa9582e 100644 --- a/esphome/components/nfc/ndef_message.h +++ b/esphome/components/nfc/ndef_message.h @@ -1,5 +1,7 @@ #pragma once +#include + #include "esphome/core/helpers.h" #include "esphome/core/log.h" #include "ndef_record.h" @@ -11,12 +13,18 @@ static const uint8_t MAX_NDEF_RECORDS = 4; class NdefMessage { public: - NdefMessage(){}; + NdefMessage() = default; NdefMessage(std::vector &data); + NdefMessage(const NdefMessage &msg) { + records_.reserve(msg.records_.size()); + for (const auto &r : msg.records_) { + records_.emplace_back(make_unique(*r)); + } + } - std::vector get_records() { return this->records_; }; + const std::vector> &get_records() { return this->records_; }; - bool add_record(NdefRecord *record); + bool add_record(std::unique_ptr record); bool add_text_record(const std::string &text); bool add_text_record(const std::string &text, const std::string &encoding); bool add_uri_record(const std::string &uri); @@ -24,7 +32,7 @@ class NdefMessage { std::vector encode(); protected: - std::vector records_; + std::vector> records_; }; } // namespace nfc diff --git a/esphome/components/nfc/ndef_record.h b/esphome/components/nfc/ndef_record.h index 2059444882..680fe20986 100644 --- a/esphome/components/nfc/ndef_record.h +++ b/esphome/components/nfc/ndef_record.h @@ -85,9 +85,9 @@ class NdefRecord { std::vector encode(bool first, bool last); uint8_t get_tnf_byte(bool first, bool last); - const std::string &get_type() { return this->type_; }; - const std::string &get_id() { return this->id_; }; - const std::string &get_payload() { return this->payload_; }; + const std::string &get_type() const { return this->type_; }; + const std::string &get_id() const { return this->id_; }; + const std::string &get_payload() const { return this->payload_; }; protected: uint8_t tnf_; diff --git a/esphome/components/nfc/nfc_tag.h b/esphome/components/nfc/nfc_tag.h index ff0d1c39b4..ab6ca650e4 100644 --- a/esphome/components/nfc/nfc_tag.h +++ b/esphome/components/nfc/nfc_tag.h @@ -1,6 +1,9 @@ #pragma once +#include + #include "esphome/core/log.h" +#include "esphome/core/helpers.h" #include "ndef_message.h" namespace esphome { @@ -20,27 +23,33 @@ class NfcTag { this->uid_ = uid; this->tag_type_ = tag_type; }; - NfcTag(std::vector &uid, const std::string &tag_type, nfc::NdefMessage *ndef_message) { + NfcTag(std::vector &uid, const std::string &tag_type, std::unique_ptr ndef_message) { this->uid_ = uid; this->tag_type_ = tag_type; - this->ndef_message_ = ndef_message; + this->ndef_message_ = std::move(ndef_message); }; NfcTag(std::vector &uid, const std::string &tag_type, std::vector &ndef_data) { this->uid_ = uid; this->tag_type_ = tag_type; - this->ndef_message_ = new NdefMessage(ndef_data); + this->ndef_message_ = make_unique(ndef_data); }; + NfcTag(const NfcTag &rhs) { + uid_ = rhs.uid_; + tag_type_ = rhs.tag_type_; + if (rhs.ndef_message_ != nullptr) + ndef_message_ = make_unique(*rhs.ndef_message_); + } std::vector &get_uid() { return this->uid_; }; const std::string &get_tag_type() { return this->tag_type_; }; bool has_ndef_message() { return this->ndef_message_ != nullptr; }; - NdefMessage *get_ndef_message() { return this->ndef_message_; }; - void set_ndef_message(NdefMessage *ndef_message) { this->ndef_message_ = ndef_message; }; + const std::unique_ptr &get_ndef_message() { return this->ndef_message_; }; + void set_ndef_message(std::unique_ptr ndef_message) { this->ndef_message_ = std::move(ndef_message); }; protected: std::vector uid_; std::string tag_type_; - NdefMessage *ndef_message_{nullptr}; + std::unique_ptr ndef_message_; }; } // namespace nfc diff --git a/esphome/components/ota/ota_component.cpp b/esphome/components/ota/ota_component.cpp index ac72befb9e..e8ac1b9bcd 100644 --- a/esphome/components/ota/ota_component.cpp +++ b/esphome/components/ota/ota_component.cpp @@ -19,7 +19,7 @@ static const char *const TAG = "ota"; static const uint8_t OTA_VERSION_1_0 = 1; void OTAComponent::setup() { - this->server_ = new WiFiServer(this->port_); + this->server_ = make_unique(this->port_); this->server_->begin(); this->dump_config(); diff --git a/esphome/components/ota/ota_component.h b/esphome/components/ota/ota_component.h index 8b5830295e..04cea56ec2 100644 --- a/esphome/components/ota/ota_component.h +++ b/esphome/components/ota/ota_component.h @@ -1,5 +1,7 @@ #pragma once +#include + #include "esphome/core/component.h" #include "esphome/core/preferences.h" #include "esphome/core/helpers.h" @@ -80,7 +82,7 @@ class OTAComponent : public Component { uint16_t port_; - WiFiServer *server_{nullptr}; + std::unique_ptr server_{nullptr}; WiFiClient client_{}; bool has_safe_mode_{false}; ///< stores whether safe mode can be enabled. diff --git a/esphome/components/pca9685/output.py b/esphome/components/pca9685/output.py index 40f7b3cd74..b7681f9ba0 100644 --- a/esphome/components/pca9685/output.py +++ b/esphome/components/pca9685/output.py @@ -20,6 +20,7 @@ CONFIG_SCHEMA = output.FLOAT_OUTPUT_SCHEMA.extend( async def to_code(config): paren = await cg.get_variable(config[CONF_PCA9685_ID]) - rhs = paren.create_channel(config[CONF_CHANNEL]) - var = cg.Pvariable(config[CONF_ID], rhs) + var = cg.new_Pvariable(config[CONF_ID]) + cg.add(var.set_channel(config[CONF_CHANNEL])) + cg.add(paren.register_channel(var)) await output.register_output(var, config) diff --git a/esphome/components/pca9685/pca9685_output.cpp b/esphome/components/pca9685/pca9685_output.cpp index c3fd2b60e4..1ad6f4a665 100644 --- a/esphome/components/pca9685/pca9685_output.cpp +++ b/esphome/components/pca9685/pca9685_output.cpp @@ -123,11 +123,11 @@ void PCA9685Output::loop() { this->update_ = false; } -PCA9685Channel *PCA9685Output::create_channel(uint8_t channel) { - this->min_channel_ = std::min(this->min_channel_, channel); - this->max_channel_ = std::max(this->max_channel_, channel); - auto *c = new PCA9685Channel(this, channel); - return c; +void PCA9685Output::register_channel(PCA9685Channel *channel) { + auto c = channel->channel_; + this->min_channel_ = std::min(this->min_channel_, c); + this->max_channel_ = std::max(this->max_channel_, c); + channel->set_parent(this); } void PCA9685Channel::write_state(float state) { diff --git a/esphome/components/pca9685/pca9685_output.h b/esphome/components/pca9685/pca9685_output.h index 55b52fc660..bd3f7f15f9 100644 --- a/esphome/components/pca9685/pca9685_output.h +++ b/esphome/components/pca9685/pca9685_output.h @@ -20,14 +20,15 @@ extern const uint8_t PCA9685_MODE_OUTNE_LOW; class PCA9685Output; -class PCA9685Channel : public output::FloatOutput { +class PCA9685Channel : public output::FloatOutput, public Parented { public: - PCA9685Channel(PCA9685Output *parent, uint8_t channel) : parent_(parent), channel_(channel) {} + void set_channel(uint8_t channel) { channel_ = channel; } protected: + friend class PCA9685Output; + void write_state(float state) override; - PCA9685Output *parent_; uint8_t channel_; }; @@ -37,7 +38,7 @@ class PCA9685Output : public Component, public i2c::I2CDevice { PCA9685Output(float frequency, uint8_t mode = PCA9685_MODE_OUTPUT_ONACK | PCA9685_MODE_OUTPUT_TOTEM_POLE) : frequency_(frequency), mode_(mode) {} - PCA9685Channel *create_channel(uint8_t channel); + void register_channel(PCA9685Channel *channel); void setup() override; void dump_config() override; diff --git a/esphome/components/pipsolar/pipsolar.cpp b/esphome/components/pipsolar/pipsolar.cpp index 9c7adc13c1..8603adfbf4 100644 --- a/esphome/components/pipsolar/pipsolar.cpp +++ b/esphome/components/pipsolar/pipsolar.cpp @@ -881,7 +881,7 @@ void Pipsolar::add_polling_command_(const char *command, ENUMPollingCommand poll size_t length = strlen(command) + 1; const char *beg = command; const char *end = command + length; - used_polling_command.command = new uint8_t[length]; + used_polling_command.command = new uint8_t[length]; // NOLINT(cppcoreguidelines-owning-memory) size_t i = 0; for (; beg != end; ++beg, ++i) { used_polling_command.command[i] = (uint8_t)(*beg); diff --git a/esphome/components/pn532/pn532.cpp b/esphome/components/pn532/pn532.cpp index fcab9872c4..8fda19cba3 100644 --- a/esphome/components/pn532/pn532.cpp +++ b/esphome/components/pn532/pn532.cpp @@ -104,7 +104,7 @@ void PN532::loop() { if (!success) { // Something failed if (!this->current_uid_.empty()) { - auto tag = new nfc::NfcTag(this->current_uid_); + auto tag = make_unique(this->current_uid_); for (auto *trigger : this->triggers_ontagremoved_) trigger->process(tag); } @@ -117,7 +117,7 @@ void PN532::loop() { if (num_targets != 1) { // no tags found or too many if (!this->current_uid_.empty()) { - auto tag = new nfc::NfcTag(this->current_uid_); + auto tag = make_unique(this->current_uid_); for (auto *trigger : this->triggers_ontagremoved_) trigger->process(tag); } @@ -158,10 +158,10 @@ void PN532::loop() { if (report) { ESP_LOGD(TAG, "Found new tag '%s'", nfc::format_uid(nfcid).c_str()); if (tag->has_ndef_message()) { - auto message = tag->get_ndef_message(); - auto records = message->get_records(); + const auto &message = tag->get_ndef_message(); + const auto &records = message->get_records(); ESP_LOGD(TAG, " NDEF formatted records:"); - for (auto &record : records) { + for (const auto &record : records) { ESP_LOGD(TAG, " %s - %s", record->get_type().c_str(), record->get_payload().c_str()); } } @@ -270,7 +270,7 @@ void PN532::turn_off_rf_() { }); } -nfc::NfcTag *PN532::read_tag_(std::vector &uid) { +std::unique_ptr PN532::read_tag_(std::vector &uid) { uint8_t type = nfc::guess_tag_type(uid.size()); if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) { @@ -281,9 +281,9 @@ nfc::NfcTag *PN532::read_tag_(std::vector &uid) { return this->read_mifare_ultralight_tag_(uid); } else if (type == nfc::TAG_TYPE_UNKNOWN) { ESP_LOGV(TAG, "Cannot determine tag type"); - return new nfc::NfcTag(uid); + return make_unique(uid); } else { - return new nfc::NfcTag(uid); + return make_unique(uid); } } @@ -373,7 +373,9 @@ bool PN532BinarySensor::process(std::vector &data) { this->found_ = true; return true; } -void PN532OnTagTrigger::process(nfc::NfcTag *tag) { this->trigger(nfc::format_uid(tag->get_uid()), *tag); } +void PN532OnTagTrigger::process(const std::unique_ptr &tag) { + this->trigger(nfc::format_uid(tag->get_uid()), *tag); +} } // namespace pn532 } // namespace esphome diff --git a/esphome/components/pn532/pn532.h b/esphome/components/pn532/pn532.h index c4854cf7f2..692a5011e6 100644 --- a/esphome/components/pn532/pn532.h +++ b/esphome/components/pn532/pn532.h @@ -54,13 +54,13 @@ class PN532 : public PollingComponent { virtual bool read_data(std::vector &data, uint8_t len) = 0; virtual bool read_response(uint8_t command, std::vector &data) = 0; - nfc::NfcTag *read_tag_(std::vector &uid); + std::unique_ptr read_tag_(std::vector &uid); bool format_tag_(std::vector &uid); bool clean_tag_(std::vector &uid); bool write_tag_(std::vector &uid, nfc::NdefMessage *message); - nfc::NfcTag *read_mifare_classic_tag_(std::vector &uid); + std::unique_ptr read_mifare_classic_tag_(std::vector &uid); bool read_mifare_classic_block_(uint8_t block_num, std::vector &data); bool write_mifare_classic_block_(uint8_t block_num, std::vector &data); bool auth_mifare_classic_block_(std::vector &uid, uint8_t block_num, uint8_t key_num, const uint8_t *key); @@ -68,7 +68,7 @@ class PN532 : public PollingComponent { bool format_mifare_classic_ndef_(std::vector &uid); bool write_mifare_classic_tag_(std::vector &uid, nfc::NdefMessage *message); - nfc::NfcTag *read_mifare_ultralight_tag_(std::vector &uid); + std::unique_ptr read_mifare_ultralight_tag_(std::vector &uid); bool read_mifare_ultralight_page_(uint8_t page_num, std::vector &data); bool is_mifare_ultralight_formatted_(); uint16_t read_mifare_ultralight_capacity_(); @@ -117,7 +117,7 @@ class PN532BinarySensor : public binary_sensor::BinarySensor { class PN532OnTagTrigger : public Trigger { public: - void process(nfc::NfcTag *tag); + void process(const std::unique_ptr &tag); }; class PN532OnFinishedWriteTrigger : public Trigger<> { diff --git a/esphome/components/pn532/pn532_mifare_classic.cpp b/esphome/components/pn532/pn532_mifare_classic.cpp index 119d1ceef6..fa99e5cfab 100644 --- a/esphome/components/pn532/pn532_mifare_classic.cpp +++ b/esphome/components/pn532/pn532_mifare_classic.cpp @@ -6,7 +6,7 @@ namespace pn532 { static const char *const TAG = "pn532.mifare_classic"; -nfc::NfcTag *PN532::read_mifare_classic_tag_(std::vector &uid) { +std::unique_ptr PN532::read_mifare_classic_tag_(std::vector &uid) { uint8_t current_block = 4; uint8_t message_start_index = 0; uint32_t message_length = 0; @@ -15,15 +15,15 @@ nfc::NfcTag *PN532::read_mifare_classic_tag_(std::vector &uid) { std::vector data; if (this->read_mifare_classic_block_(current_block, data)) { if (!nfc::decode_mifare_classic_tlv(data, message_length, message_start_index)) { - return new nfc::NfcTag(uid, nfc::ERROR); + return make_unique(uid, nfc::ERROR); } } else { ESP_LOGE(TAG, "Failed to read block %d", current_block); - return new nfc::NfcTag(uid, nfc::MIFARE_CLASSIC); + return make_unique(uid, nfc::MIFARE_CLASSIC); } } else { ESP_LOGV(TAG, "Tag is not NDEF formatted"); - return new nfc::NfcTag(uid, nfc::MIFARE_CLASSIC); + return make_unique(uid, nfc::MIFARE_CLASSIC); } uint32_t index = 0; @@ -51,7 +51,7 @@ nfc::NfcTag *PN532::read_mifare_classic_tag_(std::vector &uid) { } } buffer.erase(buffer.begin(), buffer.begin() + message_start_index); - return new nfc::NfcTag(uid, nfc::MIFARE_CLASSIC, buffer); + return make_unique(uid, nfc::MIFARE_CLASSIC, buffer); } bool PN532::read_mifare_classic_block_(uint8_t block_num, std::vector &data) { diff --git a/esphome/components/pn532/pn532_mifare_ultralight.cpp b/esphome/components/pn532/pn532_mifare_ultralight.cpp index 1787a3c225..6f118419ba 100644 --- a/esphome/components/pn532/pn532_mifare_ultralight.cpp +++ b/esphome/components/pn532/pn532_mifare_ultralight.cpp @@ -6,28 +6,28 @@ namespace pn532 { static const char *const TAG = "pn532.mifare_ultralight"; -nfc::NfcTag *PN532::read_mifare_ultralight_tag_(std::vector &uid) { +std::unique_ptr PN532::read_mifare_ultralight_tag_(std::vector &uid) { if (!this->is_mifare_ultralight_formatted_()) { ESP_LOGD(TAG, "Not NDEF formatted"); - return new nfc::NfcTag(uid, nfc::NFC_FORUM_TYPE_2); + return make_unique(uid, nfc::NFC_FORUM_TYPE_2); } uint8_t message_length; uint8_t message_start_index; if (!this->find_mifare_ultralight_ndef_(message_length, message_start_index)) { - return new nfc::NfcTag(uid, nfc::NFC_FORUM_TYPE_2); + return make_unique(uid, nfc::NFC_FORUM_TYPE_2); } ESP_LOGVV(TAG, "message length: %d, start: %d", message_length, message_start_index); if (message_length == 0) { - return new nfc::NfcTag(uid, nfc::NFC_FORUM_TYPE_2); + return make_unique(uid, nfc::NFC_FORUM_TYPE_2); } std::vector data; for (uint8_t page = nfc::MIFARE_ULTRALIGHT_DATA_START_PAGE; page < nfc::MIFARE_ULTRALIGHT_MAX_PAGE; page++) { std::vector page_data; if (!this->read_mifare_ultralight_page_(page, page_data)) { ESP_LOGE(TAG, "Error reading page %d", page); - return new nfc::NfcTag(uid, nfc::NFC_FORUM_TYPE_2); + return make_unique(uid, nfc::NFC_FORUM_TYPE_2); } data.insert(data.end(), page_data.begin(), page_data.end()); @@ -38,7 +38,7 @@ nfc::NfcTag *PN532::read_mifare_ultralight_tag_(std::vector &uid) { data.erase(data.begin(), data.begin() + message_start_index); data.erase(data.begin() + message_length, data.end()); - return new nfc::NfcTag(uid, nfc::NFC_FORUM_TYPE_2, data); + return make_unique(uid, nfc::NFC_FORUM_TYPE_2, data); } bool PN532::read_mifare_ultralight_page_(uint8_t page_num, std::vector &data) { diff --git a/esphome/components/scd30/scd30.cpp b/esphome/components/scd30/scd30.cpp index 838c92f04e..8dfd992abe 100644 --- a/esphome/components/scd30/scd30.cpp +++ b/esphome/components/scd30/scd30.cpp @@ -221,10 +221,9 @@ uint8_t SCD30Component::sht_crc_(uint8_t data1, uint8_t data2) { bool SCD30Component::read_data_(uint16_t *data, uint8_t len) { const uint8_t num_bytes = len * 3; - auto *buf = new uint8_t[num_bytes]; + std::vector buf(num_bytes); - if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { - delete[](buf); + if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) { return false; } @@ -233,13 +232,11 @@ bool SCD30Component::read_data_(uint16_t *data, uint8_t len) { uint8_t crc = sht_crc_(buf[j], buf[j + 1]); if (crc != buf[j + 2]) { ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); - delete[](buf); return false; } data[i] = (buf[j] << 8) | buf[j + 1]; } - delete[](buf); return true; } diff --git a/esphome/components/sgp30/sgp30.cpp b/esphome/components/sgp30/sgp30.cpp index e30d6d3adc..5a6f438429 100644 --- a/esphome/components/sgp30/sgp30.cpp +++ b/esphome/components/sgp30/sgp30.cpp @@ -332,10 +332,9 @@ uint8_t SGP30Component::sht_crc_(uint8_t data1, uint8_t data2) { bool SGP30Component::read_data_(uint16_t *data, uint8_t len) { const uint8_t num_bytes = len * 3; - auto *buf = new uint8_t[num_bytes]; + std::vector buf(num_bytes); - if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { - delete[](buf); + if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) { return false; } @@ -344,13 +343,11 @@ bool SGP30Component::read_data_(uint16_t *data, uint8_t len) { uint8_t crc = sht_crc_(buf[j], buf[j + 1]); if (crc != buf[j + 2]) { ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); - delete[](buf); return false; } data[i] = (buf[j] << 8) | buf[j + 1]; } - delete[](buf); return true; } diff --git a/esphome/components/sht3xd/sht3xd.cpp b/esphome/components/sht3xd/sht3xd.cpp index 0bf2cc1a81..be5b93c124 100644 --- a/esphome/components/sht3xd/sht3xd.cpp +++ b/esphome/components/sht3xd/sht3xd.cpp @@ -101,10 +101,9 @@ uint8_t sht_crc(uint8_t data1, uint8_t data2) { bool SHT3XDComponent::read_data_(uint16_t *data, uint8_t len) { const uint8_t num_bytes = len * 3; - auto *buf = new uint8_t[num_bytes]; + std::vector buf(num_bytes); - if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { - delete[](buf); + if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) { return false; } @@ -113,13 +112,11 @@ bool SHT3XDComponent::read_data_(uint16_t *data, uint8_t len) { uint8_t crc = sht_crc(buf[j], buf[j + 1]); if (crc != buf[j + 2]) { ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); - delete[](buf); return false; } data[i] = (buf[j] << 8) | buf[j + 1]; } - delete[](buf); return true; } diff --git a/esphome/components/shtcx/shtcx.cpp b/esphome/components/shtcx/shtcx.cpp index 848da8d7d7..db3a3bf803 100644 --- a/esphome/components/shtcx/shtcx.cpp +++ b/esphome/components/shtcx/shtcx.cpp @@ -130,10 +130,9 @@ uint8_t sht_crc(uint8_t data1, uint8_t data2) { bool SHTCXComponent::read_data_(uint16_t *data, uint8_t len) { const uint8_t num_bytes = len * 3; - auto *buf = new uint8_t[num_bytes]; + std::vector buf(num_bytes); - if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { - delete[](buf); + if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) { return false; } @@ -142,13 +141,11 @@ bool SHTCXComponent::read_data_(uint16_t *data, uint8_t len) { uint8_t crc = sht_crc(buf[j], buf[j + 1]); if (crc != buf[j + 2]) { ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); - delete[](buf); return false; } data[i] = (buf[j] << 8) | buf[j + 1]; } - delete[](buf); return true; } diff --git a/esphome/components/socket/lwip_raw_tcp_impl.cpp b/esphome/components/socket/lwip_raw_tcp_impl.cpp index aaeee7268a..29e1b23823 100644 --- a/esphome/components/socket/lwip_raw_tcp_impl.cpp +++ b/esphome/components/socket/lwip_raw_tcp_impl.cpp @@ -423,9 +423,9 @@ class LWIPRawImpl : public Socket { // nothing to do here, we just don't push it to the queue return ERR_OK; } - auto *sock = new LWIPRawImpl(newpcb); + auto sock = std::unique_ptr(new LWIPRawImpl(newpcb)); sock->init(); - accepted_sockets_.emplace(sock); + accepted_sockets_.push(std::move(sock)); return ERR_OK; } void err_fn(err_t err) { @@ -486,7 +486,7 @@ std::unique_ptr socket(int domain, int type, int protocol) { auto *pcb = tcp_new(); if (pcb == nullptr) return nullptr; - auto *sock = new LWIPRawImpl(pcb); + auto *sock = new LWIPRawImpl(pcb); // NOLINT(cppcoreguidelines-owning-memory) sock->init(); return std::unique_ptr{sock}; } diff --git a/esphome/components/sps30/sps30.cpp b/esphome/components/sps30/sps30.cpp index 30bd134626..3a31f4d607 100644 --- a/esphome/components/sps30/sps30.cpp +++ b/esphome/components/sps30/sps30.cpp @@ -242,10 +242,9 @@ bool SPS30Component::start_continuous_measurement_() { bool SPS30Component::read_data_(uint16_t *data, uint8_t len) { const uint8_t num_bytes = len * 3; - auto *buf = new uint8_t[num_bytes]; + std::vector buf(num_bytes); - if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { - delete[](buf); + if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) { return false; } @@ -254,13 +253,11 @@ bool SPS30Component::read_data_(uint16_t *data, uint8_t len) { uint8_t crc = sht_crc_(buf[j], buf[j + 1]); if (crc != buf[j + 2]) { ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); - delete[](buf); return false; } data[i] = (buf[j] << 8) | buf[j + 1]; } - delete[](buf); return true; } diff --git a/esphome/components/sts3x/sts3x.cpp b/esphome/components/sts3x/sts3x.cpp index 5d6d725a17..77383c6daa 100644 --- a/esphome/components/sts3x/sts3x.cpp +++ b/esphome/components/sts3x/sts3x.cpp @@ -97,10 +97,9 @@ uint8_t sts3x_crc(uint8_t data1, uint8_t data2) { bool STS3XComponent::read_data_(uint16_t *data, uint8_t len) { const uint8_t num_bytes = len * 3; - auto *buf = new uint8_t[num_bytes]; + std::vector buf(num_bytes); - if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { - delete[](buf); + if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) { return false; } @@ -109,13 +108,11 @@ bool STS3XComponent::read_data_(uint16_t *data, uint8_t len) { uint8_t crc = sts3x_crc(buf[j], buf[j + 1]); if (crc != buf[j + 2]) { ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); - delete[](buf); return false; } data[i] = (buf[j] << 8) | buf[j + 1]; } - delete[](buf); return true; } diff --git a/esphome/components/tlc59208f/output.py b/esphome/components/tlc59208f/output.py index f7cc89b252..ac45909673 100644 --- a/esphome/components/tlc59208f/output.py +++ b/esphome/components/tlc59208f/output.py @@ -20,6 +20,7 @@ CONFIG_SCHEMA = output.FLOAT_OUTPUT_SCHEMA.extend( async def to_code(config): paren = await cg.get_variable(config[CONF_TLC59208F_ID]) - rhs = paren.create_channel(config[CONF_CHANNEL]) - var = cg.Pvariable(config[CONF_ID], rhs) + var = cg.new_Pvariable(config[CONF_ID]) + cg.add(var.set_channel(config[CONF_CHANNEL])) + cg.add(paren.register_channel(var)) await output.register_output(var, config) diff --git a/esphome/components/tlc59208f/tlc59208f_output.cpp b/esphome/components/tlc59208f/tlc59208f_output.cpp index 784a0947ed..e416a5c62b 100644 --- a/esphome/components/tlc59208f/tlc59208f_output.cpp +++ b/esphome/components/tlc59208f/tlc59208f_output.cpp @@ -137,11 +137,11 @@ void TLC59208FOutput::loop() { this->update_ = false; } -TLC59208FChannel *TLC59208FOutput::create_channel(uint8_t channel) { - this->min_channel_ = std::min(this->min_channel_, channel); - this->max_channel_ = std::max(this->max_channel_, channel); - auto *c = new TLC59208FChannel(this, channel); - return c; +void TLC59208FOutput::register_channel(TLC59208FChannel *channel) { + auto c = channel->channel_; + this->min_channel_ = std::min(this->min_channel_, c); + this->max_channel_ = std::max(this->max_channel_, c); + channel->set_parent(this); } void TLC59208FChannel::write_state(float state) { diff --git a/esphome/components/tlc59208f/tlc59208f_output.h b/esphome/components/tlc59208f/tlc59208f_output.h index 06b7adc882..79fccc97f3 100644 --- a/esphome/components/tlc59208f/tlc59208f_output.h +++ b/esphome/components/tlc59208f/tlc59208f_output.h @@ -21,14 +21,15 @@ extern const uint8_t TLC59208F_MODE2_WDT_35MS; class TLC59208FOutput; -class TLC59208FChannel : public output::FloatOutput { +class TLC59208FChannel : public output::FloatOutput, public Parented { public: - TLC59208FChannel(TLC59208FOutput *parent, uint8_t channel) : parent_(parent), channel_(channel) {} + void set_channel(uint8_t channel) { channel_ = channel; } protected: + friend class TLC59208FOutput; + void write_state(float state) override; - TLC59208FOutput *parent_; uint8_t channel_; }; @@ -37,7 +38,7 @@ class TLC59208FOutput : public Component, public i2c::I2CDevice { public: TLC59208FOutput(uint8_t mode = TLC59208F_MODE2_OCH) : mode_(mode) {} - TLC59208FChannel *create_channel(uint8_t channel); + void register_channel(TLC59208FChannel *channel); void setup() override; void dump_config() override; diff --git a/esphome/components/tm1651/tm1651.cpp b/esphome/components/tm1651/tm1651.cpp index bb37e9f4c9..3689ef5894 100644 --- a/esphome/components/tm1651/tm1651.cpp +++ b/esphome/components/tm1651/tm1651.cpp @@ -1,5 +1,6 @@ #include "tm1651.h" #include "esphome/core/log.h" +#include "esphome/core/helpers.h" namespace esphome { namespace tm1651 { @@ -19,7 +20,7 @@ void TM1651Display::setup() { uint8_t clk = clk_pin_->get_pin(); uint8_t dio = dio_pin_->get_pin(); - battery_display_ = new TM1651(clk, dio); + battery_display_ = make_unique(clk, dio); battery_display_->init(); battery_display_->clearDisplay(); } diff --git a/esphome/components/tm1651/tm1651.h b/esphome/components/tm1651/tm1651.h index 6eab24687c..a18519bf41 100644 --- a/esphome/components/tm1651/tm1651.h +++ b/esphome/components/tm1651/tm1651.h @@ -1,5 +1,7 @@ #pragma once +#include + #include "esphome/core/component.h" #include "esphome/core/esphal.h" #include "esphome/core/automation.h" @@ -25,7 +27,7 @@ class TM1651Display : public Component { void turn_off(); protected: - TM1651 *battery_display_; + std::unique_ptr battery_display_; GPIOPin *clk_pin_; GPIOPin *dio_pin_; bool is_on_ = true; diff --git a/esphome/components/uart/uart_esp8266.cpp b/esphome/components/uart/uart_esp8266.cpp index bc6b0f72d3..6d207fde6c 100644 --- a/esphome/components/uart/uart_esp8266.cpp +++ b/esphome/components/uart/uart_esp8266.cpp @@ -85,7 +85,7 @@ void UARTComponent::setup() { this->hw_serial_->begin(this->baud_rate_, config); this->hw_serial_->setRxBufferSize(this->rx_buffer_size_); } else { - this->sw_serial_ = new ESP8266SoftwareSerial(); + this->sw_serial_ = new ESP8266SoftwareSerial(); // NOLINT int8_t tx = this->tx_pin_.has_value() ? *this->tx_pin_ : -1; int8_t rx = this->rx_pin_.has_value() ? *this->rx_pin_ : -1; this->sw_serial_->setup(tx, rx, this->baud_rate_, this->stop_bits_, this->data_bits_, this->parity_, @@ -227,7 +227,7 @@ void ESP8266SoftwareSerial::setup(int8_t tx_pin, int8_t rx_pin, uint32_t baud_ra pin.setup(); this->gpio_rx_pin_ = &pin; this->rx_pin_ = pin.to_isr(); - this->rx_buffer_ = new uint8_t[this->rx_buffer_size_]; + this->rx_buffer_ = new uint8_t[this->rx_buffer_size_]; // NOLINT pin.attach_interrupt(ESP8266SoftwareSerial::gpio_intr, this, FALLING); } } diff --git a/esphome/components/web_server_base/web_server_base.cpp b/esphome/components/web_server_base/web_server_base.cpp index 85711704b9..9f04c3b7bf 100644 --- a/esphome/components/web_server_base/web_server_base.cpp +++ b/esphome/components/web_server_base/web_server_base.cpp @@ -86,7 +86,9 @@ void OTARequestHandler::handleRequest(AsyncWebServerRequest *request) { request->send(response); } -void WebServerBase::add_ota_handler() { this->add_handler(new OTARequestHandler(this)); } +void WebServerBase::add_ota_handler() { + this->add_handler(new OTARequestHandler(this)); // NOLINT +} float WebServerBase::get_setup_priority() const { // Before WiFi (captive portal) return setup_priority::WIFI + 2.0f; diff --git a/esphome/components/web_server_base/web_server_base.h b/esphome/components/web_server_base/web_server_base.h index b6024ceafa..158006ae40 100644 --- a/esphome/components/web_server_base/web_server_base.h +++ b/esphome/components/web_server_base/web_server_base.h @@ -1,5 +1,6 @@ #pragma once +#include #include "esphome/core/component.h" #include @@ -14,7 +15,7 @@ class WebServerBase : public Component { this->initialized_++; return; } - this->server_ = new AsyncWebServer(this->port_); + this->server_ = std::make_shared(this->port_); this->server_->begin(); for (auto *handler : this->handlers_) @@ -25,11 +26,10 @@ class WebServerBase : public Component { void deinit() { this->initialized_--; if (this->initialized_ == 0) { - delete this->server_; this->server_ = nullptr; } } - AsyncWebServer *get_server() const { return server_; } + std::shared_ptr get_server() const { return server_; } float get_setup_priority() const override; void add_handler(AsyncWebHandler *handler) { @@ -50,7 +50,7 @@ class WebServerBase : public Component { int initialized_{0}; uint16_t port_{80}; - AsyncWebServer *server_{nullptr}; + std::shared_ptr server_{nullptr}; std::vector handlers_; }; diff --git a/esphome/components/wled/wled_light_effect.cpp b/esphome/components/wled/wled_light_effect.cpp index 915d1c6cc2..500b9bbad2 100644 --- a/esphome/components/wled/wled_light_effect.cpp +++ b/esphome/components/wled/wled_light_effect.cpp @@ -1,5 +1,6 @@ #include "wled_light_effect.h" #include "esphome/core/log.h" +#include "esphome/core/helpers.h" #ifdef ARDUINO_ARCH_ESP32 #include @@ -48,7 +49,7 @@ void WLEDLightEffect::blank_all_leds_(light::AddressableLight &it) { void WLEDLightEffect::apply(light::AddressableLight &it, const Color ¤t_color) { // Init UDP lazily if (!udp_) { - udp_.reset(new WiFiUDP()); + udp_ = make_unique(); if (!udp_->begin(port_)) { ESP_LOGW(TAG, "Cannot bind WLEDLightEffect to %d.", port_); diff --git a/esphome/core/esphal.cpp b/esphome/core/esphal.cpp index 8fb1dd86c5..849fdf95ad 100644 --- a/esphome/core/esphal.cpp +++ b/esphome/core/esphal.cpp @@ -230,10 +230,11 @@ void GPIOPin::attach_interrupt_(void (*func)(void *), void *arg, int mode) const } } #ifdef ARDUINO_ARCH_ESP8266 - ArgStructure *as = new ArgStructure; + ArgStructure *as = new ArgStructure; // NOLINT as->interruptInfo = nullptr; as->functionInfo = new ESPHomeInterruptFuncInfo{ + // NOLINT .func = func, .arg = arg, }; @@ -249,7 +250,7 @@ void GPIOPin::attach_interrupt_(void (*func)(void *), void *arg, int mode) const } ISRInternalGPIOPin *GPIOPin::to_isr() const { - return new ISRInternalGPIOPin(this->pin_, + return new ISRInternalGPIOPin(this->pin_, // NOLINT #ifdef ARDUINO_ARCH_ESP32 this->gpio_clear_, this->gpio_set_, #endif diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp index c5ff0102c3..53c7d1de43 100644 --- a/esphome/core/helpers.cpp +++ b/esphome/core/helpers.cpp @@ -141,21 +141,6 @@ std::string uint32_to_string(uint32_t num) { snprintf(buffer, sizeof(buffer), "%04X%04X", address16[1], address16[0]); return std::string(buffer); } -static char *global_json_build_buffer = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) -static size_t global_json_build_buffer_size = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) - -void reserve_global_json_build_buffer(size_t required_size) { - if (global_json_build_buffer_size == 0 || global_json_build_buffer_size < required_size) { - delete[] global_json_build_buffer; - global_json_build_buffer_size = std::max(required_size, global_json_build_buffer_size * 2); - - size_t remainder = global_json_build_buffer_size % 16U; - if (remainder != 0) - global_json_build_buffer_size += 16 - remainder; - - global_json_build_buffer = new char[global_json_build_buffer_size]; - } -} ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) { if (on == nullptr && strcasecmp(str, "on") == 0) diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index a63c627e5a..044de6c8b0 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -338,7 +338,7 @@ template T *new_buffer(size_t length) { buffer = new T[length]; } #else - buffer = new T[length]; + buffer = new T[length]; // NOLINT #endif return buffer; diff --git a/esphome/core/preferences.cpp b/esphome/core/preferences.cpp index bfc5d9f875..f051ce0e8a 100644 --- a/esphome/core/preferences.cpp +++ b/esphome/core/preferences.cpp @@ -17,13 +17,8 @@ namespace esphome { static const char *const TAG = "preferences"; -ESPPreferenceObject::ESPPreferenceObject() : offset_(0), length_words_(0), type_(0), data_(nullptr) {} ESPPreferenceObject::ESPPreferenceObject(size_t offset, size_t length, uint32_t type) - : offset_(offset), length_words_(length), type_(type) { - this->data_ = new uint32_t[this->length_words_ + 1]; // NOLINT(cppcoreguidelines-prefer-member-initializer) - for (uint32_t i = 0; i < this->length_words_ + 1; i++) - this->data_[i] = 0; -} + : offset_(offset), length_words_(length), type_(type), data_(length + 1) {} bool ESPPreferenceObject::load_() { if (!this->is_initialized()) { ESP_LOGV(TAG, "Load Pref Not initialized!"); @@ -173,7 +168,7 @@ ESPPreferences::ESPPreferences() : current_offset_(0) {} void ESPPreferences::begin() { - this->flash_storage_ = new uint32_t[ESP8266_FLASH_STORAGE_SIZE]; + this->flash_storage_ = new uint32_t[ESP8266_FLASH_STORAGE_SIZE]; // NOLINT ESP_LOGVV(TAG, "Loading preferences from flash..."); { @@ -234,7 +229,7 @@ bool ESPPreferenceObject::save_internal_() { char key[32]; sprintf(key, "%u", this->offset_); uint32_t len = (this->length_words_ + 1) * 4; - esp_err_t err = nvs_set_blob(global_preferences.nvs_handle_, key, this->data_, len); + esp_err_t err = nvs_set_blob(global_preferences.nvs_handle_, key, this->data_.data(), len); if (err) { ESP_LOGV(TAG, "nvs_set_blob('%s', len=%u) failed: %s", key, len, esp_err_to_name(err)); return false; @@ -264,7 +259,7 @@ bool ESPPreferenceObject::load_internal_() { ESP_LOGVV(TAG, "NVS length does not match. Assuming key changed (%u!=%u)", actual_len, len); return false; } - err = nvs_get_blob(global_preferences.nvs_handle_, key, this->data_, &len); + err = nvs_get_blob(global_preferences.nvs_handle_, key, this->data_.data(), &len); if (err) { ESP_LOGV(TAG, "nvs_get_blob('%s') failed: %s", key, esp_err_to_name(err)); return false; @@ -301,7 +296,7 @@ uint32_t ESPPreferenceObject::calculate_crc_() const { } return crc; } -bool ESPPreferenceObject::is_initialized() const { return this->data_ != nullptr; } +bool ESPPreferenceObject::is_initialized() const { return !this->data_.empty(); } ESPPreferences global_preferences; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) diff --git a/esphome/core/preferences.h b/esphome/core/preferences.h index 699871ca00..7ed9a2c8c5 100644 --- a/esphome/core/preferences.h +++ b/esphome/core/preferences.h @@ -1,6 +1,8 @@ #pragma once #include +#include +#include #include #include "esphome/core/defines.h" @@ -9,7 +11,7 @@ namespace esphome { class ESPPreferenceObject { public: - ESPPreferenceObject(); + ESPPreferenceObject() = default; ESPPreferenceObject(size_t offset, size_t length, uint32_t type); template bool save(T *src); @@ -28,12 +30,12 @@ class ESPPreferenceObject { uint32_t calculate_crc_() const; - size_t offset_; - size_t length_words_; - uint32_t type_; - uint32_t *data_; + size_t offset_ = 0; + size_t length_words_ = 0; + uint32_t type_ = 0; + std::vector data_; #ifdef ARDUINO_ARCH_ESP8266 - bool in_flash_{false}; + bool in_flash_ = false; #endif }; @@ -92,17 +94,18 @@ template ESPPreferenceObject ESPPreferences::make_preference(uint32_ template bool ESPPreferenceObject::save(T *src) { if (!this->is_initialized()) return false; - memset(this->data_, 0, this->length_words_ * 4); - memcpy(this->data_, src, sizeof(T)); + // ensure all bytes are 0 (in case sizeof(T) is not multiple of 4) + std::fill_n(data_.begin(), length_words_, 0); + memcpy(data_.data(), src, sizeof(T)); return this->save_(); } template bool ESPPreferenceObject::load(T *dest) { - memset(this->data_, 0, this->length_words_ * 4); + std::fill_n(data_.begin(), length_words_, 0); if (!this->load_()) return false; - memcpy(dest, this->data_, sizeof(T)); + memcpy(dest, data_.data(), sizeof(T)); return true; } diff --git a/tests/dummy_main.cpp b/tests/dummy_main.cpp index c3b192d15f..f9ba868096 100644 --- a/tests/dummy_main.cpp +++ b/tests/dummy_main.cpp @@ -13,23 +13,23 @@ using namespace esphome; void setup() { App.pre_setup("livingroom", __DATE__ ", " __TIME__, false); - auto *log = new logger::Logger(115200, 512, logger::UART_SELECTION_UART0); + auto *log = new logger::Logger(115200, 512, logger::UART_SELECTION_UART0); // NOLINT log->pre_setup(); App.register_component(log); - auto *wifi = new wifi::WiFiComponent(); + auto *wifi = new wifi::WiFiComponent(); // NOLINT App.register_component(wifi); wifi::WiFiAP ap; ap.set_ssid("Test SSID"); ap.set_password("password1"); wifi->add_sta(ap); - auto *ota = new ota::OTAComponent(); + auto *ota = new ota::OTAComponent(); // NOLINT ota->set_port(8266); - auto *gpio = new gpio::GPIOSwitch(); + auto *gpio = new gpio::GPIOSwitch(); // NOLINT gpio->set_name("GPIO Switch"); - gpio->set_pin(new GPIOPin(8, OUTPUT, false)); + gpio->set_pin(new GPIOPin(8, OUTPUT, false)); // NOLINT App.register_component(gpio); App.register_switch(gpio);