From 58d028ac1375511362fac3bf524b86567ef584b0 Mon Sep 17 00:00:00 2001 From: Oleg Tarasov Date: Tue, 12 Nov 2024 06:19:42 +0300 Subject: [PATCH 001/107] Add OpenTherm component (part 3: rest of the sensors) (#7676) Co-authored-by: FreeBear Co-authored-by: FreeBear-nc <67865163+FreeBear-nc@users.noreply.github.com> Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com> --- esphome/components/opentherm/__init__.py | 30 +- .../opentherm/binary_sensor/__init__.py | 33 ++ esphome/components/opentherm/const.py | 6 + esphome/components/opentherm/generate.py | 2 + esphome/components/opentherm/hub.cpp | 42 +- esphome/components/opentherm/hub.h | 52 ++- esphome/components/opentherm/input.h | 18 + esphome/components/opentherm/input.py | 51 +++ .../components/opentherm/number/__init__.py | 74 ++++ .../components/opentherm/number/number.cpp | 40 ++ esphome/components/opentherm/number/number.h | 31 ++ esphome/components/opentherm/opentherm.h | 33 ++ .../components/opentherm/opentherm_macros.h | 60 +++ .../components/opentherm/output/__init__.py | 47 +++ .../components/opentherm/output/output.cpp | 18 + esphome/components/opentherm/output/output.h | 33 ++ esphome/components/opentherm/schema.py | 378 +++++++++++++++++- .../components/opentherm/sensor/__init__.py | 16 + .../components/opentherm/switch/__init__.py | 43 ++ .../components/opentherm/switch/switch.cpp | 28 ++ esphome/components/opentherm/switch/switch.h | 20 + tests/components/opentherm/common.yaml | 84 ++++ 22 files changed, 1128 insertions(+), 11 deletions(-) create mode 100644 esphome/components/opentherm/binary_sensor/__init__.py create mode 100644 esphome/components/opentherm/input.h create mode 100644 esphome/components/opentherm/input.py create mode 100644 esphome/components/opentherm/number/__init__.py create mode 100644 esphome/components/opentherm/number/number.cpp create mode 100644 esphome/components/opentherm/number/number.h create mode 100644 esphome/components/opentherm/output/__init__.py create mode 100644 esphome/components/opentherm/output/output.cpp create mode 100644 esphome/components/opentherm/output/output.h create mode 100644 esphome/components/opentherm/switch/__init__.py create mode 100644 esphome/components/opentherm/switch/switch.cpp create mode 100644 esphome/components/opentherm/switch/switch.h diff --git a/esphome/components/opentherm/__init__.py b/esphome/components/opentherm/__init__.py index ee19818a29..81cd78af08 100644 --- a/esphome/components/opentherm/__init__.py +++ b/esphome/components/opentherm/__init__.py @@ -3,8 +3,9 @@ from typing import Any import esphome.codegen as cg import esphome.config_validation as cv from esphome import pins +from esphome.components import sensor from esphome.const import CONF_ID, PLATFORM_ESP32, PLATFORM_ESP8266 -from . import generate +from . import const, schema, validate, generate CODEOWNERS = ["@olegtarasov"] MULTI_CONF = True @@ -19,6 +20,7 @@ CONF_CH2_ACTIVE = "ch2_active" CONF_SUMMER_MODE_ACTIVE = "summer_mode_active" CONF_DHW_BLOCK = "dhw_block" CONF_SYNC_MODE = "sync_mode" +CONF_OPENTHERM_VERSION = "opentherm_version" CONFIG_SCHEMA = cv.All( cv.Schema( @@ -34,8 +36,15 @@ CONFIG_SCHEMA = cv.All( cv.Optional(CONF_SUMMER_MODE_ACTIVE, False): cv.boolean, cv.Optional(CONF_DHW_BLOCK, False): cv.boolean, cv.Optional(CONF_SYNC_MODE, False): cv.boolean, + cv.Optional(CONF_OPENTHERM_VERSION): cv.positive_float, } - ).extend(cv.COMPONENT_SCHEMA), + ) + .extend( + validate.create_entities_schema( + schema.INPUTS, (lambda _: cv.use_id(sensor.Sensor)) + ) + ) + .extend(cv.COMPONENT_SCHEMA), cv.only_on([PLATFORM_ESP32, PLATFORM_ESP8266]), ) @@ -52,8 +61,23 @@ async def to_code(config: dict[str, Any]) -> None: cg.add(var.set_out_pin(out_pin)) non_sensors = {CONF_ID, CONF_IN_PIN, CONF_OUT_PIN} + input_sensors = [] for key, value in config.items(): if key in non_sensors: continue + if key in schema.INPUTS: + input_sensor = await cg.get_variable(value) + cg.add( + getattr(var, f"set_{key}_{const.INPUT_SENSOR.lower()}")(input_sensor) + ) + input_sensors.append(key) + else: + cg.add(getattr(var, f"set_{key}")(value)) - cg.add(getattr(var, f"set_{key}")(value)) + if len(input_sensors) > 0: + generate.define_has_component(const.INPUT_SENSOR, input_sensors) + generate.define_message_handler( + const.INPUT_SENSOR, input_sensors, schema.INPUTS + ) + generate.define_readers(const.INPUT_SENSOR, input_sensors) + generate.add_messages(var, input_sensors, schema.INPUTS) diff --git a/esphome/components/opentherm/binary_sensor/__init__.py b/esphome/components/opentherm/binary_sensor/__init__.py new file mode 100644 index 0000000000..643734f90c --- /dev/null +++ b/esphome/components/opentherm/binary_sensor/__init__.py @@ -0,0 +1,33 @@ +from typing import Any + +import esphome.config_validation as cv +from esphome.components import binary_sensor +from .. import const, schema, validate, generate + +DEPENDENCIES = [const.OPENTHERM] +COMPONENT_TYPE = const.BINARY_SENSOR + + +def get_entity_validation_schema(entity: schema.BinarySensorSchema) -> cv.Schema: + return binary_sensor.binary_sensor_schema( + device_class=( + entity.device_class + or binary_sensor._UNDEF # pylint: disable=protected-access + ), + icon=(entity.icon or binary_sensor._UNDEF), # pylint: disable=protected-access + ) + + +CONFIG_SCHEMA = validate.create_component_schema( + schema.BINARY_SENSORS, get_entity_validation_schema +) + + +async def to_code(config: dict[str, Any]) -> None: + await generate.component_to_code( + COMPONENT_TYPE, + schema.BINARY_SENSORS, + binary_sensor.BinarySensor, + generate.create_only_conf(binary_sensor.new_binary_sensor), + config, + ) diff --git a/esphome/components/opentherm/const.py b/esphome/components/opentherm/const.py index 1f997c5d9c..a113331585 100644 --- a/esphome/components/opentherm/const.py +++ b/esphome/components/opentherm/const.py @@ -1,5 +1,11 @@ OPENTHERM = "opentherm" CONF_OPENTHERM_ID = "opentherm_id" +CONF_DATA_TYPE = "data_type" SENSOR = "sensor" +BINARY_SENSOR = "binary_sensor" +SWITCH = "switch" +NUMBER = "number" +OUTPUT = "output" +INPUT_SENSOR = "input_sensor" diff --git a/esphome/components/opentherm/generate.py b/esphome/components/opentherm/generate.py index 6a97835a57..9716cab093 100644 --- a/esphome/components/opentherm/generate.py +++ b/esphome/components/opentherm/generate.py @@ -130,6 +130,8 @@ async def component_to_code( id = conf[CONF_ID] if id and id.type == type: entity = await create(conf, key, hub) + if const.CONF_DATA_TYPE in conf: + schemas[key].message_data = conf[const.CONF_DATA_TYPE] cg.add(getattr(hub, f"set_{key}_{component_type.lower()}")(entity)) keys.append(key) diff --git a/esphome/components/opentherm/hub.cpp b/esphome/components/opentherm/hub.cpp index 770bbd82b7..432036d58d 100644 --- a/esphome/components/opentherm/hub.cpp +++ b/esphome/components/opentherm/hub.cpp @@ -29,6 +29,8 @@ uint8_t parse_u8_hb(OpenthermData &data) { return data.valueHB; } int8_t parse_s8_lb(OpenthermData &data) { return (int8_t) data.valueLB; } int8_t parse_s8_hb(OpenthermData &data) { return (int8_t) data.valueHB; } uint16_t parse_u16(OpenthermData &data) { return data.u16(); } +uint16_t parse_u8_lb_60(OpenthermData &data) { return data.valueLB * 60; } +uint16_t parse_u8_hb_60(OpenthermData &data) { return data.valueHB * 60; } int16_t parse_s16(OpenthermData &data) { return data.s16(); } float parse_f88(OpenthermData &data) { return data.f88(); } @@ -87,13 +89,40 @@ OpenthermData OpenthermHub::build_request_(MessageId request_id) const { return data; } + // Another special case is OpenTherm version number which is configured at hub level as a constant + if (request_id == MessageId::OT_VERSION_CONTROLLER) { + data.type = MessageType::WRITE_DATA; + data.id = MessageId::OT_VERSION_CONTROLLER; + data.f88(this->opentherm_version_); + + return data; + } + // Disable incomplete switch statement warnings, because the cases in each // switch are generated based on the configured sensors and inputs. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch" - switch (request_id) { OPENTHERM_SENSOR_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_READ_MESSAGE, OPENTHERM_IGNORE, , , ) } + // Next, we start with the write requests from switches and other inputs, + // because we would want to write that data if it is available, rather than + // request a read for that type (in the case that both read and write are + // supported). + switch (request_id) { + OPENTHERM_SWITCH_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_WRITE_MESSAGE, OPENTHERM_MESSAGE_WRITE_ENTITY, , + OPENTHERM_MESSAGE_WRITE_POSTSCRIPT, ) + OPENTHERM_NUMBER_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_WRITE_MESSAGE, OPENTHERM_MESSAGE_WRITE_ENTITY, , + OPENTHERM_MESSAGE_WRITE_POSTSCRIPT, ) + OPENTHERM_OUTPUT_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_WRITE_MESSAGE, OPENTHERM_MESSAGE_WRITE_ENTITY, , + OPENTHERM_MESSAGE_WRITE_POSTSCRIPT, ) + OPENTHERM_INPUT_SENSOR_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_WRITE_MESSAGE, OPENTHERM_MESSAGE_WRITE_ENTITY, , + OPENTHERM_MESSAGE_WRITE_POSTSCRIPT, ) + } + // Finally, handle the simple read requests, which only change with the message id. + switch (request_id) { OPENTHERM_SENSOR_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_READ_MESSAGE, OPENTHERM_IGNORE, , , ) } + switch (request_id) { + OPENTHERM_BINARY_SENSOR_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_READ_MESSAGE, OPENTHERM_IGNORE, , , ) + } #pragma GCC diagnostic pop // And if we get here, a message was requested which somehow wasn't handled. @@ -115,6 +144,10 @@ void OpenthermHub::process_response(OpenthermData &data) { OPENTHERM_SENSOR_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_RESPONSE_MESSAGE, OPENTHERM_MESSAGE_RESPONSE_ENTITY, , OPENTHERM_MESSAGE_RESPONSE_POSTSCRIPT, ) } + switch (data.id) { + OPENTHERM_BINARY_SENSOR_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_RESPONSE_MESSAGE, OPENTHERM_MESSAGE_RESPONSE_ENTITY, , + OPENTHERM_MESSAGE_RESPONSE_POSTSCRIPT, ) + } } void OpenthermHub::setup() { @@ -131,6 +164,13 @@ void OpenthermHub::setup() { // good practice anyway. this->add_repeating_message(MessageId::STATUS); + // Also ensure that we start communication with the STATUS message + this->initial_messages_.insert(this->initial_messages_.begin(), MessageId::STATUS); + + if (this->opentherm_version_ > 0.0f) { + this->initial_messages_.insert(this->initial_messages_.begin(), MessageId::OT_VERSION_CONTROLLER); + } + this->current_message_iterator_ = this->initial_messages_.begin(); } diff --git a/esphome/components/opentherm/hub.h b/esphome/components/opentherm/hub.h index 3b90cdf427..1f536653e8 100644 --- a/esphome/components/opentherm/hub.h +++ b/esphome/components/opentherm/hub.h @@ -4,6 +4,7 @@ #include "esphome/core/hal.h" #include "esphome/core/component.h" #include "esphome/core/log.h" +#include #include "opentherm.h" @@ -11,6 +12,22 @@ #include "esphome/components/sensor/sensor.h" #endif +#ifdef OPENTHERM_USE_BINARY_SENSOR +#include "esphome/components/binary_sensor/binary_sensor.h" +#endif + +#ifdef OPENTHERM_USE_SWITCH +#include "esphome/components/opentherm/switch/switch.h" +#endif + +#ifdef OPENTHERM_USE_OUTPUT +#include "esphome/components/opentherm/output/output.h" +#endif + +#ifdef OPENTHERM_USE_NUMBER +#include "esphome/components/opentherm/number/number.h" +#endif + #include #include #include @@ -31,15 +48,25 @@ class OpenthermHub : public Component { OPENTHERM_SENSOR_LIST(OPENTHERM_DECLARE_SENSOR, ) + OPENTHERM_BINARY_SENSOR_LIST(OPENTHERM_DECLARE_BINARY_SENSOR, ) + + OPENTHERM_SWITCH_LIST(OPENTHERM_DECLARE_SWITCH, ) + + OPENTHERM_NUMBER_LIST(OPENTHERM_DECLARE_NUMBER, ) + + OPENTHERM_OUTPUT_LIST(OPENTHERM_DECLARE_OUTPUT, ) + + OPENTHERM_INPUT_SENSOR_LIST(OPENTHERM_DECLARE_INPUT_SENSOR, ) + // The set of initial messages to send on starting communication with the boiler - std::unordered_set initial_messages_; + std::vector initial_messages_; // and the repeating messages which are sent repeatedly to update various sensors // and boiler parameters (like the setpoint). - std::unordered_set repeating_messages_; + std::vector repeating_messages_; // Indicates if we are still working on the initial requests or not bool sending_initial_ = true; // Index for the current request in one of the _requests sets. - std::unordered_set::const_iterator current_message_iterator_; + std::vector::const_iterator current_message_iterator_; uint32_t last_conversation_start_ = 0; uint32_t last_conversation_end_ = 0; @@ -51,6 +78,8 @@ class OpenthermHub : public Component { // Very likely to happen while using Dallas temperature sensors. bool sync_mode_ = false; + float opentherm_version_ = 0.0f; + // Create OpenTherm messages based on the message id OpenthermData build_request_(MessageId request_id) const; void handle_protocol_write_error_(); @@ -88,13 +117,23 @@ class OpenthermHub : public Component { OPENTHERM_SENSOR_LIST(OPENTHERM_SET_SENSOR, ) - // Add a request to the set of initial requests - void add_initial_message(MessageId message_id) { this->initial_messages_.insert(message_id); } + OPENTHERM_BINARY_SENSOR_LIST(OPENTHERM_SET_BINARY_SENSOR, ) + + OPENTHERM_SWITCH_LIST(OPENTHERM_SET_SWITCH, ) + + OPENTHERM_NUMBER_LIST(OPENTHERM_SET_NUMBER, ) + + OPENTHERM_OUTPUT_LIST(OPENTHERM_SET_OUTPUT, ) + + OPENTHERM_INPUT_SENSOR_LIST(OPENTHERM_SET_INPUT_SENSOR, ) + + // Add a request to the vector of initial requests + void add_initial_message(MessageId message_id) { this->initial_messages_.push_back(message_id); } // Add a request to the set of repeating requests. Note that a large number of repeating // requests will slow down communication with the boiler. Each request may take up to 1 second, // so with all sensors enabled, it may take about half a minute before a change in setpoint // will be processed. - void add_repeating_message(MessageId message_id) { this->repeating_messages_.insert(message_id); } + void add_repeating_message(MessageId message_id) { this->repeating_messages_.push_back(message_id); } // There are seven status variables, which can either be set as a simple variable, // or using a switch. ch_enable and dhw_enable default to true, the others to false. @@ -110,6 +149,7 @@ class OpenthermHub : public Component { void set_summer_mode_active(bool value) { this->summer_mode_active = value; } void set_dhw_block(bool value) { this->dhw_block = value; } void set_sync_mode(bool sync_mode) { this->sync_mode_ = sync_mode; } + void set_opentherm_version(float value) { this->opentherm_version_ = value; } float get_setup_priority() const override { return setup_priority::HARDWARE; } diff --git a/esphome/components/opentherm/input.h b/esphome/components/opentherm/input.h new file mode 100644 index 0000000000..3567138792 --- /dev/null +++ b/esphome/components/opentherm/input.h @@ -0,0 +1,18 @@ +#pragma once + +namespace esphome { +namespace opentherm { + +class OpenthermInput { + public: + bool auto_min_value, auto_max_value; + + virtual void set_min_value(float min_value) = 0; + virtual void set_max_value(float max_value) = 0; + + virtual void set_auto_min_value(bool auto_min_value) { this->auto_min_value = auto_min_value; } + virtual void set_auto_max_value(bool auto_max_value) { this->auto_max_value = auto_max_value; } +}; + +} // namespace opentherm +} // namespace esphome diff --git a/esphome/components/opentherm/input.py b/esphome/components/opentherm/input.py new file mode 100644 index 0000000000..7897747be1 --- /dev/null +++ b/esphome/components/opentherm/input.py @@ -0,0 +1,51 @@ +from typing import Any + +import esphome.codegen as cg +import esphome.config_validation as cv +from . import schema, generate + +CONF_min_value = "min_value" +CONF_max_value = "max_value" +CONF_auto_min_value = "auto_min_value" +CONF_auto_max_value = "auto_max_value" +CONF_step = "step" + +OpenthermInput = generate.opentherm_ns.class_("OpenthermInput") + + +def validate_min_value_less_than_max_value(conf): + if ( + CONF_min_value in conf + and CONF_max_value in conf + and conf[CONF_min_value] > conf[CONF_max_value] + ): + raise cv.Invalid(f"{CONF_min_value} must be less than {CONF_max_value}") + return conf + + +def input_schema(entity: schema.InputSchema) -> cv.Schema: + result = cv.Schema( + { + cv.Optional(CONF_min_value, entity.range[0]): cv.float_range( + entity.range[0], entity.range[1] + ), + cv.Optional(CONF_max_value, entity.range[1]): cv.float_range( + entity.range[0], entity.range[1] + ), + } + ) + result = result.add_extra(validate_min_value_less_than_max_value) + result = result.extend({cv.Optional(CONF_step, False): cv.float_}) + if entity.auto_min_value is not None: + result = result.extend({cv.Optional(CONF_auto_min_value, False): cv.boolean}) + if entity.auto_max_value is not None: + result = result.extend({cv.Optional(CONF_auto_max_value, False): cv.boolean}) + + return result + + +def generate_setters(entity: cg.MockObj, conf: dict[str, Any]) -> None: + generate.add_property_set(entity, CONF_min_value, conf) + generate.add_property_set(entity, CONF_max_value, conf) + generate.add_property_set(entity, CONF_auto_min_value, conf) + generate.add_property_set(entity, CONF_auto_max_value, conf) diff --git a/esphome/components/opentherm/number/__init__.py b/esphome/components/opentherm/number/__init__.py new file mode 100644 index 0000000000..bbf3e87586 --- /dev/null +++ b/esphome/components/opentherm/number/__init__.py @@ -0,0 +1,74 @@ +from typing import Any + +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.components import number +from esphome.const import ( + CONF_ID, + CONF_UNIT_OF_MEASUREMENT, + CONF_STEP, + CONF_INITIAL_VALUE, + CONF_RESTORE_VALUE, +) +from .. import const, schema, validate, input, generate + +DEPENDENCIES = [const.OPENTHERM] +COMPONENT_TYPE = const.NUMBER + +OpenthermNumber = generate.opentherm_ns.class_( + "OpenthermNumber", number.Number, cg.Component, input.OpenthermInput +) + + +async def new_openthermnumber(config: dict[str, Any]) -> cg.Pvariable: + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) + await number.register_number( + var, + config, + min_value=config[input.CONF_min_value], + max_value=config[input.CONF_max_value], + step=config[input.CONF_step], + ) + input.generate_setters(var, config) + + if CONF_INITIAL_VALUE in config: + cg.add(var.set_initial_value(config[CONF_INITIAL_VALUE])) + if CONF_RESTORE_VALUE in config: + cg.add(var.set_restore_value(config[CONF_RESTORE_VALUE])) + + return var + + +def get_entity_validation_schema(entity: schema.InputSchema) -> cv.Schema: + return ( + number.NUMBER_SCHEMA.extend( + { + cv.GenerateID(): cv.declare_id(OpenthermNumber), + cv.Optional( + CONF_UNIT_OF_MEASUREMENT, entity.unit_of_measurement + ): cv.string_strict, + cv.Optional(CONF_STEP, entity.step): cv.float_, + cv.Optional(CONF_INITIAL_VALUE): cv.float_, + cv.Optional(CONF_RESTORE_VALUE): cv.boolean, + } + ) + .extend(input.input_schema(entity)) + .extend(cv.COMPONENT_SCHEMA) + ) + + +CONFIG_SCHEMA = validate.create_component_schema( + schema.INPUTS, get_entity_validation_schema +) + + +async def to_code(config: dict[str, Any]) -> None: + keys = await generate.component_to_code( + COMPONENT_TYPE, + schema.INPUTS, + OpenthermNumber, + generate.create_only_conf(new_openthermnumber), + config, + ) + generate.define_readers(COMPONENT_TYPE, keys) diff --git a/esphome/components/opentherm/number/number.cpp b/esphome/components/opentherm/number/number.cpp new file mode 100644 index 0000000000..d02b99ee9c --- /dev/null +++ b/esphome/components/opentherm/number/number.cpp @@ -0,0 +1,40 @@ +#include "number.h" + +namespace esphome { +namespace opentherm { + +static const char *const TAG = "opentherm.number"; + +void OpenthermNumber::control(float value) { + this->publish_state(value); + + if (this->restore_value_) + this->pref_.save(&value); +} + +void OpenthermNumber::setup() { + float value; + if (!this->restore_value_) { + value = this->initial_value_; + } else { + this->pref_ = global_preferences->make_preference(this->get_object_id_hash()); + if (!this->pref_.load(&value)) { + if (!std::isnan(this->initial_value_)) { + value = this->initial_value_; + } else { + value = this->traits.get_min_value(); + } + } + } + this->publish_state(value); +} + +void OpenthermNumber::dump_config() { + LOG_NUMBER("", "OpenTherm Number", this); + ESP_LOGCONFIG(TAG, " Restore value: %d", this->restore_value_); + ESP_LOGCONFIG(TAG, " Initial value: %.2f", this->initial_value_); + ESP_LOGCONFIG(TAG, " Current value: %.2f", this->state); +} + +} // namespace opentherm +} // namespace esphome diff --git a/esphome/components/opentherm/number/number.h b/esphome/components/opentherm/number/number.h new file mode 100644 index 0000000000..6f86072754 --- /dev/null +++ b/esphome/components/opentherm/number/number.h @@ -0,0 +1,31 @@ +#pragma once + +#include "esphome/components/number/number.h" +#include "esphome/core/preferences.h" +#include "esphome/core/log.h" +#include "esphome/components/opentherm/input.h" + +namespace esphome { +namespace opentherm { + +// Just a simple number, which stores the number +class OpenthermNumber : public number::Number, public Component, public OpenthermInput { + protected: + void control(float value) override; + void setup() override; + void dump_config() override; + + float initial_value_{NAN}; + bool restore_value_{false}; + + ESPPreferenceObject pref_; + + public: + void set_min_value(float min_value) override { this->traits.set_min_value(min_value); } + void set_max_value(float max_value) override { this->traits.set_max_value(max_value); } + void set_initial_value(float initial_value) { initial_value_ = initial_value; } + void set_restore_value(bool restore_value) { this->restore_value_ = restore_value; } +}; + +} // namespace opentherm +} // namespace esphome diff --git a/esphome/components/opentherm/opentherm.h b/esphome/components/opentherm/opentherm.h index 23f4b39a1a..85f4611125 100644 --- a/esphome/components/opentherm/opentherm.h +++ b/esphome/components/opentherm/opentherm.h @@ -99,6 +99,8 @@ enum MessageId { EXHAUST_TEMP = 33, FAN_SPEED = 35, FLAME_CURRENT = 36, + ROOM_TEMP_CH2 = 37, + REL_HUMIDITY = 38, DHW_BOUNDS = 48, CH_BOUNDS = 49, OTC_CURVE_BOUNDS = 50, @@ -110,15 +112,46 @@ enum MessageId { HVAC_STATUS = 70, REL_VENT_SETPOINT = 71, DEVICE_VENT = 74, + HVAC_VER_ID = 75, REL_VENTILATION = 77, REL_HUMID_EXHAUST = 78, + EXHAUST_CO2 = 79, SUPPLY_INLET_TEMP = 80, SUPPLY_OUTLET_TEMP = 81, EXHAUST_INLET_TEMP = 82, EXHAUST_OUTLET_TEMP = 83, + EXHAUST_FAN_SPEED = 84, + SUPPLY_FAN_SPEED = 85, + REMOTE_VENTILATION_PARAM = 86, NOM_REL_VENTILATION = 87, + HVAC_NUM_TSP = 88, + HVAC_IDX_TSP = 89, + HVAC_FHB_SIZE = 90, + HVAC_FHB_IDX = 91, + RF_SIGNAL = 98, + DHW_MODE = 99, OVERRIDE_FUNC = 100, + + // Solar Specific Message IDs + SOLAR_MODE_FLAGS = 101, // hb0-2 Controller storage mode + // lb0 Device fault + // lb1-3 Device mode status + // lb4-5 Device status + SOLAR_ASF = 102, + SOLAR_VERSION_ID = 103, + SOLAR_PRODUCT_ID = 104, + SOLAR_NUM_TSP = 105, + SOLAR_IDX_TSP = 106, + SOLAR_FHB_SIZE = 107, + SOLAR_FHB_IDX = 108, + SOLAR_STARTS = 109, + SOLAR_HOURS = 110, + SOLAR_ENERGY = 111, + SOLAR_TOTAL_ENERGY = 112, + + FAILED_BURNER_STARTS = 113, + BURNER_FLAME_LOW = 114, OEM_DIAGNOSTIC = 115, BURNER_STARTS = 116, CH_PUMP_STARTS = 117, diff --git a/esphome/components/opentherm/opentherm_macros.h b/esphome/components/opentherm/opentherm_macros.h index 0389e975ff..8aaec0b48a 100644 --- a/esphome/components/opentherm/opentherm_macros.h +++ b/esphome/components/opentherm/opentherm_macros.h @@ -13,14 +13,49 @@ namespace opentherm { #ifndef OPENTHERM_SENSOR_LIST #define OPENTHERM_SENSOR_LIST(F, sep) #endif +#ifndef OPENTHERM_BINARY_SENSOR_LIST +#define OPENTHERM_BINARY_SENSOR_LIST(F, sep) +#endif +#ifndef OPENTHERM_SWITCH_LIST +#define OPENTHERM_SWITCH_LIST(F, sep) +#endif +#ifndef OPENTHERM_NUMBER_LIST +#define OPENTHERM_NUMBER_LIST(F, sep) +#endif +#ifndef OPENTHERM_OUTPUT_LIST +#define OPENTHERM_OUTPUT_LIST(F, sep) +#endif +#ifndef OPENTHERM_INPUT_SENSOR_LIST +#define OPENTHERM_INPUT_SENSOR_LIST(F, sep) +#endif // Use macros to create fields for every entity specified in the ESPHome configuration #define OPENTHERM_DECLARE_SENSOR(entity) sensor::Sensor *entity; +#define OPENTHERM_DECLARE_BINARY_SENSOR(entity) binary_sensor::BinarySensor *entity; +#define OPENTHERM_DECLARE_SWITCH(entity) OpenthermSwitch *entity; +#define OPENTHERM_DECLARE_NUMBER(entity) OpenthermNumber *entity; +#define OPENTHERM_DECLARE_OUTPUT(entity) OpenthermOutput *entity; +#define OPENTHERM_DECLARE_INPUT_SENSOR(entity) sensor::Sensor *entity; // Setter macros #define OPENTHERM_SET_SENSOR(entity) \ void set_##entity(sensor::Sensor *sensor) { this->entity = sensor; } +#define OPENTHERM_SET_BINARY_SENSOR(entity) \ + void set_##entity(binary_sensor::BinarySensor *binary_sensor) { this->entity = binary_sensor; } + +#define OPENTHERM_SET_SWITCH(entity) \ + void set_##entity(OpenthermSwitch *sw) { this->entity = sw; } + +#define OPENTHERM_SET_NUMBER(entity) \ + void set_##entity(OpenthermNumber *number) { this->entity = number; } + +#define OPENTHERM_SET_OUTPUT(entity) \ + void set_##entity(OpenthermOutput *output) { this->entity = output; } + +#define OPENTHERM_SET_INPUT_SENSOR(entity) \ + void set_##entity(sensor::Sensor *sensor) { this->entity = sensor; } + // ===== hub.cpp macros ===== // *_MESSAGE_HANDLERS are generated in defines.h and look like this: @@ -35,6 +70,31 @@ namespace opentherm { #ifndef OPENTHERM_SENSOR_MESSAGE_HANDLERS #define OPENTHERM_SENSOR_MESSAGE_HANDLERS(MESSAGE, ENTITY, entity_sep, postscript, msg_sep) #endif +#ifndef OPENTHERM_BINARY_SENSOR_MESSAGE_HANDLERS +#define OPENTHERM_BINARY_SENSOR_MESSAGE_HANDLERS(MESSAGE, ENTITY, entity_sep, postscript, msg_sep) +#endif +#ifndef OPENTHERM_SWITCH_MESSAGE_HANDLERS +#define OPENTHERM_SWITCH_MESSAGE_HANDLERS(MESSAGE, ENTITY, entity_sep, postscript, msg_sep) +#endif +#ifndef OPENTHERM_NUMBER_MESSAGE_HANDLERS +#define OPENTHERM_NUMBER_MESSAGE_HANDLERS(MESSAGE, ENTITY, entity_sep, postscript, msg_sep) +#endif +#ifndef OPENTHERM_OUTPUT_MESSAGE_HANDLERS +#define OPENTHERM_OUTPUT_MESSAGE_HANDLERS(MESSAGE, ENTITY, entity_sep, postscript, msg_sep) +#endif +#ifndef OPENTHERM_INPUT_SENSOR_MESSAGE_HANDLERS +#define OPENTHERM_INPUT_SENSOR_MESSAGE_HANDLERS(MESSAGE, ENTITY, entity_sep, postscript, msg_sep) +#endif + +// Write data request builders +#define OPENTHERM_MESSAGE_WRITE_MESSAGE(msg) \ + case MessageId::msg: { \ + data.type = MessageType::WRITE_DATA; \ + data.id = request_id; +#define OPENTHERM_MESSAGE_WRITE_ENTITY(key, msg_data) message_data::write_##msg_data(this->key->state, data); +#define OPENTHERM_MESSAGE_WRITE_POSTSCRIPT \ + return data; \ + } // Read data request builder #define OPENTHERM_MESSAGE_READ_MESSAGE(msg) \ diff --git a/esphome/components/opentherm/output/__init__.py b/esphome/components/opentherm/output/__init__.py new file mode 100644 index 0000000000..3a53c9d4f4 --- /dev/null +++ b/esphome/components/opentherm/output/__init__.py @@ -0,0 +1,47 @@ +from typing import Any + +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.components import output +from esphome.const import CONF_ID +from .. import const, schema, validate, input, generate + +DEPENDENCIES = [const.OPENTHERM] +COMPONENT_TYPE = const.OUTPUT + +OpenthermOutput = generate.opentherm_ns.class_( + "OpenthermOutput", output.FloatOutput, cg.Component, input.OpenthermInput +) + + +async def new_openthermoutput( + config: dict[str, Any], key: str, _hub: cg.MockObj +) -> cg.Pvariable: + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) + await output.register_output(var, config) + cg.add(getattr(var, "set_id")(cg.RawExpression(f'"{key}_{config[CONF_ID]}"'))) + input.generate_setters(var, config) + return var + + +def get_entity_validation_schema(entity: schema.InputSchema) -> cv.Schema: + return ( + output.FLOAT_OUTPUT_SCHEMA.extend( + {cv.GenerateID(): cv.declare_id(OpenthermOutput)} + ) + .extend(input.input_schema(entity)) + .extend(cv.COMPONENT_SCHEMA) + ) + + +CONFIG_SCHEMA = validate.create_component_schema( + schema.INPUTS, get_entity_validation_schema +) + + +async def to_code(config: dict[str, Any]) -> None: + keys = await generate.component_to_code( + COMPONENT_TYPE, schema.INPUTS, OpenthermOutput, new_openthermoutput, config + ) + generate.define_readers(COMPONENT_TYPE, keys) diff --git a/esphome/components/opentherm/output/output.cpp b/esphome/components/opentherm/output/output.cpp new file mode 100644 index 0000000000..f820dc76f1 --- /dev/null +++ b/esphome/components/opentherm/output/output.cpp @@ -0,0 +1,18 @@ +#include "esphome/core/helpers.h" // for clamp() and lerp() +#include "output.h" + +namespace esphome { +namespace opentherm { + +static const char *const TAG = "opentherm.output"; + +void opentherm::OpenthermOutput::write_state(float state) { + ESP_LOGD(TAG, "Received state: %.2f. Min value: %.2f, max value: %.2f", state, min_value_, max_value_); + this->state = state < 0.003 && this->zero_means_zero_ + ? 0.0 + : clamp(lerp(state, min_value_, max_value_), min_value_, max_value_); + this->has_state_ = true; + ESP_LOGD(TAG, "Output %s set to %.2f", this->id_, this->state); +} +} // namespace opentherm +} // namespace esphome diff --git a/esphome/components/opentherm/output/output.h b/esphome/components/opentherm/output/output.h new file mode 100644 index 0000000000..8d6a0ee4ba --- /dev/null +++ b/esphome/components/opentherm/output/output.h @@ -0,0 +1,33 @@ +#pragma once + +#include "esphome/components/output/float_output.h" +#include "esphome/components/opentherm/input.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace opentherm { + +class OpenthermOutput : public output::FloatOutput, public Component, public OpenthermInput { + protected: + bool has_state_ = false; + const char *id_ = nullptr; + + float min_value_, max_value_; + + public: + float state; + + void set_id(const char *id) { this->id_ = id; } + + void write_state(float state) override; + + bool has_state() { return this->has_state_; }; + + void set_min_value(float min_value) override { this->min_value_ = min_value; } + void set_max_value(float max_value) override { this->max_value_ = max_value; } + float get_min_value() { return this->min_value_; } + float get_max_value() { return this->max_value_; } +}; + +} // namespace opentherm +} // namespace esphome diff --git a/esphome/components/opentherm/schema.py b/esphome/components/opentherm/schema.py index 6ed0029437..fe0f2a77a3 100644 --- a/esphome/components/opentherm/schema.py +++ b/esphome/components/opentherm/schema.py @@ -11,9 +11,12 @@ from esphome.const import ( UNIT_MICROAMP, UNIT_PERCENT, UNIT_REVOLUTIONS_PER_MINUTE, + DEVICE_CLASS_COLD, DEVICE_CLASS_CURRENT, DEVICE_CLASS_EMPTY, + DEVICE_CLASS_HEAT, DEVICE_CLASS_PRESSURE, + DEVICE_CLASS_PROBLEM, DEVICE_CLASS_TEMPERATURE, STATE_CLASS_MEASUREMENT, STATE_CLASS_NONE, @@ -188,11 +191,23 @@ SENSORS: dict[str, SensorSchema] = { description="Boiler fan speed", unit_of_measurement=UNIT_REVOLUTIONS_PER_MINUTE, accuracy_decimals=0, + icon="mdi:fan", device_class=DEVICE_CLASS_EMPTY, state_class=STATE_CLASS_MEASUREMENT, message="FAN_SPEED", keep_updated=True, - message_data="u16", + message_data="u8_lb_60", + ), + "fan_speed_setpoint": SensorSchema( + description="Boiler fan speed setpoint", + unit_of_measurement=UNIT_REVOLUTIONS_PER_MINUTE, + accuracy_decimals=0, + icon="mdi:fan", + device_class=DEVICE_CLASS_EMPTY, + state_class=STATE_CLASS_MEASUREMENT, + message="FAN_SPEED", + keep_updated=True, + message_data="u8_hb_60", ), "flame_current": SensorSchema( description="Boiler flame current", @@ -436,3 +451,364 @@ SENSORS: dict[str, SensorSchema] = { message_data="u8_lb", ), } + + +@dataclass +class BinarySensorSchema(EntitySchema): + icon: Optional[str] = None + device_class: Optional[str] = None + + +BINARY_SENSORS: dict[str, BinarySensorSchema] = { + "fault_indication": BinarySensorSchema( + description="Status: Fault indication", + device_class=DEVICE_CLASS_PROBLEM, + message="STATUS", + keep_updated=True, + message_data="flag8_lb_0", + ), + "ch_active": BinarySensorSchema( + description="Status: Central Heating active", + device_class=DEVICE_CLASS_HEAT, + icon="mdi:radiator", + message="STATUS", + keep_updated=True, + message_data="flag8_lb_1", + ), + "dhw_active": BinarySensorSchema( + description="Status: Domestic Hot Water active", + device_class=DEVICE_CLASS_HEAT, + icon="mdi:faucet", + message="STATUS", + keep_updated=True, + message_data="flag8_lb_2", + ), + "flame_on": BinarySensorSchema( + description="Status: Flame on", + device_class=DEVICE_CLASS_HEAT, + icon="mdi:fire", + message="STATUS", + keep_updated=True, + message_data="flag8_lb_3", + ), + "cooling_active": BinarySensorSchema( + description="Status: Cooling active", + device_class=DEVICE_CLASS_COLD, + message="STATUS", + keep_updated=True, + message_data="flag8_lb_4", + ), + "ch2_active": BinarySensorSchema( + description="Status: Central Heating 2 active", + device_class=DEVICE_CLASS_HEAT, + icon="mdi:radiator", + message="STATUS", + keep_updated=True, + message_data="flag8_lb_5", + ), + "diagnostic_indication": BinarySensorSchema( + description="Status: Diagnostic event", + device_class=DEVICE_CLASS_PROBLEM, + message="STATUS", + keep_updated=True, + message_data="flag8_lb_6", + ), + "electricity_production": BinarySensorSchema( + description="Status: Electricity production", + device_class=DEVICE_CLASS_PROBLEM, + message="STATUS", + keep_updated=True, + message_data="flag8_lb_7", + ), + "dhw_present": BinarySensorSchema( + description="Configuration: DHW present", + message="DEVICE_CONFIG", + keep_updated=False, + message_data="flag8_hb_0", + ), + "control_type_on_off": BinarySensorSchema( + description="Configuration: Control type is on/off", + message="DEVICE_CONFIG", + keep_updated=False, + message_data="flag8_hb_1", + ), + "cooling_supported": BinarySensorSchema( + description="Configuration: Cooling supported", + message="DEVICE_CONFIG", + keep_updated=False, + message_data="flag8_hb_2", + ), + "dhw_storage_tank": BinarySensorSchema( + description="Configuration: DHW storage tank", + message="DEVICE_CONFIG", + keep_updated=False, + message_data="flag8_hb_3", + ), + "controller_pump_control_allowed": BinarySensorSchema( + description="Configuration: Controller pump control allowed", + message="DEVICE_CONFIG", + keep_updated=False, + message_data="flag8_hb_4", + ), + "ch2_present": BinarySensorSchema( + description="Configuration: CH2 present", + message="DEVICE_CONFIG", + keep_updated=False, + message_data="flag8_hb_5", + ), + "water_filling": BinarySensorSchema( + description="Configuration: Remote water filling", + message="DEVICE_CONFIG", + keep_updated=False, + message_data="flag8_hb_6", + ), + "heat_mode": BinarySensorSchema( + description="Configuration: Heating or cooling", + message="DEVICE_CONFIG", + keep_updated=False, + message_data="flag8_hb_7", + ), + "dhw_setpoint_transfer_enabled": BinarySensorSchema( + description="Remote boiler parameters: DHW setpoint transfer enabled", + message="REMOTE", + keep_updated=False, + message_data="flag8_hb_0", + ), + "max_ch_setpoint_transfer_enabled": BinarySensorSchema( + description="Remote boiler parameters: CH maximum setpoint transfer enabled", + message="REMOTE", + keep_updated=False, + message_data="flag8_hb_1", + ), + "dhw_setpoint_rw": BinarySensorSchema( + description="Remote boiler parameters: DHW setpoint read/write", + message="REMOTE", + keep_updated=False, + message_data="flag8_lb_0", + ), + "max_ch_setpoint_rw": BinarySensorSchema( + description="Remote boiler parameters: CH maximum setpoint read/write", + message="REMOTE", + keep_updated=False, + message_data="flag8_lb_1", + ), + "service_request": BinarySensorSchema( + description="Service required", + device_class=DEVICE_CLASS_PROBLEM, + message="FAULT_FLAGS", + keep_updated=True, + message_data="flag8_hb_0", + ), + "lockout_reset": BinarySensorSchema( + description="Lockout Reset", + device_class=DEVICE_CLASS_PROBLEM, + message="FAULT_FLAGS", + keep_updated=True, + message_data="flag8_hb_1", + ), + "low_water_pressure": BinarySensorSchema( + description="Low water pressure fault", + device_class=DEVICE_CLASS_PROBLEM, + message="FAULT_FLAGS", + keep_updated=True, + message_data="flag8_hb_2", + ), + "flame_fault": BinarySensorSchema( + description="Flame fault", + device_class=DEVICE_CLASS_PROBLEM, + message="FAULT_FLAGS", + keep_updated=True, + message_data="flag8_hb_3", + ), + "air_pressure_fault": BinarySensorSchema( + description="Air pressure fault", + device_class=DEVICE_CLASS_PROBLEM, + message="FAULT_FLAGS", + keep_updated=True, + message_data="flag8_hb_4", + ), + "water_over_temp": BinarySensorSchema( + description="Water overtemperature", + device_class=DEVICE_CLASS_PROBLEM, + message="FAULT_FLAGS", + keep_updated=True, + message_data="flag8_hb_5", + ), +} + + +@dataclass +class SwitchSchema(EntitySchema): + default_mode: Optional[str] = None + + +SWITCHES: dict[str, SwitchSchema] = { + "ch_enable": SwitchSchema( + description="Central Heating enabled", + message="STATUS", + keep_updated=True, + message_data="flag8_hb_0", + default_mode="restore_default_off", + ), + "dhw_enable": SwitchSchema( + description="Domestic Hot Water enabled", + message="STATUS", + keep_updated=True, + message_data="flag8_hb_1", + default_mode="restore_default_off", + ), + "cooling_enable": SwitchSchema( + description="Cooling enabled", + message="STATUS", + keep_updated=True, + message_data="flag8_hb_2", + default_mode="restore_default_off", + ), + "otc_active": SwitchSchema( + description="Outside temperature compensation active", + message="STATUS", + keep_updated=True, + message_data="flag8_hb_3", + default_mode="restore_default_off", + ), + "ch2_active": SwitchSchema( + description="Central Heating 2 active", + message="STATUS", + keep_updated=True, + message_data="flag8_hb_4", + default_mode="restore_default_off", + ), + "summer_mode_active": SwitchSchema( + description="Summer mode active", + message="STATUS", + keep_updated=True, + message_data="flag8_hb_5", + default_mode="restore_default_off", + ), + "dhw_block": SwitchSchema( + description="DHW blocked", + message="STATUS", + keep_updated=True, + message_data="flag8_hb_6", + default_mode="restore_default_off", + ), +} + + +@dataclass +class AutoConfigure: + message: str + message_data: str + + +@dataclass +class InputSchema(EntitySchema): + unit_of_measurement: str + step: float + range: tuple[int, int] + icon: Optional[str] = None + auto_max_value: Optional[AutoConfigure] = None + auto_min_value: Optional[AutoConfigure] = None + + +INPUTS: dict[str, InputSchema] = { + "t_set": InputSchema( + description="Control setpoint: temperature setpoint for the boiler's supply water", + unit_of_measurement=UNIT_CELSIUS, + step=0.1, + message="CH_SETPOINT", + keep_updated=True, + message_data="f88", + range=(0, 100), + auto_max_value=AutoConfigure(message="MAX_CH_SETPOINT", message_data="f88"), + ), + "t_set_ch2": InputSchema( + description="Control setpoint 2: temperature setpoint for the boiler's supply water on the second heating circuit", + unit_of_measurement=UNIT_CELSIUS, + step=0.1, + message="CH2_SETPOINT", + keep_updated=True, + message_data="f88", + range=(0, 100), + auto_max_value=AutoConfigure(message="MAX_CH_SETPOINT", message_data="f88"), + ), + "cooling_control": InputSchema( + description="Cooling control signal", + unit_of_measurement=UNIT_PERCENT, + step=1.0, + message="COOLING_CONTROL", + keep_updated=True, + message_data="f88", + range=(0, 100), + ), + "t_dhw_set": InputSchema( + description="Domestic hot water temperature setpoint", + unit_of_measurement=UNIT_CELSIUS, + step=0.1, + message="DHW_SETPOINT", + keep_updated=True, + message_data="f88", + range=(0, 127), + auto_min_value=AutoConfigure(message="DHW_BOUNDS", message_data="s8_lb"), + auto_max_value=AutoConfigure(message="DHW_BOUNDS", message_data="s8_hb"), + ), + "max_t_set": InputSchema( + description="Maximum allowable CH water setpoint", + unit_of_measurement=UNIT_CELSIUS, + step=0.1, + message="MAX_CH_SETPOINT", + keep_updated=True, + message_data="f88", + range=(0, 127), + auto_min_value=AutoConfigure(message="CH_BOUNDS", message_data="s8_lb"), + auto_max_value=AutoConfigure(message="CH_BOUNDS", message_data="s8_hb"), + ), + "t_room_set": InputSchema( + description="Current room temperature setpoint (informational)", + unit_of_measurement=UNIT_CELSIUS, + step=0.1, + message="ROOM_SETPOINT", + keep_updated=True, + message_data="f88", + range=(-40, 127), + ), + "t_room_set_ch2": InputSchema( + description="Current room temperature setpoint on CH2 (informational)", + unit_of_measurement=UNIT_CELSIUS, + step=0.1, + message="ROOM_SETPOINT_CH2", + keep_updated=True, + message_data="f88", + range=(-40, 127), + ), + "t_room": InputSchema( + description="Current sensed room temperature (informational)", + unit_of_measurement=UNIT_CELSIUS, + step=0.1, + message="ROOM_TEMP", + keep_updated=True, + message_data="f88", + range=(-40, 127), + ), + "max_rel_mod_level": InputSchema( + description="Maximum relative modulation level", + unit_of_measurement=UNIT_PERCENT, + step=1, + icon="mdi:percent", + message="MAX_MODULATION_LEVEL", + keep_updated=True, + message_data="f88", + range=(0, 100), + ), + "otc_hc_ratio": InputSchema( + description="OTC heat curve ratio", + unit_of_measurement=UNIT_CELSIUS, + step=0.1, + message="OTC_CURVE_RATIO", + keep_updated=True, + message_data="f88", + range=(0, 127), + auto_min_value=AutoConfigure(message="OTC_CURVE_BOUNDS", message_data="u8_lb"), + auto_max_value=AutoConfigure(message="OTC_CURVE_BOUNDS", message_data="u8_hb"), + ), +} diff --git a/esphome/components/opentherm/sensor/__init__.py b/esphome/components/opentherm/sensor/__init__.py index 20224e0eda..546a79054b 100644 --- a/esphome/components/opentherm/sensor/__init__.py +++ b/esphome/components/opentherm/sensor/__init__.py @@ -7,6 +7,18 @@ from .. import const, schema, validate, generate DEPENDENCIES = [const.OPENTHERM] COMPONENT_TYPE = const.SENSOR +MSG_DATA_TYPES = { + "u8_lb", + "u8_hb", + "s8_lb", + "s8_hb", + "u8_lb_60", + "u8_hb_60", + "u16", + "s16", + "f88", +} + def get_entity_validation_schema(entity: schema.SensorSchema) -> cv.Schema: return sensor.sensor_schema( @@ -17,6 +29,10 @@ def get_entity_validation_schema(entity: schema.SensorSchema) -> cv.Schema: or sensor._UNDEF, # pylint: disable=protected-access icon=entity.icon or sensor._UNDEF, # pylint: disable=protected-access state_class=entity.state_class, + ).extend( + { + cv.Optional(const.CONF_DATA_TYPE): cv.one_of(*MSG_DATA_TYPES), + } ) diff --git a/esphome/components/opentherm/switch/__init__.py b/esphome/components/opentherm/switch/__init__.py new file mode 100644 index 0000000000..94ec25e36c --- /dev/null +++ b/esphome/components/opentherm/switch/__init__.py @@ -0,0 +1,43 @@ +from typing import Any + +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.components import switch +from esphome.const import CONF_ID +from .. import const, schema, validate, generate + +DEPENDENCIES = [const.OPENTHERM] +COMPONENT_TYPE = const.SWITCH + +OpenthermSwitch = generate.opentherm_ns.class_( + "OpenthermSwitch", switch.Switch, cg.Component +) + + +async def new_openthermswitch(config: dict[str, Any]) -> cg.Pvariable: + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) + await switch.register_switch(var, config) + return var + + +def get_entity_validation_schema(entity: schema.SwitchSchema) -> cv.Schema: + return switch.SWITCH_SCHEMA.extend( + {cv.GenerateID(): cv.declare_id(OpenthermSwitch)} + ).extend(cv.COMPONENT_SCHEMA) + + +CONFIG_SCHEMA = validate.create_component_schema( + schema.SWITCHES, get_entity_validation_schema +) + + +async def to_code(config: dict[str, Any]) -> None: + keys = await generate.component_to_code( + COMPONENT_TYPE, + schema.SWITCHES, + OpenthermSwitch, + generate.create_only_conf(new_openthermswitch), + config, + ) + generate.define_readers(COMPONENT_TYPE, keys) diff --git a/esphome/components/opentherm/switch/switch.cpp b/esphome/components/opentherm/switch/switch.cpp new file mode 100644 index 0000000000..228d9ac8f3 --- /dev/null +++ b/esphome/components/opentherm/switch/switch.cpp @@ -0,0 +1,28 @@ +#include "switch.h" + +namespace esphome { +namespace opentherm { + +static const char *const TAG = "opentherm.switch"; + +void OpenthermSwitch::write_state(bool state) { this->publish_state(state); } + +void OpenthermSwitch::setup() { + auto restored = this->get_initial_state_with_restore_mode(); + bool state = false; + if (!restored.has_value()) { + ESP_LOGD(TAG, "Couldn't restore state for OpenTherm switch '%s'", this->get_name().c_str()); + } else { + ESP_LOGD(TAG, "Restored state for OpenTherm switch '%s': %d", this->get_name().c_str(), restored.value()); + state = restored.value(); + } + this->write_state(state); +} + +void OpenthermSwitch::dump_config() { + LOG_SWITCH("", "OpenTherm Switch", this); + ESP_LOGCONFIG(TAG, " Current state: %d", this->state); +} + +} // namespace opentherm +} // namespace esphome diff --git a/esphome/components/opentherm/switch/switch.h b/esphome/components/opentherm/switch/switch.h new file mode 100644 index 0000000000..0c20a0d9ed --- /dev/null +++ b/esphome/components/opentherm/switch/switch.h @@ -0,0 +1,20 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/switch/switch.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace opentherm { + +class OpenthermSwitch : public switch_::Switch, public Component { + protected: + void write_state(bool state) override; + + public: + void setup() override; + void dump_config() override; +}; + +} // namespace opentherm +} // namespace esphome diff --git a/tests/components/opentherm/common.yaml b/tests/components/opentherm/common.yaml index 27cbae280a..744580f18b 100644 --- a/tests/components/opentherm/common.yaml +++ b/tests/components/opentherm/common.yaml @@ -12,10 +12,41 @@ opentherm: cooling_enable: false otc_active: false ch2_active: true + t_room: boiler_sensor summer_mode_active: true dhw_block: true sync_mode: true +output: + - platform: opentherm + t_set: + id: t_set + min_value: 20 + auto_max_value: true + zero_means_zero: true + t_set_ch2: + id: t_set_ch2 + min_value: 20 + max_value: 40 + zero_means_zero: true + +number: + - platform: opentherm + cooling_control: + name: "Boiler Cooling control signal" + t_dhw_set: + name: "Boiler DHW Setpoint" + max_t_set: + name: "Boiler Max Setpoint" + t_room_set: + name: "Boiler Room Setpoint" + t_room_set_ch2: + name: "Boiler Room Setpoint CH2" + max_rel_mod_level: + name: "Maximum relative modulation level" + otc_hc_ratio: + name: "OTC heat curve ratio" + sensor: - platform: opentherm rel_mod_level: @@ -25,6 +56,7 @@ sensor: dhw_flow_rate: name: "Boiler Water flow rate in DHW circuit" t_boiler: + id: "boiler_sensor" name: "Boiler water temperature" t_dhw: name: "Boiler DHW temperature" @@ -74,3 +106,55 @@ sensor: name: "OTC heat curve ratio upper bound" otc_hc_ratio_lb: name: "OTC heat curve ratio lower bound" + +binary_sensor: + - platform: opentherm + fault_indication: + name: "Boiler Fault indication" + ch_active: + name: "Boiler Central Heating active" + dhw_active: + name: "Boiler Domestic Hot Water active" + flame_on: + name: "Boiler Flame on" + cooling_active: + name: "Boiler Cooling active" + ch2_active: + name: "Boiler Central Heating 2 active" + diagnostic_indication: + name: "Boiler Diagnostic event" + dhw_present: + name: "Boiler DHW present" + control_type_on_off: + name: "Boiler Control type is on/off" + cooling_supported: + name: "Boiler Cooling supported" + dhw_storage_tank: + name: "Boiler DHW storage tank" + controller_pump_control_allowed: + name: "Boiler Controller pump control allowed" + ch2_present: + name: "Boiler CH2 present" + dhw_setpoint_transfer_enabled: + name: "Boiler DHW setpoint transfer enabled" + max_ch_setpoint_transfer_enabled: + name: "Boiler CH maximum setpoint transfer enabled" + dhw_setpoint_rw: + name: "Boiler DHW setpoint read/write" + max_ch_setpoint_rw: + name: "Boiler CH maximum setpoint read/write" + +switch: + - platform: opentherm + ch_enable: + name: "Boiler Central Heating enabled" + restore_mode: RESTORE_DEFAULT_ON + dhw_enable: + name: "Boiler Domestic Hot Water enabled" + cooling_enable: + name: "Boiler Cooling enabled" + restore_mode: ALWAYS_OFF + otc_active: + name: "Boiler Outside temperature compensation active" + ch2_active: + name: "Boiler Central Heating 2 active" From 928b39f4950536ff2d6501da8c35c139ea650b8b Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 12 Nov 2024 13:20:12 -0500 Subject: [PATCH 002/107] [i2s_audio] I2S speaker improvements (#7749) --- .../components/i2s_audio/speaker/__init__.py | 13 ++- .../i2s_audio/speaker/i2s_audio_speaker.cpp | 106 +++++++++--------- .../i2s_audio/speaker/i2s_audio_speaker.h | 12 +- 3 files changed, 72 insertions(+), 59 deletions(-) diff --git a/esphome/components/i2s_audio/speaker/__init__.py b/esphome/components/i2s_audio/speaker/__init__.py index dd43d6cb39..0355c16321 100644 --- a/esphome/components/i2s_audio/speaker/__init__.py +++ b/esphome/components/i2s_audio/speaker/__init__.py @@ -24,9 +24,10 @@ I2SAudioSpeaker = i2s_audio_ns.class_( "I2SAudioSpeaker", cg.Component, speaker.Speaker, I2SAudioOut ) - +CONF_BUFFER_DURATION = "buffer_duration" CONF_DAC_TYPE = "dac_type" CONF_I2S_COMM_FMT = "i2s_comm_fmt" +CONF_NEVER = "never" i2s_dac_mode_t = cg.global_ns.enum("i2s_dac_mode_t") INTERNAL_DAC_OPTIONS = { @@ -73,8 +74,12 @@ BASE_SCHEMA = ( .extend( { cv.Optional( - CONF_TIMEOUT, default="500ms" + CONF_BUFFER_DURATION, default="500ms" ): cv.positive_time_period_milliseconds, + cv.Optional(CONF_TIMEOUT, default="500ms"): cv.Any( + cv.positive_time_period_milliseconds, + cv.one_of(CONF_NEVER, lower=True), + ), } ) .extend(cv.COMPONENT_SCHEMA) @@ -116,4 +121,6 @@ async def to_code(config): else: cg.add(var.set_dout_pin(config[CONF_I2S_DOUT_PIN])) cg.add(var.set_i2s_comm_fmt(config[CONF_I2S_COMM_FMT])) - cg.add(var.set_timeout(config[CONF_TIMEOUT])) + if config[CONF_TIMEOUT] != CONF_NEVER: + cg.add(var.set_timeout(config[CONF_TIMEOUT])) + cg.add(var.set_buffer_duration(config[CONF_BUFFER_DURATION])) diff --git a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp index cf6c3bbbba..c3f4566411 100644 --- a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp +++ b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp @@ -13,21 +13,22 @@ namespace esphome { namespace i2s_audio { -static const size_t DMA_BUFFER_SIZE = 512; +static const uint8_t DMA_BUFFER_DURATION_MS = 15; static const size_t DMA_BUFFERS_COUNT = 4; -static const size_t FRAMES_IN_ALL_DMA_BUFFERS = DMA_BUFFER_SIZE * DMA_BUFFERS_COUNT; -static const size_t RING_BUFFER_SAMPLES = 8192; -static const size_t TASK_DELAY_MS = 10; + +static const size_t TASK_DELAY_MS = DMA_BUFFER_DURATION_MS * DMA_BUFFERS_COUNT / 2; + static const size_t TASK_STACK_SIZE = 4096; static const ssize_t TASK_PRIORITY = 23; +static const size_t I2S_EVENT_QUEUE_COUNT = DMA_BUFFERS_COUNT + 1; + static const char *const TAG = "i2s_audio.speaker"; enum SpeakerEventGroupBits : uint32_t { - COMMAND_START = (1 << 0), // Starts the main task purpose - COMMAND_STOP = (1 << 1), // stops the main task - COMMAND_STOP_GRACEFULLY = (1 << 2), // Stops the task once all data has been written - MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE = (1 << 5), // Locks the ring buffer when not set + COMMAND_START = (1 << 0), // starts the speaker task + COMMAND_STOP = (1 << 1), // stops the speaker task + COMMAND_STOP_GRACEFULLY = (1 << 2), // Stops the speaker task once all data has been written STATE_STARTING = (1 << 10), STATE_RUNNING = (1 << 11), STATE_STOPPING = (1 << 12), @@ -91,15 +92,21 @@ static const std::vector Q15_VOLUME_SCALING_FACTORS = { void I2SAudioSpeaker::setup() { ESP_LOGCONFIG(TAG, "Setting up I2S Audio Speaker..."); - if (this->event_group_ == nullptr) { - this->event_group_ = xEventGroupCreate(); - } + this->event_group_ = xEventGroupCreate(); if (this->event_group_ == nullptr) { ESP_LOGE(TAG, "Failed to create event group"); this->mark_failed(); return; } + + this->i2s_event_queue_ = xQueueCreate(I2S_EVENT_QUEUE_COUNT, sizeof(i2s_event_t)); + + if (this->i2s_event_queue_ == nullptr) { + ESP_LOGE(TAG, "Failed to create I2S event queue"); + this->mark_failed(); + return; + } } void I2SAudioSpeaker::loop() { @@ -199,23 +206,17 @@ size_t I2SAudioSpeaker::play(const uint8_t *data, size_t length, TickType_t tick this->start(); } - // Wait for the ring buffer to be available - uint32_t event_bits = - xEventGroupWaitBits(this->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE, pdFALSE, - pdFALSE, pdMS_TO_TICKS(TASK_DELAY_MS)); + size_t bytes_written = 0; + if ((this->state_ == speaker::STATE_RUNNING) && (this->audio_ring_buffer_.use_count() == 1)) { + // Only one owner of the ring buffer (the speaker task), so the ring buffer is allocated and no other components are + // attempting to write to it. - if (event_bits & SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE) { - // Ring buffer is available to write - - // Lock the ring buffer, write to it, then unlock it - xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE); - size_t bytes_written = this->audio_ring_buffer_->write_without_replacement((void *) data, length, ticks_to_wait); - xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE); - - return bytes_written; + // Temporarily share ownership of the ring buffer so it won't be deallocated while writing + std::shared_ptr temp_ring_buffer = this->audio_ring_buffer_; + bytes_written = temp_ring_buffer->write_without_replacement((void *) data, length, ticks_to_wait); } - return 0; + return bytes_written; } bool I2SAudioSpeaker::has_buffered_data() const { @@ -246,10 +247,12 @@ void I2SAudioSpeaker::speaker_task(void *params) { const ssize_t bytes_per_sample = audio_stream_info.get_bytes_per_sample(); const uint8_t number_of_channels = audio_stream_info.channels; - const size_t dma_buffers_size = FRAMES_IN_ALL_DMA_BUFFERS * bytes_per_sample * number_of_channels; + const size_t dma_buffers_size = DMA_BUFFERS_COUNT * DMA_BUFFER_DURATION_MS * this_speaker->sample_rate_ / 1000 * + bytes_per_sample * number_of_channels; + const size_t ring_buffer_size = + this_speaker->buffer_duration_ms_ * this_speaker->sample_rate_ / 1000 * bytes_per_sample * number_of_channels; - if (this_speaker->send_esp_err_to_event_group_( - this_speaker->allocate_buffers_(dma_buffers_size, RING_BUFFER_SAMPLES * bytes_per_sample))) { + if (this_speaker->send_esp_err_to_event_group_(this_speaker->allocate_buffers_(dma_buffers_size, ring_buffer_size))) { // Failed to allocate buffers xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM); this_speaker->delete_task_(dma_buffers_size); @@ -258,9 +261,6 @@ void I2SAudioSpeaker::speaker_task(void *params) { if (this_speaker->send_esp_err_to_event_group_(this_speaker->start_i2s_driver_())) { // Failed to start I2S driver this_speaker->delete_task_(dma_buffers_size); - } else { - // Ring buffer is allocated, so indicate its can be written to - xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE); } if (!this_speaker->send_esp_err_to_event_group_(this_speaker->reconfigure_i2s_stream_info_(audio_stream_info))) { @@ -270,8 +270,10 @@ void I2SAudioSpeaker::speaker_task(void *params) { bool stop_gracefully = false; uint32_t last_data_received_time = millis(); + bool tx_dma_underflow = false; - while ((millis() - last_data_received_time) <= this_speaker->timeout_) { + while (!this_speaker->timeout_.has_value() || + (millis() - last_data_received_time) <= this_speaker->timeout_.value()) { event_group_bits = xEventGroupGetBits(this_speaker->event_group_); if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP) { @@ -281,12 +283,18 @@ void I2SAudioSpeaker::speaker_task(void *params) { stop_gracefully = true; } + i2s_event_t i2s_event; + while (xQueueReceive(this_speaker->i2s_event_queue_, &i2s_event, 0)) { + if (i2s_event.type == I2S_EVENT_TX_Q_OVF) { + tx_dma_underflow = true; + } + } + size_t bytes_to_read = dma_buffers_size; size_t bytes_read = this_speaker->audio_ring_buffer_->read((void *) this_speaker->data_buffer_, bytes_to_read, pdMS_TO_TICKS(TASK_DELAY_MS)); if (bytes_read > 0) { - last_data_received_time = millis(); size_t bytes_written = 0; if ((audio_stream_info.bits_per_sample == 16) && (this_speaker->q15_volume_factor_ < INT16_MAX)) { @@ -307,15 +315,13 @@ void I2SAudioSpeaker::speaker_task(void *params) { if (bytes_written != bytes_read) { xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE); } - + tx_dma_underflow = false; + last_data_received_time = millis(); } else { // No data received - - if (stop_gracefully) { + if (stop_gracefully && tx_dma_underflow) { break; } - - i2s_zero_dma_buffer(this_speaker->parent_->get_port()); } } } else { @@ -326,7 +332,6 @@ void I2SAudioSpeaker::speaker_task(void *params) { xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STOPPING); - i2s_stop(this_speaker->parent_->get_port()); i2s_driver_uninstall(this_speaker->parent_->get_port()); this_speaker->parent_->unlock(); @@ -402,8 +407,8 @@ esp_err_t I2SAudioSpeaker::allocate_buffers_(size_t data_buffer_size, size_t rin return ESP_ERR_NO_MEM; } - if (this->audio_ring_buffer_ == nullptr) { - // Allocate ring buffer + if (this->audio_ring_buffer_.use_count() == 0) { + // Allocate ring buffer. Uses a shared_ptr to ensure it isn't improperly deallocated. this->audio_ring_buffer_ = RingBuffer::create(ring_buffer_size); } @@ -419,6 +424,8 @@ esp_err_t I2SAudioSpeaker::start_i2s_driver_() { return ESP_ERR_INVALID_STATE; } + int dma_buffer_length = DMA_BUFFER_DURATION_MS * this->sample_rate_ / 1000; + i2s_driver_config_t config = { .mode = (i2s_mode_t) (this->i2s_mode_ | I2S_MODE_TX), .sample_rate = this->sample_rate_, @@ -427,7 +434,7 @@ esp_err_t I2SAudioSpeaker::start_i2s_driver_() { .communication_format = this->i2s_comm_fmt_, .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, .dma_buf_count = DMA_BUFFERS_COUNT, - .dma_buf_len = DMA_BUFFER_SIZE, + .dma_buf_len = dma_buffer_length, .use_apll = this->use_apll_, .tx_desc_auto_clear = true, .fixed_mclk = I2S_PIN_NO_CHANGE, @@ -448,7 +455,8 @@ esp_err_t I2SAudioSpeaker::start_i2s_driver_() { } #endif - esp_err_t err = i2s_driver_install(this->parent_->get_port(), &config, 0, nullptr); + esp_err_t err = + i2s_driver_install(this->parent_->get_port(), &config, I2S_EVENT_QUEUE_COUNT, &this->i2s_event_queue_); if (err != ESP_OK) { // Failed to install the driver, so unlock the I2S port this->parent_->unlock(); @@ -502,16 +510,7 @@ esp_err_t I2SAudioSpeaker::reconfigure_i2s_stream_info_(audio::AudioStreamInfo & } void I2SAudioSpeaker::delete_task_(size_t buffer_size) { - if (this->audio_ring_buffer_ != nullptr) { - xEventGroupWaitBits(this->event_group_, - MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE, // Bit message to read - pdFALSE, // Don't clear the bits on exit - pdTRUE, // Don't wait for all the bits, - portMAX_DELAY); // Block indefinitely until a command bit is set - - this->audio_ring_buffer_.reset(); // Deallocates the ring buffer stored in the unique_ptr - this->audio_ring_buffer_ = nullptr; - } + this->audio_ring_buffer_.reset(); // Releases onwership of the shared_ptr if (this->data_buffer_ != nullptr) { ExternalRAMAllocator allocator(ExternalRAMAllocator::ALLOW_FAILURE); @@ -520,6 +519,7 @@ void I2SAudioSpeaker::delete_task_(size_t buffer_size) { } xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::STATE_STOPPED); + xQueueReset(this->i2s_event_queue_); this->task_created_ = false; vTaskDelete(nullptr); diff --git a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h index 3c512d4d4d..8b7386ba58 100644 --- a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h +++ b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h @@ -7,6 +7,7 @@ #include #include +#include #include #include "esphome/components/audio/audio.h" @@ -27,6 +28,7 @@ class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Comp void setup() override; void loop() override; + void set_buffer_duration(uint32_t buffer_duration_ms) { this->buffer_duration_ms_ = buffer_duration_ms; } void set_timeout(uint32_t ms) { this->timeout_ = ms; } void set_dout_pin(uint8_t pin) { this->dout_pin_ = pin; } #if SOC_I2S_SUPPORTS_DAC @@ -117,10 +119,14 @@ class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Comp TaskHandle_t speaker_task_handle_{nullptr}; EventGroupHandle_t event_group_{nullptr}; - uint8_t *data_buffer_; - std::unique_ptr audio_ring_buffer_; + QueueHandle_t i2s_event_queue_; - uint32_t timeout_; + uint8_t *data_buffer_; + std::shared_ptr audio_ring_buffer_; + + uint32_t buffer_duration_ms_; + + optional timeout_; uint8_t dout_pin_; bool task_created_{false}; From 1e80c4807eaab36d92c732a303664d29576d9e06 Mon Sep 17 00:00:00 2001 From: FreeBear-nc <67865163+FreeBear-nc@users.noreply.github.com> Date: Tue, 12 Nov 2024 18:20:48 +0000 Subject: [PATCH 003/107] Message to string extend (#7755) --- esphome/components/opentherm/hub.cpp | 4 ++-- esphome/components/opentherm/opentherm.cpp | 27 ++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/esphome/components/opentherm/hub.cpp b/esphome/components/opentherm/hub.cpp index 432036d58d..dfa8ea95c5 100644 --- a/esphome/components/opentherm/hub.cpp +++ b/esphome/components/opentherm/hub.cpp @@ -371,11 +371,11 @@ void OpenthermHub::dump_config() { ESP_LOGCONFIG(TAG, " Numbers: %s", SHOW(OPENTHERM_NUMBER_LIST(ID, ))); ESP_LOGCONFIG(TAG, " Initial requests:"); for (auto type : this->initial_messages_) { - ESP_LOGCONFIG(TAG, " - %d", type); + ESP_LOGCONFIG(TAG, " - %d (%s)", type, this->opentherm_->message_id_to_str((type))); } ESP_LOGCONFIG(TAG, " Repeating requests:"); for (auto type : this->repeating_messages_) { - ESP_LOGCONFIG(TAG, " - %d", type); + ESP_LOGCONFIG(TAG, " - %d (%s)", type, this->opentherm_->message_id_to_str((type))); } } diff --git a/esphome/components/opentherm/opentherm.cpp b/esphome/components/opentherm/opentherm.cpp index 4a23bb94cf..26c707f9a0 100644 --- a/esphome/components/opentherm/opentherm.cpp +++ b/esphome/components/opentherm/opentherm.cpp @@ -483,6 +483,8 @@ const char *OpenTherm::message_id_to_str(MessageId id) { TO_STRING_MEMBER(EXHAUST_TEMP) TO_STRING_MEMBER(FAN_SPEED) TO_STRING_MEMBER(FLAME_CURRENT) + TO_STRING_MEMBER(ROOM_TEMP_CH2) + TO_STRING_MEMBER(REL_HUMIDITY) TO_STRING_MEMBER(DHW_BOUNDS) TO_STRING_MEMBER(CH_BOUNDS) TO_STRING_MEMBER(OTC_CURVE_BOUNDS) @@ -492,14 +494,39 @@ const char *OpenTherm::message_id_to_str(MessageId id) { TO_STRING_MEMBER(HVAC_STATUS) TO_STRING_MEMBER(REL_VENT_SETPOINT) TO_STRING_MEMBER(DEVICE_VENT) + TO_STRING_MEMBER(HVAC_VER_ID) TO_STRING_MEMBER(REL_VENTILATION) TO_STRING_MEMBER(REL_HUMID_EXHAUST) + TO_STRING_MEMBER(EXHAUST_CO2) TO_STRING_MEMBER(SUPPLY_INLET_TEMP) TO_STRING_MEMBER(SUPPLY_OUTLET_TEMP) TO_STRING_MEMBER(EXHAUST_INLET_TEMP) TO_STRING_MEMBER(EXHAUST_OUTLET_TEMP) + TO_STRING_MEMBER(EXHAUST_FAN_SPEED) + TO_STRING_MEMBER(SUPPLY_FAN_SPEED) + TO_STRING_MEMBER(REMOTE_VENTILATION_PARAM) TO_STRING_MEMBER(NOM_REL_VENTILATION) + TO_STRING_MEMBER(HVAC_NUM_TSP) + TO_STRING_MEMBER(HVAC_IDX_TSP) + TO_STRING_MEMBER(HVAC_FHB_SIZE) + TO_STRING_MEMBER(HVAC_FHB_IDX) + TO_STRING_MEMBER(RF_SIGNAL) + TO_STRING_MEMBER(DHW_MODE) TO_STRING_MEMBER(OVERRIDE_FUNC) + TO_STRING_MEMBER(SOLAR_MODE_FLAGS) + TO_STRING_MEMBER(SOLAR_ASF) + TO_STRING_MEMBER(SOLAR_VERSION_ID) + TO_STRING_MEMBER(SOLAR_PRODUCT_ID) + TO_STRING_MEMBER(SOLAR_NUM_TSP) + TO_STRING_MEMBER(SOLAR_IDX_TSP) + TO_STRING_MEMBER(SOLAR_FHB_SIZE) + TO_STRING_MEMBER(SOLAR_FHB_IDX) + TO_STRING_MEMBER(SOLAR_STARTS) + TO_STRING_MEMBER(SOLAR_HOURS) + TO_STRING_MEMBER(SOLAR_ENERGY) + TO_STRING_MEMBER(SOLAR_TOTAL_ENERGY) + TO_STRING_MEMBER(FAILED_BURNER_STARTS) + TO_STRING_MEMBER(BURNER_FLAME_LOW) TO_STRING_MEMBER(OEM_DIAGNOSTIC) TO_STRING_MEMBER(BURNER_STARTS) TO_STRING_MEMBER(CH_PUMP_STARTS) From e6a1254e65d69ae0f362891409e7085768b6a479 Mon Sep 17 00:00:00 2001 From: Edward Firmo <94725493+edwardtfn@users.noreply.github.com> Date: Tue, 12 Nov 2024 19:23:00 +0100 Subject: [PATCH 004/107] [sun] Implements `is_above_horizon()` (#7754) --- esphome/components/sun/sun.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/esphome/components/sun/sun.h b/esphome/components/sun/sun.h index de4801a655..77d62d34c3 100644 --- a/esphome/components/sun/sun.h +++ b/esphome/components/sun/sun.h @@ -59,6 +59,9 @@ class Sun { void set_latitude(double latitude) { location_.latitude = latitude; } void set_longitude(double longitude) { location_.longitude = longitude; } + // Check if the sun is above the horizon, with a default elevation angle of -0.83333 (standard for sunrise/set). + bool is_above_horizon(double elevation = -0.83333) { return this->elevation() > elevation; } + optional sunrise(double elevation); optional sunset(double elevation); optional sunrise(ESPTime date, double elevation); From b367c01b4b27ac19c75d75774c7ce162894d6035 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 12 Nov 2024 13:48:03 -0500 Subject: [PATCH 005/107] [core] Ring buffer write functions use const pointer parameter (#7750) --- esphome/core/ring_buffer.cpp | 4 ++-- esphome/core/ring_buffer.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/esphome/core/ring_buffer.cpp b/esphome/core/ring_buffer.cpp index f97c686684..6152ada314 100644 --- a/esphome/core/ring_buffer.cpp +++ b/esphome/core/ring_buffer.cpp @@ -46,7 +46,7 @@ size_t RingBuffer::read(void *data, size_t len, TickType_t ticks_to_wait) { return bytes_read; } -size_t RingBuffer::write(void *data, size_t len) { +size_t RingBuffer::write(const void *data, size_t len) { size_t free = this->free(); if (free < len) { size_t needed = len - free; @@ -56,7 +56,7 @@ size_t RingBuffer::write(void *data, size_t len) { return xStreamBufferSend(this->handle_, data, len, 0); } -size_t RingBuffer::write_without_replacement(void *data, size_t len, TickType_t ticks_to_wait) { +size_t RingBuffer::write_without_replacement(const void *data, size_t len, TickType_t ticks_to_wait) { return xStreamBufferSend(this->handle_, data, len, ticks_to_wait); } diff --git a/esphome/core/ring_buffer.h b/esphome/core/ring_buffer.h index c0511fb52e..aade1b5f49 100644 --- a/esphome/core/ring_buffer.h +++ b/esphome/core/ring_buffer.h @@ -37,7 +37,7 @@ class RingBuffer { * @param len Number of bytes to write * @return Number of bytes written */ - size_t write(void *data, size_t len); + size_t write(const void *data, size_t len); /** * @brief Writes to the ring buffer without overwriting oldest data. @@ -50,7 +50,7 @@ class RingBuffer { * @param ticks_to_wait Maximum number of FreeRTOS ticks to wait (default: 0) * @return Number of bytes written */ - size_t write_without_replacement(void *data, size_t len, TickType_t ticks_to_wait = 0); + size_t write_without_replacement(const void *data, size_t len, TickType_t ticks_to_wait = 0); /** * @brief Returns the number of available bytes in the ring buffer. From 7d75c9157bd9ddaa7c56389d6b3126a461b1e52b Mon Sep 17 00:00:00 2001 From: TFGF Date: Tue, 12 Nov 2024 17:48:40 -0300 Subject: [PATCH 006/107] [Modbus Controller] Added `on_online` and `on_offline` automation (#7417) --- .../components/modbus_controller/__init__.py | 32 ++++++++++++++++++- .../components/modbus_controller/automation.h | 16 ++++++++++ esphome/components/modbus_controller/const.py | 2 ++ .../modbus_controller/modbus_controller.cpp | 16 ++++++++-- .../modbus_controller/modbus_controller.h | 9 ++++++ .../modbus_controller/test.esp32-ard.yaml | 3 ++ .../modbus_controller/test.esp32-idf.yaml | 3 ++ 7 files changed, 78 insertions(+), 3 deletions(-) diff --git a/esphome/components/modbus_controller/__init__.py b/esphome/components/modbus_controller/__init__.py index 488baa245a..5c407d6fff 100644 --- a/esphome/components/modbus_controller/__init__.py +++ b/esphome/components/modbus_controller/__init__.py @@ -25,6 +25,8 @@ from .const import ( CONF_MODBUS_CONTROLLER_ID, CONF_OFFLINE_SKIP_UPDATES, CONF_ON_COMMAND_SENT, + CONF_ON_ONLINE, + CONF_ON_OFFLINE, CONF_REGISTER_COUNT, CONF_REGISTER_TYPE, CONF_RESPONSE_SIZE, @@ -114,6 +116,14 @@ ModbusCommandSentTrigger = modbus_controller_ns.class_( "ModbusCommandSentTrigger", automation.Trigger.template(cg.int_, cg.int_) ) +ModbusOnlineTrigger = modbus_controller_ns.class_( + "ModbusOnlineTrigger", automation.Trigger.template(cg.int_, cg.int_) +) + +ModbusOfflineTrigger = modbus_controller_ns.class_( + "ModbusOfflineTrigger", automation.Trigger.template(cg.int_, cg.int_) +) + _LOGGER = logging.getLogger(__name__) ModbusServerRegisterSchema = cv.Schema( @@ -146,6 +156,16 @@ CONFIG_SCHEMA = cv.All( ), } ), + cv.Optional(CONF_ON_ONLINE): automation.validate_automation( + { + cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(ModbusOnlineTrigger), + } + ), + cv.Optional(CONF_ON_OFFLINE): automation.validate_automation( + { + cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(ModbusOnlineTrigger), + } + ), } ) .extend(cv.polling_component_schema("60s")) @@ -284,7 +304,17 @@ async def to_code(config): for conf in config.get(CONF_ON_COMMAND_SENT, []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) await automation.build_automation( - trigger, [(int, "function_code"), (int, "address")], conf + trigger, [(cg.int_, "function_code"), (cg.int_, "address")], conf + ) + for conf in config.get(CONF_ON_ONLINE, []): + trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) + await automation.build_automation( + trigger, [(cg.int_, "function_code"), (cg.int_, "address")], conf + ) + for conf in config.get(CONF_ON_OFFLINE, []): + trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) + await automation.build_automation( + trigger, [(cg.int_, "function_code"), (cg.int_, "address")], conf ) diff --git a/esphome/components/modbus_controller/automation.h b/esphome/components/modbus_controller/automation.h index ad8de4b05d..b3338192cc 100644 --- a/esphome/components/modbus_controller/automation.h +++ b/esphome/components/modbus_controller/automation.h @@ -15,5 +15,21 @@ class ModbusCommandSentTrigger : public Trigger { } }; +class ModbusOnlineTrigger : public Trigger { + public: + ModbusOnlineTrigger(ModbusController *a_modbuscontroller) { + a_modbuscontroller->add_on_online_callback( + [this](int function_code, int address) { this->trigger(function_code, address); }); + } +}; + +class ModbusOfflineTrigger : public Trigger { + public: + ModbusOfflineTrigger(ModbusController *a_modbuscontroller) { + a_modbuscontroller->add_on_offline_callback( + [this](int function_code, int address) { this->trigger(function_code, address); }); + } +}; + } // namespace modbus_controller } // namespace esphome diff --git a/esphome/components/modbus_controller/const.py b/esphome/components/modbus_controller/const.py index 5cf7d230f1..4d39e48dcd 100644 --- a/esphome/components/modbus_controller/const.py +++ b/esphome/components/modbus_controller/const.py @@ -9,6 +9,8 @@ CONF_MAX_CMD_RETRIES = "max_cmd_retries" CONF_MODBUS_CONTROLLER_ID = "modbus_controller_id" CONF_MODBUS_FUNCTIONCODE = "modbus_functioncode" CONF_ON_COMMAND_SENT = "on_command_sent" +CONF_ON_ONLINE = "on_online" +CONF_ON_OFFLINE = "on_offline" CONF_RAW_ENCODE = "raw_encode" CONF_REGISTER_COUNT = "register_count" CONF_REGISTER_TYPE = "register_type" diff --git a/esphome/components/modbus_controller/modbus_controller.cpp b/esphome/components/modbus_controller/modbus_controller.cpp index 1dcb533629..e1102516ca 100644 --- a/esphome/components/modbus_controller/modbus_controller.cpp +++ b/esphome/components/modbus_controller/modbus_controller.cpp @@ -32,8 +32,10 @@ bool ModbusController::send_next_command_() { r.skip_updates_counter = this->offline_skip_updates_; } } + + this->module_offline_ = true; + this->offline_callback_.call((int) command->function_code, command->register_address); } - this->module_offline_ = true; ESP_LOGD(TAG, "Modbus command to device=%d register=0x%02X no response received - removed from send queue", this->address_, command->register_address); this->command_queue_.pop_front(); @@ -68,8 +70,10 @@ void ModbusController::on_modbus_data(const std::vector &data) { r.skip_updates_counter = 0; } } + // Restore module online state + this->module_offline_ = false; + this->online_callback_.call((int) current_command->function_code, current_command->register_address); } - this->module_offline_ = false; // Move the commandItem to the response queue current_command->payload = data; @@ -670,5 +674,13 @@ void ModbusController::add_on_command_sent_callback(std::functioncommand_sent_callback_.add(std::move(callback)); } +void ModbusController::add_on_online_callback(std::function &&callback) { + this->online_callback_.add(std::move(callback)); +} + +void ModbusController::add_on_offline_callback(std::function &&callback) { + this->offline_callback_.add(std::move(callback)); +} + } // namespace modbus_controller } // namespace esphome diff --git a/esphome/components/modbus_controller/modbus_controller.h b/esphome/components/modbus_controller/modbus_controller.h index 1fa35e1535..2a0b936bf5 100644 --- a/esphome/components/modbus_controller/modbus_controller.h +++ b/esphome/components/modbus_controller/modbus_controller.h @@ -468,6 +468,10 @@ class ModbusController : public PollingComponent, public modbus::ModbusDevice { bool get_module_offline() { return module_offline_; } /// Set callback for commands void add_on_command_sent_callback(std::function &&callback); + /// Set callback for online changes + void add_on_online_callback(std::function &&callback); + /// Set callback for offline changes + void add_on_offline_callback(std::function &&callback); /// called by esphome generated code to set the max_cmd_retries. void set_max_cmd_retries(uint8_t max_cmd_retries) { this->max_cmd_retries_ = max_cmd_retries; } /// get how many times a command will be (re)sent if no response is received @@ -508,7 +512,12 @@ class ModbusController : public PollingComponent, public modbus::ModbusDevice { uint16_t offline_skip_updates_; /// How many times we will retry a command if we get no response uint8_t max_cmd_retries_{4}; + /// Command sent callback CallbackManager command_sent_callback_{}; + /// Server online callback + CallbackManager online_callback_{}; + /// Server offline callback + CallbackManager offline_callback_{}; }; /** Convert vector response payload to float. diff --git a/tests/components/modbus_controller/test.esp32-ard.yaml b/tests/components/modbus_controller/test.esp32-ard.yaml index cd95d149cb..f5c5c10125 100644 --- a/tests/components/modbus_controller/test.esp32-ard.yaml +++ b/tests/components/modbus_controller/test.esp32-ard.yaml @@ -21,6 +21,9 @@ modbus_controller: address: 0x2 modbus_id: mod_bus1 allow_duplicate_commands: false + on_online: + then: + logger.log: "Module Online" - id: modbus_controller2 address: 0x2 modbus_id: mod_bus2 diff --git a/tests/components/modbus_controller/test.esp32-idf.yaml b/tests/components/modbus_controller/test.esp32-idf.yaml index ba28e94d73..0e1849dd88 100644 --- a/tests/components/modbus_controller/test.esp32-idf.yaml +++ b/tests/components/modbus_controller/test.esp32-idf.yaml @@ -13,4 +13,7 @@ modbus_controller: address: 0x2 modbus_id: mod_bus1 allow_duplicate_commands: true + on_offline: + then: + logger.log: "Module Offline" max_cmd_retries: 10 From 053465d3f627809fc890eb94271419df0368f369 Mon Sep 17 00:00:00 2001 From: Kyle Cascade Date: Tue, 12 Nov 2024 14:54:25 -0800 Subject: [PATCH 007/107] Updated dfplayer logging to be more user-friendly (#7740) --- esphome/components/dfplayer/dfplayer.cpp | 138 ++++++++++++++++++++++- esphome/components/dfplayer/dfplayer.h | 72 ++++-------- 2 files changed, 151 insertions(+), 59 deletions(-) diff --git a/esphome/components/dfplayer/dfplayer.cpp b/esphome/components/dfplayer/dfplayer.cpp index aa2dc260e0..98c3e91e46 100644 --- a/esphome/components/dfplayer/dfplayer.cpp +++ b/esphome/components/dfplayer/dfplayer.cpp @@ -6,7 +6,104 @@ namespace dfplayer { static const char *const TAG = "dfplayer"; +void DFPlayer::next() { + this->ack_set_is_playing_ = true; + ESP_LOGD(TAG, "Playing next track"); + this->send_cmd_(0x01); +} + +void DFPlayer::previous() { + this->ack_set_is_playing_ = true; + ESP_LOGD(TAG, "Playing previous track"); + this->send_cmd_(0x02); +} +void DFPlayer::play_mp3(uint16_t file) { + this->ack_set_is_playing_ = true; + ESP_LOGD(TAG, "Playing file %d in mp3 folder", file); + this->send_cmd_(0x12, file); +} + +void DFPlayer::play_file(uint16_t file) { + this->ack_set_is_playing_ = true; + ESP_LOGD(TAG, "Playing file %d", file); + this->send_cmd_(0x03, file); +} + +void DFPlayer::play_file_loop(uint16_t file) { + this->ack_set_is_playing_ = true; + ESP_LOGD(TAG, "Playing file %d in loop", file); + this->send_cmd_(0x08, file); +} + +void DFPlayer::play_folder_loop(uint16_t folder) { + this->ack_set_is_playing_ = true; + ESP_LOGD(TAG, "Playing folder %d in loop", folder); + this->send_cmd_(0x17, folder); +} + +void DFPlayer::volume_up() { + ESP_LOGD(TAG, "Increasing volume"); + this->send_cmd_(0x04); +} + +void DFPlayer::volume_down() { + ESP_LOGD(TAG, "Decreasing volume"); + this->send_cmd_(0x05); +} + +void DFPlayer::set_device(Device device) { + ESP_LOGD(TAG, "Setting device to %d", device); + this->send_cmd_(0x09, device); +} + +void DFPlayer::set_volume(uint8_t volume) { + ESP_LOGD(TAG, "Setting volume to %d", volume); + this->send_cmd_(0x06, volume); +} + +void DFPlayer::set_eq(EqPreset preset) { + ESP_LOGD(TAG, "Setting EQ to %d", preset); + this->send_cmd_(0x07, preset); +} + +void DFPlayer::sleep() { + this->ack_reset_is_playing_ = true; + ESP_LOGD(TAG, "Putting DFPlayer to sleep"); + this->send_cmd_(0x0A); +} + +void DFPlayer::reset() { + this->ack_reset_is_playing_ = true; + ESP_LOGD(TAG, "Resetting DFPlayer"); + this->send_cmd_(0x0C); +} + +void DFPlayer::start() { + this->ack_set_is_playing_ = true; + ESP_LOGD(TAG, "Starting playback"); + this->send_cmd_(0x0D); +} + +void DFPlayer::pause() { + this->ack_reset_is_playing_ = true; + ESP_LOGD(TAG, "Pausing playback"); + this->send_cmd_(0x0E); +} + +void DFPlayer::stop() { + this->ack_reset_is_playing_ = true; + ESP_LOGD(TAG, "Stopping playback"); + this->send_cmd_(0x16); +} + +void DFPlayer::random() { + this->ack_set_is_playing_ = true; + ESP_LOGD(TAG, "Playing random file"); + this->send_cmd_(0x18); +} + void DFPlayer::play_folder(uint16_t folder, uint16_t file) { + ESP_LOGD(TAG, "Playing file %d in folder %d", file, folder); if (folder < 100 && file < 256) { this->ack_set_is_playing_ = true; this->send_cmd_(0x0F, (uint8_t) folder, (uint8_t) file); @@ -29,7 +126,7 @@ void DFPlayer::send_cmd_(uint8_t cmd, uint16_t argument) { this->sent_cmd_ = cmd; - ESP_LOGD(TAG, "Send Command %#02x arg %#04x", cmd, argument); + ESP_LOGV(TAG, "Send Command %#02x arg %#04x", cmd, argument); this->write_array(buffer, 10); } @@ -101,9 +198,37 @@ void DFPlayer::loop() { ESP_LOGV(TAG, "Nack"); this->ack_set_is_playing_ = false; this->ack_reset_is_playing_ = false; - if (argument == 6) { - ESP_LOGV(TAG, "File not found"); - this->is_playing_ = false; + switch (argument) { + case 0x01: + ESP_LOGE(TAG, "Module is busy or uninitialized"); + break; + case 0x02: + ESP_LOGE(TAG, "Module is in sleep mode"); + break; + case 0x03: + ESP_LOGE(TAG, "Serial receive error"); + break; + case 0x04: + ESP_LOGE(TAG, "Checksum incorrect"); + break; + case 0x05: + ESP_LOGE(TAG, "Specified track is out of current track scope"); + this->is_playing_ = false; + break; + case 0x06: + ESP_LOGE(TAG, "Specified track is not found"); + this->is_playing_ = false; + break; + case 0x07: + ESP_LOGE(TAG, "Insertion error (an inserting operation only can be done when a track is being played)"); + break; + case 0x08: + ESP_LOGE(TAG, "SD card reading failed (SD card pulled out or damaged)"); + break; + case 0x09: + ESP_LOGE(TAG, "Entered into sleep mode"); + this->is_playing_ = false; + break; } break; case 0x41: @@ -113,12 +238,13 @@ void DFPlayer::loop() { this->ack_set_is_playing_ = false; this->ack_reset_is_playing_ = false; break; - case 0x3D: // Playback finished + case 0x3D: + ESP_LOGV(TAG, "Playback finished"); this->is_playing_ = false; this->on_finished_playback_callback_.call(); break; default: - ESP_LOGD(TAG, "Command %#02x arg %#04x", cmd, argument); + ESP_LOGV(TAG, "Received unknown cmd %#02x arg %#04x", cmd, argument); } this->sent_cmd_ = 0; this->read_pos_ = 0; diff --git a/esphome/components/dfplayer/dfplayer.h b/esphome/components/dfplayer/dfplayer.h index 26e90fd410..d2ec0a2310 100644 --- a/esphome/components/dfplayer/dfplayer.h +++ b/esphome/components/dfplayer/dfplayer.h @@ -23,64 +23,30 @@ enum Device { TF_CARD = 2, }; +// See the datasheet here: +// https://github.com/DFRobot/DFRobotDFPlayerMini/blob/master/doc/FN-M16P%2BEmbedded%2BMP3%2BAudio%2BModule%2BDatasheet.pdf class DFPlayer : public uart::UARTDevice, public Component { public: void loop() override; - void next() { - this->ack_set_is_playing_ = true; - this->send_cmd_(0x01); - } - void previous() { - this->ack_set_is_playing_ = true; - this->send_cmd_(0x02); - } - void play_mp3(uint16_t file) { - this->ack_set_is_playing_ = true; - this->send_cmd_(0x12, file); - } - void play_file(uint16_t file) { - this->ack_set_is_playing_ = true; - this->send_cmd_(0x03, file); - } - void play_file_loop(uint16_t file) { - this->ack_set_is_playing_ = true; - this->send_cmd_(0x08, file); - } + void next(); + void previous(); + void play_mp3(uint16_t file); + void play_file(uint16_t file); + void play_file_loop(uint16_t file); void play_folder(uint16_t folder, uint16_t file); - void play_folder_loop(uint16_t folder) { - this->ack_set_is_playing_ = true; - this->send_cmd_(0x17, folder); - } - void volume_up() { this->send_cmd_(0x04); } - void volume_down() { this->send_cmd_(0x05); } - void set_device(Device device) { this->send_cmd_(0x09, device); } - void set_volume(uint8_t volume) { this->send_cmd_(0x06, volume); } - void set_eq(EqPreset preset) { this->send_cmd_(0x07, preset); } - void sleep() { - this->ack_reset_is_playing_ = true; - this->send_cmd_(0x0A); - } - void reset() { - this->ack_reset_is_playing_ = true; - this->send_cmd_(0x0C); - } - void start() { - this->ack_set_is_playing_ = true; - this->send_cmd_(0x0D); - } - void pause() { - this->ack_reset_is_playing_ = true; - this->send_cmd_(0x0E); - } - void stop() { - this->ack_reset_is_playing_ = true; - this->send_cmd_(0x16); - } - void random() { - this->ack_set_is_playing_ = true; - this->send_cmd_(0x18); - } + void play_folder_loop(uint16_t folder); + void volume_up(); + void volume_down(); + void set_device(Device device); + void set_volume(uint8_t volume); + void set_eq(EqPreset preset); + void sleep(); + void reset(); + void start(); + void pause(); + void stop(); + void random(); bool is_playing() { return is_playing_; } void dump_config() override; From 80226694d5d0c5d44f0bb8c2c39b070802c4b073 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Wed, 13 Nov 2024 13:16:13 +1300 Subject: [PATCH 008/107] Bump version to 2024.11.0b1 --- esphome/const.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/const.py b/esphome/const.py index 5645c9eaab..c3c8712677 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -1,6 +1,6 @@ """Constants used by esphome.""" -__version__ = "2024.11.0-dev" +__version__ = "2024.11.0b1" ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_" VALID_SUBSTITUTIONS_CHARACTERS = ( From 1f7f03f563e3500beeda9a3c163ee48e309e7617 Mon Sep 17 00:00:00 2001 From: luar123 <49960470+luar123@users.noreply.github.com> Date: Wed, 13 Nov 2024 01:18:10 +0100 Subject: [PATCH 009/107] Fix temperature and humidity for bme680 with bsec2 (#7728) --- .../components/bme68x_bsec2/bme68x_bsec2.cpp | 95 ++++++++++--------- .../components/bme68x_bsec2/bme68x_bsec2.h | 2 - 2 files changed, 49 insertions(+), 48 deletions(-) diff --git a/esphome/components/bme68x_bsec2/bme68x_bsec2.cpp b/esphome/components/bme68x_bsec2/bme68x_bsec2.cpp index 5425bbd5b7..f83f20f1a5 100644 --- a/esphome/components/bme68x_bsec2/bme68x_bsec2.cpp +++ b/esphome/components/bme68x_bsec2/bme68x_bsec2.cpp @@ -204,11 +204,11 @@ void BME68xBSEC2Component::update_subscription_() { } void BME68xBSEC2Component::run_() { + this->op_mode_ = this->bsec_settings_.op_mode; int64_t curr_time_ns = this->get_time_ns_(); - if (curr_time_ns < this->next_call_ns_) { + if (curr_time_ns < this->bsec_settings_.next_call) { return; } - this->op_mode_ = this->bsec_settings_.op_mode; uint8_t status; ESP_LOGV(TAG, "Performing sensor run"); @@ -219,57 +219,60 @@ void BME68xBSEC2Component::run_() { ESP_LOGW(TAG, "Failed to fetch sensor control settings (BSEC2 error code %d)", this->bsec_status_); return; } - this->next_call_ns_ = this->bsec_settings_.next_call; - if (this->bsec_settings_.trigger_measurement) { - bme68x_get_conf(&bme68x_conf, &this->bme68x_); + switch (this->bsec_settings_.op_mode) { + case BME68X_FORCED_MODE: + bme68x_get_conf(&bme68x_conf, &this->bme68x_); - bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling; - bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling; - bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling; - bme68x_set_conf(&bme68x_conf, &this->bme68x_); + bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling; + bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling; + bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling; + bme68x_set_conf(&bme68x_conf, &this->bme68x_); + this->bme68x_heatr_conf_.enable = BME68X_ENABLE; + this->bme68x_heatr_conf_.heatr_temp = this->bsec_settings_.heater_temperature; + this->bme68x_heatr_conf_.heatr_dur = this->bsec_settings_.heater_duration; + + // status = bme68x_set_op_mode(this->bsec_settings_.op_mode, &this->bme68x_); + status = bme68x_set_heatr_conf(BME68X_FORCED_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); + status = bme68x_set_op_mode(BME68X_FORCED_MODE, &this->bme68x_); + this->op_mode_ = BME68X_FORCED_MODE; + ESP_LOGV(TAG, "Using forced mode"); + + break; + case BME68X_PARALLEL_MODE: + if (this->op_mode_ != this->bsec_settings_.op_mode) { + bme68x_get_conf(&bme68x_conf, &this->bme68x_); + + bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling; + bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling; + bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling; + bme68x_set_conf(&bme68x_conf, &this->bme68x_); - switch (this->bsec_settings_.op_mode) { - case BME68X_FORCED_MODE: this->bme68x_heatr_conf_.enable = BME68X_ENABLE; - this->bme68x_heatr_conf_.heatr_temp = this->bsec_settings_.heater_temperature; - this->bme68x_heatr_conf_.heatr_dur = this->bsec_settings_.heater_duration; + this->bme68x_heatr_conf_.heatr_temp_prof = this->bsec_settings_.heater_temperature_profile; + this->bme68x_heatr_conf_.heatr_dur_prof = this->bsec_settings_.heater_duration_profile; + this->bme68x_heatr_conf_.profile_len = this->bsec_settings_.heater_profile_len; + this->bme68x_heatr_conf_.shared_heatr_dur = + BSEC_TOTAL_HEAT_DUR - + (bme68x_get_meas_dur(BME68X_PARALLEL_MODE, &bme68x_conf, &this->bme68x_) / INT64_C(1000)); - status = bme68x_set_op_mode(this->bsec_settings_.op_mode, &this->bme68x_); - status = bme68x_set_heatr_conf(BME68X_FORCED_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); - status = bme68x_set_op_mode(BME68X_FORCED_MODE, &this->bme68x_); - this->op_mode_ = BME68X_FORCED_MODE; - this->sleep_mode_ = false; - ESP_LOGV(TAG, "Using forced mode"); + status = bme68x_set_heatr_conf(BME68X_PARALLEL_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); - break; - case BME68X_PARALLEL_MODE: - if (this->op_mode_ != this->bsec_settings_.op_mode) { - this->bme68x_heatr_conf_.enable = BME68X_ENABLE; - this->bme68x_heatr_conf_.heatr_temp_prof = this->bsec_settings_.heater_temperature_profile; - this->bme68x_heatr_conf_.heatr_dur_prof = this->bsec_settings_.heater_duration_profile; - this->bme68x_heatr_conf_.profile_len = this->bsec_settings_.heater_profile_len; - this->bme68x_heatr_conf_.shared_heatr_dur = - BSEC_TOTAL_HEAT_DUR - - (bme68x_get_meas_dur(BME68X_PARALLEL_MODE, &bme68x_conf, &this->bme68x_) / INT64_C(1000)); - - status = bme68x_set_heatr_conf(BME68X_PARALLEL_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); - - status = bme68x_set_op_mode(BME68X_PARALLEL_MODE, &this->bme68x_); - this->op_mode_ = BME68X_PARALLEL_MODE; - this->sleep_mode_ = false; - ESP_LOGV(TAG, "Using parallel mode"); - } - break; - case BME68X_SLEEP_MODE: - if (!this->sleep_mode_) { - bme68x_set_op_mode(BME68X_SLEEP_MODE, &this->bme68x_); - this->sleep_mode_ = true; - ESP_LOGV(TAG, "Using sleep mode"); - } - break; - } + status = bme68x_set_op_mode(BME68X_PARALLEL_MODE, &this->bme68x_); + this->op_mode_ = BME68X_PARALLEL_MODE; + ESP_LOGV(TAG, "Using parallel mode"); + } + break; + case BME68X_SLEEP_MODE: + if (this->op_mode_ != this->bsec_settings_.op_mode) { + bme68x_set_op_mode(BME68X_SLEEP_MODE, &this->bme68x_); + this->op_mode_ = BME68X_SLEEP_MODE; + ESP_LOGV(TAG, "Using sleep mode"); + } + break; + } + if (this->bsec_settings_.trigger_measurement && this->bsec_settings_.op_mode != BME68X_SLEEP_MODE) { uint32_t meas_dur = 0; meas_dur = bme68x_get_meas_dur(this->op_mode_, &bme68x_conf, &this->bme68x_); ESP_LOGV(TAG, "Queueing read in %uus", meas_dur); diff --git a/esphome/components/bme68x_bsec2/bme68x_bsec2.h b/esphome/components/bme68x_bsec2/bme68x_bsec2.h index 7b9db2b7bf..86d3e5dfbf 100644 --- a/esphome/components/bme68x_bsec2/bme68x_bsec2.h +++ b/esphome/components/bme68x_bsec2/bme68x_bsec2.h @@ -113,13 +113,11 @@ class BME68xBSEC2Component : public Component { struct bme68x_heatr_conf bme68x_heatr_conf_; uint8_t op_mode_; // operating mode of sensor - bool sleep_mode_; bsec_library_return_t bsec_status_{BSEC_OK}; int8_t bme68x_status_{BME68X_OK}; int64_t last_time_ms_{0}; uint32_t millis_overflow_counter_{0}; - int64_t next_call_ns_{0}; std::queue> queue_; From a2cab960a9d2f138fe736ce8147b383f13146475 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Wed, 13 Nov 2024 13:16:13 +1300 Subject: [PATCH 010/107] Bump version to 2024.12.0-dev --- esphome/const.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/const.py b/esphome/const.py index 5645c9eaab..d42ee5ee72 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -1,6 +1,6 @@ """Constants used by esphome.""" -__version__ = "2024.11.0-dev" +__version__ = "2024.12.0-dev" ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_" VALID_SUBSTITUTIONS_CHARACTERS = ( From c7c8711c9c8380d9d90875973e2e8c0e70678667 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Wed, 13 Nov 2024 12:39:02 -0500 Subject: [PATCH 011/107] [i2s_audio] Bugfix: Adjust I2S speaker setup priority (#7759) --- .../i2s_audio/speaker/i2s_audio_speaker.cpp | 11 +---------- .../components/i2s_audio/speaker/i2s_audio_speaker.h | 2 +- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp index c3f4566411..53b3cc8dc0 100644 --- a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp +++ b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp @@ -99,14 +99,6 @@ void I2SAudioSpeaker::setup() { this->mark_failed(); return; } - - this->i2s_event_queue_ = xQueueCreate(I2S_EVENT_QUEUE_COUNT, sizeof(i2s_event_t)); - - if (this->i2s_event_queue_ == nullptr) { - ESP_LOGE(TAG, "Failed to create I2S event queue"); - this->mark_failed(); - return; - } } void I2SAudioSpeaker::loop() { @@ -339,7 +331,7 @@ void I2SAudioSpeaker::speaker_task(void *params) { } void I2SAudioSpeaker::start() { - if (this->is_failed() || this->status_has_error()) + if (!this->is_ready() || this->is_failed() || this->status_has_error()) return; if ((this->state_ == speaker::STATE_STARTING) || (this->state_ == speaker::STATE_RUNNING)) return; @@ -519,7 +511,6 @@ void I2SAudioSpeaker::delete_task_(size_t buffer_size) { } xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::STATE_STOPPED); - xQueueReset(this->i2s_event_queue_); this->task_created_ = false; vTaskDelete(nullptr); diff --git a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h index 8b7386ba58..2b90f39399 100644 --- a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h +++ b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h @@ -23,7 +23,7 @@ namespace i2s_audio { class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Component { public: - float get_setup_priority() const override { return esphome::setup_priority::LATE; } + float get_setup_priority() const override { return esphome::setup_priority::PROCESSOR; } void setup() override; void loop() override; From 39c889e6625a212b582d519012c6b69a45862bc6 Mon Sep 17 00:00:00 2001 From: Roving Ronin <108674933+Roving-Ronin@users.noreply.github.com> Date: Thu, 14 Nov 2024 11:43:21 +1100 Subject: [PATCH 012/107] Update UNIT_VOLT_AMPS_REACTIVE = "var" (Currently 'VAR') (#7643) --- esphome/const.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/const.py b/esphome/const.py index d42ee5ee72..6a643e1e30 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -1095,7 +1095,7 @@ UNIT_STEPS = "steps" UNIT_VOLT = "V" UNIT_VOLT_AMPS = "VA" UNIT_VOLT_AMPS_HOURS = "VAh" -UNIT_VOLT_AMPS_REACTIVE = "VAR" +UNIT_VOLT_AMPS_REACTIVE = "var" UNIT_VOLT_AMPS_REACTIVE_HOURS = "VARh" UNIT_WATT = "W" UNIT_WATT_HOURS = "Wh" From d01508885531c31a2ebb518c8b07f550d5768ccc Mon Sep 17 00:00:00 2001 From: Felipe Santos Date: Wed, 13 Nov 2024 21:44:18 -0300 Subject: [PATCH 013/107] Fix reactive power unit of measurement from VAR to var (#7757) Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com> --- esphome/components/sdm_meter/sdm_meter.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/sdm_meter/sdm_meter.cpp b/esphome/components/sdm_meter/sdm_meter.cpp index 9c35d306ad..18e06e2b04 100644 --- a/esphome/components/sdm_meter/sdm_meter.cpp +++ b/esphome/components/sdm_meter/sdm_meter.cpp @@ -38,7 +38,7 @@ void SDMMeter::on_modbus_data(const std::vector &data) { ESP_LOGD( TAG, - "SDMMeter Phase %c: V=%.3f V, I=%.3f A, Active P=%.3f W, Apparent P=%.3f VA, Reactive P=%.3f VAR, PF=%.3f, " + "SDMMeter Phase %c: V=%.3f V, I=%.3f A, Active P=%.3f W, Apparent P=%.3f VA, Reactive P=%.3f var, PF=%.3f, " "PA=%.3f °", i + 'A', voltage, current, active_power, apparent_power, reactive_power, power_factor, phase_angle); if (phase.voltage_sensor_ != nullptr) From 5e62c489b08a70295f3247c19c907de57507e263 Mon Sep 17 00:00:00 2001 From: Jordan Zucker Date: Wed, 13 Nov 2024 16:57:09 -0800 Subject: [PATCH 014/107] Disable bluetooth proxy during update (#7695) Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com> --- esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp | 3 +++ tests/components/esp32_ble_tracker/common.yaml | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp b/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp index 74b4b9aa89..b86d32ee61 100644 --- a/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp +++ b/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp @@ -65,6 +65,9 @@ void ESP32BLETracker::setup() { [this](ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) { if (state == ota::OTA_STARTED) { this->stop_scan(); + for (auto *client : this->clients_) { + client->disconnect(); + } } }); #endif diff --git a/tests/components/esp32_ble_tracker/common.yaml b/tests/components/esp32_ble_tracker/common.yaml index ef23635c9e..018bbb42b3 100644 --- a/tests/components/esp32_ble_tracker/common.yaml +++ b/tests/components/esp32_ble_tracker/common.yaml @@ -39,3 +39,10 @@ esp32_ble_tracker: - then: - lambda: |- ESP_LOGD("ble_auto", "The scan has ended!"); + +wifi: + ssid: MySSID + password: password1 + +ota: + - platform: esphome From 0b51ec2c88793191f8d28fecfe9b514b9195312f Mon Sep 17 00:00:00 2001 From: Fabio Bonelli Date: Thu, 14 Nov 2024 01:57:51 +0100 Subject: [PATCH 015/107] ld2420: fix typo in log message (#7758) --- esphome/components/ld2420/ld2420.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/ld2420/ld2420.cpp b/esphome/components/ld2420/ld2420.cpp index e57fdbc84e..9d628cc14f 100644 --- a/esphome/components/ld2420/ld2420.cpp +++ b/esphome/components/ld2420/ld2420.cpp @@ -180,7 +180,7 @@ void LD2420Component::apply_config_action() { } void LD2420Component::factory_reset_action() { - ESP_LOGCONFIG(TAG, "Setiing factory defaults..."); + ESP_LOGCONFIG(TAG, "Setting factory defaults..."); if (this->set_config_mode(true) == LD2420_ERROR_TIMEOUT) { ESP_LOGE(TAG, "LD2420 module has failed to respond, check baud rate and serial connections."); this->mark_failed(); From 44545a18a0de2724d14e497357a4aea5a8f90d19 Mon Sep 17 00:00:00 2001 From: luar123 <49960470+luar123@users.noreply.github.com> Date: Wed, 13 Nov 2024 01:18:10 +0100 Subject: [PATCH 016/107] Fix temperature and humidity for bme680 with bsec2 (#7728) --- .../components/bme68x_bsec2/bme68x_bsec2.cpp | 95 ++++++++++--------- .../components/bme68x_bsec2/bme68x_bsec2.h | 2 - 2 files changed, 49 insertions(+), 48 deletions(-) diff --git a/esphome/components/bme68x_bsec2/bme68x_bsec2.cpp b/esphome/components/bme68x_bsec2/bme68x_bsec2.cpp index 5425bbd5b7..f83f20f1a5 100644 --- a/esphome/components/bme68x_bsec2/bme68x_bsec2.cpp +++ b/esphome/components/bme68x_bsec2/bme68x_bsec2.cpp @@ -204,11 +204,11 @@ void BME68xBSEC2Component::update_subscription_() { } void BME68xBSEC2Component::run_() { + this->op_mode_ = this->bsec_settings_.op_mode; int64_t curr_time_ns = this->get_time_ns_(); - if (curr_time_ns < this->next_call_ns_) { + if (curr_time_ns < this->bsec_settings_.next_call) { return; } - this->op_mode_ = this->bsec_settings_.op_mode; uint8_t status; ESP_LOGV(TAG, "Performing sensor run"); @@ -219,57 +219,60 @@ void BME68xBSEC2Component::run_() { ESP_LOGW(TAG, "Failed to fetch sensor control settings (BSEC2 error code %d)", this->bsec_status_); return; } - this->next_call_ns_ = this->bsec_settings_.next_call; - if (this->bsec_settings_.trigger_measurement) { - bme68x_get_conf(&bme68x_conf, &this->bme68x_); + switch (this->bsec_settings_.op_mode) { + case BME68X_FORCED_MODE: + bme68x_get_conf(&bme68x_conf, &this->bme68x_); - bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling; - bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling; - bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling; - bme68x_set_conf(&bme68x_conf, &this->bme68x_); + bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling; + bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling; + bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling; + bme68x_set_conf(&bme68x_conf, &this->bme68x_); + this->bme68x_heatr_conf_.enable = BME68X_ENABLE; + this->bme68x_heatr_conf_.heatr_temp = this->bsec_settings_.heater_temperature; + this->bme68x_heatr_conf_.heatr_dur = this->bsec_settings_.heater_duration; + + // status = bme68x_set_op_mode(this->bsec_settings_.op_mode, &this->bme68x_); + status = bme68x_set_heatr_conf(BME68X_FORCED_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); + status = bme68x_set_op_mode(BME68X_FORCED_MODE, &this->bme68x_); + this->op_mode_ = BME68X_FORCED_MODE; + ESP_LOGV(TAG, "Using forced mode"); + + break; + case BME68X_PARALLEL_MODE: + if (this->op_mode_ != this->bsec_settings_.op_mode) { + bme68x_get_conf(&bme68x_conf, &this->bme68x_); + + bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling; + bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling; + bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling; + bme68x_set_conf(&bme68x_conf, &this->bme68x_); - switch (this->bsec_settings_.op_mode) { - case BME68X_FORCED_MODE: this->bme68x_heatr_conf_.enable = BME68X_ENABLE; - this->bme68x_heatr_conf_.heatr_temp = this->bsec_settings_.heater_temperature; - this->bme68x_heatr_conf_.heatr_dur = this->bsec_settings_.heater_duration; + this->bme68x_heatr_conf_.heatr_temp_prof = this->bsec_settings_.heater_temperature_profile; + this->bme68x_heatr_conf_.heatr_dur_prof = this->bsec_settings_.heater_duration_profile; + this->bme68x_heatr_conf_.profile_len = this->bsec_settings_.heater_profile_len; + this->bme68x_heatr_conf_.shared_heatr_dur = + BSEC_TOTAL_HEAT_DUR - + (bme68x_get_meas_dur(BME68X_PARALLEL_MODE, &bme68x_conf, &this->bme68x_) / INT64_C(1000)); - status = bme68x_set_op_mode(this->bsec_settings_.op_mode, &this->bme68x_); - status = bme68x_set_heatr_conf(BME68X_FORCED_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); - status = bme68x_set_op_mode(BME68X_FORCED_MODE, &this->bme68x_); - this->op_mode_ = BME68X_FORCED_MODE; - this->sleep_mode_ = false; - ESP_LOGV(TAG, "Using forced mode"); + status = bme68x_set_heatr_conf(BME68X_PARALLEL_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); - break; - case BME68X_PARALLEL_MODE: - if (this->op_mode_ != this->bsec_settings_.op_mode) { - this->bme68x_heatr_conf_.enable = BME68X_ENABLE; - this->bme68x_heatr_conf_.heatr_temp_prof = this->bsec_settings_.heater_temperature_profile; - this->bme68x_heatr_conf_.heatr_dur_prof = this->bsec_settings_.heater_duration_profile; - this->bme68x_heatr_conf_.profile_len = this->bsec_settings_.heater_profile_len; - this->bme68x_heatr_conf_.shared_heatr_dur = - BSEC_TOTAL_HEAT_DUR - - (bme68x_get_meas_dur(BME68X_PARALLEL_MODE, &bme68x_conf, &this->bme68x_) / INT64_C(1000)); - - status = bme68x_set_heatr_conf(BME68X_PARALLEL_MODE, &this->bme68x_heatr_conf_, &this->bme68x_); - - status = bme68x_set_op_mode(BME68X_PARALLEL_MODE, &this->bme68x_); - this->op_mode_ = BME68X_PARALLEL_MODE; - this->sleep_mode_ = false; - ESP_LOGV(TAG, "Using parallel mode"); - } - break; - case BME68X_SLEEP_MODE: - if (!this->sleep_mode_) { - bme68x_set_op_mode(BME68X_SLEEP_MODE, &this->bme68x_); - this->sleep_mode_ = true; - ESP_LOGV(TAG, "Using sleep mode"); - } - break; - } + status = bme68x_set_op_mode(BME68X_PARALLEL_MODE, &this->bme68x_); + this->op_mode_ = BME68X_PARALLEL_MODE; + ESP_LOGV(TAG, "Using parallel mode"); + } + break; + case BME68X_SLEEP_MODE: + if (this->op_mode_ != this->bsec_settings_.op_mode) { + bme68x_set_op_mode(BME68X_SLEEP_MODE, &this->bme68x_); + this->op_mode_ = BME68X_SLEEP_MODE; + ESP_LOGV(TAG, "Using sleep mode"); + } + break; + } + if (this->bsec_settings_.trigger_measurement && this->bsec_settings_.op_mode != BME68X_SLEEP_MODE) { uint32_t meas_dur = 0; meas_dur = bme68x_get_meas_dur(this->op_mode_, &bme68x_conf, &this->bme68x_); ESP_LOGV(TAG, "Queueing read in %uus", meas_dur); diff --git a/esphome/components/bme68x_bsec2/bme68x_bsec2.h b/esphome/components/bme68x_bsec2/bme68x_bsec2.h index 7b9db2b7bf..86d3e5dfbf 100644 --- a/esphome/components/bme68x_bsec2/bme68x_bsec2.h +++ b/esphome/components/bme68x_bsec2/bme68x_bsec2.h @@ -113,13 +113,11 @@ class BME68xBSEC2Component : public Component { struct bme68x_heatr_conf bme68x_heatr_conf_; uint8_t op_mode_; // operating mode of sensor - bool sleep_mode_; bsec_library_return_t bsec_status_{BSEC_OK}; int8_t bme68x_status_{BME68X_OK}; int64_t last_time_ms_{0}; uint32_t millis_overflow_counter_{0}; - int64_t next_call_ns_{0}; std::queue> queue_; From a0159a274662b22a3c791961742cdf019894f041 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Wed, 13 Nov 2024 12:39:02 -0500 Subject: [PATCH 017/107] [i2s_audio] Bugfix: Adjust I2S speaker setup priority (#7759) --- .../i2s_audio/speaker/i2s_audio_speaker.cpp | 11 +---------- .../components/i2s_audio/speaker/i2s_audio_speaker.h | 2 +- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp index c3f4566411..53b3cc8dc0 100644 --- a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp +++ b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp @@ -99,14 +99,6 @@ void I2SAudioSpeaker::setup() { this->mark_failed(); return; } - - this->i2s_event_queue_ = xQueueCreate(I2S_EVENT_QUEUE_COUNT, sizeof(i2s_event_t)); - - if (this->i2s_event_queue_ == nullptr) { - ESP_LOGE(TAG, "Failed to create I2S event queue"); - this->mark_failed(); - return; - } } void I2SAudioSpeaker::loop() { @@ -339,7 +331,7 @@ void I2SAudioSpeaker::speaker_task(void *params) { } void I2SAudioSpeaker::start() { - if (this->is_failed() || this->status_has_error()) + if (!this->is_ready() || this->is_failed() || this->status_has_error()) return; if ((this->state_ == speaker::STATE_STARTING) || (this->state_ == speaker::STATE_RUNNING)) return; @@ -519,7 +511,6 @@ void I2SAudioSpeaker::delete_task_(size_t buffer_size) { } xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::STATE_STOPPED); - xQueueReset(this->i2s_event_queue_); this->task_created_ = false; vTaskDelete(nullptr); diff --git a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h index 8b7386ba58..2b90f39399 100644 --- a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h +++ b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h @@ -23,7 +23,7 @@ namespace i2s_audio { class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Component { public: - float get_setup_priority() const override { return esphome::setup_priority::LATE; } + float get_setup_priority() const override { return esphome::setup_priority::PROCESSOR; } void setup() override; void loop() override; From 15bfc4c91f5c567dc89fd3daced0db0339ee85ff Mon Sep 17 00:00:00 2001 From: Roving Ronin <108674933+Roving-Ronin@users.noreply.github.com> Date: Thu, 14 Nov 2024 11:43:21 +1100 Subject: [PATCH 018/107] Update UNIT_VOLT_AMPS_REACTIVE = "var" (Currently 'VAR') (#7643) --- esphome/const.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/const.py b/esphome/const.py index c3c8712677..bb0100d348 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -1095,7 +1095,7 @@ UNIT_STEPS = "steps" UNIT_VOLT = "V" UNIT_VOLT_AMPS = "VA" UNIT_VOLT_AMPS_HOURS = "VAh" -UNIT_VOLT_AMPS_REACTIVE = "VAR" +UNIT_VOLT_AMPS_REACTIVE = "var" UNIT_VOLT_AMPS_REACTIVE_HOURS = "VARh" UNIT_WATT = "W" UNIT_WATT_HOURS = "Wh" From 9bc7b74d0137aa351c906e0c38a913afa5835fee Mon Sep 17 00:00:00 2001 From: Felipe Santos Date: Wed, 13 Nov 2024 21:44:18 -0300 Subject: [PATCH 019/107] Fix reactive power unit of measurement from VAR to var (#7757) Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com> --- esphome/components/sdm_meter/sdm_meter.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/sdm_meter/sdm_meter.cpp b/esphome/components/sdm_meter/sdm_meter.cpp index 9c35d306ad..18e06e2b04 100644 --- a/esphome/components/sdm_meter/sdm_meter.cpp +++ b/esphome/components/sdm_meter/sdm_meter.cpp @@ -38,7 +38,7 @@ void SDMMeter::on_modbus_data(const std::vector &data) { ESP_LOGD( TAG, - "SDMMeter Phase %c: V=%.3f V, I=%.3f A, Active P=%.3f W, Apparent P=%.3f VA, Reactive P=%.3f VAR, PF=%.3f, " + "SDMMeter Phase %c: V=%.3f V, I=%.3f A, Active P=%.3f W, Apparent P=%.3f VA, Reactive P=%.3f var, PF=%.3f, " "PA=%.3f °", i + 'A', voltage, current, active_power, apparent_power, reactive_power, power_factor, phase_angle); if (phase.voltage_sensor_ != nullptr) From 67a4e56fcfd7bfd8017c179c8004e6f0c67920d3 Mon Sep 17 00:00:00 2001 From: Jordan Zucker Date: Wed, 13 Nov 2024 16:57:09 -0800 Subject: [PATCH 020/107] Disable bluetooth proxy during update (#7695) Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com> --- esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp | 3 +++ tests/components/esp32_ble_tracker/common.yaml | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp b/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp index 74b4b9aa89..b86d32ee61 100644 --- a/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp +++ b/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp @@ -65,6 +65,9 @@ void ESP32BLETracker::setup() { [this](ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) { if (state == ota::OTA_STARTED) { this->stop_scan(); + for (auto *client : this->clients_) { + client->disconnect(); + } } }); #endif diff --git a/tests/components/esp32_ble_tracker/common.yaml b/tests/components/esp32_ble_tracker/common.yaml index ef23635c9e..018bbb42b3 100644 --- a/tests/components/esp32_ble_tracker/common.yaml +++ b/tests/components/esp32_ble_tracker/common.yaml @@ -39,3 +39,10 @@ esp32_ble_tracker: - then: - lambda: |- ESP_LOGD("ble_auto", "The scan has ended!"); + +wifi: + ssid: MySSID + password: password1 + +ota: + - platform: esphome From 754352b4d7e717fa04615ff9ee86d43955ceaaa8 Mon Sep 17 00:00:00 2001 From: Fabio Bonelli Date: Thu, 14 Nov 2024 01:57:51 +0100 Subject: [PATCH 021/107] ld2420: fix typo in log message (#7758) --- esphome/components/ld2420/ld2420.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/ld2420/ld2420.cpp b/esphome/components/ld2420/ld2420.cpp index e57fdbc84e..9d628cc14f 100644 --- a/esphome/components/ld2420/ld2420.cpp +++ b/esphome/components/ld2420/ld2420.cpp @@ -180,7 +180,7 @@ void LD2420Component::apply_config_action() { } void LD2420Component::factory_reset_action() { - ESP_LOGCONFIG(TAG, "Setiing factory defaults..."); + ESP_LOGCONFIG(TAG, "Setting factory defaults..."); if (this->set_config_mode(true) == LD2420_ERROR_TIMEOUT) { ESP_LOGE(TAG, "LD2420 module has failed to respond, check baud rate and serial connections."); this->mark_failed(); From f4dc11477fb62014bc4397acdfbce61bfa57a90a Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Thu, 14 Nov 2024 14:21:43 +1300 Subject: [PATCH 022/107] Bump version to 2024.11.0b2 --- esphome/const.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/const.py b/esphome/const.py index bb0100d348..51c8090e91 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -1,6 +1,6 @@ """Constants used by esphome.""" -__version__ = "2024.11.0b1" +__version__ = "2024.11.0b2" ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_" VALID_SUBSTITUTIONS_CHARACTERS = ( From b29c1194089f4770b7a3e9ab99b12ac890c3e2cb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 15 Nov 2024 12:43:52 +0100 Subject: [PATCH 023/107] Bump codecov/codecov-action from 4 to 5 (#7771) Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 82a55d0e2a..f5af3ec9e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -219,7 +219,7 @@ jobs: . venv/bin/activate pytest -vv --cov-report=xml --tb=native tests - name: Upload coverage to Codecov - uses: codecov/codecov-action@v4 + uses: codecov/codecov-action@v5 with: token: ${{ secrets.CODECOV_TOKEN }} From e81191ebd2583d44b4237db8b7dad3ed18877d0d Mon Sep 17 00:00:00 2001 From: pethans <38168907+pethans@users.noreply.github.com> Date: Sun, 17 Nov 2024 10:47:29 -0800 Subject: [PATCH 024/107] TuyaFan control should use oscillation_type (#7776) Co-authored-by: Peter Hanson --- esphome/components/tuya/fan/tuya_fan.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/tuya/fan/tuya_fan.cpp b/esphome/components/tuya/fan/tuya_fan.cpp index 8a613d0bae..9b132e0de6 100644 --- a/esphome/components/tuya/fan/tuya_fan.cpp +++ b/esphome/components/tuya/fan/tuya_fan.cpp @@ -86,7 +86,7 @@ void TuyaFan::control(const fan::FanCall &call) { if (this->oscillation_id_.has_value() && call.get_oscillating().has_value()) { if (this->oscillation_type_ == TuyaDatapointType::ENUM) { this->parent_->set_enum_datapoint_value(*this->oscillation_id_, *call.get_oscillating()); - } else if (this->speed_type_ == TuyaDatapointType::BOOLEAN) { + } else if (this->oscillation_type_ == TuyaDatapointType::BOOLEAN) { this->parent_->set_boolean_datapoint_value(*this->oscillation_id_, *call.get_oscillating()); } } From 6e41c22e9d7f777a5c556725b1a54cf33a669e39 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Mon, 18 Nov 2024 20:44:39 +1300 Subject: [PATCH 025/107] Bump esphome-dashboard to 20241118.0 (#7782) --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index e11e629743..4bea8cf4ef 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,7 +12,7 @@ pyserial==3.5 platformio==6.1.16 # When updating platformio, also update Dockerfile esptool==4.7.0 click==8.1.7 -esphome-dashboard==20241025.0 +esphome-dashboard==20241118.0 aioesphomeapi==24.6.2 zeroconf==0.132.2 puremagic==1.27 From 50aeefc66299f675f62a9eb09a77ceded7c61950 Mon Sep 17 00:00:00 2001 From: pethans <38168907+pethans@users.noreply.github.com> Date: Sun, 17 Nov 2024 10:47:29 -0800 Subject: [PATCH 026/107] TuyaFan control should use oscillation_type (#7776) Co-authored-by: Peter Hanson --- esphome/components/tuya/fan/tuya_fan.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/tuya/fan/tuya_fan.cpp b/esphome/components/tuya/fan/tuya_fan.cpp index 8a613d0bae..9b132e0de6 100644 --- a/esphome/components/tuya/fan/tuya_fan.cpp +++ b/esphome/components/tuya/fan/tuya_fan.cpp @@ -86,7 +86,7 @@ void TuyaFan::control(const fan::FanCall &call) { if (this->oscillation_id_.has_value() && call.get_oscillating().has_value()) { if (this->oscillation_type_ == TuyaDatapointType::ENUM) { this->parent_->set_enum_datapoint_value(*this->oscillation_id_, *call.get_oscillating()); - } else if (this->speed_type_ == TuyaDatapointType::BOOLEAN) { + } else if (this->oscillation_type_ == TuyaDatapointType::BOOLEAN) { this->parent_->set_boolean_datapoint_value(*this->oscillation_id_, *call.get_oscillating()); } } From 585586780bf2fe6645eff64ed9528da8bd57e042 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Mon, 18 Nov 2024 20:44:39 +1300 Subject: [PATCH 027/107] Bump esphome-dashboard to 20241118.0 (#7782) --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index e11e629743..4bea8cf4ef 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,7 +12,7 @@ pyserial==3.5 platformio==6.1.16 # When updating platformio, also update Dockerfile esptool==4.7.0 click==8.1.7 -esphome-dashboard==20241025.0 +esphome-dashboard==20241118.0 aioesphomeapi==24.6.2 zeroconf==0.132.2 puremagic==1.27 From 1ed27b7cc0556679344f8fbe5101f1e338cc21a0 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Tue, 19 Nov 2024 09:04:30 +1300 Subject: [PATCH 028/107] Bump version to 2024.11.0b3 --- esphome/const.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/const.py b/esphome/const.py index 51c8090e91..e7edd8337e 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -1,6 +1,6 @@ """Constants used by esphome.""" -__version__ = "2024.11.0b2" +__version__ = "2024.11.0b3" ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_" VALID_SUBSTITUTIONS_CHARACTERS = ( From 49e9c4333979bfeae77f25ee32c3065bc610b7a5 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Wed, 20 Nov 2024 13:54:19 +1300 Subject: [PATCH 029/107] [http_request] Feed watchdog timeout around http request functions (#7786) --- esphome/components/http_request/http_request_arduino.cpp | 2 ++ esphome/components/http_request/http_request_idf.cpp | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/esphome/components/http_request/http_request_arduino.cpp b/esphome/components/http_request/http_request_arduino.cpp index af1eb6f459..85a1312aaa 100644 --- a/esphome/components/http_request/http_request_arduino.cpp +++ b/esphome/components/http_request/http_request_arduino.cpp @@ -104,7 +104,9 @@ std::shared_ptr HttpRequestArduino::start(std::string url, std::s static const size_t HEADER_COUNT = sizeof(header_keys) / sizeof(header_keys[0]); container->client_.collectHeaders(header_keys, HEADER_COUNT); + App.feed_wdt(); container->status_code = container->client_.sendRequest(method.c_str(), body.c_str()); + App.feed_wdt(); if (container->status_code < 0) { ESP_LOGW(TAG, "HTTP Request failed; URL: %s; Error: %s", url.c_str(), HTTPClient::errorToString(container->status_code).c_str()); diff --git a/esphome/components/http_request/http_request_idf.cpp b/esphome/components/http_request/http_request_idf.cpp index c6c567b620..b449f046ee 100644 --- a/esphome/components/http_request/http_request_idf.cpp +++ b/esphome/components/http_request/http_request_idf.cpp @@ -117,8 +117,11 @@ std::shared_ptr HttpRequestIDF::start(std::string url, std::strin return nullptr; } + App.feed_wdt(); container->content_length = esp_http_client_fetch_headers(client); + App.feed_wdt(); container->status_code = esp_http_client_get_status_code(client); + App.feed_wdt(); if (is_success(container->status_code)) { container->duration_ms = millis() - start; return container; @@ -148,8 +151,11 @@ std::shared_ptr HttpRequestIDF::start(std::string url, std::strin return nullptr; } + App.feed_wdt(); container->content_length = esp_http_client_fetch_headers(client); + App.feed_wdt(); container->status_code = esp_http_client_get_status_code(client); + App.feed_wdt(); if (is_success(container->status_code)) { container->duration_ms = millis() - start; return container; From cf63d627fee4224f3652a0d101fae4cad1039da4 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Wed, 20 Nov 2024 17:39:28 +1300 Subject: [PATCH 030/107] Bump esphome-dashboard to 20241120.0 (#7787) --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 4bea8cf4ef..7bc1c895df 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,7 +12,7 @@ pyserial==3.5 platformio==6.1.16 # When updating platformio, also update Dockerfile esptool==4.7.0 click==8.1.7 -esphome-dashboard==20241118.0 +esphome-dashboard==20241120.0 aioesphomeapi==24.6.2 zeroconf==0.132.2 puremagic==1.27 From eb8a2326ad2a9f32c52c94b52fbb3dfb4090c6c2 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Wed, 20 Nov 2024 13:54:19 +1300 Subject: [PATCH 031/107] [http_request] Feed watchdog timeout around http request functions (#7786) --- esphome/components/http_request/http_request_arduino.cpp | 2 ++ esphome/components/http_request/http_request_idf.cpp | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/esphome/components/http_request/http_request_arduino.cpp b/esphome/components/http_request/http_request_arduino.cpp index af1eb6f459..85a1312aaa 100644 --- a/esphome/components/http_request/http_request_arduino.cpp +++ b/esphome/components/http_request/http_request_arduino.cpp @@ -104,7 +104,9 @@ std::shared_ptr HttpRequestArduino::start(std::string url, std::s static const size_t HEADER_COUNT = sizeof(header_keys) / sizeof(header_keys[0]); container->client_.collectHeaders(header_keys, HEADER_COUNT); + App.feed_wdt(); container->status_code = container->client_.sendRequest(method.c_str(), body.c_str()); + App.feed_wdt(); if (container->status_code < 0) { ESP_LOGW(TAG, "HTTP Request failed; URL: %s; Error: %s", url.c_str(), HTTPClient::errorToString(container->status_code).c_str()); diff --git a/esphome/components/http_request/http_request_idf.cpp b/esphome/components/http_request/http_request_idf.cpp index c6c567b620..b449f046ee 100644 --- a/esphome/components/http_request/http_request_idf.cpp +++ b/esphome/components/http_request/http_request_idf.cpp @@ -117,8 +117,11 @@ std::shared_ptr HttpRequestIDF::start(std::string url, std::strin return nullptr; } + App.feed_wdt(); container->content_length = esp_http_client_fetch_headers(client); + App.feed_wdt(); container->status_code = esp_http_client_get_status_code(client); + App.feed_wdt(); if (is_success(container->status_code)) { container->duration_ms = millis() - start; return container; @@ -148,8 +151,11 @@ std::shared_ptr HttpRequestIDF::start(std::string url, std::strin return nullptr; } + App.feed_wdt(); container->content_length = esp_http_client_fetch_headers(client); + App.feed_wdt(); container->status_code = esp_http_client_get_status_code(client); + App.feed_wdt(); if (is_success(container->status_code)) { container->duration_ms = millis() - start; return container; From 872b8ee753ef5799894289ac941392383145d1d7 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Wed, 20 Nov 2024 17:39:28 +1300 Subject: [PATCH 032/107] Bump esphome-dashboard to 20241120.0 (#7787) --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 4bea8cf4ef..7bc1c895df 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,7 +12,7 @@ pyserial==3.5 platformio==6.1.16 # When updating platformio, also update Dockerfile esptool==4.7.0 click==8.1.7 -esphome-dashboard==20241118.0 +esphome-dashboard==20241120.0 aioesphomeapi==24.6.2 zeroconf==0.132.2 puremagic==1.27 From ae46dcef7e51eb148dd0858834b02dc855979a1b Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Wed, 20 Nov 2024 17:50:30 +1300 Subject: [PATCH 033/107] Bump version to 2024.11.0b4 --- esphome/const.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/const.py b/esphome/const.py index e7edd8337e..659695465e 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -1,6 +1,6 @@ """Constants used by esphome.""" -__version__ = "2024.11.0b3" +__version__ = "2024.11.0b4" ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_" VALID_SUBSTITUTIONS_CHARACTERS = ( From ef78c404dd19bb35af412a9dab0bd8e294cd7469 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Wed, 20 Nov 2024 21:29:42 +1300 Subject: [PATCH 034/107] Bump version to 2024.11.0 --- esphome/const.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/const.py b/esphome/const.py index 659695465e..408dc52869 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -1,6 +1,6 @@ """Constants used by esphome.""" -__version__ = "2024.11.0b4" +__version__ = "2024.11.0" ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_" VALID_SUBSTITUTIONS_CHARACTERS = ( From 372d68a177196d6efb688b9f15943c5fd05dd202 Mon Sep 17 00:00:00 2001 From: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com> Date: Wed, 20 Nov 2024 13:27:23 -0500 Subject: [PATCH 035/107] [remote_base] Fix extra comma in dump raw (#7774) Co-authored-by: Jonathan Swoboda --- esphome/components/remote_base/raw_protocol.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/remote_base/raw_protocol.cpp b/esphome/components/remote_base/raw_protocol.cpp index bdeb935dc4..ef0cb8454e 100644 --- a/esphome/components/remote_base/raw_protocol.cpp +++ b/esphome/components/remote_base/raw_protocol.cpp @@ -28,7 +28,7 @@ bool RawDumper::dump(RemoteReceiveData src) { ESP_LOGI(TAG, "%s", buffer); buffer_offset = 0; written = sprintf(buffer, " "); - if (i + 1 < src.size()) { + if (i + 1 < src.size() - 1) { written += sprintf(buffer + written, "%" PRId32 ", ", value); } else { written += sprintf(buffer + written, "%" PRId32, value); From 846b091aacbe72078996cd0c89419a40c32cb1f8 Mon Sep 17 00:00:00 2001 From: Edward Firmo <94725493+edwardtfn@users.noreply.github.com> Date: Wed, 20 Nov 2024 19:28:21 +0100 Subject: [PATCH 036/107] [nextion] New trigger `on_buffer_overflow` (#7772) --- esphome/components/nextion/automation.h | 7 +++++++ esphome/components/nextion/base_component.py | 1 + esphome/components/nextion/display.py | 15 +++++++++++++++ esphome/components/nextion/nextion.cpp | 8 +++++++- esphome/components/nextion/nextion.h | 7 +++++++ tests/components/nextion/test.esp32-ard.yaml | 3 +++ tests/components/nextion/test.esp32-c3-ard.yaml | 3 +++ tests/components/nextion/test.esp32-c3-idf.yaml | 3 +++ tests/components/nextion/test.esp32-idf.yaml | 3 +++ tests/components/nextion/test.esp8266-ard.yaml | 3 +++ tests/components/nextion/test.rp2040-ard.yaml | 3 +++ 11 files changed, 55 insertions(+), 1 deletion(-) diff --git a/esphome/components/nextion/automation.h b/esphome/components/nextion/automation.h index f51fe6b4f8..5182e07229 100644 --- a/esphome/components/nextion/automation.h +++ b/esphome/components/nextion/automation.h @@ -42,5 +42,12 @@ class TouchTrigger : public Trigger { } }; +class BufferOverflowTrigger : public Trigger<> { + public: + explicit BufferOverflowTrigger(Nextion *nextion) { + nextion->add_buffer_overflow_event_callback([this]() { this->trigger(); }); + } +}; + } // namespace nextion } // namespace esphome diff --git a/esphome/components/nextion/base_component.py b/esphome/components/nextion/base_component.py index 2924f66d3c..9708379861 100644 --- a/esphome/components/nextion/base_component.py +++ b/esphome/components/nextion/base_component.py @@ -18,6 +18,7 @@ CONF_ON_SLEEP = "on_sleep" CONF_ON_WAKE = "on_wake" CONF_ON_SETUP = "on_setup" CONF_ON_PAGE = "on_page" +CONF_ON_BUFFER_OVERFLOW = "on_buffer_overflow" CONF_TOUCH_SLEEP_TIMEOUT = "touch_sleep_timeout" CONF_WAKE_UP_PAGE = "wake_up_page" CONF_START_UP_PAGE = "start_up_page" diff --git a/esphome/components/nextion/display.py b/esphome/components/nextion/display.py index e403ba7ae8..6f284376af 100644 --- a/esphome/components/nextion/display.py +++ b/esphome/components/nextion/display.py @@ -13,6 +13,7 @@ from esphome.const import ( from esphome.core import CORE from . import Nextion, nextion_ns, nextion_ref from .base_component import ( + CONF_ON_BUFFER_OVERFLOW, CONF_ON_SLEEP, CONF_ON_WAKE, CONF_ON_SETUP, @@ -36,6 +37,9 @@ SleepTrigger = nextion_ns.class_("SleepTrigger", automation.Trigger.template()) WakeTrigger = nextion_ns.class_("WakeTrigger", automation.Trigger.template()) PageTrigger = nextion_ns.class_("PageTrigger", automation.Trigger.template()) TouchTrigger = nextion_ns.class_("TouchTrigger", automation.Trigger.template()) +BufferOverflowTrigger = nextion_ns.class_( + "BufferOverflowTrigger", automation.Trigger.template() +) CONFIG_SCHEMA = ( display.BASIC_DISPLAY_SCHEMA.extend( @@ -68,6 +72,13 @@ CONFIG_SCHEMA = ( cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(TouchTrigger), } ), + cv.Optional(CONF_ON_BUFFER_OVERFLOW): automation.validate_automation( + { + cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id( + BufferOverflowTrigger + ), + } + ), cv.Optional(CONF_TOUCH_SLEEP_TIMEOUT): cv.int_range(min=3, max=65535), cv.Optional(CONF_WAKE_UP_PAGE): cv.uint8_t, cv.Optional(CONF_START_UP_PAGE): cv.uint8_t, @@ -151,3 +162,7 @@ async def to_code(config): ], conf, ) + + for conf in config.get(CONF_ON_BUFFER_OVERFLOW, []): + trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) + await automation.build_automation(trigger, [], conf) diff --git a/esphome/components/nextion/nextion.cpp b/esphome/components/nextion/nextion.cpp index a80f6efc91..984db09c57 100644 --- a/esphome/components/nextion/nextion.cpp +++ b/esphome/components/nextion/nextion.cpp @@ -190,6 +190,10 @@ void Nextion::add_touch_event_callback(std::functiontouch_callback_.add(std::move(callback)); } +void Nextion::add_buffer_overflow_event_callback(std::function &&callback) { + this->buffer_overflow_callback_.add(std::move(callback)); +} + void Nextion::update_all_components() { if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping()) return; @@ -458,7 +462,9 @@ void Nextion::process_nextion_commands_() { this->remove_from_q_(); break; case 0x24: // Serial Buffer overflow occurs - ESP_LOGW(TAG, "Nextion reported Serial Buffer overflow!"); + // Buffer will continue to receive the current instruction, all previous instructions are lost. + ESP_LOGE(TAG, "Nextion reported Serial Buffer overflow!"); + this->buffer_overflow_callback_.call(); break; case 0x65: { // touch event return data if (to_process_length != 3) { diff --git a/esphome/components/nextion/nextion.h b/esphome/components/nextion/nextion.h index 732ee9b455..f539c79718 100644 --- a/esphome/components/nextion/nextion.h +++ b/esphome/components/nextion/nextion.h @@ -1134,6 +1134,12 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe */ void add_touch_event_callback(std::function &&callback); + /** Add a callback to be notified when the nextion reports a buffer overflow. + * + * @param callback The void() callback. + */ + void add_buffer_overflow_event_callback(std::function &&callback); + void update_all_components(); /** @@ -1323,6 +1329,7 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe CallbackManager wake_callback_{}; CallbackManager page_callback_{}; CallbackManager touch_callback_{}; + CallbackManager buffer_overflow_callback_{}; optional writer_; float brightness_{1.0}; diff --git a/tests/components/nextion/test.esp32-ard.yaml b/tests/components/nextion/test.esp32-ard.yaml index 27568ebc2a..ba76236fc6 100644 --- a/tests/components/nextion/test.esp32-ard.yaml +++ b/tests/components/nextion/test.esp32-ard.yaml @@ -58,3 +58,6 @@ display: on_page: then: lambda: 'ESP_LOGD("display","Display shows new page %u", x);' + on_buffer_overflow: + then: + logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.esp32-c3-ard.yaml b/tests/components/nextion/test.esp32-c3-ard.yaml index 5881d6e165..5d253268f8 100644 --- a/tests/components/nextion/test.esp32-c3-ard.yaml +++ b/tests/components/nextion/test.esp32-c3-ard.yaml @@ -58,3 +58,6 @@ display: on_page: then: lambda: 'ESP_LOGD("display","Display shows new page %u", x);' + on_buffer_overflow: + then: + logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.esp32-c3-idf.yaml b/tests/components/nextion/test.esp32-c3-idf.yaml index 5881d6e165..5d253268f8 100644 --- a/tests/components/nextion/test.esp32-c3-idf.yaml +++ b/tests/components/nextion/test.esp32-c3-idf.yaml @@ -58,3 +58,6 @@ display: on_page: then: lambda: 'ESP_LOGD("display","Display shows new page %u", x);' + on_buffer_overflow: + then: + logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.esp32-idf.yaml b/tests/components/nextion/test.esp32-idf.yaml index 27568ebc2a..ba76236fc6 100644 --- a/tests/components/nextion/test.esp32-idf.yaml +++ b/tests/components/nextion/test.esp32-idf.yaml @@ -58,3 +58,6 @@ display: on_page: then: lambda: 'ESP_LOGD("display","Display shows new page %u", x);' + on_buffer_overflow: + then: + logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.esp8266-ard.yaml b/tests/components/nextion/test.esp8266-ard.yaml index 5881d6e165..5d253268f8 100644 --- a/tests/components/nextion/test.esp8266-ard.yaml +++ b/tests/components/nextion/test.esp8266-ard.yaml @@ -58,3 +58,6 @@ display: on_page: then: lambda: 'ESP_LOGD("display","Display shows new page %u", x);' + on_buffer_overflow: + then: + logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.rp2040-ard.yaml b/tests/components/nextion/test.rp2040-ard.yaml index a1c5848ce6..9b04433095 100644 --- a/tests/components/nextion/test.rp2040-ard.yaml +++ b/tests/components/nextion/test.rp2040-ard.yaml @@ -53,3 +53,6 @@ display: on_page: then: lambda: 'ESP_LOGD("display","Display shows new page %u", x);' + on_buffer_overflow: + then: + logger.log: "Nextion reported a buffer overflow!" From 5e27a8df1f5fc3978939521d421d6330d1296128 Mon Sep 17 00:00:00 2001 From: Kjell Braden Date: Wed, 20 Nov 2024 19:29:48 +0100 Subject: [PATCH 037/107] enable rp2040 for online_image (#7769) --- esphome/components/online_image/__init__.py | 1 + .../online_image/common-rp2040.yaml | 19 +++++++++++++++++++ .../online_image/test.rp2040-ard.yaml | 4 ++++ 3 files changed, 24 insertions(+) create mode 100644 tests/components/online_image/common-rp2040.yaml create mode 100644 tests/components/online_image/test.rp2040-ard.yaml diff --git a/esphome/components/online_image/__init__.py b/esphome/components/online_image/__init__.py index dfb10137aa..be1bfb4a00 100644 --- a/esphome/components/online_image/__init__.py +++ b/esphome/components/online_image/__init__.py @@ -98,6 +98,7 @@ CONFIG_SCHEMA = cv.Schema( # esp8266_arduino=cv.Version(2, 7, 0), esp32_arduino=cv.Version(0, 0, 0), esp_idf=cv.Version(4, 0, 0), + rp2040_arduino=cv.Version(0, 0, 0), ), ) ) diff --git a/tests/components/online_image/common-rp2040.yaml b/tests/components/online_image/common-rp2040.yaml new file mode 100644 index 0000000000..16bb2b2c44 --- /dev/null +++ b/tests/components/online_image/common-rp2040.yaml @@ -0,0 +1,19 @@ +<<: !include common.yaml + +spi: + - id: spi_main_lcd + clk_pin: 18 + mosi_pin: 19 + miso_pin: 16 + +display: + - platform: ili9xxx + id: main_lcd + model: ili9342 + cs_pin: 20 + dc_pin: 17 + reset_pin: 21 + invert_colors: true + lambda: |- + it.fill(Color(0, 0, 0)); + it.image(0, 0, id(online_rgba_image)); diff --git a/tests/components/online_image/test.rp2040-ard.yaml b/tests/components/online_image/test.rp2040-ard.yaml new file mode 100644 index 0000000000..d10f36b4e9 --- /dev/null +++ b/tests/components/online_image/test.rp2040-ard.yaml @@ -0,0 +1,4 @@ +<<: !include common-rp2040.yaml + +http_request: + verify_ssl: false From 6d4f787f67b6d4dc16fcdbdca3a1984db8d9df62 Mon Sep 17 00:00:00 2001 From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com> Date: Thu, 21 Nov 2024 11:10:28 +1100 Subject: [PATCH 038/107] [http_request] Fix within context with parameters. (Bugfix) (#7790) --- esphome/components/http_request/http_request.h | 2 +- tests/components/http_request/common.yaml | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/esphome/components/http_request/http_request.h b/esphome/components/http_request/http_request.h index 4ed2c834f8..b2ce718ec4 100644 --- a/esphome/components/http_request/http_request.h +++ b/esphome/components/http_request/http_request.h @@ -189,7 +189,7 @@ template class HttpRequestSendAction : public Action { if (container == nullptr) { for (auto *trigger : this->error_triggers_) - trigger->trigger(x...); + trigger->trigger(); return; } diff --git a/tests/components/http_request/common.yaml b/tests/components/http_request/common.yaml index 593b85e435..8408f27a05 100644 --- a/tests/components/http_request/common.yaml +++ b/tests/components/http_request/common.yaml @@ -39,6 +39,14 @@ http_request: timeout: 10s verify_ssl: ${verify_ssl} +script: + - id: does_not_compile + parameters: + api_url: string + then: + - http_request.get: + url: "http://google.com" + ota: - platform: http_request on_begin: From fbb9967117d248951906b0bb19ef200e7f546360 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Thu, 21 Nov 2024 19:22:02 +1300 Subject: [PATCH 039/107] [rtttl] Clamp gain between 0 and 1 (#7793) --- esphome/components/rtttl/rtttl.h | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/esphome/components/rtttl/rtttl.h b/esphome/components/rtttl/rtttl.h index 10c290c5fb..420948bfbf 100644 --- a/esphome/components/rtttl/rtttl.h +++ b/esphome/components/rtttl/rtttl.h @@ -40,13 +40,7 @@ class Rtttl : public Component { void set_speaker(speaker::Speaker *speaker) { this->speaker_ = speaker; } #endif float get_gain() { return gain_; } - void set_gain(float gain) { - if (gain < 0.1f) - gain = 0.1f; - if (gain > 1.0f) - gain = 1.0f; - this->gain_ = gain; - } + void set_gain(float gain) { this->gain_ = clamp(gain, 0.0f, 1.0f); } void play(std::string rtttl); void stop(); void dump_config() override; From 6bcbbcce02ca9441cffe6d7f559eceb92ab76811 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Thu, 21 Nov 2024 21:10:20 +1300 Subject: [PATCH 040/107] [speaker] Add missing auto-load for ``audio`` (#7794) --- esphome/components/speaker/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/esphome/components/speaker/__init__.py b/esphome/components/speaker/__init__.py index 7a668dc2f3..948fe4b534 100644 --- a/esphome/components/speaker/__init__.py +++ b/esphome/components/speaker/__init__.py @@ -7,6 +7,7 @@ from esphome.const import CONF_DATA, CONF_ID, CONF_VOLUME from esphome.core import CORE from esphome.coroutine import coroutine_with_priority +AUTO_LOAD = ["audio"] CODEOWNERS = ["@jesserockz", "@kahrendt"] IS_PLATFORM_COMPONENT = True From 03ae6b2c1b6e4ae2a509c109c2381214e0cdb131 Mon Sep 17 00:00:00 2001 From: Manuel Kasper Date: Thu, 21 Nov 2024 10:46:49 +0100 Subject: [PATCH 041/107] [qspi_dbi] Fix garbled graphics on RM690B0 (#7795) --- esphome/components/qspi_dbi/models.py | 1 + 1 file changed, 1 insertion(+) diff --git a/esphome/components/qspi_dbi/models.py b/esphome/components/qspi_dbi/models.py index 071ea72d73..cbd9c4663f 100644 --- a/esphome/components/qspi_dbi/models.py +++ b/esphome/components/qspi_dbi/models.py @@ -55,6 +55,7 @@ chip.cmd(PAGESEL, 0x00) chip.cmd(0xC2, 0x00) chip.delay(10) chip.cmd(TEON, 0x00) +chip.cmd(PIXFMT, 0x55) chip = DriverChip("AXS15231") chip.cmd(0xBB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5A, 0xA5) From ccf2854b612a1659c27cedeb22eaf49b871f157c Mon Sep 17 00:00:00 2001 From: Spencer Owen Date: Thu, 21 Nov 2024 12:24:10 -0700 Subject: [PATCH 042/107] Check for min_version earlier in validation (#7797) --- esphome/core/config.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/esphome/core/config.py b/esphome/core/config.py index 8c130eb6db..367e61c413 100644 --- a/esphome/core/config.py +++ b/esphome/core/config.py @@ -184,6 +184,9 @@ PRELOAD_CONFIG_SCHEMA = cv.Schema( cv.Optional(CONF_ESP8266_RESTORE_FROM_FLASH): cv.valid, cv.Optional(CONF_BOARD_FLASH_MODE): cv.valid, cv.Optional(CONF_ARDUINO_VERSION): cv.valid, + cv.Optional(CONF_MIN_VERSION, default=ESPHOME_VERSION): cv.All( + cv.version_number, cv.validate_esphome_version + ), }, extra=cv.ALLOW_EXTRA, ) From 3232866dc337b0e3332f9b7283d834f025e2a642 Mon Sep 17 00:00:00 2001 From: Alain Turbide <7193213+Dilbert66@users.noreply.github.com> Date: Thu, 21 Nov 2024 15:39:32 -0500 Subject: [PATCH 043/107] Fix for OTA mode not activating in safe_mode when OTA section has an on_xxxx action (#7796) Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com> --- esphome/components/esphome/ota/__init__.py | 8 ++++---- esphome/components/ota/__init__.py | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/esphome/components/esphome/ota/__init__.py b/esphome/components/esphome/ota/__init__.py index a852d8d001..86006e3e18 100644 --- a/esphome/components/esphome/ota/__init__.py +++ b/esphome/components/esphome/ota/__init__.py @@ -1,10 +1,9 @@ import logging import esphome.codegen as cg -import esphome.config_validation as cv -import esphome.final_validate as fv -from esphome.components.ota import BASE_OTA_SCHEMA, ota_to_code, OTAComponent +from esphome.components.ota import BASE_OTA_SCHEMA, OTAComponent, ota_to_code from esphome.config_helpers import merge_config +import esphome.config_validation as cv from esphome.const import ( CONF_ESPHOME, CONF_ID, @@ -18,6 +17,7 @@ from esphome.const import ( CONF_VERSION, ) from esphome.core import coroutine_with_priority +import esphome.final_validate as fv _LOGGER = logging.getLogger(__name__) @@ -124,7 +124,6 @@ FINAL_VALIDATE_SCHEMA = ota_esphome_final_validate @coroutine_with_priority(52.0) async def to_code(config): var = cg.new_Pvariable(config[CONF_ID]) - await ota_to_code(var, config) cg.add(var.set_port(config[CONF_PORT])) if CONF_PASSWORD in config: cg.add(var.set_auth_password(config[CONF_PASSWORD])) @@ -132,3 +131,4 @@ async def to_code(config): cg.add_define("USE_OTA_VERSION", config[CONF_VERSION]) await cg.register_component(var, config) + await ota_to_code(var, config) diff --git a/esphome/components/ota/__init__.py b/esphome/components/ota/__init__.py index d9917a2aae..627c55e910 100644 --- a/esphome/components/ota/__init__.py +++ b/esphome/components/ota/__init__.py @@ -92,6 +92,7 @@ async def to_code(config): async def ota_to_code(var, config): + await cg.past_safe_mode() use_state_callback = False for conf in config.get(CONF_ON_STATE_CHANGE, []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) From 122ff731ef43206212976da35354494e928639f6 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 21 Nov 2024 14:41:31 -0600 Subject: [PATCH 044/107] Ensure storage I/O for ignored devices runs in the executor (#7792) --- esphome/dashboard/core.py | 2 +- esphome/dashboard/web_server.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/esphome/dashboard/core.py b/esphome/dashboard/core.py index 563ca1506d..f53cb7ffb1 100644 --- a/esphome/dashboard/core.py +++ b/esphome/dashboard/core.py @@ -103,7 +103,7 @@ class ESPHomeDashboard: self.loop = asyncio.get_running_loop() self.ping_request = asyncio.Event() self.entries = DashboardEntries(self) - self.load_ignored_devices() + await self.loop.run_in_executor(None, self.load_ignored_devices) def load_ignored_devices(self) -> None: storage_path = Path(ignored_devices_storage_path()) diff --git a/esphome/dashboard/web_server.py b/esphome/dashboard/web_server.py index 07f7f019f8..0fed8e9c53 100644 --- a/esphome/dashboard/web_server.py +++ b/esphome/dashboard/web_server.py @@ -544,7 +544,7 @@ class ImportRequestHandler(BaseHandler): class IgnoreDeviceRequestHandler(BaseHandler): @authenticated - def post(self) -> None: + async def post(self) -> None: dashboard = DASHBOARD try: args = json.loads(self.request.body.decode()) @@ -576,7 +576,8 @@ class IgnoreDeviceRequestHandler(BaseHandler): else: dashboard.ignored_devices.discard(ignored_device.device_name) - dashboard.save_ignored_devices() + loop = asyncio.get_running_loop() + await loop.run_in_executor(None, dashboard.save_ignored_devices) self.set_status(204) self.finish() From 888b2379647049712a94143074b95c79e1f8392b Mon Sep 17 00:00:00 2001 From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com> Date: Thu, 21 Nov 2024 11:10:28 +1100 Subject: [PATCH 045/107] [http_request] Fix within context with parameters. (Bugfix) (#7790) --- esphome/components/http_request/http_request.h | 2 +- tests/components/http_request/common.yaml | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/esphome/components/http_request/http_request.h b/esphome/components/http_request/http_request.h index 4ed2c834f8..b2ce718ec4 100644 --- a/esphome/components/http_request/http_request.h +++ b/esphome/components/http_request/http_request.h @@ -189,7 +189,7 @@ template class HttpRequestSendAction : public Action { if (container == nullptr) { for (auto *trigger : this->error_triggers_) - trigger->trigger(x...); + trigger->trigger(); return; } diff --git a/tests/components/http_request/common.yaml b/tests/components/http_request/common.yaml index 593b85e435..8408f27a05 100644 --- a/tests/components/http_request/common.yaml +++ b/tests/components/http_request/common.yaml @@ -39,6 +39,14 @@ http_request: timeout: 10s verify_ssl: ${verify_ssl} +script: + - id: does_not_compile + parameters: + api_url: string + then: + - http_request.get: + url: "http://google.com" + ota: - platform: http_request on_begin: From a0693060e401153409a2095b0a29248bd23dee0e Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Thu, 21 Nov 2024 19:22:02 +1300 Subject: [PATCH 046/107] [rtttl] Clamp gain between 0 and 1 (#7793) --- esphome/components/rtttl/rtttl.h | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/esphome/components/rtttl/rtttl.h b/esphome/components/rtttl/rtttl.h index 10c290c5fb..420948bfbf 100644 --- a/esphome/components/rtttl/rtttl.h +++ b/esphome/components/rtttl/rtttl.h @@ -40,13 +40,7 @@ class Rtttl : public Component { void set_speaker(speaker::Speaker *speaker) { this->speaker_ = speaker; } #endif float get_gain() { return gain_; } - void set_gain(float gain) { - if (gain < 0.1f) - gain = 0.1f; - if (gain > 1.0f) - gain = 1.0f; - this->gain_ = gain; - } + void set_gain(float gain) { this->gain_ = clamp(gain, 0.0f, 1.0f); } void play(std::string rtttl); void stop(); void dump_config() override; From f04e3de7b8d103a21cbe06f1b5c78e7a78be3429 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Thu, 21 Nov 2024 21:10:20 +1300 Subject: [PATCH 047/107] [speaker] Add missing auto-load for ``audio`` (#7794) --- esphome/components/speaker/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/esphome/components/speaker/__init__.py b/esphome/components/speaker/__init__.py index 7a668dc2f3..948fe4b534 100644 --- a/esphome/components/speaker/__init__.py +++ b/esphome/components/speaker/__init__.py @@ -7,6 +7,7 @@ from esphome.const import CONF_DATA, CONF_ID, CONF_VOLUME from esphome.core import CORE from esphome.coroutine import coroutine_with_priority +AUTO_LOAD = ["audio"] CODEOWNERS = ["@jesserockz", "@kahrendt"] IS_PLATFORM_COMPONENT = True From 489d0d20d2279257574038ab798755242441c18b Mon Sep 17 00:00:00 2001 From: Manuel Kasper Date: Thu, 21 Nov 2024 10:46:49 +0100 Subject: [PATCH 048/107] [qspi_dbi] Fix garbled graphics on RM690B0 (#7795) --- esphome/components/qspi_dbi/models.py | 1 + 1 file changed, 1 insertion(+) diff --git a/esphome/components/qspi_dbi/models.py b/esphome/components/qspi_dbi/models.py index 071ea72d73..cbd9c4663f 100644 --- a/esphome/components/qspi_dbi/models.py +++ b/esphome/components/qspi_dbi/models.py @@ -55,6 +55,7 @@ chip.cmd(PAGESEL, 0x00) chip.cmd(0xC2, 0x00) chip.delay(10) chip.cmd(TEON, 0x00) +chip.cmd(PIXFMT, 0x55) chip = DriverChip("AXS15231") chip.cmd(0xBB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5A, 0xA5) From ea424b069979e5c53438f95abdd43acdc521cd78 Mon Sep 17 00:00:00 2001 From: Spencer Owen Date: Thu, 21 Nov 2024 12:24:10 -0700 Subject: [PATCH 049/107] Check for min_version earlier in validation (#7797) --- esphome/core/config.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/esphome/core/config.py b/esphome/core/config.py index 8c130eb6db..367e61c413 100644 --- a/esphome/core/config.py +++ b/esphome/core/config.py @@ -184,6 +184,9 @@ PRELOAD_CONFIG_SCHEMA = cv.Schema( cv.Optional(CONF_ESP8266_RESTORE_FROM_FLASH): cv.valid, cv.Optional(CONF_BOARD_FLASH_MODE): cv.valid, cv.Optional(CONF_ARDUINO_VERSION): cv.valid, + cv.Optional(CONF_MIN_VERSION, default=ESPHOME_VERSION): cv.All( + cv.version_number, cv.validate_esphome_version + ), }, extra=cv.ALLOW_EXTRA, ) From 1c1f3f7c55607c504226f7a1ed52794a0482b123 Mon Sep 17 00:00:00 2001 From: Alain Turbide <7193213+Dilbert66@users.noreply.github.com> Date: Thu, 21 Nov 2024 15:39:32 -0500 Subject: [PATCH 050/107] Fix for OTA mode not activating in safe_mode when OTA section has an on_xxxx action (#7796) Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com> --- esphome/components/esphome/ota/__init__.py | 8 ++++---- esphome/components/ota/__init__.py | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/esphome/components/esphome/ota/__init__.py b/esphome/components/esphome/ota/__init__.py index a852d8d001..86006e3e18 100644 --- a/esphome/components/esphome/ota/__init__.py +++ b/esphome/components/esphome/ota/__init__.py @@ -1,10 +1,9 @@ import logging import esphome.codegen as cg -import esphome.config_validation as cv -import esphome.final_validate as fv -from esphome.components.ota import BASE_OTA_SCHEMA, ota_to_code, OTAComponent +from esphome.components.ota import BASE_OTA_SCHEMA, OTAComponent, ota_to_code from esphome.config_helpers import merge_config +import esphome.config_validation as cv from esphome.const import ( CONF_ESPHOME, CONF_ID, @@ -18,6 +17,7 @@ from esphome.const import ( CONF_VERSION, ) from esphome.core import coroutine_with_priority +import esphome.final_validate as fv _LOGGER = logging.getLogger(__name__) @@ -124,7 +124,6 @@ FINAL_VALIDATE_SCHEMA = ota_esphome_final_validate @coroutine_with_priority(52.0) async def to_code(config): var = cg.new_Pvariable(config[CONF_ID]) - await ota_to_code(var, config) cg.add(var.set_port(config[CONF_PORT])) if CONF_PASSWORD in config: cg.add(var.set_auth_password(config[CONF_PASSWORD])) @@ -132,3 +131,4 @@ async def to_code(config): cg.add_define("USE_OTA_VERSION", config[CONF_VERSION]) await cg.register_component(var, config) + await ota_to_code(var, config) diff --git a/esphome/components/ota/__init__.py b/esphome/components/ota/__init__.py index d9917a2aae..627c55e910 100644 --- a/esphome/components/ota/__init__.py +++ b/esphome/components/ota/__init__.py @@ -92,6 +92,7 @@ async def to_code(config): async def ota_to_code(var, config): + await cg.past_safe_mode() use_state_callback = False for conf in config.get(CONF_ON_STATE_CHANGE, []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) From e51f3d9498d377ed45d15665e1c91f91d6a2aae0 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 21 Nov 2024 14:41:31 -0600 Subject: [PATCH 051/107] Ensure storage I/O for ignored devices runs in the executor (#7792) --- esphome/dashboard/core.py | 2 +- esphome/dashboard/web_server.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/esphome/dashboard/core.py b/esphome/dashboard/core.py index 563ca1506d..f53cb7ffb1 100644 --- a/esphome/dashboard/core.py +++ b/esphome/dashboard/core.py @@ -103,7 +103,7 @@ class ESPHomeDashboard: self.loop = asyncio.get_running_loop() self.ping_request = asyncio.Event() self.entries = DashboardEntries(self) - self.load_ignored_devices() + await self.loop.run_in_executor(None, self.load_ignored_devices) def load_ignored_devices(self) -> None: storage_path = Path(ignored_devices_storage_path()) diff --git a/esphome/dashboard/web_server.py b/esphome/dashboard/web_server.py index 07f7f019f8..0fed8e9c53 100644 --- a/esphome/dashboard/web_server.py +++ b/esphome/dashboard/web_server.py @@ -544,7 +544,7 @@ class ImportRequestHandler(BaseHandler): class IgnoreDeviceRequestHandler(BaseHandler): @authenticated - def post(self) -> None: + async def post(self) -> None: dashboard = DASHBOARD try: args = json.loads(self.request.body.decode()) @@ -576,7 +576,8 @@ class IgnoreDeviceRequestHandler(BaseHandler): else: dashboard.ignored_devices.discard(ignored_device.device_name) - dashboard.save_ignored_devices() + loop = asyncio.get_running_loop() + await loop.run_in_executor(None, dashboard.save_ignored_devices) self.set_status(204) self.finish() From 2cc2a2153b2c219d1bd07a9fe427b16d38e2e6f7 Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Fri, 22 Nov 2024 10:08:00 +1300 Subject: [PATCH 052/107] Bump version to 2024.11.1 --- esphome/const.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/const.py b/esphome/const.py index 408dc52869..d14cdecb23 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -1,6 +1,6 @@ """Constants used by esphome.""" -__version__ = "2024.11.0" +__version__ = "2024.11.1" ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_" VALID_SUBSTITUTIONS_CHARACTERS = ( From dea297c8d7d73f0c4f366e58994cd6a9a3995e11 Mon Sep 17 00:00:00 2001 From: Petr Kejval Date: Sat, 23 Nov 2024 05:52:02 +0100 Subject: [PATCH 053/107] [nextion] Add publish actions (#7646) Co-authored-by: Keith Burzinski --- esphome/components/nextion/__init__.py | 2 + esphome/components/nextion/automation.h | 75 ++++- .../nextion/binary_sensor/__init__.py | 45 ++- esphome/components/nextion/sensor/__init__.py | 43 ++- esphome/components/nextion/switch/__init__.py | 40 ++- .../nextion/text_sensor/__init__.py | 39 ++- tests/components/nextion/common.yaml | 293 ++++++++++++++++++ tests/components/nextion/test.esp32-ard.yaml | 65 +--- .../components/nextion/test.esp32-c3-ard.yaml | 65 +--- .../components/nextion/test.esp32-c3-idf.yaml | 65 +--- tests/components/nextion/test.esp32-idf.yaml | 65 +--- .../components/nextion/test.esp8266-ard.yaml | 65 +--- tests/components/nextion/test.rp2040-ard.yaml | 61 +--- 13 files changed, 558 insertions(+), 365 deletions(-) create mode 100644 tests/components/nextion/common.yaml diff --git a/esphome/components/nextion/__init__.py b/esphome/components/nextion/__init__.py index 924d58198d..fb75daf4ba 100644 --- a/esphome/components/nextion/__init__.py +++ b/esphome/components/nextion/__init__.py @@ -6,3 +6,5 @@ Nextion = nextion_ns.class_("Nextion", cg.PollingComponent, uart.UARTDevice) nextion_ref = Nextion.operator("ref") CONF_NEXTION_ID = "nextion_id" +CONF_PUBLISH_STATE = "publish_state" +CONF_SEND_TO_NEXTION = "send_to_nextion" diff --git a/esphome/components/nextion/automation.h b/esphome/components/nextion/automation.h index 5182e07229..65f1fd0058 100644 --- a/esphome/components/nextion/automation.h +++ b/esphome/components/nextion/automation.h @@ -5,6 +5,13 @@ namespace esphome { namespace nextion { +class BufferOverflowTrigger : public Trigger<> { + public: + explicit BufferOverflowTrigger(Nextion *nextion) { + nextion->add_buffer_overflow_event_callback([this]() { this->trigger(); }); + } +}; + class SetupTrigger : public Trigger<> { public: explicit SetupTrigger(Nextion *nextion) { @@ -42,11 +49,73 @@ class TouchTrigger : public Trigger { } }; -class BufferOverflowTrigger : public Trigger<> { +template class NextionPublishFloatAction : public Action { public: - explicit BufferOverflowTrigger(Nextion *nextion) { - nextion->add_buffer_overflow_event_callback([this]() { this->trigger(); }); + explicit NextionPublishFloatAction(NextionComponent *component) : component_(component) {} + + TEMPLATABLE_VALUE(float, state) + TEMPLATABLE_VALUE(bool, publish_state) + TEMPLATABLE_VALUE(bool, send_to_nextion) + + void play(Ts... x) override { + this->component_->set_state(this->state_.value(x...), this->publish_state_.value(x...), + this->send_to_nextion_.value(x...)); } + + void set_state(std::function state) { this->state_ = state; } + void set_publish_state(std::function publish_state) { this->publish_state_ = publish_state; } + void set_send_to_nextion(std::function send_to_nextion) { + this->send_to_nextion_ = send_to_nextion; + } + + protected: + NextionComponent *component_; +}; + +template class NextionPublishTextAction : public Action { + public: + explicit NextionPublishTextAction(NextionComponent *component) : component_(component) {} + + TEMPLATABLE_VALUE(const char *, state) + TEMPLATABLE_VALUE(bool, publish_state) + TEMPLATABLE_VALUE(bool, send_to_nextion) + + void play(Ts... x) override { + this->component_->set_state(this->state_.value(x...), this->publish_state_.value(x...), + this->send_to_nextion_.value(x...)); + } + + void set_state(std::function state) { this->state_ = state; } + void set_publish_state(std::function publish_state) { this->publish_state_ = publish_state; } + void set_send_to_nextion(std::function send_to_nextion) { + this->send_to_nextion_ = send_to_nextion; + } + + protected: + NextionComponent *component_; +}; + +template class NextionPublishBoolAction : public Action { + public: + explicit NextionPublishBoolAction(NextionComponent *component) : component_(component) {} + + TEMPLATABLE_VALUE(bool, state) + TEMPLATABLE_VALUE(bool, publish_state) + TEMPLATABLE_VALUE(bool, send_to_nextion) + + void play(Ts... x) override { + this->component_->set_state(this->state_.value(x...), this->publish_state_.value(x...), + this->send_to_nextion_.value(x...)); + } + + void set_state(std::function state) { this->state_ = state; } + void set_publish_state(std::function publish_state) { this->publish_state_ = publish_state; } + void set_send_to_nextion(std::function send_to_nextion) { + this->send_to_nextion_ = send_to_nextion; + } + + protected: + NextionComponent *component_; }; } // namespace nextion diff --git a/esphome/components/nextion/binary_sensor/__init__.py b/esphome/components/nextion/binary_sensor/__init__.py index 8b4a45cc60..a257587e13 100644 --- a/esphome/components/nextion/binary_sensor/__init__.py +++ b/esphome/components/nextion/binary_sensor/__init__.py @@ -1,9 +1,16 @@ +from esphome import automation import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import binary_sensor -from esphome.const import CONF_COMPONENT_ID, CONF_PAGE_ID, CONF_ID -from .. import nextion_ns, CONF_NEXTION_ID +from esphome.const import ( + CONF_ID, + CONF_STATE, + CONF_COMPONENT_ID, + CONF_PAGE_ID, +) + +from .. import nextion_ns, CONF_NEXTION_ID, CONF_PUBLISH_STATE, CONF_SEND_TO_NEXTION from ..base_component import ( @@ -19,6 +26,10 @@ NextionBinarySensor = nextion_ns.class_( "NextionBinarySensor", binary_sensor.BinarySensor, cg.PollingComponent ) +NextionPublishBoolAction = nextion_ns.class_( + "NextionPublishBoolAction", automation.Action +) + CONFIG_SCHEMA = cv.All( binary_sensor.binary_sensor_schema(NextionBinarySensor) .extend( @@ -52,3 +63,33 @@ async def to_code(config): if CONF_COMPONENT_NAME in config or CONF_VARIABLE_NAME in config: await setup_component_core_(var, config, ".val") cg.add(hub.register_binarysensor_component(var)) + + +@automation.register_action( + "binary_sensor.nextion.publish", + NextionPublishBoolAction, + cv.Schema( + { + cv.Required(CONF_ID): cv.use_id(NextionBinarySensor), + cv.Required(CONF_STATE): cv.templatable(cv.boolean), + cv.Optional(CONF_PUBLISH_STATE, default="true"): cv.templatable(cv.boolean), + cv.Optional(CONF_SEND_TO_NEXTION, default="true"): cv.templatable( + cv.boolean + ), + } + ), +) +async def sensor_nextion_publish_to_code(config, action_id, template_arg, args): + paren = await cg.get_variable(config[CONF_ID]) + var = cg.new_Pvariable(action_id, template_arg, paren) + + template_ = await cg.templatable(config[CONF_STATE], args, bool) + cg.add(var.set_state(template_)) + + template_ = await cg.templatable(config[CONF_PUBLISH_STATE], args, bool) + cg.add(var.set_publish_state(template_)) + + template_ = await cg.templatable(config[CONF_SEND_TO_NEXTION], args, bool) + cg.add(var.set_send_to_nextion(template_)) + + return var diff --git a/esphome/components/nextion/sensor/__init__.py b/esphome/components/nextion/sensor/__init__.py index eefbe34d58..1058c2a04b 100644 --- a/esphome/components/nextion/sensor/__init__.py +++ b/esphome/components/nextion/sensor/__init__.py @@ -1,12 +1,11 @@ +from esphome import automation import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import sensor -from esphome.const import ( - CONF_ID, - CONF_COMPONENT_ID, -) -from .. import nextion_ns, CONF_NEXTION_ID +from esphome.const import CONF_ID, CONF_COMPONENT_ID, CONF_STATE + +from .. import nextion_ns, CONF_NEXTION_ID, CONF_PUBLISH_STATE, CONF_SEND_TO_NEXTION from ..base_component import ( setup_component_core_, @@ -25,6 +24,10 @@ CODEOWNERS = ["@senexcrenshaw"] NextionSensor = nextion_ns.class_("NextionSensor", sensor.Sensor, cg.PollingComponent) +NextionPublishFloatAction = nextion_ns.class_( + "NextionPublishFloatAction", automation.Action +) + def CheckWaveID(value): value = cv.int_(value) @@ -95,3 +98,33 @@ async def to_code(config): if CONF_WAVE_MAX_LENGTH in config: cg.add(var.set_wave_max_length(config[CONF_WAVE_MAX_LENGTH])) + + +@automation.register_action( + "sensor.nextion.publish", + NextionPublishFloatAction, + cv.Schema( + { + cv.Required(CONF_ID): cv.use_id(NextionSensor), + cv.Required(CONF_STATE): cv.templatable(cv.float_), + cv.Optional(CONF_PUBLISH_STATE, default="true"): cv.templatable(cv.boolean), + cv.Optional(CONF_SEND_TO_NEXTION, default="true"): cv.templatable( + cv.boolean + ), + } + ), +) +async def sensor_nextion_publish_to_code(config, action_id, template_arg, args): + paren = await cg.get_variable(config[CONF_ID]) + var = cg.new_Pvariable(action_id, template_arg, paren) + + template_ = await cg.templatable(config[CONF_STATE], args, float) + cg.add(var.set_state(template_)) + + template_ = await cg.templatable(config[CONF_PUBLISH_STATE], args, bool) + cg.add(var.set_publish_state(template_)) + + template_ = await cg.templatable(config[CONF_SEND_TO_NEXTION], args, bool) + cg.add(var.set_send_to_nextion(template_)) + + return var diff --git a/esphome/components/nextion/switch/__init__.py b/esphome/components/nextion/switch/__init__.py index 91ab0cc81f..de1a061478 100644 --- a/esphome/components/nextion/switch/__init__.py +++ b/esphome/components/nextion/switch/__init__.py @@ -1,9 +1,11 @@ +from esphome import automation import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import switch -from esphome.const import CONF_ID -from .. import nextion_ns, CONF_NEXTION_ID +from esphome.const import CONF_ID, CONF_STATE + +from .. import nextion_ns, CONF_NEXTION_ID, CONF_PUBLISH_STATE, CONF_SEND_TO_NEXTION from ..base_component import ( setup_component_core_, @@ -16,6 +18,10 @@ CODEOWNERS = ["@senexcrenshaw"] NextionSwitch = nextion_ns.class_("NextionSwitch", switch.Switch, cg.PollingComponent) +NextionPublishBoolAction = nextion_ns.class_( + "NextionPublishBoolAction", automation.Action +) + CONFIG_SCHEMA = cv.All( switch.switch_schema(NextionSwitch) .extend(CONFIG_SWITCH_COMPONENT_SCHEMA) @@ -33,3 +39,33 @@ async def to_code(config): cg.add(hub.register_switch_component(var)) await setup_component_core_(var, config, ".val") + + +@automation.register_action( + "switch.nextion.publish", + NextionPublishBoolAction, + cv.Schema( + { + cv.Required(CONF_ID): cv.use_id(NextionSwitch), + cv.Required(CONF_STATE): cv.templatable(cv.boolean), + cv.Optional(CONF_PUBLISH_STATE, default="true"): cv.templatable(cv.boolean), + cv.Optional(CONF_SEND_TO_NEXTION, default="true"): cv.templatable( + cv.boolean + ), + } + ), +) +async def sensor_nextion_publish_to_code(config, action_id, template_arg, args): + paren = await cg.get_variable(config[CONF_ID]) + var = cg.new_Pvariable(action_id, template_arg, paren) + + template_ = await cg.templatable(config[CONF_STATE], args, bool) + cg.add(var.set_state(template_)) + + template_ = await cg.templatable(config[CONF_PUBLISH_STATE], args, bool) + cg.add(var.set_publish_state(template_)) + + template_ = await cg.templatable(config[CONF_SEND_TO_NEXTION], args, bool) + cg.add(var.set_send_to_nextion(template_)) + + return var diff --git a/esphome/components/nextion/text_sensor/__init__.py b/esphome/components/nextion/text_sensor/__init__.py index 826ff2354e..793397b1f4 100644 --- a/esphome/components/nextion/text_sensor/__init__.py +++ b/esphome/components/nextion/text_sensor/__init__.py @@ -1,9 +1,10 @@ +from esphome import automation from esphome.components import text_sensor import esphome.config_validation as cv import esphome.codegen as cg -from esphome.const import CONF_ID +from esphome.const import CONF_ID, CONF_STATE -from .. import nextion_ns, CONF_NEXTION_ID +from .. import nextion_ns, CONF_NEXTION_ID, CONF_PUBLISH_STATE, CONF_SEND_TO_NEXTION from ..base_component import ( setup_component_core_, @@ -16,6 +17,10 @@ NextionTextSensor = nextion_ns.class_( "NextionTextSensor", text_sensor.TextSensor, cg.PollingComponent ) +NextionPublishTextAction = nextion_ns.class_( + "NextionPublishTextAction", automation.Action +) + CONFIG_SCHEMA = ( text_sensor.text_sensor_schema(NextionTextSensor) .extend(CONFIG_TEXT_COMPONENT_SCHEMA) @@ -32,3 +37,33 @@ async def to_code(config): cg.add(hub.register_textsensor_component(var)) await setup_component_core_(var, config, ".txt") + + +@automation.register_action( + "text_sensor.nextion.publish", + NextionPublishTextAction, + cv.Schema( + { + cv.Required(CONF_ID): cv.use_id(NextionTextSensor), + cv.Required(CONF_STATE): cv.templatable(cv.string_strict), + cv.Optional(CONF_PUBLISH_STATE, default="true"): cv.templatable(cv.boolean), + cv.Optional(CONF_SEND_TO_NEXTION, default="true"): cv.templatable( + cv.boolean + ), + } + ), +) +async def sensor_nextion_publish_to_code(config, action_id, template_arg, args): + paren = await cg.get_variable(config[CONF_ID]) + var = cg.new_Pvariable(action_id, template_arg, paren) + + template_ = await cg.templatable(config[CONF_STATE], args, cg.const_char_ptr) + cg.add(var.set_state(template_)) + + template_ = await cg.templatable(config[CONF_PUBLISH_STATE], args, cg.bool_) + cg.add(var.set_publish_state(template_)) + + template_ = await cg.templatable(config[CONF_SEND_TO_NEXTION], args, cg.bool_) + cg.add(var.set_send_to_nextion(template_)) + + return var diff --git a/tests/components/nextion/common.yaml b/tests/components/nextion/common.yaml new file mode 100644 index 0000000000..e84cd08422 --- /dev/null +++ b/tests/components/nextion/common.yaml @@ -0,0 +1,293 @@ +esphome: + on_boot: + # Binary sensor publish action tests + - binary_sensor.nextion.publish: + id: r0_sensor + state: True + + - binary_sensor.nextion.publish: + id: r0_sensor + state: True + publish_state: True + send_to_nextion: True + + - binary_sensor.nextion.publish: + id: r0_sensor + state: True + publish_state: False + send_to_nextion: True + + - binary_sensor.nextion.publish: + id: r0_sensor + state: True + publish_state: True + send_to_nextion: False + + - binary_sensor.nextion.publish: + id: r0_sensor + state: True + publish_state: False + send_to_nextion: False + + # Templated + - binary_sensor.nextion.publish: + id: r0_sensor + state: !lambda 'return true;' + + - binary_sensor.nextion.publish: + id: r0_sensor + state: !lambda 'return true;' + publish_state: !lambda 'return true;' + send_to_nextion: !lambda 'return true;' + + - binary_sensor.nextion.publish: + id: r0_sensor + state: !lambda 'return true;' + publish_state: !lambda 'return false;' + send_to_nextion: !lambda 'return true;' + + - binary_sensor.nextion.publish: + id: r0_sensor + state: !lambda 'return true;' + publish_state: !lambda 'return true;' + send_to_nextion: !lambda 'return false;' + + - binary_sensor.nextion.publish: + id: r0_sensor + state: !lambda 'return true;' + publish_state: !lambda 'return false;' + send_to_nextion: !lambda 'return false;' + + # Sensor publish action tests + - sensor.nextion.publish: + id: testnumber + state: 42.0 + + - sensor.nextion.publish: + id: testnumber + state: 42.0 + publish_state: True + send_to_nextion: True + + - sensor.nextion.publish: + id: testnumber + state: 42.0 + publish_state: False + send_to_nextion: True + + - sensor.nextion.publish: + id: testnumber + state: 42.0 + publish_state: True + send_to_nextion: False + + - sensor.nextion.publish: + id: testnumber + state: 42.0 + publish_state: False + send_to_nextion: False + + # Templated + - sensor.nextion.publish: + id: testnumber + state: !lambda 'return 42.0;' + + - sensor.nextion.publish: + id: testnumber + state: !lambda 'return 42.0;' + publish_state: !lambda 'return true;' + send_to_nextion: !lambda 'return true;' + + - sensor.nextion.publish: + id: testnumber + state: !lambda 'return 42.0;' + publish_state: !lambda 'return false;' + send_to_nextion: !lambda 'return true;' + + - sensor.nextion.publish: + id: testnumber + state: !lambda 'return 42.0;' + publish_state: !lambda 'return true;' + send_to_nextion: !lambda 'return false;' + + - sensor.nextion.publish: + id: testnumber + state: !lambda 'return 42.0;' + publish_state: !lambda 'return false;' + send_to_nextion: !lambda 'return false;' + + # Switch publish action tests + - switch.nextion.publish: + id: r0 + state: True + + - switch.nextion.publish: + id: r0 + state: True + publish_state: true + send_to_nextion: true + + - switch.nextion.publish: + id: r0 + state: True + publish_state: false + send_to_nextion: true + + - switch.nextion.publish: + id: r0 + state: True + publish_state: true + send_to_nextion: false + + - switch.nextion.publish: + id: r0 + state: True + publish_state: false + send_to_nextion: false + + # Templated + - switch.nextion.publish: + id: r0 + state: !lambda 'return true;' + + - switch.nextion.publish: + id: r0 + state: !lambda 'return true;' + publish_state: !lambda 'return true;' + send_to_nextion: !lambda 'return true;' + + - switch.nextion.publish: + id: r0 + state: !lambda 'return true;' + publish_state: !lambda 'return false;' + send_to_nextion: !lambda 'return true;' + + - switch.nextion.publish: + id: r0 + state: !lambda 'return true;' + publish_state: !lambda 'return true;' + send_to_nextion: !lambda 'return false;' + + - switch.nextion.publish: + id: r0 + state: !lambda 'return true;' + publish_state: !lambda 'return false;' + send_to_nextion: !lambda 'return false;' + + # Test sensor publish action tests + - text_sensor.nextion.publish: + id: text0 + state: 'Test' + publish_state: true + send_to_nextion: true + + - text_sensor.nextion.publish: + id: text0 + state: 'Test' + publish_state: false + send_to_nextion: true + + - text_sensor.nextion.publish: + id: text0 + state: 'Test' + publish_state: true + send_to_nextion: false + + - text_sensor.nextion.publish: + id: text0 + state: 'Test' + publish_state: false + send_to_nextion: false + + # Templated + - text_sensor.nextion.publish: + id: text0 + state: !lambda 'return "Test";' + + - text_sensor.nextion.publish: + id: text0 + state: !lambda 'return "Test";' + publish_state: !lambda 'return true;' + send_to_nextion: !lambda 'return true;' + + - text_sensor.nextion.publish: + id: text0 + state: !lambda 'return "Test";' + publish_state: !lambda 'return false;' + send_to_nextion: !lambda 'return true;' + + - text_sensor.nextion.publish: + id: text0 + state: !lambda 'return "Test";' + publish_state: !lambda 'return true;' + send_to_nextion: !lambda 'return false;' + + - text_sensor.nextion.publish: + id: text0 + state: !lambda 'return "Test";' + publish_state: !lambda 'return false;' + send_to_nextion: !lambda 'return false;' + +wifi: + ssid: MySSID + password: password1 + +uart: + - id: uart_nextion + tx_pin: ${tx_pin} + rx_pin: ${rx_pin} + baud_rate: 115200 + +binary_sensor: + - platform: nextion + page_id: 0 + component_id: 2 + name: Nextion Touch Component + - platform: nextion + id: r0_sensor + name: R0 Sensor + component_name: page0.r0 + +sensor: + - platform: nextion + id: testnumber + name: testnumber + variable_name: testnumber + - platform: nextion + id: testwave + name: testwave + component_id: 2 + wave_channel_id: 1 + +switch: + - platform: nextion + id: r0 + name: R0 Switch + component_name: page0.r0 + +text_sensor: + - platform: nextion + name: text0 + id: text0 + update_interval: 4s + component_name: text0 + +display: + - platform: nextion + id: main_lcd + update_interval: 5s + on_sleep: + then: + lambda: 'ESP_LOGD("display","Display went to sleep");' + on_wake: + then: + lambda: 'ESP_LOGD("display","Display woke up");' + on_setup: + then: + lambda: 'ESP_LOGD("display","Display setup completed");' + on_page: + then: + lambda: 'ESP_LOGD("display","Display shows new page %u", x);' + on_buffer_overflow: + then: + logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.esp32-ard.yaml b/tests/components/nextion/test.esp32-ard.yaml index ba76236fc6..d5e02b8b85 100644 --- a/tests/components/nextion/test.esp32-ard.yaml +++ b/tests/components/nextion/test.esp32-ard.yaml @@ -1,63 +1,10 @@ -wifi: - ssid: MySSID - password: password1 +substitutions: + tx_pin: GPIO17 + rx_pin: GPIO16 -uart: - - id: uart_nextion - tx_pin: 17 - rx_pin: 16 - baud_rate: 115200 - -binary_sensor: - - platform: nextion - page_id: 0 - component_id: 2 - name: Nextion Touch Component - - platform: nextion - id: r0_sensor - name: R0 Sensor - component_name: page0.r0 - -sensor: - - platform: nextion - id: testnumber - name: testnumber - variable_name: testnumber - - platform: nextion - id: testwave - name: testwave - component_id: 2 - wave_channel_id: 1 - -switch: - - platform: nextion - id: r0 - name: R0 Switch - component_name: page0.r0 - -text_sensor: - - platform: nextion - name: text0 - id: text0 - update_interval: 4s - component_name: text0 +packages: + base: !include common.yaml display: - - platform: nextion + - id: !extend main_lcd tft_url: http://esphome.io/default35.tft - update_interval: 5s - on_sleep: - then: - lambda: 'ESP_LOGD("display","Display went to sleep");' - on_wake: - then: - lambda: 'ESP_LOGD("display","Display woke up");' - on_setup: - then: - lambda: 'ESP_LOGD("display","Display setup completed");' - on_page: - then: - lambda: 'ESP_LOGD("display","Display shows new page %u", x);' - on_buffer_overflow: - then: - logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.esp32-c3-ard.yaml b/tests/components/nextion/test.esp32-c3-ard.yaml index 5d253268f8..5135c7e4f4 100644 --- a/tests/components/nextion/test.esp32-c3-ard.yaml +++ b/tests/components/nextion/test.esp32-c3-ard.yaml @@ -1,63 +1,10 @@ -wifi: - ssid: MySSID - password: password1 +substitutions: + tx_pin: GPIO4 + rx_pin: GPIO5 -uart: - - id: uart_nextion - tx_pin: 4 - rx_pin: 5 - baud_rate: 115200 - -binary_sensor: - - platform: nextion - page_id: 0 - component_id: 2 - name: Nextion Touch Component - - platform: nextion - id: r0_sensor - name: R0 Sensor - component_name: page0.r0 - -sensor: - - platform: nextion - id: testnumber - name: testnumber - variable_name: testnumber - - platform: nextion - id: testwave - name: testwave - component_id: 2 - wave_channel_id: 1 - -switch: - - platform: nextion - id: r0 - name: R0 Switch - component_name: page0.r0 - -text_sensor: - - platform: nextion - name: text0 - id: text0 - update_interval: 4s - component_name: text0 +packages: + base: !include common.yaml display: - - platform: nextion + - id: !extend main_lcd tft_url: http://esphome.io/default35.tft - update_interval: 5s - on_sleep: - then: - lambda: 'ESP_LOGD("display","Display went to sleep");' - on_wake: - then: - lambda: 'ESP_LOGD("display","Display woke up");' - on_setup: - then: - lambda: 'ESP_LOGD("display","Display setup completed");' - on_page: - then: - lambda: 'ESP_LOGD("display","Display shows new page %u", x);' - on_buffer_overflow: - then: - logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.esp32-c3-idf.yaml b/tests/components/nextion/test.esp32-c3-idf.yaml index 5d253268f8..5135c7e4f4 100644 --- a/tests/components/nextion/test.esp32-c3-idf.yaml +++ b/tests/components/nextion/test.esp32-c3-idf.yaml @@ -1,63 +1,10 @@ -wifi: - ssid: MySSID - password: password1 +substitutions: + tx_pin: GPIO4 + rx_pin: GPIO5 -uart: - - id: uart_nextion - tx_pin: 4 - rx_pin: 5 - baud_rate: 115200 - -binary_sensor: - - platform: nextion - page_id: 0 - component_id: 2 - name: Nextion Touch Component - - platform: nextion - id: r0_sensor - name: R0 Sensor - component_name: page0.r0 - -sensor: - - platform: nextion - id: testnumber - name: testnumber - variable_name: testnumber - - platform: nextion - id: testwave - name: testwave - component_id: 2 - wave_channel_id: 1 - -switch: - - platform: nextion - id: r0 - name: R0 Switch - component_name: page0.r0 - -text_sensor: - - platform: nextion - name: text0 - id: text0 - update_interval: 4s - component_name: text0 +packages: + base: !include common.yaml display: - - platform: nextion + - id: !extend main_lcd tft_url: http://esphome.io/default35.tft - update_interval: 5s - on_sleep: - then: - lambda: 'ESP_LOGD("display","Display went to sleep");' - on_wake: - then: - lambda: 'ESP_LOGD("display","Display woke up");' - on_setup: - then: - lambda: 'ESP_LOGD("display","Display setup completed");' - on_page: - then: - lambda: 'ESP_LOGD("display","Display shows new page %u", x);' - on_buffer_overflow: - then: - logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.esp32-idf.yaml b/tests/components/nextion/test.esp32-idf.yaml index ba76236fc6..d5e02b8b85 100644 --- a/tests/components/nextion/test.esp32-idf.yaml +++ b/tests/components/nextion/test.esp32-idf.yaml @@ -1,63 +1,10 @@ -wifi: - ssid: MySSID - password: password1 +substitutions: + tx_pin: GPIO17 + rx_pin: GPIO16 -uart: - - id: uart_nextion - tx_pin: 17 - rx_pin: 16 - baud_rate: 115200 - -binary_sensor: - - platform: nextion - page_id: 0 - component_id: 2 - name: Nextion Touch Component - - platform: nextion - id: r0_sensor - name: R0 Sensor - component_name: page0.r0 - -sensor: - - platform: nextion - id: testnumber - name: testnumber - variable_name: testnumber - - platform: nextion - id: testwave - name: testwave - component_id: 2 - wave_channel_id: 1 - -switch: - - platform: nextion - id: r0 - name: R0 Switch - component_name: page0.r0 - -text_sensor: - - platform: nextion - name: text0 - id: text0 - update_interval: 4s - component_name: text0 +packages: + base: !include common.yaml display: - - platform: nextion + - id: !extend main_lcd tft_url: http://esphome.io/default35.tft - update_interval: 5s - on_sleep: - then: - lambda: 'ESP_LOGD("display","Display went to sleep");' - on_wake: - then: - lambda: 'ESP_LOGD("display","Display woke up");' - on_setup: - then: - lambda: 'ESP_LOGD("display","Display setup completed");' - on_page: - then: - lambda: 'ESP_LOGD("display","Display shows new page %u", x);' - on_buffer_overflow: - then: - logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.esp8266-ard.yaml b/tests/components/nextion/test.esp8266-ard.yaml index 5d253268f8..5135c7e4f4 100644 --- a/tests/components/nextion/test.esp8266-ard.yaml +++ b/tests/components/nextion/test.esp8266-ard.yaml @@ -1,63 +1,10 @@ -wifi: - ssid: MySSID - password: password1 +substitutions: + tx_pin: GPIO4 + rx_pin: GPIO5 -uart: - - id: uart_nextion - tx_pin: 4 - rx_pin: 5 - baud_rate: 115200 - -binary_sensor: - - platform: nextion - page_id: 0 - component_id: 2 - name: Nextion Touch Component - - platform: nextion - id: r0_sensor - name: R0 Sensor - component_name: page0.r0 - -sensor: - - platform: nextion - id: testnumber - name: testnumber - variable_name: testnumber - - platform: nextion - id: testwave - name: testwave - component_id: 2 - wave_channel_id: 1 - -switch: - - platform: nextion - id: r0 - name: R0 Switch - component_name: page0.r0 - -text_sensor: - - platform: nextion - name: text0 - id: text0 - update_interval: 4s - component_name: text0 +packages: + base: !include common.yaml display: - - platform: nextion + - id: !extend main_lcd tft_url: http://esphome.io/default35.tft - update_interval: 5s - on_sleep: - then: - lambda: 'ESP_LOGD("display","Display went to sleep");' - on_wake: - then: - lambda: 'ESP_LOGD("display","Display woke up");' - on_setup: - then: - lambda: 'ESP_LOGD("display","Display setup completed");' - on_page: - then: - lambda: 'ESP_LOGD("display","Display shows new page %u", x);' - on_buffer_overflow: - then: - logger.log: "Nextion reported a buffer overflow!" diff --git a/tests/components/nextion/test.rp2040-ard.yaml b/tests/components/nextion/test.rp2040-ard.yaml index 9b04433095..20347c6eff 100644 --- a/tests/components/nextion/test.rp2040-ard.yaml +++ b/tests/components/nextion/test.rp2040-ard.yaml @@ -1,58 +1,7 @@ -uart: - - id: uart_nextion - tx_pin: 4 - rx_pin: 5 - baud_rate: 115200 +substitutions: + tx_pin: GPIO4 + rx_pin: GPIO5 -binary_sensor: - - platform: nextion - page_id: 0 - component_id: 2 - name: Nextion Touch Component - - platform: nextion - id: r0_sensor - name: R0 Sensor - component_name: page0.r0 +packages: + base: !include common.yaml -sensor: - - platform: nextion - id: testnumber - name: testnumber - variable_name: testnumber - - platform: nextion - id: testwave - name: testwave - component_id: 2 - wave_channel_id: 1 - -switch: - - platform: nextion - id: r0 - name: R0 Switch - component_name: page0.r0 - -text_sensor: - - platform: nextion - name: text0 - id: text0 - update_interval: 4s - component_name: text0 - -display: - - platform: nextion - update_interval: 5s - on_sleep: - then: - lambda: 'ESP_LOGD("display","Display went to sleep");' - on_wake: - then: - lambda: 'ESP_LOGD("display","Display woke up");' - on_setup: - then: - lambda: 'ESP_LOGD("display","Display setup completed");' - on_page: - then: - lambda: 'ESP_LOGD("display","Display shows new page %u", x);' - on_buffer_overflow: - then: - logger.log: "Nextion reported a buffer overflow!" From 2ecd5cff0701b807e5fa5558355c7beb7e6204ce Mon Sep 17 00:00:00 2001 From: NP v/d Spek Date: Sun, 24 Nov 2024 21:16:51 +0100 Subject: [PATCH 054/107] [wifi] Make wifi_channel_() public (#7818) --- esphome/components/wifi/wifi_component.cpp | 4 ++-- esphome/components/wifi/wifi_component.h | 4 +++- esphome/components/wifi/wifi_component_esp32_arduino.cpp | 2 +- esphome/components/wifi/wifi_component_esp8266.cpp | 2 +- esphome/components/wifi/wifi_component_esp_idf.cpp | 2 +- esphome/components/wifi/wifi_component_libretiny.cpp | 2 +- esphome/components/wifi/wifi_component_pico_w.cpp | 2 +- 7 files changed, 10 insertions(+), 8 deletions(-) diff --git a/esphome/components/wifi/wifi_component.cpp b/esphome/components/wifi/wifi_component.cpp index 8788711d5a..eef962b8c4 100644 --- a/esphome/components/wifi/wifi_component.cpp +++ b/esphome/components/wifi/wifi_component.cpp @@ -444,7 +444,7 @@ void WiFiComponent::print_connect_params_() { if (this->selected_ap_.get_bssid().has_value()) { ESP_LOGV(TAG, " Priority: %.1f", this->get_sta_priority(*this->selected_ap_.get_bssid())); } - ESP_LOGCONFIG(TAG, " Channel: %" PRId32, wifi_channel_()); + ESP_LOGCONFIG(TAG, " Channel: %" PRId32, get_wifi_channel()); ESP_LOGCONFIG(TAG, " Subnet: %s", wifi_subnet_mask_().str().c_str()); ESP_LOGCONFIG(TAG, " Gateway: %s", wifi_gateway_ip_().str().c_str()); ESP_LOGCONFIG(TAG, " DNS1: %s", wifi_dns_ip_(0).str().c_str()); @@ -763,7 +763,7 @@ void WiFiComponent::load_fast_connect_settings_() { void WiFiComponent::save_fast_connect_settings_() { bssid_t bssid = wifi_bssid(); - uint8_t channel = wifi_channel_(); + uint8_t channel = get_wifi_channel(); if (bssid != this->selected_ap_.get_bssid() || channel != this->selected_ap_.get_channel()) { SavedWifiFastConnectSettings fast_connect_save{}; diff --git a/esphome/components/wifi/wifi_component.h b/esphome/components/wifi/wifi_component.h index dde0d1d5a5..5995f72e0b 100644 --- a/esphome/components/wifi/wifi_component.h +++ b/esphome/components/wifi/wifi_component.h @@ -317,6 +317,8 @@ class WiFiComponent : public Component { Trigger<> *get_connect_trigger() const { return this->connect_trigger_; }; Trigger<> *get_disconnect_trigger() const { return this->disconnect_trigger_; }; + int32_t get_wifi_channel(); + protected: static std::string format_mac_addr(const uint8_t mac[6]); @@ -344,7 +346,7 @@ class WiFiComponent : public Component { #endif // USE_WIFI_AP bool wifi_disconnect_(); - int32_t wifi_channel_(); + network::IPAddress wifi_subnet_mask_(); network::IPAddress wifi_gateway_ip_(); network::IPAddress wifi_dns_ip_(int num); diff --git a/esphome/components/wifi/wifi_component_esp32_arduino.cpp b/esphome/components/wifi/wifi_component_esp32_arduino.cpp index 88648093c6..18c706cb01 100644 --- a/esphome/components/wifi/wifi_component_esp32_arduino.cpp +++ b/esphome/components/wifi/wifi_component_esp32_arduino.cpp @@ -799,7 +799,7 @@ bssid_t WiFiComponent::wifi_bssid() { } std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); } int8_t WiFiComponent::wifi_rssi() { return WiFi.RSSI(); } -int32_t WiFiComponent::wifi_channel_() { return WiFi.channel(); } +int32_t WiFiComponent::get_wifi_channel() { return WiFi.channel(); } network::IPAddress WiFiComponent::wifi_subnet_mask_() { return network::IPAddress(WiFi.subnetMask()); } network::IPAddress WiFiComponent::wifi_gateway_ip_() { return network::IPAddress(WiFi.gatewayIP()); } network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { return network::IPAddress(WiFi.dnsIP(num)); } diff --git a/esphome/components/wifi/wifi_component_esp8266.cpp b/esphome/components/wifi/wifi_component_esp8266.cpp index 4568895950..a18d078967 100644 --- a/esphome/components/wifi/wifi_component_esp8266.cpp +++ b/esphome/components/wifi/wifi_component_esp8266.cpp @@ -825,7 +825,7 @@ bssid_t WiFiComponent::wifi_bssid() { } std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); } int8_t WiFiComponent::wifi_rssi() { return WiFi.RSSI(); } -int32_t WiFiComponent::wifi_channel_() { return WiFi.channel(); } +int32_t WiFiComponent::get_wifi_channel() { return WiFi.channel(); } network::IPAddress WiFiComponent::wifi_subnet_mask_() { return {(const ip_addr_t *) WiFi.subnetMask()}; } network::IPAddress WiFiComponent::wifi_gateway_ip_() { return {(const ip_addr_t *) WiFi.gatewayIP()}; } network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { return {(const ip_addr_t *) WiFi.dnsIP(num)}; } diff --git a/esphome/components/wifi/wifi_component_esp_idf.cpp b/esphome/components/wifi/wifi_component_esp_idf.cpp index 13870136d4..1bf14ff40b 100644 --- a/esphome/components/wifi/wifi_component_esp_idf.cpp +++ b/esphome/components/wifi/wifi_component_esp_idf.cpp @@ -973,7 +973,7 @@ int8_t WiFiComponent::wifi_rssi() { } return info.rssi; } -int32_t WiFiComponent::wifi_channel_() { +int32_t WiFiComponent::get_wifi_channel() { uint8_t primary; wifi_second_chan_t second; esp_err_t err = esp_wifi_get_channel(&primary, &second); diff --git a/esphome/components/wifi/wifi_component_libretiny.cpp b/esphome/components/wifi/wifi_component_libretiny.cpp index afb30c3bcf..b02f8ef0ce 100644 --- a/esphome/components/wifi/wifi_component_libretiny.cpp +++ b/esphome/components/wifi/wifi_component_libretiny.cpp @@ -473,7 +473,7 @@ bssid_t WiFiComponent::wifi_bssid() { } std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); } int8_t WiFiComponent::wifi_rssi() { return WiFi.RSSI(); } -int32_t WiFiComponent::wifi_channel_() { return WiFi.channel(); } +int32_t WiFiComponent::get_wifi_channel() { return WiFi.channel(); } network::IPAddress WiFiComponent::wifi_subnet_mask_() { return {WiFi.subnetMask()}; } network::IPAddress WiFiComponent::wifi_gateway_ip_() { return {WiFi.gatewayIP()}; } network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { return {WiFi.dnsIP(num)}; } diff --git a/esphome/components/wifi/wifi_component_pico_w.cpp b/esphome/components/wifi/wifi_component_pico_w.cpp index bac986d899..23fd766abe 100644 --- a/esphome/components/wifi/wifi_component_pico_w.cpp +++ b/esphome/components/wifi/wifi_component_pico_w.cpp @@ -189,7 +189,7 @@ bssid_t WiFiComponent::wifi_bssid() { } std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); } int8_t WiFiComponent::wifi_rssi() { return WiFi.RSSI(); } -int32_t WiFiComponent::wifi_channel_() { return WiFi.channel(); } +int32_t WiFiComponent::get_wifi_channel() { return WiFi.channel(); } network::IPAddresses WiFiComponent::wifi_sta_ip_addresses() { network::IPAddresses addresses; From 4936ca17003404796d388363469badfab340d8b8 Mon Sep 17 00:00:00 2001 From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com> Date: Mon, 25 Nov 2024 07:25:16 +1100 Subject: [PATCH 055/107] [lvgl] Bugfixes (#7803) --- esphome/components/lvgl/__init__.py | 2 +- esphome/components/lvgl/lv_validation.py | 3 ++- esphome/components/lvgl/schemas.py | 1 + esphome/components/lvgl/widgets/line.py | 5 ++++- 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/esphome/components/lvgl/__init__.py b/esphome/components/lvgl/__init__.py index d03adc9624..8fdd03f647 100644 --- a/esphome/components/lvgl/__init__.py +++ b/esphome/components/lvgl/__init__.py @@ -322,8 +322,8 @@ async def to_code(configs): await encoders_to_code(lv_component, config, default_group) await keypads_to_code(lv_component, config, default_group) await theme_to_code(config) - await styles_to_code(config) await gradients_to_code(config) + await styles_to_code(config) await set_obj_properties(lv_scr_act, config) await add_widgets(lv_scr_act, config) await add_pages(lv_component, config) diff --git a/esphome/components/lvgl/lv_validation.py b/esphome/components/lvgl/lv_validation.py index b91b0905df..766c010244 100644 --- a/esphome/components/lvgl/lv_validation.py +++ b/esphome/components/lvgl/lv_validation.py @@ -30,7 +30,7 @@ from .defines import ( call_lambda, literal, ) -from .helpers import esphome_fonts_used, lv_fonts_used, requires_component +from .helpers import add_lv_use, esphome_fonts_used, lv_fonts_used, requires_component from .types import lv_font_t, lv_gradient_t, lv_img_t opacity_consts = LvConstant("LV_OPA_", "TRANSP", "COVER") @@ -326,6 +326,7 @@ def image_validator(value): value = requires_component("image")(value) value = cv.use_id(Image_)(value) lv_images_used.add(value) + add_lv_use("img", "label") return value diff --git a/esphome/components/lvgl/schemas.py b/esphome/components/lvgl/schemas.py index 516627708e..3f56b3345f 100644 --- a/esphome/components/lvgl/schemas.py +++ b/esphome/components/lvgl/schemas.py @@ -341,6 +341,7 @@ FLEX_OBJ_SCHEMA = { cv.Optional(df.CONF_FLEX_GROW): cv.int_, } + DISP_BG_SCHEMA = cv.Schema( { cv.Optional(df.CONF_DISP_BG_IMAGE): lv_image, diff --git a/esphome/components/lvgl/widgets/line.py b/esphome/components/lvgl/widgets/line.py index 4c6439fde4..548dfa8452 100644 --- a/esphome/components/lvgl/widgets/line.py +++ b/esphome/components/lvgl/widgets/line.py @@ -39,7 +39,10 @@ LINE_SCHEMA = { class LineType(WidgetType): def __init__(self): super().__init__( - CONF_LINE, LvType("lv_line_t"), (CONF_MAIN,), LINE_SCHEMA, modify_schema={} + CONF_LINE, + LvType("lv_line_t"), + (CONF_MAIN,), + LINE_SCHEMA, ) async def to_code(self, w: Widget, config): From 4001d82ca269472b6ef813fa4b894e1071d5571e Mon Sep 17 00:00:00 2001 From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com> Date: Mon, 25 Nov 2024 07:25:51 +1100 Subject: [PATCH 056/107] [docker] Leave run-time required libraries installed. (#7804) --- docker/Dockerfile | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index ed6ce083a8..c2902a9dd1 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -99,15 +99,17 @@ BUILD_DEPS=" libfreetype-dev=2.12.1+dfsg-5+deb12u3 libssl-dev=3.0.15-1~deb12u1 libffi-dev=3.4.4-1 - libopenjp2-7=2.5.0-2 - libtiff6=4.5.0-6+deb12u1 cargo=0.66.0+ds1-1 pkg-config=1.8.1-1 " +LIB_DEPS=" + libtiff6=4.5.0-6+deb12u1 + libopenjp2-7=2.5.0-2 +" if [ "$TARGETARCH$TARGETVARIANT" = "arm64" ] || [ "$TARGETARCH$TARGETVARIANT" = "armv7" ] then apt-get update - apt-get install -y --no-install-recommends $BUILD_DEPS + apt-get install -y --no-install-recommends $BUILD_DEPS $LIB_DEPS fi CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse CARGO_HOME=/root/.cargo From 13077095c2ece197c41c41324d578cb2a284edd8 Mon Sep 17 00:00:00 2001 From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com> Date: Mon, 25 Nov 2024 07:27:09 +1100 Subject: [PATCH 057/107] [qspi_dbi] Fix init sequences (Bugfix) (#7805) --- esphome/components/qspi_dbi/models.py | 2 ++ esphome/components/qspi_dbi/qspi_dbi.cpp | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/esphome/components/qspi_dbi/models.py b/esphome/components/qspi_dbi/models.py index cbd9c4663f..c1fe434853 100644 --- a/esphome/components/qspi_dbi/models.py +++ b/esphome/components/qspi_dbi/models.py @@ -1,6 +1,7 @@ # Commands SW_RESET_CMD = 0x01 SLEEP_OUT = 0x11 +NORON = 0x13 INVERT_OFF = 0x20 INVERT_ON = 0x21 ALL_ON = 0x23 @@ -56,6 +57,7 @@ chip.cmd(0xC2, 0x00) chip.delay(10) chip.cmd(TEON, 0x00) chip.cmd(PIXFMT, 0x55) +chip.cmd(NORON) chip = DriverChip("AXS15231") chip.cmd(0xBB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5A, 0xA5) diff --git a/esphome/components/qspi_dbi/qspi_dbi.cpp b/esphome/components/qspi_dbi/qspi_dbi.cpp index a649a25ea6..785885d4ec 100644 --- a/esphome/components/qspi_dbi/qspi_dbi.cpp +++ b/esphome/components/qspi_dbi/qspi_dbi.cpp @@ -111,7 +111,6 @@ void QspiDbi::reset_params_(bool ready) { mad |= MADCTL_MY; this->write_command_(MADCTL_CMD, mad); this->write_command_(BRIGHTNESS, this->brightness_); - this->write_command_(NORON); this->write_command_(DISPLAY_ON); } From e3e3d9234756b94a74f3788f64aa4d9b37d40f7a Mon Sep 17 00:00:00 2001 From: Samuel Sieb Date: Sun, 24 Nov 2024 10:42:46 -1000 Subject: [PATCH 058/107] fix modbus crashing when bad data returned (#7810) Co-authored-by: Samuel Sieb --- esphome/components/modbus/modbus.cpp | 3 +- .../modbus_controller/modbus_controller.cpp | 72 ++++++++++++++----- 2 files changed, 56 insertions(+), 19 deletions(-) diff --git a/esphome/components/modbus/modbus.cpp b/esphome/components/modbus/modbus.cpp index 8544b50261..47deea83e6 100644 --- a/esphome/components/modbus/modbus.cpp +++ b/esphome/components/modbus/modbus.cpp @@ -38,8 +38,9 @@ void Modbus::loop() { // stop blocking new send commands after sent_wait_time_ ms after response received if (now - this->last_send_ > send_wait_time_) { - if (waiting_for_response > 0) + if (waiting_for_response > 0) { ESP_LOGV(TAG, "Stop waiting for response from %d", waiting_for_response); + } waiting_for_response = 0; } } diff --git a/esphome/components/modbus_controller/modbus_controller.cpp b/esphome/components/modbus_controller/modbus_controller.cpp index e1102516ca..f8b72af817 100644 --- a/esphome/components/modbus_controller/modbus_controller.cpp +++ b/esphome/components/modbus_controller/modbus_controller.cpp @@ -622,51 +622,87 @@ int64_t payload_to_number(const std::vector &data, SensorValueType sens uint32_t bitmask) { int64_t value = 0; // int64_t because it can hold signed and unsigned 32 bits + size_t size = data.size() - offset; + bool error = false; switch (sensor_value_type) { case SensorValueType::U_WORD: - value = mask_and_shift_by_rightbit(get_data(data, offset), bitmask); // default is 0xFFFF ; + if (size >= 2) { + value = mask_and_shift_by_rightbit(get_data(data, offset), bitmask); // default is 0xFFFF ; + } else { + error = true; + } break; case SensorValueType::U_DWORD: case SensorValueType::FP32: - value = get_data(data, offset); - value = mask_and_shift_by_rightbit((uint32_t) value, bitmask); + if (size >= 4) { + value = get_data(data, offset); + value = mask_and_shift_by_rightbit((uint32_t) value, bitmask); + } else { + error = true; + } break; case SensorValueType::U_DWORD_R: case SensorValueType::FP32_R: - value = get_data(data, offset); - value = static_cast(value & 0xFFFF) << 16 | (value & 0xFFFF0000) >> 16; - value = mask_and_shift_by_rightbit((uint32_t) value, bitmask); + if (size >= 4) { + value = get_data(data, offset); + value = static_cast(value & 0xFFFF) << 16 | (value & 0xFFFF0000) >> 16; + value = mask_and_shift_by_rightbit((uint32_t) value, bitmask); + } else { + error = true; + } break; case SensorValueType::S_WORD: - value = mask_and_shift_by_rightbit(get_data(data, offset), - bitmask); // default is 0xFFFF ; + if (size >= 2) { + value = mask_and_shift_by_rightbit(get_data(data, offset), + bitmask); // default is 0xFFFF ; + } else { + error = true; + } break; case SensorValueType::S_DWORD: - value = mask_and_shift_by_rightbit(get_data(data, offset), bitmask); + if (size >= 4) { + value = mask_and_shift_by_rightbit(get_data(data, offset), bitmask); + } else { + error = true; + } break; case SensorValueType::S_DWORD_R: { - value = get_data(data, offset); - // Currently the high word is at the low position - // the sign bit is therefore at low before the switch - uint32_t sign_bit = (value & 0x8000) << 16; - value = mask_and_shift_by_rightbit( - static_cast(((value & 0x7FFF) << 16 | (value & 0xFFFF0000) >> 16) | sign_bit), bitmask); + if (size >= 4) { + value = get_data(data, offset); + // Currently the high word is at the low position + // the sign bit is therefore at low before the switch + uint32_t sign_bit = (value & 0x8000) << 16; + value = mask_and_shift_by_rightbit( + static_cast(((value & 0x7FFF) << 16 | (value & 0xFFFF0000) >> 16) | sign_bit), bitmask); + } else { + error = true; + } } break; case SensorValueType::U_QWORD: case SensorValueType::S_QWORD: // Ignore bitmask for QWORD - value = get_data(data, offset); + if (size >= 8) { + value = get_data(data, offset); + } else { + error = true; + } break; case SensorValueType::U_QWORD_R: case SensorValueType::S_QWORD_R: { // Ignore bitmask for QWORD - uint64_t tmp = get_data(data, offset); - value = (tmp << 48) | (tmp >> 48) | ((tmp & 0xFFFF0000) << 16) | ((tmp >> 16) & 0xFFFF0000); + if (size >= 8) { + uint64_t tmp = get_data(data, offset); + value = (tmp << 48) | (tmp >> 48) | ((tmp & 0xFFFF0000) << 16) | ((tmp >> 16) & 0xFFFF0000); + } else { + error = true; + } } break; case SensorValueType::RAW: default: break; } + if (error) + ESP_LOGE(TAG, "not enough data for value"); return value; } From 9fc1377b448fab25c91e3342834a0b38df0c4a80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20Mart=C3=ADn?= Date: Sun, 24 Nov 2024 23:06:21 +0100 Subject: [PATCH 059/107] feat(WiFi): Add wifi.configure action (#7335) --- esphome/components/wifi/__init__.py | 42 +++++++++++++ esphome/components/wifi/wifi_component.h | 79 ++++++++++++++++++++++++ tests/components/wifi/common.yaml | 7 +++ 3 files changed, 128 insertions(+) diff --git a/esphome/components/wifi/__init__.py b/esphome/components/wifi/__init__.py index ea03cc16d1..ad1a4f5262 100644 --- a/esphome/components/wifi/__init__.py +++ b/esphome/components/wifi/__init__.py @@ -27,6 +27,7 @@ from esphome.const import ( CONF_NETWORKS, CONF_ON_CONNECT, CONF_ON_DISCONNECT, + CONF_ON_ERROR, CONF_PASSWORD, CONF_POWER_SAVE_MODE, CONF_PRIORITY, @@ -34,6 +35,7 @@ from esphome.const import ( CONF_SSID, CONF_STATIC_IP, CONF_SUBNET, + CONF_TIMEOUT, CONF_TTLS_PHASE_2, CONF_USE_ADDRESS, CONF_USERNAME, @@ -46,6 +48,7 @@ from . import wpa2_eap AUTO_LOAD = ["network"] NO_WIFI_VARIANTS = [const.VARIANT_ESP32H2] +CONF_SAVE = "save" wifi_ns = cg.esphome_ns.namespace("wifi") EAPAuth = wifi_ns.struct("EAPAuth") @@ -63,6 +66,9 @@ WiFiConnectedCondition = wifi_ns.class_("WiFiConnectedCondition", Condition) WiFiEnabledCondition = wifi_ns.class_("WiFiEnabledCondition", Condition) WiFiEnableAction = wifi_ns.class_("WiFiEnableAction", automation.Action) WiFiDisableAction = wifi_ns.class_("WiFiDisableAction", automation.Action) +WiFiConfigureAction = wifi_ns.class_( + "WiFiConfigureAction", automation.Action, cg.Component +) def validate_password(value): @@ -483,3 +489,39 @@ async def wifi_enable_to_code(config, action_id, template_arg, args): @automation.register_action("wifi.disable", WiFiDisableAction, cv.Schema({})) async def wifi_disable_to_code(config, action_id, template_arg, args): return cg.new_Pvariable(action_id, template_arg) + + +@automation.register_action( + "wifi.configure", + WiFiConfigureAction, + cv.Schema( + { + cv.Required(CONF_SSID): cv.templatable(cv.ssid), + cv.Required(CONF_PASSWORD): cv.templatable(validate_password), + cv.Optional(CONF_SAVE, default=True): cv.templatable(cv.boolean), + cv.Optional(CONF_TIMEOUT, default="30000ms"): cv.templatable( + cv.positive_time_period_milliseconds + ), + cv.Optional(CONF_ON_CONNECT): automation.validate_automation(single=True), + cv.Optional(CONF_ON_ERROR): automation.validate_automation(single=True), + } + ), +) +async def wifi_set_sta_to_code(config, action_id, template_arg, args): + var = cg.new_Pvariable(action_id, template_arg) + ssid = await cg.templatable(config[CONF_SSID], args, cg.std_string) + password = await cg.templatable(config[CONF_PASSWORD], args, cg.std_string) + save = await cg.templatable(config[CONF_SAVE], args, cg.bool_) + timeout = await cg.templatable(config.get(CONF_TIMEOUT), args, cg.uint32) + cg.add(var.set_ssid(ssid)) + cg.add(var.set_password(password)) + cg.add(var.set_save(save)) + cg.add(var.set_connection_timeout(timeout)) + if on_connect_config := config.get(CONF_ON_CONNECT): + await automation.build_automation( + var.get_connect_trigger(), [], on_connect_config + ) + if on_error_config := config.get(CONF_ON_ERROR): + await automation.build_automation(var.get_error_trigger(), [], on_error_config) + await cg.register_component(var, config) + return var diff --git a/esphome/components/wifi/wifi_component.h b/esphome/components/wifi/wifi_component.h index 5995f72e0b..abedfab3a6 100644 --- a/esphome/components/wifi/wifi_component.h +++ b/esphome/components/wifi/wifi_component.h @@ -209,6 +209,7 @@ class WiFiComponent : public Component { WiFiComponent(); void set_sta(const WiFiAP &ap); + WiFiAP get_sta() { return this->selected_ap_; } void add_sta(const WiFiAP &ap); void clear_sta(); @@ -443,6 +444,84 @@ template class WiFiDisableAction : public Action { void play(Ts... x) override { global_wifi_component->disable(); } }; +template class WiFiConfigureAction : public Action, public Component { + public: + TEMPLATABLE_VALUE(std::string, ssid) + TEMPLATABLE_VALUE(std::string, password) + TEMPLATABLE_VALUE(bool, save) + TEMPLATABLE_VALUE(uint32_t, connection_timeout) + + void play(Ts... x) override { + auto ssid = this->ssid_.value(x...); + auto password = this->password_.value(x...); + // Avoid multiple calls + if (this->connecting_) + return; + // If already connected to the same AP, do nothing + if (global_wifi_component->wifi_ssid() == ssid) { + // Callback to notify the user that the connection was successful + this->connect_trigger_->trigger(); + return; + } + // Create a new WiFiAP object with the new SSID and password + this->new_sta_.set_ssid(ssid); + this->new_sta_.set_password(password); + // Save the current STA + this->old_sta_ = global_wifi_component->get_sta(); + // Disable WiFi + global_wifi_component->disable(); + // Set the state to connecting + this->connecting_ = true; + // Store the new STA so once the WiFi is enabled, it will connect to it + // This is necessary because the WiFiComponent will raise an error and fallback to the saved STA + // if trying to connect to a new STA while already connected to another one + if (this->save_.value(x...)) { + global_wifi_component->save_wifi_sta(new_sta_.get_ssid(), new_sta_.get_password()); + } else { + global_wifi_component->set_sta(new_sta_); + } + // Enable WiFi + global_wifi_component->enable(); + // Set timeout for the connection + this->set_timeout("wifi-connect-timeout", this->connection_timeout_.value(x...), [this]() { + this->connecting_ = false; + // If the timeout is reached, stop connecting and revert to the old AP + global_wifi_component->disable(); + global_wifi_component->save_wifi_sta(old_sta_.get_ssid(), old_sta_.get_password()); + global_wifi_component->enable(); + // Callback to notify the user that the connection failed + this->error_trigger_->trigger(); + }); + } + + Trigger<> *get_connect_trigger() const { return this->connect_trigger_; } + Trigger<> *get_error_trigger() const { return this->error_trigger_; } + + void loop() override { + if (!this->connecting_) + return; + if (global_wifi_component->is_connected()) { + // The WiFi is connected, stop the timeout and reset the connecting flag + this->cancel_timeout("wifi-connect-timeout"); + this->connecting_ = false; + if (global_wifi_component->wifi_ssid() == this->new_sta_.get_ssid()) { + // Callback to notify the user that the connection was successful + this->connect_trigger_->trigger(); + } else { + // Callback to notify the user that the connection failed + this->error_trigger_->trigger(); + } + } + } + + protected: + bool connecting_{false}; + WiFiAP new_sta_; + WiFiAP old_sta_; + Trigger<> *connect_trigger_{new Trigger<>()}; + Trigger<> *error_trigger_{new Trigger<>()}; +}; + } // namespace wifi } // namespace esphome #endif diff --git a/tests/components/wifi/common.yaml b/tests/components/wifi/common.yaml index 003f6347be..343d44b177 100644 --- a/tests/components/wifi/common.yaml +++ b/tests/components/wifi/common.yaml @@ -3,6 +3,13 @@ esphome: then: - wifi.disable - wifi.enable + - wifi.configure: + ssid: MySSID + password: password1 + on_connect: + - logger.log: "Connected to WiFi!" + on_error: + - logger.log: "Failed to connect to WiFi!" wifi: ssid: MySSID From d4d630823ccc3bdddb6e6b39176c188d353d0807 Mon Sep 17 00:00:00 2001 From: TFGF Date: Sun, 24 Nov 2024 19:15:10 -0300 Subject: [PATCH 060/107] [Modbus Controller] Fix issue #6477. Online automation triggering Offline (#7801) --- esphome/components/modbus_controller/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/modbus_controller/__init__.py b/esphome/components/modbus_controller/__init__.py index 5c407d6fff..2a08075831 100644 --- a/esphome/components/modbus_controller/__init__.py +++ b/esphome/components/modbus_controller/__init__.py @@ -163,7 +163,7 @@ CONFIG_SCHEMA = cv.All( ), cv.Optional(CONF_ON_OFFLINE): automation.validate_automation( { - cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(ModbusOnlineTrigger), + cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(ModbusOfflineTrigger), } ), } From e02f3cdac7b7e8a58711763b5d7f9dfac8ea6991 Mon Sep 17 00:00:00 2001 From: Ramil Valitov Date: Mon, 25 Nov 2024 01:23:30 +0300 Subject: [PATCH 061/107] [fix] Status sensor does not check if required network component is missing (#7734) Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com> --- esphome/components/status/binary_sensor.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/esphome/components/status/binary_sensor.py b/esphome/components/status/binary_sensor.py index 1f2b7c9d18..adc342ed4d 100644 --- a/esphome/components/status/binary_sensor.py +++ b/esphome/components/status/binary_sensor.py @@ -6,6 +6,8 @@ from esphome.const import ( ENTITY_CATEGORY_DIAGNOSTIC, ) +DEPENDENCIES = ["network"] + status_ns = cg.esphome_ns.namespace("status") StatusBinarySensor = status_ns.class_( "StatusBinarySensor", binary_sensor.BinarySensor, cg.Component From 59653ec7853a349e9e736710867daedc017a725e Mon Sep 17 00:00:00 2001 From: Samuel Sieb Date: Sun, 24 Nov 2024 12:40:28 -1000 Subject: [PATCH 062/107] allow multiple graphical menus (#7809) Co-authored-by: Samuel Sieb --- esphome/components/display_menu_base/__init__.py | 2 -- esphome/components/graphical_display_menu/__init__.py | 2 ++ 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/esphome/components/display_menu_base/__init__.py b/esphome/components/display_menu_base/__init__.py index 8ae9cbc2a4..f9c0424104 100644 --- a/esphome/components/display_menu_base/__init__.py +++ b/esphome/components/display_menu_base/__init__.py @@ -68,8 +68,6 @@ IsActiveCondition = display_menu_base_ns.class_( "IsActiveCondition", automation.Condition ) -MULTI_CONF = True - MenuItemType = display_menu_base_ns.enum("MenuItemType") MENU_ITEM_TYPES = { diff --git a/esphome/components/graphical_display_menu/__init__.py b/esphome/components/graphical_display_menu/__init__.py index f4d59b22b8..56b720e75c 100644 --- a/esphome/components/graphical_display_menu/__init__.py +++ b/esphome/components/graphical_display_menu/__init__.py @@ -36,6 +36,8 @@ CODEOWNERS = ["@MrMDavidson"] AUTO_LOAD = ["display_menu_base"] +MULTI_CONF = True + CONFIG_SCHEMA = DISPLAY_MENU_BASE_SCHEMA.extend( cv.Schema( { From b95b4a069417ea6fd31f96b5e9150ca16dd1c3f5 Mon Sep 17 00:00:00 2001 From: Samuel Sieb Date: Sun, 24 Nov 2024 12:40:51 -1000 Subject: [PATCH 063/107] keypad binary sensors should be initially off (#7808) Co-authored-by: Samuel Sieb --- esphome/components/binary_sensor/binary_sensor.h | 2 +- .../matrix_keypad/binary_sensor/matrix_keypad_binary_sensor.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/esphome/components/binary_sensor/binary_sensor.h b/esphome/components/binary_sensor/binary_sensor.h index 301a472810..57cae9e2f5 100644 --- a/esphome/components/binary_sensor/binary_sensor.h +++ b/esphome/components/binary_sensor/binary_sensor.h @@ -58,7 +58,7 @@ class BinarySensor : public EntityBase, public EntityBase_DeviceClass { void publish_initial_state(bool state); /// The current reported state of the binary sensor. - bool state; + bool state{false}; void add_filter(Filter *filter); void add_filters(const std::vector &filters); diff --git a/esphome/components/matrix_keypad/binary_sensor/matrix_keypad_binary_sensor.h b/esphome/components/matrix_keypad/binary_sensor/matrix_keypad_binary_sensor.h index d8a217f55e..2c1ce96f0a 100644 --- a/esphome/components/matrix_keypad/binary_sensor/matrix_keypad_binary_sensor.h +++ b/esphome/components/matrix_keypad/binary_sensor/matrix_keypad_binary_sensor.h @@ -6,7 +6,7 @@ namespace esphome { namespace matrix_keypad { -class MatrixKeypadBinarySensor : public MatrixKeypadListener, public binary_sensor::BinarySensor { +class MatrixKeypadBinarySensor : public MatrixKeypadListener, public binary_sensor::BinarySensorInitiallyOff { public: MatrixKeypadBinarySensor(uint8_t key) : has_key_(true), key_(key){}; MatrixKeypadBinarySensor(const char *key) : has_key_(true), key_((uint8_t) key[0]){}; From 71496574e9e104433ded1f4da497454b1b266e3d Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Mon, 25 Nov 2024 17:26:36 +1300 Subject: [PATCH 064/107] Move ``CONF_NAME_ADD_MAC_SUFFIX`` to ``const.py`` (#7820) --- esphome/const.py | 1 + esphome/core/config.py | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/esphome/const.py b/esphome/const.py index 6a643e1e30..50528b7363 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -528,6 +528,7 @@ CONF_MULTIPLE = "multiple" CONF_MULTIPLEXER = "multiplexer" CONF_MULTIPLY = "multiply" CONF_NAME = "name" +CONF_NAME_ADD_MAC_SUFFIX = "name_add_mac_suffix" CONF_NAME_FONT = "name_font" CONF_NBITS = "nbits" CONF_NEC = "nec" diff --git a/esphome/core/config.py b/esphome/core/config.py index 367e61c413..eee8b73934 100644 --- a/esphome/core/config.py +++ b/esphome/core/config.py @@ -21,6 +21,7 @@ from esphome.const import ( CONF_LIBRARIES, CONF_MIN_VERSION, CONF_NAME, + CONF_NAME_ADD_MAC_SUFFIX, CONF_ON_BOOT, CONF_ON_LOOP, CONF_ON_SHUTDOWN, @@ -59,8 +60,6 @@ ProjectUpdateTrigger = cg.esphome_ns.class_( VERSION_REGEX = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+(?:[ab]\d+)?$") -CONF_NAME_ADD_MAC_SUFFIX = "name_add_mac_suffix" - VALID_INCLUDE_EXTS = {".h", ".hpp", ".tcc", ".ino", ".cpp", ".c"} From c49f7293fef3c052691f388b6c9af6f8709b7aca Mon Sep 17 00:00:00 2001 From: Samuel Sieb Date: Sun, 24 Nov 2024 21:24:23 -1000 Subject: [PATCH 065/107] binary_sensor for switch state (#7819) --- CODEOWNERS | 1 + .../switch/binary_sensor/__init__.py | 31 +++++++++++++++++++ .../binary_sensor/switch_binary_sensor.cpp | 17 ++++++++++ .../binary_sensor/switch_binary_sensor.h | 22 +++++++++++++ tests/components/switch/common.yaml | 11 +++++++ tests/components/switch/test.bk72xx-ard.yaml | 2 ++ tests/components/switch/test.esp32-ard.yaml | 2 ++ .../components/switch/test.esp32-c3-ard.yaml | 2 ++ .../components/switch/test.esp32-c3-idf.yaml | 2 ++ tests/components/switch/test.esp32-idf.yaml | 2 ++ .../components/switch/test.esp32-s3-idf.yaml | 2 ++ tests/components/switch/test.esp8266-ard.yaml | 2 ++ tests/components/switch/test.rp2040-ard.yaml | 2 ++ 13 files changed, 98 insertions(+) create mode 100644 esphome/components/switch/binary_sensor/__init__.py create mode 100644 esphome/components/switch/binary_sensor/switch_binary_sensor.cpp create mode 100644 esphome/components/switch/binary_sensor/switch_binary_sensor.h create mode 100644 tests/components/switch/common.yaml create mode 100644 tests/components/switch/test.bk72xx-ard.yaml create mode 100644 tests/components/switch/test.esp32-ard.yaml create mode 100644 tests/components/switch/test.esp32-c3-ard.yaml create mode 100644 tests/components/switch/test.esp32-c3-idf.yaml create mode 100644 tests/components/switch/test.esp32-idf.yaml create mode 100644 tests/components/switch/test.esp32-s3-idf.yaml create mode 100644 tests/components/switch/test.esp8266-ard.yaml create mode 100644 tests/components/switch/test.rp2040-ard.yaml diff --git a/CODEOWNERS b/CODEOWNERS index 8fbbacef59..dd3926d283 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -408,6 +408,7 @@ esphome/components/substitutions/* @esphome/core esphome/components/sun/* @OttoWinter esphome/components/sun_gtil2/* @Mat931 esphome/components/switch/* @esphome/core +esphome/components/switch/binary_sensor/* @ssieb esphome/components/t6615/* @tylermenezes esphome/components/tc74/* @sethgirvan esphome/components/tca9548a/* @andreashergert1984 diff --git a/esphome/components/switch/binary_sensor/__init__.py b/esphome/components/switch/binary_sensor/__init__.py new file mode 100644 index 0000000000..61ca1a14a2 --- /dev/null +++ b/esphome/components/switch/binary_sensor/__init__.py @@ -0,0 +1,31 @@ +import esphome.codegen as cg +from esphome.components import binary_sensor +import esphome.config_validation as cv +from esphome.const import CONF_SOURCE_ID + +from .. import Switch, switch_ns + +CODEOWNERS = ["@ssieb"] + +SwitchBinarySensor = switch_ns.class_( + "SwitchBinarySensor", binary_sensor.BinarySensor, cg.Component +) + + +CONFIG_SCHEMA = ( + binary_sensor.binary_sensor_schema(SwitchBinarySensor) + .extend( + { + cv.Required(CONF_SOURCE_ID): cv.use_id(Switch), + } + ) + .extend(cv.COMPONENT_SCHEMA) +) + + +async def to_code(config): + var = await binary_sensor.new_binary_sensor(config) + await cg.register_component(var, config) + + source = await cg.get_variable(config[CONF_SOURCE_ID]) + cg.add(var.set_source(source)) diff --git a/esphome/components/switch/binary_sensor/switch_binary_sensor.cpp b/esphome/components/switch/binary_sensor/switch_binary_sensor.cpp new file mode 100644 index 0000000000..ba57154446 --- /dev/null +++ b/esphome/components/switch/binary_sensor/switch_binary_sensor.cpp @@ -0,0 +1,17 @@ +#include "switch_binary_sensor.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace switch_ { + +static const char *const TAG = "switch.binary_sensor"; + +void SwitchBinarySensor::setup() { + source_->add_on_state_callback([this](bool value) { this->publish_state(value); }); + this->publish_state(source_->state); +} + +void SwitchBinarySensor::dump_config() { LOG_BINARY_SENSOR("", "Switch Binary Sensor", this); } + +} // namespace switch_ +} // namespace esphome diff --git a/esphome/components/switch/binary_sensor/switch_binary_sensor.h b/esphome/components/switch/binary_sensor/switch_binary_sensor.h new file mode 100644 index 0000000000..5a947c2fb4 --- /dev/null +++ b/esphome/components/switch/binary_sensor/switch_binary_sensor.h @@ -0,0 +1,22 @@ +#pragma once + +#include "../switch.h" +#include "esphome/core/component.h" +#include "esphome/components/binary_sensor/binary_sensor.h" + +namespace esphome { +namespace switch_ { + +class SwitchBinarySensor : public binary_sensor::BinarySensor, public Component { + public: + void set_source(Switch *source) { source_ = source; } + void setup() override; + void dump_config() override; + float get_setup_priority() const override { return setup_priority::DATA; } + + protected: + Switch *source_; +}; + +} // namespace switch_ +} // namespace esphome diff --git a/tests/components/switch/common.yaml b/tests/components/switch/common.yaml new file mode 100644 index 0000000000..8d6972f91b --- /dev/null +++ b/tests/components/switch/common.yaml @@ -0,0 +1,11 @@ +binary_sensor: + - platform: switch + id: some_binary_sensor + name: "Template Switch State" + source_id: the_switch + +switch: + - platform: template + name: "Template Switch" + id: the_switch + optimistic: true diff --git a/tests/components/switch/test.bk72xx-ard.yaml b/tests/components/switch/test.bk72xx-ard.yaml new file mode 100644 index 0000000000..25cb37a0b4 --- /dev/null +++ b/tests/components/switch/test.bk72xx-ard.yaml @@ -0,0 +1,2 @@ +packages: + common: !include common.yaml diff --git a/tests/components/switch/test.esp32-ard.yaml b/tests/components/switch/test.esp32-ard.yaml new file mode 100644 index 0000000000..25cb37a0b4 --- /dev/null +++ b/tests/components/switch/test.esp32-ard.yaml @@ -0,0 +1,2 @@ +packages: + common: !include common.yaml diff --git a/tests/components/switch/test.esp32-c3-ard.yaml b/tests/components/switch/test.esp32-c3-ard.yaml new file mode 100644 index 0000000000..25cb37a0b4 --- /dev/null +++ b/tests/components/switch/test.esp32-c3-ard.yaml @@ -0,0 +1,2 @@ +packages: + common: !include common.yaml diff --git a/tests/components/switch/test.esp32-c3-idf.yaml b/tests/components/switch/test.esp32-c3-idf.yaml new file mode 100644 index 0000000000..25cb37a0b4 --- /dev/null +++ b/tests/components/switch/test.esp32-c3-idf.yaml @@ -0,0 +1,2 @@ +packages: + common: !include common.yaml diff --git a/tests/components/switch/test.esp32-idf.yaml b/tests/components/switch/test.esp32-idf.yaml new file mode 100644 index 0000000000..25cb37a0b4 --- /dev/null +++ b/tests/components/switch/test.esp32-idf.yaml @@ -0,0 +1,2 @@ +packages: + common: !include common.yaml diff --git a/tests/components/switch/test.esp32-s3-idf.yaml b/tests/components/switch/test.esp32-s3-idf.yaml new file mode 100644 index 0000000000..25cb37a0b4 --- /dev/null +++ b/tests/components/switch/test.esp32-s3-idf.yaml @@ -0,0 +1,2 @@ +packages: + common: !include common.yaml diff --git a/tests/components/switch/test.esp8266-ard.yaml b/tests/components/switch/test.esp8266-ard.yaml new file mode 100644 index 0000000000..25cb37a0b4 --- /dev/null +++ b/tests/components/switch/test.esp8266-ard.yaml @@ -0,0 +1,2 @@ +packages: + common: !include common.yaml diff --git a/tests/components/switch/test.rp2040-ard.yaml b/tests/components/switch/test.rp2040-ard.yaml new file mode 100644 index 0000000000..25cb37a0b4 --- /dev/null +++ b/tests/components/switch/test.rp2040-ard.yaml @@ -0,0 +1,2 @@ +packages: + common: !include common.yaml From 7f75f2135d74c6daaaf5251c12a3a1f986ec6694 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 02:22:50 -0600 Subject: [PATCH 066/107] [nextion] Remove assignment within `if` (#7824) --- esphome/components/nextion/nextion_upload_idf.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/esphome/components/nextion/nextion_upload_idf.cpp b/esphome/components/nextion/nextion_upload_idf.cpp index b5bb5478c1..7541a57d56 100644 --- a/esphome/components/nextion/nextion_upload_idf.cpp +++ b/esphome/components/nextion/nextion_upload_idf.cpp @@ -36,8 +36,8 @@ int Nextion::upload_by_chunks_(esp_http_client_handle_t http_client, uint32_t &r ESP_LOGV(TAG, "Requesting range: %s", range_header); esp_http_client_set_header(http_client, "Range", range_header); ESP_LOGV(TAG, "Opening HTTP connetion"); - esp_err_t err; - if ((err = esp_http_client_open(http_client, 0)) != ESP_OK) { + esp_err_t err = esp_http_client_open(http_client, 0); + if (err != ESP_OK) { ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err)); return -1; } From 6c548a15966b0486226d0fd7c33a105b6776d3f4 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 02:23:00 -0600 Subject: [PATCH 067/107] [ota] `void` functions should return nothing (#7825) --- esphome/components/ota/automation.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/ota/automation.h b/esphome/components/ota/automation.h index 4605193480..7e1a60f3ce 100644 --- a/esphome/components/ota/automation.h +++ b/esphome/components/ota/automation.h @@ -12,7 +12,7 @@ class OTAStateChangeTrigger : public Trigger { explicit OTAStateChangeTrigger(OTAComponent *parent) { parent->add_on_state_callback([this, parent](OTAState state, float progress, uint8_t error) { if (!parent->is_failed()) { - return trigger(state); + trigger(state); } }); } From 46a435f5f2ec8f8dfb306f953280b5b2be265195 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 02:24:35 -0600 Subject: [PATCH 068/107] [safe_mode] Remove unused capture (#7826) --- esphome/components/safe_mode/automation.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/safe_mode/automation.h b/esphome/components/safe_mode/automation.h index d1388449ee..1ffa86a588 100644 --- a/esphome/components/safe_mode/automation.h +++ b/esphome/components/safe_mode/automation.h @@ -9,7 +9,7 @@ namespace safe_mode { class SafeModeTrigger : public Trigger<> { public: explicit SafeModeTrigger(SafeModeComponent *parent) { - parent->add_on_safe_mode_callback([this, parent]() { trigger(); }); + parent->add_on_safe_mode_callback([this]() { trigger(); }); } }; From ebf895990b494ec8c09b7dbab051b0d53cc2d029 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 02:25:04 -0600 Subject: [PATCH 069/107] [stepper] Remove unnecessary ``#include`` (#7827) --- esphome/components/stepper/stepper.h | 1 - 1 file changed, 1 deletion(-) diff --git a/esphome/components/stepper/stepper.h b/esphome/components/stepper/stepper.h index 560362e4d0..ba2b3182d7 100644 --- a/esphome/components/stepper/stepper.h +++ b/esphome/components/stepper/stepper.h @@ -2,7 +2,6 @@ #include "esphome/core/component.h" #include "esphome/core/automation.h" -#include "esphome/components/stepper/stepper.h" namespace esphome { namespace stepper { From aa6cea6f7e4ea4b656fa6d3a152581e623227bd3 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 02:27:36 -0600 Subject: [PATCH 070/107] [sx1509] Fix up includes (#7828) --- esphome/components/sx1509/sx1509_gpio_pin.cpp | 3 ++- esphome/components/sx1509/sx1509_gpio_pin.h | 10 +++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/esphome/components/sx1509/sx1509_gpio_pin.cpp b/esphome/components/sx1509/sx1509_gpio_pin.cpp index 56b51ae311..a74c8b60b8 100644 --- a/esphome/components/sx1509/sx1509_gpio_pin.cpp +++ b/esphome/components/sx1509/sx1509_gpio_pin.cpp @@ -1,5 +1,6 @@ #include "esphome/core/helpers.h" #include "esphome/core/log.h" +#include "sx1509.h" #include "sx1509_gpio_pin.h" namespace esphome { @@ -13,7 +14,7 @@ bool SX1509GPIOPin::digital_read() { return this->parent_->digital_read(this->pi void SX1509GPIOPin::digital_write(bool value) { this->parent_->digital_write(this->pin_, value != this->inverted_); } std::string SX1509GPIOPin::dump_summary() const { char buffer[32]; - snprintf(buffer, sizeof(buffer), "%u via sx1509", pin_); + snprintf(buffer, sizeof(buffer), "%u via sx1509", this->pin_); return buffer; } diff --git a/esphome/components/sx1509/sx1509_gpio_pin.h b/esphome/components/sx1509/sx1509_gpio_pin.h index 4d8aa5ec83..1cfa341ee7 100644 --- a/esphome/components/sx1509/sx1509_gpio_pin.h +++ b/esphome/components/sx1509/sx1509_gpio_pin.h @@ -1,6 +1,6 @@ #pragma once -#include "sx1509.h" +#include "esphome/core/gpio.h" namespace esphome { namespace sx1509 { @@ -15,10 +15,10 @@ class SX1509GPIOPin : public GPIOPin { void digital_write(bool value) override; std::string dump_summary() const override; - void set_parent(SX1509Component *parent) { parent_ = parent; } - void set_pin(uint8_t pin) { pin_ = pin; } - void set_inverted(bool inverted) { inverted_ = inverted; } - void set_flags(gpio::Flags flags) { flags_ = flags; } + void set_parent(SX1509Component *parent) { this->parent_ = parent; } + void set_pin(uint8_t pin) { this->pin_ = pin; } + void set_inverted(bool inverted) { this->inverted_ = inverted; } + void set_flags(gpio::Flags flags) { this->flags_ = flags; } protected: SX1509Component *parent_; From 1bd2d41ffd1273eefa03aa331944d7f47d5cd7c9 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 02:39:22 -0600 Subject: [PATCH 071/107] [uart] `void` functions should return nothing (#7829) --- esphome/components/uart/uart.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/uart/uart.h b/esphome/components/uart/uart.h index d41dbe26e6..dc6962fbae 100644 --- a/esphome/components/uart/uart.h +++ b/esphome/components/uart/uart.h @@ -40,7 +40,7 @@ class UARTDevice { int available() { return this->parent_->available(); } - void flush() { return this->parent_->flush(); } + void flush() { this->parent_->flush(); } // Compat APIs int read() { From 17a09cd22151d95d510c858253b78dadae8e53e8 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 03:50:18 -0600 Subject: [PATCH 072/107] [audio] Header modernization (#7832) --- esphome/components/audio/audio.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/audio/audio.h b/esphome/components/audio/audio.h index b0968dc8da..caf325cf54 100644 --- a/esphome/components/audio/audio.h +++ b/esphome/components/audio/audio.h @@ -1,7 +1,7 @@ #pragma once +#include #include -#include namespace esphome { namespace audio { From cf835d15806481c50361cd6d8d193cc7b0b0175e Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 03:50:24 -0600 Subject: [PATCH 073/107] [opentherm] Follow variable naming convention (#7833) --- esphome/components/opentherm/opentherm.cpp | 6 +++--- esphome/components/opentherm/opentherm.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/esphome/components/opentherm/opentherm.cpp b/esphome/components/opentherm/opentherm.cpp index 26c707f9a0..78ecb53428 100644 --- a/esphome/components/opentherm/opentherm.cpp +++ b/esphome/components/opentherm/opentherm.cpp @@ -29,7 +29,7 @@ using std::to_string; static const char *const TAG = "opentherm"; #ifdef ESP8266 -OpenTherm *OpenTherm::instance_ = nullptr; +OpenTherm *OpenTherm::instance = nullptr; #endif OpenTherm::OpenTherm(InternalGPIOPin *in_pin, InternalGPIOPin *out_pin, int32_t device_timeout) @@ -53,7 +53,7 @@ OpenTherm::OpenTherm(InternalGPIOPin *in_pin, InternalGPIOPin *out_pin, int32_t bool OpenTherm::initialize() { #ifdef ESP8266 - OpenTherm::instance_ = this; + OpenTherm::instance = this; #endif this->in_pin_->pin_mode(gpio::FLAG_INPUT); this->out_pin_->pin_mode(gpio::FLAG_OUTPUT); @@ -216,7 +216,7 @@ bool IRAM_ATTR OpenTherm::timer_isr(OpenTherm *arg) { } #ifdef ESP8266 -void IRAM_ATTR OpenTherm::esp8266_timer_isr() { OpenTherm::timer_isr(OpenTherm::instance_); } +void IRAM_ATTR OpenTherm::esp8266_timer_isr() { OpenTherm::timer_isr(OpenTherm::instance); } #endif void IRAM_ATTR OpenTherm::bit_read_(uint8_t value) { diff --git a/esphome/components/opentherm/opentherm.h b/esphome/components/opentherm/opentherm.h index 85f4611125..5088bb2aa3 100644 --- a/esphome/components/opentherm/opentherm.h +++ b/esphome/components/opentherm/opentherm.h @@ -371,7 +371,7 @@ class OpenTherm { #ifdef ESP8266 // ESP8266 timer can accept callback with no parameters, so we have this hack to save a static instance of OpenTherm - static OpenTherm *instance_; + static OpenTherm *instance; #endif }; From 89ecfc20049d2358ecdbe63dacaed9143c9d9ed5 Mon Sep 17 00:00:00 2001 From: Oleg Tarasov Date: Tue, 26 Nov 2024 00:47:01 +0300 Subject: [PATCH 074/107] [opentherm] Fix out of memory errors on ESP8266 (#7835) --- esphome/components/opentherm/hub.cpp | 13 ++++---- esphome/components/opentherm/opentherm.cpp | 36 ++++++---------------- esphome/components/opentherm/opentherm.h | 7 ++--- esphome/core/helpers.cpp | 12 ++++++++ esphome/core/helpers.h | 8 +++++ 5 files changed, 39 insertions(+), 37 deletions(-) diff --git a/esphome/components/opentherm/hub.cpp b/esphome/components/opentherm/hub.cpp index dfa8ea95c5..aac2966ed1 100644 --- a/esphome/components/opentherm/hub.cpp +++ b/esphome/components/opentherm/hub.cpp @@ -138,7 +138,7 @@ OpenthermHub::OpenthermHub() : Component(), in_pin_{}, out_pin_{} {} void OpenthermHub::process_response(OpenthermData &data) { ESP_LOGD(TAG, "Received OpenTherm response with id %d (%s)", data.id, this->opentherm_->message_id_to_str((MessageId) data.id)); - ESP_LOGD(TAG, "%s", this->opentherm_->debug_data(data).c_str()); + this->opentherm_->debug_data(data); switch (data.id) { OPENTHERM_SENSOR_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_RESPONSE_MESSAGE, OPENTHERM_MESSAGE_RESPONSE_ENTITY, , @@ -315,7 +315,7 @@ void OpenthermHub::start_conversation_() { ESP_LOGD(TAG, "Sending request with id %d (%s)", request.id, this->opentherm_->message_id_to_str((MessageId) request.id)); - ESP_LOGD(TAG, "%s", this->opentherm_->debug_data(request).c_str()); + this->opentherm_->debug_data(request); // Send the request this->last_conversation_start_ = millis(); this->opentherm_->send(request); @@ -340,19 +340,18 @@ void OpenthermHub::stop_opentherm_() { this->opentherm_->stop(); this->last_conversation_end_ = millis(); } - void OpenthermHub::handle_protocol_write_error_() { ESP_LOGW(TAG, "Error while sending request: %s", this->opentherm_->operation_mode_to_str(this->opentherm_->get_mode())); - ESP_LOGW(TAG, "%s", this->opentherm_->debug_data(this->last_request_).c_str()); + this->opentherm_->debug_data(this->last_request_); } - void OpenthermHub::handle_protocol_read_error_() { OpenThermError error; this->opentherm_->get_protocol_error(error); - ESP_LOGW(TAG, "Protocol error occured while receiving response: %s", this->opentherm_->debug_error(error).c_str()); + ESP_LOGW(TAG, "Protocol error occured while receiving response: %s", + this->opentherm_->protocol_error_to_to_str(error.error_type)); + this->opentherm_->debug_error(error); } - void OpenthermHub::handle_timeout_error_() { ESP_LOGW(TAG, "Receive response timed out at a protocol level"); this->stop_opentherm_(); diff --git a/esphome/components/opentherm/opentherm.cpp b/esphome/components/opentherm/opentherm.cpp index 78ecb53428..e40fc66b7d 100644 --- a/esphome/components/opentherm/opentherm.cpp +++ b/esphome/components/opentherm/opentherm.cpp @@ -15,15 +15,11 @@ #include "Arduino.h" #endif #include -#include -#include namespace esphome { namespace opentherm { using std::string; -using std::bitset; -using std::stringstream; using std::to_string; static const char *const TAG = "opentherm"; @@ -545,29 +541,17 @@ const char *OpenTherm::message_id_to_str(MessageId id) { } } -string OpenTherm::debug_data(OpenthermData &data) { - stringstream result; - result << bitset<8>(data.type) << " " << bitset<8>(data.id) << " " << bitset<8>(data.valueHB) << " " - << bitset<8>(data.valueLB) << "\n"; - result << "type: " << this->message_type_to_str((MessageType) data.type) << "; "; - result << "id: " << to_string(data.id) << "; "; - result << "HB: " << to_string(data.valueHB) << "; "; - result << "LB: " << to_string(data.valueLB) << "; "; - result << "uint_16: " << to_string(data.u16()) << "; "; - result << "float: " << to_string(data.f88()); - - return result.str(); +void OpenTherm::debug_data(OpenthermData &data) { + ESP_LOGD(TAG, "%s %s %s %s", format_bin(data.type).c_str(), format_bin(data.id).c_str(), + format_bin(data.valueHB).c_str(), format_bin(data.valueLB).c_str()); + ESP_LOGD(TAG, "type: %s; id: %s; HB: %s; LB: %s; uint_16: %s; float: %s", + this->message_type_to_str((MessageType) data.type), to_string(data.id).c_str(), + to_string(data.valueHB).c_str(), to_string(data.valueLB).c_str(), to_string(data.u16()).c_str(), + to_string(data.f88()).c_str()); } -std::string OpenTherm::debug_error(OpenThermError &error) { - stringstream result; - result << "type: " << this->protocol_error_to_to_str(error.error_type) << "; "; - result << "data: "; - result << format_hex(error.data); - result << "; clock: " << to_string(clock_); - result << "; capture: " << bitset<32>(error.capture); - result << "; bit_pos: " << to_string(error.bit_pos); - - return result.str(); +void OpenTherm::debug_error(OpenThermError &error) const { + ESP_LOGD(TAG, "data: %s; clock: %s; capture: %s; bit_pos: %s", format_hex(error.data).c_str(), + to_string(clock_).c_str(), format_bin(error.capture).c_str(), to_string(error.bit_pos).c_str()); } float OpenthermData::f88() { return ((float) this->s16()) / 256.0; } diff --git a/esphome/components/opentherm/opentherm.h b/esphome/components/opentherm/opentherm.h index 5088bb2aa3..9532a77821 100644 --- a/esphome/components/opentherm/opentherm.h +++ b/esphome/components/opentherm/opentherm.h @@ -8,10 +8,9 @@ #pragma once #include -#include -#include #include "esphome/core/hal.h" #include "esphome/core/log.h" +#include "esphome/core/helpers.h" #if defined(ESP32) || defined(USE_ESP_IDF) #include "driver/timer.h" @@ -318,8 +317,8 @@ class OpenTherm { OperationMode get_mode() { return mode_; } - std::string debug_data(OpenthermData &data); - std::string debug_error(OpenThermError &error); + void debug_data(OpenthermData &data); + void debug_error(OpenThermError &error) const; const char *protocol_error_to_to_str(ProtocolErrorType error_type); const char *message_type_to_str(MessageType message_type); diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp index dae60a4e1d..befc84516c 100644 --- a/esphome/core/helpers.cpp +++ b/esphome/core/helpers.cpp @@ -397,6 +397,18 @@ std::string format_hex_pretty(const uint16_t *data, size_t length) { } std::string format_hex_pretty(const std::vector &data) { return format_hex_pretty(data.data(), data.size()); } +std::string format_bin(const uint8_t *data, size_t length) { + std::string result; + result.resize(length * 8); + for (size_t byte_idx = 0; byte_idx < length; byte_idx++) { + for (size_t bit_idx = 0; bit_idx < 8; bit_idx++) { + result[byte_idx * 8 + bit_idx] = ((data[byte_idx] >> (7 - bit_idx)) & 1) + '0'; + } + } + + return result; +} + ParseOnOffState parse_on_off(const char *str, const char *on, const char *off) { if (on == nullptr && strcasecmp(str, "on") == 0) return PARSE_ON; diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 43001bafdd..305ec47f76 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -420,6 +420,14 @@ template::value, int> = 0> std::stri return format_hex_pretty(reinterpret_cast(&val), sizeof(T)); } +/// Format the byte array \p data of length \p len in binary. +std::string format_bin(const uint8_t *data, size_t length); +/// Format an unsigned integer in binary, starting with the most significant byte. +template::value, int> = 0> std::string format_bin(T val) { + val = convert_big_endian(val); + return format_bin(reinterpret_cast(&val), sizeof(T)); +} + /// Return values for parse_on_off(). enum ParseOnOffState { PARSE_NONE = 0, From b027b6a711be401153847ca6607a4f7b90bc6688 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 15:57:40 -0600 Subject: [PATCH 075/107] [opentherm] Add nolint for 8266 static global (#7837) --- esphome/components/opentherm/opentherm.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/opentherm/opentherm.h b/esphome/components/opentherm/opentherm.h index 9532a77821..3be0191c63 100644 --- a/esphome/components/opentherm/opentherm.h +++ b/esphome/components/opentherm/opentherm.h @@ -370,7 +370,7 @@ class OpenTherm { #ifdef ESP8266 // ESP8266 timer can accept callback with no parameters, so we have this hack to save a static instance of OpenTherm - static OpenTherm *instance; + static OpenTherm *instance; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) #endif }; From bdb91112eada52df7c31a0b86e2f6f3b16ab9a49 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 16:20:03 -0600 Subject: [PATCH 076/107] [helpers] Add NOLINT for Mutex private field ``handle_`` (#7838) --- esphome/core/helpers.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 305ec47f76..fcbd8d8683 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -565,7 +565,8 @@ class Mutex { #if defined(USE_ESP32) || defined(USE_LIBRETINY) SemaphoreHandle_t handle_; #else - void *handle_; // d-pointer to store private data on new platforms + // d-pointer to store private data on new platforms + void *handle_; // NOLINT(clang-diagnostic-unused-private-field) #endif }; From d6f4f0509081ea38cfe799806c8225903e6cd1be Mon Sep 17 00:00:00 2001 From: programmingbgloDE <47243850+programmingbgloDE@users.noreply.github.com> Date: Mon, 25 Nov 2024 23:26:48 +0100 Subject: [PATCH 077/107] Add waveshare 1 45 in v2 b support (#7052) --- .../components/waveshare_epaper/display.py | 4 + .../waveshare_epaper/waveshare_epaper.cpp | 84 +++++++++++++++++++ .../waveshare_epaper/waveshare_epaper.h | 18 ++++ 3 files changed, 106 insertions(+) diff --git a/esphome/components/waveshare_epaper/display.py b/esphome/components/waveshare_epaper/display.py index 8287788de5..fbb5e1353d 100644 --- a/esphome/components/waveshare_epaper/display.py +++ b/esphome/components/waveshare_epaper/display.py @@ -27,6 +27,9 @@ WaveshareEPaperBWR = waveshare_epaper_ns.class_( WaveshareEPaperTypeA = waveshare_epaper_ns.class_( "WaveshareEPaperTypeA", WaveshareEPaper ) +WaveshareEpaper1P54INBV2 = waveshare_epaper_ns.class_( + "WaveshareEPaper1P54InBV2", WaveshareEPaperBWR +) WaveshareEPaper2P7In = waveshare_epaper_ns.class_( "WaveshareEPaper2P7In", WaveshareEPaper ) @@ -105,6 +108,7 @@ WaveshareEPaperTypeBModel = waveshare_epaper_ns.enum("WaveshareEPaperTypeBModel" MODELS = { "1.54in": ("a", WaveshareEPaperTypeAModel.WAVESHARE_EPAPER_1_54_IN), "1.54inv2": ("a", WaveshareEPaperTypeAModel.WAVESHARE_EPAPER_1_54_IN_V2), + "1.54inv2-b": ("b", WaveshareEpaper1P54INBV2), "2.13in": ("a", WaveshareEPaperTypeAModel.WAVESHARE_EPAPER_2_13_IN), "2.13inv2": ("a", WaveshareEPaperTypeAModel.WAVESHARE_EPAPER_2_13_IN_V2), "2.13in-ttgo": ("a", WaveshareEPaperTypeAModel.TTGO_EPAPER_2_13_IN), diff --git a/esphome/components/waveshare_epaper/waveshare_epaper.cpp b/esphome/components/waveshare_epaper/waveshare_epaper.cpp index 7c1d436673..1e27d594b8 100644 --- a/esphome/components/waveshare_epaper/waveshare_epaper.cpp +++ b/esphome/components/waveshare_epaper/waveshare_epaper.cpp @@ -808,6 +808,90 @@ void WaveshareEPaper2P7InV2::dump_config() { LOG_UPDATE_INTERVAL(this); } +// ======================================================== +// 1.54inch_v2_e-paper_b +// ======================================================== +// Datasheet: +// - https://files.waveshare.com/upload/9/9e/1.54inch-e-paper-b-v2-specification.pdf +// - https://www.waveshare.com/wiki/1.54inch_e-Paper_Module_(B)_Manual + +void WaveshareEPaper1P54InBV2::initialize() { + this->reset_(); + + this->wait_until_idle_(); + + this->command(0x12); + this->wait_until_idle_(); + + this->command(0x01); + this->data(0xC7); + this->data(0x00); + this->data(0x01); + + this->command(0x11); // data entry mode + this->data(0x01); + + this->command(0x44); // set Ram-X address start/end position + this->data(0x00); + this->data(0x18); // 0x18-->(24+1)*8=200 + + this->command(0x45); // set Ram-Y address start/end position + this->data(0xC7); // 0xC7-->(199+1)=200 + this->data(0x00); + this->data(0x00); + this->data(0x00); + + this->command(0x3C); // BorderWavefrom + this->data(0x05); + + this->command(0x18); // Read built-in temperature sensor + this->data(0x80); + + this->command(0x4E); // set RAM x address count to 0; + this->data(0x00); + this->command(0x4F); // set RAM y address count to 0X199; + this->data(0xC7); + this->data(0x00); + + this->wait_until_idle_(); +} + +void HOT WaveshareEPaper1P54InBV2::display() { + uint32_t buf_len_half = this->get_buffer_length_() >> 1; + this->initialize(); + + // COMMAND DATA START TRANSMISSION 1 (BLACK) + this->command(0x24); + delay(2); + for (uint32_t i = 0; i < buf_len_half; i++) { + this->data(~this->buffer_[i]); + } + delay(2); + + // COMMAND DATA START TRANSMISSION 2 (RED) + this->command(0x26); + delay(2); + for (uint32_t i = buf_len_half; i < buf_len_half * 2u; i++) { + this->data(this->buffer_[i]); + } + this->command(0x22); + this->data(0xf7); + this->command(0x20); + this->wait_until_idle_(); + + this->deep_sleep(); +} +int WaveshareEPaper1P54InBV2::get_height_internal() { return 200; } +int WaveshareEPaper1P54InBV2::get_width_internal() { return 200; } +void WaveshareEPaper1P54InBV2::dump_config() { + LOG_DISPLAY("", "Waveshare E-Paper", this); + ESP_LOGCONFIG(TAG, " Model: 1.54in V2 B"); + LOG_PIN(" Reset Pin: ", this->reset_pin_); + LOG_PIN(" DC Pin: ", this->dc_pin_); + LOG_PIN(" Busy Pin: ", this->busy_pin_); + LOG_UPDATE_INTERVAL(this); +} + // ======================================================== // 2.7inch_e-paper_b // ======================================================== diff --git a/esphome/components/waveshare_epaper/waveshare_epaper.h b/esphome/components/waveshare_epaper/waveshare_epaper.h index 7572982a20..a319b078d0 100644 --- a/esphome/components/waveshare_epaper/waveshare_epaper.h +++ b/esphome/components/waveshare_epaper/waveshare_epaper.h @@ -166,6 +166,24 @@ enum WaveshareEPaperTypeBModel { WAVESHARE_EPAPER_13_3_IN_K, }; +class WaveshareEPaper1P54InBV2 : public WaveshareEPaperBWR { + public: + void initialize() override; + + void display() override; + + void dump_config() override; + + void deep_sleep() override { + this->command(0x10); + this->data(0x01); + } + + protected: + int get_width_internal() override; + int get_height_internal() override; +}; + class WaveshareEPaper2P7In : public WaveshareEPaper { public: void initialize() override; From 140d77061b33895054b35c6e1245fe4217f81a1e Mon Sep 17 00:00:00 2001 From: JonasB2497 <45214989+JonasB2497@users.noreply.github.com> Date: Mon, 25 Nov 2024 23:29:58 +0100 Subject: [PATCH 078/107] added Waveshare BWR Mode for the 7.5in Display (#7687) --- .../components/waveshare_epaper/display.py | 4 + .../waveshare_epaper/waveshare_epaper.cpp | 107 ++++++++++++++++++ .../waveshare_epaper/waveshare_epaper.h | 38 +++++++ .../waveshare_epaper/test.esp32-ard.yaml | 17 +++ .../waveshare_epaper/test.esp32-c3-ard.yaml | 16 +++ .../waveshare_epaper/test.esp32-c3-idf.yaml | 16 +++ .../waveshare_epaper/test.esp32-idf.yaml | 16 +++ .../waveshare_epaper/test.esp8266-ard.yaml | 16 +++ .../waveshare_epaper/test.rp2040-ard.yaml | 16 +++ 9 files changed, 246 insertions(+) diff --git a/esphome/components/waveshare_epaper/display.py b/esphome/components/waveshare_epaper/display.py index fbb5e1353d..d5240b2674 100644 --- a/esphome/components/waveshare_epaper/display.py +++ b/esphome/components/waveshare_epaper/display.py @@ -79,6 +79,9 @@ WaveshareEPaper7P5InBV2 = waveshare_epaper_ns.class_( WaveshareEPaper7P5InBV3 = waveshare_epaper_ns.class_( "WaveshareEPaper7P5InBV3", WaveshareEPaper ) +WaveshareEPaper7P5InBV3BWR = waveshare_epaper_ns.class_( + "WaveshareEPaper7P5InBV3BWR", WaveshareEPaperBWR +) WaveshareEPaper7P5InV2 = waveshare_epaper_ns.class_( "WaveshareEPaper7P5InV2", WaveshareEPaper ) @@ -133,6 +136,7 @@ MODELS = { "7.50in": ("b", WaveshareEPaper7P5In), "7.50in-bv2": ("b", WaveshareEPaper7P5InBV2), "7.50in-bv3": ("b", WaveshareEPaper7P5InBV3), + "7.50in-bv3-bwr": ("b", WaveshareEPaper7P5InBV3BWR), "7.50in-bc": ("b", WaveshareEPaper7P5InBC), "7.50inv2": ("b", WaveshareEPaper7P5InV2), "7.50inv2alt": ("b", WaveshareEPaper7P5InV2alt), diff --git a/esphome/components/waveshare_epaper/waveshare_epaper.cpp b/esphome/components/waveshare_epaper/waveshare_epaper.cpp index 1e27d594b8..cb3b19aa1a 100644 --- a/esphome/components/waveshare_epaper/waveshare_epaper.cpp +++ b/esphome/components/waveshare_epaper/waveshare_epaper.cpp @@ -2399,6 +2399,113 @@ void WaveshareEPaper7P5InBV3::dump_config() { LOG_UPDATE_INTERVAL(this); } +void WaveshareEPaper7P5InBV3BWR::initialize() { this->init_display_(); } +bool WaveshareEPaper7P5InBV3BWR::wait_until_idle_() { + if (this->busy_pin_ == nullptr) { + return true; + } + + const uint32_t start = millis(); + while (this->busy_pin_->digital_read()) { + this->command(0x71); + if (millis() - start > this->idle_timeout_()) { + ESP_LOGI(TAG, "Timeout while displaying image!"); + return false; + } + App.feed_wdt(); + delay(10); + } + delay(200); // NOLINT + return true; +}; +void WaveshareEPaper7P5InBV3BWR::init_display_() { + this->reset_(); + + // COMMAND POWER SETTING + this->command(0x01); + + // 1-0=11: internal power + this->data(0x07); + this->data(0x17); // VGH&VGL + this->data(0x3F); // VSH + this->data(0x26); // VSL + this->data(0x11); // VSHR + + // VCOM DC Setting + this->command(0x82); + this->data(0x24); // VCOM + + // Booster Setting + this->command(0x06); + this->data(0x27); + this->data(0x27); + this->data(0x2F); + this->data(0x17); + + // POWER ON + this->command(0x04); + + delay(100); // NOLINT + this->wait_until_idle_(); + // COMMAND PANEL SETTING + this->command(0x00); + this->data(0x0F); // KW-3f KWR-2F BWROTP 0f BWOTP 1f + + // COMMAND RESOLUTION SETTING + this->command(0x61); + this->data(0x03); // source 800 + this->data(0x20); + this->data(0x01); // gate 480 + this->data(0xE0); + // COMMAND ...? + this->command(0x15); + this->data(0x00); + // COMMAND VCOM AND DATA INTERVAL SETTING + this->command(0x50); + this->data(0x20); + this->data(0x00); + // COMMAND TCON SETTING + this->command(0x60); + this->data(0x22); + // Resolution setting + this->command(0x65); + this->data(0x00); + this->data(0x00); // 800*480 + this->data(0x00); + this->data(0x00); +}; +void HOT WaveshareEPaper7P5InBV3BWR::display() { + this->init_display_(); + const uint32_t buf_len = this->get_buffer_length_() / 2u; + + this->command(0x10); // Send BW data Transmission + delay(2); + for (uint32_t i = 0; i < buf_len; i++) { + this->data(this->buffer_[i]); + } + + this->command(0x13); // Send red data Transmission + delay(2); + for (uint32_t i = 0; i < buf_len; i++) { + this->data(this->buffer_[i + buf_len]); + } + + this->command(0x12); // Display Refresh + delay(100); // NOLINT + this->wait_until_idle_(); + this->deep_sleep(); +} +int WaveshareEPaper7P5InBV3BWR::get_width_internal() { return 800; } +int WaveshareEPaper7P5InBV3BWR::get_height_internal() { return 480; } +void WaveshareEPaper7P5InBV3BWR::dump_config() { + LOG_DISPLAY("", "Waveshare E-Paper", this); + ESP_LOGCONFIG(TAG, " Model: 7.5in-bv3 BWR-Mode"); + LOG_PIN(" Reset Pin: ", this->reset_pin_); + LOG_PIN(" DC Pin: ", this->dc_pin_); + LOG_PIN(" Busy Pin: ", this->busy_pin_); + LOG_UPDATE_INTERVAL(this); +} + void WaveshareEPaper7P5In::initialize() { // COMMAND POWER SETTING this->command(0x01); diff --git a/esphome/components/waveshare_epaper/waveshare_epaper.h b/esphome/components/waveshare_epaper/waveshare_epaper.h index a319b078d0..4544f7df59 100644 --- a/esphome/components/waveshare_epaper/waveshare_epaper.h +++ b/esphome/components/waveshare_epaper/waveshare_epaper.h @@ -637,6 +637,44 @@ class WaveshareEPaper7P5InBV3 : public WaveshareEPaper { void init_display_(); }; +class WaveshareEPaper7P5InBV3BWR : public WaveshareEPaperBWR { + public: + bool wait_until_idle_(); + + void initialize() override; + + void display() override; + + void dump_config() override; + + void deep_sleep() override { + this->command(0x02); // Power off + this->wait_until_idle_(); + this->command(0x07); // Deep sleep + this->data(0xA5); + } + + void clear_screen(); + + protected: + int get_width_internal() override; + + int get_height_internal() override; + + void reset_() { + if (this->reset_pin_ != nullptr) { + this->reset_pin_->digital_write(true); + delay(200); // NOLINT + this->reset_pin_->digital_write(false); + delay(5); + this->reset_pin_->digital_write(true); + delay(200); // NOLINT + } + }; + + void init_display_(); +}; + class WaveshareEPaper7P5InBC : public WaveshareEPaper { public: void initialize() override; diff --git a/tests/components/waveshare_epaper/test.esp32-ard.yaml b/tests/components/waveshare_epaper/test.esp32-ard.yaml index 2f06c5c51b..944f98a1e9 100644 --- a/tests/components/waveshare_epaper/test.esp32-ard.yaml +++ b/tests/components/waveshare_epaper/test.esp32-ard.yaml @@ -188,3 +188,20 @@ display: full_update_every: 30 lambda: |- it.rectangle(0, 0, it.get_width(), it.get_height()); + - platform: waveshare_epaper + model: 7.50in-bv3-bwr + spi_id: spi_id_1 + cs_pin: + allow_other_uses: true + number: GPIO25 + dc_pin: + allow_other_uses: true + number: GPIO26 + busy_pin: + allow_other_uses: true + number: GPIO27 + reset_pin: + allow_other_uses: true + number: GPIO32 + lambda: |- + it.rectangle(0, 0, it.get_width(), it.get_height()); diff --git a/tests/components/waveshare_epaper/test.esp32-c3-ard.yaml b/tests/components/waveshare_epaper/test.esp32-c3-ard.yaml index 1c4547b7b4..5d651bd180 100644 --- a/tests/components/waveshare_epaper/test.esp32-c3-ard.yaml +++ b/tests/components/waveshare_epaper/test.esp32-c3-ard.yaml @@ -105,3 +105,19 @@ display: model: 1.54in-m5coreink-m09 lambda: |- it.rectangle(0, 0, it.get_width(), it.get_height()); + - platform: waveshare_epaper + cs_pin: + allow_other_uses: true + number: 4 + dc_pin: + allow_other_uses: true + number: 4 + busy_pin: + allow_other_uses: true + number: 4 + reset_pin: + allow_other_uses: true + number: 4 + model: 7.50in-bv3-bwr + lambda: |- + it.rectangle(0, 0, it.get_width(), it.get_height()); diff --git a/tests/components/waveshare_epaper/test.esp32-c3-idf.yaml b/tests/components/waveshare_epaper/test.esp32-c3-idf.yaml index 1c4547b7b4..5d651bd180 100644 --- a/tests/components/waveshare_epaper/test.esp32-c3-idf.yaml +++ b/tests/components/waveshare_epaper/test.esp32-c3-idf.yaml @@ -105,3 +105,19 @@ display: model: 1.54in-m5coreink-m09 lambda: |- it.rectangle(0, 0, it.get_width(), it.get_height()); + - platform: waveshare_epaper + cs_pin: + allow_other_uses: true + number: 4 + dc_pin: + allow_other_uses: true + number: 4 + busy_pin: + allow_other_uses: true + number: 4 + reset_pin: + allow_other_uses: true + number: 4 + model: 7.50in-bv3-bwr + lambda: |- + it.rectangle(0, 0, it.get_width(), it.get_height()); diff --git a/tests/components/waveshare_epaper/test.esp32-idf.yaml b/tests/components/waveshare_epaper/test.esp32-idf.yaml index b6082fcfbf..47f894d967 100644 --- a/tests/components/waveshare_epaper/test.esp32-idf.yaml +++ b/tests/components/waveshare_epaper/test.esp32-idf.yaml @@ -105,3 +105,19 @@ display: model: 1.54in-m5coreink-m09 lambda: |- it.rectangle(0, 0, it.get_width(), it.get_height()); + - platform: waveshare_epaper + cs_pin: + allow_other_uses: true + number: 4 + dc_pin: + allow_other_uses: true + number: 4 + busy_pin: + allow_other_uses: true + number: 4 + reset_pin: + allow_other_uses: true + number: 4 + model: 7.50in-bv3-bwr + lambda: |- + it.rectangle(0, 0, it.get_width(), it.get_height()); diff --git a/tests/components/waveshare_epaper/test.esp8266-ard.yaml b/tests/components/waveshare_epaper/test.esp8266-ard.yaml index 1f076a67be..ceda328598 100644 --- a/tests/components/waveshare_epaper/test.esp8266-ard.yaml +++ b/tests/components/waveshare_epaper/test.esp8266-ard.yaml @@ -105,3 +105,19 @@ display: model: 1.54in-m5coreink-m09 lambda: |- it.rectangle(0, 0, it.get_width(), it.get_height()); + - platform: waveshare_epaper + cs_pin: + allow_other_uses: true + number: 4 + dc_pin: + allow_other_uses: true + number: 4 + busy_pin: + allow_other_uses: true + number: 4 + reset_pin: + allow_other_uses: true + number: 4 + model: 7.50in-bv3-bwr + lambda: |- + it.rectangle(0, 0, it.get_width(), it.get_height()); diff --git a/tests/components/waveshare_epaper/test.rp2040-ard.yaml b/tests/components/waveshare_epaper/test.rp2040-ard.yaml index 6050062d7e..be7e780033 100644 --- a/tests/components/waveshare_epaper/test.rp2040-ard.yaml +++ b/tests/components/waveshare_epaper/test.rp2040-ard.yaml @@ -105,3 +105,19 @@ display: model: 1.54in-m5coreink-m09 lambda: |- it.rectangle(0, 0, it.get_width(), it.get_height()); + - platform: waveshare_epaper + cs_pin: + allow_other_uses: true + number: 5 + dc_pin: + allow_other_uses: true + number: 5 + busy_pin: + allow_other_uses: true + number: 5 + reset_pin: + allow_other_uses: true + number: 5 + model: 7.50in-bv3-bwr + lambda: |- + it.rectangle(0, 0, it.get_width(), it.get_height()); From 6ee02c47c29712c2b8cffa2ef5cebe25b29719a1 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 16:42:12 -0600 Subject: [PATCH 079/107] [homeassistant.number] Return when value not set (#7839) --- .../components/homeassistant/number/homeassistant_number.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/esphome/components/homeassistant/number/homeassistant_number.cpp b/esphome/components/homeassistant/number/homeassistant_number.cpp index d3e285f4ac..a7f71c3244 100644 --- a/esphome/components/homeassistant/number/homeassistant_number.cpp +++ b/esphome/components/homeassistant/number/homeassistant_number.cpp @@ -27,6 +27,7 @@ void HomeassistantNumber::min_retrieved_(const std::string &min) { auto min_value = parse_number(min); if (!min_value.has_value()) { ESP_LOGE(TAG, "'%s': Can't convert 'min' value '%s' to number!", this->entity_id_.c_str(), min.c_str()); + return; } ESP_LOGD(TAG, "'%s': Min retrieved: %s", get_name().c_str(), min.c_str()); this->traits.set_min_value(min_value.value()); @@ -36,6 +37,7 @@ void HomeassistantNumber::max_retrieved_(const std::string &max) { auto max_value = parse_number(max); if (!max_value.has_value()) { ESP_LOGE(TAG, "'%s': Can't convert 'max' value '%s' to number!", this->entity_id_.c_str(), max.c_str()); + return; } ESP_LOGD(TAG, "'%s': Max retrieved: %s", get_name().c_str(), max.c_str()); this->traits.set_max_value(max_value.value()); @@ -45,6 +47,7 @@ void HomeassistantNumber::step_retrieved_(const std::string &step) { auto step_value = parse_number(step); if (!step_value.has_value()) { ESP_LOGE(TAG, "'%s': Can't convert 'step' value '%s' to number!", this->entity_id_.c_str(), step.c_str()); + return; } ESP_LOGD(TAG, "'%s': Step Retrieved %s", get_name().c_str(), step.c_str()); this->traits.set_step(step_value.value()); From 4fbf41472a318bf923632508a3ba9473f06f3171 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 17:41:27 -0600 Subject: [PATCH 080/107] [CI] Add/update some system include paths (#7831) --- .clang-tidy | 6 ++++-- script/clang-tidy | 11 +++++++---- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 946f2950d8..994416b2f1 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -63,15 +63,16 @@ Checks: >- -misc-non-private-member-variables-in-classes, -misc-no-recursion, -misc-unused-parameters, - -modernize-avoid-c-arrays, -modernize-avoid-bind, + -modernize-avoid-c-arrays, -modernize-concat-nested-namespaces, -modernize-return-braced-init-list, -modernize-use-auto, -modernize-use-default-member-init, -modernize-use-equals-default, - -modernize-use-trailing-return-type, -modernize-use-nodiscard, + -modernize-use-nullptr, + -modernize-use-trailing-return-type, -mpi-*, -objc-*, -readability-container-data-pointer, @@ -82,6 +83,7 @@ Checks: >- -readability-isolate-declaration, -readability-magic-numbers, -readability-make-member-function-const, + -readability-named-parameter, -readability-redundant-string-init, -readability-uppercase-literal-suffix, -readability-use-anyofallof, diff --git a/script/clang-tidy b/script/clang-tidy index 61199edce3..319fab70a2 100755 --- a/script/clang-tidy +++ b/script/clang-tidy @@ -100,10 +100,13 @@ def clang_options(idedata): # add library include directories using -isystem to suppress their errors for directory in list(idedata["includes"]["build"]): # skip our own directories, we add those later - if ( - not directory.startswith(f"{root_path}/") - or directory.startswith(f"{root_path}/.pio/") - or directory.startswith(f"{root_path}/managed_components/") + if not directory.startswith(f"{root_path}") or directory.startswith( + ( + f"{root_path}/.pio", + f"{root_path}/.platformio", + f"{root_path}/.temp", + f"{root_path}/managed_components", + ) ): cmd.extend(["-isystem", directory]) From f4766ab74fda60c5e43eaea00c1f91f2a5e77ce2 Mon Sep 17 00:00:00 2001 From: Samuel Sieb Date: Mon, 25 Nov 2024 13:58:21 -1000 Subject: [PATCH 081/107] [wifi] fix 32 char SSIDs (#7834) Co-authored-by: Samuel Sieb --- .../wifi/wifi_component_esp32_arduino.cpp | 24 +++++++++++++++---- .../wifi/wifi_component_esp8266.cpp | 24 +++++++++++++++---- .../wifi/wifi_component_esp_idf.cpp | 24 +++++++++++++++---- 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/esphome/components/wifi/wifi_component_esp32_arduino.cpp b/esphome/components/wifi/wifi_component_esp32_arduino.cpp index 18c706cb01..bc10bbd1e5 100644 --- a/esphome/components/wifi/wifi_component_esp32_arduino.cpp +++ b/esphome/components/wifi/wifi_component_esp32_arduino.cpp @@ -137,8 +137,16 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) { // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t wifi_config_t conf; memset(&conf, 0, sizeof(conf)); - snprintf(reinterpret_cast(conf.sta.ssid), sizeof(conf.sta.ssid), "%s", ap.get_ssid().c_str()); - snprintf(reinterpret_cast(conf.sta.password), sizeof(conf.sta.password), "%s", ap.get_password().c_str()); + if (ap.get_ssid().size() > sizeof(conf.sta.ssid)) { + ESP_LOGE(TAG, "SSID is too long"); + return false; + } + if (ap.get_password().size() > sizeof(conf.sta.password)) { + ESP_LOGE(TAG, "password is too long"); + return false; + } + memcpy(reinterpret_cast(conf.sta.ssid), ap.get_ssid().c_str(), ap.get_ssid().size()); + memcpy(reinterpret_cast(conf.sta.password), ap.get_password().c_str(), ap.get_password().size()); // The weakest authmode to accept in the fast scan mode if (ap.get_password().empty()) { @@ -746,7 +754,11 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) { wifi_config_t conf; memset(&conf, 0, sizeof(conf)); - snprintf(reinterpret_cast(conf.ap.ssid), sizeof(conf.ap.ssid), "%s", ap.get_ssid().c_str()); + if (ap.get_ssid().size() > sizeof(conf.ap.ssid)) { + ESP_LOGE(TAG, "AP SSID is too long"); + return false; + } + memcpy(reinterpret_cast(conf.ap.ssid), ap.get_ssid().c_str(), ap.get_ssid().size()); conf.ap.channel = ap.get_channel().value_or(1); conf.ap.ssid_hidden = ap.get_ssid().size(); conf.ap.max_connection = 5; @@ -757,7 +769,11 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) { *conf.ap.password = 0; } else { conf.ap.authmode = WIFI_AUTH_WPA2_PSK; - snprintf(reinterpret_cast(conf.ap.password), sizeof(conf.ap.password), "%s", ap.get_password().c_str()); + if (ap.get_password().size() > sizeof(conf.ap.password)) { + ESP_LOGE(TAG, "AP password is too long"); + return false; + } + memcpy(reinterpret_cast(conf.ap.password), ap.get_password().c_str(), ap.get_password().size()); } // pairwise cipher of SoftAP, group cipher will be derived using this. diff --git a/esphome/components/wifi/wifi_component_esp8266.cpp b/esphome/components/wifi/wifi_component_esp8266.cpp index a18d078967..8e1c2e70d8 100644 --- a/esphome/components/wifi/wifi_component_esp8266.cpp +++ b/esphome/components/wifi/wifi_component_esp8266.cpp @@ -236,8 +236,16 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) { struct station_config conf {}; memset(&conf, 0, sizeof(conf)); - snprintf(reinterpret_cast(conf.ssid), sizeof(conf.ssid), "%s", ap.get_ssid().c_str()); - snprintf(reinterpret_cast(conf.password), sizeof(conf.password), "%s", ap.get_password().c_str()); + if (ap.get_ssid().size() > sizeof(conf.ssid)) { + ESP_LOGE(TAG, "SSID is too long"); + return false; + } + if (ap.get_password().size() > sizeof(conf.password)) { + ESP_LOGE(TAG, "password is too long"); + return false; + } + memcpy(reinterpret_cast(conf.ssid), ap.get_ssid().c_str(), ap.get_ssid().size()); + memcpy(reinterpret_cast(conf.password), ap.get_password().c_str(), ap.get_password().size()); if (ap.get_bssid().has_value()) { conf.bssid_set = 1; @@ -775,7 +783,11 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) { return false; struct softap_config conf {}; - snprintf(reinterpret_cast(conf.ssid), sizeof(conf.ssid), "%s", ap.get_ssid().c_str()); + if (ap.get_ssid().size() > sizeof(conf.ssid)) { + ESP_LOGE(TAG, "AP SSID is too long"); + return false; + } + memcpy(reinterpret_cast(conf.ssid), ap.get_ssid().c_str(), ap.get_ssid().size()); conf.ssid_len = static_cast(ap.get_ssid().size()); conf.channel = ap.get_channel().value_or(1); conf.ssid_hidden = ap.get_hidden(); @@ -787,7 +799,11 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) { *conf.password = 0; } else { conf.authmode = AUTH_WPA2_PSK; - snprintf(reinterpret_cast(conf.password), sizeof(conf.password), "%s", ap.get_password().c_str()); + if (ap.get_password().size() > sizeof(conf.password)) { + ESP_LOGE(TAG, "AP password is too long"); + return false; + } + memcpy(reinterpret_cast(conf.password), ap.get_password().c_str(), ap.get_password().size()); } ETS_UART_INTR_DISABLE(); diff --git a/esphome/components/wifi/wifi_component_esp_idf.cpp b/esphome/components/wifi/wifi_component_esp_idf.cpp index 1bf14ff40b..1af271345f 100644 --- a/esphome/components/wifi/wifi_component_esp_idf.cpp +++ b/esphome/components/wifi/wifi_component_esp_idf.cpp @@ -289,8 +289,16 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) { // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t wifi_config_t conf; memset(&conf, 0, sizeof(conf)); - snprintf(reinterpret_cast(conf.sta.ssid), sizeof(conf.sta.ssid), "%s", ap.get_ssid().c_str()); - snprintf(reinterpret_cast(conf.sta.password), sizeof(conf.sta.password), "%s", ap.get_password().c_str()); + if (ap.get_ssid().size() > sizeof(conf.sta.ssid)) { + ESP_LOGE(TAG, "SSID is too long"); + return false; + } + if (ap.get_password().size() > sizeof(conf.sta.password)) { + ESP_LOGE(TAG, "password is too long"); + return false; + } + memcpy(reinterpret_cast(conf.sta.ssid), ap.get_ssid().c_str(), ap.get_ssid().size()); + memcpy(reinterpret_cast(conf.sta.password), ap.get_password().c_str(), ap.get_password().size()); // The weakest authmode to accept in the fast scan mode if (ap.get_password().empty()) { @@ -902,7 +910,11 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) { wifi_config_t conf; memset(&conf, 0, sizeof(conf)); - strncpy(reinterpret_cast(conf.ap.ssid), ap.get_ssid().c_str(), sizeof(conf.ap.ssid)); + if (ap.get_ssid().size() > sizeof(conf.ap.ssid)) { + ESP_LOGE(TAG, "AP SSID is too long"); + return false; + } + memcpy(reinterpret_cast(conf.ap.ssid), ap.get_ssid().c_str(), ap.get_ssid().size()); conf.ap.channel = ap.get_channel().value_or(1); conf.ap.ssid_hidden = ap.get_ssid().size(); conf.ap.max_connection = 5; @@ -913,7 +925,11 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) { *conf.ap.password = 0; } else { conf.ap.authmode = WIFI_AUTH_WPA2_PSK; - strncpy(reinterpret_cast(conf.ap.password), ap.get_password().c_str(), sizeof(conf.ap.password)); + if (ap.get_password().size() > sizeof(conf.ap.password)) { + ESP_LOGE(TAG, "AP password is too long"); + return false; + } + memcpy(reinterpret_cast(conf.ap.password), ap.get_password().c_str(), ap.get_password().size()); } // pairwise cipher of SoftAP, group cipher will be derived using this. From a70cee1dc1162da1ee5f1f078991aa2c68d421a3 Mon Sep 17 00:00:00 2001 From: Samuel Sieb Date: Mon, 25 Nov 2024 14:15:01 -1000 Subject: [PATCH 082/107] fix local time timestamp calculation (#7807) Co-authored-by: Samuel Sieb --- .../components/datetime/datetime_entity.cpp | 4 +-- esphome/core/time.cpp | 34 +++++++++++-------- esphome/core/time.h | 4 +-- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/esphome/components/datetime/datetime_entity.cpp b/esphome/components/datetime/datetime_entity.cpp index f215b7acb5..3d92194efa 100644 --- a/esphome/components/datetime/datetime_entity.cpp +++ b/esphome/components/datetime/datetime_entity.cpp @@ -60,9 +60,7 @@ ESPTime DateTimeEntity::state_as_esptime() const { obj.hour = this->hour_; obj.minute = this->minute_; obj.second = this->second_; - obj.day_of_week = 1; // Required to be valid for recalc_timestamp_local but not used. - obj.day_of_year = 1; // Required to be valid for recalc_timestamp_local but not used. - obj.recalc_timestamp_local(false); + obj.recalc_timestamp_local(); return obj; } diff --git a/esphome/core/time.cpp b/esphome/core/time.cpp index f7aa4fdddb..31977d972b 100644 --- a/esphome/core/time.cpp +++ b/esphome/core/time.cpp @@ -5,20 +5,18 @@ namespace esphome { -bool is_leap_year(uint32_t year) { return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0); } - uint8_t days_in_month(uint8_t month, uint16_t year) { static const uint8_t DAYS_IN_MONTH[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - uint8_t days = DAYS_IN_MONTH[month]; - if (month == 2 && is_leap_year(year)) + if (month == 2 && (year % 4 == 0)) return 29; - return days; + return DAYS_IN_MONTH[month]; } size_t ESPTime::strftime(char *buffer, size_t buffer_len, const char *format) { struct tm c_tm = this->to_c_tm(); return ::strftime(buffer, buffer_len, format, &c_tm); } + ESPTime ESPTime::from_c_tm(struct tm *c_tm, time_t c_time) { ESPTime res{}; res.second = uint8_t(c_tm->tm_sec); @@ -33,6 +31,7 @@ ESPTime ESPTime::from_c_tm(struct tm *c_tm, time_t c_time) { res.timestamp = c_time; return res; } + struct tm ESPTime::to_c_tm() { struct tm c_tm {}; c_tm.tm_sec = this->second; @@ -46,6 +45,7 @@ struct tm ESPTime::to_c_tm() { c_tm.tm_isdst = this->is_dst; return c_tm; } + std::string ESPTime::strftime(const std::string &format) { std::string timestr; timestr.resize(format.size() * 4); @@ -142,6 +142,7 @@ void ESPTime::increment_second() { this->year++; } } + void ESPTime::increment_day() { this->timestamp += 86400; @@ -159,23 +160,22 @@ void ESPTime::increment_day() { this->year++; } } + void ESPTime::recalc_timestamp_utc(bool use_day_of_year) { time_t res = 0; - if (!this->fields_in_range()) { this->timestamp = -1; return; } for (int i = 1970; i < this->year; i++) - res += is_leap_year(i) ? 366 : 365; + res += (year % 4 == 0) ? 366 : 365; if (use_day_of_year) { res += this->day_of_year - 1; } else { for (int i = 1; i < this->month; i++) res += days_in_month(i, this->year); - res += this->day_of_month - 1; } @@ -188,13 +188,17 @@ void ESPTime::recalc_timestamp_utc(bool use_day_of_year) { this->timestamp = res; } -void ESPTime::recalc_timestamp_local(bool use_day_of_year) { - this->recalc_timestamp_utc(use_day_of_year); - this->timestamp -= ESPTime::timezone_offset(); - ESPTime temp = ESPTime::from_epoch_local(this->timestamp); - if (temp.is_dst) { - this->timestamp -= 3600; - } +void ESPTime::recalc_timestamp_local() { + struct tm tm; + + tm.tm_year = this->year - 1900; + tm.tm_mon = this->month - 1; + tm.tm_mday = this->day_of_month; + tm.tm_hour = this->hour; + tm.tm_min = this->minute; + tm.tm_sec = this->second; + + this->timestamp = mktime(&tm); } int32_t ESPTime::timezone_offset() { diff --git a/esphome/core/time.h b/esphome/core/time.h index bce1108d93..5cbd9369fb 100644 --- a/esphome/core/time.h +++ b/esphome/core/time.h @@ -9,8 +9,6 @@ namespace esphome { template bool increment_time_value(T ¤t, uint16_t begin, uint16_t end); -bool is_leap_year(uint32_t year); - uint8_t days_in_month(uint8_t month, uint16_t year); /// A more user-friendly version of struct tm from time.h @@ -100,7 +98,7 @@ struct ESPTime { void recalc_timestamp_utc(bool use_day_of_year = true); /// Recalculate the timestamp field from the other fields of this ESPTime instance assuming local fields. - void recalc_timestamp_local(bool use_day_of_year = true); + void recalc_timestamp_local(); /// Convert this ESPTime instance back to a tm struct. struct tm to_c_tm(); From d9d368d38eff2024bf50ab9fc034d19ef91d6799 Mon Sep 17 00:00:00 2001 From: Samuel Sieb Date: Mon, 25 Nov 2024 14:21:47 -1000 Subject: [PATCH 083/107] add on_key trigger to matrix_keypad (#7830) Co-authored-by: Samuel Sieb --- esphome/components/matrix_keypad/__init__.py | 18 +++++++++++++++--- .../components/matrix_keypad/matrix_keypad.cpp | 4 ++++ .../components/matrix_keypad/matrix_keypad.h | 5 +++++ esphome/components/wiegand/__init__.py | 7 +++---- esphome/const.py | 1 + tests/components/matrix_keypad/common.yaml | 8 ++++++++ .../matrix_keypad/test.esp32-ard.yaml | 12 ++++-------- .../matrix_keypad/test.esp32-c3-ard.yaml | 12 ++++-------- .../matrix_keypad/test.esp32-c3-idf.yaml | 12 ++++-------- .../matrix_keypad/test.esp32-idf.yaml | 12 ++++-------- .../matrix_keypad/test.esp32-s3-idf.yaml | 15 +++++++++++++++ .../matrix_keypad/test.esp8266-ard.yaml | 12 ++++-------- .../matrix_keypad/test.rp2040-ard.yaml | 12 ++++-------- 13 files changed, 75 insertions(+), 55 deletions(-) create mode 100644 tests/components/matrix_keypad/common.yaml create mode 100644 tests/components/matrix_keypad/test.esp32-s3-idf.yaml diff --git a/esphome/components/matrix_keypad/__init__.py b/esphome/components/matrix_keypad/__init__.py index 5250a45732..b2bcde98ec 100644 --- a/esphome/components/matrix_keypad/__init__.py +++ b/esphome/components/matrix_keypad/__init__.py @@ -1,8 +1,8 @@ +from esphome import automation, pins import esphome.codegen as cg -import esphome.config_validation as cv -from esphome import pins from esphome.components import key_provider -from esphome.const import CONF_ID, CONF_PIN +import esphome.config_validation as cv +from esphome.const import CONF_ID, CONF_ON_KEY, CONF_PIN, CONF_TRIGGER_ID CODEOWNERS = ["@ssieb"] @@ -14,6 +14,9 @@ matrix_keypad_ns = cg.esphome_ns.namespace("matrix_keypad") MatrixKeypad = matrix_keypad_ns.class_( "MatrixKeypad", key_provider.KeyProvider, cg.Component ) +MatrixKeyTrigger = matrix_keypad_ns.class_( + "MatrixKeyTrigger", automation.Trigger.template(cg.uint8) +) CONF_KEYPAD_ID = "keypad_id" CONF_ROWS = "rows" @@ -47,6 +50,11 @@ CONFIG_SCHEMA = cv.All( cv.Optional(CONF_DEBOUNCE_TIME, default=1): cv.int_range(min=1, max=100), cv.Optional(CONF_HAS_DIODES): cv.boolean, cv.Optional(CONF_HAS_PULLDOWNS): cv.boolean, + cv.Optional(CONF_ON_KEY): automation.validate_automation( + { + cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(MatrixKeyTrigger), + } + ), } ), check_keys, @@ -73,3 +81,7 @@ async def to_code(config): cg.add(var.set_has_diodes(config[CONF_HAS_DIODES])) if CONF_HAS_PULLDOWNS in config: cg.add(var.set_has_pulldowns(config[CONF_HAS_PULLDOWNS])) + for conf in config.get(CONF_ON_KEY, []): + trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID]) + cg.add(var.register_key_trigger(trigger)) + await automation.build_automation(trigger, [(cg.uint8, "x")], conf) diff --git a/esphome/components/matrix_keypad/matrix_keypad.cpp b/esphome/components/matrix_keypad/matrix_keypad.cpp index f62c75c869..8537997935 100644 --- a/esphome/components/matrix_keypad/matrix_keypad.cpp +++ b/esphome/components/matrix_keypad/matrix_keypad.cpp @@ -86,6 +86,8 @@ void MatrixKeypad::loop() { if (!this->keys_.empty()) { uint8_t keycode = this->keys_[key]; ESP_LOGD(TAG, "key '%c' pressed", keycode); + for (auto &trigger : this->key_triggers_) + trigger->trigger(keycode); for (auto &listener : this->listeners_) listener->key_pressed(keycode); this->send_key_(keycode); @@ -107,5 +109,7 @@ void MatrixKeypad::dump_config() { void MatrixKeypad::register_listener(MatrixKeypadListener *listener) { this->listeners_.push_back(listener); } +void MatrixKeypad::register_key_trigger(MatrixKeyTrigger *trig) { this->key_triggers_.push_back(trig); } + } // namespace matrix_keypad } // namespace esphome diff --git a/esphome/components/matrix_keypad/matrix_keypad.h b/esphome/components/matrix_keypad/matrix_keypad.h index d506040b7c..8b309b42c2 100644 --- a/esphome/components/matrix_keypad/matrix_keypad.h +++ b/esphome/components/matrix_keypad/matrix_keypad.h @@ -1,6 +1,7 @@ #pragma once #include "esphome/components/key_provider/key_provider.h" +#include "esphome/core/automation.h" #include "esphome/core/component.h" #include "esphome/core/hal.h" #include "esphome/core/helpers.h" @@ -18,6 +19,8 @@ class MatrixKeypadListener { virtual void key_released(uint8_t key){}; }; +class MatrixKeyTrigger : public Trigger {}; + class MatrixKeypad : public key_provider::KeyProvider, public Component { public: void setup() override; @@ -31,6 +34,7 @@ class MatrixKeypad : public key_provider::KeyProvider, public Component { void set_has_pulldowns(int has_pulldowns) { has_pulldowns_ = has_pulldowns; }; void register_listener(MatrixKeypadListener *listener); + void register_key_trigger(MatrixKeyTrigger *trig); protected: std::vector rows_; @@ -42,6 +46,7 @@ class MatrixKeypad : public key_provider::KeyProvider, public Component { int pressed_key_ = -1; std::vector listeners_{}; + std::vector key_triggers_; }; } // namespace matrix_keypad diff --git a/esphome/components/wiegand/__init__.py b/esphome/components/wiegand/__init__.py index 7b05c43198..962ac4c373 100644 --- a/esphome/components/wiegand/__init__.py +++ b/esphome/components/wiegand/__init__.py @@ -1,8 +1,8 @@ +from esphome import automation, pins import esphome.codegen as cg -import esphome.config_validation as cv -from esphome import pins, automation from esphome.components import key_provider -from esphome.const import CONF_ID, CONF_ON_TAG, CONF_TRIGGER_ID +import esphome.config_validation as cv +from esphome.const import CONF_ID, CONF_ON_KEY, CONF_ON_TAG, CONF_TRIGGER_ID CODEOWNERS = ["@ssieb"] @@ -25,7 +25,6 @@ WiegandKeyTrigger = wiegand_ns.class_( CONF_D0 = "d0" CONF_D1 = "d1" -CONF_ON_KEY = "on_key" CONF_ON_RAW = "on_raw" CONFIG_SCHEMA = cv.Schema( diff --git a/esphome/const.py b/esphome/const.py index 50528b7363..d2df83aa43 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -575,6 +575,7 @@ CONF_ON_FINGER_SCAN_UNMATCHED = "on_finger_scan_unmatched" CONF_ON_FINISHED_WRITE = "on_finished_write" CONF_ON_IDLE = "on_idle" CONF_ON_JSON_MESSAGE = "on_json_message" +CONF_ON_KEY = "on_key" CONF_ON_LOCK = "on_lock" CONF_ON_LOOP = "on_loop" CONF_ON_MESSAGE = "on_message" diff --git a/tests/components/matrix_keypad/common.yaml b/tests/components/matrix_keypad/common.yaml new file mode 100644 index 0000000000..32e334d890 --- /dev/null +++ b/tests/components/matrix_keypad/common.yaml @@ -0,0 +1,8 @@ +binary_sensor: + - platform: matrix_keypad + id: key4 + row: 1 + col: 1 + - platform: matrix_keypad + id: key1 + key: 1 diff --git a/tests/components/matrix_keypad/test.esp32-ard.yaml b/tests/components/matrix_keypad/test.esp32-ard.yaml index c8e9b54534..70bb70638d 100644 --- a/tests/components/matrix_keypad/test.esp32-ard.yaml +++ b/tests/components/matrix_keypad/test.esp32-ard.yaml @@ -1,11 +1,5 @@ -binary_sensor: - - platform: matrix_keypad - id: key4 - row: 1 - col: 1 - - platform: matrix_keypad - id: key1 - key: 1 +packages: + common: !include common.yaml matrix_keypad: id: keypad @@ -17,3 +11,5 @@ matrix_keypad: - pin: 15 keys: "1234" has_pulldowns: true + on_key: + - lambda: ESP_LOGI("KEY", "key %d pressed", x); diff --git a/tests/components/matrix_keypad/test.esp32-c3-ard.yaml b/tests/components/matrix_keypad/test.esp32-c3-ard.yaml index d15e6af21a..75d9c0b263 100644 --- a/tests/components/matrix_keypad/test.esp32-c3-ard.yaml +++ b/tests/components/matrix_keypad/test.esp32-c3-ard.yaml @@ -1,11 +1,5 @@ -binary_sensor: - - platform: matrix_keypad - id: key4 - row: 1 - col: 1 - - platform: matrix_keypad - id: key1 - key: 1 +packages: + common: !include common.yaml matrix_keypad: id: keypad @@ -17,3 +11,5 @@ matrix_keypad: - pin: 4 keys: "1234" has_pulldowns: true + on_key: + - lambda: ESP_LOGI("KEY", "key %d pressed", x); diff --git a/tests/components/matrix_keypad/test.esp32-c3-idf.yaml b/tests/components/matrix_keypad/test.esp32-c3-idf.yaml index d15e6af21a..75d9c0b263 100644 --- a/tests/components/matrix_keypad/test.esp32-c3-idf.yaml +++ b/tests/components/matrix_keypad/test.esp32-c3-idf.yaml @@ -1,11 +1,5 @@ -binary_sensor: - - platform: matrix_keypad - id: key4 - row: 1 - col: 1 - - platform: matrix_keypad - id: key1 - key: 1 +packages: + common: !include common.yaml matrix_keypad: id: keypad @@ -17,3 +11,5 @@ matrix_keypad: - pin: 4 keys: "1234" has_pulldowns: true + on_key: + - lambda: ESP_LOGI("KEY", "key %d pressed", x); diff --git a/tests/components/matrix_keypad/test.esp32-idf.yaml b/tests/components/matrix_keypad/test.esp32-idf.yaml index c8e9b54534..70bb70638d 100644 --- a/tests/components/matrix_keypad/test.esp32-idf.yaml +++ b/tests/components/matrix_keypad/test.esp32-idf.yaml @@ -1,11 +1,5 @@ -binary_sensor: - - platform: matrix_keypad - id: key4 - row: 1 - col: 1 - - platform: matrix_keypad - id: key1 - key: 1 +packages: + common: !include common.yaml matrix_keypad: id: keypad @@ -17,3 +11,5 @@ matrix_keypad: - pin: 15 keys: "1234" has_pulldowns: true + on_key: + - lambda: ESP_LOGI("KEY", "key %d pressed", x); diff --git a/tests/components/matrix_keypad/test.esp32-s3-idf.yaml b/tests/components/matrix_keypad/test.esp32-s3-idf.yaml new file mode 100644 index 0000000000..a491f2ed59 --- /dev/null +++ b/tests/components/matrix_keypad/test.esp32-s3-idf.yaml @@ -0,0 +1,15 @@ +packages: + common: !include common.yaml + +matrix_keypad: + id: keypad + rows: + - pin: 10 + - pin: 11 + columns: + - pin: 12 + - pin: 13 + keys: "1234" + has_pulldowns: true + on_key: + - lambda: ESP_LOGI("KEY", "key %d pressed", x); diff --git a/tests/components/matrix_keypad/test.esp8266-ard.yaml b/tests/components/matrix_keypad/test.esp8266-ard.yaml index c8e9b54534..70bb70638d 100644 --- a/tests/components/matrix_keypad/test.esp8266-ard.yaml +++ b/tests/components/matrix_keypad/test.esp8266-ard.yaml @@ -1,11 +1,5 @@ -binary_sensor: - - platform: matrix_keypad - id: key4 - row: 1 - col: 1 - - platform: matrix_keypad - id: key1 - key: 1 +packages: + common: !include common.yaml matrix_keypad: id: keypad @@ -17,3 +11,5 @@ matrix_keypad: - pin: 15 keys: "1234" has_pulldowns: true + on_key: + - lambda: ESP_LOGI("KEY", "key %d pressed", x); diff --git a/tests/components/matrix_keypad/test.rp2040-ard.yaml b/tests/components/matrix_keypad/test.rp2040-ard.yaml index d15e6af21a..75d9c0b263 100644 --- a/tests/components/matrix_keypad/test.rp2040-ard.yaml +++ b/tests/components/matrix_keypad/test.rp2040-ard.yaml @@ -1,11 +1,5 @@ -binary_sensor: - - platform: matrix_keypad - id: key4 - row: 1 - col: 1 - - platform: matrix_keypad - id: key1 - key: 1 +packages: + common: !include common.yaml matrix_keypad: id: keypad @@ -17,3 +11,5 @@ matrix_keypad: - pin: 4 keys: "1234" has_pulldowns: true + on_key: + - lambda: ESP_LOGI("KEY", "key %d pressed", x); From c0dcecc465fa8b0d3205880174ca820bc8bfd3d3 Mon Sep 17 00:00:00 2001 From: Citric Lee <37475446+limengdu@users.noreply.github.com> Date: Tue, 26 Nov 2024 08:53:21 +0800 Subject: [PATCH 084/107] Add: Seeed Studio mr60fda2 mmwave sensor (#7576) Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Co-authored-by: Spencer Yan --- CODEOWNERS | 1 + esphome/components/seeed_mr60fda2/__init__.py | 41 ++ .../seeed_mr60fda2/binary_sensor.py | 33 ++ .../seeed_mr60fda2/button/__init__.py | 45 +++ .../button/get_radar_parameters_button.cpp | 9 + .../button/get_radar_parameters_button.h | 18 + .../button/reset_radar_button.cpp | 9 + .../button/reset_radar_button.h | 18 + .../seeed_mr60fda2/seeed_mr60fda2.cpp | 368 ++++++++++++++++++ .../seeed_mr60fda2/seeed_mr60fda2.h | 101 +++++ .../seeed_mr60fda2/select/__init__.py | 59 +++ .../select/height_threshold_select.cpp | 15 + .../select/height_threshold_select.h | 18 + .../select/install_height_select.cpp | 15 + .../select/install_height_select.h | 18 + .../select/sensitivity_select.cpp | 15 + .../select/sensitivity_select.h | 18 + tests/components/seeed_mr60fda2/common.yaml | 34 ++ .../seeed_mr60fda2/test.esp32-c3-ard.yaml | 5 + .../seeed_mr60fda2/test.esp32-c3-idf.yaml | 5 + 20 files changed, 845 insertions(+) create mode 100644 esphome/components/seeed_mr60fda2/__init__.py create mode 100644 esphome/components/seeed_mr60fda2/binary_sensor.py create mode 100644 esphome/components/seeed_mr60fda2/button/__init__.py create mode 100644 esphome/components/seeed_mr60fda2/button/get_radar_parameters_button.cpp create mode 100644 esphome/components/seeed_mr60fda2/button/get_radar_parameters_button.h create mode 100644 esphome/components/seeed_mr60fda2/button/reset_radar_button.cpp create mode 100644 esphome/components/seeed_mr60fda2/button/reset_radar_button.h create mode 100644 esphome/components/seeed_mr60fda2/seeed_mr60fda2.cpp create mode 100644 esphome/components/seeed_mr60fda2/seeed_mr60fda2.h create mode 100644 esphome/components/seeed_mr60fda2/select/__init__.py create mode 100644 esphome/components/seeed_mr60fda2/select/height_threshold_select.cpp create mode 100644 esphome/components/seeed_mr60fda2/select/height_threshold_select.h create mode 100644 esphome/components/seeed_mr60fda2/select/install_height_select.cpp create mode 100644 esphome/components/seeed_mr60fda2/select/install_height_select.h create mode 100644 esphome/components/seeed_mr60fda2/select/sensitivity_select.cpp create mode 100644 esphome/components/seeed_mr60fda2/select/sensitivity_select.h create mode 100644 tests/components/seeed_mr60fda2/common.yaml create mode 100644 tests/components/seeed_mr60fda2/test.esp32-c3-ard.yaml create mode 100644 tests/components/seeed_mr60fda2/test.esp32-c3-idf.yaml diff --git a/CODEOWNERS b/CODEOWNERS index dd3926d283..fb6d11d1fb 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -354,6 +354,7 @@ esphome/components/sdl/* @clydebarrow esphome/components/sdm_meter/* @jesserockz @polyfaces esphome/components/sdp3x/* @Azimath esphome/components/seeed_mr24hpc1/* @limengdu +esphome/components/seeed_mr60fda2/* @limengdu esphome/components/selec_meter/* @sourabhjaiswal esphome/components/select/* @esphome/core esphome/components/sen0321/* @notjj diff --git a/esphome/components/seeed_mr60fda2/__init__.py b/esphome/components/seeed_mr60fda2/__init__.py new file mode 100644 index 0000000000..e79134deec --- /dev/null +++ b/esphome/components/seeed_mr60fda2/__init__.py @@ -0,0 +1,41 @@ +import esphome.codegen as cg +from esphome.components import uart +import esphome.config_validation as cv +from esphome.const import CONF_ID + +CODEOWNERS = ["@limengdu"] +DEPENDENCIES = ["uart"] +MULTI_CONF = True + +mr60fda2_ns = cg.esphome_ns.namespace("seeed_mr60fda2") + +MR60FDA2Component = mr60fda2_ns.class_( + "MR60FDA2Component", cg.Component, uart.UARTDevice +) + +CONF_MR60FDA2_ID = "mr60fda2_id" + +CONFIG_SCHEMA = ( + cv.Schema( + { + cv.GenerateID(): cv.declare_id(MR60FDA2Component), + } + ) + .extend(uart.UART_DEVICE_SCHEMA) + .extend(cv.COMPONENT_SCHEMA) +) + +FINAL_VALIDATE_SCHEMA = uart.final_validate_device_schema( + "seeed_mr60fda2", + require_tx=True, + require_rx=True, + baud_rate=115200, + parity="NONE", + stop_bits=1, +) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) + await uart.register_uart_device(var, config) diff --git a/esphome/components/seeed_mr60fda2/binary_sensor.py b/esphome/components/seeed_mr60fda2/binary_sensor.py new file mode 100644 index 0000000000..2860ac0100 --- /dev/null +++ b/esphome/components/seeed_mr60fda2/binary_sensor.py @@ -0,0 +1,33 @@ +import esphome.codegen as cg +from esphome.components import binary_sensor +import esphome.config_validation as cv +from esphome.const import DEVICE_CLASS_OCCUPANCY, DEVICE_CLASS_SAFETY + +from . import CONF_MR60FDA2_ID, MR60FDA2Component + +DEPENDENCIES = ["seeed_mr60fda2"] + +CONF_PEOPLE_EXIST = "people_exist" +CONF_FALL_DETECTED = "fall_detected" + +CONFIG_SCHEMA = { + cv.GenerateID(CONF_MR60FDA2_ID): cv.use_id(MR60FDA2Component), + cv.Optional(CONF_PEOPLE_EXIST): binary_sensor.binary_sensor_schema( + device_class=DEVICE_CLASS_OCCUPANCY, icon="mdi:motion-sensor" + ), + cv.Optional(CONF_FALL_DETECTED): binary_sensor.binary_sensor_schema( + device_class=DEVICE_CLASS_SAFETY, icon="mdi:emergency" + ), +} + + +async def to_code(config): + mr60fda2_component = await cg.get_variable(config[CONF_MR60FDA2_ID]) + + if people_exist_config := config.get(CONF_PEOPLE_EXIST): + sens = await binary_sensor.new_binary_sensor(people_exist_config) + cg.add(mr60fda2_component.set_people_exist_binary_sensor(sens)) + + if is_fall_config := config.get(CONF_FALL_DETECTED): + sens = await binary_sensor.new_binary_sensor(is_fall_config) + cg.add(mr60fda2_component.set_fall_detected_binary_sensor(sens)) diff --git a/esphome/components/seeed_mr60fda2/button/__init__.py b/esphome/components/seeed_mr60fda2/button/__init__.py new file mode 100644 index 0000000000..1415dc27ca --- /dev/null +++ b/esphome/components/seeed_mr60fda2/button/__init__.py @@ -0,0 +1,45 @@ +import esphome.codegen as cg +from esphome.components import button +import esphome.config_validation as cv +from esphome.const import ( + DEVICE_CLASS_RESTART, + DEVICE_CLASS_UPDATE, + ENTITY_CATEGORY_DIAGNOSTIC, + ENTITY_CATEGORY_NONE, + CONF_FACTORY_RESET, +) + +from .. import CONF_MR60FDA2_ID, MR60FDA2Component, mr60fda2_ns + +DEPENDENCIES = ["seeed_mr60fda2"] + +GetRadarParametersButton = mr60fda2_ns.class_("GetRadarParametersButton", button.Button) +ResetRadarButton = mr60fda2_ns.class_("ResetRadarButton", button.Button) + +CONF_GET_RADAR_PARAMETERS = "get_radar_parameters" + +CONFIG_SCHEMA = { + cv.GenerateID(CONF_MR60FDA2_ID): cv.use_id(MR60FDA2Component), + cv.Optional(CONF_GET_RADAR_PARAMETERS): button.button_schema( + GetRadarParametersButton, + device_class=DEVICE_CLASS_UPDATE, + entity_category=ENTITY_CATEGORY_NONE, + ), + cv.Optional(CONF_FACTORY_RESET): button.button_schema( + ResetRadarButton, + device_class=DEVICE_CLASS_RESTART, + entity_category=ENTITY_CATEGORY_DIAGNOSTIC, + ), +} + + +async def to_code(config): + mr60fda2_component = await cg.get_variable(config[CONF_MR60FDA2_ID]) + if get_radar_parameters_config := config.get(CONF_GET_RADAR_PARAMETERS): + b = await button.new_button(get_radar_parameters_config) + await cg.register_parented(b, config[CONF_MR60FDA2_ID]) + cg.add(mr60fda2_component.set_get_radar_parameters_button(b)) + if factory_reset_config := config.get(CONF_FACTORY_RESET): + b = await button.new_button(factory_reset_config) + await cg.register_parented(b, config[CONF_MR60FDA2_ID]) + cg.add(mr60fda2_component.set_factory_reset_button(b)) diff --git a/esphome/components/seeed_mr60fda2/button/get_radar_parameters_button.cpp b/esphome/components/seeed_mr60fda2/button/get_radar_parameters_button.cpp new file mode 100644 index 0000000000..88be6dfe7c --- /dev/null +++ b/esphome/components/seeed_mr60fda2/button/get_radar_parameters_button.cpp @@ -0,0 +1,9 @@ +#include "get_radar_parameters_button.h" + +namespace esphome { +namespace seeed_mr60fda2 { + +void GetRadarParametersButton::press_action() { this->parent_->get_radar_parameters(); } + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/button/get_radar_parameters_button.h b/esphome/components/seeed_mr60fda2/button/get_radar_parameters_button.h new file mode 100644 index 0000000000..9d6d507383 --- /dev/null +++ b/esphome/components/seeed_mr60fda2/button/get_radar_parameters_button.h @@ -0,0 +1,18 @@ +#pragma once + +#include "esphome/components/button/button.h" +#include "../seeed_mr60fda2.h" + +namespace esphome { +namespace seeed_mr60fda2 { + +class GetRadarParametersButton : public button::Button, public Parented { + public: + GetRadarParametersButton() = default; + + protected: + void press_action() override; +}; + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/button/reset_radar_button.cpp b/esphome/components/seeed_mr60fda2/button/reset_radar_button.cpp new file mode 100644 index 0000000000..0a5833a18c --- /dev/null +++ b/esphome/components/seeed_mr60fda2/button/reset_radar_button.cpp @@ -0,0 +1,9 @@ +#include "reset_radar_button.h" + +namespace esphome { +namespace seeed_mr60fda2 { + +void ResetRadarButton::press_action() { this->parent_->factory_reset(); } + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/button/reset_radar_button.h b/esphome/components/seeed_mr60fda2/button/reset_radar_button.h new file mode 100644 index 0000000000..66780fb8af --- /dev/null +++ b/esphome/components/seeed_mr60fda2/button/reset_radar_button.h @@ -0,0 +1,18 @@ +#pragma once + +#include "esphome/components/button/button.h" +#include "../seeed_mr60fda2.h" + +namespace esphome { +namespace seeed_mr60fda2 { + +class ResetRadarButton : public button::Button, public Parented { + public: + ResetRadarButton() = default; + + protected: + void press_action() override; +}; + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/seeed_mr60fda2.cpp b/esphome/components/seeed_mr60fda2/seeed_mr60fda2.cpp new file mode 100644 index 0000000000..d183a1f77f --- /dev/null +++ b/esphome/components/seeed_mr60fda2/seeed_mr60fda2.cpp @@ -0,0 +1,368 @@ +#include "seeed_mr60fda2.h" +#include "esphome/core/log.h" + +#include +#include + +namespace esphome { +namespace seeed_mr60fda2 { + +static const char *const TAG = "seeed_mr60fda2"; + +// Prints the component's configuration data. dump_config() prints all of the component's configuration +// items in an easy-to-read format, including the configuration key-value pairs. +void MR60FDA2Component::dump_config() { + ESP_LOGCONFIG(TAG, "MR60FDA2:"); +#ifdef USE_BINARY_SENSOR + LOG_BINARY_SENSOR(" ", "People Exist Binary Sensor", this->people_exist_binary_sensor_); + LOG_BINARY_SENSOR(" ", "Is Fall Binary Sensor", this->fall_detected_binary_sensor_); +#endif +#ifdef USE_BUTTON + LOG_BUTTON(" ", "Get Radar Parameters Button", this->get_radar_parameters_button_); + LOG_BUTTON(" ", "Reset Radar Button", this->factory_reset_button_); +#endif +#ifdef USE_SELECT + LOG_SELECT(" ", "Install Height Select", this->install_height_select_); + LOG_SELECT(" ", "Height Threshold Select", this->height_threshold_select_); + LOG_SELECT(" ", "Sensitivity Select", this->sensitivity_select_); +#endif +} + +// Initialisation functions +void MR60FDA2Component::setup() { + ESP_LOGCONFIG(TAG, "Setting up MR60FDA2..."); + this->check_uart_settings(115200); + + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + this->current_frame_id_ = 0; + this->current_frame_len_ = 0; + this->current_data_frame_len_ = 0; + this->current_frame_type_ = 0; + this->get_radar_parameters(); + + memset(this->current_frame_buf_, 0, FRAME_BUF_MAX_SIZE); + memset(this->current_data_buf_, 0, DATA_BUF_MAX_SIZE); + + ESP_LOGCONFIG(TAG, "Set up MR60FDA2 complete"); +} + +// main loop +void MR60FDA2Component::loop() { + uint8_t byte; + + // Is there data on the serial port + while (this->available()) { + this->read_byte(&byte); + this->split_frame_(byte); // split data frame + } +} + +/** + * @brief Calculate the checksum for a byte array. + * + * This function calculates the checksum for the provided byte array using an + * XOR-based checksum algorithm. + * + * @param data The byte array to calculate the checksum for. + * @param len The length of the byte array. + * @return The calculated checksum. + */ +static uint8_t calculate_checksum(const uint8_t *data, size_t len) { + uint8_t checksum = 0; + for (size_t i = 0; i < len; i++) { + checksum ^= data[i]; + } + checksum = ~checksum; + return checksum; +} + +/** + * @brief Validate the checksum of a byte array. + * + * This function validates the checksum of the provided byte array by comparing + * it to the expected checksum. + * + * @param data The byte array to validate. + * @param len The length of the byte array. + * @param expected_checksum The expected checksum. + * @return True if the checksum is valid, false otherwise. + */ +static bool validate_checksum(const uint8_t *data, size_t len, uint8_t expected_checksum) { + return calculate_checksum(data, len) == expected_checksum; +} + +static uint8_t find_nearest_index(float value, const float *arr, int size) { + int nearest_index = 0; + float min_diff = std::abs(value - arr[0]); + for (int i = 1; i < size; ++i) { + float diff = std::abs(value - arr[i]); + if (diff < min_diff) { + min_diff = diff; + nearest_index = i; + } + } + return nearest_index; +} + +/** + * @brief Convert a float value to a byte array. + * + * This function converts a float value to a byte array. + * + * @param value The float value to convert. + * @param bytes The byte array to store the converted value. + */ +static void float_to_bytes(float value, unsigned char *bytes) { + union { + float float_value; + unsigned char byte_array[4]; + } u; + + u.float_value = value; + memcpy(bytes, u.byte_array, 4); +} + +/** + * @brief Convert a 32-bit unsigned integer to a byte array. + * + * This function converts a 32-bit unsigned integer to a byte array. + * + * @param value The 32-bit unsigned integer to convert. + * @param bytes The byte array to store the converted value. + */ +static void int_to_bytes(uint32_t value, unsigned char *bytes) { + bytes[0] = value & 0xFF; + bytes[1] = (value >> 8) & 0xFF; + bytes[2] = (value >> 16) & 0xFF; + bytes[3] = (value >> 24) & 0xFF; +} + +void MR60FDA2Component::split_frame_(uint8_t buffer) { + switch (this->current_frame_locate_) { + case LOCATE_FRAME_HEADER: // starting buffer + if (buffer == FRAME_HEADER_BUFFER) { + this->current_frame_len_ = 1; + this->current_frame_buf_[this->current_frame_len_ - 1] = buffer; + this->current_frame_locate_++; + } + break; + case LOCATE_ID_FRAME1: + this->current_frame_id_ = buffer << 8; + this->current_frame_len_++; + this->current_frame_buf_[this->current_frame_len_ - 1] = buffer; + this->current_frame_locate_++; + break; + case LOCATE_ID_FRAME2: + this->current_frame_id_ += buffer; + this->current_frame_len_++; + this->current_frame_buf_[this->current_frame_len_ - 1] = buffer; + this->current_frame_locate_++; + break; + case LOCATE_LENGTH_FRAME_H: + this->current_data_frame_len_ = buffer << 8; + if (this->current_data_frame_len_ == 0x00) { + this->current_frame_len_++; + this->current_frame_buf_[this->current_frame_len_ - 1] = buffer; + this->current_frame_locate_++; + } else { + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + } + break; + case LOCATE_LENGTH_FRAME_L: + this->current_data_frame_len_ += buffer; + if (this->current_data_frame_len_ > DATA_BUF_MAX_SIZE) { + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + } else { + this->current_frame_len_++; + this->current_frame_buf_[this->current_frame_len_ - 1] = buffer; + this->current_frame_locate_++; + } + break; + case LOCATE_TYPE_FRAME1: + this->current_frame_type_ = buffer << 8; + this->current_frame_len_++; + this->current_frame_buf_[this->current_frame_len_ - 1] = buffer; + this->current_frame_locate_++; + break; + case LOCATE_TYPE_FRAME2: + this->current_frame_type_ += buffer; + if ((this->current_frame_type_ == IS_FALL_TYPE_BUFFER) || + (this->current_frame_type_ == PEOPLE_EXIST_TYPE_BUFFER) || + (this->current_frame_type_ == RESULT_INSTALL_HEIGHT) || (this->current_frame_type_ == RESULT_PARAMETERS) || + (this->current_frame_type_ == RESULT_HEIGHT_THRESHOLD) || (this->current_frame_type_ == RESULT_SENSITIVITY)) { + this->current_frame_len_++; + this->current_frame_buf_[this->current_frame_len_ - 1] = buffer; + this->current_frame_locate_++; + } else { + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + } + break; + case LOCATE_HEAD_CKSUM_FRAME: + if (validate_checksum(this->current_frame_buf_, this->current_frame_len_, buffer)) { + this->current_frame_len_++; + this->current_frame_buf_[this->current_frame_len_ - 1] = buffer; + this->current_frame_locate_++; + } else { + ESP_LOGD(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", buffer); + ESP_LOGV(TAG, "CURRENT_FRAME: %s %s", + format_hex_pretty(this->current_frame_buf_, this->current_frame_len_).c_str(), + format_hex_pretty(&buffer, 1).c_str()); + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + } + break; + case LOCATE_DATA_FRAME: + this->current_frame_len_++; + this->current_frame_buf_[this->current_frame_len_ - 1] = buffer; + this->current_data_buf_[this->current_frame_len_ - LEN_TO_DATA_FRAME] = buffer; + if (this->current_frame_len_ - LEN_TO_HEAD_CKSUM == this->current_data_frame_len_) { + this->current_frame_locate_++; + } + if (this->current_frame_len_ > FRAME_BUF_MAX_SIZE) { + ESP_LOGD(TAG, "PRACTICE_DATA_FRAME_LEN ERROR: %d", this->current_frame_len_ - LEN_TO_HEAD_CKSUM); + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + } + break; + case LOCATE_DATA_CKSUM_FRAME: + if (validate_checksum(this->current_data_buf_, this->current_data_frame_len_, buffer)) { + this->current_frame_len_++; + this->current_frame_buf_[this->current_frame_len_ - 1] = buffer; + this->current_frame_locate_++; + this->process_frame_(); + } else { + ESP_LOGD(TAG, "DATA_CKSUM_FRAME ERROR: 0x%02x", buffer); + ESP_LOGV(TAG, "GET CURRENT_FRAME: %s %s", + format_hex_pretty(this->current_frame_buf_, this->current_frame_len_).c_str(), + format_hex_pretty(&buffer, 1).c_str()); + + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + } + break; + default: + break; + } +} + +void MR60FDA2Component::process_frame_() { + switch (this->current_frame_type_) { + case IS_FALL_TYPE_BUFFER: + if (this->fall_detected_binary_sensor_ != nullptr) { + this->fall_detected_binary_sensor_->publish_state(this->current_frame_buf_[LEN_TO_HEAD_CKSUM]); + } + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + break; + + case PEOPLE_EXIST_TYPE_BUFFER: + if (this->people_exist_binary_sensor_ != nullptr) + this->people_exist_binary_sensor_->publish_state(this->current_frame_buf_[LEN_TO_HEAD_CKSUM]); + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + break; + + case RESULT_INSTALL_HEIGHT: + if (this->current_data_buf_[0]) { + ESP_LOGD(TAG, "Successfully set the mounting height"); + } else { + ESP_LOGD(TAG, "Failed to set the mounting height"); + } + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + break; + + case RESULT_HEIGHT_THRESHOLD: + if (this->current_data_buf_[0]) { + ESP_LOGD(TAG, "Successfully set the height threshold"); + } else { + ESP_LOGD(TAG, "Failed to set the height threshold"); + } + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + break; + + case RESULT_SENSITIVITY: + if (this->current_data_buf_[0]) { + ESP_LOGD(TAG, "Successfully set the sensitivity"); + } else { + ESP_LOGD(TAG, "Failed to set the sensitivity"); + } + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + break; + + case RESULT_PARAMETERS: { + float install_height_float = 0; + float height_threshold_float = 0; + uint32_t current_sensitivity = 0; + if (this->install_height_select_ != nullptr) { + uint32_t current_install_height_int = + encode_uint32(current_data_buf_[3], current_data_buf_[2], current_data_buf_[1], current_data_buf_[0]); + + install_height_float = bit_cast(current_install_height_int); + uint32_t select_index = find_nearest_index(install_height_float, INSTALL_HEIGHT, 7); + this->install_height_select_->publish_state(this->install_height_select_->at(select_index).value()); + } + + if (this->height_threshold_select_ != nullptr) { + uint32_t current_height_threshold_int = + encode_uint32(current_data_buf_[7], current_data_buf_[6], current_data_buf_[5], current_data_buf_[4]); + + height_threshold_float = bit_cast(current_height_threshold_int); + size_t select_index = find_nearest_index(height_threshold_float, HEIGHT_THRESHOLD, 7); + this->height_threshold_select_->publish_state(this->height_threshold_select_->at(select_index).value()); + } + + if (this->sensitivity_select_ != nullptr) { + current_sensitivity = + encode_uint32(current_data_buf_[11], current_data_buf_[10], current_data_buf_[9], current_data_buf_[8]); + + uint32_t select_index = find_nearest_index(current_sensitivity, SENSITIVITY, 3); + this->sensitivity_select_->publish_state(this->sensitivity_select_->at(select_index).value()); + } + + ESP_LOGD(TAG, "Mounting height: %.2f, Height threshold: %.2f, Sensitivity: %" PRIu32, install_height_float, + height_threshold_float, current_sensitivity); + this->current_frame_locate_ = LOCATE_FRAME_HEADER; + break; + } + default: + break; + } +} + +// Send Heartbeat Packet Command +void MR60FDA2Component::set_install_height(uint8_t index) { + uint8_t send_data[13] = {0x01, 0x00, 0x00, 0x00, 0x04, 0x0E, 0x04, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00}; + float_to_bytes(INSTALL_HEIGHT[index], &send_data[8]); + send_data[12] = calculate_checksum(send_data + 8, 4); + this->write_array(send_data, 13); + ESP_LOGV(TAG, "SEND INSTALL HEIGHT FRAME: %s", format_hex_pretty(send_data, 13).c_str()); +} + +void MR60FDA2Component::set_height_threshold(uint8_t index) { + uint8_t send_data[13] = {0x01, 0x00, 0x00, 0x00, 0x04, 0x0E, 0x08, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00}; + float_to_bytes(INSTALL_HEIGHT[index], &send_data[8]); + send_data[12] = calculate_checksum(send_data + 8, 4); + this->write_array(send_data, 13); + ESP_LOGV(TAG, "SEND HEIGHT THRESHOLD: %s", format_hex_pretty(send_data, 13).c_str()); +} + +void MR60FDA2Component::set_sensitivity(uint8_t index) { + uint8_t send_data[13] = {0x01, 0x00, 0x00, 0x00, 0x04, 0x0E, 0x0A, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00}; + + int_to_bytes(SENSITIVITY[index], &send_data[8]); + + send_data[12] = calculate_checksum(send_data + 8, 4); + this->write_array(send_data, 13); + ESP_LOGV(TAG, "SEND SET SENSITIVITY: %s", format_hex_pretty(send_data, 13).c_str()); +} + +void MR60FDA2Component::get_radar_parameters() { + uint8_t send_data[8] = {0x01, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x06, 0xF6}; + this->write_array(send_data, 8); + ESP_LOGV(TAG, "SEND GET PARAMETERS: %s", format_hex_pretty(send_data, 8).c_str()); +} + +void MR60FDA2Component::factory_reset() { + uint8_t send_data[8] = {0x01, 0x00, 0x00, 0x00, 0x00, 0x21, 0x10, 0xCF}; + this->write_array(send_data, 8); + ESP_LOGV(TAG, "SEND RESET: %s", format_hex_pretty(send_data, 8).c_str()); + this->get_radar_parameters(); +} + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/seeed_mr60fda2.h b/esphome/components/seeed_mr60fda2/seeed_mr60fda2.h new file mode 100644 index 0000000000..e1ffa4f071 --- /dev/null +++ b/esphome/components/seeed_mr60fda2/seeed_mr60fda2.h @@ -0,0 +1,101 @@ +#pragma once +#include "esphome/core/component.h" +#include "esphome/core/defines.h" +#ifdef USE_BINARY_SENSOR +#include "esphome/components/binary_sensor/binary_sensor.h" +#endif +#ifdef USE_BUTTON +#include "esphome/components/button/button.h" +#endif +#ifdef USE_SELECT +#include "esphome/components/select/select.h" +#endif +#ifdef USE_TEXT_SENSOR +#include "esphome/components/text_sensor/text_sensor.h" +#endif +#include "esphome/components/uart/uart.h" +#include "esphome/core/automation.h" +#include "esphome/core/helpers.h" + +#include + +namespace esphome { +namespace seeed_mr60fda2 { + +static const uint8_t DATA_BUF_MAX_SIZE = 28; +static const uint8_t FRAME_BUF_MAX_SIZE = 37; +static const uint8_t LEN_TO_HEAD_CKSUM = 8; +static const uint8_t LEN_TO_DATA_FRAME = 9; + +static const uint8_t FRAME_HEADER_BUFFER = 0x01; +static const uint16_t IS_FALL_TYPE_BUFFER = 0x0E02; +static const uint16_t PEOPLE_EXIST_TYPE_BUFFER = 0x0F09; +static const uint16_t RESULT_INSTALL_HEIGHT = 0x0E04; +static const uint16_t RESULT_PARAMETERS = 0x0E06; +static const uint16_t RESULT_HEIGHT_THRESHOLD = 0x0E08; +static const uint16_t RESULT_SENSITIVITY = 0x0E0A; + +enum FrameLocation { + LOCATE_FRAME_HEADER, + LOCATE_ID_FRAME1, + LOCATE_ID_FRAME2, + LOCATE_LENGTH_FRAME_H, + LOCATE_LENGTH_FRAME_L, + LOCATE_TYPE_FRAME1, + LOCATE_TYPE_FRAME2, + LOCATE_HEAD_CKSUM_FRAME, // Header checksum: [from the first byte to the previous byte of the HEAD_CKSUM bit] + LOCATE_DATA_FRAME, + LOCATE_DATA_CKSUM_FRAME, // Data checksum: [from the first to the previous byte of the DATA_CKSUM bit] + LOCATE_PROCESS_FRAME, +}; + +static const float INSTALL_HEIGHT[7] = {2.4f, 2.5f, 2.6f, 2.7f, 2.8f, 2.9f, 3.0f}; +static const float HEIGHT_THRESHOLD[7] = {0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f}; +static const float SENSITIVITY[3] = {3, 15, 30}; + +static const char *const INSTALL_HEIGHT_STR[7] = {"2.4m", "2.5m", "2.6", "2.7m", "2.8", "2.9m", "3.0m"}; +static const char *const HEIGHT_THRESHOLD_STR[7] = {"0.0m", "0.1m", "0.2m", "0.3m", "0.4m", "0.5m", "0.6m"}; +static const char *const SENSITIVITY_STR[3] = {"1", "2", "3"}; + +class MR60FDA2Component : public Component, + public uart::UARTDevice { // The class name must be the name defined by text_sensor.py +#ifdef USE_BINARY_SENSOR + SUB_BINARY_SENSOR(people_exist) + SUB_BINARY_SENSOR(fall_detected) +#endif +#ifdef USE_BUTTON + SUB_BUTTON(get_radar_parameters) + SUB_BUTTON(factory_reset) +#endif +#ifdef USE_SELECT + SUB_SELECT(install_height) + SUB_SELECT(height_threshold) + SUB_SELECT(sensitivity) +#endif + + protected: + uint8_t current_frame_locate_; + uint8_t current_frame_buf_[FRAME_BUF_MAX_SIZE]; + uint8_t current_data_buf_[DATA_BUF_MAX_SIZE]; + uint16_t current_frame_id_; + size_t current_frame_len_; + size_t current_data_frame_len_; + uint16_t current_frame_type_; + + void split_frame_(uint8_t buffer); + void process_frame_(); + + public: + float get_setup_priority() const override { return esphome::setup_priority::LATE; } + void setup() override; + void dump_config() override; + void loop() override; + void set_install_height(uint8_t index); + void set_height_threshold(uint8_t index); + void set_sensitivity(uint8_t index); + void get_radar_parameters(); + void factory_reset(); +}; + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/select/__init__.py b/esphome/components/seeed_mr60fda2/select/__init__.py new file mode 100644 index 0000000000..a6f9eeb920 --- /dev/null +++ b/esphome/components/seeed_mr60fda2/select/__init__.py @@ -0,0 +1,59 @@ +import esphome.codegen as cg +from esphome.components import select +import esphome.config_validation as cv +from esphome.const import CONF_SENSITIVITY, ENTITY_CATEGORY_CONFIG, ICON_ACCELERATION_Z + +from .. import CONF_MR60FDA2_ID, MR60FDA2Component, mr60fda2_ns + + +DEPENDENCIES = ["seeed_mr60fda2"] + +InstallHeightSelect = mr60fda2_ns.class_("InstallHeightSelect", select.Select) +HeightThresholdSelect = mr60fda2_ns.class_("HeightThresholdSelect", select.Select) +SensitivitySelect = mr60fda2_ns.class_("SensitivitySelect", select.Select) + +CONF_INSTALL_HEIGHT = "install_height" +CONF_HEIGHT_THRESHOLD = "height_threshold" + +CONFIG_SCHEMA = { + cv.GenerateID(CONF_MR60FDA2_ID): cv.use_id(MR60FDA2Component), + cv.Optional(CONF_INSTALL_HEIGHT): select.select_schema( + InstallHeightSelect, + entity_category=ENTITY_CATEGORY_CONFIG, + icon=ICON_ACCELERATION_Z, + ), + cv.Optional(CONF_HEIGHT_THRESHOLD): select.select_schema( + HeightThresholdSelect, + entity_category=ENTITY_CATEGORY_CONFIG, + icon=ICON_ACCELERATION_Z, + ), + cv.Optional(CONF_SENSITIVITY): select.select_schema( + SensitivitySelect, + entity_category=ENTITY_CATEGORY_CONFIG, + ), +} + + +async def to_code(config): + mr60fda2_component = await cg.get_variable(config[CONF_MR60FDA2_ID]) + if install_height_config := config.get(CONF_INSTALL_HEIGHT): + s = await select.new_select( + install_height_config, + options=["2.4m", "2.5m", "2.6m", "2.7m", "2.8m", "2.9m", "3.0m"], + ) + await cg.register_parented(s, config[CONF_MR60FDA2_ID]) + cg.add(mr60fda2_component.set_install_height_select(s)) + if height_threshold_config := config.get(CONF_HEIGHT_THRESHOLD): + s = await select.new_select( + height_threshold_config, + options=["0.0m", "0.1m", "0.2m", "0.3m", "0.4m", "0.5m", "0.6m"], + ) + await cg.register_parented(s, config[CONF_MR60FDA2_ID]) + cg.add(mr60fda2_component.set_height_threshold_select(s)) + if sensitivity_config := config.get(CONF_SENSITIVITY): + s = await select.new_select( + sensitivity_config, + options=["1", "2", "3"], + ) + await cg.register_parented(s, config[CONF_MR60FDA2_ID]) + cg.add(mr60fda2_component.set_sensitivity_select(s)) diff --git a/esphome/components/seeed_mr60fda2/select/height_threshold_select.cpp b/esphome/components/seeed_mr60fda2/select/height_threshold_select.cpp new file mode 100644 index 0000000000..037f8c6036 --- /dev/null +++ b/esphome/components/seeed_mr60fda2/select/height_threshold_select.cpp @@ -0,0 +1,15 @@ +#include "height_threshold_select.h" + +namespace esphome { +namespace seeed_mr60fda2 { + +void HeightThresholdSelect::control(const std::string &value) { + this->publish_state(value); + auto index = this->index_of(value); + if (index.has_value()) { + this->parent_->set_height_threshold(index.value()); + } +} + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/select/height_threshold_select.h b/esphome/components/seeed_mr60fda2/select/height_threshold_select.h new file mode 100644 index 0000000000..b856dbc89a --- /dev/null +++ b/esphome/components/seeed_mr60fda2/select/height_threshold_select.h @@ -0,0 +1,18 @@ +#pragma once + +#include "esphome/components/select/select.h" +#include "../seeed_mr60fda2.h" + +namespace esphome { +namespace seeed_mr60fda2 { + +class HeightThresholdSelect : public select::Select, public Parented { + public: + HeightThresholdSelect() = default; + + protected: + void control(const std::string &value) override; +}; + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/select/install_height_select.cpp b/esphome/components/seeed_mr60fda2/select/install_height_select.cpp new file mode 100644 index 0000000000..e791911613 --- /dev/null +++ b/esphome/components/seeed_mr60fda2/select/install_height_select.cpp @@ -0,0 +1,15 @@ +#include "install_height_select.h" + +namespace esphome { +namespace seeed_mr60fda2 { + +void InstallHeightSelect::control(const std::string &value) { + this->publish_state(value); + auto index = this->index_of(value); + if (index.has_value()) { + this->parent_->set_install_height(index.value()); + } +} + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/select/install_height_select.h b/esphome/components/seeed_mr60fda2/select/install_height_select.h new file mode 100644 index 0000000000..7430da3493 --- /dev/null +++ b/esphome/components/seeed_mr60fda2/select/install_height_select.h @@ -0,0 +1,18 @@ +#pragma once + +#include "esphome/components/select/select.h" +#include "../seeed_mr60fda2.h" + +namespace esphome { +namespace seeed_mr60fda2 { + +class InstallHeightSelect : public select::Select, public Parented { + public: + InstallHeightSelect() = default; + + protected: + void control(const std::string &value) override; +}; + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/select/sensitivity_select.cpp b/esphome/components/seeed_mr60fda2/select/sensitivity_select.cpp new file mode 100644 index 0000000000..e2507fb7cc --- /dev/null +++ b/esphome/components/seeed_mr60fda2/select/sensitivity_select.cpp @@ -0,0 +1,15 @@ +#include "sensitivity_select.h" + +namespace esphome { +namespace seeed_mr60fda2 { + +void SensitivitySelect::control(const std::string &value) { + this->publish_state(value); + auto index = this->index_of(value); + if (index.has_value()) { + this->parent_->set_sensitivity(index.value()); + } +} + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/esphome/components/seeed_mr60fda2/select/sensitivity_select.h b/esphome/components/seeed_mr60fda2/select/sensitivity_select.h new file mode 100644 index 0000000000..d1accc1b5b --- /dev/null +++ b/esphome/components/seeed_mr60fda2/select/sensitivity_select.h @@ -0,0 +1,18 @@ +#pragma once + +#include "esphome/components/select/select.h" +#include "../seeed_mr60fda2.h" + +namespace esphome { +namespace seeed_mr60fda2 { + +class SensitivitySelect : public select::Select, public Parented { + public: + SensitivitySelect() = default; + + protected: + void control(const std::string &value) override; +}; + +} // namespace seeed_mr60fda2 +} // namespace esphome diff --git a/tests/components/seeed_mr60fda2/common.yaml b/tests/components/seeed_mr60fda2/common.yaml new file mode 100644 index 0000000000..55a7cc1ab3 --- /dev/null +++ b/tests/components/seeed_mr60fda2/common.yaml @@ -0,0 +1,34 @@ +uart: + - id: seeed_mr60fda2_uart + tx_pin: ${uart_tx_pin} + rx_pin: ${uart_rx_pin} + baud_rate: 115200 + parity: NONE + stop_bits: 1 + +seeed_mr60fda2: + id: my_seeed_mr60fda2 + uart_id: seeed_mr60fda2_uart + +binary_sensor: + - platform: seeed_mr60fda2 + people_exist: + name: "Person Information" + fall_detected: + name: "Falling Information" + +button: + - platform: seeed_mr60fda2 + get_radar_parameters: + name: "Get Radar Parameters" + factory_reset: + name: "Reset" + +select: + - platform: seeed_mr60fda2 + install_height: + name: "Set Install Height" + height_threshold: + name: "Set Height Threshold" + sensitivity: + name: "Set Sensitivity" diff --git a/tests/components/seeed_mr60fda2/test.esp32-c3-ard.yaml b/tests/components/seeed_mr60fda2/test.esp32-c3-ard.yaml new file mode 100644 index 0000000000..4fb884abf4 --- /dev/null +++ b/tests/components/seeed_mr60fda2/test.esp32-c3-ard.yaml @@ -0,0 +1,5 @@ +substitutions: + uart_tx_pin: GPIO5 + uart_rx_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/seeed_mr60fda2/test.esp32-c3-idf.yaml b/tests/components/seeed_mr60fda2/test.esp32-c3-idf.yaml new file mode 100644 index 0000000000..4fb884abf4 --- /dev/null +++ b/tests/components/seeed_mr60fda2/test.esp32-c3-idf.yaml @@ -0,0 +1,5 @@ +substitutions: + uart_tx_pin: GPIO5 + uart_rx_pin: GPIO4 + +<<: !include common.yaml From ae6736311a47ddc5c63dd36b0d2cb4af29f4dd14 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Mon, 25 Nov 2024 22:29:36 -0600 Subject: [PATCH 085/107] [lvgl] clang-tidy fixes for #7822 (#7843) --- esphome/components/lvgl/lvgl_esphome.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/lvgl/lvgl_esphome.cpp b/esphome/components/lvgl/lvgl_esphome.cpp index 41346bc732..61bdfe9755 100644 --- a/esphome/components/lvgl/lvgl_esphome.cpp +++ b/esphome/components/lvgl/lvgl_esphome.cpp @@ -279,7 +279,7 @@ std::string LvSelectable::get_selected_text() { static std::string join_string(std::vector options) { return std::accumulate( options.begin(), options.end(), std::string(), - [](const std::string &a, const std::string &b) -> std::string { return a + (a.length() > 0 ? "\n" : "") + b; }); + [](const std::string &a, const std::string &b) -> std::string { return a + (!a.empty() ? "\n" : "") + b; }); } void LvSelectable::set_selected_text(const std::string &text, lv_anim_enable_t anim) { From 72df3d1606aaaf650d49c342439bb2294d9ca76c Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 03:37:20 -0600 Subject: [PATCH 086/107] [xiaomi_ble] clang-tidy fixes for #7822 (#7860) --- esphome/components/xiaomi_ble/xiaomi_ble.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/xiaomi_ble/xiaomi_ble.cpp b/esphome/components/xiaomi_ble/xiaomi_ble.cpp index 85434341cc..04e0724ba7 100644 --- a/esphome/components/xiaomi_ble/xiaomi_ble.cpp +++ b/esphome/components/xiaomi_ble/xiaomi_ble.cpp @@ -249,7 +249,7 @@ optional parse_xiaomi_header(const esp32_ble_tracker::Service } bool decrypt_xiaomi_payload(std::vector &raw, const uint8_t *bindkey, const uint64_t &address) { - if (!((raw.size() == 19) || ((raw.size() >= 22) && (raw.size() <= 24)))) { + if ((raw.size() != 19) && ((raw.size() < 22) || (raw.size() > 24))) { ESP_LOGVV(TAG, "decrypt_xiaomi_payload(): data packet has wrong size (%d)!", raw.size()); ESP_LOGVV(TAG, " Packet : %s", format_hex_pretty(raw.data(), raw.size()).c_str()); return false; From 11076e4614075109ce8cc51d4aae70559fc2394b Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 03:47:24 -0600 Subject: [PATCH 087/107] [wireguard] clang-tidy fixes for #7822 (#7859) --- esphome/components/wireguard/wireguard.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/esphome/components/wireguard/wireguard.cpp b/esphome/components/wireguard/wireguard.cpp index 7b4011cb79..431bf52227 100644 --- a/esphome/components/wireguard/wireguard.cpp +++ b/esphome/components/wireguard/wireguard.cpp @@ -37,7 +37,7 @@ void Wireguard::setup() { this->wg_config_.netmask = this->netmask_.c_str(); this->wg_config_.persistent_keepalive = this->keepalive_; - if (this->preshared_key_.length() > 0) + if (!this->preshared_key_.empty()) this->wg_config_.preshared_key = this->preshared_key_.c_str(); this->publish_enabled_state(); @@ -137,7 +137,7 @@ void Wireguard::dump_config() { ESP_LOGCONFIG(TAG, " Peer Port: " LOG_SECRET("%d"), this->peer_port_); ESP_LOGCONFIG(TAG, " Peer Public Key: " LOG_SECRET("%s"), this->peer_public_key_.c_str()); ESP_LOGCONFIG(TAG, " Peer Pre-shared Key: " LOG_SECRET("%s"), - (this->preshared_key_.length() > 0 ? mask_key(this->preshared_key_).c_str() : "NOT IN USE")); + (!this->preshared_key_.empty() ? mask_key(this->preshared_key_).c_str() : "NOT IN USE")); ESP_LOGCONFIG(TAG, " Peer Allowed IPs:"); for (auto &allowed_ip : this->allowed_ips_) { ESP_LOGCONFIG(TAG, " - %s/%s", std::get<0>(allowed_ip).c_str(), std::get<1>(allowed_ip).c_str()); From 841d278224d7a82ff8112cb3ee80dbe31347d84b Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 03:47:57 -0600 Subject: [PATCH 088/107] [dsmr] clang-tidy fixes for #7822 (#7848) --- esphome/components/dsmr/dsmr.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/dsmr/dsmr.cpp b/esphome/components/dsmr/dsmr.cpp index 193ea1d4e5..c0a2883d79 100644 --- a/esphome/components/dsmr/dsmr.cpp +++ b/esphome/components/dsmr/dsmr.cpp @@ -296,7 +296,7 @@ void Dsmr::dump_config() { } void Dsmr::set_decryption_key(const std::string &decryption_key) { - if (decryption_key.length() == 0) { + if (decryption_key.empty()) { ESP_LOGI(TAG, "Disabling decryption"); this->decryption_key_.clear(); if (this->crypt_telegram_ != nullptr) { From 6e50e2aa6534c31dbc9e425781c76581178ea68c Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Tue, 26 Nov 2024 22:50:16 +1300 Subject: [PATCH 089/107] Fix entity name validation to allow "Off" and "On" (#7821) --- esphome/config_validation.py | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/esphome/config_validation.py b/esphome/config_validation.py index 98b81ec328..ebfb2631c3 100644 --- a/esphome/config_validation.py +++ b/esphome/config_validation.py @@ -1839,8 +1839,6 @@ def validate_registry_entry(name, registry): def none(value): if value in ("none", "None"): return None - if boolean(value) is False: - return None raise Invalid("Must be none") @@ -1912,17 +1910,23 @@ MQTT_COMMAND_COMPONENT_SCHEMA = MQTT_COMPONENT_SCHEMA.extend( } ) + +def _validate_entity_name(value): + value = string(value) + try: + value = none(value) # pylint: disable=assignment-from-none + except Invalid: + pass + else: + requires_friendly_name( + "Name cannot be None when esphome->friendly_name is not set!" + )(value) + return value + + ENTITY_BASE_SCHEMA = Schema( { - Optional(CONF_NAME): Any( - All( - none, - requires_friendly_name( - "Name cannot be None when esphome->friendly_name is not set!" - ), - ), - string, - ), + Optional(CONF_NAME): _validate_entity_name, Optional(CONF_INTERNAL): boolean, Optional(CONF_DISABLED_BY_DEFAULT, default=False): boolean, Optional(CONF_ICON): icon, From 2eac8b6c4643494640aa6889025ba5791c09dc36 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 03:50:33 -0600 Subject: [PATCH 090/107] [camera_web_server] Use header instead of mock struct (#7823) --- esphome/components/esp32_camera_web_server/camera_web_server.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/esp32_camera_web_server/camera_web_server.h b/esphome/components/esp32_camera_web_server/camera_web_server.h index f65625554c..3ba8f31dd7 100644 --- a/esphome/components/esp32_camera_web_server/camera_web_server.h +++ b/esphome/components/esp32_camera_web_server/camera_web_server.h @@ -11,7 +11,7 @@ #include "esphome/core/helpers.h" #include "esphome/core/preferences.h" -struct httpd_req; +struct httpd_req; // NOLINT(readability-identifier-naming) namespace esphome { namespace esp32_camera_web_server { From 1c2d2bce5af36527abe758d88f68289b7bccd482 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 03:52:26 -0600 Subject: [PATCH 091/107] [display_menu_base] clang-tidy fixes for #7822 (#7847) --- esphome/components/display_menu_base/display_menu_base.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/display_menu_base/display_menu_base.cpp b/esphome/components/display_menu_base/display_menu_base.cpp index 5502623607..2d8e6ae5fc 100644 --- a/esphome/components/display_menu_base/display_menu_base.cpp +++ b/esphome/components/display_menu_base/display_menu_base.cpp @@ -280,7 +280,7 @@ bool DisplayMenuComponent::cursor_down_() { bool DisplayMenuComponent::enter_menu_() { this->displayed_item_->on_leave(); this->displayed_item_ = static_cast(this->get_selected_item_()); - this->selection_stack_.push_front({this->top_index_, this->cursor_index_}); + this->selection_stack_.emplace_front(this->top_index_, this->cursor_index_); this->cursor_index_ = this->top_index_ = 0; this->displayed_item_->on_enter(); From 536bcab5def03c8177cdfc31c6deb3aa01d8ccf3 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 03:52:57 -0600 Subject: [PATCH 092/107] [nextion] clang-tidy fixes for #7822 (#7852) --- esphome/components/nextion/nextion.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/nextion/nextion.cpp b/esphome/components/nextion/nextion.cpp index 984db09c57..7c41f8dfe2 100644 --- a/esphome/components/nextion/nextion.cpp +++ b/esphome/components/nextion/nextion.cpp @@ -343,7 +343,7 @@ void Nextion::process_serial_() { } // nextion.tech/instruction-set/ void Nextion::process_nextion_commands_() { - if (this->command_data_.length() == 0) { + if (this->command_data_.empty()) { return; } From 2d4688a2061e5734ad136f717ba77a7dc7a9fec7 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 03:53:23 -0600 Subject: [PATCH 093/107] [shelly_dimmer] clang-tidy fixes for #7822 (#7844) --- esphome/components/shelly_dimmer/shelly_dimmer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/shelly_dimmer/shelly_dimmer.cpp b/esphome/components/shelly_dimmer/shelly_dimmer.cpp index b415840bdc..d4229b2384 100644 --- a/esphome/components/shelly_dimmer/shelly_dimmer.cpp +++ b/esphome/components/shelly_dimmer/shelly_dimmer.cpp @@ -466,7 +466,7 @@ bool ShellyDimmer::handle_frame_() { } case SHELLY_DIMMER_PROTO_CMD_SWITCH: case SHELLY_DIMMER_PROTO_CMD_SETTINGS: { - return !(payload_len < 1 || payload[0] != 0x01); + return payload_len >= 1 && payload[0] == 0x01; } default: { return false; From e6bd2238ce1fceef7db2cadbae3736a5759e16b2 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 03:54:16 -0600 Subject: [PATCH 094/107] [sim800l] clang-tidy fixes for #7822 (#7856) --- esphome/components/sim800l/sim800l.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/sim800l/sim800l.cpp b/esphome/components/sim800l/sim800l.cpp index 4f7aa228e9..38775b0062 100644 --- a/esphome/components/sim800l/sim800l.cpp +++ b/esphome/components/sim800l/sim800l.cpp @@ -324,7 +324,7 @@ void Sim800LComponent::parse_cmd_(std::string message) { this->sms_received_callback_.call(this->message_, this->sender_); this->state_ = STATE_RECEIVED_SMS; } else { - if (this->message_.length() > 0) + if (!this->message_.empty()) this->message_ += "\n"; this->message_ += message; } From 6b59f55a5097f40c3db18ded853cc27888bd2885 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 03:58:18 -0600 Subject: [PATCH 095/107] [nfc, pn532, pn7150, pn7160] clang-tidy fixes for #7822 (#7853) --- esphome/components/nfc/ndef_record.cpp | 6 +++--- esphome/components/pn532/pn532_mifare_ultralight.cpp | 4 ++-- esphome/components/pn7150/pn7150_mifare_ultralight.cpp | 4 ++-- esphome/components/pn7160/pn7160_mifare_ultralight.cpp | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/esphome/components/nfc/ndef_record.cpp b/esphome/components/nfc/ndef_record.cpp index 8eb0c3b901..540ba62940 100644 --- a/esphome/components/nfc/ndef_record.cpp +++ b/esphome/components/nfc/ndef_record.cpp @@ -30,13 +30,13 @@ std::vector NdefRecord::encode(bool first, bool last) { data.push_back(payload_length & 0xFF); } - if (this->id_.length()) { + if (!this->id_.empty()) { data.push_back(this->id_.length()); } data.insert(data.end(), this->type_.begin(), this->type_.end()); - if (this->id_.length()) { + if (!this->id_.empty()) { data.insert(data.end(), this->id_.begin(), this->id_.end()); } @@ -55,7 +55,7 @@ uint8_t NdefRecord::create_flag_byte(bool first, bool last, size_t payload_size) if (payload_size <= 255) { value = value | 0x10; // Set SR bit } - if (this->id_.length()) { + if (!this->id_.empty()) { value = value | 0x08; // Set IL bit } return value; diff --git a/esphome/components/pn532/pn532_mifare_ultralight.cpp b/esphome/components/pn532/pn532_mifare_ultralight.cpp index b08a7336c7..f823829a6c 100644 --- a/esphome/components/pn532/pn532_mifare_ultralight.cpp +++ b/esphome/components/pn532/pn532_mifare_ultralight.cpp @@ -80,8 +80,8 @@ bool PN532::is_mifare_ultralight_formatted_(const std::vector &page_3_t const uint8_t p4_offset = nfc::MIFARE_ULTRALIGHT_PAGE_SIZE; // page 4 will begin 4 bytes into the vector return (page_3_to_6.size() > p4_offset + 3) && - !((page_3_to_6[p4_offset + 0] == 0xFF) && (page_3_to_6[p4_offset + 1] == 0xFF) && - (page_3_to_6[p4_offset + 2] == 0xFF) && (page_3_to_6[p4_offset + 3] == 0xFF)); + ((page_3_to_6[p4_offset + 0] != 0xFF) || (page_3_to_6[p4_offset + 1] != 0xFF) || + (page_3_to_6[p4_offset + 2] != 0xFF) || (page_3_to_6[p4_offset + 3] != 0xFF)); } uint16_t PN532::read_mifare_ultralight_capacity_() { diff --git a/esphome/components/pn7150/pn7150_mifare_ultralight.cpp b/esphome/components/pn7150/pn7150_mifare_ultralight.cpp index 791b0634d6..b107f6f79e 100644 --- a/esphome/components/pn7150/pn7150_mifare_ultralight.cpp +++ b/esphome/components/pn7150/pn7150_mifare_ultralight.cpp @@ -81,8 +81,8 @@ bool PN7150::is_mifare_ultralight_formatted_(const std::vector &page_3_ const uint8_t p4_offset = nfc::MIFARE_ULTRALIGHT_PAGE_SIZE; // page 4 will begin 4 bytes into the vector return (page_3_to_6.size() > p4_offset + 3) && - !((page_3_to_6[p4_offset + 0] == 0xFF) && (page_3_to_6[p4_offset + 1] == 0xFF) && - (page_3_to_6[p4_offset + 2] == 0xFF) && (page_3_to_6[p4_offset + 3] == 0xFF)); + ((page_3_to_6[p4_offset + 0] != 0xFF) || (page_3_to_6[p4_offset + 1] != 0xFF) || + (page_3_to_6[p4_offset + 2] != 0xFF) || (page_3_to_6[p4_offset + 3] != 0xFF)); } uint16_t PN7150::read_mifare_ultralight_capacity_() { diff --git a/esphome/components/pn7160/pn7160_mifare_ultralight.cpp b/esphome/components/pn7160/pn7160_mifare_ultralight.cpp index a74f23d4f2..65daac494f 100644 --- a/esphome/components/pn7160/pn7160_mifare_ultralight.cpp +++ b/esphome/components/pn7160/pn7160_mifare_ultralight.cpp @@ -81,8 +81,8 @@ bool PN7160::is_mifare_ultralight_formatted_(const std::vector &page_3_ const uint8_t p4_offset = nfc::MIFARE_ULTRALIGHT_PAGE_SIZE; // page 4 will begin 4 bytes into the vector return (page_3_to_6.size() > p4_offset + 3) && - !((page_3_to_6[p4_offset + 0] == 0xFF) && (page_3_to_6[p4_offset + 1] == 0xFF) && - (page_3_to_6[p4_offset + 2] == 0xFF) && (page_3_to_6[p4_offset + 3] == 0xFF)); + ((page_3_to_6[p4_offset + 0] != 0xFF) || (page_3_to_6[p4_offset + 1] != 0xFF) || + (page_3_to_6[p4_offset + 2] != 0xFF) || (page_3_to_6[p4_offset + 3] != 0xFF)); } uint16_t PN7160::read_mifare_ultralight_capacity_() { From 31c13e4c16f18e3ae241b223a529ee5ed2a08fd8 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 03:59:29 -0600 Subject: [PATCH 096/107] [output] clang-tidy fixes for #7822 (#7854) --- esphome/components/output/float_output.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/output/float_output.cpp b/esphome/components/output/float_output.cpp index f120f86f1f..e7dba1d81d 100644 --- a/esphome/components/output/float_output.cpp +++ b/esphome/components/output/float_output.cpp @@ -32,7 +32,7 @@ void FloatOutput::set_level(float state) { } #endif - if (!(state == 0.0f && this->zero_means_zero_)) // regardless of min_power_, 0.0 means off + if (state != 0.0f || !this->zero_means_zero_) // regardless of min_power_, 0.0 means off state = (state * (this->max_power_ - this->min_power_)) + this->min_power_; if (this->is_inverted()) From bdc6302ea1b17319d2529d9d5e277ba416e18687 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 04:00:03 -0600 Subject: [PATCH 097/107] [sun_gtil2] clang-tidy fixes for #7822 (#7858) --- esphome/components/sun_gtil2/sun_gtil2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/sun_gtil2/sun_gtil2.cpp b/esphome/components/sun_gtil2/sun_gtil2.cpp index 1653f937dd..46b4902654 100644 --- a/esphome/components/sun_gtil2/sun_gtil2.cpp +++ b/esphome/components/sun_gtil2/sun_gtil2.cpp @@ -83,7 +83,7 @@ void SunGTIL2::handle_char_(uint8_t c) { memcpy(&msg, this->rx_message_.data(), MESSAGE_SIZE); this->rx_message_.clear(); - if (!((msg.end[0] == 0) && (msg.end[38] == 0x08))) + if ((msg.end[0] != 0) || (msg.end[38] != 0x08)) return; ESP_LOGVV(TAG, "Frequency raw value: %02x", msg.frequency); From 4c383906c490192a692cc74da82fca5d81fe17fc Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 04:00:40 -0600 Subject: [PATCH 098/107] [pipsolar] clang-tidy fixes for #7822 (#7855) --- esphome/components/pipsolar/pipsolar.cpp | 4 ++-- esphome/components/pipsolar/switch/pipsolar_switch.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/esphome/components/pipsolar/pipsolar.cpp b/esphome/components/pipsolar/pipsolar.cpp index c4bc018b75..03c699e7d4 100644 --- a/esphome/components/pipsolar/pipsolar.cpp +++ b/esphome/components/pipsolar/pipsolar.cpp @@ -790,7 +790,7 @@ uint8_t Pipsolar::check_incoming_crc_() { // send next command used uint8_t Pipsolar::send_next_command_() { uint16_t crc16; - if (this->command_queue_[this->command_queue_position_].length() != 0) { + if (!this->command_queue_[this->command_queue_position_].empty()) { const char *command = this->command_queue_[this->command_queue_position_].c_str(); uint8_t byte_command[16]; uint8_t length = this->command_queue_[this->command_queue_position_].length(); @@ -846,7 +846,7 @@ void Pipsolar::queue_command_(const char *command, uint8_t length) { uint8_t next_position = command_queue_position_; for (uint8_t i = 0; i < COMMAND_QUEUE_LENGTH; i++) { uint8_t testposition = (next_position + i) % COMMAND_QUEUE_LENGTH; - if (command_queue_[testposition].length() == 0) { + if (command_queue_[testposition].empty()) { command_queue_[testposition] = command; ESP_LOGD(TAG, "Command queued successfully: %s with length %u at position %d", command, command_queue_[testposition].length(), testposition); diff --git a/esphome/components/pipsolar/switch/pipsolar_switch.cpp b/esphome/components/pipsolar/switch/pipsolar_switch.cpp index 7eaeac1c2d..be7763226b 100644 --- a/esphome/components/pipsolar/switch/pipsolar_switch.cpp +++ b/esphome/components/pipsolar/switch/pipsolar_switch.cpp @@ -10,11 +10,11 @@ static const char *const TAG = "pipsolar.switch"; void PipsolarSwitch::dump_config() { LOG_SWITCH("", "Pipsolar Switch", this); } void PipsolarSwitch::write_state(bool state) { if (state) { - if (this->on_command_.length() > 0) { + if (!this->on_command_.empty()) { this->parent_->switch_command(this->on_command_); } } else { - if (this->off_command_.length() > 0) { + if (!this->off_command_.empty()) { this->parent_->switch_command(this->off_command_); } } From 2fa8d907b3506a0db2dc4ed28940bb7d7e30ca4f Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 04:01:34 -0600 Subject: [PATCH 099/107] [ltr501] clang-tidy fixes for #7822 (#7850) --- esphome/components/ltr501/ltr501.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/ltr501/ltr501.cpp b/esphome/components/ltr501/ltr501.cpp index 4f4e26f44f..b30e520f2b 100644 --- a/esphome/components/ltr501/ltr501.cpp +++ b/esphome/components/ltr501/ltr501.cpp @@ -23,7 +23,7 @@ bool operator==(const GainTimePair &lhs, const GainTimePair &rhs) { } bool operator!=(const GainTimePair &lhs, const GainTimePair &rhs) { - return !(lhs.gain == rhs.gain && lhs.time == rhs.time); + return lhs.gain != rhs.gain || lhs.time != rhs.time; } template T get_next(const T (&array)[size], const T val) { From cd1ee9660644177c99302d0698cefed6a9802361 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 04:04:50 -0600 Subject: [PATCH 100/107] [cse7766] clang-tidy fixes for #7822 (#7846) --- esphome/components/cse7766/cse7766.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/cse7766/cse7766.cpp b/esphome/components/cse7766/cse7766.cpp index 48240464b3..3907c195d0 100644 --- a/esphome/components/cse7766/cse7766.cpp +++ b/esphome/components/cse7766/cse7766.cpp @@ -43,7 +43,7 @@ bool CSE7766Component::check_byte_() { uint8_t index = this->raw_data_index_; uint8_t byte = this->raw_data_[index]; if (index == 0) { - return !((byte != 0x55) && ((byte & 0xF0) != 0xF0) && (byte != 0xAA)); + return (byte == 0x55) || ((byte & 0xF0) == 0xF0) || (byte == 0xAA); } if (index == 1) { From be7882727448093efd3043364607ad925058606b Mon Sep 17 00:00:00 2001 From: Samuel Sieb Date: Tue, 26 Nov 2024 00:05:20 -1000 Subject: [PATCH 101/107] [honeywell] use warning instead of failing (#7862) Co-authored-by: Samuel Sieb --- .../components/honeywellabp2_i2c/honeywellabp2.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/esphome/components/honeywellabp2_i2c/honeywellabp2.cpp b/esphome/components/honeywellabp2_i2c/honeywellabp2.cpp index e2910032cc..d111723669 100644 --- a/esphome/components/honeywellabp2_i2c/honeywellabp2.cpp +++ b/esphome/components/honeywellabp2_i2c/honeywellabp2.cpp @@ -15,7 +15,7 @@ static const char *const TAG = "honeywellabp2"; void HONEYWELLABP2Sensor::read_sensor_data() { if (this->read(raw_data_, 7) != i2c::ERROR_OK) { ESP_LOGE(TAG, "Communication with ABP2 failed!"); - this->mark_failed(); + this->status_set_warning("couldn't read sensor data"); return; } float press_counts = encode_uint24(raw_data_[1], raw_data_[2], raw_data_[3]); // calculate digital pressure counts @@ -25,12 +25,13 @@ void HONEYWELLABP2Sensor::read_sensor_data() { (this->max_pressure_ - this->min_pressure_)) + this->min_pressure_; this->last_temperature_ = (temp_counts * 200 / 16777215) - 50; + this->status_clear_warning(); } void HONEYWELLABP2Sensor::start_measurement() { if (this->write(i2c_cmd_, 3) != i2c::ERROR_OK) { ESP_LOGE(TAG, "Communication with ABP2 failed!"); - this->mark_failed(); + this->status_set_warning("couldn't start measurement"); return; } this->measurement_running_ = true; @@ -39,7 +40,7 @@ void HONEYWELLABP2Sensor::start_measurement() { bool HONEYWELLABP2Sensor::is_measurement_ready() { if (this->read(raw_data_, 1) != i2c::ERROR_OK) { ESP_LOGE(TAG, "Communication with ABP2 failed!"); - this->mark_failed(); + this->status_set_warning("couldn't check measurement"); return false; } if ((raw_data_[0] & (0x1 << STATUS_BIT_BUSY)) > 0) { @@ -52,7 +53,7 @@ bool HONEYWELLABP2Sensor::is_measurement_ready() { void HONEYWELLABP2Sensor::measurement_timeout() { ESP_LOGE(TAG, "Timeout!"); this->measurement_running_ = false; - this->mark_failed(); + this->status_set_warning("measurement timed out"); } float HONEYWELLABP2Sensor::get_pressure() { return this->last_pressure_; } @@ -79,7 +80,7 @@ void HONEYWELLABP2Sensor::update() { ESP_LOGV(TAG, "Update Honeywell ABP2 Sensor"); this->start_measurement(); - this->set_timeout("meas_timeout", 50, [this] { this->measurement_timeout(); }); + this->set_timeout("meas_timeout", 100, [this] { this->measurement_timeout(); }); } void HONEYWELLABP2Sensor::dump_config() { From 2b9013699d841a7878a796f5621adfa3461f597d Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 04:05:39 -0600 Subject: [PATCH 102/107] [alarm_control_panel] clang-tidy fixes for #7822 (#7845) --- .../alarm_control_panel/alarm_control_panel_call.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/esphome/components/alarm_control_panel/alarm_control_panel_call.cpp b/esphome/components/alarm_control_panel/alarm_control_panel_call.cpp index b1d2b2a097..7bb9b9989c 100644 --- a/esphome/components/alarm_control_panel/alarm_control_panel_call.cpp +++ b/esphome/components/alarm_control_panel/alarm_control_panel_call.cpp @@ -72,10 +72,9 @@ void AlarmControlPanelCall::validate_() { this->state_.reset(); return; } - if (state == ACP_STATE_DISARMED && - !(this->parent_->is_state_armed(this->parent_->get_state()) || - this->parent_->get_state() == ACP_STATE_PENDING || this->parent_->get_state() == ACP_STATE_ARMING || - this->parent_->get_state() == ACP_STATE_TRIGGERED)) { + if (state == ACP_STATE_DISARMED && !this->parent_->is_state_armed(this->parent_->get_state()) && + this->parent_->get_state() != ACP_STATE_PENDING && this->parent_->get_state() != ACP_STATE_ARMING && + this->parent_->get_state() != ACP_STATE_TRIGGERED) { ESP_LOGW(TAG, "Cannot disarm when not armed"); this->state_.reset(); return; From 3730b0310b23c989c8c27d5701c3d423b6c749d6 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 12:07:36 -0600 Subject: [PATCH 103/107] [sprinkler] clang-tidy fixes for #7822 (#7857) --- esphome/components/sprinkler/sprinkler.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/esphome/components/sprinkler/sprinkler.cpp b/esphome/components/sprinkler/sprinkler.cpp index 59565251c3..5384d29871 100644 --- a/esphome/components/sprinkler/sprinkler.cpp +++ b/esphome/components/sprinkler/sprinkler.cpp @@ -419,7 +419,7 @@ void Sprinkler::add_valve(SprinklerControllerSwitch *valve_sw, SprinklerControll SprinklerValve *new_valve = &this->valve_[new_valve_number]; new_valve->controller_switch = valve_sw; - new_valve->controller_switch->set_state_lambda([=]() -> optional { + new_valve->controller_switch->set_state_lambda([this, new_valve_number]() -> optional { if (this->valve_pump_switch(new_valve_number) != nullptr) { return this->valve_switch(new_valve_number)->state() && this->valve_pump_switch(new_valve_number)->state(); } @@ -445,7 +445,7 @@ void Sprinkler::add_controller(Sprinkler *other_controller) { this->other_contro void Sprinkler::set_controller_main_switch(SprinklerControllerSwitch *controller_switch) { this->controller_sw_ = controller_switch; - controller_switch->set_state_lambda([=]() -> optional { + controller_switch->set_state_lambda([this]() -> optional { for (size_t valve_number = 0; valve_number < this->number_of_valves(); valve_number++) { if (this->valve_[valve_number].controller_switch->state) { return true; From 53691d28a81644b84f82e4441da153b27cbfddd7 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 12:07:42 -0600 Subject: [PATCH 104/107] [haier] clang-tidy fixes for #7822 (#7849) --- esphome/components/haier/hon_climate.cpp | 135 ++++++++++------------- 1 file changed, 60 insertions(+), 75 deletions(-) diff --git a/esphome/components/haier/hon_climate.cpp b/esphome/components/haier/hon_climate.cpp index e7be1fa418..85e9cf37b9 100644 --- a/esphome/components/haier/hon_climate.cpp +++ b/esphome/components/haier/hon_climate.cpp @@ -1069,19 +1069,17 @@ void HonClimate::fill_control_messages_queue_() { climate_control = this->current_hvac_settings_; // Beeper command { - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::BEEPER_STATUS, - this->get_beeper_state() ? ZERO_BUF : ONE_BUF, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::BEEPER_STATUS, + this->get_beeper_state() ? ZERO_BUF : ONE_BUF, 2); } // Health mode { - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::HEALTH_MODE, - this->get_health_mode() ? ONE_BUF : ZERO_BUF, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::HEALTH_MODE, + this->get_health_mode() ? ONE_BUF : ZERO_BUF, 2); this->health_mode_ = (SwitchState) ((uint8_t) this->health_mode_ & 0b01); } // Climate mode @@ -1099,51 +1097,46 @@ void HonClimate::fill_control_messages_queue_() { case CLIMATE_MODE_HEAT_COOL: new_power = true; buffer[1] = (uint8_t) hon_protocol::ConditioningMode::AUTO; - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::AC_MODE, - buffer, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::AC_MODE, + buffer, 2); fan_mode_buf[1] = this->other_modes_fan_speed_; break; case CLIMATE_MODE_HEAT: new_power = true; buffer[1] = (uint8_t) hon_protocol::ConditioningMode::HEAT; - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::AC_MODE, - buffer, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::AC_MODE, + buffer, 2); fan_mode_buf[1] = this->other_modes_fan_speed_; break; case CLIMATE_MODE_DRY: new_power = true; buffer[1] = (uint8_t) hon_protocol::ConditioningMode::DRY; - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::AC_MODE, - buffer, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::AC_MODE, + buffer, 2); fan_mode_buf[1] = this->other_modes_fan_speed_; break; case CLIMATE_MODE_FAN_ONLY: new_power = true; buffer[1] = (uint8_t) hon_protocol::ConditioningMode::FAN; - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::AC_MODE, - buffer, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::AC_MODE, + buffer, 2); fan_mode_buf[1] = this->other_modes_fan_speed_; // Auto doesn't work in fan only mode break; case CLIMATE_MODE_COOL: new_power = true; buffer[1] = (uint8_t) hon_protocol::ConditioningMode::COOL; - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::AC_MODE, - buffer, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::AC_MODE, + buffer, 2); fan_mode_buf[1] = this->other_modes_fan_speed_; break; default: @@ -1153,11 +1146,10 @@ void HonClimate::fill_control_messages_queue_() { } // Climate power { - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::AC_POWER, - new_power ? ONE_BUF : ZERO_BUF, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::AC_POWER, + new_power ? ONE_BUF : ZERO_BUF, 2); } // CLimate preset { @@ -1199,36 +1191,32 @@ void HonClimate::fill_control_messages_queue_() { } auto presets = this->traits_.get_supported_presets(); if (quiet_mode_buf[1] != 0xFF) { - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::QUIET_MODE, - quiet_mode_buf, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::QUIET_MODE, + quiet_mode_buf, 2); } if ((fast_mode_buf[1] != 0xFF) && ((presets.find(climate::ClimatePreset::CLIMATE_PRESET_BOOST) != presets.end()))) { - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::FAST_MODE, - fast_mode_buf, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::FAST_MODE, + fast_mode_buf, 2); } if ((away_mode_buf[1] != 0xFF) && ((presets.find(climate::ClimatePreset::CLIMATE_PRESET_AWAY) != presets.end()))) { - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::TEN_DEGREE, - away_mode_buf, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::TEN_DEGREE, + away_mode_buf, 2); } } // Target temperature if (climate_control.target_temperature.has_value() && (this->mode != ClimateMode::CLIMATE_MODE_FAN_ONLY)) { uint8_t buffer[2] = {0x00, 0x00}; buffer[1] = ((uint8_t) climate_control.target_temperature.value()) - 16; - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::SET_POINT, - buffer, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::SET_POINT, + buffer, 2); } // Vertical swing mode if (climate_control.swing_mode.has_value()) { @@ -1248,16 +1236,14 @@ void HonClimate::fill_control_messages_queue_() { case CLIMATE_SWING_BOTH: break; } - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::HORIZONTAL_SWING_MODE, - horizontal_swing_buf, 2)); - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::VERTICAL_SWING_MODE, - vertical_swing_buf, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::HORIZONTAL_SWING_MODE, + horizontal_swing_buf, 2); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::VERTICAL_SWING_MODE, + vertical_swing_buf, 2); } // Fan mode if (climate_control.fan_mode.has_value()) { @@ -1280,11 +1266,10 @@ void HonClimate::fill_control_messages_queue_() { break; } if (fan_mode_buf[1] != 0xFF) { - this->control_messages_queue_.push( - haier_protocol::HaierMessage(haier_protocol::FrameType::CONTROL, - (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + - (uint8_t) hon_protocol::DataParameters::FAN_MODE, - fan_mode_buf, 2)); + this->control_messages_queue_.emplace(haier_protocol::FrameType::CONTROL, + (uint16_t) hon_protocol::SubcommandsControl::SET_SINGLE_PARAMETER + + (uint8_t) hon_protocol::DataParameters::FAN_MODE, + fan_mode_buf, 2); } } } From 39f3f795e2b927af404e80286d5af8100fc7c80d Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 12:07:53 -0600 Subject: [PATCH 105/107] [mqtt] clang-tidy fixes for #7822 (#7851) --- esphome/components/mqtt/mqtt_backend_esp32.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/esphome/components/mqtt/mqtt_backend_esp32.cpp b/esphome/components/mqtt/mqtt_backend_esp32.cpp index ed500c6d44..2cccb957eb 100644 --- a/esphome/components/mqtt/mqtt_backend_esp32.cpp +++ b/esphome/components/mqtt/mqtt_backend_esp32.cpp @@ -151,11 +151,11 @@ void MQTTBackendESP32::mqtt_event_handler_(const Event &event) { break; case MQTT_EVENT_DATA: { static std::string topic; - if (event.topic.length() > 0) { + if (!event.topic.empty()) { topic = event.topic; } ESP_LOGV(TAG, "MQTT_EVENT_DATA %s", topic.c_str()); - this->on_message_.call(event.topic.length() > 0 ? topic.c_str() : nullptr, event.data.data(), event.data.size(), + this->on_message_.call(!event.topic.empty() ? topic.c_str() : nullptr, event.data.data(), event.data.size(), event.current_data_offset, event.total_data_len); } break; case MQTT_EVENT_ERROR: @@ -184,7 +184,7 @@ void MQTTBackendESP32::mqtt_event_handler(void *handler_args, esp_event_base_t b // queue event to decouple processing if (instance) { auto event = *static_cast(event_data); - instance->mqtt_events_.push(Event(event)); + instance->mqtt_events_.emplace(event); } } From e3d673d16c766181c9cda046cca78bc17e0936a6 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Tue, 26 Nov 2024 12:08:02 -0600 Subject: [PATCH 106/107] [helpers, optional] clang-tidy fixes for #7822 (#7841) --- esphome/core/helpers.cpp | 2 +- esphome/core/optional.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp index befc84516c..103173095b 100644 --- a/esphome/core/helpers.cpp +++ b/esphome/core/helpers.cpp @@ -293,7 +293,7 @@ std::string str_sanitize(const std::string &str) { std::replace_if( out.begin(), out.end(), [](const char &c) { - return !(c == '-' || c == '_' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); + return c != '-' && c != '_' && (c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z'); }, '_'); return out; diff --git a/esphome/core/optional.h b/esphome/core/optional.h index 1e28ef1354..591bc7aa68 100644 --- a/esphome/core/optional.h +++ b/esphome/core/optional.h @@ -59,7 +59,7 @@ template class optional { // NOLINT return *this; } - void swap(optional &rhs) { + void swap(optional &rhs) noexcept { using std::swap; if (has_value() && rhs.has_value()) { swap(**this, *rhs); @@ -206,7 +206,7 @@ template inline bool operator>=(U const &v, optional // Specialized algorithms -template void swap(optional &x, optional &y) { x.swap(y); } +template void swap(optional &x, optional &y) noexcept { x.swap(y); } // Convenience function to create an optional. From 921be1a17c5b8fdd638518e8c3c92f87ed0cca2d Mon Sep 17 00:00:00 2001 From: Jesse Hills <3060199+jesserockz@users.noreply.github.com> Date: Wed, 27 Nov 2024 07:09:16 +1300 Subject: [PATCH 107/107] Move ``USE_CAPTIVE_PORTAL`` into all define groups it can be used with (#7863) --- esphome/core/defines.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/esphome/core/defines.h b/esphome/core/defines.h index 3798ddba6a..eb3b20d007 100644 --- a/esphome/core/defines.h +++ b/esphome/core/defines.h @@ -84,7 +84,6 @@ // Arduino-specific feature flags #ifdef USE_ARDUINO -#define USE_CAPTIVE_PORTAL #define USE_PROMETHEUS #define USE_WIFI_WPA2_EAP #endif @@ -97,6 +96,7 @@ // ESP32-specific feature flags #ifdef USE_ESP32 #define USE_BLUETOOTH_PROXY +#define USE_CAPTIVE_PORTAL #define USE_ESP32_BLE #define USE_ESP32_BLE_CLIENT #define USE_ESP32_BLE_SERVER @@ -135,6 +135,7 @@ #ifdef USE_ESP8266 #define USE_ADC_SENSOR_VCC #define USE_ARDUINO_VERSION_CODE VERSION_CODE(3, 1, 2) +#define USE_CAPTIVE_PORTAL #define USE_ESP8266_PREFERENCES_FLASH #define USE_HTTP_REQUEST_ESP8266_HTTPS #define USE_SOCKET_IMPL_LWIP_TCP @@ -159,6 +160,7 @@ #endif #ifdef USE_LIBRETINY +#define USE_CAPTIVE_PORTAL #define USE_SOCKET_IMPL_LWIP_SOCKETS #define USE_WEBSERVER #define USE_WEBSERVER_PORT 80 // NOLINT