Activate owning-memory clang-tidy check (#1891)

* Activate owning-memory clang-tidy check

* Lint

* Lint

* Fix issue with new NfcTag constructor

* Update pointers for number and select

* Add back the NOLINT to display buffer

* Fix merge

* DSMR fixes

* Nextion fixes

* Fix pipsolar

* Fix lwip socket

* Format

* Change socket fix

Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
This commit is contained in:
Otto Winter 2021-09-13 11:31:02 +02:00 committed by GitHub
parent e0cff214b2
commit a4867a00ea
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
75 changed files with 293 additions and 321 deletions

View file

@ -30,7 +30,6 @@ Checks: >-
-cppcoreguidelines-macro-usage, -cppcoreguidelines-macro-usage,
-cppcoreguidelines-narrowing-conversions, -cppcoreguidelines-narrowing-conversions,
-cppcoreguidelines-non-private-member-variables-in-classes, -cppcoreguidelines-non-private-member-variables-in-classes,
-cppcoreguidelines-owning-memory,
-cppcoreguidelines-pro-bounds-array-to-pointer-decay, -cppcoreguidelines-pro-bounds-array-to-pointer-decay,
-cppcoreguidelines-pro-bounds-constant-array-index, -cppcoreguidelines-pro-bounds-constant-array-index,
-cppcoreguidelines-pro-bounds-pointer-arithmetic, -cppcoreguidelines-pro-bounds-pointer-arithmetic,

View file

@ -64,7 +64,7 @@ void APIServer::setup() {
#ifdef USE_LOGGER #ifdef USE_LOGGER
if (logger::global_logger != nullptr) { if (logger::global_logger != nullptr) {
logger::global_logger->add_on_log_callback([this](int level, const char *tag, const char *message) { 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_) if (!c->remove_)
c->send_log_message(level, tag, message); c->send_log_message(level, tag, message);
} }
@ -77,7 +77,7 @@ void APIServer::setup() {
#ifdef USE_ESP32_CAMERA #ifdef USE_ESP32_CAMERA
if (esp32_camera::global_esp32_camera != nullptr) { if (esp32_camera::global_esp32_camera != nullptr) {
esp32_camera::global_esp32_camera->add_image_callback([this](std::shared_ptr<esp32_camera::CameraImage> image) { esp32_camera::global_esp32_camera->add_image_callback([this](std::shared_ptr<esp32_camera::CameraImage> image) {
for (auto *c : this->clients_) for (auto &c : this->clients_)
if (!c->remove_) if (!c->remove_)
c->send_camera_state(image); c->send_camera_state(image);
}); });
@ -95,25 +95,21 @@ void APIServer::loop() {
ESP_LOGD(TAG, "Accepted %s", sock->getpeername().c_str()); ESP_LOGD(TAG, "Accepted %s", sock->getpeername().c_str());
auto *conn = new APIConnection(std::move(sock), this); auto *conn = new APIConnection(std::move(sock), this);
clients_.push_back(conn); clients_.emplace_back(conn);
conn->start(); conn->start();
} }
// Partition clients into remove and active // Partition clients into remove and active
auto new_end = auto new_end = std::partition(this->clients_.begin(), this->clients_.end(),
std::partition(this->clients_.begin(), this->clients_.end(), [](APIConnection *conn) { return !conn->remove_; }); [](const std::unique_ptr<APIConnection> &conn) { return !conn->remove_; });
// print disconnection messages // print disconnection messages
for (auto it = new_end; it != this->clients_.end(); ++it) { for (auto it = new_end; it != this->clients_.end(); ++it) {
ESP_LOGD(TAG, "Disconnecting %s", (*it)->client_info_.c_str()); 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 // resize vector
this->clients_.erase(new_end, this->clients_.end()); this->clients_.erase(new_end, this->clients_.end());
for (auto *client : this->clients_) { for (auto &client : this->clients_) {
client->loop(); client->loop();
} }
@ -169,7 +165,7 @@ void APIServer::handle_disconnect(APIConnection *conn) {}
void APIServer::on_binary_sensor_update(binary_sensor::BinarySensor *obj, bool state) { void APIServer::on_binary_sensor_update(binary_sensor::BinarySensor *obj, bool state) {
if (obj->is_internal()) if (obj->is_internal())
return; return;
for (auto *c : this->clients_) for (auto &c : this->clients_)
c->send_binary_sensor_state(obj, state); c->send_binary_sensor_state(obj, state);
} }
#endif #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) { void APIServer::on_cover_update(cover::Cover *obj) {
if (obj->is_internal()) if (obj->is_internal())
return; return;
for (auto *c : this->clients_) for (auto &c : this->clients_)
c->send_cover_state(obj); c->send_cover_state(obj);
} }
#endif #endif
@ -187,7 +183,7 @@ void APIServer::on_cover_update(cover::Cover *obj) {
void APIServer::on_fan_update(fan::FanState *obj) { void APIServer::on_fan_update(fan::FanState *obj) {
if (obj->is_internal()) if (obj->is_internal())
return; return;
for (auto *c : this->clients_) for (auto &c : this->clients_)
c->send_fan_state(obj); c->send_fan_state(obj);
} }
#endif #endif
@ -196,7 +192,7 @@ void APIServer::on_fan_update(fan::FanState *obj) {
void APIServer::on_light_update(light::LightState *obj) { void APIServer::on_light_update(light::LightState *obj) {
if (obj->is_internal()) if (obj->is_internal())
return; return;
for (auto *c : this->clients_) for (auto &c : this->clients_)
c->send_light_state(obj); c->send_light_state(obj);
} }
#endif #endif
@ -205,7 +201,7 @@ void APIServer::on_light_update(light::LightState *obj) {
void APIServer::on_sensor_update(sensor::Sensor *obj, float state) { void APIServer::on_sensor_update(sensor::Sensor *obj, float state) {
if (obj->is_internal()) if (obj->is_internal())
return; return;
for (auto *c : this->clients_) for (auto &c : this->clients_)
c->send_sensor_state(obj, state); c->send_sensor_state(obj, state);
} }
#endif #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) { void APIServer::on_switch_update(switch_::Switch *obj, bool state) {
if (obj->is_internal()) if (obj->is_internal())
return; return;
for (auto *c : this->clients_) for (auto &c : this->clients_)
c->send_switch_state(obj, state); c->send_switch_state(obj, state);
} }
#endif #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) { void APIServer::on_text_sensor_update(text_sensor::TextSensor *obj, const std::string &state) {
if (obj->is_internal()) if (obj->is_internal())
return; return;
for (auto *c : this->clients_) for (auto &c : this->clients_)
c->send_text_sensor_state(obj, state); c->send_text_sensor_state(obj, state);
} }
#endif #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) { void APIServer::on_climate_update(climate::Climate *obj) {
if (obj->is_internal()) if (obj->is_internal())
return; return;
for (auto *c : this->clients_) for (auto &c : this->clients_)
c->send_climate_state(obj); c->send_climate_state(obj);
} }
#endif #endif
@ -241,7 +237,7 @@ void APIServer::on_climate_update(climate::Climate *obj) {
void APIServer::on_number_update(number::Number *obj, float state) { void APIServer::on_number_update(number::Number *obj, float state) {
if (obj->is_internal()) if (obj->is_internal())
return; return;
for (auto *c : this->clients_) for (auto &c : this->clients_)
c->send_number_state(obj, state); c->send_number_state(obj, state);
} }
#endif #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) { void APIServer::on_select_update(select::Select *obj, const std::string &state) {
if (obj->is_internal()) if (obj->is_internal())
return; return;
for (auto *c : this->clients_) for (auto &c : this->clients_)
c->send_select_state(obj, state); c->send_select_state(obj, state);
} }
#endif #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::set_password(const std::string &password) { this->password_ = password; }
void APIServer::send_homeassistant_service_call(const HomeassistantServiceResponse &call) { 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); 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; } void APIServer::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
#ifdef USE_HOMEASSISTANT_TIME #ifdef USE_HOMEASSISTANT_TIME
void APIServer::request_time() { void APIServer::request_time() {
for (auto *client : this->clients_) { for (auto &client : this->clients_) {
if (!client->remove_ && client->connection_state_ == APIConnection::ConnectionState::CONNECTED) if (!client->remove_ && client->connection_state_ == APIConnection::ConnectionState::CONNECTED)
client->send_time_request(); client->send_time_request();
} }
@ -289,7 +285,7 @@ void APIServer::request_time() {
#endif #endif
bool APIServer::is_connected() const { return !this->clients_.empty(); } bool APIServer::is_connected() const { return !this->clients_.empty(); }
void APIServer::on_shutdown() { void APIServer::on_shutdown() {
for (auto *c : this->clients_) { for (auto &c : this->clients_) {
c->send_disconnect_request(DisconnectRequest()); c->send_disconnect_request(DisconnectRequest());
} }
delay(10); delay(10);

View file

@ -91,7 +91,7 @@ class APIServer : public Component, public Controller {
uint16_t port_{6053}; uint16_t port_{6053};
uint32_t reboot_timeout_{300000}; uint32_t reboot_timeout_{300000};
uint32_t last_connected_{0}; uint32_t last_connected_{0};
std::vector<APIConnection *> clients_; std::vector<std::unique_ptr<APIConnection>> clients_;
std::string password_; std::string password_;
std::vector<HomeAssistantStateSubscription> state_subs_; std::vector<HomeAssistantStateSubscription> state_subs_;
std::vector<UserServiceDescriptor *> user_services_; std::vector<UserServiceDescriptor *> user_services_;

View file

@ -49,7 +49,7 @@ class CustomAPIDevice {
template<typename T, typename... Ts> template<typename T, typename... Ts>
void register_service(void (T::*callback)(Ts...), const std::string &name, void register_service(void (T::*callback)(Ts...), const std::string &name,
const std::array<std::string, sizeof...(Ts)> &arg_names) { const std::array<std::string, sizeof...(Ts)> &arg_names) {
auto *service = new CustomAPIDeviceService<T, Ts...>(name, arg_names, (T *) this, callback); auto *service = new CustomAPIDeviceService<T, Ts...>(name, arg_names, (T *) this, callback); // NOLINT
global_api_server->register_user_service(service); 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. * @param name The name of the arguments for the service, must match the arguments of the function.
*/ */
template<typename T> void register_service(void (T::*callback)(), const std::string &name) { template<typename T> void register_service(void (T::*callback)(), const std::string &name) {
auto *service = new CustomAPIDeviceService<T>(name, {}, (T *) this, callback); auto *service = new CustomAPIDeviceService<T>(name, {}, (T *) this, callback); // NOLINT
global_api_server->register_user_service(service); global_api_server->register_user_service(service);
} }

View file

@ -76,7 +76,7 @@ void CaptivePortal::start() {
this->base_->add_ota_handler(); this->base_->add_ota_handler();
} }
this->dns_server_ = new DNSServer(); this->dns_server_ = make_unique<DNSServer>();
this->dns_server_->setErrorReplyCode(DNSReplyCode::NoError); this->dns_server_->setErrorReplyCode(DNSReplyCode::NoError);
IPAddress ip = wifi::global_wifi_component->wifi_soft_ap_ip(); IPAddress ip = wifi::global_wifi_component->wifi_soft_ap_ip();
this->dns_server_->start(53, "*", ip); this->dns_server_->start(53, "*", ip);

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <memory>
#include <DNSServer.h> #include <DNSServer.h>
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/core/helpers.h" #include "esphome/core/helpers.h"
@ -26,7 +27,7 @@ class CaptivePortal : public AsyncWebHandler, public Component {
this->active_ = false; this->active_ = false;
this->base_->deinit(); this->base_->deinit();
this->dns_server_->stop(); this->dns_server_->stop();
delete this->dns_server_; this->dns_server_ = nullptr;
} }
bool canHandle(AsyncWebServerRequest *request) override { bool canHandle(AsyncWebServerRequest *request) override {
@ -65,7 +66,7 @@ class CaptivePortal : public AsyncWebHandler, public Component {
web_server_base::WebServerBase *base_; web_server_base::WebServerBase *base_;
bool initialized_{false}; bool initialized_{false};
bool active_{false}; bool active_{false};
DNSServer *dns_server_{nullptr}; std::unique_ptr<DNSServer> dns_server_{nullptr};
}; };
extern CaptivePortal *global_captive_portal; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) extern CaptivePortal *global_captive_portal; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)

View file

@ -97,16 +97,7 @@ void DallasComponent::dump_config() {
} }
} }
DallasTemperatureSensor *DallasComponent::get_sensor_by_address(uint64_t address, uint8_t resolution) { void DallasComponent::register_sensor(DallasTemperatureSensor *sensor) { this->sensors_.push_back(sensor); }
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::update() { void DallasComponent::update() {
this->status_clear_warning(); this->status_clear_warning();
@ -157,11 +148,6 @@ void DallasComponent::update() {
} }
DallasComponent::DallasComponent(ESPOneWire *one_wire) : one_wire_(one_wire) {} 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; } void DallasTemperatureSensor::set_address(uint64_t address) { this->address_ = address; }
uint8_t DallasTemperatureSensor::get_resolution() const { return this->resolution_; } uint8_t DallasTemperatureSensor::get_resolution() const { return this->resolution_; }
void DallasTemperatureSensor::set_resolution(uint8_t resolution) { this->resolution_ = resolution; } void DallasTemperatureSensor::set_resolution(uint8_t resolution) { this->resolution_ = resolution; }

View file

@ -13,8 +13,7 @@ class DallasComponent : public PollingComponent {
public: public:
explicit DallasComponent(ESPOneWire *one_wire); explicit DallasComponent(ESPOneWire *one_wire);
DallasTemperatureSensor *get_sensor_by_address(uint64_t address, uint8_t resolution); void register_sensor(DallasTemperatureSensor *sensor);
DallasTemperatureSensor *get_sensor_by_index(uint8_t index, uint8_t resolution);
void setup() override; void setup() override;
void dump_config() 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. /// Internal class that helps us create multiple sensors for one Dallas hub.
class DallasTemperatureSensor : public sensor::Sensor { class DallasTemperatureSensor : public sensor::Sensor {
public: 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. /// Helper to get a pointer to the address as uint8_t.
uint8_t *get_address8(); uint8_t *get_address8();
/// Helper to create (and cache) the name for this sensor. For example "0xfe0000031f1eaf29". /// Helper to create (and cache) the name for this sensor. For example "0xfe0000031f1eaf29".

View file

@ -36,10 +36,15 @@ CONFIG_SCHEMA = cv.All(
async def to_code(config): async def to_code(config):
hub = await cg.get_variable(config[CONF_DALLAS_ID]) hub = await cg.get_variable(config[CONF_DALLAS_ID])
var = cg.new_Pvariable(config[CONF_ID])
if CONF_ADDRESS in config: if CONF_ADDRESS in config:
address = config[CONF_ADDRESS] cg.add(var.set_address(config[CONF_ADDRESS]))
rhs = hub.Pget_sensor_by_address(address, config.get(CONF_RESOLUTION))
else: else:
rhs = hub.Pget_sensor_by_index(config[CONF_INDEX], config.get(CONF_RESOLUTION)) cg.add(var.set_index(config[CONF_INDEX]))
var = cg.Pvariable(config[CONF_ID], rhs)
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) await sensor.register_sensor(var, config)

View file

@ -1,9 +1,9 @@
#include "display_buffer.h" #include "display_buffer.h"
#include <utility>
#include "esphome/core/application.h" #include "esphome/core/application.h"
#include "esphome/core/color.h" #include "esphome/core/color.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include <utility>
namespace esphome { namespace esphome {
namespace display { namespace display {
@ -14,7 +14,7 @@ const Color COLOR_OFF(0, 0, 0, 0);
const Color COLOR_ON(255, 255, 255, 255); const Color COLOR_ON(255, 255, 255, 255);
void DisplayBuffer::init_internal_(uint32_t buffer_length) { 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) { if (this->buffer_ == nullptr) {
ESP_LOGE(TAG, "Could not allocate buffer for display!"); ESP_LOGE(TAG, "Could not allocate buffer for display!");
return; return;

View file

@ -105,7 +105,7 @@ void Dsmr::receive_encrypted_() {
&buffer[18], &buffer[18],
// cipher size // cipher size
buffer_length - 17); buffer_length - 17);
delete gcmaes128; delete gcmaes128; // NOLINT(cppcoreguidelines-owning-memory)
telegram_len_ = strnlen(this->telegram_, sizeof(this->telegram_)); telegram_len_ = strnlen(this->telegram_, sizeof(this->telegram_));
ESP_LOGV(TAG, "Decrypted data length: %d", telegram_len_); ESP_LOGV(TAG, "Decrypted data length: %d", telegram_len_);

View file

@ -26,7 +26,7 @@ E131Component::~E131Component() {
} }
void E131Component::setup() { void E131Component::setup() {
udp_.reset(new WiFiUDP()); udp_ = make_unique<WiFiUDP>();
if (!udp_->begin(PORT)) { if (!udp_->begin(PORT)) {
ESP_LOGE(TAG, "Cannot bind E131 to %d.", PORT); ESP_LOGE(TAG, "Cannot bind E131 to %d.", PORT);

View file

@ -10,7 +10,7 @@ void FastLEDLightOutput::setup() {
ESP_LOGCONFIG(TAG, "Setting up FastLED light..."); ESP_LOGCONFIG(TAG, "Setting up FastLED light...");
this->controller_->init(); this->controller_->init();
this->controller_->setLeds(this->leds_, this->num_leds_); 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()) { if (!this->max_refresh_rate_.has_value()) {
this->set_max_refresh_rate(this->controller_->getMaxRefreshRate()); this->set_max_refresh_rate(this->controller_->getMaxRefreshRate());
} }

View file

@ -30,7 +30,7 @@ class FastLEDLightOutput : public light::AddressableLight {
CLEDController &add_leds(CLEDController *controller, int num_leds) { CLEDController &add_leds(CLEDController *controller, int num_leds) {
this->controller_ = controller; this->controller_ = controller;
this->num_leds_ = num_leds; 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++) for (int i = 0; i < this->num_leds_; i++)
this->leds_[i] = CRGB::Black; this->leds_[i] = CRGB::Black;

View file

@ -12,7 +12,7 @@ static const uint8_t PM_10_0_VALUE_INDEX = 7;
void HM3301Component::setup() { void HM3301Component::setup() {
ESP_LOGCONFIG(TAG, "Setting up HM3301..."); ESP_LOGCONFIG(TAG, "Setting up HM3301...");
hm3301_ = new HM330X(); hm3301_ = make_unique<HM330X>();
error_code_ = hm3301_->init(); error_code_ = hm3301_->init();
if (error_code_ != NO_ERROR) { if (error_code_ != NO_ERROR) {
this->mark_failed(); this->mark_failed();

View file

@ -27,7 +27,7 @@ class HM3301Component : public PollingComponent, public i2c::I2CDevice {
void update() override; void update() override;
protected: protected:
HM330X *hm3301_; std::unique_ptr<HM330X> hm3301_;
HM330XErrorCode error_code_{NO_ERROR}; HM330XErrorCode error_code_{NO_ERROR};

View file

@ -75,10 +75,10 @@ void HttpRequestComponent::send(const std::vector<HttpRequestResponseTrigger *>
} }
#ifdef ARDUINO_ARCH_ESP8266 #ifdef ARDUINO_ARCH_ESP8266
WiFiClient *HttpRequestComponent::get_wifi_client_() { std::shared_ptr<WiFiClient> HttpRequestComponent::get_wifi_client_() {
if (this->secure_) { if (this->secure_) {
if (this->wifi_client_secure_ == nullptr) { if (this->wifi_client_secure_ == nullptr) {
this->wifi_client_secure_ = new BearSSL::WiFiClientSecure(); this->wifi_client_secure_ = std::make_shared<BearSSL::WiFiClientSecure>();
this->wifi_client_secure_->setInsecure(); this->wifi_client_secure_->setInsecure();
this->wifi_client_secure_->setBufferSizes(512, 512); this->wifi_client_secure_->setBufferSizes(512, 512);
} }
@ -86,7 +86,7 @@ WiFiClient *HttpRequestComponent::get_wifi_client_() {
} }
if (this->wifi_client_ == nullptr) { if (this->wifi_client_ == nullptr) {
this->wifi_client_ = new WiFiClient(); this->wifi_client_ = std::make_shared<WiFiClient>();
} }
return this->wifi_client_; return this->wifi_client_;
} }

View file

@ -6,6 +6,7 @@
#include <list> #include <list>
#include <map> #include <map>
#include <utility> #include <utility>
#include <memory>
#ifdef ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP32
#include <HTTPClient.h> #include <HTTPClient.h>
@ -51,9 +52,9 @@ class HttpRequestComponent : public Component {
std::string body_; std::string body_;
std::list<Header> headers_; std::list<Header> headers_;
#ifdef ARDUINO_ARCH_ESP8266 #ifdef ARDUINO_ARCH_ESP8266
WiFiClient *wifi_client_{nullptr}; std::shared_ptr<WiFiClient> wifi_client_;
BearSSL::WiFiClientSecure *wifi_client_secure_{nullptr}; std::shared_ptr<BearSSL::WiFiClientSecure> wifi_client_secure_;
WiFiClient *get_wifi_client_(); std::shared_ptr<WiFiClient> get_wifi_client_();
#endif #endif
}; };

View file

@ -6,21 +6,7 @@ namespace json {
static const char *const TAG = "json"; static const char *const TAG = "json";
static char *global_json_build_buffer = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) static std::vector<char> global_json_build_buffer; // NOLINT
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];
}
}
const char *build_json(const json_build_t &f, size_t *length) { const char *build_json(const json_build_t &f, size_t *length) {
global_json_buffer.clear(); global_json_buffer.clear();
@ -35,16 +21,16 @@ const char *build_json(const json_build_t &f, size_t *length) {
// Discovery | 372 | 356 | // Discovery | 372 | 356 |
// Discovery | 336 | 311 | // Discovery | 336 | 311 |
// Discovery | 408 | 393 | // Discovery | 408 | 393 |
reserve_global_json_build_buffer(global_json_buffer.size()); global_json_build_buffer.reserve(global_json_buffer.size() + 1);
size_t bytes_written = root.printTo(global_json_build_buffer, global_json_build_buffer_size); 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) { if (bytes_written >= global_json_build_buffer.capacity() - 1) {
reserve_global_json_build_buffer(root.measureLength() + 1); global_json_build_buffer.reserve(root.measureLength() + 1);
bytes_written = root.printTo(global_json_build_buffer, global_json_build_buffer_size); bytes_written = root.printTo(global_json_build_buffer.data(), global_json_build_buffer.capacity());
} }
*length = bytes_written; *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) { void parse_json(const std::string &data, const json_parse_t &f) {
global_json_buffer.clear(); global_json_buffer.clear();
@ -113,7 +99,7 @@ void VectorJsonBuffer::reserve(size_t size) { // NOLINT
target_capacity *= 2; target_capacity *= 2;
char *old_buffer = this->buffer_; 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) { if (old_buffer != nullptr && this->capacity_ != 0) {
this->free_blocks_.push_back(old_buffer); this->free_blocks_.push_back(old_buffer);
memcpy(this->buffer_, old_buffer, this->capacity_); memcpy(this->buffer_, old_buffer, this->capacity_);

View file

@ -1,5 +1,7 @@
#pragma once #pragma once
#include <vector>
#include "esphome/core/helpers.h" #include "esphome/core/helpers.h"
#include <ArduinoJson.h> #include <ArduinoJson.h>

View file

@ -29,7 +29,7 @@ static const uint8_t LCD_DISPLAY_FUNCTION_2_LINE = 0x08;
static const uint8_t LCD_DISPLAY_FUNCTION_5X10_DOTS = 0x04; static const uint8_t LCD_DISPLAY_FUNCTION_5X10_DOTS = 0x04;
void LCDDisplay::setup() { 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++) for (uint8_t i = 0; i < this->rows_ * this->columns_; i++)
this->buffer_[i] = ' '; this->buffer_[i] = ' ';

View file

@ -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) 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) { : baud_rate_(baud_rate), tx_buffer_size_(tx_buffer_size), uart_(uart) {
// add 1 to buffer size for null terminator // 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() { void Logger::pre_setup() {

View file

@ -117,7 +117,7 @@ float MAX7219Component::get_setup_priority() const { return setup_priority::PROC
void MAX7219Component::setup() { void MAX7219Component::setup() {
ESP_LOGCONFIG(TAG, "Setting up MAX7219..."); ESP_LOGCONFIG(TAG, "Setting up MAX7219...");
this->spi_setup(); 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++) for (uint8_t i = 0; i < this->num_chips_ * 8; i++)
this->buffer_[i] = 0; this->buffer_[i] = 0;

View file

@ -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, void MQTTComponent::set_availability(std::string topic, std::string payload_available,
std::string payload_not_available) { std::string payload_not_available) {
delete this->availability_; this->availability_ = make_unique<Availability>();
this->availability_ = new Availability();
this->availability_->topic = std::move(topic); this->availability_->topic = std::move(topic);
this->availability_->payload_available = std::move(payload_available); this->availability_->payload_available = std::move(payload_available);
this->availability_->payload_not_available = std::move(payload_not_available); this->availability_->payload_not_available = std::move(payload_not_available);

View file

@ -1,5 +1,7 @@
#pragma once #pragma once
#include <memory>
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "mqtt_client.h" #include "mqtt_client.h"
@ -171,7 +173,7 @@ class MQTTComponent : public Component {
std::string custom_command_topic_{}; std::string custom_command_topic_{};
bool retain_{true}; bool retain_{true};
bool discovery_enabled_{true}; bool discovery_enabled_{true};
Availability *availability_{nullptr}; std::unique_ptr<Availability> availability_;
bool resend_state_{false}; bool resend_state_{false};
}; };

View file

@ -79,7 +79,7 @@ class NeoPixelBusLightOutputBase : public light::AddressableLight {
(*this)[i] = Color(0, 0, 0, 0); (*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(); this->controller_->Begin();
} }

View file

@ -33,7 +33,7 @@ void NextionBinarySensor::update() {
if (this->variable_name_.empty()) // This is a touch component if (this->variable_name_.empty()) // This is a touch component
return; 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) { 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; this->needs_to_send_update_ = true;
} else { } else {
this->needs_to_send_update_ = false; 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);
} }
} }

View file

@ -10,7 +10,8 @@ class NextionBinarySensor;
class NextionBinarySensor : public NextionComponent, class NextionBinarySensor : public NextionComponent,
public binary_sensor::BinarySensorInitiallyOff, public binary_sensor::BinarySensorInitiallyOff,
public PollingComponent { public PollingComponent,
public std::enable_shared_from_this<NextionBinarySensor> {
public: public:
NextionBinarySensor(NextionBase *nextion) { this->nextion_ = nextion; } NextionBinarySensor(NextionBase *nextion) { this->nextion_ = nextion; }

View file

@ -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, "print_queue_members_ (top 10) size %zu", this->nextion_queue_.size());
ESP_LOGN(TAG, "*******************************************"); ESP_LOGN(TAG, "*******************************************");
int count = 0; int count = 0;
for (auto *i : this->nextion_queue_) { for (auto &i : this->nextion_queue_) {
if (count++ == 10) if (count++ == 10)
break; break;
@ -257,8 +257,9 @@ bool Nextion::remove_from_q_(bool report_empty) {
return false; return false;
} }
NextionQueue *nb = this->nextion_queue_.front(); auto nb = std::move(this->nextion_queue_.front());
NextionComponentBase *component = nb->component; this->nextion_queue_.pop_front();
auto &component = nb->component;
ESP_LOGN(TAG, "Removing %s from the queue", component->get_variable_name().c_str()); 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") { if (component->get_variable_name() == "sleep_wake") {
this->is_sleeping_ = false; this->is_sleeping_ = false;
} }
delete component;
} }
delete nb;
this->nextion_queue_.pop_front();
return true; return true;
} }
@ -358,7 +357,7 @@ void Nextion::process_nextion_commands_() {
int index = 0; int index = 0;
int found = -1; int found = -1;
for (auto &nb : this->nextion_queue_) { for (auto &nb : this->nextion_queue_) {
NextionComponentBase *component = nb->component; auto &component = nb->component;
if (component->get_queue_type() == NextionQueueType::WAVEFORM_SENSOR) { if (component->get_queue_type() == NextionQueueType::WAVEFORM_SENSOR) {
ESP_LOGW(TAG, "Nextion reported invalid Waveform ID %d or Channel # %d was used!", 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; found = index;
delete component;
delete nb;
break; break;
} }
++index; ++index;
@ -468,8 +464,9 @@ void Nextion::process_nextion_commands_() {
break; break;
} }
NextionQueue *nb = this->nextion_queue_.front(); auto nb = std::move(this->nextion_queue_.front());
NextionComponentBase *component = nb->component; this->nextion_queue_.pop_front();
auto &component = nb->component;
if (component->get_queue_type() != NextionQueueType::TEXT_SENSOR) { 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", 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); component->set_state_from_string(to_process, true, false);
} }
delete nb;
this->nextion_queue_.pop_front();
break; break;
} }
// 0x71 0x01 0x02 0x03 0x04 0xFF 0xFF 0xFF // 0x71 0x01 0x02 0x03 0x04 0xFF 0xFF 0xFF
@ -511,8 +505,9 @@ void Nextion::process_nextion_commands_() {
++dataindex; ++dataindex;
} }
NextionQueue *nb = this->nextion_queue_.front(); auto nb = std::move(this->nextion_queue_.front());
NextionComponentBase *component = nb->component; this->nextion_queue_.pop_front();
auto &component = nb->component;
if (component->get_queue_type() != NextionQueueType::SENSOR && if (component->get_queue_type() != NextionQueueType::SENSOR &&
component->get_queue_type() != NextionQueueType::BINARY_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); component->set_state_from_int(value, true, false);
} }
delete nb;
this->nextion_queue_.pop_front();
break; break;
} }
@ -690,7 +682,7 @@ void Nextion::process_nextion_commands_() {
int index = 0; int index = 0;
int found = -1; int found = -1;
for (auto &nb : this->nextion_queue_) { for (auto &nb : this->nextion_queue_) {
auto component = nb->component; auto &component = nb->component;
if (component->get_queue_type() == NextionQueueType::WAVEFORM_SENSOR) { if (component->get_queue_type() == NextionQueueType::WAVEFORM_SENSOR) {
size_t buffer_to_send = component->get_wave_buffer().size() < 255 ? component->get_wave_buffer().size() size_t buffer_to_send = component->get_wave_buffer().size() < 255 ? component->get_wave_buffer().size()
: 255; // ADDT command can only send 255 : 255; // ADDT command can only send 255
@ -707,8 +699,6 @@ void Nextion::process_nextion_commands_() {
component->get_wave_buffer().begin() + buffer_to_send); component->get_wave_buffer().begin() + buffer_to_send);
} }
found = index; found = index;
delete component;
delete nb;
break; break;
} }
++index; ++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) { 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++) { 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 + this->max_q_age_ms_ < ms) {
if (this->nextion_queue_[i]->queue_time == 0) if (this->nextion_queue_[i]->queue_time == 0)
ESP_LOGD(TAG, "Removing old queue type \"%s\" name \"%s\" 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") { if (component->get_variable_name() == "sleep_wake") {
this->is_sleeping_ = false; this->is_sleeping_ = false;
} }
delete component;
} }
delete this->nextion_queue_[i];
this->nextion_queue_.erase(this->nextion_queue_.begin() + i); this->nextion_queue_.erase(this->nextion_queue_.begin() + i);
i--;
} else { } else {
break; 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 * @param variable_name Name for the queue
*/ */
void Nextion::add_no_result_to_queue_(const std::string &variable_name) { 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::NextionQueue>();
nextion_queue->component = new nextion::NextionComponentBase; nextion_queue->component = make_unique<nextion::NextionComponentBase>();
nextion_queue->component->set_variable_name(variable_name); nextion_queue->component->set_variable_name(variable_name);
nextion_queue->queue_time = millis(); 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()); 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 * @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<NextionComponentBase> component, int state_value) {
this->add_no_result_to_queue_with_set(component->get_variable_name(), component->get_variable_name_to_send(), this->add_no_result_to_queue_with_set(component->get_variable_name(), component->get_variable_name_to_send(),
state_value); 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 state_value String value to set
* @param is_sleep_safe The command is safe to send when the Nextion is sleeping * @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<NextionComponentBase> component,
const std::string &state_value) {
this->add_no_result_to_queue_with_set(component->get_variable_name(), component->get_variable_name_to_send(), this->add_no_result_to_queue_with_set(component->get_variable_name(), component->get_variable_name_to_send(),
state_value); state_value);
} }
@ -1039,11 +1028,11 @@ void Nextion::add_no_result_to_queue_with_set_internal_(const std::string &varia
state_value.c_str()); state_value.c_str());
} }
void Nextion::add_to_get_queue(NextionComponentBase *component) { void Nextion::add_to_get_queue(std::shared_ptr<NextionComponentBase> component) {
if ((!this->is_setup() && !this->ignore_is_setup_)) if ((!this->is_setup() && !this->ignore_is_setup_))
return; return;
nextion::NextionQueue *nextion_queue = new nextion::NextionQueue; auto nextion_queue = make_unique<nextion::NextionQueue>();
nextion_queue->component = component; nextion_queue->component = component;
nextion_queue->queue_time = millis(); 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(); std::string command = "get " + component->get_variable_name_to_send();
if (this->send_command_(command)) { 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_to_send The buffer size
* @param buffer_size The buffer data * @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<NextionComponentBase> component) {
if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping()) if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping())
return; return;
nextion::NextionQueue *nextion_queue = new nextion::NextionQueue; auto nextion_queue = make_unique<nextion::NextionQueue>();
nextion_queue->component = new nextion::NextionComponentBase; nextion_queue->component = std::make_shared<nextion::NextionComponentBase>();
nextion_queue->queue_time = millis(); nextion_queue->queue_time = millis();
size_t buffer_to_send = component->get_wave_buffer_size() < 255 ? component->get_wave_buffer_size() 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()) + "," + std::string command = "addt " + to_string(component->get_component_id()) + "," +
to_string(component->get_wave_channel_id()) + "," + to_string(buffer_to_send); to_string(component->get_wave_channel_id()) + "," + to_string(buffer_to_send);
if (this->send_command_(command)) { if (this->send_command_(command)) {
this->nextion_queue_.push_back(nextion_queue); this->nextion_queue_.push_back(std::move(nextion_queue));
} }
} }

View file

@ -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_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 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<NextionComponentBase> 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, void add_no_result_to_queue_with_set(const std::string &variable_name, const std::string &variable_name_to_send,
int state_value) override; 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<NextionComponentBase> 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, 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; const std::string &state_value) override;
void add_to_get_queue(NextionComponentBase *component) override; void add_to_get_queue(std::shared_ptr<NextionComponentBase> component) override;
void add_addt_command_to_queue(NextionComponentBase *component) override; void add_addt_command_to_queue(std::shared_ptr<NextionComponentBase> component) override;
void update_components_by_prefix(const std::string &prefix); 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; } void set_auto_wake_on_touch_internal(bool auto_wake_on_touch) { this->auto_wake_on_touch_ = auto_wake_on_touch; }
protected: protected:
std::deque<NextionQueue *> nextion_queue_; std::deque<std::unique_ptr<NextionQueue>> nextion_queue_;
uint16_t recv_ret_string_(std::string &response, uint32_t timeout, bool recv_flag); uint16_t recv_ret_string_(std::string &response, uint32_t timeout, bool recv_flag);
void all_components_send_state_(bool force_update = false); void all_components_send_state_(bool force_update = false);
uint64_t comok_sent_ = 0; uint64_t comok_sent_ = 0;

View file

@ -24,18 +24,19 @@ class NextionBase;
class NextionBase { class NextionBase {
public: 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<NextionComponentBase> component, int state_value) = 0;
virtual void add_no_result_to_queue_with_set(const std::string &variable_name, 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; 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<NextionComponentBase> component,
const std::string &state_value) = 0;
virtual void add_no_result_to_queue_with_set(const std::string &variable_name, virtual void add_no_result_to_queue_with_set(const std::string &variable_name,
const std::string &variable_name_to_send, const std::string &variable_name_to_send,
const std::string &state_value) = 0; 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<NextionComponentBase> component) = 0;
virtual void add_to_get_queue(NextionComponentBase *component) = 0; virtual void add_to_get_queue(std::shared_ptr<NextionComponentBase> component) = 0;
virtual void set_component_background_color(const char *component, Color color) = 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; virtual void set_component_pressed_background_color(const char *component, Color color) = 0;

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <utility> #include <utility>
#include <memory>
#include "esphome/core/defines.h" #include "esphome/core/defines.h"
namespace esphome { namespace esphome {
@ -22,7 +23,7 @@ class NextionComponentBase;
class NextionQueue { class NextionQueue {
public: public:
virtual ~NextionQueue() = default; virtual ~NextionQueue() = default;
NextionComponentBase *component; std::shared_ptr<NextionComponentBase> component;
uint32_t queue_time = 0; uint32_t queue_time = 0;
}; };

View file

@ -275,12 +275,12 @@ void Nextion::upload_tft() {
} else { } else {
#endif #endif
ESP_LOGD(TAG, "Allocating buffer size %d, Heap size is %u", chunk_size, ESP.getFreeHeap()); 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]; this->transfer_buffer_ = new (std::nothrow) uint8_t[chunk_size]; // NOLINT(cppcoreguidelines-owning-memory)
if (this->transfer_buffer_ == nullptr) { // Try a smaller size if (this->transfer_buffer_ == nullptr) { // Try a smaller size
ESP_LOGD(TAG, "Could not allocate buffer size: %d trying 4096 instead", chunk_size); ESP_LOGD(TAG, "Could not allocate buffer size: %d trying 4096 instead", chunk_size);
chunk_size = 4096; chunk_size = 4096;
ESP_LOGD(TAG, "Allocating %d buffer", chunk_size); 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_) if (!this->transfer_buffer_)
this->upload_end_(); this->upload_end_();
@ -322,7 +322,7 @@ void Nextion::upload_end_() {
WiFiClient *Nextion::get_wifi_client_() { WiFiClient *Nextion::get_wifi_client_() {
if (this->tft_url_.compare(0, 6, "https:") == 0) { if (this->tft_url_.compare(0, 6, "https:") == 0) {
if (this->wifi_client_secure_ == nullptr) { 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_->setInsecure();
this->wifi_client_secure_->setBufferSizes(512, 512); this->wifi_client_secure_->setBufferSizes(512, 512);
} }
@ -330,7 +330,7 @@ WiFiClient *Nextion::get_wifi_client_() {
} }
if (this->wifi_client_ == nullptr) { if (this->wifi_client_ == nullptr) {
this->wifi_client_ = new WiFiClient(); this->wifi_client_ = new WiFiClient(); // NOLINT(cppcoreguidelines-owning-memory)
} }
return this->wifi_client_; return this->wifi_client_;
} }

View file

@ -34,7 +34,7 @@ void NextionSensor::update() {
return; return;
if (this->wave_chan_id_ == UINT8_MAX) { if (this->wave_chan_id_ == UINT8_MAX) {
this->nextion_->add_to_get_queue(this); this->nextion_->add_to_get_queue(shared_from_this());
} else { } else {
if (this->send_last_value_) { if (this->send_last_value_) {
this->add_to_wave_buffer(this->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_); double to_multiply = pow(10, this->precision_);
int state_value = (int) (state * to_multiply); 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 { } 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_); buffer_to_send, this->wave_buffer_.size(), this->component_id_, this->wave_chan_id_);
#endif #endif
this->nextion_->add_addt_command_to_queue(this); this->nextion_->add_addt_command_to_queue(shared_from_this());
} }
} // namespace nextion } // namespace nextion

View file

@ -8,7 +8,10 @@ namespace esphome {
namespace nextion { namespace nextion {
class NextionSensor; 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<NextionSensor> {
public: public:
NextionSensor(NextionBase *nextion) { this->nextion_ = nextion; } NextionSensor(NextionBase *nextion) { this->nextion_ = nextion; }
void send_state_to_nextion() override { this->set_state(this->state, false, true); }; void send_state_to_nextion() override { this->set_state(this->state, false, true); };

View file

@ -20,7 +20,7 @@ void NextionSwitch::process_bool(const std::string &variable_name, bool on) {
void NextionSwitch::update() { void NextionSwitch::update() {
if (!this->nextion_->is_setup()) if (!this->nextion_->is_setup())
return; 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) { 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; this->needs_to_send_update_ = true;
} else { } else {
this->needs_to_send_update_ = false; 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) { if (publish) {

View file

@ -8,7 +8,10 @@ namespace esphome {
namespace nextion { namespace nextion {
class NextionSwitch; 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<NextionSwitch> {
public: public:
NextionSwitch(NextionBase *nextion) { this->nextion_ = nextion; } NextionSwitch(NextionBase *nextion) { this->nextion_ = nextion; }

View file

@ -18,7 +18,7 @@ void NextionTextSensor::process_text(const std::string &variable_name, const std
void NextionTextSensor::update() { void NextionTextSensor::update() {
if (!this->nextion_->is_setup()) if (!this->nextion_->is_setup())
return; 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) { 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_) { if (this->nextion_->is_sleeping() || !this->visible_) {
this->needs_to_send_update_ = true; this->needs_to_send_update_ = true;
} else { } 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);
} }
} }

View file

@ -8,7 +8,10 @@ namespace esphome {
namespace nextion { namespace nextion {
class NextionTextSensor; 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<NextionTextSensor> {
public: public:
NextionTextSensor(NextionBase *nextion) { this->nextion_ = nextion; } NextionTextSensor(NextionBase *nextion) { this->nextion_ = nextion; }
void update() override; void update() override;

View file

@ -17,7 +17,7 @@ NdefMessage::NdefMessage(std::vector<uint8_t> &data) {
ESP_LOGVV(TAG, "me=%s, sr=%s, il=%s, tnf=%d", YESNO(me), YESNO(sr), YESNO(il), tnf); 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<NdefRecord>();
record->set_tnf(tnf); record->set_tnf(tnf);
uint8_t type_length = data[index++]; uint8_t type_length = data[index++];
@ -62,20 +62,20 @@ NdefMessage::NdefMessage(std::vector<uint8_t> &data) {
record->set_payload(payload_str); record->set_payload(payload_str);
index += payload_length; 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()); 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) if (me)
break; break;
} }
} }
bool NdefMessage::add_record(NdefRecord *record) { bool NdefMessage::add_record(std::unique_ptr<NdefRecord> record) {
if (this->records_.size() >= MAX_NDEF_RECORDS) { if (this->records_.size() >= MAX_NDEF_RECORDS) {
ESP_LOGE(TAG, "Too many records. Max: %d", MAX_NDEF_RECORDS); ESP_LOGE(TAG, "Too many records. Max: %d", MAX_NDEF_RECORDS);
return false; return false;
} }
this->records_.push_back(record); this->records_.emplace_back(std::move(record));
return true; 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) { bool NdefMessage::add_text_record(const std::string &text, const std::string &encoding) {
std::string payload = to_string(text.length()) + encoding + text; std::string payload = to_string(text.length()) + encoding + text;
auto r = new NdefRecord(TNF_WELL_KNOWN, "T", payload); return this->add_record(make_unique<NdefRecord>(TNF_WELL_KNOWN, "T", payload));
return this->add_record(r);
} }
bool NdefMessage::add_uri_record(const std::string &uri) { bool NdefMessage::add_uri_record(const std::string &uri) {
auto r = new NdefRecord(TNF_WELL_KNOWN, "U", uri); return this->add_record(make_unique<NdefRecord>(TNF_WELL_KNOWN, "U", uri));
return this->add_record(r);
} }
std::vector<uint8_t> NdefMessage::encode() { std::vector<uint8_t> NdefMessage::encode() {

View file

@ -1,5 +1,7 @@
#pragma once #pragma once
#include <memory>
#include "esphome/core/helpers.h" #include "esphome/core/helpers.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include "ndef_record.h" #include "ndef_record.h"
@ -11,12 +13,18 @@ static const uint8_t MAX_NDEF_RECORDS = 4;
class NdefMessage { class NdefMessage {
public: public:
NdefMessage(){}; NdefMessage() = default;
NdefMessage(std::vector<uint8_t> &data); NdefMessage(std::vector<uint8_t> &data);
NdefMessage(const NdefMessage &msg) {
records_.reserve(msg.records_.size());
for (const auto &r : msg.records_) {
records_.emplace_back(make_unique<NdefRecord>(*r));
}
}
std::vector<NdefRecord *> get_records() { return this->records_; }; const std::vector<std::unique_ptr<NdefRecord>> &get_records() { return this->records_; };
bool add_record(NdefRecord *record); bool add_record(std::unique_ptr<NdefRecord> record);
bool add_text_record(const std::string &text); bool add_text_record(const std::string &text);
bool add_text_record(const std::string &text, const std::string &encoding); bool add_text_record(const std::string &text, const std::string &encoding);
bool add_uri_record(const std::string &uri); bool add_uri_record(const std::string &uri);
@ -24,7 +32,7 @@ class NdefMessage {
std::vector<uint8_t> encode(); std::vector<uint8_t> encode();
protected: protected:
std::vector<NdefRecord *> records_; std::vector<std::unique_ptr<NdefRecord>> records_;
}; };
} // namespace nfc } // namespace nfc

View file

@ -85,9 +85,9 @@ class NdefRecord {
std::vector<uint8_t> encode(bool first, bool last); std::vector<uint8_t> encode(bool first, bool last);
uint8_t get_tnf_byte(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_type() const { return this->type_; };
const std::string &get_id() { return this->id_; }; const std::string &get_id() const { return this->id_; };
const std::string &get_payload() { return this->payload_; }; const std::string &get_payload() const { return this->payload_; };
protected: protected:
uint8_t tnf_; uint8_t tnf_;

View file

@ -1,6 +1,9 @@
#pragma once #pragma once
#include <memory>
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include "esphome/core/helpers.h"
#include "ndef_message.h" #include "ndef_message.h"
namespace esphome { namespace esphome {
@ -20,27 +23,33 @@ class NfcTag {
this->uid_ = uid; this->uid_ = uid;
this->tag_type_ = tag_type; this->tag_type_ = tag_type;
}; };
NfcTag(std::vector<uint8_t> &uid, const std::string &tag_type, nfc::NdefMessage *ndef_message) { NfcTag(std::vector<uint8_t> &uid, const std::string &tag_type, std::unique_ptr<nfc::NdefMessage> ndef_message) {
this->uid_ = uid; this->uid_ = uid;
this->tag_type_ = tag_type; this->tag_type_ = tag_type;
this->ndef_message_ = ndef_message; this->ndef_message_ = std::move(ndef_message);
}; };
NfcTag(std::vector<uint8_t> &uid, const std::string &tag_type, std::vector<uint8_t> &ndef_data) { NfcTag(std::vector<uint8_t> &uid, const std::string &tag_type, std::vector<uint8_t> &ndef_data) {
this->uid_ = uid; this->uid_ = uid;
this->tag_type_ = tag_type; this->tag_type_ = tag_type;
this->ndef_message_ = new NdefMessage(ndef_data); this->ndef_message_ = make_unique<NdefMessage>(ndef_data);
}; };
NfcTag(const NfcTag &rhs) {
uid_ = rhs.uid_;
tag_type_ = rhs.tag_type_;
if (rhs.ndef_message_ != nullptr)
ndef_message_ = make_unique<NdefMessage>(*rhs.ndef_message_);
}
std::vector<uint8_t> &get_uid() { return this->uid_; }; std::vector<uint8_t> &get_uid() { return this->uid_; };
const std::string &get_tag_type() { return this->tag_type_; }; const std::string &get_tag_type() { return this->tag_type_; };
bool has_ndef_message() { return this->ndef_message_ != nullptr; }; bool has_ndef_message() { return this->ndef_message_ != nullptr; };
NdefMessage *get_ndef_message() { return this->ndef_message_; }; const std::unique_ptr<NdefMessage> &get_ndef_message() { return this->ndef_message_; };
void set_ndef_message(NdefMessage *ndef_message) { this->ndef_message_ = ndef_message; }; void set_ndef_message(std::unique_ptr<NdefMessage> ndef_message) { this->ndef_message_ = std::move(ndef_message); };
protected: protected:
std::vector<uint8_t> uid_; std::vector<uint8_t> uid_;
std::string tag_type_; std::string tag_type_;
NdefMessage *ndef_message_{nullptr}; std::unique_ptr<NdefMessage> ndef_message_;
}; };
} // namespace nfc } // namespace nfc

View file

@ -19,7 +19,7 @@ static const char *const TAG = "ota";
static const uint8_t OTA_VERSION_1_0 = 1; static const uint8_t OTA_VERSION_1_0 = 1;
void OTAComponent::setup() { void OTAComponent::setup() {
this->server_ = new WiFiServer(this->port_); this->server_ = make_unique<WiFiServer>(this->port_);
this->server_->begin(); this->server_->begin();
this->dump_config(); this->dump_config();

View file

@ -1,5 +1,7 @@
#pragma once #pragma once
#include <memory>
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/core/preferences.h" #include "esphome/core/preferences.h"
#include "esphome/core/helpers.h" #include "esphome/core/helpers.h"
@ -80,7 +82,7 @@ class OTAComponent : public Component {
uint16_t port_; uint16_t port_;
WiFiServer *server_{nullptr}; std::unique_ptr<WiFiServer> server_{nullptr};
WiFiClient client_{}; WiFiClient client_{};
bool has_safe_mode_{false}; ///< stores whether safe mode can be enabled. bool has_safe_mode_{false}; ///< stores whether safe mode can be enabled.

View file

@ -20,6 +20,7 @@ CONFIG_SCHEMA = output.FLOAT_OUTPUT_SCHEMA.extend(
async def to_code(config): async def to_code(config):
paren = await cg.get_variable(config[CONF_PCA9685_ID]) paren = await cg.get_variable(config[CONF_PCA9685_ID])
rhs = paren.create_channel(config[CONF_CHANNEL]) var = cg.new_Pvariable(config[CONF_ID])
var = cg.Pvariable(config[CONF_ID], rhs) cg.add(var.set_channel(config[CONF_CHANNEL]))
cg.add(paren.register_channel(var))
await output.register_output(var, config) await output.register_output(var, config)

View file

@ -123,11 +123,11 @@ void PCA9685Output::loop() {
this->update_ = false; this->update_ = false;
} }
PCA9685Channel *PCA9685Output::create_channel(uint8_t channel) { void PCA9685Output::register_channel(PCA9685Channel *channel) {
this->min_channel_ = std::min(this->min_channel_, channel); auto c = channel->channel_;
this->max_channel_ = std::max(this->max_channel_, channel); this->min_channel_ = std::min(this->min_channel_, c);
auto *c = new PCA9685Channel(this, channel); this->max_channel_ = std::max(this->max_channel_, c);
return c; channel->set_parent(this);
} }
void PCA9685Channel::write_state(float state) { void PCA9685Channel::write_state(float state) {

View file

@ -20,14 +20,15 @@ extern const uint8_t PCA9685_MODE_OUTNE_LOW;
class PCA9685Output; class PCA9685Output;
class PCA9685Channel : public output::FloatOutput { class PCA9685Channel : public output::FloatOutput, public Parented<PCA9685Output> {
public: public:
PCA9685Channel(PCA9685Output *parent, uint8_t channel) : parent_(parent), channel_(channel) {} void set_channel(uint8_t channel) { channel_ = channel; }
protected: protected:
friend class PCA9685Output;
void write_state(float state) override; void write_state(float state) override;
PCA9685Output *parent_;
uint8_t channel_; 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) PCA9685Output(float frequency, uint8_t mode = PCA9685_MODE_OUTPUT_ONACK | PCA9685_MODE_OUTPUT_TOTEM_POLE)
: frequency_(frequency), mode_(mode) {} : frequency_(frequency), mode_(mode) {}
PCA9685Channel *create_channel(uint8_t channel); void register_channel(PCA9685Channel *channel);
void setup() override; void setup() override;
void dump_config() override; void dump_config() override;

View file

@ -881,7 +881,7 @@ void Pipsolar::add_polling_command_(const char *command, ENUMPollingCommand poll
size_t length = strlen(command) + 1; size_t length = strlen(command) + 1;
const char *beg = command; const char *beg = command;
const char *end = command + length; 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; size_t i = 0;
for (; beg != end; ++beg, ++i) { for (; beg != end; ++beg, ++i) {
used_polling_command.command[i] = (uint8_t)(*beg); used_polling_command.command[i] = (uint8_t)(*beg);

View file

@ -104,7 +104,7 @@ void PN532::loop() {
if (!success) { if (!success) {
// Something failed // Something failed
if (!this->current_uid_.empty()) { if (!this->current_uid_.empty()) {
auto tag = new nfc::NfcTag(this->current_uid_); auto tag = make_unique<nfc::NfcTag>(this->current_uid_);
for (auto *trigger : this->triggers_ontagremoved_) for (auto *trigger : this->triggers_ontagremoved_)
trigger->process(tag); trigger->process(tag);
} }
@ -117,7 +117,7 @@ void PN532::loop() {
if (num_targets != 1) { if (num_targets != 1) {
// no tags found or too many // no tags found or too many
if (!this->current_uid_.empty()) { if (!this->current_uid_.empty()) {
auto tag = new nfc::NfcTag(this->current_uid_); auto tag = make_unique<nfc::NfcTag>(this->current_uid_);
for (auto *trigger : this->triggers_ontagremoved_) for (auto *trigger : this->triggers_ontagremoved_)
trigger->process(tag); trigger->process(tag);
} }
@ -158,10 +158,10 @@ void PN532::loop() {
if (report) { if (report) {
ESP_LOGD(TAG, "Found new tag '%s'", nfc::format_uid(nfcid).c_str()); ESP_LOGD(TAG, "Found new tag '%s'", nfc::format_uid(nfcid).c_str());
if (tag->has_ndef_message()) { if (tag->has_ndef_message()) {
auto message = tag->get_ndef_message(); const auto &message = tag->get_ndef_message();
auto records = message->get_records(); const auto &records = message->get_records();
ESP_LOGD(TAG, " NDEF formatted 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()); 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<uint8_t> &uid) { std::unique_ptr<nfc::NfcTag> PN532::read_tag_(std::vector<uint8_t> &uid) {
uint8_t type = nfc::guess_tag_type(uid.size()); uint8_t type = nfc::guess_tag_type(uid.size());
if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) { if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) {
@ -281,9 +281,9 @@ nfc::NfcTag *PN532::read_tag_(std::vector<uint8_t> &uid) {
return this->read_mifare_ultralight_tag_(uid); return this->read_mifare_ultralight_tag_(uid);
} else if (type == nfc::TAG_TYPE_UNKNOWN) { } else if (type == nfc::TAG_TYPE_UNKNOWN) {
ESP_LOGV(TAG, "Cannot determine tag type"); ESP_LOGV(TAG, "Cannot determine tag type");
return new nfc::NfcTag(uid); return make_unique<nfc::NfcTag>(uid);
} else { } else {
return new nfc::NfcTag(uid); return make_unique<nfc::NfcTag>(uid);
} }
} }
@ -373,7 +373,9 @@ bool PN532BinarySensor::process(std::vector<uint8_t> &data) {
this->found_ = true; this->found_ = true;
return 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<nfc::NfcTag> &tag) {
this->trigger(nfc::format_uid(tag->get_uid()), *tag);
}
} // namespace pn532 } // namespace pn532
} // namespace esphome } // namespace esphome

View file

@ -54,13 +54,13 @@ class PN532 : public PollingComponent {
virtual bool read_data(std::vector<uint8_t> &data, uint8_t len) = 0; virtual bool read_data(std::vector<uint8_t> &data, uint8_t len) = 0;
virtual bool read_response(uint8_t command, std::vector<uint8_t> &data) = 0; virtual bool read_response(uint8_t command, std::vector<uint8_t> &data) = 0;
nfc::NfcTag *read_tag_(std::vector<uint8_t> &uid); std::unique_ptr<nfc::NfcTag> read_tag_(std::vector<uint8_t> &uid);
bool format_tag_(std::vector<uint8_t> &uid); bool format_tag_(std::vector<uint8_t> &uid);
bool clean_tag_(std::vector<uint8_t> &uid); bool clean_tag_(std::vector<uint8_t> &uid);
bool write_tag_(std::vector<uint8_t> &uid, nfc::NdefMessage *message); bool write_tag_(std::vector<uint8_t> &uid, nfc::NdefMessage *message);
nfc::NfcTag *read_mifare_classic_tag_(std::vector<uint8_t> &uid); std::unique_ptr<nfc::NfcTag> read_mifare_classic_tag_(std::vector<uint8_t> &uid);
bool read_mifare_classic_block_(uint8_t block_num, std::vector<uint8_t> &data); bool read_mifare_classic_block_(uint8_t block_num, std::vector<uint8_t> &data);
bool write_mifare_classic_block_(uint8_t block_num, std::vector<uint8_t> &data); bool write_mifare_classic_block_(uint8_t block_num, std::vector<uint8_t> &data);
bool auth_mifare_classic_block_(std::vector<uint8_t> &uid, uint8_t block_num, uint8_t key_num, const uint8_t *key); bool auth_mifare_classic_block_(std::vector<uint8_t> &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<uint8_t> &uid); bool format_mifare_classic_ndef_(std::vector<uint8_t> &uid);
bool write_mifare_classic_tag_(std::vector<uint8_t> &uid, nfc::NdefMessage *message); bool write_mifare_classic_tag_(std::vector<uint8_t> &uid, nfc::NdefMessage *message);
nfc::NfcTag *read_mifare_ultralight_tag_(std::vector<uint8_t> &uid); std::unique_ptr<nfc::NfcTag> read_mifare_ultralight_tag_(std::vector<uint8_t> &uid);
bool read_mifare_ultralight_page_(uint8_t page_num, std::vector<uint8_t> &data); bool read_mifare_ultralight_page_(uint8_t page_num, std::vector<uint8_t> &data);
bool is_mifare_ultralight_formatted_(); bool is_mifare_ultralight_formatted_();
uint16_t read_mifare_ultralight_capacity_(); uint16_t read_mifare_ultralight_capacity_();
@ -117,7 +117,7 @@ class PN532BinarySensor : public binary_sensor::BinarySensor {
class PN532OnTagTrigger : public Trigger<std::string, nfc::NfcTag> { class PN532OnTagTrigger : public Trigger<std::string, nfc::NfcTag> {
public: public:
void process(nfc::NfcTag *tag); void process(const std::unique_ptr<nfc::NfcTag> &tag);
}; };
class PN532OnFinishedWriteTrigger : public Trigger<> { class PN532OnFinishedWriteTrigger : public Trigger<> {

View file

@ -6,7 +6,7 @@ namespace pn532 {
static const char *const TAG = "pn532.mifare_classic"; static const char *const TAG = "pn532.mifare_classic";
nfc::NfcTag *PN532::read_mifare_classic_tag_(std::vector<uint8_t> &uid) { std::unique_ptr<nfc::NfcTag> PN532::read_mifare_classic_tag_(std::vector<uint8_t> &uid) {
uint8_t current_block = 4; uint8_t current_block = 4;
uint8_t message_start_index = 0; uint8_t message_start_index = 0;
uint32_t message_length = 0; uint32_t message_length = 0;
@ -15,15 +15,15 @@ nfc::NfcTag *PN532::read_mifare_classic_tag_(std::vector<uint8_t> &uid) {
std::vector<uint8_t> data; std::vector<uint8_t> data;
if (this->read_mifare_classic_block_(current_block, data)) { if (this->read_mifare_classic_block_(current_block, data)) {
if (!nfc::decode_mifare_classic_tlv(data, message_length, message_start_index)) { if (!nfc::decode_mifare_classic_tlv(data, message_length, message_start_index)) {
return new nfc::NfcTag(uid, nfc::ERROR); return make_unique<nfc::NfcTag>(uid, nfc::ERROR);
} }
} else { } else {
ESP_LOGE(TAG, "Failed to read block %d", current_block); ESP_LOGE(TAG, "Failed to read block %d", current_block);
return new nfc::NfcTag(uid, nfc::MIFARE_CLASSIC); return make_unique<nfc::NfcTag>(uid, nfc::MIFARE_CLASSIC);
} }
} else { } else {
ESP_LOGV(TAG, "Tag is not NDEF formatted"); ESP_LOGV(TAG, "Tag is not NDEF formatted");
return new nfc::NfcTag(uid, nfc::MIFARE_CLASSIC); return make_unique<nfc::NfcTag>(uid, nfc::MIFARE_CLASSIC);
} }
uint32_t index = 0; uint32_t index = 0;
@ -51,7 +51,7 @@ nfc::NfcTag *PN532::read_mifare_classic_tag_(std::vector<uint8_t> &uid) {
} }
} }
buffer.erase(buffer.begin(), buffer.begin() + message_start_index); buffer.erase(buffer.begin(), buffer.begin() + message_start_index);
return new nfc::NfcTag(uid, nfc::MIFARE_CLASSIC, buffer); return make_unique<nfc::NfcTag>(uid, nfc::MIFARE_CLASSIC, buffer);
} }
bool PN532::read_mifare_classic_block_(uint8_t block_num, std::vector<uint8_t> &data) { bool PN532::read_mifare_classic_block_(uint8_t block_num, std::vector<uint8_t> &data) {

View file

@ -6,28 +6,28 @@ namespace pn532 {
static const char *const TAG = "pn532.mifare_ultralight"; static const char *const TAG = "pn532.mifare_ultralight";
nfc::NfcTag *PN532::read_mifare_ultralight_tag_(std::vector<uint8_t> &uid) { std::unique_ptr<nfc::NfcTag> PN532::read_mifare_ultralight_tag_(std::vector<uint8_t> &uid) {
if (!this->is_mifare_ultralight_formatted_()) { if (!this->is_mifare_ultralight_formatted_()) {
ESP_LOGD(TAG, "Not NDEF formatted"); ESP_LOGD(TAG, "Not NDEF formatted");
return new nfc::NfcTag(uid, nfc::NFC_FORUM_TYPE_2); return make_unique<nfc::NfcTag>(uid, nfc::NFC_FORUM_TYPE_2);
} }
uint8_t message_length; uint8_t message_length;
uint8_t message_start_index; uint8_t message_start_index;
if (!this->find_mifare_ultralight_ndef_(message_length, 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<nfc::NfcTag>(uid, nfc::NFC_FORUM_TYPE_2);
} }
ESP_LOGVV(TAG, "message length: %d, start: %d", message_length, message_start_index); ESP_LOGVV(TAG, "message length: %d, start: %d", message_length, message_start_index);
if (message_length == 0) { if (message_length == 0) {
return new nfc::NfcTag(uid, nfc::NFC_FORUM_TYPE_2); return make_unique<nfc::NfcTag>(uid, nfc::NFC_FORUM_TYPE_2);
} }
std::vector<uint8_t> data; std::vector<uint8_t> data;
for (uint8_t page = nfc::MIFARE_ULTRALIGHT_DATA_START_PAGE; page < nfc::MIFARE_ULTRALIGHT_MAX_PAGE; page++) { for (uint8_t page = nfc::MIFARE_ULTRALIGHT_DATA_START_PAGE; page < nfc::MIFARE_ULTRALIGHT_MAX_PAGE; page++) {
std::vector<uint8_t> page_data; std::vector<uint8_t> page_data;
if (!this->read_mifare_ultralight_page_(page, page_data)) { if (!this->read_mifare_ultralight_page_(page, page_data)) {
ESP_LOGE(TAG, "Error reading page %d", page); ESP_LOGE(TAG, "Error reading page %d", page);
return new nfc::NfcTag(uid, nfc::NFC_FORUM_TYPE_2); return make_unique<nfc::NfcTag>(uid, nfc::NFC_FORUM_TYPE_2);
} }
data.insert(data.end(), page_data.begin(), page_data.end()); data.insert(data.end(), page_data.begin(), page_data.end());
@ -38,7 +38,7 @@ nfc::NfcTag *PN532::read_mifare_ultralight_tag_(std::vector<uint8_t> &uid) {
data.erase(data.begin(), data.begin() + message_start_index); data.erase(data.begin(), data.begin() + message_start_index);
data.erase(data.begin() + message_length, data.end()); data.erase(data.begin() + message_length, data.end());
return new nfc::NfcTag(uid, nfc::NFC_FORUM_TYPE_2, data); return make_unique<nfc::NfcTag>(uid, nfc::NFC_FORUM_TYPE_2, data);
} }
bool PN532::read_mifare_ultralight_page_(uint8_t page_num, std::vector<uint8_t> &data) { bool PN532::read_mifare_ultralight_page_(uint8_t page_num, std::vector<uint8_t> &data) {

View file

@ -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) { bool SCD30Component::read_data_(uint16_t *data, uint8_t len) {
const uint8_t num_bytes = len * 3; const uint8_t num_bytes = len * 3;
auto *buf = new uint8_t[num_bytes]; std::vector<uint8_t> buf(num_bytes);
if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) {
delete[](buf);
return false; 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]); uint8_t crc = sht_crc_(buf[j], buf[j + 1]);
if (crc != buf[j + 2]) { if (crc != buf[j + 2]) {
ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc);
delete[](buf);
return false; return false;
} }
data[i] = (buf[j] << 8) | buf[j + 1]; data[i] = (buf[j] << 8) | buf[j + 1];
} }
delete[](buf);
return true; return true;
} }

View file

@ -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) { bool SGP30Component::read_data_(uint16_t *data, uint8_t len) {
const uint8_t num_bytes = len * 3; const uint8_t num_bytes = len * 3;
auto *buf = new uint8_t[num_bytes]; std::vector<uint8_t> buf(num_bytes);
if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) {
delete[](buf);
return false; 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]); uint8_t crc = sht_crc_(buf[j], buf[j + 1]);
if (crc != buf[j + 2]) { if (crc != buf[j + 2]) {
ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc);
delete[](buf);
return false; return false;
} }
data[i] = (buf[j] << 8) | buf[j + 1]; data[i] = (buf[j] << 8) | buf[j + 1];
} }
delete[](buf);
return true; return true;
} }

View file

@ -101,10 +101,9 @@ uint8_t sht_crc(uint8_t data1, uint8_t data2) {
bool SHT3XDComponent::read_data_(uint16_t *data, uint8_t len) { bool SHT3XDComponent::read_data_(uint16_t *data, uint8_t len) {
const uint8_t num_bytes = len * 3; const uint8_t num_bytes = len * 3;
auto *buf = new uint8_t[num_bytes]; std::vector<uint8_t> buf(num_bytes);
if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) {
delete[](buf);
return false; 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]); uint8_t crc = sht_crc(buf[j], buf[j + 1]);
if (crc != buf[j + 2]) { if (crc != buf[j + 2]) {
ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc);
delete[](buf);
return false; return false;
} }
data[i] = (buf[j] << 8) | buf[j + 1]; data[i] = (buf[j] << 8) | buf[j + 1];
} }
delete[](buf);
return true; return true;
} }

View file

@ -130,10 +130,9 @@ uint8_t sht_crc(uint8_t data1, uint8_t data2) {
bool SHTCXComponent::read_data_(uint16_t *data, uint8_t len) { bool SHTCXComponent::read_data_(uint16_t *data, uint8_t len) {
const uint8_t num_bytes = len * 3; const uint8_t num_bytes = len * 3;
auto *buf = new uint8_t[num_bytes]; std::vector<uint8_t> buf(num_bytes);
if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) {
delete[](buf);
return false; 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]); uint8_t crc = sht_crc(buf[j], buf[j + 1]);
if (crc != buf[j + 2]) { if (crc != buf[j + 2]) {
ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc);
delete[](buf);
return false; return false;
} }
data[i] = (buf[j] << 8) | buf[j + 1]; data[i] = (buf[j] << 8) | buf[j + 1];
} }
delete[](buf);
return true; return true;
} }

View file

@ -423,9 +423,9 @@ class LWIPRawImpl : public Socket {
// nothing to do here, we just don't push it to the queue // nothing to do here, we just don't push it to the queue
return ERR_OK; return ERR_OK;
} }
auto *sock = new LWIPRawImpl(newpcb); auto sock = std::unique_ptr<LWIPRawImpl>(new LWIPRawImpl(newpcb));
sock->init(); sock->init();
accepted_sockets_.emplace(sock); accepted_sockets_.push(std::move(sock));
return ERR_OK; return ERR_OK;
} }
void err_fn(err_t err) { void err_fn(err_t err) {
@ -486,7 +486,7 @@ std::unique_ptr<Socket> socket(int domain, int type, int protocol) {
auto *pcb = tcp_new(); auto *pcb = tcp_new();
if (pcb == nullptr) if (pcb == nullptr)
return nullptr; return nullptr;
auto *sock = new LWIPRawImpl(pcb); auto *sock = new LWIPRawImpl(pcb); // NOLINT(cppcoreguidelines-owning-memory)
sock->init(); sock->init();
return std::unique_ptr<Socket>{sock}; return std::unique_ptr<Socket>{sock};
} }

View file

@ -242,10 +242,9 @@ bool SPS30Component::start_continuous_measurement_() {
bool SPS30Component::read_data_(uint16_t *data, uint8_t len) { bool SPS30Component::read_data_(uint16_t *data, uint8_t len) {
const uint8_t num_bytes = len * 3; const uint8_t num_bytes = len * 3;
auto *buf = new uint8_t[num_bytes]; std::vector<uint8_t> buf(num_bytes);
if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) {
delete[](buf);
return false; 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]); uint8_t crc = sht_crc_(buf[j], buf[j + 1]);
if (crc != buf[j + 2]) { if (crc != buf[j + 2]) {
ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc);
delete[](buf);
return false; return false;
} }
data[i] = (buf[j] << 8) | buf[j + 1]; data[i] = (buf[j] << 8) | buf[j + 1];
} }
delete[](buf);
return true; return true;
} }

View file

@ -97,10 +97,9 @@ uint8_t sts3x_crc(uint8_t data1, uint8_t data2) {
bool STS3XComponent::read_data_(uint16_t *data, uint8_t len) { bool STS3XComponent::read_data_(uint16_t *data, uint8_t len) {
const uint8_t num_bytes = len * 3; const uint8_t num_bytes = len * 3;
auto *buf = new uint8_t[num_bytes]; std::vector<uint8_t> buf(num_bytes);
if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { if (!this->parent_->raw_receive(this->address_, buf.data(), num_bytes)) {
delete[](buf);
return false; 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]); uint8_t crc = sts3x_crc(buf[j], buf[j + 1]);
if (crc != buf[j + 2]) { if (crc != buf[j + 2]) {
ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc); ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc);
delete[](buf);
return false; return false;
} }
data[i] = (buf[j] << 8) | buf[j + 1]; data[i] = (buf[j] << 8) | buf[j + 1];
} }
delete[](buf);
return true; return true;
} }

View file

@ -20,6 +20,7 @@ CONFIG_SCHEMA = output.FLOAT_OUTPUT_SCHEMA.extend(
async def to_code(config): async def to_code(config):
paren = await cg.get_variable(config[CONF_TLC59208F_ID]) paren = await cg.get_variable(config[CONF_TLC59208F_ID])
rhs = paren.create_channel(config[CONF_CHANNEL]) var = cg.new_Pvariable(config[CONF_ID])
var = cg.Pvariable(config[CONF_ID], rhs) cg.add(var.set_channel(config[CONF_CHANNEL]))
cg.add(paren.register_channel(var))
await output.register_output(var, config) await output.register_output(var, config)

View file

@ -137,11 +137,11 @@ void TLC59208FOutput::loop() {
this->update_ = false; this->update_ = false;
} }
TLC59208FChannel *TLC59208FOutput::create_channel(uint8_t channel) { void TLC59208FOutput::register_channel(TLC59208FChannel *channel) {
this->min_channel_ = std::min(this->min_channel_, channel); auto c = channel->channel_;
this->max_channel_ = std::max(this->max_channel_, channel); this->min_channel_ = std::min(this->min_channel_, c);
auto *c = new TLC59208FChannel(this, channel); this->max_channel_ = std::max(this->max_channel_, c);
return c; channel->set_parent(this);
} }
void TLC59208FChannel::write_state(float state) { void TLC59208FChannel::write_state(float state) {

View file

@ -21,14 +21,15 @@ extern const uint8_t TLC59208F_MODE2_WDT_35MS;
class TLC59208FOutput; class TLC59208FOutput;
class TLC59208FChannel : public output::FloatOutput { class TLC59208FChannel : public output::FloatOutput, public Parented<TLC59208FOutput> {
public: public:
TLC59208FChannel(TLC59208FOutput *parent, uint8_t channel) : parent_(parent), channel_(channel) {} void set_channel(uint8_t channel) { channel_ = channel; }
protected: protected:
friend class TLC59208FOutput;
void write_state(float state) override; void write_state(float state) override;
TLC59208FOutput *parent_;
uint8_t channel_; uint8_t channel_;
}; };
@ -37,7 +38,7 @@ class TLC59208FOutput : public Component, public i2c::I2CDevice {
public: public:
TLC59208FOutput(uint8_t mode = TLC59208F_MODE2_OCH) : mode_(mode) {} TLC59208FOutput(uint8_t mode = TLC59208F_MODE2_OCH) : mode_(mode) {}
TLC59208FChannel *create_channel(uint8_t channel); void register_channel(TLC59208FChannel *channel);
void setup() override; void setup() override;
void dump_config() override; void dump_config() override;

View file

@ -1,5 +1,6 @@
#include "tm1651.h" #include "tm1651.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include "esphome/core/helpers.h"
namespace esphome { namespace esphome {
namespace tm1651 { namespace tm1651 {
@ -19,7 +20,7 @@ void TM1651Display::setup() {
uint8_t clk = clk_pin_->get_pin(); uint8_t clk = clk_pin_->get_pin();
uint8_t dio = dio_pin_->get_pin(); uint8_t dio = dio_pin_->get_pin();
battery_display_ = new TM1651(clk, dio); battery_display_ = make_unique<TM1651>(clk, dio);
battery_display_->init(); battery_display_->init();
battery_display_->clearDisplay(); battery_display_->clearDisplay();
} }

View file

@ -1,5 +1,7 @@
#pragma once #pragma once
#include <memory>
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/core/esphal.h" #include "esphome/core/esphal.h"
#include "esphome/core/automation.h" #include "esphome/core/automation.h"
@ -25,7 +27,7 @@ class TM1651Display : public Component {
void turn_off(); void turn_off();
protected: protected:
TM1651 *battery_display_; std::unique_ptr<TM1651> battery_display_;
GPIOPin *clk_pin_; GPIOPin *clk_pin_;
GPIOPin *dio_pin_; GPIOPin *dio_pin_;
bool is_on_ = true; bool is_on_ = true;

View file

@ -85,7 +85,7 @@ void UARTComponent::setup() {
this->hw_serial_->begin(this->baud_rate_, config); this->hw_serial_->begin(this->baud_rate_, config);
this->hw_serial_->setRxBufferSize(this->rx_buffer_size_); this->hw_serial_->setRxBufferSize(this->rx_buffer_size_);
} else { } 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 tx = this->tx_pin_.has_value() ? *this->tx_pin_ : -1;
int8_t rx = this->rx_pin_.has_value() ? *this->rx_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_, 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(); pin.setup();
this->gpio_rx_pin_ = &pin; this->gpio_rx_pin_ = &pin;
this->rx_pin_ = pin.to_isr(); 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); pin.attach_interrupt(ESP8266SoftwareSerial::gpio_intr, this, FALLING);
} }
} }

View file

@ -86,7 +86,9 @@ void OTARequestHandler::handleRequest(AsyncWebServerRequest *request) {
request->send(response); 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 { float WebServerBase::get_setup_priority() const {
// Before WiFi (captive portal) // Before WiFi (captive portal)
return setup_priority::WIFI + 2.0f; return setup_priority::WIFI + 2.0f;

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <memory>
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include <ESPAsyncWebServer.h> #include <ESPAsyncWebServer.h>
@ -14,7 +15,7 @@ class WebServerBase : public Component {
this->initialized_++; this->initialized_++;
return; return;
} }
this->server_ = new AsyncWebServer(this->port_); this->server_ = std::make_shared<AsyncWebServer>(this->port_);
this->server_->begin(); this->server_->begin();
for (auto *handler : this->handlers_) for (auto *handler : this->handlers_)
@ -25,11 +26,10 @@ class WebServerBase : public Component {
void deinit() { void deinit() {
this->initialized_--; this->initialized_--;
if (this->initialized_ == 0) { if (this->initialized_ == 0) {
delete this->server_;
this->server_ = nullptr; this->server_ = nullptr;
} }
} }
AsyncWebServer *get_server() const { return server_; } std::shared_ptr<AsyncWebServer> get_server() const { return server_; }
float get_setup_priority() const override; float get_setup_priority() const override;
void add_handler(AsyncWebHandler *handler) { void add_handler(AsyncWebHandler *handler) {
@ -50,7 +50,7 @@ class WebServerBase : public Component {
int initialized_{0}; int initialized_{0};
uint16_t port_{80}; uint16_t port_{80};
AsyncWebServer *server_{nullptr}; std::shared_ptr<AsyncWebServer> server_{nullptr};
std::vector<AsyncWebHandler *> handlers_; std::vector<AsyncWebHandler *> handlers_;
}; };

View file

@ -1,5 +1,6 @@
#include "wled_light_effect.h" #include "wled_light_effect.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include "esphome/core/helpers.h"
#ifdef ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP32
#include <WiFi.h> #include <WiFi.h>
@ -48,7 +49,7 @@ void WLEDLightEffect::blank_all_leds_(light::AddressableLight &it) {
void WLEDLightEffect::apply(light::AddressableLight &it, const Color &current_color) { void WLEDLightEffect::apply(light::AddressableLight &it, const Color &current_color) {
// Init UDP lazily // Init UDP lazily
if (!udp_) { if (!udp_) {
udp_.reset(new WiFiUDP()); udp_ = make_unique<WiFiUDP>();
if (!udp_->begin(port_)) { if (!udp_->begin(port_)) {
ESP_LOGW(TAG, "Cannot bind WLEDLightEffect to %d.", port_); ESP_LOGW(TAG, "Cannot bind WLEDLightEffect to %d.", port_);

View file

@ -230,10 +230,11 @@ void GPIOPin::attach_interrupt_(void (*func)(void *), void *arg, int mode) const
} }
} }
#ifdef ARDUINO_ARCH_ESP8266 #ifdef ARDUINO_ARCH_ESP8266
ArgStructure *as = new ArgStructure; ArgStructure *as = new ArgStructure; // NOLINT
as->interruptInfo = nullptr; as->interruptInfo = nullptr;
as->functionInfo = new ESPHomeInterruptFuncInfo{ as->functionInfo = new ESPHomeInterruptFuncInfo{
// NOLINT
.func = func, .func = func,
.arg = arg, .arg = arg,
}; };
@ -249,7 +250,7 @@ void GPIOPin::attach_interrupt_(void (*func)(void *), void *arg, int mode) const
} }
ISRInternalGPIOPin *GPIOPin::to_isr() const { ISRInternalGPIOPin *GPIOPin::to_isr() const {
return new ISRInternalGPIOPin(this->pin_, return new ISRInternalGPIOPin(this->pin_, // NOLINT
#ifdef ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP32
this->gpio_clear_, this->gpio_set_, this->gpio_clear_, this->gpio_set_,
#endif #endif

View file

@ -141,21 +141,6 @@ std::string uint32_to_string(uint32_t num) {
snprintf(buffer, sizeof(buffer), "%04X%04X", address16[1], address16[0]); snprintf(buffer, sizeof(buffer), "%04X%04X", address16[1], address16[0]);
return std::string(buffer); 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) { ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) {
if (on == nullptr && strcasecmp(str, "on") == 0) if (on == nullptr && strcasecmp(str, "on") == 0)

View file

@ -338,7 +338,7 @@ template<typename T> T *new_buffer(size_t length) {
buffer = new T[length]; buffer = new T[length];
} }
#else #else
buffer = new T[length]; buffer = new T[length]; // NOLINT
#endif #endif
return buffer; return buffer;

View file

@ -17,13 +17,8 @@ namespace esphome {
static const char *const TAG = "preferences"; 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) ESPPreferenceObject::ESPPreferenceObject(size_t offset, size_t length, uint32_t type)
: offset_(offset), length_words_(length), type_(type) { : offset_(offset), length_words_(length), type_(type), data_(length + 1) {}
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;
}
bool ESPPreferenceObject::load_() { bool ESPPreferenceObject::load_() {
if (!this->is_initialized()) { if (!this->is_initialized()) {
ESP_LOGV(TAG, "Load Pref Not initialized!"); ESP_LOGV(TAG, "Load Pref Not initialized!");
@ -173,7 +168,7 @@ ESPPreferences::ESPPreferences()
: current_offset_(0) {} : current_offset_(0) {}
void ESPPreferences::begin() { 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..."); ESP_LOGVV(TAG, "Loading preferences from flash...");
{ {
@ -234,7 +229,7 @@ bool ESPPreferenceObject::save_internal_() {
char key[32]; char key[32];
sprintf(key, "%u", this->offset_); sprintf(key, "%u", this->offset_);
uint32_t len = (this->length_words_ + 1) * 4; 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) { if (err) {
ESP_LOGV(TAG, "nvs_set_blob('%s', len=%u) failed: %s", key, len, esp_err_to_name(err)); ESP_LOGV(TAG, "nvs_set_blob('%s', len=%u) failed: %s", key, len, esp_err_to_name(err));
return false; 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); ESP_LOGVV(TAG, "NVS length does not match. Assuming key changed (%u!=%u)", actual_len, len);
return false; 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) { if (err) {
ESP_LOGV(TAG, "nvs_get_blob('%s') failed: %s", key, esp_err_to_name(err)); ESP_LOGV(TAG, "nvs_get_blob('%s') failed: %s", key, esp_err_to_name(err));
return false; return false;
@ -301,7 +296,7 @@ uint32_t ESPPreferenceObject::calculate_crc_() const {
} }
return crc; 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) ESPPreferences global_preferences; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)

View file

@ -1,6 +1,8 @@
#pragma once #pragma once
#include <string> #include <string>
#include <vector>
#include <algorithm>
#include <cstring> #include <cstring>
#include "esphome/core/defines.h" #include "esphome/core/defines.h"
@ -9,7 +11,7 @@ namespace esphome {
class ESPPreferenceObject { class ESPPreferenceObject {
public: public:
ESPPreferenceObject(); ESPPreferenceObject() = default;
ESPPreferenceObject(size_t offset, size_t length, uint32_t type); ESPPreferenceObject(size_t offset, size_t length, uint32_t type);
template<typename T> bool save(T *src); template<typename T> bool save(T *src);
@ -28,12 +30,12 @@ class ESPPreferenceObject {
uint32_t calculate_crc_() const; uint32_t calculate_crc_() const;
size_t offset_; size_t offset_ = 0;
size_t length_words_; size_t length_words_ = 0;
uint32_t type_; uint32_t type_ = 0;
uint32_t *data_; std::vector<uint32_t> data_;
#ifdef ARDUINO_ARCH_ESP8266 #ifdef ARDUINO_ARCH_ESP8266
bool in_flash_{false}; bool in_flash_ = false;
#endif #endif
}; };
@ -92,17 +94,18 @@ template<typename T> ESPPreferenceObject ESPPreferences::make_preference(uint32_
template<typename T> bool ESPPreferenceObject::save(T *src) { template<typename T> bool ESPPreferenceObject::save(T *src) {
if (!this->is_initialized()) if (!this->is_initialized())
return false; return false;
memset(this->data_, 0, this->length_words_ * 4); // ensure all bytes are 0 (in case sizeof(T) is not multiple of 4)
memcpy(this->data_, src, sizeof(T)); std::fill_n(data_.begin(), length_words_, 0);
memcpy(data_.data(), src, sizeof(T));
return this->save_(); return this->save_();
} }
template<typename T> bool ESPPreferenceObject::load(T *dest) { template<typename T> bool ESPPreferenceObject::load(T *dest) {
memset(this->data_, 0, this->length_words_ * 4); std::fill_n(data_.begin(), length_words_, 0);
if (!this->load_()) if (!this->load_())
return false; return false;
memcpy(dest, this->data_, sizeof(T)); memcpy(dest, data_.data(), sizeof(T));
return true; return true;
} }

View file

@ -13,23 +13,23 @@ using namespace esphome;
void setup() { void setup() {
App.pre_setup("livingroom", __DATE__ ", " __TIME__, false); 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(); log->pre_setup();
App.register_component(log); App.register_component(log);
auto *wifi = new wifi::WiFiComponent(); auto *wifi = new wifi::WiFiComponent(); // NOLINT
App.register_component(wifi); App.register_component(wifi);
wifi::WiFiAP ap; wifi::WiFiAP ap;
ap.set_ssid("Test SSID"); ap.set_ssid("Test SSID");
ap.set_password("password1"); ap.set_password("password1");
wifi->add_sta(ap); wifi->add_sta(ap);
auto *ota = new ota::OTAComponent(); auto *ota = new ota::OTAComponent(); // NOLINT
ota->set_port(8266); ota->set_port(8266);
auto *gpio = new gpio::GPIOSwitch(); auto *gpio = new gpio::GPIOSwitch(); // NOLINT
gpio->set_name("GPIO Switch"); 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_component(gpio);
App.register_switch(gpio); App.register_switch(gpio);