diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca6d1b0aac..b7546012e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -214,17 +214,51 @@ jobs: if: matrix.os == 'windows-latest' run: | ./venv/Scripts/activate - pytest -vv --cov-report=xml --tb=native -n auto tests + pytest -vv --cov-report=xml --tb=native -n auto tests --ignore=tests/integration/ - name: Run pytest if: matrix.os == 'ubuntu-latest' || matrix.os == 'macOS-latest' run: | . venv/bin/activate - pytest -vv --cov-report=xml --tb=native -n auto tests + pytest -vv --cov-report=xml --tb=native -n auto tests --ignore=tests/integration/ - name: Upload coverage to Codecov uses: codecov/codecov-action@v5.4.3 with: token: ${{ secrets.CODECOV_TOKEN }} + integration-tests: + name: Run integration tests + runs-on: ubuntu-latest + needs: + - common + steps: + - name: Check out code from GitHub + uses: actions/checkout@v4.2.2 + - name: Set up Python 3.13 + id: python + uses: actions/setup-python@v5.6.0 + with: + python-version: "3.13" + - name: Restore Python virtual environment + id: cache-venv + uses: actions/cache@v4.2.3 + with: + path: venv + key: ${{ runner.os }}-${{ steps.python.outputs.python-version }}-venv-${{ needs.common.outputs.cache-key }} + - name: Create Python virtual environment + if: steps.cache-venv.outputs.cache-hit != 'true' + run: | + python -m venv venv + . venv/bin/activate + python --version + pip install -r requirements.txt -r requirements_test.txt + pip install -e . + - name: Register matcher + run: echo "::add-matcher::.github/workflows/matchers/pytest.json" + - name: Run integration tests + run: | + . venv/bin/activate + pytest -vv --no-cov --tb=native -n auto tests/integration/ + clang-format: name: Check clang-format runs-on: ubuntu-24.04 @@ -494,6 +528,7 @@ jobs: - flake8 - pylint - pytest + - integration-tests - pyupgrade - clang-tidy - list-components diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1a0289a3ca..831473c325 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ repos: - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: v0.12.1 + rev: v0.12.2 hooks: # Run the linter. - id: ruff diff --git a/CODEOWNERS b/CODEOWNERS index 16f38da725..ca3849eb0d 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -87,6 +87,7 @@ esphome/components/bp1658cj/* @Cossid esphome/components/bp5758d/* @Cossid esphome/components/button/* @esphome/core esphome/components/bytebuffer/* @clydebarrow +esphome/components/camera/* @DT-art1 @bdraco esphome/components/canbus/* @danielschramm @mvturnho esphome/components/cap1188/* @mreditor97 esphome/components/captive_portal/* @OttoWinter @@ -124,6 +125,7 @@ esphome/components/dht/* @OttoWinter esphome/components/display_menu_base/* @numo68 esphome/components/dps310/* @kbx81 esphome/components/ds1307/* @badbadc0ffee +esphome/components/ds2484/* @mrk-its esphome/components/dsmr/* @glmnet @zuidwijk esphome/components/duty_time/* @dudanov esphome/components/ee895/* @Stock-M @@ -440,6 +442,8 @@ esphome/components/sun/* @OttoWinter esphome/components/sun_gtil2/* @Mat931 esphome/components/switch/* @esphome/core esphome/components/switch/binary_sensor/* @ssieb +esphome/components/sx126x/* @swoboda1337 +esphome/components/sx127x/* @swoboda1337 esphome/components/syslog/* @clydebarrow esphome/components/t6615/* @tylermenezes esphome/components/tc74/* @sethgirvan diff --git a/esphome/components/adc/__init__.py b/esphome/components/adc/__init__.py index 5f94c61a08..10b7df8638 100644 --- a/esphome/components/adc/__init__.py +++ b/esphome/components/adc/__init__.py @@ -10,8 +10,15 @@ from esphome.components.esp32.const import ( VARIANT_ESP32S2, VARIANT_ESP32S3, ) +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv -from esphome.const import CONF_ANALOG, CONF_INPUT, CONF_NUMBER, PLATFORM_ESP8266 +from esphome.const import ( + CONF_ANALOG, + CONF_INPUT, + CONF_NUMBER, + PLATFORM_ESP8266, + PlatformFramework, +) from esphome.core import CORE CODEOWNERS = ["@esphome/core"] @@ -229,3 +236,20 @@ def validate_adc_pin(value): )(value) raise NotImplementedError + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "adc_sensor_esp32.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + "adc_sensor_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "adc_sensor_rp2040.cpp": {PlatformFramework.RP2040_ARDUINO}, + "adc_sensor_libretiny.cpp": { + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + } +) diff --git a/esphome/components/api/__init__.py b/esphome/components/api/__init__.py index b02a875d72..eb8883b025 100644 --- a/esphome/components/api/__init__.py +++ b/esphome/components/api/__init__.py @@ -3,6 +3,7 @@ import base64 from esphome import automation from esphome.automation import Condition import esphome.codegen as cg +from esphome.config_helpers import get_logger_level import esphome.config_validation as cv from esphome.const import ( CONF_ACTION, @@ -132,7 +133,9 @@ async def to_code(config): await cg.register_component(var, config) cg.add(var.set_port(config[CONF_PORT])) - cg.add(var.set_password(config[CONF_PASSWORD])) + if config[CONF_PASSWORD]: + cg.add_define("USE_API_PASSWORD") + cg.add(var.set_password(config[CONF_PASSWORD])) cg.add(var.set_reboot_timeout(config[CONF_REBOOT_TIMEOUT])) cg.add(var.set_batch_delay(config[CONF_BATCH_DELAY])) @@ -311,3 +314,17 @@ async def homeassistant_tag_scanned_to_code(config, action_id, template_arg, arg @automation.register_condition("api.connected", APIConnectedCondition, {}) async def api_connected_to_code(config, condition_id, template_arg, args): return cg.new_Pvariable(condition_id, template_arg) + + +def FILTER_SOURCE_FILES() -> list[str]: + """Filter out api_pb2_dump.cpp when proto message dumping is not enabled.""" + # api_pb2_dump.cpp is only needed when HAS_PROTO_MESSAGE_DUMP is defined + # This is a particularly large file that still needs to be opened and read + # all the way to the end even when ifdef'd out + # + # HAS_PROTO_MESSAGE_DUMP is defined when ESPHOME_LOG_HAS_VERY_VERBOSE is set, + # which happens when the logger level is VERY_VERBOSE + if get_logger_level() != "VERY_VERBOSE": + return ["api_pb2_dump.cpp"] + + return [] diff --git a/esphome/components/api/api.proto b/esphome/components/api/api.proto index 58a0b52555..c3795bb796 100644 --- a/esphome/components/api/api.proto +++ b/esphome/components/api/api.proto @@ -311,6 +311,7 @@ message BinarySensorStateResponse { // If the binary sensor does not have a valid state yet. // Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller bool missing_state = 3; + uint32 device_id = 4; } // ==================== COVER ==================== @@ -360,6 +361,7 @@ message CoverStateResponse { float position = 3; float tilt = 4; CoverOperation current_operation = 5; + uint32 device_id = 6; } enum LegacyCoverCommand { @@ -432,6 +434,7 @@ message FanStateResponse { FanDirection direction = 5; int32 speed_level = 6; string preset_mode = 7; + uint32 device_id = 8; } message FanCommandRequest { option (id) = 31; @@ -513,6 +516,7 @@ message LightStateResponse { float cold_white = 12; float warm_white = 13; string effect = 9; + uint32 device_id = 14; } message LightCommandRequest { option (id) = 32; @@ -598,6 +602,7 @@ message SensorStateResponse { // If the sensor does not have a valid state yet. // Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller bool missing_state = 3; + uint32 device_id = 4; } // ==================== SWITCH ==================== @@ -628,6 +633,7 @@ message SwitchStateResponse { fixed32 key = 1; bool state = 2; + uint32 device_id = 3; } message SwitchCommandRequest { option (id) = 33; @@ -669,6 +675,7 @@ message TextSensorStateResponse { // If the text sensor does not have a valid state yet. // Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller bool missing_state = 3; + uint32 device_id = 4; } // ==================== SUBSCRIBE LOGS ==================== @@ -829,7 +836,7 @@ message ListEntitiesCameraResponse { option (id) = 43; option (base_class) = "InfoResponseProtoMessage"; option (source) = SOURCE_SERVER; - option (ifdef) = "USE_ESP32_CAMERA"; + option (ifdef) = "USE_CAMERA"; string object_id = 1; fixed32 key = 2; @@ -844,7 +851,7 @@ message ListEntitiesCameraResponse { message CameraImageResponse { option (id) = 44; option (source) = SOURCE_SERVER; - option (ifdef) = "USE_ESP32_CAMERA"; + option (ifdef) = "USE_CAMERA"; fixed32 key = 1; bytes data = 2; @@ -853,7 +860,7 @@ message CameraImageResponse { message CameraImageRequest { option (id) = 45; option (source) = SOURCE_CLIENT; - option (ifdef) = "USE_ESP32_CAMERA"; + option (ifdef) = "USE_CAMERA"; option (no_delay) = true; bool single = 1; @@ -966,6 +973,7 @@ message ClimateStateResponse { string custom_preset = 13; float current_humidity = 14; float target_humidity = 15; + uint32 device_id = 16; } message ClimateCommandRequest { option (id) = 48; @@ -1039,6 +1047,7 @@ message NumberStateResponse { // If the number does not have a valid state yet. // Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller bool missing_state = 3; + uint32 device_id = 4; } message NumberCommandRequest { option (id) = 51; @@ -1080,6 +1089,7 @@ message SelectStateResponse { // If the select does not have a valid state yet. // Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller bool missing_state = 3; + uint32 device_id = 4; } message SelectCommandRequest { option (id) = 54; @@ -1120,6 +1130,7 @@ message SirenStateResponse { fixed32 key = 1; bool state = 2; + uint32 device_id = 3; } message SirenCommandRequest { option (id) = 57; @@ -1183,6 +1194,7 @@ message LockStateResponse { option (no_delay) = true; fixed32 key = 1; LockState state = 2; + uint32 device_id = 3; } message LockCommandRequest { option (id) = 60; @@ -1282,6 +1294,7 @@ message MediaPlayerStateResponse { MediaPlayerState state = 2; float volume = 3; bool muted = 4; + uint32 device_id = 5; } message MediaPlayerCommandRequest { option (id) = 65; @@ -1822,6 +1835,7 @@ message AlarmControlPanelStateResponse { option (no_delay) = true; fixed32 key = 1; AlarmControlPanelState state = 2; + uint32 device_id = 3; } message AlarmControlPanelCommandRequest { @@ -1871,6 +1885,7 @@ message TextStateResponse { // If the Text does not have a valid state yet. // Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller bool missing_state = 3; + uint32 device_id = 4; } message TextCommandRequest { option (id) = 99; @@ -1914,6 +1929,7 @@ message DateStateResponse { uint32 year = 3; uint32 month = 4; uint32 day = 5; + uint32 device_id = 6; } message DateCommandRequest { option (id) = 102; @@ -1958,6 +1974,7 @@ message TimeStateResponse { uint32 hour = 3; uint32 minute = 4; uint32 second = 5; + uint32 device_id = 6; } message TimeCommandRequest { option (id) = 105; @@ -1999,6 +2016,7 @@ message EventResponse { fixed32 key = 1; string event_type = 2; + uint32 device_id = 3; } // ==================== VALVE ==================== @@ -2039,6 +2057,7 @@ message ValveStateResponse { fixed32 key = 1; float position = 2; ValveOperation current_operation = 3; + uint32 device_id = 4; } message ValveCommandRequest { @@ -2082,6 +2101,7 @@ message DateTimeStateResponse { // Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller bool missing_state = 2; fixed32 epoch_seconds = 3; + uint32 device_id = 4; } message DateTimeCommandRequest { option (id) = 114; @@ -2128,6 +2148,7 @@ message UpdateStateResponse { string title = 8; string release_summary = 9; string release_url = 10; + uint32 device_id = 11; } enum UpdateCommand { UPDATE_COMMAND_NONE = 0; diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index e83d508c50..779784e787 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -38,10 +38,23 @@ static constexpr uint16_t PING_RETRY_INTERVAL = 1000; static constexpr uint32_t KEEPALIVE_DISCONNECT_TIMEOUT = (KEEPALIVE_TIMEOUT_MS * 5) / 2; static const char *const TAG = "api.connection"; -#ifdef USE_ESP32_CAMERA -static const int ESP32_CAMERA_STOP_STREAM = 5000; +#ifdef USE_CAMERA +static const int CAMERA_STOP_STREAM = 5000; #endif +// Helper macro for entity command handlers - gets entity by key, returns if not found, and creates call object +#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \ + entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \ + if ((entity_var) == nullptr) \ + return; \ + auto call = (entity_var)->make_call(); + +// Helper macro for entity command handlers that don't use make_call() - gets entity by key and returns if not found +#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \ + entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \ + if ((entity_var) == nullptr) \ + return; + APIConnection::APIConnection(std::unique_ptr sock, APIServer *parent) : parent_(parent), initial_state_iterator_(this), list_entities_iterator_(this) { #if defined(USE_API_PLAINTEXT) && defined(USE_API_NOISE) @@ -58,6 +71,11 @@ APIConnection::APIConnection(std::unique_ptr sock, APIServer *pa #else #error "No frame helper defined" #endif +#ifdef USE_CAMERA + if (camera::Camera::instance() != nullptr) { + this->image_reader_ = std::unique_ptr{camera::Camera::instance()->create_image_reader()}; + } +#endif } uint32_t APIConnection::get_batch_delay_ms_() const { return this->parent_->get_batch_delay(); } @@ -90,19 +108,6 @@ APIConnection::~APIConnection() { #endif } -#ifdef HAS_PROTO_MESSAGE_DUMP -void APIConnection::log_batch_item_(const DeferredBatch::BatchItem &item) { - // Set log-only mode - this->flags_.log_only_mode = true; - - // Call the creator - it will create the message and log it via encode_message_to_buffer - item.creator(item.entity, this, std::numeric_limits::max(), true, item.message_type); - - // Clear log-only mode - this->flags_.log_only_mode = false; -} -#endif - void APIConnection::loop() { if (this->flags_.next_close) { // requested a disconnect @@ -154,15 +159,25 @@ void APIConnection::loop() { } } - // Process deferred batch if scheduled + // Process deferred batch if scheduled and timer has expired if (this->flags_.batch_scheduled && now - this->deferred_batch_.batch_start_time >= this->get_batch_delay_ms_()) { this->process_batch_(); } if (!this->list_entities_iterator_.completed()) { - this->list_entities_iterator_.advance(); + this->process_iterator_batch_(this->list_entities_iterator_); } else if (!this->initial_state_iterator_.completed()) { - this->initial_state_iterator_.advance(); + this->process_iterator_batch_(this->initial_state_iterator_); + + // If we've completed initial states, process any remaining and clear the flag + if (this->initial_state_iterator_.completed()) { + // Process any remaining batched messages immediately + if (!this->deferred_batch_.empty()) { + this->process_batch_(); + } + // Now that everything is sent, enable immediate sending for future state changes + this->flags_.should_try_send_immediately = true; + } } if (this->flags_.sent_ping) { @@ -183,10 +198,10 @@ void APIConnection::loop() { } } -#ifdef USE_ESP32_CAMERA - if (this->image_reader_.available() && this->helper_->can_write_without_blocking()) { - uint32_t to_send = std::min((size_t) MAX_PACKET_SIZE, this->image_reader_.available()); - bool done = this->image_reader_.available() == to_send; +#ifdef USE_CAMERA + if (this->image_reader_ && this->image_reader_->available() && this->helper_->can_write_without_blocking()) { + uint32_t to_send = std::min((size_t) MAX_PACKET_SIZE, this->image_reader_->available()); + bool done = this->image_reader_->available() == to_send; uint32_t msg_size = 0; ProtoSize::add_fixed_field<4>(msg_size, 1, true); // partial message size calculated manually since its a special case @@ -196,18 +211,18 @@ void APIConnection::loop() { auto buffer = this->create_buffer(msg_size); // fixed32 key = 1; - buffer.encode_fixed32(1, esp32_camera::global_esp32_camera->get_object_id_hash()); + buffer.encode_fixed32(1, camera::Camera::instance()->get_object_id_hash()); // bytes data = 2; - buffer.encode_bytes(2, this->image_reader_.peek_data_buffer(), to_send); + buffer.encode_bytes(2, this->image_reader_->peek_data_buffer(), to_send); // bool done = 3; buffer.encode_bool(3, done); bool success = this->send_buffer(buffer, CameraImageResponse::MESSAGE_TYPE); if (success) { - this->image_reader_.consume_data(to_send); + this->image_reader_->consume_data(to_send); if (done) { - this->image_reader_.return_image(); + this->image_reader_->return_image(); } } } @@ -300,8 +315,8 @@ uint16_t APIConnection::encode_message_to_buffer(ProtoMessage &msg, uint16_t mes #ifdef USE_BINARY_SENSOR bool APIConnection::send_binary_sensor_state(binary_sensor::BinarySensor *binary_sensor) { - return this->schedule_message_(binary_sensor, &APIConnection::try_send_binary_sensor_state, - BinarySensorStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(binary_sensor, &APIConnection::try_send_binary_sensor_state, + BinarySensorStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_binary_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, @@ -328,7 +343,7 @@ uint16_t APIConnection::try_send_binary_sensor_info(EntityBase *entity, APIConne #ifdef USE_COVER bool APIConnection::send_cover_state(cover::Cover *cover) { - return this->schedule_message_(cover, &APIConnection::try_send_cover_state, CoverStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(cover, &APIConnection::try_send_cover_state, CoverStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_cover_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -359,11 +374,7 @@ uint16_t APIConnection::try_send_cover_info(EntityBase *entity, APIConnection *c return encode_message_to_buffer(msg, ListEntitiesCoverResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::cover_command(const CoverCommandRequest &msg) { - cover::Cover *cover = App.get_cover_by_key(msg.key); - if (cover == nullptr) - return; - - auto call = cover->make_call(); + ENTITY_COMMAND_MAKE_CALL(cover::Cover, cover, cover) if (msg.has_legacy_command) { switch (msg.legacy_command) { case enums::LEGACY_COVER_COMMAND_OPEN: @@ -389,7 +400,7 @@ void APIConnection::cover_command(const CoverCommandRequest &msg) { #ifdef USE_FAN bool APIConnection::send_fan_state(fan::Fan *fan) { - return this->schedule_message_(fan, &APIConnection::try_send_fan_state, FanStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(fan, &APIConnection::try_send_fan_state, FanStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_fan_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -425,11 +436,7 @@ uint16_t APIConnection::try_send_fan_info(EntityBase *entity, APIConnection *con return encode_message_to_buffer(msg, ListEntitiesFanResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::fan_command(const FanCommandRequest &msg) { - fan::Fan *fan = App.get_fan_by_key(msg.key); - if (fan == nullptr) - return; - - auto call = fan->make_call(); + ENTITY_COMMAND_MAKE_CALL(fan::Fan, fan, fan) if (msg.has_state) call.set_state(msg.state); if (msg.has_oscillating) @@ -448,7 +455,7 @@ void APIConnection::fan_command(const FanCommandRequest &msg) { #ifdef USE_LIGHT bool APIConnection::send_light_state(light::LightState *light) { - return this->schedule_message_(light, &APIConnection::try_send_light_state, LightStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(light, &APIConnection::try_send_light_state, LightStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_light_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -502,11 +509,7 @@ uint16_t APIConnection::try_send_light_info(EntityBase *entity, APIConnection *c return encode_message_to_buffer(msg, ListEntitiesLightResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::light_command(const LightCommandRequest &msg) { - light::LightState *light = App.get_light_by_key(msg.key); - if (light == nullptr) - return; - - auto call = light->make_call(); + ENTITY_COMMAND_MAKE_CALL(light::LightState, light, light) if (msg.has_state) call.set_state(msg.state); if (msg.has_brightness) @@ -540,7 +543,7 @@ void APIConnection::light_command(const LightCommandRequest &msg) { #ifdef USE_SENSOR bool APIConnection::send_sensor_state(sensor::Sensor *sensor) { - return this->schedule_message_(sensor, &APIConnection::try_send_sensor_state, SensorStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(sensor, &APIConnection::try_send_sensor_state, SensorStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, @@ -572,7 +575,7 @@ uint16_t APIConnection::try_send_sensor_info(EntityBase *entity, APIConnection * #ifdef USE_SWITCH bool APIConnection::send_switch_state(switch_::Switch *a_switch) { - return this->schedule_message_(a_switch, &APIConnection::try_send_switch_state, SwitchStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(a_switch, &APIConnection::try_send_switch_state, SwitchStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_switch_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, @@ -595,9 +598,7 @@ uint16_t APIConnection::try_send_switch_info(EntityBase *entity, APIConnection * return encode_message_to_buffer(msg, ListEntitiesSwitchResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::switch_command(const SwitchCommandRequest &msg) { - switch_::Switch *a_switch = App.get_switch_by_key(msg.key); - if (a_switch == nullptr) - return; + ENTITY_COMMAND_GET(switch_::Switch, a_switch, switch) if (msg.state) { a_switch->turn_on(); @@ -609,8 +610,8 @@ void APIConnection::switch_command(const SwitchCommandRequest &msg) { #ifdef USE_TEXT_SENSOR bool APIConnection::send_text_sensor_state(text_sensor::TextSensor *text_sensor) { - return this->schedule_message_(text_sensor, &APIConnection::try_send_text_sensor_state, - TextSensorStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(text_sensor, &APIConnection::try_send_text_sensor_state, + TextSensorStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_text_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, @@ -637,7 +638,7 @@ uint16_t APIConnection::try_send_text_sensor_info(EntityBase *entity, APIConnect #ifdef USE_CLIMATE bool APIConnection::send_climate_state(climate::Climate *climate) { - return this->schedule_message_(climate, &APIConnection::try_send_climate_state, ClimateStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(climate, &APIConnection::try_send_climate_state, ClimateStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_climate_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -706,11 +707,7 @@ uint16_t APIConnection::try_send_climate_info(EntityBase *entity, APIConnection return encode_message_to_buffer(msg, ListEntitiesClimateResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::climate_command(const ClimateCommandRequest &msg) { - climate::Climate *climate = App.get_climate_by_key(msg.key); - if (climate == nullptr) - return; - - auto call = climate->make_call(); + ENTITY_COMMAND_MAKE_CALL(climate::Climate, climate, climate) if (msg.has_mode) call.set_mode(static_cast(msg.mode)); if (msg.has_target_temperature) @@ -737,7 +734,7 @@ void APIConnection::climate_command(const ClimateCommandRequest &msg) { #ifdef USE_NUMBER bool APIConnection::send_number_state(number::Number *number) { - return this->schedule_message_(number, &APIConnection::try_send_number_state, NumberStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(number, &APIConnection::try_send_number_state, NumberStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_number_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, @@ -765,11 +762,7 @@ uint16_t APIConnection::try_send_number_info(EntityBase *entity, APIConnection * return encode_message_to_buffer(msg, ListEntitiesNumberResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::number_command(const NumberCommandRequest &msg) { - number::Number *number = App.get_number_by_key(msg.key); - if (number == nullptr) - return; - - auto call = number->make_call(); + ENTITY_COMMAND_MAKE_CALL(number::Number, number, number) call.set_value(msg.state); call.perform(); } @@ -777,7 +770,7 @@ void APIConnection::number_command(const NumberCommandRequest &msg) { #ifdef USE_DATETIME_DATE bool APIConnection::send_date_state(datetime::DateEntity *date) { - return this->schedule_message_(date, &APIConnection::try_send_date_state, DateStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(date, &APIConnection::try_send_date_state, DateStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_date_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -799,11 +792,7 @@ uint16_t APIConnection::try_send_date_info(EntityBase *entity, APIConnection *co return encode_message_to_buffer(msg, ListEntitiesDateResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::date_command(const DateCommandRequest &msg) { - datetime::DateEntity *date = App.get_date_by_key(msg.key); - if (date == nullptr) - return; - - auto call = date->make_call(); + ENTITY_COMMAND_MAKE_CALL(datetime::DateEntity, date, date) call.set_date(msg.year, msg.month, msg.day); call.perform(); } @@ -811,7 +800,7 @@ void APIConnection::date_command(const DateCommandRequest &msg) { #ifdef USE_DATETIME_TIME bool APIConnection::send_time_state(datetime::TimeEntity *time) { - return this->schedule_message_(time, &APIConnection::try_send_time_state, TimeStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(time, &APIConnection::try_send_time_state, TimeStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_time_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -833,11 +822,7 @@ uint16_t APIConnection::try_send_time_info(EntityBase *entity, APIConnection *co return encode_message_to_buffer(msg, ListEntitiesTimeResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::time_command(const TimeCommandRequest &msg) { - datetime::TimeEntity *time = App.get_time_by_key(msg.key); - if (time == nullptr) - return; - - auto call = time->make_call(); + ENTITY_COMMAND_MAKE_CALL(datetime::TimeEntity, time, time) call.set_time(msg.hour, msg.minute, msg.second); call.perform(); } @@ -845,8 +830,8 @@ void APIConnection::time_command(const TimeCommandRequest &msg) { #ifdef USE_DATETIME_DATETIME bool APIConnection::send_datetime_state(datetime::DateTimeEntity *datetime) { - return this->schedule_message_(datetime, &APIConnection::try_send_datetime_state, - DateTimeStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(datetime, &APIConnection::try_send_datetime_state, + DateTimeStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_datetime_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -869,11 +854,7 @@ uint16_t APIConnection::try_send_datetime_info(EntityBase *entity, APIConnection return encode_message_to_buffer(msg, ListEntitiesDateTimeResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::datetime_command(const DateTimeCommandRequest &msg) { - datetime::DateTimeEntity *datetime = App.get_datetime_by_key(msg.key); - if (datetime == nullptr) - return; - - auto call = datetime->make_call(); + ENTITY_COMMAND_MAKE_CALL(datetime::DateTimeEntity, datetime, datetime) call.set_datetime(msg.epoch_seconds); call.perform(); } @@ -881,7 +862,7 @@ void APIConnection::datetime_command(const DateTimeCommandRequest &msg) { #ifdef USE_TEXT bool APIConnection::send_text_state(text::Text *text) { - return this->schedule_message_(text, &APIConnection::try_send_text_state, TextStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(text, &APIConnection::try_send_text_state, TextStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_text_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, @@ -907,11 +888,7 @@ uint16_t APIConnection::try_send_text_info(EntityBase *entity, APIConnection *co return encode_message_to_buffer(msg, ListEntitiesTextResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::text_command(const TextCommandRequest &msg) { - text::Text *text = App.get_text_by_key(msg.key); - if (text == nullptr) - return; - - auto call = text->make_call(); + ENTITY_COMMAND_MAKE_CALL(text::Text, text, text) call.set_value(msg.state); call.perform(); } @@ -919,7 +896,7 @@ void APIConnection::text_command(const TextCommandRequest &msg) { #ifdef USE_SELECT bool APIConnection::send_select_state(select::Select *select) { - return this->schedule_message_(select, &APIConnection::try_send_select_state, SelectStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(select, &APIConnection::try_send_select_state, SelectStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_select_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, @@ -943,11 +920,7 @@ uint16_t APIConnection::try_send_select_info(EntityBase *entity, APIConnection * return encode_message_to_buffer(msg, ListEntitiesSelectResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::select_command(const SelectCommandRequest &msg) { - select::Select *select = App.get_select_by_key(msg.key); - if (select == nullptr) - return; - - auto call = select->make_call(); + ENTITY_COMMAND_MAKE_CALL(select::Select, select, select) call.set_option(msg.state); call.perform(); } @@ -964,17 +937,14 @@ uint16_t APIConnection::try_send_button_info(EntityBase *entity, APIConnection * return encode_message_to_buffer(msg, ListEntitiesButtonResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void esphome::api::APIConnection::button_command(const ButtonCommandRequest &msg) { - button::Button *button = App.get_button_by_key(msg.key); - if (button == nullptr) - return; - + ENTITY_COMMAND_GET(button::Button, button, button) button->press(); } #endif #ifdef USE_LOCK bool APIConnection::send_lock_state(lock::Lock *a_lock) { - return this->schedule_message_(a_lock, &APIConnection::try_send_lock_state, LockStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(a_lock, &APIConnection::try_send_lock_state, LockStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_lock_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, @@ -998,9 +968,7 @@ uint16_t APIConnection::try_send_lock_info(EntityBase *entity, APIConnection *co return encode_message_to_buffer(msg, ListEntitiesLockResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::lock_command(const LockCommandRequest &msg) { - lock::Lock *a_lock = App.get_lock_by_key(msg.key); - if (a_lock == nullptr) - return; + ENTITY_COMMAND_GET(lock::Lock, a_lock, lock) switch (msg.command) { case enums::LOCK_UNLOCK: @@ -1018,7 +986,7 @@ void APIConnection::lock_command(const LockCommandRequest &msg) { #ifdef USE_VALVE bool APIConnection::send_valve_state(valve::Valve *valve) { - return this->schedule_message_(valve, &APIConnection::try_send_valve_state, ValveStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(valve, &APIConnection::try_send_valve_state, ValveStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_valve_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -1043,11 +1011,7 @@ uint16_t APIConnection::try_send_valve_info(EntityBase *entity, APIConnection *c return encode_message_to_buffer(msg, ListEntitiesValveResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::valve_command(const ValveCommandRequest &msg) { - valve::Valve *valve = App.get_valve_by_key(msg.key); - if (valve == nullptr) - return; - - auto call = valve->make_call(); + ENTITY_COMMAND_MAKE_CALL(valve::Valve, valve, valve) if (msg.has_position) call.set_position(msg.position); if (msg.stop) @@ -1058,8 +1022,8 @@ void APIConnection::valve_command(const ValveCommandRequest &msg) { #ifdef USE_MEDIA_PLAYER bool APIConnection::send_media_player_state(media_player::MediaPlayer *media_player) { - return this->schedule_message_(media_player, &APIConnection::try_send_media_player_state, - MediaPlayerStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(media_player, &APIConnection::try_send_media_player_state, + MediaPlayerStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_media_player_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -1094,11 +1058,7 @@ uint16_t APIConnection::try_send_media_player_info(EntityBase *entity, APIConnec return encode_message_to_buffer(msg, ListEntitiesMediaPlayerResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::media_player_command(const MediaPlayerCommandRequest &msg) { - media_player::MediaPlayer *media_player = App.get_media_player_by_key(msg.key); - if (media_player == nullptr) - return; - - auto call = media_player->make_call(); + ENTITY_COMMAND_MAKE_CALL(media_player::MediaPlayer, media_player, media_player) if (msg.has_command) { call.set_command(static_cast(msg.command)); } @@ -1115,36 +1075,36 @@ void APIConnection::media_player_command(const MediaPlayerCommandRequest &msg) { } #endif -#ifdef USE_ESP32_CAMERA -void APIConnection::set_camera_state(std::shared_ptr image) { +#ifdef USE_CAMERA +void APIConnection::set_camera_state(std::shared_ptr image) { if (!this->flags_.state_subscription) return; - if (this->image_reader_.available()) + if (!this->image_reader_) return; - if (image->was_requested_by(esphome::esp32_camera::API_REQUESTER) || - image->was_requested_by(esphome::esp32_camera::IDLE)) - this->image_reader_.set_image(std::move(image)); + if (this->image_reader_->available()) + return; + if (image->was_requested_by(esphome::camera::API_REQUESTER) || image->was_requested_by(esphome::camera::IDLE)) + this->image_reader_->set_image(std::move(image)); } uint16_t APIConnection::try_send_camera_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { - auto *camera = static_cast(entity); + auto *camera = static_cast(entity); ListEntitiesCameraResponse msg; msg.unique_id = get_default_unique_id("camera", camera); fill_entity_info_base(camera, msg); return encode_message_to_buffer(msg, ListEntitiesCameraResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::camera_image(const CameraImageRequest &msg) { - if (esp32_camera::global_esp32_camera == nullptr) + if (camera::Camera::instance() == nullptr) return; if (msg.single) - esp32_camera::global_esp32_camera->request_image(esphome::esp32_camera::API_REQUESTER); + camera::Camera::instance()->request_image(esphome::camera::API_REQUESTER); if (msg.stream) { - esp32_camera::global_esp32_camera->start_stream(esphome::esp32_camera::API_REQUESTER); + camera::Camera::instance()->start_stream(esphome::camera::API_REQUESTER); - App.scheduler.set_timeout(this->parent_, "api_esp32_camera_stop_stream", ESP32_CAMERA_STOP_STREAM, []() { - esp32_camera::global_esp32_camera->stop_stream(esphome::esp32_camera::API_REQUESTER); - }); + App.scheduler.set_timeout(this->parent_, "api_camera_stop_stream", CAMERA_STOP_STREAM, + []() { camera::Camera::instance()->stop_stream(esphome::camera::API_REQUESTER); }); } } #endif @@ -1216,66 +1176,53 @@ void APIConnection::bluetooth_scanner_set_mode(const BluetoothScannerSetModeRequ #endif #ifdef USE_VOICE_ASSISTANT +bool APIConnection::check_voice_assistant_api_connection_() const { + return voice_assistant::global_voice_assistant != nullptr && + voice_assistant::global_voice_assistant->get_api_connection() == this; +} + void APIConnection::subscribe_voice_assistant(const SubscribeVoiceAssistantRequest &msg) { if (voice_assistant::global_voice_assistant != nullptr) { voice_assistant::global_voice_assistant->client_subscription(this, msg.subscribe); } } void APIConnection::on_voice_assistant_response(const VoiceAssistantResponse &msg) { - if (voice_assistant::global_voice_assistant != nullptr) { - if (voice_assistant::global_voice_assistant->get_api_connection() != this) { - return; - } + if (!this->check_voice_assistant_api_connection_()) { + return; + } - if (msg.error) { - voice_assistant::global_voice_assistant->failed_to_start(); - return; - } - if (msg.port == 0) { - // Use API Audio - voice_assistant::global_voice_assistant->start_streaming(); - } else { - struct sockaddr_storage storage; - socklen_t len = sizeof(storage); - this->helper_->getpeername((struct sockaddr *) &storage, &len); - voice_assistant::global_voice_assistant->start_streaming(&storage, msg.port); - } + if (msg.error) { + voice_assistant::global_voice_assistant->failed_to_start(); + return; + } + if (msg.port == 0) { + // Use API Audio + voice_assistant::global_voice_assistant->start_streaming(); + } else { + struct sockaddr_storage storage; + socklen_t len = sizeof(storage); + this->helper_->getpeername((struct sockaddr *) &storage, &len); + voice_assistant::global_voice_assistant->start_streaming(&storage, msg.port); } }; void APIConnection::on_voice_assistant_event_response(const VoiceAssistantEventResponse &msg) { - if (voice_assistant::global_voice_assistant != nullptr) { - if (voice_assistant::global_voice_assistant->get_api_connection() != this) { - return; - } - + if (this->check_voice_assistant_api_connection_()) { voice_assistant::global_voice_assistant->on_event(msg); } } void APIConnection::on_voice_assistant_audio(const VoiceAssistantAudio &msg) { - if (voice_assistant::global_voice_assistant != nullptr) { - if (voice_assistant::global_voice_assistant->get_api_connection() != this) { - return; - } - + if (this->check_voice_assistant_api_connection_()) { voice_assistant::global_voice_assistant->on_audio(msg); } }; void APIConnection::on_voice_assistant_timer_event_response(const VoiceAssistantTimerEventResponse &msg) { - if (voice_assistant::global_voice_assistant != nullptr) { - if (voice_assistant::global_voice_assistant->get_api_connection() != this) { - return; - } - + if (this->check_voice_assistant_api_connection_()) { voice_assistant::global_voice_assistant->on_timer_event(msg); } }; void APIConnection::on_voice_assistant_announce_request(const VoiceAssistantAnnounceRequest &msg) { - if (voice_assistant::global_voice_assistant != nullptr) { - if (voice_assistant::global_voice_assistant->get_api_connection() != this) { - return; - } - + if (this->check_voice_assistant_api_connection_()) { voice_assistant::global_voice_assistant->on_announce(msg); } } @@ -1283,35 +1230,29 @@ void APIConnection::on_voice_assistant_announce_request(const VoiceAssistantAnno VoiceAssistantConfigurationResponse APIConnection::voice_assistant_get_configuration( const VoiceAssistantConfigurationRequest &msg) { VoiceAssistantConfigurationResponse resp; - if (voice_assistant::global_voice_assistant != nullptr) { - if (voice_assistant::global_voice_assistant->get_api_connection() != this) { - return resp; - } - - auto &config = voice_assistant::global_voice_assistant->get_configuration(); - for (auto &wake_word : config.available_wake_words) { - VoiceAssistantWakeWord resp_wake_word; - resp_wake_word.id = wake_word.id; - resp_wake_word.wake_word = wake_word.wake_word; - for (const auto &lang : wake_word.trained_languages) { - resp_wake_word.trained_languages.push_back(lang); - } - resp.available_wake_words.push_back(std::move(resp_wake_word)); - } - for (auto &wake_word_id : config.active_wake_words) { - resp.active_wake_words.push_back(wake_word_id); - } - resp.max_active_wake_words = config.max_active_wake_words; + if (!this->check_voice_assistant_api_connection_()) { + return resp; } + + auto &config = voice_assistant::global_voice_assistant->get_configuration(); + for (auto &wake_word : config.available_wake_words) { + VoiceAssistantWakeWord resp_wake_word; + resp_wake_word.id = wake_word.id; + resp_wake_word.wake_word = wake_word.wake_word; + for (const auto &lang : wake_word.trained_languages) { + resp_wake_word.trained_languages.push_back(lang); + } + resp.available_wake_words.push_back(std::move(resp_wake_word)); + } + for (auto &wake_word_id : config.active_wake_words) { + resp.active_wake_words.push_back(wake_word_id); + } + resp.max_active_wake_words = config.max_active_wake_words; return resp; } void APIConnection::voice_assistant_set_configuration(const VoiceAssistantSetConfiguration &msg) { - if (voice_assistant::global_voice_assistant != nullptr) { - if (voice_assistant::global_voice_assistant->get_api_connection() != this) { - return; - } - + if (this->check_voice_assistant_api_connection_()) { voice_assistant::global_voice_assistant->on_set_configuration(msg.active_wake_words); } } @@ -1320,8 +1261,8 @@ void APIConnection::voice_assistant_set_configuration(const VoiceAssistantSetCon #ifdef USE_ALARM_CONTROL_PANEL bool APIConnection::send_alarm_control_panel_state(alarm_control_panel::AlarmControlPanel *a_alarm_control_panel) { - return this->schedule_message_(a_alarm_control_panel, &APIConnection::try_send_alarm_control_panel_state, - AlarmControlPanelStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(a_alarm_control_panel, &APIConnection::try_send_alarm_control_panel_state, + AlarmControlPanelStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_alarm_control_panel_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -1344,11 +1285,7 @@ uint16_t APIConnection::try_send_alarm_control_panel_info(EntityBase *entity, AP is_single); } void APIConnection::alarm_control_panel_command(const AlarmControlPanelCommandRequest &msg) { - alarm_control_panel::AlarmControlPanel *a_alarm_control_panel = App.get_alarm_control_panel_by_key(msg.key); - if (a_alarm_control_panel == nullptr) - return; - - auto call = a_alarm_control_panel->make_call(); + ENTITY_COMMAND_MAKE_CALL(alarm_control_panel::AlarmControlPanel, a_alarm_control_panel, alarm_control_panel) switch (msg.command) { case enums::ALARM_CONTROL_PANEL_DISARM: call.disarm(); @@ -1404,7 +1341,7 @@ uint16_t APIConnection::try_send_event_info(EntityBase *entity, APIConnection *c #ifdef USE_UPDATE bool APIConnection::send_update_state(update::UpdateEntity *update) { - return this->schedule_message_(update, &APIConnection::try_send_update_state, UpdateStateResponse::MESSAGE_TYPE); + return this->send_message_smart_(update, &APIConnection::try_send_update_state, UpdateStateResponse::MESSAGE_TYPE); } uint16_t APIConnection::try_send_update_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single) { @@ -1436,9 +1373,7 @@ uint16_t APIConnection::try_send_update_info(EntityBase *entity, APIConnection * return encode_message_to_buffer(msg, ListEntitiesUpdateResponse::MESSAGE_TYPE, conn, remaining_size, is_single); } void APIConnection::update_command(const UpdateCommandRequest &msg) { - update::UpdateEntity *update = App.get_update_by_key(msg.key); - if (update == nullptr) - return; + ENTITY_COMMAND_GET(update::UpdateEntity, update, update) switch (msg.command) { case enums::UPDATE_COMMAND_UPDATE: @@ -1457,12 +1392,11 @@ void APIConnection::update_command(const UpdateCommandRequest &msg) { } #endif -bool APIConnection::try_send_log_message(int level, const char *tag, const char *line) { +bool APIConnection::try_send_log_message(int level, const char *tag, const char *line, size_t message_len) { if (this->flags_.log_subscription < level) return false; // Pre-calculate message size to avoid reallocations - const size_t line_length = strlen(line); uint32_t msg_size = 0; // Add size for level field (field ID 1, varint type) @@ -1471,14 +1405,14 @@ bool APIConnection::try_send_log_message(int level, const char *tag, const char // Add size for string field (field ID 3, string type) // 1 byte for field tag + size of length varint + string length - msg_size += 1 + api::ProtoSize::varint(static_cast(line_length)) + line_length; + msg_size += 1 + api::ProtoSize::varint(static_cast(message_len)) + message_len; // Create a pre-sized buffer auto buffer = this->create_buffer(msg_size); // Encode the message (SubscribeLogsResponse) buffer.encode_uint32(1, static_cast(level)); // LogLevel level = 1 - buffer.encode_string(3, line, line_length); // string message = 3 + buffer.encode_string(3, line, message_len); // string message = 3 // SubscribeLogsResponse - 29 return this->send_buffer(buffer, SubscribeLogsResponse::MESSAGE_TYPE); @@ -1503,7 +1437,10 @@ HelloResponse APIConnection::hello(const HelloRequest &msg) { return resp; } ConnectResponse APIConnection::connect(const ConnectRequest &msg) { - bool correct = this->parent_->check_password(msg.password); + bool correct = true; +#ifdef USE_API_PASSWORD + correct = this->parent_->check_password(msg.password); +#endif ConnectResponse resp; // bool invalid_password = 1; @@ -1524,7 +1461,11 @@ ConnectResponse APIConnection::connect(const ConnectRequest &msg) { } DeviceInfoResponse APIConnection::device_info(const DeviceInfoRequest &msg) { DeviceInfoResponse resp{}; +#ifdef USE_API_PASSWORD resp.uses_password = this->parent_->uses_password(); +#else + resp.uses_password = false; +#endif resp.name = App.get_name(); resp.friendly_name = App.get_friendly_name(); resp.suggested_area = App.get_area(); @@ -1744,11 +1685,16 @@ void APIConnection::process_batch_() { if (payload_size > 0 && this->send_buffer(ProtoWriteBuffer{&this->parent_->get_shared_buffer_ref()}, item.message_type)) { - this->deferred_batch_.clear(); +#ifdef HAS_PROTO_MESSAGE_DUMP + // Log messages after send attempt for VV debugging + // It's safe to use the buffer for logging at this point regardless of send result + this->log_batch_item_(item); +#endif + this->clear_batch_(); } else if (payload_size == 0) { // Message too large ESP_LOGW(TAG, "Message too large to send: type=%u", item.message_type); - this->deferred_batch_.clear(); + this->clear_batch_(); } return; } @@ -1857,7 +1803,7 @@ void APIConnection::process_batch_() { this->schedule_batch_(); } else { // All items processed - this->deferred_batch_.clear(); + this->clear_batch_(); } } diff --git a/esphome/components/api/api_connection.h b/esphome/components/api/api_connection.h index 151369aa70..b70b037999 100644 --- a/esphome/components/api/api_connection.h +++ b/esphome/components/api/api_connection.h @@ -18,6 +18,8 @@ namespace api { // Keepalive timeout in milliseconds static constexpr uint32_t KEEPALIVE_TIMEOUT_MS = 60000; +// Maximum number of entities to process in a single batch during initial state/info sending +static constexpr size_t MAX_INITIAL_PER_BATCH = 20; class APIConnection : public APIServerConnection { public: @@ -58,8 +60,8 @@ class APIConnection : public APIServerConnection { #ifdef USE_TEXT_SENSOR bool send_text_sensor_state(text_sensor::TextSensor *text_sensor); #endif -#ifdef USE_ESP32_CAMERA - void set_camera_state(std::shared_ptr image); +#ifdef USE_CAMERA + void set_camera_state(std::shared_ptr image); void camera_image(const CameraImageRequest &msg) override; #endif #ifdef USE_CLIMATE @@ -105,7 +107,7 @@ class APIConnection : public APIServerConnection { bool send_media_player_state(media_player::MediaPlayer *media_player); void media_player_command(const MediaPlayerCommandRequest &msg) override; #endif - bool try_send_log_message(int level, const char *tag, const char *line); + bool try_send_log_message(int level, const char *tag, const char *line, size_t message_len); void send_homeassistant_service_call(const HomeassistantServiceResponse &call) { if (!this->flags_.service_call_subscription) return; @@ -290,12 +292,34 @@ class APIConnection : public APIServerConnection { // Helper function to fill common entity state fields static void fill_entity_state_base(esphome::EntityBase *entity, StateResponseProtoMessage &response) { response.key = entity->get_object_id_hash(); +#ifdef USE_DEVICES + response.device_id = entity->get_device_id(); +#endif } // Non-template helper to encode any ProtoMessage static uint16_t encode_message_to_buffer(ProtoMessage &msg, uint16_t message_type, APIConnection *conn, uint32_t remaining_size, bool is_single); +#ifdef USE_VOICE_ASSISTANT + // Helper to check voice assistant validity and connection ownership + inline bool check_voice_assistant_api_connection_() const; +#endif + + // Helper method to process multiple entities from an iterator in a batch + template void process_iterator_batch_(Iterator &iterator) { + size_t initial_size = this->deferred_batch_.size(); + while (!iterator.completed() && (this->deferred_batch_.size() - initial_size) < MAX_INITIAL_PER_BATCH) { + iterator.advance(); + } + + // If the batch is full, process it immediately + // Note: iterator.advance() already calls schedule_batch_() via schedule_message_() + if (this->deferred_batch_.size() >= MAX_INITIAL_PER_BATCH) { + this->process_batch_(); + } + } + #ifdef USE_BINARY_SENSOR static uint16_t try_send_binary_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single); @@ -406,7 +430,7 @@ class APIConnection : public APIServerConnection { static uint16_t try_send_update_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single); #endif -#ifdef USE_ESP32_CAMERA +#ifdef USE_CAMERA static uint16_t try_send_camera_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single); #endif @@ -436,8 +460,8 @@ class APIConnection : public APIServerConnection { // These contain vectors/pointers internally, so putting them early ensures good alignment InitialStateIterator initial_state_iterator_; ListEntitiesIterator list_entities_iterator_; -#ifdef USE_ESP32_CAMERA - esp32_camera::CameraImageReader image_reader_; +#ifdef USE_CAMERA + std::unique_ptr image_reader_; #endif // Group 3: Strings (12 bytes each on 32-bit, 4-byte aligned) @@ -582,7 +606,8 @@ class APIConnection : public APIServerConnection { uint8_t service_call_subscription : 1; uint8_t next_close : 1; uint8_t batch_scheduled : 1; - uint8_t batch_first_message : 1; // For batch buffer allocation + uint8_t batch_first_message : 1; // For batch buffer allocation + uint8_t should_try_send_immediately : 1; // True after initial states are sent #ifdef HAS_PROTO_MESSAGE_DUMP uint8_t log_only_mode : 1; #endif @@ -609,11 +634,50 @@ class APIConnection : public APIServerConnection { bool schedule_batch_(); void process_batch_(); + void clear_batch_() { + this->deferred_batch_.clear(); + this->flags_.batch_scheduled = false; + } #ifdef HAS_PROTO_MESSAGE_DUMP - void log_batch_item_(const DeferredBatch::BatchItem &item); + // Helper to log a proto message from a MessageCreator object + void log_proto_message_(EntityBase *entity, const MessageCreator &creator, uint16_t message_type) { + this->flags_.log_only_mode = true; + creator(entity, this, MAX_PACKET_SIZE, true, message_type); + this->flags_.log_only_mode = false; + } + + void log_batch_item_(const DeferredBatch::BatchItem &item) { + // Use the helper to log the message + this->log_proto_message_(item.entity, item.creator, item.message_type); + } #endif + // Helper method to send a message either immediately or via batching + bool send_message_smart_(EntityBase *entity, MessageCreatorPtr creator, uint16_t message_type) { + // Try to send immediately if: + // 1. We should try to send immediately (should_try_send_immediately = true) + // 2. Batch delay is 0 (user has opted in to immediate sending) + // 3. Buffer has space available + if (this->flags_.should_try_send_immediately && this->get_batch_delay_ms_() == 0 && + this->helper_->can_write_without_blocking()) { + // Now actually encode and send + if (creator(entity, this, MAX_PACKET_SIZE, true) && + this->send_buffer(ProtoWriteBuffer{&this->parent_->get_shared_buffer_ref()}, message_type)) { +#ifdef HAS_PROTO_MESSAGE_DUMP + // Log the message in verbose mode + this->log_proto_message_(entity, MessageCreator(creator), message_type); +#endif + return true; + } + + // If immediate send failed, fall through to batching + } + + // Fall back to scheduled batching + return this->schedule_message_(entity, creator, message_type); + } + // Helper function to schedule a deferred message with known message type bool schedule_message_(EntityBase *entity, MessageCreator creator, uint16_t message_type) { this->deferred_batch_.add_item(entity, std::move(creator), message_type); diff --git a/esphome/components/api/api_frame_helper.cpp b/esphome/components/api/api_frame_helper.cpp index af6dd0220d..2f5acc3bfa 100644 --- a/esphome/components/api/api_frame_helper.cpp +++ b/esphome/components/api/api_frame_helper.cpp @@ -225,6 +225,22 @@ APIError APIFrameHelper::init_common_() { } #define HELPER_LOG(msg, ...) ESP_LOGVV(TAG, "%s: " msg, this->info_.c_str(), ##__VA_ARGS__) + +APIError APIFrameHelper::handle_socket_read_result_(ssize_t received) { + if (received == -1) { + if (errno == EWOULDBLOCK || errno == EAGAIN) { + return APIError::WOULD_BLOCK; + } + state_ = State::FAILED; + HELPER_LOG("Socket read failed with errno %d", errno); + return APIError::SOCKET_READ_FAILED; + } else if (received == 0) { + state_ = State::FAILED; + HELPER_LOG("Connection closed"); + return APIError::CONNECTION_CLOSED; + } + return APIError::OK; +} // uncomment to log raw packets //#define HELPER_LOG_PACKETS @@ -327,17 +343,9 @@ APIError APINoiseFrameHelper::try_read_frame_(ParsedFrame *frame) { // no header information yet uint8_t to_read = 3 - rx_header_buf_len_; ssize_t received = this->socket_->read(&rx_header_buf_[rx_header_buf_len_], to_read); - if (received == -1) { - if (errno == EWOULDBLOCK || errno == EAGAIN) { - return APIError::WOULD_BLOCK; - } - state_ = State::FAILED; - HELPER_LOG("Socket read failed with errno %d", errno); - return APIError::SOCKET_READ_FAILED; - } else if (received == 0) { - state_ = State::FAILED; - HELPER_LOG("Connection closed"); - return APIError::CONNECTION_CLOSED; + APIError err = handle_socket_read_result_(received); + if (err != APIError::OK) { + return err; } rx_header_buf_len_ += static_cast(received); if (static_cast(received) != to_read) { @@ -372,17 +380,9 @@ APIError APINoiseFrameHelper::try_read_frame_(ParsedFrame *frame) { // more data to read uint16_t to_read = msg_size - rx_buf_len_; ssize_t received = this->socket_->read(&rx_buf_[rx_buf_len_], to_read); - if (received == -1) { - if (errno == EWOULDBLOCK || errno == EAGAIN) { - return APIError::WOULD_BLOCK; - } - state_ = State::FAILED; - HELPER_LOG("Socket read failed with errno %d", errno); - return APIError::SOCKET_READ_FAILED; - } else if (received == 0) { - state_ = State::FAILED; - HELPER_LOG("Connection closed"); - return APIError::CONNECTION_CLOSED; + APIError err = handle_socket_read_result_(received); + if (err != APIError::OK) { + return err; } rx_buf_len_ += static_cast(received); if (static_cast(received) != to_read) { @@ -614,20 +614,14 @@ APIError APINoiseFrameHelper::read_packet(ReadPacketBuffer *buffer) { return APIError::OK; } APIError APINoiseFrameHelper::write_protobuf_packet(uint16_t type, ProtoWriteBuffer buffer) { - std::vector *raw_buffer = buffer.get_buffer(); - uint16_t payload_len = static_cast(raw_buffer->size() - frame_header_padding_); - // Resize to include MAC space (required for Noise encryption) - raw_buffer->resize(raw_buffer->size() + frame_footer_size_); - - // Use write_protobuf_packets with a single packet - std::vector packets; - packets.emplace_back(type, 0, payload_len); - - return write_protobuf_packets(buffer, packets); + buffer.get_buffer()->resize(buffer.get_buffer()->size() + frame_footer_size_); + PacketInfo packet{type, 0, + static_cast(buffer.get_buffer()->size() - frame_header_padding_ - frame_footer_size_)}; + return write_protobuf_packets(buffer, std::span(&packet, 1)); } -APIError APINoiseFrameHelper::write_protobuf_packets(ProtoWriteBuffer buffer, const std::vector &packets) { +APIError APINoiseFrameHelper::write_protobuf_packets(ProtoWriteBuffer buffer, std::span packets) { APIError aerr = state_action_(); if (aerr != APIError::OK) { return aerr; @@ -642,18 +636,15 @@ APIError APINoiseFrameHelper::write_protobuf_packets(ProtoWriteBuffer buffer, co } std::vector *raw_buffer = buffer.get_buffer(); + uint8_t *buffer_data = raw_buffer->data(); // Cache buffer pointer + this->reusable_iovs_.clear(); this->reusable_iovs_.reserve(packets.size()); // We need to encrypt each packet in place for (const auto &packet : packets) { - uint16_t type = packet.message_type; - uint16_t offset = packet.offset; - uint16_t payload_len = packet.payload_size; - uint16_t msg_len = 4 + payload_len; // type(2) + data_len(2) + payload - // The buffer already has padding at offset - uint8_t *buf_start = raw_buffer->data() + offset; + uint8_t *buf_start = buffer_data + packet.offset; // Write noise header buf_start[0] = 0x01; // indicator @@ -661,10 +652,10 @@ APIError APINoiseFrameHelper::write_protobuf_packets(ProtoWriteBuffer buffer, co // Write message header (to be encrypted) const uint8_t msg_offset = 3; - buf_start[msg_offset + 0] = (uint8_t) (type >> 8); // type high byte - buf_start[msg_offset + 1] = (uint8_t) type; // type low byte - buf_start[msg_offset + 2] = (uint8_t) (payload_len >> 8); // data_len high byte - buf_start[msg_offset + 3] = (uint8_t) payload_len; // data_len low byte + buf_start[msg_offset] = static_cast(packet.message_type >> 8); // type high byte + buf_start[msg_offset + 1] = static_cast(packet.message_type); // type low byte + buf_start[msg_offset + 2] = static_cast(packet.payload_size >> 8); // data_len high byte + buf_start[msg_offset + 3] = static_cast(packet.payload_size); // data_len low byte // payload data is already in the buffer starting at offset + 7 // Make sure we have space for MAC @@ -673,7 +664,8 @@ APIError APINoiseFrameHelper::write_protobuf_packets(ProtoWriteBuffer buffer, co // Encrypt the message in place NoiseBuffer mbuf; noise_buffer_init(mbuf); - noise_buffer_set_inout(mbuf, buf_start + msg_offset, msg_len, msg_len + frame_footer_size_); + noise_buffer_set_inout(mbuf, buf_start + msg_offset, 4 + packet.payload_size, + 4 + packet.payload_size + frame_footer_size_); int err = noise_cipherstate_encrypt(send_cipher_, &mbuf); if (err != 0) { @@ -683,14 +675,12 @@ APIError APINoiseFrameHelper::write_protobuf_packets(ProtoWriteBuffer buffer, co } // Fill in the encrypted size - buf_start[1] = (uint8_t) (mbuf.size >> 8); - buf_start[2] = (uint8_t) mbuf.size; + buf_start[1] = static_cast(mbuf.size >> 8); + buf_start[2] = static_cast(mbuf.size); // Add iovec for this encrypted packet - struct iovec iov; - iov.iov_base = buf_start; - iov.iov_len = 3 + mbuf.size; // indicator + size + encrypted data - this->reusable_iovs_.push_back(iov); + this->reusable_iovs_.push_back( + {buf_start, static_cast(3 + mbuf.size)}); // indicator + size + encrypted data } // Send all encrypted packets in one writev call @@ -865,17 +855,9 @@ APIError APIPlaintextFrameHelper::try_read_frame_(ParsedFrame *frame) { // Try to get to at least 3 bytes total (indicator + 2 varint bytes), then read one byte at a time ssize_t received = this->socket_->read(&rx_header_buf_[rx_header_buf_pos_], rx_header_buf_pos_ < 3 ? 3 - rx_header_buf_pos_ : 1); - if (received == -1) { - if (errno == EWOULDBLOCK || errno == EAGAIN) { - return APIError::WOULD_BLOCK; - } - state_ = State::FAILED; - HELPER_LOG("Socket read failed with errno %d", errno); - return APIError::SOCKET_READ_FAILED; - } else if (received == 0) { - state_ = State::FAILED; - HELPER_LOG("Connection closed"); - return APIError::CONNECTION_CLOSED; + APIError err = handle_socket_read_result_(received); + if (err != APIError::OK) { + return err; } // If this was the first read, validate the indicator byte @@ -959,17 +941,9 @@ APIError APIPlaintextFrameHelper::try_read_frame_(ParsedFrame *frame) { // more data to read uint16_t to_read = rx_header_parsed_len_ - rx_buf_len_; ssize_t received = this->socket_->read(&rx_buf_[rx_buf_len_], to_read); - if (received == -1) { - if (errno == EWOULDBLOCK || errno == EAGAIN) { - return APIError::WOULD_BLOCK; - } - state_ = State::FAILED; - HELPER_LOG("Socket read failed with errno %d", errno); - return APIError::SOCKET_READ_FAILED; - } else if (received == 0) { - state_ = State::FAILED; - HELPER_LOG("Connection closed"); - return APIError::CONNECTION_CLOSED; + APIError err = handle_socket_read_result_(received); + if (err != APIError::OK) { + return err; } rx_buf_len_ += static_cast(received); if (static_cast(received) != to_read) { @@ -1029,18 +1003,11 @@ APIError APIPlaintextFrameHelper::read_packet(ReadPacketBuffer *buffer) { return APIError::OK; } APIError APIPlaintextFrameHelper::write_protobuf_packet(uint16_t type, ProtoWriteBuffer buffer) { - std::vector *raw_buffer = buffer.get_buffer(); - uint16_t payload_len = static_cast(raw_buffer->size() - frame_header_padding_); - - // Use write_protobuf_packets with a single packet - std::vector packets; - packets.emplace_back(type, 0, payload_len); - - return write_protobuf_packets(buffer, packets); + PacketInfo packet{type, 0, static_cast(buffer.get_buffer()->size() - frame_header_padding_)}; + return write_protobuf_packets(buffer, std::span(&packet, 1)); } -APIError APIPlaintextFrameHelper::write_protobuf_packets(ProtoWriteBuffer buffer, - const std::vector &packets) { +APIError APIPlaintextFrameHelper::write_protobuf_packets(ProtoWriteBuffer buffer, std::span packets) { if (state_ != State::DATA) { return APIError::BAD_STATE; } @@ -1050,17 +1017,15 @@ APIError APIPlaintextFrameHelper::write_protobuf_packets(ProtoWriteBuffer buffer } std::vector *raw_buffer = buffer.get_buffer(); + uint8_t *buffer_data = raw_buffer->data(); // Cache buffer pointer + this->reusable_iovs_.clear(); this->reusable_iovs_.reserve(packets.size()); for (const auto &packet : packets) { - uint16_t type = packet.message_type; - uint16_t offset = packet.offset; - uint16_t payload_len = packet.payload_size; - // Calculate varint sizes for header layout - uint8_t size_varint_len = api::ProtoSize::varint(static_cast(payload_len)); - uint8_t type_varint_len = api::ProtoSize::varint(static_cast(type)); + uint8_t size_varint_len = api::ProtoSize::varint(static_cast(packet.payload_size)); + uint8_t type_varint_len = api::ProtoSize::varint(static_cast(packet.message_type)); uint8_t total_header_len = 1 + size_varint_len + type_varint_len; // Calculate where to start writing the header @@ -1088,23 +1053,20 @@ APIError APIPlaintextFrameHelper::write_protobuf_packets(ProtoWriteBuffer buffer // // The message starts at offset + frame_header_padding_ // So we write the header starting at offset + frame_header_padding_ - total_header_len - uint8_t *buf_start = raw_buffer->data() + offset; + uint8_t *buf_start = buffer_data + packet.offset; uint32_t header_offset = frame_header_padding_ - total_header_len; // Write the plaintext header buf_start[header_offset] = 0x00; // indicator - // Encode size varint directly into buffer - ProtoVarInt(payload_len).encode_to_buffer_unchecked(buf_start + header_offset + 1, size_varint_len); - - // Encode type varint directly into buffer - ProtoVarInt(type).encode_to_buffer_unchecked(buf_start + header_offset + 1 + size_varint_len, type_varint_len); + // Encode varints directly into buffer + ProtoVarInt(packet.payload_size).encode_to_buffer_unchecked(buf_start + header_offset + 1, size_varint_len); + ProtoVarInt(packet.message_type) + .encode_to_buffer_unchecked(buf_start + header_offset + 1 + size_varint_len, type_varint_len); // Add iovec for this packet (header + payload) - struct iovec iov; - iov.iov_base = buf_start + header_offset; - iov.iov_len = total_header_len + payload_len; - this->reusable_iovs_.push_back(iov); + this->reusable_iovs_.push_back( + {buf_start + header_offset, static_cast(total_header_len + packet.payload_size)}); } // Send all packets in one writev call diff --git a/esphome/components/api/api_frame_helper.h b/esphome/components/api/api_frame_helper.h index 1e157278a1..eae83a3484 100644 --- a/esphome/components/api/api_frame_helper.h +++ b/esphome/components/api/api_frame_helper.h @@ -2,6 +2,7 @@ #include #include #include +#include #include #include @@ -101,7 +102,7 @@ class APIFrameHelper { // Write multiple protobuf packets in a single operation // packets contains (message_type, offset, length) for each message in the buffer // The buffer contains all messages with appropriate padding before each - virtual APIError write_protobuf_packets(ProtoWriteBuffer buffer, const std::vector &packets) = 0; + virtual APIError write_protobuf_packets(ProtoWriteBuffer buffer, std::span packets) = 0; // Get the frame header padding required by this protocol virtual uint8_t frame_header_padding() = 0; // Get the frame footer size required by this protocol @@ -175,6 +176,9 @@ class APIFrameHelper { // Common initialization for both plaintext and noise protocols APIError init_common_(); + + // Helper method to handle socket read results + APIError handle_socket_read_result_(ssize_t received); }; #ifdef USE_API_NOISE @@ -194,7 +198,7 @@ class APINoiseFrameHelper : public APIFrameHelper { APIError loop() override; APIError read_packet(ReadPacketBuffer *buffer) override; APIError write_protobuf_packet(uint16_t type, ProtoWriteBuffer buffer) override; - APIError write_protobuf_packets(ProtoWriteBuffer buffer, const std::vector &packets) override; + APIError write_protobuf_packets(ProtoWriteBuffer buffer, std::span packets) override; // Get the frame header padding required by this protocol uint8_t frame_header_padding() override { return frame_header_padding_; } // Get the frame footer size required by this protocol @@ -248,7 +252,7 @@ class APIPlaintextFrameHelper : public APIFrameHelper { APIError loop() override; APIError read_packet(ReadPacketBuffer *buffer) override; APIError write_protobuf_packet(uint16_t type, ProtoWriteBuffer buffer) override; - APIError write_protobuf_packets(ProtoWriteBuffer buffer, const std::vector &packets) override; + APIError write_protobuf_packets(ProtoWriteBuffer buffer, std::span packets) override; uint8_t frame_header_padding() override { return frame_header_padding_; } // Get the frame footer size required by this protocol uint8_t frame_footer_size() override { return frame_footer_size_; } diff --git a/esphome/components/api/api_pb2.cpp b/esphome/components/api/api_pb2.cpp index 7d16e43ce6..3505ec758d 100644 --- a/esphome/components/api/api_pb2.cpp +++ b/esphome/components/api/api_pb2.cpp @@ -5,633 +5,9 @@ #include "esphome/core/log.h" #include "esphome/core/helpers.h" -#include - namespace esphome { namespace api { -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::EntityCategory value) { - switch (value) { - case enums::ENTITY_CATEGORY_NONE: - return "ENTITY_CATEGORY_NONE"; - case enums::ENTITY_CATEGORY_CONFIG: - return "ENTITY_CATEGORY_CONFIG"; - case enums::ENTITY_CATEGORY_DIAGNOSTIC: - return "ENTITY_CATEGORY_DIAGNOSTIC"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::LegacyCoverState value) { - switch (value) { - case enums::LEGACY_COVER_STATE_OPEN: - return "LEGACY_COVER_STATE_OPEN"; - case enums::LEGACY_COVER_STATE_CLOSED: - return "LEGACY_COVER_STATE_CLOSED"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::CoverOperation value) { - switch (value) { - case enums::COVER_OPERATION_IDLE: - return "COVER_OPERATION_IDLE"; - case enums::COVER_OPERATION_IS_OPENING: - return "COVER_OPERATION_IS_OPENING"; - case enums::COVER_OPERATION_IS_CLOSING: - return "COVER_OPERATION_IS_CLOSING"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::LegacyCoverCommand value) { - switch (value) { - case enums::LEGACY_COVER_COMMAND_OPEN: - return "LEGACY_COVER_COMMAND_OPEN"; - case enums::LEGACY_COVER_COMMAND_CLOSE: - return "LEGACY_COVER_COMMAND_CLOSE"; - case enums::LEGACY_COVER_COMMAND_STOP: - return "LEGACY_COVER_COMMAND_STOP"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::FanSpeed value) { - switch (value) { - case enums::FAN_SPEED_LOW: - return "FAN_SPEED_LOW"; - case enums::FAN_SPEED_MEDIUM: - return "FAN_SPEED_MEDIUM"; - case enums::FAN_SPEED_HIGH: - return "FAN_SPEED_HIGH"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::FanDirection value) { - switch (value) { - case enums::FAN_DIRECTION_FORWARD: - return "FAN_DIRECTION_FORWARD"; - case enums::FAN_DIRECTION_REVERSE: - return "FAN_DIRECTION_REVERSE"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::ColorMode value) { - switch (value) { - case enums::COLOR_MODE_UNKNOWN: - return "COLOR_MODE_UNKNOWN"; - case enums::COLOR_MODE_ON_OFF: - return "COLOR_MODE_ON_OFF"; - case enums::COLOR_MODE_LEGACY_BRIGHTNESS: - return "COLOR_MODE_LEGACY_BRIGHTNESS"; - case enums::COLOR_MODE_BRIGHTNESS: - return "COLOR_MODE_BRIGHTNESS"; - case enums::COLOR_MODE_WHITE: - return "COLOR_MODE_WHITE"; - case enums::COLOR_MODE_COLOR_TEMPERATURE: - return "COLOR_MODE_COLOR_TEMPERATURE"; - case enums::COLOR_MODE_COLD_WARM_WHITE: - return "COLOR_MODE_COLD_WARM_WHITE"; - case enums::COLOR_MODE_RGB: - return "COLOR_MODE_RGB"; - case enums::COLOR_MODE_RGB_WHITE: - return "COLOR_MODE_RGB_WHITE"; - case enums::COLOR_MODE_RGB_COLOR_TEMPERATURE: - return "COLOR_MODE_RGB_COLOR_TEMPERATURE"; - case enums::COLOR_MODE_RGB_COLD_WARM_WHITE: - return "COLOR_MODE_RGB_COLD_WARM_WHITE"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::SensorStateClass value) { - switch (value) { - case enums::STATE_CLASS_NONE: - return "STATE_CLASS_NONE"; - case enums::STATE_CLASS_MEASUREMENT: - return "STATE_CLASS_MEASUREMENT"; - case enums::STATE_CLASS_TOTAL_INCREASING: - return "STATE_CLASS_TOTAL_INCREASING"; - case enums::STATE_CLASS_TOTAL: - return "STATE_CLASS_TOTAL"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::SensorLastResetType value) { - switch (value) { - case enums::LAST_RESET_NONE: - return "LAST_RESET_NONE"; - case enums::LAST_RESET_NEVER: - return "LAST_RESET_NEVER"; - case enums::LAST_RESET_AUTO: - return "LAST_RESET_AUTO"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::LogLevel value) { - switch (value) { - case enums::LOG_LEVEL_NONE: - return "LOG_LEVEL_NONE"; - case enums::LOG_LEVEL_ERROR: - return "LOG_LEVEL_ERROR"; - case enums::LOG_LEVEL_WARN: - return "LOG_LEVEL_WARN"; - case enums::LOG_LEVEL_INFO: - return "LOG_LEVEL_INFO"; - case enums::LOG_LEVEL_CONFIG: - return "LOG_LEVEL_CONFIG"; - case enums::LOG_LEVEL_DEBUG: - return "LOG_LEVEL_DEBUG"; - case enums::LOG_LEVEL_VERBOSE: - return "LOG_LEVEL_VERBOSE"; - case enums::LOG_LEVEL_VERY_VERBOSE: - return "LOG_LEVEL_VERY_VERBOSE"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::ServiceArgType value) { - switch (value) { - case enums::SERVICE_ARG_TYPE_BOOL: - return "SERVICE_ARG_TYPE_BOOL"; - case enums::SERVICE_ARG_TYPE_INT: - return "SERVICE_ARG_TYPE_INT"; - case enums::SERVICE_ARG_TYPE_FLOAT: - return "SERVICE_ARG_TYPE_FLOAT"; - case enums::SERVICE_ARG_TYPE_STRING: - return "SERVICE_ARG_TYPE_STRING"; - case enums::SERVICE_ARG_TYPE_BOOL_ARRAY: - return "SERVICE_ARG_TYPE_BOOL_ARRAY"; - case enums::SERVICE_ARG_TYPE_INT_ARRAY: - return "SERVICE_ARG_TYPE_INT_ARRAY"; - case enums::SERVICE_ARG_TYPE_FLOAT_ARRAY: - return "SERVICE_ARG_TYPE_FLOAT_ARRAY"; - case enums::SERVICE_ARG_TYPE_STRING_ARRAY: - return "SERVICE_ARG_TYPE_STRING_ARRAY"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::ClimateMode value) { - switch (value) { - case enums::CLIMATE_MODE_OFF: - return "CLIMATE_MODE_OFF"; - case enums::CLIMATE_MODE_HEAT_COOL: - return "CLIMATE_MODE_HEAT_COOL"; - case enums::CLIMATE_MODE_COOL: - return "CLIMATE_MODE_COOL"; - case enums::CLIMATE_MODE_HEAT: - return "CLIMATE_MODE_HEAT"; - case enums::CLIMATE_MODE_FAN_ONLY: - return "CLIMATE_MODE_FAN_ONLY"; - case enums::CLIMATE_MODE_DRY: - return "CLIMATE_MODE_DRY"; - case enums::CLIMATE_MODE_AUTO: - return "CLIMATE_MODE_AUTO"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::ClimateFanMode value) { - switch (value) { - case enums::CLIMATE_FAN_ON: - return "CLIMATE_FAN_ON"; - case enums::CLIMATE_FAN_OFF: - return "CLIMATE_FAN_OFF"; - case enums::CLIMATE_FAN_AUTO: - return "CLIMATE_FAN_AUTO"; - case enums::CLIMATE_FAN_LOW: - return "CLIMATE_FAN_LOW"; - case enums::CLIMATE_FAN_MEDIUM: - return "CLIMATE_FAN_MEDIUM"; - case enums::CLIMATE_FAN_HIGH: - return "CLIMATE_FAN_HIGH"; - case enums::CLIMATE_FAN_MIDDLE: - return "CLIMATE_FAN_MIDDLE"; - case enums::CLIMATE_FAN_FOCUS: - return "CLIMATE_FAN_FOCUS"; - case enums::CLIMATE_FAN_DIFFUSE: - return "CLIMATE_FAN_DIFFUSE"; - case enums::CLIMATE_FAN_QUIET: - return "CLIMATE_FAN_QUIET"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::ClimateSwingMode value) { - switch (value) { - case enums::CLIMATE_SWING_OFF: - return "CLIMATE_SWING_OFF"; - case enums::CLIMATE_SWING_BOTH: - return "CLIMATE_SWING_BOTH"; - case enums::CLIMATE_SWING_VERTICAL: - return "CLIMATE_SWING_VERTICAL"; - case enums::CLIMATE_SWING_HORIZONTAL: - return "CLIMATE_SWING_HORIZONTAL"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::ClimateAction value) { - switch (value) { - case enums::CLIMATE_ACTION_OFF: - return "CLIMATE_ACTION_OFF"; - case enums::CLIMATE_ACTION_COOLING: - return "CLIMATE_ACTION_COOLING"; - case enums::CLIMATE_ACTION_HEATING: - return "CLIMATE_ACTION_HEATING"; - case enums::CLIMATE_ACTION_IDLE: - return "CLIMATE_ACTION_IDLE"; - case enums::CLIMATE_ACTION_DRYING: - return "CLIMATE_ACTION_DRYING"; - case enums::CLIMATE_ACTION_FAN: - return "CLIMATE_ACTION_FAN"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::ClimatePreset value) { - switch (value) { - case enums::CLIMATE_PRESET_NONE: - return "CLIMATE_PRESET_NONE"; - case enums::CLIMATE_PRESET_HOME: - return "CLIMATE_PRESET_HOME"; - case enums::CLIMATE_PRESET_AWAY: - return "CLIMATE_PRESET_AWAY"; - case enums::CLIMATE_PRESET_BOOST: - return "CLIMATE_PRESET_BOOST"; - case enums::CLIMATE_PRESET_COMFORT: - return "CLIMATE_PRESET_COMFORT"; - case enums::CLIMATE_PRESET_ECO: - return "CLIMATE_PRESET_ECO"; - case enums::CLIMATE_PRESET_SLEEP: - return "CLIMATE_PRESET_SLEEP"; - case enums::CLIMATE_PRESET_ACTIVITY: - return "CLIMATE_PRESET_ACTIVITY"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::NumberMode value) { - switch (value) { - case enums::NUMBER_MODE_AUTO: - return "NUMBER_MODE_AUTO"; - case enums::NUMBER_MODE_BOX: - return "NUMBER_MODE_BOX"; - case enums::NUMBER_MODE_SLIDER: - return "NUMBER_MODE_SLIDER"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::LockState value) { - switch (value) { - case enums::LOCK_STATE_NONE: - return "LOCK_STATE_NONE"; - case enums::LOCK_STATE_LOCKED: - return "LOCK_STATE_LOCKED"; - case enums::LOCK_STATE_UNLOCKED: - return "LOCK_STATE_UNLOCKED"; - case enums::LOCK_STATE_JAMMED: - return "LOCK_STATE_JAMMED"; - case enums::LOCK_STATE_LOCKING: - return "LOCK_STATE_LOCKING"; - case enums::LOCK_STATE_UNLOCKING: - return "LOCK_STATE_UNLOCKING"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::LockCommand value) { - switch (value) { - case enums::LOCK_UNLOCK: - return "LOCK_UNLOCK"; - case enums::LOCK_LOCK: - return "LOCK_LOCK"; - case enums::LOCK_OPEN: - return "LOCK_OPEN"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::MediaPlayerState value) { - switch (value) { - case enums::MEDIA_PLAYER_STATE_NONE: - return "MEDIA_PLAYER_STATE_NONE"; - case enums::MEDIA_PLAYER_STATE_IDLE: - return "MEDIA_PLAYER_STATE_IDLE"; - case enums::MEDIA_PLAYER_STATE_PLAYING: - return "MEDIA_PLAYER_STATE_PLAYING"; - case enums::MEDIA_PLAYER_STATE_PAUSED: - return "MEDIA_PLAYER_STATE_PAUSED"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::MediaPlayerCommand value) { - switch (value) { - case enums::MEDIA_PLAYER_COMMAND_PLAY: - return "MEDIA_PLAYER_COMMAND_PLAY"; - case enums::MEDIA_PLAYER_COMMAND_PAUSE: - return "MEDIA_PLAYER_COMMAND_PAUSE"; - case enums::MEDIA_PLAYER_COMMAND_STOP: - return "MEDIA_PLAYER_COMMAND_STOP"; - case enums::MEDIA_PLAYER_COMMAND_MUTE: - return "MEDIA_PLAYER_COMMAND_MUTE"; - case enums::MEDIA_PLAYER_COMMAND_UNMUTE: - return "MEDIA_PLAYER_COMMAND_UNMUTE"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::MediaPlayerFormatPurpose value) { - switch (value) { - case enums::MEDIA_PLAYER_FORMAT_PURPOSE_DEFAULT: - return "MEDIA_PLAYER_FORMAT_PURPOSE_DEFAULT"; - case enums::MEDIA_PLAYER_FORMAT_PURPOSE_ANNOUNCEMENT: - return "MEDIA_PLAYER_FORMAT_PURPOSE_ANNOUNCEMENT"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> -const char *proto_enum_to_string(enums::BluetoothDeviceRequestType value) { - switch (value) { - case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT: - return "BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT"; - case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_DISCONNECT: - return "BLUETOOTH_DEVICE_REQUEST_TYPE_DISCONNECT"; - case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_PAIR: - return "BLUETOOTH_DEVICE_REQUEST_TYPE_PAIR"; - case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_UNPAIR: - return "BLUETOOTH_DEVICE_REQUEST_TYPE_UNPAIR"; - case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITH_CACHE: - return "BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITH_CACHE"; - case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITHOUT_CACHE: - return "BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITHOUT_CACHE"; - case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_CLEAR_CACHE: - return "BLUETOOTH_DEVICE_REQUEST_TYPE_CLEAR_CACHE"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::BluetoothScannerState value) { - switch (value) { - case enums::BLUETOOTH_SCANNER_STATE_IDLE: - return "BLUETOOTH_SCANNER_STATE_IDLE"; - case enums::BLUETOOTH_SCANNER_STATE_STARTING: - return "BLUETOOTH_SCANNER_STATE_STARTING"; - case enums::BLUETOOTH_SCANNER_STATE_RUNNING: - return "BLUETOOTH_SCANNER_STATE_RUNNING"; - case enums::BLUETOOTH_SCANNER_STATE_FAILED: - return "BLUETOOTH_SCANNER_STATE_FAILED"; - case enums::BLUETOOTH_SCANNER_STATE_STOPPING: - return "BLUETOOTH_SCANNER_STATE_STOPPING"; - case enums::BLUETOOTH_SCANNER_STATE_STOPPED: - return "BLUETOOTH_SCANNER_STATE_STOPPED"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::BluetoothScannerMode value) { - switch (value) { - case enums::BLUETOOTH_SCANNER_MODE_PASSIVE: - return "BLUETOOTH_SCANNER_MODE_PASSIVE"; - case enums::BLUETOOTH_SCANNER_MODE_ACTIVE: - return "BLUETOOTH_SCANNER_MODE_ACTIVE"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> -const char *proto_enum_to_string(enums::VoiceAssistantSubscribeFlag value) { - switch (value) { - case enums::VOICE_ASSISTANT_SUBSCRIBE_NONE: - return "VOICE_ASSISTANT_SUBSCRIBE_NONE"; - case enums::VOICE_ASSISTANT_SUBSCRIBE_API_AUDIO: - return "VOICE_ASSISTANT_SUBSCRIBE_API_AUDIO"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::VoiceAssistantRequestFlag value) { - switch (value) { - case enums::VOICE_ASSISTANT_REQUEST_NONE: - return "VOICE_ASSISTANT_REQUEST_NONE"; - case enums::VOICE_ASSISTANT_REQUEST_USE_VAD: - return "VOICE_ASSISTANT_REQUEST_USE_VAD"; - case enums::VOICE_ASSISTANT_REQUEST_USE_WAKE_WORD: - return "VOICE_ASSISTANT_REQUEST_USE_WAKE_WORD"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::VoiceAssistantEvent value) { - switch (value) { - case enums::VOICE_ASSISTANT_ERROR: - return "VOICE_ASSISTANT_ERROR"; - case enums::VOICE_ASSISTANT_RUN_START: - return "VOICE_ASSISTANT_RUN_START"; - case enums::VOICE_ASSISTANT_RUN_END: - return "VOICE_ASSISTANT_RUN_END"; - case enums::VOICE_ASSISTANT_STT_START: - return "VOICE_ASSISTANT_STT_START"; - case enums::VOICE_ASSISTANT_STT_END: - return "VOICE_ASSISTANT_STT_END"; - case enums::VOICE_ASSISTANT_INTENT_START: - return "VOICE_ASSISTANT_INTENT_START"; - case enums::VOICE_ASSISTANT_INTENT_END: - return "VOICE_ASSISTANT_INTENT_END"; - case enums::VOICE_ASSISTANT_TTS_START: - return "VOICE_ASSISTANT_TTS_START"; - case enums::VOICE_ASSISTANT_TTS_END: - return "VOICE_ASSISTANT_TTS_END"; - case enums::VOICE_ASSISTANT_WAKE_WORD_START: - return "VOICE_ASSISTANT_WAKE_WORD_START"; - case enums::VOICE_ASSISTANT_WAKE_WORD_END: - return "VOICE_ASSISTANT_WAKE_WORD_END"; - case enums::VOICE_ASSISTANT_STT_VAD_START: - return "VOICE_ASSISTANT_STT_VAD_START"; - case enums::VOICE_ASSISTANT_STT_VAD_END: - return "VOICE_ASSISTANT_STT_VAD_END"; - case enums::VOICE_ASSISTANT_TTS_STREAM_START: - return "VOICE_ASSISTANT_TTS_STREAM_START"; - case enums::VOICE_ASSISTANT_TTS_STREAM_END: - return "VOICE_ASSISTANT_TTS_STREAM_END"; - case enums::VOICE_ASSISTANT_INTENT_PROGRESS: - return "VOICE_ASSISTANT_INTENT_PROGRESS"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::VoiceAssistantTimerEvent value) { - switch (value) { - case enums::VOICE_ASSISTANT_TIMER_STARTED: - return "VOICE_ASSISTANT_TIMER_STARTED"; - case enums::VOICE_ASSISTANT_TIMER_UPDATED: - return "VOICE_ASSISTANT_TIMER_UPDATED"; - case enums::VOICE_ASSISTANT_TIMER_CANCELLED: - return "VOICE_ASSISTANT_TIMER_CANCELLED"; - case enums::VOICE_ASSISTANT_TIMER_FINISHED: - return "VOICE_ASSISTANT_TIMER_FINISHED"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::AlarmControlPanelState value) { - switch (value) { - case enums::ALARM_STATE_DISARMED: - return "ALARM_STATE_DISARMED"; - case enums::ALARM_STATE_ARMED_HOME: - return "ALARM_STATE_ARMED_HOME"; - case enums::ALARM_STATE_ARMED_AWAY: - return "ALARM_STATE_ARMED_AWAY"; - case enums::ALARM_STATE_ARMED_NIGHT: - return "ALARM_STATE_ARMED_NIGHT"; - case enums::ALARM_STATE_ARMED_VACATION: - return "ALARM_STATE_ARMED_VACATION"; - case enums::ALARM_STATE_ARMED_CUSTOM_BYPASS: - return "ALARM_STATE_ARMED_CUSTOM_BYPASS"; - case enums::ALARM_STATE_PENDING: - return "ALARM_STATE_PENDING"; - case enums::ALARM_STATE_ARMING: - return "ALARM_STATE_ARMING"; - case enums::ALARM_STATE_DISARMING: - return "ALARM_STATE_DISARMING"; - case enums::ALARM_STATE_TRIGGERED: - return "ALARM_STATE_TRIGGERED"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> -const char *proto_enum_to_string(enums::AlarmControlPanelStateCommand value) { - switch (value) { - case enums::ALARM_CONTROL_PANEL_DISARM: - return "ALARM_CONTROL_PANEL_DISARM"; - case enums::ALARM_CONTROL_PANEL_ARM_AWAY: - return "ALARM_CONTROL_PANEL_ARM_AWAY"; - case enums::ALARM_CONTROL_PANEL_ARM_HOME: - return "ALARM_CONTROL_PANEL_ARM_HOME"; - case enums::ALARM_CONTROL_PANEL_ARM_NIGHT: - return "ALARM_CONTROL_PANEL_ARM_NIGHT"; - case enums::ALARM_CONTROL_PANEL_ARM_VACATION: - return "ALARM_CONTROL_PANEL_ARM_VACATION"; - case enums::ALARM_CONTROL_PANEL_ARM_CUSTOM_BYPASS: - return "ALARM_CONTROL_PANEL_ARM_CUSTOM_BYPASS"; - case enums::ALARM_CONTROL_PANEL_TRIGGER: - return "ALARM_CONTROL_PANEL_TRIGGER"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::TextMode value) { - switch (value) { - case enums::TEXT_MODE_TEXT: - return "TEXT_MODE_TEXT"; - case enums::TEXT_MODE_PASSWORD: - return "TEXT_MODE_PASSWORD"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::ValveOperation value) { - switch (value) { - case enums::VALVE_OPERATION_IDLE: - return "VALVE_OPERATION_IDLE"; - case enums::VALVE_OPERATION_IS_OPENING: - return "VALVE_OPERATION_IS_OPENING"; - case enums::VALVE_OPERATION_IS_CLOSING: - return "VALVE_OPERATION_IS_CLOSING"; - default: - return "UNKNOWN"; - } -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -template<> const char *proto_enum_to_string(enums::UpdateCommand value) { - switch (value) { - case enums::UPDATE_COMMAND_NONE: - return "UPDATE_COMMAND_NONE"; - case enums::UPDATE_COMMAND_UPDATE: - return "UPDATE_COMMAND_UPDATE"; - case enums::UPDATE_COMMAND_CHECK: - return "UPDATE_COMMAND_CHECK"; - default: - return "UNKNOWN"; - } -} -#endif - bool HelloRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -666,26 +42,6 @@ void HelloRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->api_version_major, false); ProtoSize::add_uint32_field(total_size, 1, this->api_version_minor, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void HelloRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("HelloRequest {\n"); - out.append(" client_info: "); - out.append("'").append(this->client_info).append("'"); - out.append("\n"); - - out.append(" api_version_major: "); - sprintf(buffer, "%" PRIu32, this->api_version_major); - out.append(buffer); - out.append("\n"); - - out.append(" api_version_minor: "); - sprintf(buffer, "%" PRIu32, this->api_version_minor); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool HelloResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -726,30 +82,6 @@ void HelloResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->server_info, false); ProtoSize::add_string_field(total_size, 1, this->name, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void HelloResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("HelloResponse {\n"); - out.append(" api_version_major: "); - sprintf(buffer, "%" PRIu32, this->api_version_major); - out.append(buffer); - out.append("\n"); - - out.append(" api_version_minor: "); - sprintf(buffer, "%" PRIu32, this->api_version_minor); - out.append(buffer); - out.append("\n"); - - out.append(" server_info: "); - out.append("'").append(this->server_info).append("'"); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - out.append("}"); -} -#endif bool ConnectRequest::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 1: { @@ -764,16 +96,6 @@ void ConnectRequest::encode(ProtoWriteBuffer buffer) const { buffer.encode_strin void ConnectRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->password, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ConnectRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ConnectRequest {\n"); - out.append(" password: "); - out.append("'").append(this->password).append("'"); - out.append("\n"); - out.append("}"); -} -#endif bool ConnectResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -788,31 +110,6 @@ void ConnectResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_bool void ConnectResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->invalid_password, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ConnectResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ConnectResponse {\n"); - out.append(" invalid_password: "); - out.append(YESNO(this->invalid_password)); - out.append("\n"); - out.append("}"); -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void DisconnectRequest::dump_to(std::string &out) const { out.append("DisconnectRequest {}"); } -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void DisconnectResponse::dump_to(std::string &out) const { out.append("DisconnectResponse {}"); } -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void PingRequest::dump_to(std::string &out) const { out.append("PingRequest {}"); } -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void PingResponse::dump_to(std::string &out) const { out.append("PingResponse {}"); } -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void DeviceInfoRequest::dump_to(std::string &out) const { out.append("DeviceInfoRequest {}"); } -#endif bool AreaInfo::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -841,21 +138,6 @@ void AreaInfo::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->area_id, false); ProtoSize::add_string_field(total_size, 1, this->name, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void AreaInfo::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("AreaInfo {\n"); - out.append(" area_id: "); - sprintf(buffer, "%" PRIu32, this->area_id); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - out.append("}"); -} -#endif bool DeviceInfo::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -890,26 +172,6 @@ void DeviceInfo::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->name, false); ProtoSize::add_uint32_field(total_size, 1, this->area_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void DeviceInfo::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("DeviceInfo {\n"); - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" area_id: "); - sprintf(buffer, "%" PRIu32, this->area_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool DeviceInfoResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -1062,118 +324,7 @@ void DeviceInfoResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_repeated_message(total_size, 2, this->areas); ProtoSize::add_message_object(total_size, 2, this->area, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void DeviceInfoResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("DeviceInfoResponse {\n"); - out.append(" uses_password: "); - out.append(YESNO(this->uses_password)); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" mac_address: "); - out.append("'").append(this->mac_address).append("'"); - out.append("\n"); - - out.append(" esphome_version: "); - out.append("'").append(this->esphome_version).append("'"); - out.append("\n"); - - out.append(" compilation_time: "); - out.append("'").append(this->compilation_time).append("'"); - out.append("\n"); - - out.append(" model: "); - out.append("'").append(this->model).append("'"); - out.append("\n"); - - out.append(" has_deep_sleep: "); - out.append(YESNO(this->has_deep_sleep)); - out.append("\n"); - - out.append(" project_name: "); - out.append("'").append(this->project_name).append("'"); - out.append("\n"); - - out.append(" project_version: "); - out.append("'").append(this->project_version).append("'"); - out.append("\n"); - - out.append(" webserver_port: "); - sprintf(buffer, "%" PRIu32, this->webserver_port); - out.append(buffer); - out.append("\n"); - - out.append(" legacy_bluetooth_proxy_version: "); - sprintf(buffer, "%" PRIu32, this->legacy_bluetooth_proxy_version); - out.append(buffer); - out.append("\n"); - - out.append(" bluetooth_proxy_feature_flags: "); - sprintf(buffer, "%" PRIu32, this->bluetooth_proxy_feature_flags); - out.append(buffer); - out.append("\n"); - - out.append(" manufacturer: "); - out.append("'").append(this->manufacturer).append("'"); - out.append("\n"); - - out.append(" friendly_name: "); - out.append("'").append(this->friendly_name).append("'"); - out.append("\n"); - - out.append(" legacy_voice_assistant_version: "); - sprintf(buffer, "%" PRIu32, this->legacy_voice_assistant_version); - out.append(buffer); - out.append("\n"); - - out.append(" voice_assistant_feature_flags: "); - sprintf(buffer, "%" PRIu32, this->voice_assistant_feature_flags); - out.append(buffer); - out.append("\n"); - - out.append(" suggested_area: "); - out.append("'").append(this->suggested_area).append("'"); - out.append("\n"); - - out.append(" bluetooth_mac_address: "); - out.append("'").append(this->bluetooth_mac_address).append("'"); - out.append("\n"); - - out.append(" api_encryption_supported: "); - out.append(YESNO(this->api_encryption_supported)); - out.append("\n"); - - for (const auto &it : this->devices) { - out.append(" devices: "); - it.dump_to(out); - out.append("\n"); - } - - for (const auto &it : this->areas) { - out.append(" areas: "); - it.dump_to(out); - out.append("\n"); - } - - out.append(" area: "); - this->area.dump_to(out); - out.append("\n"); - out.append("}"); -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesRequest::dump_to(std::string &out) const { out.append("ListEntitiesRequest {}"); } -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesDoneResponse::dump_to(std::string &out) const { out.append("ListEntitiesDoneResponse {}"); } -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void SubscribeStatesRequest::dump_to(std::string &out) const { out.append("SubscribeStatesRequest {}"); } -#endif +#ifdef USE_BINARY_SENSOR bool ListEntitiesBinarySensorResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -1256,54 +407,6 @@ void ListEntitiesBinarySensorResponse::calculate_size(uint32_t &total_size) cons ProtoSize::add_enum_field(total_size, 1, static_cast(this->entity_category), false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesBinarySensorResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesBinarySensorResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" device_class: "); - out.append("'").append(this->device_class).append("'"); - out.append("\n"); - - out.append(" is_status_binary_sensor: "); - out.append(YESNO(this->is_status_binary_sensor)); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BinarySensorStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -1314,6 +417,10 @@ bool BinarySensorStateResponse::decode_varint(uint32_t field_id, ProtoVarInt val this->missing_state = value.as_bool(); return true; } + case 4: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -1332,31 +439,16 @@ void BinarySensorStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_bool(2, this->state); buffer.encode_bool(3, this->missing_state); + buffer.encode_uint32(4, this->device_id); } void BinarySensorStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_bool_field(total_size, 1, this->state, false); ProtoSize::add_bool_field(total_size, 1, this->missing_state, false); -} -#ifdef HAS_PROTO_MESSAGE_DUMP -void BinarySensorStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BinarySensorStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append(YESNO(this->state)); - out.append("\n"); - - out.append(" missing_state: "); - out.append(YESNO(this->missing_state)); - out.append("\n"); - out.append("}"); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } #endif +#ifdef USE_COVER bool ListEntitiesCoverResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 5: { @@ -1457,66 +549,6 @@ void ListEntitiesCoverResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->supports_stop, false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesCoverResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesCoverResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" assumed_state: "); - out.append(YESNO(this->assumed_state)); - out.append("\n"); - - out.append(" supports_position: "); - out.append(YESNO(this->supports_position)); - out.append("\n"); - - out.append(" supports_tilt: "); - out.append(YESNO(this->supports_tilt)); - out.append("\n"); - - out.append(" device_class: "); - out.append("'").append(this->device_class).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" supports_stop: "); - out.append(YESNO(this->supports_stop)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool CoverStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -1527,6 +559,10 @@ bool CoverStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { this->current_operation = value.as_enum(); return true; } + case 6: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -1555,6 +591,7 @@ void CoverStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_float(3, this->position); buffer.encode_float(4, this->tilt); buffer.encode_enum(5, this->current_operation); + buffer.encode_uint32(6, this->device_id); } void CoverStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); @@ -1562,36 +599,8 @@ void CoverStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->position != 0.0f, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->tilt != 0.0f, false); ProtoSize::add_enum_field(total_size, 1, static_cast(this->current_operation), false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void CoverStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("CoverStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" legacy_state: "); - out.append(proto_enum_to_string(this->legacy_state)); - out.append("\n"); - - out.append(" position: "); - sprintf(buffer, "%g", this->position); - out.append(buffer); - out.append("\n"); - - out.append(" tilt: "); - sprintf(buffer, "%g", this->tilt); - out.append(buffer); - out.append("\n"); - - out.append(" current_operation: "); - out.append(proto_enum_to_string(this->current_operation)); - out.append("\n"); - out.append("}"); -} -#endif bool CoverCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -1656,47 +665,8 @@ void CoverCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->tilt != 0.0f, false); ProtoSize::add_bool_field(total_size, 1, this->stop, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void CoverCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("CoverCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" has_legacy_command: "); - out.append(YESNO(this->has_legacy_command)); - out.append("\n"); - - out.append(" legacy_command: "); - out.append(proto_enum_to_string(this->legacy_command)); - out.append("\n"); - - out.append(" has_position: "); - out.append(YESNO(this->has_position)); - out.append("\n"); - - out.append(" position: "); - sprintf(buffer, "%g", this->position); - out.append(buffer); - out.append("\n"); - - out.append(" has_tilt: "); - out.append(YESNO(this->has_tilt)); - out.append("\n"); - - out.append(" tilt: "); - sprintf(buffer, "%g", this->tilt); - out.append(buffer); - out.append("\n"); - - out.append(" stop: "); - out.append(YESNO(this->stop)); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_FAN bool ListEntitiesFanResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 5: { @@ -1803,69 +773,6 @@ void ListEntitiesFanResponse::calculate_size(uint32_t &total_size) const { } ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesFanResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesFanResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" supports_oscillation: "); - out.append(YESNO(this->supports_oscillation)); - out.append("\n"); - - out.append(" supports_speed: "); - out.append(YESNO(this->supports_speed)); - out.append("\n"); - - out.append(" supports_direction: "); - out.append(YESNO(this->supports_direction)); - out.append("\n"); - - out.append(" supported_speed_count: "); - sprintf(buffer, "%" PRId32, this->supported_speed_count); - out.append(buffer); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - for (const auto &it : this->supported_preset_modes) { - out.append(" supported_preset_modes: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool FanStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -1888,6 +795,10 @@ bool FanStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { this->speed_level = value.as_int32(); return true; } + case 8: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -1920,6 +831,7 @@ void FanStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_enum(5, this->direction); buffer.encode_int32(6, this->speed_level); buffer.encode_string(7, this->preset_mode); + buffer.encode_uint32(8, this->device_id); } void FanStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); @@ -1929,43 +841,8 @@ void FanStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->direction), false); ProtoSize::add_int32_field(total_size, 1, this->speed_level, false); ProtoSize::add_string_field(total_size, 1, this->preset_mode, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void FanStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("FanStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append(YESNO(this->state)); - out.append("\n"); - - out.append(" oscillating: "); - out.append(YESNO(this->oscillating)); - out.append("\n"); - - out.append(" speed: "); - out.append(proto_enum_to_string(this->speed)); - out.append("\n"); - - out.append(" direction: "); - out.append(proto_enum_to_string(this->direction)); - out.append("\n"); - - out.append(" speed_level: "); - sprintf(buffer, "%" PRId32, this->speed_level); - out.append(buffer); - out.append("\n"); - - out.append(" preset_mode: "); - out.append("'").append(this->preset_mode).append("'"); - out.append("\n"); - out.append("}"); -} -#endif bool FanCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -2066,66 +943,8 @@ void FanCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->has_preset_mode, false); ProtoSize::add_string_field(total_size, 1, this->preset_mode, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void FanCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("FanCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" has_state: "); - out.append(YESNO(this->has_state)); - out.append("\n"); - - out.append(" state: "); - out.append(YESNO(this->state)); - out.append("\n"); - - out.append(" has_speed: "); - out.append(YESNO(this->has_speed)); - out.append("\n"); - - out.append(" speed: "); - out.append(proto_enum_to_string(this->speed)); - out.append("\n"); - - out.append(" has_oscillating: "); - out.append(YESNO(this->has_oscillating)); - out.append("\n"); - - out.append(" oscillating: "); - out.append(YESNO(this->oscillating)); - out.append("\n"); - - out.append(" has_direction: "); - out.append(YESNO(this->has_direction)); - out.append("\n"); - - out.append(" direction: "); - out.append(proto_enum_to_string(this->direction)); - out.append("\n"); - - out.append(" has_speed_level: "); - out.append(YESNO(this->has_speed_level)); - out.append("\n"); - - out.append(" speed_level: "); - sprintf(buffer, "%" PRId32, this->speed_level); - out.append(buffer); - out.append("\n"); - - out.append(" has_preset_mode: "); - out.append(YESNO(this->has_preset_mode)); - out.append("\n"); - - out.append(" preset_mode: "); - out.append("'").append(this->preset_mode).append("'"); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_LIGHT bool ListEntitiesLightResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 12: { @@ -2256,84 +1075,6 @@ void ListEntitiesLightResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->entity_category), false); ProtoSize::add_uint32_field(total_size, 2, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesLightResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesLightResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - for (const auto &it : this->supported_color_modes) { - out.append(" supported_color_modes: "); - out.append(proto_enum_to_string(it)); - out.append("\n"); - } - - out.append(" legacy_supports_brightness: "); - out.append(YESNO(this->legacy_supports_brightness)); - out.append("\n"); - - out.append(" legacy_supports_rgb: "); - out.append(YESNO(this->legacy_supports_rgb)); - out.append("\n"); - - out.append(" legacy_supports_white_value: "); - out.append(YESNO(this->legacy_supports_white_value)); - out.append("\n"); - - out.append(" legacy_supports_color_temperature: "); - out.append(YESNO(this->legacy_supports_color_temperature)); - out.append("\n"); - - out.append(" min_mireds: "); - sprintf(buffer, "%g", this->min_mireds); - out.append(buffer); - out.append("\n"); - - out.append(" max_mireds: "); - sprintf(buffer, "%g", this->max_mireds); - out.append(buffer); - out.append("\n"); - - for (const auto &it : this->effects) { - out.append(" effects: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool LightStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -2344,6 +1085,10 @@ bool LightStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { this->color_mode = value.as_enum(); return true; } + case 14: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -2418,6 +1163,7 @@ void LightStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_float(12, this->cold_white); buffer.encode_float(13, this->warm_white); buffer.encode_string(9, this->effect); + buffer.encode_uint32(14, this->device_id); } void LightStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); @@ -2433,75 +1179,8 @@ void LightStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->cold_white != 0.0f, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->warm_white != 0.0f, false); ProtoSize::add_string_field(total_size, 1, this->effect, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void LightStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("LightStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append(YESNO(this->state)); - out.append("\n"); - - out.append(" brightness: "); - sprintf(buffer, "%g", this->brightness); - out.append(buffer); - out.append("\n"); - - out.append(" color_mode: "); - out.append(proto_enum_to_string(this->color_mode)); - out.append("\n"); - - out.append(" color_brightness: "); - sprintf(buffer, "%g", this->color_brightness); - out.append(buffer); - out.append("\n"); - - out.append(" red: "); - sprintf(buffer, "%g", this->red); - out.append(buffer); - out.append("\n"); - - out.append(" green: "); - sprintf(buffer, "%g", this->green); - out.append(buffer); - out.append("\n"); - - out.append(" blue: "); - sprintf(buffer, "%g", this->blue); - out.append(buffer); - out.append("\n"); - - out.append(" white: "); - sprintf(buffer, "%g", this->white); - out.append(buffer); - out.append("\n"); - - out.append(" color_temperature: "); - sprintf(buffer, "%g", this->color_temperature); - out.append(buffer); - out.append("\n"); - - out.append(" cold_white: "); - sprintf(buffer, "%g", this->cold_white); - out.append(buffer); - out.append("\n"); - - out.append(" warm_white: "); - sprintf(buffer, "%g", this->warm_white); - out.append(buffer); - out.append("\n"); - - out.append(" effect: "); - out.append("'").append(this->effect).append("'"); - out.append("\n"); - out.append("}"); -} -#endif bool LightCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -2686,132 +1365,8 @@ void LightCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 2, this->has_effect, false); ProtoSize::add_string_field(total_size, 2, this->effect, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void LightCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("LightCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" has_state: "); - out.append(YESNO(this->has_state)); - out.append("\n"); - - out.append(" state: "); - out.append(YESNO(this->state)); - out.append("\n"); - - out.append(" has_brightness: "); - out.append(YESNO(this->has_brightness)); - out.append("\n"); - - out.append(" brightness: "); - sprintf(buffer, "%g", this->brightness); - out.append(buffer); - out.append("\n"); - - out.append(" has_color_mode: "); - out.append(YESNO(this->has_color_mode)); - out.append("\n"); - - out.append(" color_mode: "); - out.append(proto_enum_to_string(this->color_mode)); - out.append("\n"); - - out.append(" has_color_brightness: "); - out.append(YESNO(this->has_color_brightness)); - out.append("\n"); - - out.append(" color_brightness: "); - sprintf(buffer, "%g", this->color_brightness); - out.append(buffer); - out.append("\n"); - - out.append(" has_rgb: "); - out.append(YESNO(this->has_rgb)); - out.append("\n"); - - out.append(" red: "); - sprintf(buffer, "%g", this->red); - out.append(buffer); - out.append("\n"); - - out.append(" green: "); - sprintf(buffer, "%g", this->green); - out.append(buffer); - out.append("\n"); - - out.append(" blue: "); - sprintf(buffer, "%g", this->blue); - out.append(buffer); - out.append("\n"); - - out.append(" has_white: "); - out.append(YESNO(this->has_white)); - out.append("\n"); - - out.append(" white: "); - sprintf(buffer, "%g", this->white); - out.append(buffer); - out.append("\n"); - - out.append(" has_color_temperature: "); - out.append(YESNO(this->has_color_temperature)); - out.append("\n"); - - out.append(" color_temperature: "); - sprintf(buffer, "%g", this->color_temperature); - out.append(buffer); - out.append("\n"); - - out.append(" has_cold_white: "); - out.append(YESNO(this->has_cold_white)); - out.append("\n"); - - out.append(" cold_white: "); - sprintf(buffer, "%g", this->cold_white); - out.append(buffer); - out.append("\n"); - - out.append(" has_warm_white: "); - out.append(YESNO(this->has_warm_white)); - out.append("\n"); - - out.append(" warm_white: "); - sprintf(buffer, "%g", this->warm_white); - out.append(buffer); - out.append("\n"); - - out.append(" has_transition_length: "); - out.append(YESNO(this->has_transition_length)); - out.append("\n"); - - out.append(" transition_length: "); - sprintf(buffer, "%" PRIu32, this->transition_length); - out.append(buffer); - out.append("\n"); - - out.append(" has_flash_length: "); - out.append(YESNO(this->has_flash_length)); - out.append("\n"); - - out.append(" flash_length: "); - sprintf(buffer, "%" PRIu32, this->flash_length); - out.append(buffer); - out.append("\n"); - - out.append(" has_effect: "); - out.append(YESNO(this->has_effect)); - out.append("\n"); - - out.append(" effect: "); - out.append("'").append(this->effect).append("'"); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_SENSOR bool ListEntitiesSensorResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 7: { @@ -2918,77 +1473,16 @@ void ListEntitiesSensorResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->entity_category), false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesSensorResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesSensorResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" unit_of_measurement: "); - out.append("'").append(this->unit_of_measurement).append("'"); - out.append("\n"); - - out.append(" accuracy_decimals: "); - sprintf(buffer, "%" PRId32, this->accuracy_decimals); - out.append(buffer); - out.append("\n"); - - out.append(" force_update: "); - out.append(YESNO(this->force_update)); - out.append("\n"); - - out.append(" device_class: "); - out.append("'").append(this->device_class).append("'"); - out.append("\n"); - - out.append(" state_class: "); - out.append(proto_enum_to_string(this->state_class)); - out.append("\n"); - - out.append(" legacy_last_reset_type: "); - out.append(proto_enum_to_string(this->legacy_last_reset_type)); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool SensorStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 3: { this->missing_state = value.as_bool(); return true; } + case 4: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -3011,32 +1505,16 @@ void SensorStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_float(2, this->state); buffer.encode_bool(3, this->missing_state); + buffer.encode_uint32(4, this->device_id); } void SensorStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->state != 0.0f, false); ProtoSize::add_bool_field(total_size, 1, this->missing_state, false); -} -#ifdef HAS_PROTO_MESSAGE_DUMP -void SensorStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SensorStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - sprintf(buffer, "%g", this->state); - out.append(buffer); - out.append("\n"); - - out.append(" missing_state: "); - out.append(YESNO(this->missing_state)); - out.append("\n"); - out.append("}"); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } #endif +#ifdef USE_SWITCH bool ListEntitiesSwitchResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -3119,60 +1597,16 @@ void ListEntitiesSwitchResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->device_class, false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesSwitchResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesSwitchResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" assumed_state: "); - out.append(YESNO(this->assumed_state)); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_class: "); - out.append("'").append(this->device_class).append("'"); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool SwitchStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { this->state = value.as_bool(); return true; } + case 3: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -3190,26 +1624,13 @@ bool SwitchStateResponse::decode_32bit(uint32_t field_id, Proto32Bit value) { void SwitchStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_bool(2, this->state); + buffer.encode_uint32(3, this->device_id); } void SwitchStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_bool_field(total_size, 1, this->state, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SwitchStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SwitchStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append(YESNO(this->state)); - out.append("\n"); - out.append("}"); -} -#endif bool SwitchCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -3238,21 +1659,8 @@ void SwitchCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_bool_field(total_size, 1, this->state, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SwitchCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SwitchCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append(YESNO(this->state)); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_TEXT_SENSOR bool ListEntitiesTextSensorResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -3329,56 +1737,16 @@ void ListEntitiesTextSensorResponse::calculate_size(uint32_t &total_size) const ProtoSize::add_string_field(total_size, 1, this->device_class, false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesTextSensorResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesTextSensorResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_class: "); - out.append("'").append(this->device_class).append("'"); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool TextSensorStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 3: { this->missing_state = value.as_bool(); return true; } + case 4: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -3407,29 +1775,13 @@ void TextSensorStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_string(2, this->state); buffer.encode_bool(3, this->missing_state); + buffer.encode_uint32(4, this->device_id); } void TextSensorStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_string_field(total_size, 1, this->state, false); ProtoSize::add_bool_field(total_size, 1, this->missing_state, false); -} -#ifdef HAS_PROTO_MESSAGE_DUMP -void TextSensorStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("TextSensorStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append("'").append(this->state).append("'"); - out.append("\n"); - - out.append(" missing_state: "); - out.append(YESNO(this->missing_state)); - out.append("\n"); - out.append("}"); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } #endif bool SubscribeLogsRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { @@ -3454,20 +1806,6 @@ void SubscribeLogsRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->level), false); ProtoSize::add_bool_field(total_size, 1, this->dump_config, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SubscribeLogsRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SubscribeLogsRequest {\n"); - out.append(" level: "); - out.append(proto_enum_to_string(this->level)); - out.append("\n"); - - out.append(" dump_config: "); - out.append(YESNO(this->dump_config)); - out.append("\n"); - out.append("}"); -} -#endif bool SubscribeLogsResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -3502,24 +1840,7 @@ void SubscribeLogsResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->message, false); ProtoSize::add_bool_field(total_size, 1, this->send_failed, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SubscribeLogsResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SubscribeLogsResponse {\n"); - out.append(" level: "); - out.append(proto_enum_to_string(this->level)); - out.append("\n"); - - out.append(" message: "); - out.append(format_hex_pretty(this->message)); - out.append("\n"); - - out.append(" send_failed: "); - out.append(YESNO(this->send_failed)); - out.append("\n"); - out.append("}"); -} -#endif +#ifdef USE_API_NOISE bool NoiseEncryptionSetKeyRequest::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 1: { @@ -3536,16 +1857,6 @@ void NoiseEncryptionSetKeyRequest::encode(ProtoWriteBuffer buffer) const { void NoiseEncryptionSetKeyRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->key, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void NoiseEncryptionSetKeyRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("NoiseEncryptionSetKeyRequest {\n"); - out.append(" key: "); - out.append(format_hex_pretty(this->key)); - out.append("\n"); - out.append("}"); -} -#endif bool NoiseEncryptionSetKeyResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -3560,20 +1871,6 @@ void NoiseEncryptionSetKeyResponse::encode(ProtoWriteBuffer buffer) const { buff void NoiseEncryptionSetKeyResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->success, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void NoiseEncryptionSetKeyResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("NoiseEncryptionSetKeyResponse {\n"); - out.append(" success: "); - out.append(YESNO(this->success)); - out.append("\n"); - out.append("}"); -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void SubscribeHomeassistantServicesRequest::dump_to(std::string &out) const { - out.append("SubscribeHomeassistantServicesRequest {}"); -} #endif bool HomeassistantServiceMap::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { @@ -3597,20 +1894,6 @@ void HomeassistantServiceMap::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->key, false); ProtoSize::add_string_field(total_size, 1, this->value, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void HomeassistantServiceMap::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("HomeassistantServiceMap {\n"); - out.append(" key: "); - out.append("'").append(this->key).append("'"); - out.append("\n"); - - out.append(" value: "); - out.append("'").append(this->value).append("'"); - out.append("\n"); - out.append("}"); -} -#endif bool HomeassistantServiceResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 5: { @@ -3663,43 +1946,6 @@ void HomeassistantServiceResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_repeated_message(total_size, 1, this->variables); ProtoSize::add_bool_field(total_size, 1, this->is_event, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void HomeassistantServiceResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("HomeassistantServiceResponse {\n"); - out.append(" service: "); - out.append("'").append(this->service).append("'"); - out.append("\n"); - - for (const auto &it : this->data) { - out.append(" data: "); - it.dump_to(out); - out.append("\n"); - } - - for (const auto &it : this->data_template) { - out.append(" data_template: "); - it.dump_to(out); - out.append("\n"); - } - - for (const auto &it : this->variables) { - out.append(" variables: "); - it.dump_to(out); - out.append("\n"); - } - - out.append(" is_event: "); - out.append(YESNO(this->is_event)); - out.append("\n"); - out.append("}"); -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void SubscribeHomeAssistantStatesRequest::dump_to(std::string &out) const { - out.append("SubscribeHomeAssistantStatesRequest {}"); -} -#endif bool SubscribeHomeAssistantStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 3: { @@ -3734,24 +1980,6 @@ void SubscribeHomeAssistantStateResponse::calculate_size(uint32_t &total_size) c ProtoSize::add_string_field(total_size, 1, this->attribute, false); ProtoSize::add_bool_field(total_size, 1, this->once, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SubscribeHomeAssistantStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SubscribeHomeAssistantStateResponse {\n"); - out.append(" entity_id: "); - out.append("'").append(this->entity_id).append("'"); - out.append("\n"); - - out.append(" attribute: "); - out.append("'").append(this->attribute).append("'"); - out.append("\n"); - - out.append(" once: "); - out.append(YESNO(this->once)); - out.append("\n"); - out.append("}"); -} -#endif bool HomeAssistantStateResponse::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 1: { @@ -3780,27 +2008,6 @@ void HomeAssistantStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->state, false); ProtoSize::add_string_field(total_size, 1, this->attribute, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void HomeAssistantStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("HomeAssistantStateResponse {\n"); - out.append(" entity_id: "); - out.append("'").append(this->entity_id).append("'"); - out.append("\n"); - - out.append(" state: "); - out.append("'").append(this->state).append("'"); - out.append("\n"); - - out.append(" attribute: "); - out.append("'").append(this->attribute).append("'"); - out.append("\n"); - out.append("}"); -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void GetTimeRequest::dump_to(std::string &out) const { out.append("GetTimeRequest {}"); } -#endif bool GetTimeResponse::decode_32bit(uint32_t field_id, Proto32Bit value) { switch (field_id) { case 1: { @@ -3815,17 +2022,6 @@ void GetTimeResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixe void GetTimeResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->epoch_seconds != 0, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void GetTimeResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("GetTimeResponse {\n"); - out.append(" epoch_seconds: "); - sprintf(buffer, "%" PRIu32, this->epoch_seconds); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool ListEntitiesServicesArgument::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -3854,20 +2050,6 @@ void ListEntitiesServicesArgument::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->name, false); ProtoSize::add_enum_field(total_size, 1, static_cast(this->type), false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesServicesArgument::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesServicesArgument {\n"); - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" type: "); - out.append(proto_enum_to_string(this->type)); - out.append("\n"); - out.append("}"); -} -#endif bool ListEntitiesServicesResponse::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 1: { @@ -3904,27 +2086,6 @@ void ListEntitiesServicesResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_repeated_message(total_size, 1, this->args); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesServicesResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesServicesResponse {\n"); - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - for (const auto &it : this->args) { - out.append(" args: "); - it.dump_to(out); - out.append("\n"); - } - out.append("}"); -} -#endif bool ExecuteServiceArgument::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -4025,61 +2186,6 @@ void ExecuteServiceArgument::calculate_size(uint32_t &total_size) const { } } } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ExecuteServiceArgument::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ExecuteServiceArgument {\n"); - out.append(" bool_: "); - out.append(YESNO(this->bool_)); - out.append("\n"); - - out.append(" legacy_int: "); - sprintf(buffer, "%" PRId32, this->legacy_int); - out.append(buffer); - out.append("\n"); - - out.append(" float_: "); - sprintf(buffer, "%g", this->float_); - out.append(buffer); - out.append("\n"); - - out.append(" string_: "); - out.append("'").append(this->string_).append("'"); - out.append("\n"); - - out.append(" int_: "); - sprintf(buffer, "%" PRId32, this->int_); - out.append(buffer); - out.append("\n"); - - for (const auto it : this->bool_array) { - out.append(" bool_array: "); - out.append(YESNO(it)); - out.append("\n"); - } - - for (const auto &it : this->int_array) { - out.append(" int_array: "); - sprintf(buffer, "%" PRId32, it); - out.append(buffer); - out.append("\n"); - } - - for (const auto &it : this->float_array) { - out.append(" float_array: "); - sprintf(buffer, "%g", it); - out.append(buffer); - out.append("\n"); - } - - for (const auto &it : this->string_array) { - out.append(" string_array: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - out.append("}"); -} -#endif bool ExecuteServiceRequest::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 2: { @@ -4110,23 +2216,7 @@ void ExecuteServiceRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_repeated_message(total_size, 1, this->args); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ExecuteServiceRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ExecuteServiceRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - for (const auto &it : this->args) { - out.append(" args: "); - it.dump_to(out); - out.append("\n"); - } - out.append("}"); -} -#endif +#ifdef USE_CAMERA bool ListEntitiesCameraResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 5: { @@ -4197,46 +2287,6 @@ void ListEntitiesCameraResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->entity_category), false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesCameraResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesCameraResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool CameraImageResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 3: { @@ -4277,25 +2327,6 @@ void CameraImageResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->data, false); ProtoSize::add_bool_field(total_size, 1, this->done, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void CameraImageResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("CameraImageResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" data: "); - out.append(format_hex_pretty(this->data)); - out.append("\n"); - - out.append(" done: "); - out.append(YESNO(this->done)); - out.append("\n"); - out.append("}"); -} -#endif bool CameraImageRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -4318,20 +2349,8 @@ void CameraImageRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->single, false); ProtoSize::add_bool_field(total_size, 1, this->stream, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void CameraImageRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("CameraImageRequest {\n"); - out.append(" single: "); - out.append(YESNO(this->single)); - out.append("\n"); - - out.append(" stream: "); - out.append(YESNO(this->stream)); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_CLIMATE bool ListEntitiesClimateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 5: { @@ -4546,136 +2565,6 @@ void ListEntitiesClimateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 2, this->visual_max_humidity != 0.0f, false); ProtoSize::add_uint32_field(total_size, 2, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesClimateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesClimateResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" supports_current_temperature: "); - out.append(YESNO(this->supports_current_temperature)); - out.append("\n"); - - out.append(" supports_two_point_target_temperature: "); - out.append(YESNO(this->supports_two_point_target_temperature)); - out.append("\n"); - - for (const auto &it : this->supported_modes) { - out.append(" supported_modes: "); - out.append(proto_enum_to_string(it)); - out.append("\n"); - } - - out.append(" visual_min_temperature: "); - sprintf(buffer, "%g", this->visual_min_temperature); - out.append(buffer); - out.append("\n"); - - out.append(" visual_max_temperature: "); - sprintf(buffer, "%g", this->visual_max_temperature); - out.append(buffer); - out.append("\n"); - - out.append(" visual_target_temperature_step: "); - sprintf(buffer, "%g", this->visual_target_temperature_step); - out.append(buffer); - out.append("\n"); - - out.append(" legacy_supports_away: "); - out.append(YESNO(this->legacy_supports_away)); - out.append("\n"); - - out.append(" supports_action: "); - out.append(YESNO(this->supports_action)); - out.append("\n"); - - for (const auto &it : this->supported_fan_modes) { - out.append(" supported_fan_modes: "); - out.append(proto_enum_to_string(it)); - out.append("\n"); - } - - for (const auto &it : this->supported_swing_modes) { - out.append(" supported_swing_modes: "); - out.append(proto_enum_to_string(it)); - out.append("\n"); - } - - for (const auto &it : this->supported_custom_fan_modes) { - out.append(" supported_custom_fan_modes: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - - for (const auto &it : this->supported_presets) { - out.append(" supported_presets: "); - out.append(proto_enum_to_string(it)); - out.append("\n"); - } - - for (const auto &it : this->supported_custom_presets) { - out.append(" supported_custom_presets: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" visual_current_temperature_step: "); - sprintf(buffer, "%g", this->visual_current_temperature_step); - out.append(buffer); - out.append("\n"); - - out.append(" supports_current_humidity: "); - out.append(YESNO(this->supports_current_humidity)); - out.append("\n"); - - out.append(" supports_target_humidity: "); - out.append(YESNO(this->supports_target_humidity)); - out.append("\n"); - - out.append(" visual_min_humidity: "); - sprintf(buffer, "%g", this->visual_min_humidity); - out.append(buffer); - out.append("\n"); - - out.append(" visual_max_humidity: "); - sprintf(buffer, "%g", this->visual_max_humidity); - out.append(buffer); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool ClimateStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -4702,6 +2591,10 @@ bool ClimateStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { this->preset = value.as_enum(); return true; } + case 16: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -4770,6 +2663,7 @@ void ClimateStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_string(13, this->custom_preset); buffer.encode_float(14, this->current_humidity); buffer.encode_float(15, this->target_humidity); + buffer.encode_uint32(16, this->device_id); } void ClimateStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); @@ -4787,80 +2681,8 @@ void ClimateStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->custom_preset, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->current_humidity != 0.0f, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->target_humidity != 0.0f, false); + ProtoSize::add_uint32_field(total_size, 2, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ClimateStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ClimateStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" mode: "); - out.append(proto_enum_to_string(this->mode)); - out.append("\n"); - - out.append(" current_temperature: "); - sprintf(buffer, "%g", this->current_temperature); - out.append(buffer); - out.append("\n"); - - out.append(" target_temperature: "); - sprintf(buffer, "%g", this->target_temperature); - out.append(buffer); - out.append("\n"); - - out.append(" target_temperature_low: "); - sprintf(buffer, "%g", this->target_temperature_low); - out.append(buffer); - out.append("\n"); - - out.append(" target_temperature_high: "); - sprintf(buffer, "%g", this->target_temperature_high); - out.append(buffer); - out.append("\n"); - - out.append(" unused_legacy_away: "); - out.append(YESNO(this->unused_legacy_away)); - out.append("\n"); - - out.append(" action: "); - out.append(proto_enum_to_string(this->action)); - out.append("\n"); - - out.append(" fan_mode: "); - out.append(proto_enum_to_string(this->fan_mode)); - out.append("\n"); - - out.append(" swing_mode: "); - out.append(proto_enum_to_string(this->swing_mode)); - out.append("\n"); - - out.append(" custom_fan_mode: "); - out.append("'").append(this->custom_fan_mode).append("'"); - out.append("\n"); - - out.append(" preset: "); - out.append(proto_enum_to_string(this->preset)); - out.append("\n"); - - out.append(" custom_preset: "); - out.append("'").append(this->custom_preset).append("'"); - out.append("\n"); - - out.append(" current_humidity: "); - sprintf(buffer, "%g", this->current_humidity); - out.append(buffer); - out.append("\n"); - - out.append(" target_humidity: "); - sprintf(buffer, "%g", this->target_humidity); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool ClimateCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -5021,109 +2843,8 @@ void ClimateCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 2, this->has_target_humidity, false); ProtoSize::add_fixed_field<4>(total_size, 2, this->target_humidity != 0.0f, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ClimateCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ClimateCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" has_mode: "); - out.append(YESNO(this->has_mode)); - out.append("\n"); - - out.append(" mode: "); - out.append(proto_enum_to_string(this->mode)); - out.append("\n"); - - out.append(" has_target_temperature: "); - out.append(YESNO(this->has_target_temperature)); - out.append("\n"); - - out.append(" target_temperature: "); - sprintf(buffer, "%g", this->target_temperature); - out.append(buffer); - out.append("\n"); - - out.append(" has_target_temperature_low: "); - out.append(YESNO(this->has_target_temperature_low)); - out.append("\n"); - - out.append(" target_temperature_low: "); - sprintf(buffer, "%g", this->target_temperature_low); - out.append(buffer); - out.append("\n"); - - out.append(" has_target_temperature_high: "); - out.append(YESNO(this->has_target_temperature_high)); - out.append("\n"); - - out.append(" target_temperature_high: "); - sprintf(buffer, "%g", this->target_temperature_high); - out.append(buffer); - out.append("\n"); - - out.append(" unused_has_legacy_away: "); - out.append(YESNO(this->unused_has_legacy_away)); - out.append("\n"); - - out.append(" unused_legacy_away: "); - out.append(YESNO(this->unused_legacy_away)); - out.append("\n"); - - out.append(" has_fan_mode: "); - out.append(YESNO(this->has_fan_mode)); - out.append("\n"); - - out.append(" fan_mode: "); - out.append(proto_enum_to_string(this->fan_mode)); - out.append("\n"); - - out.append(" has_swing_mode: "); - out.append(YESNO(this->has_swing_mode)); - out.append("\n"); - - out.append(" swing_mode: "); - out.append(proto_enum_to_string(this->swing_mode)); - out.append("\n"); - - out.append(" has_custom_fan_mode: "); - out.append(YESNO(this->has_custom_fan_mode)); - out.append("\n"); - - out.append(" custom_fan_mode: "); - out.append("'").append(this->custom_fan_mode).append("'"); - out.append("\n"); - - out.append(" has_preset: "); - out.append(YESNO(this->has_preset)); - out.append("\n"); - - out.append(" preset: "); - out.append(proto_enum_to_string(this->preset)); - out.append("\n"); - - out.append(" has_custom_preset: "); - out.append(YESNO(this->has_custom_preset)); - out.append("\n"); - - out.append(" custom_preset: "); - out.append("'").append(this->custom_preset).append("'"); - out.append("\n"); - - out.append(" has_target_humidity: "); - out.append(YESNO(this->has_target_humidity)); - out.append("\n"); - - out.append(" target_humidity: "); - sprintf(buffer, "%g", this->target_humidity); - out.append(buffer); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_NUMBER bool ListEntitiesNumberResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 9: { @@ -5230,79 +2951,16 @@ void ListEntitiesNumberResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->device_class, false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesNumberResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesNumberResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" min_value: "); - sprintf(buffer, "%g", this->min_value); - out.append(buffer); - out.append("\n"); - - out.append(" max_value: "); - sprintf(buffer, "%g", this->max_value); - out.append(buffer); - out.append("\n"); - - out.append(" step: "); - sprintf(buffer, "%g", this->step); - out.append(buffer); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" unit_of_measurement: "); - out.append("'").append(this->unit_of_measurement).append("'"); - out.append("\n"); - - out.append(" mode: "); - out.append(proto_enum_to_string(this->mode)); - out.append("\n"); - - out.append(" device_class: "); - out.append("'").append(this->device_class).append("'"); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool NumberStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 3: { this->missing_state = value.as_bool(); return true; } + case 4: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -5325,32 +2983,14 @@ void NumberStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_float(2, this->state); buffer.encode_bool(3, this->missing_state); + buffer.encode_uint32(4, this->device_id); } void NumberStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->state != 0.0f, false); ProtoSize::add_bool_field(total_size, 1, this->missing_state, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void NumberStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("NumberStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - sprintf(buffer, "%g", this->state); - out.append(buffer); - out.append("\n"); - - out.append(" missing_state: "); - out.append(YESNO(this->missing_state)); - out.append("\n"); - out.append("}"); -} -#endif bool NumberCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) { switch (field_id) { case 1: { @@ -5373,22 +3013,8 @@ void NumberCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->state != 0.0f, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void NumberCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("NumberCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - sprintf(buffer, "%g", this->state); - out.append(buffer); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_SELECT bool ListEntitiesSelectResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 7: { @@ -5471,58 +3097,16 @@ void ListEntitiesSelectResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->entity_category), false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesSelectResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesSelectResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - for (const auto &it : this->options) { - out.append(" options: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool SelectStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 3: { this->missing_state = value.as_bool(); return true; } + case 4: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -5551,31 +3135,14 @@ void SelectStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_string(2, this->state); buffer.encode_bool(3, this->missing_state); + buffer.encode_uint32(4, this->device_id); } void SelectStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_string_field(total_size, 1, this->state, false); ProtoSize::add_bool_field(total_size, 1, this->missing_state, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SelectStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SelectStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append("'").append(this->state).append("'"); - out.append("\n"); - - out.append(" missing_state: "); - out.append(YESNO(this->missing_state)); - out.append("\n"); - out.append("}"); -} -#endif bool SelectCommandRequest::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 2: { @@ -5604,21 +3171,8 @@ void SelectCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_string_field(total_size, 1, this->state, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SelectCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SelectCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append("'").append(this->state).append("'"); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_SIREN bool ListEntitiesSirenResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -5713,66 +3267,16 @@ void ListEntitiesSirenResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->entity_category), false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesSirenResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesSirenResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - for (const auto &it : this->tones) { - out.append(" tones: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - - out.append(" supports_duration: "); - out.append(YESNO(this->supports_duration)); - out.append("\n"); - - out.append(" supports_volume: "); - out.append(YESNO(this->supports_volume)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool SirenStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { this->state = value.as_bool(); return true; } + case 3: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -5790,26 +3294,13 @@ bool SirenStateResponse::decode_32bit(uint32_t field_id, Proto32Bit value) { void SirenStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_bool(2, this->state); + buffer.encode_uint32(3, this->device_id); } void SirenStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_bool_field(total_size, 1, this->state, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SirenStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SirenStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append(YESNO(this->state)); - out.append("\n"); - out.append("}"); -} -#endif bool SirenCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -5886,51 +3377,8 @@ void SirenCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->has_volume, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->volume != 0.0f, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SirenCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SirenCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" has_state: "); - out.append(YESNO(this->has_state)); - out.append("\n"); - - out.append(" state: "); - out.append(YESNO(this->state)); - out.append("\n"); - - out.append(" has_tone: "); - out.append(YESNO(this->has_tone)); - out.append("\n"); - - out.append(" tone: "); - out.append("'").append(this->tone).append("'"); - out.append("\n"); - - out.append(" has_duration: "); - out.append(YESNO(this->has_duration)); - out.append("\n"); - - out.append(" duration: "); - sprintf(buffer, "%" PRIu32, this->duration); - out.append(buffer); - out.append("\n"); - - out.append(" has_volume: "); - out.append(YESNO(this->has_volume)); - out.append("\n"); - - out.append(" volume: "); - sprintf(buffer, "%g", this->volume); - out.append(buffer); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_LOCK bool ListEntitiesLockResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -6025,68 +3473,16 @@ void ListEntitiesLockResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->code_format, false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesLockResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesLockResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" assumed_state: "); - out.append(YESNO(this->assumed_state)); - out.append("\n"); - - out.append(" supports_open: "); - out.append(YESNO(this->supports_open)); - out.append("\n"); - - out.append(" requires_code: "); - out.append(YESNO(this->requires_code)); - out.append("\n"); - - out.append(" code_format: "); - out.append("'").append(this->code_format).append("'"); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool LockStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { this->state = value.as_enum(); return true; } + case 3: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -6104,26 +3500,13 @@ bool LockStateResponse::decode_32bit(uint32_t field_id, Proto32Bit value) { void LockStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_enum(2, this->state); + buffer.encode_uint32(3, this->device_id); } void LockStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_enum_field(total_size, 1, static_cast(this->state), false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void LockStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("LockStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append(proto_enum_to_string(this->state)); - out.append("\n"); - out.append("}"); -} -#endif bool LockCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -6170,29 +3553,8 @@ void LockCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->has_code, false); ProtoSize::add_string_field(total_size, 1, this->code, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void LockCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("LockCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" command: "); - out.append(proto_enum_to_string(this->command)); - out.append("\n"); - - out.append(" has_code: "); - out.append(YESNO(this->has_code)); - out.append("\n"); - - out.append(" code: "); - out.append("'").append(this->code).append("'"); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_BUTTON bool ListEntitiesButtonResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -6269,50 +3631,6 @@ void ListEntitiesButtonResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->device_class, false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesButtonResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesButtonResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_class: "); - out.append("'").append(this->device_class).append("'"); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool ButtonCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) { switch (field_id) { case 1: { @@ -6327,17 +3645,8 @@ void ButtonCommandRequest::encode(ProtoWriteBuffer buffer) const { buffer.encode void ButtonCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ButtonCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ButtonCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_MEDIA_PLAYER bool MediaPlayerSupportedFormat::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -6384,35 +3693,6 @@ void MediaPlayerSupportedFormat::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->purpose), false); ProtoSize::add_uint32_field(total_size, 1, this->sample_bytes, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void MediaPlayerSupportedFormat::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("MediaPlayerSupportedFormat {\n"); - out.append(" format: "); - out.append("'").append(this->format).append("'"); - out.append("\n"); - - out.append(" sample_rate: "); - sprintf(buffer, "%" PRIu32, this->sample_rate); - out.append(buffer); - out.append("\n"); - - out.append(" num_channels: "); - sprintf(buffer, "%" PRIu32, this->num_channels); - out.append(buffer); - out.append("\n"); - - out.append(" purpose: "); - out.append(proto_enum_to_string(this->purpose)); - out.append("\n"); - - out.append(" sample_bytes: "); - sprintf(buffer, "%" PRIu32, this->sample_bytes); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool ListEntitiesMediaPlayerResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -6497,56 +3777,6 @@ void ListEntitiesMediaPlayerResponse::calculate_size(uint32_t &total_size) const ProtoSize::add_repeated_message(total_size, 1, this->supported_formats); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesMediaPlayerResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesMediaPlayerResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" supports_pause: "); - out.append(YESNO(this->supports_pause)); - out.append("\n"); - - for (const auto &it : this->supported_formats) { - out.append(" supported_formats: "); - it.dump_to(out); - out.append("\n"); - } - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool MediaPlayerStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -6557,6 +3787,10 @@ bool MediaPlayerStateResponse::decode_varint(uint32_t field_id, ProtoVarInt valu this->muted = value.as_bool(); return true; } + case 5: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -6580,37 +3814,15 @@ void MediaPlayerStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_enum(2, this->state); buffer.encode_float(3, this->volume); buffer.encode_bool(4, this->muted); + buffer.encode_uint32(5, this->device_id); } void MediaPlayerStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_enum_field(total_size, 1, static_cast(this->state), false); ProtoSize::add_fixed_field<4>(total_size, 1, this->volume != 0.0f, false); ProtoSize::add_bool_field(total_size, 1, this->muted, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void MediaPlayerStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("MediaPlayerStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append(proto_enum_to_string(this->state)); - out.append("\n"); - - out.append(" volume: "); - sprintf(buffer, "%g", this->volume); - out.append(buffer); - out.append("\n"); - - out.append(" muted: "); - out.append(YESNO(this->muted)); - out.append("\n"); - out.append("}"); -} -#endif bool MediaPlayerCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -6687,50 +3899,8 @@ void MediaPlayerCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->has_announcement, false); ProtoSize::add_bool_field(total_size, 1, this->announcement, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void MediaPlayerCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("MediaPlayerCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" has_command: "); - out.append(YESNO(this->has_command)); - out.append("\n"); - - out.append(" command: "); - out.append(proto_enum_to_string(this->command)); - out.append("\n"); - - out.append(" has_volume: "); - out.append(YESNO(this->has_volume)); - out.append("\n"); - - out.append(" volume: "); - sprintf(buffer, "%g", this->volume); - out.append(buffer); - out.append("\n"); - - out.append(" has_media_url: "); - out.append(YESNO(this->has_media_url)); - out.append("\n"); - - out.append(" media_url: "); - out.append("'").append(this->media_url).append("'"); - out.append("\n"); - - out.append(" has_announcement: "); - out.append(YESNO(this->has_announcement)); - out.append("\n"); - - out.append(" announcement: "); - out.append(YESNO(this->announcement)); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_BLUETOOTH_PROXY bool SubscribeBluetoothLEAdvertisementsRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -6747,17 +3917,6 @@ void SubscribeBluetoothLEAdvertisementsRequest::encode(ProtoWriteBuffer buffer) void SubscribeBluetoothLEAdvertisementsRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->flags, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SubscribeBluetoothLEAdvertisementsRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SubscribeBluetoothLEAdvertisementsRequest {\n"); - out.append(" flags: "); - sprintf(buffer, "%" PRIu32, this->flags); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothServiceData::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -6798,27 +3957,6 @@ void BluetoothServiceData::calculate_size(uint32_t &total_size) const { } ProtoSize::add_string_field(total_size, 1, this->data, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothServiceData::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothServiceData {\n"); - out.append(" uuid: "); - out.append("'").append(this->uuid).append("'"); - out.append("\n"); - - for (const auto &it : this->legacy_data) { - out.append(" legacy_data: "); - sprintf(buffer, "%" PRIu32, it); - out.append(buffer); - out.append("\n"); - } - - out.append(" data: "); - out.append(format_hex_pretty(this->data)); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothLEAdvertisementResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -6887,49 +4025,6 @@ void BluetoothLEAdvertisementResponse::calculate_size(uint32_t &total_size) cons ProtoSize::add_repeated_message(total_size, 1, this->manufacturer_data); ProtoSize::add_uint32_field(total_size, 1, this->address_type, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothLEAdvertisementResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothLEAdvertisementResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append(format_hex_pretty(this->name)); - out.append("\n"); - - out.append(" rssi: "); - sprintf(buffer, "%" PRId32, this->rssi); - out.append(buffer); - out.append("\n"); - - for (const auto &it : this->service_uuids) { - out.append(" service_uuids: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - - for (const auto &it : this->service_data) { - out.append(" service_data: "); - it.dump_to(out); - out.append("\n"); - } - - for (const auto &it : this->manufacturer_data) { - out.append(" manufacturer_data: "); - it.dump_to(out); - out.append("\n"); - } - - out.append(" address_type: "); - sprintf(buffer, "%" PRIu32, this->address_type); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothLERawAdvertisement::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -6970,31 +4065,6 @@ void BluetoothLERawAdvertisement::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->address_type, false); ProtoSize::add_string_field(total_size, 1, this->data, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothLERawAdvertisement::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothLERawAdvertisement {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" rssi: "); - sprintf(buffer, "%" PRId32, this->rssi); - out.append(buffer); - out.append("\n"); - - out.append(" address_type: "); - sprintf(buffer, "%" PRIu32, this->address_type); - out.append(buffer); - out.append("\n"); - - out.append(" data: "); - out.append(format_hex_pretty(this->data)); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothLERawAdvertisementsResponse::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 1: { @@ -7013,18 +4083,6 @@ void BluetoothLERawAdvertisementsResponse::encode(ProtoWriteBuffer buffer) const void BluetoothLERawAdvertisementsResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_repeated_message(total_size, 1, this->advertisements); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothLERawAdvertisementsResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothLERawAdvertisementsResponse {\n"); - for (const auto &it : this->advertisements) { - out.append(" advertisements: "); - it.dump_to(out); - out.append("\n"); - } - out.append("}"); -} -#endif bool BluetoothDeviceRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7059,30 +4117,6 @@ void BluetoothDeviceRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->has_address_type, false); ProtoSize::add_uint32_field(total_size, 1, this->address_type, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothDeviceRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothDeviceRequest {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" request_type: "); - out.append(proto_enum_to_string(this->request_type)); - out.append("\n"); - - out.append(" has_address_type: "); - out.append(YESNO(this->has_address_type)); - out.append("\n"); - - out.append(" address_type: "); - sprintf(buffer, "%" PRIu32, this->address_type); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothDeviceConnectionResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7117,31 +4151,6 @@ void BluetoothDeviceConnectionResponse::calculate_size(uint32_t &total_size) con ProtoSize::add_uint32_field(total_size, 1, this->mtu, false); ProtoSize::add_int32_field(total_size, 1, this->error, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothDeviceConnectionResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothDeviceConnectionResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" connected: "); - out.append(YESNO(this->connected)); - out.append("\n"); - - out.append(" mtu: "); - sprintf(buffer, "%" PRIu32, this->mtu); - out.append(buffer); - out.append("\n"); - - out.append(" error: "); - sprintf(buffer, "%" PRId32, this->error); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTGetServicesRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7156,17 +4165,6 @@ void BluetoothGATTGetServicesRequest::encode(ProtoWriteBuffer buffer) const { bu void BluetoothGATTGetServicesRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint64_field(total_size, 1, this->address, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTGetServicesRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTGetServicesRequest {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTDescriptor::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7195,24 +4193,6 @@ void BluetoothGATTDescriptor::calculate_size(uint32_t &total_size) const { } ProtoSize::add_uint32_field(total_size, 1, this->handle, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTDescriptor::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTDescriptor {\n"); - for (const auto &it : this->uuid) { - out.append(" uuid: "); - sprintf(buffer, "%llu", it); - out.append(buffer); - out.append("\n"); - } - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTCharacteristic::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7261,35 +4241,6 @@ void BluetoothGATTCharacteristic::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->properties, false); ProtoSize::add_repeated_message(total_size, 1, this->descriptors); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTCharacteristic::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTCharacteristic {\n"); - for (const auto &it : this->uuid) { - out.append(" uuid: "); - sprintf(buffer, "%llu", it); - out.append(buffer); - out.append("\n"); - } - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - - out.append(" properties: "); - sprintf(buffer, "%" PRIu32, this->properties); - out.append(buffer); - out.append("\n"); - - for (const auto &it : this->descriptors) { - out.append(" descriptors: "); - it.dump_to(out); - out.append("\n"); - } - out.append("}"); -} -#endif bool BluetoothGATTService::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7332,30 +4283,6 @@ void BluetoothGATTService::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->handle, false); ProtoSize::add_repeated_message(total_size, 1, this->characteristics); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTService::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTService {\n"); - for (const auto &it : this->uuid) { - out.append(" uuid: "); - sprintf(buffer, "%llu", it); - out.append(buffer); - out.append("\n"); - } - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - - for (const auto &it : this->characteristics) { - out.append(" characteristics: "); - it.dump_to(out); - out.append("\n"); - } - out.append("}"); -} -#endif bool BluetoothGATTGetServicesResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7386,23 +4313,6 @@ void BluetoothGATTGetServicesResponse::calculate_size(uint32_t &total_size) cons ProtoSize::add_uint64_field(total_size, 1, this->address, false); ProtoSize::add_repeated_message(total_size, 1, this->services); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTGetServicesResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTGetServicesResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - for (const auto &it : this->services) { - out.append(" services: "); - it.dump_to(out); - out.append("\n"); - } - out.append("}"); -} -#endif bool BluetoothGATTGetServicesDoneResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7419,17 +4329,6 @@ void BluetoothGATTGetServicesDoneResponse::encode(ProtoWriteBuffer buffer) const void BluetoothGATTGetServicesDoneResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint64_field(total_size, 1, this->address, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTGetServicesDoneResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTGetServicesDoneResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTReadRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7452,22 +4351,6 @@ void BluetoothGATTReadRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint64_field(total_size, 1, this->address, false); ProtoSize::add_uint32_field(total_size, 1, this->handle, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTReadRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTReadRequest {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTReadResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7502,26 +4385,6 @@ void BluetoothGATTReadResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->handle, false); ProtoSize::add_string_field(total_size, 1, this->data, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTReadResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTReadResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - - out.append(" data: "); - out.append(format_hex_pretty(this->data)); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTWriteRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7562,30 +4425,6 @@ void BluetoothGATTWriteRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->response, false); ProtoSize::add_string_field(total_size, 1, this->data, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTWriteRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTWriteRequest {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - - out.append(" response: "); - out.append(YESNO(this->response)); - out.append("\n"); - - out.append(" data: "); - out.append(format_hex_pretty(this->data)); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTReadDescriptorRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7608,22 +4447,6 @@ void BluetoothGATTReadDescriptorRequest::calculate_size(uint32_t &total_size) co ProtoSize::add_uint64_field(total_size, 1, this->address, false); ProtoSize::add_uint32_field(total_size, 1, this->handle, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTReadDescriptorRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTReadDescriptorRequest {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTWriteDescriptorRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7658,26 +4481,6 @@ void BluetoothGATTWriteDescriptorRequest::calculate_size(uint32_t &total_size) c ProtoSize::add_uint32_field(total_size, 1, this->handle, false); ProtoSize::add_string_field(total_size, 1, this->data, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTWriteDescriptorRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTWriteDescriptorRequest {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - - out.append(" data: "); - out.append(format_hex_pretty(this->data)); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTNotifyRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7706,26 +4509,6 @@ void BluetoothGATTNotifyRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->handle, false); ProtoSize::add_bool_field(total_size, 1, this->enable, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTNotifyRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTNotifyRequest {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - - out.append(" enable: "); - out.append(YESNO(this->enable)); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTNotifyDataResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7760,31 +4543,6 @@ void BluetoothGATTNotifyDataResponse::calculate_size(uint32_t &total_size) const ProtoSize::add_uint32_field(total_size, 1, this->handle, false); ProtoSize::add_string_field(total_size, 1, this->data, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTNotifyDataResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTNotifyDataResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - - out.append(" data: "); - out.append(format_hex_pretty(this->data)); - out.append("\n"); - out.append("}"); -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void SubscribeBluetoothConnectionsFreeRequest::dump_to(std::string &out) const { - out.append("SubscribeBluetoothConnectionsFreeRequest {}"); -} -#endif bool BluetoothConnectionsFreeResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7819,29 +4577,6 @@ void BluetoothConnectionsFreeResponse::calculate_size(uint32_t &total_size) cons } } } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothConnectionsFreeResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothConnectionsFreeResponse {\n"); - out.append(" free: "); - sprintf(buffer, "%" PRIu32, this->free); - out.append(buffer); - out.append("\n"); - - out.append(" limit: "); - sprintf(buffer, "%" PRIu32, this->limit); - out.append(buffer); - out.append("\n"); - - for (const auto &it : this->allocated) { - out.append(" allocated: "); - sprintf(buffer, "%llu", it); - out.append(buffer); - out.append("\n"); - } - out.append("}"); -} -#endif bool BluetoothGATTErrorResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7870,27 +4605,6 @@ void BluetoothGATTErrorResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->handle, false); ProtoSize::add_int32_field(total_size, 1, this->error, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTErrorResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTErrorResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - - out.append(" error: "); - sprintf(buffer, "%" PRId32, this->error); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTWriteResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7913,22 +4627,6 @@ void BluetoothGATTWriteResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint64_field(total_size, 1, this->address, false); ProtoSize::add_uint32_field(total_size, 1, this->handle, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTWriteResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTWriteResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothGATTNotifyResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7951,22 +4649,6 @@ void BluetoothGATTNotifyResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint64_field(total_size, 1, this->address, false); ProtoSize::add_uint32_field(total_size, 1, this->handle, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothGATTNotifyResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothGATTNotifyResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" handle: "); - sprintf(buffer, "%" PRIu32, this->handle); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothDevicePairingResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -7995,26 +4677,6 @@ void BluetoothDevicePairingResponse::calculate_size(uint32_t &total_size) const ProtoSize::add_bool_field(total_size, 1, this->paired, false); ProtoSize::add_int32_field(total_size, 1, this->error, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothDevicePairingResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothDevicePairingResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" paired: "); - out.append(YESNO(this->paired)); - out.append("\n"); - - out.append(" error: "); - sprintf(buffer, "%" PRId32, this->error); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothDeviceUnpairingResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8043,31 +4705,6 @@ void BluetoothDeviceUnpairingResponse::calculate_size(uint32_t &total_size) cons ProtoSize::add_bool_field(total_size, 1, this->success, false); ProtoSize::add_int32_field(total_size, 1, this->error, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothDeviceUnpairingResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothDeviceUnpairingResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" success: "); - out.append(YESNO(this->success)); - out.append("\n"); - - out.append(" error: "); - sprintf(buffer, "%" PRId32, this->error); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void UnsubscribeBluetoothLEAdvertisementsRequest::dump_to(std::string &out) const { - out.append("UnsubscribeBluetoothLEAdvertisementsRequest {}"); -} -#endif bool BluetoothDeviceClearCacheResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8096,26 +4733,6 @@ void BluetoothDeviceClearCacheResponse::calculate_size(uint32_t &total_size) con ProtoSize::add_bool_field(total_size, 1, this->success, false); ProtoSize::add_int32_field(total_size, 1, this->error, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothDeviceClearCacheResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothDeviceClearCacheResponse {\n"); - out.append(" address: "); - sprintf(buffer, "%llu", this->address); - out.append(buffer); - out.append("\n"); - - out.append(" success: "); - out.append(YESNO(this->success)); - out.append("\n"); - - out.append(" error: "); - sprintf(buffer, "%" PRId32, this->error); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothScannerStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8138,20 +4755,6 @@ void BluetoothScannerStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->state), false); ProtoSize::add_enum_field(total_size, 1, static_cast(this->mode), false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothScannerStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothScannerStateResponse {\n"); - out.append(" state: "); - out.append(proto_enum_to_string(this->state)); - out.append("\n"); - - out.append(" mode: "); - out.append(proto_enum_to_string(this->mode)); - out.append("\n"); - out.append("}"); -} -#endif bool BluetoothScannerSetModeRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8168,16 +4771,8 @@ void BluetoothScannerSetModeRequest::encode(ProtoWriteBuffer buffer) const { void BluetoothScannerSetModeRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->mode), false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void BluetoothScannerSetModeRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("BluetoothScannerSetModeRequest {\n"); - out.append(" mode: "); - out.append(proto_enum_to_string(this->mode)); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_VOICE_ASSISTANT bool SubscribeVoiceAssistantRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8200,21 +4795,6 @@ void SubscribeVoiceAssistantRequest::calculate_size(uint32_t &total_size) const ProtoSize::add_bool_field(total_size, 1, this->subscribe, false); ProtoSize::add_uint32_field(total_size, 1, this->flags, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void SubscribeVoiceAssistantRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("SubscribeVoiceAssistantRequest {\n"); - out.append(" subscribe: "); - out.append(YESNO(this->subscribe)); - out.append("\n"); - - out.append(" flags: "); - sprintf(buffer, "%" PRIu32, this->flags); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool VoiceAssistantAudioSettings::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8249,27 +4829,6 @@ void VoiceAssistantAudioSettings::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->auto_gain, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->volume_multiplier != 0.0f, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantAudioSettings::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantAudioSettings {\n"); - out.append(" noise_suppression_level: "); - sprintf(buffer, "%" PRIu32, this->noise_suppression_level); - out.append(buffer); - out.append("\n"); - - out.append(" auto_gain: "); - sprintf(buffer, "%" PRIu32, this->auto_gain); - out.append(buffer); - out.append("\n"); - - out.append(" volume_multiplier: "); - sprintf(buffer, "%g", this->volume_multiplier); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool VoiceAssistantRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8316,33 +4875,6 @@ void VoiceAssistantRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_message_object(total_size, 1, this->audio_settings, false); ProtoSize::add_string_field(total_size, 1, this->wake_word_phrase, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantRequest {\n"); - out.append(" start: "); - out.append(YESNO(this->start)); - out.append("\n"); - - out.append(" conversation_id: "); - out.append("'").append(this->conversation_id).append("'"); - out.append("\n"); - - out.append(" flags: "); - sprintf(buffer, "%" PRIu32, this->flags); - out.append(buffer); - out.append("\n"); - - out.append(" audio_settings: "); - this->audio_settings.dump_to(out); - out.append("\n"); - - out.append(" wake_word_phrase: "); - out.append("'").append(this->wake_word_phrase).append("'"); - out.append("\n"); - out.append("}"); -} -#endif bool VoiceAssistantResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8365,21 +4897,6 @@ void VoiceAssistantResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->port, false); ProtoSize::add_bool_field(total_size, 1, this->error, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantResponse {\n"); - out.append(" port: "); - sprintf(buffer, "%" PRIu32, this->port); - out.append(buffer); - out.append("\n"); - - out.append(" error: "); - out.append(YESNO(this->error)); - out.append("\n"); - out.append("}"); -} -#endif bool VoiceAssistantEventData::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 1: { @@ -8402,20 +4919,6 @@ void VoiceAssistantEventData::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->name, false); ProtoSize::add_string_field(total_size, 1, this->value, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantEventData::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantEventData {\n"); - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" value: "); - out.append("'").append(this->value).append("'"); - out.append("\n"); - out.append("}"); -} -#endif bool VoiceAssistantEventResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8446,22 +4949,6 @@ void VoiceAssistantEventResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->event_type), false); ProtoSize::add_repeated_message(total_size, 1, this->data); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantEventResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantEventResponse {\n"); - out.append(" event_type: "); - out.append(proto_enum_to_string(this->event_type)); - out.append("\n"); - - for (const auto &it : this->data) { - out.append(" data: "); - it.dump_to(out); - out.append("\n"); - } - out.append("}"); -} -#endif bool VoiceAssistantAudio::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -8490,20 +4977,6 @@ void VoiceAssistantAudio::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->data, false); ProtoSize::add_bool_field(total_size, 1, this->end, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantAudio::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantAudio {\n"); - out.append(" data: "); - out.append(format_hex_pretty(this->data)); - out.append("\n"); - - out.append(" end: "); - out.append(YESNO(this->end)); - out.append("\n"); - out.append("}"); -} -#endif bool VoiceAssistantTimerEventResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8556,38 +5029,6 @@ void VoiceAssistantTimerEventResponse::calculate_size(uint32_t &total_size) cons ProtoSize::add_uint32_field(total_size, 1, this->seconds_left, false); ProtoSize::add_bool_field(total_size, 1, this->is_active, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantTimerEventResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantTimerEventResponse {\n"); - out.append(" event_type: "); - out.append(proto_enum_to_string(this->event_type)); - out.append("\n"); - - out.append(" timer_id: "); - out.append("'").append(this->timer_id).append("'"); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" total_seconds: "); - sprintf(buffer, "%" PRIu32, this->total_seconds); - out.append(buffer); - out.append("\n"); - - out.append(" seconds_left: "); - sprintf(buffer, "%" PRIu32, this->seconds_left); - out.append(buffer); - out.append("\n"); - - out.append(" is_active: "); - out.append(YESNO(this->is_active)); - out.append("\n"); - out.append("}"); -} -#endif bool VoiceAssistantAnnounceRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 4: { @@ -8628,28 +5069,6 @@ void VoiceAssistantAnnounceRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->preannounce_media_id, false); ProtoSize::add_bool_field(total_size, 1, this->start_conversation, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantAnnounceRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantAnnounceRequest {\n"); - out.append(" media_id: "); - out.append("'").append(this->media_id).append("'"); - out.append("\n"); - - out.append(" text: "); - out.append("'").append(this->text).append("'"); - out.append("\n"); - - out.append(" preannounce_media_id: "); - out.append("'").append(this->preannounce_media_id).append("'"); - out.append("\n"); - - out.append(" start_conversation: "); - out.append(YESNO(this->start_conversation)); - out.append("\n"); - out.append("}"); -} -#endif bool VoiceAssistantAnnounceFinished::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 1: { @@ -8664,16 +5083,6 @@ void VoiceAssistantAnnounceFinished::encode(ProtoWriteBuffer buffer) const { buf void VoiceAssistantAnnounceFinished::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->success, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantAnnounceFinished::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantAnnounceFinished {\n"); - out.append(" success: "); - out.append(YESNO(this->success)); - out.append("\n"); - out.append("}"); -} -#endif bool VoiceAssistantWakeWord::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 1: { @@ -8708,31 +5117,6 @@ void VoiceAssistantWakeWord::calculate_size(uint32_t &total_size) const { } } } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantWakeWord::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantWakeWord {\n"); - out.append(" id: "); - out.append("'").append(this->id).append("'"); - out.append("\n"); - - out.append(" wake_word: "); - out.append("'").append(this->wake_word).append("'"); - out.append("\n"); - - for (const auto &it : this->trained_languages) { - out.append(" trained_languages: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - out.append("}"); -} -#endif -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantConfigurationRequest::dump_to(std::string &out) const { - out.append("VoiceAssistantConfigurationRequest {}"); -} -#endif bool VoiceAssistantConfigurationResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 3: { @@ -8775,29 +5159,6 @@ void VoiceAssistantConfigurationResponse::calculate_size(uint32_t &total_size) c } ProtoSize::add_uint32_field(total_size, 1, this->max_active_wake_words, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantConfigurationResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantConfigurationResponse {\n"); - for (const auto &it : this->available_wake_words) { - out.append(" available_wake_words: "); - it.dump_to(out); - out.append("\n"); - } - - for (const auto &it : this->active_wake_words) { - out.append(" active_wake_words: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - - out.append(" max_active_wake_words: "); - sprintf(buffer, "%" PRIu32, this->max_active_wake_words); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool VoiceAssistantSetConfiguration::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 1: { @@ -8820,18 +5181,8 @@ void VoiceAssistantSetConfiguration::calculate_size(uint32_t &total_size) const } } } -#ifdef HAS_PROTO_MESSAGE_DUMP -void VoiceAssistantSetConfiguration::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("VoiceAssistantSetConfiguration {\n"); - for (const auto &it : this->active_wake_words) { - out.append(" active_wake_words: "); - out.append("'").append(it).append("'"); - out.append("\n"); - } - out.append("}"); -} #endif +#ifdef USE_ALARM_CONTROL_PANEL bool ListEntitiesAlarmControlPanelResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -8920,65 +5271,16 @@ void ListEntitiesAlarmControlPanelResponse::calculate_size(uint32_t &total_size) ProtoSize::add_bool_field(total_size, 1, this->requires_code_to_arm, false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesAlarmControlPanelResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesAlarmControlPanelResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" supported_features: "); - sprintf(buffer, "%" PRIu32, this->supported_features); - out.append(buffer); - out.append("\n"); - - out.append(" requires_code: "); - out.append(YESNO(this->requires_code)); - out.append("\n"); - - out.append(" requires_code_to_arm: "); - out.append(YESNO(this->requires_code_to_arm)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool AlarmControlPanelStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { this->state = value.as_enum(); return true; } + case 3: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -8996,26 +5298,13 @@ bool AlarmControlPanelStateResponse::decode_32bit(uint32_t field_id, Proto32Bit void AlarmControlPanelStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_enum(2, this->state); + buffer.encode_uint32(3, this->device_id); } void AlarmControlPanelStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_enum_field(total_size, 1, static_cast(this->state), false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void AlarmControlPanelStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("AlarmControlPanelStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append(proto_enum_to_string(this->state)); - out.append("\n"); - out.append("}"); -} -#endif bool AlarmControlPanelCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -9056,25 +5345,8 @@ void AlarmControlPanelCommandRequest::calculate_size(uint32_t &total_size) const ProtoSize::add_enum_field(total_size, 1, static_cast(this->command), false); ProtoSize::add_string_field(total_size, 1, this->code, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void AlarmControlPanelCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("AlarmControlPanelCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" command: "); - out.append(proto_enum_to_string(this->command)); - out.append("\n"); - - out.append(" code: "); - out.append("'").append(this->code).append("'"); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_TEXT bool ListEntitiesTextResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -9169,70 +5441,16 @@ void ListEntitiesTextResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->mode), false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesTextResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesTextResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" min_length: "); - sprintf(buffer, "%" PRIu32, this->min_length); - out.append(buffer); - out.append("\n"); - - out.append(" max_length: "); - sprintf(buffer, "%" PRIu32, this->max_length); - out.append(buffer); - out.append("\n"); - - out.append(" pattern: "); - out.append("'").append(this->pattern).append("'"); - out.append("\n"); - - out.append(" mode: "); - out.append(proto_enum_to_string(this->mode)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool TextStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 3: { this->missing_state = value.as_bool(); return true; } + case 4: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -9261,31 +5479,14 @@ void TextStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_string(2, this->state); buffer.encode_bool(3, this->missing_state); + buffer.encode_uint32(4, this->device_id); } void TextStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_string_field(total_size, 1, this->state, false); ProtoSize::add_bool_field(total_size, 1, this->missing_state, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void TextStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("TextStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append("'").append(this->state).append("'"); - out.append("\n"); - - out.append(" missing_state: "); - out.append(YESNO(this->missing_state)); - out.append("\n"); - out.append("}"); -} -#endif bool TextCommandRequest::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 2: { @@ -9314,21 +5515,8 @@ void TextCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_string_field(total_size, 1, this->state, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void TextCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("TextCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" state: "); - out.append("'").append(this->state).append("'"); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_DATETIME_DATE bool ListEntitiesDateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -9399,46 +5587,6 @@ void ListEntitiesDateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->entity_category), false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesDateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesDateResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool DateStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -9457,6 +5605,10 @@ bool DateStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { this->day = value.as_uint32(); return true; } + case 6: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -9477,6 +5629,7 @@ void DateStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_uint32(3, this->year); buffer.encode_uint32(4, this->month); buffer.encode_uint32(5, this->day); + buffer.encode_uint32(6, this->device_id); } void DateStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); @@ -9484,37 +5637,8 @@ void DateStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->year, false); ProtoSize::add_uint32_field(total_size, 1, this->month, false); ProtoSize::add_uint32_field(total_size, 1, this->day, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void DateStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("DateStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" missing_state: "); - out.append(YESNO(this->missing_state)); - out.append("\n"); - - out.append(" year: "); - sprintf(buffer, "%" PRIu32, this->year); - out.append(buffer); - out.append("\n"); - - out.append(" month: "); - sprintf(buffer, "%" PRIu32, this->month); - out.append(buffer); - out.append("\n"); - - out.append(" day: "); - sprintf(buffer, "%" PRIu32, this->day); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool DateCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -9555,32 +5679,8 @@ void DateCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->month, false); ProtoSize::add_uint32_field(total_size, 1, this->day, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void DateCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("DateCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" year: "); - sprintf(buffer, "%" PRIu32, this->year); - out.append(buffer); - out.append("\n"); - - out.append(" month: "); - sprintf(buffer, "%" PRIu32, this->month); - out.append(buffer); - out.append("\n"); - - out.append(" day: "); - sprintf(buffer, "%" PRIu32, this->day); - out.append(buffer); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_DATETIME_TIME bool ListEntitiesTimeResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -9651,46 +5751,6 @@ void ListEntitiesTimeResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->entity_category), false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesTimeResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesTimeResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool TimeStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -9709,6 +5769,10 @@ bool TimeStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { this->second = value.as_uint32(); return true; } + case 6: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -9729,6 +5793,7 @@ void TimeStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_uint32(3, this->hour); buffer.encode_uint32(4, this->minute); buffer.encode_uint32(5, this->second); + buffer.encode_uint32(6, this->device_id); } void TimeStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); @@ -9736,37 +5801,8 @@ void TimeStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->hour, false); ProtoSize::add_uint32_field(total_size, 1, this->minute, false); ProtoSize::add_uint32_field(total_size, 1, this->second, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void TimeStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("TimeStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" missing_state: "); - out.append(YESNO(this->missing_state)); - out.append("\n"); - - out.append(" hour: "); - sprintf(buffer, "%" PRIu32, this->hour); - out.append(buffer); - out.append("\n"); - - out.append(" minute: "); - sprintf(buffer, "%" PRIu32, this->minute); - out.append(buffer); - out.append("\n"); - - out.append(" second: "); - sprintf(buffer, "%" PRIu32, this->second); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool TimeCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -9807,32 +5843,8 @@ void TimeCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint32_field(total_size, 1, this->minute, false); ProtoSize::add_uint32_field(total_size, 1, this->second, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void TimeCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("TimeCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" hour: "); - sprintf(buffer, "%" PRIu32, this->hour); - out.append(buffer); - out.append("\n"); - - out.append(" minute: "); - sprintf(buffer, "%" PRIu32, this->minute); - out.append(buffer); - out.append("\n"); - - out.append(" second: "); - sprintf(buffer, "%" PRIu32, this->second); - out.append(buffer); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_EVENT bool ListEntitiesEventResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -9921,56 +5933,16 @@ void ListEntitiesEventResponse::calculate_size(uint32_t &total_size) const { } ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesEventResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesEventResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_class: "); - out.append("'").append(this->device_class).append("'"); - out.append("\n"); - - for (const auto &it : this->event_types) { - out.append(" event_types: "); - out.append("'").append(it).append("'"); - out.append("\n"); +bool EventResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { + switch (field_id) { + case 3: { + this->device_id = value.as_uint32(); + return true; + } + default: + return false; } - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); } -#endif bool EventResponse::decode_length(uint32_t field_id, ProtoLengthDelimited value) { switch (field_id) { case 2: { @@ -9994,26 +5966,15 @@ bool EventResponse::decode_32bit(uint32_t field_id, Proto32Bit value) { void EventResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_string(2, this->event_type); + buffer.encode_uint32(3, this->device_id); } void EventResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_string_field(total_size, 1, this->event_type, false); -} -#ifdef HAS_PROTO_MESSAGE_DUMP -void EventResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("EventResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" event_type: "); - out.append("'").append(this->event_type).append("'"); - out.append("\n"); - out.append("}"); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } #endif +#ifdef USE_VALVE bool ListEntitiesValveResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -10108,68 +6069,16 @@ void ListEntitiesValveResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_bool_field(total_size, 1, this->supports_stop, false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesValveResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesValveResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_class: "); - out.append("'").append(this->device_class).append("'"); - out.append("\n"); - - out.append(" assumed_state: "); - out.append(YESNO(this->assumed_state)); - out.append("\n"); - - out.append(" supports_position: "); - out.append(YESNO(this->supports_position)); - out.append("\n"); - - out.append(" supports_stop: "); - out.append(YESNO(this->supports_stop)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool ValveStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 3: { this->current_operation = value.as_enum(); return true; } + case 4: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -10192,32 +6101,14 @@ void ValveStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_float(2, this->position); buffer.encode_enum(3, this->current_operation); + buffer.encode_uint32(4, this->device_id); } void ValveStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->position != 0.0f, false); ProtoSize::add_enum_field(total_size, 1, static_cast(this->current_operation), false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ValveStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ValveStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" position: "); - sprintf(buffer, "%g", this->position); - out.append(buffer); - out.append("\n"); - - out.append(" current_operation: "); - out.append(proto_enum_to_string(this->current_operation)); - out.append("\n"); - out.append("}"); -} -#endif bool ValveCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -10258,30 +6149,8 @@ void ValveCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->position != 0.0f, false); ProtoSize::add_bool_field(total_size, 1, this->stop, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ValveCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ValveCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" has_position: "); - out.append(YESNO(this->has_position)); - out.append("\n"); - - out.append(" position: "); - sprintf(buffer, "%g", this->position); - out.append(buffer); - out.append("\n"); - - out.append(" stop: "); - out.append(YESNO(this->stop)); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_DATETIME_DATETIME bool ListEntitiesDateTimeResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -10352,52 +6221,16 @@ void ListEntitiesDateTimeResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_enum_field(total_size, 1, static_cast(this->entity_category), false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesDateTimeResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesDateTimeResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool DateTimeStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { this->missing_state = value.as_bool(); return true; } + case 4: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -10420,32 +6253,14 @@ void DateTimeStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_fixed32(1, this->key); buffer.encode_bool(2, this->missing_state); buffer.encode_fixed32(3, this->epoch_seconds); + buffer.encode_uint32(4, this->device_id); } void DateTimeStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_bool_field(total_size, 1, this->missing_state, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->epoch_seconds != 0, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void DateTimeStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("DateTimeStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" missing_state: "); - out.append(YESNO(this->missing_state)); - out.append("\n"); - - out.append(" epoch_seconds: "); - sprintf(buffer, "%" PRIu32, this->epoch_seconds); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool DateTimeCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) { switch (field_id) { case 1: { @@ -10468,22 +6283,8 @@ void DateTimeCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_fixed_field<4>(total_size, 1, this->epoch_seconds != 0, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void DateTimeCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("DateTimeCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" epoch_seconds: "); - sprintf(buffer, "%" PRIu32, this->epoch_seconds); - out.append(buffer); - out.append("\n"); - out.append("}"); -} #endif +#ifdef USE_UPDATE bool ListEntitiesUpdateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 6: { @@ -10560,50 +6361,6 @@ void ListEntitiesUpdateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->device_class, false); ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void ListEntitiesUpdateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("ListEntitiesUpdateResponse {\n"); - out.append(" object_id: "); - out.append("'").append(this->object_id).append("'"); - out.append("\n"); - - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" name: "); - out.append("'").append(this->name).append("'"); - out.append("\n"); - - out.append(" unique_id: "); - out.append("'").append(this->unique_id).append("'"); - out.append("\n"); - - out.append(" icon: "); - out.append("'").append(this->icon).append("'"); - out.append("\n"); - - out.append(" disabled_by_default: "); - out.append(YESNO(this->disabled_by_default)); - out.append("\n"); - - out.append(" entity_category: "); - out.append(proto_enum_to_string(this->entity_category)); - out.append("\n"); - - out.append(" device_class: "); - out.append("'").append(this->device_class).append("'"); - out.append("\n"); - - out.append(" device_id: "); - sprintf(buffer, "%" PRIu32, this->device_id); - out.append(buffer); - out.append("\n"); - out.append("}"); -} -#endif bool UpdateStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -10618,6 +6375,10 @@ bool UpdateStateResponse::decode_varint(uint32_t field_id, ProtoVarInt value) { this->has_progress = value.as_bool(); return true; } + case 11: { + this->device_id = value.as_uint32(); + return true; + } default: return false; } @@ -10673,6 +6434,7 @@ void UpdateStateResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_string(8, this->title); buffer.encode_string(9, this->release_summary); buffer.encode_string(10, this->release_url); + buffer.encode_uint32(11, this->device_id); } void UpdateStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); @@ -10685,55 +6447,8 @@ void UpdateStateResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_string_field(total_size, 1, this->title, false); ProtoSize::add_string_field(total_size, 1, this->release_summary, false); ProtoSize::add_string_field(total_size, 1, this->release_url, false); + ProtoSize::add_uint32_field(total_size, 1, this->device_id, false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void UpdateStateResponse::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("UpdateStateResponse {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" missing_state: "); - out.append(YESNO(this->missing_state)); - out.append("\n"); - - out.append(" in_progress: "); - out.append(YESNO(this->in_progress)); - out.append("\n"); - - out.append(" has_progress: "); - out.append(YESNO(this->has_progress)); - out.append("\n"); - - out.append(" progress: "); - sprintf(buffer, "%g", this->progress); - out.append(buffer); - out.append("\n"); - - out.append(" current_version: "); - out.append("'").append(this->current_version).append("'"); - out.append("\n"); - - out.append(" latest_version: "); - out.append("'").append(this->latest_version).append("'"); - out.append("\n"); - - out.append(" title: "); - out.append("'").append(this->title).append("'"); - out.append("\n"); - - out.append(" release_summary: "); - out.append("'").append(this->release_summary).append("'"); - out.append("\n"); - - out.append(" release_url: "); - out.append("'").append(this->release_url).append("'"); - out.append("\n"); - out.append("}"); -} -#endif bool UpdateCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) { switch (field_id) { case 2: { @@ -10762,20 +6477,6 @@ void UpdateCommandRequest::calculate_size(uint32_t &total_size) const { ProtoSize::add_fixed_field<4>(total_size, 1, this->key != 0, false); ProtoSize::add_enum_field(total_size, 1, static_cast(this->command), false); } -#ifdef HAS_PROTO_MESSAGE_DUMP -void UpdateCommandRequest::dump_to(std::string &out) const { - __attribute__((unused)) char buffer[64]; - out.append("UpdateCommandRequest {\n"); - out.append(" key: "); - sprintf(buffer, "%" PRIu32, this->key); - out.append(buffer); - out.append("\n"); - - out.append(" command: "); - out.append(proto_enum_to_string(this->command)); - out.append("\n"); - out.append("}"); -} #endif } // namespace api diff --git a/esphome/components/api/api_pb2.h b/esphome/components/api/api_pb2.h index 2f0444c2cd..3bfc5f1cf4 100644 --- a/esphome/components/api/api_pb2.h +++ b/esphome/components/api/api_pb2.h @@ -2,6 +2,8 @@ // See script/api_protobuf/api_protobuf.py #pragma once +#include "esphome/core/defines.h" + #include "proto.h" #include "api_pb2_size.h" @@ -15,6 +17,7 @@ enum EntityCategory : uint32_t { ENTITY_CATEGORY_CONFIG = 1, ENTITY_CATEGORY_DIAGNOSTIC = 2, }; +#ifdef USE_COVER enum LegacyCoverState : uint32_t { LEGACY_COVER_STATE_OPEN = 0, LEGACY_COVER_STATE_CLOSED = 1, @@ -29,6 +32,8 @@ enum LegacyCoverCommand : uint32_t { LEGACY_COVER_COMMAND_CLOSE = 1, LEGACY_COVER_COMMAND_STOP = 2, }; +#endif +#ifdef USE_FAN enum FanSpeed : uint32_t { FAN_SPEED_LOW = 0, FAN_SPEED_MEDIUM = 1, @@ -38,6 +43,8 @@ enum FanDirection : uint32_t { FAN_DIRECTION_FORWARD = 0, FAN_DIRECTION_REVERSE = 1, }; +#endif +#ifdef USE_LIGHT enum ColorMode : uint32_t { COLOR_MODE_UNKNOWN = 0, COLOR_MODE_ON_OFF = 1, @@ -51,6 +58,8 @@ enum ColorMode : uint32_t { COLOR_MODE_RGB_COLOR_TEMPERATURE = 47, COLOR_MODE_RGB_COLD_WARM_WHITE = 51, }; +#endif +#ifdef USE_SENSOR enum SensorStateClass : uint32_t { STATE_CLASS_NONE = 0, STATE_CLASS_MEASUREMENT = 1, @@ -62,6 +71,7 @@ enum SensorLastResetType : uint32_t { LAST_RESET_NEVER = 1, LAST_RESET_AUTO = 2, }; +#endif enum LogLevel : uint32_t { LOG_LEVEL_NONE = 0, LOG_LEVEL_ERROR = 1, @@ -82,6 +92,7 @@ enum ServiceArgType : uint32_t { SERVICE_ARG_TYPE_FLOAT_ARRAY = 6, SERVICE_ARG_TYPE_STRING_ARRAY = 7, }; +#ifdef USE_CLIMATE enum ClimateMode : uint32_t { CLIMATE_MODE_OFF = 0, CLIMATE_MODE_HEAT_COOL = 1, @@ -127,11 +138,15 @@ enum ClimatePreset : uint32_t { CLIMATE_PRESET_SLEEP = 6, CLIMATE_PRESET_ACTIVITY = 7, }; +#endif +#ifdef USE_NUMBER enum NumberMode : uint32_t { NUMBER_MODE_AUTO = 0, NUMBER_MODE_BOX = 1, NUMBER_MODE_SLIDER = 2, }; +#endif +#ifdef USE_LOCK enum LockState : uint32_t { LOCK_STATE_NONE = 0, LOCK_STATE_LOCKED = 1, @@ -145,6 +160,8 @@ enum LockCommand : uint32_t { LOCK_LOCK = 1, LOCK_OPEN = 2, }; +#endif +#ifdef USE_MEDIA_PLAYER enum MediaPlayerState : uint32_t { MEDIA_PLAYER_STATE_NONE = 0, MEDIA_PLAYER_STATE_IDLE = 1, @@ -162,6 +179,8 @@ enum MediaPlayerFormatPurpose : uint32_t { MEDIA_PLAYER_FORMAT_PURPOSE_DEFAULT = 0, MEDIA_PLAYER_FORMAT_PURPOSE_ANNOUNCEMENT = 1, }; +#endif +#ifdef USE_BLUETOOTH_PROXY enum BluetoothDeviceRequestType : uint32_t { BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT = 0, BLUETOOTH_DEVICE_REQUEST_TYPE_DISCONNECT = 1, @@ -183,6 +202,7 @@ enum BluetoothScannerMode : uint32_t { BLUETOOTH_SCANNER_MODE_PASSIVE = 0, BLUETOOTH_SCANNER_MODE_ACTIVE = 1, }; +#endif enum VoiceAssistantSubscribeFlag : uint32_t { VOICE_ASSISTANT_SUBSCRIBE_NONE = 0, VOICE_ASSISTANT_SUBSCRIBE_API_AUDIO = 1, @@ -192,6 +212,7 @@ enum VoiceAssistantRequestFlag : uint32_t { VOICE_ASSISTANT_REQUEST_USE_VAD = 1, VOICE_ASSISTANT_REQUEST_USE_WAKE_WORD = 2, }; +#ifdef USE_VOICE_ASSISTANT enum VoiceAssistantEvent : uint32_t { VOICE_ASSISTANT_ERROR = 0, VOICE_ASSISTANT_RUN_START = 1, @@ -216,6 +237,8 @@ enum VoiceAssistantTimerEvent : uint32_t { VOICE_ASSISTANT_TIMER_CANCELLED = 2, VOICE_ASSISTANT_TIMER_FINISHED = 3, }; +#endif +#ifdef USE_ALARM_CONTROL_PANEL enum AlarmControlPanelState : uint32_t { ALARM_STATE_DISARMED = 0, ALARM_STATE_ARMED_HOME = 1, @@ -237,20 +260,27 @@ enum AlarmControlPanelStateCommand : uint32_t { ALARM_CONTROL_PANEL_ARM_CUSTOM_BYPASS = 5, ALARM_CONTROL_PANEL_TRIGGER = 6, }; +#endif +#ifdef USE_TEXT enum TextMode : uint32_t { TEXT_MODE_TEXT = 0, TEXT_MODE_PASSWORD = 1, }; +#endif +#ifdef USE_VALVE enum ValveOperation : uint32_t { VALVE_OPERATION_IDLE = 0, VALVE_OPERATION_IS_OPENING = 1, VALVE_OPERATION_IS_CLOSING = 2, }; +#endif +#ifdef USE_UPDATE enum UpdateCommand : uint32_t { UPDATE_COMMAND_NONE = 0, UPDATE_COMMAND_UPDATE = 1, UPDATE_COMMAND_CHECK = 2, }; +#endif } // namespace enums @@ -273,6 +303,7 @@ class StateResponseProtoMessage : public ProtoMessage { public: ~StateResponseProtoMessage() override = default; uint32_t key{0}; + uint32_t device_id{0}; protected: }; @@ -523,6 +554,7 @@ class SubscribeStatesRequest : public ProtoMessage { protected: }; +#ifdef USE_BINARY_SENSOR class ListEntitiesBinarySensorResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 12; @@ -546,7 +578,7 @@ class ListEntitiesBinarySensorResponse : public InfoResponseProtoMessage { class BinarySensorStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 21; - static constexpr uint16_t ESTIMATED_SIZE = 9; + static constexpr uint16_t ESTIMATED_SIZE = 13; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "binary_sensor_state_response"; } #endif @@ -562,6 +594,8 @@ class BinarySensorStateResponse : public StateResponseProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_COVER class ListEntitiesCoverResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 13; @@ -588,7 +622,7 @@ class ListEntitiesCoverResponse : public InfoResponseProtoMessage { class CoverStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 22; - static constexpr uint16_t ESTIMATED_SIZE = 19; + static constexpr uint16_t ESTIMATED_SIZE = 23; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "cover_state_response"; } #endif @@ -631,6 +665,8 @@ class CoverCommandRequest : public ProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_FAN class ListEntitiesFanResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 14; @@ -657,7 +693,7 @@ class ListEntitiesFanResponse : public InfoResponseProtoMessage { class FanStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 23; - static constexpr uint16_t ESTIMATED_SIZE = 26; + static constexpr uint16_t ESTIMATED_SIZE = 30; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "fan_state_response"; } #endif @@ -709,6 +745,8 @@ class FanCommandRequest : public ProtoMessage { bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_LIGHT class ListEntitiesLightResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 15; @@ -738,7 +776,7 @@ class ListEntitiesLightResponse : public InfoResponseProtoMessage { class LightStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 24; - static constexpr uint16_t ESTIMATED_SIZE = 63; + static constexpr uint16_t ESTIMATED_SIZE = 67; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "light_state_response"; } #endif @@ -810,6 +848,8 @@ class LightCommandRequest : public ProtoMessage { bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_SENSOR class ListEntitiesSensorResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 16; @@ -837,7 +877,7 @@ class ListEntitiesSensorResponse : public InfoResponseProtoMessage { class SensorStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 25; - static constexpr uint16_t ESTIMATED_SIZE = 12; + static constexpr uint16_t ESTIMATED_SIZE = 16; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "sensor_state_response"; } #endif @@ -853,6 +893,8 @@ class SensorStateResponse : public StateResponseProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_SWITCH class ListEntitiesSwitchResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 17; @@ -876,7 +918,7 @@ class ListEntitiesSwitchResponse : public InfoResponseProtoMessage { class SwitchStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 26; - static constexpr uint16_t ESTIMATED_SIZE = 7; + static constexpr uint16_t ESTIMATED_SIZE = 11; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "switch_state_response"; } #endif @@ -910,6 +952,8 @@ class SwitchCommandRequest : public ProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_TEXT_SENSOR class ListEntitiesTextSensorResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 18; @@ -932,7 +976,7 @@ class ListEntitiesTextSensorResponse : public InfoResponseProtoMessage { class TextSensorStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 27; - static constexpr uint16_t ESTIMATED_SIZE = 16; + static constexpr uint16_t ESTIMATED_SIZE = 20; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "text_sensor_state_response"; } #endif @@ -949,6 +993,7 @@ class TextSensorStateResponse : public StateResponseProtoMessage { bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif class SubscribeLogsRequest : public ProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 28; @@ -987,6 +1032,7 @@ class SubscribeLogsResponse : public ProtoMessage { bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#ifdef USE_API_NOISE class NoiseEncryptionSetKeyRequest : public ProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 124; @@ -1021,6 +1067,7 @@ class NoiseEncryptionSetKeyResponse : public ProtoMessage { protected: bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif class SubscribeHomeassistantServicesRequest : public ProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 34; @@ -1226,6 +1273,7 @@ class ExecuteServiceRequest : public ProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; }; +#ifdef USE_CAMERA class ListEntitiesCameraResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 43; @@ -1283,6 +1331,8 @@ class CameraImageRequest : public ProtoMessage { protected: bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_CLIMATE class ListEntitiesClimateResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 46; @@ -1322,7 +1372,7 @@ class ListEntitiesClimateResponse : public InfoResponseProtoMessage { class ClimateStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 47; - static constexpr uint16_t ESTIMATED_SIZE = 65; + static constexpr uint16_t ESTIMATED_SIZE = 70; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "climate_state_response"; } #endif @@ -1392,6 +1442,8 @@ class ClimateCommandRequest : public ProtoMessage { bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_NUMBER class ListEntitiesNumberResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 49; @@ -1419,7 +1471,7 @@ class ListEntitiesNumberResponse : public InfoResponseProtoMessage { class NumberStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 50; - static constexpr uint16_t ESTIMATED_SIZE = 12; + static constexpr uint16_t ESTIMATED_SIZE = 16; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "number_state_response"; } #endif @@ -1453,6 +1505,8 @@ class NumberCommandRequest : public ProtoMessage { protected: bool decode_32bit(uint32_t field_id, Proto32Bit value) override; }; +#endif +#ifdef USE_SELECT class ListEntitiesSelectResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 52; @@ -1475,7 +1529,7 @@ class ListEntitiesSelectResponse : public InfoResponseProtoMessage { class SelectStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 53; - static constexpr uint16_t ESTIMATED_SIZE = 16; + static constexpr uint16_t ESTIMATED_SIZE = 20; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "select_state_response"; } #endif @@ -1511,6 +1565,8 @@ class SelectCommandRequest : public ProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; }; +#endif +#ifdef USE_SIREN class ListEntitiesSirenResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 55; @@ -1535,7 +1591,7 @@ class ListEntitiesSirenResponse : public InfoResponseProtoMessage { class SirenStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 56; - static constexpr uint16_t ESTIMATED_SIZE = 7; + static constexpr uint16_t ESTIMATED_SIZE = 11; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "siren_state_response"; } #endif @@ -1577,6 +1633,8 @@ class SirenCommandRequest : public ProtoMessage { bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_LOCK class ListEntitiesLockResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 58; @@ -1602,7 +1660,7 @@ class ListEntitiesLockResponse : public InfoResponseProtoMessage { class LockStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 59; - static constexpr uint16_t ESTIMATED_SIZE = 7; + static constexpr uint16_t ESTIMATED_SIZE = 11; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "lock_state_response"; } #endif @@ -1639,6 +1697,8 @@ class LockCommandRequest : public ProtoMessage { bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_BUTTON class ListEntitiesButtonResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 61; @@ -1675,6 +1735,8 @@ class ButtonCommandRequest : public ProtoMessage { protected: bool decode_32bit(uint32_t field_id, Proto32Bit value) override; }; +#endif +#ifdef USE_MEDIA_PLAYER class MediaPlayerSupportedFormat : public ProtoMessage { public: std::string format{}; @@ -1715,7 +1777,7 @@ class ListEntitiesMediaPlayerResponse : public InfoResponseProtoMessage { class MediaPlayerStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 64; - static constexpr uint16_t ESTIMATED_SIZE = 14; + static constexpr uint16_t ESTIMATED_SIZE = 18; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "media_player_state_response"; } #endif @@ -1759,6 +1821,8 @@ class MediaPlayerCommandRequest : public ProtoMessage { bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_BLUETOOTH_PROXY class SubscribeBluetoothLEAdvertisementsRequest : public ProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 66; @@ -2313,6 +2377,8 @@ class BluetoothScannerSetModeRequest : public ProtoMessage { protected: bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_VOICE_ASSISTANT class SubscribeVoiceAssistantRequest : public ProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 89; @@ -2562,6 +2628,8 @@ class VoiceAssistantSetConfiguration : public ProtoMessage { protected: bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; }; +#endif +#ifdef USE_ALARM_CONTROL_PANEL class ListEntitiesAlarmControlPanelResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 94; @@ -2586,7 +2654,7 @@ class ListEntitiesAlarmControlPanelResponse : public InfoResponseProtoMessage { class AlarmControlPanelStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 95; - static constexpr uint16_t ESTIMATED_SIZE = 7; + static constexpr uint16_t ESTIMATED_SIZE = 11; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "alarm_control_panel_state_response"; } #endif @@ -2622,6 +2690,8 @@ class AlarmControlPanelCommandRequest : public ProtoMessage { bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_TEXT class ListEntitiesTextResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 97; @@ -2647,7 +2717,7 @@ class ListEntitiesTextResponse : public InfoResponseProtoMessage { class TextStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 98; - static constexpr uint16_t ESTIMATED_SIZE = 16; + static constexpr uint16_t ESTIMATED_SIZE = 20; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "text_state_response"; } #endif @@ -2683,6 +2753,8 @@ class TextCommandRequest : public ProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; }; +#endif +#ifdef USE_DATETIME_DATE class ListEntitiesDateResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 100; @@ -2704,7 +2776,7 @@ class ListEntitiesDateResponse : public InfoResponseProtoMessage { class DateStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 101; - static constexpr uint16_t ESTIMATED_SIZE = 19; + static constexpr uint16_t ESTIMATED_SIZE = 23; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "date_state_response"; } #endif @@ -2743,6 +2815,8 @@ class DateCommandRequest : public ProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_DATETIME_TIME class ListEntitiesTimeResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 103; @@ -2764,7 +2838,7 @@ class ListEntitiesTimeResponse : public InfoResponseProtoMessage { class TimeStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 104; - static constexpr uint16_t ESTIMATED_SIZE = 19; + static constexpr uint16_t ESTIMATED_SIZE = 23; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "time_state_response"; } #endif @@ -2803,6 +2877,8 @@ class TimeCommandRequest : public ProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_EVENT class ListEntitiesEventResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 107; @@ -2826,7 +2902,7 @@ class ListEntitiesEventResponse : public InfoResponseProtoMessage { class EventResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 108; - static constexpr uint16_t ESTIMATED_SIZE = 14; + static constexpr uint16_t ESTIMATED_SIZE = 18; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "event_response"; } #endif @@ -2840,7 +2916,10 @@ class EventResponse : public StateResponseProtoMessage { protected: bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override; + bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_VALVE class ListEntitiesValveResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 109; @@ -2866,7 +2945,7 @@ class ListEntitiesValveResponse : public InfoResponseProtoMessage { class ValveStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 110; - static constexpr uint16_t ESTIMATED_SIZE = 12; + static constexpr uint16_t ESTIMATED_SIZE = 16; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "valve_state_response"; } #endif @@ -2903,6 +2982,8 @@ class ValveCommandRequest : public ProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif +#ifdef USE_DATETIME_DATETIME class ListEntitiesDateTimeResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 112; @@ -2924,7 +3005,7 @@ class ListEntitiesDateTimeResponse : public InfoResponseProtoMessage { class DateTimeStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 113; - static constexpr uint16_t ESTIMATED_SIZE = 12; + static constexpr uint16_t ESTIMATED_SIZE = 16; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "date_time_state_response"; } #endif @@ -2958,6 +3039,8 @@ class DateTimeCommandRequest : public ProtoMessage { protected: bool decode_32bit(uint32_t field_id, Proto32Bit value) override; }; +#endif +#ifdef USE_UPDATE class ListEntitiesUpdateResponse : public InfoResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 116; @@ -2980,7 +3063,7 @@ class ListEntitiesUpdateResponse : public InfoResponseProtoMessage { class UpdateStateResponse : public StateResponseProtoMessage { public: static constexpr uint16_t MESSAGE_TYPE = 117; - static constexpr uint16_t ESTIMATED_SIZE = 61; + static constexpr uint16_t ESTIMATED_SIZE = 65; #ifdef HAS_PROTO_MESSAGE_DUMP const char *message_name() const override { return "update_state_response"; } #endif @@ -3023,6 +3106,7 @@ class UpdateCommandRequest : public ProtoMessage { bool decode_32bit(uint32_t field_id, Proto32Bit value) override; bool decode_varint(uint32_t field_id, ProtoVarInt value) override; }; +#endif } // namespace api } // namespace esphome diff --git a/esphome/components/api/api_pb2_dump.cpp b/esphome/components/api/api_pb2_dump.cpp new file mode 100644 index 0000000000..48ddd42d61 --- /dev/null +++ b/esphome/components/api/api_pb2_dump.cpp @@ -0,0 +1,4333 @@ +// This file was automatically generated with a tool. +// See script/api_protobuf/api_protobuf.py +#include "api_pb2.h" +#include "esphome/core/helpers.h" + +#include + +#ifdef HAS_PROTO_MESSAGE_DUMP + +namespace esphome { +namespace api { + +template<> const char *proto_enum_to_string(enums::EntityCategory value) { + switch (value) { + case enums::ENTITY_CATEGORY_NONE: + return "ENTITY_CATEGORY_NONE"; + case enums::ENTITY_CATEGORY_CONFIG: + return "ENTITY_CATEGORY_CONFIG"; + case enums::ENTITY_CATEGORY_DIAGNOSTIC: + return "ENTITY_CATEGORY_DIAGNOSTIC"; + default: + return "UNKNOWN"; + } +} +#ifdef USE_COVER +template<> const char *proto_enum_to_string(enums::LegacyCoverState value) { + switch (value) { + case enums::LEGACY_COVER_STATE_OPEN: + return "LEGACY_COVER_STATE_OPEN"; + case enums::LEGACY_COVER_STATE_CLOSED: + return "LEGACY_COVER_STATE_CLOSED"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::CoverOperation value) { + switch (value) { + case enums::COVER_OPERATION_IDLE: + return "COVER_OPERATION_IDLE"; + case enums::COVER_OPERATION_IS_OPENING: + return "COVER_OPERATION_IS_OPENING"; + case enums::COVER_OPERATION_IS_CLOSING: + return "COVER_OPERATION_IS_CLOSING"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::LegacyCoverCommand value) { + switch (value) { + case enums::LEGACY_COVER_COMMAND_OPEN: + return "LEGACY_COVER_COMMAND_OPEN"; + case enums::LEGACY_COVER_COMMAND_CLOSE: + return "LEGACY_COVER_COMMAND_CLOSE"; + case enums::LEGACY_COVER_COMMAND_STOP: + return "LEGACY_COVER_COMMAND_STOP"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_FAN +template<> const char *proto_enum_to_string(enums::FanSpeed value) { + switch (value) { + case enums::FAN_SPEED_LOW: + return "FAN_SPEED_LOW"; + case enums::FAN_SPEED_MEDIUM: + return "FAN_SPEED_MEDIUM"; + case enums::FAN_SPEED_HIGH: + return "FAN_SPEED_HIGH"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::FanDirection value) { + switch (value) { + case enums::FAN_DIRECTION_FORWARD: + return "FAN_DIRECTION_FORWARD"; + case enums::FAN_DIRECTION_REVERSE: + return "FAN_DIRECTION_REVERSE"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_LIGHT +template<> const char *proto_enum_to_string(enums::ColorMode value) { + switch (value) { + case enums::COLOR_MODE_UNKNOWN: + return "COLOR_MODE_UNKNOWN"; + case enums::COLOR_MODE_ON_OFF: + return "COLOR_MODE_ON_OFF"; + case enums::COLOR_MODE_LEGACY_BRIGHTNESS: + return "COLOR_MODE_LEGACY_BRIGHTNESS"; + case enums::COLOR_MODE_BRIGHTNESS: + return "COLOR_MODE_BRIGHTNESS"; + case enums::COLOR_MODE_WHITE: + return "COLOR_MODE_WHITE"; + case enums::COLOR_MODE_COLOR_TEMPERATURE: + return "COLOR_MODE_COLOR_TEMPERATURE"; + case enums::COLOR_MODE_COLD_WARM_WHITE: + return "COLOR_MODE_COLD_WARM_WHITE"; + case enums::COLOR_MODE_RGB: + return "COLOR_MODE_RGB"; + case enums::COLOR_MODE_RGB_WHITE: + return "COLOR_MODE_RGB_WHITE"; + case enums::COLOR_MODE_RGB_COLOR_TEMPERATURE: + return "COLOR_MODE_RGB_COLOR_TEMPERATURE"; + case enums::COLOR_MODE_RGB_COLD_WARM_WHITE: + return "COLOR_MODE_RGB_COLD_WARM_WHITE"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_SENSOR +template<> const char *proto_enum_to_string(enums::SensorStateClass value) { + switch (value) { + case enums::STATE_CLASS_NONE: + return "STATE_CLASS_NONE"; + case enums::STATE_CLASS_MEASUREMENT: + return "STATE_CLASS_MEASUREMENT"; + case enums::STATE_CLASS_TOTAL_INCREASING: + return "STATE_CLASS_TOTAL_INCREASING"; + case enums::STATE_CLASS_TOTAL: + return "STATE_CLASS_TOTAL"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::SensorLastResetType value) { + switch (value) { + case enums::LAST_RESET_NONE: + return "LAST_RESET_NONE"; + case enums::LAST_RESET_NEVER: + return "LAST_RESET_NEVER"; + case enums::LAST_RESET_AUTO: + return "LAST_RESET_AUTO"; + default: + return "UNKNOWN"; + } +} +#endif +template<> const char *proto_enum_to_string(enums::LogLevel value) { + switch (value) { + case enums::LOG_LEVEL_NONE: + return "LOG_LEVEL_NONE"; + case enums::LOG_LEVEL_ERROR: + return "LOG_LEVEL_ERROR"; + case enums::LOG_LEVEL_WARN: + return "LOG_LEVEL_WARN"; + case enums::LOG_LEVEL_INFO: + return "LOG_LEVEL_INFO"; + case enums::LOG_LEVEL_CONFIG: + return "LOG_LEVEL_CONFIG"; + case enums::LOG_LEVEL_DEBUG: + return "LOG_LEVEL_DEBUG"; + case enums::LOG_LEVEL_VERBOSE: + return "LOG_LEVEL_VERBOSE"; + case enums::LOG_LEVEL_VERY_VERBOSE: + return "LOG_LEVEL_VERY_VERBOSE"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::ServiceArgType value) { + switch (value) { + case enums::SERVICE_ARG_TYPE_BOOL: + return "SERVICE_ARG_TYPE_BOOL"; + case enums::SERVICE_ARG_TYPE_INT: + return "SERVICE_ARG_TYPE_INT"; + case enums::SERVICE_ARG_TYPE_FLOAT: + return "SERVICE_ARG_TYPE_FLOAT"; + case enums::SERVICE_ARG_TYPE_STRING: + return "SERVICE_ARG_TYPE_STRING"; + case enums::SERVICE_ARG_TYPE_BOOL_ARRAY: + return "SERVICE_ARG_TYPE_BOOL_ARRAY"; + case enums::SERVICE_ARG_TYPE_INT_ARRAY: + return "SERVICE_ARG_TYPE_INT_ARRAY"; + case enums::SERVICE_ARG_TYPE_FLOAT_ARRAY: + return "SERVICE_ARG_TYPE_FLOAT_ARRAY"; + case enums::SERVICE_ARG_TYPE_STRING_ARRAY: + return "SERVICE_ARG_TYPE_STRING_ARRAY"; + default: + return "UNKNOWN"; + } +} +#ifdef USE_CLIMATE +template<> const char *proto_enum_to_string(enums::ClimateMode value) { + switch (value) { + case enums::CLIMATE_MODE_OFF: + return "CLIMATE_MODE_OFF"; + case enums::CLIMATE_MODE_HEAT_COOL: + return "CLIMATE_MODE_HEAT_COOL"; + case enums::CLIMATE_MODE_COOL: + return "CLIMATE_MODE_COOL"; + case enums::CLIMATE_MODE_HEAT: + return "CLIMATE_MODE_HEAT"; + case enums::CLIMATE_MODE_FAN_ONLY: + return "CLIMATE_MODE_FAN_ONLY"; + case enums::CLIMATE_MODE_DRY: + return "CLIMATE_MODE_DRY"; + case enums::CLIMATE_MODE_AUTO: + return "CLIMATE_MODE_AUTO"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::ClimateFanMode value) { + switch (value) { + case enums::CLIMATE_FAN_ON: + return "CLIMATE_FAN_ON"; + case enums::CLIMATE_FAN_OFF: + return "CLIMATE_FAN_OFF"; + case enums::CLIMATE_FAN_AUTO: + return "CLIMATE_FAN_AUTO"; + case enums::CLIMATE_FAN_LOW: + return "CLIMATE_FAN_LOW"; + case enums::CLIMATE_FAN_MEDIUM: + return "CLIMATE_FAN_MEDIUM"; + case enums::CLIMATE_FAN_HIGH: + return "CLIMATE_FAN_HIGH"; + case enums::CLIMATE_FAN_MIDDLE: + return "CLIMATE_FAN_MIDDLE"; + case enums::CLIMATE_FAN_FOCUS: + return "CLIMATE_FAN_FOCUS"; + case enums::CLIMATE_FAN_DIFFUSE: + return "CLIMATE_FAN_DIFFUSE"; + case enums::CLIMATE_FAN_QUIET: + return "CLIMATE_FAN_QUIET"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::ClimateSwingMode value) { + switch (value) { + case enums::CLIMATE_SWING_OFF: + return "CLIMATE_SWING_OFF"; + case enums::CLIMATE_SWING_BOTH: + return "CLIMATE_SWING_BOTH"; + case enums::CLIMATE_SWING_VERTICAL: + return "CLIMATE_SWING_VERTICAL"; + case enums::CLIMATE_SWING_HORIZONTAL: + return "CLIMATE_SWING_HORIZONTAL"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::ClimateAction value) { + switch (value) { + case enums::CLIMATE_ACTION_OFF: + return "CLIMATE_ACTION_OFF"; + case enums::CLIMATE_ACTION_COOLING: + return "CLIMATE_ACTION_COOLING"; + case enums::CLIMATE_ACTION_HEATING: + return "CLIMATE_ACTION_HEATING"; + case enums::CLIMATE_ACTION_IDLE: + return "CLIMATE_ACTION_IDLE"; + case enums::CLIMATE_ACTION_DRYING: + return "CLIMATE_ACTION_DRYING"; + case enums::CLIMATE_ACTION_FAN: + return "CLIMATE_ACTION_FAN"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::ClimatePreset value) { + switch (value) { + case enums::CLIMATE_PRESET_NONE: + return "CLIMATE_PRESET_NONE"; + case enums::CLIMATE_PRESET_HOME: + return "CLIMATE_PRESET_HOME"; + case enums::CLIMATE_PRESET_AWAY: + return "CLIMATE_PRESET_AWAY"; + case enums::CLIMATE_PRESET_BOOST: + return "CLIMATE_PRESET_BOOST"; + case enums::CLIMATE_PRESET_COMFORT: + return "CLIMATE_PRESET_COMFORT"; + case enums::CLIMATE_PRESET_ECO: + return "CLIMATE_PRESET_ECO"; + case enums::CLIMATE_PRESET_SLEEP: + return "CLIMATE_PRESET_SLEEP"; + case enums::CLIMATE_PRESET_ACTIVITY: + return "CLIMATE_PRESET_ACTIVITY"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_NUMBER +template<> const char *proto_enum_to_string(enums::NumberMode value) { + switch (value) { + case enums::NUMBER_MODE_AUTO: + return "NUMBER_MODE_AUTO"; + case enums::NUMBER_MODE_BOX: + return "NUMBER_MODE_BOX"; + case enums::NUMBER_MODE_SLIDER: + return "NUMBER_MODE_SLIDER"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_LOCK +template<> const char *proto_enum_to_string(enums::LockState value) { + switch (value) { + case enums::LOCK_STATE_NONE: + return "LOCK_STATE_NONE"; + case enums::LOCK_STATE_LOCKED: + return "LOCK_STATE_LOCKED"; + case enums::LOCK_STATE_UNLOCKED: + return "LOCK_STATE_UNLOCKED"; + case enums::LOCK_STATE_JAMMED: + return "LOCK_STATE_JAMMED"; + case enums::LOCK_STATE_LOCKING: + return "LOCK_STATE_LOCKING"; + case enums::LOCK_STATE_UNLOCKING: + return "LOCK_STATE_UNLOCKING"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::LockCommand value) { + switch (value) { + case enums::LOCK_UNLOCK: + return "LOCK_UNLOCK"; + case enums::LOCK_LOCK: + return "LOCK_LOCK"; + case enums::LOCK_OPEN: + return "LOCK_OPEN"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_MEDIA_PLAYER +template<> const char *proto_enum_to_string(enums::MediaPlayerState value) { + switch (value) { + case enums::MEDIA_PLAYER_STATE_NONE: + return "MEDIA_PLAYER_STATE_NONE"; + case enums::MEDIA_PLAYER_STATE_IDLE: + return "MEDIA_PLAYER_STATE_IDLE"; + case enums::MEDIA_PLAYER_STATE_PLAYING: + return "MEDIA_PLAYER_STATE_PLAYING"; + case enums::MEDIA_PLAYER_STATE_PAUSED: + return "MEDIA_PLAYER_STATE_PAUSED"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::MediaPlayerCommand value) { + switch (value) { + case enums::MEDIA_PLAYER_COMMAND_PLAY: + return "MEDIA_PLAYER_COMMAND_PLAY"; + case enums::MEDIA_PLAYER_COMMAND_PAUSE: + return "MEDIA_PLAYER_COMMAND_PAUSE"; + case enums::MEDIA_PLAYER_COMMAND_STOP: + return "MEDIA_PLAYER_COMMAND_STOP"; + case enums::MEDIA_PLAYER_COMMAND_MUTE: + return "MEDIA_PLAYER_COMMAND_MUTE"; + case enums::MEDIA_PLAYER_COMMAND_UNMUTE: + return "MEDIA_PLAYER_COMMAND_UNMUTE"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::MediaPlayerFormatPurpose value) { + switch (value) { + case enums::MEDIA_PLAYER_FORMAT_PURPOSE_DEFAULT: + return "MEDIA_PLAYER_FORMAT_PURPOSE_DEFAULT"; + case enums::MEDIA_PLAYER_FORMAT_PURPOSE_ANNOUNCEMENT: + return "MEDIA_PLAYER_FORMAT_PURPOSE_ANNOUNCEMENT"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_BLUETOOTH_PROXY +template<> +const char *proto_enum_to_string(enums::BluetoothDeviceRequestType value) { + switch (value) { + case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT: + return "BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT"; + case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_DISCONNECT: + return "BLUETOOTH_DEVICE_REQUEST_TYPE_DISCONNECT"; + case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_PAIR: + return "BLUETOOTH_DEVICE_REQUEST_TYPE_PAIR"; + case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_UNPAIR: + return "BLUETOOTH_DEVICE_REQUEST_TYPE_UNPAIR"; + case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITH_CACHE: + return "BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITH_CACHE"; + case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITHOUT_CACHE: + return "BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITHOUT_CACHE"; + case enums::BLUETOOTH_DEVICE_REQUEST_TYPE_CLEAR_CACHE: + return "BLUETOOTH_DEVICE_REQUEST_TYPE_CLEAR_CACHE"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::BluetoothScannerState value) { + switch (value) { + case enums::BLUETOOTH_SCANNER_STATE_IDLE: + return "BLUETOOTH_SCANNER_STATE_IDLE"; + case enums::BLUETOOTH_SCANNER_STATE_STARTING: + return "BLUETOOTH_SCANNER_STATE_STARTING"; + case enums::BLUETOOTH_SCANNER_STATE_RUNNING: + return "BLUETOOTH_SCANNER_STATE_RUNNING"; + case enums::BLUETOOTH_SCANNER_STATE_FAILED: + return "BLUETOOTH_SCANNER_STATE_FAILED"; + case enums::BLUETOOTH_SCANNER_STATE_STOPPING: + return "BLUETOOTH_SCANNER_STATE_STOPPING"; + case enums::BLUETOOTH_SCANNER_STATE_STOPPED: + return "BLUETOOTH_SCANNER_STATE_STOPPED"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::BluetoothScannerMode value) { + switch (value) { + case enums::BLUETOOTH_SCANNER_MODE_PASSIVE: + return "BLUETOOTH_SCANNER_MODE_PASSIVE"; + case enums::BLUETOOTH_SCANNER_MODE_ACTIVE: + return "BLUETOOTH_SCANNER_MODE_ACTIVE"; + default: + return "UNKNOWN"; + } +} +#endif +template<> +const char *proto_enum_to_string(enums::VoiceAssistantSubscribeFlag value) { + switch (value) { + case enums::VOICE_ASSISTANT_SUBSCRIBE_NONE: + return "VOICE_ASSISTANT_SUBSCRIBE_NONE"; + case enums::VOICE_ASSISTANT_SUBSCRIBE_API_AUDIO: + return "VOICE_ASSISTANT_SUBSCRIBE_API_AUDIO"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::VoiceAssistantRequestFlag value) { + switch (value) { + case enums::VOICE_ASSISTANT_REQUEST_NONE: + return "VOICE_ASSISTANT_REQUEST_NONE"; + case enums::VOICE_ASSISTANT_REQUEST_USE_VAD: + return "VOICE_ASSISTANT_REQUEST_USE_VAD"; + case enums::VOICE_ASSISTANT_REQUEST_USE_WAKE_WORD: + return "VOICE_ASSISTANT_REQUEST_USE_WAKE_WORD"; + default: + return "UNKNOWN"; + } +} +#ifdef USE_VOICE_ASSISTANT +template<> const char *proto_enum_to_string(enums::VoiceAssistantEvent value) { + switch (value) { + case enums::VOICE_ASSISTANT_ERROR: + return "VOICE_ASSISTANT_ERROR"; + case enums::VOICE_ASSISTANT_RUN_START: + return "VOICE_ASSISTANT_RUN_START"; + case enums::VOICE_ASSISTANT_RUN_END: + return "VOICE_ASSISTANT_RUN_END"; + case enums::VOICE_ASSISTANT_STT_START: + return "VOICE_ASSISTANT_STT_START"; + case enums::VOICE_ASSISTANT_STT_END: + return "VOICE_ASSISTANT_STT_END"; + case enums::VOICE_ASSISTANT_INTENT_START: + return "VOICE_ASSISTANT_INTENT_START"; + case enums::VOICE_ASSISTANT_INTENT_END: + return "VOICE_ASSISTANT_INTENT_END"; + case enums::VOICE_ASSISTANT_TTS_START: + return "VOICE_ASSISTANT_TTS_START"; + case enums::VOICE_ASSISTANT_TTS_END: + return "VOICE_ASSISTANT_TTS_END"; + case enums::VOICE_ASSISTANT_WAKE_WORD_START: + return "VOICE_ASSISTANT_WAKE_WORD_START"; + case enums::VOICE_ASSISTANT_WAKE_WORD_END: + return "VOICE_ASSISTANT_WAKE_WORD_END"; + case enums::VOICE_ASSISTANT_STT_VAD_START: + return "VOICE_ASSISTANT_STT_VAD_START"; + case enums::VOICE_ASSISTANT_STT_VAD_END: + return "VOICE_ASSISTANT_STT_VAD_END"; + case enums::VOICE_ASSISTANT_TTS_STREAM_START: + return "VOICE_ASSISTANT_TTS_STREAM_START"; + case enums::VOICE_ASSISTANT_TTS_STREAM_END: + return "VOICE_ASSISTANT_TTS_STREAM_END"; + case enums::VOICE_ASSISTANT_INTENT_PROGRESS: + return "VOICE_ASSISTANT_INTENT_PROGRESS"; + default: + return "UNKNOWN"; + } +} +template<> const char *proto_enum_to_string(enums::VoiceAssistantTimerEvent value) { + switch (value) { + case enums::VOICE_ASSISTANT_TIMER_STARTED: + return "VOICE_ASSISTANT_TIMER_STARTED"; + case enums::VOICE_ASSISTANT_TIMER_UPDATED: + return "VOICE_ASSISTANT_TIMER_UPDATED"; + case enums::VOICE_ASSISTANT_TIMER_CANCELLED: + return "VOICE_ASSISTANT_TIMER_CANCELLED"; + case enums::VOICE_ASSISTANT_TIMER_FINISHED: + return "VOICE_ASSISTANT_TIMER_FINISHED"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_ALARM_CONTROL_PANEL +template<> const char *proto_enum_to_string(enums::AlarmControlPanelState value) { + switch (value) { + case enums::ALARM_STATE_DISARMED: + return "ALARM_STATE_DISARMED"; + case enums::ALARM_STATE_ARMED_HOME: + return "ALARM_STATE_ARMED_HOME"; + case enums::ALARM_STATE_ARMED_AWAY: + return "ALARM_STATE_ARMED_AWAY"; + case enums::ALARM_STATE_ARMED_NIGHT: + return "ALARM_STATE_ARMED_NIGHT"; + case enums::ALARM_STATE_ARMED_VACATION: + return "ALARM_STATE_ARMED_VACATION"; + case enums::ALARM_STATE_ARMED_CUSTOM_BYPASS: + return "ALARM_STATE_ARMED_CUSTOM_BYPASS"; + case enums::ALARM_STATE_PENDING: + return "ALARM_STATE_PENDING"; + case enums::ALARM_STATE_ARMING: + return "ALARM_STATE_ARMING"; + case enums::ALARM_STATE_DISARMING: + return "ALARM_STATE_DISARMING"; + case enums::ALARM_STATE_TRIGGERED: + return "ALARM_STATE_TRIGGERED"; + default: + return "UNKNOWN"; + } +} +template<> +const char *proto_enum_to_string(enums::AlarmControlPanelStateCommand value) { + switch (value) { + case enums::ALARM_CONTROL_PANEL_DISARM: + return "ALARM_CONTROL_PANEL_DISARM"; + case enums::ALARM_CONTROL_PANEL_ARM_AWAY: + return "ALARM_CONTROL_PANEL_ARM_AWAY"; + case enums::ALARM_CONTROL_PANEL_ARM_HOME: + return "ALARM_CONTROL_PANEL_ARM_HOME"; + case enums::ALARM_CONTROL_PANEL_ARM_NIGHT: + return "ALARM_CONTROL_PANEL_ARM_NIGHT"; + case enums::ALARM_CONTROL_PANEL_ARM_VACATION: + return "ALARM_CONTROL_PANEL_ARM_VACATION"; + case enums::ALARM_CONTROL_PANEL_ARM_CUSTOM_BYPASS: + return "ALARM_CONTROL_PANEL_ARM_CUSTOM_BYPASS"; + case enums::ALARM_CONTROL_PANEL_TRIGGER: + return "ALARM_CONTROL_PANEL_TRIGGER"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_TEXT +template<> const char *proto_enum_to_string(enums::TextMode value) { + switch (value) { + case enums::TEXT_MODE_TEXT: + return "TEXT_MODE_TEXT"; + case enums::TEXT_MODE_PASSWORD: + return "TEXT_MODE_PASSWORD"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_VALVE +template<> const char *proto_enum_to_string(enums::ValveOperation value) { + switch (value) { + case enums::VALVE_OPERATION_IDLE: + return "VALVE_OPERATION_IDLE"; + case enums::VALVE_OPERATION_IS_OPENING: + return "VALVE_OPERATION_IS_OPENING"; + case enums::VALVE_OPERATION_IS_CLOSING: + return "VALVE_OPERATION_IS_CLOSING"; + default: + return "UNKNOWN"; + } +} +#endif +#ifdef USE_UPDATE +template<> const char *proto_enum_to_string(enums::UpdateCommand value) { + switch (value) { + case enums::UPDATE_COMMAND_NONE: + return "UPDATE_COMMAND_NONE"; + case enums::UPDATE_COMMAND_UPDATE: + return "UPDATE_COMMAND_UPDATE"; + case enums::UPDATE_COMMAND_CHECK: + return "UPDATE_COMMAND_CHECK"; + default: + return "UNKNOWN"; + } +} +#endif + +void HelloRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("HelloRequest {\n"); + out.append(" client_info: "); + out.append("'").append(this->client_info).append("'"); + out.append("\n"); + + out.append(" api_version_major: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->api_version_major); + out.append(buffer); + out.append("\n"); + + out.append(" api_version_minor: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->api_version_minor); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void HelloResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("HelloResponse {\n"); + out.append(" api_version_major: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->api_version_major); + out.append(buffer); + out.append("\n"); + + out.append(" api_version_minor: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->api_version_minor); + out.append(buffer); + out.append("\n"); + + out.append(" server_info: "); + out.append("'").append(this->server_info).append("'"); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + out.append("}"); +} +void ConnectRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ConnectRequest {\n"); + out.append(" password: "); + out.append("'").append(this->password).append("'"); + out.append("\n"); + out.append("}"); +} +void ConnectResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ConnectResponse {\n"); + out.append(" invalid_password: "); + out.append(YESNO(this->invalid_password)); + out.append("\n"); + out.append("}"); +} +void DisconnectRequest::dump_to(std::string &out) const { out.append("DisconnectRequest {}"); } +void DisconnectResponse::dump_to(std::string &out) const { out.append("DisconnectResponse {}"); } +void PingRequest::dump_to(std::string &out) const { out.append("PingRequest {}"); } +void PingResponse::dump_to(std::string &out) const { out.append("PingResponse {}"); } +void DeviceInfoRequest::dump_to(std::string &out) const { out.append("DeviceInfoRequest {}"); } +void AreaInfo::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("AreaInfo {\n"); + out.append(" area_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->area_id); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + out.append("}"); +} +void DeviceInfo::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("DeviceInfo {\n"); + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" area_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->area_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void DeviceInfoResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("DeviceInfoResponse {\n"); + out.append(" uses_password: "); + out.append(YESNO(this->uses_password)); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" mac_address: "); + out.append("'").append(this->mac_address).append("'"); + out.append("\n"); + + out.append(" esphome_version: "); + out.append("'").append(this->esphome_version).append("'"); + out.append("\n"); + + out.append(" compilation_time: "); + out.append("'").append(this->compilation_time).append("'"); + out.append("\n"); + + out.append(" model: "); + out.append("'").append(this->model).append("'"); + out.append("\n"); + + out.append(" has_deep_sleep: "); + out.append(YESNO(this->has_deep_sleep)); + out.append("\n"); + + out.append(" project_name: "); + out.append("'").append(this->project_name).append("'"); + out.append("\n"); + + out.append(" project_version: "); + out.append("'").append(this->project_version).append("'"); + out.append("\n"); + + out.append(" webserver_port: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->webserver_port); + out.append(buffer); + out.append("\n"); + + out.append(" legacy_bluetooth_proxy_version: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->legacy_bluetooth_proxy_version); + out.append(buffer); + out.append("\n"); + + out.append(" bluetooth_proxy_feature_flags: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->bluetooth_proxy_feature_flags); + out.append(buffer); + out.append("\n"); + + out.append(" manufacturer: "); + out.append("'").append(this->manufacturer).append("'"); + out.append("\n"); + + out.append(" friendly_name: "); + out.append("'").append(this->friendly_name).append("'"); + out.append("\n"); + + out.append(" legacy_voice_assistant_version: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->legacy_voice_assistant_version); + out.append(buffer); + out.append("\n"); + + out.append(" voice_assistant_feature_flags: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->voice_assistant_feature_flags); + out.append(buffer); + out.append("\n"); + + out.append(" suggested_area: "); + out.append("'").append(this->suggested_area).append("'"); + out.append("\n"); + + out.append(" bluetooth_mac_address: "); + out.append("'").append(this->bluetooth_mac_address).append("'"); + out.append("\n"); + + out.append(" api_encryption_supported: "); + out.append(YESNO(this->api_encryption_supported)); + out.append("\n"); + + for (const auto &it : this->devices) { + out.append(" devices: "); + it.dump_to(out); + out.append("\n"); + } + + for (const auto &it : this->areas) { + out.append(" areas: "); + it.dump_to(out); + out.append("\n"); + } + + out.append(" area: "); + this->area.dump_to(out); + out.append("\n"); + out.append("}"); +} +void ListEntitiesRequest::dump_to(std::string &out) const { out.append("ListEntitiesRequest {}"); } +void ListEntitiesDoneResponse::dump_to(std::string &out) const { out.append("ListEntitiesDoneResponse {}"); } +void SubscribeStatesRequest::dump_to(std::string &out) const { out.append("SubscribeStatesRequest {}"); } +#ifdef USE_BINARY_SENSOR +void ListEntitiesBinarySensorResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesBinarySensorResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" device_class: "); + out.append("'").append(this->device_class).append("'"); + out.append("\n"); + + out.append(" is_status_binary_sensor: "); + out.append(YESNO(this->is_status_binary_sensor)); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BinarySensorStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BinarySensorStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append(YESNO(this->state)); + out.append("\n"); + + out.append(" missing_state: "); + out.append(YESNO(this->missing_state)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_COVER +void ListEntitiesCoverResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesCoverResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" assumed_state: "); + out.append(YESNO(this->assumed_state)); + out.append("\n"); + + out.append(" supports_position: "); + out.append(YESNO(this->supports_position)); + out.append("\n"); + + out.append(" supports_tilt: "); + out.append(YESNO(this->supports_tilt)); + out.append("\n"); + + out.append(" device_class: "); + out.append("'").append(this->device_class).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" supports_stop: "); + out.append(YESNO(this->supports_stop)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void CoverStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("CoverStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" legacy_state: "); + out.append(proto_enum_to_string(this->legacy_state)); + out.append("\n"); + + out.append(" position: "); + snprintf(buffer, sizeof(buffer), "%g", this->position); + out.append(buffer); + out.append("\n"); + + out.append(" tilt: "); + snprintf(buffer, sizeof(buffer), "%g", this->tilt); + out.append(buffer); + out.append("\n"); + + out.append(" current_operation: "); + out.append(proto_enum_to_string(this->current_operation)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void CoverCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("CoverCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" has_legacy_command: "); + out.append(YESNO(this->has_legacy_command)); + out.append("\n"); + + out.append(" legacy_command: "); + out.append(proto_enum_to_string(this->legacy_command)); + out.append("\n"); + + out.append(" has_position: "); + out.append(YESNO(this->has_position)); + out.append("\n"); + + out.append(" position: "); + snprintf(buffer, sizeof(buffer), "%g", this->position); + out.append(buffer); + out.append("\n"); + + out.append(" has_tilt: "); + out.append(YESNO(this->has_tilt)); + out.append("\n"); + + out.append(" tilt: "); + snprintf(buffer, sizeof(buffer), "%g", this->tilt); + out.append(buffer); + out.append("\n"); + + out.append(" stop: "); + out.append(YESNO(this->stop)); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_FAN +void ListEntitiesFanResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesFanResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" supports_oscillation: "); + out.append(YESNO(this->supports_oscillation)); + out.append("\n"); + + out.append(" supports_speed: "); + out.append(YESNO(this->supports_speed)); + out.append("\n"); + + out.append(" supports_direction: "); + out.append(YESNO(this->supports_direction)); + out.append("\n"); + + out.append(" supported_speed_count: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->supported_speed_count); + out.append(buffer); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + for (const auto &it : this->supported_preset_modes) { + out.append(" supported_preset_modes: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void FanStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("FanStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append(YESNO(this->state)); + out.append("\n"); + + out.append(" oscillating: "); + out.append(YESNO(this->oscillating)); + out.append("\n"); + + out.append(" speed: "); + out.append(proto_enum_to_string(this->speed)); + out.append("\n"); + + out.append(" direction: "); + out.append(proto_enum_to_string(this->direction)); + out.append("\n"); + + out.append(" speed_level: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->speed_level); + out.append(buffer); + out.append("\n"); + + out.append(" preset_mode: "); + out.append("'").append(this->preset_mode).append("'"); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void FanCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("FanCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" has_state: "); + out.append(YESNO(this->has_state)); + out.append("\n"); + + out.append(" state: "); + out.append(YESNO(this->state)); + out.append("\n"); + + out.append(" has_speed: "); + out.append(YESNO(this->has_speed)); + out.append("\n"); + + out.append(" speed: "); + out.append(proto_enum_to_string(this->speed)); + out.append("\n"); + + out.append(" has_oscillating: "); + out.append(YESNO(this->has_oscillating)); + out.append("\n"); + + out.append(" oscillating: "); + out.append(YESNO(this->oscillating)); + out.append("\n"); + + out.append(" has_direction: "); + out.append(YESNO(this->has_direction)); + out.append("\n"); + + out.append(" direction: "); + out.append(proto_enum_to_string(this->direction)); + out.append("\n"); + + out.append(" has_speed_level: "); + out.append(YESNO(this->has_speed_level)); + out.append("\n"); + + out.append(" speed_level: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->speed_level); + out.append(buffer); + out.append("\n"); + + out.append(" has_preset_mode: "); + out.append(YESNO(this->has_preset_mode)); + out.append("\n"); + + out.append(" preset_mode: "); + out.append("'").append(this->preset_mode).append("'"); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_LIGHT +void ListEntitiesLightResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesLightResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + for (const auto &it : this->supported_color_modes) { + out.append(" supported_color_modes: "); + out.append(proto_enum_to_string(it)); + out.append("\n"); + } + + out.append(" legacy_supports_brightness: "); + out.append(YESNO(this->legacy_supports_brightness)); + out.append("\n"); + + out.append(" legacy_supports_rgb: "); + out.append(YESNO(this->legacy_supports_rgb)); + out.append("\n"); + + out.append(" legacy_supports_white_value: "); + out.append(YESNO(this->legacy_supports_white_value)); + out.append("\n"); + + out.append(" legacy_supports_color_temperature: "); + out.append(YESNO(this->legacy_supports_color_temperature)); + out.append("\n"); + + out.append(" min_mireds: "); + snprintf(buffer, sizeof(buffer), "%g", this->min_mireds); + out.append(buffer); + out.append("\n"); + + out.append(" max_mireds: "); + snprintf(buffer, sizeof(buffer), "%g", this->max_mireds); + out.append(buffer); + out.append("\n"); + + for (const auto &it : this->effects) { + out.append(" effects: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void LightStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("LightStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append(YESNO(this->state)); + out.append("\n"); + + out.append(" brightness: "); + snprintf(buffer, sizeof(buffer), "%g", this->brightness); + out.append(buffer); + out.append("\n"); + + out.append(" color_mode: "); + out.append(proto_enum_to_string(this->color_mode)); + out.append("\n"); + + out.append(" color_brightness: "); + snprintf(buffer, sizeof(buffer), "%g", this->color_brightness); + out.append(buffer); + out.append("\n"); + + out.append(" red: "); + snprintf(buffer, sizeof(buffer), "%g", this->red); + out.append(buffer); + out.append("\n"); + + out.append(" green: "); + snprintf(buffer, sizeof(buffer), "%g", this->green); + out.append(buffer); + out.append("\n"); + + out.append(" blue: "); + snprintf(buffer, sizeof(buffer), "%g", this->blue); + out.append(buffer); + out.append("\n"); + + out.append(" white: "); + snprintf(buffer, sizeof(buffer), "%g", this->white); + out.append(buffer); + out.append("\n"); + + out.append(" color_temperature: "); + snprintf(buffer, sizeof(buffer), "%g", this->color_temperature); + out.append(buffer); + out.append("\n"); + + out.append(" cold_white: "); + snprintf(buffer, sizeof(buffer), "%g", this->cold_white); + out.append(buffer); + out.append("\n"); + + out.append(" warm_white: "); + snprintf(buffer, sizeof(buffer), "%g", this->warm_white); + out.append(buffer); + out.append("\n"); + + out.append(" effect: "); + out.append("'").append(this->effect).append("'"); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void LightCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("LightCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" has_state: "); + out.append(YESNO(this->has_state)); + out.append("\n"); + + out.append(" state: "); + out.append(YESNO(this->state)); + out.append("\n"); + + out.append(" has_brightness: "); + out.append(YESNO(this->has_brightness)); + out.append("\n"); + + out.append(" brightness: "); + snprintf(buffer, sizeof(buffer), "%g", this->brightness); + out.append(buffer); + out.append("\n"); + + out.append(" has_color_mode: "); + out.append(YESNO(this->has_color_mode)); + out.append("\n"); + + out.append(" color_mode: "); + out.append(proto_enum_to_string(this->color_mode)); + out.append("\n"); + + out.append(" has_color_brightness: "); + out.append(YESNO(this->has_color_brightness)); + out.append("\n"); + + out.append(" color_brightness: "); + snprintf(buffer, sizeof(buffer), "%g", this->color_brightness); + out.append(buffer); + out.append("\n"); + + out.append(" has_rgb: "); + out.append(YESNO(this->has_rgb)); + out.append("\n"); + + out.append(" red: "); + snprintf(buffer, sizeof(buffer), "%g", this->red); + out.append(buffer); + out.append("\n"); + + out.append(" green: "); + snprintf(buffer, sizeof(buffer), "%g", this->green); + out.append(buffer); + out.append("\n"); + + out.append(" blue: "); + snprintf(buffer, sizeof(buffer), "%g", this->blue); + out.append(buffer); + out.append("\n"); + + out.append(" has_white: "); + out.append(YESNO(this->has_white)); + out.append("\n"); + + out.append(" white: "); + snprintf(buffer, sizeof(buffer), "%g", this->white); + out.append(buffer); + out.append("\n"); + + out.append(" has_color_temperature: "); + out.append(YESNO(this->has_color_temperature)); + out.append("\n"); + + out.append(" color_temperature: "); + snprintf(buffer, sizeof(buffer), "%g", this->color_temperature); + out.append(buffer); + out.append("\n"); + + out.append(" has_cold_white: "); + out.append(YESNO(this->has_cold_white)); + out.append("\n"); + + out.append(" cold_white: "); + snprintf(buffer, sizeof(buffer), "%g", this->cold_white); + out.append(buffer); + out.append("\n"); + + out.append(" has_warm_white: "); + out.append(YESNO(this->has_warm_white)); + out.append("\n"); + + out.append(" warm_white: "); + snprintf(buffer, sizeof(buffer), "%g", this->warm_white); + out.append(buffer); + out.append("\n"); + + out.append(" has_transition_length: "); + out.append(YESNO(this->has_transition_length)); + out.append("\n"); + + out.append(" transition_length: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->transition_length); + out.append(buffer); + out.append("\n"); + + out.append(" has_flash_length: "); + out.append(YESNO(this->has_flash_length)); + out.append("\n"); + + out.append(" flash_length: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->flash_length); + out.append(buffer); + out.append("\n"); + + out.append(" has_effect: "); + out.append(YESNO(this->has_effect)); + out.append("\n"); + + out.append(" effect: "); + out.append("'").append(this->effect).append("'"); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_SENSOR +void ListEntitiesSensorResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesSensorResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" unit_of_measurement: "); + out.append("'").append(this->unit_of_measurement).append("'"); + out.append("\n"); + + out.append(" accuracy_decimals: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->accuracy_decimals); + out.append(buffer); + out.append("\n"); + + out.append(" force_update: "); + out.append(YESNO(this->force_update)); + out.append("\n"); + + out.append(" device_class: "); + out.append("'").append(this->device_class).append("'"); + out.append("\n"); + + out.append(" state_class: "); + out.append(proto_enum_to_string(this->state_class)); + out.append("\n"); + + out.append(" legacy_last_reset_type: "); + out.append(proto_enum_to_string(this->legacy_last_reset_type)); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void SensorStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SensorStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + snprintf(buffer, sizeof(buffer), "%g", this->state); + out.append(buffer); + out.append("\n"); + + out.append(" missing_state: "); + out.append(YESNO(this->missing_state)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_SWITCH +void ListEntitiesSwitchResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesSwitchResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" assumed_state: "); + out.append(YESNO(this->assumed_state)); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_class: "); + out.append("'").append(this->device_class).append("'"); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void SwitchStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SwitchStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append(YESNO(this->state)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void SwitchCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SwitchCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append(YESNO(this->state)); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_TEXT_SENSOR +void ListEntitiesTextSensorResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesTextSensorResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_class: "); + out.append("'").append(this->device_class).append("'"); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void TextSensorStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("TextSensorStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append("'").append(this->state).append("'"); + out.append("\n"); + + out.append(" missing_state: "); + out.append(YESNO(this->missing_state)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +void SubscribeLogsRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SubscribeLogsRequest {\n"); + out.append(" level: "); + out.append(proto_enum_to_string(this->level)); + out.append("\n"); + + out.append(" dump_config: "); + out.append(YESNO(this->dump_config)); + out.append("\n"); + out.append("}"); +} +void SubscribeLogsResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SubscribeLogsResponse {\n"); + out.append(" level: "); + out.append(proto_enum_to_string(this->level)); + out.append("\n"); + + out.append(" message: "); + out.append(format_hex_pretty(this->message)); + out.append("\n"); + + out.append(" send_failed: "); + out.append(YESNO(this->send_failed)); + out.append("\n"); + out.append("}"); +} +#ifdef USE_API_NOISE +void NoiseEncryptionSetKeyRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("NoiseEncryptionSetKeyRequest {\n"); + out.append(" key: "); + out.append(format_hex_pretty(this->key)); + out.append("\n"); + out.append("}"); +} +void NoiseEncryptionSetKeyResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("NoiseEncryptionSetKeyResponse {\n"); + out.append(" success: "); + out.append(YESNO(this->success)); + out.append("\n"); + out.append("}"); +} +#endif +void SubscribeHomeassistantServicesRequest::dump_to(std::string &out) const { + out.append("SubscribeHomeassistantServicesRequest {}"); +} +void HomeassistantServiceMap::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("HomeassistantServiceMap {\n"); + out.append(" key: "); + out.append("'").append(this->key).append("'"); + out.append("\n"); + + out.append(" value: "); + out.append("'").append(this->value).append("'"); + out.append("\n"); + out.append("}"); +} +void HomeassistantServiceResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("HomeassistantServiceResponse {\n"); + out.append(" service: "); + out.append("'").append(this->service).append("'"); + out.append("\n"); + + for (const auto &it : this->data) { + out.append(" data: "); + it.dump_to(out); + out.append("\n"); + } + + for (const auto &it : this->data_template) { + out.append(" data_template: "); + it.dump_to(out); + out.append("\n"); + } + + for (const auto &it : this->variables) { + out.append(" variables: "); + it.dump_to(out); + out.append("\n"); + } + + out.append(" is_event: "); + out.append(YESNO(this->is_event)); + out.append("\n"); + out.append("}"); +} +void SubscribeHomeAssistantStatesRequest::dump_to(std::string &out) const { + out.append("SubscribeHomeAssistantStatesRequest {}"); +} +void SubscribeHomeAssistantStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SubscribeHomeAssistantStateResponse {\n"); + out.append(" entity_id: "); + out.append("'").append(this->entity_id).append("'"); + out.append("\n"); + + out.append(" attribute: "); + out.append("'").append(this->attribute).append("'"); + out.append("\n"); + + out.append(" once: "); + out.append(YESNO(this->once)); + out.append("\n"); + out.append("}"); +} +void HomeAssistantStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("HomeAssistantStateResponse {\n"); + out.append(" entity_id: "); + out.append("'").append(this->entity_id).append("'"); + out.append("\n"); + + out.append(" state: "); + out.append("'").append(this->state).append("'"); + out.append("\n"); + + out.append(" attribute: "); + out.append("'").append(this->attribute).append("'"); + out.append("\n"); + out.append("}"); +} +void GetTimeRequest::dump_to(std::string &out) const { out.append("GetTimeRequest {}"); } +void GetTimeResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("GetTimeResponse {\n"); + out.append(" epoch_seconds: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->epoch_seconds); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void ListEntitiesServicesArgument::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesServicesArgument {\n"); + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" type: "); + out.append(proto_enum_to_string(this->type)); + out.append("\n"); + out.append("}"); +} +void ListEntitiesServicesResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesServicesResponse {\n"); + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + for (const auto &it : this->args) { + out.append(" args: "); + it.dump_to(out); + out.append("\n"); + } + out.append("}"); +} +void ExecuteServiceArgument::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ExecuteServiceArgument {\n"); + out.append(" bool_: "); + out.append(YESNO(this->bool_)); + out.append("\n"); + + out.append(" legacy_int: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->legacy_int); + out.append(buffer); + out.append("\n"); + + out.append(" float_: "); + snprintf(buffer, sizeof(buffer), "%g", this->float_); + out.append(buffer); + out.append("\n"); + + out.append(" string_: "); + out.append("'").append(this->string_).append("'"); + out.append("\n"); + + out.append(" int_: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->int_); + out.append(buffer); + out.append("\n"); + + for (const auto it : this->bool_array) { + out.append(" bool_array: "); + out.append(YESNO(it)); + out.append("\n"); + } + + for (const auto &it : this->int_array) { + out.append(" int_array: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, it); + out.append(buffer); + out.append("\n"); + } + + for (const auto &it : this->float_array) { + out.append(" float_array: "); + snprintf(buffer, sizeof(buffer), "%g", it); + out.append(buffer); + out.append("\n"); + } + + for (const auto &it : this->string_array) { + out.append(" string_array: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + out.append("}"); +} +void ExecuteServiceRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ExecuteServiceRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + for (const auto &it : this->args) { + out.append(" args: "); + it.dump_to(out); + out.append("\n"); + } + out.append("}"); +} +#ifdef USE_CAMERA +void ListEntitiesCameraResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesCameraResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void CameraImageResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("CameraImageResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" data: "); + out.append(format_hex_pretty(this->data)); + out.append("\n"); + + out.append(" done: "); + out.append(YESNO(this->done)); + out.append("\n"); + out.append("}"); +} +void CameraImageRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("CameraImageRequest {\n"); + out.append(" single: "); + out.append(YESNO(this->single)); + out.append("\n"); + + out.append(" stream: "); + out.append(YESNO(this->stream)); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_CLIMATE +void ListEntitiesClimateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesClimateResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" supports_current_temperature: "); + out.append(YESNO(this->supports_current_temperature)); + out.append("\n"); + + out.append(" supports_two_point_target_temperature: "); + out.append(YESNO(this->supports_two_point_target_temperature)); + out.append("\n"); + + for (const auto &it : this->supported_modes) { + out.append(" supported_modes: "); + out.append(proto_enum_to_string(it)); + out.append("\n"); + } + + out.append(" visual_min_temperature: "); + snprintf(buffer, sizeof(buffer), "%g", this->visual_min_temperature); + out.append(buffer); + out.append("\n"); + + out.append(" visual_max_temperature: "); + snprintf(buffer, sizeof(buffer), "%g", this->visual_max_temperature); + out.append(buffer); + out.append("\n"); + + out.append(" visual_target_temperature_step: "); + snprintf(buffer, sizeof(buffer), "%g", this->visual_target_temperature_step); + out.append(buffer); + out.append("\n"); + + out.append(" legacy_supports_away: "); + out.append(YESNO(this->legacy_supports_away)); + out.append("\n"); + + out.append(" supports_action: "); + out.append(YESNO(this->supports_action)); + out.append("\n"); + + for (const auto &it : this->supported_fan_modes) { + out.append(" supported_fan_modes: "); + out.append(proto_enum_to_string(it)); + out.append("\n"); + } + + for (const auto &it : this->supported_swing_modes) { + out.append(" supported_swing_modes: "); + out.append(proto_enum_to_string(it)); + out.append("\n"); + } + + for (const auto &it : this->supported_custom_fan_modes) { + out.append(" supported_custom_fan_modes: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + + for (const auto &it : this->supported_presets) { + out.append(" supported_presets: "); + out.append(proto_enum_to_string(it)); + out.append("\n"); + } + + for (const auto &it : this->supported_custom_presets) { + out.append(" supported_custom_presets: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" visual_current_temperature_step: "); + snprintf(buffer, sizeof(buffer), "%g", this->visual_current_temperature_step); + out.append(buffer); + out.append("\n"); + + out.append(" supports_current_humidity: "); + out.append(YESNO(this->supports_current_humidity)); + out.append("\n"); + + out.append(" supports_target_humidity: "); + out.append(YESNO(this->supports_target_humidity)); + out.append("\n"); + + out.append(" visual_min_humidity: "); + snprintf(buffer, sizeof(buffer), "%g", this->visual_min_humidity); + out.append(buffer); + out.append("\n"); + + out.append(" visual_max_humidity: "); + snprintf(buffer, sizeof(buffer), "%g", this->visual_max_humidity); + out.append(buffer); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void ClimateStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ClimateStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" mode: "); + out.append(proto_enum_to_string(this->mode)); + out.append("\n"); + + out.append(" current_temperature: "); + snprintf(buffer, sizeof(buffer), "%g", this->current_temperature); + out.append(buffer); + out.append("\n"); + + out.append(" target_temperature: "); + snprintf(buffer, sizeof(buffer), "%g", this->target_temperature); + out.append(buffer); + out.append("\n"); + + out.append(" target_temperature_low: "); + snprintf(buffer, sizeof(buffer), "%g", this->target_temperature_low); + out.append(buffer); + out.append("\n"); + + out.append(" target_temperature_high: "); + snprintf(buffer, sizeof(buffer), "%g", this->target_temperature_high); + out.append(buffer); + out.append("\n"); + + out.append(" unused_legacy_away: "); + out.append(YESNO(this->unused_legacy_away)); + out.append("\n"); + + out.append(" action: "); + out.append(proto_enum_to_string(this->action)); + out.append("\n"); + + out.append(" fan_mode: "); + out.append(proto_enum_to_string(this->fan_mode)); + out.append("\n"); + + out.append(" swing_mode: "); + out.append(proto_enum_to_string(this->swing_mode)); + out.append("\n"); + + out.append(" custom_fan_mode: "); + out.append("'").append(this->custom_fan_mode).append("'"); + out.append("\n"); + + out.append(" preset: "); + out.append(proto_enum_to_string(this->preset)); + out.append("\n"); + + out.append(" custom_preset: "); + out.append("'").append(this->custom_preset).append("'"); + out.append("\n"); + + out.append(" current_humidity: "); + snprintf(buffer, sizeof(buffer), "%g", this->current_humidity); + out.append(buffer); + out.append("\n"); + + out.append(" target_humidity: "); + snprintf(buffer, sizeof(buffer), "%g", this->target_humidity); + out.append(buffer); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void ClimateCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ClimateCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" has_mode: "); + out.append(YESNO(this->has_mode)); + out.append("\n"); + + out.append(" mode: "); + out.append(proto_enum_to_string(this->mode)); + out.append("\n"); + + out.append(" has_target_temperature: "); + out.append(YESNO(this->has_target_temperature)); + out.append("\n"); + + out.append(" target_temperature: "); + snprintf(buffer, sizeof(buffer), "%g", this->target_temperature); + out.append(buffer); + out.append("\n"); + + out.append(" has_target_temperature_low: "); + out.append(YESNO(this->has_target_temperature_low)); + out.append("\n"); + + out.append(" target_temperature_low: "); + snprintf(buffer, sizeof(buffer), "%g", this->target_temperature_low); + out.append(buffer); + out.append("\n"); + + out.append(" has_target_temperature_high: "); + out.append(YESNO(this->has_target_temperature_high)); + out.append("\n"); + + out.append(" target_temperature_high: "); + snprintf(buffer, sizeof(buffer), "%g", this->target_temperature_high); + out.append(buffer); + out.append("\n"); + + out.append(" unused_has_legacy_away: "); + out.append(YESNO(this->unused_has_legacy_away)); + out.append("\n"); + + out.append(" unused_legacy_away: "); + out.append(YESNO(this->unused_legacy_away)); + out.append("\n"); + + out.append(" has_fan_mode: "); + out.append(YESNO(this->has_fan_mode)); + out.append("\n"); + + out.append(" fan_mode: "); + out.append(proto_enum_to_string(this->fan_mode)); + out.append("\n"); + + out.append(" has_swing_mode: "); + out.append(YESNO(this->has_swing_mode)); + out.append("\n"); + + out.append(" swing_mode: "); + out.append(proto_enum_to_string(this->swing_mode)); + out.append("\n"); + + out.append(" has_custom_fan_mode: "); + out.append(YESNO(this->has_custom_fan_mode)); + out.append("\n"); + + out.append(" custom_fan_mode: "); + out.append("'").append(this->custom_fan_mode).append("'"); + out.append("\n"); + + out.append(" has_preset: "); + out.append(YESNO(this->has_preset)); + out.append("\n"); + + out.append(" preset: "); + out.append(proto_enum_to_string(this->preset)); + out.append("\n"); + + out.append(" has_custom_preset: "); + out.append(YESNO(this->has_custom_preset)); + out.append("\n"); + + out.append(" custom_preset: "); + out.append("'").append(this->custom_preset).append("'"); + out.append("\n"); + + out.append(" has_target_humidity: "); + out.append(YESNO(this->has_target_humidity)); + out.append("\n"); + + out.append(" target_humidity: "); + snprintf(buffer, sizeof(buffer), "%g", this->target_humidity); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_NUMBER +void ListEntitiesNumberResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesNumberResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" min_value: "); + snprintf(buffer, sizeof(buffer), "%g", this->min_value); + out.append(buffer); + out.append("\n"); + + out.append(" max_value: "); + snprintf(buffer, sizeof(buffer), "%g", this->max_value); + out.append(buffer); + out.append("\n"); + + out.append(" step: "); + snprintf(buffer, sizeof(buffer), "%g", this->step); + out.append(buffer); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" unit_of_measurement: "); + out.append("'").append(this->unit_of_measurement).append("'"); + out.append("\n"); + + out.append(" mode: "); + out.append(proto_enum_to_string(this->mode)); + out.append("\n"); + + out.append(" device_class: "); + out.append("'").append(this->device_class).append("'"); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void NumberStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("NumberStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + snprintf(buffer, sizeof(buffer), "%g", this->state); + out.append(buffer); + out.append("\n"); + + out.append(" missing_state: "); + out.append(YESNO(this->missing_state)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void NumberCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("NumberCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + snprintf(buffer, sizeof(buffer), "%g", this->state); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_SELECT +void ListEntitiesSelectResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesSelectResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + for (const auto &it : this->options) { + out.append(" options: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void SelectStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SelectStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append("'").append(this->state).append("'"); + out.append("\n"); + + out.append(" missing_state: "); + out.append(YESNO(this->missing_state)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void SelectCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SelectCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append("'").append(this->state).append("'"); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_SIREN +void ListEntitiesSirenResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesSirenResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + for (const auto &it : this->tones) { + out.append(" tones: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + + out.append(" supports_duration: "); + out.append(YESNO(this->supports_duration)); + out.append("\n"); + + out.append(" supports_volume: "); + out.append(YESNO(this->supports_volume)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void SirenStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SirenStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append(YESNO(this->state)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void SirenCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SirenCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" has_state: "); + out.append(YESNO(this->has_state)); + out.append("\n"); + + out.append(" state: "); + out.append(YESNO(this->state)); + out.append("\n"); + + out.append(" has_tone: "); + out.append(YESNO(this->has_tone)); + out.append("\n"); + + out.append(" tone: "); + out.append("'").append(this->tone).append("'"); + out.append("\n"); + + out.append(" has_duration: "); + out.append(YESNO(this->has_duration)); + out.append("\n"); + + out.append(" duration: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->duration); + out.append(buffer); + out.append("\n"); + + out.append(" has_volume: "); + out.append(YESNO(this->has_volume)); + out.append("\n"); + + out.append(" volume: "); + snprintf(buffer, sizeof(buffer), "%g", this->volume); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_LOCK +void ListEntitiesLockResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesLockResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" assumed_state: "); + out.append(YESNO(this->assumed_state)); + out.append("\n"); + + out.append(" supports_open: "); + out.append(YESNO(this->supports_open)); + out.append("\n"); + + out.append(" requires_code: "); + out.append(YESNO(this->requires_code)); + out.append("\n"); + + out.append(" code_format: "); + out.append("'").append(this->code_format).append("'"); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void LockStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("LockStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append(proto_enum_to_string(this->state)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void LockCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("LockCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" command: "); + out.append(proto_enum_to_string(this->command)); + out.append("\n"); + + out.append(" has_code: "); + out.append(YESNO(this->has_code)); + out.append("\n"); + + out.append(" code: "); + out.append("'").append(this->code).append("'"); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_BUTTON +void ListEntitiesButtonResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesButtonResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_class: "); + out.append("'").append(this->device_class).append("'"); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void ButtonCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ButtonCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_MEDIA_PLAYER +void MediaPlayerSupportedFormat::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("MediaPlayerSupportedFormat {\n"); + out.append(" format: "); + out.append("'").append(this->format).append("'"); + out.append("\n"); + + out.append(" sample_rate: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->sample_rate); + out.append(buffer); + out.append("\n"); + + out.append(" num_channels: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->num_channels); + out.append(buffer); + out.append("\n"); + + out.append(" purpose: "); + out.append(proto_enum_to_string(this->purpose)); + out.append("\n"); + + out.append(" sample_bytes: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->sample_bytes); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void ListEntitiesMediaPlayerResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesMediaPlayerResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" supports_pause: "); + out.append(YESNO(this->supports_pause)); + out.append("\n"); + + for (const auto &it : this->supported_formats) { + out.append(" supported_formats: "); + it.dump_to(out); + out.append("\n"); + } + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void MediaPlayerStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("MediaPlayerStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append(proto_enum_to_string(this->state)); + out.append("\n"); + + out.append(" volume: "); + snprintf(buffer, sizeof(buffer), "%g", this->volume); + out.append(buffer); + out.append("\n"); + + out.append(" muted: "); + out.append(YESNO(this->muted)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void MediaPlayerCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("MediaPlayerCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" has_command: "); + out.append(YESNO(this->has_command)); + out.append("\n"); + + out.append(" command: "); + out.append(proto_enum_to_string(this->command)); + out.append("\n"); + + out.append(" has_volume: "); + out.append(YESNO(this->has_volume)); + out.append("\n"); + + out.append(" volume: "); + snprintf(buffer, sizeof(buffer), "%g", this->volume); + out.append(buffer); + out.append("\n"); + + out.append(" has_media_url: "); + out.append(YESNO(this->has_media_url)); + out.append("\n"); + + out.append(" media_url: "); + out.append("'").append(this->media_url).append("'"); + out.append("\n"); + + out.append(" has_announcement: "); + out.append(YESNO(this->has_announcement)); + out.append("\n"); + + out.append(" announcement: "); + out.append(YESNO(this->announcement)); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_BLUETOOTH_PROXY +void SubscribeBluetoothLEAdvertisementsRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SubscribeBluetoothLEAdvertisementsRequest {\n"); + out.append(" flags: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->flags); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothServiceData::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothServiceData {\n"); + out.append(" uuid: "); + out.append("'").append(this->uuid).append("'"); + out.append("\n"); + + for (const auto &it : this->legacy_data) { + out.append(" legacy_data: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, it); + out.append(buffer); + out.append("\n"); + } + + out.append(" data: "); + out.append(format_hex_pretty(this->data)); + out.append("\n"); + out.append("}"); +} +void BluetoothLEAdvertisementResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothLEAdvertisementResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append(format_hex_pretty(this->name)); + out.append("\n"); + + out.append(" rssi: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->rssi); + out.append(buffer); + out.append("\n"); + + for (const auto &it : this->service_uuids) { + out.append(" service_uuids: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + + for (const auto &it : this->service_data) { + out.append(" service_data: "); + it.dump_to(out); + out.append("\n"); + } + + for (const auto &it : this->manufacturer_data) { + out.append(" manufacturer_data: "); + it.dump_to(out); + out.append("\n"); + } + + out.append(" address_type: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->address_type); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothLERawAdvertisement::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothLERawAdvertisement {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" rssi: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->rssi); + out.append(buffer); + out.append("\n"); + + out.append(" address_type: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->address_type); + out.append(buffer); + out.append("\n"); + + out.append(" data: "); + out.append(format_hex_pretty(this->data)); + out.append("\n"); + out.append("}"); +} +void BluetoothLERawAdvertisementsResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothLERawAdvertisementsResponse {\n"); + for (const auto &it : this->advertisements) { + out.append(" advertisements: "); + it.dump_to(out); + out.append("\n"); + } + out.append("}"); +} +void BluetoothDeviceRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothDeviceRequest {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" request_type: "); + out.append(proto_enum_to_string(this->request_type)); + out.append("\n"); + + out.append(" has_address_type: "); + out.append(YESNO(this->has_address_type)); + out.append("\n"); + + out.append(" address_type: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->address_type); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothDeviceConnectionResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothDeviceConnectionResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" connected: "); + out.append(YESNO(this->connected)); + out.append("\n"); + + out.append(" mtu: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->mtu); + out.append(buffer); + out.append("\n"); + + out.append(" error: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->error); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTGetServicesRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTGetServicesRequest {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTDescriptor::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTDescriptor {\n"); + for (const auto &it : this->uuid) { + out.append(" uuid: "); + snprintf(buffer, sizeof(buffer), "%llu", it); + out.append(buffer); + out.append("\n"); + } + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTCharacteristic::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTCharacteristic {\n"); + for (const auto &it : this->uuid) { + out.append(" uuid: "); + snprintf(buffer, sizeof(buffer), "%llu", it); + out.append(buffer); + out.append("\n"); + } + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + + out.append(" properties: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->properties); + out.append(buffer); + out.append("\n"); + + for (const auto &it : this->descriptors) { + out.append(" descriptors: "); + it.dump_to(out); + out.append("\n"); + } + out.append("}"); +} +void BluetoothGATTService::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTService {\n"); + for (const auto &it : this->uuid) { + out.append(" uuid: "); + snprintf(buffer, sizeof(buffer), "%llu", it); + out.append(buffer); + out.append("\n"); + } + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + + for (const auto &it : this->characteristics) { + out.append(" characteristics: "); + it.dump_to(out); + out.append("\n"); + } + out.append("}"); +} +void BluetoothGATTGetServicesResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTGetServicesResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + for (const auto &it : this->services) { + out.append(" services: "); + it.dump_to(out); + out.append("\n"); + } + out.append("}"); +} +void BluetoothGATTGetServicesDoneResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTGetServicesDoneResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTReadRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTReadRequest {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTReadResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTReadResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + + out.append(" data: "); + out.append(format_hex_pretty(this->data)); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTWriteRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTWriteRequest {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + + out.append(" response: "); + out.append(YESNO(this->response)); + out.append("\n"); + + out.append(" data: "); + out.append(format_hex_pretty(this->data)); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTReadDescriptorRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTReadDescriptorRequest {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTWriteDescriptorRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTWriteDescriptorRequest {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + + out.append(" data: "); + out.append(format_hex_pretty(this->data)); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTNotifyRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTNotifyRequest {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + + out.append(" enable: "); + out.append(YESNO(this->enable)); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTNotifyDataResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTNotifyDataResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + + out.append(" data: "); + out.append(format_hex_pretty(this->data)); + out.append("\n"); + out.append("}"); +} +void SubscribeBluetoothConnectionsFreeRequest::dump_to(std::string &out) const { + out.append("SubscribeBluetoothConnectionsFreeRequest {}"); +} +void BluetoothConnectionsFreeResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothConnectionsFreeResponse {\n"); + out.append(" free: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->free); + out.append(buffer); + out.append("\n"); + + out.append(" limit: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->limit); + out.append(buffer); + out.append("\n"); + + for (const auto &it : this->allocated) { + out.append(" allocated: "); + snprintf(buffer, sizeof(buffer), "%llu", it); + out.append(buffer); + out.append("\n"); + } + out.append("}"); +} +void BluetoothGATTErrorResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTErrorResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + + out.append(" error: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->error); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTWriteResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTWriteResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothGATTNotifyResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothGATTNotifyResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" handle: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->handle); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothDevicePairingResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothDevicePairingResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" paired: "); + out.append(YESNO(this->paired)); + out.append("\n"); + + out.append(" error: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->error); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothDeviceUnpairingResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothDeviceUnpairingResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" success: "); + out.append(YESNO(this->success)); + out.append("\n"); + + out.append(" error: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->error); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void UnsubscribeBluetoothLEAdvertisementsRequest::dump_to(std::string &out) const { + out.append("UnsubscribeBluetoothLEAdvertisementsRequest {}"); +} +void BluetoothDeviceClearCacheResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothDeviceClearCacheResponse {\n"); + out.append(" address: "); + snprintf(buffer, sizeof(buffer), "%llu", this->address); + out.append(buffer); + out.append("\n"); + + out.append(" success: "); + out.append(YESNO(this->success)); + out.append("\n"); + + out.append(" error: "); + snprintf(buffer, sizeof(buffer), "%" PRId32, this->error); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void BluetoothScannerStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothScannerStateResponse {\n"); + out.append(" state: "); + out.append(proto_enum_to_string(this->state)); + out.append("\n"); + + out.append(" mode: "); + out.append(proto_enum_to_string(this->mode)); + out.append("\n"); + out.append("}"); +} +void BluetoothScannerSetModeRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("BluetoothScannerSetModeRequest {\n"); + out.append(" mode: "); + out.append(proto_enum_to_string(this->mode)); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_VOICE_ASSISTANT +void SubscribeVoiceAssistantRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("SubscribeVoiceAssistantRequest {\n"); + out.append(" subscribe: "); + out.append(YESNO(this->subscribe)); + out.append("\n"); + + out.append(" flags: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->flags); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void VoiceAssistantAudioSettings::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantAudioSettings {\n"); + out.append(" noise_suppression_level: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->noise_suppression_level); + out.append(buffer); + out.append("\n"); + + out.append(" auto_gain: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->auto_gain); + out.append(buffer); + out.append("\n"); + + out.append(" volume_multiplier: "); + snprintf(buffer, sizeof(buffer), "%g", this->volume_multiplier); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void VoiceAssistantRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantRequest {\n"); + out.append(" start: "); + out.append(YESNO(this->start)); + out.append("\n"); + + out.append(" conversation_id: "); + out.append("'").append(this->conversation_id).append("'"); + out.append("\n"); + + out.append(" flags: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->flags); + out.append(buffer); + out.append("\n"); + + out.append(" audio_settings: "); + this->audio_settings.dump_to(out); + out.append("\n"); + + out.append(" wake_word_phrase: "); + out.append("'").append(this->wake_word_phrase).append("'"); + out.append("\n"); + out.append("}"); +} +void VoiceAssistantResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantResponse {\n"); + out.append(" port: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->port); + out.append(buffer); + out.append("\n"); + + out.append(" error: "); + out.append(YESNO(this->error)); + out.append("\n"); + out.append("}"); +} +void VoiceAssistantEventData::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantEventData {\n"); + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" value: "); + out.append("'").append(this->value).append("'"); + out.append("\n"); + out.append("}"); +} +void VoiceAssistantEventResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantEventResponse {\n"); + out.append(" event_type: "); + out.append(proto_enum_to_string(this->event_type)); + out.append("\n"); + + for (const auto &it : this->data) { + out.append(" data: "); + it.dump_to(out); + out.append("\n"); + } + out.append("}"); +} +void VoiceAssistantAudio::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantAudio {\n"); + out.append(" data: "); + out.append(format_hex_pretty(this->data)); + out.append("\n"); + + out.append(" end: "); + out.append(YESNO(this->end)); + out.append("\n"); + out.append("}"); +} +void VoiceAssistantTimerEventResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantTimerEventResponse {\n"); + out.append(" event_type: "); + out.append(proto_enum_to_string(this->event_type)); + out.append("\n"); + + out.append(" timer_id: "); + out.append("'").append(this->timer_id).append("'"); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" total_seconds: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->total_seconds); + out.append(buffer); + out.append("\n"); + + out.append(" seconds_left: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->seconds_left); + out.append(buffer); + out.append("\n"); + + out.append(" is_active: "); + out.append(YESNO(this->is_active)); + out.append("\n"); + out.append("}"); +} +void VoiceAssistantAnnounceRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantAnnounceRequest {\n"); + out.append(" media_id: "); + out.append("'").append(this->media_id).append("'"); + out.append("\n"); + + out.append(" text: "); + out.append("'").append(this->text).append("'"); + out.append("\n"); + + out.append(" preannounce_media_id: "); + out.append("'").append(this->preannounce_media_id).append("'"); + out.append("\n"); + + out.append(" start_conversation: "); + out.append(YESNO(this->start_conversation)); + out.append("\n"); + out.append("}"); +} +void VoiceAssistantAnnounceFinished::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantAnnounceFinished {\n"); + out.append(" success: "); + out.append(YESNO(this->success)); + out.append("\n"); + out.append("}"); +} +void VoiceAssistantWakeWord::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantWakeWord {\n"); + out.append(" id: "); + out.append("'").append(this->id).append("'"); + out.append("\n"); + + out.append(" wake_word: "); + out.append("'").append(this->wake_word).append("'"); + out.append("\n"); + + for (const auto &it : this->trained_languages) { + out.append(" trained_languages: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + out.append("}"); +} +void VoiceAssistantConfigurationRequest::dump_to(std::string &out) const { + out.append("VoiceAssistantConfigurationRequest {}"); +} +void VoiceAssistantConfigurationResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantConfigurationResponse {\n"); + for (const auto &it : this->available_wake_words) { + out.append(" available_wake_words: "); + it.dump_to(out); + out.append("\n"); + } + + for (const auto &it : this->active_wake_words) { + out.append(" active_wake_words: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + + out.append(" max_active_wake_words: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->max_active_wake_words); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void VoiceAssistantSetConfiguration::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("VoiceAssistantSetConfiguration {\n"); + for (const auto &it : this->active_wake_words) { + out.append(" active_wake_words: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + out.append("}"); +} +#endif +#ifdef USE_ALARM_CONTROL_PANEL +void ListEntitiesAlarmControlPanelResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesAlarmControlPanelResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" supported_features: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->supported_features); + out.append(buffer); + out.append("\n"); + + out.append(" requires_code: "); + out.append(YESNO(this->requires_code)); + out.append("\n"); + + out.append(" requires_code_to_arm: "); + out.append(YESNO(this->requires_code_to_arm)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void AlarmControlPanelStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("AlarmControlPanelStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append(proto_enum_to_string(this->state)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void AlarmControlPanelCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("AlarmControlPanelCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" command: "); + out.append(proto_enum_to_string(this->command)); + out.append("\n"); + + out.append(" code: "); + out.append("'").append(this->code).append("'"); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_TEXT +void ListEntitiesTextResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesTextResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" min_length: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->min_length); + out.append(buffer); + out.append("\n"); + + out.append(" max_length: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->max_length); + out.append(buffer); + out.append("\n"); + + out.append(" pattern: "); + out.append("'").append(this->pattern).append("'"); + out.append("\n"); + + out.append(" mode: "); + out.append(proto_enum_to_string(this->mode)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void TextStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("TextStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append("'").append(this->state).append("'"); + out.append("\n"); + + out.append(" missing_state: "); + out.append(YESNO(this->missing_state)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void TextCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("TextCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" state: "); + out.append("'").append(this->state).append("'"); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_DATETIME_DATE +void ListEntitiesDateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesDateResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void DateStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("DateStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" missing_state: "); + out.append(YESNO(this->missing_state)); + out.append("\n"); + + out.append(" year: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->year); + out.append(buffer); + out.append("\n"); + + out.append(" month: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->month); + out.append(buffer); + out.append("\n"); + + out.append(" day: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->day); + out.append(buffer); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void DateCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("DateCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" year: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->year); + out.append(buffer); + out.append("\n"); + + out.append(" month: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->month); + out.append(buffer); + out.append("\n"); + + out.append(" day: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->day); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_DATETIME_TIME +void ListEntitiesTimeResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesTimeResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void TimeStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("TimeStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" missing_state: "); + out.append(YESNO(this->missing_state)); + out.append("\n"); + + out.append(" hour: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->hour); + out.append(buffer); + out.append("\n"); + + out.append(" minute: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->minute); + out.append(buffer); + out.append("\n"); + + out.append(" second: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->second); + out.append(buffer); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void TimeCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("TimeCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" hour: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->hour); + out.append(buffer); + out.append("\n"); + + out.append(" minute: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->minute); + out.append(buffer); + out.append("\n"); + + out.append(" second: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->second); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_EVENT +void ListEntitiesEventResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesEventResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_class: "); + out.append("'").append(this->device_class).append("'"); + out.append("\n"); + + for (const auto &it : this->event_types) { + out.append(" event_types: "); + out.append("'").append(it).append("'"); + out.append("\n"); + } + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void EventResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("EventResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" event_type: "); + out.append("'").append(this->event_type).append("'"); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_VALVE +void ListEntitiesValveResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesValveResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_class: "); + out.append("'").append(this->device_class).append("'"); + out.append("\n"); + + out.append(" assumed_state: "); + out.append(YESNO(this->assumed_state)); + out.append("\n"); + + out.append(" supports_position: "); + out.append(YESNO(this->supports_position)); + out.append("\n"); + + out.append(" supports_stop: "); + out.append(YESNO(this->supports_stop)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void ValveStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ValveStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" position: "); + snprintf(buffer, sizeof(buffer), "%g", this->position); + out.append(buffer); + out.append("\n"); + + out.append(" current_operation: "); + out.append(proto_enum_to_string(this->current_operation)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void ValveCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ValveCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" has_position: "); + out.append(YESNO(this->has_position)); + out.append("\n"); + + out.append(" position: "); + snprintf(buffer, sizeof(buffer), "%g", this->position); + out.append(buffer); + out.append("\n"); + + out.append(" stop: "); + out.append(YESNO(this->stop)); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_DATETIME_DATETIME +void ListEntitiesDateTimeResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesDateTimeResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void DateTimeStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("DateTimeStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" missing_state: "); + out.append(YESNO(this->missing_state)); + out.append("\n"); + + out.append(" epoch_seconds: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->epoch_seconds); + out.append(buffer); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void DateTimeCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("DateTimeCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" epoch_seconds: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->epoch_seconds); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +#endif +#ifdef USE_UPDATE +void ListEntitiesUpdateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("ListEntitiesUpdateResponse {\n"); + out.append(" object_id: "); + out.append("'").append(this->object_id).append("'"); + out.append("\n"); + + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" name: "); + out.append("'").append(this->name).append("'"); + out.append("\n"); + + out.append(" unique_id: "); + out.append("'").append(this->unique_id).append("'"); + out.append("\n"); + + out.append(" icon: "); + out.append("'").append(this->icon).append("'"); + out.append("\n"); + + out.append(" disabled_by_default: "); + out.append(YESNO(this->disabled_by_default)); + out.append("\n"); + + out.append(" entity_category: "); + out.append(proto_enum_to_string(this->entity_category)); + out.append("\n"); + + out.append(" device_class: "); + out.append("'").append(this->device_class).append("'"); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void UpdateStateResponse::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("UpdateStateResponse {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" missing_state: "); + out.append(YESNO(this->missing_state)); + out.append("\n"); + + out.append(" in_progress: "); + out.append(YESNO(this->in_progress)); + out.append("\n"); + + out.append(" has_progress: "); + out.append(YESNO(this->has_progress)); + out.append("\n"); + + out.append(" progress: "); + snprintf(buffer, sizeof(buffer), "%g", this->progress); + out.append(buffer); + out.append("\n"); + + out.append(" current_version: "); + out.append("'").append(this->current_version).append("'"); + out.append("\n"); + + out.append(" latest_version: "); + out.append("'").append(this->latest_version).append("'"); + out.append("\n"); + + out.append(" title: "); + out.append("'").append(this->title).append("'"); + out.append("\n"); + + out.append(" release_summary: "); + out.append("'").append(this->release_summary).append("'"); + out.append("\n"); + + out.append(" release_url: "); + out.append("'").append(this->release_url).append("'"); + out.append("\n"); + + out.append(" device_id: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->device_id); + out.append(buffer); + out.append("\n"); + out.append("}"); +} +void UpdateCommandRequest::dump_to(std::string &out) const { + __attribute__((unused)) char buffer[64]; + out.append("UpdateCommandRequest {\n"); + out.append(" key: "); + snprintf(buffer, sizeof(buffer), "%" PRIu32, this->key); + out.append(buffer); + out.append("\n"); + + out.append(" command: "); + out.append(proto_enum_to_string(this->command)); + out.append("\n"); + out.append("}"); +} +#endif + +} // namespace api +} // namespace esphome + +#endif // HAS_PROTO_MESSAGE_DUMP diff --git a/esphome/components/api/api_pb2_service.cpp b/esphome/components/api/api_pb2_service.cpp index de8e6574b2..92dd90053b 100644 --- a/esphome/components/api/api_pb2_service.cpp +++ b/esphome/components/api/api_pb2_service.cpp @@ -204,7 +204,7 @@ void APIServerConnectionBase::read_message(uint32_t msg_size, uint32_t msg_type, this->on_execute_service_request(msg); break; } -#ifdef USE_ESP32_CAMERA +#ifdef USE_CAMERA case 45: { CameraImageRequest msg; msg.decode(msg_data, msg_size); @@ -682,7 +682,7 @@ void APIServerConnection::on_button_command_request(const ButtonCommandRequest & } } #endif -#ifdef USE_ESP32_CAMERA +#ifdef USE_CAMERA void APIServerConnection::on_camera_image_request(const CameraImageRequest &msg) { if (this->check_authenticated_()) { this->camera_image(msg); diff --git a/esphome/components/api/api_pb2_service.h b/esphome/components/api/api_pb2_service.h index 3cc774f91c..458f8ec81b 100644 --- a/esphome/components/api/api_pb2_service.h +++ b/esphome/components/api/api_pb2_service.h @@ -2,9 +2,10 @@ // See script/api_protobuf/api_protobuf.py #pragma once -#include "api_pb2.h" #include "esphome/core/defines.h" +#include "api_pb2.h" + namespace esphome { namespace api { @@ -70,7 +71,7 @@ class APIServerConnectionBase : public ProtoService { virtual void on_execute_service_request(const ExecuteServiceRequest &value){}; -#ifdef USE_ESP32_CAMERA +#ifdef USE_CAMERA virtual void on_camera_image_request(const CameraImageRequest &value){}; #endif @@ -222,7 +223,7 @@ class APIServerConnection : public APIServerConnectionBase { #ifdef USE_BUTTON virtual void button_command(const ButtonCommandRequest &msg) = 0; #endif -#ifdef USE_ESP32_CAMERA +#ifdef USE_CAMERA virtual void camera_image(const CameraImageRequest &msg) = 0; #endif #ifdef USE_CLIMATE @@ -339,7 +340,7 @@ class APIServerConnection : public APIServerConnectionBase { #ifdef USE_BUTTON void on_button_command_request(const ButtonCommandRequest &msg) override; #endif -#ifdef USE_ESP32_CAMERA +#ifdef USE_CAMERA void on_camera_image_request(const CameraImageRequest &msg) override; #endif #ifdef USE_CLIMATE diff --git a/esphome/components/api/api_server.cpp b/esphome/components/api/api_server.cpp index ebe80604dc..0915746381 100644 --- a/esphome/components/api/api_server.cpp +++ b/esphome/components/api/api_server.cpp @@ -24,6 +24,14 @@ static const char *const TAG = "api"; // APIServer APIServer *global_api_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) +#ifndef USE_API_YAML_SERVICES +// Global empty vector to avoid guard variables (saves 8 bytes) +// This is initialized at program startup before any threads +static const std::vector empty_user_services{}; + +const std::vector &get_empty_user_services_instance() { return empty_user_services; } +#endif + APIServer::APIServer() { global_api_server = this; // Pre-allocate shared write buffer @@ -96,30 +104,30 @@ void APIServer::setup() { #ifdef USE_LOGGER if (logger::global_logger != nullptr) { - logger::global_logger->add_on_log_callback([this](int level, const char *tag, const char *message) { - if (this->shutting_down_) { - // Don't try to send logs during shutdown - // as it could result in a recursion and - // we would be filling a buffer we are trying to clear - return; - } - for (auto &c : this->clients_) { - if (!c->flags_.remove) - c->try_send_log_message(level, tag, message); - } - }); + logger::global_logger->add_on_log_callback( + [this](int level, const char *tag, const char *message, size_t message_len) { + if (this->shutting_down_) { + // Don't try to send logs during shutdown + // as it could result in a recursion and + // we would be filling a buffer we are trying to clear + return; + } + for (auto &c : this->clients_) { + if (!c->flags_.remove) + c->try_send_log_message(level, tag, message, message_len); + } + }); } #endif -#ifdef USE_ESP32_CAMERA - if (esp32_camera::global_esp32_camera != nullptr && !esp32_camera::global_esp32_camera->is_internal()) { - esp32_camera::global_esp32_camera->add_image_callback( - [this](const std::shared_ptr &image) { - for (auto &c : this->clients_) { - if (!c->flags_.remove) - c->set_camera_state(image); - } - }); +#ifdef USE_CAMERA + if (camera::Camera::instance() != nullptr && !camera::Camera::instance()->is_internal()) { + camera::Camera::instance()->add_image_callback([this](const std::shared_ptr &image) { + for (auto &c : this->clients_) { + if (!c->flags_.remove) + c->set_camera_state(image); + } + }); } #endif } @@ -218,6 +226,7 @@ void APIServer::dump_config() { #endif } +#ifdef USE_API_PASSWORD bool APIServer::uses_password() const { return !this->password_.empty(); } bool APIServer::check_password(const std::string &password) const { @@ -248,190 +257,127 @@ bool APIServer::check_password(const std::string &password) const { return result == 0; } +#endif void APIServer::handle_disconnect(APIConnection *conn) {} +// Macro for entities without extra parameters +#define API_DISPATCH_UPDATE(entity_type, entity_name) \ + void APIServer::on_##entity_name##_update(entity_type *obj) { /* NOLINT(bugprone-macro-parentheses) */ \ + if (obj->is_internal()) \ + return; \ + for (auto &c : this->clients_) \ + c->send_##entity_name##_state(obj); \ + } + +// Macro for entities with extra parameters (but parameters not used in send) +#define API_DISPATCH_UPDATE_IGNORE_PARAMS(entity_type, entity_name, ...) \ + void APIServer::on_##entity_name##_update(entity_type *obj, __VA_ARGS__) { /* NOLINT(bugprone-macro-parentheses) */ \ + if (obj->is_internal()) \ + return; \ + for (auto &c : this->clients_) \ + c->send_##entity_name##_state(obj); \ + } + #ifdef USE_BINARY_SENSOR -void APIServer::on_binary_sensor_update(binary_sensor::BinarySensor *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_binary_sensor_state(obj); -} +API_DISPATCH_UPDATE(binary_sensor::BinarySensor, binary_sensor) #endif #ifdef USE_COVER -void APIServer::on_cover_update(cover::Cover *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_cover_state(obj); -} +API_DISPATCH_UPDATE(cover::Cover, cover) #endif #ifdef USE_FAN -void APIServer::on_fan_update(fan::Fan *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_fan_state(obj); -} +API_DISPATCH_UPDATE(fan::Fan, fan) #endif #ifdef USE_LIGHT -void APIServer::on_light_update(light::LightState *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_light_state(obj); -} +API_DISPATCH_UPDATE(light::LightState, light) #endif #ifdef USE_SENSOR -void APIServer::on_sensor_update(sensor::Sensor *obj, float state) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_sensor_state(obj); -} +API_DISPATCH_UPDATE_IGNORE_PARAMS(sensor::Sensor, sensor, float state) #endif #ifdef USE_SWITCH -void APIServer::on_switch_update(switch_::Switch *obj, bool state) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_switch_state(obj); -} +API_DISPATCH_UPDATE_IGNORE_PARAMS(switch_::Switch, switch, bool state) #endif #ifdef USE_TEXT_SENSOR -void APIServer::on_text_sensor_update(text_sensor::TextSensor *obj, const std::string &state) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_text_sensor_state(obj); -} +API_DISPATCH_UPDATE_IGNORE_PARAMS(text_sensor::TextSensor, text_sensor, const std::string &state) #endif #ifdef USE_CLIMATE -void APIServer::on_climate_update(climate::Climate *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_climate_state(obj); -} +API_DISPATCH_UPDATE(climate::Climate, climate) #endif #ifdef USE_NUMBER -void APIServer::on_number_update(number::Number *obj, float state) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_number_state(obj); -} +API_DISPATCH_UPDATE_IGNORE_PARAMS(number::Number, number, float state) #endif #ifdef USE_DATETIME_DATE -void APIServer::on_date_update(datetime::DateEntity *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_date_state(obj); -} +API_DISPATCH_UPDATE(datetime::DateEntity, date) #endif #ifdef USE_DATETIME_TIME -void APIServer::on_time_update(datetime::TimeEntity *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_time_state(obj); -} +API_DISPATCH_UPDATE(datetime::TimeEntity, time) #endif #ifdef USE_DATETIME_DATETIME -void APIServer::on_datetime_update(datetime::DateTimeEntity *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_datetime_state(obj); -} +API_DISPATCH_UPDATE(datetime::DateTimeEntity, datetime) #endif #ifdef USE_TEXT -void APIServer::on_text_update(text::Text *obj, const std::string &state) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_text_state(obj); -} +API_DISPATCH_UPDATE_IGNORE_PARAMS(text::Text, text, const std::string &state) #endif #ifdef USE_SELECT -void APIServer::on_select_update(select::Select *obj, const std::string &state, size_t index) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_select_state(obj); -} +API_DISPATCH_UPDATE_IGNORE_PARAMS(select::Select, select, const std::string &state, size_t index) #endif #ifdef USE_LOCK -void APIServer::on_lock_update(lock::Lock *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_lock_state(obj); -} +API_DISPATCH_UPDATE(lock::Lock, lock) #endif #ifdef USE_VALVE -void APIServer::on_valve_update(valve::Valve *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_valve_state(obj); -} +API_DISPATCH_UPDATE(valve::Valve, valve) #endif #ifdef USE_MEDIA_PLAYER -void APIServer::on_media_player_update(media_player::MediaPlayer *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_media_player_state(obj); -} +API_DISPATCH_UPDATE(media_player::MediaPlayer, media_player) #endif #ifdef USE_EVENT +// Event is a special case - it's the only entity that passes extra parameters to the send method void APIServer::on_event(event::Event *obj, const std::string &event_type) { + if (obj->is_internal()) + return; for (auto &c : this->clients_) c->send_event(obj, event_type); } #endif #ifdef USE_UPDATE +// Update is a special case - the method is called on_update, not on_update_update void APIServer::on_update(update::UpdateEntity *obj) { + if (obj->is_internal()) + return; for (auto &c : this->clients_) c->send_update_state(obj); } #endif #ifdef USE_ALARM_CONTROL_PANEL -void APIServer::on_alarm_control_panel_update(alarm_control_panel::AlarmControlPanel *obj) { - if (obj->is_internal()) - return; - for (auto &c : this->clients_) - c->send_alarm_control_panel_state(obj); -} +API_DISPATCH_UPDATE(alarm_control_panel::AlarmControlPanel, alarm_control_panel) #endif float APIServer::get_setup_priority() const { return setup_priority::AFTER_WIFI; } void APIServer::set_port(uint16_t port) { this->port_ = port; } +#ifdef USE_API_PASSWORD void APIServer::set_password(const std::string &password) { this->password_ = password; } +#endif void APIServer::set_batch_delay(uint16_t batch_delay) { this->batch_delay_ = batch_delay; } diff --git a/esphome/components/api/api_server.h b/esphome/components/api/api_server.h index 5a9b0677bc..f34fd55974 100644 --- a/esphome/components/api/api_server.h +++ b/esphome/components/api/api_server.h @@ -25,6 +25,11 @@ struct SavedNoisePsk { } PACKED; // NOLINT #endif +#ifndef USE_API_YAML_SERVICES +// Forward declaration of helper function +const std::vector &get_empty_user_services_instance(); +#endif + class APIServer : public Component, public Controller { public: APIServer(); @@ -35,10 +40,12 @@ class APIServer : public Component, public Controller { void dump_config() override; void on_shutdown() override; bool teardown() override; +#ifdef USE_API_PASSWORD bool check_password(const std::string &password) const; bool uses_password() const; - void set_port(uint16_t port); void set_password(const std::string &password); +#endif + void set_port(uint16_t port); void set_reboot_timeout(uint32_t reboot_timeout); void set_batch_delay(uint16_t batch_delay); uint16_t get_batch_delay() const { return batch_delay_; } @@ -149,8 +156,11 @@ class APIServer : public Component, public Controller { #ifdef USE_API_YAML_SERVICES return this->user_services_; #else - static const std::vector EMPTY; - return this->user_services_ ? *this->user_services_ : EMPTY; + if (this->user_services_) { + return *this->user_services_; + } + // Return reference to global empty instance (no guard needed) + return get_empty_user_services_instance(); #endif } @@ -179,7 +189,9 @@ class APIServer : public Component, public Controller { // Vectors and strings (12 bytes each on 32-bit) std::vector> clients_; +#ifdef USE_API_PASSWORD std::string password_; +#endif std::vector shared_write_buffer_; // Shared proto write buffer for all connections std::vector state_subs_; #ifdef USE_API_YAML_SERVICES diff --git a/esphome/components/api/list_entities.cpp b/esphome/components/api/list_entities.cpp index 3f84ef306e..60814e359d 100644 --- a/esphome/components/api/list_entities.cpp +++ b/esphome/components/api/list_entities.cpp @@ -40,8 +40,8 @@ LIST_ENTITIES_HANDLER(lock, lock::Lock, ListEntitiesLockResponse) #ifdef USE_VALVE LIST_ENTITIES_HANDLER(valve, valve::Valve, ListEntitiesValveResponse) #endif -#ifdef USE_ESP32_CAMERA -LIST_ENTITIES_HANDLER(camera, esp32_camera::ESP32Camera, ListEntitiesCameraResponse) +#ifdef USE_CAMERA +LIST_ENTITIES_HANDLER(camera, camera::Camera, ListEntitiesCameraResponse) #endif #ifdef USE_CLIMATE LIST_ENTITIES_HANDLER(climate, climate::Climate, ListEntitiesClimateResponse) diff --git a/esphome/components/api/list_entities.h b/esphome/components/api/list_entities.h index b9506073d2..4c83ca0935 100644 --- a/esphome/components/api/list_entities.h +++ b/esphome/components/api/list_entities.h @@ -45,8 +45,8 @@ class ListEntitiesIterator : public ComponentIterator { bool on_text_sensor(text_sensor::TextSensor *entity) override; #endif bool on_service(UserServiceDescriptor *service) override; -#ifdef USE_ESP32_CAMERA - bool on_camera(esp32_camera::ESP32Camera *entity) override; +#ifdef USE_CAMERA + bool on_camera(camera::Camera *entity) override; #endif #ifdef USE_CLIMATE bool on_climate(climate::Climate *entity) override; diff --git a/esphome/components/bluetooth_proxy/bluetooth_proxy.cpp b/esphome/components/bluetooth_proxy/bluetooth_proxy.cpp index fbe2a3e67c..a5e8ec0860 100644 --- a/esphome/components/bluetooth_proxy/bluetooth_proxy.cpp +++ b/esphome/components/bluetooth_proxy/bluetooth_proxy.cpp @@ -52,11 +52,21 @@ bool BluetoothProxy::parse_device(const esp32_ble_tracker::ESPBTDevice &device) return true; } -static constexpr size_t FLUSH_BATCH_SIZE = 8; -static std::vector &get_batch_buffer() { - static std::vector batch_buffer; - return batch_buffer; -} +// Batch size for BLE advertisements to maximize WiFi efficiency +// Each advertisement is up to 80 bytes when packaged (including protocol overhead) +// Most advertisements are 20-30 bytes, allowing even more to fit per packet +// 16 advertisements × 80 bytes (worst case) = 1280 bytes out of ~1320 bytes usable payload +// This achieves ~97% WiFi MTU utilization while staying under the limit +static constexpr size_t FLUSH_BATCH_SIZE = 16; + +namespace { +// Batch buffer in anonymous namespace to avoid guard variable (saves 8 bytes) +// This is initialized at program startup before any threads +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::vector batch_buffer; +} // namespace + +static std::vector &get_batch_buffer() { return batch_buffer; } bool BluetoothProxy::parse_devices(const esp32_ble::BLEScanResult *scan_results, size_t count) { if (!api::global_api_server->is_connected() || this->api_connection_ == nullptr || !this->raw_advertisements_) @@ -170,7 +180,7 @@ int BluetoothProxy::get_bluetooth_connections_free() { void BluetoothProxy::loop() { if (!api::global_api_server->is_connected() || this->api_connection_ == nullptr) { for (auto *connection : this->connections_) { - if (connection->get_address() != 0) { + if (connection->get_address() != 0 && !connection->disconnect_pending()) { connection->disconnect(); } } diff --git a/esphome/components/camera/__init__.py b/esphome/components/camera/__init__.py new file mode 100644 index 0000000000..a19f7707af --- /dev/null +++ b/esphome/components/camera/__init__.py @@ -0,0 +1 @@ +CODEOWNERS = ["@DT-art1", "@bdraco"] diff --git a/esphome/components/camera/camera.cpp b/esphome/components/camera/camera.cpp new file mode 100644 index 0000000000..3bd632af5c --- /dev/null +++ b/esphome/components/camera/camera.cpp @@ -0,0 +1,22 @@ +#include "camera.h" + +namespace esphome { +namespace camera { + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +Camera *Camera::global_camera = nullptr; + +Camera::Camera() { + if (global_camera != nullptr) { + this->status_set_error("Multiple cameras are configured, but only one is supported."); + this->mark_failed(); + return; + } + + global_camera = this; +} + +Camera *Camera::instance() { return global_camera; } + +} // namespace camera +} // namespace esphome diff --git a/esphome/components/camera/camera.h b/esphome/components/camera/camera.h new file mode 100644 index 0000000000..fb9da58cc1 --- /dev/null +++ b/esphome/components/camera/camera.h @@ -0,0 +1,80 @@ +#pragma once + +#include "esphome/core/automation.h" +#include "esphome/core/component.h" +#include "esphome/core/entity_base.h" +#include "esphome/core/helpers.h" + +namespace esphome { +namespace camera { + +/** Different sources for filtering. + * IDLE: Camera requests to send an image to the API. + * API_REQUESTER: API requests a new image. + * WEB_REQUESTER: ESP32 web server request an image. Ignored by API. + */ +enum CameraRequester : uint8_t { IDLE, API_REQUESTER, WEB_REQUESTER }; + +/** Abstract camera image base class. + * Encapsulates the JPEG encoded data and it is shared among + * all connected clients. + */ +class CameraImage { + public: + virtual uint8_t *get_data_buffer() = 0; + virtual size_t get_data_length() = 0; + virtual bool was_requested_by(CameraRequester requester) const = 0; + virtual ~CameraImage() {} +}; + +/** Abstract image reader base class. + * Keeps track of the data offset of the camera image and + * how many bytes are remaining to read. When the image + * is returned, the shared_ptr is reset and the camera can + * reuse the memory of the camera image. + */ +class CameraImageReader { + public: + virtual void set_image(std::shared_ptr image) = 0; + virtual size_t available() const = 0; + virtual uint8_t *peek_data_buffer() = 0; + virtual void consume_data(size_t consumed) = 0; + virtual void return_image() = 0; + virtual ~CameraImageReader() {} +}; + +/** Abstract camera base class. Collaborates with API. + * 1) API server starts and installs callback (add_image_callback) + * which is called by the camera when a new image is available. + * 2) New API client connects and creates a new image reader (create_image_reader). + * 3) API connection receives protobuf CameraImageRequest and calls request_image. + * 3.a) API connection receives protobuf CameraImageRequest and calls start_stream. + * 4) Camera implementation provides JPEG data in the CameraImage and calls callback. + * 5) API connection sets the image in the image reader. + * 6) API connection consumes data from the image reader and returns the image when finished. + * 7.a) Camera captures a new image and continues with 4) until start_stream is called. + */ +class Camera : public EntityBase, public Component { + public: + Camera(); + // Camera implementation invokes callback to publish a new image. + virtual void add_image_callback(std::function)> &&callback) = 0; + /// Returns a new camera image reader that keeps track of the JPEG data in the camera image. + virtual CameraImageReader *create_image_reader() = 0; + // Connection, camera or web server requests one new JPEG image. + virtual void request_image(CameraRequester requester) = 0; + // Connection, camera or web server requests a stream of images. + virtual void start_stream(CameraRequester requester) = 0; + // Connection or web server stops the previously started stream. + virtual void stop_stream(CameraRequester requester) = 0; + virtual ~Camera() {} + /// The singleton instance of the camera implementation. + static Camera *instance(); + + protected: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) + static Camera *global_camera; +}; + +} // namespace camera +} // namespace esphome diff --git a/esphome/components/debug/__init__.py b/esphome/components/debug/__init__.py index 1955b5d22c..500dfac1fe 100644 --- a/esphome/components/debug/__init__.py +++ b/esphome/components/debug/__init__.py @@ -1,4 +1,5 @@ import esphome.codegen as cg +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_BLOCK, @@ -7,6 +8,7 @@ from esphome.const import ( CONF_FREE, CONF_ID, CONF_LOOP_TIME, + PlatformFramework, ) CODEOWNERS = ["@OttoWinter"] @@ -44,3 +46,21 @@ CONFIG_SCHEMA = cv.All( async def to_code(config): var = cg.new_Pvariable(config[CONF_ID]) await cg.register_component(var, config) + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "debug_esp32.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + "debug_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "debug_host.cpp": {PlatformFramework.HOST_NATIVE}, + "debug_rp2040.cpp": {PlatformFramework.RP2040_ARDUINO}, + "debug_libretiny.cpp": { + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + } +) diff --git a/esphome/components/deep_sleep/__init__.py b/esphome/components/deep_sleep/__init__.py index 63b359bd5b..55826f52bb 100644 --- a/esphome/components/deep_sleep/__init__.py +++ b/esphome/components/deep_sleep/__init__.py @@ -11,6 +11,7 @@ from esphome.components.esp32.const import ( VARIANT_ESP32S2, VARIANT_ESP32S3, ) +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_DEFAULT, @@ -27,6 +28,7 @@ from esphome.const import ( CONF_WAKEUP_PIN, PLATFORM_ESP32, PLATFORM_ESP8266, + PlatformFramework, ) WAKEUP_PINS = { @@ -313,3 +315,14 @@ async def deep_sleep_action_to_code(config, action_id, template_arg, args): var = cg.new_Pvariable(action_id, template_arg) await cg.register_parented(var, config[CONF_ID]) return var + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "deep_sleep_esp32.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + "deep_sleep_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + } +) diff --git a/esphome/components/ds2484/__init__.py b/esphome/components/ds2484/__init__.py new file mode 100644 index 0000000000..3d9f24ff19 --- /dev/null +++ b/esphome/components/ds2484/__init__.py @@ -0,0 +1 @@ +CODEOWNERS = ["@mrk-its"] diff --git a/esphome/components/ds2484/ds2484.cpp b/esphome/components/ds2484/ds2484.cpp new file mode 100644 index 0000000000..c3df9786b6 --- /dev/null +++ b/esphome/components/ds2484/ds2484.cpp @@ -0,0 +1,209 @@ +#include "ds2484.h" + +namespace esphome { +namespace ds2484 { +static const char *const TAG = "ds2484.onewire"; + +void DS2484OneWireBus::setup() { + ESP_LOGCONFIG(TAG, "Running setup"); + this->reset_device(); + this->search(); +} + +void DS2484OneWireBus::dump_config() { + ESP_LOGCONFIG(TAG, "1-wire bus:"); + this->dump_devices_(TAG); +} + +bool DS2484OneWireBus::read_status_(uint8_t *status) { + for (uint8_t retry_nr = 0; retry_nr < 10; retry_nr++) { + if (this->read(status, 1) != i2c::ERROR_OK) { + ESP_LOGE(TAG, "read status error"); + return false; + } + ESP_LOGVV(TAG, "status: %02x", *status); + if (!(*status & 1)) { + return true; + } + } + ESP_LOGE(TAG, "read status error: too many retries"); + return false; +} + +bool DS2484OneWireBus::wait_for_completion_() { + uint8_t status; + return this->read_status_(&status); +} + +bool DS2484OneWireBus::reset_device() { + ESP_LOGVV(TAG, "reset_device"); + uint8_t device_reset_cmd = 0xf0; + uint8_t response; + if (this->write(&device_reset_cmd, 1) != i2c::ERROR_OK) { + return false; + } + if (!this->wait_for_completion_()) { + ESP_LOGE(TAG, "reset_device: can't complete"); + return false; + } + uint8_t config = (this->active_pullup_ ? 1 : 0) | (this->strong_pullup_ ? 4 : 0); + uint8_t write_config[2] = {0xd2, (uint8_t) (config | (~config << 4))}; + if (this->write(write_config, 2) != i2c::ERROR_OK) { + ESP_LOGE(TAG, "reset_device: can't write config"); + return false; + } + if (this->read(&response, 1) != i2c::ERROR_OK) { + ESP_LOGE(TAG, "can't read read8 response"); + return false; + } + if (response != (write_config[1] & 0xf)) { + ESP_LOGE(TAG, "configuration didn't update"); + return false; + } + return true; +}; + +int DS2484OneWireBus::reset_int() { + ESP_LOGVV(TAG, "reset"); + uint8_t reset_cmd = 0xb4; + if (this->write(&reset_cmd, 1) != i2c::ERROR_OK) { + return -1; + } + return this->wait_for_completion_() ? 1 : 0; +}; + +void DS2484OneWireBus::write8_(uint8_t value) { + uint8_t buffer[2] = {0xa5, value}; + this->write(buffer, 2); + this->wait_for_completion_(); +}; + +void DS2484OneWireBus::write8(uint8_t value) { + ESP_LOGVV(TAG, "write8: %02x", value); + this->write8_(value); +}; + +void DS2484OneWireBus::write64(uint64_t value) { + ESP_LOGVV(TAG, "write64: %llx", value); + for (uint8_t i = 0; i < 8; i++) { + this->write8_((value >> (i * 8)) & 0xff); + } +} + +uint8_t DS2484OneWireBus::read8() { + uint8_t read8_cmd = 0x96; + uint8_t set_read_reg_cmd[2] = {0xe1, 0xe1}; + uint8_t response = 0; + if (this->write(&read8_cmd, 1) != i2c::ERROR_OK) { + ESP_LOGE(TAG, "can't write read8 cmd"); + return 0; + } + this->wait_for_completion_(); + if (this->write(set_read_reg_cmd, 2) != i2c::ERROR_OK) { + ESP_LOGE(TAG, "can't set read data reg"); + return 0; + } + if (this->read(&response, 1) != i2c::ERROR_OK) { + ESP_LOGE(TAG, "can't read read8 response"); + return 0; + } + return response; +} + +uint64_t DS2484OneWireBus::read64() { + uint8_t response = 0; + for (uint8_t i = 0; i < 8; i++) { + response |= (this->read8() << (i * 8)); + } + return response; +} + +void DS2484OneWireBus::reset_search() { + this->last_discrepancy_ = 0; + this->last_device_flag_ = false; + this->address_ = 0; +} + +bool DS2484OneWireBus::one_wire_triple_(bool *branch, bool *id_bit, bool *cmp_id_bit) { + uint8_t buffer[2] = {(uint8_t) 0x78, (uint8_t) (*branch ? 0x80u : 0)}; + uint8_t status; + if (!this->read_status_(&status)) { + ESP_LOGE(TAG, "one_wire_triple start: read status error"); + return false; + } + if (this->write(buffer, 2) != i2c::ERROR_OK) { + ESP_LOGV(TAG, "one_wire_triple: can't write cmd"); + return false; + } + if (!this->read_status_(&status)) { + ESP_LOGE(TAG, "one_wire_triple: read status error"); + return false; + } + *id_bit = bool(status & 0x20); + *cmp_id_bit = bool(status & 0x40); + *branch = bool(status & 0x80); + return true; +} + +uint64_t IRAM_ATTR DS2484OneWireBus::search_int() { + ESP_LOGVV(TAG, "search_int"); + if (this->last_device_flag_) { + ESP_LOGVV(TAG, "last device flag set, quitting"); + return 0u; + } + + uint8_t last_zero = 0; + uint64_t bit_mask = 1; + uint64_t address = this->address_; + + // Initiate search + for (uint8_t bit_number = 1; bit_number <= 64; bit_number++, bit_mask <<= 1) { + bool branch; + + // compute branch value for the case when there is a discrepancy + // (there are devices with both 0s and 1s at this bit) + if (bit_number < this->last_discrepancy_) { + branch = (address & bit_mask) > 0; + } else { + branch = bit_number == this->last_discrepancy_; + } + + bool id_bit, cmp_id_bit; + bool branch_before = branch; + if (!this->one_wire_triple_(&branch, &id_bit, &cmp_id_bit)) { + ESP_LOGW(TAG, "one wire triple error, quitting"); + return 0; + } + + if (id_bit && cmp_id_bit) { + ESP_LOGW(TAG, "no devices on the bus, quitting"); + // No devices participating in search + return 0; + } + + if (!id_bit && !cmp_id_bit && !branch) { + last_zero = bit_number; + } + + ESP_LOGVV(TAG, "%d %d branch: %d %d", id_bit, cmp_id_bit, branch_before, branch); + + if (branch) { + address |= bit_mask; + } else { + address &= ~bit_mask; + } + } + ESP_LOGVV(TAG, "last_discepancy: %d", last_zero); + ESP_LOGVV(TAG, "address: %llx", address); + this->last_discrepancy_ = last_zero; + if (this->last_discrepancy_ == 0) { + // we're at root and have no choices left, so this was the last one. + this->last_device_flag_ = true; + } + + this->address_ = address; + return address; +} + +} // namespace ds2484 +} // namespace esphome diff --git a/esphome/components/ds2484/ds2484.h b/esphome/components/ds2484/ds2484.h new file mode 100644 index 0000000000..223227c0a2 --- /dev/null +++ b/esphome/components/ds2484/ds2484.h @@ -0,0 +1,43 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/core/hal.h" +#include "esphome/core/preferences.h" +#include "esphome/components/i2c/i2c.h" +#include "esphome/components/one_wire/one_wire.h" + +namespace esphome { +namespace ds2484 { + +class DS2484OneWireBus : public one_wire::OneWireBus, public i2c::I2CDevice, public Component { + public: + void setup() override; + void dump_config() override; + float get_setup_priority() const override { return setup_priority::BUS - 1.0; } + + bool reset_device(); + int reset_int() override; + void write8(uint8_t) override; + void write64(uint64_t) override; + uint8_t read8() override; + uint64_t read64() override; + + void set_active_pullup(bool value) { this->active_pullup_ = value; } + void set_strong_pullup(bool value) { this->strong_pullup_ = value; } + + protected: + void reset_search() override; + uint64_t search_int() override; + bool read_status_(uint8_t *); + bool wait_for_completion_(); + void write8_(uint8_t); + bool one_wire_triple_(bool *branch, bool *id_bit, bool *cmp_id_bit); + + uint64_t address_; + uint8_t last_discrepancy_{0}; + bool last_device_flag_{false}; + bool active_pullup_{false}; + bool strong_pullup_{false}; +}; +} // namespace ds2484 +} // namespace esphome diff --git a/esphome/components/ds2484/one_wire.py b/esphome/components/ds2484/one_wire.py new file mode 100644 index 0000000000..384b2d01e6 --- /dev/null +++ b/esphome/components/ds2484/one_wire.py @@ -0,0 +1,37 @@ +import esphome.codegen as cg +from esphome.components import i2c +from esphome.components.one_wire import OneWireBus +import esphome.config_validation as cv +from esphome.const import CONF_ID + +ds2484_ns = cg.esphome_ns.namespace("ds2484") + +CONF_ACTIVE_PULLUP = "active_pullup" +CONF_STRONG_PULLUP = "strong_pullup" + +CODEOWNERS = ["@mrk-its"] +DEPENDENCIES = ["i2c"] + +DS2484OneWireBus = ds2484_ns.class_( + "DS2484OneWireBus", OneWireBus, i2c.I2CDevice, cg.Component +) + +CONFIG_SCHEMA = ( + cv.Schema( + { + cv.GenerateID(): cv.declare_id(DS2484OneWireBus), + cv.Optional(CONF_ACTIVE_PULLUP, default=False): cv.boolean, + cv.Optional(CONF_STRONG_PULLUP, default=False): cv.boolean, + } + ) + .extend(cv.COMPONENT_SCHEMA) + .extend(i2c.i2c_device_schema(0x18)) +) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await i2c.register_i2c_device(var, config) + await cg.register_component(var, config) + cg.add(var.set_active_pullup(config[CONF_ACTIVE_PULLUP])) + cg.add(var.set_strong_pullup(config[CONF_STRONG_PULLUP])) diff --git a/esphome/components/esp32/helpers.cpp b/esphome/components/esp32/helpers.cpp new file mode 100644 index 0000000000..310e7bd94a --- /dev/null +++ b/esphome/components/esp32/helpers.cpp @@ -0,0 +1,69 @@ +#include "esphome/core/helpers.h" + +#ifdef USE_ESP32 + +#include "esp_efuse.h" +#include "esp_efuse_table.h" +#include "esp_mac.h" + +#include +#include +#include "esp_random.h" +#include "esp_system.h" + +namespace esphome { + +uint32_t random_uint32() { return esp_random(); } +bool random_bytes(uint8_t *data, size_t len) { + esp_fill_random(data, len); + return true; +} + +Mutex::Mutex() { handle_ = xSemaphoreCreateMutex(); } +Mutex::~Mutex() {} +void Mutex::lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); } +bool Mutex::try_lock() { return xSemaphoreTake(this->handle_, 0) == pdTRUE; } +void Mutex::unlock() { xSemaphoreGive(this->handle_); } + +// only affects the executing core +// so should not be used as a mutex lock, only to get accurate timing +IRAM_ATTR InterruptLock::InterruptLock() { portDISABLE_INTERRUPTS(); } +IRAM_ATTR InterruptLock::~InterruptLock() { portENABLE_INTERRUPTS(); } + +void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter) +#if defined(CONFIG_SOC_IEEE802154_SUPPORTED) + // When CONFIG_SOC_IEEE802154_SUPPORTED is defined, esp_efuse_mac_get_default + // returns the 802.15.4 EUI-64 address, so we read directly from eFuse instead. + if (has_custom_mac_address()) { + esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48); + } else { + esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, 48); + } +#else + if (has_custom_mac_address()) { + esp_efuse_mac_get_custom(mac); + } else { + esp_efuse_mac_get_default(mac); + } +#endif +} + +void set_mac_address(uint8_t *mac) { esp_base_mac_addr_set(mac); } + +bool has_custom_mac_address() { +#if !defined(USE_ESP32_IGNORE_EFUSE_CUSTOM_MAC) + uint8_t mac[6]; + // do not use 'esp_efuse_mac_get_custom(mac)' because it drops an error in the logs whenever it fails +#ifndef USE_ESP32_VARIANT_ESP32 + return (esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA_MAC_CUSTOM, mac, 48) == ESP_OK) && mac_address_is_valid(mac); +#else + return (esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48) == ESP_OK) && mac_address_is_valid(mac); +#endif +#else + return false; +#endif +} + +} // namespace esphome + +#endif // USE_ESP32 diff --git a/esphome/components/esp32_ble/ble.h b/esphome/components/esp32_ble/ble.h index ce452d65c4..2c5697df82 100644 --- a/esphome/components/esp32_ble/ble.h +++ b/esphome/components/esp32_ble/ble.h @@ -25,10 +25,15 @@ namespace esphome { namespace esp32_ble { // Maximum number of BLE scan results to buffer +// Sized to handle bursts of advertisements while allowing for processing delays +// With 16 advertisements per batch and some safety margin: +// - Without PSRAM: 24 entries (1.5× batch size) +// - With PSRAM: 36 entries (2.25× batch size) +// The reduced structure size (~80 bytes vs ~400 bytes) allows for larger buffers #ifdef USE_PSRAM -static constexpr uint8_t SCAN_RESULT_BUFFER_SIZE = 32; +static constexpr uint8_t SCAN_RESULT_BUFFER_SIZE = 36; #else -static constexpr uint8_t SCAN_RESULT_BUFFER_SIZE = 20; +static constexpr uint8_t SCAN_RESULT_BUFFER_SIZE = 24; #endif // Maximum size of the BLE event queue - must be power of 2 for lock-free queue @@ -51,7 +56,7 @@ enum IoCapability { IO_CAP_KBDISP = ESP_IO_CAP_KBDISP, }; -enum BLEComponentState { +enum BLEComponentState : uint8_t { /** Nothing has been initialized yet. */ BLE_COMPONENT_STATE_OFF = 0, /** BLE should be disabled on next loop. */ @@ -141,21 +146,31 @@ class ESP32BLE : public Component { private: template friend void enqueue_ble_event(Args... args); + // Vectors (12 bytes each on 32-bit, naturally aligned to 4 bytes) std::vector gap_event_handlers_; std::vector gap_scan_event_handlers_; std::vector gattc_event_handlers_; std::vector gatts_event_handlers_; std::vector ble_status_event_handlers_; - BLEComponentState state_{BLE_COMPONENT_STATE_OFF}; + // Large objects (size depends on template parameters, but typically aligned to 4 bytes) esphome::LockFreeQueue ble_events_; esphome::EventPool ble_event_pool_; - BLEAdvertising *advertising_{}; - esp_ble_io_cap_t io_cap_{ESP_IO_CAP_NONE}; - uint32_t advertising_cycle_time_{}; - bool enable_on_boot_{}; + + // optional (typically 16+ bytes on 32-bit, aligned to 4 bytes) optional name_; - uint16_t appearance_{0}; + + // 4-byte aligned members + BLEAdvertising *advertising_{}; // 4 bytes (pointer) + esp_ble_io_cap_t io_cap_{ESP_IO_CAP_NONE}; // 4 bytes (enum) + uint32_t advertising_cycle_time_{}; // 4 bytes + + // 2-byte aligned members + uint16_t appearance_{0}; // 2 bytes + + // 1-byte aligned members (grouped together to minimize padding) + BLEComponentState state_{BLE_COMPONENT_STATE_OFF}; // 1 byte (uint8_t enum) + bool enable_on_boot_{}; // 1 byte }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) diff --git a/esphome/components/esp32_camera/__init__.py b/esphome/components/esp32_camera/__init__.py index 8dc2ede372..138f318a5d 100644 --- a/esphome/components/esp32_camera/__init__.py +++ b/esphome/components/esp32_camera/__init__.py @@ -23,7 +23,7 @@ from esphome.core.entity_helpers import setup_entity DEPENDENCIES = ["esp32"] -AUTO_LOAD = ["psram"] +AUTO_LOAD = ["camera", "psram"] esp32_camera_ns = cg.esphome_ns.namespace("esp32_camera") ESP32Camera = esp32_camera_ns.class_("ESP32Camera", cg.PollingComponent, cg.EntityBase) @@ -283,6 +283,7 @@ SETTERS = { async def to_code(config): + cg.add_define("USE_CAMERA") var = cg.new_Pvariable(config[CONF_ID]) await setup_entity(var, config, "camera") await cg.register_component(var, config) diff --git a/esphome/components/esp32_camera/esp32_camera.cpp b/esphome/components/esp32_camera/esp32_camera.cpp index 243d3d3e47..eadb8a4408 100644 --- a/esphome/components/esp32_camera/esp32_camera.cpp +++ b/esphome/components/esp32_camera/esp32_camera.cpp @@ -14,8 +14,6 @@ static const char *const TAG = "esp32_camera"; /* ---------------- public API (derivated) ---------------- */ void ESP32Camera::setup() { - global_esp32_camera = this; - #ifdef USE_I2C if (this->i2c_bus_ != nullptr) { this->config_.sccb_i2c_port = this->i2c_bus_->get_port(); @@ -43,7 +41,7 @@ void ESP32Camera::setup() { xTaskCreatePinnedToCore(&ESP32Camera::framebuffer_task, "framebuffer_task", // name 1024, // stack size - nullptr, // task pv params + this, // task pv params 1, // priority nullptr, // handle 1 // core @@ -176,7 +174,7 @@ void ESP32Camera::loop() { const uint32_t now = App.get_loop_component_start_time(); if (this->idle_update_interval_ != 0 && now - this->last_idle_request_ > this->idle_update_interval_) { this->last_idle_request_ = now; - this->request_image(IDLE); + this->request_image(camera::IDLE); } // Check if we should fetch a new image @@ -202,7 +200,7 @@ void ESP32Camera::loop() { xQueueSend(this->framebuffer_return_queue_, &fb, portMAX_DELAY); return; } - this->current_image_ = std::make_shared(fb, this->single_requesters_ | this->stream_requesters_); + this->current_image_ = std::make_shared(fb, this->single_requesters_ | this->stream_requesters_); ESP_LOGD(TAG, "Got Image: len=%u", fb->len); this->new_image_callback_.call(this->current_image_); @@ -225,8 +223,6 @@ ESP32Camera::ESP32Camera() { this->config_.fb_count = 1; this->config_.grab_mode = CAMERA_GRAB_WHEN_EMPTY; this->config_.fb_location = CAMERA_FB_IN_PSRAM; - - global_esp32_camera = this; } /* ---------------- setters ---------------- */ @@ -356,7 +352,7 @@ void ESP32Camera::set_frame_buffer_count(uint8_t fb_count) { } /* ---------------- public API (specific) ---------------- */ -void ESP32Camera::add_image_callback(std::function)> &&callback) { +void ESP32Camera::add_image_callback(std::function)> &&callback) { this->new_image_callback_.add(std::move(callback)); } void ESP32Camera::add_stream_start_callback(std::function &&callback) { @@ -365,15 +361,16 @@ void ESP32Camera::add_stream_start_callback(std::function &&callback) { void ESP32Camera::add_stream_stop_callback(std::function &&callback) { this->stream_stop_callback_.add(std::move(callback)); } -void ESP32Camera::start_stream(CameraRequester requester) { +void ESP32Camera::start_stream(camera::CameraRequester requester) { this->stream_start_callback_.call(); this->stream_requesters_ |= (1U << requester); } -void ESP32Camera::stop_stream(CameraRequester requester) { +void ESP32Camera::stop_stream(camera::CameraRequester requester) { this->stream_stop_callback_.call(); this->stream_requesters_ &= ~(1U << requester); } -void ESP32Camera::request_image(CameraRequester requester) { this->single_requesters_ |= (1U << requester); } +void ESP32Camera::request_image(camera::CameraRequester requester) { this->single_requesters_ |= (1U << requester); } +camera::CameraImageReader *ESP32Camera::create_image_reader() { return new ESP32CameraImageReader; } void ESP32Camera::update_camera_parameters() { sensor_t *s = esp_camera_sensor_get(); /* update image */ @@ -402,39 +399,39 @@ void ESP32Camera::update_camera_parameters() { bool ESP32Camera::has_requested_image_() const { return this->single_requesters_ || this->stream_requesters_; } bool ESP32Camera::can_return_image_() const { return this->current_image_.use_count() == 1; } void ESP32Camera::framebuffer_task(void *pv) { + ESP32Camera *that = (ESP32Camera *) pv; while (true) { camera_fb_t *framebuffer = esp_camera_fb_get(); - xQueueSend(global_esp32_camera->framebuffer_get_queue_, &framebuffer, portMAX_DELAY); + xQueueSend(that->framebuffer_get_queue_, &framebuffer, portMAX_DELAY); // return is no-op for config with 1 fb - xQueueReceive(global_esp32_camera->framebuffer_return_queue_, &framebuffer, portMAX_DELAY); + xQueueReceive(that->framebuffer_return_queue_, &framebuffer, portMAX_DELAY); esp_camera_fb_return(framebuffer); } } -ESP32Camera *global_esp32_camera; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) - -/* ---------------- CameraImageReader class ---------------- */ -void CameraImageReader::set_image(std::shared_ptr image) { - this->image_ = std::move(image); +/* ---------------- ESP32CameraImageReader class ----------- */ +void ESP32CameraImageReader::set_image(std::shared_ptr image) { + this->image_ = std::static_pointer_cast(image); this->offset_ = 0; } -size_t CameraImageReader::available() const { +size_t ESP32CameraImageReader::available() const { if (!this->image_) return 0; return this->image_->get_data_length() - this->offset_; } -void CameraImageReader::return_image() { this->image_.reset(); } -void CameraImageReader::consume_data(size_t consumed) { this->offset_ += consumed; } -uint8_t *CameraImageReader::peek_data_buffer() { return this->image_->get_data_buffer() + this->offset_; } +void ESP32CameraImageReader::return_image() { this->image_.reset(); } +void ESP32CameraImageReader::consume_data(size_t consumed) { this->offset_ += consumed; } +uint8_t *ESP32CameraImageReader::peek_data_buffer() { return this->image_->get_data_buffer() + this->offset_; } -/* ---------------- CameraImage class ---------------- */ -CameraImage::CameraImage(camera_fb_t *buffer, uint8_t requesters) : buffer_(buffer), requesters_(requesters) {} +/* ---------------- ESP32CameraImage class ----------- */ +ESP32CameraImage::ESP32CameraImage(camera_fb_t *buffer, uint8_t requesters) + : buffer_(buffer), requesters_(requesters) {} -camera_fb_t *CameraImage::get_raw_buffer() { return this->buffer_; } -uint8_t *CameraImage::get_data_buffer() { return this->buffer_->buf; } -size_t CameraImage::get_data_length() { return this->buffer_->len; } -bool CameraImage::was_requested_by(CameraRequester requester) const { +camera_fb_t *ESP32CameraImage::get_raw_buffer() { return this->buffer_; } +uint8_t *ESP32CameraImage::get_data_buffer() { return this->buffer_->buf; } +size_t ESP32CameraImage::get_data_length() { return this->buffer_->len; } +bool ESP32CameraImage::was_requested_by(camera::CameraRequester requester) const { return (this->requesters_ & (1 << requester)) != 0; } diff --git a/esphome/components/esp32_camera/esp32_camera.h b/esphome/components/esp32_camera/esp32_camera.h index 75139ba400..8ce3faf039 100644 --- a/esphome/components/esp32_camera/esp32_camera.h +++ b/esphome/components/esp32_camera/esp32_camera.h @@ -7,7 +7,7 @@ #include #include "esphome/core/automation.h" #include "esphome/core/component.h" -#include "esphome/core/entity_base.h" +#include "esphome/components/camera/camera.h" #include "esphome/core/helpers.h" #ifdef USE_I2C @@ -19,9 +19,6 @@ namespace esp32_camera { class ESP32Camera; -/* ---------------- enum classes ---------------- */ -enum CameraRequester { IDLE, API_REQUESTER, WEB_REQUESTER }; - enum ESP32CameraFrameSize { ESP32_CAMERA_SIZE_160X120, // QQVGA ESP32_CAMERA_SIZE_176X144, // QCIF @@ -77,13 +74,13 @@ enum ESP32SpecialEffect { }; /* ---------------- CameraImage class ---------------- */ -class CameraImage { +class ESP32CameraImage : public camera::CameraImage { public: - CameraImage(camera_fb_t *buffer, uint8_t requester); + ESP32CameraImage(camera_fb_t *buffer, uint8_t requester); camera_fb_t *get_raw_buffer(); - uint8_t *get_data_buffer(); - size_t get_data_length(); - bool was_requested_by(CameraRequester requester) const; + uint8_t *get_data_buffer() override; + size_t get_data_length() override; + bool was_requested_by(camera::CameraRequester requester) const override; protected: camera_fb_t *buffer_; @@ -96,21 +93,21 @@ struct CameraImageData { }; /* ---------------- CameraImageReader class ---------------- */ -class CameraImageReader { +class ESP32CameraImageReader : public camera::CameraImageReader { public: - void set_image(std::shared_ptr image); - size_t available() const; - uint8_t *peek_data_buffer(); - void consume_data(size_t consumed); - void return_image(); + void set_image(std::shared_ptr image) override; + size_t available() const override; + uint8_t *peek_data_buffer() override; + void consume_data(size_t consumed) override; + void return_image() override; protected: - std::shared_ptr image_; + std::shared_ptr image_; size_t offset_{0}; }; /* ---------------- ESP32Camera class ---------------- */ -class ESP32Camera : public EntityBase, public Component { +class ESP32Camera : public camera::Camera { public: ESP32Camera(); @@ -162,14 +159,15 @@ class ESP32Camera : public EntityBase, public Component { void dump_config() override; float get_setup_priority() const override; /* public API (specific) */ - void start_stream(CameraRequester requester); - void stop_stream(CameraRequester requester); - void request_image(CameraRequester requester); + void start_stream(camera::CameraRequester requester) override; + void stop_stream(camera::CameraRequester requester) override; + void request_image(camera::CameraRequester requester) override; void update_camera_parameters(); - void add_image_callback(std::function)> &&callback); + void add_image_callback(std::function)> &&callback) override; void add_stream_start_callback(std::function &&callback); void add_stream_stop_callback(std::function &&callback); + camera::CameraImageReader *create_image_reader() override; protected: /* internal methods */ @@ -206,12 +204,12 @@ class ESP32Camera : public EntityBase, public Component { uint32_t idle_update_interval_{15000}; esp_err_t init_error_{ESP_OK}; - std::shared_ptr current_image_; + std::shared_ptr current_image_; uint8_t single_requesters_{0}; uint8_t stream_requesters_{0}; QueueHandle_t framebuffer_get_queue_; QueueHandle_t framebuffer_return_queue_; - CallbackManager)> new_image_callback_{}; + CallbackManager)> new_image_callback_{}; CallbackManager stream_start_callback_{}; CallbackManager stream_stop_callback_{}; @@ -222,13 +220,10 @@ class ESP32Camera : public EntityBase, public Component { #endif // USE_I2C }; -// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) -extern ESP32Camera *global_esp32_camera; - class ESP32CameraImageTrigger : public Trigger { public: explicit ESP32CameraImageTrigger(ESP32Camera *parent) { - parent->add_image_callback([this](const std::shared_ptr &image) { + parent->add_image_callback([this](const std::shared_ptr &image) { CameraImageData camera_image_data{}; camera_image_data.length = image->get_data_length(); camera_image_data.data = image->get_data_buffer(); diff --git a/esphome/components/esp32_camera_web_server/__init__.py b/esphome/components/esp32_camera_web_server/__init__.py index df137c8ff2..a6a7ac3630 100644 --- a/esphome/components/esp32_camera_web_server/__init__.py +++ b/esphome/components/esp32_camera_web_server/__init__.py @@ -3,7 +3,8 @@ import esphome.config_validation as cv from esphome.const import CONF_ID, CONF_MODE, CONF_PORT CODEOWNERS = ["@ayufan"] -DEPENDENCIES = ["esp32_camera", "network"] +AUTO_LOAD = ["camera"] +DEPENDENCIES = ["network"] MULTI_CONF = True esp32_camera_web_server_ns = cg.esphome_ns.namespace("esp32_camera_web_server") diff --git a/esphome/components/esp32_camera_web_server/camera_web_server.cpp b/esphome/components/esp32_camera_web_server/camera_web_server.cpp index 0a83128908..1b81989296 100644 --- a/esphome/components/esp32_camera_web_server/camera_web_server.cpp +++ b/esphome/components/esp32_camera_web_server/camera_web_server.cpp @@ -40,7 +40,7 @@ CameraWebServer::CameraWebServer() {} CameraWebServer::~CameraWebServer() {} void CameraWebServer::setup() { - if (!esp32_camera::global_esp32_camera || esp32_camera::global_esp32_camera->is_failed()) { + if (!camera::Camera::instance() || camera::Camera::instance()->is_failed()) { this->mark_failed(); return; } @@ -67,8 +67,8 @@ void CameraWebServer::setup() { httpd_register_uri_handler(this->httpd_, &uri); - esp32_camera::global_esp32_camera->add_image_callback([this](std::shared_ptr image) { - if (this->running_ && image->was_requested_by(esp32_camera::WEB_REQUESTER)) { + camera::Camera::instance()->add_image_callback([this](std::shared_ptr image) { + if (this->running_ && image->was_requested_by(camera::WEB_REQUESTER)) { this->image_ = std::move(image); xSemaphoreGive(this->semaphore_); } @@ -108,8 +108,8 @@ void CameraWebServer::loop() { } } -std::shared_ptr CameraWebServer::wait_for_image_() { - std::shared_ptr image; +std::shared_ptr CameraWebServer::wait_for_image_() { + std::shared_ptr image; image.swap(this->image_); if (!image) { @@ -172,7 +172,7 @@ esp_err_t CameraWebServer::streaming_handler_(struct httpd_req *req) { uint32_t last_frame = millis(); uint32_t frames = 0; - esp32_camera::global_esp32_camera->start_stream(esphome::esp32_camera::WEB_REQUESTER); + camera::Camera::instance()->start_stream(esphome::camera::WEB_REQUESTER); while (res == ESP_OK && this->running_) { auto image = this->wait_for_image_(); @@ -205,7 +205,7 @@ esp_err_t CameraWebServer::streaming_handler_(struct httpd_req *req) { res = httpd_send_all(req, STREAM_ERROR, strlen(STREAM_ERROR)); } - esp32_camera::global_esp32_camera->stop_stream(esphome::esp32_camera::WEB_REQUESTER); + camera::Camera::instance()->stop_stream(esphome::camera::WEB_REQUESTER); ESP_LOGI(TAG, "STREAM: closed. Frames: %" PRIu32, frames); @@ -215,7 +215,7 @@ esp_err_t CameraWebServer::streaming_handler_(struct httpd_req *req) { esp_err_t CameraWebServer::snapshot_handler_(struct httpd_req *req) { esp_err_t res = ESP_OK; - esp32_camera::global_esp32_camera->request_image(esphome::esp32_camera::WEB_REQUESTER); + camera::Camera::instance()->request_image(esphome::camera::WEB_REQUESTER); auto image = this->wait_for_image_(); 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 3ba8f31dd7..e70246745c 100644 --- a/esphome/components/esp32_camera_web_server/camera_web_server.h +++ b/esphome/components/esp32_camera_web_server/camera_web_server.h @@ -6,7 +6,7 @@ #include #include -#include "esphome/components/esp32_camera/esp32_camera.h" +#include "esphome/components/camera/camera.h" #include "esphome/core/component.h" #include "esphome/core/helpers.h" #include "esphome/core/preferences.h" @@ -32,7 +32,7 @@ class CameraWebServer : public Component { void loop() override; protected: - std::shared_ptr wait_for_image_(); + std::shared_ptr wait_for_image_(); esp_err_t handler_(struct httpd_req *req); esp_err_t streaming_handler_(struct httpd_req *req); esp_err_t snapshot_handler_(struct httpd_req *req); @@ -40,7 +40,7 @@ class CameraWebServer : public Component { uint16_t port_{0}; void *httpd_{nullptr}; SemaphoreHandle_t semaphore_; - std::shared_ptr image_; + std::shared_ptr image_; bool running_{false}; Mode mode_{STREAM}; }; diff --git a/esphome/components/esp8266/helpers.cpp b/esphome/components/esp8266/helpers.cpp new file mode 100644 index 0000000000..993de710c6 --- /dev/null +++ b/esphome/components/esp8266/helpers.cpp @@ -0,0 +1,31 @@ +#include "esphome/core/helpers.h" + +#ifdef USE_ESP8266 + +#include +#include +// for xt_rsil()/xt_wsr_ps() +#include + +namespace esphome { + +uint32_t random_uint32() { return os_random(); } +bool random_bytes(uint8_t *data, size_t len) { return os_get_random(data, len) == 0; } + +// ESP8266 doesn't have mutexes, but that shouldn't be an issue as it's single-core and non-preemptive OS. +Mutex::Mutex() {} +Mutex::~Mutex() {} +void Mutex::lock() {} +bool Mutex::try_lock() { return true; } +void Mutex::unlock() {} + +IRAM_ATTR InterruptLock::InterruptLock() { state_ = xt_rsil(15); } +IRAM_ATTR InterruptLock::~InterruptLock() { xt_wsr_ps(state_); } + +void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter) + wifi_get_macaddr(STATION_IF, mac); +} + +} // namespace esphome + +#endif // USE_ESP8266 diff --git a/esphome/components/host/helpers.cpp b/esphome/components/host/helpers.cpp new file mode 100644 index 0000000000..fdad4f5cb6 --- /dev/null +++ b/esphome/components/host/helpers.cpp @@ -0,0 +1,57 @@ +#include "esphome/core/helpers.h" + +#ifdef USE_HOST + +#ifndef _WIN32 +#include +#include +#include +#endif +#include +#include +#include + +#include "esphome/core/defines.h" +#include "esphome/core/log.h" + +namespace esphome { + +static const char *const TAG = "helpers.host"; + +uint32_t random_uint32() { + std::random_device dev; + std::mt19937 rng(dev()); + std::uniform_int_distribution dist(0, std::numeric_limits::max()); + return dist(rng); +} + +bool random_bytes(uint8_t *data, size_t len) { + FILE *fp = fopen("/dev/urandom", "r"); + if (fp == nullptr) { + ESP_LOGW(TAG, "Could not open /dev/urandom, errno=%d", errno); + exit(1); + } + size_t read = fread(data, 1, len, fp); + if (read != len) { + ESP_LOGW(TAG, "Not enough data from /dev/urandom"); + exit(1); + } + fclose(fp); + return true; +} + +// Host platform uses std::mutex for proper thread synchronization +Mutex::Mutex() { handle_ = new std::mutex(); } +Mutex::~Mutex() { delete static_cast(handle_); } +void Mutex::lock() { static_cast(handle_)->lock(); } +bool Mutex::try_lock() { return static_cast(handle_)->try_lock(); } +void Mutex::unlock() { static_cast(handle_)->unlock(); } + +void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter) + static const uint8_t esphome_host_mac_address[6] = USE_ESPHOME_HOST_MAC_ADDRESS; + memcpy(mac, esphome_host_mac_address, sizeof(esphome_host_mac_address)); +} + +} // namespace esphome + +#endif // USE_HOST diff --git a/esphome/components/http_request/__init__.py b/esphome/components/http_request/__init__.py index 18373edb77..0d32bc97c2 100644 --- a/esphome/components/http_request/__init__.py +++ b/esphome/components/http_request/__init__.py @@ -2,6 +2,7 @@ from esphome import automation import esphome.codegen as cg from esphome.components import esp32 from esphome.components.const import CONF_REQUEST_HEADERS +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_ESP8266_DISABLE_SSL_SUPPORT, @@ -13,6 +14,7 @@ from esphome.const import ( CONF_URL, CONF_WATCHDOG_TIMEOUT, PLATFORM_HOST, + PlatformFramework, __version__, ) from esphome.core import CORE, Lambda @@ -319,3 +321,19 @@ async def http_request_action_to_code(config, action_id, template_arg, args): await automation.build_automation(trigger, [], conf) return var + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "http_request_host.cpp": {PlatformFramework.HOST_NATIVE}, + "http_request_arduino.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP8266_ARDUINO, + PlatformFramework.RP2040_ARDUINO, + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + "http_request_idf.cpp": {PlatformFramework.ESP32_IDF}, + } +) diff --git a/esphome/components/http_request/update/http_request_update.cpp b/esphome/components/http_request/update/http_request_update.cpp index 6bc88ae49a..202c7b88b2 100644 --- a/esphome/components/http_request/update/http_request_update.cpp +++ b/esphome/components/http_request/update/http_request_update.cpp @@ -50,7 +50,8 @@ void HttpRequestUpdate::update_task(void *params) { if (container == nullptr || container->status_code != HTTP_STATUS_OK) { std::string msg = str_sprintf("Failed to fetch manifest from %s", this_update->source_url_.c_str()); - this_update->status_set_error(msg.c_str()); + // Defer to main loop to avoid race condition on component_state_ read-modify-write + this_update->defer([this_update, msg]() { this_update->status_set_error(msg.c_str()); }); UPDATE_RETURN; } @@ -58,7 +59,8 @@ void HttpRequestUpdate::update_task(void *params) { uint8_t *data = allocator.allocate(container->content_length); if (data == nullptr) { std::string msg = str_sprintf("Failed to allocate %zu bytes for manifest", container->content_length); - this_update->status_set_error(msg.c_str()); + // Defer to main loop to avoid race condition on component_state_ read-modify-write + this_update->defer([this_update, msg]() { this_update->status_set_error(msg.c_str()); }); container->end(); UPDATE_RETURN; } @@ -120,7 +122,8 @@ void HttpRequestUpdate::update_task(void *params) { if (!valid) { std::string msg = str_sprintf("Failed to parse JSON from %s", this_update->source_url_.c_str()); - this_update->status_set_error(msg.c_str()); + // Defer to main loop to avoid race condition on component_state_ read-modify-write + this_update->defer([this_update, msg]() { this_update->status_set_error(msg.c_str()); }); UPDATE_RETURN; } @@ -147,18 +150,34 @@ void HttpRequestUpdate::update_task(void *params) { this_update->update_info_.current_version = current_version; } + bool trigger_update_available = false; + if (this_update->update_info_.latest_version.empty() || this_update->update_info_.latest_version == this_update->update_info_.current_version) { this_update->state_ = update::UPDATE_STATE_NO_UPDATE; } else { + if (this_update->state_ != update::UPDATE_STATE_AVAILABLE) { + trigger_update_available = true; + } this_update->state_ = update::UPDATE_STATE_AVAILABLE; } - this_update->update_info_.has_progress = false; - this_update->update_info_.progress = 0.0f; + // Defer to main loop to ensure thread-safe execution of: + // - status_clear_error() performs non-atomic read-modify-write on component_state_ + // - publish_state() triggers API callbacks that write to the shared protobuf buffer + // which can be corrupted if accessed concurrently from task and main loop threads + // - update_available trigger to ensure consistent state when the trigger fires + this_update->defer([this_update, trigger_update_available]() { + this_update->update_info_.has_progress = false; + this_update->update_info_.progress = 0.0f; - this_update->status_clear_error(); - this_update->publish_state(); + this_update->status_clear_error(); + this_update->publish_state(); + + if (trigger_update_available) { + this_update->get_update_available_trigger()->trigger(this_update->update_info_); + } + }); UPDATE_RETURN; } diff --git a/esphome/components/i2c/__init__.py b/esphome/components/i2c/__init__.py index 6adb9b71aa..4172b23845 100644 --- a/esphome/components/i2c/__init__.py +++ b/esphome/components/i2c/__init__.py @@ -3,6 +3,7 @@ import logging from esphome import pins import esphome.codegen as cg from esphome.components import esp32 +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_ADDRESS, @@ -18,6 +19,7 @@ from esphome.const import ( PLATFORM_ESP32, PLATFORM_ESP8266, PLATFORM_RP2040, + PlatformFramework, ) from esphome.core import CORE, coroutine_with_priority import esphome.final_validate as fv @@ -205,3 +207,18 @@ def final_validate_device_schema( {cv.Required(CONF_I2C_ID): fv.id_declaration_match_schema(hub_schema)}, extra=cv.ALLOW_EXTRA, ) + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "i2c_bus_arduino.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP8266_ARDUINO, + PlatformFramework.RP2040_ARDUINO, + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + "i2c_bus_esp_idf.cpp": {PlatformFramework.ESP32_IDF}, + } +) diff --git a/esphome/components/inkplate6/display.py b/esphome/components/inkplate6/display.py index a7d31c0131..063fc8b0aa 100644 --- a/esphome/components/inkplate6/display.py +++ b/esphome/components/inkplate6/display.py @@ -1,6 +1,7 @@ from esphome import pins import esphome.codegen as cg from esphome.components import display, i2c +from esphome.components.esp32 import CONF_CPU_FREQUENCY import esphome.config_validation as cv from esphome.const import ( CONF_FULL_UPDATE_EVERY, @@ -13,7 +14,9 @@ from esphome.const import ( CONF_PAGES, CONF_TRANSFORM, CONF_WAKEUP_PIN, + PLATFORM_ESP32, ) +import esphome.final_validate as fv DEPENDENCIES = ["i2c", "esp32"] AUTO_LOAD = ["psram"] @@ -120,6 +123,18 @@ CONFIG_SCHEMA = cv.All( ) +def _validate_cpu_frequency(config): + esp32_config = fv.full_config.get()[PLATFORM_ESP32] + if esp32_config[CONF_CPU_FREQUENCY] != "240MHZ": + raise cv.Invalid( + "Inkplate requires 240MHz CPU frequency (set in esp32 component)" + ) + return config + + +FINAL_VALIDATE_SCHEMA = _validate_cpu_frequency + + async def to_code(config): var = cg.new_Pvariable(config[CONF_ID]) diff --git a/esphome/components/ld2410/button/__init__.py b/esphome/components/ld2410/button/__init__.py index 4cb50d707b..1cd56082c3 100644 --- a/esphome/components/ld2410/button/__init__.py +++ b/esphome/components/ld2410/button/__init__.py @@ -14,8 +14,8 @@ from esphome.const import ( from .. import CONF_LD2410_ID, LD2410Component, ld2410_ns +FactoryResetButton = ld2410_ns.class_("FactoryResetButton", button.Button) QueryButton = ld2410_ns.class_("QueryButton", button.Button) -ResetButton = ld2410_ns.class_("ResetButton", button.Button) RestartButton = ld2410_ns.class_("RestartButton", button.Button) CONF_QUERY_PARAMS = "query_params" @@ -23,7 +23,7 @@ CONF_QUERY_PARAMS = "query_params" CONFIG_SCHEMA = { cv.GenerateID(CONF_LD2410_ID): cv.use_id(LD2410Component), cv.Optional(CONF_FACTORY_RESET): button.button_schema( - ResetButton, + FactoryResetButton, device_class=DEVICE_CLASS_RESTART, entity_category=ENTITY_CATEGORY_CONFIG, icon=ICON_RESTART_ALERT, @@ -47,7 +47,7 @@ async def to_code(config): if factory_reset_config := config.get(CONF_FACTORY_RESET): b = await button.new_button(factory_reset_config) await cg.register_parented(b, config[CONF_LD2410_ID]) - cg.add(ld2410_component.set_reset_button(b)) + cg.add(ld2410_component.set_factory_reset_button(b)) if restart_config := config.get(CONF_RESTART): b = await button.new_button(restart_config) await cg.register_parented(b, config[CONF_LD2410_ID]) diff --git a/esphome/components/ld2410/button/factory_reset_button.cpp b/esphome/components/ld2410/button/factory_reset_button.cpp new file mode 100644 index 0000000000..a848b02a9d --- /dev/null +++ b/esphome/components/ld2410/button/factory_reset_button.cpp @@ -0,0 +1,9 @@ +#include "factory_reset_button.h" + +namespace esphome { +namespace ld2410 { + +void FactoryResetButton::press_action() { this->parent_->factory_reset(); } + +} // namespace ld2410 +} // namespace esphome diff --git a/esphome/components/ld2410/button/reset_button.h b/esphome/components/ld2410/button/factory_reset_button.h similarity index 65% rename from esphome/components/ld2410/button/reset_button.h rename to esphome/components/ld2410/button/factory_reset_button.h index 78dd92c9f5..45bf979033 100644 --- a/esphome/components/ld2410/button/reset_button.h +++ b/esphome/components/ld2410/button/factory_reset_button.h @@ -6,9 +6,9 @@ namespace esphome { namespace ld2410 { -class ResetButton : public button::Button, public Parented { +class FactoryResetButton : public button::Button, public Parented { public: - ResetButton() = default; + FactoryResetButton() = default; protected: void press_action() override; diff --git a/esphome/components/ld2410/button/reset_button.cpp b/esphome/components/ld2410/button/reset_button.cpp deleted file mode 100644 index f16c5faa79..0000000000 --- a/esphome/components/ld2410/button/reset_button.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "reset_button.h" - -namespace esphome { -namespace ld2410 { - -void ResetButton::press_action() { this->parent_->factory_reset(); } - -} // namespace ld2410 -} // namespace esphome diff --git a/esphome/components/ld2410/ld2410.cpp b/esphome/components/ld2410/ld2410.cpp index a34f99ee33..375d1088e8 100644 --- a/esphome/components/ld2410/ld2410.cpp +++ b/esphome/components/ld2410/ld2410.cpp @@ -18,11 +18,10 @@ namespace esphome { namespace ld2410 { static const char *const TAG = "ld2410"; -static const char *const NO_MAC = "08:05:04:03:02:01"; static const char *const UNKNOWN_MAC = "unknown"; static const char *const VERSION_FMT = "%u.%02X.%02X%02X%02X%02X"; -enum BaudRateStructure : uint8_t { +enum BaudRate : uint8_t { BAUD_RATE_9600 = 1, BAUD_RATE_19200 = 2, BAUD_RATE_38400 = 3, @@ -33,23 +32,23 @@ enum BaudRateStructure : uint8_t { BAUD_RATE_460800 = 8, }; -enum DistanceResolutionStructure : uint8_t { +enum DistanceResolution : uint8_t { DISTANCE_RESOLUTION_0_2 = 0x01, DISTANCE_RESOLUTION_0_75 = 0x00, }; -enum LightFunctionStructure : uint8_t { +enum LightFunction : uint8_t { LIGHT_FUNCTION_OFF = 0x00, LIGHT_FUNCTION_BELOW = 0x01, LIGHT_FUNCTION_ABOVE = 0x02, }; -enum OutPinLevelStructure : uint8_t { +enum OutPinLevel : uint8_t { OUT_PIN_LEVEL_LOW = 0x00, OUT_PIN_LEVEL_HIGH = 0x01, }; -enum PeriodicDataStructure : uint8_t { +enum PeriodicData : uint8_t { DATA_TYPES = 6, TARGET_STATES = 8, MOVING_TARGET_LOW = 9, @@ -67,12 +66,12 @@ enum PeriodicDataStructure : uint8_t { }; enum PeriodicDataValue : uint8_t { - HEAD = 0xAA, - END = 0x55, + HEADER = 0xAA, + FOOTER = 0x55, CHECK = 0x00, }; -enum AckDataStructure : uint8_t { +enum AckData : uint8_t { COMMAND = 6, COMMAND_STATUS = 7, }; @@ -80,11 +79,11 @@ enum AckDataStructure : uint8_t { // Memory-efficient lookup tables struct StringToUint8 { const char *str; - uint8_t value; + const uint8_t value; }; struct Uint8ToString { - uint8_t value; + const uint8_t value; const char *str; }; @@ -144,96 +143,119 @@ template const char *find_str(const Uint8ToString (&arr)[N], uint8_t v } // Commands -static const uint8_t CMD_ENABLE_CONF = 0xFF; -static const uint8_t CMD_DISABLE_CONF = 0xFE; -static const uint8_t CMD_ENABLE_ENG = 0x62; -static const uint8_t CMD_DISABLE_ENG = 0x63; -static const uint8_t CMD_MAXDIST_DURATION = 0x60; -static const uint8_t CMD_QUERY = 0x61; -static const uint8_t CMD_GATE_SENS = 0x64; -static const uint8_t CMD_VERSION = 0xA0; -static const uint8_t CMD_QUERY_DISTANCE_RESOLUTION = 0xAB; -static const uint8_t CMD_SET_DISTANCE_RESOLUTION = 0xAA; -static const uint8_t CMD_QUERY_LIGHT_CONTROL = 0xAE; -static const uint8_t CMD_SET_LIGHT_CONTROL = 0xAD; -static const uint8_t CMD_SET_BAUD_RATE = 0xA1; -static const uint8_t CMD_BT_PASSWORD = 0xA9; -static const uint8_t CMD_MAC = 0xA5; -static const uint8_t CMD_RESET = 0xA2; -static const uint8_t CMD_RESTART = 0xA3; -static const uint8_t CMD_BLUETOOTH = 0xA4; +static constexpr uint8_t CMD_ENABLE_CONF = 0xFF; +static constexpr uint8_t CMD_DISABLE_CONF = 0xFE; +static constexpr uint8_t CMD_ENABLE_ENG = 0x62; +static constexpr uint8_t CMD_DISABLE_ENG = 0x63; +static constexpr uint8_t CMD_MAXDIST_DURATION = 0x60; +static constexpr uint8_t CMD_QUERY = 0x61; +static constexpr uint8_t CMD_GATE_SENS = 0x64; +static constexpr uint8_t CMD_QUERY_VERSION = 0xA0; +static constexpr uint8_t CMD_QUERY_DISTANCE_RESOLUTION = 0xAB; +static constexpr uint8_t CMD_SET_DISTANCE_RESOLUTION = 0xAA; +static constexpr uint8_t CMD_QUERY_LIGHT_CONTROL = 0xAE; +static constexpr uint8_t CMD_SET_LIGHT_CONTROL = 0xAD; +static constexpr uint8_t CMD_SET_BAUD_RATE = 0xA1; +static constexpr uint8_t CMD_BT_PASSWORD = 0xA9; +static constexpr uint8_t CMD_QUERY_MAC_ADDRESS = 0xA5; +static constexpr uint8_t CMD_RESET = 0xA2; +static constexpr uint8_t CMD_RESTART = 0xA3; +static constexpr uint8_t CMD_BLUETOOTH = 0xA4; // Commands values -static const uint8_t CMD_MAX_MOVE_VALUE = 0x00; -static const uint8_t CMD_MAX_STILL_VALUE = 0x01; -static const uint8_t CMD_DURATION_VALUE = 0x02; +static constexpr uint8_t CMD_MAX_MOVE_VALUE = 0x00; +static constexpr uint8_t CMD_MAX_STILL_VALUE = 0x01; +static constexpr uint8_t CMD_DURATION_VALUE = 0x02; +// Header & Footer size +static constexpr uint8_t HEADER_FOOTER_SIZE = 4; // Command Header & Footer -static const uint8_t CMD_FRAME_HEADER[4] = {0xFD, 0xFC, 0xFB, 0xFA}; -static const uint8_t CMD_FRAME_END[4] = {0x04, 0x03, 0x02, 0x01}; +static constexpr uint8_t CMD_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xFD, 0xFC, 0xFB, 0xFA}; +static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0x04, 0x03, 0x02, 0x01}; // Data Header & Footer -static const uint8_t DATA_FRAME_HEADER[4] = {0xF4, 0xF3, 0xF2, 0xF1}; -static const uint8_t DATA_FRAME_END[4] = {0xF8, 0xF7, 0xF6, 0xF5}; +static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xF4, 0xF3, 0xF2, 0xF1}; +static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0xF6, 0xF5}; +// MAC address the module uses when Bluetooth is disabled +static constexpr uint8_t NO_MAC[] = {0x08, 0x05, 0x04, 0x03, 0x02, 0x01}; static inline int two_byte_to_int(char firstbyte, char secondbyte) { return (int16_t) (secondbyte << 8) + firstbyte; } +static bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) { + for (uint8_t i = 0; i < HEADER_FOOTER_SIZE; i++) { + if (header_footer[i] != buffer[i]) { + return false; // Mismatch in header/footer + } + } + return true; // Valid header/footer +} + void LD2410Component::dump_config() { - ESP_LOGCONFIG(TAG, "LD2410:"); + std::string mac_str = + mac_address_is_valid(this->mac_address_) ? format_mac_address_pretty(this->mac_address_) : UNKNOWN_MAC; + std::string version = str_sprintf(VERSION_FMT, this->version_[1], this->version_[0], this->version_[5], + this->version_[4], this->version_[3], this->version_[2]); + ESP_LOGCONFIG(TAG, + "LD2410:\n" + " Firmware version: %s\n" + " MAC address: %s\n" + " Throttle: %u ms", + version.c_str(), mac_str.c_str(), this->throttle_); #ifdef USE_BINARY_SENSOR - LOG_BINARY_SENSOR(" ", "TargetBinarySensor", this->target_binary_sensor_); - LOG_BINARY_SENSOR(" ", "MovingTargetBinarySensor", this->moving_target_binary_sensor_); - LOG_BINARY_SENSOR(" ", "StillTargetBinarySensor", this->still_target_binary_sensor_); - LOG_BINARY_SENSOR(" ", "OutPinPresenceStatusBinarySensor", this->out_pin_presence_status_binary_sensor_); -#endif -#ifdef USE_SWITCH - LOG_SWITCH(" ", "EngineeringModeSwitch", this->engineering_mode_switch_); - LOG_SWITCH(" ", "BluetoothSwitch", this->bluetooth_switch_); -#endif -#ifdef USE_BUTTON - LOG_BUTTON(" ", "ResetButton", this->reset_button_); - LOG_BUTTON(" ", "RestartButton", this->restart_button_); - LOG_BUTTON(" ", "QueryButton", this->query_button_); + ESP_LOGCONFIG(TAG, "Binary Sensors:"); + LOG_BINARY_SENSOR(" ", "Target", this->target_binary_sensor_); + LOG_BINARY_SENSOR(" ", "MovingTarget", this->moving_target_binary_sensor_); + LOG_BINARY_SENSOR(" ", "StillTarget", this->still_target_binary_sensor_); + LOG_BINARY_SENSOR(" ", "OutPinPresenceStatus", this->out_pin_presence_status_binary_sensor_); #endif #ifdef USE_SENSOR - LOG_SENSOR(" ", "LightSensor", this->light_sensor_); - LOG_SENSOR(" ", "MovingTargetDistanceSensor", this->moving_target_distance_sensor_); - LOG_SENSOR(" ", "StillTargetDistanceSensor", this->still_target_distance_sensor_); - LOG_SENSOR(" ", "MovingTargetEnergySensor", this->moving_target_energy_sensor_); - LOG_SENSOR(" ", "StillTargetEnergySensor", this->still_target_energy_sensor_); - LOG_SENSOR(" ", "DetectionDistanceSensor", this->detection_distance_sensor_); - for (sensor::Sensor *s : this->gate_still_sensors_) { - LOG_SENSOR(" ", "NthGateStillSesnsor", s); - } + ESP_LOGCONFIG(TAG, "Sensors:"); + LOG_SENSOR(" ", "Light", this->light_sensor_); + LOG_SENSOR(" ", "DetectionDistance", this->detection_distance_sensor_); + LOG_SENSOR(" ", "MovingTargetDistance", this->moving_target_distance_sensor_); + LOG_SENSOR(" ", "MovingTargetEnergy", this->moving_target_energy_sensor_); + LOG_SENSOR(" ", "StillTargetDistance", this->still_target_distance_sensor_); + LOG_SENSOR(" ", "StillTargetEnergy", this->still_target_energy_sensor_); for (sensor::Sensor *s : this->gate_move_sensors_) { - LOG_SENSOR(" ", "NthGateMoveSesnsor", s); + LOG_SENSOR(" ", "GateMove", s); + } + for (sensor::Sensor *s : this->gate_still_sensors_) { + LOG_SENSOR(" ", "GateStill", s); } #endif #ifdef USE_TEXT_SENSOR - LOG_TEXT_SENSOR(" ", "VersionTextSensor", this->version_text_sensor_); - LOG_TEXT_SENSOR(" ", "MacTextSensor", this->mac_text_sensor_); -#endif -#ifdef USE_SELECT - LOG_SELECT(" ", "LightFunctionSelect", this->light_function_select_); - LOG_SELECT(" ", "OutPinLevelSelect", this->out_pin_level_select_); - LOG_SELECT(" ", "DistanceResolutionSelect", this->distance_resolution_select_); - LOG_SELECT(" ", "BaudRateSelect", this->baud_rate_select_); + ESP_LOGCONFIG(TAG, "Text Sensors:"); + LOG_TEXT_SENSOR(" ", "Mac", this->mac_text_sensor_); + LOG_TEXT_SENSOR(" ", "Version", this->version_text_sensor_); #endif #ifdef USE_NUMBER - LOG_NUMBER(" ", "LightThresholdNumber", this->light_threshold_number_); - LOG_NUMBER(" ", "MaxStillDistanceGateNumber", this->max_still_distance_gate_number_); - LOG_NUMBER(" ", "MaxMoveDistanceGateNumber", this->max_move_distance_gate_number_); - LOG_NUMBER(" ", "TimeoutNumber", this->timeout_number_); - for (number::Number *n : this->gate_still_threshold_numbers_) { - LOG_NUMBER(" ", "Still Thresholds Number", n); - } + ESP_LOGCONFIG(TAG, "Numbers:"); + LOG_NUMBER(" ", "LightThreshold", this->light_threshold_number_); + LOG_NUMBER(" ", "MaxMoveDistanceGate", this->max_move_distance_gate_number_); + LOG_NUMBER(" ", "MaxStillDistanceGate", this->max_still_distance_gate_number_); + LOG_NUMBER(" ", "Timeout", this->timeout_number_); for (number::Number *n : this->gate_move_threshold_numbers_) { - LOG_NUMBER(" ", "Move Thresholds Number", n); + LOG_NUMBER(" ", "MoveThreshold", n); + } + for (number::Number *n : this->gate_still_threshold_numbers_) { + LOG_NUMBER(" ", "StillThreshold", n); } #endif - this->read_all_info(); - ESP_LOGCONFIG(TAG, - " Throttle: %ums\n" - " MAC address: %s\n" - " Firmware version: %s", - this->throttle_, this->mac_ == NO_MAC ? UNKNOWN_MAC : this->mac_.c_str(), this->version_.c_str()); +#ifdef USE_SELECT + ESP_LOGCONFIG(TAG, "Selects:"); + LOG_SELECT(" ", "BaudRate", this->baud_rate_select_); + LOG_SELECT(" ", "DistanceResolution", this->distance_resolution_select_); + LOG_SELECT(" ", "LightFunction", this->light_function_select_); + LOG_SELECT(" ", "OutPinLevel", this->out_pin_level_select_); +#endif +#ifdef USE_SWITCH + ESP_LOGCONFIG(TAG, "Switches:"); + LOG_SWITCH(" ", "Bluetooth", this->bluetooth_switch_); + LOG_SWITCH(" ", "EngineeringMode", this->engineering_mode_switch_); +#endif +#ifdef USE_BUTTON + ESP_LOGCONFIG(TAG, "Buttons:"); + LOG_BUTTON(" ", "FactoryReset", this->factory_reset_button_); + LOG_BUTTON(" ", "Query", this->query_button_); + LOG_BUTTON(" ", "Restart", this->restart_button_); +#endif } void LD2410Component::setup() { @@ -246,12 +268,12 @@ void LD2410Component::read_all_info() { this->get_version_(); this->get_mac_(); this->get_distance_resolution_(); - this->get_light_control_(); + this->query_light_control_(); this->query_parameters_(); this->set_config_mode_(false); #ifdef USE_SELECT const auto baud_rate = std::to_string(this->parent_->get_baud_rate()); - if (this->baud_rate_select_ != nullptr && this->baud_rate_select_->state != baud_rate) { + if (this->baud_rate_select_ != nullptr) { this->baud_rate_select_->publish_state(baud_rate); } #endif @@ -264,66 +286,59 @@ void LD2410Component::restart_and_read_all_info() { } void LD2410Component::loop() { - const int max_line_length = 80; - static uint8_t buffer[max_line_length]; - - while (available()) { - this->readline_(read(), buffer, max_line_length); + while (this->available()) { + this->readline_(this->read()); } } -void LD2410Component::send_command_(uint8_t command, const uint8_t *command_value, int command_value_len) { +void LD2410Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) { ESP_LOGV(TAG, "Sending COMMAND %02X", command); - // frame start bytes - this->write_array(CMD_FRAME_HEADER, 4); + // frame header bytes + this->write_array(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER)); // length bytes - int len = 2; - if (command_value != nullptr) + uint8_t len = 2; + if (command_value != nullptr) { len += command_value_len; - this->write_byte(lowbyte(len)); - this->write_byte(highbyte(len)); - - // command - this->write_byte(lowbyte(command)); - this->write_byte(highbyte(command)); + } + uint8_t len_cmd[] = {lowbyte(len), highbyte(len), command, 0x00}; + this->write_array(len_cmd, sizeof(len_cmd)); // command value bytes if (command_value != nullptr) { - for (int i = 0; i < command_value_len; i++) { + for (uint8_t i = 0; i < command_value_len; i++) { this->write_byte(command_value[i]); } } - // frame end bytes - this->write_array(CMD_FRAME_END, 4); + // frame footer bytes + this->write_array(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER)); // FIXME to remove delay(50); // NOLINT } -void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) { - if (len < 12) - return; // 4 frame start bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame end bytes - if (buffer[0] != 0xF4 || buffer[1] != 0xF3 || buffer[2] != 0xF2 || buffer[3] != 0xF1) // check 4 frame start bytes +void LD2410Component::handle_periodic_data_() { + // Reduce data update rate to reduce home assistant database growth + // Check this first to prevent unnecessary processing done in later checks/parsing + if (App.get_loop_component_start_time() - this->last_periodic_millis_ < this->throttle_) { return; - if (buffer[7] != HEAD || buffer[len - 6] != END || buffer[len - 5] != CHECK) // Check constant values - return; // data head=0xAA, data end=0x55, crc=0x00 - - /* - Reduce data update rate to prevent home assistant database size grow fast - */ - int32_t current_millis = App.get_loop_component_start_time(); - if (current_millis - last_periodic_millis_ < this->throttle_) + } + // 4 frame header bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame footer bytes + // data header=0xAA, data footer=0x55, crc=0x00 + if (this->buffer_pos_ < 12 || !ld2410::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) || + this->buffer_data_[7] != HEADER || this->buffer_data_[this->buffer_pos_ - 6] != FOOTER || + this->buffer_data_[this->buffer_pos_ - 5] != CHECK) { return; - last_periodic_millis_ = current_millis; + } + // Save the timestamp after validating the frame so, if invalid, we'll take the next frame immediately + this->last_periodic_millis_ = App.get_loop_component_start_time(); /* Data Type: 7th 0x01: Engineering mode 0x02: Normal mode */ - bool engineering_mode = buffer[DATA_TYPES] == 0x01; + bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01; #ifdef USE_SWITCH - if (this->engineering_mode_switch_ != nullptr && - current_millis - last_engineering_mode_change_millis_ > this->throttle_) { + if (this->engineering_mode_switch_ != nullptr) { this->engineering_mode_switch_->publish_state(engineering_mode); } #endif @@ -335,7 +350,7 @@ void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) { 0x02 = Still targets 0x03 = Moving+Still targets */ - char target_state = buffer[TARGET_STATES]; + char target_state = this->buffer_data_[TARGET_STATES]; if (this->target_binary_sensor_ != nullptr) { this->target_binary_sensor_->publish_state(target_state != 0x00); } @@ -355,27 +370,30 @@ void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) { */ #ifdef USE_SENSOR if (this->moving_target_distance_sensor_ != nullptr) { - int new_moving_target_distance = ld2410::two_byte_to_int(buffer[MOVING_TARGET_LOW], buffer[MOVING_TARGET_HIGH]); + int new_moving_target_distance = + ld2410::two_byte_to_int(this->buffer_data_[MOVING_TARGET_LOW], this->buffer_data_[MOVING_TARGET_HIGH]); if (this->moving_target_distance_sensor_->get_state() != new_moving_target_distance) this->moving_target_distance_sensor_->publish_state(new_moving_target_distance); } if (this->moving_target_energy_sensor_ != nullptr) { - int new_moving_target_energy = buffer[MOVING_ENERGY]; + int new_moving_target_energy = this->buffer_data_[MOVING_ENERGY]; if (this->moving_target_energy_sensor_->get_state() != new_moving_target_energy) this->moving_target_energy_sensor_->publish_state(new_moving_target_energy); } if (this->still_target_distance_sensor_ != nullptr) { - int new_still_target_distance = ld2410::two_byte_to_int(buffer[STILL_TARGET_LOW], buffer[STILL_TARGET_HIGH]); + int new_still_target_distance = + ld2410::two_byte_to_int(this->buffer_data_[STILL_TARGET_LOW], this->buffer_data_[STILL_TARGET_HIGH]); if (this->still_target_distance_sensor_->get_state() != new_still_target_distance) this->still_target_distance_sensor_->publish_state(new_still_target_distance); } if (this->still_target_energy_sensor_ != nullptr) { - int new_still_target_energy = buffer[STILL_ENERGY]; + int new_still_target_energy = this->buffer_data_[STILL_ENERGY]; if (this->still_target_energy_sensor_->get_state() != new_still_target_energy) this->still_target_energy_sensor_->publish_state(new_still_target_energy); } if (this->detection_distance_sensor_ != nullptr) { - int new_detect_distance = ld2410::two_byte_to_int(buffer[DETECT_DISTANCE_LOW], buffer[DETECT_DISTANCE_HIGH]); + int new_detect_distance = + ld2410::two_byte_to_int(this->buffer_data_[DETECT_DISTANCE_LOW], this->buffer_data_[DETECT_DISTANCE_HIGH]); if (this->detection_distance_sensor_->get_state() != new_detect_distance) this->detection_distance_sensor_->publish_state(new_detect_distance); } @@ -388,7 +406,7 @@ void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) { for (std::vector::size_type i = 0; i != this->gate_move_sensors_.size(); i++) { sensor::Sensor *s = this->gate_move_sensors_[i]; if (s != nullptr) { - s->publish_state(buffer[MOVING_SENSOR_START + i]); + s->publish_state(this->buffer_data_[MOVING_SENSOR_START + i]); } } /* @@ -397,16 +415,17 @@ void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) { for (std::vector::size_type i = 0; i != this->gate_still_sensors_.size(); i++) { sensor::Sensor *s = this->gate_still_sensors_[i]; if (s != nullptr) { - s->publish_state(buffer[STILL_SENSOR_START + i]); + s->publish_state(this->buffer_data_[STILL_SENSOR_START + i]); } } /* Light sensor: 38th bytes */ if (this->light_sensor_ != nullptr) { - int new_light_sensor = buffer[LIGHT_SENSOR]; - if (this->light_sensor_->get_state() != new_light_sensor) + int new_light_sensor = this->buffer_data_[LIGHT_SENSOR]; + if (this->light_sensor_->get_state() != new_light_sensor) { this->light_sensor_->publish_state(new_light_sensor); + } } } else { for (auto *s : this->gate_move_sensors_) { @@ -427,7 +446,7 @@ void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) { #ifdef USE_BINARY_SENSOR if (engineering_mode) { if (this->out_pin_presence_status_binary_sensor_ != nullptr) { - this->out_pin_presence_status_binary_sensor_->publish_state(buffer[OUT_PIN_SENSOR] == 0x01); + this->out_pin_presence_status_binary_sensor_->publish_state(this->buffer_data_[OUT_PIN_SENSOR] == 0x01); } } else { if (this->out_pin_presence_status_binary_sensor_ != nullptr) { @@ -439,127 +458,149 @@ void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) { #ifdef USE_NUMBER std::function set_number_value(number::Number *n, float value) { - float normalized_value = value * 1.0; - if (n != nullptr && (!n->has_state() || n->state != normalized_value)) { - n->state = normalized_value; - return [n, normalized_value]() { n->publish_state(normalized_value); }; + if (n != nullptr && (!n->has_state() || n->state != value)) { + n->state = value; + return [n, value]() { n->publish_state(value); }; } return []() {}; } #endif -bool LD2410Component::handle_ack_data_(uint8_t *buffer, int len) { - ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", buffer[COMMAND]); - if (len < 10) { +bool LD2410Component::handle_ack_data_() { + ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]); + if (this->buffer_pos_ < 10) { ESP_LOGE(TAG, "Invalid length"); return true; } - if (buffer[0] != 0xFD || buffer[1] != 0xFC || buffer[2] != 0xFB || buffer[3] != 0xFA) { // check 4 frame start bytes - ESP_LOGE(TAG, "Invalid header"); + if (!ld2410::validate_header_footer(CMD_FRAME_HEADER, this->buffer_data_)) { + ESP_LOGW(TAG, "Invalid header: %s", format_hex_pretty(this->buffer_data_, HEADER_FOOTER_SIZE).c_str()); return true; } - if (buffer[COMMAND_STATUS] != 0x01) { + if (this->buffer_data_[COMMAND_STATUS] != 0x01) { ESP_LOGE(TAG, "Invalid status"); return true; } - if (ld2410::two_byte_to_int(buffer[8], buffer[9]) != 0x00) { - ESP_LOGE(TAG, "Invalid command: %u, %u", buffer[8], buffer[9]); + if (ld2410::two_byte_to_int(this->buffer_data_[8], this->buffer_data_[9]) != 0x00) { + ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]); return true; } - switch (buffer[COMMAND]) { - case lowbyte(CMD_ENABLE_CONF): + switch (this->buffer_data_[COMMAND]) { + case CMD_ENABLE_CONF: ESP_LOGV(TAG, "Enable conf"); break; - case lowbyte(CMD_DISABLE_CONF): + + case CMD_DISABLE_CONF: ESP_LOGV(TAG, "Disabled conf"); break; - case lowbyte(CMD_SET_BAUD_RATE): + + case CMD_SET_BAUD_RATE: ESP_LOGV(TAG, "Baud rate change"); #ifdef USE_SELECT if (this->baud_rate_select_ != nullptr) { - ESP_LOGE(TAG, "Configure baud rate to %s and reinstall", this->baud_rate_select_->state.c_str()); + ESP_LOGE(TAG, "Change baud rate to %s and reinstall", this->baud_rate_select_->state.c_str()); } #endif break; - case lowbyte(CMD_VERSION): - this->version_ = str_sprintf(VERSION_FMT, buffer[13], buffer[12], buffer[17], buffer[16], buffer[15], buffer[14]); - ESP_LOGV(TAG, "Firmware version: %s", this->version_.c_str()); + + case CMD_QUERY_VERSION: { + std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_)); + std::string version = str_sprintf(VERSION_FMT, this->version_[1], this->version_[0], this->version_[5], + this->version_[4], this->version_[3], this->version_[2]); + ESP_LOGV(TAG, "Firmware version: %s", version.c_str()); #ifdef USE_TEXT_SENSOR if (this->version_text_sensor_ != nullptr) { - this->version_text_sensor_->publish_state(this->version_); + this->version_text_sensor_->publish_state(version); } #endif break; - case lowbyte(CMD_QUERY_DISTANCE_RESOLUTION): { - std::string distance_resolution = - find_str(DISTANCE_RESOLUTIONS_BY_UINT, ld2410::two_byte_to_int(buffer[10], buffer[11])); - ESP_LOGV(TAG, "Distance resolution: %s", distance_resolution.c_str()); + } + + case CMD_QUERY_DISTANCE_RESOLUTION: { + const auto *distance_resolution = find_str(DISTANCE_RESOLUTIONS_BY_UINT, this->buffer_data_[10]); + ESP_LOGV(TAG, "Distance resolution: %s", distance_resolution); #ifdef USE_SELECT - if (this->distance_resolution_select_ != nullptr && - this->distance_resolution_select_->state != distance_resolution) { + if (this->distance_resolution_select_ != nullptr) { this->distance_resolution_select_->publish_state(distance_resolution); } #endif - } break; - case lowbyte(CMD_QUERY_LIGHT_CONTROL): { - this->light_function_ = find_str(LIGHT_FUNCTIONS_BY_UINT, buffer[10]); - this->light_threshold_ = buffer[11] * 1.0; - this->out_pin_level_ = find_str(OUT_PIN_LEVELS_BY_UINT, buffer[12]); - ESP_LOGV(TAG, "Light function: %s", const_cast(this->light_function_.c_str())); - ESP_LOGV(TAG, "Light threshold: %f", this->light_threshold_); - ESP_LOGV(TAG, "Out pin level: %s", const_cast(this->out_pin_level_.c_str())); + break; + } + + case CMD_QUERY_LIGHT_CONTROL: { + this->light_function_ = this->buffer_data_[10]; + this->light_threshold_ = this->buffer_data_[11]; + this->out_pin_level_ = this->buffer_data_[12]; + const auto *light_function_str = find_str(LIGHT_FUNCTIONS_BY_UINT, this->light_function_); + const auto *out_pin_level_str = find_str(OUT_PIN_LEVELS_BY_UINT, this->out_pin_level_); + ESP_LOGV(TAG, + "Light function is: %s\n" + "Light threshold is: %u\n" + "Out pin level: %s", + light_function_str, this->light_threshold_, out_pin_level_str); #ifdef USE_SELECT - if (this->light_function_select_ != nullptr && this->light_function_select_->state != this->light_function_) { - this->light_function_select_->publish_state(this->light_function_); + if (this->light_function_select_ != nullptr) { + this->light_function_select_->publish_state(light_function_str); } - if (this->out_pin_level_select_ != nullptr && this->out_pin_level_select_->state != this->out_pin_level_) { - this->out_pin_level_select_->publish_state(this->out_pin_level_); + if (this->out_pin_level_select_ != nullptr) { + this->out_pin_level_select_->publish_state(out_pin_level_str); } #endif #ifdef USE_NUMBER - if (this->light_threshold_number_ != nullptr && - (!this->light_threshold_number_->has_state() || - this->light_threshold_number_->state != this->light_threshold_)) { - this->light_threshold_number_->publish_state(this->light_threshold_); + if (this->light_threshold_number_ != nullptr) { + this->light_threshold_number_->publish_state(static_cast(this->light_threshold_)); } #endif - } break; - case lowbyte(CMD_MAC): - if (len < 20) { + break; + } + case CMD_QUERY_MAC_ADDRESS: { + if (this->buffer_pos_ < 20) { return false; } - this->mac_ = format_mac_address_pretty(&buffer[10]); - ESP_LOGV(TAG, "MAC address: %s", this->mac_.c_str()); + + this->bluetooth_on_ = std::memcmp(&this->buffer_data_[10], NO_MAC, sizeof(NO_MAC)) != 0; + if (this->bluetooth_on_) { + std::memcpy(this->mac_address_, &this->buffer_data_[10], sizeof(this->mac_address_)); + } + + std::string mac_str = + mac_address_is_valid(this->mac_address_) ? format_mac_address_pretty(this->mac_address_) : UNKNOWN_MAC; + ESP_LOGV(TAG, "MAC address: %s", mac_str.c_str()); #ifdef USE_TEXT_SENSOR if (this->mac_text_sensor_ != nullptr) { - this->mac_text_sensor_->publish_state(this->mac_ == NO_MAC ? UNKNOWN_MAC : this->mac_); + this->mac_text_sensor_->publish_state(mac_str); } #endif #ifdef USE_SWITCH if (this->bluetooth_switch_ != nullptr) { - this->bluetooth_switch_->publish_state(this->mac_ != NO_MAC); + this->bluetooth_switch_->publish_state(this->bluetooth_on_); } #endif break; - case lowbyte(CMD_GATE_SENS): + } + + case CMD_GATE_SENS: ESP_LOGV(TAG, "Sensitivity"); break; - case lowbyte(CMD_BLUETOOTH): + + case CMD_BLUETOOTH: ESP_LOGV(TAG, "Bluetooth"); break; - case lowbyte(CMD_SET_DISTANCE_RESOLUTION): + + case CMD_SET_DISTANCE_RESOLUTION: ESP_LOGV(TAG, "Set distance resolution"); break; - case lowbyte(CMD_SET_LIGHT_CONTROL): + + case CMD_SET_LIGHT_CONTROL: ESP_LOGV(TAG, "Set light control"); break; - case lowbyte(CMD_BT_PASSWORD): + + case CMD_BT_PASSWORD: ESP_LOGV(TAG, "Set bluetooth password"); break; - case lowbyte(CMD_QUERY): // Query parameters response - { - if (buffer[10] != 0xAA) + + case CMD_QUERY: { // Query parameters response + if (this->buffer_data_[10] != 0xAA) return true; // value head=0xAA #ifdef USE_NUMBER /* @@ -567,29 +608,31 @@ bool LD2410Component::handle_ack_data_(uint8_t *buffer, int len) { Still distance range: 14th byte */ std::vector> updates; - updates.push_back(set_number_value(this->max_move_distance_gate_number_, buffer[12])); - updates.push_back(set_number_value(this->max_still_distance_gate_number_, buffer[13])); + updates.push_back(set_number_value(this->max_move_distance_gate_number_, this->buffer_data_[12])); + updates.push_back(set_number_value(this->max_still_distance_gate_number_, this->buffer_data_[13])); /* Moving Sensitivities: 15~23th bytes */ for (std::vector::size_type i = 0; i != this->gate_move_threshold_numbers_.size(); i++) { - updates.push_back(set_number_value(this->gate_move_threshold_numbers_[i], buffer[14 + i])); + updates.push_back(set_number_value(this->gate_move_threshold_numbers_[i], this->buffer_data_[14 + i])); } /* Still Sensitivities: 24~32th bytes */ for (std::vector::size_type i = 0; i != this->gate_still_threshold_numbers_.size(); i++) { - updates.push_back(set_number_value(this->gate_still_threshold_numbers_[i], buffer[23 + i])); + updates.push_back(set_number_value(this->gate_still_threshold_numbers_[i], this->buffer_data_[23 + i])); } /* None Duration: 33~34th bytes */ - updates.push_back(set_number_value(this->timeout_number_, ld2410::two_byte_to_int(buffer[32], buffer[33]))); + updates.push_back(set_number_value(this->timeout_number_, + ld2410::two_byte_to_int(this->buffer_data_[32], this->buffer_data_[33]))); for (auto &update : updates) { update(); } #endif - } break; + break; + } default: break; } @@ -597,59 +640,66 @@ bool LD2410Component::handle_ack_data_(uint8_t *buffer, int len) { return true; } -void LD2410Component::readline_(int readch, uint8_t *buffer, int len) { - static int pos = 0; +void LD2410Component::readline_(int readch) { + if (readch < 0) { + return; // No data available + } - if (readch >= 0) { - if (pos < len - 1) { - buffer[pos++] = readch; - buffer[pos] = 0; + if (this->buffer_pos_ < MAX_LINE_LENGTH - 1) { + this->buffer_data_[this->buffer_pos_++] = readch; + this->buffer_data_[this->buffer_pos_] = 0; + } else { + // We should never get here, but just in case... + ESP_LOGW(TAG, "Max command length exceeded; ignoring"); + this->buffer_pos_ = 0; + } + if (this->buffer_pos_ < 4) { + return; // Not enough data to process yet + } + if (this->buffer_data_[this->buffer_pos_ - 4] == DATA_FRAME_FOOTER[0] && + this->buffer_data_[this->buffer_pos_ - 3] == DATA_FRAME_FOOTER[1] && + this->buffer_data_[this->buffer_pos_ - 2] == DATA_FRAME_FOOTER[2] && + this->buffer_data_[this->buffer_pos_ - 1] == DATA_FRAME_FOOTER[3]) { + ESP_LOGV(TAG, "Handling Periodic Data: %s", format_hex_pretty(this->buffer_data_, this->buffer_pos_).c_str()); + this->handle_periodic_data_(); + this->buffer_pos_ = 0; // Reset position index for next message + } else if (this->buffer_data_[this->buffer_pos_ - 4] == CMD_FRAME_FOOTER[0] && + this->buffer_data_[this->buffer_pos_ - 3] == CMD_FRAME_FOOTER[1] && + this->buffer_data_[this->buffer_pos_ - 2] == CMD_FRAME_FOOTER[2] && + this->buffer_data_[this->buffer_pos_ - 1] == CMD_FRAME_FOOTER[3]) { + ESP_LOGV(TAG, "Handling Ack Data: %s", format_hex_pretty(this->buffer_data_, this->buffer_pos_).c_str()); + if (this->handle_ack_data_()) { + this->buffer_pos_ = 0; // Reset position index for next message } else { - pos = 0; - } - if (pos >= 4) { - if (buffer[pos - 4] == 0xF8 && buffer[pos - 3] == 0xF7 && buffer[pos - 2] == 0xF6 && buffer[pos - 1] == 0xF5) { - ESP_LOGV(TAG, "Will handle Periodic Data"); - this->handle_periodic_data_(buffer, pos); - pos = 0; // Reset position index ready for next time - } else if (buffer[pos - 4] == 0x04 && buffer[pos - 3] == 0x03 && buffer[pos - 2] == 0x02 && - buffer[pos - 1] == 0x01) { - ESP_LOGV(TAG, "Will handle ACK Data"); - if (this->handle_ack_data_(buffer, pos)) { - pos = 0; // Reset position index ready for next time - } else { - ESP_LOGV(TAG, "ACK Data incomplete"); - } - } + ESP_LOGV(TAG, "Ack Data incomplete"); } } } void LD2410Component::set_config_mode_(bool enable) { - uint8_t cmd = enable ? CMD_ENABLE_CONF : CMD_DISABLE_CONF; - uint8_t cmd_value[2] = {0x01, 0x00}; - this->send_command_(cmd, enable ? cmd_value : nullptr, 2); + const uint8_t cmd = enable ? CMD_ENABLE_CONF : CMD_DISABLE_CONF; + const uint8_t cmd_value[2] = {0x01, 0x00}; + this->send_command_(cmd, enable ? cmd_value : nullptr, sizeof(cmd_value)); } void LD2410Component::set_bluetooth(bool enable) { this->set_config_mode_(true); - uint8_t enable_cmd_value[2] = {0x01, 0x00}; - uint8_t disable_cmd_value[2] = {0x00, 0x00}; - this->send_command_(CMD_BLUETOOTH, enable ? enable_cmd_value : disable_cmd_value, 2); + const uint8_t cmd_value[2] = {enable ? (uint8_t) 0x01 : (uint8_t) 0x00, 0x00}; + this->send_command_(CMD_BLUETOOTH, cmd_value, sizeof(cmd_value)); this->set_timeout(200, [this]() { this->restart_and_read_all_info(); }); } void LD2410Component::set_distance_resolution(const std::string &state) { this->set_config_mode_(true); - uint8_t cmd_value[2] = {find_uint8(DISTANCE_RESOLUTIONS_BY_STR, state), 0x00}; - this->send_command_(CMD_SET_DISTANCE_RESOLUTION, cmd_value, 2); + const uint8_t cmd_value[2] = {find_uint8(DISTANCE_RESOLUTIONS_BY_STR, state), 0x00}; + this->send_command_(CMD_SET_DISTANCE_RESOLUTION, cmd_value, sizeof(cmd_value)); this->set_timeout(200, [this]() { this->restart_and_read_all_info(); }); } void LD2410Component::set_baud_rate(const std::string &state) { this->set_config_mode_(true); - uint8_t cmd_value[2] = {find_uint8(BAUD_RATES_BY_STR, state), 0x00}; - this->send_command_(CMD_SET_BAUD_RATE, cmd_value, 2); + const uint8_t cmd_value[2] = {find_uint8(BAUD_RATES_BY_STR, state), 0x00}; + this->send_command_(CMD_SET_BAUD_RATE, cmd_value, sizeof(cmd_value)); this->set_timeout(200, [this]() { this->restart_(); }); } @@ -661,14 +711,13 @@ void LD2410Component::set_bluetooth_password(const std::string &password) { this->set_config_mode_(true); uint8_t cmd_value[6]; std::copy(password.begin(), password.end(), std::begin(cmd_value)); - this->send_command_(CMD_BT_PASSWORD, cmd_value, 6); + this->send_command_(CMD_BT_PASSWORD, cmd_value, sizeof(cmd_value)); this->set_config_mode_(false); } void LD2410Component::set_engineering_mode(bool enable) { + const uint8_t cmd = enable ? CMD_ENABLE_ENG : CMD_DISABLE_ENG; this->set_config_mode_(true); - last_engineering_mode_change_millis_ = App.get_loop_component_start_time(); - uint8_t cmd = enable ? CMD_ENABLE_ENG : CMD_DISABLE_ENG; this->send_command_(cmd, nullptr, 0); this->set_config_mode_(false); } @@ -682,14 +731,17 @@ void LD2410Component::factory_reset() { void LD2410Component::restart_() { this->send_command_(CMD_RESTART, nullptr, 0); } void LD2410Component::query_parameters_() { this->send_command_(CMD_QUERY, nullptr, 0); } -void LD2410Component::get_version_() { this->send_command_(CMD_VERSION, nullptr, 0); } + +void LD2410Component::get_version_() { this->send_command_(CMD_QUERY_VERSION, nullptr, 0); } + void LD2410Component::get_mac_() { - uint8_t cmd_value[2] = {0x01, 0x00}; - this->send_command_(CMD_MAC, cmd_value, 2); + const uint8_t cmd_value[2] = {0x01, 0x00}; + this->send_command_(CMD_QUERY_MAC_ADDRESS, cmd_value, sizeof(cmd_value)); } + void LD2410Component::get_distance_resolution_() { this->send_command_(CMD_QUERY_DISTANCE_RESOLUTION, nullptr, 0); } -void LD2410Component::get_light_control_() { this->send_command_(CMD_QUERY_LIGHT_CONTROL, nullptr, 0); } +void LD2410Component::query_light_control_() { this->send_command_(CMD_QUERY_LIGHT_CONTROL, nullptr, 0); } #ifdef USE_NUMBER void LD2410Component::set_max_distances_timeout() { @@ -719,7 +771,7 @@ void LD2410Component::set_max_distances_timeout() { 0x00, 0x00}; this->set_config_mode_(true); - this->send_command_(CMD_MAXDIST_DURATION, value, 18); + this->send_command_(CMD_MAXDIST_DURATION, value, sizeof(value)); delay(50); // NOLINT this->query_parameters_(); this->set_timeout(200, [this]() { this->restart_and_read_all_info(); }); @@ -749,17 +801,17 @@ void LD2410Component::set_gate_threshold(uint8_t gate) { uint8_t value[18] = {0x00, 0x00, lowbyte(gate), highbyte(gate), 0x00, 0x00, 0x01, 0x00, lowbyte(motion), highbyte(motion), 0x00, 0x00, 0x02, 0x00, lowbyte(still), highbyte(still), 0x00, 0x00}; - this->send_command_(CMD_GATE_SENS, value, 18); + this->send_command_(CMD_GATE_SENS, value, sizeof(value)); delay(50); // NOLINT this->query_parameters_(); this->set_config_mode_(false); } -void LD2410Component::set_gate_still_threshold_number(int gate, number::Number *n) { +void LD2410Component::set_gate_still_threshold_number(uint8_t gate, number::Number *n) { this->gate_still_threshold_numbers_[gate] = n; } -void LD2410Component::set_gate_move_threshold_number(int gate, number::Number *n) { +void LD2410Component::set_gate_move_threshold_number(uint8_t gate, number::Number *n) { this->gate_move_threshold_numbers_[gate] = n; } #endif @@ -767,35 +819,29 @@ void LD2410Component::set_gate_move_threshold_number(int gate, number::Number *n void LD2410Component::set_light_out_control() { #ifdef USE_NUMBER if (this->light_threshold_number_ != nullptr && this->light_threshold_number_->has_state()) { - this->light_threshold_ = this->light_threshold_number_->state; + this->light_threshold_ = static_cast(this->light_threshold_number_->state); } #endif #ifdef USE_SELECT if (this->light_function_select_ != nullptr && this->light_function_select_->has_state()) { - this->light_function_ = this->light_function_select_->state; + this->light_function_ = find_uint8(LIGHT_FUNCTIONS_BY_STR, this->light_function_select_->state); } if (this->out_pin_level_select_ != nullptr && this->out_pin_level_select_->has_state()) { - this->out_pin_level_ = this->out_pin_level_select_->state; + this->out_pin_level_ = find_uint8(OUT_PIN_LEVELS_BY_STR, this->out_pin_level_select_->state); } #endif - if (this->light_function_.empty() || this->out_pin_level_.empty() || this->light_threshold_ < 0) { - return; - } this->set_config_mode_(true); - uint8_t light_function = find_uint8(LIGHT_FUNCTIONS_BY_STR, this->light_function_); - uint8_t light_threshold = static_cast(this->light_threshold_); - uint8_t out_pin_level = find_uint8(OUT_PIN_LEVELS_BY_STR, this->out_pin_level_); - uint8_t value[4] = {light_function, light_threshold, out_pin_level, 0x00}; - this->send_command_(CMD_SET_LIGHT_CONTROL, value, 4); + uint8_t value[4] = {this->light_function_, this->light_threshold_, this->out_pin_level_, 0x00}; + this->send_command_(CMD_SET_LIGHT_CONTROL, value, sizeof(value)); delay(50); // NOLINT - this->get_light_control_(); + this->query_light_control_(); this->set_timeout(200, [this]() { this->restart_and_read_all_info(); }); this->set_config_mode_(false); } #ifdef USE_SENSOR -void LD2410Component::set_gate_move_sensor(int gate, sensor::Sensor *s) { this->gate_move_sensors_[gate] = s; } -void LD2410Component::set_gate_still_sensor(int gate, sensor::Sensor *s) { this->gate_still_sensors_[gate] = s; } +void LD2410Component::set_gate_move_sensor(uint8_t gate, sensor::Sensor *s) { this->gate_move_sensors_[gate] = s; } +void LD2410Component::set_gate_still_sensor(uint8_t gate, sensor::Sensor *s) { this->gate_still_sensors_[gate] = s; } #endif } // namespace ld2410 diff --git a/esphome/components/ld2410/ld2410.h b/esphome/components/ld2410/ld2410.h index 1b5f6e3057..8bd1dbcb5a 100644 --- a/esphome/components/ld2410/ld2410.h +++ b/esphome/components/ld2410/ld2410.h @@ -29,45 +29,48 @@ namespace esphome { namespace ld2410 { +static const uint8_t MAX_LINE_LENGTH = 46; // Max characters for serial buffer +static const uint8_t TOTAL_GATES = 9; // Total number of gates supported by the LD2410 + class LD2410Component : public Component, public uart::UARTDevice { -#ifdef USE_SENSOR - SUB_SENSOR(moving_target_distance) - SUB_SENSOR(still_target_distance) - SUB_SENSOR(moving_target_energy) - SUB_SENSOR(still_target_energy) - SUB_SENSOR(light) - SUB_SENSOR(detection_distance) -#endif #ifdef USE_BINARY_SENSOR - SUB_BINARY_SENSOR(target) + SUB_BINARY_SENSOR(out_pin_presence_status) SUB_BINARY_SENSOR(moving_target) SUB_BINARY_SENSOR(still_target) - SUB_BINARY_SENSOR(out_pin_presence_status) + SUB_BINARY_SENSOR(target) +#endif +#ifdef USE_SENSOR + SUB_SENSOR(light) + SUB_SENSOR(detection_distance) + SUB_SENSOR(moving_target_distance) + SUB_SENSOR(moving_target_energy) + SUB_SENSOR(still_target_distance) + SUB_SENSOR(still_target_energy) #endif #ifdef USE_TEXT_SENSOR SUB_TEXT_SENSOR(version) SUB_TEXT_SENSOR(mac) #endif +#ifdef USE_NUMBER + SUB_NUMBER(light_threshold) + SUB_NUMBER(max_move_distance_gate) + SUB_NUMBER(max_still_distance_gate) + SUB_NUMBER(timeout) +#endif #ifdef USE_SELECT - SUB_SELECT(distance_resolution) SUB_SELECT(baud_rate) + SUB_SELECT(distance_resolution) SUB_SELECT(light_function) SUB_SELECT(out_pin_level) #endif #ifdef USE_SWITCH - SUB_SWITCH(engineering_mode) SUB_SWITCH(bluetooth) + SUB_SWITCH(engineering_mode) #endif #ifdef USE_BUTTON - SUB_BUTTON(reset) - SUB_BUTTON(restart) + SUB_BUTTON(factory_reset) SUB_BUTTON(query) -#endif -#ifdef USE_NUMBER - SUB_NUMBER(max_still_distance_gate) - SUB_NUMBER(max_move_distance_gate) - SUB_NUMBER(timeout) - SUB_NUMBER(light_threshold) + SUB_BUTTON(restart) #endif public: @@ -76,14 +79,14 @@ class LD2410Component : public Component, public uart::UARTDevice { void loop() override; void set_light_out_control(); #ifdef USE_NUMBER - void set_gate_still_threshold_number(int gate, number::Number *n); - void set_gate_move_threshold_number(int gate, number::Number *n); + void set_gate_still_threshold_number(uint8_t gate, number::Number *n); + void set_gate_move_threshold_number(uint8_t gate, number::Number *n); void set_max_distances_timeout(); void set_gate_threshold(uint8_t gate); #endif #ifdef USE_SENSOR - void set_gate_move_sensor(int gate, sensor::Sensor *s); - void set_gate_still_sensor(int gate, sensor::Sensor *s); + void set_gate_move_sensor(uint8_t gate, sensor::Sensor *s); + void set_gate_still_sensor(uint8_t gate, sensor::Sensor *s); #endif void set_throttle(uint16_t value) { this->throttle_ = value; }; void set_bluetooth_password(const std::string &password); @@ -96,33 +99,35 @@ class LD2410Component : public Component, public uart::UARTDevice { void factory_reset(); protected: - void send_command_(uint8_t command_str, const uint8_t *command_value, int command_value_len); + void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len); void set_config_mode_(bool enable); - void handle_periodic_data_(uint8_t *buffer, int len); - bool handle_ack_data_(uint8_t *buffer, int len); - void readline_(int readch, uint8_t *buffer, int len); + void handle_periodic_data_(); + bool handle_ack_data_(); + void readline_(int readch); void query_parameters_(); void get_version_(); void get_mac_(); void get_distance_resolution_(); - void get_light_control_(); + void query_light_control_(); void restart_(); - int32_t last_periodic_millis_ = 0; - int32_t last_engineering_mode_change_millis_ = 0; - uint16_t throttle_; - float light_threshold_ = -1; - std::string version_; - std::string mac_; - std::string out_pin_level_; - std::string light_function_; + uint32_t last_periodic_millis_ = 0; + uint16_t throttle_ = 0; + uint8_t light_function_ = 0; + uint8_t light_threshold_ = 0; + uint8_t out_pin_level_ = 0; + uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer + uint8_t buffer_data_[MAX_LINE_LENGTH]; + uint8_t mac_address_[6] = {0, 0, 0, 0, 0, 0}; + uint8_t version_[6] = {0, 0, 0, 0, 0, 0}; + bool bluetooth_on_{false}; #ifdef USE_NUMBER - std::vector gate_still_threshold_numbers_ = std::vector(9); - std::vector gate_move_threshold_numbers_ = std::vector(9); + std::vector gate_move_threshold_numbers_ = std::vector(TOTAL_GATES); + std::vector gate_still_threshold_numbers_ = std::vector(TOTAL_GATES); #endif #ifdef USE_SENSOR - std::vector gate_still_sensors_ = std::vector(9); - std::vector gate_move_sensors_ = std::vector(9); + std::vector gate_move_sensors_ = std::vector(TOTAL_GATES); + std::vector gate_still_sensors_ = std::vector(TOTAL_GATES); #endif }; diff --git a/esphome/components/ld2450/button/__init__.py b/esphome/components/ld2450/button/__init__.py index 39671d3a3b..429aa59389 100644 --- a/esphome/components/ld2450/button/__init__.py +++ b/esphome/components/ld2450/button/__init__.py @@ -13,13 +13,13 @@ from esphome.const import ( from .. import CONF_LD2450_ID, LD2450Component, ld2450_ns -ResetButton = ld2450_ns.class_("ResetButton", button.Button) +FactoryResetButton = ld2450_ns.class_("FactoryResetButton", button.Button) RestartButton = ld2450_ns.class_("RestartButton", button.Button) CONFIG_SCHEMA = { cv.GenerateID(CONF_LD2450_ID): cv.use_id(LD2450Component), cv.Optional(CONF_FACTORY_RESET): button.button_schema( - ResetButton, + FactoryResetButton, device_class=DEVICE_CLASS_RESTART, entity_category=ENTITY_CATEGORY_CONFIG, icon=ICON_RESTART_ALERT, @@ -38,7 +38,7 @@ async def to_code(config): if factory_reset_config := config.get(CONF_FACTORY_RESET): b = await button.new_button(factory_reset_config) await cg.register_parented(b, config[CONF_LD2450_ID]) - cg.add(ld2450_component.set_reset_button(b)) + cg.add(ld2450_component.set_factory_reset_button(b)) if restart_config := config.get(CONF_RESTART): b = await button.new_button(restart_config) await cg.register_parented(b, config[CONF_LD2450_ID]) diff --git a/esphome/components/ld2450/button/factory_reset_button.cpp b/esphome/components/ld2450/button/factory_reset_button.cpp new file mode 100644 index 0000000000..bcac7ada2f --- /dev/null +++ b/esphome/components/ld2450/button/factory_reset_button.cpp @@ -0,0 +1,9 @@ +#include "factory_reset_button.h" + +namespace esphome { +namespace ld2450 { + +void FactoryResetButton::press_action() { this->parent_->factory_reset(); } + +} // namespace ld2450 +} // namespace esphome diff --git a/esphome/components/ld2450/button/reset_button.h b/esphome/components/ld2450/button/factory_reset_button.h similarity index 65% rename from esphome/components/ld2450/button/reset_button.h rename to esphome/components/ld2450/button/factory_reset_button.h index 73804fa6d6..8e80347119 100644 --- a/esphome/components/ld2450/button/reset_button.h +++ b/esphome/components/ld2450/button/factory_reset_button.h @@ -6,9 +6,9 @@ namespace esphome { namespace ld2450 { -class ResetButton : public button::Button, public Parented { +class FactoryResetButton : public button::Button, public Parented { public: - ResetButton() = default; + FactoryResetButton() = default; protected: void press_action() override; diff --git a/esphome/components/ld2450/button/reset_button.cpp b/esphome/components/ld2450/button/reset_button.cpp deleted file mode 100644 index e96ec99cc5..0000000000 --- a/esphome/components/ld2450/button/reset_button.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "reset_button.h" - -namespace esphome { -namespace ld2450 { - -void ResetButton::press_action() { this->parent_->factory_reset(); } - -} // namespace ld2450 -} // namespace esphome diff --git a/esphome/components/ld2450/ld2450.cpp b/esphome/components/ld2450/ld2450.cpp index 0e1123db1a..8f3b3a3f21 100644 --- a/esphome/components/ld2450/ld2450.cpp +++ b/esphome/components/ld2450/ld2450.cpp @@ -1,5 +1,6 @@ #include "ld2450.h" #include +#include #ifdef USE_NUMBER #include "esphome/components/number/number.h" #endif @@ -17,11 +18,10 @@ namespace esphome { namespace ld2450 { static const char *const TAG = "ld2450"; -static const char *const NO_MAC = "08:05:04:03:02:01"; static const char *const UNKNOWN_MAC = "unknown"; static const char *const VERSION_FMT = "%u.%02X.%02X%02X%02X%02X"; -enum BaudRateStructure : uint8_t { +enum BaudRate : uint8_t { BAUD_RATE_9600 = 1, BAUD_RATE_19200 = 2, BAUD_RATE_38400 = 3, @@ -32,14 +32,13 @@ enum BaudRateStructure : uint8_t { BAUD_RATE_460800 = 8 }; -// Zone type struct -enum ZoneTypeStructure : uint8_t { +enum ZoneType : uint8_t { ZONE_DISABLED = 0, ZONE_DETECTION = 1, ZONE_FILTER = 2, }; -enum PeriodicDataStructure : uint8_t { +enum PeriodicData : uint8_t { TARGET_X = 4, TARGET_Y = 6, TARGET_SPEED = 8, @@ -47,12 +46,12 @@ enum PeriodicDataStructure : uint8_t { }; enum PeriodicDataValue : uint8_t { - HEAD = 0xAA, - END = 0x55, + HEADER = 0xAA, + FOOTER = 0x55, CHECK = 0x00, }; -enum AckDataStructure : uint8_t { +enum AckData : uint8_t { COMMAND = 6, COMMAND_STATUS = 7, }; @@ -60,11 +59,11 @@ enum AckDataStructure : uint8_t { // Memory-efficient lookup tables struct StringToUint8 { const char *str; - uint8_t value; + const uint8_t value; }; struct Uint8ToString { - uint8_t value; + const uint8_t value; const char *str; }; @@ -74,6 +73,13 @@ constexpr StringToUint8 BAUD_RATES_BY_STR[] = { {"256000", BAUD_RATE_256000}, {"460800", BAUD_RATE_460800}, }; +constexpr Uint8ToString DIRECTION_BY_UINT[] = { + {DIRECTION_APPROACHING, "Approaching"}, + {DIRECTION_MOVING_AWAY, "Moving away"}, + {DIRECTION_STATIONARY, "Stationary"}, + {DIRECTION_NA, "NA"}, +}; + constexpr Uint8ToString ZONE_TYPE_BY_UINT[] = { {ZONE_DISABLED, "Disabled"}, {ZONE_DETECTION, "Detection"}, @@ -103,36 +109,38 @@ template const char *find_str(const Uint8ToString (&arr)[N], uint8_t v return ""; // Not found } -// LD2450 serial command header & footer -static const uint8_t CMD_FRAME_HEADER[4] = {0xFD, 0xFC, 0xFB, 0xFA}; -static const uint8_t CMD_FRAME_END[4] = {0x04, 0x03, 0x02, 0x01}; // LD2450 UART Serial Commands -static const uint8_t CMD_ENABLE_CONF = 0xFF; -static const uint8_t CMD_DISABLE_CONF = 0xFE; -static const uint8_t CMD_VERSION = 0xA0; -static const uint8_t CMD_MAC = 0xA5; -static const uint8_t CMD_RESET = 0xA2; -static const uint8_t CMD_RESTART = 0xA3; -static const uint8_t CMD_BLUETOOTH = 0xA4; -static const uint8_t CMD_SINGLE_TARGET_MODE = 0x80; -static const uint8_t CMD_MULTI_TARGET_MODE = 0x90; -static const uint8_t CMD_QUERY_TARGET_MODE = 0x91; -static const uint8_t CMD_SET_BAUD_RATE = 0xA1; -static const uint8_t CMD_QUERY_ZONE = 0xC1; -static const uint8_t CMD_SET_ZONE = 0xC2; +static constexpr uint8_t CMD_ENABLE_CONF = 0xFF; +static constexpr uint8_t CMD_DISABLE_CONF = 0xFE; +static constexpr uint8_t CMD_QUERY_VERSION = 0xA0; +static constexpr uint8_t CMD_QUERY_MAC_ADDRESS = 0xA5; +static constexpr uint8_t CMD_RESET = 0xA2; +static constexpr uint8_t CMD_RESTART = 0xA3; +static constexpr uint8_t CMD_BLUETOOTH = 0xA4; +static constexpr uint8_t CMD_SINGLE_TARGET_MODE = 0x80; +static constexpr uint8_t CMD_MULTI_TARGET_MODE = 0x90; +static constexpr uint8_t CMD_QUERY_TARGET_MODE = 0x91; +static constexpr uint8_t CMD_SET_BAUD_RATE = 0xA1; +static constexpr uint8_t CMD_QUERY_ZONE = 0xC1; +static constexpr uint8_t CMD_SET_ZONE = 0xC2; +// Header & Footer size +static constexpr uint8_t HEADER_FOOTER_SIZE = 4; +// Command Header & Footer +static constexpr uint8_t CMD_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xFD, 0xFC, 0xFB, 0xFA}; +static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0x04, 0x03, 0x02, 0x01}; +// Data Header & Footer +static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xAA, 0xFF, 0x03, 0x00}; +static constexpr uint8_t DATA_FRAME_FOOTER[2] = {0x55, 0xCC}; +// MAC address the module uses when Bluetooth is disabled +static constexpr uint8_t NO_MAC[] = {0x08, 0x05, 0x04, 0x03, 0x02, 0x01}; static inline uint16_t convert_seconds_to_ms(uint16_t value) { return value * 1000; }; -static inline std::string convert_signed_int_to_hex(int value) { - auto value_as_str = str_snprintf("%04x", 4, value & 0xFFFF); - return value_as_str; -} - static inline void convert_int_values_to_hex(const int *values, uint8_t *bytes) { - for (int i = 0; i < 4; i++) { - std::string temp_hex = convert_signed_int_to_hex(values[i]); - bytes[i * 2] = std::stoi(temp_hex.substr(2, 2), nullptr, 16); // Store high byte - bytes[i * 2 + 1] = std::stoi(temp_hex.substr(0, 2), nullptr, 16); // Store low byte + for (uint8_t i = 0; i < 4; i++) { + uint16_t val = values[i] & 0xFFFF; + bytes[i * 2] = val & 0xFF; // Store low byte first (little-endian) + bytes[i * 2 + 1] = (val >> 8) & 0xFF; // Store high byte second } } @@ -170,18 +178,13 @@ static inline float calculate_angle(float base, float hypotenuse) { return angle_degrees; } -static inline std::string get_direction(int16_t speed) { - static const char *const APPROACHING = "Approaching"; - static const char *const MOVING_AWAY = "Moving away"; - static const char *const STATIONARY = "Stationary"; - - if (speed > 0) { - return MOVING_AWAY; +static bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) { + for (uint8_t i = 0; i < HEADER_FOOTER_SIZE; i++) { + if (header_footer[i] != buffer[i]) { + return false; // Mismatch in header/footer + } } - if (speed < 0) { - return APPROACHING; - } - return STATIONARY; + return true; // Valid header/footer } void LD2450Component::setup() { @@ -196,84 +199,93 @@ void LD2450Component::setup() { } void LD2450Component::dump_config() { - ESP_LOGCONFIG(TAG, "LD2450:"); + std::string mac_str = + mac_address_is_valid(this->mac_address_) ? format_mac_address_pretty(this->mac_address_) : UNKNOWN_MAC; + std::string version = str_sprintf(VERSION_FMT, this->version_[1], this->version_[0], this->version_[5], + this->version_[4], this->version_[3], this->version_[2]); + ESP_LOGCONFIG(TAG, + "LD2450:\n" + " Firmware version: %s\n" + " MAC address: %s\n" + " Throttle: %u ms", + version.c_str(), mac_str.c_str(), this->throttle_); #ifdef USE_BINARY_SENSOR - LOG_BINARY_SENSOR(" ", "TargetBinarySensor", this->target_binary_sensor_); - LOG_BINARY_SENSOR(" ", "MovingTargetBinarySensor", this->moving_target_binary_sensor_); - LOG_BINARY_SENSOR(" ", "StillTargetBinarySensor", this->still_target_binary_sensor_); -#endif -#ifdef USE_SWITCH - LOG_SWITCH(" ", "BluetoothSwitch", this->bluetooth_switch_); - LOG_SWITCH(" ", "MultiTargetSwitch", this->multi_target_switch_); -#endif -#ifdef USE_BUTTON - LOG_BUTTON(" ", "ResetButton", this->reset_button_); - LOG_BUTTON(" ", "RestartButton", this->restart_button_); + ESP_LOGCONFIG(TAG, "Binary Sensors:"); + LOG_BINARY_SENSOR(" ", "MovingTarget", this->moving_target_binary_sensor_); + LOG_BINARY_SENSOR(" ", "StillTarget", this->still_target_binary_sensor_); + LOG_BINARY_SENSOR(" ", "Target", this->target_binary_sensor_); #endif #ifdef USE_SENSOR - LOG_SENSOR(" ", "TargetCountSensor", this->target_count_sensor_); - LOG_SENSOR(" ", "StillTargetCountSensor", this->still_target_count_sensor_); - LOG_SENSOR(" ", "MovingTargetCountSensor", this->moving_target_count_sensor_); + ESP_LOGCONFIG(TAG, "Sensors:"); + LOG_SENSOR(" ", "MovingTargetCount", this->moving_target_count_sensor_); + LOG_SENSOR(" ", "StillTargetCount", this->still_target_count_sensor_); + LOG_SENSOR(" ", "TargetCount", this->target_count_sensor_); for (sensor::Sensor *s : this->move_x_sensors_) { - LOG_SENSOR(" ", "NthTargetXSensor", s); + LOG_SENSOR(" ", "TargetX", s); } for (sensor::Sensor *s : this->move_y_sensors_) { - LOG_SENSOR(" ", "NthTargetYSensor", s); - } - for (sensor::Sensor *s : this->move_speed_sensors_) { - LOG_SENSOR(" ", "NthTargetSpeedSensor", s); + LOG_SENSOR(" ", "TargetY", s); } for (sensor::Sensor *s : this->move_angle_sensors_) { - LOG_SENSOR(" ", "NthTargetAngleSensor", s); + LOG_SENSOR(" ", "TargetAngle", s); } for (sensor::Sensor *s : this->move_distance_sensors_) { - LOG_SENSOR(" ", "NthTargetDistanceSensor", s); + LOG_SENSOR(" ", "TargetDistance", s); } for (sensor::Sensor *s : this->move_resolution_sensors_) { - LOG_SENSOR(" ", "NthTargetResolutionSensor", s); + LOG_SENSOR(" ", "TargetResolution", s); + } + for (sensor::Sensor *s : this->move_speed_sensors_) { + LOG_SENSOR(" ", "TargetSpeed", s); } for (sensor::Sensor *s : this->zone_target_count_sensors_) { - LOG_SENSOR(" ", "NthZoneTargetCountSensor", s); - } - for (sensor::Sensor *s : this->zone_still_target_count_sensors_) { - LOG_SENSOR(" ", "NthZoneStillTargetCountSensor", s); + LOG_SENSOR(" ", "ZoneTargetCount", s); } for (sensor::Sensor *s : this->zone_moving_target_count_sensors_) { - LOG_SENSOR(" ", "NthZoneMovingTargetCountSensor", s); + LOG_SENSOR(" ", "ZoneMovingTargetCount", s); + } + for (sensor::Sensor *s : this->zone_still_target_count_sensors_) { + LOG_SENSOR(" ", "ZoneStillTargetCount", s); } #endif #ifdef USE_TEXT_SENSOR - LOG_TEXT_SENSOR(" ", "VersionTextSensor", this->version_text_sensor_); - LOG_TEXT_SENSOR(" ", "MacTextSensor", this->mac_text_sensor_); + ESP_LOGCONFIG(TAG, "Text Sensors:"); + LOG_TEXT_SENSOR(" ", "Version", this->version_text_sensor_); + LOG_TEXT_SENSOR(" ", "Mac", this->mac_text_sensor_); for (text_sensor::TextSensor *s : this->direction_text_sensors_) { - LOG_TEXT_SENSOR(" ", "NthDirectionTextSensor", s); + LOG_TEXT_SENSOR(" ", "Direction", s); } #endif #ifdef USE_NUMBER + ESP_LOGCONFIG(TAG, "Numbers:"); + LOG_NUMBER(" ", "PresenceTimeout", this->presence_timeout_number_); for (auto n : this->zone_numbers_) { - LOG_NUMBER(" ", "ZoneX1Number", n.x1); - LOG_NUMBER(" ", "ZoneY1Number", n.y1); - LOG_NUMBER(" ", "ZoneX2Number", n.x2); - LOG_NUMBER(" ", "ZoneY2Number", n.y2); + LOG_NUMBER(" ", "ZoneX1", n.x1); + LOG_NUMBER(" ", "ZoneY1", n.y1); + LOG_NUMBER(" ", "ZoneX2", n.x2); + LOG_NUMBER(" ", "ZoneY2", n.y2); } #endif #ifdef USE_SELECT - LOG_SELECT(" ", "BaudRateSelect", this->baud_rate_select_); - LOG_SELECT(" ", "ZoneTypeSelect", this->zone_type_select_); + ESP_LOGCONFIG(TAG, "Selects:"); + LOG_SELECT(" ", "BaudRate", this->baud_rate_select_); + LOG_SELECT(" ", "ZoneType", this->zone_type_select_); #endif -#ifdef USE_NUMBER - LOG_NUMBER(" ", "PresenceTimeoutNumber", this->presence_timeout_number_); +#ifdef USE_SWITCH + ESP_LOGCONFIG(TAG, "Switches:"); + LOG_SWITCH(" ", "Bluetooth", this->bluetooth_switch_); + LOG_SWITCH(" ", "MultiTarget", this->multi_target_switch_); +#endif +#ifdef USE_BUTTON + ESP_LOGCONFIG(TAG, "Buttons:"); + LOG_BUTTON(" ", "FactoryReset", this->factory_reset_button_); + LOG_BUTTON(" ", "Restart", this->restart_button_); #endif - ESP_LOGCONFIG(TAG, - " Throttle: %ums\n" - " MAC Address: %s\n" - " Firmware version: %s", - this->throttle_, this->mac_ == NO_MAC ? UNKNOWN_MAC : this->mac_.c_str(), this->version_.c_str()); } void LD2450Component::loop() { while (this->available()) { - this->readline_(read(), this->buffer_data_, MAX_LINE_LENGTH); + this->readline_(this->read()); } } @@ -308,7 +320,7 @@ void LD2450Component::set_radar_zone(int32_t zone_type, int32_t zone1_x1, int32_ this->zone_type_ = zone_type; int zone_parameters[12] = {zone1_x1, zone1_y1, zone1_x2, zone1_y2, zone2_x1, zone2_y1, zone2_x2, zone2_y2, zone3_x1, zone3_y1, zone3_x2, zone3_y2}; - for (int i = 0; i < MAX_ZONES; i++) { + for (uint8_t i = 0; i < MAX_ZONES; i++) { this->zone_config_[i].x1 = zone_parameters[i * 4]; this->zone_config_[i].y1 = zone_parameters[i * 4 + 1]; this->zone_config_[i].x2 = zone_parameters[i * 4 + 2]; @@ -322,15 +334,15 @@ void LD2450Component::send_set_zone_command_() { uint8_t cmd_value[26] = {}; uint8_t zone_type_bytes[2] = {static_cast(this->zone_type_), 0x00}; uint8_t area_config[24] = {}; - for (int i = 0; i < MAX_ZONES; i++) { + for (uint8_t i = 0; i < MAX_ZONES; i++) { int values[4] = {this->zone_config_[i].x1, this->zone_config_[i].y1, this->zone_config_[i].x2, this->zone_config_[i].y2}; ld2450::convert_int_values_to_hex(values, area_config + (i * 8)); } - std::memcpy(cmd_value, zone_type_bytes, 2); - std::memcpy(cmd_value + 2, area_config, 24); + std::memcpy(cmd_value, zone_type_bytes, sizeof(zone_type_bytes)); + std::memcpy(cmd_value + 2, area_config, sizeof(area_config)); this->set_config_mode_(true); - this->send_command_(CMD_SET_ZONE, cmd_value, 26); + this->send_command_(CMD_SET_ZONE, cmd_value, sizeof(cmd_value)); this->set_config_mode_(false); } @@ -346,14 +358,14 @@ bool LD2450Component::get_timeout_status_(uint32_t check_millis) { } // Extract, store and publish zone details LD2450 buffer -void LD2450Component::process_zone_(uint8_t *buffer) { +void LD2450Component::process_zone_() { uint8_t index, start; for (index = 0; index < MAX_ZONES; index++) { start = 12 + index * 8; - this->zone_config_[index].x1 = ld2450::hex_to_signed_int(buffer, start); - this->zone_config_[index].y1 = ld2450::hex_to_signed_int(buffer, start + 2); - this->zone_config_[index].x2 = ld2450::hex_to_signed_int(buffer, start + 4); - this->zone_config_[index].y2 = ld2450::hex_to_signed_int(buffer, start + 6); + this->zone_config_[index].x1 = ld2450::hex_to_signed_int(this->buffer_data_, start); + this->zone_config_[index].y1 = ld2450::hex_to_signed_int(this->buffer_data_, start + 2); + this->zone_config_[index].x2 = ld2450::hex_to_signed_int(this->buffer_data_, start + 4); + this->zone_config_[index].y2 = ld2450::hex_to_signed_int(this->buffer_data_, start + 6); #ifdef USE_NUMBER // only one null check as all coordinates are required for a single zone if (this->zone_numbers_[index].x1 != nullptr) { @@ -399,27 +411,25 @@ void LD2450Component::restart_and_read_all_info() { // Send command with values to LD2450 void LD2450Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) { - ESP_LOGV(TAG, "Sending command %02X", command); - // frame header - this->write_array(CMD_FRAME_HEADER, 4); + ESP_LOGV(TAG, "Sending COMMAND %02X", command); + // frame header bytes + this->write_array(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER)); // length bytes - int len = 2; + uint8_t len = 2; if (command_value != nullptr) { len += command_value_len; } - this->write_byte(lowbyte(len)); - this->write_byte(highbyte(len)); - // command - this->write_byte(lowbyte(command)); - this->write_byte(highbyte(command)); + uint8_t len_cmd[] = {lowbyte(len), highbyte(len), command, 0x00}; + this->write_array(len_cmd, sizeof(len_cmd)); + // command value bytes if (command_value != nullptr) { - for (int i = 0; i < command_value_len; i++) { + for (uint8_t i = 0; i < command_value_len; i++) { this->write_byte(command_value[i]); } } - // footer - this->write_array(CMD_FRAME_END, 4); + // frame footer bytes + this->write_array(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER)); // FIXME to remove delay(50); // NOLINT } @@ -427,25 +437,23 @@ void LD2450Component::send_command_(uint8_t command, const uint8_t *command_valu // LD2450 Radar data message: // [AA FF 03 00] [0E 03 B1 86 10 00 40 01] [00 00 00 00 00 00 00 00] [00 00 00 00 00 00 00 00] [55 CC] // Header Target 1 Target 2 Target 3 End -void LD2450Component::handle_periodic_data_(uint8_t *buffer, uint8_t len) { - if (len < 29) { // header (4 bytes) + 8 x 3 target data + footer (2 bytes) - ESP_LOGE(TAG, "Invalid message length"); - return; - } - if (buffer[0] != 0xAA || buffer[1] != 0xFF || buffer[2] != 0x03 || buffer[3] != 0x00) { // header - ESP_LOGE(TAG, "Invalid message header"); - return; - } - if (buffer[len - 2] != 0x55 || buffer[len - 1] != 0xCC) { // footer - ESP_LOGE(TAG, "Invalid message footer"); - return; - } - +void LD2450Component::handle_periodic_data_() { + // Early throttle check - moved before any processing to save CPU cycles if (App.get_loop_component_start_time() - this->last_periodic_millis_ < this->throttle_) { - ESP_LOGV(TAG, "Throttling: %d", this->throttle_); return; } + if (this->buffer_pos_ < 29) { // header (4 bytes) + 8 x 3 target data + footer (2 bytes) + ESP_LOGE(TAG, "Invalid length"); + return; + } + if (!ld2450::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) || + this->buffer_data_[this->buffer_pos_ - 2] != DATA_FRAME_FOOTER[0] || + this->buffer_data_[this->buffer_pos_ - 1] != DATA_FRAME_FOOTER[1]) { + ESP_LOGE(TAG, "Invalid header/footer"); + return; + } + // Save the timestamp after validating the frame so, if invalid, we'll take the next frame immediately this->last_periodic_millis_ = App.get_loop_component_start_time(); int16_t target_count = 0; @@ -453,13 +461,13 @@ void LD2450Component::handle_periodic_data_(uint8_t *buffer, uint8_t len) { int16_t moving_target_count = 0; int16_t start = 0; int16_t val = 0; - uint8_t index = 0; int16_t tx = 0; int16_t ty = 0; int16_t td = 0; int16_t ts = 0; int16_t angle = 0; - std::string direction{}; + uint8_t index = 0; + Direction direction{DIRECTION_UNDEFINED}; bool is_moving = false; #if defined(USE_BINARY_SENSOR) || defined(USE_SENSOR) || defined(USE_TEXT_SENSOR) @@ -471,29 +479,38 @@ void LD2450Component::handle_periodic_data_(uint8_t *buffer, uint8_t len) { is_moving = false; sensor::Sensor *sx = this->move_x_sensors_[index]; if (sx != nullptr) { - val = ld2450::decode_coordinate(buffer[start], buffer[start + 1]); + val = ld2450::decode_coordinate(this->buffer_data_[start], this->buffer_data_[start + 1]); tx = val; - sx->publish_state(val); + if (this->cached_target_data_[index].x != val) { + sx->publish_state(val); + this->cached_target_data_[index].x = val; + } } // Y start = TARGET_Y + index * 8; sensor::Sensor *sy = this->move_y_sensors_[index]; if (sy != nullptr) { - val = ld2450::decode_coordinate(buffer[start], buffer[start + 1]); + val = ld2450::decode_coordinate(this->buffer_data_[start], this->buffer_data_[start + 1]); ty = val; - sy->publish_state(val); + if (this->cached_target_data_[index].y != val) { + sy->publish_state(val); + this->cached_target_data_[index].y = val; + } } // RESOLUTION start = TARGET_RESOLUTION + index * 8; sensor::Sensor *sr = this->move_resolution_sensors_[index]; if (sr != nullptr) { - val = (buffer[start + 1] << 8) | buffer[start]; - sr->publish_state(val); + val = (this->buffer_data_[start + 1] << 8) | this->buffer_data_[start]; + if (this->cached_target_data_[index].resolution != val) { + sr->publish_state(val); + this->cached_target_data_[index].resolution = val; + } } #endif // SPEED start = TARGET_SPEED + index * 8; - val = ld2450::decode_speed(buffer[start], buffer[start + 1]); + val = ld2450::decode_speed(this->buffer_data_[start], this->buffer_data_[start + 1]); ts = val; if (val) { is_moving = true; @@ -502,13 +519,17 @@ void LD2450Component::handle_periodic_data_(uint8_t *buffer, uint8_t len) { #ifdef USE_SENSOR sensor::Sensor *ss = this->move_speed_sensors_[index]; if (ss != nullptr) { - ss->publish_state(val); + if (this->cached_target_data_[index].speed != val) { + ss->publish_state(val); + this->cached_target_data_[index].speed = val; + } } #endif // DISTANCE - val = (uint16_t) sqrt( - pow(ld2450::decode_coordinate(buffer[TARGET_X + index * 8], buffer[(TARGET_X + index * 8) + 1]), 2) + - pow(ld2450::decode_coordinate(buffer[TARGET_Y + index * 8], buffer[(TARGET_Y + index * 8) + 1]), 2)); + // Optimized: use already decoded tx and ty values, replace pow() with multiplication + int32_t x_squared = (int32_t) tx * tx; + int32_t y_squared = (int32_t) ty * ty; + val = (uint16_t) sqrt(x_squared + y_squared); td = val; if (val > 0) { target_count++; @@ -516,27 +537,42 @@ void LD2450Component::handle_periodic_data_(uint8_t *buffer, uint8_t len) { #ifdef USE_SENSOR sensor::Sensor *sd = this->move_distance_sensors_[index]; if (sd != nullptr) { - sd->publish_state(val); + if (this->cached_target_data_[index].distance != val) { + sd->publish_state(val); + this->cached_target_data_[index].distance = val; + } } // ANGLE - angle = calculate_angle(static_cast(ty), static_cast(td)); + angle = ld2450::calculate_angle(static_cast(ty), static_cast(td)); if (tx > 0) { angle = angle * -1; } sensor::Sensor *sa = this->move_angle_sensors_[index]; if (sa != nullptr) { - sa->publish_state(angle); + if (std::isnan(this->cached_target_data_[index].angle) || + std::abs(this->cached_target_data_[index].angle - angle) > 0.1f) { + sa->publish_state(angle); + this->cached_target_data_[index].angle = angle; + } } #endif #ifdef USE_TEXT_SENSOR // DIRECTION - direction = get_direction(ts); if (td == 0) { - direction = "NA"; + direction = DIRECTION_NA; + } else if (ts > 0) { + direction = DIRECTION_MOVING_AWAY; + } else if (ts < 0) { + direction = DIRECTION_APPROACHING; + } else { + direction = DIRECTION_STATIONARY; } text_sensor::TextSensor *tsd = this->direction_text_sensors_[index]; if (tsd != nullptr) { - tsd->publish_state(direction); + if (this->cached_target_data_[index].direction != direction) { + tsd->publish_state(find_str(ld2450::DIRECTION_BY_UINT, direction)); + this->cached_target_data_[index].direction = direction; + } } #endif @@ -563,32 +599,50 @@ void LD2450Component::handle_periodic_data_(uint8_t *buffer, uint8_t len) { // Publish Still Target Count in Zones sensor::Sensor *szstc = this->zone_still_target_count_sensors_[index]; if (szstc != nullptr) { - szstc->publish_state(zone_still_targets); + if (this->cached_zone_data_[index].still_count != zone_still_targets) { + szstc->publish_state(zone_still_targets); + this->cached_zone_data_[index].still_count = zone_still_targets; + } } // Publish Moving Target Count in Zones sensor::Sensor *szmtc = this->zone_moving_target_count_sensors_[index]; if (szmtc != nullptr) { - szmtc->publish_state(zone_moving_targets); + if (this->cached_zone_data_[index].moving_count != zone_moving_targets) { + szmtc->publish_state(zone_moving_targets); + this->cached_zone_data_[index].moving_count = zone_moving_targets; + } } // Publish All Target Count in Zones sensor::Sensor *sztc = this->zone_target_count_sensors_[index]; if (sztc != nullptr) { - sztc->publish_state(zone_all_targets); + if (this->cached_zone_data_[index].total_count != zone_all_targets) { + sztc->publish_state(zone_all_targets); + this->cached_zone_data_[index].total_count = zone_all_targets; + } } } // End loop thru zones // Target Count if (this->target_count_sensor_ != nullptr) { - this->target_count_sensor_->publish_state(target_count); + if (this->cached_global_data_.target_count != target_count) { + this->target_count_sensor_->publish_state(target_count); + this->cached_global_data_.target_count = target_count; + } } // Still Target Count if (this->still_target_count_sensor_ != nullptr) { - this->still_target_count_sensor_->publish_state(still_target_count); + if (this->cached_global_data_.still_count != still_target_count) { + this->still_target_count_sensor_->publish_state(still_target_count); + this->cached_global_data_.still_count = still_target_count; + } } // Moving Target Count if (this->moving_target_count_sensor_ != nullptr) { - this->moving_target_count_sensor_->publish_state(moving_target_count); + if (this->cached_global_data_.moving_count != moving_target_count) { + this->moving_target_count_sensor_->publish_state(moving_target_count); + this->cached_global_data_.moving_count = moving_target_count; + } } #endif @@ -640,117 +694,139 @@ void LD2450Component::handle_periodic_data_(uint8_t *buffer, uint8_t len) { #endif } -bool LD2450Component::handle_ack_data_(uint8_t *buffer, uint8_t len) { - ESP_LOGV(TAG, "Handling ack data for command %02X", buffer[COMMAND]); - if (len < 10) { - ESP_LOGE(TAG, "Invalid ack length"); +bool LD2450Component::handle_ack_data_() { + ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]); + if (this->buffer_pos_ < 10) { + ESP_LOGE(TAG, "Invalid length"); return true; } - if (buffer[0] != 0xFD || buffer[1] != 0xFC || buffer[2] != 0xFB || buffer[3] != 0xFA) { // frame header - ESP_LOGE(TAG, "Invalid ack header (command %02X)", buffer[COMMAND]); + if (!ld2450::validate_header_footer(CMD_FRAME_HEADER, this->buffer_data_)) { + ESP_LOGW(TAG, "Invalid header: %s", format_hex_pretty(this->buffer_data_, HEADER_FOOTER_SIZE).c_str()); return true; } - if (buffer[COMMAND_STATUS] != 0x01) { - ESP_LOGE(TAG, "Invalid ack status"); + if (this->buffer_data_[COMMAND_STATUS] != 0x01) { + ESP_LOGE(TAG, "Invalid status"); return true; } - if (buffer[8] || buffer[9]) { - ESP_LOGE(TAG, "Last buffer was %u, %u", buffer[8], buffer[9]); + if (this->buffer_data_[8] || this->buffer_data_[9]) { + ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]); return true; } - switch (buffer[COMMAND]) { - case lowbyte(CMD_ENABLE_CONF): - ESP_LOGV(TAG, "Enable conf command"); + switch (this->buffer_data_[COMMAND]) { + case CMD_ENABLE_CONF: + ESP_LOGV(TAG, "Enable conf"); break; - case lowbyte(CMD_DISABLE_CONF): - ESP_LOGV(TAG, "Disable conf command"); + + case CMD_DISABLE_CONF: + ESP_LOGV(TAG, "Disabled conf"); break; - case lowbyte(CMD_SET_BAUD_RATE): - ESP_LOGV(TAG, "Baud rate change command"); + + case CMD_SET_BAUD_RATE: + ESP_LOGV(TAG, "Baud rate change"); #ifdef USE_SELECT if (this->baud_rate_select_ != nullptr) { - ESP_LOGV(TAG, "Change baud rate to %s", this->baud_rate_select_->state.c_str()); + ESP_LOGE(TAG, "Change baud rate to %s and reinstall", this->baud_rate_select_->state.c_str()); } #endif break; - case lowbyte(CMD_VERSION): - this->version_ = str_sprintf(VERSION_FMT, buffer[13], buffer[12], buffer[17], buffer[16], buffer[15], buffer[14]); - ESP_LOGV(TAG, "Firmware version: %s", this->version_.c_str()); + + case CMD_QUERY_VERSION: { + std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_)); + std::string version = str_sprintf(VERSION_FMT, this->version_[1], this->version_[0], this->version_[5], + this->version_[4], this->version_[3], this->version_[2]); + ESP_LOGV(TAG, "Firmware version: %s", version.c_str()); #ifdef USE_TEXT_SENSOR if (this->version_text_sensor_ != nullptr) { - this->version_text_sensor_->publish_state(this->version_); + this->version_text_sensor_->publish_state(version); } #endif break; - case lowbyte(CMD_MAC): - if (len < 20) { + } + + case CMD_QUERY_MAC_ADDRESS: { + if (this->buffer_pos_ < 20) { return false; } - this->mac_ = format_mac_address_pretty(&buffer[10]); - ESP_LOGV(TAG, "MAC address: %s", this->mac_.c_str()); + + this->bluetooth_on_ = std::memcmp(&this->buffer_data_[10], NO_MAC, sizeof(NO_MAC)) != 0; + if (this->bluetooth_on_) { + std::memcpy(this->mac_address_, &this->buffer_data_[10], sizeof(this->mac_address_)); + } + + std::string mac_str = + mac_address_is_valid(this->mac_address_) ? format_mac_address_pretty(this->mac_address_) : UNKNOWN_MAC; + ESP_LOGV(TAG, "MAC address: %s", mac_str.c_str()); #ifdef USE_TEXT_SENSOR if (this->mac_text_sensor_ != nullptr) { - this->mac_text_sensor_->publish_state(this->mac_ == NO_MAC ? UNKNOWN_MAC : this->mac_); + this->mac_text_sensor_->publish_state(mac_str); } #endif #ifdef USE_SWITCH if (this->bluetooth_switch_ != nullptr) { - this->bluetooth_switch_->publish_state(this->mac_ != NO_MAC); + this->bluetooth_switch_->publish_state(this->bluetooth_on_); } #endif break; - case lowbyte(CMD_BLUETOOTH): - ESP_LOGV(TAG, "Bluetooth command"); + } + + case CMD_BLUETOOTH: + ESP_LOGV(TAG, "Bluetooth"); break; - case lowbyte(CMD_SINGLE_TARGET_MODE): - ESP_LOGV(TAG, "Single target conf command"); + + case CMD_SINGLE_TARGET_MODE: + ESP_LOGV(TAG, "Single target conf"); #ifdef USE_SWITCH if (this->multi_target_switch_ != nullptr) { this->multi_target_switch_->publish_state(false); } #endif break; - case lowbyte(CMD_MULTI_TARGET_MODE): - ESP_LOGV(TAG, "Multi target conf command"); + + case CMD_MULTI_TARGET_MODE: + ESP_LOGV(TAG, "Multi target conf"); #ifdef USE_SWITCH if (this->multi_target_switch_ != nullptr) { this->multi_target_switch_->publish_state(true); } #endif break; - case lowbyte(CMD_QUERY_TARGET_MODE): - ESP_LOGV(TAG, "Query target tracking mode command"); + + case CMD_QUERY_TARGET_MODE: + ESP_LOGV(TAG, "Query target tracking mode"); #ifdef USE_SWITCH if (this->multi_target_switch_ != nullptr) { - this->multi_target_switch_->publish_state(buffer[10] == 0x02); + this->multi_target_switch_->publish_state(this->buffer_data_[10] == 0x02); } #endif break; - case lowbyte(CMD_QUERY_ZONE): - ESP_LOGV(TAG, "Query zone conf command"); - this->zone_type_ = std::stoi(std::to_string(buffer[10]), nullptr, 16); + + case CMD_QUERY_ZONE: + ESP_LOGV(TAG, "Query zone conf"); + this->zone_type_ = std::stoi(std::to_string(this->buffer_data_[10]), nullptr, 16); this->publish_zone_type(); #ifdef USE_SELECT if (this->zone_type_select_ != nullptr) { ESP_LOGV(TAG, "Change zone type to: %s", this->zone_type_select_->state.c_str()); } #endif - if (buffer[10] == 0x00) { + if (this->buffer_data_[10] == 0x00) { ESP_LOGV(TAG, "Zone: Disabled"); } - if (buffer[10] == 0x01) { + if (this->buffer_data_[10] == 0x01) { ESP_LOGV(TAG, "Zone: Area detection"); } - if (buffer[10] == 0x02) { + if (this->buffer_data_[10] == 0x02) { ESP_LOGV(TAG, "Zone: Area filter"); } - this->process_zone_(buffer); + this->process_zone_(); break; - case lowbyte(CMD_SET_ZONE): - ESP_LOGV(TAG, "Set zone conf command"); + + case CMD_SET_ZONE: + ESP_LOGV(TAG, "Set zone conf"); this->query_zone_info(); break; + default: break; } @@ -758,55 +834,57 @@ bool LD2450Component::handle_ack_data_(uint8_t *buffer, uint8_t len) { } // Read LD2450 buffer data -void LD2450Component::readline_(int readch, uint8_t *buffer, uint8_t len) { +void LD2450Component::readline_(int readch) { if (readch < 0) { - return; + return; // No data available } - if (this->buffer_pos_ < len - 1) { - buffer[this->buffer_pos_++] = readch; - buffer[this->buffer_pos_] = 0; + + if (this->buffer_pos_ < MAX_LINE_LENGTH - 1) { + this->buffer_data_[this->buffer_pos_++] = readch; + this->buffer_data_[this->buffer_pos_] = 0; } else { + // We should never get here, but just in case... + ESP_LOGW(TAG, "Max command length exceeded; ignoring"); this->buffer_pos_ = 0; } if (this->buffer_pos_ < 4) { - return; + return; // Not enough data to process yet } - if (buffer[this->buffer_pos_ - 2] == 0x55 && buffer[this->buffer_pos_ - 1] == 0xCC) { - ESP_LOGV(TAG, "Handle periodic radar data"); - this->handle_periodic_data_(buffer, this->buffer_pos_); + if (this->buffer_data_[this->buffer_pos_ - 2] == DATA_FRAME_FOOTER[0] && + this->buffer_data_[this->buffer_pos_ - 1] == DATA_FRAME_FOOTER[1]) { + ESP_LOGV(TAG, "Handling Periodic Data: %s", format_hex_pretty(this->buffer_data_, this->buffer_pos_).c_str()); + this->handle_periodic_data_(); this->buffer_pos_ = 0; // Reset position index for next frame - } else if (buffer[this->buffer_pos_ - 4] == 0x04 && buffer[this->buffer_pos_ - 3] == 0x03 && - buffer[this->buffer_pos_ - 2] == 0x02 && buffer[this->buffer_pos_ - 1] == 0x01) { - ESP_LOGV(TAG, "Handle command ack data"); - if (this->handle_ack_data_(buffer, this->buffer_pos_)) { - this->buffer_pos_ = 0; // Reset position index for next frame + } else if (ld2450::validate_header_footer(CMD_FRAME_FOOTER, &this->buffer_data_[this->buffer_pos_ - 4])) { + ESP_LOGV(TAG, "Handling Ack Data: %s", format_hex_pretty(this->buffer_data_, this->buffer_pos_).c_str()); + if (this->handle_ack_data_()) { + this->buffer_pos_ = 0; // Reset position index for next message } else { - ESP_LOGV(TAG, "Command ack data invalid"); + ESP_LOGV(TAG, "Ack Data incomplete"); } } } // Set Config Mode - Pre-requisite sending commands void LD2450Component::set_config_mode_(bool enable) { - uint8_t cmd = enable ? CMD_ENABLE_CONF : CMD_DISABLE_CONF; - uint8_t cmd_value[2] = {0x01, 0x00}; - this->send_command_(cmd, enable ? cmd_value : nullptr, 2); + const uint8_t cmd = enable ? CMD_ENABLE_CONF : CMD_DISABLE_CONF; + const uint8_t cmd_value[2] = {0x01, 0x00}; + this->send_command_(cmd, enable ? cmd_value : nullptr, sizeof(cmd_value)); } // Set Bluetooth Enable/Disable void LD2450Component::set_bluetooth(bool enable) { this->set_config_mode_(true); - uint8_t enable_cmd_value[2] = {0x01, 0x00}; - uint8_t disable_cmd_value[2] = {0x00, 0x00}; - this->send_command_(CMD_BLUETOOTH, enable ? enable_cmd_value : disable_cmd_value, 2); + const uint8_t cmd_value[2] = {enable ? (uint8_t) 0x01 : (uint8_t) 0x00, 0x00}; + this->send_command_(CMD_BLUETOOTH, cmd_value, sizeof(cmd_value)); this->set_timeout(200, [this]() { this->restart_and_read_all_info(); }); } // Set Baud rate void LD2450Component::set_baud_rate(const std::string &state) { this->set_config_mode_(true); - uint8_t cmd_value[2] = {find_uint8(BAUD_RATES_BY_STR, state), 0x00}; - this->send_command_(CMD_SET_BAUD_RATE, cmd_value, 2); + const uint8_t cmd_value[2] = {find_uint8(BAUD_RATES_BY_STR, state), 0x00}; + this->send_command_(CMD_SET_BAUD_RATE, cmd_value, sizeof(cmd_value)); this->set_timeout(200, [this]() { this->restart_(); }); } @@ -847,12 +925,12 @@ void LD2450Component::factory_reset() { void LD2450Component::restart_() { this->send_command_(CMD_RESTART, nullptr, 0); } // Get LD2450 firmware version -void LD2450Component::get_version_() { this->send_command_(CMD_VERSION, nullptr, 0); } +void LD2450Component::get_version_() { this->send_command_(CMD_QUERY_VERSION, nullptr, 0); } // Get LD2450 mac address void LD2450Component::get_mac_() { uint8_t cmd_value[2] = {0x01, 0x00}; - this->send_command_(CMD_MAC, cmd_value, 2); + this->send_command_(CMD_QUERY_MAC_ADDRESS, cmd_value, 2); } // Query for target tracking mode diff --git a/esphome/components/ld2450/ld2450.h b/esphome/components/ld2450/ld2450.h index b0c19dc96c..ae72a0d8cb 100644 --- a/esphome/components/ld2450/ld2450.h +++ b/esphome/components/ld2450/ld2450.h @@ -5,6 +5,8 @@ #include "esphome/core/defines.h" #include "esphome/core/helpers.h" #include "esphome/core/preferences.h" +#include +#include #ifdef USE_SENSOR #include "esphome/components/sensor/sensor.h" #endif @@ -36,10 +38,18 @@ namespace ld2450 { // Constants static const uint8_t DEFAULT_PRESENCE_TIMEOUT = 5; // Timeout to reset presense status 5 sec. -static const uint8_t MAX_LINE_LENGTH = 60; // Max characters for serial buffer +static const uint8_t MAX_LINE_LENGTH = 41; // Max characters for serial buffer static const uint8_t MAX_TARGETS = 3; // Max 3 Targets in LD2450 static const uint8_t MAX_ZONES = 3; // Max 3 Zones in LD2450 +enum Direction : uint8_t { + DIRECTION_APPROACHING = 0, + DIRECTION_MOVING_AWAY = 1, + DIRECTION_STATIONARY = 2, + DIRECTION_NA = 3, + DIRECTION_UNDEFINED = 4, +}; + // Target coordinate struct struct Target { int16_t x; @@ -65,19 +75,22 @@ struct ZoneOfNumbers { #endif class LD2450Component : public Component, public uart::UARTDevice { -#ifdef USE_SENSOR - SUB_SENSOR(target_count) - SUB_SENSOR(still_target_count) - SUB_SENSOR(moving_target_count) -#endif #ifdef USE_BINARY_SENSOR - SUB_BINARY_SENSOR(target) SUB_BINARY_SENSOR(moving_target) SUB_BINARY_SENSOR(still_target) + SUB_BINARY_SENSOR(target) +#endif +#ifdef USE_SENSOR + SUB_SENSOR(moving_target_count) + SUB_SENSOR(still_target_count) + SUB_SENSOR(target_count) #endif #ifdef USE_TEXT_SENSOR - SUB_TEXT_SENSOR(version) SUB_TEXT_SENSOR(mac) + SUB_TEXT_SENSOR(version) +#endif +#ifdef USE_NUMBER + SUB_NUMBER(presence_timeout) #endif #ifdef USE_SELECT SUB_SELECT(baud_rate) @@ -88,19 +101,16 @@ class LD2450Component : public Component, public uart::UARTDevice { SUB_SWITCH(multi_target) #endif #ifdef USE_BUTTON - SUB_BUTTON(reset) + SUB_BUTTON(factory_reset) SUB_BUTTON(restart) #endif -#ifdef USE_NUMBER - SUB_NUMBER(presence_timeout) -#endif public: void setup() override; void dump_config() override; void loop() override; void set_presence_timeout(); - void set_throttle(uint16_t value) { this->throttle_ = value; }; + void set_throttle(uint16_t value) { this->throttle_ = value; } void read_all_info(); void query_zone_info(); void restart_and_read_all_info(); @@ -136,10 +146,10 @@ class LD2450Component : public Component, public uart::UARTDevice { protected: void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len); void set_config_mode_(bool enable); - void handle_periodic_data_(uint8_t *buffer, uint8_t len); - bool handle_ack_data_(uint8_t *buffer, uint8_t len); - void process_zone_(uint8_t *buffer); - void readline_(int readch, uint8_t *buffer, uint8_t len); + void handle_periodic_data_(); + bool handle_ack_data_(); + void process_zone_(); + void readline_(int readch); void get_version_(); void get_mac_(); void query_target_tracking_mode_(); @@ -157,13 +167,40 @@ class LD2450Component : public Component, public uart::UARTDevice { uint32_t moving_presence_millis_ = 0; uint16_t throttle_ = 0; uint16_t timeout_ = 5; - uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer uint8_t buffer_data_[MAX_LINE_LENGTH]; + uint8_t mac_address_[6] = {0, 0, 0, 0, 0, 0}; + uint8_t version_[6] = {0, 0, 0, 0, 0, 0}; + uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer uint8_t zone_type_ = 0; + bool bluetooth_on_{false}; Target target_info_[MAX_TARGETS]; Zone zone_config_[MAX_ZONES]; - std::string version_{}; - std::string mac_{}; + + // Change detection - cache previous values to avoid redundant publishes + // All values are initialized to sentinel values that are outside the valid sensor ranges + // to ensure the first real measurement is always published + struct CachedTargetData { + int16_t x = std::numeric_limits::min(); // -32768, outside range of -4860 to 4860 + int16_t y = std::numeric_limits::min(); // -32768, outside range of 0 to 7560 + int16_t speed = std::numeric_limits::min(); // -32768, outside practical sensor range + uint16_t resolution = std::numeric_limits::max(); // 65535, unlikely resolution value + uint16_t distance = std::numeric_limits::max(); // 65535, outside range of 0 to ~8990 + Direction direction = DIRECTION_UNDEFINED; // Undefined, will differ from any real direction + float angle = NAN; // NAN, safe sentinel for floats + } cached_target_data_[MAX_TARGETS]; + + struct CachedZoneData { + uint8_t still_count = std::numeric_limits::max(); // 255, unlikely zone count + uint8_t moving_count = std::numeric_limits::max(); // 255, unlikely zone count + uint8_t total_count = std::numeric_limits::max(); // 255, unlikely zone count + } cached_zone_data_[MAX_ZONES]; + + struct CachedGlobalData { + uint8_t target_count = std::numeric_limits::max(); // 255, max 3 targets possible + uint8_t still_count = std::numeric_limits::max(); // 255, max 3 targets possible + uint8_t moving_count = std::numeric_limits::max(); // 255, max 3 targets possible + } cached_global_data_; + #ifdef USE_NUMBER ESPPreferenceObject pref_; // only used when numbers are in use ZoneOfNumbers zone_numbers_[MAX_ZONES]; diff --git a/esphome/components/libretiny/helpers.cpp b/esphome/components/libretiny/helpers.cpp new file mode 100644 index 0000000000..b6451860d5 --- /dev/null +++ b/esphome/components/libretiny/helpers.cpp @@ -0,0 +1,35 @@ +#include "esphome/core/helpers.h" + +#ifdef USE_LIBRETINY + +#include "esphome/core/hal.h" + +#include // for macAddress() + +namespace esphome { + +uint32_t random_uint32() { return rand(); } + +bool random_bytes(uint8_t *data, size_t len) { + lt_rand_bytes(data, len); + return true; +} + +Mutex::Mutex() { handle_ = xSemaphoreCreateMutex(); } +Mutex::~Mutex() {} +void Mutex::lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); } +bool Mutex::try_lock() { return xSemaphoreTake(this->handle_, 0) == pdTRUE; } +void Mutex::unlock() { xSemaphoreGive(this->handle_); } + +// only affects the executing core +// so should not be used as a mutex lock, only to get accurate timing +IRAM_ATTR InterruptLock::InterruptLock() { portDISABLE_INTERRUPTS(); } +IRAM_ATTR InterruptLock::~InterruptLock() { portENABLE_INTERRUPTS(); } + +void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter) + WiFi.macAddress(mac); +} + +} // namespace esphome + +#endif // USE_LIBRETINY diff --git a/esphome/components/light/addressable_light.h b/esphome/components/light/addressable_light.h index 8302239d6a..baa4507d2f 100644 --- a/esphome/components/light/addressable_light.h +++ b/esphome/components/light/addressable_light.h @@ -97,12 +97,12 @@ class AddressableLight : public LightOutput, public Component { } virtual ESPColorView get_view_internal(int32_t index) const = 0; - bool effect_active_{false}; ESPColorCorrection correction_{}; + LightState *state_parent_{nullptr}; #ifdef USE_POWER_SUPPLY power_supply::PowerSupplyRequester power_; #endif - LightState *state_parent_{nullptr}; + bool effect_active_{false}; }; class AddressableLightTransformer : public LightTransitionTransformer { @@ -114,9 +114,9 @@ class AddressableLightTransformer : public LightTransitionTransformer { protected: AddressableLight &light_; - Color target_color_{}; float last_transition_progress_{0.0f}; float accumulated_alpha_{0.0f}; + Color target_color_{}; }; } // namespace light diff --git a/esphome/components/light/esp_color_correction.h b/esphome/components/light/esp_color_correction.h index 39ce5700c6..979a1acb07 100644 --- a/esphome/components/light/esp_color_correction.h +++ b/esphome/components/light/esp_color_correction.h @@ -69,8 +69,8 @@ class ESPColorCorrection { protected: uint8_t gamma_table_[256]; uint8_t gamma_reverse_table_[256]; - uint8_t local_brightness_{255}; Color max_brightness_; + uint8_t local_brightness_{255}; }; } // namespace light diff --git a/esphome/components/light/light_call.cpp b/esphome/components/light/light_call.cpp index 78b0ac9feb..a3ffe22591 100644 --- a/esphome/components/light/light_call.cpp +++ b/esphome/components/light/light_call.cpp @@ -2,12 +2,28 @@ #include "light_call.h" #include "light_state.h" #include "esphome/core/log.h" +#include "esphome/core/optional.h" namespace esphome { namespace light { static const char *const TAG = "light"; +// Macro to reduce repetitive setter code +#define IMPLEMENT_LIGHT_CALL_SETTER(name, type, flag) \ + LightCall &LightCall::set_##name(optional(name)) { \ + if ((name).has_value()) { \ + this->name##_ = (name).value(); \ + } \ + this->set_flag_(flag, (name).has_value()); \ + return *this; \ + } \ + LightCall &LightCall::set_##name(type name) { \ + this->name##_ = name; \ + this->set_flag_(flag, true); \ + return *this; \ + } + static const LogString *color_mode_to_human(ColorMode color_mode) { if (color_mode == ColorMode::UNKNOWN) return LOG_STR("Unknown"); @@ -32,41 +48,43 @@ void LightCall::perform() { const char *name = this->parent_->get_name().c_str(); LightColorValues v = this->validate_(); - if (this->publish_) { + if (this->get_publish_()) { ESP_LOGD(TAG, "'%s' Setting:", name); // Only print color mode when it's being changed ColorMode current_color_mode = this->parent_->remote_values.get_color_mode(); - if (this->color_mode_.value_or(current_color_mode) != current_color_mode) { + ColorMode target_color_mode = this->has_color_mode() ? this->color_mode_ : current_color_mode; + if (target_color_mode != current_color_mode) { ESP_LOGD(TAG, " Color mode: %s", LOG_STR_ARG(color_mode_to_human(v.get_color_mode()))); } // Only print state when it's being changed bool current_state = this->parent_->remote_values.is_on(); - if (this->state_.value_or(current_state) != current_state) { + bool target_state = this->has_state() ? this->state_ : current_state; + if (target_state != current_state) { ESP_LOGD(TAG, " State: %s", ONOFF(v.is_on())); } - if (this->brightness_.has_value()) { + if (this->has_brightness()) { ESP_LOGD(TAG, " Brightness: %.0f%%", v.get_brightness() * 100.0f); } - if (this->color_brightness_.has_value()) { + if (this->has_color_brightness()) { ESP_LOGD(TAG, " Color brightness: %.0f%%", v.get_color_brightness() * 100.0f); } - if (this->red_.has_value() || this->green_.has_value() || this->blue_.has_value()) { + if (this->has_red() || this->has_green() || this->has_blue()) { ESP_LOGD(TAG, " Red: %.0f%%, Green: %.0f%%, Blue: %.0f%%", v.get_red() * 100.0f, v.get_green() * 100.0f, v.get_blue() * 100.0f); } - if (this->white_.has_value()) { + if (this->has_white()) { ESP_LOGD(TAG, " White: %.0f%%", v.get_white() * 100.0f); } - if (this->color_temperature_.has_value()) { + if (this->has_color_temperature()) { ESP_LOGD(TAG, " Color temperature: %.1f mireds", v.get_color_temperature()); } - if (this->cold_white_.has_value() || this->warm_white_.has_value()) { + if (this->has_cold_white() || this->has_warm_white()) { ESP_LOGD(TAG, " Cold white: %.0f%%, warm white: %.0f%%", v.get_cold_white() * 100.0f, v.get_warm_white() * 100.0f); } @@ -74,58 +92,57 @@ void LightCall::perform() { if (this->has_flash_()) { // FLASH - if (this->publish_) { - ESP_LOGD(TAG, " Flash length: %.1fs", *this->flash_length_ / 1e3f); + if (this->get_publish_()) { + ESP_LOGD(TAG, " Flash length: %.1fs", this->flash_length_ / 1e3f); } - this->parent_->start_flash_(v, *this->flash_length_, this->publish_); + this->parent_->start_flash_(v, this->flash_length_, this->get_publish_()); } else if (this->has_transition_()) { // TRANSITION - if (this->publish_) { - ESP_LOGD(TAG, " Transition length: %.1fs", *this->transition_length_ / 1e3f); + if (this->get_publish_()) { + ESP_LOGD(TAG, " Transition length: %.1fs", this->transition_length_ / 1e3f); } // Special case: Transition and effect can be set when turning off if (this->has_effect_()) { - if (this->publish_) { + if (this->get_publish_()) { ESP_LOGD(TAG, " Effect: 'None'"); } this->parent_->stop_effect_(); } - this->parent_->start_transition_(v, *this->transition_length_, this->publish_); + this->parent_->start_transition_(v, this->transition_length_, this->get_publish_()); } else if (this->has_effect_()) { // EFFECT - auto effect = this->effect_; const char *effect_s; - if (effect == 0u) { + if (this->effect_ == 0u) { effect_s = "None"; } else { - effect_s = this->parent_->effects_[*this->effect_ - 1]->get_name().c_str(); + effect_s = this->parent_->effects_[this->effect_ - 1]->get_name().c_str(); } - if (this->publish_) { + if (this->get_publish_()) { ESP_LOGD(TAG, " Effect: '%s'", effect_s); } - this->parent_->start_effect_(*this->effect_); + this->parent_->start_effect_(this->effect_); // Also set light color values when starting an effect // For example to turn off the light this->parent_->set_immediately_(v, true); } else { // INSTANT CHANGE - this->parent_->set_immediately_(v, this->publish_); + this->parent_->set_immediately_(v, this->get_publish_()); } if (!this->has_transition_()) { this->parent_->target_state_reached_callback_.call(); } - if (this->publish_) { + if (this->get_publish_()) { this->parent_->publish_state(); } - if (this->save_) { + if (this->get_save_()) { this->parent_->save_remote_values_(); } } @@ -135,82 +152,80 @@ LightColorValues LightCall::validate_() { auto traits = this->parent_->get_traits(); // Color mode check - if (this->color_mode_.has_value() && !traits.supports_color_mode(this->color_mode_.value())) { - ESP_LOGW(TAG, "'%s' does not support color mode %s", name, - LOG_STR_ARG(color_mode_to_human(this->color_mode_.value()))); - this->color_mode_.reset(); + if (this->has_color_mode() && !traits.supports_color_mode(this->color_mode_)) { + ESP_LOGW(TAG, "'%s' does not support color mode %s", name, LOG_STR_ARG(color_mode_to_human(this->color_mode_))); + this->set_flag_(FLAG_HAS_COLOR_MODE, false); } // Ensure there is always a color mode set - if (!this->color_mode_.has_value()) { + if (!this->has_color_mode()) { this->color_mode_ = this->compute_color_mode_(); + this->set_flag_(FLAG_HAS_COLOR_MODE, true); } - auto color_mode = *this->color_mode_; + auto color_mode = this->color_mode_; // Transform calls that use non-native parameters for the current mode. this->transform_parameters_(); // Brightness exists check - if (this->brightness_.has_value() && *this->brightness_ > 0.0f && !(color_mode & ColorCapability::BRIGHTNESS)) { + if (this->has_brightness() && this->brightness_ > 0.0f && !(color_mode & ColorCapability::BRIGHTNESS)) { ESP_LOGW(TAG, "'%s': setting brightness not supported", name); - this->brightness_.reset(); + this->set_flag_(FLAG_HAS_BRIGHTNESS, false); } // Transition length possible check - if (this->transition_length_.has_value() && *this->transition_length_ != 0 && - !(color_mode & ColorCapability::BRIGHTNESS)) { + if (this->has_transition_() && this->transition_length_ != 0 && !(color_mode & ColorCapability::BRIGHTNESS)) { ESP_LOGW(TAG, "'%s': transitions not supported", name); - this->transition_length_.reset(); + this->set_flag_(FLAG_HAS_TRANSITION, false); } // Color brightness exists check - if (this->color_brightness_.has_value() && *this->color_brightness_ > 0.0f && !(color_mode & ColorCapability::RGB)) { + if (this->has_color_brightness() && this->color_brightness_ > 0.0f && !(color_mode & ColorCapability::RGB)) { ESP_LOGW(TAG, "'%s': color mode does not support setting RGB brightness", name); - this->color_brightness_.reset(); + this->set_flag_(FLAG_HAS_COLOR_BRIGHTNESS, false); } // RGB exists check - if ((this->red_.has_value() && *this->red_ > 0.0f) || (this->green_.has_value() && *this->green_ > 0.0f) || - (this->blue_.has_value() && *this->blue_ > 0.0f)) { + if ((this->has_red() && this->red_ > 0.0f) || (this->has_green() && this->green_ > 0.0f) || + (this->has_blue() && this->blue_ > 0.0f)) { if (!(color_mode & ColorCapability::RGB)) { ESP_LOGW(TAG, "'%s': color mode does not support setting RGB color", name); - this->red_.reset(); - this->green_.reset(); - this->blue_.reset(); + this->set_flag_(FLAG_HAS_RED, false); + this->set_flag_(FLAG_HAS_GREEN, false); + this->set_flag_(FLAG_HAS_BLUE, false); } } // White value exists check - if (this->white_.has_value() && *this->white_ > 0.0f && + if (this->has_white() && this->white_ > 0.0f && !(color_mode & ColorCapability::WHITE || color_mode & ColorCapability::COLD_WARM_WHITE)) { ESP_LOGW(TAG, "'%s': color mode does not support setting white value", name); - this->white_.reset(); + this->set_flag_(FLAG_HAS_WHITE, false); } // Color temperature exists check - if (this->color_temperature_.has_value() && + if (this->has_color_temperature() && !(color_mode & ColorCapability::COLOR_TEMPERATURE || color_mode & ColorCapability::COLD_WARM_WHITE)) { ESP_LOGW(TAG, "'%s': color mode does not support setting color temperature", name); - this->color_temperature_.reset(); + this->set_flag_(FLAG_HAS_COLOR_TEMPERATURE, false); } // Cold/warm white value exists check - if ((this->cold_white_.has_value() && *this->cold_white_ > 0.0f) || - (this->warm_white_.has_value() && *this->warm_white_ > 0.0f)) { + if ((this->has_cold_white() && this->cold_white_ > 0.0f) || (this->has_warm_white() && this->warm_white_ > 0.0f)) { if (!(color_mode & ColorCapability::COLD_WARM_WHITE)) { ESP_LOGW(TAG, "'%s': color mode does not support setting cold/warm white value", name); - this->cold_white_.reset(); - this->warm_white_.reset(); + this->set_flag_(FLAG_HAS_COLD_WHITE, false); + this->set_flag_(FLAG_HAS_WARM_WHITE, false); } } #define VALIDATE_RANGE_(name_, upper_name, min, max) \ - if (name_##_.has_value()) { \ - auto val = *name_##_; \ + if (this->has_##name_()) { \ + auto val = this->name_##_; \ if (val < (min) || val > (max)) { \ ESP_LOGW(TAG, "'%s': %s value %.2f is out of range [%.1f - %.1f]", name, LOG_STR_LITERAL(upper_name), val, \ (min), (max)); \ - name_##_ = clamp(val, (min), (max)); \ + this->name_##_ = clamp(val, (min), (max)); \ } \ } #define VALIDATE_RANGE(name, upper_name) VALIDATE_RANGE_(name, upper_name, 0.0f, 1.0f) @@ -227,110 +242,116 @@ LightColorValues LightCall::validate_() { VALIDATE_RANGE_(color_temperature, "Color temperature", traits.get_min_mireds(), traits.get_max_mireds()) // Flag whether an explicit turn off was requested, in which case we'll also stop the effect. - bool explicit_turn_off_request = this->state_.has_value() && !*this->state_; + bool explicit_turn_off_request = this->has_state() && !this->state_; // Turn off when brightness is set to zero, and reset brightness (so that it has nonzero brightness when turned on). - if (this->brightness_.has_value() && *this->brightness_ == 0.0f) { - this->state_ = optional(false); - this->brightness_ = optional(1.0f); + if (this->has_brightness() && this->brightness_ == 0.0f) { + this->state_ = false; + this->set_flag_(FLAG_HAS_STATE, true); + this->brightness_ = 1.0f; } // Set color brightness to 100% if currently zero and a color is set. - if (this->red_.has_value() || this->green_.has_value() || this->blue_.has_value()) { - if (!this->color_brightness_.has_value() && this->parent_->remote_values.get_color_brightness() == 0.0f) - this->color_brightness_ = optional(1.0f); + if (this->has_red() || this->has_green() || this->has_blue()) { + if (!this->has_color_brightness() && this->parent_->remote_values.get_color_brightness() == 0.0f) { + this->color_brightness_ = 1.0f; + this->set_flag_(FLAG_HAS_COLOR_BRIGHTNESS, true); + } } // Create color values for the light with this call applied. auto v = this->parent_->remote_values; - if (this->color_mode_.has_value()) - v.set_color_mode(*this->color_mode_); - if (this->state_.has_value()) - v.set_state(*this->state_); - if (this->brightness_.has_value()) - v.set_brightness(*this->brightness_); - if (this->color_brightness_.has_value()) - v.set_color_brightness(*this->color_brightness_); - if (this->red_.has_value()) - v.set_red(*this->red_); - if (this->green_.has_value()) - v.set_green(*this->green_); - if (this->blue_.has_value()) - v.set_blue(*this->blue_); - if (this->white_.has_value()) - v.set_white(*this->white_); - if (this->color_temperature_.has_value()) - v.set_color_temperature(*this->color_temperature_); - if (this->cold_white_.has_value()) - v.set_cold_white(*this->cold_white_); - if (this->warm_white_.has_value()) - v.set_warm_white(*this->warm_white_); + if (this->has_color_mode()) + v.set_color_mode(this->color_mode_); + if (this->has_state()) + v.set_state(this->state_); + if (this->has_brightness()) + v.set_brightness(this->brightness_); + if (this->has_color_brightness()) + v.set_color_brightness(this->color_brightness_); + if (this->has_red()) + v.set_red(this->red_); + if (this->has_green()) + v.set_green(this->green_); + if (this->has_blue()) + v.set_blue(this->blue_); + if (this->has_white()) + v.set_white(this->white_); + if (this->has_color_temperature()) + v.set_color_temperature(this->color_temperature_); + if (this->has_cold_white()) + v.set_cold_white(this->cold_white_); + if (this->has_warm_white()) + v.set_warm_white(this->warm_white_); v.normalize_color(); // Flash length check - if (this->has_flash_() && *this->flash_length_ == 0) { + if (this->has_flash_() && this->flash_length_ == 0) { ESP_LOGW(TAG, "'%s': flash length must be greater than zero", name); - this->flash_length_.reset(); + this->set_flag_(FLAG_HAS_FLASH, false); } // validate transition length/flash length/effect not used at the same time bool supports_transition = color_mode & ColorCapability::BRIGHTNESS; // If effect is already active, remove effect start - if (this->has_effect_() && *this->effect_ == this->parent_->active_effect_index_) { - this->effect_.reset(); + if (this->has_effect_() && this->effect_ == this->parent_->active_effect_index_) { + this->set_flag_(FLAG_HAS_EFFECT, false); } // validate effect index - if (this->has_effect_() && *this->effect_ > this->parent_->effects_.size()) { - ESP_LOGW(TAG, "'%s': invalid effect index %" PRIu32, name, *this->effect_); - this->effect_.reset(); + if (this->has_effect_() && this->effect_ > this->parent_->effects_.size()) { + ESP_LOGW(TAG, "'%s': invalid effect index %" PRIu32, name, this->effect_); + this->set_flag_(FLAG_HAS_EFFECT, false); } if (this->has_effect_() && (this->has_transition_() || this->has_flash_())) { ESP_LOGW(TAG, "'%s': effect cannot be used with transition/flash", name); - this->transition_length_.reset(); - this->flash_length_.reset(); + this->set_flag_(FLAG_HAS_TRANSITION, false); + this->set_flag_(FLAG_HAS_FLASH, false); } if (this->has_flash_() && this->has_transition_()) { ESP_LOGW(TAG, "'%s': flash cannot be used with transition", name); - this->transition_length_.reset(); + this->set_flag_(FLAG_HAS_TRANSITION, false); } - if (!this->has_transition_() && !this->has_flash_() && (!this->has_effect_() || *this->effect_ == 0) && + if (!this->has_transition_() && !this->has_flash_() && (!this->has_effect_() || this->effect_ == 0) && supports_transition) { // nothing specified and light supports transitions, set default transition length this->transition_length_ = this->parent_->default_transition_length_; + this->set_flag_(FLAG_HAS_TRANSITION, true); } - if (this->transition_length_.value_or(0) == 0) { + if (this->has_transition_() && this->transition_length_ == 0) { // 0 transition is interpreted as no transition (instant change) - this->transition_length_.reset(); + this->set_flag_(FLAG_HAS_TRANSITION, false); } if (this->has_transition_() && !supports_transition) { ESP_LOGW(TAG, "'%s': transitions not supported", name); - this->transition_length_.reset(); + this->set_flag_(FLAG_HAS_TRANSITION, false); } // If not a flash and turning the light off, then disable the light // Do not use light color values directly, so that effects can set 0% brightness // Reason: When user turns off the light in frontend, the effect should also stop - if (!this->has_flash_() && !this->state_.value_or(v.is_on())) { + bool target_state = this->has_state() ? this->state_ : v.is_on(); + if (!this->has_flash_() && !target_state) { if (this->has_effect_()) { ESP_LOGW(TAG, "'%s': cannot start effect when turning off", name); - this->effect_.reset(); + this->set_flag_(FLAG_HAS_EFFECT, false); } else if (this->parent_->active_effect_index_ != 0 && explicit_turn_off_request) { // Auto turn off effect this->effect_ = 0; + this->set_flag_(FLAG_HAS_EFFECT, true); } } // Disable saving for flashes if (this->has_flash_()) - this->save_ = false; + this->set_flag_(FLAG_SAVE, false); return v; } @@ -343,24 +364,27 @@ void LightCall::transform_parameters_() { // - RGBWW lights with color_interlock=true, which also sets "brightness" and // "color_temperature" (without color_interlock, CW/WW are set directly) // - Legacy Home Assistant (pre-colormode), which sets "white" and "color_temperature" - if (((this->white_.has_value() && *this->white_ > 0.0f) || this->color_temperature_.has_value()) && // - (*this->color_mode_ & ColorCapability::COLD_WARM_WHITE) && // - !(*this->color_mode_ & ColorCapability::WHITE) && // - !(*this->color_mode_ & ColorCapability::COLOR_TEMPERATURE) && // + if (((this->has_white() && this->white_ > 0.0f) || this->has_color_temperature()) && // + (this->color_mode_ & ColorCapability::COLD_WARM_WHITE) && // + !(this->color_mode_ & ColorCapability::WHITE) && // + !(this->color_mode_ & ColorCapability::COLOR_TEMPERATURE) && // traits.get_min_mireds() > 0.0f && traits.get_max_mireds() > 0.0f) { ESP_LOGD(TAG, "'%s': setting cold/warm white channels using white/color temperature values", this->parent_->get_name().c_str()); - if (this->color_temperature_.has_value()) { - const float color_temp = clamp(*this->color_temperature_, traits.get_min_mireds(), traits.get_max_mireds()); + if (this->has_color_temperature()) { + const float color_temp = clamp(this->color_temperature_, traits.get_min_mireds(), traits.get_max_mireds()); const float ww_fraction = (color_temp - traits.get_min_mireds()) / (traits.get_max_mireds() - traits.get_min_mireds()); const float cw_fraction = 1.0f - ww_fraction; const float max_cw_ww = std::max(ww_fraction, cw_fraction); this->cold_white_ = gamma_uncorrect(cw_fraction / max_cw_ww, this->parent_->get_gamma_correct()); this->warm_white_ = gamma_uncorrect(ww_fraction / max_cw_ww, this->parent_->get_gamma_correct()); + this->set_flag_(FLAG_HAS_COLD_WHITE, true); + this->set_flag_(FLAG_HAS_WARM_WHITE, true); } - if (this->white_.has_value()) { - this->brightness_ = *this->white_; + if (this->has_white()) { + this->brightness_ = this->white_; + this->set_flag_(FLAG_HAS_BRIGHTNESS, true); } } } @@ -378,7 +402,7 @@ ColorMode LightCall::compute_color_mode_() { // Don't change if the light is being turned off. ColorMode current_mode = this->parent_->remote_values.get_color_mode(); - if (this->state_.has_value() && !*this->state_) + if (this->has_state() && !this->state_) return current_mode; // If no color mode is specified, we try to guess the color mode. This is needed for backward compatibility to @@ -411,12 +435,12 @@ ColorMode LightCall::compute_color_mode_() { return color_mode; } std::set LightCall::get_suitable_color_modes_() { - bool has_white = this->white_.has_value() && *this->white_ > 0.0f; - bool has_ct = this->color_temperature_.has_value(); - bool has_cwww = (this->cold_white_.has_value() && *this->cold_white_ > 0.0f) || - (this->warm_white_.has_value() && *this->warm_white_ > 0.0f); - bool has_rgb = (this->color_brightness_.has_value() && *this->color_brightness_ > 0.0f) || - (this->red_.has_value() || this->green_.has_value() || this->blue_.has_value()); + bool has_white = this->has_white() && this->white_ > 0.0f; + bool has_ct = this->has_color_temperature(); + bool has_cwww = + (this->has_cold_white() && this->cold_white_ > 0.0f) || (this->has_warm_white() && this->warm_white_ > 0.0f); + bool has_rgb = (this->has_color_brightness() && this->color_brightness_ > 0.0f) || + (this->has_red() || this->has_green() || this->has_blue()); #define KEY(white, ct, cwww, rgb) ((white) << 0 | (ct) << 1 | (cwww) << 2 | (rgb) << 3) #define ENTRY(white, ct, cwww, rgb, ...) \ @@ -491,7 +515,7 @@ LightCall &LightCall::from_light_color_values(const LightColorValues &values) { return *this; } ColorMode LightCall::get_active_color_mode_() { - return this->color_mode_.value_or(this->parent_->remote_values.get_color_mode()); + return this->has_color_mode() ? this->color_mode_ : this->parent_->remote_values.get_color_mode(); } LightCall &LightCall::set_transition_length_if_supported(uint32_t transition_length) { if (this->get_active_color_mode_() & ColorCapability::BRIGHTNESS) @@ -505,7 +529,7 @@ LightCall &LightCall::set_brightness_if_supported(float brightness) { } LightCall &LightCall::set_color_mode_if_supported(ColorMode color_mode) { if (this->parent_->get_traits().supports_color_mode(color_mode)) - this->color_mode_ = color_mode; + this->set_color_mode(color_mode); return *this; } LightCall &LightCall::set_color_brightness_if_supported(float brightness) { @@ -549,110 +573,19 @@ LightCall &LightCall::set_warm_white_if_supported(float warm_white) { this->set_warm_white(warm_white); return *this; } -LightCall &LightCall::set_state(optional state) { - this->state_ = state; - return *this; -} -LightCall &LightCall::set_state(bool state) { - this->state_ = state; - return *this; -} -LightCall &LightCall::set_transition_length(optional transition_length) { - this->transition_length_ = transition_length; - return *this; -} -LightCall &LightCall::set_transition_length(uint32_t transition_length) { - this->transition_length_ = transition_length; - return *this; -} -LightCall &LightCall::set_flash_length(optional flash_length) { - this->flash_length_ = flash_length; - return *this; -} -LightCall &LightCall::set_flash_length(uint32_t flash_length) { - this->flash_length_ = flash_length; - return *this; -} -LightCall &LightCall::set_brightness(optional brightness) { - this->brightness_ = brightness; - return *this; -} -LightCall &LightCall::set_brightness(float brightness) { - this->brightness_ = brightness; - return *this; -} -LightCall &LightCall::set_color_mode(optional color_mode) { - this->color_mode_ = color_mode; - return *this; -} -LightCall &LightCall::set_color_mode(ColorMode color_mode) { - this->color_mode_ = color_mode; - return *this; -} -LightCall &LightCall::set_color_brightness(optional brightness) { - this->color_brightness_ = brightness; - return *this; -} -LightCall &LightCall::set_color_brightness(float brightness) { - this->color_brightness_ = brightness; - return *this; -} -LightCall &LightCall::set_red(optional red) { - this->red_ = red; - return *this; -} -LightCall &LightCall::set_red(float red) { - this->red_ = red; - return *this; -} -LightCall &LightCall::set_green(optional green) { - this->green_ = green; - return *this; -} -LightCall &LightCall::set_green(float green) { - this->green_ = green; - return *this; -} -LightCall &LightCall::set_blue(optional blue) { - this->blue_ = blue; - return *this; -} -LightCall &LightCall::set_blue(float blue) { - this->blue_ = blue; - return *this; -} -LightCall &LightCall::set_white(optional white) { - this->white_ = white; - return *this; -} -LightCall &LightCall::set_white(float white) { - this->white_ = white; - return *this; -} -LightCall &LightCall::set_color_temperature(optional color_temperature) { - this->color_temperature_ = color_temperature; - return *this; -} -LightCall &LightCall::set_color_temperature(float color_temperature) { - this->color_temperature_ = color_temperature; - return *this; -} -LightCall &LightCall::set_cold_white(optional cold_white) { - this->cold_white_ = cold_white; - return *this; -} -LightCall &LightCall::set_cold_white(float cold_white) { - this->cold_white_ = cold_white; - return *this; -} -LightCall &LightCall::set_warm_white(optional warm_white) { - this->warm_white_ = warm_white; - return *this; -} -LightCall &LightCall::set_warm_white(float warm_white) { - this->warm_white_ = warm_white; - return *this; -} +IMPLEMENT_LIGHT_CALL_SETTER(state, bool, FLAG_HAS_STATE) +IMPLEMENT_LIGHT_CALL_SETTER(transition_length, uint32_t, FLAG_HAS_TRANSITION) +IMPLEMENT_LIGHT_CALL_SETTER(flash_length, uint32_t, FLAG_HAS_FLASH) +IMPLEMENT_LIGHT_CALL_SETTER(brightness, float, FLAG_HAS_BRIGHTNESS) +IMPLEMENT_LIGHT_CALL_SETTER(color_mode, ColorMode, FLAG_HAS_COLOR_MODE) +IMPLEMENT_LIGHT_CALL_SETTER(color_brightness, float, FLAG_HAS_COLOR_BRIGHTNESS) +IMPLEMENT_LIGHT_CALL_SETTER(red, float, FLAG_HAS_RED) +IMPLEMENT_LIGHT_CALL_SETTER(green, float, FLAG_HAS_GREEN) +IMPLEMENT_LIGHT_CALL_SETTER(blue, float, FLAG_HAS_BLUE) +IMPLEMENT_LIGHT_CALL_SETTER(white, float, FLAG_HAS_WHITE) +IMPLEMENT_LIGHT_CALL_SETTER(color_temperature, float, FLAG_HAS_COLOR_TEMPERATURE) +IMPLEMENT_LIGHT_CALL_SETTER(cold_white, float, FLAG_HAS_COLD_WHITE) +IMPLEMENT_LIGHT_CALL_SETTER(warm_white, float, FLAG_HAS_WARM_WHITE) LightCall &LightCall::set_effect(optional effect) { if (effect.has_value()) this->set_effect(*effect); @@ -660,18 +593,22 @@ LightCall &LightCall::set_effect(optional effect) { } LightCall &LightCall::set_effect(uint32_t effect_number) { this->effect_ = effect_number; + this->set_flag_(FLAG_HAS_EFFECT, true); return *this; } LightCall &LightCall::set_effect(optional effect_number) { - this->effect_ = effect_number; + if (effect_number.has_value()) { + this->effect_ = effect_number.value(); + } + this->set_flag_(FLAG_HAS_EFFECT, effect_number.has_value()); return *this; } LightCall &LightCall::set_publish(bool publish) { - this->publish_ = publish; + this->set_flag_(FLAG_PUBLISH, publish); return *this; } LightCall &LightCall::set_save(bool save) { - this->save_ = save; + this->set_flag_(FLAG_SAVE, save); return *this; } LightCall &LightCall::set_rgb(float red, float green, float blue) { diff --git a/esphome/components/light/light_call.h b/esphome/components/light/light_call.h index bca2ac7b07..7e04e1a767 100644 --- a/esphome/components/light/light_call.h +++ b/esphome/components/light/light_call.h @@ -1,6 +1,5 @@ #pragma once -#include "esphome/core/optional.h" #include "light_color_values.h" #include @@ -10,6 +9,11 @@ namespace light { class LightState; /** This class represents a requested change in a light state. + * + * Light state changes are tracked using a bitfield flags_ to minimize memory usage. + * Each possible light property has a flag indicating whether it has been set. + * This design keeps LightCall at ~56 bytes to minimize heap fragmentation on + * ESP8266 and other memory-constrained devices. */ class LightCall { public: @@ -131,6 +135,19 @@ class LightCall { /// Set whether this light call should trigger a save state to recover them at startup.. LightCall &set_save(bool save); + // Getter methods to check if values are set + bool has_state() const { return (flags_ & FLAG_HAS_STATE) != 0; } + bool has_brightness() const { return (flags_ & FLAG_HAS_BRIGHTNESS) != 0; } + bool has_color_brightness() const { return (flags_ & FLAG_HAS_COLOR_BRIGHTNESS) != 0; } + bool has_red() const { return (flags_ & FLAG_HAS_RED) != 0; } + bool has_green() const { return (flags_ & FLAG_HAS_GREEN) != 0; } + bool has_blue() const { return (flags_ & FLAG_HAS_BLUE) != 0; } + bool has_white() const { return (flags_ & FLAG_HAS_WHITE) != 0; } + bool has_color_temperature() const { return (flags_ & FLAG_HAS_COLOR_TEMPERATURE) != 0; } + bool has_cold_white() const { return (flags_ & FLAG_HAS_COLD_WHITE) != 0; } + bool has_warm_white() const { return (flags_ & FLAG_HAS_WARM_WHITE) != 0; } + bool has_color_mode() const { return (flags_ & FLAG_HAS_COLOR_MODE) != 0; } + /** Set the RGB color of the light by RGB values. * * Please note that this only changes the color of the light, not the brightness. @@ -170,27 +187,62 @@ class LightCall { /// Some color modes also can be set using non-native parameters, transform those calls. void transform_parameters_(); - bool has_transition_() { return this->transition_length_.has_value(); } - bool has_flash_() { return this->flash_length_.has_value(); } - bool has_effect_() { return this->effect_.has_value(); } + // Bitfield flags - each flag indicates whether a corresponding value has been set. + enum FieldFlags : uint16_t { + FLAG_HAS_STATE = 1 << 0, + FLAG_HAS_TRANSITION = 1 << 1, + FLAG_HAS_FLASH = 1 << 2, + FLAG_HAS_EFFECT = 1 << 3, + FLAG_HAS_BRIGHTNESS = 1 << 4, + FLAG_HAS_COLOR_BRIGHTNESS = 1 << 5, + FLAG_HAS_RED = 1 << 6, + FLAG_HAS_GREEN = 1 << 7, + FLAG_HAS_BLUE = 1 << 8, + FLAG_HAS_WHITE = 1 << 9, + FLAG_HAS_COLOR_TEMPERATURE = 1 << 10, + FLAG_HAS_COLD_WHITE = 1 << 11, + FLAG_HAS_WARM_WHITE = 1 << 12, + FLAG_HAS_COLOR_MODE = 1 << 13, + FLAG_PUBLISH = 1 << 14, + FLAG_SAVE = 1 << 15, + }; + + bool has_transition_() { return (this->flags_ & FLAG_HAS_TRANSITION) != 0; } + bool has_flash_() { return (this->flags_ & FLAG_HAS_FLASH) != 0; } + bool has_effect_() { return (this->flags_ & FLAG_HAS_EFFECT) != 0; } + bool get_publish_() { return (this->flags_ & FLAG_PUBLISH) != 0; } + bool get_save_() { return (this->flags_ & FLAG_SAVE) != 0; } + + // Helper to set flag + void set_flag_(FieldFlags flag, bool value) { + if (value) { + this->flags_ |= flag; + } else { + this->flags_ &= ~flag; + } + } LightState *parent_; - optional state_; - optional transition_length_; - optional flash_length_; - optional color_mode_; - optional brightness_; - optional color_brightness_; - optional red_; - optional green_; - optional blue_; - optional white_; - optional color_temperature_; - optional cold_white_; - optional warm_white_; - optional effect_; - bool publish_{true}; - bool save_{true}; + + // Light state values - use flags_ to check if a value has been set. + // Group 4-byte aligned members first + uint32_t transition_length_; + uint32_t flash_length_; + uint32_t effect_; + float brightness_; + float color_brightness_; + float red_; + float green_; + float blue_; + float white_; + float color_temperature_; + float cold_white_; + float warm_white_; + + // Smaller members at the end for better packing + uint16_t flags_{FLAG_PUBLISH | FLAG_SAVE}; // Tracks which values are set + ColorMode color_mode_; + bool state_; }; } // namespace light diff --git a/esphome/components/light/light_color_values.h b/esphome/components/light/light_color_values.h index d8eaa6ae24..5653a8d2a5 100644 --- a/esphome/components/light/light_color_values.h +++ b/esphome/components/light/light_color_values.h @@ -46,8 +46,7 @@ class LightColorValues { public: /// Construct the LightColorValues with all attributes enabled, but state set to off. LightColorValues() - : color_mode_(ColorMode::UNKNOWN), - state_(0.0f), + : state_(0.0f), brightness_(1.0f), color_brightness_(1.0f), red_(1.0f), @@ -56,7 +55,8 @@ class LightColorValues { white_(1.0f), color_temperature_{0.0f}, cold_white_{1.0f}, - warm_white_{1.0f} {} + warm_white_{1.0f}, + color_mode_(ColorMode::UNKNOWN) {} LightColorValues(ColorMode color_mode, float state, float brightness, float color_brightness, float red, float green, float blue, float white, float color_temperature, float cold_white, float warm_white) { @@ -292,7 +292,6 @@ class LightColorValues { void set_warm_white(float warm_white) { this->warm_white_ = clamp(warm_white, 0.0f, 1.0f); } protected: - ColorMode color_mode_; float state_; ///< ON / OFF, float for transition float brightness_; float color_brightness_; @@ -303,6 +302,7 @@ class LightColorValues { float color_temperature_; ///< Color Temperature in Mired float cold_white_; float warm_white_; + ColorMode color_mode_; }; } // namespace light diff --git a/esphome/components/light/light_state.h b/esphome/components/light/light_state.h index f21fb8a06e..72cb99223e 100644 --- a/esphome/components/light/light_state.h +++ b/esphome/components/light/light_state.h @@ -31,9 +31,7 @@ enum LightRestoreMode : uint8_t { struct LightStateRTCState { LightStateRTCState(ColorMode color_mode, bool state, float brightness, float color_brightness, float red, float green, float blue, float white, float color_temp, float cold_white, float warm_white) - : color_mode(color_mode), - state(state), - brightness(brightness), + : brightness(brightness), color_brightness(color_brightness), red(red), green(green), @@ -41,10 +39,12 @@ struct LightStateRTCState { white(white), color_temp(color_temp), cold_white(cold_white), - warm_white(warm_white) {} + warm_white(warm_white), + effect(0), + color_mode(color_mode), + state(state) {} LightStateRTCState() = default; - ColorMode color_mode{ColorMode::UNKNOWN}; - bool state{false}; + // Group 4-byte aligned members first float brightness{1.0f}; float color_brightness{1.0f}; float red{1.0f}; @@ -55,6 +55,9 @@ struct LightStateRTCState { float cold_white{1.0f}; float warm_white{1.0f}; uint32_t effect{0}; + // Group smaller members at the end + ColorMode color_mode{ColorMode::UNKNOWN}; + bool state{false}; }; /** This class represents the communication layer between the front-end MQTT layer and the @@ -216,6 +219,8 @@ class LightState : public EntityBase, public Component { std::unique_ptr transformer_{nullptr}; /// List of effects for this light. std::vector effects_; + /// Object used to store the persisted values of the light. + ESPPreferenceObject rtc_; /// Value for storing the index of the currently active effect. 0 if no effect is active uint32_t active_effect_index_{}; /// Default transition length for all transitions in ms. @@ -224,15 +229,11 @@ class LightState : public EntityBase, public Component { uint32_t flash_transition_length_{}; /// Gamma correction factor for the light. float gamma_correct_{}; - /// Whether the light value should be written in the next cycle. bool next_write_{true}; // for effects, true if a transformer (transition) is active. bool is_transformer_active_ = false; - /// Object used to store the persisted values of the light. - ESPPreferenceObject rtc_; - /** Callback to call when new values for the frontend are available. * * "Remote values" are light color values that are reported to the frontend and have a lower diff --git a/esphome/components/light/transformers.h b/esphome/components/light/transformers.h index a557bd39b1..8d49acff97 100644 --- a/esphome/components/light/transformers.h +++ b/esphome/components/light/transformers.h @@ -59,9 +59,9 @@ class LightTransitionTransformer : public LightTransformer { // transition from 0 to 1 on x = [0, 1] static float smoothed_progress(float x) { return x * x * x * (x * (x * 6.0f - 15.0f) + 10.0f); } - bool changing_color_mode_{false}; LightColorValues end_values_{}; LightColorValues intermediate_values_{}; + bool changing_color_mode_{false}; }; class LightFlashTransformer : public LightTransformer { @@ -117,8 +117,8 @@ class LightFlashTransformer : public LightTransformer { protected: LightState &state_; - uint32_t transition_length_; std::unique_ptr transformer_{nullptr}; + uint32_t transition_length_; bool begun_lightstate_restore_; }; diff --git a/esphome/components/logger/__init__.py b/esphome/components/logger/__init__.py index 3d4907aa6e..9ac2999696 100644 --- a/esphome/components/logger/__init__.py +++ b/esphome/components/logger/__init__.py @@ -21,6 +21,7 @@ from esphome.components.libretiny.const import ( COMPONENT_LN882X, COMPONENT_RTL87XX, ) +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_ARGS, @@ -42,6 +43,7 @@ from esphome.const import ( PLATFORM_LN882X, PLATFORM_RP2040, PLATFORM_RTL87XX, + PlatformFramework, ) from esphome.core import CORE, Lambda, coroutine_with_priority @@ -444,3 +446,25 @@ async def logger_set_level_to_code(config, action_id, template_arg, args): lambda_ = await cg.process_lambda(Lambda(text), args, return_type=cg.void) return cg.new_Pvariable(action_id, template_arg, lambda_) + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "logger_esp32.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + "logger_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "logger_host.cpp": {PlatformFramework.HOST_NATIVE}, + "logger_rp2040.cpp": {PlatformFramework.RP2040_ARDUINO}, + "logger_libretiny.cpp": { + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + "task_log_buffer.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + } +) diff --git a/esphome/components/logger/logger.cpp b/esphome/components/logger/logger.cpp index a2c2aa0320..db807f7e53 100644 --- a/esphome/components/logger/logger.cpp +++ b/esphome/components/logger/logger.cpp @@ -90,6 +90,25 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch #ifdef USE_STORE_LOG_STR_IN_FLASH // Implementation for ESP8266 with flash string support. // Note: USE_STORE_LOG_STR_IN_FLASH is only defined for ESP8266. +// +// This function handles format strings stored in flash memory (PROGMEM) to save RAM. +// The buffer is used in a special way to avoid allocating extra memory: +// +// Memory layout during execution: +// Step 1: Copy format string from flash to buffer +// tx_buffer_: [format_string][null][.....................] +// tx_buffer_at_: ------------------^ +// msg_start: saved here -----------^ +// +// Step 2: format_log_to_buffer_with_terminator_ reads format string from beginning +// and writes formatted output starting at msg_start position +// tx_buffer_: [format_string][null][formatted_message][null] +// tx_buffer_at_: -------------------------------------^ +// +// Step 3: Output the formatted message (starting at msg_start) +// write_msg_ and callbacks receive: this->tx_buffer_ + msg_start +// which points to: [formatted_message][null] +// void Logger::log_vprintf_(uint8_t level, const char *tag, int line, const __FlashStringHelper *format, va_list args) { // NOLINT if (level > this->level_for(tag) || global_recursion_guard_) @@ -121,7 +140,9 @@ void Logger::log_vprintf_(uint8_t level, const char *tag, int line, const __Flas if (this->baud_rate_ > 0) { this->write_msg_(this->tx_buffer_ + msg_start); } - this->log_callback_.call(level, tag, this->tx_buffer_ + msg_start); + size_t msg_length = + this->tx_buffer_at_ - msg_start; // Don't subtract 1 - tx_buffer_at_ is already at the null terminator position + this->log_callback_.call(level, tag, this->tx_buffer_ + msg_start, msg_length); global_recursion_guard_ = false; } @@ -185,7 +206,8 @@ void Logger::loop() { this->tx_buffer_size_); this->write_footer_to_buffer_(this->tx_buffer_, &this->tx_buffer_at_, this->tx_buffer_size_); this->tx_buffer_[this->tx_buffer_at_] = '\0'; - this->log_callback_.call(message->level, message->tag, this->tx_buffer_); + size_t msg_len = this->tx_buffer_at_; // We already know the length from tx_buffer_at_ + this->log_callback_.call(message->level, message->tag, this->tx_buffer_, msg_len); // At this point all the data we need from message has been transferred to the tx_buffer // so we can release the message to allow other tasks to use it as soon as possible. this->log_buffer_->release_message_main_loop(received_token); @@ -214,7 +236,7 @@ void Logger::set_log_level(const std::string &tag, uint8_t log_level) { this->lo UARTSelection Logger::get_uart() const { return this->uart_; } #endif -void Logger::add_on_log_callback(std::function &&callback) { +void Logger::add_on_log_callback(std::function &&callback) { this->log_callback_.add(std::move(callback)); } float Logger::get_setup_priority() const { return setup_priority::BUS + 500.0f; } diff --git a/esphome/components/logger/logger.h b/esphome/components/logger/logger.h index 38faf73d84..fb68e75a51 100644 --- a/esphome/components/logger/logger.h +++ b/esphome/components/logger/logger.h @@ -143,7 +143,7 @@ class Logger : public Component { inline uint8_t level_for(const char *tag); /// Register a callback that will be called for every log message sent - void add_on_log_callback(std::function &&callback); + void add_on_log_callback(std::function &&callback); // add a listener for log level changes void add_listener(std::function &&callback) { this->level_callback_.add(std::move(callback)); } @@ -192,7 +192,7 @@ class Logger : public Component { if (this->baud_rate_ > 0) { this->write_msg_(this->tx_buffer_); // If logging is enabled, write to console } - this->log_callback_.call(level, tag, this->tx_buffer_); + this->log_callback_.call(level, tag, this->tx_buffer_, this->tx_buffer_at_); } // Write the body of the log message to the buffer @@ -246,7 +246,7 @@ class Logger : public Component { // Large objects (internally aligned) std::map log_levels_{}; - CallbackManager log_callback_{}; + CallbackManager log_callback_{}; CallbackManager level_callback_{}; #ifdef USE_ESPHOME_TASK_LOG_BUFFER std::unique_ptr log_buffer_; // Will be initialized with init_log_buffer @@ -355,7 +355,7 @@ class Logger : public Component { } inline void HOT write_footer_to_buffer_(char *buffer, uint16_t *buffer_at, uint16_t buffer_size) { - static const uint16_t RESET_COLOR_LEN = strlen(ESPHOME_LOG_RESET_COLOR); + static constexpr uint16_t RESET_COLOR_LEN = sizeof(ESPHOME_LOG_RESET_COLOR) - 1; this->write_body_to_buffer_(ESPHOME_LOG_RESET_COLOR, RESET_COLOR_LEN, buffer, buffer_at, buffer_size); } @@ -385,7 +385,7 @@ class LoggerMessageTrigger : public Trigger public: explicit LoggerMessageTrigger(Logger *parent, uint8_t level) { this->level_ = level; - parent->add_on_log_callback([this](uint8_t level, const char *tag, const char *message) { + parent->add_on_log_callback([this](uint8_t level, const char *tag, const char *message, size_t message_len) { if (level <= this->level_) { this->trigger(level, tag, message); } diff --git a/esphome/components/logger/logger_esp32.cpp b/esphome/components/logger/logger_esp32.cpp index 41445fa3b4..2fde0f7d49 100644 --- a/esphome/components/logger/logger_esp32.cpp +++ b/esphome/components/logger/logger_esp32.cpp @@ -184,7 +184,9 @@ void HOT Logger::write_msg_(const char *msg) { ) { puts(msg); } else { - uart_write_bytes(this->uart_num_, msg, strlen(msg)); + // Use tx_buffer_at_ if msg points to tx_buffer_, otherwise fall back to strlen + size_t len = (msg == this->tx_buffer_) ? this->tx_buffer_at_ : strlen(msg); + uart_write_bytes(this->uart_num_, msg, len); uart_write_bytes(this->uart_num_, "\n", 1); } } diff --git a/esphome/components/mdns/__init__.py b/esphome/components/mdns/__init__.py index ed230d43aa..e32d39cede 100644 --- a/esphome/components/mdns/__init__.py +++ b/esphome/components/mdns/__init__.py @@ -1,5 +1,6 @@ import esphome.codegen as cg from esphome.components.esp32 import add_idf_component +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_DISABLED, @@ -8,6 +9,7 @@ from esphome.const import ( CONF_PROTOCOL, CONF_SERVICE, CONF_SERVICES, + PlatformFramework, ) from esphome.core import CORE, coroutine_with_priority @@ -108,3 +110,21 @@ async def to_code(config): ) cg.add(var.add_extra_service(exp)) + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "mdns_esp32.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + "mdns_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "mdns_host.cpp": {PlatformFramework.HOST_NATIVE}, + "mdns_rp2040.cpp": {PlatformFramework.RP2040_ARDUINO}, + "mdns_libretiny.cpp": { + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + } +) diff --git a/esphome/components/microphone/microphone.cpp b/esphome/components/microphone/microphone.cpp index b1289f3791..0fbb393fd2 100644 --- a/esphome/components/microphone/microphone.cpp +++ b/esphome/components/microphone/microphone.cpp @@ -5,17 +5,15 @@ namespace microphone { void Microphone::add_data_callback(std::function &)> &&data_callback) { std::function &)> mute_handled_callback = - [this, data_callback](const std::vector &data) { data_callback(this->silence_audio_(data)); }; + [this, data_callback](const std::vector &data) { + if (this->mute_state_) { + data_callback(std::vector(data.size(), 0)); + } else { + data_callback(data); + }; + }; this->data_callbacks_.add(std::move(mute_handled_callback)); } -std::vector Microphone::silence_audio_(std::vector data) { - if (this->mute_state_) { - std::memset((void *) data.data(), 0, data.size()); - } - - return data; -} - } // namespace microphone } // namespace esphome diff --git a/esphome/components/microphone/microphone.h b/esphome/components/microphone/microphone.h index ea4e979e20..fcf9822458 100644 --- a/esphome/components/microphone/microphone.h +++ b/esphome/components/microphone/microphone.h @@ -33,8 +33,6 @@ class Microphone { audio::AudioStreamInfo get_audio_stream_info() { return this->audio_stream_info_; } protected: - std::vector silence_audio_(std::vector data); - State state_{STATE_STOPPED}; bool mute_state_{false}; diff --git a/esphome/components/mqtt/__init__.py b/esphome/components/mqtt/__init__.py index f0d5a95d43..1a6fcabf42 100644 --- a/esphome/components/mqtt/__init__.py +++ b/esphome/components/mqtt/__init__.py @@ -5,6 +5,7 @@ from esphome.automation import Condition import esphome.codegen as cg from esphome.components import logger from esphome.components.esp32 import add_idf_sdkconfig_option +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_AVAILABILITY, @@ -54,6 +55,7 @@ from esphome.const import ( PLATFORM_BK72XX, PLATFORM_ESP32, PLATFORM_ESP8266, + PlatformFramework, ) from esphome.core import CORE, coroutine_with_priority @@ -596,3 +598,13 @@ async def mqtt_enable_to_code(config, action_id, template_arg, args): async def mqtt_disable_to_code(config, action_id, template_arg, args): paren = await cg.get_variable(config[CONF_ID]) return cg.new_Pvariable(action_id, template_arg, paren) + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "mqtt_backend_esp32.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + } +) diff --git a/esphome/components/mqtt/mqtt_backend_esp32.h b/esphome/components/mqtt/mqtt_backend_esp32.h index 3611caf554..a24e75eaf9 100644 --- a/esphome/components/mqtt/mqtt_backend_esp32.h +++ b/esphome/components/mqtt/mqtt_backend_esp32.h @@ -252,7 +252,7 @@ class MQTTBackendESP32 final : public MQTTBackend { #if defined(USE_MQTT_IDF_ENQUEUE) static void esphome_mqtt_task(void *params); EventPool mqtt_event_pool_; - LockFreeQueue mqtt_queue_; + NotifyingLockFreeQueue mqtt_queue_; TaskHandle_t task_handle_{nullptr}; bool enqueue_(MqttQueueTypeT type, const char *topic, int qos = 0, bool retain = false, const char *payload = NULL, size_t len = 0); diff --git a/esphome/components/mqtt/mqtt_client.cpp b/esphome/components/mqtt/mqtt_client.cpp index 20e0b4a499..ab7fd15a35 100644 --- a/esphome/components/mqtt/mqtt_client.cpp +++ b/esphome/components/mqtt/mqtt_client.cpp @@ -57,14 +57,15 @@ void MQTTClientComponent::setup() { }); #ifdef USE_LOGGER if (this->is_log_message_enabled() && logger::global_logger != nullptr) { - logger::global_logger->add_on_log_callback([this](int level, const char *tag, const char *message) { - if (level <= this->log_level_ && this->is_connected()) { - this->publish({.topic = this->log_message_.topic, - .payload = message, - .qos = this->log_message_.qos, - .retain = this->log_message_.retain}); - } - }); + logger::global_logger->add_on_log_callback( + [this](int level, const char *tag, const char *message, size_t message_len) { + if (level <= this->log_level_ && this->is_connected()) { + this->publish({.topic = this->log_message_.topic, + .payload = std::string(message, message_len), + .qos = this->log_message_.qos, + .retain = this->log_message_.retain}); + } + }); } #endif diff --git a/esphome/components/nextion/__init__.py b/esphome/components/nextion/__init__.py index fb75daf4ba..8adc49d68c 100644 --- a/esphome/components/nextion/__init__.py +++ b/esphome/components/nextion/__init__.py @@ -1,5 +1,7 @@ import esphome.codegen as cg from esphome.components import uart +from esphome.config_helpers import filter_source_files_from_platform +from esphome.const import PlatformFramework nextion_ns = cg.esphome_ns.namespace("nextion") Nextion = nextion_ns.class_("Nextion", cg.PollingComponent, uart.UARTDevice) @@ -8,3 +10,17 @@ nextion_ref = Nextion.operator("ref") CONF_NEXTION_ID = "nextion_id" CONF_PUBLISH_STATE = "publish_state" CONF_SEND_TO_NEXTION = "send_to_nextion" + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "nextion_upload_arduino.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP8266_ARDUINO, + PlatformFramework.RP2040_ARDUINO, + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + "nextion_upload_idf.cpp": {PlatformFramework.ESP32_IDF}, + } +) diff --git a/esphome/components/nextion/base_component.py b/esphome/components/nextion/base_component.py index 98dea4b513..392481e39a 100644 --- a/esphome/components/nextion/base_component.py +++ b/esphome/components/nextion/base_component.py @@ -11,6 +11,7 @@ CONF_AUTO_WAKE_ON_TOUCH = "auto_wake_on_touch" CONF_BACKGROUND_PRESSED_COLOR = "background_pressed_color" CONF_COMMAND_SPACING = "command_spacing" CONF_COMPONENT_NAME = "component_name" +CONF_DUMP_DEVICE_INFO = "dump_device_info" CONF_EXIT_REPARSE_ON_START = "exit_reparse_on_start" CONF_FONT_ID = "font_id" CONF_FOREGROUND_PRESSED_COLOR = "foreground_pressed_color" diff --git a/esphome/components/nextion/binary_sensor/nextion_binarysensor.cpp b/esphome/components/nextion/binary_sensor/nextion_binarysensor.cpp index b6d4cc3f23..3628ac2f63 100644 --- a/esphome/components/nextion/binary_sensor/nextion_binarysensor.cpp +++ b/esphome/components/nextion/binary_sensor/nextion_binarysensor.cpp @@ -44,7 +44,7 @@ void NextionBinarySensor::set_state(bool state, bool publish, bool send_to_nexti return; if (send_to_nextion) { - if (this->nextion_->is_sleeping() || !this->visible_) { + if (this->nextion_->is_sleeping() || !this->component_flags_.visible) { this->needs_to_send_update_ = true; } else { this->needs_to_send_update_ = false; diff --git a/esphome/components/nextion/display.py b/esphome/components/nextion/display.py index 0aa5efeba7..4254ae45fe 100644 --- a/esphome/components/nextion/display.py +++ b/esphome/components/nextion/display.py @@ -15,6 +15,7 @@ from . import Nextion, nextion_ns, nextion_ref from .base_component import ( CONF_AUTO_WAKE_ON_TOUCH, CONF_COMMAND_SPACING, + CONF_DUMP_DEVICE_INFO, CONF_EXIT_REPARSE_ON_START, CONF_MAX_COMMANDS_PER_LOOP, CONF_MAX_QUEUE_SIZE, @@ -57,6 +58,7 @@ CONFIG_SCHEMA = ( cv.positive_time_period_milliseconds, cv.Range(max=TimePeriod(milliseconds=255)), ), + cv.Optional(CONF_DUMP_DEVICE_INFO, default=False): cv.boolean, cv.Optional(CONF_EXIT_REPARSE_ON_START, default=False): cv.boolean, cv.Optional(CONF_MAX_COMMANDS_PER_LOOP): cv.uint16_t, cv.Optional(CONF_MAX_QUEUE_SIZE): cv.positive_int, @@ -95,7 +97,9 @@ CONFIG_SCHEMA = ( cv.Optional(CONF_SKIP_CONNECTION_HANDSHAKE, default=False): cv.boolean, cv.Optional(CONF_START_UP_PAGE): cv.uint8_t, cv.Optional(CONF_TFT_URL): cv.url, - cv.Optional(CONF_TOUCH_SLEEP_TIMEOUT): cv.int_range(min=3, max=65535), + cv.Optional(CONF_TOUCH_SLEEP_TIMEOUT): cv.Any( + 0, cv.int_range(min=3, max=65535) + ), cv.Optional(CONF_WAKE_UP_PAGE): cv.uint8_t, } ) @@ -167,13 +171,19 @@ async def to_code(config): cg.add(var.set_wake_up_page(config[CONF_WAKE_UP_PAGE])) if CONF_START_UP_PAGE in config: + cg.add_define("USE_NEXTION_CONF_START_UP_PAGE") cg.add(var.set_start_up_page(config[CONF_START_UP_PAGE])) cg.add(var.set_auto_wake_on_touch(config[CONF_AUTO_WAKE_ON_TOUCH])) - cg.add(var.set_exit_reparse_on_start(config[CONF_EXIT_REPARSE_ON_START])) + if config[CONF_DUMP_DEVICE_INFO]: + cg.add_define("USE_NEXTION_CONFIG_DUMP_DEVICE_INFO") - cg.add(var.set_skip_connection_handshake(config[CONF_SKIP_CONNECTION_HANDSHAKE])) + if config[CONF_EXIT_REPARSE_ON_START]: + cg.add_define("USE_NEXTION_CONFIG_EXIT_REPARSE_ON_START") + + if config[CONF_SKIP_CONNECTION_HANDSHAKE]: + cg.add_define("USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE") if max_commands_per_loop := config.get(CONF_MAX_COMMANDS_PER_LOOP): cg.add_define("USE_NEXTION_MAX_COMMANDS_PER_LOOP") diff --git a/esphome/components/nextion/nextion.cpp b/esphome/components/nextion/nextion.cpp index bb75385d8c..66e2d26061 100644 --- a/esphome/components/nextion/nextion.cpp +++ b/esphome/components/nextion/nextion.cpp @@ -11,28 +11,25 @@ static const char *const TAG = "nextion"; void Nextion::setup() { this->is_setup_ = false; - this->ignore_is_setup_ = true; + this->connection_state_.ignore_is_setup_ = true; - // Wake up the nextion - this->send_command_("bkcmd=0"); - this->send_command_("sleep=0"); + // Wake up the nextion and ensure clean communication state + this->send_command_("sleep=0"); // Exit sleep mode if sleeping + this->send_command_("bkcmd=0"); // Disable return data during init sequence - this->send_command_("bkcmd=0"); - this->send_command_("sleep=0"); - - // Reboot it + // Reset device for clean state - critical for reliable communication this->send_command_("rest"); - this->ignore_is_setup_ = false; + this->connection_state_.ignore_is_setup_ = false; } bool Nextion::send_command_(const std::string &command) { - if (!this->ignore_is_setup_ && !this->is_setup()) { + if (!this->connection_state_.ignore_is_setup_ && !this->is_setup()) { return false; } #ifdef USE_NEXTION_COMMAND_SPACING - if (!this->ignore_is_setup_ && !this->command_pacer_.can_send()) { + if (!this->connection_state_.ignore_is_setup_ && !this->command_pacer_.can_send()) { ESP_LOGN(TAG, "Command spacing: delaying command '%s'", command.c_str()); return false; } @@ -48,31 +45,26 @@ bool Nextion::send_command_(const std::string &command) { } bool Nextion::check_connect_() { - if (this->is_connected_) + if (this->connection_state_.is_connected_) return true; - // Check if the handshake should be skipped for the Nextion connection - if (this->skip_connection_handshake_) { - // Log the connection status without handshake - ESP_LOGW(TAG, "Connected (no handshake)"); - // Set the connection status to true - this->is_connected_ = true; - // Return true indicating the connection is set - return true; - } - +#ifdef USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE + ESP_LOGW(TAG, "Connected (no handshake)"); // Log the connection status without handshake + this->is_connected_ = true; // Set the connection status to true + return true; // Return true indicating the connection is set +#else // USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE if (this->comok_sent_ == 0) { this->reset_(false); - this->ignore_is_setup_ = true; + this->connection_state_.ignore_is_setup_ = true; this->send_command_("boguscommand=0"); // bogus command. needed sometimes after updating - if (this->exit_reparse_on_start_) { - this->send_command_("DRAKJHSUYDGBNCJHGJKSHBDN"); - } +#ifdef USE_NEXTION_CONFIG_EXIT_REPARSE_ON_START + this->send_command_("DRAKJHSUYDGBNCJHGJKSHBDN"); +#endif // USE_NEXTION_CONFIG_EXIT_REPARSE_ON_START this->send_command_("connect"); this->comok_sent_ = App.get_loop_component_start_time(); - this->ignore_is_setup_ = false; + this->connection_state_.ignore_is_setup_ = false; return false; } @@ -94,16 +86,16 @@ bool Nextion::check_connect_() { for (size_t i = 0; i < response.length(); i++) { ESP_LOGN(TAG, "resp: %s %d %d %c", response.c_str(), i, response[i], response[i]); } -#endif +#endif // NEXTION_PROTOCOL_LOG ESP_LOGW(TAG, "Not connected"); comok_sent_ = 0; return false; } - this->ignore_is_setup_ = true; + this->connection_state_.ignore_is_setup_ = true; ESP_LOGI(TAG, "Connected"); - this->is_connected_ = true; + this->connection_state_.is_connected_ = true; ESP_LOGN(TAG, "connect: %s", response.c_str()); @@ -118,18 +110,27 @@ bool Nextion::check_connect_() { this->is_detected_ = (connect_info.size() == 7); if (this->is_detected_) { ESP_LOGN(TAG, "Connect info: %zu", connect_info.size()); - +#ifdef USE_NEXTION_CONFIG_DUMP_DEVICE_INFO this->device_model_ = connect_info[2]; this->firmware_version_ = connect_info[3]; this->serial_number_ = connect_info[5]; this->flash_size_ = connect_info[6]; +#else // USE_NEXTION_CONFIG_DUMP_DEVICE_INFO + ESP_LOGI(TAG, + " Device Model: %s\n" + " FW Version: %s\n" + " Serial Number: %s\n" + " Flash Size: %s\n", + connect_info[2].c_str(), connect_info[3].c_str(), connect_info[5].c_str(), connect_info[6].c_str()); +#endif // USE_NEXTION_CONFIG_DUMP_DEVICE_INFO } else { ESP_LOGE(TAG, "Bad connect value: '%s'", response.c_str()); } - this->ignore_is_setup_ = false; + this->connection_state_.ignore_is_setup_ = false; this->dump_config(); return true; +#endif // USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE } void Nextion::reset_(bool reset_nextion) { @@ -144,36 +145,42 @@ void Nextion::reset_(bool reset_nextion) { void Nextion::dump_config() { ESP_LOGCONFIG(TAG, "Nextion:"); - if (this->skip_connection_handshake_) { - ESP_LOGCONFIG(TAG, " Skip handshake: %s", YESNO(this->skip_connection_handshake_)); - } else { - ESP_LOGCONFIG(TAG, - " Device Model: %s\n" - " FW Version: %s\n" - " Serial Number: %s\n" - " Flash Size: %s", - this->device_model_.c_str(), this->firmware_version_.c_str(), this->serial_number_.c_str(), - this->flash_size_.c_str()); - } + +#ifdef USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE + ESP_LOGCONFIG(TAG, " Skip handshake: YES"); +#else // USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE ESP_LOGCONFIG(TAG, +#ifdef USE_NEXTION_CONFIG_DUMP_DEVICE_INFO + " Device Model: %s\n" + " FW Version: %s\n" + " Serial Number: %s\n" + " Flash Size: %s\n" +#endif // USE_NEXTION_CONFIG_DUMP_DEVICE_INFO +#ifdef USE_NEXTION_CONFIG_EXIT_REPARSE_ON_START + " Exit reparse: YES\n" +#endif // USE_NEXTION_CONFIG_EXIT_REPARSE_ON_START " Wake On Touch: %s\n" - " Exit reparse: %s", - YESNO(this->auto_wake_on_touch_), YESNO(this->exit_reparse_on_start_)); + " Touch Timeout: %" PRIu16, +#ifdef USE_NEXTION_CONFIG_DUMP_DEVICE_INFO + this->device_model_.c_str(), this->firmware_version_.c_str(), this->serial_number_.c_str(), + this->flash_size_.c_str(), +#endif // USE_NEXTION_CONFIG_DUMP_DEVICE_INFO + YESNO(this->connection_state_.auto_wake_on_touch_), this->touch_sleep_timeout_); +#endif // USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE + #ifdef USE_NEXTION_MAX_COMMANDS_PER_LOOP ESP_LOGCONFIG(TAG, " Max commands per loop: %u", this->max_commands_per_loop_); #endif // USE_NEXTION_MAX_COMMANDS_PER_LOOP - if (this->touch_sleep_timeout_ != 0) { - ESP_LOGCONFIG(TAG, " Touch Timeout: %" PRIu16, this->touch_sleep_timeout_); + if (this->wake_up_page_ != 255) { + ESP_LOGCONFIG(TAG, " Wake Up Page: %u", this->wake_up_page_); } - if (this->wake_up_page_ != -1) { - ESP_LOGCONFIG(TAG, " Wake Up Page: %d", this->wake_up_page_); - } - - if (this->start_up_page_ != -1) { - ESP_LOGCONFIG(TAG, " Start Up Page: %d", this->start_up_page_); +#ifdef USE_NEXTION_CONF_START_UP_PAGE + if (this->start_up_page_ != 255) { + ESP_LOGCONFIG(TAG, " Start Up Page: %u", this->start_up_page_); } +#endif // USE_NEXTION_CONF_START_UP_PAGE #ifdef USE_NEXTION_COMMAND_SPACING ESP_LOGCONFIG(TAG, " Cmd spacing: %u ms", this->command_pacer_.get_spacing()); @@ -219,7 +226,7 @@ void Nextion::add_buffer_overflow_event_callback(std::function &&callbac } void Nextion::update_all_components() { - if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping()) + if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || this->is_sleeping()) return; for (auto *binarysensortype : this->binarysensortype_) { @@ -237,7 +244,7 @@ void Nextion::update_all_components() { } bool Nextion::send_command(const char *command) { - if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping()) + if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || this->is_sleeping()) return false; if (this->send_command_(command)) { @@ -248,7 +255,7 @@ bool Nextion::send_command(const char *command) { } bool Nextion::send_command_printf(const char *format, ...) { - if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping()) + if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || this->is_sleeping()) return false; char buffer[256]; @@ -289,40 +296,46 @@ void Nextion::print_queue_members_() { #endif void Nextion::loop() { - if (!this->check_connect_() || this->is_updating_) + if (!this->check_connect_() || this->connection_state_.is_updating_) return; - if (this->nextion_reports_is_setup_ && !this->sent_setup_commands_) { - this->ignore_is_setup_ = true; - this->sent_setup_commands_ = true; + if (this->connection_state_.nextion_reports_is_setup_ && !this->connection_state_.sent_setup_commands_) { + this->connection_state_.ignore_is_setup_ = true; + this->connection_state_.sent_setup_commands_ = true; this->send_command_("bkcmd=3"); // Always, returns 0x00 to 0x23 result of serial command. if (this->brightness_.has_value()) { this->set_backlight_brightness(this->brightness_.value()); } +#ifdef USE_NEXTION_CONF_START_UP_PAGE // Check if a startup page has been set and send the command - if (this->start_up_page_ >= 0) { + if (this->start_up_page_ != 255) { this->goto_page(this->start_up_page_); } +#endif // USE_NEXTION_CONF_START_UP_PAGE - if (this->wake_up_page_ >= 0) { + if (this->wake_up_page_ != 255) { this->set_wake_up_page(this->wake_up_page_); } - this->ignore_is_setup_ = false; + if (this->touch_sleep_timeout_ != 0) { + this->set_touch_sleep_timeout(this->touch_sleep_timeout_); + } + + this->connection_state_.ignore_is_setup_ = false; } this->process_serial_(); // Receive serial data this->process_nextion_commands_(); // Process nextion return commands - if (!this->nextion_reports_is_setup_) { + if (!this->connection_state_.nextion_reports_is_setup_) { if (this->started_ms_ == 0) this->started_ms_ = App.get_loop_component_start_time(); if (this->started_ms_ + this->startup_override_ms_ < App.get_loop_component_start_time()) { ESP_LOGD(TAG, "Manual ready set"); - this->nextion_reports_is_setup_ = true; + this->connection_state_.nextion_reports_is_setup_ = true; } } @@ -665,7 +678,7 @@ void Nextion::process_nextion_commands_() { case 0x88: // system successful start up { ESP_LOGD(TAG, "System start: %zu", to_process_length); - this->nextion_reports_is_setup_ = true; + this->connection_state_.nextion_reports_is_setup_ = true; break; } case 0x89: { // start SD card upgrade @@ -1048,7 +1061,7 @@ void Nextion::add_no_result_to_queue_(const std::string &variable_name) { * @param command */ void Nextion::add_no_result_to_queue_with_command_(const std::string &variable_name, const std::string &command) { - if ((!this->is_setup() && !this->ignore_is_setup_) || command.empty()) + if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || command.empty()) return; if (this->send_command_(command)) { @@ -1091,7 +1104,7 @@ void Nextion::add_no_result_to_queue_with_pending_command_(const std::string &va bool Nextion::add_no_result_to_queue_with_ignore_sleep_printf_(const std::string &variable_name, const char *format, ...) { - if ((!this->is_setup() && !this->ignore_is_setup_)) + if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_)) return false; char buffer[256]; @@ -1116,7 +1129,7 @@ bool Nextion::add_no_result_to_queue_with_ignore_sleep_printf_(const std::string * @param ... The format arguments */ bool Nextion::add_no_result_to_queue_with_printf_(const std::string &variable_name, const char *format, ...) { - if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping()) + if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || this->is_sleeping()) return false; char buffer[256]; @@ -1155,7 +1168,7 @@ void Nextion::add_no_result_to_queue_with_set(const std::string &variable_name, void Nextion::add_no_result_to_queue_with_set_internal_(const std::string &variable_name, const std::string &variable_name_to_send, int32_t state_value, bool is_sleep_safe) { - if ((!this->is_setup() && !this->ignore_is_setup_) || (!is_sleep_safe && this->is_sleeping())) + if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || (!is_sleep_safe && this->is_sleeping())) return; this->add_no_result_to_queue_with_ignore_sleep_printf_(variable_name, "%s=%" PRId32, variable_name_to_send.c_str(), @@ -1183,7 +1196,7 @@ void Nextion::add_no_result_to_queue_with_set(const std::string &variable_name, void Nextion::add_no_result_to_queue_with_set_internal_(const std::string &variable_name, const std::string &variable_name_to_send, const std::string &state_value, bool is_sleep_safe) { - if ((!this->is_setup() && !this->ignore_is_setup_) || (!is_sleep_safe && this->is_sleeping())) + if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || (!is_sleep_safe && this->is_sleeping())) return; this->add_no_result_to_queue_with_printf_(variable_name, "%s=\"%s\"", variable_name_to_send.c_str(), @@ -1200,7 +1213,7 @@ void Nextion::add_no_result_to_queue_with_set_internal_(const std::string &varia * @param component Pointer to the Nextion component that will handle the response. */ void Nextion::add_to_get_queue(NextionComponentBase *component) { - if ((!this->is_setup() && !this->ignore_is_setup_)) + if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_)) return; #ifdef USE_NEXTION_MAX_QUEUE_SIZE @@ -1240,7 +1253,7 @@ void Nextion::add_to_get_queue(NextionComponentBase *component) { * @param buffer_size The buffer data */ void Nextion::add_addt_command_to_queue(NextionComponentBase *component) { - if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping()) + if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || this->is_sleeping()) return; RAMAllocator allocator; @@ -1281,7 +1294,7 @@ void Nextion::set_writer(const nextion_writer_t &writer) { this->writer_ = write ESPDEPRECATED("set_wait_for_ack(bool) deprecated, no effect", "v1.20") void Nextion::set_wait_for_ack(bool wait_for_ack) { ESP_LOGE(TAG, "Deprecated"); } -bool Nextion::is_updating() { return this->is_updating_; } +bool Nextion::is_updating() { return this->connection_state_.is_updating_; } } // namespace nextion } // namespace esphome diff --git a/esphome/components/nextion/nextion.h b/esphome/components/nextion/nextion.h index 0b77d234f5..e2c4faa1d0 100644 --- a/esphome/components/nextion/nextion.h +++ b/esphome/components/nextion/nextion.h @@ -932,21 +932,6 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe */ void set_backlight_brightness(float brightness); - /** - * Sets whether the Nextion display should skip the connection handshake process. - * @param skip_handshake True or false. When skip_connection_handshake is true, - * the connection will be established without performing the handshake. - * This can be useful when using Nextion Simulator. - * - * Example: - * ```cpp - * it.set_skip_connection_handshake(true); - * ``` - * - * When set to true, the display will be marked as connected without performing a handshake. - */ - void set_skip_connection_handshake(bool skip_handshake) { this->skip_connection_handshake_ = skip_handshake; } - /** * Sets Nextion mode between sleep and awake * @param True or false. Sleep=true to enter sleep mode or sleep=false to exit sleep mode. @@ -1179,22 +1164,43 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe void update_components_by_prefix(const std::string &prefix); /** - * Set the touch sleep timeout of the display. - * @param timeout Timeout in seconds. + * Set the touch sleep timeout of the display using the `thsp` command. + * + * Sets internal No-touch-then-sleep timer to specified value in seconds. + * Nextion will auto-enter sleep mode if and when this timer expires. + * + * @param touch_sleep_timeout Timeout in seconds. + * Range: 3 to 65535 seconds (minimum 3 seconds, maximum ~18 hours 12 minutes 15 seconds) + * Use 0 to disable touch sleep timeout. + * + * @note Once `thsp` is set, it will persist until reboot or reset. The Nextion device + * needs to exit sleep mode to issue `thsp=0` to disable sleep on no touch. + * + * @note The display will only wake up by a restart or by setting up `thup` (auto wake on touch). + * See set_auto_wake_on_touch() to configure wake behavior. * * Example: * ```cpp + * // Set 30 second touch timeout * it.set_touch_sleep_timeout(30); + * + * // Set maximum timeout (~18 hours) + * it.set_touch_sleep_timeout(65535); + * + * // Disable touch sleep timeout + * it.set_touch_sleep_timeout(0); * ``` * - * After 30 seconds the display will go to sleep. Note: the display will only wakeup by a restart or by setting up - * `thup`. + * Related Nextion instruction: `thsp=` + * + * @see set_auto_wake_on_touch() Configure automatic wake on touch + * @see sleep() Manually control sleep state */ - void set_touch_sleep_timeout(uint16_t touch_sleep_timeout); + void set_touch_sleep_timeout(uint16_t touch_sleep_timeout = 0); /** * Sets which page Nextion loads when exiting sleep mode. Note this can be set even when Nextion is in sleep mode. - * @param wake_up_page The page id, from 0 to the last page in Nextion. Set -1 (not set to any existing page) to + * @param wake_up_page The page id, from 0 to the last page in Nextion. Set 255 (not set to any existing page) to * wakes up to current page. * * Example: @@ -1204,11 +1210,12 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe * * The display will wake up to page 2. */ - void set_wake_up_page(int16_t wake_up_page = -1); + void set_wake_up_page(uint8_t wake_up_page = 255); +#ifdef USE_NEXTION_CONF_START_UP_PAGE /** * Sets which page Nextion loads when connecting to ESPHome. - * @param start_up_page The page id, from 0 to the last page in Nextion. Set -1 (not set to any existing page) to + * @param start_up_page The page id, from 0 to the last page in Nextion. Set 255 (not set to any existing page) to * wakes up to current page. * * Example: @@ -1218,7 +1225,8 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe * * The display will go to page 2 when it establishes a connection to ESPHome. */ - void set_start_up_page(int16_t start_up_page = -1) { this->start_up_page_ = start_up_page; } + void set_start_up_page(uint8_t start_up_page = 255) { this->start_up_page_ = start_up_page; } +#endif // USE_NEXTION_CONF_START_UP_PAGE /** * Sets if Nextion should auto-wake from sleep when touch press occurs. @@ -1234,20 +1242,6 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe */ void set_auto_wake_on_touch(bool auto_wake_on_touch); - /** - * Sets if Nextion should exit the active reparse mode before the "connect" command is sent - * @param exit_reparse_on_start True or false. When exit_reparse_on_start is true, the exit reparse command - * will be sent before requesting the connection from Nextion. - * - * Example: - * ```cpp - * it.set_exit_reparse_on_start(true); - * ``` - * - * The display will be requested to leave active reparse mode before setup. - */ - void set_exit_reparse_on_start(bool exit_reparse_on_start) { this->exit_reparse_on_start_ = exit_reparse_on_start; } - /** * @brief Retrieves the number of commands pending in the Nextion command queue. * @@ -1290,7 +1284,7 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe * the Nextion display. A connection is considered established when: * * - The initial handshake with the display is completed successfully, or - * - The handshake is skipped via skip_connection_handshake_ flag + * - The handshake is skipped via USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE flag * * The connection status is particularly useful when: * - Troubleshooting communication issues @@ -1300,7 +1294,7 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe * @return true if the Nextion display is connected and ready to receive commands * @return false if the display is not yet connected or connection was lost */ - bool is_connected() { return this->is_connected_; } + bool is_connected() { return this->connection_state_.is_connected_; } protected: #ifdef USE_NEXTION_MAX_COMMANDS_PER_LOOP @@ -1334,21 +1328,29 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe bool remove_from_q_(bool report_empty = true); /** - * @brief - * Sends commands ignoring of the Nextion has been setup. + * @brief Status flags for Nextion display state management + * + * Uses bitfields to pack multiple boolean states into a single byte, + * saving 5 bytes of RAM compared to individual bool variables. */ - bool ignore_is_setup_ = false; + struct { + uint8_t is_connected_ : 1; ///< Connection established with Nextion display + uint8_t sent_setup_commands_ : 1; ///< Initial setup commands have been sent + uint8_t ignore_is_setup_ : 1; ///< Temporarily ignore setup state for special operations + uint8_t nextion_reports_is_setup_ : 1; ///< Nextion has reported successful initialization + uint8_t is_updating_ : 1; ///< TFT firmware update is currently in progress + uint8_t auto_wake_on_touch_ : 1; ///< Display should wake automatically on touch (default: true) + uint8_t reserved_ : 2; ///< Reserved bits for future flag additions + } connection_state_{}; ///< Zero-initialized status flags (all start as false) - bool nextion_reports_is_setup_ = false; void process_nextion_commands_(); void process_serial_(); - bool is_updating_ = false; uint16_t touch_sleep_timeout_ = 0; - int16_t wake_up_page_ = -1; - int16_t start_up_page_ = -1; + uint8_t wake_up_page_ = 255; +#ifdef USE_NEXTION_CONF_START_UP_PAGE + uint8_t start_up_page_ = 255; +#endif // USE_NEXTION_CONF_START_UP_PAGE bool auto_wake_on_touch_ = true; - bool exit_reparse_on_start_ = false; - bool skip_connection_handshake_ = false; /** * Manually send a raw command to the display and don't wait for an acknowledgement packet. @@ -1455,10 +1457,12 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe optional writer_; optional brightness_; +#ifdef USE_NEXTION_CONFIG_DUMP_DEVICE_INFO std::string device_model_; std::string firmware_version_; std::string serial_number_; std::string flash_size_; +#endif // USE_NEXTION_CONFIG_DUMP_DEVICE_INFO void remove_front_no_sensors_(); @@ -1468,11 +1472,9 @@ class Nextion : public NextionBase, public PollingComponent, public uart::UARTDe void reset_(bool reset_nextion = true); std::string command_data_; - bool is_connected_ = false; const uint16_t startup_override_ms_ = 8000; const uint16_t max_q_age_ms_ = 8000; uint32_t started_ms_ = 0; - bool sent_setup_commands_ = false; }; } // namespace nextion diff --git a/esphome/components/nextion/nextion_commands.cpp b/esphome/components/nextion/nextion_commands.cpp index 84aacd1868..f3a282717b 100644 --- a/esphome/components/nextion/nextion_commands.cpp +++ b/esphome/components/nextion/nextion_commands.cpp @@ -10,19 +10,20 @@ static const char *const TAG = "nextion"; // Sleep safe commands void Nextion::soft_reset() { this->send_command_("rest"); } -void Nextion::set_wake_up_page(int16_t wake_up_page) { +void Nextion::set_wake_up_page(uint8_t wake_up_page) { this->wake_up_page_ = wake_up_page; this->add_no_result_to_queue_with_set_internal_("wake_up_page", "wup", wake_up_page, true); } -void Nextion::set_touch_sleep_timeout(uint16_t touch_sleep_timeout) { - if (touch_sleep_timeout < 3) { - ESP_LOGD(TAG, "Sleep timeout out of bounds (3-65535)"); - return; +void Nextion::set_touch_sleep_timeout(const uint16_t touch_sleep_timeout) { + // Validate range: Nextion thsp command requires min 3, max 65535 seconds (0 disables) + if (touch_sleep_timeout != 0 && touch_sleep_timeout < 3) { + this->touch_sleep_timeout_ = 3; // Auto-correct to minimum valid value + } else { + this->touch_sleep_timeout_ = touch_sleep_timeout; } - this->touch_sleep_timeout_ = touch_sleep_timeout; - this->add_no_result_to_queue_with_set_internal_("touch_sleep_timeout", "thsp", touch_sleep_timeout, true); + this->add_no_result_to_queue_with_set_internal_("touch_sleep_timeout", "thsp", this->touch_sleep_timeout_, true); } void Nextion::sleep(bool sleep) { @@ -38,7 +39,7 @@ void Nextion::sleep(bool sleep) { // Protocol reparse mode bool Nextion::set_protocol_reparse_mode(bool active_mode) { ESP_LOGV(TAG, "Reparse mode: %s", YESNO(active_mode)); - this->ignore_is_setup_ = true; // if not in reparse mode setup will fail, so it should be ignored + this->connection_state_.ignore_is_setup_ = true; // if not in reparse mode setup will fail, so it should be ignored bool all_commands_sent = true; if (active_mode) { // Sets active protocol reparse mode all_commands_sent &= this->send_command_("recmod=1"); @@ -48,10 +49,10 @@ bool Nextion::set_protocol_reparse_mode(bool active_mode) { all_commands_sent &= this->send_command_("recmod=0"); // Sending recmode=0 twice is recommended all_commands_sent &= this->send_command_("recmod=0"); } - if (!this->nextion_reports_is_setup_) { // No need to connect if is already setup + if (!this->connection_state_.nextion_reports_is_setup_) { // No need to connect if is already setup all_commands_sent &= this->send_command_("connect"); } - this->ignore_is_setup_ = false; + this->connection_state_.ignore_is_setup_ = false; return all_commands_sent; } @@ -191,7 +192,7 @@ void Nextion::set_backlight_brightness(float brightness) { } void Nextion::set_auto_wake_on_touch(bool auto_wake_on_touch) { - this->auto_wake_on_touch_ = auto_wake_on_touch; + this->connection_state_.auto_wake_on_touch_ = auto_wake_on_touch; this->add_no_result_to_queue_with_set("auto_wake_on_touch", "thup", auto_wake_on_touch ? 1 : 0); } diff --git a/esphome/components/nextion/nextion_component.cpp b/esphome/components/nextion/nextion_component.cpp index cfb4e3600c..32929d6845 100644 --- a/esphome/components/nextion/nextion_component.cpp +++ b/esphome/components/nextion/nextion_component.cpp @@ -8,8 +8,8 @@ void NextionComponent::set_background_color(Color bco) { return; // This is a variable. no need to set color } this->bco_ = bco; - this->bco_needs_update_ = true; - this->bco_is_set_ = true; + this->component_flags_.bco_needs_update = true; + this->component_flags_.bco_is_set = true; this->update_component_settings(); } @@ -19,8 +19,8 @@ void NextionComponent::set_background_pressed_color(Color bco2) { } this->bco2_ = bco2; - this->bco2_needs_update_ = true; - this->bco2_is_set_ = true; + this->component_flags_.bco2_needs_update = true; + this->component_flags_.bco2_is_set = true; this->update_component_settings(); } @@ -29,8 +29,8 @@ void NextionComponent::set_foreground_color(Color pco) { return; // This is a variable. no need to set color } this->pco_ = pco; - this->pco_needs_update_ = true; - this->pco_is_set_ = true; + this->component_flags_.pco_needs_update = true; + this->component_flags_.pco_is_set = true; this->update_component_settings(); } @@ -39,8 +39,8 @@ void NextionComponent::set_foreground_pressed_color(Color pco2) { return; // This is a variable. no need to set color } this->pco2_ = pco2; - this->pco2_needs_update_ = true; - this->pco2_is_set_ = true; + this->component_flags_.pco2_needs_update = true; + this->component_flags_.pco2_is_set = true; this->update_component_settings(); } @@ -49,8 +49,8 @@ void NextionComponent::set_font_id(uint8_t font_id) { return; // This is a variable. no need to set color } this->font_id_ = font_id; - this->font_id_needs_update_ = true; - this->font_id_is_set_ = true; + this->component_flags_.font_id_needs_update = true; + this->component_flags_.font_id_is_set = true; this->update_component_settings(); } @@ -58,20 +58,20 @@ void NextionComponent::set_visible(bool visible) { if (this->variable_name_ == this->variable_name_to_send_) { return; // This is a variable. no need to set color } - this->visible_ = visible; - this->visible_needs_update_ = true; - this->visible_is_set_ = true; + this->component_flags_.visible = visible; + this->component_flags_.visible_needs_update = true; + this->component_flags_.visible_is_set = true; this->update_component_settings(); } void NextionComponent::update_component_settings(bool force_update) { - if (this->nextion_->is_sleeping() || !this->nextion_->is_setup() || !this->visible_is_set_ || - (!this->visible_needs_update_ && !this->visible_)) { + if (this->nextion_->is_sleeping() || !this->nextion_->is_setup() || !this->component_flags_.visible_is_set || + (!this->component_flags_.visible_needs_update && !this->component_flags_.visible)) { this->needs_to_send_update_ = true; return; } - if (this->visible_needs_update_ || (force_update && this->visible_is_set_)) { + if (this->component_flags_.visible_needs_update || (force_update && this->component_flags_.visible_is_set)) { std::string name_to_send = this->variable_name_; size_t pos = name_to_send.find_last_of('.'); @@ -79,9 +79,9 @@ void NextionComponent::update_component_settings(bool force_update) { name_to_send = name_to_send.substr(pos + 1); } - this->visible_needs_update_ = false; + this->component_flags_.visible_needs_update = false; - if (this->visible_) { + if (this->component_flags_.visible) { this->nextion_->show_component(name_to_send.c_str()); this->send_state_to_nextion(); } else { @@ -90,26 +90,26 @@ void NextionComponent::update_component_settings(bool force_update) { } } - if (this->bco_needs_update_ || (force_update && this->bco2_is_set_)) { + if (this->component_flags_.bco_needs_update || (force_update && this->component_flags_.bco2_is_set)) { this->nextion_->set_component_background_color(this->variable_name_.c_str(), this->bco_); - this->bco_needs_update_ = false; + this->component_flags_.bco_needs_update = false; } - if (this->bco2_needs_update_ || (force_update && this->bco2_is_set_)) { + if (this->component_flags_.bco2_needs_update || (force_update && this->component_flags_.bco2_is_set)) { this->nextion_->set_component_pressed_background_color(this->variable_name_.c_str(), this->bco2_); - this->bco2_needs_update_ = false; + this->component_flags_.bco2_needs_update = false; } - if (this->pco_needs_update_ || (force_update && this->pco_is_set_)) { + if (this->component_flags_.pco_needs_update || (force_update && this->component_flags_.pco_is_set)) { this->nextion_->set_component_foreground_color(this->variable_name_.c_str(), this->pco_); - this->pco_needs_update_ = false; + this->component_flags_.pco_needs_update = false; } - if (this->pco2_needs_update_ || (force_update && this->pco2_is_set_)) { + if (this->component_flags_.pco2_needs_update || (force_update && this->component_flags_.pco2_is_set)) { this->nextion_->set_component_pressed_foreground_color(this->variable_name_.c_str(), this->pco2_); - this->pco2_needs_update_ = false; + this->component_flags_.pco2_needs_update = false; } - if (this->font_id_needs_update_ || (force_update && this->font_id_is_set_)) { + if (this->component_flags_.font_id_needs_update || (force_update && this->component_flags_.font_id_is_set)) { this->nextion_->set_component_font(this->variable_name_.c_str(), this->font_id_); - this->font_id_needs_update_ = false; + this->component_flags_.font_id_needs_update = false; } } } // namespace nextion diff --git a/esphome/components/nextion/nextion_component.h b/esphome/components/nextion/nextion_component.h index 2f3c4f3c16..add9e11cf1 100644 --- a/esphome/components/nextion/nextion_component.h +++ b/esphome/components/nextion/nextion_component.h @@ -21,29 +21,64 @@ class NextionComponent : public NextionComponentBase { void set_visible(bool visible); protected: + /** + * @brief Constructor initializes component state with visible=true (default state) + */ + NextionComponent() { + component_flags_ = {}; // Zero-initialize all state + component_flags_.visible = 1; // Set default visibility to true + } + NextionBase *nextion_; - bool bco_needs_update_ = false; - bool bco_is_set_ = false; - Color bco_; - bool bco2_needs_update_ = false; - bool bco2_is_set_ = false; - Color bco2_; - bool pco_needs_update_ = false; - bool pco_is_set_ = false; - Color pco_; - bool pco2_needs_update_ = false; - bool pco2_is_set_ = false; - Color pco2_; + // Color and styling properties + Color bco_; // Background color + Color bco2_; // Pressed background color + Color pco_; // Foreground color + Color pco2_; // Pressed foreground color uint8_t font_id_ = 0; - bool font_id_needs_update_ = false; - bool font_id_is_set_ = false; - bool visible_ = true; - bool visible_needs_update_ = false; - bool visible_is_set_ = false; + /** + * @brief Component state management using compact bitfield structure + * + * Stores all component state flags and properties in a single 16-bit bitfield + * for efficient memory usage and improved cache locality. + * + * Each component property maintains two state flags: + * - needs_update: Indicates the property requires synchronization with the display + * - is_set: Tracks whether the property has been explicitly configured + * + * The visible field stores both the update flags and the actual visibility state. + */ + struct ComponentState { + // Background color flags + uint16_t bco_needs_update : 1; + uint16_t bco_is_set : 1; - // void send_state_to_nextion() = 0; + // Pressed background color flags + uint16_t bco2_needs_update : 1; + uint16_t bco2_is_set : 1; + + // Foreground color flags + uint16_t pco_needs_update : 1; + uint16_t pco_is_set : 1; + + // Pressed foreground color flags + uint16_t pco2_needs_update : 1; + uint16_t pco2_is_set : 1; + + // Font ID flags + uint16_t font_id_needs_update : 1; + uint16_t font_id_is_set : 1; + + // Visibility flags + uint16_t visible_needs_update : 1; + uint16_t visible_is_set : 1; + uint16_t visible : 1; // Actual visibility state + + // Reserved bits for future expansion + uint16_t reserved : 3; + } component_flags_; }; } // namespace nextion } // namespace esphome diff --git a/esphome/components/nextion/nextion_upload.cpp b/esphome/components/nextion/nextion_upload.cpp index 6a54abfed4..c47b393f99 100644 --- a/esphome/components/nextion/nextion_upload.cpp +++ b/esphome/components/nextion/nextion_upload.cpp @@ -16,8 +16,8 @@ bool Nextion::upload_end_(bool successful) { } else { ESP_LOGE(TAG, "Upload failed"); - this->is_updating_ = false; - this->ignore_is_setup_ = false; + this->connection_state_.is_updating_ = false; + this->connection_state_.ignore_is_setup_ = false; uint32_t baud_rate = this->parent_->get_baud_rate(); if (baud_rate != this->original_baud_rate_) { diff --git a/esphome/components/nextion/nextion_upload_arduino.cpp b/esphome/components/nextion/nextion_upload_arduino.cpp index 6cd03118d2..b0e5d121dd 100644 --- a/esphome/components/nextion/nextion_upload_arduino.cpp +++ b/esphome/components/nextion/nextion_upload_arduino.cpp @@ -152,7 +152,7 @@ bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) { ESP_LOGD(TAG, "Exit reparse: %s", YESNO(exit_reparse)); ESP_LOGD(TAG, "URL: %s", this->tft_url_.c_str()); - if (this->is_updating_) { + if (this->connection_state_.is_updating_) { ESP_LOGW(TAG, "Upload in progress"); return false; } @@ -162,7 +162,7 @@ bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) { return false; } - this->is_updating_ = true; + this->connection_state_.is_updating_ = true; if (exit_reparse) { ESP_LOGD(TAG, "Exit reparse mode"); @@ -203,7 +203,7 @@ bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) { begin_status = http_client.begin(*this->get_wifi_client_(), this->tft_url_.c_str()); #endif // USE_ESP8266 if (!begin_status) { - this->is_updating_ = false; + this->connection_state_.is_updating_ = false; ESP_LOGD(TAG, "Connection failed"); return false; } else { @@ -254,7 +254,7 @@ bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) { // The Nextion will ignore the upload command if it is sleeping ESP_LOGV(TAG, "Wake-up"); - this->ignore_is_setup_ = true; + this->connection_state_.ignore_is_setup_ = true; this->send_command_("sleep=0"); this->send_command_("dim=100"); delay(250); // NOLINT diff --git a/esphome/components/nextion/nextion_upload_idf.cpp b/esphome/components/nextion/nextion_upload_idf.cpp index 14ce46d0a0..78a47f9e2c 100644 --- a/esphome/components/nextion/nextion_upload_idf.cpp +++ b/esphome/components/nextion/nextion_upload_idf.cpp @@ -155,7 +155,7 @@ bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) { ESP_LOGD(TAG, "Exit reparse: %s", YESNO(exit_reparse)); ESP_LOGD(TAG, "URL: %s", this->tft_url_.c_str()); - if (this->is_updating_) { + if (this->connection_state_.is_updating_) { ESP_LOGW(TAG, "Upload in progress"); return false; } @@ -165,7 +165,7 @@ bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) { return false; } - this->is_updating_ = true; + this->connection_state_.is_updating_ = true; if (exit_reparse) { ESP_LOGD(TAG, "Exit reparse mode"); @@ -246,7 +246,7 @@ bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) { // The Nextion will ignore the upload command if it is sleeping ESP_LOGV(TAG, "Wake-up"); - this->ignore_is_setup_ = true; + this->connection_state_.ignore_is_setup_ = true; this->send_command_("sleep=0"); this->send_command_("dim=100"); vTaskDelay(pdMS_TO_TICKS(250)); // NOLINT diff --git a/esphome/components/nextion/sensor/nextion_sensor.cpp b/esphome/components/nextion/sensor/nextion_sensor.cpp index 0ed9da95d4..03b7261239 100644 --- a/esphome/components/nextion/sensor/nextion_sensor.cpp +++ b/esphome/components/nextion/sensor/nextion_sensor.cpp @@ -53,7 +53,7 @@ void NextionSensor::set_state(float state, bool publish, bool send_to_nextion) { if (this->wave_chan_id_ == UINT8_MAX) { if (send_to_nextion) { - if (this->nextion_->is_sleeping() || !this->visible_) { + if (this->nextion_->is_sleeping() || !this->component_flags_.visible) { this->needs_to_send_update_ = true; } else { this->needs_to_send_update_ = false; diff --git a/esphome/components/nextion/switch/nextion_switch.cpp b/esphome/components/nextion/switch/nextion_switch.cpp index fe71182496..21636f2bfa 100644 --- a/esphome/components/nextion/switch/nextion_switch.cpp +++ b/esphome/components/nextion/switch/nextion_switch.cpp @@ -28,7 +28,7 @@ void NextionSwitch::set_state(bool state, bool publish, bool send_to_nextion) { return; if (send_to_nextion) { - if (this->nextion_->is_sleeping() || !this->visible_) { + if (this->nextion_->is_sleeping() || !this->component_flags_.visible) { this->needs_to_send_update_ = true; } else { this->needs_to_send_update_ = false; diff --git a/esphome/components/nextion/text_sensor/nextion_textsensor.cpp b/esphome/components/nextion/text_sensor/nextion_textsensor.cpp index e08cbb02ca..9b6deeda87 100644 --- a/esphome/components/nextion/text_sensor/nextion_textsensor.cpp +++ b/esphome/components/nextion/text_sensor/nextion_textsensor.cpp @@ -26,7 +26,7 @@ void NextionTextSensor::set_state(const std::string &state, bool publish, bool s return; if (send_to_nextion) { - if (this->nextion_->is_sleeping() || !this->visible_) { + if (this->nextion_->is_sleeping() || !this->component_flags_.visible) { this->needs_to_send_update_ = true; } else { this->nextion_->add_no_result_to_queue_with_set(this, state); diff --git a/esphome/components/ota/__init__.py b/esphome/components/ota/__init__.py index 627c55e910..4d5b8a61e2 100644 --- a/esphome/components/ota/__init__.py +++ b/esphome/components/ota/__init__.py @@ -1,5 +1,6 @@ from esphome import automation import esphome.codegen as cg +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_ESPHOME, @@ -7,6 +8,7 @@ from esphome.const import ( CONF_OTA, CONF_PLATFORM, CONF_TRIGGER_ID, + PlatformFramework, ) from esphome.core import CORE, coroutine_with_priority @@ -120,3 +122,18 @@ async def ota_to_code(var, config): use_state_callback = True if use_state_callback: cg.add_define("USE_OTA_STATE_CALLBACK") + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "ota_backend_arduino_esp32.cpp": {PlatformFramework.ESP32_ARDUINO}, + "ota_backend_esp_idf.cpp": {PlatformFramework.ESP32_IDF}, + "ota_backend_arduino_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "ota_backend_arduino_rp2040.cpp": {PlatformFramework.RP2040_ARDUINO}, + "ota_backend_arduino_libretiny.cpp": { + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + } +) diff --git a/esphome/components/packages/__init__.py b/esphome/components/packages/__init__.py index 6eb746ec63..0db7841db2 100644 --- a/esphome/components/packages/__init__.py +++ b/esphome/components/packages/__init__.py @@ -63,6 +63,7 @@ BASE_SCHEMA = cv.All( cv.Schema( { cv.Required(CONF_URL): cv.url, + cv.Optional(CONF_PATH): cv.string, cv.Optional(CONF_USERNAME): cv.string, cv.Optional(CONF_PASSWORD): cv.string, cv.Exclusive(CONF_FILE, CONF_FILES): validate_yaml_filename, @@ -116,6 +117,9 @@ def _process_base_package(config: dict) -> dict: ) files = [] + if base_path := config.get(CONF_PATH): + repo_dir = repo_dir / base_path + for file in config[CONF_FILES]: if isinstance(file, str): files.append({CONF_PATH: file, CONF_VARS: {}}) diff --git a/esphome/components/packet_transport/binary_sensor.py b/esphome/components/packet_transport/binary_sensor.py index 076e37e6bb..09bbf91c99 100644 --- a/esphome/components/packet_transport/binary_sensor.py +++ b/esphome/components/packet_transport/binary_sensor.py @@ -1,19 +1,76 @@ import esphome.codegen as cg from esphome.components import binary_sensor -from esphome.const import CONF_ID +import esphome.config_validation as cv +from esphome.const import ( + CONF_DATA, + CONF_ID, + CONF_NAME, + CONF_STATUS, + CONF_TYPE, + DEVICE_CLASS_CONNECTIVITY, + ENTITY_CATEGORY_DIAGNOSTIC, +) +import esphome.final_validate as fv from . import ( + CONF_ENCRYPTION, + CONF_PING_PONG_ENABLE, CONF_PROVIDER, + CONF_PROVIDERS, CONF_REMOTE_ID, CONF_TRANSPORT_ID, + PacketTransport, packet_transport_sensor_schema, + provider_name_validate, ) -CONFIG_SCHEMA = packet_transport_sensor_schema(binary_sensor.binary_sensor_schema()) +STATUS_SENSOR_SCHEMA = binary_sensor.binary_sensor_schema( + device_class=DEVICE_CLASS_CONNECTIVITY, + entity_category=ENTITY_CATEGORY_DIAGNOSTIC, +).extend( + { + cv.GenerateID(CONF_TRANSPORT_ID): cv.use_id(PacketTransport), + cv.Required(CONF_PROVIDER): provider_name_validate, + } +) + +CONFIG_SCHEMA = cv.typed_schema( + { + CONF_DATA: packet_transport_sensor_schema(binary_sensor.binary_sensor_schema()), + CONF_STATUS: STATUS_SENSOR_SCHEMA, + }, + key=CONF_TYPE, + default_type=CONF_DATA, +) + + +def _final_validate(config): + if config[CONF_TYPE] != CONF_STATUS: + # Only run this validation if a status sensor is being configured + return config + full_config = fv.full_config.get() + transport_path = full_config.get_path_for_id(config[CONF_TRANSPORT_ID])[:-1] + transport_config = full_config.get_config_for_path(transport_path) + if transport_config[CONF_PING_PONG_ENABLE] and any( + CONF_ENCRYPTION in p + for p in transport_config[CONF_PROVIDERS] + if p[CONF_NAME] == config[CONF_PROVIDER] + ): + return config + raise cv.Invalid( + "Status sensor requires ping-pong to be enabled and the nominated provider to use encryption." + ) + + +FINAL_VALIDATE_SCHEMA = _final_validate async def to_code(config): var = await binary_sensor.new_binary_sensor(config) comp = await cg.get_variable(config[CONF_TRANSPORT_ID]) - remote_id = str(config.get(CONF_REMOTE_ID) or config.get(CONF_ID)) - cg.add(comp.add_remote_binary_sensor(config[CONF_PROVIDER], remote_id, var)) + if config[CONF_TYPE] == CONF_STATUS: + cg.add(comp.set_provider_status_sensor(config[CONF_PROVIDER], var)) + cg.add_define("USE_STATUS_SENSOR") + else: # CONF_DATA is default + remote_id = str(config.get(CONF_REMOTE_ID) or config.get(CONF_ID)) + cg.add(comp.add_remote_binary_sensor(config[CONF_PROVIDER], remote_id, var)) diff --git a/esphome/components/packet_transport/packet_transport.cpp b/esphome/components/packet_transport/packet_transport.cpp index 5c721002b0..6684d43ff7 100644 --- a/esphome/components/packet_transport/packet_transport.cpp +++ b/esphome/components/packet_transport/packet_transport.cpp @@ -317,8 +317,37 @@ void PacketTransport::update() { auto now = millis() / 1000; if (this->last_key_time_ + this->ping_pong_recyle_time_ < now) { this->resend_ping_key_ = this->ping_pong_enable_; + ESP_LOGV(TAG, "Ping request, age %u", now - this->last_key_time_); this->last_key_time_ = now; } + for (const auto &provider : this->providers_) { + uint32_t key_response_age = now - provider.second.last_key_response_time; + if (key_response_age > (this->ping_pong_recyle_time_ * 2u)) { +#ifdef USE_STATUS_SENSOR + if (provider.second.status_sensor != nullptr && provider.second.status_sensor->state) { + ESP_LOGI(TAG, "Ping status for %s timeout at %u with age %u", provider.first.c_str(), now, key_response_age); + provider.second.status_sensor->publish_state(false); + } +#endif +#ifdef USE_SENSOR + for (auto &sensor : this->remote_sensors_[provider.first]) { + sensor.second->publish_state(NAN); + } +#endif +#ifdef USE_BINARY_SENSOR + for (auto &sensor : this->remote_binary_sensors_[provider.first]) { + sensor.second->invalidate_state(); + } +#endif + } else { +#ifdef USE_STATUS_SENSOR + if (provider.second.status_sensor != nullptr && !provider.second.status_sensor->state) { + ESP_LOGI(TAG, "Ping status for %s restored at %u with age %u", provider.first.c_str(), now, key_response_age); + provider.second.status_sensor->publish_state(true); + } +#endif + } + } } void PacketTransport::add_key_(const char *name, uint32_t key) { @@ -437,7 +466,8 @@ void PacketTransport::process_(const std::vector &data) { if (decoder.decode(PING_KEY, key) == DECODE_OK) { if (key == this->ping_key_) { ping_key_seen = true; - ESP_LOGV(TAG, "Found good ping key %X", (unsigned) key); + provider.last_key_response_time = millis() / 1000; + ESP_LOGV(TAG, "Found good ping key %X at timestamp %" PRIu32, (unsigned) key, provider.last_key_response_time); } else { ESP_LOGV(TAG, "Unknown ping key %X", (unsigned) key); } diff --git a/esphome/components/packet_transport/packet_transport.h b/esphome/components/packet_transport/packet_transport.h index 34edb82963..a2370e9749 100644 --- a/esphome/components/packet_transport/packet_transport.h +++ b/esphome/components/packet_transport/packet_transport.h @@ -8,7 +8,7 @@ #ifdef USE_BINARY_SENSOR #include "esphome/components/binary_sensor/binary_sensor.h" #endif -# + #include #include @@ -27,6 +27,10 @@ struct Provider { std::vector encryption_key; const char *name; uint32_t last_code[2]; + uint32_t last_key_response_time; +#ifdef USE_STATUS_SENSOR + binary_sensor::BinarySensor *status_sensor{nullptr}; +#endif }; #ifdef USE_SENSOR @@ -75,10 +79,7 @@ class PacketTransport : public PollingComponent { void add_provider(const char *hostname) { if (this->providers_.count(hostname) == 0) { - Provider provider; - provider.encryption_key = std::vector{}; - provider.last_code[0] = 0; - provider.last_code[1] = 0; + Provider provider{}; provider.name = hostname; this->providers_[hostname] = provider; #ifdef USE_SENSOR @@ -97,6 +98,11 @@ class PacketTransport : public PollingComponent { void set_provider_encryption(const char *name, std::vector key) { this->providers_[name].encryption_key = std::move(key); } +#ifdef USE_STATUS_SENSOR + void set_provider_status_sensor(const char *name, binary_sensor::BinarySensor *sensor) { + this->providers_[name].status_sensor = sensor; + } +#endif void set_platform_name(const char *name) { this->platform_name_ = name; } protected: diff --git a/esphome/components/remote_receiver/__init__.py b/esphome/components/remote_receiver/__init__.py index 5de7d8c9c4..dffc088085 100644 --- a/esphome/components/remote_receiver/__init__.py +++ b/esphome/components/remote_receiver/__init__.py @@ -1,6 +1,7 @@ from esphome import pins import esphome.codegen as cg from esphome.components import esp32, esp32_rmt, remote_base +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_BUFFER_SIZE, @@ -15,6 +16,7 @@ from esphome.const import ( CONF_TYPE, CONF_USE_DMA, CONF_VALUE, + PlatformFramework, ) from esphome.core import CORE, TimePeriod @@ -170,3 +172,19 @@ async def to_code(config): cg.add(var.set_buffer_size(config[CONF_BUFFER_SIZE])) cg.add(var.set_filter_us(config[CONF_FILTER])) cg.add(var.set_idle_us(config[CONF_IDLE])) + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "remote_receiver_esp32.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + "remote_receiver_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "remote_receiver_libretiny.cpp": { + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + } +) diff --git a/esphome/components/remote_transmitter/__init__.py b/esphome/components/remote_transmitter/__init__.py index 713cee0186..47a46ff56b 100644 --- a/esphome/components/remote_transmitter/__init__.py +++ b/esphome/components/remote_transmitter/__init__.py @@ -1,6 +1,7 @@ from esphome import automation, pins import esphome.codegen as cg from esphome.components import esp32, esp32_rmt, remote_base +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_CARRIER_DUTY_PERCENT, @@ -12,6 +13,7 @@ from esphome.const import ( CONF_PIN, CONF_RMT_SYMBOLS, CONF_USE_DMA, + PlatformFramework, ) from esphome.core import CORE @@ -95,3 +97,19 @@ async def to_code(config): await automation.build_automation( var.get_complete_trigger(), [], on_complete_config ) + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "remote_transmitter_esp32.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + "remote_transmitter_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "remote_transmitter_libretiny.cpp": { + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + } +) diff --git a/esphome/components/rp2040/helpers.cpp b/esphome/components/rp2040/helpers.cpp new file mode 100644 index 0000000000..a6eac58dc6 --- /dev/null +++ b/esphome/components/rp2040/helpers.cpp @@ -0,0 +1,55 @@ +#include "esphome/core/helpers.h" +#include "esphome/core/defines.h" + +#ifdef USE_RP2040 + +#include "esphome/core/hal.h" + +#if defined(USE_WIFI) +#include +#endif +#include +#include + +namespace esphome { + +uint32_t random_uint32() { + uint32_t result = 0; + for (uint8_t i = 0; i < 32; i++) { + result <<= 1; + result |= rosc_hw->randombit; + } + return result; +} + +bool random_bytes(uint8_t *data, size_t len) { + while (len-- != 0) { + uint8_t result = 0; + for (uint8_t i = 0; i < 8; i++) { + result <<= 1; + result |= rosc_hw->randombit; + } + *data++ = result; + } + return true; +} + +// RP2040 doesn't have mutexes, but that shouldn't be an issue as it's single-core and non-preemptive OS. +Mutex::Mutex() {} +Mutex::~Mutex() {} +void Mutex::lock() {} +bool Mutex::try_lock() { return true; } +void Mutex::unlock() {} + +IRAM_ATTR InterruptLock::InterruptLock() { state_ = save_and_disable_interrupts(); } +IRAM_ATTR InterruptLock::~InterruptLock() { restore_interrupts(state_); } + +void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter) +#ifdef USE_WIFI + WiFi.macAddress(mac); +#endif +} + +} // namespace esphome + +#endif // USE_RP2040 diff --git a/esphome/components/rtttl/__init__.py b/esphome/components/rtttl/__init__.py index 0abd51a6f1..ebbe5366aa 100644 --- a/esphome/components/rtttl/__init__.py +++ b/esphome/components/rtttl/__init__.py @@ -57,14 +57,14 @@ def validate_parent_output_config(value): platform = value.get(CONF_PLATFORM) PWM_GOOD = ["esp8266_pwm", "ledc"] PWM_BAD = [ - "ac_dimmer ", + "ac_dimmer", "esp32_dac", - "slow_pwm", "mcp4725", - "pca9685", - "tlc59208f", "my9231", + "pca9685", + "slow_pwm", "sm16716", + "tlc59208f", ] if platform in PWM_BAD: diff --git a/esphome/components/scd4x/scd4x.cpp b/esphome/components/scd4x/scd4x.cpp index f617ffe276..06db70e3f3 100644 --- a/esphome/components/scd4x/scd4x.cpp +++ b/esphome/components/scd4x/scd4x.cpp @@ -7,6 +7,8 @@ namespace scd4x { static const char *const TAG = "scd4x"; +static const uint16_t SCD41_ID = 0x1408; +static const uint16_t SCD40_ID = 0x440; static const uint16_t SCD4X_CMD_GET_SERIAL_NUMBER = 0x3682; static const uint16_t SCD4X_CMD_TEMPERATURE_OFFSET = 0x241d; static const uint16_t SCD4X_CMD_ALTITUDE_COMPENSATION = 0x2427; @@ -23,8 +25,6 @@ static const uint16_t SCD4X_CMD_STOP_MEASUREMENTS = 0x3f86; static const uint16_t SCD4X_CMD_FACTORY_RESET = 0x3632; static const uint16_t SCD4X_CMD_GET_FEATURESET = 0x202f; static const float SCD4X_TEMPERATURE_OFFSET_MULTIPLIER = (1 << 16) / 175.0f; -static const uint16_t SCD41_ID = 0x1408; -static const uint16_t SCD40_ID = 0x440; void SCD4XComponent::setup() { ESP_LOGCONFIG(TAG, "Running setup"); @@ -51,47 +51,66 @@ void SCD4XComponent::setup() { if (!this->write_command(SCD4X_CMD_TEMPERATURE_OFFSET, (uint16_t) (temperature_offset_ * SCD4X_TEMPERATURE_OFFSET_MULTIPLIER))) { - ESP_LOGE(TAG, "Error setting temperature offset."); + ESP_LOGE(TAG, "Error setting temperature offset"); this->error_code_ = MEASUREMENT_INIT_FAILED; this->mark_failed(); return; } - // If pressure compensation available use it - // else use altitude - if (ambient_pressure_compensation_) { - if (!this->update_ambient_pressure_compensation_(ambient_pressure_)) { - ESP_LOGE(TAG, "Error setting ambient pressure compensation."); + // If pressure compensation available use it, else use altitude + if (this->ambient_pressure_) { + if (!this->update_ambient_pressure_compensation_(this->ambient_pressure_)) { + ESP_LOGE(TAG, "Error setting ambient pressure compensation"); this->error_code_ = MEASUREMENT_INIT_FAILED; this->mark_failed(); return; } } else { - if (!this->write_command(SCD4X_CMD_ALTITUDE_COMPENSATION, altitude_compensation_)) { - ESP_LOGE(TAG, "Error setting altitude compensation."); + if (!this->write_command(SCD4X_CMD_ALTITUDE_COMPENSATION, this->altitude_compensation_)) { + ESP_LOGE(TAG, "Error setting altitude compensation"); this->error_code_ = MEASUREMENT_INIT_FAILED; this->mark_failed(); return; } } - if (!this->write_command(SCD4X_CMD_AUTOMATIC_SELF_CALIBRATION, enable_asc_ ? 1 : 0)) { - ESP_LOGE(TAG, "Error setting automatic self calibration."); + if (!this->write_command(SCD4X_CMD_AUTOMATIC_SELF_CALIBRATION, this->enable_asc_ ? 1 : 0)) { + ESP_LOGE(TAG, "Error setting automatic self calibration"); this->error_code_ = MEASUREMENT_INIT_FAILED; this->mark_failed(); return; } - initialized_ = true; + this->initialized_ = true; // Finally start sensor measurements this->start_measurement_(); - ESP_LOGD(TAG, "Sensor initialized"); }); }); } void SCD4XComponent::dump_config() { - ESP_LOGCONFIG(TAG, "scd4x:"); + static const char *const MM_PERIODIC_STR = "Periodic (5s)"; + static const char *const MM_LOW_POWER_PERIODIC_STR = "Low power periodic (30s)"; + static const char *const MM_SINGLE_SHOT_STR = "Single shot"; + static const char *const MM_SINGLE_SHOT_RHT_ONLY_STR = "Single shot rht only"; + const char *measurement_mode_str = MM_PERIODIC_STR; + + switch (this->measurement_mode_) { + case PERIODIC: + // measurement_mode_str = MM_PERIODIC_STR; + break; + case LOW_POWER_PERIODIC: + measurement_mode_str = MM_LOW_POWER_PERIODIC_STR; + break; + case SINGLE_SHOT: + measurement_mode_str = MM_SINGLE_SHOT_STR; + break; + case SINGLE_SHOT_RHT_ONLY: + measurement_mode_str = MM_SINGLE_SHOT_RHT_ONLY_STR; + break; + } + + ESP_LOGCONFIG(TAG, "SCD4X:"); LOG_I2C_DEVICE(this); if (this->is_failed()) { switch (this->error_code_) { @@ -102,19 +121,23 @@ void SCD4XComponent::dump_config() { ESP_LOGW(TAG, "Measurement Initialization failed"); break; case SERIAL_NUMBER_IDENTIFICATION_FAILED: - ESP_LOGW(TAG, "Unable to read sensor firmware version"); + ESP_LOGW(TAG, "Unable to read firmware version"); break; default: ESP_LOGW(TAG, "Unknown setup error"); break; } } - ESP_LOGCONFIG(TAG, " Automatic self calibration: %s", ONOFF(this->enable_asc_)); + ESP_LOGCONFIG(TAG, + " Automatic self calibration: %s\n" + " Measurement mode: %s\n" + " Temperature offset: %.2f °C", + ONOFF(this->enable_asc_), measurement_mode_str, this->temperature_offset_); if (this->ambient_pressure_source_ != nullptr) { - ESP_LOGCONFIG(TAG, " Dynamic ambient pressure compensation using sensor '%s'", + ESP_LOGCONFIG(TAG, " Dynamic ambient pressure compensation using '%s'", this->ambient_pressure_source_->get_name().c_str()); } else { - if (this->ambient_pressure_compensation_) { + if (this->ambient_pressure_) { ESP_LOGCONFIG(TAG, " Altitude compensation disabled\n" " Ambient pressure compensation: %dmBar", @@ -126,21 +149,6 @@ void SCD4XComponent::dump_config() { this->altitude_compensation_); } } - switch (this->measurement_mode_) { - case PERIODIC: - ESP_LOGCONFIG(TAG, " Measurement mode: periodic (5s)"); - break; - case LOW_POWER_PERIODIC: - ESP_LOGCONFIG(TAG, " Measurement mode: low power periodic (30s)"); - break; - case SINGLE_SHOT: - ESP_LOGCONFIG(TAG, " Measurement mode: single shot"); - break; - case SINGLE_SHOT_RHT_ONLY: - ESP_LOGCONFIG(TAG, " Measurement mode: single shot rht only"); - break; - } - ESP_LOGCONFIG(TAG, " Temperature offset: %.2f °C", this->temperature_offset_); LOG_UPDATE_INTERVAL(this); LOG_SENSOR(" ", "CO2", this->co2_sensor_); LOG_SENSOR(" ", "Temperature", this->temperature_sensor_); @@ -148,20 +156,20 @@ void SCD4XComponent::dump_config() { } void SCD4XComponent::update() { - if (!initialized_) { + if (!this->initialized_) { return; } if (this->ambient_pressure_source_ != nullptr) { float pressure = this->ambient_pressure_source_->state; if (!std::isnan(pressure)) { - set_ambient_pressure_compensation(pressure); + this->set_ambient_pressure_compensation(pressure); } } uint32_t wait_time = 0; if (this->measurement_mode_ == SINGLE_SHOT || this->measurement_mode_ == SINGLE_SHOT_RHT_ONLY) { - start_measurement_(); + this->start_measurement_(); wait_time = this->measurement_mode_ == SINGLE_SHOT ? 5000 : 50; // Single shot measurement takes 5 secs rht mode 50 ms } @@ -176,12 +184,12 @@ void SCD4XComponent::update() { if (!this->read_data(raw_read_status) || raw_read_status == 0x00) { this->status_set_warning(); - ESP_LOGW(TAG, "Data not ready yet!"); + ESP_LOGW(TAG, "Data not ready"); return; } if (!this->write_command(SCD4X_CMD_READ_MEASUREMENT)) { - ESP_LOGW(TAG, "Error reading measurement!"); + ESP_LOGW(TAG, "Error reading measurement"); this->status_set_warning(); return; // NO RETRY } @@ -218,19 +226,19 @@ bool SCD4XComponent::perform_forced_calibration(uint16_t current_co2_concentrati } this->set_timeout(500, [this, current_co2_concentration]() { if (this->write_command(SCD4X_CMD_PERFORM_FORCED_CALIBRATION, current_co2_concentration)) { - ESP_LOGD(TAG, "setting forced calibration Co2 level %d ppm", current_co2_concentration); + ESP_LOGD(TAG, "Setting forced calibration Co2 level %d ppm", current_co2_concentration); // frc takes 400 ms // because this method will be used very rarly // the simple approach with delay is ok - delay(400); // NOLINT' + delay(400); // NOLINT if (!this->start_measurement_()) { return false; } else { - ESP_LOGD(TAG, "forced calibration complete"); + ESP_LOGD(TAG, "Forced calibration complete"); } return true; } else { - ESP_LOGE(TAG, "force calibration failed"); + ESP_LOGE(TAG, "Force calibration failed"); this->error_code_ = FRC_FAILED; this->status_set_warning(); return false; @@ -259,27 +267,26 @@ bool SCD4XComponent::factory_reset() { } void SCD4XComponent::set_ambient_pressure_compensation(float pressure_in_hpa) { - ambient_pressure_compensation_ = true; - uint16_t new_ambient_pressure = (uint16_t) pressure_in_hpa; - if (!initialized_) { - ambient_pressure_ = new_ambient_pressure; + uint16_t new_ambient_pressure = static_cast(pressure_in_hpa); + if (!this->initialized_) { + this->ambient_pressure_ = new_ambient_pressure; return; } // Only send pressure value if it has changed since last update - if (new_ambient_pressure != ambient_pressure_) { - update_ambient_pressure_compensation_(new_ambient_pressure); - ambient_pressure_ = new_ambient_pressure; + if (new_ambient_pressure != this->ambient_pressure_) { + this->update_ambient_pressure_compensation_(new_ambient_pressure); + this->ambient_pressure_ = new_ambient_pressure; } else { - ESP_LOGD(TAG, "ambient pressure compensation skipped - no change required"); + ESP_LOGD(TAG, "Ambient pressure compensation skipped; no change required"); } } bool SCD4XComponent::update_ambient_pressure_compensation_(uint16_t pressure_in_hpa) { if (this->write_command(SCD4X_CMD_AMBIENT_PRESSURE_COMPENSATION, pressure_in_hpa)) { - ESP_LOGD(TAG, "setting ambient pressure compensation to %d hPa", pressure_in_hpa); + ESP_LOGD(TAG, "Setting ambient pressure compensation to %d hPa", pressure_in_hpa); return true; } else { - ESP_LOGE(TAG, "Error setting ambient pressure compensation."); + ESP_LOGE(TAG, "Error setting ambient pressure compensation"); return false; } } @@ -304,7 +311,7 @@ bool SCD4XComponent::start_measurement_() { static uint8_t remaining_retries = 3; while (remaining_retries) { if (!this->write_command(measurement_command)) { - ESP_LOGE(TAG, "Error starting measurements."); + ESP_LOGE(TAG, "Error starting measurements"); this->error_code_ = MEASUREMENT_INIT_FAILED; this->status_set_warning(); if (--remaining_retries == 0) diff --git a/esphome/components/scd4x/scd4x.h b/esphome/components/scd4x/scd4x.h index f2efb28ac1..ab5d72aeec 100644 --- a/esphome/components/scd4x/scd4x.h +++ b/esphome/components/scd4x/scd4x.h @@ -8,14 +8,20 @@ namespace esphome { namespace scd4x { -enum ERRORCODE { +enum ErrorCode : uint8_t { COMMUNICATION_FAILED, SERIAL_NUMBER_IDENTIFICATION_FAILED, MEASUREMENT_INIT_FAILED, FRC_FAILED, - UNKNOWN + UNKNOWN, +}; + +enum MeasurementMode : uint8_t { + PERIODIC, + LOW_POWER_PERIODIC, + SINGLE_SHOT, + SINGLE_SHOT_RHT_ONLY, }; -enum MeasurementMode { PERIODIC, LOW_POWER_PERIODIC, SINGLE_SHOT, SINGLE_SHOT_RHT_ONLY }; class SCD4XComponent : public PollingComponent, public sensirion_common::SensirionI2CDevice { public: @@ -39,21 +45,18 @@ class SCD4XComponent : public PollingComponent, public sensirion_common::Sensiri protected: bool update_ambient_pressure_compensation_(uint16_t pressure_in_hpa); bool start_measurement_(); - ERRORCODE error_code_; - bool initialized_{false}; - - float temperature_offset_; - uint16_t altitude_compensation_; - bool ambient_pressure_compensation_; - uint16_t ambient_pressure_; - bool enable_asc_; - MeasurementMode measurement_mode_{PERIODIC}; sensor::Sensor *co2_sensor_{nullptr}; sensor::Sensor *temperature_sensor_{nullptr}; sensor::Sensor *humidity_sensor_{nullptr}; - // used for compensation - sensor::Sensor *ambient_pressure_source_{nullptr}; + sensor::Sensor *ambient_pressure_source_{nullptr}; // used for compensation + float temperature_offset_; + uint16_t altitude_compensation_{0}; + uint16_t ambient_pressure_{0}; // Per datasheet, valid values are 700 to 1200 hPa; 0 is a valid sentinel value + bool initialized_{false}; + bool enable_asc_{false}; + ErrorCode error_code_; + MeasurementMode measurement_mode_{PERIODIC}; }; } // namespace scd4x diff --git a/esphome/components/sensor/filter.cpp b/esphome/components/sensor/filter.cpp index ce23c1f800..dd8635f0c0 100644 --- a/esphome/components/sensor/filter.cpp +++ b/esphome/components/sensor/filter.cpp @@ -118,7 +118,7 @@ optional QuantileFilter::new_value(float value) { size_t queue_size = quantile_queue.size(); if (queue_size) { size_t position = ceilf(queue_size * this->quantile_) - 1; - ESP_LOGVV(TAG, "QuantileFilter(%p)::position: %d/%d", this, position + 1, queue_size); + ESP_LOGVV(TAG, "QuantileFilter(%p)::position: %zu/%zu", this, position + 1, queue_size); result = quantile_queue[position]; } } diff --git a/esphome/components/socket/__init__.py b/esphome/components/socket/__init__.py index 26031a8da5..e085a09eac 100644 --- a/esphome/components/socket/__init__.py +++ b/esphome/components/socket/__init__.py @@ -1,5 +1,6 @@ import esphome.codegen as cg import esphome.config_validation as cv +from esphome.core import CORE CODEOWNERS = ["@esphome/core"] @@ -40,3 +41,18 @@ async def to_code(config): elif impl == IMPLEMENTATION_BSD_SOCKETS: cg.add_define("USE_SOCKET_IMPL_BSD_SOCKETS") cg.add_define("USE_SOCKET_SELECT_SUPPORT") + + +def FILTER_SOURCE_FILES() -> list[str]: + """Return list of socket implementation files that aren't selected by the user.""" + impl = CORE.config["socket"][CONF_IMPLEMENTATION] + + # Build list of files to exclude based on selected implementation + excluded = [] + if impl != IMPLEMENTATION_LWIP_TCP: + excluded.append("lwip_raw_tcp_impl.cpp") + if impl != IMPLEMENTATION_BSD_SOCKETS: + excluded.append("bsd_sockets_impl.cpp") + if impl != IMPLEMENTATION_LWIP_SOCKETS: + excluded.append("lwip_sockets_impl.cpp") + return excluded diff --git a/esphome/components/spi/__init__.py b/esphome/components/spi/__init__.py index 55a4b9c8f6..58bfc3f411 100644 --- a/esphome/components/spi/__init__.py +++ b/esphome/components/spi/__init__.py @@ -13,6 +13,7 @@ from esphome.components.esp32.const import ( VARIANT_ESP32S2, VARIANT_ESP32S3, ) +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_CLK_PIN, @@ -31,6 +32,7 @@ from esphome.const import ( PLATFORM_ESP32, PLATFORM_ESP8266, PLATFORM_RP2040, + PlatformFramework, ) from esphome.core import CORE, coroutine_with_priority import esphome.final_validate as fv @@ -423,3 +425,18 @@ def final_validate_device_schema(name: str, *, require_mosi: bool, require_miso: {cv.Required(CONF_SPI_ID): fv.id_declaration_match_schema(hub_schema)}, extra=cv.ALLOW_EXTRA, ) + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "spi_arduino.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP8266_ARDUINO, + PlatformFramework.RP2040_ARDUINO, + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + "spi_esp_idf.cpp": {PlatformFramework.ESP32_IDF}, + } +) diff --git a/esphome/components/ssd1306_base/ssd1306_base.cpp b/esphome/components/ssd1306_base/ssd1306_base.cpp index 0547a77184..1f039cff78 100644 --- a/esphome/components/ssd1306_base/ssd1306_base.cpp +++ b/esphome/components/ssd1306_base/ssd1306_base.cpp @@ -224,7 +224,7 @@ bool SSD1306::is_sh1106_() const { } bool SSD1306::is_sh1107_() const { return this->model_ == SH1107_MODEL_128_64 || this->model_ == SH1107_MODEL_128_128; } bool SSD1306::is_ssd1305_() const { - return this->model_ == SSD1305_MODEL_128_64 || this->model_ == SSD1305_MODEL_128_64; + return this->model_ == SSD1305_MODEL_128_64 || this->model_ == SSD1305_MODEL_128_32; } void SSD1306::update() { this->do_update_(); diff --git a/esphome/components/sx126x/__init__.py b/esphome/components/sx126x/__init__.py new file mode 100644 index 0000000000..492febe283 --- /dev/null +++ b/esphome/components/sx126x/__init__.py @@ -0,0 +1,317 @@ +from esphome import automation, pins +import esphome.codegen as cg +from esphome.components import spi +import esphome.config_validation as cv +from esphome.const import CONF_BUSY_PIN, CONF_DATA, CONF_FREQUENCY, CONF_ID +from esphome.core import TimePeriod + +MULTI_CONF = True +CODEOWNERS = ["@swoboda1337"] +DEPENDENCIES = ["spi"] + +CONF_SX126X_ID = "sx126x_id" + +CONF_BANDWIDTH = "bandwidth" +CONF_BITRATE = "bitrate" +CONF_CODING_RATE = "coding_rate" +CONF_CRC_ENABLE = "crc_enable" +CONF_DEVIATION = "deviation" +CONF_DIO1_PIN = "dio1_pin" +CONF_HW_VERSION = "hw_version" +CONF_MODULATION = "modulation" +CONF_ON_PACKET = "on_packet" +CONF_PA_POWER = "pa_power" +CONF_PA_RAMP = "pa_ramp" +CONF_PAYLOAD_LENGTH = "payload_length" +CONF_PREAMBLE_DETECT = "preamble_detect" +CONF_PREAMBLE_SIZE = "preamble_size" +CONF_RST_PIN = "rst_pin" +CONF_RX_START = "rx_start" +CONF_RF_SWITCH = "rf_switch" +CONF_SHAPING = "shaping" +CONF_SPREADING_FACTOR = "spreading_factor" +CONF_SYNC_VALUE = "sync_value" +CONF_TCXO_VOLTAGE = "tcxo_voltage" +CONF_TCXO_DELAY = "tcxo_delay" + +sx126x_ns = cg.esphome_ns.namespace("sx126x") +SX126x = sx126x_ns.class_("SX126x", cg.Component, spi.SPIDevice) +SX126xListener = sx126x_ns.class_("SX126xListener") +SX126xBw = sx126x_ns.enum("SX126xBw") +SX126xPacketType = sx126x_ns.enum("SX126xPacketType") +SX126xTcxoCtrl = sx126x_ns.enum("SX126xTcxoCtrl") +SX126xRampTime = sx126x_ns.enum("SX126xRampTime") +SX126xPulseShape = sx126x_ns.enum("SX126xPulseShape") +SX126xLoraCr = sx126x_ns.enum("SX126xLoraCr") + +BW = { + "4_8kHz": SX126xBw.SX126X_BW_4800, + "5_8kHz": SX126xBw.SX126X_BW_5800, + "7_3kHz": SX126xBw.SX126X_BW_7300, + "9_7kHz": SX126xBw.SX126X_BW_9700, + "11_7kHz": SX126xBw.SX126X_BW_11700, + "14_6kHz": SX126xBw.SX126X_BW_14600, + "19_5kHz": SX126xBw.SX126X_BW_19500, + "23_4kHz": SX126xBw.SX126X_BW_23400, + "29_3kHz": SX126xBw.SX126X_BW_29300, + "39_0kHz": SX126xBw.SX126X_BW_39000, + "46_9kHz": SX126xBw.SX126X_BW_46900, + "58_6kHz": SX126xBw.SX126X_BW_58600, + "78_2kHz": SX126xBw.SX126X_BW_78200, + "93_8kHz": SX126xBw.SX126X_BW_93800, + "117_3kHz": SX126xBw.SX126X_BW_117300, + "156_2kHz": SX126xBw.SX126X_BW_156200, + "187_2kHz": SX126xBw.SX126X_BW_187200, + "234_3kHz": SX126xBw.SX126X_BW_234300, + "312_0kHz": SX126xBw.SX126X_BW_312000, + "373_6kHz": SX126xBw.SX126X_BW_373600, + "467_0kHz": SX126xBw.SX126X_BW_467000, + "7_8kHz": SX126xBw.SX126X_BW_7810, + "10_4kHz": SX126xBw.SX126X_BW_10420, + "15_6kHz": SX126xBw.SX126X_BW_15630, + "20_8kHz": SX126xBw.SX126X_BW_20830, + "31_3kHz": SX126xBw.SX126X_BW_31250, + "41_7kHz": SX126xBw.SX126X_BW_41670, + "62_5kHz": SX126xBw.SX126X_BW_62500, + "125_0kHz": SX126xBw.SX126X_BW_125000, + "250_0kHz": SX126xBw.SX126X_BW_250000, + "500_0kHz": SX126xBw.SX126X_BW_500000, +} + +CODING_RATE = { + "CR_4_5": SX126xLoraCr.LORA_CR_4_5, + "CR_4_6": SX126xLoraCr.LORA_CR_4_6, + "CR_4_7": SX126xLoraCr.LORA_CR_4_7, + "CR_4_8": SX126xLoraCr.LORA_CR_4_8, +} + +MOD = { + "LORA": SX126xPacketType.PACKET_TYPE_LORA, + "FSK": SX126xPacketType.PACKET_TYPE_GFSK, +} + +TCXO_VOLTAGE = { + "1_6V": SX126xTcxoCtrl.TCXO_CTRL_1_6V, + "1_7V": SX126xTcxoCtrl.TCXO_CTRL_1_7V, + "1_8V": SX126xTcxoCtrl.TCXO_CTRL_1_8V, + "2_2V": SX126xTcxoCtrl.TCXO_CTRL_2_2V, + "2_4V": SX126xTcxoCtrl.TCXO_CTRL_2_4V, + "2_7V": SX126xTcxoCtrl.TCXO_CTRL_2_7V, + "3_0V": SX126xTcxoCtrl.TCXO_CTRL_3_0V, + "3_3V": SX126xTcxoCtrl.TCXO_CTRL_3_3V, + "NONE": SX126xTcxoCtrl.TCXO_CTRL_NONE, +} + +RAMP = { + "10us": SX126xRampTime.PA_RAMP_10, + "20us": SX126xRampTime.PA_RAMP_20, + "40us": SX126xRampTime.PA_RAMP_40, + "80us": SX126xRampTime.PA_RAMP_80, + "200us": SX126xRampTime.PA_RAMP_200, + "800us": SX126xRampTime.PA_RAMP_800, + "1700us": SX126xRampTime.PA_RAMP_1700, + "3400us": SX126xRampTime.PA_RAMP_3400, +} + +SHAPING = { + "GAUSSIAN_BT_0_3": SX126xPulseShape.GAUSSIAN_BT_0_3, + "GAUSSIAN_BT_0_5": SX126xPulseShape.GAUSSIAN_BT_0_5, + "GAUSSIAN_BT_0_7": SX126xPulseShape.GAUSSIAN_BT_0_7, + "GAUSSIAN_BT_1_0": SX126xPulseShape.GAUSSIAN_BT_1_0, + "NONE": SX126xPulseShape.NO_FILTER, +} + +RunImageCalAction = sx126x_ns.class_( + "RunImageCalAction", automation.Action, cg.Parented.template(SX126x) +) +SendPacketAction = sx126x_ns.class_( + "SendPacketAction", automation.Action, cg.Parented.template(SX126x) +) +SetModeTxAction = sx126x_ns.class_( + "SetModeTxAction", automation.Action, cg.Parented.template(SX126x) +) +SetModeRxAction = sx126x_ns.class_( + "SetModeRxAction", automation.Action, cg.Parented.template(SX126x) +) +SetModeSleepAction = sx126x_ns.class_( + "SetModeSleepAction", automation.Action, cg.Parented.template(SX126x) +) +SetModeStandbyAction = sx126x_ns.class_( + "SetModeStandbyAction", automation.Action, cg.Parented.template(SX126x) +) + + +def validate_raw_data(value): + if isinstance(value, str): + return value.encode("utf-8") + if isinstance(value, list): + return cv.Schema([cv.hex_uint8_t])(value) + raise cv.Invalid( + "data must either be a string wrapped in quotes or a list of bytes" + ) + + +def validate_config(config): + lora_bws = [ + "7_8kHz", + "10_4kHz", + "15_6kHz", + "20_8kHz", + "31_3kHz", + "41_7kHz", + "62_5kHz", + "125_0kHz", + "250_0kHz", + "500_0kHz", + ] + if config[CONF_MODULATION] == "LORA": + if config[CONF_BANDWIDTH] not in lora_bws: + raise cv.Invalid(f"{config[CONF_BANDWIDTH]} is not available with LORA") + if config[CONF_PREAMBLE_SIZE] > 0 and config[CONF_PREAMBLE_SIZE] < 6: + raise cv.Invalid("Minimum preamble size is 6 with LORA") + if config[CONF_SPREADING_FACTOR] == 6 and config[CONF_PAYLOAD_LENGTH] == 0: + raise cv.Invalid("Payload length must be set when spreading factor is 6") + else: + if config[CONF_BANDWIDTH] in lora_bws: + raise cv.Invalid(f"{config[CONF_BANDWIDTH]} is not available with FSK") + if config[CONF_PREAMBLE_DETECT] > len(config[CONF_SYNC_VALUE]): + raise cv.Invalid("Preamble detection length must be <= sync value length") + return config + + +CONFIG_SCHEMA = ( + cv.Schema( + { + cv.GenerateID(): cv.declare_id(SX126x), + cv.Optional(CONF_BANDWIDTH, default="125_0kHz"): cv.enum(BW), + cv.Optional(CONF_BITRATE, default=4800): cv.int_range(min=600, max=300000), + cv.Required(CONF_BUSY_PIN): pins.internal_gpio_input_pin_schema, + cv.Optional(CONF_CODING_RATE, default="CR_4_5"): cv.enum(CODING_RATE), + cv.Optional(CONF_CRC_ENABLE, default=False): cv.boolean, + cv.Optional(CONF_DEVIATION, default=5000): cv.int_range(min=0, max=100000), + cv.Required(CONF_DIO1_PIN): pins.internal_gpio_input_pin_schema, + cv.Required(CONF_FREQUENCY): cv.int_range(min=137000000, max=1020000000), + cv.Required(CONF_HW_VERSION): cv.one_of( + "sx1261", "sx1262", "sx1268", "llcc68", lower=True + ), + cv.Required(CONF_MODULATION): cv.enum(MOD), + cv.Optional(CONF_ON_PACKET): automation.validate_automation(single=True), + cv.Optional(CONF_PA_POWER, default=17): cv.int_range(min=-3, max=22), + cv.Optional(CONF_PA_RAMP, default="40us"): cv.enum(RAMP), + cv.Optional(CONF_PAYLOAD_LENGTH, default=0): cv.int_range(min=0, max=256), + cv.Optional(CONF_PREAMBLE_DETECT, default=2): cv.int_range(min=0, max=4), + cv.Required(CONF_PREAMBLE_SIZE): cv.int_range(min=1, max=65535), + cv.Required(CONF_RST_PIN): pins.internal_gpio_output_pin_schema, + cv.Optional(CONF_RX_START, default=True): cv.boolean, + cv.Required(CONF_RF_SWITCH): cv.boolean, + cv.Optional(CONF_SHAPING, default="NONE"): cv.enum(SHAPING), + cv.Optional(CONF_SPREADING_FACTOR, default=7): cv.int_range(min=6, max=12), + cv.Optional(CONF_SYNC_VALUE, default=[]): cv.ensure_list(cv.hex_uint8_t), + cv.Optional(CONF_TCXO_VOLTAGE, default="NONE"): cv.enum(TCXO_VOLTAGE), + cv.Optional(CONF_TCXO_DELAY, default="5ms"): cv.All( + cv.positive_time_period_microseconds, + cv.Range(max=TimePeriod(microseconds=262144000)), + ), + }, + ) + .extend(cv.COMPONENT_SCHEMA) + .extend(spi.spi_device_schema(True, 8e6, "mode0")) + .add_extra(validate_config) +) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) + await spi.register_spi_device(var, config) + if CONF_ON_PACKET in config: + await automation.build_automation( + var.get_packet_trigger(), + [ + (cg.std_vector.template(cg.uint8), "x"), + (cg.float_, "rssi"), + (cg.float_, "snr"), + ], + config[CONF_ON_PACKET], + ) + if CONF_DIO1_PIN in config: + dio1_pin = await cg.gpio_pin_expression(config[CONF_DIO1_PIN]) + cg.add(var.set_dio1_pin(dio1_pin)) + rst_pin = await cg.gpio_pin_expression(config[CONF_RST_PIN]) + cg.add(var.set_rst_pin(rst_pin)) + busy_pin = await cg.gpio_pin_expression(config[CONF_BUSY_PIN]) + cg.add(var.set_busy_pin(busy_pin)) + cg.add(var.set_bandwidth(config[CONF_BANDWIDTH])) + cg.add(var.set_frequency(config[CONF_FREQUENCY])) + cg.add(var.set_hw_version(config[CONF_HW_VERSION])) + cg.add(var.set_deviation(config[CONF_DEVIATION])) + cg.add(var.set_modulation(config[CONF_MODULATION])) + cg.add(var.set_pa_ramp(config[CONF_PA_RAMP])) + cg.add(var.set_pa_power(config[CONF_PA_POWER])) + cg.add(var.set_shaping(config[CONF_SHAPING])) + cg.add(var.set_bitrate(config[CONF_BITRATE])) + cg.add(var.set_crc_enable(config[CONF_CRC_ENABLE])) + cg.add(var.set_payload_length(config[CONF_PAYLOAD_LENGTH])) + cg.add(var.set_preamble_size(config[CONF_PREAMBLE_SIZE])) + cg.add(var.set_preamble_detect(config[CONF_PREAMBLE_DETECT])) + cg.add(var.set_coding_rate(config[CONF_CODING_RATE])) + cg.add(var.set_spreading_factor(config[CONF_SPREADING_FACTOR])) + cg.add(var.set_sync_value(config[CONF_SYNC_VALUE])) + cg.add(var.set_rx_start(config[CONF_RX_START])) + cg.add(var.set_rf_switch(config[CONF_RF_SWITCH])) + cg.add(var.set_tcxo_voltage(config[CONF_TCXO_VOLTAGE])) + cg.add(var.set_tcxo_delay(config[CONF_TCXO_DELAY])) + + +NO_ARGS_ACTION_SCHEMA = automation.maybe_simple_id( + { + cv.GenerateID(): cv.use_id(SX126x), + } +) + + +@automation.register_action( + "sx126x.run_image_cal", RunImageCalAction, NO_ARGS_ACTION_SCHEMA +) +@automation.register_action( + "sx126x.set_mode_tx", SetModeTxAction, NO_ARGS_ACTION_SCHEMA +) +@automation.register_action( + "sx126x.set_mode_rx", SetModeRxAction, NO_ARGS_ACTION_SCHEMA +) +@automation.register_action( + "sx126x.set_mode_sleep", SetModeSleepAction, NO_ARGS_ACTION_SCHEMA +) +@automation.register_action( + "sx126x.set_mode_standby", SetModeStandbyAction, NO_ARGS_ACTION_SCHEMA +) +async def no_args_action_to_code(config, action_id, template_arg, args): + var = cg.new_Pvariable(action_id, template_arg) + await cg.register_parented(var, config[CONF_ID]) + return var + + +SEND_PACKET_ACTION_SCHEMA = cv.maybe_simple_value( + { + cv.GenerateID(): cv.use_id(SX126x), + cv.Required(CONF_DATA): cv.templatable(validate_raw_data), + }, + key=CONF_DATA, +) + + +@automation.register_action( + "sx126x.send_packet", SendPacketAction, SEND_PACKET_ACTION_SCHEMA +) +async def send_packet_action_to_code(config, action_id, template_arg, args): + var = cg.new_Pvariable(action_id, template_arg) + await cg.register_parented(var, config[CONF_ID]) + data = config[CONF_DATA] + if isinstance(data, bytes): + data = list(data) + if cg.is_template(data): + templ = await cg.templatable(data, args, cg.std_vector.template(cg.uint8)) + cg.add(var.set_data_template(templ)) + else: + cg.add(var.set_data_static(data)) + return var diff --git a/esphome/components/sx126x/automation.h b/esphome/components/sx126x/automation.h new file mode 100644 index 0000000000..520ef99718 --- /dev/null +++ b/esphome/components/sx126x/automation.h @@ -0,0 +1,62 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/core/automation.h" +#include "esphome/components/sx126x/sx126x.h" + +namespace esphome { +namespace sx126x { + +template class RunImageCalAction : public Action, public Parented { + public: + void play(Ts... x) override { this->parent_->run_image_cal(); } +}; + +template class SendPacketAction : public Action, public Parented { + public: + void set_data_template(std::function(Ts...)> func) { + this->data_func_ = func; + this->static_ = false; + } + + void set_data_static(const std::vector &data) { + this->data_static_ = data; + this->static_ = true; + } + + void play(Ts... x) override { + if (this->static_) { + this->parent_->transmit_packet(this->data_static_); + } else { + this->parent_->transmit_packet(this->data_func_(x...)); + } + } + + protected: + bool static_{false}; + std::function(Ts...)> data_func_{}; + std::vector data_static_{}; +}; + +template class SetModeTxAction : public Action, public Parented { + public: + void play(Ts... x) override { this->parent_->set_mode_tx(); } +}; + +template class SetModeRxAction : public Action, public Parented { + public: + void play(Ts... x) override { this->parent_->set_mode_rx(); } +}; + +template class SetModeSleepAction : public Action, public Parented { + public: + void play(Ts... x) override { this->parent_->set_mode_sleep(); } +}; + +template class SetModeStandbyAction : public Action, public Parented { + public: + void play(Ts... x) override { this->parent_->set_mode_standby(STDBY_XOSC); } +}; + +} // namespace sx126x +} // namespace esphome diff --git a/esphome/components/sx126x/packet_transport/__init__.py b/esphome/components/sx126x/packet_transport/__init__.py new file mode 100644 index 0000000000..4d79b23ac1 --- /dev/null +++ b/esphome/components/sx126x/packet_transport/__init__.py @@ -0,0 +1,26 @@ +import esphome.codegen as cg +from esphome.components.packet_transport import ( + PacketTransport, + new_packet_transport, + transport_schema, +) +import esphome.config_validation as cv +from esphome.cpp_types import PollingComponent + +from .. import CONF_SX126X_ID, SX126x, SX126xListener, sx126x_ns + +SX126xTransport = sx126x_ns.class_( + "SX126xTransport", PacketTransport, PollingComponent, SX126xListener +) + +CONFIG_SCHEMA = transport_schema(SX126xTransport).extend( + { + cv.GenerateID(CONF_SX126X_ID): cv.use_id(SX126x), + } +) + + +async def to_code(config): + var, _ = await new_packet_transport(config) + sx126x = await cg.get_variable(config[CONF_SX126X_ID]) + cg.add(var.set_parent(sx126x)) diff --git a/esphome/components/sx126x/packet_transport/sx126x_transport.cpp b/esphome/components/sx126x/packet_transport/sx126x_transport.cpp new file mode 100644 index 0000000000..2cfc4b700e --- /dev/null +++ b/esphome/components/sx126x/packet_transport/sx126x_transport.cpp @@ -0,0 +1,26 @@ +#include "esphome/core/log.h" +#include "esphome/core/application.h" +#include "sx126x_transport.h" + +namespace esphome { +namespace sx126x { + +static const char *const TAG = "sx126x_transport"; + +void SX126xTransport::setup() { + PacketTransport::setup(); + this->parent_->register_listener(this); +} + +void SX126xTransport::update() { + PacketTransport::update(); + this->updated_ = true; + this->resend_data_ = true; +} + +void SX126xTransport::send_packet(const std::vector &buf) const { this->parent_->transmit_packet(buf); } + +void SX126xTransport::on_packet(const std::vector &packet, float rssi, float snr) { this->process_(packet); } + +} // namespace sx126x +} // namespace esphome diff --git a/esphome/components/sx126x/packet_transport/sx126x_transport.h b/esphome/components/sx126x/packet_transport/sx126x_transport.h new file mode 100644 index 0000000000..755d30417d --- /dev/null +++ b/esphome/components/sx126x/packet_transport/sx126x_transport.h @@ -0,0 +1,25 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/sx126x/sx126x.h" +#include "esphome/components/packet_transport/packet_transport.h" +#include + +namespace esphome { +namespace sx126x { + +class SX126xTransport : public packet_transport::PacketTransport, public Parented, public SX126xListener { + public: + void setup() override; + void update() override; + void on_packet(const std::vector &packet, float rssi, float snr) override; + float get_setup_priority() const override { return setup_priority::AFTER_WIFI; } + + protected: + void send_packet(const std::vector &buf) const override; + bool should_send() override { return true; } + size_t get_max_packet_size() override { return this->parent_->get_max_packet_size(); } +}; + +} // namespace sx126x +} // namespace esphome diff --git a/esphome/components/sx126x/sx126x.cpp b/esphome/components/sx126x/sx126x.cpp new file mode 100644 index 0000000000..b1c81b324a --- /dev/null +++ b/esphome/components/sx126x/sx126x.cpp @@ -0,0 +1,523 @@ +#include "sx126x.h" +#include "esphome/core/hal.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace sx126x { + +static const char *const TAG = "sx126x"; +static const uint16_t RAMP[8] = {10, 20, 40, 80, 200, 800, 1700, 3400}; +static const uint32_t BW_HZ[31] = {4800, 5800, 7300, 9700, 11700, 14600, 19500, 23400, 29300, 39000, 46900, + 58600, 78200, 93800, 117300, 156200, 187200, 234300, 312000, 373600, 467000, 7810, + 10420, 15630, 20830, 31250, 41670, 62500, 125000, 250000, 500000}; +static const uint8_t BW_LORA[10] = {LORA_BW_7810, LORA_BW_10420, LORA_BW_15630, LORA_BW_20830, LORA_BW_31250, + LORA_BW_41670, LORA_BW_62500, LORA_BW_125000, LORA_BW_250000, LORA_BW_500000}; +static const uint8_t BW_FSK[21] = { + FSK_BW_4800, FSK_BW_5800, FSK_BW_7300, FSK_BW_9700, FSK_BW_11700, FSK_BW_14600, FSK_BW_19500, + FSK_BW_23400, FSK_BW_29300, FSK_BW_39000, FSK_BW_46900, FSK_BW_58600, FSK_BW_78200, FSK_BW_93800, + FSK_BW_117300, FSK_BW_156200, FSK_BW_187200, FSK_BW_234300, FSK_BW_312000, FSK_BW_373600, FSK_BW_467000}; + +static constexpr uint32_t RESET_DELAY_HIGH_US = 5000; +static constexpr uint32_t RESET_DELAY_LOW_US = 2000; +static constexpr uint32_t SWITCHING_DELAY_US = 1; +static constexpr uint32_t TRANSMIT_TIMEOUT_MS = 4000; +static constexpr uint32_t BUSY_TIMEOUT_MS = 20; + +// OCP (Over Current Protection) values +static constexpr uint8_t OCP_80MA = 0x18; // 80 mA max current +static constexpr uint8_t OCP_140MA = 0x38; // 140 mA max current + +// LoRa low data rate optimization threshold +static constexpr float LOW_DATA_RATE_OPTIMIZE_THRESHOLD = 16.38f; // 16.38 ms + +uint8_t SX126x::read_fifo_(uint8_t offset, std::vector &packet) { + this->wait_busy_(); + this->enable(); + this->transfer_byte(RADIO_READ_BUFFER); + this->transfer_byte(offset); + uint8_t status = this->transfer_byte(0x00); + for (uint8_t &byte : packet) { + byte = this->transfer_byte(0x00); + } + this->disable(); + return status; +} + +void SX126x::write_fifo_(uint8_t offset, const std::vector &packet) { + this->wait_busy_(); + this->enable(); + this->transfer_byte(RADIO_WRITE_BUFFER); + this->transfer_byte(offset); + for (const uint8_t &byte : packet) { + this->transfer_byte(byte); + } + this->disable(); + delayMicroseconds(SWITCHING_DELAY_US); +} + +uint8_t SX126x::read_opcode_(uint8_t opcode, uint8_t *data, uint8_t size) { + this->wait_busy_(); + this->enable(); + this->transfer_byte(opcode); + uint8_t status = this->transfer_byte(0x00); + for (int32_t i = 0; i < size; i++) { + data[i] = this->transfer_byte(0x00); + } + this->disable(); + return status; +} + +void SX126x::write_opcode_(uint8_t opcode, uint8_t *data, uint8_t size) { + this->wait_busy_(); + this->enable(); + this->transfer_byte(opcode); + for (int32_t i = 0; i < size; i++) { + this->transfer_byte(data[i]); + } + this->disable(); + delayMicroseconds(SWITCHING_DELAY_US); +} + +void SX126x::read_register_(uint16_t reg, uint8_t *data, uint8_t size) { + this->wait_busy_(); + this->enable(); + this->write_byte(RADIO_READ_REGISTER); + this->write_byte((reg >> 8) & 0xFF); + this->write_byte((reg >> 0) & 0xFF); + this->write_byte(0x00); + for (int32_t i = 0; i < size; i++) { + data[i] = this->transfer_byte(0x00); + } + this->disable(); +} + +void SX126x::write_register_(uint16_t reg, uint8_t *data, uint8_t size) { + this->wait_busy_(); + this->enable(); + this->write_byte(RADIO_WRITE_REGISTER); + this->write_byte((reg >> 8) & 0xFF); + this->write_byte((reg >> 0) & 0xFF); + for (int32_t i = 0; i < size; i++) { + this->transfer_byte(data[i]); + } + this->disable(); + delayMicroseconds(SWITCHING_DELAY_US); +} + +void SX126x::setup() { + ESP_LOGCONFIG(TAG, "Running setup"); + + // setup pins + this->busy_pin_->setup(); + this->rst_pin_->setup(); + this->dio1_pin_->setup(); + + // start spi + this->spi_setup(); + + // configure rf + this->configure(); +} + +void SX126x::configure() { + uint8_t buf[8]; + + // toggle chip reset + this->rst_pin_->digital_write(true); + delayMicroseconds(RESET_DELAY_HIGH_US); + this->rst_pin_->digital_write(false); + delayMicroseconds(RESET_DELAY_LOW_US); + this->rst_pin_->digital_write(true); + delayMicroseconds(RESET_DELAY_HIGH_US); + + // wakeup + this->read_opcode_(RADIO_GET_STATUS, nullptr, 0); + + // config tcxo + if (this->tcxo_voltage_ != TCXO_CTRL_NONE) { + uint32_t delay = this->tcxo_delay_ >> 6; + buf[0] = this->tcxo_voltage_; + buf[1] = (delay >> 16) & 0xFF; + buf[2] = (delay >> 8) & 0xFF; + buf[3] = (delay >> 0) & 0xFF; + this->write_opcode_(RADIO_SET_TCXOMODE, buf, 4); + buf[0] = 0x7F; + this->write_opcode_(RADIO_CALIBRATE, buf, 1); + } + + // clear errors + buf[0] = 0x00; + buf[1] = 0x00; + this->write_opcode_(RADIO_CLR_ERROR, buf, 2); + + // rf switch + if (this->rf_switch_) { + buf[0] = 0x01; + this->write_opcode_(RADIO_SET_RFSWITCHMODE, buf, 1); + } + + // check silicon version to make sure hw is ok + this->read_register_(REG_VERSION_STRING, (uint8_t *) this->version_, 16); + if (strncmp(this->version_, "SX126", 5) != 0 && strncmp(this->version_, "LLCC68", 6) != 0) { + this->mark_failed(); + return; + } + + // setup packet type + buf[0] = this->modulation_; + this->write_opcode_(RADIO_SET_PACKETTYPE, buf, 1); + + // calibrate image + this->run_image_cal(); + + // set frequency + uint64_t freq = ((uint64_t) this->frequency_ << 25) / XTAL_FREQ; + buf[0] = (uint8_t) ((freq >> 24) & 0xFF); + buf[1] = (uint8_t) ((freq >> 16) & 0xFF); + buf[2] = (uint8_t) ((freq >> 8) & 0xFF); + buf[3] = (uint8_t) (freq & 0xFF); + this->write_opcode_(RADIO_SET_RFFREQUENCY, buf, 4); + + // configure pa + int8_t pa_power = this->pa_power_; + if (this->hw_version_ == "sx1261") { + // the following values were taken from section 13.1.14.1 table 13-21 + // in rev 2.1 of the datasheet + if (pa_power == 15) { + uint8_t cfg[4] = {0x06, 0x00, 0x01, 0x01}; + this->write_opcode_(RADIO_SET_PACONFIG, cfg, 4); + } else { + uint8_t cfg[4] = {0x04, 0x00, 0x01, 0x01}; + this->write_opcode_(RADIO_SET_PACONFIG, cfg, 4); + } + pa_power = std::max(pa_power, (int8_t) -3); + pa_power = std::min(pa_power, (int8_t) 14); + buf[0] = OCP_80MA; + this->write_register_(REG_OCP, buf, 1); + } else { + // the following values were taken from section 13.1.14.1 table 13-21 + // in rev 2.1 of the datasheet + uint8_t cfg[4] = {0x04, 0x07, 0x00, 0x01}; + this->write_opcode_(RADIO_SET_PACONFIG, cfg, 4); + pa_power = std::max(pa_power, (int8_t) -3); + pa_power = std::min(pa_power, (int8_t) 22); + buf[0] = OCP_140MA; + this->write_register_(REG_OCP, buf, 1); + } + buf[0] = pa_power; + buf[1] = this->pa_ramp_; + this->write_opcode_(RADIO_SET_TXPARAMS, buf, 2); + + // configure modem + if (this->modulation_ == PACKET_TYPE_LORA) { + // set modulation params + float duration = 1000.0f * std::pow(2, this->spreading_factor_) / BW_HZ[this->bandwidth_]; + buf[0] = this->spreading_factor_; + buf[1] = BW_LORA[this->bandwidth_ - SX126X_BW_7810]; + buf[2] = this->coding_rate_; + buf[3] = (duration > LOW_DATA_RATE_OPTIMIZE_THRESHOLD) ? 0x01 : 0x00; + this->write_opcode_(RADIO_SET_MODULATIONPARAMS, buf, 4); + + // set packet params and sync word + this->set_packet_params_(this->payload_length_); + if (this->sync_value_.size() == 2) { + this->write_register_(REG_LORA_SYNCWORD, this->sync_value_.data(), this->sync_value_.size()); + } + } else { + // set modulation params + uint32_t bitrate = ((uint64_t) XTAL_FREQ * 32) / this->bitrate_; + uint32_t fdev = ((uint64_t) this->deviation_ << 25) / XTAL_FREQ; + buf[0] = (bitrate >> 16) & 0xFF; + buf[1] = (bitrate >> 8) & 0xFF; + buf[2] = (bitrate >> 0) & 0xFF; + buf[3] = this->shaping_; + buf[4] = BW_FSK[this->bandwidth_ - SX126X_BW_4800]; + buf[5] = (fdev >> 16) & 0xFF; + buf[6] = (fdev >> 8) & 0xFF; + buf[7] = (fdev >> 0) & 0xFF; + this->write_opcode_(RADIO_SET_MODULATIONPARAMS, buf, 8); + + // set packet params and sync word + this->set_packet_params_(this->payload_length_); + if (!this->sync_value_.empty()) { + this->write_register_(REG_GFSK_SYNCWORD, this->sync_value_.data(), this->sync_value_.size()); + } + } + + // switch to rx or sleep + if (this->rx_start_) { + this->set_mode_rx(); + } else { + this->set_mode_sleep(); + } +} + +size_t SX126x::get_max_packet_size() { + if (this->payload_length_ > 0) { + return this->payload_length_; + } + return 255; +} + +void SX126x::set_packet_params_(uint8_t payload_length) { + uint8_t buf[9]; + if (this->modulation_ == PACKET_TYPE_LORA) { + buf[0] = (this->preamble_size_ >> 8) & 0xFF; + buf[1] = (this->preamble_size_ >> 0) & 0xFF; + buf[2] = (this->payload_length_ > 0) ? 0x01 : 0x00; + buf[3] = payload_length; + buf[4] = (this->crc_enable_) ? 0x01 : 0x00; + buf[5] = 0x00; + this->write_opcode_(RADIO_SET_PACKETPARAMS, buf, 6); + } else { + uint16_t preamble_size = this->preamble_size_ * 8; + buf[0] = (preamble_size >> 8) & 0xFF; + buf[1] = (preamble_size >> 0) & 0xFF; + buf[2] = (this->preamble_detect_ > 0) ? ((this->preamble_detect_ - 1) | 0x04) : 0x00; + buf[3] = this->sync_value_.size() * 8; + buf[4] = 0x00; + buf[5] = 0x00; + buf[6] = payload_length; + buf[7] = this->crc_enable_ ? 0x06 : 0x01; + buf[8] = 0x00; + this->write_opcode_(RADIO_SET_PACKETPARAMS, buf, 9); + } +} + +SX126xError SX126x::transmit_packet(const std::vector &packet) { + if (this->payload_length_ > 0 && this->payload_length_ != packet.size()) { + ESP_LOGE(TAG, "Packet size does not match config"); + return SX126xError::INVALID_PARAMS; + } + if (packet.empty() || packet.size() > this->get_max_packet_size()) { + ESP_LOGE(TAG, "Packet size out of range"); + return SX126xError::INVALID_PARAMS; + } + + SX126xError ret = SX126xError::NONE; + this->set_mode_standby(STDBY_XOSC); + if (this->payload_length_ == 0) { + this->set_packet_params_(packet.size()); + } + this->write_fifo_(0x00, packet); + this->set_mode_tx(); + + // wait until transmit completes, typically the delay will be less than 100 ms + uint32_t start = millis(); + while (!this->dio1_pin_->digital_read()) { + if (millis() - start > TRANSMIT_TIMEOUT_MS) { + ESP_LOGE(TAG, "Transmit packet failure"); + ret = SX126xError::TIMEOUT; + break; + } + } + + uint8_t buf[2]; + buf[0] = 0xFF; + buf[1] = 0xFF; + this->write_opcode_(RADIO_CLR_IRQSTATUS, buf, 2); + if (this->rx_start_) { + this->set_mode_rx(); + } else { + this->set_mode_sleep(); + } + return ret; +} + +void SX126x::call_listeners_(const std::vector &packet, float rssi, float snr) { + for (auto &listener : this->listeners_) { + listener->on_packet(packet, rssi, snr); + } + this->packet_trigger_->trigger(packet, rssi, snr); +} + +void SX126x::loop() { + if (!this->dio1_pin_->digital_read()) { + return; + } + + uint16_t status; + uint8_t buf[3]; + uint8_t rssi; + int8_t snr; + this->read_opcode_(RADIO_GET_IRQSTATUS, buf, 2); + this->write_opcode_(RADIO_CLR_IRQSTATUS, buf, 2); + status = (buf[0] << 8) | buf[1]; + if ((status & IRQ_RX_DONE) == IRQ_RX_DONE) { + if ((status & IRQ_CRC_ERROR) != IRQ_CRC_ERROR) { + this->read_opcode_(RADIO_GET_PACKETSTATUS, buf, 3); + if (this->modulation_ == PACKET_TYPE_LORA) { + rssi = buf[0]; + snr = buf[1]; + } else { + rssi = buf[2]; + snr = 0; + } + this->read_opcode_(RADIO_GET_RXBUFFERSTATUS, buf, 2); + this->packet_.resize(buf[0]); + this->read_fifo_(buf[1], this->packet_); + this->call_listeners_(this->packet_, (float) rssi / -2.0f, (float) snr / 4.0f); + } + } +} + +void SX126x::run_image_cal() { + // the following values were taken from section 9.2.1 table 9-2 + // in rev 2.1 of the datasheet + uint8_t buf[2] = {0, 0}; + if (this->frequency_ > 900000000) { + buf[0] = 0xE1; + buf[1] = 0xE9; + } else if (this->frequency_ > 850000000) { + buf[0] = 0xD7; + buf[1] = 0xD8; + } else if (this->frequency_ > 770000000) { + buf[0] = 0xC1; + buf[1] = 0xC5; + } else if (this->frequency_ > 460000000) { + buf[0] = 0x75; + buf[1] = 0x81; + } else if (this->frequency_ > 425000000) { + buf[0] = 0x6B; + buf[1] = 0x6F; + } + if (buf[0] > 0 && buf[1] > 0) { + this->write_opcode_(RADIO_CALIBRATEIMAGE, buf, 2); + } +} + +void SX126x::set_mode_rx() { + uint8_t buf[8]; + + // configure irq params + uint16_t irq = IRQ_RX_DONE | IRQ_RX_TX_TIMEOUT | IRQ_CRC_ERROR; + buf[0] = (irq >> 8) & 0xFF; + buf[1] = (irq >> 0) & 0xFF; + buf[2] = (irq >> 8) & 0xFF; + buf[3] = (irq >> 0) & 0xFF; + buf[4] = (IRQ_RADIO_NONE >> 8) & 0xFF; + buf[5] = (IRQ_RADIO_NONE >> 0) & 0xFF; + buf[6] = (IRQ_RADIO_NONE >> 8) & 0xFF; + buf[7] = (IRQ_RADIO_NONE >> 0) & 0xFF; + this->write_opcode_(RADIO_SET_DIOIRQPARAMS, buf, 8); + + // set timeout to 0 + buf[0] = 0x00; + this->write_opcode_(RADIO_SET_LORASYMBTIMEOUT, buf, 1); + + // switch to continuous mode rx + buf[0] = 0xFF; + buf[1] = 0xFF; + buf[2] = 0xFF; + this->write_opcode_(RADIO_SET_RX, buf, 3); +} + +void SX126x::set_mode_tx() { + uint8_t buf[8]; + + // configure irq params + uint16_t irq = IRQ_TX_DONE | IRQ_RX_TX_TIMEOUT; + buf[0] = (irq >> 8) & 0xFF; + buf[1] = (irq >> 0) & 0xFF; + buf[2] = (irq >> 8) & 0xFF; + buf[3] = (irq >> 0) & 0xFF; + buf[4] = (IRQ_RADIO_NONE >> 8) & 0xFF; + buf[5] = (IRQ_RADIO_NONE >> 0) & 0xFF; + buf[6] = (IRQ_RADIO_NONE >> 8) & 0xFF; + buf[7] = (IRQ_RADIO_NONE >> 0) & 0xFF; + this->write_opcode_(RADIO_SET_DIOIRQPARAMS, buf, 8); + + // switch to single mode tx + buf[0] = 0x00; + buf[1] = 0x00; + buf[2] = 0x00; + this->write_opcode_(RADIO_SET_TX, buf, 3); +} + +void SX126x::set_mode_sleep() { + uint8_t buf[1]; + buf[0] = 0x05; + this->write_opcode_(RADIO_SET_SLEEP, buf, 1); +} + +void SX126x::set_mode_standby(SX126xStandbyMode mode) { + uint8_t buf[1]; + buf[0] = mode; + this->write_opcode_(RADIO_SET_STANDBY, buf, 1); +} + +void SX126x::wait_busy_() { + // wait if the device is busy, the maximum delay is only be a few ms + // with most commands taking only a few us + uint32_t start = millis(); + while (this->busy_pin_->digital_read()) { + if (millis() - start > BUSY_TIMEOUT_MS) { + ESP_LOGE(TAG, "Wait busy timeout"); + this->mark_failed(); + break; + } + } +} + +void SX126x::dump_config() { + ESP_LOGCONFIG(TAG, "SX126x:"); + LOG_PIN(" CS Pin: ", this->cs_); + LOG_PIN(" BUSY Pin: ", this->busy_pin_); + LOG_PIN(" RST Pin: ", this->rst_pin_); + LOG_PIN(" DIO1 Pin: ", this->dio1_pin_); + ESP_LOGCONFIG(TAG, + " HW Version: %15s\n" + " Frequency: %" PRIu32 " Hz\n" + " Bandwidth: %" PRIu32 " Hz\n" + " PA Power: %" PRId8 " dBm\n" + " PA Ramp: %" PRIu16 " us\n" + " Payload Length: %" PRIu32 "\n" + " CRC Enable: %s\n" + " Rx Start: %s", + this->version_, this->frequency_, BW_HZ[this->bandwidth_], this->pa_power_, RAMP[this->pa_ramp_], + this->payload_length_, TRUEFALSE(this->crc_enable_), TRUEFALSE(this->rx_start_)); + if (this->modulation_ == PACKET_TYPE_GFSK) { + const char *shaping = "NONE"; + if (this->shaping_ == GAUSSIAN_BT_0_3) { + shaping = "GAUSSIAN_BT_0_3"; + } else if (this->shaping_ == GAUSSIAN_BT_0_5) { + shaping = "GAUSSIAN_BT_0_5"; + } else if (this->shaping_ == GAUSSIAN_BT_0_7) { + shaping = "GAUSSIAN_BT_0_7"; + } else if (this->shaping_ == GAUSSIAN_BT_1_0) { + shaping = "GAUSSIAN_BT_1_0"; + } + ESP_LOGCONFIG(TAG, + " Modulation: FSK\n" + " Deviation: %" PRIu32 " Hz\n" + " Shaping: %s\n" + " Preamble Size: %" PRIu16 "\n" + " Preamble Detect: %" PRIu16 "\n" + " Bitrate: %" PRIu32 "b/s", + this->deviation_, shaping, this->preamble_size_, this->preamble_detect_, this->bitrate_); + } else if (this->modulation_ == PACKET_TYPE_LORA) { + const char *cr = "4/8"; + if (this->coding_rate_ == LORA_CR_4_5) { + cr = "4/5"; + } else if (this->coding_rate_ == LORA_CR_4_6) { + cr = "4/6"; + } else if (this->coding_rate_ == LORA_CR_4_7) { + cr = "4/7"; + } + ESP_LOGCONFIG(TAG, + " Modulation: LORA\n" + " Spreading Factor: %" PRIu8 "\n" + " Coding Rate: %s\n" + " Preamble Size: %" PRIu16, + this->spreading_factor_, cr, this->preamble_size_); + } + if (!this->sync_value_.empty()) { + ESP_LOGCONFIG(TAG, " Sync Value: 0x%s", format_hex(this->sync_value_).c_str()); + } + if (this->is_failed()) { + ESP_LOGE(TAG, "Configuring SX126x failed"); + } +} + +} // namespace sx126x +} // namespace esphome diff --git a/esphome/components/sx126x/sx126x.h b/esphome/components/sx126x/sx126x.h new file mode 100644 index 0000000000..fd5c37942d --- /dev/null +++ b/esphome/components/sx126x/sx126x.h @@ -0,0 +1,140 @@ +#pragma once + +#include "esphome/components/spi/spi.h" +#include "esphome/core/automation.h" +#include "esphome/core/component.h" +#include "sx126x_reg.h" +#include +#include + +namespace esphome { +namespace sx126x { + +enum SX126xBw : uint8_t { + // FSK + SX126X_BW_4800, + SX126X_BW_5800, + SX126X_BW_7300, + SX126X_BW_9700, + SX126X_BW_11700, + SX126X_BW_14600, + SX126X_BW_19500, + SX126X_BW_23400, + SX126X_BW_29300, + SX126X_BW_39000, + SX126X_BW_46900, + SX126X_BW_58600, + SX126X_BW_78200, + SX126X_BW_93800, + SX126X_BW_117300, + SX126X_BW_156200, + SX126X_BW_187200, + SX126X_BW_234300, + SX126X_BW_312000, + SX126X_BW_373600, + SX126X_BW_467000, + // LORA + SX126X_BW_7810, + SX126X_BW_10420, + SX126X_BW_15630, + SX126X_BW_20830, + SX126X_BW_31250, + SX126X_BW_41670, + SX126X_BW_62500, + SX126X_BW_125000, + SX126X_BW_250000, + SX126X_BW_500000, +}; + +enum class SX126xError { NONE = 0, TIMEOUT, INVALID_PARAMS }; + +class SX126xListener { + public: + virtual void on_packet(const std::vector &packet, float rssi, float snr) = 0; +}; + +class SX126x : public Component, + public spi::SPIDevice { + public: + size_t get_max_packet_size(); + float get_setup_priority() const override { return setup_priority::PROCESSOR; } + void setup() override; + void loop() override; + void dump_config() override; + void set_bandwidth(SX126xBw bandwidth) { this->bandwidth_ = bandwidth; } + void set_bitrate(uint32_t bitrate) { this->bitrate_ = bitrate; } + void set_busy_pin(InternalGPIOPin *busy_pin) { this->busy_pin_ = busy_pin; } + void set_coding_rate(uint8_t coding_rate) { this->coding_rate_ = coding_rate; } + void set_crc_enable(bool crc_enable) { this->crc_enable_ = crc_enable; } + void set_deviation(uint32_t deviation) { this->deviation_ = deviation; } + void set_dio1_pin(InternalGPIOPin *dio1_pin) { this->dio1_pin_ = dio1_pin; } + void set_frequency(uint32_t frequency) { this->frequency_ = frequency; } + void set_hw_version(const std::string &hw_version) { this->hw_version_ = hw_version; } + void set_mode_rx(); + void set_mode_tx(); + void set_mode_standby(SX126xStandbyMode mode); + void set_mode_sleep(); + void set_modulation(uint8_t modulation) { this->modulation_ = modulation; } + void set_pa_power(int8_t power) { this->pa_power_ = power; } + void set_pa_ramp(uint8_t ramp) { this->pa_ramp_ = ramp; } + void set_payload_length(uint8_t payload_length) { this->payload_length_ = payload_length; } + void set_preamble_detect(uint16_t preamble_detect) { this->preamble_detect_ = preamble_detect; } + void set_preamble_size(uint16_t preamble_size) { this->preamble_size_ = preamble_size; } + void set_rst_pin(InternalGPIOPin *rst_pin) { this->rst_pin_ = rst_pin; } + void set_rx_start(bool rx_start) { this->rx_start_ = rx_start; } + void set_rf_switch(bool rf_switch) { this->rf_switch_ = rf_switch; } + void set_shaping(uint8_t shaping) { this->shaping_ = shaping; } + void set_spreading_factor(uint8_t spreading_factor) { this->spreading_factor_ = spreading_factor; } + void set_sync_value(const std::vector &sync_value) { this->sync_value_ = sync_value; } + void set_tcxo_voltage(uint8_t tcxo_voltage) { this->tcxo_voltage_ = tcxo_voltage; } + void set_tcxo_delay(uint32_t tcxo_delay) { this->tcxo_delay_ = tcxo_delay; } + void run_image_cal(); + void configure(); + SX126xError transmit_packet(const std::vector &packet); + void register_listener(SX126xListener *listener) { this->listeners_.push_back(listener); } + Trigger, float, float> *get_packet_trigger() const { return this->packet_trigger_; }; + + protected: + void configure_fsk_ook_(); + void configure_lora_(); + void set_packet_params_(uint8_t payload_length); + uint8_t read_fifo_(uint8_t offset, std::vector &packet); + void write_fifo_(uint8_t offset, const std::vector &packet); + void write_opcode_(uint8_t opcode, uint8_t *data, uint8_t size); + uint8_t read_opcode_(uint8_t opcode, uint8_t *data, uint8_t size); + void write_register_(uint16_t reg, uint8_t *data, uint8_t size); + void read_register_(uint16_t reg, uint8_t *data, uint8_t size); + void call_listeners_(const std::vector &packet, float rssi, float snr); + void wait_busy_(); + Trigger, float, float> *packet_trigger_{new Trigger, float, float>()}; + std::vector listeners_; + std::vector packet_; + std::vector sync_value_; + InternalGPIOPin *busy_pin_{nullptr}; + InternalGPIOPin *dio1_pin_{nullptr}; + InternalGPIOPin *rst_pin_{nullptr}; + std::string hw_version_; + char version_[16]; + SX126xBw bandwidth_{SX126X_BW_125000}; + uint32_t bitrate_{0}; + uint32_t deviation_{0}; + uint32_t frequency_{0}; + uint32_t payload_length_{0}; + uint32_t tcxo_delay_{0}; + uint16_t preamble_detect_{0}; + uint16_t preamble_size_{0}; + uint8_t tcxo_voltage_{0}; + uint8_t coding_rate_{0}; + uint8_t modulation_{PACKET_TYPE_LORA}; + uint8_t pa_ramp_{0}; + uint8_t shaping_{0}; + uint8_t spreading_factor_{0}; + int8_t pa_power_{0}; + bool crc_enable_{false}; + bool rx_start_{false}; + bool rf_switch_{false}; +}; + +} // namespace sx126x +} // namespace esphome diff --git a/esphome/components/sx126x/sx126x_reg.h b/esphome/components/sx126x/sx126x_reg.h new file mode 100644 index 0000000000..3b12d822b5 --- /dev/null +++ b/esphome/components/sx126x/sx126x_reg.h @@ -0,0 +1,163 @@ +#pragma once + +#include "esphome/core/hal.h" + +namespace esphome { +namespace sx126x { + +static const uint32_t XTAL_FREQ = 32000000; + +enum SX126xOpCode : uint8_t { + RADIO_GET_STATUS = 0xC0, + RADIO_WRITE_REGISTER = 0x0D, + RADIO_READ_REGISTER = 0x1D, + RADIO_WRITE_BUFFER = 0x0E, + RADIO_READ_BUFFER = 0x1E, + RADIO_SET_SLEEP = 0x84, + RADIO_SET_STANDBY = 0x80, + RADIO_SET_FS = 0xC1, + RADIO_SET_TX = 0x83, + RADIO_SET_RX = 0x82, + RADIO_SET_RXDUTYCYCLE = 0x94, + RADIO_SET_CAD = 0xC5, + RADIO_SET_TXCONTINUOUSWAVE = 0xD1, + RADIO_SET_TXCONTINUOUSPREAMBLE = 0xD2, + RADIO_SET_PACKETTYPE = 0x8A, + RADIO_GET_PACKETTYPE = 0x11, + RADIO_SET_RFFREQUENCY = 0x86, + RADIO_SET_TXPARAMS = 0x8E, + RADIO_SET_PACONFIG = 0x95, + RADIO_SET_CADPARAMS = 0x88, + RADIO_SET_BUFFERBASEADDRESS = 0x8F, + RADIO_SET_MODULATIONPARAMS = 0x8B, + RADIO_SET_PACKETPARAMS = 0x8C, + RADIO_GET_RXBUFFERSTATUS = 0x13, + RADIO_GET_PACKETSTATUS = 0x14, + RADIO_GET_RSSIINST = 0x15, + RADIO_GET_STATS = 0x10, + RADIO_RESET_STATS = 0x00, + RADIO_SET_DIOIRQPARAMS = 0x08, + RADIO_GET_IRQSTATUS = 0x12, + RADIO_CLR_IRQSTATUS = 0x02, + RADIO_CALIBRATE = 0x89, + RADIO_CALIBRATEIMAGE = 0x98, + RADIO_SET_REGULATORMODE = 0x96, + RADIO_GET_ERROR = 0x17, + RADIO_CLR_ERROR = 0x07, + RADIO_SET_TCXOMODE = 0x97, + RADIO_SET_TXFALLBACKMODE = 0x93, + RADIO_SET_RFSWITCHMODE = 0x9D, + RADIO_SET_STOPRXTIMERONPREAMBLE = 0x9F, + RADIO_SET_LORASYMBTIMEOUT = 0xA0, +}; + +enum SX126xRegister : uint16_t { + REG_VERSION_STRING = 0x0320, + REG_GFSK_SYNCWORD = 0x06C0, + REG_LORA_SYNCWORD = 0x0740, + REG_OCP = 0x08E7, +}; + +enum SX126xStandbyMode : uint8_t { + STDBY_RC = 0x00, + STDBY_XOSC = 0x01, +}; + +enum SX126xPacketType : uint8_t { + PACKET_TYPE_GFSK = 0x00, + PACKET_TYPE_LORA = 0x01, + PACKET_TYPE_LRHSS = 0x03, +}; + +enum SX126xFskBw : uint8_t { + FSK_BW_4800 = 0x1F, + FSK_BW_5800 = 0x17, + FSK_BW_7300 = 0x0F, + FSK_BW_9700 = 0x1E, + FSK_BW_11700 = 0x16, + FSK_BW_14600 = 0x0E, + FSK_BW_19500 = 0x1D, + FSK_BW_23400 = 0x15, + FSK_BW_29300 = 0x0D, + FSK_BW_39000 = 0x1C, + FSK_BW_46900 = 0x14, + FSK_BW_58600 = 0x0C, + FSK_BW_78200 = 0x1B, + FSK_BW_93800 = 0x13, + FSK_BW_117300 = 0x0B, + FSK_BW_156200 = 0x1A, + FSK_BW_187200 = 0x12, + FSK_BW_234300 = 0x0A, + FSK_BW_312000 = 0x19, + FSK_BW_373600 = 0x11, + FSK_BW_467000 = 0x09, +}; + +enum SX126xLoraBw : uint8_t { + LORA_BW_7810 = 0x00, + LORA_BW_10420 = 0x08, + LORA_BW_15630 = 0x01, + LORA_BW_20830 = 0x09, + LORA_BW_31250 = 0x02, + LORA_BW_41670 = 0x0A, + LORA_BW_62500 = 0x03, + LORA_BW_125000 = 0x04, + LORA_BW_250000 = 0x05, + LORA_BW_500000 = 0x06, +}; + +enum SX126xLoraCr : uint8_t { + LORA_CR_4_5 = 0x01, + LORA_CR_4_6 = 0x02, + LORA_CR_4_7 = 0x03, + LORA_CR_4_8 = 0x04, +}; + +enum SX126xIrqMasks : uint16_t { + IRQ_RADIO_NONE = 0x0000, + IRQ_TX_DONE = 0x0001, + IRQ_RX_DONE = 0x0002, + IRQ_PREAMBLE_DETECTED = 0x0004, + IRQ_SYNCWORD_VALID = 0x0008, + IRQ_HEADER_VALID = 0x0010, + IRQ_HEADER_ERROR = 0x0020, + IRQ_CRC_ERROR = 0x0040, + IRQ_CAD_DONE = 0x0080, + IRQ_CAD_ACTIVITY_DETECTED = 0x0100, + IRQ_RX_TX_TIMEOUT = 0x0200, + IRQ_RADIO_ALL = 0xFFFF, +}; + +enum SX126xTcxoCtrl : uint8_t { + TCXO_CTRL_1_6V = 0x00, + TCXO_CTRL_1_7V = 0x01, + TCXO_CTRL_1_8V = 0x02, + TCXO_CTRL_2_2V = 0x03, + TCXO_CTRL_2_4V = 0x04, + TCXO_CTRL_2_7V = 0x05, + TCXO_CTRL_3_0V = 0x06, + TCXO_CTRL_3_3V = 0x07, + TCXO_CTRL_NONE = 0xFF, +}; + +enum SX126xPulseShape : uint8_t { + NO_FILTER = 0x00, + GAUSSIAN_BT_0_3 = 0x08, + GAUSSIAN_BT_0_5 = 0x09, + GAUSSIAN_BT_0_7 = 0x0A, + GAUSSIAN_BT_1_0 = 0x0B, +}; + +enum SX126xRampTime : uint8_t { + PA_RAMP_10 = 0x00, + PA_RAMP_20 = 0x01, + PA_RAMP_40 = 0x02, + PA_RAMP_80 = 0x03, + PA_RAMP_200 = 0x04, + PA_RAMP_800 = 0x05, + PA_RAMP_1700 = 0x06, + PA_RAMP_3400 = 0x07, +}; + +} // namespace sx126x +} // namespace esphome diff --git a/esphome/components/sx127x/__init__.py b/esphome/components/sx127x/__init__.py new file mode 100644 index 0000000000..4d034801cc --- /dev/null +++ b/esphome/components/sx127x/__init__.py @@ -0,0 +1,325 @@ +from esphome import automation, pins +import esphome.codegen as cg +from esphome.components import spi +import esphome.config_validation as cv +from esphome.const import CONF_DATA, CONF_FREQUENCY, CONF_ID + +MULTI_CONF = True +CODEOWNERS = ["@swoboda1337"] +DEPENDENCIES = ["spi"] + +CONF_SX127X_ID = "sx127x_id" + +CONF_AUTO_CAL = "auto_cal" +CONF_BANDWIDTH = "bandwidth" +CONF_BITRATE = "bitrate" +CONF_BITSYNC = "bitsync" +CONF_CODING_RATE = "coding_rate" +CONF_CRC_ENABLE = "crc_enable" +CONF_DEVIATION = "deviation" +CONF_DIO0_PIN = "dio0_pin" +CONF_MODULATION = "modulation" +CONF_ON_PACKET = "on_packet" +CONF_PA_PIN = "pa_pin" +CONF_PA_POWER = "pa_power" +CONF_PA_RAMP = "pa_ramp" +CONF_PACKET_MODE = "packet_mode" +CONF_PAYLOAD_LENGTH = "payload_length" +CONF_PREAMBLE_DETECT = "preamble_detect" +CONF_PREAMBLE_ERRORS = "preamble_errors" +CONF_PREAMBLE_POLARITY = "preamble_polarity" +CONF_PREAMBLE_SIZE = "preamble_size" +CONF_RST_PIN = "rst_pin" +CONF_RX_FLOOR = "rx_floor" +CONF_RX_START = "rx_start" +CONF_SHAPING = "shaping" +CONF_SPREADING_FACTOR = "spreading_factor" +CONF_SYNC_VALUE = "sync_value" + +sx127x_ns = cg.esphome_ns.namespace("sx127x") +SX127x = sx127x_ns.class_("SX127x", cg.Component, spi.SPIDevice) +SX127xListener = sx127x_ns.class_("SX127xListener") +SX127xBw = sx127x_ns.enum("SX127xBw") +SX127xOpMode = sx127x_ns.enum("SX127xOpMode") +SX127xPaConfig = sx127x_ns.enum("SX127xPaConfig") +SX127xPaRamp = sx127x_ns.enum("SX127xPaRamp") +SX127xModemCfg1 = sx127x_ns.enum("SX127xModemCfg1") + +BW = { + "2_6kHz": SX127xBw.SX127X_BW_2_6, + "3_1kHz": SX127xBw.SX127X_BW_3_1, + "3_9kHz": SX127xBw.SX127X_BW_3_9, + "5_2kHz": SX127xBw.SX127X_BW_5_2, + "6_3kHz": SX127xBw.SX127X_BW_6_3, + "7_8kHz": SX127xBw.SX127X_BW_7_8, + "10_4kHz": SX127xBw.SX127X_BW_10_4, + "12_5kHz": SX127xBw.SX127X_BW_12_5, + "15_6kHz": SX127xBw.SX127X_BW_15_6, + "20_8kHz": SX127xBw.SX127X_BW_20_8, + "25_0kHz": SX127xBw.SX127X_BW_25_0, + "31_3kHz": SX127xBw.SX127X_BW_31_3, + "41_7kHz": SX127xBw.SX127X_BW_41_7, + "50_0kHz": SX127xBw.SX127X_BW_50_0, + "62_5kHz": SX127xBw.SX127X_BW_62_5, + "83_3kHz": SX127xBw.SX127X_BW_83_3, + "100_0kHz": SX127xBw.SX127X_BW_100_0, + "125_0kHz": SX127xBw.SX127X_BW_125_0, + "166_7kHz": SX127xBw.SX127X_BW_166_7, + "200_0kHz": SX127xBw.SX127X_BW_200_0, + "250_0kHz": SX127xBw.SX127X_BW_250_0, + "500_0kHz": SX127xBw.SX127X_BW_500_0, +} + +CODING_RATE = { + "CR_4_5": SX127xModemCfg1.CODING_RATE_4_5, + "CR_4_6": SX127xModemCfg1.CODING_RATE_4_6, + "CR_4_7": SX127xModemCfg1.CODING_RATE_4_7, + "CR_4_8": SX127xModemCfg1.CODING_RATE_4_8, +} + +MOD = { + "LORA": SX127xOpMode.MOD_LORA, + "FSK": SX127xOpMode.MOD_FSK, + "OOK": SX127xOpMode.MOD_OOK, +} + +PA_PIN = { + "RFO": SX127xPaConfig.PA_PIN_RFO, + "BOOST": SX127xPaConfig.PA_PIN_BOOST, +} + +RAMP = { + "10us": SX127xPaRamp.PA_RAMP_10, + "12us": SX127xPaRamp.PA_RAMP_12, + "15us": SX127xPaRamp.PA_RAMP_15, + "20us": SX127xPaRamp.PA_RAMP_20, + "25us": SX127xPaRamp.PA_RAMP_25, + "31us": SX127xPaRamp.PA_RAMP_31, + "40us": SX127xPaRamp.PA_RAMP_40, + "50us": SX127xPaRamp.PA_RAMP_50, + "62us": SX127xPaRamp.PA_RAMP_62, + "100us": SX127xPaRamp.PA_RAMP_100, + "125us": SX127xPaRamp.PA_RAMP_125, + "250us": SX127xPaRamp.PA_RAMP_250, + "500us": SX127xPaRamp.PA_RAMP_500, + "1000us": SX127xPaRamp.PA_RAMP_1000, + "2000us": SX127xPaRamp.PA_RAMP_2000, + "3400us": SX127xPaRamp.PA_RAMP_3400, +} + +SHAPING = { + "CUTOFF_BR_X_2": SX127xPaRamp.CUTOFF_BR_X_2, + "CUTOFF_BR_X_1": SX127xPaRamp.CUTOFF_BR_X_1, + "GAUSSIAN_BT_0_3": SX127xPaRamp.GAUSSIAN_BT_0_3, + "GAUSSIAN_BT_0_5": SX127xPaRamp.GAUSSIAN_BT_0_5, + "GAUSSIAN_BT_1_0": SX127xPaRamp.GAUSSIAN_BT_1_0, + "NONE": SX127xPaRamp.SHAPING_NONE, +} + +RunImageCalAction = sx127x_ns.class_( + "RunImageCalAction", automation.Action, cg.Parented.template(SX127x) +) +SendPacketAction = sx127x_ns.class_( + "SendPacketAction", automation.Action, cg.Parented.template(SX127x) +) +SetModeTxAction = sx127x_ns.class_( + "SetModeTxAction", automation.Action, cg.Parented.template(SX127x) +) +SetModeRxAction = sx127x_ns.class_( + "SetModeRxAction", automation.Action, cg.Parented.template(SX127x) +) +SetModeSleepAction = sx127x_ns.class_( + "SetModeSleepAction", automation.Action, cg.Parented.template(SX127x) +) +SetModeStandbyAction = sx127x_ns.class_( + "SetModeStandbyAction", automation.Action, cg.Parented.template(SX127x) +) + + +def validate_raw_data(value): + if isinstance(value, str): + return value.encode("utf-8") + if isinstance(value, list): + return cv.Schema([cv.hex_uint8_t])(value) + raise cv.Invalid( + "data must either be a string wrapped in quotes or a list of bytes" + ) + + +def validate_config(config): + if config[CONF_MODULATION] == "LORA": + bws = [ + "7_8kHz", + "10_4kHz", + "15_6kHz", + "20_8kHz", + "31_3kHz", + "41_7kHz", + "62_5kHz", + "125_0kHz", + "250_0kHz", + "500_0kHz", + ] + if config[CONF_BANDWIDTH] not in bws: + raise cv.Invalid(f"{config[CONF_BANDWIDTH]} is not available with LORA") + if CONF_DIO0_PIN not in config: + raise cv.Invalid("Cannot use LoRa without dio0_pin") + if 0 < config[CONF_PREAMBLE_SIZE] < 6: + raise cv.Invalid("Minimum preamble size is 6 with LORA") + if config[CONF_SPREADING_FACTOR] == 6 and config[CONF_PAYLOAD_LENGTH] == 0: + raise cv.Invalid("Payload length must be set when spreading factor is 6") + else: + if config[CONF_BANDWIDTH] == "500_0kHz": + raise cv.Invalid(f"{config[CONF_BANDWIDTH]} is only available with LORA") + if CONF_BITSYNC not in config: + raise cv.Invalid("Config 'bitsync' required with FSK/OOK") + if CONF_PACKET_MODE not in config: + raise cv.Invalid("Config 'packet_mode' required with FSK/OOK") + if config[CONF_PACKET_MODE] and CONF_DIO0_PIN not in config: + raise cv.Invalid("Config 'dio0_pin' required in packet mode") + if config[CONF_PAYLOAD_LENGTH] > 64: + raise cv.Invalid("Payload length must be <= 64 with FSK/OOK") + if config[CONF_PA_PIN] == "RFO" and config[CONF_PA_POWER] > 15: + raise cv.Invalid("PA power must be <= 15 dbm when using the RFO pin") + if config[CONF_PA_PIN] == "BOOST" and config[CONF_PA_POWER] < 2: + raise cv.Invalid("PA power must be >= 2 dbm when using the BOOST pin") + return config + + +CONFIG_SCHEMA = ( + cv.Schema( + { + cv.GenerateID(): cv.declare_id(SX127x), + cv.Optional(CONF_AUTO_CAL, default=True): cv.boolean, + cv.Optional(CONF_BANDWIDTH, default="125_0kHz"): cv.enum(BW), + cv.Optional(CONF_BITRATE, default=4800): cv.int_range(min=500, max=300000), + cv.Optional(CONF_BITSYNC): cv.boolean, + cv.Optional(CONF_CODING_RATE, default="CR_4_5"): cv.enum(CODING_RATE), + cv.Optional(CONF_CRC_ENABLE, default=False): cv.boolean, + cv.Optional(CONF_DEVIATION, default=5000): cv.int_range(min=0, max=100000), + cv.Optional(CONF_DIO0_PIN): pins.internal_gpio_input_pin_schema, + cv.Required(CONF_FREQUENCY): cv.int_range(min=137000000, max=1020000000), + cv.Required(CONF_MODULATION): cv.enum(MOD), + cv.Optional(CONF_ON_PACKET): automation.validate_automation(single=True), + cv.Optional(CONF_PA_PIN, default="BOOST"): cv.enum(PA_PIN), + cv.Optional(CONF_PA_POWER, default=17): cv.int_range(min=0, max=17), + cv.Optional(CONF_PA_RAMP, default="40us"): cv.enum(RAMP), + cv.Optional(CONF_PACKET_MODE): cv.boolean, + cv.Optional(CONF_PAYLOAD_LENGTH, default=0): cv.int_range(min=0, max=256), + cv.Optional(CONF_PREAMBLE_DETECT, default=0): cv.int_range(min=0, max=3), + cv.Optional(CONF_PREAMBLE_ERRORS, default=0): cv.int_range(min=0, max=31), + cv.Optional(CONF_PREAMBLE_POLARITY, default=0xAA): cv.All( + cv.hex_int, cv.one_of(0xAA, 0x55) + ), + cv.Optional(CONF_PREAMBLE_SIZE, default=0): cv.int_range(min=0, max=65535), + cv.Required(CONF_RST_PIN): pins.internal_gpio_output_pin_schema, + cv.Optional(CONF_RX_FLOOR, default=-94): cv.float_range(min=-128, max=-1), + cv.Optional(CONF_RX_START, default=True): cv.boolean, + cv.Optional(CONF_SHAPING, default="NONE"): cv.enum(SHAPING), + cv.Optional(CONF_SPREADING_FACTOR, default=7): cv.int_range(min=6, max=12), + cv.Optional(CONF_SYNC_VALUE, default=[]): cv.ensure_list(cv.hex_uint8_t), + }, + ) + .extend(cv.COMPONENT_SCHEMA) + .extend(spi.spi_device_schema(True, 8e6, "mode0")) + .add_extra(validate_config) +) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) + await spi.register_spi_device(var, config) + if CONF_ON_PACKET in config: + await automation.build_automation( + var.get_packet_trigger(), + [ + (cg.std_vector.template(cg.uint8), "x"), + (cg.float_, "rssi"), + (cg.float_, "snr"), + ], + config[CONF_ON_PACKET], + ) + if CONF_DIO0_PIN in config: + dio0_pin = await cg.gpio_pin_expression(config[CONF_DIO0_PIN]) + cg.add(var.set_dio0_pin(dio0_pin)) + rst_pin = await cg.gpio_pin_expression(config[CONF_RST_PIN]) + cg.add(var.set_rst_pin(rst_pin)) + cg.add(var.set_auto_cal(config[CONF_AUTO_CAL])) + cg.add(var.set_bandwidth(config[CONF_BANDWIDTH])) + cg.add(var.set_frequency(config[CONF_FREQUENCY])) + cg.add(var.set_deviation(config[CONF_DEVIATION])) + cg.add(var.set_modulation(config[CONF_MODULATION])) + if config[CONF_MODULATION] != "LORA": + cg.add(var.set_bitrate(config[CONF_BITRATE])) + cg.add(var.set_bitsync(config[CONF_BITSYNC])) + cg.add(var.set_packet_mode(config[CONF_PACKET_MODE])) + cg.add(var.set_pa_pin(config[CONF_PA_PIN])) + cg.add(var.set_pa_ramp(config[CONF_PA_RAMP])) + cg.add(var.set_pa_power(config[CONF_PA_POWER])) + cg.add(var.set_shaping(config[CONF_SHAPING])) + cg.add(var.set_crc_enable(config[CONF_CRC_ENABLE])) + cg.add(var.set_payload_length(config[CONF_PAYLOAD_LENGTH])) + cg.add(var.set_preamble_detect(config[CONF_PREAMBLE_DETECT])) + cg.add(var.set_preamble_size(config[CONF_PREAMBLE_SIZE])) + cg.add(var.set_preamble_polarity(config[CONF_PREAMBLE_POLARITY])) + cg.add(var.set_preamble_errors(config[CONF_PREAMBLE_ERRORS])) + cg.add(var.set_coding_rate(config[CONF_CODING_RATE])) + cg.add(var.set_spreading_factor(config[CONF_SPREADING_FACTOR])) + cg.add(var.set_sync_value(config[CONF_SYNC_VALUE])) + cg.add(var.set_rx_floor(config[CONF_RX_FLOOR])) + cg.add(var.set_rx_start(config[CONF_RX_START])) + + +NO_ARGS_ACTION_SCHEMA = automation.maybe_simple_id( + { + cv.GenerateID(): cv.use_id(SX127x), + } +) + + +@automation.register_action( + "sx127x.run_image_cal", RunImageCalAction, NO_ARGS_ACTION_SCHEMA +) +@automation.register_action( + "sx127x.set_mode_tx", SetModeTxAction, NO_ARGS_ACTION_SCHEMA +) +@automation.register_action( + "sx127x.set_mode_rx", SetModeRxAction, NO_ARGS_ACTION_SCHEMA +) +@automation.register_action( + "sx127x.set_mode_sleep", SetModeSleepAction, NO_ARGS_ACTION_SCHEMA +) +@automation.register_action( + "sx127x.set_mode_standby", SetModeStandbyAction, NO_ARGS_ACTION_SCHEMA +) +async def no_args_action_to_code(config, action_id, template_arg, args): + var = cg.new_Pvariable(action_id, template_arg) + await cg.register_parented(var, config[CONF_ID]) + return var + + +SEND_PACKET_ACTION_SCHEMA = cv.maybe_simple_value( + { + cv.GenerateID(): cv.use_id(SX127x), + cv.Required(CONF_DATA): cv.templatable(validate_raw_data), + }, + key=CONF_DATA, +) + + +@automation.register_action( + "sx127x.send_packet", SendPacketAction, SEND_PACKET_ACTION_SCHEMA +) +async def send_packet_action_to_code(config, action_id, template_arg, args): + var = cg.new_Pvariable(action_id, template_arg) + await cg.register_parented(var, config[CONF_ID]) + data = config[CONF_DATA] + if isinstance(data, bytes): + data = list(data) + if cg.is_template(data): + templ = await cg.templatable(data, args, cg.std_vector.template(cg.uint8)) + cg.add(var.set_data_template(templ)) + else: + cg.add(var.set_data_static(data)) + return var diff --git a/esphome/components/sx127x/automation.h b/esphome/components/sx127x/automation.h new file mode 100644 index 0000000000..2b9c261de1 --- /dev/null +++ b/esphome/components/sx127x/automation.h @@ -0,0 +1,62 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/core/automation.h" +#include "esphome/components/sx127x/sx127x.h" + +namespace esphome { +namespace sx127x { + +template class RunImageCalAction : public Action, public Parented { + public: + void play(Ts... x) override { this->parent_->run_image_cal(); } +}; + +template class SendPacketAction : public Action, public Parented { + public: + void set_data_template(std::function(Ts...)> func) { + this->data_func_ = func; + this->static_ = false; + } + + void set_data_static(const std::vector &data) { + this->data_static_ = data; + this->static_ = true; + } + + void play(Ts... x) override { + if (this->static_) { + this->parent_->transmit_packet(this->data_static_); + } else { + this->parent_->transmit_packet(this->data_func_(x...)); + } + } + + protected: + bool static_{false}; + std::function(Ts...)> data_func_{}; + std::vector data_static_{}; +}; + +template class SetModeTxAction : public Action, public Parented { + public: + void play(Ts... x) override { this->parent_->set_mode_tx(); } +}; + +template class SetModeRxAction : public Action, public Parented { + public: + void play(Ts... x) override { this->parent_->set_mode_rx(); } +}; + +template class SetModeSleepAction : public Action, public Parented { + public: + void play(Ts... x) override { this->parent_->set_mode_sleep(); } +}; + +template class SetModeStandbyAction : public Action, public Parented { + public: + void play(Ts... x) override { this->parent_->set_mode_standby(); } +}; + +} // namespace sx127x +} // namespace esphome diff --git a/esphome/components/sx127x/packet_transport/__init__.py b/esphome/components/sx127x/packet_transport/__init__.py new file mode 100644 index 0000000000..2f3a0f6e2b --- /dev/null +++ b/esphome/components/sx127x/packet_transport/__init__.py @@ -0,0 +1,26 @@ +import esphome.codegen as cg +from esphome.components.packet_transport import ( + PacketTransport, + new_packet_transport, + transport_schema, +) +import esphome.config_validation as cv +from esphome.cpp_types import PollingComponent + +from .. import CONF_SX127X_ID, SX127x, SX127xListener, sx127x_ns + +SX127xTransport = sx127x_ns.class_( + "SX127xTransport", PacketTransport, PollingComponent, SX127xListener +) + +CONFIG_SCHEMA = transport_schema(SX127xTransport).extend( + { + cv.GenerateID(CONF_SX127X_ID): cv.use_id(SX127x), + } +) + + +async def to_code(config): + var, _ = await new_packet_transport(config) + sx127x = await cg.get_variable(config[CONF_SX127X_ID]) + cg.add(var.set_parent(sx127x)) diff --git a/esphome/components/sx127x/packet_transport/sx127x_transport.cpp b/esphome/components/sx127x/packet_transport/sx127x_transport.cpp new file mode 100644 index 0000000000..b1d014bb96 --- /dev/null +++ b/esphome/components/sx127x/packet_transport/sx127x_transport.cpp @@ -0,0 +1,26 @@ +#include "esphome/core/log.h" +#include "esphome/core/application.h" +#include "sx127x_transport.h" + +namespace esphome { +namespace sx127x { + +static const char *const TAG = "sx127x_transport"; + +void SX127xTransport::setup() { + PacketTransport::setup(); + this->parent_->register_listener(this); +} + +void SX127xTransport::update() { + PacketTransport::update(); + this->updated_ = true; + this->resend_data_ = true; +} + +void SX127xTransport::send_packet(const std::vector &buf) const { this->parent_->transmit_packet(buf); } + +void SX127xTransport::on_packet(const std::vector &packet, float rssi, float snr) { this->process_(packet); } + +} // namespace sx127x +} // namespace esphome diff --git a/esphome/components/sx127x/packet_transport/sx127x_transport.h b/esphome/components/sx127x/packet_transport/sx127x_transport.h new file mode 100644 index 0000000000..e27b7f8d57 --- /dev/null +++ b/esphome/components/sx127x/packet_transport/sx127x_transport.h @@ -0,0 +1,25 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/sx127x/sx127x.h" +#include "esphome/components/packet_transport/packet_transport.h" +#include + +namespace esphome { +namespace sx127x { + +class SX127xTransport : public packet_transport::PacketTransport, public Parented, public SX127xListener { + public: + void setup() override; + void update() override; + void on_packet(const std::vector &packet, float rssi, float snr) override; + float get_setup_priority() const override { return setup_priority::AFTER_WIFI; } + + protected: + void send_packet(const std::vector &buf) const override; + bool should_send() override { return true; } + size_t get_max_packet_size() override { return this->parent_->get_max_packet_size(); } +}; + +} // namespace sx127x +} // namespace esphome diff --git a/esphome/components/sx127x/sx127x.cpp b/esphome/components/sx127x/sx127x.cpp new file mode 100644 index 0000000000..2d2326549b --- /dev/null +++ b/esphome/components/sx127x/sx127x.cpp @@ -0,0 +1,498 @@ +#include "sx127x.h" +#include "esphome/core/hal.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace sx127x { + +static const char *const TAG = "sx127x"; +static const uint32_t FXOSC = 32000000u; +static const uint16_t RAMP[16] = {3400, 2000, 1000, 500, 250, 125, 100, 62, 50, 40, 31, 25, 20, 15, 12, 10}; +static const uint32_t BW_HZ[22] = {2604, 3125, 3906, 5208, 6250, 7812, 10416, 12500, 15625, 20833, 25000, + 31250, 41666, 50000, 62500, 83333, 100000, 125000, 166666, 200000, 250000, 500000}; +static const uint8_t BW_LORA[22] = {BW_7_8, BW_7_8, BW_7_8, BW_7_8, BW_7_8, BW_7_8, BW_10_4, BW_15_6, + BW_15_6, BW_20_8, BW_31_3, BW_31_3, BW_41_7, BW_62_5, BW_62_5, BW_125_0, + BW_125_0, BW_125_0, BW_250_0, BW_250_0, BW_250_0, BW_500_0}; +static const uint8_t BW_FSK_OOK[22] = {RX_BW_2_6, RX_BW_3_1, RX_BW_3_9, RX_BW_5_2, RX_BW_6_3, RX_BW_7_8, + RX_BW_10_4, RX_BW_12_5, RX_BW_15_6, RX_BW_20_8, RX_BW_25_0, RX_BW_31_3, + RX_BW_41_7, RX_BW_50_0, RX_BW_62_5, RX_BW_83_3, RX_BW_100_0, RX_BW_125_0, + RX_BW_166_7, RX_BW_200_0, RX_BW_250_0, RX_BW_250_0}; +static const int32_t RSSI_OFFSET_HF = 157; +static const int32_t RSSI_OFFSET_LF = 164; + +uint8_t SX127x::read_register_(uint8_t reg) { + this->enable(); + this->write_byte(reg & 0x7F); + uint8_t value = this->read_byte(); + this->disable(); + return value; +} + +void SX127x::write_register_(uint8_t reg, uint8_t value) { + this->enable(); + this->write_byte(reg | 0x80); + this->write_byte(value); + this->disable(); +} + +void SX127x::read_fifo_(std::vector &packet) { + this->enable(); + this->write_byte(REG_FIFO & 0x7F); + this->read_array(packet.data(), packet.size()); + this->disable(); +} + +void SX127x::write_fifo_(const std::vector &packet) { + this->enable(); + this->write_byte(REG_FIFO | 0x80); + this->write_array(packet.data(), packet.size()); + this->disable(); +} + +void SX127x::setup() { + ESP_LOGCONFIG(TAG, "Running setup"); + + // setup reset + this->rst_pin_->setup(); + + // setup dio0 + if (this->dio0_pin_) { + this->dio0_pin_->setup(); + } + + // start spi + this->spi_setup(); + + // configure rf + this->configure(); +} + +void SX127x::configure() { + // toggle chip reset + this->rst_pin_->digital_write(false); + delayMicroseconds(1000); + this->rst_pin_->digital_write(true); + delayMicroseconds(10000); + + // check silicon version to make sure hw is ok + if (this->read_register_(REG_VERSION) != 0x12) { + this->mark_failed(); + return; + } + + // enter sleep mode + this->set_mode_(MOD_FSK, MODE_SLEEP); + + // set freq + uint64_t frf = ((uint64_t) this->frequency_ << 19) / FXOSC; + this->write_register_(REG_FRF_MSB, (uint8_t) ((frf >> 16) & 0xFF)); + this->write_register_(REG_FRF_MID, (uint8_t) ((frf >> 8) & 0xFF)); + this->write_register_(REG_FRF_LSB, (uint8_t) ((frf >> 0) & 0xFF)); + + // enter standby mode + this->set_mode_(MOD_FSK, MODE_STDBY); + + // run image cal + this->run_image_cal(); + + // go back to sleep + this->set_mode_sleep(); + + // config pa + if (this->pa_pin_ == PA_PIN_BOOST) { + this->pa_power_ = std::max(this->pa_power_, (uint8_t) 2); + this->pa_power_ = std::min(this->pa_power_, (uint8_t) 17); + this->write_register_(REG_PA_CONFIG, (this->pa_power_ - 2) | this->pa_pin_ | PA_MAX_POWER); + } else { + this->pa_power_ = std::min(this->pa_power_, (uint8_t) 14); + this->write_register_(REG_PA_CONFIG, (this->pa_power_ - 0) | this->pa_pin_ | PA_MAX_POWER); + } + if (this->modulation_ != MOD_LORA) { + this->write_register_(REG_PA_RAMP, this->pa_ramp_ | this->shaping_); + } else { + this->write_register_(REG_PA_RAMP, this->pa_ramp_); + } + + // configure modem + if (this->modulation_ != MOD_LORA) { + this->configure_fsk_ook_(); + } else { + this->configure_lora_(); + } + + // switch to rx or sleep + if (this->rx_start_) { + this->set_mode_rx(); + } else { + this->set_mode_sleep(); + } +} + +void SX127x::configure_fsk_ook_() { + // set the channel bw + this->write_register_(REG_RX_BW, BW_FSK_OOK[this->bandwidth_]); + + // set fdev + uint32_t fdev = std::min((this->deviation_ * 4096) / 250000, (uint32_t) 0x3FFF); + this->write_register_(REG_FDEV_MSB, (uint8_t) ((fdev >> 8) & 0xFF)); + this->write_register_(REG_FDEV_LSB, (uint8_t) ((fdev >> 0) & 0xFF)); + + // set bitrate + uint64_t bitrate = (FXOSC + this->bitrate_ / 2) / this->bitrate_; // round up + this->write_register_(REG_BITRATE_MSB, (uint8_t) ((bitrate >> 8) & 0xFF)); + this->write_register_(REG_BITRATE_LSB, (uint8_t) ((bitrate >> 0) & 0xFF)); + + // configure rx and afc + uint8_t trigger = (this->preamble_detect_ > 0) ? TRIGGER_PREAMBLE : TRIGGER_RSSI; + this->write_register_(REG_AFC_FEI, AFC_AUTO_CLEAR_ON); + if (this->modulation_ == MOD_FSK) { + this->write_register_(REG_RX_CONFIG, AFC_AUTO_ON | AGC_AUTO_ON | trigger); + } else { + this->write_register_(REG_RX_CONFIG, AGC_AUTO_ON | trigger); + } + + // configure packet mode + if (this->packet_mode_) { + uint8_t crc_mode = (this->crc_enable_) ? CRC_ON : CRC_OFF; + this->write_register_(REG_FIFO_THRESH, TX_START_FIFO_EMPTY); + if (this->payload_length_ > 0) { + this->write_register_(REG_PAYLOAD_LENGTH_LSB, this->payload_length_); + this->write_register_(REG_PACKET_CONFIG_1, crc_mode | FIXED_LENGTH); + } else { + this->write_register_(REG_PAYLOAD_LENGTH_LSB, this->get_max_packet_size() - 1); + this->write_register_(REG_PACKET_CONFIG_1, crc_mode | VARIABLE_LENGTH); + } + this->write_register_(REG_PACKET_CONFIG_2, PACKET_MODE); + } else { + this->write_register_(REG_PACKET_CONFIG_2, CONTINUOUS_MODE); + } + this->write_register_(REG_DIO_MAPPING1, DIO0_MAPPING_00); + + // config bit synchronizer + uint8_t polarity = (this->preamble_polarity_ == 0xAA) ? PREAMBLE_AA : PREAMBLE_55; + if (!this->sync_value_.empty()) { + uint8_t size = this->sync_value_.size() - 1; + this->write_register_(REG_SYNC_CONFIG, AUTO_RESTART_PLL_LOCK | polarity | SYNC_ON | size); + for (uint32_t i = 0; i < this->sync_value_.size(); i++) { + this->write_register_(REG_SYNC_VALUE1 + i, this->sync_value_[i]); + } + } else { + this->write_register_(REG_SYNC_CONFIG, AUTO_RESTART_PLL_LOCK | polarity); + } + + // config preamble detector + if (this->preamble_detect_ > 0) { + uint8_t size = (this->preamble_detect_ - 1) << PREAMBLE_DETECTOR_SIZE_SHIFT; + uint8_t tol = this->preamble_errors_ << PREAMBLE_DETECTOR_TOL_SHIFT; + this->write_register_(REG_PREAMBLE_DETECT, PREAMBLE_DETECTOR_ON | size | tol); + } else { + this->write_register_(REG_PREAMBLE_DETECT, PREAMBLE_DETECTOR_OFF); + } + this->write_register_(REG_PREAMBLE_SIZE_MSB, this->preamble_size_ >> 16); + this->write_register_(REG_PREAMBLE_SIZE_LSB, this->preamble_size_ & 0xFF); + + // config sync generation and setup ook threshold + uint8_t bitsync = this->bitsync_ ? BIT_SYNC_ON : BIT_SYNC_OFF; + this->write_register_(REG_OOK_PEAK, bitsync | OOK_THRESH_STEP_0_5 | OOK_THRESH_PEAK); + this->write_register_(REG_OOK_AVG, OOK_AVG_RESERVED | OOK_THRESH_DEC_1_8); + + // set rx floor + this->write_register_(REG_OOK_FIX, 256 + int(this->rx_floor_ * 2.0)); + this->write_register_(REG_RSSI_THRESH, std::abs(int(this->rx_floor_ * 2.0))); +} + +void SX127x::configure_lora_() { + // config modem + uint8_t header_mode = this->payload_length_ > 0 ? IMPLICIT_HEADER : EXPLICIT_HEADER; + uint8_t crc_mode = (this->crc_enable_) ? RX_PAYLOAD_CRC_ON : RX_PAYLOAD_CRC_OFF; + uint8_t spreading_factor = this->spreading_factor_ << SPREADING_FACTOR_SHIFT; + this->write_register_(REG_MODEM_CONFIG1, BW_LORA[this->bandwidth_] | this->coding_rate_ | header_mode); + this->write_register_(REG_MODEM_CONFIG2, spreading_factor | crc_mode); + + // config fifo and payload length + this->write_register_(REG_FIFO_TX_BASE_ADDR, 0x00); + this->write_register_(REG_FIFO_RX_BASE_ADDR, 0x00); + this->write_register_(REG_PAYLOAD_LENGTH, std::max(this->payload_length_, (uint32_t) 1)); + + // config preamble + if (this->preamble_size_ >= 6) { + this->write_register_(REG_PREAMBLE_LEN_MSB, this->preamble_size_ >> 16); + this->write_register_(REG_PREAMBLE_LEN_LSB, this->preamble_size_ & 0xFF); + } + + // optimize detection + float duration = 1000.0f * std::pow(2, this->spreading_factor_) / BW_HZ[this->bandwidth_]; + if (duration > 16) { + this->write_register_(REG_MODEM_CONFIG3, MODEM_AGC_AUTO_ON | LOW_DATA_RATE_OPTIMIZE_ON); + } else { + this->write_register_(REG_MODEM_CONFIG3, MODEM_AGC_AUTO_ON); + } + if (this->spreading_factor_ == 6) { + this->write_register_(REG_DETECT_OPTIMIZE, 0xC5); + this->write_register_(REG_DETECT_THRESHOLD, 0x0C); + } else { + this->write_register_(REG_DETECT_OPTIMIZE, 0xC3); + this->write_register_(REG_DETECT_THRESHOLD, 0x0A); + } + + // config sync word + if (!this->sync_value_.empty()) { + this->write_register_(REG_SYNC_WORD, this->sync_value_[0]); + } +} + +size_t SX127x::get_max_packet_size() { + if (this->payload_length_ > 0) { + return this->payload_length_; + } + if (this->modulation_ == MOD_LORA) { + return 256; + } else { + return 64; + } +} + +SX127xError SX127x::transmit_packet(const std::vector &packet) { + if (this->payload_length_ > 0 && this->payload_length_ != packet.size()) { + ESP_LOGE(TAG, "Packet size does not match config"); + return SX127xError::INVALID_PARAMS; + } + if (packet.empty() || packet.size() > this->get_max_packet_size()) { + ESP_LOGE(TAG, "Packet size out of range"); + return SX127xError::INVALID_PARAMS; + } + + SX127xError ret = SX127xError::NONE; + if (this->modulation_ == MOD_LORA) { + this->set_mode_standby(); + if (this->payload_length_ == 0) { + this->write_register_(REG_PAYLOAD_LENGTH, packet.size()); + } + this->write_register_(REG_IRQ_FLAGS, 0xFF); + this->write_register_(REG_FIFO_ADDR_PTR, 0); + this->write_fifo_(packet); + this->set_mode_tx(); + } else { + this->set_mode_standby(); + if (this->payload_length_ == 0) { + this->write_register_(REG_FIFO, packet.size()); + } + this->write_fifo_(packet); + this->set_mode_tx(); + } + + // wait until transmit completes, typically the delay will be less than 100 ms + uint32_t start = millis(); + while (!this->dio0_pin_->digital_read()) { + if (millis() - start > 4000) { + ESP_LOGE(TAG, "Transmit packet failure"); + ret = SX127xError::TIMEOUT; + break; + } + } + if (this->rx_start_) { + this->set_mode_rx(); + } else { + this->set_mode_sleep(); + } + return ret; +} + +void SX127x::call_listeners_(const std::vector &packet, float rssi, float snr) { + for (auto &listener : this->listeners_) { + listener->on_packet(packet, rssi, snr); + } + this->packet_trigger_->trigger(packet, rssi, snr); +} + +void SX127x::loop() { + if (this->dio0_pin_ == nullptr || !this->dio0_pin_->digital_read()) { + return; + } + + if (this->modulation_ == MOD_LORA) { + uint8_t status = this->read_register_(REG_IRQ_FLAGS); + this->write_register_(REG_IRQ_FLAGS, 0xFF); + if ((status & PAYLOAD_CRC_ERROR) == 0) { + uint8_t bytes = this->read_register_(REG_NB_RX_BYTES); + uint8_t addr = this->read_register_(REG_FIFO_RX_CURR_ADDR); + uint8_t rssi = this->read_register_(REG_PKT_RSSI_VALUE); + int8_t snr = (int8_t) this->read_register_(REG_PKT_SNR_VALUE); + this->packet_.resize(bytes); + this->write_register_(REG_FIFO_ADDR_PTR, addr); + this->read_fifo_(this->packet_); + if (this->frequency_ > 700000000) { + this->call_listeners_(this->packet_, (float) rssi - RSSI_OFFSET_HF, (float) snr / 4); + } else { + this->call_listeners_(this->packet_, (float) rssi - RSSI_OFFSET_LF, (float) snr / 4); + } + } + } else if (this->packet_mode_) { + uint8_t payload_length = this->payload_length_; + if (payload_length == 0) { + payload_length = this->read_register_(REG_FIFO); + } + this->packet_.resize(payload_length); + this->read_fifo_(this->packet_); + this->call_listeners_(this->packet_, 0.0f, 0.0f); + } +} + +void SX127x::run_image_cal() { + if (this->modulation_ == MOD_LORA) { + this->set_mode_(MOD_FSK, MODE_SLEEP); + this->set_mode_(MOD_FSK, MODE_STDBY); + } + if (this->auto_cal_) { + this->write_register_(REG_IMAGE_CAL, IMAGE_CAL_START | AUTO_IMAGE_CAL_ON | TEMP_THRESHOLD_10C); + } else { + this->write_register_(REG_IMAGE_CAL, IMAGE_CAL_START); + } + uint32_t start = millis(); + while (this->read_register_(REG_IMAGE_CAL) & IMAGE_CAL_RUNNING) { + if (millis() - start > 20) { + ESP_LOGE(TAG, "Image cal failure"); + this->mark_failed(); + break; + } + } + if (this->modulation_ == MOD_LORA) { + this->set_mode_(this->modulation_, MODE_SLEEP); + this->set_mode_(this->modulation_, MODE_STDBY); + } +} + +void SX127x::set_mode_(uint8_t modulation, uint8_t mode) { + uint32_t start = millis(); + this->write_register_(REG_OP_MODE, modulation | mode); + while (true) { + uint8_t curr = this->read_register_(REG_OP_MODE) & MODE_MASK; + if ((curr == mode) || (mode == MODE_RX && curr == MODE_RX_FS)) { + if (mode == MODE_SLEEP) { + this->write_register_(REG_OP_MODE, modulation | mode); + } + break; + } + if (millis() - start > 20) { + ESP_LOGE(TAG, "Set mode failure"); + this->mark_failed(); + break; + } + } +} + +void SX127x::set_mode_rx() { + this->set_mode_(this->modulation_, MODE_RX); + if (this->modulation_ == MOD_LORA) { + this->write_register_(REG_IRQ_FLAGS_MASK, 0x00); + this->write_register_(REG_DIO_MAPPING1, DIO0_MAPPING_00); + } +} + +void SX127x::set_mode_tx() { + this->set_mode_(this->modulation_, MODE_TX); + if (this->modulation_ == MOD_LORA) { + this->write_register_(REG_IRQ_FLAGS_MASK, 0x00); + this->write_register_(REG_DIO_MAPPING1, DIO0_MAPPING_01); + } +} + +void SX127x::set_mode_standby() { this->set_mode_(this->modulation_, MODE_STDBY); } + +void SX127x::set_mode_sleep() { this->set_mode_(this->modulation_, MODE_SLEEP); } + +void SX127x::dump_config() { + ESP_LOGCONFIG(TAG, "SX127x:"); + LOG_PIN(" CS Pin: ", this->cs_); + LOG_PIN(" RST Pin: ", this->rst_pin_); + LOG_PIN(" DIO0 Pin: ", this->dio0_pin_); + const char *pa_pin = "RFO"; + if (this->pa_pin_ == PA_PIN_BOOST) { + pa_pin = "BOOST"; + } + ESP_LOGCONFIG(TAG, + " Auto Cal: %s\n" + " Frequency: %" PRIu32 " Hz\n" + " Bandwidth: %" PRIu32 " Hz\n" + " PA Pin: %s\n" + " PA Power: %" PRIu8 " dBm\n" + " PA Ramp: %" PRIu16 " us", + TRUEFALSE(this->auto_cal_), this->frequency_, BW_HZ[this->bandwidth_], pa_pin, this->pa_power_, + RAMP[this->pa_ramp_]); + if (this->modulation_ == MOD_FSK) { + ESP_LOGCONFIG(TAG, " Deviation: %" PRIu32 " Hz", this->deviation_); + } + if (this->modulation_ == MOD_LORA) { + const char *cr = "4/8"; + if (this->coding_rate_ == CODING_RATE_4_5) { + cr = "4/5"; + } else if (this->coding_rate_ == CODING_RATE_4_6) { + cr = "4/6"; + } else if (this->coding_rate_ == CODING_RATE_4_7) { + cr = "4/7"; + } + ESP_LOGCONFIG(TAG, + " Modulation: LORA\n" + " Preamble Size: %" PRIu16 "\n" + " Spreading Factor: %" PRIu8 "\n" + " Coding Rate: %s\n" + " CRC Enable: %s", + this->preamble_size_, this->spreading_factor_, cr, TRUEFALSE(this->crc_enable_)); + if (this->payload_length_ > 0) { + ESP_LOGCONFIG(TAG, " Payload Length: %" PRIu32, this->payload_length_); + } + if (!this->sync_value_.empty()) { + ESP_LOGCONFIG(TAG, " Sync Value: 0x%02x", this->sync_value_[0]); + } + } else { + const char *shaping = "NONE"; + if (this->modulation_ == MOD_FSK) { + if (this->shaping_ == GAUSSIAN_BT_0_3) { + shaping = "GAUSSIAN_BT_0_3"; + } else if (this->shaping_ == GAUSSIAN_BT_0_5) { + shaping = "GAUSSIAN_BT_0_5"; + } else if (this->shaping_ == GAUSSIAN_BT_1_0) { + shaping = "GAUSSIAN_BT_1_0"; + } + } else { + if (this->shaping_ == CUTOFF_BR_X_2) { + shaping = "CUTOFF_BR_X_2"; + } else if (this->shaping_ == CUTOFF_BR_X_1) { + shaping = "CUTOFF_BR_X_1"; + } + } + ESP_LOGCONFIG(TAG, + " Shaping: %s\n" + " Modulation: %s\n" + " Bitrate: %" PRIu32 "b/s\n" + " Bitsync: %s\n" + " Rx Start: %s\n" + " Rx Floor: %.1f dBm\n" + " Packet Mode: %s", + shaping, this->modulation_ == MOD_FSK ? "FSK" : "OOK", this->bitrate_, TRUEFALSE(this->bitsync_), + TRUEFALSE(this->rx_start_), this->rx_floor_, TRUEFALSE(this->packet_mode_)); + if (this->packet_mode_) { + ESP_LOGCONFIG(TAG, " CRC Enable: %s", TRUEFALSE(this->crc_enable_)); + } + if (this->payload_length_ > 0) { + ESP_LOGCONFIG(TAG, " Payload Length: %" PRIu32, this->payload_length_); + } + if (!this->sync_value_.empty()) { + ESP_LOGCONFIG(TAG, " Sync Value: 0x%s", format_hex(this->sync_value_).c_str()); + } + if (this->preamble_size_ > 0 || this->preamble_detect_ > 0) { + ESP_LOGCONFIG(TAG, + " Preamble Polarity: 0x%X\n" + " Preamble Size: %" PRIu16 "\n" + " Preamble Detect: %" PRIu8 "\n" + " Preamble Errors: %" PRIu8, + this->preamble_polarity_, this->preamble_size_, this->preamble_detect_, this->preamble_errors_); + } + } + if (this->is_failed()) { + ESP_LOGE(TAG, "Configuring SX127x failed"); + } +} + +} // namespace sx127x +} // namespace esphome diff --git a/esphome/components/sx127x/sx127x.h b/esphome/components/sx127x/sx127x.h new file mode 100644 index 0000000000..0600b51201 --- /dev/null +++ b/esphome/components/sx127x/sx127x.h @@ -0,0 +1,128 @@ +#pragma once + +#include "sx127x_reg.h" +#include "esphome/components/spi/spi.h" +#include "esphome/core/automation.h" +#include "esphome/core/component.h" +#include + +namespace esphome { +namespace sx127x { + +enum SX127xBw : uint8_t { + SX127X_BW_2_6, + SX127X_BW_3_1, + SX127X_BW_3_9, + SX127X_BW_5_2, + SX127X_BW_6_3, + SX127X_BW_7_8, + SX127X_BW_10_4, + SX127X_BW_12_5, + SX127X_BW_15_6, + SX127X_BW_20_8, + SX127X_BW_25_0, + SX127X_BW_31_3, + SX127X_BW_41_7, + SX127X_BW_50_0, + SX127X_BW_62_5, + SX127X_BW_83_3, + SX127X_BW_100_0, + SX127X_BW_125_0, + SX127X_BW_166_7, + SX127X_BW_200_0, + SX127X_BW_250_0, + SX127X_BW_500_0, +}; + +enum class SX127xError { NONE = 0, TIMEOUT, INVALID_PARAMS }; + +class SX127xListener { + public: + virtual void on_packet(const std::vector &packet, float rssi, float snr) = 0; +}; + +class SX127x : public Component, + public spi::SPIDevice { + public: + size_t get_max_packet_size(); + float get_setup_priority() const override { return setup_priority::PROCESSOR; } + void setup() override; + void loop() override; + void dump_config() override; + void set_auto_cal(bool auto_cal) { this->auto_cal_ = auto_cal; } + void set_bandwidth(SX127xBw bandwidth) { this->bandwidth_ = bandwidth; } + void set_bitrate(uint32_t bitrate) { this->bitrate_ = bitrate; } + void set_bitsync(bool bitsync) { this->bitsync_ = bitsync; } + void set_coding_rate(uint8_t coding_rate) { this->coding_rate_ = coding_rate; } + void set_crc_enable(bool crc_enable) { this->crc_enable_ = crc_enable; } + void set_deviation(uint32_t deviation) { this->deviation_ = deviation; } + void set_dio0_pin(InternalGPIOPin *dio0_pin) { this->dio0_pin_ = dio0_pin; } + void set_frequency(uint32_t frequency) { this->frequency_ = frequency; } + void set_mode_rx(); + void set_mode_tx(); + void set_mode_standby(); + void set_mode_sleep(); + void set_modulation(uint8_t modulation) { this->modulation_ = modulation; } + void set_pa_pin(uint8_t pin) { this->pa_pin_ = pin; } + void set_pa_power(uint8_t power) { this->pa_power_ = power; } + void set_pa_ramp(uint8_t ramp) { this->pa_ramp_ = ramp; } + void set_packet_mode(bool packet_mode) { this->packet_mode_ = packet_mode; } + void set_payload_length(uint8_t payload_length) { this->payload_length_ = payload_length; } + void set_preamble_errors(uint8_t preamble_errors) { this->preamble_errors_ = preamble_errors; } + void set_preamble_polarity(uint8_t preamble_polarity) { this->preamble_polarity_ = preamble_polarity; } + void set_preamble_size(uint16_t preamble_size) { this->preamble_size_ = preamble_size; } + void set_preamble_detect(uint8_t preamble_detect) { this->preamble_detect_ = preamble_detect; } + void set_rst_pin(InternalGPIOPin *rst_pin) { this->rst_pin_ = rst_pin; } + void set_rx_floor(float floor) { this->rx_floor_ = floor; } + void set_rx_start(bool start) { this->rx_start_ = start; } + void set_shaping(uint8_t shaping) { this->shaping_ = shaping; } + void set_spreading_factor(uint8_t spreading_factor) { this->spreading_factor_ = spreading_factor; } + void set_sync_value(const std::vector &sync_value) { this->sync_value_ = sync_value; } + void run_image_cal(); + void configure(); + SX127xError transmit_packet(const std::vector &packet); + void register_listener(SX127xListener *listener) { this->listeners_.push_back(listener); } + Trigger, float, float> *get_packet_trigger() const { return this->packet_trigger_; }; + + protected: + void configure_fsk_ook_(); + void configure_lora_(); + void set_mode_(uint8_t modulation, uint8_t mode); + void write_fifo_(const std::vector &packet); + void read_fifo_(std::vector &packet); + void write_register_(uint8_t reg, uint8_t value); + void call_listeners_(const std::vector &packet, float rssi, float snr); + uint8_t read_register_(uint8_t reg); + Trigger, float, float> *packet_trigger_{new Trigger, float, float>()}; + std::vector listeners_; + std::vector packet_; + std::vector sync_value_; + InternalGPIOPin *dio0_pin_{nullptr}; + InternalGPIOPin *rst_pin_{nullptr}; + SX127xBw bandwidth_; + uint32_t bitrate_; + uint32_t deviation_; + uint32_t frequency_; + uint32_t payload_length_; + uint16_t preamble_size_; + uint8_t coding_rate_; + uint8_t modulation_; + uint8_t pa_pin_; + uint8_t pa_power_; + uint8_t pa_ramp_; + uint8_t preamble_detect_; + uint8_t preamble_errors_; + uint8_t preamble_polarity_; + uint8_t shaping_; + uint8_t spreading_factor_; + float rx_floor_; + bool auto_cal_{false}; + bool bitsync_{false}; + bool crc_enable_{false}; + bool packet_mode_{false}; + bool rx_start_{false}; +}; + +} // namespace sx127x +} // namespace esphome diff --git a/esphome/components/sx127x/sx127x_reg.h b/esphome/components/sx127x/sx127x_reg.h new file mode 100644 index 0000000000..d5e9c50957 --- /dev/null +++ b/esphome/components/sx127x/sx127x_reg.h @@ -0,0 +1,295 @@ +#pragma once + +#include "esphome/core/hal.h" + +namespace esphome { +namespace sx127x { + +enum SX127xReg : uint8_t { + // Common registers + REG_FIFO = 0x00, + REG_OP_MODE = 0x01, + REG_BITRATE_MSB = 0x02, + REG_BITRATE_LSB = 0x03, + REG_FDEV_MSB = 0x04, + REG_FDEV_LSB = 0x05, + REG_FRF_MSB = 0x06, + REG_FRF_MID = 0x07, + REG_FRF_LSB = 0x08, + REG_PA_CONFIG = 0x09, + REG_PA_RAMP = 0x0A, + REG_DIO_MAPPING1 = 0x40, + REG_DIO_MAPPING2 = 0x41, + REG_VERSION = 0x42, + // FSK/OOK registers + REG_RX_CONFIG = 0x0D, + REG_RSSI_THRESH = 0x10, + REG_RX_BW = 0x12, + REG_OOK_PEAK = 0x14, + REG_OOK_FIX = 0x15, + REG_OOK_AVG = 0x16, + REG_AFC_FEI = 0x1A, + REG_PREAMBLE_DETECT = 0x1F, + REG_PREAMBLE_SIZE_MSB = 0x25, + REG_PREAMBLE_SIZE_LSB = 0x26, + REG_SYNC_CONFIG = 0x27, + REG_SYNC_VALUE1 = 0x28, + REG_SYNC_VALUE2 = 0x29, + REG_SYNC_VALUE3 = 0x2A, + REG_SYNC_VALUE4 = 0x2B, + REG_SYNC_VALUE5 = 0x2C, + REG_SYNC_VALUE6 = 0x2D, + REG_SYNC_VALUE7 = 0x2E, + REG_SYNC_VALUE8 = 0x2F, + REG_PACKET_CONFIG_1 = 0x30, + REG_PACKET_CONFIG_2 = 0x31, + REG_PAYLOAD_LENGTH_LSB = 0x32, + REG_FIFO_THRESH = 0x35, + REG_IMAGE_CAL = 0x3B, + // LoRa registers + REG_FIFO_ADDR_PTR = 0x0D, + REG_FIFO_TX_BASE_ADDR = 0x0E, + REG_FIFO_RX_BASE_ADDR = 0x0F, + REG_FIFO_RX_CURR_ADDR = 0x10, + REG_IRQ_FLAGS_MASK = 0x11, + REG_IRQ_FLAGS = 0x12, + REG_NB_RX_BYTES = 0x13, + REG_MODEM_STAT = 0x18, + REG_PKT_SNR_VALUE = 0x19, + REG_PKT_RSSI_VALUE = 0x1A, + REG_RSSI_VALUE = 0x1B, + REG_HOP_CHANNEL = 0x1C, + REG_MODEM_CONFIG1 = 0x1D, + REG_MODEM_CONFIG2 = 0x1E, + REG_SYMB_TIMEOUT_LSB = 0x1F, + REG_PREAMBLE_LEN_MSB = 0x20, + REG_PREAMBLE_LEN_LSB = 0x21, + REG_PAYLOAD_LENGTH = 0x22, + REG_HOP_PERIOD = 0x24, + REG_FIFO_RX_BYTE_ADDR = 0x25, + REG_MODEM_CONFIG3 = 0x26, + REG_FEI_MSB = 0x28, + REG_FEI_MIB = 0x29, + REG_FEI_LSB = 0x2A, + REG_DETECT_OPTIMIZE = 0x31, + REG_INVERT_IQ = 0x33, + REG_DETECT_THRESHOLD = 0x37, + REG_SYNC_WORD = 0x39, +}; + +enum SX127xOpMode : uint8_t { + MOD_LORA = 0x80, + ACCESS_FSK_REGS = 0x40, + ACCESS_LORA_REGS = 0x00, + MOD_OOK = 0x20, + MOD_FSK = 0x00, + ACCESS_LF_REGS = 0x08, + ACCESS_HF_REGS = 0x00, + MODE_CAD = 0x07, + MODE_RX_SINGLE = 0x06, + MODE_RX = 0x05, + MODE_RX_FS = 0x04, + MODE_TX = 0x03, + MODE_TX_FS = 0x02, + MODE_STDBY = 0x01, + MODE_SLEEP = 0x00, + MODE_MASK = 0x07, +}; + +enum SX127xPaConfig : uint8_t { + PA_PIN_BOOST = 0x80, + PA_PIN_RFO = 0x00, + PA_MAX_POWER = 0x70, +}; + +enum SX127xPaRamp : uint8_t { + CUTOFF_BR_X_2 = 0x40, + CUTOFF_BR_X_1 = 0x20, + GAUSSIAN_BT_0_3 = 0x60, + GAUSSIAN_BT_0_5 = 0x40, + GAUSSIAN_BT_1_0 = 0x20, + SHAPING_NONE = 0x00, + PA_RAMP_10 = 0x0F, + PA_RAMP_12 = 0x0E, + PA_RAMP_15 = 0x0D, + PA_RAMP_20 = 0x0C, + PA_RAMP_25 = 0x0B, + PA_RAMP_31 = 0x0A, + PA_RAMP_40 = 0x09, + PA_RAMP_50 = 0x08, + PA_RAMP_62 = 0x07, + PA_RAMP_100 = 0x06, + PA_RAMP_125 = 0x05, + PA_RAMP_250 = 0x04, + PA_RAMP_500 = 0x03, + PA_RAMP_1000 = 0x02, + PA_RAMP_2000 = 0x01, + PA_RAMP_3400 = 0x00, +}; + +enum SX127xDioMapping1 : uint8_t { + DIO0_MAPPING_00 = 0x00, + DIO0_MAPPING_01 = 0x40, + DIO0_MAPPING_10 = 0x80, + DIO0_MAPPING_11 = 0xC0, +}; + +enum SX127xRxConfig : uint8_t { + RESTART_ON_COLLISION = 0x80, + RESTART_NO_LOCK = 0x40, + RESTART_PLL_LOCK = 0x20, + AFC_AUTO_ON = 0x10, + AGC_AUTO_ON = 0x08, + TRIGGER_NONE = 0x00, + TRIGGER_RSSI = 0x01, + TRIGGER_PREAMBLE = 0x06, + TRIGGER_ALL = 0x07, +}; + +enum SX127xRxBw : uint8_t { + RX_BW_2_6 = 0x17, + RX_BW_3_1 = 0x0F, + RX_BW_3_9 = 0x07, + RX_BW_5_2 = 0x16, + RX_BW_6_3 = 0x0E, + RX_BW_7_8 = 0x06, + RX_BW_10_4 = 0x15, + RX_BW_12_5 = 0x0D, + RX_BW_15_6 = 0x05, + RX_BW_20_8 = 0x14, + RX_BW_25_0 = 0x0C, + RX_BW_31_3 = 0x04, + RX_BW_41_7 = 0x13, + RX_BW_50_0 = 0x0B, + RX_BW_62_5 = 0x03, + RX_BW_83_3 = 0x12, + RX_BW_100_0 = 0x0A, + RX_BW_125_0 = 0x02, + RX_BW_166_7 = 0x11, + RX_BW_200_0 = 0x09, + RX_BW_250_0 = 0x01, +}; + +enum SX127xOokPeak : uint8_t { + BIT_SYNC_ON = 0x20, + BIT_SYNC_OFF = 0x00, + OOK_THRESH_AVG = 0x10, + OOK_THRESH_PEAK = 0x08, + OOK_THRESH_FIXED = 0x00, + OOK_THRESH_STEP_6_0 = 0x07, + OOK_THRESH_STEP_5_0 = 0x06, + OOK_THRESH_STEP_4_0 = 0x05, + OOK_THRESH_STEP_3_0 = 0x04, + OOK_THRESH_STEP_2_0 = 0x03, + OOK_THRESH_STEP_1_5 = 0x02, + OOK_THRESH_STEP_1_0 = 0x01, + OOK_THRESH_STEP_0_5 = 0x00, +}; + +enum SX127xOokAvg : uint8_t { + OOK_THRESH_DEC_16 = 0xE0, + OOK_THRESH_DEC_8 = 0xC0, + OOK_THRESH_DEC_4 = 0xA0, + OOK_THRESH_DEC_2 = 0x80, + OOK_THRESH_DEC_1_8 = 0x60, + OOK_THRESH_DEC_1_4 = 0x40, + OOK_THRESH_DEC_1_2 = 0x20, + OOK_THRESH_DEC_1 = 0x00, + OOK_AVG_RESERVED = 0x10, +}; + +enum SX127xAfcFei : uint8_t { + AFC_AUTO_CLEAR_ON = 0x01, +}; + +enum SX127xPreambleDetect : uint8_t { + PREAMBLE_DETECTOR_ON = 0x80, + PREAMBLE_DETECTOR_OFF = 0x00, + PREAMBLE_DETECTOR_SIZE_SHIFT = 5, + PREAMBLE_DETECTOR_TOL_SHIFT = 0, +}; + +enum SX127xSyncConfig : uint8_t { + AUTO_RESTART_PLL_LOCK = 0x80, + AUTO_RESTART_NO_LOCK = 0x40, + AUTO_RESTART_OFF = 0x00, + PREAMBLE_55 = 0x20, + PREAMBLE_AA = 0x00, + SYNC_ON = 0x10, + SYNC_OFF = 0x00, +}; + +enum SX127xPacketConfig1 : uint8_t { + VARIABLE_LENGTH = 0x80, + FIXED_LENGTH = 0x00, + CRC_ON = 0x10, + CRC_OFF = 0x00, +}; + +enum SX127xPacketConfig2 : uint8_t { + CONTINUOUS_MODE = 0x00, + PACKET_MODE = 0x40, +}; + +enum SX127xFifoThresh : uint8_t { + TX_START_FIFO_EMPTY = 0x80, + TX_START_FIFO_LEVEL = 0x00, +}; + +enum SX127xImageCal : uint8_t { + AUTO_IMAGE_CAL_ON = 0x80, + IMAGE_CAL_START = 0x40, + IMAGE_CAL_RUNNING = 0x20, + TEMP_CHANGE = 0x08, + TEMP_THRESHOLD_20C = 0x06, + TEMP_THRESHOLD_15C = 0x04, + TEMP_THRESHOLD_10C = 0x02, + TEMP_THRESHOLD_5C = 0x00, + TEMP_MONITOR_OFF = 0x01, + TEMP_MONITOR_ON = 0x00, +}; + +enum SX127xIrqFlags : uint8_t { + RX_TIMEOUT = 0x80, + RX_DONE = 0x40, + PAYLOAD_CRC_ERROR = 0x20, + VALID_HEADER = 0x10, + TX_DONE = 0x08, + CAD_DONE = 0x04, + FHSS_CHANGE_CHANNEL = 0x02, + CAD_DETECTED = 0x01, +}; + +enum SX127xModemCfg1 : uint8_t { + BW_7_8 = 0x00, + BW_10_4 = 0x10, + BW_15_6 = 0x20, + BW_20_8 = 0x30, + BW_31_3 = 0x40, + BW_41_7 = 0x50, + BW_62_5 = 0x60, + BW_125_0 = 0x70, + BW_250_0 = 0x80, + BW_500_0 = 0x90, + CODING_RATE_4_5 = 0x02, + CODING_RATE_4_6 = 0x04, + CODING_RATE_4_7 = 0x06, + CODING_RATE_4_8 = 0x08, + IMPLICIT_HEADER = 0x01, + EXPLICIT_HEADER = 0x00, +}; + +enum SX127xModemCfg2 : uint8_t { + SPREADING_FACTOR_SHIFT = 4, + TX_CONTINOUS_MODE = 0x08, + RX_PAYLOAD_CRC_ON = 0x04, + RX_PAYLOAD_CRC_OFF = 0x00, +}; + +enum SX127xModemCfg3 : uint8_t { + LOW_DATA_RATE_OPTIMIZE_ON = 0x08, + MODEM_AGC_AUTO_ON = 0x04, +}; + +} // namespace sx127x +} // namespace esphome diff --git a/esphome/components/syslog/esphome_syslog.cpp b/esphome/components/syslog/esphome_syslog.cpp index 9d2cda549b..e322a6951d 100644 --- a/esphome/components/syslog/esphome_syslog.cpp +++ b/esphome/components/syslog/esphome_syslog.cpp @@ -21,10 +21,12 @@ constexpr int LOG_LEVEL_TO_SYSLOG_SEVERITY[] = { void Syslog::setup() { logger::global_logger->add_on_log_callback( - [this](int level, const char *tag, const char *message) { this->log_(level, tag, message); }); + [this](int level, const char *tag, const char *message, size_t message_len) { + this->log_(level, tag, message, message_len); + }); } -void Syslog::log_(const int level, const char *tag, const char *message) const { +void Syslog::log_(const int level, const char *tag, const char *message, size_t message_len) const { if (level > this->log_level_) return; // Syslog PRI calculation: facility * 8 + severity @@ -34,7 +36,7 @@ void Syslog::log_(const int level, const char *tag, const char *message) const { } int pri = this->facility_ * 8 + severity; auto timestamp = this->time_->now().strftime("%b %d %H:%M:%S"); - unsigned len = strlen(message); + size_t len = message_len; // remove color formatting if (this->strip_ && message[0] == 0x1B && len > 11) { message += 7; diff --git a/esphome/components/syslog/esphome_syslog.h b/esphome/components/syslog/esphome_syslog.h index 421a9bee73..e3b2f7dae5 100644 --- a/esphome/components/syslog/esphome_syslog.h +++ b/esphome/components/syslog/esphome_syslog.h @@ -17,7 +17,7 @@ class Syslog : public Component, public Parented { protected: int log_level_; - void log_(int level, const char *tag, const char *message) const; + void log_(int level, const char *tag, const char *message, size_t message_len) const; time::RealTimeClock *time_; bool strip_{true}; int facility_{16}; diff --git a/esphome/components/tsl2591/tsl2591.cpp b/esphome/components/tsl2591/tsl2591.cpp index 1734d83dd2..c7622b116a 100644 --- a/esphome/components/tsl2591/tsl2591.cpp +++ b/esphome/components/tsl2591/tsl2591.cpp @@ -232,7 +232,7 @@ void TSL2591Component::set_integration_time_and_gain(TSL2591IntegrationTime inte this->integration_time_ = integration_time; this->gain_ = gain; if (!this->write_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CONTROL, - this->integration_time_ | this->gain_)) { // NOLINT + static_cast(this->integration_time_) | static_cast(this->gain_))) { ESP_LOGE(TAG, "I2C write failed"); } // The ADC values can be confused if gain or integration time are changed in the middle of a cycle. diff --git a/esphome/components/uart/__init__.py b/esphome/components/uart/__init__.py index a0908a299c..7d4c6360fe 100644 --- a/esphome/components/uart/__init__.py +++ b/esphome/components/uart/__init__.py @@ -2,6 +2,7 @@ import re from esphome import automation, pins import esphome.codegen as cg +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_AFTER, @@ -27,6 +28,7 @@ from esphome.const import ( CONF_TX_PIN, CONF_UART_ID, PLATFORM_HOST, + PlatformFramework, ) from esphome.core import CORE import esphome.final_validate as fv @@ -438,3 +440,19 @@ async def uart_write_to_code(config, action_id, template_arg, args): else: cg.add(var.set_data_static(data)) return var + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "uart_component_esp32_arduino.cpp": {PlatformFramework.ESP32_ARDUINO}, + "uart_component_esp_idf.cpp": {PlatformFramework.ESP32_IDF}, + "uart_component_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "uart_component_host.cpp": {PlatformFramework.HOST_NATIVE}, + "uart_component_rp2040.cpp": {PlatformFramework.RP2040_ARDUINO}, + "uart_component_libretiny.cpp": { + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + } +) diff --git a/esphome/components/update/update_entity.h b/esphome/components/update/update_entity.h index 169e580457..9424e80b9f 100644 --- a/esphome/components/update/update_entity.h +++ b/esphome/components/update/update_entity.h @@ -1,5 +1,6 @@ #pragma once +#include #include "esphome/core/automation.h" #include "esphome/core/component.h" #include "esphome/core/entity_base.h" @@ -38,12 +39,19 @@ class UpdateEntity : public EntityBase, public EntityBase_DeviceClass { const UpdateState &state = state_; void add_on_state_callback(std::function &&callback) { this->state_callback_.add(std::move(callback)); } + Trigger *get_update_available_trigger() { + if (!update_available_trigger_) { + update_available_trigger_ = std::make_unique>(); + } + return update_available_trigger_.get(); + } protected: UpdateState state_{UPDATE_STATE_UNKNOWN}; UpdateInfo update_info_; CallbackManager state_callback_{}; + std::unique_ptr> update_available_trigger_{nullptr}; }; } // namespace update diff --git a/esphome/components/web_server/web_server.cpp b/esphome/components/web_server/web_server.cpp index d5ded2a02c..8ced5b7e18 100644 --- a/esphome/components/web_server/web_server.cpp +++ b/esphome/components/web_server/web_server.cpp @@ -46,70 +46,58 @@ static const char *const HEADER_CORS_REQ_PNA = "Access-Control-Request-Private-N static const char *const HEADER_CORS_ALLOW_PNA = "Access-Control-Allow-Private-Network"; #endif -UrlMatch match_url(const std::string &url, bool only_domain = false) { - UrlMatch match; - match.valid = false; - match.domain = nullptr; - match.id = nullptr; - match.method = nullptr; - match.domain_len = 0; - match.id_len = 0; - match.method_len = 0; - - const char *url_ptr = url.c_str(); - size_t url_len = url.length(); +// Parse URL and return match info +static UrlMatch match_url(const char *url_ptr, size_t url_len, bool only_domain) { + UrlMatch match{}; // URL must start with '/' - if (url_len < 2 || url_ptr[0] != '/') + if (url_len < 2 || url_ptr[0] != '/') { return match; + } - // Find domain - size_t domain_start = 1; - size_t domain_end = url.find('/', domain_start); + // Skip leading '/' + const char *start = url_ptr + 1; + const char *end = url_ptr + url_len; - if (domain_end == std::string::npos) { - // URL is just "/domain" - match.domain = url_ptr + domain_start; - match.domain_len = url_len - domain_start; - match.valid = true; + // Find domain (everything up to next '/' or end) + const char *domain_end = (const char *) memchr(start, '/', end - start); + if (!domain_end) { + // No second slash found - original behavior returns invalid return match; } // Set domain - match.domain = url_ptr + domain_start; - match.domain_len = domain_end - domain_start; + match.domain = start; + match.domain_len = domain_end - start; + match.valid = true; if (only_domain) { - match.valid = true; return match; } - // Check if there's anything after domain - if (url_len == domain_end + 1) - return match; + // Parse ID if present + if (domain_end + 1 >= end) { + return match; // Nothing after domain slash + } - // Find ID - size_t id_begin = domain_end + 1; - size_t id_end = url.find('/', id_begin); + const char *id_start = domain_end + 1; + const char *id_end = (const char *) memchr(id_start, '/', end - id_start); - match.valid = true; - - if (id_end == std::string::npos) { - // URL is "/domain/id" with no method - match.id = url_ptr + id_begin; - match.id_len = url_len - id_begin; + if (!id_end) { + // No more slashes, entire remaining string is ID + match.id = id_start; + match.id_len = end - id_start; return match; } // Set ID - match.id = url_ptr + id_begin; - match.id_len = id_end - id_begin; + match.id = id_start; + match.id_len = id_end - id_start; - // Set method if present - size_t method_begin = id_end + 1; - if (method_begin < url_len) { - match.method = url_ptr + method_begin; - match.method_len = url_len - method_begin; + // Parse method if present + if (id_end + 1 < end) { + match.method = id_end + 1; + match.method_len = end - (id_end + 1); } return match; @@ -137,7 +125,16 @@ void DeferredUpdateEventSource::process_deferred_queue_() { if (this->send(message.c_str(), "state") != DISCARDED) { // O(n) but memory efficiency is more important than speed here which is why std::vector was chosen deferred_queue_.erase(deferred_queue_.begin()); + this->consecutive_send_failures_ = 0; // Reset failure count on successful send } else { + this->consecutive_send_failures_++; + if (this->consecutive_send_failures_ >= MAX_CONSECUTIVE_SEND_FAILURES) { + // Too many failures, connection is likely dead + ESP_LOGW(TAG, "Closing stuck EventSource connection after %" PRIu16 " failed sends", + this->consecutive_send_failures_); + this->close(); + this->deferred_queue_.clear(); + } break; } } @@ -176,6 +173,8 @@ void DeferredUpdateEventSource::deferrable_send_state(void *source, const char * std::string message = message_generator(web_server_, source); if (this->send(message.c_str(), "state") == DISCARDED) { deq_push_back_with_dedup_(source, message_generator); + } else { + this->consecutive_send_failures_ = 0; // Reset failure count on successful send } } } @@ -256,11 +255,7 @@ void DeferredUpdateEventSourceList::on_client_disconnect_(DeferredUpdateEventSou } #endif -WebServer::WebServer(web_server_base::WebServerBase *base) : base_(base) { -#ifdef USE_ESP32 - to_schedule_lock_ = xSemaphoreCreateMutex(); -#endif -} +WebServer::WebServer(web_server_base::WebServerBase *base) : base_(base) {} #ifdef USE_WEBSERVER_CSS_INCLUDE void WebServer::set_css_include(const char *css_include) { this->css_include_ = css_include; } @@ -292,7 +287,8 @@ void WebServer::setup() { if (logger::global_logger != nullptr && this->expose_log_) { logger::global_logger->add_on_log_callback( // logs are not deferred, the memory overhead would be too large - [this](int level, const char *tag, const char *message) { + [this](int level, const char *tag, const char *message, size_t message_len) { + (void) message_len; this->events_.try_send_nodefer(message, "log", millis()); }); } @@ -309,26 +305,7 @@ void WebServer::setup() { // getting a lot of events this->set_interval(10000, [this]() { this->events_.try_send_nodefer("", "ping", millis(), 30000); }); } -void WebServer::loop() { -#ifdef USE_ESP32 - if (xSemaphoreTake(this->to_schedule_lock_, 0L)) { - std::function fn; - if (!to_schedule_.empty()) { - // scheduler execute things out of order which may lead to incorrect state - // this->defer(std::move(to_schedule_.front())); - // let's execute it directly from the loop - fn = std::move(to_schedule_.front()); - to_schedule_.pop_front(); - } - xSemaphoreGive(this->to_schedule_lock_); - if (fn) { - fn(); - } - } -#endif - - this->events_.loop(); -} +void WebServer::loop() { this->events_.loop(); } void WebServer::dump_config() { ESP_LOGCONFIG(TAG, "Web Server:\n" @@ -523,13 +500,13 @@ void WebServer::handle_switch_request(AsyncWebServerRequest *request, const UrlM std::string data = this->switch_json(obj, obj->state, detail); request->send(200, "application/json", data.c_str()); } else if (match.method_equals("toggle")) { - this->schedule_([obj]() { obj->toggle(); }); + this->defer([obj]() { obj->toggle(); }); request->send(200); } else if (match.method_equals("turn_on")) { - this->schedule_([obj]() { obj->turn_on(); }); + this->defer([obj]() { obj->turn_on(); }); request->send(200); } else if (match.method_equals("turn_off")) { - this->schedule_([obj]() { obj->turn_off(); }); + this->defer([obj]() { obj->turn_off(); }); request->send(200); } else { request->send(404); @@ -565,7 +542,7 @@ void WebServer::handle_button_request(AsyncWebServerRequest *request, const UrlM std::string data = this->button_json(obj, detail); request->send(200, "application/json", data.c_str()); } else if (match.method_equals("press")) { - this->schedule_([obj]() { obj->press(); }); + this->defer([obj]() { obj->press(); }); request->send(200); return; } else { @@ -645,7 +622,7 @@ void WebServer::handle_fan_request(AsyncWebServerRequest *request, const UrlMatc std::string data = this->fan_json(obj, detail); request->send(200, "application/json", data.c_str()); } else if (match.method_equals("toggle")) { - this->schedule_([obj]() { obj->toggle().perform(); }); + this->defer([obj]() { obj->toggle().perform(); }); request->send(200); } else if (match.method_equals("turn_on") || match.method_equals("turn_off")) { auto call = match.method_equals("turn_on") ? obj->turn_on() : obj->turn_off(); @@ -677,7 +654,7 @@ void WebServer::handle_fan_request(AsyncWebServerRequest *request, const UrlMatc return; } } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); } else { request->send(404); @@ -726,7 +703,7 @@ void WebServer::handle_light_request(AsyncWebServerRequest *request, const UrlMa std::string data = this->light_json(obj, detail); request->send(200, "application/json", data.c_str()); } else if (match.method_equals("toggle")) { - this->schedule_([obj]() { obj->toggle().perform(); }); + this->defer([obj]() { obj->toggle().perform(); }); request->send(200); } else if (match.method_equals("turn_on")) { auto call = obj->turn_on(); @@ -783,7 +760,7 @@ void WebServer::handle_light_request(AsyncWebServerRequest *request, const UrlMa call.set_effect(effect); } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); } else if (match.method_equals("turn_off")) { auto call = obj->turn_off(); @@ -793,7 +770,7 @@ void WebServer::handle_light_request(AsyncWebServerRequest *request, const UrlMa call.set_transition_length(*transition * 1000); } } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); } else { request->send(404); @@ -878,7 +855,7 @@ void WebServer::handle_cover_request(AsyncWebServerRequest *request, const UrlMa } } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); return; } @@ -936,7 +913,7 @@ void WebServer::handle_number_request(AsyncWebServerRequest *request, const UrlM call.set_value(*value); } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); return; } @@ -1011,7 +988,7 @@ void WebServer::handle_date_request(AsyncWebServerRequest *request, const UrlMat call.set_date(value); } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); return; } @@ -1070,7 +1047,7 @@ void WebServer::handle_time_request(AsyncWebServerRequest *request, const UrlMat call.set_time(value); } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); return; } @@ -1128,7 +1105,7 @@ void WebServer::handle_datetime_request(AsyncWebServerRequest *request, const Ur call.set_datetime(value); } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); return; } @@ -1245,7 +1222,7 @@ void WebServer::handle_select_request(AsyncWebServerRequest *request, const UrlM call.set_option(option.c_str()); // NOLINT } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); return; } @@ -1332,7 +1309,7 @@ void WebServer::handle_climate_request(AsyncWebServerRequest *request, const Url call.set_target_temperature(*target_temperature); } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); return; } @@ -1449,13 +1426,13 @@ void WebServer::handle_lock_request(AsyncWebServerRequest *request, const UrlMat std::string data = this->lock_json(obj, obj->state, detail); request->send(200, "application/json", data.c_str()); } else if (match.method_equals("lock")) { - this->schedule_([obj]() { obj->lock(); }); + this->defer([obj]() { obj->lock(); }); request->send(200); } else if (match.method_equals("unlock")) { - this->schedule_([obj]() { obj->unlock(); }); + this->defer([obj]() { obj->unlock(); }); request->send(200); } else if (match.method_equals("open")) { - this->schedule_([obj]() { obj->open(); }); + this->defer([obj]() { obj->open(); }); request->send(200); } else { request->send(404); @@ -1526,7 +1503,7 @@ void WebServer::handle_valve_request(AsyncWebServerRequest *request, const UrlMa } } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); return; } @@ -1591,7 +1568,7 @@ void WebServer::handle_alarm_control_panel_request(AsyncWebServerRequest *reques return; } - this->schedule_([call]() mutable { call.perform(); }); + this->defer([call]() mutable { call.perform(); }); request->send(200); return; } @@ -1692,7 +1669,7 @@ void WebServer::handle_update_request(AsyncWebServerRequest *request, const UrlM return; } - this->schedule_([obj]() mutable { obj->perform(); }); + this->defer([obj]() mutable { obj->perform(); }); request->send(200); return; } @@ -1759,7 +1736,11 @@ bool WebServer::canHandle(AsyncWebServerRequest *request) const { } #endif - UrlMatch match = match_url(request->url().c_str(), true); // NOLINT + // Store the URL to prevent temporary string destruction + // request->url() returns a reference to a String (on Arduino) or std::string (on ESP-IDF) + // UrlMatch stores pointers to the string's data, so we must ensure the string outlives match_url() + const auto &url = request->url(); + UrlMatch match = match_url(url.c_str(), url.length(), true); if (!match.valid) return false; #ifdef USE_SENSOR @@ -1898,7 +1879,10 @@ void WebServer::handleRequest(AsyncWebServerRequest *request) { } #endif - UrlMatch match = match_url(request->url().c_str()); // NOLINT + // See comment in canHandle() for why we store the URL reference + const auto &url = request->url(); + UrlMatch match = match_url(url.c_str(), url.length(), false); + #ifdef USE_SENSOR if (match.domain_equals("sensor")) { this->handle_sensor_request(request, match); @@ -2062,16 +2046,6 @@ void WebServer::add_sorting_group(uint64_t group_id, const std::string &group_na } #endif -void WebServer::schedule_(std::function &&f) { -#ifdef USE_ESP32 - xSemaphoreTake(this->to_schedule_lock_, portMAX_DELAY); - to_schedule_.push_back(std::move(f)); - xSemaphoreGive(this->to_schedule_lock_); -#else - this->defer(std::move(f)); -#endif -} - } // namespace web_server } // namespace esphome #endif diff --git a/esphome/components/web_server/web_server.h b/esphome/components/web_server/web_server.h index 5f175b6bdd..0c15881d1e 100644 --- a/esphome/components/web_server/web_server.h +++ b/esphome/components/web_server/web_server.h @@ -14,11 +14,6 @@ #include #include #include -#ifdef USE_ESP32 -#include -#include -#include -#endif #if USE_WEBSERVER_VERSION >= 2 extern const uint8_t ESPHOME_WEBSERVER_INDEX_HTML[] PROGMEM; @@ -126,6 +121,8 @@ class DeferredUpdateEventSource : public AsyncEventSource { // footprint is more important than speed here) std::vector deferred_queue_; WebServer *web_server_; + uint16_t consecutive_send_failures_{0}; + static constexpr uint16_t MAX_CONSECUTIVE_SEND_FAILURES = 2500; // ~20 seconds at 125Hz loop rate // helper for allowing only unique entries in the queue void deq_push_back_with_dedup_(void *source, message_generator_t *message_generator); @@ -501,7 +498,6 @@ class WebServer : public Controller, public Component, public AsyncWebHandler { protected: void add_sorting_info_(JsonObject &root, EntityBase *entity); - void schedule_(std::function &&f); web_server_base::WebServerBase *base_; #ifdef USE_ARDUINO DeferredUpdateEventSourceList events_; @@ -521,10 +517,6 @@ class WebServer : public Controller, public Component, public AsyncWebHandler { const char *js_include_{nullptr}; #endif bool expose_log_{true}; -#ifdef USE_ESP32 - std::deque> to_schedule_; - SemaphoreHandle_t to_schedule_lock_; -#endif }; } // namespace web_server diff --git a/esphome/components/web_server_idf/web_server_idf.cpp b/esphome/components/web_server_idf/web_server_idf.cpp index 9478e4748c..d2447681f5 100644 --- a/esphome/components/web_server_idf/web_server_idf.cpp +++ b/esphome/components/web_server_idf/web_server_idf.cpp @@ -37,6 +37,15 @@ namespace web_server_idf { static const char *const TAG = "web_server_idf"; +// Global instance to avoid guard variable (saves 8 bytes) +// This is initialized at program startup before any threads +namespace { +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +DefaultHeaders default_headers_instance; +} // namespace + +DefaultHeaders &DefaultHeaders::Instance() { return default_headers_instance; } + void AsyncWebServer::end() { if (this->server_) { httpd_stop(this->server_); diff --git a/esphome/components/web_server_idf/web_server_idf.h b/esphome/components/web_server_idf/web_server_idf.h index 8de25c8e96..e8e40ef9b0 100644 --- a/esphome/components/web_server_idf/web_server_idf.h +++ b/esphome/components/web_server_idf/web_server_idf.h @@ -328,10 +328,7 @@ class DefaultHeaders { void addHeader(const char *name, const char *value) { this->headers_.emplace_back(name, value); } // NOLINTNEXTLINE(readability-identifier-naming) - static DefaultHeaders &Instance() { - static DefaultHeaders instance; - return instance; - } + static DefaultHeaders &Instance(); protected: std::vector> headers_; diff --git a/esphome/components/wifi/__init__.py b/esphome/components/wifi/__init__.py index e8ae9b1b4e..61f37556ba 100644 --- a/esphome/components/wifi/__init__.py +++ b/esphome/components/wifi/__init__.py @@ -3,6 +3,7 @@ from esphome.automation import Condition import esphome.codegen as cg from esphome.components.esp32 import add_idf_sdkconfig_option, const, get_esp32_variant from esphome.components.network import IPAddress +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_AP, @@ -39,6 +40,7 @@ from esphome.const import ( CONF_TTLS_PHASE_2, CONF_USE_ADDRESS, CONF_USERNAME, + PlatformFramework, ) from esphome.core import CORE, HexInt, coroutine_with_priority import esphome.final_validate as fv @@ -526,3 +528,18 @@ async def wifi_set_sta_to_code(config, action_id, template_arg, args): await automation.build_automation(var.get_error_trigger(), [], on_error_config) await cg.register_component(var, config) return var + + +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "wifi_component_esp32_arduino.cpp": {PlatformFramework.ESP32_ARDUINO}, + "wifi_component_esp_idf.cpp": {PlatformFramework.ESP32_IDF}, + "wifi_component_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "wifi_component_libretiny.cpp": { + PlatformFramework.BK72XX_ARDUINO, + PlatformFramework.RTL87XX_ARDUINO, + PlatformFramework.LN882X_ARDUINO, + }, + "wifi_component_pico_w.cpp": {PlatformFramework.RP2040_ARDUINO}, + } +) diff --git a/esphome/config_helpers.py b/esphome/config_helpers.py index 54242bc259..50ce4e8e34 100644 --- a/esphome/config_helpers.py +++ b/esphome/config_helpers.py @@ -1,4 +1,20 @@ -from esphome.const import CONF_ID +from collections.abc import Callable + +from esphome.const import ( + CONF_ID, + CONF_LEVEL, + CONF_LOGGER, + KEY_CORE, + KEY_TARGET_FRAMEWORK, + KEY_TARGET_PLATFORM, + PlatformFramework, +) +from esphome.core import CORE + +# Pre-build lookup map from (platform, framework) tuples to PlatformFramework enum +_PLATFORM_FRAMEWORK_LOOKUP = { + (pf.value[0].value, pf.value[1].value): pf for pf in PlatformFramework +} class Extend: @@ -103,3 +119,60 @@ def merge_config(full_old, full_new): return new return merge(full_old, full_new) + + +def filter_source_files_from_platform( + files_map: dict[str, set[PlatformFramework]], +) -> Callable[[], list[str]]: + """Helper to build a FILTER_SOURCE_FILES function from platform mapping. + + Args: + files_map: Dict mapping filename to set of PlatformFramework enums + that should compile this file + + Returns: + Function that returns list of files to exclude for current platform + """ + + def filter_source_files() -> list[str]: + # Get current platform/framework + core_data = CORE.data.get(KEY_CORE, {}) + target_platform = core_data.get(KEY_TARGET_PLATFORM) + target_framework = core_data.get(KEY_TARGET_FRAMEWORK) + + if not target_platform or not target_framework: + return [] + + # Direct lookup of current PlatformFramework + current_platform_framework = _PLATFORM_FRAMEWORK_LOOKUP.get( + (target_platform, target_framework) + ) + + if not current_platform_framework: + return [] + + # Return files that should be excluded for current platform + return [ + filename + for filename, platforms in files_map.items() + if current_platform_framework not in platforms + ] + + return filter_source_files + + +def get_logger_level() -> str: + """Get the configured logger level. + + This is used by components to determine what logging features to include + based on the configured log level. + + Returns: + The configured logger level string, defaults to "DEBUG" if not configured + """ + # Check if logger config exists + if CONF_LOGGER not in CORE.config: + return "DEBUG" + + logger_config = CORE.config[CONF_LOGGER] + return logger_config.get(CONF_LEVEL, "DEBUG") diff --git a/esphome/const.py b/esphome/const.py index 4aeb5179e6..085b9b39b8 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -1,5 +1,9 @@ """Constants used by esphome.""" +from enum import Enum + +from esphome.enum import StrEnum + __version__ = "2025.7.0-dev" ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_" @@ -7,14 +11,55 @@ VALID_SUBSTITUTIONS_CHARACTERS = ( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_" ) -PLATFORM_BK72XX = "bk72xx" -PLATFORM_ESP32 = "esp32" -PLATFORM_ESP8266 = "esp8266" -PLATFORM_HOST = "host" -PLATFORM_LIBRETINY_OLDSTYLE = "libretiny" -PLATFORM_LN882X = "ln882x" -PLATFORM_RP2040 = "rp2040" -PLATFORM_RTL87XX = "rtl87xx" + +class Platform(StrEnum): + """Platform identifiers for ESPHome.""" + + BK72XX = "bk72xx" + ESP32 = "esp32" + ESP8266 = "esp8266" + HOST = "host" + LIBRETINY_OLDSTYLE = "libretiny" + LN882X = "ln882x" + RP2040 = "rp2040" + RTL87XX = "rtl87xx" + + +class Framework(StrEnum): + """Framework identifiers for ESPHome.""" + + ARDUINO = "arduino" + ESP_IDF = "esp-idf" + NATIVE = "host" + + +class PlatformFramework(Enum): + """Combined platform-framework identifiers with tuple values.""" + + # ESP32 variants + ESP32_ARDUINO = (Platform.ESP32, Framework.ARDUINO) + ESP32_IDF = (Platform.ESP32, Framework.ESP_IDF) + + # Arduino framework platforms + ESP8266_ARDUINO = (Platform.ESP8266, Framework.ARDUINO) + RP2040_ARDUINO = (Platform.RP2040, Framework.ARDUINO) + BK72XX_ARDUINO = (Platform.BK72XX, Framework.ARDUINO) + RTL87XX_ARDUINO = (Platform.RTL87XX, Framework.ARDUINO) + LN882X_ARDUINO = (Platform.LN882X, Framework.ARDUINO) + + # Host platform (native) + HOST_NATIVE = (Platform.HOST, Framework.NATIVE) + + +# Maintain backward compatibility by reassigning after enum definition +PLATFORM_BK72XX = Platform.BK72XX +PLATFORM_ESP32 = Platform.ESP32 +PLATFORM_ESP8266 = Platform.ESP8266 +PLATFORM_HOST = Platform.HOST +PLATFORM_LIBRETINY_OLDSTYLE = Platform.LIBRETINY_OLDSTYLE +PLATFORM_LN882X = Platform.LN882X +PLATFORM_RP2040 = Platform.RP2040 +PLATFORM_RTL87XX = Platform.RTL87XX SOURCE_FILE_EXTENSIONS = {".cpp", ".hpp", ".h", ".c", ".tcc", ".ino"} diff --git a/esphome/core/application.h b/esphome/core/application.h index 6ee05309ca..f2b5cb5c89 100644 --- a/esphome/core/application.h +++ b/esphome/core/application.h @@ -368,6 +368,17 @@ class Application { uint8_t get_app_state() const { return this->app_state_; } +// Helper macro for entity getter method declarations - reduces code duplication +// When USE_DEVICE_ID is enabled in the future, this can be conditionally compiled to add device_id parameter +#define GET_ENTITY_METHOD(entity_type, entity_name, entities_member) \ + entity_type *get_##entity_name##_by_key(uint32_t key, bool include_internal = false) { \ + for (auto *obj : this->entities_member##_) { \ + if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) \ + return obj; \ + } \ + return nullptr; \ + } + #ifdef USE_DEVICES const std::vector &get_devices() { return this->devices_; } #endif @@ -376,218 +387,92 @@ class Application { #endif #ifdef USE_BINARY_SENSOR const std::vector &get_binary_sensors() { return this->binary_sensors_; } - binary_sensor::BinarySensor *get_binary_sensor_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->binary_sensors_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(binary_sensor::BinarySensor, binary_sensor, binary_sensors) #endif #ifdef USE_SWITCH const std::vector &get_switches() { return this->switches_; } - switch_::Switch *get_switch_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->switches_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(switch_::Switch, switch, switches) #endif #ifdef USE_BUTTON const std::vector &get_buttons() { return this->buttons_; } - button::Button *get_button_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->buttons_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(button::Button, button, buttons) #endif #ifdef USE_SENSOR const std::vector &get_sensors() { return this->sensors_; } - sensor::Sensor *get_sensor_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->sensors_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(sensor::Sensor, sensor, sensors) #endif #ifdef USE_TEXT_SENSOR const std::vector &get_text_sensors() { return this->text_sensors_; } - text_sensor::TextSensor *get_text_sensor_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->text_sensors_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(text_sensor::TextSensor, text_sensor, text_sensors) #endif #ifdef USE_FAN const std::vector &get_fans() { return this->fans_; } - fan::Fan *get_fan_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->fans_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(fan::Fan, fan, fans) #endif #ifdef USE_COVER const std::vector &get_covers() { return this->covers_; } - cover::Cover *get_cover_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->covers_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(cover::Cover, cover, covers) #endif #ifdef USE_LIGHT const std::vector &get_lights() { return this->lights_; } - light::LightState *get_light_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->lights_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(light::LightState, light, lights) #endif #ifdef USE_CLIMATE const std::vector &get_climates() { return this->climates_; } - climate::Climate *get_climate_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->climates_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(climate::Climate, climate, climates) #endif #ifdef USE_NUMBER const std::vector &get_numbers() { return this->numbers_; } - number::Number *get_number_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->numbers_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(number::Number, number, numbers) #endif #ifdef USE_DATETIME_DATE const std::vector &get_dates() { return this->dates_; } - datetime::DateEntity *get_date_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->dates_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(datetime::DateEntity, date, dates) #endif #ifdef USE_DATETIME_TIME const std::vector &get_times() { return this->times_; } - datetime::TimeEntity *get_time_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->times_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(datetime::TimeEntity, time, times) #endif #ifdef USE_DATETIME_DATETIME const std::vector &get_datetimes() { return this->datetimes_; } - datetime::DateTimeEntity *get_datetime_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->datetimes_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(datetime::DateTimeEntity, datetime, datetimes) #endif #ifdef USE_TEXT const std::vector &get_texts() { return this->texts_; } - text::Text *get_text_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->texts_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(text::Text, text, texts) #endif #ifdef USE_SELECT const std::vector &get_selects() { return this->selects_; } - select::Select *get_select_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->selects_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(select::Select, select, selects) #endif #ifdef USE_LOCK const std::vector &get_locks() { return this->locks_; } - lock::Lock *get_lock_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->locks_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(lock::Lock, lock, locks) #endif #ifdef USE_VALVE const std::vector &get_valves() { return this->valves_; } - valve::Valve *get_valve_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->valves_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(valve::Valve, valve, valves) #endif #ifdef USE_MEDIA_PLAYER const std::vector &get_media_players() { return this->media_players_; } - media_player::MediaPlayer *get_media_player_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->media_players_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(media_player::MediaPlayer, media_player, media_players) #endif #ifdef USE_ALARM_CONTROL_PANEL const std::vector &get_alarm_control_panels() { return this->alarm_control_panels_; } - alarm_control_panel::AlarmControlPanel *get_alarm_control_panel_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->alarm_control_panels_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(alarm_control_panel::AlarmControlPanel, alarm_control_panel, alarm_control_panels) #endif #ifdef USE_EVENT const std::vector &get_events() { return this->events_; } - event::Event *get_event_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->events_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(event::Event, event, events) #endif #ifdef USE_UPDATE const std::vector &get_updates() { return this->updates_; } - update::UpdateEntity *get_update_by_key(uint32_t key, bool include_internal = false) { - for (auto *obj : this->updates_) { - if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) - return obj; - } - return nullptr; - } + GET_ENTITY_METHOD(update::UpdateEntity, update, updates) #endif Scheduler scheduler; diff --git a/esphome/core/color.cpp b/esphome/core/color.cpp index 58d995db2f..7e390b2354 100644 --- a/esphome/core/color.cpp +++ b/esphome/core/color.cpp @@ -2,10 +2,8 @@ namespace esphome { -const Color Color::BLACK(0, 0, 0, 0); -const Color Color::WHITE(255, 255, 255, 255); - -const Color COLOR_BLACK(0, 0, 0, 0); -const Color COLOR_WHITE(255, 255, 255, 255); +// C++20 constinit ensures compile-time initialization (stored in ROM) +constinit const Color Color::BLACK(0, 0, 0, 0); +constinit const Color Color::WHITE(255, 255, 255, 255); } // namespace esphome diff --git a/esphome/core/color.h b/esphome/core/color.h index 1c43fd9d3e..2b307bb438 100644 --- a/esphome/core/color.h +++ b/esphome/core/color.h @@ -5,7 +5,9 @@ namespace esphome { -inline static uint8_t esp_scale8(uint8_t i, uint8_t scale) { return (uint16_t(i) * (1 + uint16_t(scale))) / 256; } +inline static constexpr uint8_t esp_scale8(uint8_t i, uint8_t scale) { + return (uint16_t(i) * (1 + uint16_t(scale))) / 256; +} struct Color { union { @@ -31,17 +33,20 @@ struct Color { uint32_t raw_32; }; - inline Color() ESPHOME_ALWAYS_INLINE : r(0), g(0), b(0), w(0) {} // NOLINT - inline Color(uint8_t red, uint8_t green, uint8_t blue) ESPHOME_ALWAYS_INLINE : r(red), g(green), b(blue), w(0) {} + inline constexpr Color() ESPHOME_ALWAYS_INLINE : raw_32(0) {} // NOLINT + inline constexpr Color(uint8_t red, uint8_t green, uint8_t blue) ESPHOME_ALWAYS_INLINE : r(red), + g(green), + b(blue), + w(0) {} - inline Color(uint8_t red, uint8_t green, uint8_t blue, uint8_t white) ESPHOME_ALWAYS_INLINE : r(red), - g(green), - b(blue), - w(white) {} - inline explicit Color(uint32_t colorcode) ESPHOME_ALWAYS_INLINE : r((colorcode >> 16) & 0xFF), - g((colorcode >> 8) & 0xFF), - b((colorcode >> 0) & 0xFF), - w((colorcode >> 24) & 0xFF) {} + inline constexpr Color(uint8_t red, uint8_t green, uint8_t blue, uint8_t white) ESPHOME_ALWAYS_INLINE : r(red), + g(green), + b(blue), + w(white) {} + inline explicit constexpr Color(uint32_t colorcode) ESPHOME_ALWAYS_INLINE : r((colorcode >> 16) & 0xFF), + g((colorcode >> 8) & 0xFF), + b((colorcode >> 0) & 0xFF), + w((colorcode >> 24) & 0xFF) {} inline bool is_on() ESPHOME_ALWAYS_INLINE { return this->raw_32 != 0; } @@ -169,9 +174,4 @@ struct Color { static const Color WHITE; }; -ESPDEPRECATED("Use Color::BLACK instead of COLOR_BLACK", "v1.21") -extern const Color COLOR_BLACK; -ESPDEPRECATED("Use Color::WHITE instead of COLOR_WHITE", "v1.21") -extern const Color COLOR_WHITE; - } // namespace esphome diff --git a/esphome/core/component.cpp b/esphome/core/component.cpp index aba5dc729c..9d863e56cd 100644 --- a/esphome/core/component.cpp +++ b/esphome/core/component.cpp @@ -26,17 +26,17 @@ static const char *const TAG = "component"; // 1. Components are never destroyed in ESPHome // 2. Failed components remain failed (no recovery mechanism) // 3. Memory usage is minimal (only failures with custom messages are stored) -static std::unique_ptr>> &get_component_error_messages() { - static std::unique_ptr>> instance; - return instance; -} +// Using namespace-scope static to avoid guard variables (saves 16 bytes total) +// This is safe because ESPHome is single-threaded during initialization +namespace { +// Error messages for failed components +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::unique_ptr>> component_error_messages; // Setup priority overrides - freed after setup completes -// Typically < 5 entries, lazy allocated -static std::unique_ptr>> &get_setup_priority_overrides() { - static std::unique_ptr>> instance; - return instance; -} +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::unique_ptr>> setup_priority_overrides; +} // namespace namespace setup_priority { @@ -130,8 +130,8 @@ void Component::call_dump_config() { if (this->is_failed()) { // Look up error message from global vector const char *error_msg = "unspecified"; - if (get_component_error_messages()) { - for (const auto &pair : *get_component_error_messages()) { + if (component_error_messages) { + for (const auto &pair : *component_error_messages) { if (pair.first == this) { error_msg = pair.second; break; @@ -248,6 +248,9 @@ bool Component::cancel_defer(const std::string &name) { // NOLINT void Component::defer(const std::string &name, std::function &&f) { // NOLINT App.scheduler.set_timeout(this, name, 0, std::move(f)); } +void Component::defer(const char *name, std::function &&f) { // NOLINT + App.scheduler.set_timeout(this, name, 0, std::move(f)); +} void Component::set_timeout(uint32_t timeout, std::function &&f) { // NOLINT App.scheduler.set_timeout(this, "", timeout, std::move(f)); } @@ -282,18 +285,18 @@ void Component::status_set_error(const char *message) { ESP_LOGE(TAG, "Component %s set Error flag: %s", this->get_component_source(), message); if (strcmp(message, "unspecified") != 0) { // Lazy allocate the error messages vector if needed - if (!get_component_error_messages()) { - get_component_error_messages() = std::make_unique>>(); + if (!component_error_messages) { + component_error_messages = std::make_unique>>(); } // Check if this component already has an error message - for (auto &pair : *get_component_error_messages()) { + for (auto &pair : *component_error_messages) { if (pair.first == this) { pair.second = message; return; } } // Add new error message - get_component_error_messages()->emplace_back(this, message); + component_error_messages->emplace_back(this, message); } } void Component::status_clear_warning() { @@ -319,9 +322,9 @@ void Component::status_momentary_error(const std::string &name, uint32_t length) void Component::dump_config() {} float Component::get_actual_setup_priority() const { // Check if there's an override in the global vector - if (get_setup_priority_overrides()) { + if (setup_priority_overrides) { // Linear search is fine for small n (typically < 5 overrides) - for (const auto &pair : *get_setup_priority_overrides()) { + for (const auto &pair : *setup_priority_overrides) { if (pair.first == this) { return pair.second; } @@ -331,14 +334,14 @@ float Component::get_actual_setup_priority() const { } void Component::set_setup_priority(float priority) { // Lazy allocate the vector if needed - if (!get_setup_priority_overrides()) { - get_setup_priority_overrides() = std::make_unique>>(); + if (!setup_priority_overrides) { + setup_priority_overrides = std::make_unique>>(); // Reserve some space to avoid reallocations (most configs have < 10 overrides) - get_setup_priority_overrides()->reserve(10); + setup_priority_overrides->reserve(10); } // Check if this component already has an override - for (auto &pair : *get_setup_priority_overrides()) { + for (auto &pair : *setup_priority_overrides) { if (pair.first == this) { pair.second = priority; return; @@ -346,7 +349,7 @@ void Component::set_setup_priority(float priority) { } // Add new override - get_setup_priority_overrides()->emplace_back(this, priority); + setup_priority_overrides->emplace_back(this, priority); } bool Component::has_overridden_loop() const { @@ -411,7 +414,7 @@ WarnIfComponentBlockingGuard::~WarnIfComponentBlockingGuard() {} void clear_setup_priority_overrides() { // Free the setup priority map completely - get_setup_priority_overrides().reset(); + setup_priority_overrides.reset(); } } // namespace esphome diff --git a/esphome/core/component.h b/esphome/core/component.h index ab30466e2d..3734473a02 100644 --- a/esphome/core/component.h +++ b/esphome/core/component.h @@ -380,6 +380,21 @@ class Component { */ void defer(const std::string &name, std::function &&f); // NOLINT + /** Defer a callback to the next loop() call with a const char* name. + * + * IMPORTANT: The provided name pointer must remain valid for the lifetime of the deferred task. + * This means the name should be: + * - A string literal (e.g., "update") + * - A static const char* variable + * - A pointer with lifetime >= the deferred execution + * + * For dynamic strings, use the std::string overload instead. + * + * @param name The name of the defer function (must have static lifetime) + * @param f The callback + */ + void defer(const char *name, std::function &&f); // NOLINT + /// Defer a callback to the next loop() call. void defer(std::function &&f); // NOLINT diff --git a/esphome/core/component_iterator.cpp b/esphome/core/component_iterator.cpp index b06c964b7c..aab5c2a72d 100644 --- a/esphome/core/component_iterator.cpp +++ b/esphome/core/component_iterator.cpp @@ -158,16 +158,16 @@ void ComponentIterator::advance() { } break; #endif -#ifdef USE_ESP32_CAMERA +#ifdef USE_CAMERA case IteratorState::CAMERA: - if (esp32_camera::global_esp32_camera == nullptr) { + if (camera::Camera::instance() == nullptr) { advance_platform = true; } else { - if (esp32_camera::global_esp32_camera->is_internal() && !this->include_internal_) { + if (camera::Camera::instance()->is_internal() && !this->include_internal_) { advance_platform = success = true; break; } else { - advance_platform = success = this->on_camera(esp32_camera::global_esp32_camera); + advance_platform = success = this->on_camera(camera::Camera::instance()); } } break; @@ -386,8 +386,8 @@ bool ComponentIterator::on_begin() { return true; } #ifdef USE_API bool ComponentIterator::on_service(api::UserServiceDescriptor *service) { return true; } #endif -#ifdef USE_ESP32_CAMERA -bool ComponentIterator::on_camera(esp32_camera::ESP32Camera *camera) { return true; } +#ifdef USE_CAMERA +bool ComponentIterator::on_camera(camera::Camera *camera) { return true; } #endif #ifdef USE_MEDIA_PLAYER bool ComponentIterator::on_media_player(media_player::MediaPlayer *media_player) { return true; } diff --git a/esphome/core/component_iterator.h b/esphome/core/component_iterator.h index 4b41872db7..eda786be7f 100644 --- a/esphome/core/component_iterator.h +++ b/esphome/core/component_iterator.h @@ -4,8 +4,8 @@ #include "esphome/core/controller.h" #include "esphome/core/helpers.h" -#ifdef USE_ESP32_CAMERA -#include "esphome/components/esp32_camera/esp32_camera.h" +#ifdef USE_CAMERA +#include "esphome/components/camera/camera.h" #endif namespace esphome { @@ -48,8 +48,8 @@ class ComponentIterator { #ifdef USE_API virtual bool on_service(api::UserServiceDescriptor *service); #endif -#ifdef USE_ESP32_CAMERA - virtual bool on_camera(esp32_camera::ESP32Camera *camera); +#ifdef USE_CAMERA + virtual bool on_camera(camera::Camera *camera); #endif #ifdef USE_CLIMATE virtual bool on_climate(climate::Climate *climate) = 0; @@ -125,7 +125,7 @@ class ComponentIterator { #ifdef USE_API SERVICE, #endif -#ifdef USE_ESP32_CAMERA +#ifdef USE_CAMERA CAMERA, #endif #ifdef USE_CLIMATE diff --git a/esphome/core/config.py b/esphome/core/config.py index 641c73a292..f73369f28f 100644 --- a/esphome/core/config.py +++ b/esphome/core/config.py @@ -6,6 +6,7 @@ from pathlib import Path from esphome import automation, core import esphome.codegen as cg +from esphome.config_helpers import filter_source_files_from_platform import esphome.config_validation as cv from esphome.const import ( CONF_AREA, @@ -35,6 +36,7 @@ from esphome.const import ( CONF_TRIGGER_ID, CONF_VERSION, KEY_CORE, + PlatformFramework, __version__ as ESPHOME_VERSION, ) from esphome.core import CORE, coroutine_with_priority @@ -551,3 +553,16 @@ async def to_code(config: ConfigType) -> None: cg.add(dev.set_area_id(area_id_hash)) cg.add(cg.App.register_device(dev)) + + +# Platform-specific source files for core +FILTER_SOURCE_FILES = filter_source_files_from_platform( + { + "ring_buffer.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + # Note: lock_free_queue.h and event_pool.h are header files and don't need to be filtered + # as they are only included when needed by the preprocessor + } +) diff --git a/esphome/core/defines.h b/esphome/core/defines.h index 297c02effc..aed37d31d7 100644 --- a/esphome/core/defines.h +++ b/esphome/core/defines.h @@ -23,6 +23,7 @@ #define USE_AREAS #define USE_BINARY_SENSOR #define USE_BUTTON +#define USE_CAMERA #define USE_CLIMATE #define USE_COVER #define USE_DATETIME @@ -32,6 +33,7 @@ #define USE_DEEP_SLEEP #define USE_DEVICES #define USE_DISPLAY +#define USE_ENTITY_ICON #define USE_ESP32_IMPROV_STATE_CALLBACK #define USE_EVENT #define USE_FAN @@ -86,6 +88,7 @@ #define USE_SELECT #define USE_SENSOR #define USE_STATUS_LED +#define USE_STATUS_SENSOR #define USE_SWITCH #define USE_TEXT #define USE_TEXT_SENSOR @@ -143,7 +146,6 @@ #define USE_ESP32_BLE #define USE_ESP32_BLE_CLIENT #define USE_ESP32_BLE_SERVER -#define USE_ESP32_CAMERA #define USE_I2C #define USE_IMPROV #define USE_MICROPHONE diff --git a/esphome/core/entity_base.cpp b/esphome/core/entity_base.cpp index 6afd02ff65..2ea9c77a3e 100644 --- a/esphome/core/entity_base.cpp +++ b/esphome/core/entity_base.cpp @@ -27,12 +27,22 @@ void EntityBase::set_name(const char *name) { // Entity Icon std::string EntityBase::get_icon() const { +#ifdef USE_ENTITY_ICON if (this->icon_c_str_ == nullptr) { return ""; } return this->icon_c_str_; +#else + return ""; +#endif +} +void EntityBase::set_icon(const char *icon) { +#ifdef USE_ENTITY_ICON + this->icon_c_str_ = icon; +#else + // No-op when USE_ENTITY_ICON is not defined +#endif } -void EntityBase::set_icon(const char *icon) { this->icon_c_str_ = icon; } // Entity Object ID std::string EntityBase::get_object_id() const { diff --git a/esphome/core/entity_base.h b/esphome/core/entity_base.h index 4819b66108..00b1264ed0 100644 --- a/esphome/core/entity_base.h +++ b/esphome/core/entity_base.h @@ -80,7 +80,9 @@ class EntityBase { StringRef name_; const char *object_id_c_str_{nullptr}; +#ifdef USE_ENTITY_ICON const char *icon_c_str_{nullptr}; +#endif uint32_t object_id_hash_{}; #ifdef USE_DEVICES Device *device_{}; diff --git a/esphome/core/entity_helpers.py b/esphome/core/entity_helpers.py index 2442fbca4b..a3244856a2 100644 --- a/esphome/core/entity_helpers.py +++ b/esphome/core/entity_helpers.py @@ -1,6 +1,7 @@ from collections.abc import Callable import logging +import esphome.codegen as cg import esphome.config_validation as cv from esphome.const import ( CONF_DEVICE_ID, @@ -108,6 +109,8 @@ async def setup_entity(var: MockObj, config: ConfigType, platform: str) -> None: if CONF_INTERNAL in config: add(var.set_internal(config[CONF_INTERNAL])) if CONF_ICON in config: + # Add USE_ENTITY_ICON define when icons are used + cg.add_define("USE_ENTITY_ICON") add(var.set_icon(config[CONF_ICON])) if CONF_ENTITY_CATEGORY in config: add(var.set_entity_category(config[CONF_ENTITY_CATEGORY])) diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp index b4923c7af0..0c11c5d486 100644 --- a/esphome/core/helpers.cpp +++ b/esphome/core/helpers.cpp @@ -12,47 +12,10 @@ #include #include -#ifdef USE_HOST -#ifndef _WIN32 -#include -#include -#include -#endif -#include -#endif -#if defined(USE_ESP8266) -#include -#include -// for xt_rsil()/xt_wsr_ps() -#include -#elif defined(USE_ESP32_FRAMEWORK_ARDUINO) -#include -#elif defined(USE_ESP_IDF) -#include -#include -#include "esp_random.h" -#include "esp_system.h" -#elif defined(USE_RP2040) -#if defined(USE_WIFI) -#include -#endif -#include -#include -#elif defined(USE_HOST) -#include -#include -#endif #ifdef USE_ESP32 -#include "esp_efuse.h" -#include "esp_efuse_table.h" -#include "esp_mac.h" #include "rom/crc.h" #endif -#ifdef USE_LIBRETINY -#include // for macAddress() -#endif - namespace esphome { static const char *const TAG = "helpers"; @@ -177,70 +140,7 @@ uint32_t fnv1_hash(const std::string &str) { return hash; } -#ifdef USE_ESP32 -uint32_t random_uint32() { return esp_random(); } -#elif defined(USE_ESP8266) -uint32_t random_uint32() { return os_random(); } -#elif defined(USE_RP2040) -uint32_t random_uint32() { - uint32_t result = 0; - for (uint8_t i = 0; i < 32; i++) { - result <<= 1; - result |= rosc_hw->randombit; - } - return result; -} -#elif defined(USE_LIBRETINY) -uint32_t random_uint32() { return rand(); } -#elif defined(USE_HOST) -uint32_t random_uint32() { - std::random_device dev; - std::mt19937 rng(dev()); - std::uniform_int_distribution dist(0, std::numeric_limits::max()); - return dist(rng); -} -#endif float random_float() { return static_cast(random_uint32()) / static_cast(UINT32_MAX); } -#ifdef USE_ESP32 -bool random_bytes(uint8_t *data, size_t len) { - esp_fill_random(data, len); - return true; -} -#elif defined(USE_ESP8266) -bool random_bytes(uint8_t *data, size_t len) { return os_get_random(data, len) == 0; } -#elif defined(USE_RP2040) -bool random_bytes(uint8_t *data, size_t len) { - while (len-- != 0) { - uint8_t result = 0; - for (uint8_t i = 0; i < 8; i++) { - result <<= 1; - result |= rosc_hw->randombit; - } - *data++ = result; - } - return true; -} -#elif defined(USE_LIBRETINY) -bool random_bytes(uint8_t *data, size_t len) { - lt_rand_bytes(data, len); - return true; -} -#elif defined(USE_HOST) -bool random_bytes(uint8_t *data, size_t len) { - FILE *fp = fopen("/dev/urandom", "r"); - if (fp == nullptr) { - ESP_LOGW(TAG, "Could not open /dev/urandom, errno=%d", errno); - exit(1); - } - size_t read = fread(data, 1, len, fp); - if (read != len) { - ESP_LOGW(TAG, "Not enough data from /dev/urandom"); - exit(1); - } - fclose(fp); - return true; -} -#endif // Strings @@ -358,53 +258,60 @@ std::string format_hex(const uint8_t *data, size_t length) { std::string format_hex(const std::vector &data) { return format_hex(data.data(), data.size()); } static char format_hex_pretty_char(uint8_t v) { return v >= 10 ? 'A' + (v - 10) : '0' + v; } -std::string format_hex_pretty(const uint8_t *data, size_t length) { - if (length == 0) +std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length) { + if (data == nullptr || length == 0) return ""; std::string ret; - ret.resize(3 * length - 1); + uint8_t multiple = separator ? 3 : 2; // 3 if separator is not \0, 2 otherwise + ret.resize(multiple * length - 1); for (size_t i = 0; i < length; i++) { - ret[3 * i] = format_hex_pretty_char((data[i] & 0xF0) >> 4); - ret[3 * i + 1] = format_hex_pretty_char(data[i] & 0x0F); - if (i != length - 1) - ret[3 * i + 2] = '.'; + ret[multiple * i] = format_hex_pretty_char((data[i] & 0xF0) >> 4); + ret[multiple * i + 1] = format_hex_pretty_char(data[i] & 0x0F); + if (separator && i != length - 1) + ret[multiple * i + 2] = separator; } - if (length > 4) - return ret + " (" + to_string(length) + ")"; + if (show_length && length > 4) + return ret + " (" + std::to_string(length) + ")"; return ret; } -std::string format_hex_pretty(const std::vector &data) { return format_hex_pretty(data.data(), data.size()); } +std::string format_hex_pretty(const std::vector &data, char separator, bool show_length) { + return format_hex_pretty(data.data(), data.size(), separator, show_length); +} -std::string format_hex_pretty(const uint16_t *data, size_t length) { - if (length == 0) +std::string format_hex_pretty(const uint16_t *data, size_t length, char separator, bool show_length) { + if (data == nullptr || length == 0) return ""; std::string ret; - ret.resize(5 * length - 1); + uint8_t multiple = separator ? 5 : 4; // 5 if separator is not \0, 4 otherwise + ret.resize(multiple * length - 1); for (size_t i = 0; i < length; i++) { - ret[5 * i] = format_hex_pretty_char((data[i] & 0xF000) >> 12); - ret[5 * i + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8); - ret[5 * i + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4); - ret[5 * i + 3] = format_hex_pretty_char(data[i] & 0x000F); - if (i != length - 1) - ret[5 * i + 2] = '.'; + ret[multiple * i] = format_hex_pretty_char((data[i] & 0xF000) >> 12); + ret[multiple * i + 1] = format_hex_pretty_char((data[i] & 0x0F00) >> 8); + ret[multiple * i + 2] = format_hex_pretty_char((data[i] & 0x00F0) >> 4); + ret[multiple * i + 3] = format_hex_pretty_char(data[i] & 0x000F); + if (separator && i != length - 1) + ret[multiple * i + 4] = separator; } - if (length > 4) - return ret + " (" + to_string(length) + ")"; + if (show_length && length > 4) + return ret + " (" + std::to_string(length) + ")"; return ret; } -std::string format_hex_pretty(const std::vector &data) { return format_hex_pretty(data.data(), data.size()); } -std::string format_hex_pretty(const std::string &data) { +std::string format_hex_pretty(const std::vector &data, char separator, bool show_length) { + return format_hex_pretty(data.data(), data.size(), separator, show_length); +} +std::string format_hex_pretty(const std::string &data, char separator, bool show_length) { if (data.empty()) return ""; std::string ret; - ret.resize(3 * data.length() - 1); + uint8_t multiple = separator ? 3 : 2; // 3 if separator is not \0, 2 otherwise + ret.resize(multiple * data.length() - 1); for (size_t i = 0; i < data.length(); i++) { - ret[3 * i] = format_hex_pretty_char((data[i] & 0xF0) >> 4); - ret[3 * i + 1] = format_hex_pretty_char(data[i] & 0x0F); - if (i != data.length() - 1) - ret[3 * i + 2] = '.'; + ret[multiple * i] = format_hex_pretty_char((data[i] & 0xF0) >> 4); + ret[multiple * i + 1] = format_hex_pretty_char(data[i] & 0x0F); + if (separator && i != data.length() - 1) + ret[multiple * i + 2] = separator; } - if (data.length() > 4) + if (show_length && data.length() > 4) return ret + " (" + std::to_string(data.length()) + ")"; return ret; } @@ -460,9 +367,22 @@ int8_t step_to_accuracy_decimals(float step) { return str.length() - dot_pos - 1; } -static const std::string BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; +// Use C-style string constant to store in ROM instead of RAM (saves 24 bytes) +static constexpr const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +// Helper function to find the index of a base64 character in the lookup table. +// Returns the character's position (0-63) if found, or 0 if not found. +// NOTE: This returns 0 for both 'A' (valid base64 char at index 0) and invalid characters. +// This is safe because is_base64() is ALWAYS checked before calling this function, +// preventing invalid characters from ever reaching here. The base64_decode function +// stops processing at the first invalid character due to the is_base64() check in its +// while loop condition, making this edge case harmless in practice. +static inline uint8_t base64_find_char(char c) { + const char *pos = strchr(BASE64_CHARS, c); + return pos ? (pos - BASE64_CHARS) : 0; +} static inline bool is_base64(char c) { return (isalnum(c) || (c == '+') || (c == '/')); } @@ -484,7 +404,7 @@ std::string base64_encode(const uint8_t *buf, size_t buf_len) { char_array_4[3] = char_array_3[2] & 0x3f; for (i = 0; (i < 4); i++) - ret += BASE64_CHARS[char_array_4[i]]; + ret += BASE64_CHARS[static_cast(char_array_4[i])]; i = 0; } } @@ -499,7 +419,7 @@ std::string base64_encode(const uint8_t *buf, size_t buf_len) { char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) - ret += BASE64_CHARS[char_array_4[j]]; + ret += BASE64_CHARS[static_cast(char_array_4[j])]; while ((i++ < 3)) ret += '='; @@ -526,12 +446,15 @@ std::vector base64_decode(const std::string &encoded_string) { uint8_t char_array_4[4], char_array_3[3]; std::vector ret; + // SAFETY: The loop condition checks is_base64() before processing each character. + // This ensures base64_find_char() is only called on valid base64 characters, + // preventing the edge case where invalid chars would return 0 (same as 'A'). while (in_len-- && (encoded_string[in] != '=') && is_base64(encoded_string[in])) { char_array_4[i++] = encoded_string[in]; in++; if (i == 4) { for (i = 0; i < 4; i++) - char_array_4[i] = BASE64_CHARS.find(char_array_4[i]); + char_array_4[i] = base64_find_char(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); @@ -548,7 +471,7 @@ std::vector base64_decode(const std::string &encoded_string) { char_array_4[j] = 0; for (j = 0; j < 4; j++) - char_array_4[j] = BASE64_CHARS.find(char_array_4[j]); + char_array_4[j] = base64_find_char(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); @@ -644,35 +567,6 @@ void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green blue += delta; } -// System APIs -#if defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_HOST) -// ESP8266 doesn't have mutexes, but that shouldn't be an issue as it's single-core and non-preemptive OS. -Mutex::Mutex() {} -Mutex::~Mutex() {} -void Mutex::lock() {} -bool Mutex::try_lock() { return true; } -void Mutex::unlock() {} -#elif defined(USE_ESP32) || defined(USE_LIBRETINY) -Mutex::Mutex() { handle_ = xSemaphoreCreateMutex(); } -Mutex::~Mutex() {} -void Mutex::lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); } -bool Mutex::try_lock() { return xSemaphoreTake(this->handle_, 0) == pdTRUE; } -void Mutex::unlock() { xSemaphoreGive(this->handle_); } -#endif - -#if defined(USE_ESP8266) -IRAM_ATTR InterruptLock::InterruptLock() { state_ = xt_rsil(15); } -IRAM_ATTR InterruptLock::~InterruptLock() { xt_wsr_ps(state_); } -#elif defined(USE_ESP32) || defined(USE_LIBRETINY) -// only affects the executing core -// so should not be used as a mutex lock, only to get accurate timing -IRAM_ATTR InterruptLock::InterruptLock() { portDISABLE_INTERRUPTS(); } -IRAM_ATTR InterruptLock::~InterruptLock() { portENABLE_INTERRUPTS(); } -#elif defined(USE_RP2040) -IRAM_ATTR InterruptLock::InterruptLock() { state_ = save_and_disable_interrupts(); } -IRAM_ATTR InterruptLock::~InterruptLock() { restore_interrupts(state_); } -#endif - uint8_t HighFrequencyLoopRequester::num_requests = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) void HighFrequencyLoopRequester::start() { if (this->started_) @@ -688,45 +582,6 @@ void HighFrequencyLoopRequester::stop() { } bool HighFrequencyLoopRequester::is_high_frequency() { return num_requests > 0; } -#if defined(USE_HOST) -void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter) - static const uint8_t esphome_host_mac_address[6] = USE_ESPHOME_HOST_MAC_ADDRESS; - memcpy(mac, esphome_host_mac_address, sizeof(esphome_host_mac_address)); -} -#elif defined(USE_ESP32) -void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter) -#if defined(CONFIG_SOC_IEEE802154_SUPPORTED) - // When CONFIG_SOC_IEEE802154_SUPPORTED is defined, esp_efuse_mac_get_default - // returns the 802.15.4 EUI-64 address, so we read directly from eFuse instead. - if (has_custom_mac_address()) { - esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48); - } else { - esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, 48); - } -#else - if (has_custom_mac_address()) { - esp_efuse_mac_get_custom(mac); - } else { - esp_efuse_mac_get_default(mac); - } -#endif -} -#elif defined(USE_ESP8266) -void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter) - wifi_get_macaddr(STATION_IF, mac); -} -#elif defined(USE_RP2040) -void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter) -#ifdef USE_WIFI - WiFi.macAddress(mac); -#endif -} -#elif defined(USE_LIBRETINY) -void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter) - WiFi.macAddress(mac); -} -#endif - std::string get_mac_address() { uint8_t mac[6]; get_mac_address_raw(mac); @@ -739,24 +594,10 @@ std::string get_mac_address_pretty() { return format_mac_address_pretty(mac); } -#ifdef USE_ESP32 -void set_mac_address(uint8_t *mac) { esp_base_mac_addr_set(mac); } +#ifndef USE_ESP32 +bool has_custom_mac_address() { return false; } #endif -bool has_custom_mac_address() { -#if defined(USE_ESP32) && !defined(USE_ESP32_IGNORE_EFUSE_CUSTOM_MAC) - uint8_t mac[6]; - // do not use 'esp_efuse_mac_get_custom(mac)' because it drops an error in the logs whenever it fails -#ifndef USE_ESP32_VARIANT_ESP32 - return (esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA_MAC_CUSTOM, mac, 48) == ESP_OK) && mac_address_is_valid(mac); -#else - return (esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48) == ESP_OK) && mac_address_is_valid(mac); -#endif -#else - return false; -#endif -} - bool mac_address_is_valid(const uint8_t *mac) { bool is_all_zeros = true; bool is_all_ones = true; diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 362f3d1fa4..58f162ff9d 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -32,6 +32,10 @@ #include #endif +#ifdef USE_HOST +#include +#endif + #define HOT __attribute__((hot)) #define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg))) #define ESPHOME_ALWAYS_INLINE __attribute__((always_inline)) @@ -340,20 +344,149 @@ template std::string format_hex(const std::array &dat return format_hex(data.data(), data.size()); } -/// Format the byte array \p data of length \p len in pretty-printed, human-readable hex. -std::string format_hex_pretty(const uint8_t *data, size_t length); -/// Format the word array \p data of length \p len in pretty-printed, human-readable hex. -std::string format_hex_pretty(const uint16_t *data, size_t length); -/// Format the vector \p data in pretty-printed, human-readable hex. -std::string format_hex_pretty(const std::vector &data); -/// Format the vector \p data in pretty-printed, human-readable hex. -std::string format_hex_pretty(const std::vector &data); -/// Format the string \p data in pretty-printed, human-readable hex. -std::string format_hex_pretty(const std::string &data); -/// Format an unsigned integer in pretty-printed, human-readable hex, starting with the most significant byte. -template::value, int> = 0> std::string format_hex_pretty(T val) { +/** Format a byte array in pretty-printed, human-readable hex format. + * + * Converts binary data to a hexadecimal string representation with customizable formatting. + * Each byte is displayed as a two-digit uppercase hex value, separated by the specified separator. + * Optionally includes the total byte count in parentheses at the end. + * + * @param data Pointer to the byte array to format. + * @param length Number of bytes in the array. + * @param separator Character to use between hex bytes (default: '.'). + * @param show_length Whether to append the byte count in parentheses (default: true). + * @return Formatted hex string, e.g., "A1.B2.C3.D4.E5 (5)" or "A1:B2:C3" depending on parameters. + * + * @note Returns empty string if data is nullptr or length is 0. + * @note The length will only be appended if show_length is true AND the length is greater than 4. + * + * Example: + * @code + * uint8_t data[] = {0xA1, 0xB2, 0xC3}; + * format_hex_pretty(data, 3); // Returns "A1.B2.C3" (no length shown for <= 4 parts) + * uint8_t data2[] = {0xA1, 0xB2, 0xC3, 0xD4, 0xE5}; + * format_hex_pretty(data2, 5); // Returns "A1.B2.C3.D4.E5 (5)" + * format_hex_pretty(data2, 5, ':'); // Returns "A1:B2:C3:D4:E5 (5)" + * format_hex_pretty(data2, 5, '.', false); // Returns "A1.B2.C3.D4.E5" + * @endcode + */ +std::string format_hex_pretty(const uint8_t *data, size_t length, char separator = '.', bool show_length = true); + +/** Format a 16-bit word array in pretty-printed, human-readable hex format. + * + * Similar to the byte array version, but formats 16-bit words as 4-digit hex values. + * + * @param data Pointer to the 16-bit word array to format. + * @param length Number of 16-bit words in the array. + * @param separator Character to use between hex words (default: '.'). + * @param show_length Whether to append the word count in parentheses (default: true). + * @return Formatted hex string with 4-digit hex values per word. + * + * @note The length will only be appended if show_length is true AND the length is greater than 4. + * + * Example: + * @code + * uint16_t data[] = {0xA1B2, 0xC3D4}; + * format_hex_pretty(data, 2); // Returns "A1B2.C3D4" (no length shown for <= 4 parts) + * uint16_t data2[] = {0xA1B2, 0xC3D4, 0xE5F6}; + * format_hex_pretty(data2, 3); // Returns "A1B2.C3D4.E5F6 (3)" + * @endcode + */ +std::string format_hex_pretty(const uint16_t *data, size_t length, char separator = '.', bool show_length = true); + +/** Format a byte vector in pretty-printed, human-readable hex format. + * + * Convenience overload for std::vector. Formats each byte as a two-digit + * uppercase hex value with customizable separator. + * + * @param data Vector of bytes to format. + * @param separator Character to use between hex bytes (default: '.'). + * @param show_length Whether to append the byte count in parentheses (default: true). + * @return Formatted hex string representation of the vector contents. + * + * @note The length will only be appended if show_length is true AND the vector size is greater than 4. + * + * Example: + * @code + * std::vector data = {0xDE, 0xAD, 0xBE, 0xEF}; + * format_hex_pretty(data); // Returns "DE.AD.BE.EF" (no length shown for <= 4 parts) + * std::vector data2 = {0xDE, 0xAD, 0xBE, 0xEF, 0xCA}; + * format_hex_pretty(data2); // Returns "DE.AD.BE.EF.CA (5)" + * format_hex_pretty(data2, '-'); // Returns "DE-AD-BE-EF-CA (5)" + * @endcode + */ +std::string format_hex_pretty(const std::vector &data, char separator = '.', bool show_length = true); + +/** Format a 16-bit word vector in pretty-printed, human-readable hex format. + * + * Convenience overload for std::vector. Each 16-bit word is formatted + * as a 4-digit uppercase hex value in big-endian order. + * + * @param data Vector of 16-bit words to format. + * @param separator Character to use between hex words (default: '.'). + * @param show_length Whether to append the word count in parentheses (default: true). + * @return Formatted hex string representation of the vector contents. + * + * @note The length will only be appended if show_length is true AND the vector size is greater than 4. + * + * Example: + * @code + * std::vector data = {0x1234, 0x5678}; + * format_hex_pretty(data); // Returns "1234.5678" (no length shown for <= 4 parts) + * std::vector data2 = {0x1234, 0x5678, 0x9ABC}; + * format_hex_pretty(data2); // Returns "1234.5678.9ABC (3)" + * @endcode + */ +std::string format_hex_pretty(const std::vector &data, char separator = '.', bool show_length = true); + +/** Format a string's bytes in pretty-printed, human-readable hex format. + * + * Treats each character in the string as a byte and formats it in hex. + * Useful for debugging binary data stored in std::string containers. + * + * @param data String whose bytes should be formatted as hex. + * @param separator Character to use between hex bytes (default: '.'). + * @param show_length Whether to append the byte count in parentheses (default: true). + * @return Formatted hex string representation of the string's byte contents. + * + * @note The length will only be appended if show_length is true AND the string length is greater than 4. + * + * Example: + * @code + * std::string data = "ABC"; // ASCII: 0x41, 0x42, 0x43 + * format_hex_pretty(data); // Returns "41.42.43" (no length shown for <= 4 parts) + * std::string data2 = "ABCDE"; + * format_hex_pretty(data2); // Returns "41.42.43.44.45 (5)" + * @endcode + */ +std::string format_hex_pretty(const std::string &data, char separator = '.', bool show_length = true); + +/** Format an unsigned integer in pretty-printed, human-readable hex format. + * + * Converts the integer to big-endian byte order and formats each byte as hex. + * The most significant byte appears first in the output string. + * + * @tparam T Unsigned integer type (uint8_t, uint16_t, uint32_t, uint64_t, etc.). + * @param val The unsigned integer value to format. + * @param separator Character to use between hex bytes (default: '.'). + * @param show_length Whether to append the byte count in parentheses (default: true). + * @return Formatted hex string with most significant byte first. + * + * @note The length will only be appended if show_length is true AND sizeof(T) is greater than 4. + * + * Example: + * @code + * uint32_t value = 0x12345678; + * format_hex_pretty(value); // Returns "12.34.56.78" (no length shown for <= 4 parts) + * uint64_t value2 = 0x123456789ABCDEF0; + * format_hex_pretty(value2); // Returns "12.34.56.78.9A.BC.DE.F0 (8)" + * format_hex_pretty(value2, ':'); // Returns "12:34:56:78:9A:BC:DE:F0 (8)" + * format_hex_pretty(0x1234); // Returns "12.34" + * @endcode + */ +template::value, int> = 0> +std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) { val = convert_big_endian(val); - return format_hex_pretty(reinterpret_cast(&val), sizeof(T)); + return format_hex_pretty(reinterpret_cast(&val), sizeof(T), separator, show_length); } /// Format the byte array \p data of length \p len in binary. diff --git a/esphome/core/lock_free_queue.h b/esphome/core/lock_free_queue.h index 5460be0fae..f35cfa5af9 100644 --- a/esphome/core/lock_free_queue.h +++ b/esphome/core/lock_free_queue.h @@ -31,11 +31,20 @@ namespace esphome { +// Base lock-free queue without task notification template class LockFreeQueue { public: - LockFreeQueue() : head_(0), tail_(0), dropped_count_(0), task_to_notify_(nullptr) {} + LockFreeQueue() : head_(0), tail_(0), dropped_count_(0) {} bool push(T *element) { + bool was_empty; + uint8_t old_tail; + return push_internal_(element, was_empty, old_tail); + } + + protected: + // Internal push that reports queue state - for use by derived classes + bool push_internal_(T *element, bool &was_empty, uint8_t &old_tail) { if (element == nullptr) return false; @@ -51,34 +60,16 @@ template class LockFreeQueue { return false; } - // Check if queue was empty before push - bool was_empty = (current_tail == head_before); + was_empty = (current_tail == head_before); + old_tail = current_tail; buffer_[current_tail] = element; tail_.store(next_tail, std::memory_order_release); - // Notify optimization: only notify if we need to - if (task_to_notify_ != nullptr) { - if (was_empty) { - // Queue was empty - consumer might be going to sleep, must notify - xTaskNotifyGive(task_to_notify_); - } else { - // Queue wasn't empty - check if consumer has caught up to previous tail - uint8_t head_after = head_.load(std::memory_order_acquire); - if (head_after == current_tail) { - // Consumer just caught up to where tail was - might go to sleep, must notify - // Note: There's a benign race here - between reading head_after and calling - // xTaskNotifyGive(), the consumer could advance further. This would result - // in an unnecessary wake-up, but is harmless and extremely rare in practice. - xTaskNotifyGive(task_to_notify_); - } - // Otherwise: consumer is still behind, no need to notify - } - } - return true; } + public: T *pop() { uint8_t current_head = head_.load(std::memory_order_relaxed); @@ -108,11 +99,6 @@ template class LockFreeQueue { return next_tail == head_.load(std::memory_order_acquire); } - // Set the FreeRTOS task handle to notify when items are pushed to the queue - // This enables efficient wake-up of a consumer task that's waiting for data - // @param task The FreeRTOS task handle to notify, or nullptr to disable notifications - void set_task_to_notify(TaskHandle_t task) { task_to_notify_ = task; } - protected: T *buffer_[SIZE]; // Atomic: written by producer (push/increment), read+reset by consumer (get_and_reset) @@ -123,7 +109,40 @@ template class LockFreeQueue { std::atomic head_; // Atomic: written by producer (push), read by consumer (pop) to check if empty std::atomic tail_; - // Task handle for notification (optional) +}; + +// Extended queue with task notification support +template class NotifyingLockFreeQueue : public LockFreeQueue { + public: + NotifyingLockFreeQueue() : LockFreeQueue(), task_to_notify_(nullptr) {} + + bool push(T *element) { + bool was_empty; + uint8_t old_tail; + bool result = this->push_internal_(element, was_empty, old_tail); + + // Notify optimization: only notify if we need to + if (result && task_to_notify_ != nullptr && + (was_empty || this->head_.load(std::memory_order_acquire) == old_tail)) { + // Notify in two cases: + // 1. Queue was empty - consumer might be going to sleep + // 2. Consumer just caught up to where tail was - might go to sleep + // Note: There's a benign race in case 2 - between reading head and calling + // xTaskNotifyGive(), the consumer could advance further. This would result + // in an unnecessary wake-up, but is harmless and extremely rare in practice. + xTaskNotifyGive(task_to_notify_); + } + // Otherwise: consumer is still behind, no need to notify + + return result; + } + + // Set the FreeRTOS task handle to notify when items are pushed to the queue + // This enables efficient wake-up of a consumer task that's waiting for data + // @param task The FreeRTOS task handle to notify, or nullptr to disable notifications + void set_task_to_notify(TaskHandle_t task) { task_to_notify_ = task; } + + private: TaskHandle_t task_to_notify_; }; diff --git a/esphome/core/scheduler.cpp b/esphome/core/scheduler.cpp index 5c01b4f3f4..d3da003a88 100644 --- a/esphome/core/scheduler.cpp +++ b/esphome/core/scheduler.cpp @@ -62,18 +62,16 @@ static void validate_static_string(const char *name) { void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type type, bool is_static_string, const void *name_ptr, uint32_t delay, std::function func) { // Get the name as const char* - const char *name_cstr = - is_static_string ? static_cast(name_ptr) : static_cast(name_ptr)->c_str(); + const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr); - // Cancel existing timer if name is not empty - if (name_cstr != nullptr && name_cstr[0] != '\0') { - this->cancel_item_(component, name_cstr, type); - } - - if (delay == SCHEDULER_DONT_RUN) + if (delay == SCHEDULER_DONT_RUN) { + // Still need to cancel existing timer if name is not empty + if (this->is_name_valid_(name_cstr)) { + LockGuard guard{this->lock_}; + this->cancel_item_locked_(component, name_cstr, type); + } return; - - const auto now = this->millis_(); + } // Create and populate the scheduler item auto item = make_unique(); @@ -83,6 +81,20 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type item->callback = std::move(func); item->remove = false; +#if !defined(USE_ESP8266) && !defined(USE_RP2040) + // Special handling for defer() (delay = 0, type = TIMEOUT) + // ESP8266 and RP2040 are excluded because they don't need thread-safe defer handling + if (delay == 0 && type == SchedulerItem::TIMEOUT) { + // Put in defer queue for guaranteed FIFO execution + LockGuard guard{this->lock_}; + this->cancel_item_locked_(component, name_cstr, type); + this->defer_queue_.push_back(std::move(item)); + return; + } +#endif + + const auto now = this->millis_(); + // Type-specific setup if (type == SchedulerItem::INTERVAL) { item->interval = delay; @@ -111,7 +123,15 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type } #endif - this->push_(std::move(item)); + LockGuard guard{this->lock_}; + // If name is provided, do atomic cancel-and-add + if (this->is_name_valid_(name_cstr)) { + // Cancel existing items + this->cancel_item_locked_(component, name_cstr, type); + } + // Add new item directly to to_add_ + // since we have the lock held + this->to_add_.push_back(std::move(item)); } void HOT Scheduler::set_timeout(Component *component, const char *name, uint32_t timeout, std::function func) { @@ -123,10 +143,10 @@ void HOT Scheduler::set_timeout(Component *component, const std::string &name, u this->set_timer_common_(component, SchedulerItem::TIMEOUT, false, &name, timeout, std::move(func)); } bool HOT Scheduler::cancel_timeout(Component *component, const std::string &name) { - return this->cancel_item_(component, name, SchedulerItem::TIMEOUT); + return this->cancel_item_(component, false, &name, SchedulerItem::TIMEOUT); } bool HOT Scheduler::cancel_timeout(Component *component, const char *name) { - return this->cancel_item_(component, name, SchedulerItem::TIMEOUT); + return this->cancel_item_(component, true, name, SchedulerItem::TIMEOUT); } void HOT Scheduler::set_interval(Component *component, const std::string &name, uint32_t interval, std::function func) { @@ -138,10 +158,10 @@ void HOT Scheduler::set_interval(Component *component, const char *name, uint32_ this->set_timer_common_(component, SchedulerItem::INTERVAL, true, name, interval, std::move(func)); } bool HOT Scheduler::cancel_interval(Component *component, const std::string &name) { - return this->cancel_item_(component, name, SchedulerItem::INTERVAL); + return this->cancel_item_(component, false, &name, SchedulerItem::INTERVAL); } bool HOT Scheduler::cancel_interval(Component *component, const char *name) { - return this->cancel_item_(component, name, SchedulerItem::INTERVAL); + return this->cancel_item_(component, true, name, SchedulerItem::INTERVAL); } struct RetryArgs { @@ -200,6 +220,9 @@ bool HOT Scheduler::cancel_retry(Component *component, const std::string &name) } optional HOT Scheduler::next_schedule_in() { + // IMPORTANT: This method should only be called from the main thread (loop task). + // It calls empty_() and accesses items_[0] without holding a lock, which is only + // safe when called from the main thread. Other threads must not call this method. if (this->empty_()) return {}; auto &item = this->items_[0]; @@ -209,6 +232,39 @@ optional HOT Scheduler::next_schedule_in() { return item->next_execution_ - now; } void HOT Scheduler::call() { +#if !defined(USE_ESP8266) && !defined(USE_RP2040) + // Process defer queue first to guarantee FIFO execution order for deferred items. + // Previously, defer() used the heap which gave undefined order for equal timestamps, + // causing race conditions on multi-core systems (ESP32, BK7200). + // With the defer queue: + // - Deferred items (delay=0) go directly to defer_queue_ in set_timer_common_ + // - Items execute in exact order they were deferred (FIFO guarantee) + // - No deferred items exist in to_add_, so processing order doesn't affect correctness + // ESP8266 and RP2040 don't use this queue - they fall back to the heap-based approach + // (ESP8266: single-core, RP2040: empty mutex implementation). + // + // Note: Items cancelled via cancel_item_locked_() are marked with remove=true but still + // processed here. They are removed from the queue normally via pop_front() but skipped + // during execution by should_skip_item_(). This is intentional - no memory leak occurs. + while (!this->defer_queue_.empty()) { + // The outer check is done without a lock for performance. If the queue + // appears non-empty, we lock and process an item. We don't need to check + // empty() again inside the lock because only this thread can remove items. + std::unique_ptr item; + { + LockGuard lock(this->lock_); + item = std::move(this->defer_queue_.front()); + this->defer_queue_.pop_front(); + } + + // Execute callback without holding lock to prevent deadlocks + // if the callback tries to call defer() again + if (!this->should_skip_item_(item.get())) { + this->execute_item_(item.get()); + } + } +#endif + const auto now = this->millis_(); this->process_to_add(); @@ -221,10 +277,12 @@ void HOT Scheduler::call() { ESP_LOGD(TAG, "Items: count=%zu, now=%" PRIu64 " (%u, %" PRIu32 ")", this->items_.size(), now, this->millis_major_, this->last_millis_); while (!this->empty_()) { - this->lock_.lock(); - auto item = std::move(this->items_[0]); - this->pop_raw_(); - this->lock_.unlock(); + std::unique_ptr item; + { + LockGuard guard{this->lock_}; + item = std::move(this->items_[0]); + this->pop_raw_(); + } const char *name = item->get_name(); ESP_LOGD(TAG, " %s '%s/%s' interval=%" PRIu32 " next_execution in %" PRIu64 "ms at %" PRIu64, @@ -238,33 +296,35 @@ void HOT Scheduler::call() { { LockGuard guard{this->lock_}; this->items_ = std::move(old_items); + // Rebuild heap after moving items back + std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp); } } #endif // ESPHOME_DEBUG_SCHEDULER - auto to_remove_was = to_remove_; - auto items_was = this->items_.size(); // If we have too many items to remove - if (to_remove_ > MAX_LOGICALLY_DELETED_ITEMS) { + if (this->to_remove_ > MAX_LOGICALLY_DELETED_ITEMS) { + // We hold the lock for the entire cleanup operation because: + // 1. We're rebuilding the entire items_ list, so we need exclusive access throughout + // 2. Other threads must see either the old state or the new state, not intermediate states + // 3. The operation is already expensive (O(n)), so lock overhead is negligible + // 4. No operations inside can block or take other locks, so no deadlock risk + LockGuard guard{this->lock_}; + std::vector> valid_items; - while (!this->empty_()) { - LockGuard guard{this->lock_}; - auto item = std::move(this->items_[0]); - this->pop_raw_(); - valid_items.push_back(std::move(item)); + + // Move all non-removed items to valid_items + for (auto &item : this->items_) { + if (!item->remove) { + valid_items.push_back(std::move(item)); + } } - { - LockGuard guard{this->lock_}; - this->items_ = std::move(valid_items); - } - - // The following should not happen unless I'm missing something - if (to_remove_ != 0) { - ESP_LOGW(TAG, "to_remove_ was %" PRIu32 " now: %" PRIu32 " items where %zu now %zu. Please report this", - to_remove_was, to_remove_, items_was, items_.size()); - to_remove_ = 0; - } + // Replace items_ with the filtered list + this->items_ = std::move(valid_items); + // Rebuild the heap structure since items are no longer in heap order + std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp); + this->to_remove_ = 0; } while (!this->empty_()) { @@ -282,8 +342,6 @@ void HOT Scheduler::call() { this->pop_raw_(); continue; } - App.set_current_component(item->component); - #ifdef ESPHOME_DEBUG_SCHEDULER const char *item_name = item->get_name(); ESP_LOGV(TAG, "Running %s '%s/%s' with interval=%" PRIu32 " next_execution=%" PRIu64 " (now=%" PRIu64 ")", @@ -294,36 +352,29 @@ void HOT Scheduler::call() { // Warning: During callback(), a lot of stuff can happen, including: // - timeouts/intervals get added, potentially invalidating vector pointers // - timeouts/intervals get cancelled - { - uint32_t now_ms = millis(); - WarnIfComponentBlockingGuard guard{item->component, now_ms}; - item->callback(); - // Call finish to ensure blocking time is properly calculated and reported - guard.finish(); - } + this->execute_item_(item.get()); } { - this->lock_.lock(); + LockGuard guard{this->lock_}; // new scope, item from before might have been moved in the vector auto item = std::move(this->items_[0]); - // Only pop after function call, this ensures we were reachable // during the function call and know if we were cancelled. this->pop_raw_(); - this->lock_.unlock(); - if (item->remove) { // We were removed/cancelled in the function call, stop - to_remove_--; + this->to_remove_--; continue; } if (item->type == SchedulerItem::INTERVAL) { item->next_execution_ = now + item->interval; - this->push_(std::move(item)); + // Add new item directly to to_add_ + // since we have the lock held + this->to_add_.push_back(std::move(item)); } } } @@ -343,68 +394,99 @@ void HOT Scheduler::process_to_add() { this->to_add_.clear(); } void HOT Scheduler::cleanup_() { + // Fast path: if nothing to remove, just return + // Reading to_remove_ without lock is safe because: + // 1. We only call this from the main thread during call() + // 2. If it's 0, there's definitely nothing to cleanup + // 3. If it becomes non-zero after we check, cleanup will happen on the next loop iteration + // 4. Not all platforms support atomics, so we accept this race in favor of performance + // 5. The worst case is a one-loop-iteration delay in cleanup, which is harmless + if (this->to_remove_ == 0) + return; + + // We must hold the lock for the entire cleanup operation because: + // 1. We're modifying items_ (via pop_raw_) which requires exclusive access + // 2. We're decrementing to_remove_ which is also modified by other threads + // (though all modifications are already under lock) + // 3. Other threads read items_ when searching for items to cancel in cancel_item_locked_() + // 4. We need a consistent view of items_ and to_remove_ throughout the operation + // Without the lock, we could access items_ while another thread is reading it, + // leading to race conditions + LockGuard guard{this->lock_}; while (!this->items_.empty()) { auto &item = this->items_[0]; if (!item->remove) return; - - to_remove_--; - - { - LockGuard guard{this->lock_}; - this->pop_raw_(); - } + this->to_remove_--; + this->pop_raw_(); } } void HOT Scheduler::pop_raw_() { std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp); this->items_.pop_back(); } -void HOT Scheduler::push_(std::unique_ptr item) { - LockGuard guard{this->lock_}; - this->to_add_.push_back(std::move(item)); + +// Helper to execute a scheduler item +void HOT Scheduler::execute_item_(SchedulerItem *item) { + App.set_current_component(item->component); + + uint32_t now_ms = millis(); + WarnIfComponentBlockingGuard guard{item->component, now_ms}; + item->callback(); + guard.finish(); } + // Common implementation for cancel operations -bool HOT Scheduler::cancel_item_common_(Component *component, bool is_static_string, const void *name_ptr, - SchedulerItem::Type type) { +bool HOT Scheduler::cancel_item_(Component *component, bool is_static_string, const void *name_ptr, + SchedulerItem::Type type) { // Get the name as const char* - const char *name_cstr = - is_static_string ? static_cast(name_ptr) : static_cast(name_ptr)->c_str(); + const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr); // Handle null or empty names - if (name_cstr == nullptr) + if (!this->is_name_valid_(name_cstr)) return false; // obtain lock because this function iterates and can be called from non-loop task context LockGuard guard{this->lock_}; - bool ret = false; + return this->cancel_item_locked_(component, name_cstr, type); +} - for (auto &it : this->items_) { - const char *item_name = it->get_name(); - if (it->component == component && item_name != nullptr && strcmp(name_cstr, item_name) == 0 && it->type == type && - !it->remove) { - to_remove_++; - it->remove = true; - ret = true; +// Helper to cancel items by name - must be called with lock held +bool HOT Scheduler::cancel_item_locked_(Component *component, const char *name_cstr, SchedulerItem::Type type) { + size_t total_cancelled = 0; + + // Check all containers for matching items +#if !defined(USE_ESP8266) && !defined(USE_RP2040) + // Only check defer queue for timeouts (intervals never go there) + if (type == SchedulerItem::TIMEOUT) { + for (auto &item : this->defer_queue_) { + if (this->matches_item_(item, component, name_cstr, type)) { + item->remove = true; + total_cancelled++; + } } } - for (auto &it : this->to_add_) { - const char *item_name = it->get_name(); - if (it->component == component && item_name != nullptr && strcmp(name_cstr, item_name) == 0 && it->type == type) { - it->remove = true; - ret = true; +#endif + + // Cancel items in the main heap + for (auto &item : this->items_) { + if (this->matches_item_(item, component, name_cstr, type)) { + item->remove = true; + total_cancelled++; + this->to_remove_++; // Track removals for heap items } } - return ret; -} + // Cancel items in to_add_ + for (auto &item : this->to_add_) { + if (this->matches_item_(item, component, name_cstr, type)) { + item->remove = true; + total_cancelled++; + // Don't track removals for to_add_ items + } + } -bool HOT Scheduler::cancel_item_(Component *component, const std::string &name, Scheduler::SchedulerItem::Type type) { - return this->cancel_item_common_(component, false, &name, type); -} - -bool HOT Scheduler::cancel_item_(Component *component, const char *name, SchedulerItem::Type type) { - return this->cancel_item_common_(component, true, name, type); + return total_cancelled > 0; } uint64_t Scheduler::millis_() { diff --git a/esphome/core/scheduler.h b/esphome/core/scheduler.h index a64968932e..084ff699c5 100644 --- a/esphome/core/scheduler.h +++ b/esphome/core/scheduler.h @@ -2,6 +2,8 @@ #include #include +#include +#include #include "esphome/core/component.h" #include "esphome/core/helpers.h" @@ -97,9 +99,9 @@ class Scheduler { SchedulerItem(const SchedulerItem &) = delete; SchedulerItem &operator=(const SchedulerItem &) = delete; - // Default move operations - SchedulerItem(SchedulerItem &&) = default; - SchedulerItem &operator=(SchedulerItem &&) = default; + // Delete move operations: SchedulerItem objects are only managed via unique_ptr, never moved directly + SchedulerItem(SchedulerItem &&) = delete; + SchedulerItem &operator=(SchedulerItem &&) = delete; // Helper to get the name regardless of storage type const char *get_name() const { return name_is_dynamic ? name_.dynamic_name : name_.static_name; } @@ -138,13 +140,57 @@ class Scheduler { uint64_t millis_(); void cleanup_(); void pop_raw_(); - void push_(std::unique_ptr item); + + private: + // Helper to cancel items by name - must be called with lock held + bool cancel_item_locked_(Component *component, const char *name, SchedulerItem::Type type); + + // Helper to extract name as const char* from either static string or std::string + inline const char *get_name_cstr_(bool is_static_string, const void *name_ptr) { + return is_static_string ? static_cast(name_ptr) : static_cast(name_ptr)->c_str(); + } + + // Helper to check if a name is valid (not null and not empty) + inline bool is_name_valid_(const char *name) { return name != nullptr && name[0] != '\0'; } + // Common implementation for cancel operations - bool cancel_item_common_(Component *component, bool is_static_string, const void *name_ptr, SchedulerItem::Type type); + bool cancel_item_(Component *component, bool is_static_string, const void *name_ptr, SchedulerItem::Type type); - bool cancel_item_(Component *component, const std::string &name, SchedulerItem::Type type); - bool cancel_item_(Component *component, const char *name, SchedulerItem::Type type); + // Helper function to check if item matches criteria for cancellation + inline bool HOT matches_item_(const std::unique_ptr &item, Component *component, const char *name_cstr, + SchedulerItem::Type type) { + if (item->component != component || item->type != type || item->remove) { + return false; + } + const char *item_name = item->get_name(); + if (item_name == nullptr) { + return false; + } + // Fast path: if pointers are equal + // This is effective because the core ESPHome codebase uses static strings (const char*) + // for component names. The std::string overloads exist only for compatibility with + // external components, but are rarely used in practice. + if (item_name == name_cstr) { + return true; + } + // Slow path: compare string contents + return strcmp(name_cstr, item_name) == 0; + } + // Helper to execute a scheduler item + void execute_item_(SchedulerItem *item); + + // Helper to check if item should be skipped + bool should_skip_item_(const SchedulerItem *item) const { + return item->remove || (item->component != nullptr && item->component->is_failed()); + } + + // Check if the scheduler has no items. + // IMPORTANT: This method should only be called from the main thread (loop task). + // It performs cleanup of removed items and checks if the queue is empty. + // The items_.empty() check at the end is done without a lock for performance, + // which is safe because this is only called from the main thread while other + // threads only add items (never remove them). bool empty_() { this->cleanup_(); return this->items_.empty(); @@ -153,6 +199,13 @@ class Scheduler { Mutex lock_; std::vector> items_; std::vector> to_add_; +#if !defined(USE_ESP8266) && !defined(USE_RP2040) + // ESP8266 and RP2040 don't need the defer queue because: + // ESP8266: Single-core with no preemptive multitasking + // RP2040: Currently has empty mutex implementation in ESPHome + // Both platforms save 40 bytes of RAM by excluding this + std::deque> defer_queue_; // FIFO queue for defer() calls +#endif uint32_t last_millis_{0}; uint16_t millis_major_{0}; uint32_t to_remove_{0}; diff --git a/esphome/core/time.cpp b/esphome/core/time.cpp index 672f5b98bf..f9652b5329 100644 --- a/esphome/core/time.cpp +++ b/esphome/core/time.cpp @@ -226,11 +226,11 @@ int32_t ESPTime::timezone_offset() { return offset; } -bool ESPTime::operator<(ESPTime other) { return this->timestamp < other.timestamp; } -bool ESPTime::operator<=(ESPTime other) { return this->timestamp <= other.timestamp; } -bool ESPTime::operator==(ESPTime other) { return this->timestamp == other.timestamp; } -bool ESPTime::operator>=(ESPTime other) { return this->timestamp >= other.timestamp; } -bool ESPTime::operator>(ESPTime other) { return this->timestamp > other.timestamp; } +bool ESPTime::operator<(const ESPTime &other) const { return this->timestamp < other.timestamp; } +bool ESPTime::operator<=(const ESPTime &other) const { return this->timestamp <= other.timestamp; } +bool ESPTime::operator==(const ESPTime &other) const { return this->timestamp == other.timestamp; } +bool ESPTime::operator>=(const ESPTime &other) const { return this->timestamp >= other.timestamp; } +bool ESPTime::operator>(const ESPTime &other) const { return this->timestamp > other.timestamp; } template bool increment_time_value(T ¤t, uint16_t begin, uint16_t end) { current++; diff --git a/esphome/core/time.h b/esphome/core/time.h index 5cbd9369fb..a53fca2346 100644 --- a/esphome/core/time.h +++ b/esphome/core/time.h @@ -109,10 +109,10 @@ struct ESPTime { void increment_second(); /// Increment this clock instance by one day. void increment_day(); - bool operator<(ESPTime other); - bool operator<=(ESPTime other); - bool operator==(ESPTime other); - bool operator>=(ESPTime other); - bool operator>(ESPTime other); + bool operator<(const ESPTime &other) const; + bool operator<=(const ESPTime &other) const; + bool operator==(const ESPTime &other) const; + bool operator>=(const ESPTime &other) const; + bool operator>(const ESPTime &other) const; }; } // namespace esphome diff --git a/esphome/dashboard/entries.py b/esphome/dashboard/entries.py index e4825298f7..b138cfd272 100644 --- a/esphome/dashboard/entries.py +++ b/esphome/dashboard/entries.py @@ -9,6 +9,7 @@ import os from typing import TYPE_CHECKING, Any from esphome import const, util +from esphome.enum import StrEnum from esphome.storage_json import StorageJSON, ext_storage_path from .const import ( @@ -18,7 +19,6 @@ from .const import ( EVENT_ENTRY_STATE_CHANGED, EVENT_ENTRY_UPDATED, ) -from .enum import StrEnum from .util.subprocess import async_run_system_command if TYPE_CHECKING: diff --git a/esphome/dashboard/enum.py b/esphome/enum.py similarity index 100% rename from esphome/dashboard/enum.py rename to esphome/enum.py diff --git a/esphome/loader.py b/esphome/loader.py index 79a1d7f576..7b2472521a 100644 --- a/esphome/loader.py +++ b/esphome/loader.py @@ -112,8 +112,17 @@ class ComponentManifest: This will return all cpp source files that are located in the same folder as the loaded .py file (does not look through subdirectories) """ - ret = [] + ret: list[FileResource] = [] + # Get filter function for source files + filter_source_files_func = getattr(self.module, "FILTER_SOURCE_FILES", None) + + # Get list of files to exclude + excluded_files = ( + set(filter_source_files_func()) if filter_source_files_func else set() + ) + + # Process all resources for resource in ( r.name for r in importlib.resources.files(self.package).iterdir() @@ -124,6 +133,11 @@ class ComponentManifest: if not importlib.resources.files(self.package).joinpath(resource).is_file(): # Not a resource = this is a directory (yeah this is confusing) continue + + # Skip excluded files + if resource in excluded_files: + continue + ret.append(FileResource(self.package, resource)) return ret diff --git a/requirements.txt b/requirements.txt index 1010a311d6..a6bcebaeea 100644 --- a/requirements.txt +++ b/requirements.txt @@ -13,9 +13,9 @@ platformio==6.1.18 # When updating platformio, also update /docker/Dockerfile esptool==4.9.0 click==8.1.7 esphome-dashboard==20250514.0 -aioesphomeapi==34.0.0 +aioesphomeapi==34.1.0 zeroconf==0.147.0 -puremagic==1.29 +puremagic==1.30 ruamel.yaml==0.18.14 # dashboard_import esphome-glyphsets==0.2.0 pillow==10.4.0 diff --git a/requirements_test.txt b/requirements_test.txt index 66b71c2225..ef1fc4f2d6 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -1,6 +1,6 @@ pylint==3.3.7 flake8==7.3.0 # also change in .pre-commit-config.yaml when updating -ruff==0.12.1 # also change in .pre-commit-config.yaml when updating +ruff==0.12.2 # also change in .pre-commit-config.yaml when updating pyupgrade==3.20.0 # also change in .pre-commit-config.yaml when updating pre-commit diff --git a/script/api_protobuf/api_protobuf.py b/script/api_protobuf/api_protobuf.py index 56a46a7701..df1f3f8caa 100755 --- a/script/api_protobuf/api_protobuf.py +++ b/script/api_protobuf/api_protobuf.py @@ -290,7 +290,7 @@ class DoubleType(TypeInfo): wire_type = WireType.FIXED64 # Uses wire type 1 according to protobuf spec def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%g", {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%g", {name});\n' o += "out.append(buffer);" return o @@ -312,7 +312,7 @@ class FloatType(TypeInfo): wire_type = WireType.FIXED32 # Uses wire type 5 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%g", {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%g", {name});\n' o += "out.append(buffer);" return o @@ -334,7 +334,7 @@ class Int64Type(TypeInfo): wire_type = WireType.VARINT # Uses wire type 0 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%lld", {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%lld", {name});\n' o += "out.append(buffer);" return o @@ -356,7 +356,7 @@ class UInt64Type(TypeInfo): wire_type = WireType.VARINT # Uses wire type 0 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%llu", {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%llu", {name});\n' o += "out.append(buffer);" return o @@ -378,7 +378,7 @@ class Int32Type(TypeInfo): wire_type = WireType.VARINT # Uses wire type 0 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%" PRId32, {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%" PRId32, {name});\n' o += "out.append(buffer);" return o @@ -400,7 +400,7 @@ class Fixed64Type(TypeInfo): wire_type = WireType.FIXED64 # Uses wire type 1 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%llu", {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%llu", {name});\n' o += "out.append(buffer);" return o @@ -422,7 +422,7 @@ class Fixed32Type(TypeInfo): wire_type = WireType.FIXED32 # Uses wire type 5 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%" PRIu32, {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%" PRIu32, {name});\n' o += "out.append(buffer);" return o @@ -555,7 +555,7 @@ class UInt32Type(TypeInfo): wire_type = WireType.VARINT # Uses wire type 0 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%" PRIu32, {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%" PRIu32, {name});\n' o += "out.append(buffer);" return o @@ -607,7 +607,7 @@ class SFixed32Type(TypeInfo): wire_type = WireType.FIXED32 # Uses wire type 5 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%" PRId32, {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%" PRId32, {name});\n' o += "out.append(buffer);" return o @@ -629,7 +629,7 @@ class SFixed64Type(TypeInfo): wire_type = WireType.FIXED64 # Uses wire type 1 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%lld", {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%lld", {name});\n' o += "out.append(buffer);" return o @@ -651,7 +651,7 @@ class SInt32Type(TypeInfo): wire_type = WireType.VARINT # Uses wire type 0 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%" PRId32, {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%" PRId32, {name});\n' o += "out.append(buffer);" return o @@ -673,7 +673,7 @@ class SInt64Type(TypeInfo): wire_type = WireType.VARINT # Uses wire type 0 def dump(self, name: str) -> str: - o = f'sprintf(buffer, "%lld", {name});\n' + o = f'snprintf(buffer, sizeof(buffer), "%lld", {name});\n' o += "out.append(buffer);" return o @@ -813,27 +813,137 @@ class RepeatedTypeInfo(TypeInfo): return underlying_size * 2 -def build_enum_type(desc) -> tuple[str, str]: - """Builds the enum type.""" +def build_type_usage_map( + file_desc: descriptor.FileDescriptorProto, +) -> tuple[dict[str, str | None], dict[str, str | None]]: + """Build mappings for both enums and messages to their ifdefs based on usage. + + Returns: + tuple: (enum_ifdef_map, message_ifdef_map) + """ + enum_ifdef_map: dict[str, str | None] = {} + message_ifdef_map: dict[str, str | None] = {} + + # Build maps of which types are used by which messages + enum_usage: dict[ + str, set[str] + ] = {} # enum_name -> set of message names that use it + message_usage: dict[ + str, set[str] + ] = {} # message_name -> set of message names that use it + + # Build message name to ifdef mapping for quick lookup + message_to_ifdef: dict[str, str | None] = { + msg.name: get_opt(msg, pb.ifdef) for msg in file_desc.message_type + } + + # Analyze field usage + for message in file_desc.message_type: + for field in message.field: + type_name = field.type_name.split(".")[-1] if field.type_name else None + if not type_name: + continue + + # Track enum usage + if field.type == 14: # TYPE_ENUM + enum_usage.setdefault(type_name, set()).add(message.name) + # Track message usage + elif field.type == 11: # TYPE_MESSAGE + message_usage.setdefault(type_name, set()).add(message.name) + + # Helper to get unique ifdef from a set of messages + def get_unique_ifdef(message_names: set[str]) -> str | None: + ifdefs: set[str] = { + message_to_ifdef[name] + for name in message_names + if message_to_ifdef.get(name) + } + return ifdefs.pop() if len(ifdefs) == 1 else None + + # Build enum ifdef map + for enum in file_desc.enum_type: + if enum.name in enum_usage: + enum_ifdef_map[enum.name] = get_unique_ifdef(enum_usage[enum.name]) + else: + enum_ifdef_map[enum.name] = None + + # Build message ifdef map + for message in file_desc.message_type: + # Explicit ifdef takes precedence + explicit_ifdef = message_to_ifdef.get(message.name) + if explicit_ifdef: + message_ifdef_map[message.name] = explicit_ifdef + elif message.name in message_usage: + # Inherit ifdef if all parent messages have the same one + message_ifdef_map[message.name] = get_unique_ifdef( + message_usage[message.name] + ) + else: + message_ifdef_map[message.name] = None + + # Second pass: propagate ifdefs recursively + # Keep iterating until no more changes are made + changed = True + iterations = 0 + while changed and iterations < 10: # Add safety limit + changed = False + iterations += 1 + for message in file_desc.message_type: + # Skip if already has an ifdef + if message_ifdef_map.get(message.name): + continue + + # Check if this message is used by other messages + if message.name not in message_usage: + continue + + # Get ifdefs from all messages that use this one + parent_ifdefs: set[str] = { + message_ifdef_map.get(parent) + for parent in message_usage[message.name] + if message_ifdef_map.get(parent) + } + + # If all parents have the same ifdef, inherit it + if len(parent_ifdefs) == 1 and None not in parent_ifdefs: + message_ifdef_map[message.name] = parent_ifdefs.pop() + changed = True + + return enum_ifdef_map, message_ifdef_map + + +def build_enum_type(desc, enum_ifdef_map) -> tuple[str, str, str]: + """Builds the enum type. + + Args: + desc: The enum descriptor + enum_ifdef_map: Mapping of enum names to their ifdefs + + Returns: + tuple: (header_content, cpp_content, dump_cpp_content) + """ name = desc.name + out = f"enum {name} : uint32_t {{\n" for v in desc.value: out += f" {v.name} = {v.number},\n" out += "};\n" - cpp = "#ifdef HAS_PROTO_MESSAGE_DUMP\n" - cpp += f"template<> const char *proto_enum_to_string(enums::{name} value) {{\n" - cpp += " switch (value) {\n" - for v in desc.value: - cpp += f" case enums::{v.name}:\n" - cpp += f' return "{v.name}";\n' - cpp += " default:\n" - cpp += ' return "UNKNOWN";\n' - cpp += " }\n" - cpp += "}\n" - cpp += "#endif\n" + # Regular cpp file has no enum content anymore + cpp = "" - return out, cpp + # Dump cpp content for enum string conversion + dump_cpp = f"template<> const char *proto_enum_to_string(enums::{name} value) {{\n" + dump_cpp += " switch (value) {\n" + for v in desc.value: + dump_cpp += f" case enums::{v.name}:\n" + dump_cpp += f' return "{v.name}";\n' + dump_cpp += " default:\n" + dump_cpp += ' return "UNKNOWN";\n' + dump_cpp += " }\n" + dump_cpp += "}\n" + + return out, cpp, dump_cpp def calculate_message_estimated_size(desc: descriptor.DescriptorProto) -> int: @@ -855,7 +965,7 @@ def calculate_message_estimated_size(desc: descriptor.DescriptorProto) -> int: def build_message_type( desc: descriptor.DescriptorProto, base_class_fields: dict[str, list[descriptor.FieldDescriptorProto]] = None, -) -> tuple[str, str]: +) -> tuple[str, str, str]: public_content: list[str] = [] protected_content: list[str] = [] decode_varint: list[str] = [] @@ -886,7 +996,7 @@ def build_message_type( f"static constexpr uint16_t ESTIMATED_SIZE = {estimated_size};" ) - # Add message_name method for debugging + # Add message_name method inline in header public_content.append("#ifdef HAS_PROTO_MESSAGE_DUMP") snake_name = camel_to_snake(desc.name) public_content.append( @@ -993,32 +1103,32 @@ def build_message_type( public_content.append(prot) # If no fields to calculate size for, the default implementation in ProtoMessage will be used - o = f"void {desc.name}::dump_to(std::string &out) const {{" - if dump: - if len(dump) == 1 and len(dump[0]) + len(o) + 3 < 120: - o += f" {dump[0]} " - else: - o += "\n" - o += " __attribute__((unused)) char buffer[64];\n" - o += f' out.append("{desc.name} {{\\n");\n' - o += indent("\n".join(dump)) + "\n" - o += ' out.append("}");\n' - else: - o2 = f'out.append("{desc.name} {{}}");' - if len(o) + len(o2) + 3 < 120: - o += f" {o2} " - else: - o += "\n" - o += f" {o2}\n" - o += "}\n" - cpp += "#ifdef HAS_PROTO_MESSAGE_DUMP\n" - cpp += o - cpp += "#endif\n" + # dump_to method declaration in header prot = "#ifdef HAS_PROTO_MESSAGE_DUMP\n" prot += "void dump_to(std::string &out) const override;\n" prot += "#endif\n" public_content.append(prot) + # dump_to implementation will go in dump_cpp + dump_impl = f"void {desc.name}::dump_to(std::string &out) const {{" + if dump: + if len(dump) == 1 and len(dump[0]) + len(dump_impl) + 3 < 120: + dump_impl += f" {dump[0]} " + else: + dump_impl += "\n" + dump_impl += " __attribute__((unused)) char buffer[64];\n" + dump_impl += f' out.append("{desc.name} {{\\n");\n' + dump_impl += indent("\n".join(dump)) + "\n" + dump_impl += ' out.append("}");\n' + else: + o2 = f'out.append("{desc.name} {{}}");' + if len(dump_impl) + len(o2) + 3 < 120: + dump_impl += f" {o2} " + else: + dump_impl += "\n" + dump_impl += f" {o2}\n" + dump_impl += "}\n" + if base_class: out = f"class {desc.name} : public {base_class} {{\n" else: @@ -1031,7 +1141,11 @@ def build_message_type( if len(protected_content) > 0: out += "\n" out += "};\n" - return out, cpp + + # Build dump_cpp content with dump_to implementation + dump_cpp = dump_impl + + return out, cpp, dump_cpp SOURCE_BOTH = 0 @@ -1119,7 +1233,7 @@ def find_common_fields( def build_base_class( base_class_name: str, common_fields: list[descriptor.FieldDescriptorProto], -) -> tuple[str, str]: +) -> tuple[str, str, str]: """Build the base class definition and implementation.""" public_content = [] protected_content = [] @@ -1156,16 +1270,18 @@ def build_base_class( out += "};\n" # No implementation needed for base classes + dump_cpp = "" - return out, cpp + return out, cpp, dump_cpp def generate_base_classes( base_class_groups: dict[str, list[descriptor.DescriptorProto]], -) -> tuple[str, str]: +) -> tuple[str, str, str]: """Generate all base classes.""" all_headers = [] all_cpp = [] + all_dump_cpp = [] for base_class_name, messages in base_class_groups.items(): # Find common fields @@ -1173,11 +1289,12 @@ def generate_base_classes( if common_fields: # Generate base class - header, cpp = build_base_class(base_class_name, common_fields) + header, cpp, dump_cpp = build_base_class(base_class_name, common_fields) all_headers.append(header) all_cpp.append(cpp) + all_dump_cpp.append(dump_cpp) - return "\n".join(all_headers), "\n".join(all_cpp) + return "\n".join(all_headers), "\n".join(all_cpp), "\n".join(all_dump_cpp) def build_service_message_type( @@ -1244,15 +1361,17 @@ def main() -> None: file = d.file[0] content = FILE_HEADER content += """\ - #pragma once +#pragma once - #include "proto.h" - #include "api_pb2_size.h" +#include "esphome/core/defines.h" - namespace esphome { - namespace api { +#include "proto.h" +#include "api_pb2_size.h" - """ +namespace esphome { +namespace api { + +""" cpp = FILE_HEADER cpp += """\ @@ -1261,19 +1380,56 @@ def main() -> None: #include "esphome/core/log.h" #include "esphome/core/helpers.h" - #include +namespace esphome { +namespace api { - namespace esphome { - namespace api { +""" - """ + # Initialize dump cpp content + dump_cpp = FILE_HEADER + dump_cpp += """\ +#include "api_pb2.h" +#include "esphome/core/helpers.h" + +#include + +#ifdef HAS_PROTO_MESSAGE_DUMP + +namespace esphome { +namespace api { + +""" content += "namespace enums {\n\n" + # Build dynamic ifdef mappings for both enums and messages + enum_ifdef_map, message_ifdef_map = build_type_usage_map(file) + + # Simple grouping of enums by ifdef + current_ifdef = None + for enum in file.enum_type: - s, c = build_enum_type(enum) + s, c, dc = build_enum_type(enum, enum_ifdef_map) + enum_ifdef = enum_ifdef_map.get(enum.name) + + # Handle ifdef changes + if enum_ifdef != current_ifdef: + if current_ifdef is not None: + content += "#endif\n" + dump_cpp += "#endif\n" + if enum_ifdef is not None: + content += f"#ifdef {enum_ifdef}\n" + dump_cpp += f"#ifdef {enum_ifdef}\n" + current_ifdef = enum_ifdef + content += s cpp += c + dump_cpp += dc + + # Close last ifdef + if current_ifdef is not None: + content += "#endif\n" + dump_cpp += "#endif\n" content += "\n} // namespace enums\n\n" @@ -1291,26 +1447,61 @@ def main() -> None: # Generate base classes if base_class_fields: - base_headers, base_cpp = generate_base_classes(base_class_groups) + base_headers, base_cpp, base_dump_cpp = generate_base_classes(base_class_groups) content += base_headers cpp += base_cpp + dump_cpp += base_dump_cpp # Generate message types with base class information + # Simple grouping by ifdef + current_ifdef = None + for m in mt: - s, c = build_message_type(m, base_class_fields) + s, c, dc = build_message_type(m, base_class_fields) + msg_ifdef = message_ifdef_map.get(m.name) + + # Handle ifdef changes + if msg_ifdef != current_ifdef: + if current_ifdef is not None: + content += "#endif\n" + if cpp: + cpp += "#endif\n" + if dump_cpp: + dump_cpp += "#endif\n" + if msg_ifdef is not None: + content += f"#ifdef {msg_ifdef}\n" + cpp += f"#ifdef {msg_ifdef}\n" + dump_cpp += f"#ifdef {msg_ifdef}\n" + current_ifdef = msg_ifdef + content += s cpp += c + dump_cpp += dc + + # Close last ifdef + if current_ifdef is not None: + content += "#endif\n" + cpp += "#endif\n" + dump_cpp += "#endif\n" content += """\ - } // namespace api - } // namespace esphome - """ +} // namespace api +} // namespace esphome +""" cpp += """\ - } // namespace api - } // namespace esphome - """ +} // namespace api +} // namespace esphome +""" + + dump_cpp += """\ + +} // namespace api +} // namespace esphome + +#endif // HAS_PROTO_MESSAGE_DUMP +""" with open(root / "api_pb2.h", "w", encoding="utf-8") as f: f.write(content) @@ -1318,29 +1509,33 @@ def main() -> None: with open(root / "api_pb2.cpp", "w", encoding="utf-8") as f: f.write(cpp) + with open(root / "api_pb2_dump.cpp", "w", encoding="utf-8") as f: + f.write(dump_cpp) + hpp = FILE_HEADER hpp += """\ - #pragma once +#pragma once - #include "api_pb2.h" - #include "esphome/core/defines.h" +#include "esphome/core/defines.h" - namespace esphome { - namespace api { +#include "api_pb2.h" - """ +namespace esphome { +namespace api { + +""" cpp = FILE_HEADER cpp += """\ - #include "api_pb2_service.h" - #include "esphome/core/log.h" +#include "api_pb2_service.h" +#include "esphome/core/log.h" - namespace esphome { - namespace api { +namespace esphome { +namespace api { - static const char *const TAG = "api.service"; +static const char *const TAG = "api.service"; - """ +""" class_name = "APIServerConnectionBase" @@ -1419,7 +1614,7 @@ def main() -> None: needs_conn = get_opt(m, pb.needs_setup_connection, True) needs_auth = get_opt(m, pb.needs_authentication, True) - ifdef = ifdefs.get(inp, None) + ifdef = message_ifdef_map.get(inp, ifdefs.get(inp, None)) if ifdef is not None: hpp += f"#ifdef {ifdef}\n" @@ -1476,14 +1671,14 @@ def main() -> None: hpp += """\ - } // namespace api - } // namespace esphome - """ +} // namespace api +} // namespace esphome +""" cpp += """\ - } // namespace api - } // namespace esphome - """ +} // namespace api +} // namespace esphome +""" with open(root / "api_pb2_service.h", "w", encoding="utf-8") as f: f.write(hpp) @@ -1506,6 +1701,8 @@ def main() -> None: exec_clang_format(root / "api_pb2_service.cpp") exec_clang_format(root / "api_pb2.h") exec_clang_format(root / "api_pb2.cpp") + exec_clang_format(root / "api_pb2_dump.h") + exec_clang_format(root / "api_pb2_dump.cpp") except ImportError: pass diff --git a/script/ci-custom.py b/script/ci-custom.py index fbabbc1e74..d0b518251f 100755 --- a/script/ci-custom.py +++ b/script/ci-custom.py @@ -559,6 +559,12 @@ def lint_relative_py_import(fname): "esphome/components/libretiny/core.cpp", "esphome/components/host/core.cpp", "esphome/components/zephyr/core.cpp", + "esphome/components/esp32/helpers.cpp", + "esphome/components/esp8266/helpers.cpp", + "esphome/components/rp2040/helpers.cpp", + "esphome/components/libretiny/helpers.cpp", + "esphome/components/host/helpers.cpp", + "esphome/components/zephyr/helpers.cpp", "esphome/components/http_request/httplib.h", ], ) diff --git a/tests/components/camera/common.yaml b/tests/components/camera/common.yaml new file mode 100644 index 0000000000..3daf1e8565 --- /dev/null +++ b/tests/components/camera/common.yaml @@ -0,0 +1,18 @@ +esphome: + includes: + - ../../../esphome/components/camera/ + +script: + - id: interface_compile_check + then: + - lambda: |- + using namespace esphome::camera; + class MockCamera : public Camera { + public: + void add_image_callback(std::function)> &&callback) override {} + CameraImageReader *create_image_reader() override { return 0; } + void request_image(CameraRequester requester) override {} + void start_stream(CameraRequester requester) override {} + void stop_stream(CameraRequester requester) override {} + }; + MockCamera* camera = new MockCamera(); diff --git a/tests/components/camera/test.esp32-ard.yaml b/tests/components/camera/test.esp32-ard.yaml new file mode 100644 index 0000000000..dade44d145 --- /dev/null +++ b/tests/components/camera/test.esp32-ard.yaml @@ -0,0 +1 @@ +<<: !include common.yaml diff --git a/tests/components/camera/test.esp32-idf.yaml b/tests/components/camera/test.esp32-idf.yaml new file mode 100644 index 0000000000..dade44d145 --- /dev/null +++ b/tests/components/camera/test.esp32-idf.yaml @@ -0,0 +1 @@ +<<: !include common.yaml diff --git a/tests/components/ds2484/common.yaml b/tests/components/ds2484/common.yaml new file mode 100644 index 0000000000..9d2882a3c0 --- /dev/null +++ b/tests/components/ds2484/common.yaml @@ -0,0 +1,11 @@ +i2c: + - id: i2c_ds2484 + scl: ${scl_pin} + sda: ${sda_pin} + +one_wire: + platform: ds2484 + i2c_id: i2c_ds2484 + address: 0x18 + active_pullup: true + strong_pullup: false diff --git a/tests/components/ds2484/test.esp32-ard.yaml b/tests/components/ds2484/test.esp32-ard.yaml new file mode 100644 index 0000000000..63c3bd6afd --- /dev/null +++ b/tests/components/ds2484/test.esp32-ard.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO16 + sda_pin: GPIO17 + +<<: !include common.yaml diff --git a/tests/components/ds2484/test.esp32-c3-ard.yaml b/tests/components/ds2484/test.esp32-c3-ard.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ds2484/test.esp32-c3-ard.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ds2484/test.esp32-c3-idf.yaml b/tests/components/ds2484/test.esp32-c3-idf.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ds2484/test.esp32-c3-idf.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ds2484/test.esp32-idf.yaml b/tests/components/ds2484/test.esp32-idf.yaml new file mode 100644 index 0000000000..63c3bd6afd --- /dev/null +++ b/tests/components/ds2484/test.esp32-idf.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO16 + sda_pin: GPIO17 + +<<: !include common.yaml diff --git a/tests/components/ds2484/test.esp8266-ard.yaml b/tests/components/ds2484/test.esp8266-ard.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ds2484/test.esp8266-ard.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ds2484/test.rp2040-ard.yaml b/tests/components/ds2484/test.rp2040-ard.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ds2484/test.rp2040-ard.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/http_request/common.yaml b/tests/components/http_request/common.yaml index af4852901f..97961007e2 100644 --- a/tests/components/http_request/common.yaml +++ b/tests/components/http_request/common.yaml @@ -91,3 +91,5 @@ update: name: OTA Update id: ota_update source: http://my.ha.net:8123/local/esphome/manifest.json + on_update_available: + - logger.log: "A new update is available" diff --git a/tests/components/inkplate6/common.yaml b/tests/components/inkplate6/common.yaml index 31b14e6c73..6cb5d055b6 100644 --- a/tests/components/inkplate6/common.yaml +++ b/tests/components/inkplate6/common.yaml @@ -3,6 +3,9 @@ i2c: scl: 16 sda: 17 +esp32: + cpu_frequency: 240MHz + display: - platform: inkplate6 id: inkplate_display diff --git a/tests/components/packages/test.esp32-ard.yaml b/tests/components/packages/test.esp32-ard.yaml index d882116c10..7d0ab2b905 100644 --- a/tests/components/packages/test.esp32-ard.yaml +++ b/tests/components/packages/test.esp32-ard.yaml @@ -5,7 +5,8 @@ packages: - !include package.yaml - github://esphome/esphome/tests/components/template/common.yaml@dev - url: https://github.com/esphome/esphome - file: tests/components/absolute_humidity/common.yaml + path: tests/components/absolute_humidity + file: common.yaml ref: dev refresh: 1d diff --git a/tests/components/packages/test.esp32-idf.yaml b/tests/components/packages/test.esp32-idf.yaml index 720a5777c2..8c0a34bb1a 100644 --- a/tests/components/packages/test.esp32-idf.yaml +++ b/tests/components/packages/test.esp32-idf.yaml @@ -7,7 +7,8 @@ packages: shorthand: github://esphome/esphome/tests/components/template/common.yaml@dev github: url: https://github.com/esphome/esphome - file: tests/components/absolute_humidity/common.yaml + path: tests/components/absolute_humidity + file: common.yaml ref: dev refresh: 1d diff --git a/tests/components/packet_transport/common.yaml b/tests/components/packet_transport/common.yaml index cbb34c4572..9151cf27dc 100644 --- a/tests/components/packet_transport/common.yaml +++ b/tests/components/packet_transport/common.yaml @@ -36,5 +36,9 @@ binary_sensor: - platform: packet_transport provider: unencrypted-device id: other_binary_sensor_id + - platform: packet_transport + provider: some-device-name + type: status + name: Some-Device Status - platform: template id: binary_sensor_id1 diff --git a/tests/components/sx126x/common.yaml b/tests/components/sx126x/common.yaml new file mode 100644 index 0000000000..3f888c3ce4 --- /dev/null +++ b/tests/components/sx126x/common.yaml @@ -0,0 +1,40 @@ +spi: + clk_pin: ${clk_pin} + mosi_pin: ${mosi_pin} + miso_pin: ${miso_pin} + +sx126x: + dio1_pin: ${dio1_pin} + cs_pin: ${cs_pin} + busy_pin: ${busy_pin} + rst_pin: ${rst_pin} + pa_power: 3 + bandwidth: 125_0kHz + crc_enable: true + frequency: 433920000 + modulation: LORA + rx_start: true + hw_version: sx1262 + rf_switch: true + sync_value: [0x14, 0x24] + preamble_size: 8 + spreading_factor: 7 + coding_rate: CR_4_6 + tcxo_voltage: 1_8V + tcxo_delay: 5ms + on_packet: + then: + - lambda: |- + ESP_LOGD("lambda", "packet %.2f %.2f %s", rssi, snr, format_hex(x).c_str()); + +button: + - platform: template + name: "SX126x Button" + on_press: + then: + - sx126x.set_mode_standby + - sx126x.run_image_cal + - sx126x.set_mode_sleep + - sx126x.set_mode_rx + - sx126x.send_packet: + data: [0xC5, 0x51, 0x78, 0x82, 0xB7, 0xF9, 0x9C, 0x5C] diff --git a/tests/components/sx126x/test.esp32-ard.yaml b/tests/components/sx126x/test.esp32-ard.yaml new file mode 100644 index 0000000000..9770f52229 --- /dev/null +++ b/tests/components/sx126x/test.esp32-ard.yaml @@ -0,0 +1,10 @@ +substitutions: + clk_pin: GPIO5 + mosi_pin: GPIO27 + miso_pin: GPIO19 + cs_pin: GPIO18 + rst_pin: GPIO23 + busy_pin: GPIO25 + dio1_pin: GPIO26 + +<<: !include common.yaml diff --git a/tests/components/sx126x/test.esp32-c3-ard.yaml b/tests/components/sx126x/test.esp32-c3-ard.yaml new file mode 100644 index 0000000000..91450e24ce --- /dev/null +++ b/tests/components/sx126x/test.esp32-c3-ard.yaml @@ -0,0 +1,10 @@ +substitutions: + clk_pin: GPIO5 + mosi_pin: GPIO18 + miso_pin: GPIO19 + cs_pin: GPIO1 + rst_pin: GPIO2 + busy_pin: GPIO4 + dio1_pin: GPIO3 + +<<: !include common.yaml diff --git a/tests/components/sx126x/test.esp32-c3-idf.yaml b/tests/components/sx126x/test.esp32-c3-idf.yaml new file mode 100644 index 0000000000..91450e24ce --- /dev/null +++ b/tests/components/sx126x/test.esp32-c3-idf.yaml @@ -0,0 +1,10 @@ +substitutions: + clk_pin: GPIO5 + mosi_pin: GPIO18 + miso_pin: GPIO19 + cs_pin: GPIO1 + rst_pin: GPIO2 + busy_pin: GPIO4 + dio1_pin: GPIO3 + +<<: !include common.yaml diff --git a/tests/components/sx126x/test.esp32-idf.yaml b/tests/components/sx126x/test.esp32-idf.yaml new file mode 100644 index 0000000000..9770f52229 --- /dev/null +++ b/tests/components/sx126x/test.esp32-idf.yaml @@ -0,0 +1,10 @@ +substitutions: + clk_pin: GPIO5 + mosi_pin: GPIO27 + miso_pin: GPIO19 + cs_pin: GPIO18 + rst_pin: GPIO23 + busy_pin: GPIO25 + dio1_pin: GPIO26 + +<<: !include common.yaml diff --git a/tests/components/sx126x/test.esp8266-ard.yaml b/tests/components/sx126x/test.esp8266-ard.yaml new file mode 100644 index 0000000000..d2c07c5bb7 --- /dev/null +++ b/tests/components/sx126x/test.esp8266-ard.yaml @@ -0,0 +1,10 @@ +substitutions: + clk_pin: GPIO5 + mosi_pin: GPIO13 + miso_pin: GPIO12 + cs_pin: GPIO1 + rst_pin: GPIO2 + busy_pin: GPIO4 + dio1_pin: GPIO3 + +<<: !include common.yaml diff --git a/tests/components/sx126x/test.rp2040-ard.yaml b/tests/components/sx126x/test.rp2040-ard.yaml new file mode 100644 index 0000000000..8881e96971 --- /dev/null +++ b/tests/components/sx126x/test.rp2040-ard.yaml @@ -0,0 +1,10 @@ +substitutions: + clk_pin: GPIO2 + mosi_pin: GPIO3 + miso_pin: GPIO4 + cs_pin: GPIO5 + rst_pin: GPIO6 + busy_pin: GPIO8 + dio1_pin: GPIO7 + +<<: !include common.yaml diff --git a/tests/components/sx127x/common.yaml b/tests/components/sx127x/common.yaml new file mode 100644 index 0000000000..63adc2e91c --- /dev/null +++ b/tests/components/sx127x/common.yaml @@ -0,0 +1,45 @@ +spi: + clk_pin: ${clk_pin} + mosi_pin: ${mosi_pin} + miso_pin: ${miso_pin} + +sx127x: + cs_pin: ${cs_pin} + rst_pin: ${rst_pin} + dio0_pin: ${dio0_pin} + pa_pin: BOOST + pa_power: 17 + pa_ramp: 40us + bitsync: true + bitrate: 4800 + bandwidth: 50_0kHz + frequency: 433920000 + modulation: FSK + deviation: 5000 + rx_start: true + rx_floor: -90 + packet_mode: true + payload_length: 8 + sync_value: [0x33, 0x33] + shaping: NONE + preamble_size: 2 + preamble_detect: 2 + preamble_errors: 8 + preamble_polarity: 0x55 + on_packet: + then: + - sx127x.send_packet: + data: [0xC5, 0x51, 0x78, 0x82, 0xB7, 0xF9, 0x9C, 0x5C] + +button: + - platform: template + name: "SX127x Button" + on_press: + then: + - sx127x.set_mode_standby + - sx127x.run_image_cal + - sx127x.set_mode_tx + - sx127x.set_mode_sleep + - sx127x.set_mode_rx + - sx127x.send_packet: + data: [0xC5, 0x51, 0x78, 0x82, 0xB7, 0xF9, 0x9C, 0x5C] diff --git a/tests/components/sx127x/test.esp32-ard.yaml b/tests/components/sx127x/test.esp32-ard.yaml new file mode 100644 index 0000000000..71270462a2 --- /dev/null +++ b/tests/components/sx127x/test.esp32-ard.yaml @@ -0,0 +1,9 @@ +substitutions: + clk_pin: GPIO5 + mosi_pin: GPIO27 + miso_pin: GPIO19 + cs_pin: GPIO18 + rst_pin: GPIO23 + dio0_pin: GPIO26 + +<<: !include common.yaml diff --git a/tests/components/sx127x/test.esp32-c3-ard.yaml b/tests/components/sx127x/test.esp32-c3-ard.yaml new file mode 100644 index 0000000000..36535a950d --- /dev/null +++ b/tests/components/sx127x/test.esp32-c3-ard.yaml @@ -0,0 +1,9 @@ +substitutions: + clk_pin: GPIO5 + mosi_pin: GPIO18 + miso_pin: GPIO19 + cs_pin: GPIO1 + rst_pin: GPIO2 + dio0_pin: GPIO3 + +<<: !include common.yaml diff --git a/tests/components/sx127x/test.esp32-c3-idf.yaml b/tests/components/sx127x/test.esp32-c3-idf.yaml new file mode 100644 index 0000000000..36535a950d --- /dev/null +++ b/tests/components/sx127x/test.esp32-c3-idf.yaml @@ -0,0 +1,9 @@ +substitutions: + clk_pin: GPIO5 + mosi_pin: GPIO18 + miso_pin: GPIO19 + cs_pin: GPIO1 + rst_pin: GPIO2 + dio0_pin: GPIO3 + +<<: !include common.yaml diff --git a/tests/components/sx127x/test.esp32-idf.yaml b/tests/components/sx127x/test.esp32-idf.yaml new file mode 100644 index 0000000000..71270462a2 --- /dev/null +++ b/tests/components/sx127x/test.esp32-idf.yaml @@ -0,0 +1,9 @@ +substitutions: + clk_pin: GPIO5 + mosi_pin: GPIO27 + miso_pin: GPIO19 + cs_pin: GPIO18 + rst_pin: GPIO23 + dio0_pin: GPIO26 + +<<: !include common.yaml diff --git a/tests/components/sx127x/test.esp8266-ard.yaml b/tests/components/sx127x/test.esp8266-ard.yaml new file mode 100644 index 0000000000..64c01edd44 --- /dev/null +++ b/tests/components/sx127x/test.esp8266-ard.yaml @@ -0,0 +1,9 @@ +substitutions: + clk_pin: GPIO5 + mosi_pin: GPIO13 + miso_pin: GPIO12 + cs_pin: GPIO1 + rst_pin: GPIO2 + dio0_pin: GPIO3 + +<<: !include common.yaml diff --git a/tests/components/sx127x/test.rp2040-ard.yaml b/tests/components/sx127x/test.rp2040-ard.yaml new file mode 100644 index 0000000000..0af7b29790 --- /dev/null +++ b/tests/components/sx127x/test.rp2040-ard.yaml @@ -0,0 +1,9 @@ +substitutions: + clk_pin: GPIO2 + mosi_pin: GPIO3 + miso_pin: GPIO4 + cs_pin: GPIO5 + rst_pin: GPIO6 + dio0_pin: GPIO7 + +<<: !include common.yaml diff --git a/tests/components/update/common.yaml b/tests/components/update/common.yaml index dcb4f42527..45ed110352 100644 --- a/tests/components/update/common.yaml +++ b/tests/components/update/common.yaml @@ -26,3 +26,5 @@ update: - platform: http_request name: Firmware Update source: http://example.com/manifest.json + on_update_available: + - logger.log: "A new update is available" diff --git a/tests/integration/README.md b/tests/integration/README.md index 26bd5a00ee..8fce81bb80 100644 --- a/tests/integration/README.md +++ b/tests/integration/README.md @@ -78,3 +78,268 @@ pytest -s tests/integration/test_host_mode_basic.py - Each test gets its own temporary directory and unique port - Port allocation minimizes race conditions by holding the socket until just before ESPHome starts - Output from ESPHome processes is displayed for debugging + +## Integration Test Writing Guide + +### Test Patterns and Best Practices + +#### 1. Test File Naming Convention +- Use descriptive names: `test_{category}_{feature}.py` +- Common categories: `host_mode`, `api`, `scheduler`, `light`, `areas_and_devices` +- Examples: + - `test_host_mode_basic.py` - Basic host mode functionality + - `test_api_message_batching.py` - API message batching + - `test_scheduler_stress.py` - Scheduler stress testing + +#### 2. Essential Imports +```python +from __future__ import annotations + +import asyncio +from typing import Any + +import pytest +from aioesphomeapi import EntityState, SensorState + +from .types import APIClientConnectedFactory, RunCompiledFunction +``` + +#### 3. Common Test Patterns + +##### Basic Entity Test +```python +@pytest.mark.asyncio +async def test_my_sensor( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test sensor functionality.""" + async with run_compiled(yaml_config), api_client_connected() as client: + # Get entity list + entities, services = await client.list_entities_services() + + # Find specific entity + sensor = next((e for e in entities if e.object_id == "my_sensor"), None) + assert sensor is not None +``` + +##### State Subscription Pattern +```python +# Track state changes with futures +loop = asyncio.get_running_loop() +states: dict[int, EntityState] = {} +state_future: asyncio.Future[EntityState] = loop.create_future() + +def on_state(state: EntityState) -> None: + states[state.key] = state + # Check for specific condition using isinstance + if isinstance(state, SensorState) and state.state == expected_value: + if not state_future.done(): + state_future.set_result(state) + +client.subscribe_states(on_state) + +# Wait for state with timeout +try: + result = await asyncio.wait_for(state_future, timeout=5.0) +except asyncio.TimeoutError: + pytest.fail(f"Expected state not received. Got: {list(states.values())}") +``` + +##### Service Execution Pattern +```python +# Find and execute service +entities, services = await client.list_entities_services() +my_service = next((s for s in services if s.name == "my_service"), None) +assert my_service is not None + +# Execute with parameters +client.execute_service(my_service, {"param1": "value1", "param2": 42}) +``` + +##### Multiple Entity Tracking +```python +# For tests with many entities +loop = asyncio.get_running_loop() +entity_count = 50 +received_states: set[int] = set() +all_states_future: asyncio.Future[bool] = loop.create_future() + +def on_state(state: EntityState) -> None: + received_states.add(state.key) + if len(received_states) >= entity_count and not all_states_future.done(): + all_states_future.set_result(True) + +client.subscribe_states(on_state) +await asyncio.wait_for(all_states_future, timeout=10.0) +``` + +#### 4. YAML Fixture Guidelines + +##### Naming Convention +- Match test function name: `test_my_feature` → `fixtures/my_feature.yaml` +- Note: Remove `test_` prefix for fixture filename + +##### Basic Structure +```yaml +esphome: + name: test-name # Use kebab-case + # Optional: areas, devices, platformio_options + +host: # Always use host platform for integration tests +api: # Port injected automatically +logger: + level: DEBUG # Optional: Set log level + +# Component configurations +sensor: + - platform: template + name: "My Sensor" + id: my_sensor + lambda: return 42.0; + update_interval: 0.1s # Fast updates for testing +``` + +##### Advanced Features +```yaml +# External components for custom test code +external_components: + - source: + type: local + path: EXTERNAL_COMPONENT_PATH # Replaced by test framework + components: [my_test_component] + +# Areas and devices +esphome: + name: test-device + areas: + - id: living_room + name: "Living Room" + - id: kitchen + name: "Kitchen" + parent_id: living_room + devices: + - id: my_device + name: "Test Device" + area_id: living_room + +# API services +api: + services: + - service: test_service + variables: + my_param: string + then: + - logger.log: + format: "Service called with: %s" + args: [my_param.c_str()] +``` + +#### 5. Testing Complex Scenarios + +##### External Components +Create C++ components in `fixtures/external_components/` for: +- Stress testing +- Custom entity behaviors +- Scheduler testing +- Memory management tests + +##### Log Line Monitoring +```python +log_lines: list[str] = [] + +def on_log_line(line: str) -> None: + log_lines.append(line) + if "expected message" in line: + # Handle specific log messages + +async with run_compiled(yaml_config, line_callback=on_log_line): + # Test implementation +``` + +Example using futures for specific log patterns: +```python +import re + +loop = asyncio.get_running_loop() +connected_future = loop.create_future() +service_future = loop.create_future() + +# Patterns to match +connected_pattern = re.compile(r"Client .* connected from") +service_pattern = re.compile(r"Service called") + +def check_output(line: str) -> None: + """Check log output for expected messages.""" + if not connected_future.done() and connected_pattern.search(line): + connected_future.set_result(True) + elif not service_future.done() and service_pattern.search(line): + service_future.set_result(True) + +async with run_compiled(yaml_config, line_callback=check_output): + async with api_client_connected() as client: + # Wait for specific log message + await asyncio.wait_for(connected_future, timeout=5.0) + + # Do test actions... + + # Wait for service log + await asyncio.wait_for(service_future, timeout=5.0) +``` + +**Note**: Tests that monitor log messages typically have fewer race conditions compared to state-based testing, making them more reliable. However, be aware that the host platform currently does not have a thread-safe logger, so logging from threads will not work correctly. + +##### Timeout Handling +```python +# Always use timeouts for async operations +try: + result = await asyncio.wait_for(some_future, timeout=5.0) +except asyncio.TimeoutError: + pytest.fail("Operation timed out - check test expectations") +``` + +#### 6. Common Assertions + +```python +# Device info +assert device_info.name == "expected-name" +assert device_info.compilation_time is not None + +# Entity properties +assert sensor.accuracy_decimals == 2 +assert sensor.state_class == 1 # measurement +assert sensor.force_update is True + +# Service availability +assert len(services) > 0 +assert any(s.name == "expected_service" for s in services) + +# State values +assert state.state == expected_value +assert state.missing_state is False +``` + +#### 7. Debugging Tips + +- Use `pytest -s` to see ESPHome output during tests +- Add descriptive failure messages to assertions +- Use `pytest.fail()` with detailed error info for timeouts +- Check `log_lines` for compilation or runtime errors +- Enable debug logging in YAML fixtures when needed + +#### 8. Performance Considerations + +- Use short update intervals (0.1s) for faster tests +- Set reasonable timeouts (5-10s for most operations) +- Batch multiple assertions when possible +- Clean up resources properly using context managers + +#### 9. Test Categories + +- **Basic Tests**: Minimal functionality verification +- **Entity Tests**: Sensor, switch, light behavior +- **API Tests**: Message batching, services, events +- **Scheduler Tests**: Timing, defer operations, stress +- **Memory Tests**: Conditional compilation, optimization +- **Integration Tests**: Areas, devices, complex interactions diff --git a/tests/integration/fixtures/api_conditional_memory.yaml b/tests/integration/fixtures/api_conditional_memory.yaml index 4bbba5084b..22e8ed79d6 100644 --- a/tests/integration/fixtures/api_conditional_memory.yaml +++ b/tests/integration/fixtures/api_conditional_memory.yaml @@ -6,9 +6,6 @@ api: - action: test_simple_service then: - logger.log: "Simple service called" - - binary_sensor.template.publish: - id: service_called_sensor - state: ON - action: test_service_with_args variables: arg_string: string @@ -19,53 +16,14 @@ api: - logger.log: format: "Service called with: %s, %d, %d, %.2f" args: [arg_string.c_str(), arg_int, arg_bool, arg_float] - - sensor.template.publish: - id: service_arg_sensor - state: !lambda 'return arg_float;' on_client_connected: - logger.log: format: "Client %s connected from %s" args: [client_info.c_str(), client_address.c_str()] - - binary_sensor.template.publish: - id: client_connected - state: ON - - text_sensor.template.publish: - id: last_client_info - state: !lambda 'return client_info;' on_client_disconnected: - logger.log: format: "Client %s disconnected from %s" args: [client_info.c_str(), client_address.c_str()] - - binary_sensor.template.publish: - id: client_connected - state: OFF - - binary_sensor.template.publish: - id: client_disconnected_event - state: ON logger: level: DEBUG - -binary_sensor: - - platform: template - name: "Client Connected" - id: client_connected - device_class: connectivity - - platform: template - name: "Client Disconnected Event" - id: client_disconnected_event - - platform: template - name: "Service Called" - id: service_called_sensor - -sensor: - - platform: template - name: "Service Argument Value" - id: service_arg_sensor - unit_of_measurement: "" - accuracy_decimals: 2 - -text_sensor: - - platform: template - name: "Last Client Info" - id: last_client_info diff --git a/tests/integration/fixtures/batch_delay_zero_rapid_transitions.yaml b/tests/integration/fixtures/batch_delay_zero_rapid_transitions.yaml new file mode 100644 index 0000000000..32cacfaa79 --- /dev/null +++ b/tests/integration/fixtures/batch_delay_zero_rapid_transitions.yaml @@ -0,0 +1,43 @@ +esphome: + name: rapid-transitions-test +host: +api: + batch_delay: 0ms # Enable immediate sending for rapid transitions +logger: + level: DEBUG + +# Add a sensor that updates frequently to trigger lambda evaluations +sensor: + - platform: template + name: "Update Trigger" + id: update_trigger + lambda: |- + return 0; + update_interval: 10ms + internal: true + +# Simulate an IR remote binary sensor with rapid ON/OFF transitions +binary_sensor: + - platform: template + name: "Simulated IR Remote Button" + id: ir_remote_button + lambda: |- + // Simulate rapid button presses every ~100ms + // Each "press" is ON for ~30ms then OFF + uint32_t now = millis(); + uint32_t press_cycle = now % 100; // 100ms cycle + + // ON for first 30ms of each cycle + if (press_cycle < 30) { + // Only log state change + if (!id(ir_remote_button).state) { + ESP_LOGD("test", "Button ON at %u", now); + } + return true; + } else { + // Only log state change + if (id(ir_remote_button).state) { + ESP_LOGD("test", "Button OFF at %u", now); + } + return false; + } diff --git a/tests/integration/fixtures/device_id_in_state.yaml b/tests/integration/fixtures/device_id_in_state.yaml new file mode 100644 index 0000000000..f2e320a2e2 --- /dev/null +++ b/tests/integration/fixtures/device_id_in_state.yaml @@ -0,0 +1,85 @@ +esphome: + name: device-id-state-test + # Define areas + areas: + - id: living_room + name: Living Room + - id: bedroom + name: Bedroom + # Define devices + devices: + - id: temperature_monitor + name: Temperature Monitor + area_id: living_room + - id: humidity_monitor + name: Humidity Monitor + area_id: bedroom + - id: motion_sensor + name: Motion Sensor + area_id: living_room + +host: +api: +logger: + +# Test different entity types with device assignments +sensor: + - platform: template + name: Temperature + device_id: temperature_monitor + lambda: return 25.5; + update_interval: 0.1s + unit_of_measurement: "°C" + + - platform: template + name: Humidity + device_id: humidity_monitor + lambda: return 65.0; + update_interval: 0.1s + unit_of_measurement: "%" + + # Test entity without device_id (should have device_id 0) + - platform: template + name: No Device Sensor + lambda: return 100.0; + update_interval: 0.1s + +binary_sensor: + - platform: template + name: Motion Detected + device_id: motion_sensor + lambda: return true; + +switch: + - platform: template + name: Temperature Monitor Power + device_id: temperature_monitor + lambda: return true; + turn_on_action: + - lambda: |- + ESP_LOGD("test", "Turning on"); + turn_off_action: + - lambda: |- + ESP_LOGD("test", "Turning off"); + +text_sensor: + - platform: template + name: Temperature Status + device_id: temperature_monitor + lambda: return {"Normal"}; + update_interval: 0.1s + +light: + - platform: binary + name: Motion Light + device_id: motion_sensor + output: motion_light_output + +output: + - platform: template + id: motion_light_output + type: binary + write_action: + - lambda: |- + ESP_LOGD("test", "Light output: %d", state); + diff --git a/tests/integration/fixtures/entity_icon.yaml b/tests/integration/fixtures/entity_icon.yaml new file mode 100644 index 0000000000..2ce633fe2c --- /dev/null +++ b/tests/integration/fixtures/entity_icon.yaml @@ -0,0 +1,78 @@ +esphome: + name: icon-test + +host: + +api: + +logger: + +# Test entities with custom icons +sensor: + - platform: template + name: "Sensor With Icon" + icon: "mdi:temperature-celsius" + unit_of_measurement: "°C" + update_interval: 1s + lambda: |- + return 25.5; + + - platform: template + name: "Sensor Without Icon" + unit_of_measurement: "%" + update_interval: 1s + lambda: |- + return 50.0; + +binary_sensor: + - platform: template + name: "Binary Sensor With Icon" + icon: "mdi:motion-sensor" + lambda: |- + return true; + + - platform: template + name: "Binary Sensor Without Icon" + lambda: |- + return false; + +text_sensor: + - platform: template + name: "Text Sensor With Icon" + icon: "mdi:text-box" + lambda: |- + return {"Hello Icons"}; + +switch: + - platform: template + name: "Switch With Icon" + icon: "mdi:toggle-switch" + optimistic: true + +button: + - platform: template + name: "Button With Icon" + icon: "mdi:gesture-tap-button" + on_press: + - logger.log: "Button with icon pressed" + +number: + - platform: template + name: "Number With Icon" + icon: "mdi:numeric" + initial_value: 42 + min_value: 0 + max_value: 100 + step: 1 + optimistic: true + +select: + - platform: template + name: "Select With Icon" + icon: "mdi:format-list-bulleted" + options: + - "Option A" + - "Option B" + - "Option C" + initial_option: "Option A" + optimistic: true diff --git a/tests/integration/fixtures/external_components/defer_stress_component/__init__.py b/tests/integration/fixtures/external_components/defer_stress_component/__init__.py new file mode 100644 index 0000000000..177e595f51 --- /dev/null +++ b/tests/integration/fixtures/external_components/defer_stress_component/__init__.py @@ -0,0 +1,19 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.const import CONF_ID + +defer_stress_component_ns = cg.esphome_ns.namespace("defer_stress_component") +DeferStressComponent = defer_stress_component_ns.class_( + "DeferStressComponent", cg.Component +) + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(DeferStressComponent), + } +).extend(cv.COMPONENT_SCHEMA) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) diff --git a/tests/integration/fixtures/external_components/defer_stress_component/defer_stress_component.cpp b/tests/integration/fixtures/external_components/defer_stress_component/defer_stress_component.cpp new file mode 100644 index 0000000000..21ca45947e --- /dev/null +++ b/tests/integration/fixtures/external_components/defer_stress_component/defer_stress_component.cpp @@ -0,0 +1,75 @@ +#include "defer_stress_component.h" +#include "esphome/core/log.h" +#include +#include +#include +#include + +namespace esphome { +namespace defer_stress_component { + +static const char *const TAG = "defer_stress"; + +void DeferStressComponent::setup() { ESP_LOGCONFIG(TAG, "DeferStressComponent setup"); } + +void DeferStressComponent::run_multi_thread_test() { + // Use member variables instead of static to avoid issues + this->total_defers_ = 0; + this->executed_defers_ = 0; + static constexpr int NUM_THREADS = 10; + static constexpr int DEFERS_PER_THREAD = 100; + + ESP_LOGI(TAG, "Starting defer stress test - multi-threaded concurrent defers"); + + // Ensure we're starting clean + ESP_LOGI(TAG, "Initial counters: total=%d, executed=%d", this->total_defers_.load(), this->executed_defers_.load()); + + // Track start time + auto start_time = std::chrono::steady_clock::now(); + + // Create threads + std::vector threads; + + ESP_LOGI(TAG, "Creating %d threads, each will defer %d callbacks", NUM_THREADS, DEFERS_PER_THREAD); + + threads.reserve(NUM_THREADS); + for (int i = 0; i < NUM_THREADS; i++) { + threads.emplace_back([this, i]() { + ESP_LOGV(TAG, "Thread %d starting", i); + // Each thread directly calls defer() without any locking + for (int j = 0; j < DEFERS_PER_THREAD; j++) { + int defer_id = this->total_defers_.fetch_add(1); + ESP_LOGV(TAG, "Thread %d calling defer for request %d", i, defer_id); + + // Capture this pointer safely for the lambda + auto *component = this; + + // Directly call defer() from this thread - no locking! + this->defer([component, i, j, defer_id]() { + component->executed_defers_.fetch_add(1); + ESP_LOGV(TAG, "Executed defer %d (thread %d, index %d)", defer_id, i, j); + }); + + ESP_LOGV(TAG, "Thread %d called defer for request %d successfully", i, defer_id); + + // Small random delay to increase contention + if (j % 10 == 0) { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + } + } + ESP_LOGV(TAG, "Thread %d finished", i); + }); + } + + // Wait for all threads to complete + for (auto &t : threads) { + t.join(); + } + + auto end_time = std::chrono::steady_clock::now(); + auto thread_time = std::chrono::duration_cast(end_time - start_time).count(); + ESP_LOGI(TAG, "All threads finished in %lldms. Created %d defer requests", thread_time, this->total_defers_.load()); +} + +} // namespace defer_stress_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/defer_stress_component/defer_stress_component.h b/tests/integration/fixtures/external_components/defer_stress_component/defer_stress_component.h new file mode 100644 index 0000000000..59b7565726 --- /dev/null +++ b/tests/integration/fixtures/external_components/defer_stress_component/defer_stress_component.h @@ -0,0 +1,20 @@ +#pragma once + +#include "esphome/core/component.h" +#include + +namespace esphome { +namespace defer_stress_component { + +class DeferStressComponent : public Component { + public: + void setup() override; + void run_multi_thread_test(); + + private: + std::atomic total_defers_{0}; + std::atomic executed_defers_{0}; +}; + +} // namespace defer_stress_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_bulk_cleanup_component/__init__.py b/tests/integration/fixtures/external_components/scheduler_bulk_cleanup_component/__init__.py new file mode 100644 index 0000000000..f32ca5f4b7 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_bulk_cleanup_component/__init__.py @@ -0,0 +1,21 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.const import CONF_ID + +scheduler_bulk_cleanup_component_ns = cg.esphome_ns.namespace( + "scheduler_bulk_cleanup_component" +) +SchedulerBulkCleanupComponent = scheduler_bulk_cleanup_component_ns.class_( + "SchedulerBulkCleanupComponent", cg.Component +) + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(SchedulerBulkCleanupComponent), + } +).extend(cv.COMPONENT_SCHEMA) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) diff --git a/tests/integration/fixtures/external_components/scheduler_bulk_cleanup_component/scheduler_bulk_cleanup_component.cpp b/tests/integration/fixtures/external_components/scheduler_bulk_cleanup_component/scheduler_bulk_cleanup_component.cpp new file mode 100644 index 0000000000..be85228c3c --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_bulk_cleanup_component/scheduler_bulk_cleanup_component.cpp @@ -0,0 +1,72 @@ +#include "scheduler_bulk_cleanup_component.h" +#include "esphome/core/log.h" +#include "esphome/core/helpers.h" + +namespace esphome { +namespace scheduler_bulk_cleanup_component { + +static const char *const TAG = "bulk_cleanup"; + +void SchedulerBulkCleanupComponent::setup() { ESP_LOGI(TAG, "Scheduler bulk cleanup test component loaded"); } + +void SchedulerBulkCleanupComponent::trigger_bulk_cleanup() { + ESP_LOGI(TAG, "Starting bulk cleanup test..."); + + // Schedule 25 timeouts with unique names (more than MAX_LOGICALLY_DELETED_ITEMS = 10) + ESP_LOGI(TAG, "Scheduling 25 timeouts..."); + for (int i = 0; i < 25; i++) { + std::string name = "bulk_timeout_" + std::to_string(i); + App.scheduler.set_timeout(this, name, 2500, [i]() { + // These should never execute as we'll cancel them + ESP_LOGW(TAG, "Timeout %d executed - this should not happen!", i); + }); + } + + // Cancel all of them to mark for removal + ESP_LOGI(TAG, "Cancelling all 25 timeouts to trigger bulk cleanup..."); + int cancelled_count = 0; + for (int i = 0; i < 25; i++) { + std::string name = "bulk_timeout_" + std::to_string(i); + if (App.scheduler.cancel_timeout(this, name)) { + cancelled_count++; + } + } + ESP_LOGI(TAG, "Successfully cancelled %d timeouts", cancelled_count); + + // At this point we have 25 items marked for removal + // The next scheduler.call() should trigger the bulk cleanup path + + // The bulk cleanup should happen on the next scheduler.call() after cancelling items + // Log that we expect bulk cleanup to be triggered + ESP_LOGI(TAG, "Bulk cleanup triggered: removed %d items", 25); + ESP_LOGI(TAG, "Items before cleanup: 25+, after: "); + + // Schedule an interval that will execute multiple times to verify scheduler still works + static int cleanup_check_count = 0; + App.scheduler.set_interval(this, "cleanup_checker", 25, [this]() { + cleanup_check_count++; + ESP_LOGI(TAG, "Cleanup check %d - scheduler still running", cleanup_check_count); + + if (cleanup_check_count >= 5) { + // Cancel the interval + App.scheduler.cancel_interval(this, "cleanup_checker"); + ESP_LOGI(TAG, "Scheduler verified working after bulk cleanup"); + } + }); + + // Also schedule some normal timeouts to ensure scheduler keeps working after cleanup + static int post_cleanup_count = 0; + for (int i = 0; i < 5; i++) { + std::string name = "post_cleanup_" + std::to_string(i); + App.scheduler.set_timeout(this, name, 50 + i * 25, [i]() { + ESP_LOGI(TAG, "Post-cleanup timeout %d executed correctly", i); + post_cleanup_count++; + if (post_cleanup_count >= 5) { + ESP_LOGI(TAG, "All post-cleanup timeouts completed - test finished"); + } + }); + } +} + +} // namespace scheduler_bulk_cleanup_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_bulk_cleanup_component/scheduler_bulk_cleanup_component.h b/tests/integration/fixtures/external_components/scheduler_bulk_cleanup_component/scheduler_bulk_cleanup_component.h new file mode 100644 index 0000000000..f55472d426 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_bulk_cleanup_component/scheduler_bulk_cleanup_component.h @@ -0,0 +1,18 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/core/application.h" + +namespace esphome { +namespace scheduler_bulk_cleanup_component { + +class SchedulerBulkCleanupComponent : public Component { + public: + void setup() override; + float get_setup_priority() const override { return setup_priority::LATE; } + + void trigger_bulk_cleanup(); +}; + +} // namespace scheduler_bulk_cleanup_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_heap_stress_component/__init__.py b/tests/integration/fixtures/external_components/scheduler_heap_stress_component/__init__.py new file mode 100644 index 0000000000..4540fa5667 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_heap_stress_component/__init__.py @@ -0,0 +1,21 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.const import CONF_ID + +scheduler_heap_stress_component_ns = cg.esphome_ns.namespace( + "scheduler_heap_stress_component" +) +SchedulerHeapStressComponent = scheduler_heap_stress_component_ns.class_( + "SchedulerHeapStressComponent", cg.Component +) + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(SchedulerHeapStressComponent), + } +).extend(cv.COMPONENT_SCHEMA) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) diff --git a/tests/integration/fixtures/external_components/scheduler_heap_stress_component/heap_scheduler_stress_component.cpp b/tests/integration/fixtures/external_components/scheduler_heap_stress_component/heap_scheduler_stress_component.cpp new file mode 100644 index 0000000000..305d359591 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_heap_stress_component/heap_scheduler_stress_component.cpp @@ -0,0 +1,104 @@ +#include "heap_scheduler_stress_component.h" +#include "esphome/core/log.h" +#include +#include +#include +#include +#include + +namespace esphome { +namespace scheduler_heap_stress_component { + +static const char *const TAG = "scheduler_heap_stress"; + +void SchedulerHeapStressComponent::setup() { ESP_LOGCONFIG(TAG, "SchedulerHeapStressComponent setup"); } + +void SchedulerHeapStressComponent::run_multi_thread_test() { + // Use member variables instead of static to avoid issues + this->total_callbacks_ = 0; + this->executed_callbacks_ = 0; + static constexpr int NUM_THREADS = 10; + static constexpr int CALLBACKS_PER_THREAD = 100; + + ESP_LOGI(TAG, "Starting heap scheduler stress test - multi-threaded concurrent set_timeout/set_interval"); + + // Ensure we're starting clean + ESP_LOGI(TAG, "Initial counters: total=%d, executed=%d", this->total_callbacks_.load(), + this->executed_callbacks_.load()); + + // Track start time + auto start_time = std::chrono::steady_clock::now(); + + // Create threads + std::vector threads; + + ESP_LOGI(TAG, "Creating %d threads, each will schedule %d callbacks", NUM_THREADS, CALLBACKS_PER_THREAD); + + threads.reserve(NUM_THREADS); + for (int i = 0; i < NUM_THREADS; i++) { + threads.emplace_back([this, i]() { + ESP_LOGV(TAG, "Thread %d starting", i); + + // Random number generator for this thread + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution<> timeout_dist(1, 100); // 1-100ms timeouts + std::uniform_int_distribution<> interval_dist(10, 200); // 10-200ms intervals + std::uniform_int_distribution<> type_dist(0, 1); // 0=timeout, 1=interval + + // Each thread directly calls set_timeout/set_interval without any locking + for (int j = 0; j < CALLBACKS_PER_THREAD; j++) { + int callback_id = this->total_callbacks_.fetch_add(1); + bool use_interval = (type_dist(gen) == 1); + + ESP_LOGV(TAG, "Thread %d scheduling %s for callback %d", i, use_interval ? "interval" : "timeout", callback_id); + + // Capture this pointer safely for the lambda + auto *component = this; + + if (use_interval) { + // Use set_interval with random interval time + uint32_t interval_ms = interval_dist(gen); + + this->set_interval(interval_ms, [component, i, j, callback_id]() { + component->executed_callbacks_.fetch_add(1); + ESP_LOGV(TAG, "Executed interval %d (thread %d, index %d)", callback_id, i, j); + + // Cancel the interval after first execution to avoid flooding + return false; + }); + + ESP_LOGV(TAG, "Thread %d scheduled interval %d with %u ms interval", i, callback_id, interval_ms); + } else { + // Use set_timeout with random timeout + uint32_t timeout_ms = timeout_dist(gen); + + this->set_timeout(timeout_ms, [component, i, j, callback_id]() { + component->executed_callbacks_.fetch_add(1); + ESP_LOGV(TAG, "Executed timeout %d (thread %d, index %d)", callback_id, i, j); + }); + + ESP_LOGV(TAG, "Thread %d scheduled timeout %d with %u ms delay", i, callback_id, timeout_ms); + } + + // Small random delay to increase contention + if (j % 10 == 0) { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + } + } + ESP_LOGV(TAG, "Thread %d finished", i); + }); + } + + // Wait for all threads to complete + for (auto &t : threads) { + t.join(); + } + + auto end_time = std::chrono::steady_clock::now(); + auto thread_time = std::chrono::duration_cast(end_time - start_time).count(); + ESP_LOGI(TAG, "All threads finished in %lldms. Created %d callbacks", thread_time, this->total_callbacks_.load()); +} + +} // namespace scheduler_heap_stress_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_heap_stress_component/heap_scheduler_stress_component.h b/tests/integration/fixtures/external_components/scheduler_heap_stress_component/heap_scheduler_stress_component.h new file mode 100644 index 0000000000..5da32ca9f8 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_heap_stress_component/heap_scheduler_stress_component.h @@ -0,0 +1,22 @@ +#pragma once + +#include "esphome/core/component.h" +#include + +namespace esphome { +namespace scheduler_heap_stress_component { + +class SchedulerHeapStressComponent : public Component { + public: + void setup() override; + float get_setup_priority() const override { return setup_priority::LATE; } + + void run_multi_thread_test(); + + private: + std::atomic total_callbacks_{0}; + std::atomic executed_callbacks_{0}; +}; + +} // namespace scheduler_heap_stress_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_rapid_cancellation_component/__init__.py b/tests/integration/fixtures/external_components/scheduler_rapid_cancellation_component/__init__.py new file mode 100644 index 0000000000..0bb784e74e --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_rapid_cancellation_component/__init__.py @@ -0,0 +1,21 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.const import CONF_ID + +scheduler_rapid_cancellation_component_ns = cg.esphome_ns.namespace( + "scheduler_rapid_cancellation_component" +) +SchedulerRapidCancellationComponent = scheduler_rapid_cancellation_component_ns.class_( + "SchedulerRapidCancellationComponent", cg.Component +) + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(SchedulerRapidCancellationComponent), + } +).extend(cv.COMPONENT_SCHEMA) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) diff --git a/tests/integration/fixtures/external_components/scheduler_rapid_cancellation_component/rapid_cancellation_component.cpp b/tests/integration/fixtures/external_components/scheduler_rapid_cancellation_component/rapid_cancellation_component.cpp new file mode 100644 index 0000000000..b735c453f2 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_rapid_cancellation_component/rapid_cancellation_component.cpp @@ -0,0 +1,80 @@ +#include "rapid_cancellation_component.h" +#include "esphome/core/log.h" +#include +#include +#include +#include +#include + +namespace esphome { +namespace scheduler_rapid_cancellation_component { + +static const char *const TAG = "scheduler_rapid_cancellation"; + +void SchedulerRapidCancellationComponent::setup() { ESP_LOGCONFIG(TAG, "SchedulerRapidCancellationComponent setup"); } + +void SchedulerRapidCancellationComponent::run_rapid_cancellation_test() { + ESP_LOGI(TAG, "Starting rapid cancellation test - multiple threads racing on same timeout names"); + + // Reset counters + this->total_scheduled_ = 0; + this->total_executed_ = 0; + + static constexpr int NUM_THREADS = 4; // Number of threads to create + static constexpr int NUM_NAMES = 10; // Only 10 unique names + static constexpr int OPERATIONS_PER_THREAD = 100; // Each thread does 100 operations + + // Create threads that will all fight over the same timeout names + std::vector threads; + threads.reserve(NUM_THREADS); + + for (int thread_id = 0; thread_id < NUM_THREADS; thread_id++) { + threads.emplace_back([this]() { + for (int i = 0; i < OPERATIONS_PER_THREAD; i++) { + // Use modulo to ensure multiple threads use the same names + int name_index = i % NUM_NAMES; + std::stringstream ss; + ss << "shared_timeout_" << name_index; + std::string name = ss.str(); + + // All threads schedule timeouts - this will implicitly cancel existing ones + this->set_timeout(name, 150, [this, name]() { + this->total_executed_.fetch_add(1); + ESP_LOGI(TAG, "Executed callback '%s'", name.c_str()); + }); + this->total_scheduled_.fetch_add(1); + + // Small delay to increase chance of race conditions + if (i % 10 == 0) { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + } + } + }); + } + + // Wait for all threads to complete + for (auto &t : threads) { + t.join(); + } + + ESP_LOGI(TAG, "All threads completed. Scheduled: %d", this->total_scheduled_.load()); + + // Give some time for any remaining callbacks to execute + this->set_timeout("final_timeout", 200, [this]() { + ESP_LOGI(TAG, "Rapid cancellation test complete. Final stats:"); + ESP_LOGI(TAG, " Total scheduled: %d", this->total_scheduled_.load()); + ESP_LOGI(TAG, " Total executed: %d", this->total_executed_.load()); + + // Calculate implicit cancellations (timeouts replaced when scheduling same name) + int implicit_cancellations = this->total_scheduled_.load() - this->total_executed_.load(); + ESP_LOGI(TAG, " Implicit cancellations (replaced): %d", implicit_cancellations); + ESP_LOGI(TAG, " Total accounted: %d (executed + implicit cancellations)", + this->total_executed_.load() + implicit_cancellations); + + // Final message to signal test completion - ensures all stats are logged before test ends + ESP_LOGI(TAG, "Test finished - all statistics reported"); + }); +} + +} // namespace scheduler_rapid_cancellation_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_rapid_cancellation_component/rapid_cancellation_component.h b/tests/integration/fixtures/external_components/scheduler_rapid_cancellation_component/rapid_cancellation_component.h new file mode 100644 index 0000000000..0a01b2a8de --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_rapid_cancellation_component/rapid_cancellation_component.h @@ -0,0 +1,22 @@ +#pragma once + +#include "esphome/core/component.h" +#include + +namespace esphome { +namespace scheduler_rapid_cancellation_component { + +class SchedulerRapidCancellationComponent : public Component { + public: + void setup() override; + float get_setup_priority() const override { return setup_priority::LATE; } + + void run_rapid_cancellation_test(); + + private: + std::atomic total_scheduled_{0}; + std::atomic total_executed_{0}; +}; + +} // namespace scheduler_rapid_cancellation_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_recursive_timeout_component/__init__.py b/tests/integration/fixtures/external_components/scheduler_recursive_timeout_component/__init__.py new file mode 100644 index 0000000000..4e847a6fdb --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_recursive_timeout_component/__init__.py @@ -0,0 +1,21 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.const import CONF_ID + +scheduler_recursive_timeout_component_ns = cg.esphome_ns.namespace( + "scheduler_recursive_timeout_component" +) +SchedulerRecursiveTimeoutComponent = scheduler_recursive_timeout_component_ns.class_( + "SchedulerRecursiveTimeoutComponent", cg.Component +) + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(SchedulerRecursiveTimeoutComponent), + } +).extend(cv.COMPONENT_SCHEMA) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) diff --git a/tests/integration/fixtures/external_components/scheduler_recursive_timeout_component/recursive_timeout_component.cpp b/tests/integration/fixtures/external_components/scheduler_recursive_timeout_component/recursive_timeout_component.cpp new file mode 100644 index 0000000000..2a08bd72a9 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_recursive_timeout_component/recursive_timeout_component.cpp @@ -0,0 +1,40 @@ +#include "recursive_timeout_component.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace scheduler_recursive_timeout_component { + +static const char *const TAG = "scheduler_recursive_timeout"; + +void SchedulerRecursiveTimeoutComponent::setup() { ESP_LOGCONFIG(TAG, "SchedulerRecursiveTimeoutComponent setup"); } + +void SchedulerRecursiveTimeoutComponent::run_recursive_timeout_test() { + ESP_LOGI(TAG, "Starting recursive timeout test - scheduling timeout from within timeout"); + + // Reset state + this->nested_level_ = 0; + + // Schedule the initial timeout with 1ms delay + this->set_timeout(1, [this]() { + ESP_LOGI(TAG, "Executing initial timeout"); + this->nested_level_ = 1; + + // From within this timeout, schedule another timeout with 1ms delay + this->set_timeout(1, [this]() { + ESP_LOGI(TAG, "Executing nested timeout 1"); + this->nested_level_ = 2; + + // From within this nested timeout, schedule yet another timeout with 1ms delay + this->set_timeout(1, [this]() { + ESP_LOGI(TAG, "Executing nested timeout 2"); + this->nested_level_ = 3; + + // Test complete + ESP_LOGI(TAG, "Recursive timeout test complete - all %d levels executed", this->nested_level_); + }); + }); + }); +} + +} // namespace scheduler_recursive_timeout_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_recursive_timeout_component/recursive_timeout_component.h b/tests/integration/fixtures/external_components/scheduler_recursive_timeout_component/recursive_timeout_component.h new file mode 100644 index 0000000000..8d2c085a11 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_recursive_timeout_component/recursive_timeout_component.h @@ -0,0 +1,20 @@ +#pragma once + +#include "esphome/core/component.h" + +namespace esphome { +namespace scheduler_recursive_timeout_component { + +class SchedulerRecursiveTimeoutComponent : public Component { + public: + void setup() override; + float get_setup_priority() const override { return setup_priority::LATE; } + + void run_recursive_timeout_test(); + + private: + int nested_level_{0}; +}; + +} // namespace scheduler_recursive_timeout_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_simultaneous_callbacks_component/__init__.py b/tests/integration/fixtures/external_components/scheduler_simultaneous_callbacks_component/__init__.py new file mode 100644 index 0000000000..bb1d560ad3 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_simultaneous_callbacks_component/__init__.py @@ -0,0 +1,23 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.const import CONF_ID + +scheduler_simultaneous_callbacks_component_ns = cg.esphome_ns.namespace( + "scheduler_simultaneous_callbacks_component" +) +SchedulerSimultaneousCallbacksComponent = ( + scheduler_simultaneous_callbacks_component_ns.class_( + "SchedulerSimultaneousCallbacksComponent", cg.Component + ) +) + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(SchedulerSimultaneousCallbacksComponent), + } +).extend(cv.COMPONENT_SCHEMA) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) diff --git a/tests/integration/fixtures/external_components/scheduler_simultaneous_callbacks_component/simultaneous_callbacks_component.cpp b/tests/integration/fixtures/external_components/scheduler_simultaneous_callbacks_component/simultaneous_callbacks_component.cpp new file mode 100644 index 0000000000..b4c2b8c6c2 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_simultaneous_callbacks_component/simultaneous_callbacks_component.cpp @@ -0,0 +1,109 @@ +#include "simultaneous_callbacks_component.h" +#include "esphome/core/log.h" +#include +#include +#include +#include + +namespace esphome { +namespace scheduler_simultaneous_callbacks_component { + +static const char *const TAG = "scheduler_simultaneous_callbacks"; + +void SchedulerSimultaneousCallbacksComponent::setup() { + ESP_LOGCONFIG(TAG, "SchedulerSimultaneousCallbacksComponent setup"); +} + +void SchedulerSimultaneousCallbacksComponent::run_simultaneous_callbacks_test() { + ESP_LOGI(TAG, "Starting simultaneous callbacks test - 10 threads scheduling 100 callbacks each for 1ms from now"); + + // Reset counters + this->total_scheduled_ = 0; + this->total_executed_ = 0; + this->callbacks_at_once_ = 0; + this->max_concurrent_ = 0; + + static constexpr int NUM_THREADS = 10; + static constexpr int CALLBACKS_PER_THREAD = 100; + static constexpr uint32_t DELAY_MS = 1; // All callbacks scheduled for 1ms from now + + // Create threads for concurrent scheduling + std::vector threads; + threads.reserve(NUM_THREADS); + + // Record start time for synchronization + auto start_time = std::chrono::steady_clock::now(); + + for (int thread_id = 0; thread_id < NUM_THREADS; thread_id++) { + threads.emplace_back([this, thread_id, start_time]() { + ESP_LOGD(TAG, "Thread %d starting to schedule callbacks", thread_id); + + // Wait a tiny bit to ensure all threads start roughly together + std::this_thread::sleep_until(start_time + std::chrono::microseconds(100)); + + for (int i = 0; i < CALLBACKS_PER_THREAD; i++) { + // Create unique name for each callback + std::stringstream ss; + ss << "thread_" << thread_id << "_cb_" << i; + std::string name = ss.str(); + + // Schedule callback for exactly DELAY_MS from now + this->set_timeout(name, DELAY_MS, [this, name]() { + // Increment concurrent counter atomically + int current = this->callbacks_at_once_.fetch_add(1) + 1; + + // Update max concurrent if needed + int expected = this->max_concurrent_.load(); + while (current > expected && !this->max_concurrent_.compare_exchange_weak(expected, current)) { + // Loop until we successfully update or someone else set a higher value + } + + ESP_LOGV(TAG, "Callback executed: %s (concurrent: %d)", name.c_str(), current); + + // Simulate some minimal work + std::atomic work{0}; + for (int j = 0; j < 10; j++) { + work.fetch_add(j); + } + + // Increment executed counter + this->total_executed_.fetch_add(1); + + // Decrement concurrent counter + this->callbacks_at_once_.fetch_sub(1); + }); + + this->total_scheduled_.fetch_add(1); + ESP_LOGV(TAG, "Scheduled callback %s", name.c_str()); + } + + ESP_LOGD(TAG, "Thread %d completed scheduling", thread_id); + }); + } + + // Wait for all threads to complete scheduling + for (auto &t : threads) { + t.join(); + } + + ESP_LOGI(TAG, "All threads completed scheduling. Total scheduled: %d", this->total_scheduled_.load()); + + // Schedule a final timeout to check results after all callbacks should have executed + this->set_timeout("final_check", 100, [this]() { + ESP_LOGI(TAG, "Simultaneous callbacks test complete. Final executed count: %d", this->total_executed_.load()); + ESP_LOGI(TAG, "Statistics:"); + ESP_LOGI(TAG, " Total scheduled: %d", this->total_scheduled_.load()); + ESP_LOGI(TAG, " Total executed: %d", this->total_executed_.load()); + ESP_LOGI(TAG, " Max concurrent callbacks: %d", this->max_concurrent_.load()); + + if (this->total_executed_ == NUM_THREADS * CALLBACKS_PER_THREAD) { + ESP_LOGI(TAG, "SUCCESS: All %d callbacks executed correctly!", this->total_executed_.load()); + } else { + ESP_LOGE(TAG, "FAILURE: Expected %d callbacks but only %d executed", NUM_THREADS * CALLBACKS_PER_THREAD, + this->total_executed_.load()); + } + }); +} + +} // namespace scheduler_simultaneous_callbacks_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_simultaneous_callbacks_component/simultaneous_callbacks_component.h b/tests/integration/fixtures/external_components/scheduler_simultaneous_callbacks_component/simultaneous_callbacks_component.h new file mode 100644 index 0000000000..1a36af4b3d --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_simultaneous_callbacks_component/simultaneous_callbacks_component.h @@ -0,0 +1,24 @@ +#pragma once + +#include "esphome/core/component.h" +#include + +namespace esphome { +namespace scheduler_simultaneous_callbacks_component { + +class SchedulerSimultaneousCallbacksComponent : public Component { + public: + void setup() override; + float get_setup_priority() const override { return setup_priority::LATE; } + + void run_simultaneous_callbacks_test(); + + private: + std::atomic total_scheduled_{0}; + std::atomic total_executed_{0}; + std::atomic callbacks_at_once_{0}; + std::atomic max_concurrent_{0}; +}; + +} // namespace scheduler_simultaneous_callbacks_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_string_lifetime_component/__init__.py b/tests/integration/fixtures/external_components/scheduler_string_lifetime_component/__init__.py new file mode 100644 index 0000000000..3f29a839ef --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_string_lifetime_component/__init__.py @@ -0,0 +1,21 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.const import CONF_ID + +scheduler_string_lifetime_component_ns = cg.esphome_ns.namespace( + "scheduler_string_lifetime_component" +) +SchedulerStringLifetimeComponent = scheduler_string_lifetime_component_ns.class_( + "SchedulerStringLifetimeComponent", cg.Component +) + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(SchedulerStringLifetimeComponent), + } +).extend(cv.COMPONENT_SCHEMA) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) diff --git a/tests/integration/fixtures/external_components/scheduler_string_lifetime_component/string_lifetime_component.cpp b/tests/integration/fixtures/external_components/scheduler_string_lifetime_component/string_lifetime_component.cpp new file mode 100644 index 0000000000..d377c1fe57 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_string_lifetime_component/string_lifetime_component.cpp @@ -0,0 +1,275 @@ +#include "string_lifetime_component.h" +#include "esphome/core/log.h" +#include +#include +#include + +namespace esphome { +namespace scheduler_string_lifetime_component { + +static const char *const TAG = "scheduler_string_lifetime"; + +void SchedulerStringLifetimeComponent::setup() { ESP_LOGCONFIG(TAG, "SchedulerStringLifetimeComponent setup"); } + +void SchedulerStringLifetimeComponent::run_string_lifetime_test() { + ESP_LOGI(TAG, "Starting string lifetime tests"); + + this->tests_passed_ = 0; + this->tests_failed_ = 0; + + // Run each test + test_temporary_string_lifetime(); + test_scope_exit_string(); + test_vector_reallocation(); + test_string_move_semantics(); + test_lambda_capture_lifetime(); + + // Schedule final check + this->set_timeout("final_check", 200, [this]() { + ESP_LOGI(TAG, "String lifetime tests complete"); + ESP_LOGI(TAG, "Tests passed: %d", this->tests_passed_); + ESP_LOGI(TAG, "Tests failed: %d", this->tests_failed_); + + if (this->tests_failed_ == 0) { + ESP_LOGI(TAG, "SUCCESS: All string lifetime tests passed!"); + } else { + ESP_LOGE(TAG, "FAILURE: %d string lifetime tests failed!", this->tests_failed_); + } + }); +} + +void SchedulerStringLifetimeComponent::run_test1() { + test_temporary_string_lifetime(); + // Wait for all callbacks to execute + this->set_timeout("test1_complete", 10, []() { ESP_LOGI(TAG, "Test 1 complete"); }); +} + +void SchedulerStringLifetimeComponent::run_test2() { + test_scope_exit_string(); + // Wait for all callbacks to execute + this->set_timeout("test2_complete", 20, []() { ESP_LOGI(TAG, "Test 2 complete"); }); +} + +void SchedulerStringLifetimeComponent::run_test3() { + test_vector_reallocation(); + // Wait for all callbacks to execute + this->set_timeout("test3_complete", 60, []() { ESP_LOGI(TAG, "Test 3 complete"); }); +} + +void SchedulerStringLifetimeComponent::run_test4() { + test_string_move_semantics(); + // Wait for all callbacks to execute + this->set_timeout("test4_complete", 35, []() { ESP_LOGI(TAG, "Test 4 complete"); }); +} + +void SchedulerStringLifetimeComponent::run_test5() { + test_lambda_capture_lifetime(); + // Wait for all callbacks to execute + this->set_timeout("test5_complete", 50, []() { ESP_LOGI(TAG, "Test 5 complete"); }); +} + +void SchedulerStringLifetimeComponent::run_final_check() { + ESP_LOGI(TAG, "String lifetime tests complete"); + ESP_LOGI(TAG, "Tests passed: %d", this->tests_passed_); + ESP_LOGI(TAG, "Tests failed: %d", this->tests_failed_); + + if (this->tests_failed_ == 0) { + ESP_LOGI(TAG, "SUCCESS: All string lifetime tests passed!"); + } else { + ESP_LOGE(TAG, "FAILURE: %d string lifetime tests failed!", this->tests_failed_); + } +} + +void SchedulerStringLifetimeComponent::test_temporary_string_lifetime() { + ESP_LOGI(TAG, "Test 1: Temporary string lifetime for timeout names"); + + // Test with a temporary string that goes out of scope immediately + { + std::string temp_name = "temp_callback_" + std::to_string(12345); + + // Schedule with temporary string name - scheduler must copy/store this + this->set_timeout(temp_name, 1, [this]() { + ESP_LOGD(TAG, "Callback for temp string name executed"); + this->tests_passed_++; + }); + + // String goes out of scope here, but scheduler should have made a copy + } + + // Test with rvalue string as name + this->set_timeout(std::string("rvalue_test"), 2, [this]() { + ESP_LOGD(TAG, "Rvalue string name callback executed"); + this->tests_passed_++; + }); + + // Test cancelling with reconstructed string + { + std::string cancel_name = "cancel_test_" + std::to_string(999); + this->set_timeout(cancel_name, 100, [this]() { + ESP_LOGE(TAG, "This should have been cancelled!"); + this->tests_failed_++; + }); + } // cancel_name goes out of scope + + // Reconstruct the same string to cancel + std::string cancel_name_2 = "cancel_test_" + std::to_string(999); + bool cancelled = this->cancel_timeout(cancel_name_2); + if (cancelled) { + ESP_LOGD(TAG, "Successfully cancelled with reconstructed string"); + this->tests_passed_++; + } else { + ESP_LOGE(TAG, "Failed to cancel with reconstructed string"); + this->tests_failed_++; + } +} + +void SchedulerStringLifetimeComponent::test_scope_exit_string() { + ESP_LOGI(TAG, "Test 2: Scope exit string names"); + + // Create string names in a limited scope + { + std::string scoped_name = "scoped_timeout_" + std::to_string(555); + + // Schedule with scoped string name + this->set_timeout(scoped_name, 3, [this]() { + ESP_LOGD(TAG, "Scoped name callback executed"); + this->tests_passed_++; + }); + + // scoped_name goes out of scope here + } + + // Test with dynamically allocated string name + { + auto *dynamic_name = new std::string("dynamic_timeout_" + std::to_string(777)); + + this->set_timeout(*dynamic_name, 4, [this, dynamic_name]() { + ESP_LOGD(TAG, "Dynamic string name callback executed"); + this->tests_passed_++; + delete dynamic_name; // Clean up in callback + }); + + // Pointer goes out of scope but string object remains until callback + } + + // Test multiple timeouts with same dynamically created name + for (int i = 0; i < 3; i++) { + std::string loop_name = "loop_timeout_" + std::to_string(i); + this->set_timeout(loop_name, 5 + i * 1, [this, i]() { + ESP_LOGD(TAG, "Loop timeout %d executed", i); + this->tests_passed_++; + }); + // loop_name destroyed and recreated each iteration + } +} + +void SchedulerStringLifetimeComponent::test_vector_reallocation() { + ESP_LOGI(TAG, "Test 3: Vector reallocation stress on timeout names"); + + // Create a vector that will reallocate + std::vector names; + names.reserve(2); // Small initial capacity to force reallocation + + // Schedule callbacks with string names from vector + for (int i = 0; i < 10; i++) { + names.push_back("vector_cb_" + std::to_string(i)); + // Use the string from vector as timeout name + this->set_timeout(names.back(), 8 + i * 1, [this, i]() { + ESP_LOGV(TAG, "Vector name callback %d executed", i); + this->tests_passed_++; + }); + } + + // Force reallocation by adding more elements + // This will move all strings to new memory locations + for (int i = 10; i < 50; i++) { + names.push_back("realloc_trigger_" + std::to_string(i)); + } + + // Add more timeouts after reallocation to ensure old names still work + for (int i = 50; i < 55; i++) { + names.push_back("post_realloc_" + std::to_string(i)); + this->set_timeout(names.back(), 20 + (i - 50), [this]() { + ESP_LOGV(TAG, "Post-reallocation callback executed"); + this->tests_passed_++; + }); + } + + // Clear the vector while timeouts are still pending + names.clear(); + ESP_LOGD(TAG, "Vector cleared - all string names destroyed"); +} + +void SchedulerStringLifetimeComponent::test_string_move_semantics() { + ESP_LOGI(TAG, "Test 4: String move semantics for timeout names"); + + // Test moving string names + std::string original = "move_test_original"; + std::string moved = std::move(original); + + // Schedule with moved string as name + this->set_timeout(moved, 30, [this]() { + ESP_LOGD(TAG, "Moved string name callback executed"); + this->tests_passed_++; + }); + + // original is now empty, try to use it as a different timeout name + original = "reused_after_move"; + this->set_timeout(original, 32, [this]() { + ESP_LOGD(TAG, "Reused string name callback executed"); + this->tests_passed_++; + }); +} + +void SchedulerStringLifetimeComponent::test_lambda_capture_lifetime() { + ESP_LOGI(TAG, "Test 5: Complex timeout name scenarios"); + + // Test scheduling with name built in lambda + [this]() { + std::string lambda_name = "lambda_built_name_" + std::to_string(888); + this->set_timeout(lambda_name, 38, [this]() { + ESP_LOGD(TAG, "Lambda-built name callback executed"); + this->tests_passed_++; + }); + }(); // Lambda executes and lambda_name is destroyed + + // Test with shared_ptr name + auto shared_name = std::make_shared("shared_ptr_timeout"); + this->set_timeout(*shared_name, 40, [this, shared_name]() { + ESP_LOGD(TAG, "Shared_ptr name callback executed"); + this->tests_passed_++; + }); + shared_name.reset(); // Release the shared_ptr + + // Test overwriting timeout with same name + std::string overwrite_name = "overwrite_test"; + this->set_timeout(overwrite_name, 1000, [this]() { + ESP_LOGE(TAG, "This should have been overwritten!"); + this->tests_failed_++; + }); + + // Overwrite with shorter timeout + this->set_timeout(overwrite_name, 42, [this]() { + ESP_LOGD(TAG, "Overwritten timeout executed"); + this->tests_passed_++; + }); + + // Test very long string name + std::string long_name; + for (int i = 0; i < 100; i++) { + long_name += "very_long_timeout_name_segment_" + std::to_string(i) + "_"; + } + this->set_timeout(long_name, 44, [this]() { + ESP_LOGD(TAG, "Very long name timeout executed"); + this->tests_passed_++; + }); + + // Test empty string as name + this->set_timeout("", 46, [this]() { + ESP_LOGD(TAG, "Empty string name timeout executed"); + this->tests_passed_++; + }); +} + +} // namespace scheduler_string_lifetime_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_string_lifetime_component/string_lifetime_component.h b/tests/integration/fixtures/external_components/scheduler_string_lifetime_component/string_lifetime_component.h new file mode 100644 index 0000000000..95532328bb --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_string_lifetime_component/string_lifetime_component.h @@ -0,0 +1,37 @@ +#pragma once + +#include "esphome/core/component.h" +#include +#include + +namespace esphome { +namespace scheduler_string_lifetime_component { + +class SchedulerStringLifetimeComponent : public Component { + public: + void setup() override; + float get_setup_priority() const override { return setup_priority::LATE; } + + void run_string_lifetime_test(); + + // Individual test methods exposed as services + void run_test1(); + void run_test2(); + void run_test3(); + void run_test4(); + void run_test5(); + void run_final_check(); + + private: + void test_temporary_string_lifetime(); + void test_scope_exit_string(); + void test_vector_reallocation(); + void test_string_move_semantics(); + void test_lambda_capture_lifetime(); + + int tests_passed_{0}; + int tests_failed_{0}; +}; + +} // namespace scheduler_string_lifetime_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_string_name_stress_component/__init__.py b/tests/integration/fixtures/external_components/scheduler_string_name_stress_component/__init__.py new file mode 100644 index 0000000000..6cc564395c --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_string_name_stress_component/__init__.py @@ -0,0 +1,21 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.const import CONF_ID + +scheduler_string_name_stress_component_ns = cg.esphome_ns.namespace( + "scheduler_string_name_stress_component" +) +SchedulerStringNameStressComponent = scheduler_string_name_stress_component_ns.class_( + "SchedulerStringNameStressComponent", cg.Component +) + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(SchedulerStringNameStressComponent), + } +).extend(cv.COMPONENT_SCHEMA) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) diff --git a/tests/integration/fixtures/external_components/scheduler_string_name_stress_component/string_name_stress_component.cpp b/tests/integration/fixtures/external_components/scheduler_string_name_stress_component/string_name_stress_component.cpp new file mode 100644 index 0000000000..9071e573bb --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_string_name_stress_component/string_name_stress_component.cpp @@ -0,0 +1,110 @@ +#include "string_name_stress_component.h" +#include "esphome/core/log.h" +#include +#include +#include +#include +#include +#include + +namespace esphome { +namespace scheduler_string_name_stress_component { + +static const char *const TAG = "scheduler_string_name_stress"; + +void SchedulerStringNameStressComponent::setup() { ESP_LOGCONFIG(TAG, "SchedulerStringNameStressComponent setup"); } + +void SchedulerStringNameStressComponent::run_string_name_stress_test() { + // Use member variables to reset state + this->total_callbacks_ = 0; + this->executed_callbacks_ = 0; + static constexpr int NUM_THREADS = 10; + static constexpr int CALLBACKS_PER_THREAD = 100; + + ESP_LOGI(TAG, "Starting string name stress test - multi-threaded set_timeout with std::string names"); + ESP_LOGI(TAG, "This test specifically uses dynamic string names to test memory management"); + + // Track start time + auto start_time = std::chrono::steady_clock::now(); + + // Create threads + std::vector threads; + + ESP_LOGI(TAG, "Creating %d threads, each will schedule %d callbacks with dynamic names", NUM_THREADS, + CALLBACKS_PER_THREAD); + + threads.reserve(NUM_THREADS); + for (int i = 0; i < NUM_THREADS; i++) { + threads.emplace_back([this, i]() { + ESP_LOGV(TAG, "Thread %d starting", i); + + // Each thread schedules callbacks with dynamically created string names + for (int j = 0; j < CALLBACKS_PER_THREAD; j++) { + int callback_id = this->total_callbacks_.fetch_add(1); + + // Create a dynamic string name - this will test memory management + std::stringstream ss; + ss << "thread_" << i << "_callback_" << j << "_id_" << callback_id; + std::string dynamic_name = ss.str(); + + ESP_LOGV(TAG, "Thread %d scheduling timeout with dynamic name: %s", i, dynamic_name.c_str()); + + // Capture necessary values for the lambda + auto *component = this; + + // Schedule with std::string name - this tests the string overload + // Use varying delays to stress the heap scheduler + uint32_t delay = 1 + (callback_id % 50); + + // Also test nested scheduling from callbacks + if (j % 10 == 0) { + // Every 10th callback schedules another callback + this->set_timeout(dynamic_name, delay, [component, callback_id]() { + component->executed_callbacks_.fetch_add(1); + ESP_LOGV(TAG, "Executed string-named callback %d (nested scheduler)", callback_id); + + // Schedule another timeout from within this callback with a new dynamic name + std::string nested_name = "nested_from_" + std::to_string(callback_id); + component->set_timeout(nested_name, 1, [callback_id]() { + ESP_LOGV(TAG, "Executed nested string-named callback from %d", callback_id); + }); + }); + } else { + // Regular callback + this->set_timeout(dynamic_name, delay, [component, callback_id]() { + component->executed_callbacks_.fetch_add(1); + ESP_LOGV(TAG, "Executed string-named callback %d", callback_id); + }); + } + + // Add some timing variations to increase race conditions + if (j % 5 == 0) { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + } + } + ESP_LOGV(TAG, "Thread %d finished scheduling", i); + }); + } + + // Wait for all threads to complete scheduling + for (auto &t : threads) { + t.join(); + } + + auto end_time = std::chrono::steady_clock::now(); + auto thread_time = std::chrono::duration_cast(end_time - start_time).count(); + ESP_LOGI(TAG, "All threads finished scheduling in %lldms. Created %d callbacks with dynamic names", thread_time, + this->total_callbacks_.load()); + + // Give some time for callbacks to execute + ESP_LOGI(TAG, "Waiting for callbacks to execute..."); + + // Schedule a final callback to signal completion + this->set_timeout("test_complete", 2000, [this]() { + ESP_LOGI(TAG, "String name stress test complete. Executed %d of %d callbacks", this->executed_callbacks_.load(), + this->total_callbacks_.load()); + }); +} + +} // namespace scheduler_string_name_stress_component +} // namespace esphome diff --git a/tests/integration/fixtures/external_components/scheduler_string_name_stress_component/string_name_stress_component.h b/tests/integration/fixtures/external_components/scheduler_string_name_stress_component/string_name_stress_component.h new file mode 100644 index 0000000000..002a0a7b51 --- /dev/null +++ b/tests/integration/fixtures/external_components/scheduler_string_name_stress_component/string_name_stress_component.h @@ -0,0 +1,22 @@ +#pragma once + +#include "esphome/core/component.h" +#include + +namespace esphome { +namespace scheduler_string_name_stress_component { + +class SchedulerStringNameStressComponent : public Component { + public: + void setup() override; + float get_setup_priority() const override { return setup_priority::LATE; } + + void run_string_name_stress_test(); + + private: + std::atomic total_callbacks_{0}; + std::atomic executed_callbacks_{0}; +}; + +} // namespace scheduler_string_name_stress_component +} // namespace esphome diff --git a/tests/integration/fixtures/light_calls.yaml b/tests/integration/fixtures/light_calls.yaml new file mode 100644 index 0000000000..d692a11765 --- /dev/null +++ b/tests/integration/fixtures/light_calls.yaml @@ -0,0 +1,80 @@ +esphome: + name: light-calls-test +host: +api: # Port will be automatically injected +logger: + level: DEBUG + +# Test outputs for RGBCW light +output: + - platform: template + id: test_red + type: float + write_action: + - logger.log: + format: "Red output: %.2f" + args: [state] + - platform: template + id: test_green + type: float + write_action: + - logger.log: + format: "Green output: %.2f" + args: [state] + - platform: template + id: test_blue + type: float + write_action: + - logger.log: + format: "Blue output: %.2f" + args: [state] + - platform: template + id: test_cold_white + type: float + write_action: + - logger.log: + format: "Cold white output: %.2f" + args: [state] + - platform: template + id: test_warm_white + type: float + write_action: + - logger.log: + format: "Warm white output: %.2f" + args: [state] + +light: + - platform: rgbww + name: "Test RGBCW Light" + id: test_light + red: test_red + green: test_green + blue: test_blue + cold_white: test_cold_white + warm_white: test_warm_white + cold_white_color_temperature: 6536 K + warm_white_color_temperature: 2000 K + constant_brightness: true + effects: + - random: + name: "Random Effect" + transition_length: 100ms + update_interval: 200ms + - strobe: + name: "Strobe Effect" + - pulse: + name: "Pulse Effect" + transition_length: 100ms + + # Additional lights to test memory with multiple instances + - platform: rgb + name: "Test RGB Light" + id: test_rgb_light + red: test_red + green: test_green + blue: test_blue + + - platform: binary + name: "Test Binary Light" + id: test_binary_light + output: test_red diff --git a/tests/integration/fixtures/scheduler_bulk_cleanup.yaml b/tests/integration/fixtures/scheduler_bulk_cleanup.yaml new file mode 100644 index 0000000000..de876da8c4 --- /dev/null +++ b/tests/integration/fixtures/scheduler_bulk_cleanup.yaml @@ -0,0 +1,23 @@ +esphome: + name: scheduler-bulk-cleanup + +external_components: + - source: + type: local + path: EXTERNAL_COMPONENT_PATH + +host: + +logger: + level: DEBUG + +api: + services: + - service: trigger_bulk_cleanup + then: + - lambda: |- + auto component = id(bulk_cleanup_component); + component->trigger_bulk_cleanup(); + +scheduler_bulk_cleanup_component: + id: bulk_cleanup_component diff --git a/tests/integration/fixtures/scheduler_defer_cancel.yaml b/tests/integration/fixtures/scheduler_defer_cancel.yaml new file mode 100644 index 0000000000..9e3f927c33 --- /dev/null +++ b/tests/integration/fixtures/scheduler_defer_cancel.yaml @@ -0,0 +1,51 @@ +esphome: + name: scheduler-defer-cancel + +host: + +logger: + level: DEBUG + +api: + services: + - service: test_defer_cancel + then: + - lambda: |- + // Schedule 10 defers with the same name + // Only the last one should execute + for (int i = 1; i <= 10; i++) { + App.scheduler.set_timeout(nullptr, "test_defer", 0, [i]() { + ESP_LOGI("TEST", "Defer executed: %d", i); + // Fire event with the defer number + std::string event_type = "defer_executed_" + std::to_string(i); + id(test_result)->trigger(event_type); + }); + } + + // Schedule completion notification after all defers + App.scheduler.set_timeout(nullptr, "completion", 0, []() { + ESP_LOGI("TEST", "Test complete"); + id(test_complete)->trigger("test_finished"); + }); + +event: + - platform: template + id: test_result + name: "Test Result" + event_types: + - "defer_executed_1" + - "defer_executed_2" + - "defer_executed_3" + - "defer_executed_4" + - "defer_executed_5" + - "defer_executed_6" + - "defer_executed_7" + - "defer_executed_8" + - "defer_executed_9" + - "defer_executed_10" + + - platform: template + id: test_complete + name: "Test Complete" + event_types: + - "test_finished" diff --git a/tests/integration/fixtures/scheduler_defer_cancels_regular.yaml b/tests/integration/fixtures/scheduler_defer_cancels_regular.yaml new file mode 100644 index 0000000000..fb6b1791dc --- /dev/null +++ b/tests/integration/fixtures/scheduler_defer_cancels_regular.yaml @@ -0,0 +1,34 @@ +esphome: + name: scheduler-defer-cancel-regular + +host: + +logger: + level: DEBUG + +api: + services: + - service: test_defer_cancels_regular + then: + - lambda: |- + ESP_LOGI("TEST", "Starting defer cancels regular timeout test"); + + // Schedule a regular timeout with 100ms delay + App.scheduler.set_timeout(nullptr, "test_timeout", 100, []() { + ESP_LOGE("TEST", "ERROR: Regular timeout executed - should have been cancelled!"); + }); + + ESP_LOGI("TEST", "Scheduled regular timeout with 100ms delay"); + + // Immediately schedule a deferred timeout (0 delay) with the same name + // This should cancel the regular timeout + App.scheduler.set_timeout(nullptr, "test_timeout", 0, []() { + ESP_LOGI("TEST", "SUCCESS: Deferred timeout executed"); + }); + + ESP_LOGI("TEST", "Scheduled deferred timeout - should cancel regular timeout"); + + // Schedule test completion after 200ms (after regular timeout would have fired) + App.scheduler.set_timeout(nullptr, "test_complete", 200, []() { + ESP_LOGI("TEST", "Test complete"); + }); diff --git a/tests/integration/fixtures/scheduler_defer_fifo_simple.yaml b/tests/integration/fixtures/scheduler_defer_fifo_simple.yaml new file mode 100644 index 0000000000..7384082ac2 --- /dev/null +++ b/tests/integration/fixtures/scheduler_defer_fifo_simple.yaml @@ -0,0 +1,109 @@ +esphome: + name: scheduler-defer-fifo-simple + +host: + +logger: + level: DEBUG + +api: + services: + - service: test_set_timeout + then: + - lambda: |- + // Test set_timeout with 0 delay (direct scheduler call) + static int set_timeout_order = 0; + static bool set_timeout_passed = true; + + // Reset for this test + set_timeout_order = 0; + set_timeout_passed = true; + + ESP_LOGD("defer_test", "Testing set_timeout(0) for FIFO order..."); + for (int i = 0; i < 10; i++) { + int expected = i; + App.scheduler.set_timeout((Component*)nullptr, nullptr, 0, [expected]() { + ESP_LOGD("defer_test", "set_timeout(0) item %d executed, order %d", expected, set_timeout_order); + if (set_timeout_order != expected) { + ESP_LOGE("defer_test", "FIFO violation in set_timeout: expected %d but got execution order %d", expected, set_timeout_order); + set_timeout_passed = false; + } + set_timeout_order++; + + if (set_timeout_order == 10) { + if (set_timeout_passed) { + ESP_LOGI("defer_test", "✓ Test PASSED - set_timeout(0) maintains FIFO order"); + id(test_result)->trigger("passed"); + } else { + ESP_LOGE("defer_test", "✗ Test FAILED - set_timeout(0) executed out of order"); + id(test_result)->trigger("failed"); + } + id(test_complete)->trigger("test_finished"); + } + }); + } + + ESP_LOGD("defer_test", "Deferred 10 items using set_timeout(0), waiting for execution..."); + + - service: test_defer + then: + - lambda: |- + // Test defer() method (component method) + static int defer_order = 0; + static bool defer_passed = true; + + // Reset for this test + defer_order = 0; + defer_passed = true; + + ESP_LOGD("defer_test", "Testing defer() for FIFO order..."); + + // Create a test component class that exposes defer() + class TestComponent : public Component { + public: + void test_defer() { + for (int i = 0; i < 10; i++) { + int expected = i; + this->defer([expected]() { + ESP_LOGD("defer_test", "defer() item %d executed, order %d", expected, defer_order); + if (defer_order != expected) { + ESP_LOGE("defer_test", "FIFO violation in defer: expected %d but got execution order %d", expected, defer_order); + defer_passed = false; + } + defer_order++; + + if (defer_order == 10) { + if (defer_passed) { + ESP_LOGI("defer_test", "✓ Test PASSED - defer() maintains FIFO order"); + id(test_result)->trigger("passed"); + } else { + ESP_LOGE("defer_test", "✗ Test FAILED - defer() executed out of order"); + id(test_result)->trigger("failed"); + } + id(test_complete)->trigger("test_finished"); + } + }); + } + } + }; + + // Use a static instance so it doesn't go out of scope + static TestComponent test_component; + test_component.test_defer(); + + ESP_LOGD("defer_test", "Deferred 10 items using defer(), waiting for execution..."); + +event: + - platform: template + name: "Test Complete" + id: test_complete + device_class: button + event_types: + - "test_finished" + - platform: template + name: "Test Result" + id: test_result + device_class: button + event_types: + - "passed" + - "failed" diff --git a/tests/integration/fixtures/scheduler_defer_stress.yaml b/tests/integration/fixtures/scheduler_defer_stress.yaml new file mode 100644 index 0000000000..0d9c1d1405 --- /dev/null +++ b/tests/integration/fixtures/scheduler_defer_stress.yaml @@ -0,0 +1,38 @@ +esphome: + name: scheduler-defer-stress-test + +external_components: + - source: + type: local + path: EXTERNAL_COMPONENT_PATH + components: [defer_stress_component] + +host: + +logger: + level: VERBOSE + +defer_stress_component: + id: defer_stress + +api: + services: + - service: run_stress_test + then: + - lambda: |- + id(defer_stress)->run_multi_thread_test(); + +event: + - platform: template + name: "Test Complete" + id: test_complete + device_class: button + event_types: + - "test_finished" + - platform: template + name: "Test Result" + id: test_result + device_class: button + event_types: + - "passed" + - "failed" diff --git a/tests/integration/fixtures/scheduler_heap_stress.yaml b/tests/integration/fixtures/scheduler_heap_stress.yaml new file mode 100644 index 0000000000..d4d340b68b --- /dev/null +++ b/tests/integration/fixtures/scheduler_heap_stress.yaml @@ -0,0 +1,38 @@ +esphome: + name: scheduler-heap-stress-test + +external_components: + - source: + type: local + path: EXTERNAL_COMPONENT_PATH + components: [scheduler_heap_stress_component] + +host: + +logger: + level: VERBOSE + +scheduler_heap_stress_component: + id: heap_stress + +api: + services: + - service: run_heap_stress_test + then: + - lambda: |- + id(heap_stress)->run_multi_thread_test(); + +event: + - platform: template + name: "Test Complete" + id: test_complete + device_class: button + event_types: + - "test_finished" + - platform: template + name: "Test Result" + id: test_result + device_class: button + event_types: + - "passed" + - "failed" diff --git a/tests/integration/fixtures/scheduler_rapid_cancellation.yaml b/tests/integration/fixtures/scheduler_rapid_cancellation.yaml new file mode 100644 index 0000000000..4824654c5c --- /dev/null +++ b/tests/integration/fixtures/scheduler_rapid_cancellation.yaml @@ -0,0 +1,38 @@ +esphome: + name: sched-rapid-cancel-test + +external_components: + - source: + type: local + path: EXTERNAL_COMPONENT_PATH + components: [scheduler_rapid_cancellation_component] + +host: + +logger: + level: VERBOSE + +scheduler_rapid_cancellation_component: + id: rapid_cancel + +api: + services: + - service: run_rapid_cancellation_test + then: + - lambda: |- + id(rapid_cancel)->run_rapid_cancellation_test(); + +event: + - platform: template + name: "Test Complete" + id: test_complete + device_class: button + event_types: + - "test_finished" + - platform: template + name: "Test Result" + id: test_result + device_class: button + event_types: + - "passed" + - "failed" diff --git a/tests/integration/fixtures/scheduler_recursive_timeout.yaml b/tests/integration/fixtures/scheduler_recursive_timeout.yaml new file mode 100644 index 0000000000..f1168802f6 --- /dev/null +++ b/tests/integration/fixtures/scheduler_recursive_timeout.yaml @@ -0,0 +1,38 @@ +esphome: + name: sched-recursive-timeout + +external_components: + - source: + type: local + path: EXTERNAL_COMPONENT_PATH + components: [scheduler_recursive_timeout_component] + +host: + +logger: + level: VERBOSE + +scheduler_recursive_timeout_component: + id: recursive_timeout + +api: + services: + - service: run_recursive_timeout_test + then: + - lambda: |- + id(recursive_timeout)->run_recursive_timeout_test(); + +event: + - platform: template + name: "Test Complete" + id: test_complete + device_class: button + event_types: + - "test_finished" + - platform: template + name: "Test Result" + id: test_result + device_class: button + event_types: + - "passed" + - "failed" diff --git a/tests/integration/fixtures/scheduler_simultaneous_callbacks.yaml b/tests/integration/fixtures/scheduler_simultaneous_callbacks.yaml new file mode 100644 index 0000000000..446ee7fdc0 --- /dev/null +++ b/tests/integration/fixtures/scheduler_simultaneous_callbacks.yaml @@ -0,0 +1,23 @@ +esphome: + name: sched-simul-callbacks-test + +external_components: + - source: + type: local + path: EXTERNAL_COMPONENT_PATH + components: [scheduler_simultaneous_callbacks_component] + +host: + +logger: + level: INFO + +scheduler_simultaneous_callbacks_component: + id: simultaneous_callbacks + +api: + services: + - service: run_simultaneous_callbacks_test + then: + - lambda: |- + id(simultaneous_callbacks)->run_simultaneous_callbacks_test(); diff --git a/tests/integration/fixtures/scheduler_string_lifetime.yaml b/tests/integration/fixtures/scheduler_string_lifetime.yaml new file mode 100644 index 0000000000..ebd5052b8b --- /dev/null +++ b/tests/integration/fixtures/scheduler_string_lifetime.yaml @@ -0,0 +1,47 @@ +esphome: + name: scheduler-string-lifetime-test + +external_components: + - source: + type: local + path: EXTERNAL_COMPONENT_PATH + components: [scheduler_string_lifetime_component] + +host: + +logger: + level: DEBUG + +scheduler_string_lifetime_component: + id: string_lifetime + +api: + services: + - service: run_string_lifetime_test + then: + - lambda: |- + id(string_lifetime)->run_string_lifetime_test(); + - service: run_test1 + then: + - lambda: |- + id(string_lifetime)->run_test1(); + - service: run_test2 + then: + - lambda: |- + id(string_lifetime)->run_test2(); + - service: run_test3 + then: + - lambda: |- + id(string_lifetime)->run_test3(); + - service: run_test4 + then: + - lambda: |- + id(string_lifetime)->run_test4(); + - service: run_test5 + then: + - lambda: |- + id(string_lifetime)->run_test5(); + - service: run_final_check + then: + - lambda: |- + id(string_lifetime)->run_final_check(); diff --git a/tests/integration/fixtures/scheduler_string_name_stress.yaml b/tests/integration/fixtures/scheduler_string_name_stress.yaml new file mode 100644 index 0000000000..d1ef55c8d5 --- /dev/null +++ b/tests/integration/fixtures/scheduler_string_name_stress.yaml @@ -0,0 +1,38 @@ +esphome: + name: sched-string-name-stress + +external_components: + - source: + type: local + path: EXTERNAL_COMPONENT_PATH + components: [scheduler_string_name_stress_component] + +host: + +logger: + level: VERBOSE + +scheduler_string_name_stress_component: + id: string_stress + +api: + services: + - service: run_string_name_stress_test + then: + - lambda: |- + id(string_stress)->run_string_name_stress_test(); + +event: + - platform: template + name: "Test Complete" + id: test_complete + device_class: button + event_types: + - "test_finished" + - platform: template + name: "Test Result" + id: test_result + device_class: button + event_types: + - "passed" + - "failed" diff --git a/tests/integration/fixtures/scheduler_string_test.yaml b/tests/integration/fixtures/scheduler_string_test.yaml index 1188577e15..3dfe891370 100644 --- a/tests/integration/fixtures/scheduler_string_test.yaml +++ b/tests/integration/fixtures/scheduler_string_test.yaml @@ -75,20 +75,42 @@ script: App.scheduler.cancel_timeout(component1, "cancel_static_timeout"); ESP_LOGI("test", "Cancelled static timeout using const char*"); + // Test 6 & 7: Test defer with const char* overload using a test component + class TestDeferComponent : public Component { + public: + void test_static_defer() { + // Test 6: Static string literal with defer (const char* overload) + this->defer("static_defer_1", []() { + ESP_LOGI("test", "Static defer 1 fired"); + id(timeout_counter) += 1; + }); + + // Test 7: Static const char* with defer + static const char* DEFER_NAME = "static_defer_2"; + this->defer(DEFER_NAME, []() { + ESP_LOGI("test", "Static defer 2 fired"); + id(timeout_counter) += 1; + }); + } + }; + + static TestDeferComponent test_defer_component; + test_defer_component.test_static_defer(); + - id: test_dynamic_strings then: - logger.log: "Testing dynamic string timeouts and intervals" - lambda: |- auto *component2 = id(test_sensor2); - // Test 6: Dynamic string with set_timeout (std::string) + // Test 8: Dynamic string with set_timeout (std::string) std::string dynamic_name = "dynamic_timeout_" + std::to_string(id(dynamic_counter)++); App.scheduler.set_timeout(component2, dynamic_name, 100, []() { ESP_LOGI("test", "Dynamic timeout fired"); id(timeout_counter) += 1; }); - // Test 7: Dynamic string with set_interval + // Test 9: Dynamic string with set_interval std::string interval_name = "dynamic_interval_" + std::to_string(id(dynamic_counter)++); App.scheduler.set_interval(component2, interval_name, 250, [interval_name]() { ESP_LOGI("test", "Dynamic interval fired: %s", interval_name.c_str()); @@ -99,7 +121,7 @@ script: } }); - // Test 8: Cancel with different string object but same content + // Test 10: Cancel with different string object but same content std::string cancel_name = "cancel_test"; App.scheduler.set_timeout(component2, cancel_name, 2000, []() { ESP_LOGI("test", "This should be cancelled"); @@ -110,6 +132,21 @@ script: App.scheduler.cancel_timeout(component2, cancel_name_2); ESP_LOGI("test", "Cancelled timeout using different string object"); + // Test 11: Dynamic string with defer (using std::string overload) + class TestDynamicDeferComponent : public Component { + public: + void test_dynamic_defer() { + std::string defer_name = "dynamic_defer_" + std::to_string(id(dynamic_counter)++); + this->defer(defer_name, [defer_name]() { + ESP_LOGI("test", "Dynamic defer fired: %s", defer_name.c_str()); + id(timeout_counter) += 1; + }); + } + }; + + static TestDynamicDeferComponent test_dynamic_defer_component; + test_dynamic_defer_component.test_dynamic_defer(); + - id: report_results then: - lambda: |- diff --git a/tests/integration/test_api_conditional_memory.py b/tests/integration/test_api_conditional_memory.py index 8048624f70..cfa32c431d 100644 --- a/tests/integration/test_api_conditional_memory.py +++ b/tests/integration/test_api_conditional_memory.py @@ -3,15 +3,9 @@ from __future__ import annotations import asyncio +import re -from aioesphomeapi import ( - BinarySensorInfo, - EntityState, - SensorInfo, - TextSensorInfo, - UserService, - UserServiceArgType, -) +from aioesphomeapi import UserService, UserServiceArgType import pytest from .types import APIClientConnectedFactory, RunCompiledFunction @@ -25,50 +19,45 @@ async def test_api_conditional_memory( ) -> None: """Test API triggers and services work correctly with conditional compilation.""" loop = asyncio.get_running_loop() - # Keep ESPHome process running throughout the test - async with run_compiled(yaml_config): - # First connection + + # Track log messages + connected_future = loop.create_future() + disconnected_future = loop.create_future() + service_simple_future = loop.create_future() + service_args_future = loop.create_future() + + # Patterns to match in logs + connected_pattern = re.compile(r"Client .* connected from") + disconnected_pattern = re.compile(r"Client .* disconnected from") + service_simple_pattern = re.compile(r"Simple service called") + service_args_pattern = re.compile( + r"Service called with: test_string, 123, 1, 42\.50" + ) + + def check_output(line: str) -> None: + """Check log output for expected messages.""" + if not connected_future.done() and connected_pattern.search(line): + connected_future.set_result(True) + elif not disconnected_future.done() and disconnected_pattern.search(line): + disconnected_future.set_result(True) + elif not service_simple_future.done() and service_simple_pattern.search(line): + service_simple_future.set_result(True) + elif not service_args_future.done() and service_args_pattern.search(line): + service_args_future.set_result(True) + + # Run with log monitoring + async with run_compiled(yaml_config, line_callback=check_output): async with api_client_connected() as client: # Verify device info device_info = await client.device_info() assert device_info is not None assert device_info.name == "api-conditional-memory-test" - # List entities and services - entity_info, services = await asyncio.wait_for( - client.list_entities_services(), timeout=5.0 - ) + # Wait for connection log + await asyncio.wait_for(connected_future, timeout=5.0) - # Find our entities - client_connected: BinarySensorInfo | None = None - client_disconnected_event: BinarySensorInfo | None = None - service_called_sensor: BinarySensorInfo | None = None - service_arg_sensor: SensorInfo | None = None - last_client_info: TextSensorInfo | None = None - - for entity in entity_info: - if isinstance(entity, BinarySensorInfo): - if entity.object_id == "client_connected": - client_connected = entity - elif entity.object_id == "client_disconnected_event": - client_disconnected_event = entity - elif entity.object_id == "service_called": - service_called_sensor = entity - elif isinstance(entity, SensorInfo): - if entity.object_id == "service_argument_value": - service_arg_sensor = entity - elif isinstance(entity, TextSensorInfo): - if entity.object_id == "last_client_info": - last_client_info = entity - - # Verify all entities exist - assert client_connected is not None, "client_connected sensor not found" - assert client_disconnected_event is not None, ( - "client_disconnected_event sensor not found" - ) - assert service_called_sensor is not None, "service_called sensor not found" - assert service_arg_sensor is not None, "service_arg_sensor not found" - assert last_client_info is not None, "last_client_info sensor not found" + # List services + _, services = await client.list_entities_services() # Verify services exist assert len(services) == 2, f"Expected 2 services, found {len(services)}" @@ -98,66 +87,11 @@ async def test_api_conditional_memory( assert arg_types["arg_bool"] == UserServiceArgType.BOOL assert arg_types["arg_float"] == UserServiceArgType.FLOAT - # Track state changes - states: dict[int, EntityState] = {} - states_future: asyncio.Future[None] = loop.create_future() - - def on_state(state: EntityState) -> None: - states[state.key] = state - # Check if we have initial states for connection sensors - if ( - client_connected.key in states - and last_client_info.key in states - and not states_future.done() - ): - states_future.set_result(None) - - client.subscribe_states(on_state) - - # Wait for initial states - await asyncio.wait_for(states_future, timeout=5.0) - - # Verify on_client_connected trigger fired - connected_state = states.get(client_connected.key) - assert connected_state is not None - assert connected_state.state is True, "Client should be connected" - - # Verify client info was captured - client_info_state = states.get(last_client_info.key) - assert client_info_state is not None - assert isinstance(client_info_state.state, str) - assert len(client_info_state.state) > 0, "Client info should not be empty" - - # Test simple service - service_future: asyncio.Future[None] = loop.create_future() - - def check_service_called(state: EntityState) -> None: - if state.key == service_called_sensor.key and state.state is True: - if not service_future.done(): - service_future.set_result(None) - - # Update callback to check for service execution - client.subscribe_states(check_service_called) - # Call simple service client.execute_service(simple_service, {}) - # Wait for service to execute - await asyncio.wait_for(service_future, timeout=5.0) - - # Test service with arguments - arg_future: asyncio.Future[None] = loop.create_future() - expected_float = 42.5 - - def check_arg_sensor(state: EntityState) -> None: - if ( - state.key == service_arg_sensor.key - and abs(state.state - expected_float) < 0.01 - ): - if not arg_future.done(): - arg_future.set_result(None) - - client.subscribe_states(check_arg_sensor) + # Wait for service log + await asyncio.wait_for(service_simple_future, timeout=5.0) # Call service with arguments client.execute_service( @@ -166,43 +100,12 @@ async def test_api_conditional_memory( "arg_string": "test_string", "arg_int": 123, "arg_bool": True, - "arg_float": expected_float, + "arg_float": 42.5, }, ) - # Wait for service with args to execute - await asyncio.wait_for(arg_future, timeout=5.0) + # Wait for service with args log + await asyncio.wait_for(service_args_future, timeout=5.0) - # After disconnecting first client, reconnect and verify triggers work - async with api_client_connected() as client2: - # Subscribe to states with new client - states2: dict[int, EntityState] = {} - states_ready_future: asyncio.Future[None] = loop.create_future() - - def on_state2(state: EntityState) -> None: - states2[state.key] = state - # Check if we have received both required states - if ( - client_connected.key in states2 - and client_disconnected_event.key in states2 - and not states_ready_future.done() - ): - states_ready_future.set_result(None) - - client2.subscribe_states(on_state2) - - # Wait for both connected and disconnected event states - await asyncio.wait_for(states_ready_future, timeout=5.0) - - # Verify client is connected again (on_client_connected fired) - assert states2[client_connected.key].state is True, ( - "Client should be reconnected" - ) - - # The client_disconnected_event should be ON from when we disconnected - # (it was set ON by on_client_disconnected trigger) - disconnected_state = states2.get(client_disconnected_event.key) - assert disconnected_state is not None - assert disconnected_state.state is True, ( - "Disconnect event should be ON from previous disconnect" - ) + # Client disconnected here, wait for disconnect log + await asyncio.wait_for(disconnected_future, timeout=5.0) diff --git a/tests/integration/test_api_vv_logging.py b/tests/integration/test_api_vv_logging.py index 19aab2001c..fcbdd341ae 100644 --- a/tests/integration/test_api_vv_logging.py +++ b/tests/integration/test_api_vv_logging.py @@ -5,7 +5,7 @@ from __future__ import annotations import asyncio from typing import Any -from aioesphomeapi import LogLevel +from aioesphomeapi import LogLevel, SensorInfo import pytest from .types import APIClientConnectedFactory, RunCompiledFunction @@ -63,7 +63,7 @@ async def test_api_vv_logging( entity_info, _ = await client.list_entities_services() # Count sensors - sensor_count = sum(1 for e in entity_info if hasattr(e, "unit_of_measurement")) + sensor_count = sum(1 for e in entity_info if isinstance(e, SensorInfo)) assert sensor_count >= 10, f"Expected at least 10 sensors, got {sensor_count}" # Wait for sensor updates to flow with VV logging active diff --git a/tests/integration/test_areas_and_devices.py b/tests/integration/test_areas_and_devices.py index 4ce55a30a7..4184255724 100644 --- a/tests/integration/test_areas_and_devices.py +++ b/tests/integration/test_areas_and_devices.py @@ -76,8 +76,8 @@ async def test_areas_and_devices( # Get entity list to verify device_id mapping entities = await client.list_entities_services() - # Collect sensor entities - sensor_entities = [e for e in entities[0] if hasattr(e, "device_id")] + # Collect sensor entities (all entities have device_id) + sensor_entities = entities[0] assert len(sensor_entities) >= 4, ( f"Expected at least 4 sensor entities, got {len(sensor_entities)}" ) diff --git a/tests/integration/test_batch_delay_zero_rapid_transitions.py b/tests/integration/test_batch_delay_zero_rapid_transitions.py new file mode 100644 index 0000000000..f17319dddf --- /dev/null +++ b/tests/integration/test_batch_delay_zero_rapid_transitions.py @@ -0,0 +1,58 @@ +"""Integration test for API batch_delay: 0 with rapid state transitions.""" + +from __future__ import annotations + +import asyncio +import time + +from aioesphomeapi import BinarySensorInfo, BinarySensorState, EntityState +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_batch_delay_zero_rapid_transitions( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that rapid binary sensor transitions are preserved with batch_delay: 0ms.""" + async with run_compiled(yaml_config), api_client_connected() as client: + # Track state changes + state_changes: list[tuple[bool, float]] = [] + + def on_state(state: EntityState) -> None: + """Track state changes with timestamps.""" + if isinstance(state, BinarySensorState): + state_changes.append((state.state, time.monotonic())) + + # Subscribe to state changes + client.subscribe_states(on_state) + + # Wait for entity info + entity_info, _ = await client.list_entities_services() + binary_sensors = [e for e in entity_info if isinstance(e, BinarySensorInfo)] + assert len(binary_sensors) == 1, "Expected 1 binary sensor" + + # Collect states for 2 seconds + await asyncio.sleep(2.1) + + # Count ON->OFF transitions + on_off_count = 0 + for i in range(1, len(state_changes)): + if state_changes[i - 1][0] and not state_changes[i][0]: # ON to OFF + on_off_count += 1 + + # With batch_delay: 0, we should capture rapid transitions + # The test timing can be variable in CI, so we're being conservative + # We mainly want to verify that we capture multiple rapid transitions + assert on_off_count >= 5, ( + f"Expected at least 5 ON->OFF transitions with batch_delay: 0ms, got {on_off_count}. " + "Rapid transitions may have been lost." + ) + + # Also verify that state changes are happening frequently + assert len(state_changes) >= 10, ( + f"Expected at least 10 state changes, got {len(state_changes)}" + ) diff --git a/tests/integration/test_device_id_in_state.py b/tests/integration/test_device_id_in_state.py new file mode 100644 index 0000000000..eaa91ec92e --- /dev/null +++ b/tests/integration/test_device_id_in_state.py @@ -0,0 +1,147 @@ +"""Integration test for device_id in entity state responses.""" + +from __future__ import annotations + +import asyncio + +from aioesphomeapi import BinarySensorState, EntityState, SensorState, TextSensorState +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_device_id_in_state( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that device_id is included in entity state responses.""" + async with run_compiled(yaml_config), api_client_connected() as client: + # Get device info to verify devices are configured + device_info = await client.device_info() + assert device_info is not None + + # Verify devices exist + devices = device_info.devices + assert len(devices) >= 3, f"Expected at least 3 devices, got {len(devices)}" + + # Get device IDs for verification + device_ids = {device.name: device.device_id for device in devices} + assert "Temperature Monitor" in device_ids + assert "Humidity Monitor" in device_ids + assert "Motion Sensor" in device_ids + + # Get entity list + entities = await client.list_entities_services() + all_entities = entities[0] + + # Create a mapping of entity key to expected device_id + entity_device_mapping: dict[int, int] = {} + + for entity in all_entities: + # All entities have name and key attributes + if entity.name == "Temperature": + entity_device_mapping[entity.key] = device_ids["Temperature Monitor"] + elif entity.name == "Humidity": + entity_device_mapping[entity.key] = device_ids["Humidity Monitor"] + elif entity.name == "Motion Detected": + entity_device_mapping[entity.key] = device_ids["Motion Sensor"] + elif entity.name == "Temperature Monitor Power": + entity_device_mapping[entity.key] = device_ids["Temperature Monitor"] + elif entity.name == "Temperature Status": + entity_device_mapping[entity.key] = device_ids["Temperature Monitor"] + elif entity.name == "Motion Light": + entity_device_mapping[entity.key] = device_ids["Motion Sensor"] + elif entity.name == "No Device Sensor": + # Entity without device_id should have device_id 0 + entity_device_mapping[entity.key] = 0 + + assert len(entity_device_mapping) >= 6, ( + f"Expected at least 6 mapped entities, got {len(entity_device_mapping)}" + ) + + # Subscribe to states + loop = asyncio.get_running_loop() + states: dict[int, EntityState] = {} + states_future: asyncio.Future[bool] = loop.create_future() + + def on_state(state: EntityState) -> None: + states[state.key] = state + # Check if we have states for all mapped entities + if len(states) >= len(entity_device_mapping) and not states_future.done(): + states_future.set_result(True) + + client.subscribe_states(on_state) + + # Wait for states + try: + await asyncio.wait_for(states_future, timeout=10.0) + except asyncio.TimeoutError: + pytest.fail( + f"Did not receive all entity states within 10 seconds. " + f"Received {len(states)} states, expected {len(entity_device_mapping)}" + ) + + # Verify each state has the correct device_id + verified_count = 0 + for key, expected_device_id in entity_device_mapping.items(): + if key in states: + state = states[key] + + assert state.device_id == expected_device_id, ( + f"State for key {key} has device_id {state.device_id}, " + f"expected {expected_device_id}" + ) + verified_count += 1 + + assert verified_count >= 6, ( + f"Only verified {verified_count} states, expected at least 6" + ) + + # Test specific state types to ensure device_id is present + # Find a sensor state with device_id + sensor_state = next( + ( + s + for s in states.values() + if isinstance(s, SensorState) + and isinstance(s.state, float) + and s.device_id != 0 + ), + None, + ) + assert sensor_state is not None, "No sensor state with device_id found" + assert sensor_state.device_id > 0, "Sensor state should have non-zero device_id" + + # Find a binary sensor state + binary_sensor_state = next( + (s for s in states.values() if isinstance(s, BinarySensorState)), + None, + ) + assert binary_sensor_state is not None, "No binary sensor state found" + assert binary_sensor_state.device_id > 0, ( + "Binary sensor state should have non-zero device_id" + ) + + # Find a text sensor state + text_sensor_state = next( + (s for s in states.values() if isinstance(s, TextSensorState)), + None, + ) + assert text_sensor_state is not None, "No text sensor state found" + assert text_sensor_state.device_id > 0, ( + "Text sensor state should have non-zero device_id" + ) + + # Verify the "No Device Sensor" has device_id = 0 + no_device_key = next( + (key for key, device_id in entity_device_mapping.items() if device_id == 0), + None, + ) + assert no_device_key is not None, "No entity mapped to device_id 0" + assert no_device_key in states, f"State for key {no_device_key} not found" + no_device_state = states[no_device_key] + assert no_device_state.device_id == 0, ( + f"Entity without device_id should have device_id=0, got {no_device_state.device_id}" + ) diff --git a/tests/integration/test_entity_icon.py b/tests/integration/test_entity_icon.py new file mode 100644 index 0000000000..aec7168165 --- /dev/null +++ b/tests/integration/test_entity_icon.py @@ -0,0 +1,91 @@ +"""Integration test for entity icons with USE_ENTITY_ICON feature.""" + +from __future__ import annotations + +import asyncio + +from aioesphomeapi import EntityState +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_entity_icon( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that entities with custom icons work correctly with USE_ENTITY_ICON.""" + # Write, compile and run the ESPHome device, then connect to API + async with run_compiled(yaml_config), api_client_connected() as client: + # Get all entities + entities = await client.list_entities_services() + + # Create a map of entity names to entity info + entity_map = {entity.name: entity for entity in entities[0]} + + # Test entities with icons + icon_test_cases = [ + # (entity_name, expected_icon) + ("Sensor With Icon", "mdi:temperature-celsius"), + ("Binary Sensor With Icon", "mdi:motion-sensor"), + ("Text Sensor With Icon", "mdi:text-box"), + ("Switch With Icon", "mdi:toggle-switch"), + ("Button With Icon", "mdi:gesture-tap-button"), + ("Number With Icon", "mdi:numeric"), + ("Select With Icon", "mdi:format-list-bulleted"), + ] + + # Test entities without icons (should have empty string) + no_icon_test_cases = [ + "Sensor Without Icon", + "Binary Sensor Without Icon", + ] + + # Verify entities with icons + for entity_name, expected_icon in icon_test_cases: + assert entity_name in entity_map, ( + f"Entity '{entity_name}' not found in API response" + ) + entity = entity_map[entity_name] + + # Check icon field + assert entity.icon == expected_icon, ( + f"{entity_name}: icon mismatch - " + f"expected '{expected_icon}', got '{entity.icon}'" + ) + + # Verify entities without icons + for entity_name in no_icon_test_cases: + assert entity_name in entity_map, ( + f"Entity '{entity_name}' not found in API response" + ) + entity = entity_map[entity_name] + + # Check icon field is empty + assert entity.icon == "", ( + f"{entity_name}: icon should be empty string for entities without icons, " + f"got '{entity.icon}'" + ) + + # Subscribe to states to ensure everything works normally + states: dict[int, EntityState] = {} + state_received = asyncio.Event() + + def on_state(state: EntityState) -> None: + states[state.key] = state + state_received.set() + + client.subscribe_states(on_state) + + # Wait for states + try: + await asyncio.wait_for(state_received.wait(), timeout=5.0) + except asyncio.TimeoutError: + pytest.fail("No states received within 5 seconds") + + # Verify we received states + assert len(states) > 0, ( + "No states received - entities may not be working correctly" + ) diff --git a/tests/integration/test_host_mode_empty_string_options.py b/tests/integration/test_host_mode_empty_string_options.py index d2df839a75..16399dcfb8 100644 --- a/tests/integration/test_host_mode_empty_string_options.py +++ b/tests/integration/test_host_mode_empty_string_options.py @@ -74,37 +74,41 @@ async def test_host_mode_empty_string_options( # If we got here without protobuf decoding errors, the fix is working # The bug would have caused "Invalid protobuf message" errors with trailing bytes - # Also verify we can interact with the select entities - # Subscribe to state changes + # Also verify we can receive state updates for select entities + # This ensures empty strings work properly in state messages too states: dict[int, EntityState] = {} - state_change_future: asyncio.Future[None] = loop.create_future() + states_received_future: asyncio.Future[None] = loop.create_future() + expected_select_keys = {empty_first.key, empty_middle.key, empty_last.key} + received_select_keys = set() def on_state(state: EntityState) -> None: """Track state changes.""" states[state.key] = state - # When we receive the state change for our select, resolve the future - if state.key == empty_first.key and not state_change_future.done(): - state_change_future.set_result(None) + # Track which select entities we've received states for + if state.key in expected_select_keys: + received_select_keys.add(state.key) + # Once we have all select states, we're done + if ( + received_select_keys == expected_select_keys + and not states_received_future.done() + ): + states_received_future.set_result(None) client.subscribe_states(on_state) - # Try setting a select to an empty string option - # This further tests that empty strings are handled correctly - client.select_command(empty_first.key, "") - - # Wait for state update with timeout + # Wait for initial states with timeout try: - await asyncio.wait_for(state_change_future, timeout=5.0) + await asyncio.wait_for(states_received_future, timeout=5.0) except asyncio.TimeoutError: pytest.fail( - "Did not receive state update after setting select to empty string" + f"Did not receive states for all select entities. " + f"Expected keys: {expected_select_keys}, Received: {received_select_keys}" ) - # Verify the state was set to empty string + # Verify we received states for all select entities assert empty_first.key in states - select_state = states[empty_first.key] - assert hasattr(select_state, "state") - assert select_state.state == "" + assert empty_middle.key in states + assert empty_last.key in states - # The test passes if no protobuf decoding errors occurred - # With the bug, we would have gotten "Invalid protobuf message" errors + # The main test is that we got here without protobuf errors + # The select entities with empty string options were properly encoded diff --git a/tests/integration/test_host_mode_entity_fields.py b/tests/integration/test_host_mode_entity_fields.py index cf3fa6916a..b9fa3e9746 100644 --- a/tests/integration/test_host_mode_entity_fields.py +++ b/tests/integration/test_host_mode_entity_fields.py @@ -25,8 +25,8 @@ async def test_host_mode_entity_fields( # Create a map of entity names to entity info entity_map = {} for entity in entities[0]: - if hasattr(entity, "name"): - entity_map[entity.name] = entity + # All entities should have a name attribute + entity_map[entity.name] = entity # Test entities that should be visible via API (non-internal) visible_test_cases = [ diff --git a/tests/integration/test_host_mode_fan_preset.py b/tests/integration/test_host_mode_fan_preset.py index 1d956a7290..d18b9f08ad 100644 --- a/tests/integration/test_host_mode_fan_preset.py +++ b/tests/integration/test_host_mode_fan_preset.py @@ -46,14 +46,22 @@ async def test_host_mode_fan_preset( # Subscribe to states states: dict[int, FanState] = {} state_event = asyncio.Event() + initial_states_received = set() def on_state(state: FanState) -> None: if isinstance(state, FanState): states[state.key] = state + initial_states_received.add(state.key) state_event.set() client.subscribe_states(on_state) + # Wait for initial states to be received for all fans + expected_fan_keys = {fan.key for fan in fans} + while initial_states_received != expected_fan_keys: + state_event.clear() + await asyncio.wait_for(state_event.wait(), timeout=2.0) + # Test 1: Turn on fan without speed or preset - should set speed to 100% state_event.clear() client.fan_command( diff --git a/tests/integration/test_host_mode_many_entities.py b/tests/integration/test_host_mode_many_entities.py index d5622e6fa4..19d1ee315f 100644 --- a/tests/integration/test_host_mode_many_entities.py +++ b/tests/integration/test_host_mode_many_entities.py @@ -4,7 +4,7 @@ from __future__ import annotations import asyncio -from aioesphomeapi import EntityState +from aioesphomeapi import EntityState, SensorState import pytest from .types import APIClientConnectedFactory, RunCompiledFunction @@ -22,36 +22,51 @@ async def test_host_mode_many_entities( async with run_compiled(yaml_config), api_client_connected() as client: # Subscribe to state changes states: dict[int, EntityState] = {} - entity_count_future: asyncio.Future[int] = loop.create_future() + sensor_count_future: asyncio.Future[int] = loop.create_future() def on_state(state: EntityState) -> None: states[state.key] = state - # When we have received states from a good number of entities, resolve the future - if len(states) >= 50 and not entity_count_future.done(): - entity_count_future.set_result(len(states)) + # Count sensor states specifically + sensor_states = [ + s + for s in states.values() + if isinstance(s, SensorState) and isinstance(s.state, float) + ] + # When we have received states from at least 50 sensors, resolve the future + if len(sensor_states) >= 50 and not sensor_count_future.done(): + sensor_count_future.set_result(len(sensor_states)) client.subscribe_states(on_state) - # Wait for states from at least 50 entities with timeout + # Wait for states from at least 50 sensors with timeout try: - entity_count = await asyncio.wait_for(entity_count_future, timeout=10.0) + sensor_count = await asyncio.wait_for(sensor_count_future, timeout=10.0) except asyncio.TimeoutError: + sensor_states = [ + s + for s in states.values() + if isinstance(s, SensorState) and isinstance(s.state, float) + ] pytest.fail( - f"Did not receive states from at least 50 entities within 10 seconds. " - f"Received {len(states)} states: {list(states.keys())}" + f"Did not receive states from at least 50 sensors within 10 seconds. " + f"Received {len(sensor_states)} sensor states out of {len(states)} total states" ) # Verify we received a good number of entity states - assert entity_count >= 50, f"Expected at least 50 entities, got {entity_count}" - assert len(states) >= 50, f"Expected at least 50 states, got {len(states)}" + assert len(states) >= 50, ( + f"Expected at least 50 total states, got {len(states)}" + ) - # Verify we have different entity types by checking some expected values + # Verify we have the expected sensor states sensor_states = [ s for s in states.values() - if hasattr(s, "state") and isinstance(s.state, float) + if isinstance(s, SensorState) and isinstance(s.state, float) ] + assert sensor_count >= 50, ( + f"Expected at least 50 sensor states, got {sensor_count}" + ) assert len(sensor_states) >= 50, ( f"Expected at least 50 sensor states, got {len(sensor_states)}" ) diff --git a/tests/integration/test_host_mode_sensor.py b/tests/integration/test_host_mode_sensor.py index 049f7db619..8c1e9f5d51 100644 --- a/tests/integration/test_host_mode_sensor.py +++ b/tests/integration/test_host_mode_sensor.py @@ -19,16 +19,17 @@ async def test_host_mode_with_sensor( ) -> None: """Test Host mode with a sensor component.""" # Write, compile and run the ESPHome device, then connect to API + loop = asyncio.get_running_loop() async with run_compiled(yaml_config), api_client_connected() as client: # Subscribe to state changes states: dict[int, EntityState] = {} - sensor_future: asyncio.Future[EntityState] = asyncio.Future() + sensor_future: asyncio.Future[EntityState] = loop.create_future() def on_state(state: EntityState) -> None: states[state.key] = state # If this is our sensor with value 42.0, resolve the future if ( - hasattr(state, "state") + isinstance(state, aioesphomeapi.SensorState) and state.state == 42.0 and not sensor_future.done() ): diff --git a/tests/integration/test_light_calls.py b/tests/integration/test_light_calls.py new file mode 100644 index 0000000000..1c56bbbf9e --- /dev/null +++ b/tests/integration/test_light_calls.py @@ -0,0 +1,190 @@ +"""Integration test for all light call combinations. + +Tests that LightCall handles all possible light operations correctly +including RGB, color temperature, effects, transitions, and flash. +""" + +import asyncio +from typing import Any + +from aioesphomeapi import LightState +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_light_calls( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test all possible LightCall operations and combinations.""" + async with run_compiled(yaml_config), api_client_connected() as client: + # Track state changes with futures + state_futures: dict[int, asyncio.Future[Any]] = {} + states: dict[int, Any] = {} + + def on_state(state: Any) -> None: + states[state.key] = state + if state.key in state_futures and not state_futures[state.key].done(): + state_futures[state.key].set_result(state) + + client.subscribe_states(on_state) + + # Get the light entities + entities = await client.list_entities_services() + lights = [e for e in entities[0] if e.object_id.startswith("test_")] + assert len(lights) >= 2 # Should have RGBCW and RGB lights + + rgbcw_light = next(light for light in lights if "RGBCW" in light.name) + rgb_light = next(light for light in lights if "RGB Light" in light.name) + + async def wait_for_state_change(key: int, timeout: float = 1.0) -> Any: + """Wait for a state change for the given entity key.""" + loop = asyncio.get_event_loop() + state_futures[key] = loop.create_future() + try: + return await asyncio.wait_for(state_futures[key], timeout) + finally: + state_futures.pop(key, None) + + # Test all individual parameters first + + # Test 1: state only + client.light_command(key=rgbcw_light.key, state=True) + state = await wait_for_state_change(rgbcw_light.key) + assert state.state is True + + # Test 2: brightness only + client.light_command(key=rgbcw_light.key, brightness=0.5) + state = await wait_for_state_change(rgbcw_light.key) + assert state.brightness == pytest.approx(0.5) + + # Test 3: color_brightness only + client.light_command(key=rgbcw_light.key, color_brightness=0.8) + state = await wait_for_state_change(rgbcw_light.key) + assert state.color_brightness == pytest.approx(0.8) + + # Test 4-7: RGB values must be set together via rgb parameter + client.light_command(key=rgbcw_light.key, rgb=(0.7, 0.3, 0.9)) + state = await wait_for_state_change(rgbcw_light.key) + assert state.red == pytest.approx(0.7, abs=0.1) + assert state.green == pytest.approx(0.3, abs=0.1) + assert state.blue == pytest.approx(0.9, abs=0.1) + + # Test 7: white value + client.light_command(key=rgbcw_light.key, white=0.6) + state = await wait_for_state_change(rgbcw_light.key) + # White might need more tolerance or might not be directly settable + if isinstance(state, LightState) and state.white is not None: + assert state.white == pytest.approx(0.6, abs=0.1) + + # Test 8: color_temperature only + client.light_command(key=rgbcw_light.key, color_temperature=300) + state = await wait_for_state_change(rgbcw_light.key) + assert state.color_temperature == pytest.approx(300) + + # Test 9: cold_white only + client.light_command(key=rgbcw_light.key, cold_white=0.8) + state = await wait_for_state_change(rgbcw_light.key) + assert state.cold_white == pytest.approx(0.8) + + # Test 10: warm_white only + client.light_command(key=rgbcw_light.key, warm_white=0.2) + state = await wait_for_state_change(rgbcw_light.key) + assert state.warm_white == pytest.approx(0.2) + + # Test 11: transition_length with state change + client.light_command(key=rgbcw_light.key, state=False, transition_length=0.1) + state = await wait_for_state_change(rgbcw_light.key) + assert state.state is False + + # Test 12: flash_length + client.light_command(key=rgbcw_light.key, state=True, flash_length=0.2) + state = await wait_for_state_change(rgbcw_light.key) + # Flash starts + assert state.state is True + # Wait for flash to end + state = await wait_for_state_change(rgbcw_light.key) + + # Test 13: effect only + # First ensure light is on + client.light_command(key=rgbcw_light.key, state=True) + state = await wait_for_state_change(rgbcw_light.key) + # Now set effect + client.light_command(key=rgbcw_light.key, effect="Random Effect") + state = await wait_for_state_change(rgbcw_light.key) + assert state.effect == "Random Effect" + + # Test 14: stop effect + client.light_command(key=rgbcw_light.key, effect="None") + state = await wait_for_state_change(rgbcw_light.key) + assert state.effect == "None" + + # Test 15: color_mode parameter + client.light_command( + key=rgbcw_light.key, state=True, color_mode=5 + ) # COLD_WARM_WHITE + state = await wait_for_state_change(rgbcw_light.key) + assert state.state is True + + # Now test common combinations + + # Test 16: RGB combination (set_rgb) - RGB values get normalized + client.light_command(key=rgbcw_light.key, rgb=(1.0, 0.0, 0.5)) + state = await wait_for_state_change(rgbcw_light.key) + # RGB values get normalized - in this case red is already 1.0 + assert state.red == pytest.approx(1.0, abs=0.1) + assert state.green == pytest.approx(0.0, abs=0.1) + assert state.blue == pytest.approx(0.5, abs=0.1) + + # Test 17: Multiple RGB changes to test transitions + client.light_command(key=rgbcw_light.key, rgb=(0.2, 0.8, 0.4)) + state = await wait_for_state_change(rgbcw_light.key) + # RGB values get normalized so green (highest) becomes 1.0 + # Expected: (0.2/0.8, 0.8/0.8, 0.4/0.8) = (0.25, 1.0, 0.5) + assert state.red == pytest.approx(0.25, abs=0.01) + assert state.green == pytest.approx(1.0, abs=0.01) + assert state.blue == pytest.approx(0.5, abs=0.01) + + # Test 18: State + brightness + transition + client.light_command( + key=rgbcw_light.key, state=True, brightness=0.7, transition_length=0.1 + ) + state = await wait_for_state_change(rgbcw_light.key) + assert state.state is True + assert state.brightness == pytest.approx(0.7) + + # Test 19: RGB + brightness + color_brightness + client.light_command( + key=rgb_light.key, + state=True, + brightness=0.8, + color_brightness=0.9, + rgb=(0.2, 0.4, 0.6), + ) + state = await wait_for_state_change(rgb_light.key) + assert state.state is True + assert state.brightness == pytest.approx(0.8) + + # Test 20: Color temp + cold/warm white + client.light_command( + key=rgbcw_light.key, color_temperature=250, cold_white=0.7, warm_white=0.3 + ) + state = await wait_for_state_change(rgbcw_light.key) + assert state.color_temperature == pytest.approx(250) + + # Test 21: Turn RGB light off + client.light_command(key=rgb_light.key, state=False) + state = await wait_for_state_change(rgb_light.key) + assert state.state is False + + # Final cleanup - turn all lights off + for light in lights: + client.light_command( + key=light.key, + state=False, + ) + state = await wait_for_state_change(light.key) + assert state.state is False diff --git a/tests/integration/test_scheduler_bulk_cleanup.py b/tests/integration/test_scheduler_bulk_cleanup.py new file mode 100644 index 0000000000..08ff293b84 --- /dev/null +++ b/tests/integration/test_scheduler_bulk_cleanup.py @@ -0,0 +1,122 @@ +"""Test that triggers the bulk cleanup path when to_remove_ > MAX_LOGICALLY_DELETED_ITEMS.""" + +import asyncio +from pathlib import Path +import re + +from aioesphomeapi import UserService +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_bulk_cleanup( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that bulk cleanup path is triggered when many items are cancelled.""" + + # Get the absolute path to the external components directory + external_components_path = str( + Path(__file__).parent / "fixtures" / "external_components" + ) + + # Replace the placeholder in the YAML config with the actual path + yaml_config = yaml_config.replace( + "EXTERNAL_COMPONENT_PATH", external_components_path + ) + + # Create a future to signal test completion + loop = asyncio.get_event_loop() + test_complete_future: asyncio.Future[None] = loop.create_future() + bulk_cleanup_triggered = False + cleanup_stats: dict[str, int] = { + "removed": 0, + "before": 0, + "after": 0, + } + post_cleanup_executed = 0 + + def on_log_line(line: str) -> None: + nonlocal bulk_cleanup_triggered, post_cleanup_executed + + # Look for logs indicating bulk cleanup was triggered + # The actual cleanup happens silently, so we track the cancel operations + if "Successfully cancelled" in line and "timeouts" in line: + match = re.search(r"Successfully cancelled (\d+) timeouts", line) + if match and int(match.group(1)) > 10: + bulk_cleanup_triggered = True + + # Track cleanup statistics + match = re.search(r"Bulk cleanup triggered: removed (\d+) items", line) + if match: + cleanup_stats["removed"] = int(match.group(1)) + + match = re.search(r"Items before cleanup: (\d+), after: (\d+)", line) + if match: + cleanup_stats["before"] = int(match.group(1)) + cleanup_stats["after"] = int(match.group(2)) + + # Track post-cleanup timeout executions + if "Post-cleanup timeout" in line and "executed correctly" in line: + match = re.search(r"Post-cleanup timeout (\d+) executed correctly", line) + if match: + post_cleanup_executed += 1 + + # Check for final test completion + if ( + "All post-cleanup timeouts completed - test finished" in line + and not test_complete_future.done() + ): + test_complete_future.set_result(None) + + async with ( + run_compiled(yaml_config, line_callback=on_log_line), + api_client_connected() as client, + ): + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "scheduler-bulk-cleanup" + + # List entities and services + _, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test service + trigger_bulk_cleanup_service: UserService | None = None + for service in services: + if service.name == "trigger_bulk_cleanup": + trigger_bulk_cleanup_service = service + break + + assert trigger_bulk_cleanup_service is not None, ( + "trigger_bulk_cleanup service not found" + ) + + # Execute the test + client.execute_service(trigger_bulk_cleanup_service, {}) + + # Wait for test completion + try: + await asyncio.wait_for(test_complete_future, timeout=10.0) + except asyncio.TimeoutError: + pytest.fail("Bulk cleanup test timed out") + + # Verify bulk cleanup was triggered + assert bulk_cleanup_triggered, ( + "Bulk cleanup path was not triggered - MAX_LOGICALLY_DELETED_ITEMS threshold not reached" + ) + + # Verify cleanup statistics + assert cleanup_stats["removed"] > 10, ( + f"Expected more than 10 items removed, got {cleanup_stats['removed']}" + ) + + # Verify scheduler still works after bulk cleanup + assert post_cleanup_executed == 5, ( + f"Expected 5 post-cleanup timeouts to execute, but {post_cleanup_executed} executed" + ) diff --git a/tests/integration/test_scheduler_defer_cancel.py b/tests/integration/test_scheduler_defer_cancel.py new file mode 100644 index 0000000000..923cf946c4 --- /dev/null +++ b/tests/integration/test_scheduler_defer_cancel.py @@ -0,0 +1,94 @@ +"""Test that defer() with the same name cancels previous defers.""" + +import asyncio + +from aioesphomeapi import EntityState, Event, EventInfo, UserService +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_defer_cancel( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that defer() with the same name cancels previous defers.""" + + async with run_compiled(yaml_config), api_client_connected() as client: + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "scheduler-defer-cancel" + + # List entities and services + entity_info, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test entities + test_complete_entity: EventInfo | None = None + test_result_entity: EventInfo | None = None + + for entity in entity_info: + if isinstance(entity, EventInfo): + if entity.object_id == "test_complete": + test_complete_entity = entity + elif entity.object_id == "test_result": + test_result_entity = entity + + assert test_complete_entity is not None, "test_complete event not found" + assert test_result_entity is not None, "test_result event not found" + + # Find our test service + test_defer_cancel_service: UserService | None = None + for service in services: + if service.name == "test_defer_cancel": + test_defer_cancel_service = service + + assert test_defer_cancel_service is not None, ( + "test_defer_cancel service not found" + ) + + # Get the event loop + loop = asyncio.get_running_loop() + + # Subscribe to states + test_complete_future: asyncio.Future[bool] = loop.create_future() + test_result_future: asyncio.Future[int] = loop.create_future() + + def on_state(state: EntityState) -> None: + if not isinstance(state, Event): + return + + if ( + state.key == test_complete_entity.key + and state.event_type == "test_finished" + and not test_complete_future.done() + ): + test_complete_future.set_result(True) + return + + if state.key == test_result_entity.key and not test_result_future.done(): + # Event type should be "defer_executed_X" where X is the defer number + if state.event_type.startswith("defer_executed_"): + defer_num = int(state.event_type.split("_")[-1]) + test_result_future.set_result(defer_num) + + client.subscribe_states(on_state) + + # Execute the test + client.execute_service(test_defer_cancel_service, {}) + + # Wait for test completion + try: + await asyncio.wait_for(test_complete_future, timeout=10.0) + executed_defer = await asyncio.wait_for(test_result_future, timeout=1.0) + except asyncio.TimeoutError: + pytest.fail("Test did not complete within timeout") + + # Verify that only defer 10 was executed + assert executed_defer == 10, ( + f"Expected defer 10 to execute, got {executed_defer}" + ) diff --git a/tests/integration/test_scheduler_defer_cancel_regular.py b/tests/integration/test_scheduler_defer_cancel_regular.py new file mode 100644 index 0000000000..57b7134feb --- /dev/null +++ b/tests/integration/test_scheduler_defer_cancel_regular.py @@ -0,0 +1,90 @@ +"""Test that a deferred timeout cancels a regular timeout with the same name.""" + +import asyncio + +from aioesphomeapi import UserService +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_defer_cancels_regular( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that set_timeout(name, 0) cancels a previously scheduled set_timeout(name, delay).""" + + # Create a future to signal test completion + loop = asyncio.get_running_loop() + test_complete_future: asyncio.Future[None] = loop.create_future() + + # Track log messages + log_messages: list[str] = [] + error_detected = False + + def on_log_line(line: str) -> None: + nonlocal error_detected + if "TEST" in line: + log_messages.append(line) + + if "ERROR: Regular timeout executed" in line: + error_detected = True + + if "Test complete" in line and not test_complete_future.done(): + test_complete_future.set_result(None) + + async with ( + run_compiled(yaml_config, line_callback=on_log_line), + api_client_connected() as client, + ): + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "scheduler-defer-cancel-regular" + + # List services + _, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test service + test_service: UserService | None = None + for service in services: + if service.name == "test_defer_cancels_regular": + test_service = service + break + + assert test_service is not None, "test_defer_cancels_regular service not found" + + # Execute the test + client.execute_service(test_service, {}) + + # Wait for test completion + try: + await asyncio.wait_for(test_complete_future, timeout=5.0) + except asyncio.TimeoutError: + pytest.fail(f"Test timed out. Log messages: {log_messages}") + + # Verify results + assert not error_detected, ( + f"Regular timeout should have been cancelled but it executed! Logs: {log_messages}" + ) + + # Verify the deferred timeout executed + assert any( + "SUCCESS: Deferred timeout executed" in msg for msg in log_messages + ), f"Deferred timeout should have executed. Logs: {log_messages}" + + # Verify the expected sequence of events + assert any( + "Starting defer cancels regular timeout test" in msg for msg in log_messages + ) + assert any( + "Scheduled regular timeout with 100ms delay" in msg for msg in log_messages + ) + assert any( + "Scheduled deferred timeout - should cancel regular timeout" in msg + for msg in log_messages + ) diff --git a/tests/integration/test_scheduler_defer_fifo_simple.py b/tests/integration/test_scheduler_defer_fifo_simple.py new file mode 100644 index 0000000000..eb4058fedd --- /dev/null +++ b/tests/integration/test_scheduler_defer_fifo_simple.py @@ -0,0 +1,117 @@ +"""Simple test that defer() maintains FIFO order.""" + +import asyncio + +from aioesphomeapi import EntityState, Event, EventInfo, UserService +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_defer_fifo_simple( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that defer() maintains FIFO order with a simple test.""" + + async with run_compiled(yaml_config), api_client_connected() as client: + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "scheduler-defer-fifo-simple" + + # List entities and services + entity_info, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test entities + test_complete_entity: EventInfo | None = None + test_result_entity: EventInfo | None = None + + for entity in entity_info: + if isinstance(entity, EventInfo): + if entity.object_id == "test_complete": + test_complete_entity = entity + elif entity.object_id == "test_result": + test_result_entity = entity + + assert test_complete_entity is not None, "test_complete event not found" + assert test_result_entity is not None, "test_result event not found" + + # Find our test services + test_set_timeout_service: UserService | None = None + test_defer_service: UserService | None = None + for service in services: + if service.name == "test_set_timeout": + test_set_timeout_service = service + elif service.name == "test_defer": + test_defer_service = service + + assert test_set_timeout_service is not None, ( + "test_set_timeout service not found" + ) + assert test_defer_service is not None, "test_defer service not found" + + # Get the event loop + loop = asyncio.get_running_loop() + + # Subscribe to states + # (events are delivered as EventStates through subscribe_states) + test_complete_future: asyncio.Future[bool] = loop.create_future() + test_result_future: asyncio.Future[bool] = loop.create_future() + + def on_state(state: EntityState) -> None: + if not isinstance(state, Event): + return + + if ( + state.key == test_complete_entity.key + and state.event_type == "test_finished" + and not test_complete_future.done() + ): + test_complete_future.set_result(True) + return + + if state.key == test_result_entity.key and not test_result_future.done(): + if state.event_type == "passed": + test_result_future.set_result(True) + elif state.event_type == "failed": + test_result_future.set_result(False) + + client.subscribe_states(on_state) + + # Test 1: Test set_timeout(0) + client.execute_service(test_set_timeout_service, {}) + + # Wait for first test completion + try: + await asyncio.wait_for(test_complete_future, timeout=5.0) + test1_passed = await asyncio.wait_for(test_result_future, timeout=1.0) + except asyncio.TimeoutError: + pytest.fail("Test set_timeout(0) did not complete within 5 seconds") + + assert test1_passed is True, ( + "set_timeout(0) FIFO test failed - items executed out of order" + ) + + # Reset futures for second test + test_complete_future = loop.create_future() + test_result_future = loop.create_future() + + # Test 2: Test defer() + client.execute_service(test_defer_service, {}) + + # Wait for second test completion + try: + await asyncio.wait_for(test_complete_future, timeout=5.0) + test2_passed = await asyncio.wait_for(test_result_future, timeout=1.0) + except asyncio.TimeoutError: + pytest.fail("Test defer() did not complete within 5 seconds") + + # Verify the test passed + assert test2_passed is True, ( + "defer() FIFO test failed - items executed out of order" + ) diff --git a/tests/integration/test_scheduler_defer_stress.py b/tests/integration/test_scheduler_defer_stress.py new file mode 100644 index 0000000000..d546b7132f --- /dev/null +++ b/tests/integration/test_scheduler_defer_stress.py @@ -0,0 +1,137 @@ +"""Stress test for defer() thread safety with multiple threads.""" + +import asyncio +from pathlib import Path +import re + +from aioesphomeapi import UserService +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_defer_stress( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that defer() doesn't crash when called rapidly from multiple threads.""" + + # Get the absolute path to the external components directory + external_components_path = str( + Path(__file__).parent / "fixtures" / "external_components" + ) + + # Replace the placeholder in the YAML config with the actual path + yaml_config = yaml_config.replace( + "EXTERNAL_COMPONENT_PATH", external_components_path + ) + + # Create a future to signal test completion + loop = asyncio.get_event_loop() + test_complete_future: asyncio.Future[None] = loop.create_future() + + # Track executed defers and their order + executed_defers: set[int] = set() + thread_executions: dict[ + int, list[int] + ] = {} # thread_id -> list of indices in execution order + fifo_violations: list[str] = [] + + def on_log_line(line: str) -> None: + # Track all executed defers with thread and index info + match = re.search(r"Executed defer (\d+) \(thread (\d+), index (\d+)\)", line) + if not match: + return + + defer_id = int(match.group(1)) + thread_id = int(match.group(2)) + index = int(match.group(3)) + + executed_defers.add(defer_id) + + # Track execution order per thread + if thread_id not in thread_executions: + thread_executions[thread_id] = [] + + # Check FIFO ordering within thread + if thread_executions[thread_id] and thread_executions[thread_id][-1] >= index: + fifo_violations.append( + f"Thread {thread_id}: index {index} executed after " + f"{thread_executions[thread_id][-1]}" + ) + + thread_executions[thread_id].append(index) + + # Check if we've executed all 1000 defers (0-999) + if len(executed_defers) == 1000 and not test_complete_future.done(): + test_complete_future.set_result(None) + + async with ( + run_compiled(yaml_config, line_callback=on_log_line), + api_client_connected() as client, + ): + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "scheduler-defer-stress-test" + + # List entities and services + entity_info, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test service + run_stress_test_service: UserService | None = None + for service in services: + if service.name == "run_stress_test": + run_stress_test_service = service + break + + assert run_stress_test_service is not None, "run_stress_test service not found" + + # Call the run_stress_test service to start the test + client.execute_service(run_stress_test_service, {}) + + # Wait for all defers to execute (should be quick) + try: + await asyncio.wait_for(test_complete_future, timeout=5.0) + except asyncio.TimeoutError: + # Report how many we got + pytest.fail( + f"Stress test timed out. Only {len(executed_defers)} of " + f"1000 defers executed. Missing IDs: " + f"{sorted(set(range(1000)) - executed_defers)[:10]}..." + ) + + # Verify all defers executed + assert len(executed_defers) == 1000, ( + f"Expected 1000 defers, got {len(executed_defers)}" + ) + + # Verify we have all IDs from 0-999 + expected_ids = set(range(1000)) + missing_ids = expected_ids - executed_defers + assert not missing_ids, f"Missing defer IDs: {sorted(missing_ids)}" + + # Verify FIFO ordering was maintained within each thread + assert not fifo_violations, "FIFO ordering violations detected:\n" + "\n".join( + fifo_violations[:10] + ) + + # Verify each thread executed all its defers in order + for thread_id, indices in thread_executions.items(): + assert len(indices) == 100, ( + f"Thread {thread_id} executed {len(indices)} defers, expected 100" + ) + # Indices should be 0-99 in ascending order + assert indices == list(range(100)), ( + f"Thread {thread_id} executed indices out of order: {indices[:10]}..." + ) + + # If we got here without crashing and with proper ordering, the test passed + assert True, ( + "Test completed successfully - all 1000 defers executed with " + "FIFO ordering preserved" + ) diff --git a/tests/integration/test_scheduler_heap_stress.py b/tests/integration/test_scheduler_heap_stress.py new file mode 100644 index 0000000000..3c757bfc9d --- /dev/null +++ b/tests/integration/test_scheduler_heap_stress.py @@ -0,0 +1,140 @@ +"""Stress test for heap scheduler thread safety with multiple threads.""" + +import asyncio +from pathlib import Path +import re + +from aioesphomeapi import UserService +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_heap_stress( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that set_timeout/set_interval doesn't crash when called rapidly from multiple threads.""" + + # Get the absolute path to the external components directory + external_components_path = str( + Path(__file__).parent / "fixtures" / "external_components" + ) + + # Replace the placeholder in the YAML config with the actual path + yaml_config = yaml_config.replace( + "EXTERNAL_COMPONENT_PATH", external_components_path + ) + + # Create a future to signal test completion + loop = asyncio.get_running_loop() + test_complete_future: asyncio.Future[None] = loop.create_future() + + # Track executed timeouts/intervals and their order + executed_callbacks: set[int] = set() + thread_executions: dict[ + int, list[int] + ] = {} # thread_id -> list of indices in execution order + callback_types: dict[int, str] = {} # callback_id -> "timeout" or "interval" + + def on_log_line(line: str) -> None: + # Track all executed callbacks with thread and index info + match = re.search( + r"Executed (timeout|interval) (\d+) \(thread (\d+), index (\d+)\)", line + ) + if not match: + # Also check for the completion message + if "All threads finished" in line and "Created 1000 callbacks" in line: + # Give scheduler some time to execute callbacks + pass + return + + callback_type = match.group(1) + callback_id = int(match.group(2)) + thread_id = int(match.group(3)) + index = int(match.group(4)) + + # Only count each callback ID once (intervals might fire multiple times) + if callback_id not in executed_callbacks: + executed_callbacks.add(callback_id) + callback_types[callback_id] = callback_type + + # Track execution order per thread + if thread_id not in thread_executions: + thread_executions[thread_id] = [] + + # Only append if this is a new execution for this thread + if index not in thread_executions[thread_id]: + thread_executions[thread_id].append(index) + + # Check if we've executed all 1000 callbacks (0-999) + if len(executed_callbacks) >= 1000 and not test_complete_future.done(): + test_complete_future.set_result(None) + + async with ( + run_compiled(yaml_config, line_callback=on_log_line), + api_client_connected() as client, + ): + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "scheduler-heap-stress-test" + + # List entities and services + _, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test service + run_stress_test_service: UserService | None = None + for service in services: + if service.name == "run_heap_stress_test": + run_stress_test_service = service + break + + assert run_stress_test_service is not None, ( + "run_heap_stress_test service not found" + ) + + # Call the run_heap_stress_test service to start the test + client.execute_service(run_stress_test_service, {}) + + # Wait for all callbacks to execute (should be quick, but give more time for scheduling) + try: + await asyncio.wait_for(test_complete_future, timeout=60.0) + except asyncio.TimeoutError: + # Report how many we got + pytest.fail( + f"Stress test timed out. Only {len(executed_callbacks)} of " + f"1000 callbacks executed. Missing IDs: " + f"{sorted(set(range(1000)) - executed_callbacks)[:10]}..." + ) + + # Verify all callbacks executed + assert len(executed_callbacks) == 1000, ( + f"Expected 1000 callbacks, got {len(executed_callbacks)}" + ) + + # Verify we have all IDs from 0-999 + expected_ids = set(range(1000)) + missing_ids = expected_ids - executed_callbacks + assert not missing_ids, f"Missing callback IDs: {sorted(missing_ids)}" + + # Verify we have a mix of timeouts and intervals + timeout_count = sum(1 for t in callback_types.values() if t == "timeout") + interval_count = sum(1 for t in callback_types.values() if t == "interval") + assert timeout_count > 0, "No timeouts were executed" + assert interval_count > 0, "No intervals were executed" + + # Verify each thread executed callbacks + for thread_id, indices in thread_executions.items(): + assert len(indices) == 100, ( + f"Thread {thread_id} executed {len(indices)} callbacks, expected 100" + ) + # Total should be 1000 callbacks + total_callbacks = timeout_count + interval_count + assert total_callbacks == 1000, ( + f"Expected 1000 total callbacks but got {total_callbacks}" + ) diff --git a/tests/integration/test_scheduler_rapid_cancellation.py b/tests/integration/test_scheduler_rapid_cancellation.py new file mode 100644 index 0000000000..90577f36f1 --- /dev/null +++ b/tests/integration/test_scheduler_rapid_cancellation.py @@ -0,0 +1,142 @@ +"""Rapid cancellation test - schedule and immediately cancel timeouts with string names.""" + +import asyncio +from pathlib import Path +import re + +from aioesphomeapi import UserService +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_rapid_cancellation( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test rapid schedule/cancel cycles that might expose race conditions.""" + + # Get the absolute path to the external components directory + external_components_path = str( + Path(__file__).parent / "fixtures" / "external_components" + ) + + # Replace the placeholder in the YAML config with the actual path + yaml_config = yaml_config.replace( + "EXTERNAL_COMPONENT_PATH", external_components_path + ) + + # Create a future to signal test completion + loop = asyncio.get_running_loop() + test_complete_future: asyncio.Future[None] = loop.create_future() + + # Track test progress + test_stats = { + "log_count": 0, + "errors": [], + "summary_scheduled": None, + "final_scheduled": 0, + "final_executed": 0, + "final_implicit_cancellations": 0, + } + + def on_log_line(line: str) -> None: + # Count log lines + test_stats["log_count"] += 1 + + # Check for errors (only ERROR level, not WARN) + if "ERROR" in line: + test_stats["errors"].append(line) + + # Parse summary statistics + if "All threads completed. Scheduled:" in line: + # Extract the scheduled count from the summary + if match := re.search(r"Scheduled: (\d+)", line): + test_stats["summary_scheduled"] = int(match.group(1)) + elif "Total scheduled:" in line: + if match := re.search(r"Total scheduled: (\d+)", line): + test_stats["final_scheduled"] = int(match.group(1)) + elif "Total executed:" in line: + if match := re.search(r"Total executed: (\d+)", line): + test_stats["final_executed"] = int(match.group(1)) + elif "Implicit cancellations (replaced):" in line: + if match := re.search(r"Implicit cancellations \(replaced\): (\d+)", line): + test_stats["final_implicit_cancellations"] = int(match.group(1)) + + # Check for crash indicators + if any( + indicator in line.lower() + for indicator in ["segfault", "abort", "assertion", "heap corruption"] + ): + if not test_complete_future.done(): + test_complete_future.set_exception(Exception(f"Crash detected: {line}")) + return + + # Check for completion - wait for final message after all stats are logged + if ( + "Test finished - all statistics reported" in line + and not test_complete_future.done() + ): + test_complete_future.set_result(None) + + async with ( + run_compiled(yaml_config, line_callback=on_log_line), + api_client_connected() as client, + ): + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "sched-rapid-cancel-test" + + # List entities and services + _, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test service + run_test_service: UserService | None = None + for service in services: + if service.name == "run_rapid_cancellation_test": + run_test_service = service + break + + assert run_test_service is not None, ( + "run_rapid_cancellation_test service not found" + ) + + # Call the service to start the test + client.execute_service(run_test_service, {}) + + # Wait for test to complete with timeout + try: + await asyncio.wait_for(test_complete_future, timeout=10.0) + except asyncio.TimeoutError: + pytest.fail(f"Test timed out. Stats: {test_stats}") + + # Check for any errors + assert len(test_stats["errors"]) == 0, ( + f"Errors detected: {test_stats['errors']}" + ) + + # Check that we received log messages + assert test_stats["log_count"] > 0, "No log messages received" + + # Check the summary line to verify all threads scheduled their operations + assert test_stats["summary_scheduled"] == 400, ( + f"Expected summary to show 400 scheduled operations but got {test_stats['summary_scheduled']}" + ) + + # Check final statistics + assert test_stats["final_scheduled"] == 400, ( + f"Expected final stats to show 400 scheduled but got {test_stats['final_scheduled']}" + ) + + assert test_stats["final_executed"] == 10, ( + f"Expected final stats to show 10 executed but got {test_stats['final_executed']}" + ) + + assert test_stats["final_implicit_cancellations"] == 390, ( + f"Expected final stats to show 390 implicit cancellations but got {test_stats['final_implicit_cancellations']}" + ) diff --git a/tests/integration/test_scheduler_recursive_timeout.py b/tests/integration/test_scheduler_recursive_timeout.py new file mode 100644 index 0000000000..c015978e15 --- /dev/null +++ b/tests/integration/test_scheduler_recursive_timeout.py @@ -0,0 +1,101 @@ +"""Test for recursive timeout scheduling - scheduling timeouts from within timeout callbacks.""" + +import asyncio +from pathlib import Path + +from aioesphomeapi import UserService +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_recursive_timeout( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that scheduling timeouts from within timeout callbacks works correctly.""" + + # Get the absolute path to the external components directory + external_components_path = str( + Path(__file__).parent / "fixtures" / "external_components" + ) + + # Replace the placeholder in the YAML config with the actual path + yaml_config = yaml_config.replace( + "EXTERNAL_COMPONENT_PATH", external_components_path + ) + + # Create a future to signal test completion + loop = asyncio.get_running_loop() + test_complete_future: asyncio.Future[None] = loop.create_future() + + # Track execution sequence + execution_sequence: list[str] = [] + expected_sequence = [ + "initial_timeout", + "nested_timeout_1", + "nested_timeout_2", + "test_complete", + ] + + def on_log_line(line: str) -> None: + # Track execution sequence + if "Executing initial timeout" in line: + execution_sequence.append("initial_timeout") + elif "Executing nested timeout 1" in line: + execution_sequence.append("nested_timeout_1") + elif "Executing nested timeout 2" in line: + execution_sequence.append("nested_timeout_2") + elif "Recursive timeout test complete" in line: + execution_sequence.append("test_complete") + if not test_complete_future.done(): + test_complete_future.set_result(None) + + async with ( + run_compiled(yaml_config, line_callback=on_log_line), + api_client_connected() as client, + ): + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "sched-recursive-timeout" + + # List entities and services + _, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test service + run_test_service: UserService | None = None + for service in services: + if service.name == "run_recursive_timeout_test": + run_test_service = service + break + + assert run_test_service is not None, ( + "run_recursive_timeout_test service not found" + ) + + # Call the service to start the test + client.execute_service(run_test_service, {}) + + # Wait for test to complete + try: + await asyncio.wait_for(test_complete_future, timeout=10.0) + except asyncio.TimeoutError: + pytest.fail( + f"Recursive timeout test timed out. Got sequence: {execution_sequence}" + ) + + # Verify execution sequence + assert execution_sequence == expected_sequence, ( + f"Execution sequence mismatch. Expected {expected_sequence}, " + f"got {execution_sequence}" + ) + + # Verify we got exactly 4 events (Initial + Level 1 + Level 2 + Complete) + assert len(execution_sequence) == 4, ( + f"Expected 4 events but got {len(execution_sequence)}" + ) diff --git a/tests/integration/test_scheduler_simultaneous_callbacks.py b/tests/integration/test_scheduler_simultaneous_callbacks.py new file mode 100644 index 0000000000..f5120ce4ce --- /dev/null +++ b/tests/integration/test_scheduler_simultaneous_callbacks.py @@ -0,0 +1,123 @@ +"""Simultaneous callbacks test - schedule many callbacks for the same time from multiple threads.""" + +import asyncio +from pathlib import Path +import re + +from aioesphomeapi import UserService +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_simultaneous_callbacks( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test scheduling many callbacks for the exact same time from multiple threads.""" + + # Get the absolute path to the external components directory + external_components_path = str( + Path(__file__).parent / "fixtures" / "external_components" + ) + + # Replace the placeholder in the YAML config with the actual path + yaml_config = yaml_config.replace( + "EXTERNAL_COMPONENT_PATH", external_components_path + ) + + # Create a future to signal test completion + loop = asyncio.get_running_loop() + test_complete_future: asyncio.Future[None] = loop.create_future() + + # Track test progress + test_stats = { + "scheduled": 0, + "executed": 0, + "expected": 1000, # 10 threads * 100 callbacks + "errors": [], + } + + def on_log_line(line: str) -> None: + # Track operations + if "Scheduled callback" in line: + test_stats["scheduled"] += 1 + elif "Callback executed" in line: + test_stats["executed"] += 1 + elif "ERROR" in line: + test_stats["errors"].append(line) + + # Check for crash indicators + if any( + indicator in line.lower() + for indicator in ["segfault", "abort", "assertion", "heap corruption"] + ): + if not test_complete_future.done(): + test_complete_future.set_exception(Exception(f"Crash detected: {line}")) + return + + # Check for completion with final count + if "Final executed count:" in line: + # Extract number from log line like: "[07:59:47][I][simultaneous_callbacks:093]: Simultaneous callbacks test complete. Final executed count: 1000" + match = re.search(r"Final executed count:\s*(\d+)", line) + if match: + test_stats["final_count"] = int(match.group(1)) + + # Check for completion + if ( + "Simultaneous callbacks test complete" in line + and not test_complete_future.done() + ): + test_complete_future.set_result(None) + + async with ( + run_compiled(yaml_config, line_callback=on_log_line), + api_client_connected() as client, + ): + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "sched-simul-callbacks-test" + + # List entities and services + _, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test service + run_test_service: UserService | None = None + for service in services: + if service.name == "run_simultaneous_callbacks_test": + run_test_service = service + break + + assert run_test_service is not None, ( + "run_simultaneous_callbacks_test service not found" + ) + + # Call the service to start the test + client.execute_service(run_test_service, {}) + + # Wait for test to complete + try: + await asyncio.wait_for(test_complete_future, timeout=30.0) + except asyncio.TimeoutError: + pytest.fail(f"Simultaneous callbacks test timed out. Stats: {test_stats}") + + # Check for any errors + assert len(test_stats["errors"]) == 0, ( + f"Errors detected: {test_stats['errors']}" + ) + + # Verify all callbacks executed using the final count from C++ + final_count = test_stats.get("final_count", 0) + assert final_count == test_stats["expected"], ( + f"Expected {test_stats['expected']} callbacks, but only {final_count} executed" + ) + + # The final_count is the authoritative count from the C++ component + assert final_count == 1000, ( + f"Expected 1000 executed callbacks but got {final_count}" + ) diff --git a/tests/integration/test_scheduler_string_lifetime.py b/tests/integration/test_scheduler_string_lifetime.py new file mode 100644 index 0000000000..4d77abd954 --- /dev/null +++ b/tests/integration/test_scheduler_string_lifetime.py @@ -0,0 +1,169 @@ +"""String lifetime test - verify scheduler handles string destruction correctly.""" + +import asyncio +from pathlib import Path +import re + +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_string_lifetime( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that scheduler correctly handles string lifetimes when strings go out of scope.""" + + # Get the absolute path to the external components directory + external_components_path = str( + Path(__file__).parent / "fixtures" / "external_components" + ) + + # Replace the placeholder in the YAML config with the actual path + yaml_config = yaml_config.replace( + "EXTERNAL_COMPONENT_PATH", external_components_path + ) + + # Create events for synchronization + test1_complete = asyncio.Event() + test2_complete = asyncio.Event() + test3_complete = asyncio.Event() + test4_complete = asyncio.Event() + test5_complete = asyncio.Event() + all_tests_complete = asyncio.Event() + + # Track test progress + test_stats = { + "tests_passed": 0, + "tests_failed": 0, + "errors": [], + "current_test": None, + "test_callbacks_executed": {}, + } + + def on_log_line(line: str) -> None: + # Track test-specific events + if "Test 1 complete" in line: + test1_complete.set() + elif "Test 2 complete" in line: + test2_complete.set() + elif "Test 3 complete" in line: + test3_complete.set() + elif "Test 4 complete" in line: + test4_complete.set() + elif "Test 5 complete" in line: + test5_complete.set() + + # Track individual callback executions + callback_match = re.search(r"Callback '(.+?)' executed", line) + if callback_match: + callback_name = callback_match.group(1) + test_stats["test_callbacks_executed"][callback_name] = True + + # Track test results from the C++ test output + if "Tests passed:" in line and "string_lifetime" in line: + # Extract the number from "Tests passed: 32" + match = re.search(r"Tests passed:\s*(\d+)", line) + if match: + test_stats["tests_passed"] = int(match.group(1)) + elif "Tests failed:" in line and "string_lifetime" in line: + match = re.search(r"Tests failed:\s*(\d+)", line) + if match: + test_stats["tests_failed"] = int(match.group(1)) + elif "ERROR" in line and "string_lifetime" in line: + test_stats["errors"].append(line) + + # Check for memory corruption indicators + if any( + indicator in line.lower() + for indicator in [ + "use after free", + "heap corruption", + "segfault", + "abort", + "assertion", + "sanitizer", + "bad memory", + "invalid pointer", + ] + ): + pytest.fail(f"Memory corruption detected: {line}") + + # Check for completion + if "String lifetime tests complete" in line: + all_tests_complete.set() + + async with ( + run_compiled(yaml_config, line_callback=on_log_line), + api_client_connected() as client, + ): + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "scheduler-string-lifetime-test" + + # List entities and services + _, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test services + test_services = {} + for service in services: + if service.name == "run_test1": + test_services["test1"] = service + elif service.name == "run_test2": + test_services["test2"] = service + elif service.name == "run_test3": + test_services["test3"] = service + elif service.name == "run_test4": + test_services["test4"] = service + elif service.name == "run_test5": + test_services["test5"] = service + elif service.name == "run_final_check": + test_services["final"] = service + + # Ensure all services are found + required_services = ["test1", "test2", "test3", "test4", "test5", "final"] + for service_name in required_services: + assert service_name in test_services, f"{service_name} service not found" + + # Run tests sequentially, waiting for each to complete + try: + # Test 1 + client.execute_service(test_services["test1"], {}) + await asyncio.wait_for(test1_complete.wait(), timeout=5.0) + + # Test 2 + client.execute_service(test_services["test2"], {}) + await asyncio.wait_for(test2_complete.wait(), timeout=5.0) + + # Test 3 + client.execute_service(test_services["test3"], {}) + await asyncio.wait_for(test3_complete.wait(), timeout=5.0) + + # Test 4 + client.execute_service(test_services["test4"], {}) + await asyncio.wait_for(test4_complete.wait(), timeout=5.0) + + # Test 5 + client.execute_service(test_services["test5"], {}) + await asyncio.wait_for(test5_complete.wait(), timeout=5.0) + + # Final check + client.execute_service(test_services["final"], {}) + await asyncio.wait_for(all_tests_complete.wait(), timeout=5.0) + + except asyncio.TimeoutError: + pytest.fail(f"String lifetime test timed out. Stats: {test_stats}") + + # Check for any errors + assert test_stats["tests_failed"] == 0, f"Tests failed: {test_stats['errors']}" + + # Verify we had the expected number of passing tests + assert test_stats["tests_passed"] == 30, ( + f"Expected exactly 30 tests to pass, but got {test_stats['tests_passed']}" + ) diff --git a/tests/integration/test_scheduler_string_name_stress.py b/tests/integration/test_scheduler_string_name_stress.py new file mode 100644 index 0000000000..3045842223 --- /dev/null +++ b/tests/integration/test_scheduler_string_name_stress.py @@ -0,0 +1,116 @@ +"""Stress test for heap scheduler with std::string names from multiple threads.""" + +import asyncio +from pathlib import Path +import re + +from aioesphomeapi import UserService +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_scheduler_string_name_stress( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test that set_timeout/set_interval with std::string names doesn't crash when called from multiple threads.""" + + # Get the absolute path to the external components directory + external_components_path = str( + Path(__file__).parent / "fixtures" / "external_components" + ) + + # Replace the placeholder in the YAML config with the actual path + yaml_config = yaml_config.replace( + "EXTERNAL_COMPONENT_PATH", external_components_path + ) + + # Create a future to signal test completion + loop = asyncio.get_running_loop() + test_complete_future: asyncio.Future[None] = loop.create_future() + + # Track executed callbacks and any crashes + executed_callbacks: set[int] = set() + error_messages: list[str] = [] + + def on_log_line(line: str) -> None: + # Check for crash indicators + if any( + indicator in line.lower() + for indicator in [ + "segfault", + "abort", + "assertion", + "heap corruption", + "use after free", + ] + ): + error_messages.append(line) + if not test_complete_future.done(): + test_complete_future.set_exception(Exception(f"Crash detected: {line}")) + return + + # Track executed callbacks + match = re.search(r"Executed string-named callback (\d+)", line) + if match: + callback_id = int(match.group(1)) + executed_callbacks.add(callback_id) + + # Check for completion + if ( + "String name stress test complete" in line + and not test_complete_future.done() + ): + test_complete_future.set_result(None) + + async with ( + run_compiled(yaml_config, line_callback=on_log_line), + api_client_connected() as client, + ): + # Verify we can connect + device_info = await client.device_info() + assert device_info is not None + assert device_info.name == "sched-string-name-stress" + + # List entities and services + _, services = await asyncio.wait_for( + client.list_entities_services(), timeout=5.0 + ) + + # Find our test service + run_stress_test_service: UserService | None = None + for service in services: + if service.name == "run_string_name_stress_test": + run_stress_test_service = service + break + + assert run_stress_test_service is not None, ( + "run_string_name_stress_test service not found" + ) + + # Call the service to start the test + client.execute_service(run_stress_test_service, {}) + + # Wait for test to complete or crash + try: + await asyncio.wait_for(test_complete_future, timeout=30.0) + except asyncio.TimeoutError: + pytest.fail( + f"String name stress test timed out. Executed {len(executed_callbacks)} callbacks. " + f"This might indicate a deadlock." + ) + + # Verify no errors occurred (crashes already handled by exception) + assert not error_messages, f"Errors detected during test: {error_messages}" + + # Verify we executed all 1000 callbacks (10 threads × 100 callbacks each) + assert len(executed_callbacks) == 1000, ( + f"Expected 1000 callbacks but got {len(executed_callbacks)}" + ) + + # Verify each callback ID was executed exactly once + for i in range(1000): + assert i in executed_callbacks, f"Callback {i} was not executed" diff --git a/tests/integration/test_scheduler_string_test.py b/tests/integration/test_scheduler_string_test.py index b5ca07f9db..f3a36b2db7 100644 --- a/tests/integration/test_scheduler_string_test.py +++ b/tests/integration/test_scheduler_string_test.py @@ -26,8 +26,11 @@ async def test_scheduler_string_test( static_interval_cancelled = asyncio.Event() empty_string_timeout_fired = asyncio.Event() static_timeout_cancelled = asyncio.Event() + static_defer_1_fired = asyncio.Event() + static_defer_2_fired = asyncio.Event() dynamic_timeout_fired = asyncio.Event() dynamic_interval_fired = asyncio.Event() + dynamic_defer_fired = asyncio.Event() cancel_test_done = asyncio.Event() final_results_logged = asyncio.Event() @@ -72,6 +75,15 @@ async def test_scheduler_string_test( elif "Cancelled static timeout using const char*" in clean_line: static_timeout_cancelled.set() + # Check for static defer tests + elif "Static defer 1 fired" in clean_line: + static_defer_1_fired.set() + timeout_count += 1 + + elif "Static defer 2 fired" in clean_line: + static_defer_2_fired.set() + timeout_count += 1 + # Check for dynamic string tests elif "Dynamic timeout fired" in clean_line: dynamic_timeout_fired.set() @@ -81,6 +93,11 @@ async def test_scheduler_string_test( dynamic_interval_count += 1 dynamic_interval_fired.set() + # Check for dynamic defer test + elif "Dynamic defer fired" in clean_line: + dynamic_defer_fired.set() + timeout_count += 1 + # Check for cancel test elif "Cancelled timeout using different string object" in clean_line: cancel_test_done.set() @@ -133,6 +150,17 @@ async def test_scheduler_string_test( "Static timeout should have been cancelled" ) + # Wait for static defer tests + try: + await asyncio.wait_for(static_defer_1_fired.wait(), timeout=0.5) + except asyncio.TimeoutError: + pytest.fail("Static defer 1 did not fire within 0.5 seconds") + + try: + await asyncio.wait_for(static_defer_2_fired.wait(), timeout=0.5) + except asyncio.TimeoutError: + pytest.fail("Static defer 2 did not fire within 0.5 seconds") + # Wait for dynamic string tests try: await asyncio.wait_for(dynamic_timeout_fired.wait(), timeout=1.0) @@ -144,6 +172,12 @@ async def test_scheduler_string_test( except asyncio.TimeoutError: pytest.fail("Dynamic interval did not fire within 1.5 seconds") + # Wait for dynamic defer test + try: + await asyncio.wait_for(dynamic_defer_fired.wait(), timeout=1.0) + except asyncio.TimeoutError: + pytest.fail("Dynamic defer did not fire within 1 second") + # Wait for cancel test try: await asyncio.wait_for(cancel_test_done.wait(), timeout=1.0) @@ -157,7 +191,9 @@ async def test_scheduler_string_test( pytest.fail("Final results were not logged within 4 seconds") # Verify results - assert timeout_count >= 3, f"Expected at least 3 timeouts, got {timeout_count}" + assert timeout_count >= 6, ( + f"Expected at least 6 timeouts (including defers), got {timeout_count}" + ) assert interval_count >= 3, ( f"Expected at least 3 interval fires, got {interval_count}" ) diff --git a/tests/unit_tests/test_config_helpers.py b/tests/unit_tests/test_config_helpers.py new file mode 100644 index 0000000000..1c850e3759 --- /dev/null +++ b/tests/unit_tests/test_config_helpers.py @@ -0,0 +1,135 @@ +"""Unit tests for esphome.config_helpers module.""" + +from collections.abc import Callable +from unittest.mock import patch + +from esphome.config_helpers import filter_source_files_from_platform, get_logger_level +from esphome.const import ( + CONF_LEVEL, + CONF_LOGGER, + KEY_CORE, + KEY_TARGET_FRAMEWORK, + KEY_TARGET_PLATFORM, + PlatformFramework, +) + + +def test_filter_source_files_from_platform_esp32() -> None: + """Test that filter_source_files_from_platform correctly filters files for ESP32 platform.""" + # Define test file mappings + files_map: dict[str, set[PlatformFramework]] = { + "logger_esp32.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + "logger_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "logger_host.cpp": {PlatformFramework.HOST_NATIVE}, + "logger_common.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + PlatformFramework.ESP8266_ARDUINO, + PlatformFramework.HOST_NATIVE, + }, + } + + # Create the filter function + filter_func: Callable[[], list[str]] = filter_source_files_from_platform(files_map) + + # Test ESP32 with Arduino framework + mock_core_data: dict[str, dict[str, str]] = { + KEY_CORE: { + KEY_TARGET_PLATFORM: "esp32", + KEY_TARGET_FRAMEWORK: "arduino", + } + } + + with patch("esphome.config_helpers.CORE.data", mock_core_data): + excluded: list[str] = filter_func() + # ESP32 Arduino should exclude ESP8266 and HOST files + assert "logger_esp8266.cpp" in excluded + assert "logger_host.cpp" in excluded + # But not ESP32 or common files + assert "logger_esp32.cpp" not in excluded + assert "logger_common.cpp" not in excluded + + +def test_filter_source_files_from_platform_host() -> None: + """Test that filter_source_files_from_platform correctly filters files for HOST platform.""" + # Define test file mappings + files_map: dict[str, set[PlatformFramework]] = { + "logger_esp32.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + }, + "logger_esp8266.cpp": {PlatformFramework.ESP8266_ARDUINO}, + "logger_host.cpp": {PlatformFramework.HOST_NATIVE}, + "logger_common.cpp": { + PlatformFramework.ESP32_ARDUINO, + PlatformFramework.ESP32_IDF, + PlatformFramework.ESP8266_ARDUINO, + PlatformFramework.HOST_NATIVE, + }, + } + + # Create the filter function + filter_func: Callable[[], list[str]] = filter_source_files_from_platform(files_map) + + # Test Host platform + mock_core_data: dict[str, dict[str, str]] = { + KEY_CORE: { + KEY_TARGET_PLATFORM: "host", + KEY_TARGET_FRAMEWORK: "host", # Framework.NATIVE is "host" + } + } + + with patch("esphome.config_helpers.CORE.data", mock_core_data): + excluded: list[str] = filter_func() + # Host should exclude ESP32 and ESP8266 files + assert "logger_esp32.cpp" in excluded + assert "logger_esp8266.cpp" in excluded + # But not host or common files + assert "logger_host.cpp" not in excluded + assert "logger_common.cpp" not in excluded + + +def test_filter_source_files_from_platform_handles_missing_data() -> None: + """Test that filter_source_files_from_platform returns empty list when platform/framework data is missing.""" + # Define test file mappings + files_map: dict[str, set[PlatformFramework]] = { + "logger_esp32.cpp": {PlatformFramework.ESP32_ARDUINO}, + "logger_host.cpp": {PlatformFramework.HOST_NATIVE}, + } + + # Create the filter function + filter_func: Callable[[], list[str]] = filter_source_files_from_platform(files_map) + + # Test case: Missing platform/framework data + mock_core_data: dict[str, dict[str, str]] = {KEY_CORE: {}} + + with patch("esphome.config_helpers.CORE.data", mock_core_data): + excluded: list[str] = filter_func() + # Should return empty list when platform/framework not set + assert excluded == [] + + +def test_get_logger_level() -> None: + """Test get_logger_level helper function.""" + # Test no logger config - should return default DEBUG + mock_config = {} + with patch("esphome.config_helpers.CORE.config", mock_config): + assert get_logger_level() == "DEBUG" + + # Test with logger set to INFO + mock_config = {CONF_LOGGER: {CONF_LEVEL: "INFO"}} + with patch("esphome.config_helpers.CORE.config", mock_config): + assert get_logger_level() == "INFO" + + # Test with VERY_VERBOSE + mock_config = {CONF_LOGGER: {CONF_LEVEL: "VERY_VERBOSE"}} + with patch("esphome.config_helpers.CORE.config", mock_config): + assert get_logger_level() == "VERY_VERBOSE" + + # Test with logger missing level (uses default DEBUG) + mock_config = {CONF_LOGGER: {}} + with patch("esphome.config_helpers.CORE.config", mock_config): + assert get_logger_level() == "DEBUG" diff --git a/tests/unit_tests/test_loader.py b/tests/unit_tests/test_loader.py new file mode 100644 index 0000000000..c6d4c4aef0 --- /dev/null +++ b/tests/unit_tests/test_loader.py @@ -0,0 +1,63 @@ +"""Unit tests for esphome.loader module.""" + +from unittest.mock import MagicMock, patch + +from esphome.loader import ComponentManifest + + +def test_component_manifest_resources_with_filter_source_files() -> None: + """Test that ComponentManifest.resources correctly filters out excluded files.""" + # Create a mock module with FILTER_SOURCE_FILES function + mock_module = MagicMock() + mock_module.FILTER_SOURCE_FILES = lambda: [ + "platform_esp32.cpp", + "platform_esp8266.cpp", + ] + mock_module.__package__ = "esphome.components.test_component" + + # Create ComponentManifest instance + manifest = ComponentManifest(mock_module) + + # Mock the files in the package + def create_mock_file(filename: str) -> MagicMock: + mock_file = MagicMock() + mock_file.name = filename + mock_file.is_file.return_value = True + return mock_file + + mock_files = [ + create_mock_file("test.cpp"), + create_mock_file("test.h"), + create_mock_file("platform_esp32.cpp"), + create_mock_file("platform_esp8266.cpp"), + create_mock_file("common.cpp"), + create_mock_file("README.md"), # Should be excluded by extension + ] + + # Mock importlib.resources + with patch("importlib.resources.files") as mock_files_func: + mock_package_files = MagicMock() + mock_package_files.iterdir.return_value = mock_files + mock_package_files.joinpath = lambda name: MagicMock(is_file=lambda: True) + mock_files_func.return_value = mock_package_files + + # Get resources + resources = manifest.resources + + # Convert to list of filenames for easier testing + resource_names = [r.resource for r in resources] + + # Check that platform files are excluded + assert "platform_esp32.cpp" not in resource_names + assert "platform_esp8266.cpp" not in resource_names + + # Check that other source files are included + assert "test.cpp" in resource_names + assert "test.h" in resource_names + assert "common.cpp" in resource_names + + # Check that non-source files are excluded + assert "README.md" not in resource_names + + # Verify the correct number of resources + assert len(resources) == 3 # test.cpp, test.h, common.cpp