diff --git a/setup.cfg b/.flake8 similarity index 56% rename from setup.cfg rename to .flake8 index b3cfbba6a1..2724da06b6 100644 --- a/setup.cfg +++ b/.flake8 @@ -1,19 +1,3 @@ -[metadata] -license = MIT -license_file = LICENSE -platforms = any -description = Make creating custom firmwares for ESP32/ESP8266 super easy. -long_description = file: README.md -keywords = home, automation -classifier = - Environment :: Console - Intended Audience :: Developers - Intended Audience :: End Users/Desktop - License :: OSI Approved :: MIT License - Programming Language :: C++ - Programming Language :: Python :: 3 - Topic :: Home Automation - [flake8] max-line-length = 120 # Following 4 for black compatibility @@ -37,25 +21,22 @@ max-line-length = 120 # D401 First line should be in imperative mood ignore = - E501, - W503, - E203, - D202, + E501, + W503, + E203, + D202, - D100, - D101, - D102, - D103, - D104, - D105, - D107, - D200, - D205, - D209, - D400, - D401, + D100, + D101, + D102, + D103, + D104, + D105, + D107, + D200, + D205, + D209, + D400, + D401, exclude = api_pb2.py - -[bdist_wheel] -universal = 1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 03ed523e1d..c1c502394a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -61,7 +61,9 @@ jobs: ESPHOME_NO_VENV: 1 run: script/setup - name: Build - run: python setup.py sdist bdist_wheel + run: |- + pip3 install build + python3 -m build - name: Publish uses: pypa/gh-action-pypi-publish@v1.8.14 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ce226846e3..418716e4f4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -44,6 +44,6 @@ repos: hooks: - id: pylint name: pylint - entry: pylint - language: system + entry: script/run-in-env.sh pylint + language: script types: [python] diff --git a/CODEOWNERS b/CODEOWNERS index 30694ead4d..3cfb643acb 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -6,7 +6,7 @@ # the integration's code owner is automatically notified. # Core Code -setup.py @esphome/core +pyproject.toml @esphome/core esphome/*.py @esphome/core esphome/core/* @esphome/core @@ -52,6 +52,8 @@ esphome/components/bang_bang/* @OttoWinter esphome/components/bedjet/* @jhansche esphome/components/bedjet/climate/* @jhansche esphome/components/bedjet/fan/* @jhansche +esphome/components/bedjet/sensor/* @javawizard @jhansche +esphome/components/beken_spi_led_strip/* @Mat931 esphome/components/bh1750/* @OttoWinter esphome/components/binary_sensor/* @esphome/core esphome/components/bk72xx/* @kuba2k2 @@ -110,7 +112,10 @@ esphome/components/ee895/* @Stock-M esphome/components/ektf2232/touchscreen/* @jesserockz esphome/components/emc2101/* @ellull esphome/components/emmeti/* @E440QF -esphome/components/ens160/* @vincentscode +esphome/components/ens160/* @latonita +esphome/components/ens160_base/* @latonita @vincentscode +esphome/components/ens160_i2c/* @latonita +esphome/components/ens160_spi/* @latonita esphome/components/ens210/* @itn3rd77 esphome/components/esp32/* @esphome/core esphome/components/esp32_ble/* @Rapsssito @jesserockz @@ -176,6 +181,9 @@ esphome/components/improv_base/* @esphome/core esphome/components/improv_serial/* @esphome/core esphome/components/ina226/* @Sergio303 @latonita esphome/components/ina260/* @mreditor97 +esphome/components/ina2xx_base/* @latonita +esphome/components/ina2xx_i2c/* @latonita +esphome/components/ina2xx_spi/* @latonita esphome/components/inkbird_ibsth1_mini/* @fkirill esphome/components/inkplate6/* @jesserockz esphome/components/integration/* @OttoWinter diff --git a/docker/Dockerfile b/docker/Dockerfile index 5d9ece16a1..3c661b7e1c 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -110,7 +110,7 @@ RUN if [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]; then \ export PIP_EXTRA_INDEX_URL="https://www.piwheels.org/simple"; \ fi; \ pip3 install \ - --break-system-packages --no-cache-dir --no-use-pep517 -e /esphome + --break-system-packages --no-cache-dir -e /esphome # Settings for dashboard ENV USERNAME="" PASSWORD="" @@ -160,7 +160,7 @@ RUN if [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]; then \ export PIP_EXTRA_INDEX_URL="https://www.piwheels.org/simple"; \ fi; \ pip3 install \ - --break-system-packages --no-cache-dir --no-use-pep517 -e /esphome + --break-system-packages --no-cache-dir -e /esphome # Labels LABEL \ diff --git a/esphome/__main__.py b/esphome/__main__.py index 54c1aa112a..9930119c86 100644 --- a/esphome/__main__.py +++ b/esphome/__main__.py @@ -18,22 +18,23 @@ from esphome.const import ( CONF_BAUD_RATE, CONF_BROKER, CONF_DEASSERT_RTS_DTR, + CONF_DISABLED, + CONF_ESPHOME, CONF_LOGGER, + CONF_MDNS, + CONF_MQTT, CONF_NAME, CONF_OTA, - CONF_MQTT, - CONF_MDNS, - CONF_DISABLED, CONF_PASSWORD, - CONF_PORT, - CONF_ESPHOME, + CONF_PLATFORM, CONF_PLATFORMIO_OPTIONS, + CONF_PORT, CONF_SUBSTITUTIONS, PLATFORM_BK72XX, - PLATFORM_RTL87XX, PLATFORM_ESP32, PLATFORM_ESP8266, PLATFORM_RP2040, + PLATFORM_RTL87XX, SECRETS_FILES, ) from esphome.core import CORE, EsphomeError, coroutine @@ -65,7 +66,7 @@ def choose_prompt(options, purpose: str = None): f'Found multiple options{f" for {purpose}" if purpose else ""}, please choose one:' ) for i, (desc, _) in enumerate(options): - safe_print(f" [{i+1}] {desc}") + safe_print(f" [{i + 1}] {desc}") while True: opt = input("(number): ") @@ -330,15 +331,19 @@ def upload_program(config, args, host): return 1 # Unknown target platform - if CONF_OTA not in config: + ota_conf = {} + for ota_item in config.get(CONF_OTA, []): + if ota_item[CONF_PLATFORM] == CONF_ESPHOME: + ota_conf = ota_item + break + + if not ota_conf: raise EsphomeError( - "Cannot upload Over the Air as the config does not include the ota: " - "component" + f"Cannot upload Over the Air as the {CONF_OTA} configuration is not present or does not include {CONF_PLATFORM}: {CONF_ESPHOME}" ) from esphome import espota2 - ota_conf = config[CONF_OTA] remote_port = ota_conf[CONF_PORT] password = ota_conf.get(CONF_PASSWORD, "") diff --git a/esphome/components/adc/__init__.py b/esphome/components/adc/__init__.py index 87d769fec2..11b0ba2389 100644 --- a/esphome/components/adc/__init__.py +++ b/esphome/components/adc/__init__.py @@ -18,11 +18,23 @@ from esphome.components.esp32.const import ( CODEOWNERS = ["@esphome/core"] +adc_ns = cg.esphome_ns.namespace("adc") + + +""" +From the below patch versions (and 5.2+) ADC_ATTEN_DB_11 is deprecated and replaced with ADC_ATTEN_DB_12. +4.4.7 +5.0.5 +5.1.3 +5.2+ +""" + ATTENUATION_MODES = { "0db": cg.global_ns.ADC_ATTEN_DB_0, "2.5db": cg.global_ns.ADC_ATTEN_DB_2_5, "6db": cg.global_ns.ADC_ATTEN_DB_6, - "11db": cg.global_ns.ADC_ATTEN_DB_11, + "11db": adc_ns.ADC_ATTEN_DB_12_COMPAT, + "12db": adc_ns.ADC_ATTEN_DB_12_COMPAT, "auto": "auto", } diff --git a/esphome/components/adc/adc_sensor.cpp b/esphome/components/adc/adc_sensor.cpp index a9ac5a5cfe..7257793016 100644 --- a/esphome/components/adc/adc_sensor.cpp +++ b/esphome/components/adc/adc_sensor.cpp @@ -46,27 +46,27 @@ extern "C" ADCSensor::setup() { ESP_LOGCONFIG(TAG, "Setting up ADC '%s'...", this->get_name().c_str()); #if !defined(USE_ADC_SENSOR_VCC) && !defined(USE_RP2040) - pin_->setup(); + this->pin_->setup(); #endif #ifdef USE_ESP32 - if (channel1_ != ADC1_CHANNEL_MAX) { + if (this->channel1_ != ADC1_CHANNEL_MAX) { adc1_config_width(ADC_WIDTH_MAX_SOC_BITS); - if (!autorange_) { - adc1_config_channel_atten(channel1_, attenuation_); + if (!this->autorange_) { + adc1_config_channel_atten(this->channel1_, this->attenuation_); } - } else if (channel2_ != ADC2_CHANNEL_MAX) { - if (!autorange_) { - adc2_config_channel_atten(channel2_, attenuation_); + } else if (this->channel2_ != ADC2_CHANNEL_MAX) { + if (!this->autorange_) { + adc2_config_channel_atten(this->channel2_, this->attenuation_); } } // load characteristics for each attenuation - for (int32_t i = 0; i <= ADC_ATTEN_DB_11; i++) { - auto adc_unit = channel1_ != ADC1_CHANNEL_MAX ? ADC_UNIT_1 : ADC_UNIT_2; + for (int32_t i = 0; i <= ADC_ATTEN_DB_12_COMPAT; i++) { + auto adc_unit = this->channel1_ != ADC1_CHANNEL_MAX ? ADC_UNIT_1 : ADC_UNIT_2; auto cal_value = esp_adc_cal_characterize(adc_unit, (adc_atten_t) i, ADC_WIDTH_MAX_SOC_BITS, 1100, // default vref - &cal_characteristics_[i]); + &this->cal_characteristics_[i]); switch (cal_value) { case ESP_ADC_CAL_VAL_EFUSE_VREF: ESP_LOGV(TAG, "Using eFuse Vref for calibration"); @@ -99,27 +99,27 @@ void ADCSensor::dump_config() { #ifdef USE_ADC_SENSOR_VCC ESP_LOGCONFIG(TAG, " Pin: VCC"); #else - LOG_PIN(" Pin: ", pin_); + LOG_PIN(" Pin: ", this->pin_); #endif #endif // USE_ESP8266 || USE_LIBRETINY #ifdef USE_ESP32 - LOG_PIN(" Pin: ", pin_); - if (autorange_) { - ESP_LOGCONFIG(TAG, " Attenuation: auto"); + LOG_PIN(" Pin: ", this->pin_); + if (this->autorange_) { + ESP_LOGCONFIG(TAG, " Attenuation: auto"); } else { switch (this->attenuation_) { case ADC_ATTEN_DB_0: - ESP_LOGCONFIG(TAG, " Attenuation: 0db"); + ESP_LOGCONFIG(TAG, " Attenuation: 0db"); break; case ADC_ATTEN_DB_2_5: - ESP_LOGCONFIG(TAG, " Attenuation: 2.5db"); + ESP_LOGCONFIG(TAG, " Attenuation: 2.5db"); break; case ADC_ATTEN_DB_6: - ESP_LOGCONFIG(TAG, " Attenuation: 6db"); + ESP_LOGCONFIG(TAG, " Attenuation: 6db"); break; - case ADC_ATTEN_DB_11: - ESP_LOGCONFIG(TAG, " Attenuation: 11db"); + case ADC_ATTEN_DB_12_COMPAT: + ESP_LOGCONFIG(TAG, " Attenuation: 12db"); break; default: // This is to satisfy the unused ADC_ATTEN_MAX break; @@ -134,11 +134,11 @@ void ADCSensor::dump_config() { #ifdef USE_ADC_SENSOR_VCC ESP_LOGCONFIG(TAG, " Pin: VCC"); #else - LOG_PIN(" Pin: ", pin_); + LOG_PIN(" Pin: ", this->pin_); #endif // USE_ADC_SENSOR_VCC } #endif // USE_RP2040 - + ESP_LOGCONFIG(TAG, " Samples: %i", this->sample_count_); LOG_UPDATE_INTERVAL(this); } @@ -149,14 +149,24 @@ void ADCSensor::update() { this->publish_state(value_v); } +void ADCSensor::set_sample_count(uint8_t sample_count) { + if (sample_count != 0) { + this->sample_count_ = sample_count; + } +} + #ifdef USE_ESP8266 float ADCSensor::sample() { + uint32_t raw = 0; + for (uint8_t sample = 0; sample < this->sample_count_; sample++) { #ifdef USE_ADC_SENSOR_VCC - int32_t raw = ESP.getVcc(); // NOLINT(readability-static-accessed-through-instance) + raw += ESP.getVcc(); // NOLINT(readability-static-accessed-through-instance) #else - int32_t raw = analogRead(this->pin_->get_pin()); // NOLINT + raw += analogRead(this->pin_->get_pin()); // NOLINT #endif - if (output_raw_) { + } + raw = (raw + (this->sample_count_ >> 1)) / this->sample_count_; // NOLINT(clang-analyzer-core.DivideZero) + if (this->output_raw_) { return raw; } return raw / 1024.0f; @@ -165,77 +175,81 @@ float ADCSensor::sample() { #ifdef USE_ESP32 float ADCSensor::sample() { - if (!autorange_) { - int raw = -1; - if (channel1_ != ADC1_CHANNEL_MAX) { - raw = adc1_get_raw(channel1_); - } else if (channel2_ != ADC2_CHANNEL_MAX) { - adc2_get_raw(channel2_, ADC_WIDTH_MAX_SOC_BITS, &raw); + if (!this->autorange_) { + uint32_t sum = 0; + for (uint8_t sample = 0; sample < this->sample_count_; sample++) { + int raw = -1; + if (this->channel1_ != ADC1_CHANNEL_MAX) { + raw = adc1_get_raw(this->channel1_); + } else if (this->channel2_ != ADC2_CHANNEL_MAX) { + adc2_get_raw(this->channel2_, ADC_WIDTH_MAX_SOC_BITS, &raw); + } + if (raw == -1) { + return NAN; + } + sum += raw; } - - if (raw == -1) { - return NAN; + sum = (sum + (this->sample_count_ >> 1)) / this->sample_count_; // NOLINT(clang-analyzer-core.DivideZero) + if (this->output_raw_) { + return sum; } - if (output_raw_) { - return raw; - } - uint32_t mv = esp_adc_cal_raw_to_voltage(raw, &cal_characteristics_[(int32_t) attenuation_]); + uint32_t mv = esp_adc_cal_raw_to_voltage(sum, &this->cal_characteristics_[(int32_t) this->attenuation_]); return mv / 1000.0f; } - int raw11 = ADC_MAX, raw6 = ADC_MAX, raw2 = ADC_MAX, raw0 = ADC_MAX; + int raw12 = ADC_MAX, raw6 = ADC_MAX, raw2 = ADC_MAX, raw0 = ADC_MAX; - if (channel1_ != ADC1_CHANNEL_MAX) { - adc1_config_channel_atten(channel1_, ADC_ATTEN_DB_11); - raw11 = adc1_get_raw(channel1_); - if (raw11 < ADC_MAX) { - adc1_config_channel_atten(channel1_, ADC_ATTEN_DB_6); - raw6 = adc1_get_raw(channel1_); + if (this->channel1_ != ADC1_CHANNEL_MAX) { + adc1_config_channel_atten(this->channel1_, ADC_ATTEN_DB_12_COMPAT); + raw12 = adc1_get_raw(this->channel1_); + if (raw12 < ADC_MAX) { + adc1_config_channel_atten(this->channel1_, ADC_ATTEN_DB_6); + raw6 = adc1_get_raw(this->channel1_); if (raw6 < ADC_MAX) { - adc1_config_channel_atten(channel1_, ADC_ATTEN_DB_2_5); - raw2 = adc1_get_raw(channel1_); + adc1_config_channel_atten(this->channel1_, ADC_ATTEN_DB_2_5); + raw2 = adc1_get_raw(this->channel1_); if (raw2 < ADC_MAX) { - adc1_config_channel_atten(channel1_, ADC_ATTEN_DB_0); - raw0 = adc1_get_raw(channel1_); + adc1_config_channel_atten(this->channel1_, ADC_ATTEN_DB_0); + raw0 = adc1_get_raw(this->channel1_); } } } - } else if (channel2_ != ADC2_CHANNEL_MAX) { - adc2_config_channel_atten(channel2_, ADC_ATTEN_DB_11); - adc2_get_raw(channel2_, ADC_WIDTH_MAX_SOC_BITS, &raw11); - if (raw11 < ADC_MAX) { - adc2_config_channel_atten(channel2_, ADC_ATTEN_DB_6); - adc2_get_raw(channel2_, ADC_WIDTH_MAX_SOC_BITS, &raw6); + } else if (this->channel2_ != ADC2_CHANNEL_MAX) { + adc2_config_channel_atten(this->channel2_, ADC_ATTEN_DB_12_COMPAT); + adc2_get_raw(this->channel2_, ADC_WIDTH_MAX_SOC_BITS, &raw12); + if (raw12 < ADC_MAX) { + adc2_config_channel_atten(this->channel2_, ADC_ATTEN_DB_6); + adc2_get_raw(this->channel2_, ADC_WIDTH_MAX_SOC_BITS, &raw6); if (raw6 < ADC_MAX) { - adc2_config_channel_atten(channel2_, ADC_ATTEN_DB_2_5); - adc2_get_raw(channel2_, ADC_WIDTH_MAX_SOC_BITS, &raw2); + adc2_config_channel_atten(this->channel2_, ADC_ATTEN_DB_2_5); + adc2_get_raw(this->channel2_, ADC_WIDTH_MAX_SOC_BITS, &raw2); if (raw2 < ADC_MAX) { - adc2_config_channel_atten(channel2_, ADC_ATTEN_DB_0); - adc2_get_raw(channel2_, ADC_WIDTH_MAX_SOC_BITS, &raw0); + adc2_config_channel_atten(this->channel2_, ADC_ATTEN_DB_0); + adc2_get_raw(this->channel2_, ADC_WIDTH_MAX_SOC_BITS, &raw0); } } } } - if (raw0 == -1 || raw2 == -1 || raw6 == -1 || raw11 == -1) { + if (raw0 == -1 || raw2 == -1 || raw6 == -1 || raw12 == -1) { return NAN; } - uint32_t mv11 = esp_adc_cal_raw_to_voltage(raw11, &cal_characteristics_[(int32_t) ADC_ATTEN_DB_11]); - uint32_t mv6 = esp_adc_cal_raw_to_voltage(raw6, &cal_characteristics_[(int32_t) ADC_ATTEN_DB_6]); - uint32_t mv2 = esp_adc_cal_raw_to_voltage(raw2, &cal_characteristics_[(int32_t) ADC_ATTEN_DB_2_5]); - uint32_t mv0 = esp_adc_cal_raw_to_voltage(raw0, &cal_characteristics_[(int32_t) ADC_ATTEN_DB_0]); + uint32_t mv12 = esp_adc_cal_raw_to_voltage(raw12, &this->cal_characteristics_[(int32_t) ADC_ATTEN_DB_12_COMPAT]); + uint32_t mv6 = esp_adc_cal_raw_to_voltage(raw6, &this->cal_characteristics_[(int32_t) ADC_ATTEN_DB_6]); + uint32_t mv2 = esp_adc_cal_raw_to_voltage(raw2, &this->cal_characteristics_[(int32_t) ADC_ATTEN_DB_2_5]); + uint32_t mv0 = esp_adc_cal_raw_to_voltage(raw0, &this->cal_characteristics_[(int32_t) ADC_ATTEN_DB_0]); // Contribution of each value, in range 0-2048 (12 bit ADC) or 0-4096 (13 bit ADC) - uint32_t c11 = std::min(raw11, ADC_HALF); + uint32_t c12 = std::min(raw12, ADC_HALF); uint32_t c6 = ADC_HALF - std::abs(raw6 - ADC_HALF); uint32_t c2 = ADC_HALF - std::abs(raw2 - ADC_HALF); uint32_t c0 = std::min(ADC_MAX - raw0, ADC_HALF); // max theoretical csum value is 4096*4 = 16384 - uint32_t csum = c11 + c6 + c2 + c0; + uint32_t csum = c12 + c6 + c2 + c0; // each mv is max 3900; so max value is 3900*4096*4, fits in unsigned32 - uint32_t mv_scaled = (mv11 * c11) + (mv6 * c6) + (mv2 * c2) + (mv0 * c0); + uint32_t mv_scaled = (mv12 * c12) + (mv6 * c6) + (mv2 * c2) + (mv0 * c0); return mv_scaled / (float) (csum * 1000U); } #endif // USE_ESP32 @@ -246,8 +260,11 @@ float ADCSensor::sample() { adc_set_temp_sensor_enabled(true); delay(1); adc_select_input(4); - - int32_t raw = adc_read(); + uint32_t raw = 0; + for (uint8_t sample = 0; sample < this->sample_count_; sample++) { + raw += adc_read(); + } + raw = (raw + (this->sample_count_ >> 1)) / this->sample_count_; // NOLINT(clang-analyzer-core.DivideZero) adc_set_temp_sensor_enabled(false); if (this->output_raw_) { return raw; @@ -268,7 +285,11 @@ float ADCSensor::sample() { adc_gpio_init(pin); adc_select_input(pin - 26); - int32_t raw = adc_read(); + uint32_t raw = 0; + for (uint8_t sample = 0; sample < this->sample_count_; sample++) { + raw += adc_read(); + } + raw = (raw + (this->sample_count_ >> 1)) / this->sample_count_; // NOLINT(clang-analyzer-core.DivideZero) #ifdef CYW43_USES_VSYS_PIN if (pin == PICO_VSYS_PIN) { @@ -276,7 +297,7 @@ float ADCSensor::sample() { } #endif // CYW43_USES_VSYS_PIN - if (output_raw_) { + if (this->output_raw_) { return raw; } float coeff = pin == PICO_VSYS_PIN ? 3.0 : 1.0; @@ -287,10 +308,19 @@ float ADCSensor::sample() { #ifdef USE_LIBRETINY float ADCSensor::sample() { - if (output_raw_) { - return analogRead(this->pin_->get_pin()); // NOLINT + uint32_t raw = 0; + if (this->output_raw_) { + for (uint8_t sample = 0; sample < this->sample_count_; sample++) { + raw += analogRead(this->pin_->get_pin()); // NOLINT + } + raw = (raw + (this->sample_count_ >> 1)) / this->sample_count_; // NOLINT(clang-analyzer-core.DivideZero) + return raw; } - return analogReadVoltage(this->pin_->get_pin()) / 1000.0f; // NOLINT + for (uint8_t sample = 0; sample < this->sample_count_; sample++) { + raw += analogReadVoltage(this->pin_->get_pin()); // NOLINT + } + raw = (raw + (this->sample_count_ >> 1)) / this->sample_count_; // NOLINT(clang-analyzer-core.DivideZero) + return raw / 1000.0f; } #endif // USE_LIBRETINY diff --git a/esphome/components/adc/adc_sensor.h b/esphome/components/adc/adc_sensor.h index b1fdcd5d29..b697d6dd7e 100644 --- a/esphome/components/adc/adc_sensor.h +++ b/esphome/components/adc/adc_sensor.h @@ -1,33 +1,48 @@ #pragma once -#include "esphome/core/component.h" -#include "esphome/core/hal.h" -#include "esphome/core/defines.h" #include "esphome/components/sensor/sensor.h" #include "esphome/components/voltage_sampler/voltage_sampler.h" +#include "esphome/core/component.h" +#include "esphome/core/defines.h" +#include "esphome/core/hal.h" #ifdef USE_ESP32 -#include "driver/adc.h" #include +#include "driver/adc.h" #endif namespace esphome { namespace adc { +#ifdef USE_ESP32 +// clang-format off +#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 7)) || \ + (ESP_IDF_VERSION_MAJOR == 5 && \ + ((ESP_IDF_VERSION_MINOR == 0 && ESP_IDF_VERSION_PATCH >= 5) || \ + (ESP_IDF_VERSION_MINOR == 1 && ESP_IDF_VERSION_PATCH >= 3) || \ + (ESP_IDF_VERSION_MINOR >= 2)) \ + ) +// clang-format on +static const adc_atten_t ADC_ATTEN_DB_12_COMPAT = ADC_ATTEN_DB_12; +#else +static const adc_atten_t ADC_ATTEN_DB_12_COMPAT = ADC_ATTEN_DB_11; +#endif +#endif // USE_ESP32 + class ADCSensor : public sensor::Sensor, public PollingComponent, public voltage_sampler::VoltageSampler { public: #ifdef USE_ESP32 /// Set the attenuation for this pin. Only available on the ESP32. - void set_attenuation(adc_atten_t attenuation) { attenuation_ = attenuation; } + void set_attenuation(adc_atten_t attenuation) { this->attenuation_ = attenuation; } void set_channel1(adc1_channel_t channel) { - channel1_ = channel; - channel2_ = ADC2_CHANNEL_MAX; + this->channel1_ = channel; + this->channel2_ = ADC2_CHANNEL_MAX; } void set_channel2(adc2_channel_t channel) { - channel2_ = channel; - channel1_ = ADC1_CHANNEL_MAX; + this->channel2_ = channel; + this->channel1_ = ADC1_CHANNEL_MAX; } - void set_autorange(bool autorange) { autorange_ = autorange; } + void set_autorange(bool autorange) { this->autorange_ = autorange; } #endif /// Update ADC values @@ -38,7 +53,8 @@ class ADCSensor : public sensor::Sensor, public PollingComponent, public voltage /// `HARDWARE_LATE` setup priority float get_setup_priority() const override; void set_pin(InternalGPIOPin *pin) { this->pin_ = pin; } - void set_output_raw(bool output_raw) { output_raw_ = output_raw; } + void set_output_raw(bool output_raw) { this->output_raw_ = output_raw; } + void set_sample_count(uint8_t sample_count); float sample() override; #ifdef USE_ESP8266 @@ -46,12 +62,13 @@ class ADCSensor : public sensor::Sensor, public PollingComponent, public voltage #endif #ifdef USE_RP2040 - void set_is_temperature() { is_temperature_ = true; } + void set_is_temperature() { this->is_temperature_ = true; } #endif protected: InternalGPIOPin *pin_; bool output_raw_{false}; + uint8_t sample_count_{1}; #ifdef USE_RP2040 bool is_temperature_{false}; diff --git a/esphome/components/adc/sensor.py b/esphome/components/adc/sensor.py index c1ae22214d..59ea9e184c 100644 --- a/esphome/components/adc/sensor.py +++ b/esphome/components/adc/sensor.py @@ -1,3 +1,5 @@ +import logging + import esphome.codegen as cg import esphome.config_validation as cv import esphome.final_validate as fv @@ -19,16 +21,35 @@ from . import ( ATTENUATION_MODES, ESP32_VARIANT_ADC1_PIN_TO_CHANNEL, ESP32_VARIANT_ADC2_PIN_TO_CHANNEL, + adc_ns, validate_adc_pin, ) +_LOGGER = logging.getLogger(__name__) + AUTO_LOAD = ["voltage_sampler"] +CONF_SAMPLES = "samples" + + +_attenuation = cv.enum(ATTENUATION_MODES, lower=True) + def validate_config(config): if config[CONF_RAW] and config.get(CONF_ATTENUATION, None) == "auto": raise cv.Invalid("Automatic attenuation cannot be used when raw output is set") + if config.get(CONF_ATTENUATION, None) == "auto" and config.get(CONF_SAMPLES, 1) > 1: + raise cv.Invalid( + "Automatic attenuation cannot be used when multisampling is set" + ) + if config.get(CONF_ATTENUATION) == "11db": + _LOGGER.warning( + "`attenuation: 11db` is deprecated, use `attenuation: 12db` instead" + ) + # Alter value here so `config` command prints the recommended change + config[CONF_ATTENUATION] = _attenuation("12db") + return config @@ -47,7 +68,6 @@ def final_validate_config(config): return config -adc_ns = cg.esphome_ns.namespace("adc") ADCSensor = adc_ns.class_( "ADCSensor", sensor.Sensor, cg.PollingComponent, voltage_sampler.VoltageSampler ) @@ -65,8 +85,9 @@ CONFIG_SCHEMA = cv.All( cv.Required(CONF_PIN): validate_adc_pin, cv.Optional(CONF_RAW, default=False): cv.boolean, cv.SplitDefault(CONF_ATTENUATION, esp32="0db"): cv.All( - cv.only_on_esp32, cv.enum(ATTENUATION_MODES, lower=True) + cv.only_on_esp32, _attenuation ), + cv.Optional(CONF_SAMPLES, default=1): cv.int_range(min=1, max=255), } ) .extend(cv.polling_component_schema("60s")), @@ -90,6 +111,7 @@ async def to_code(config): cg.add(var.set_pin(pin)) cg.add(var.set_output_raw(config[CONF_RAW])) + cg.add(var.set_sample_count(config[CONF_SAMPLES])) if attenuation := config.get(CONF_ATTENUATION): if attenuation == "auto": diff --git a/esphome/components/animation/__init__.py b/esphome/components/animation/__init__.py index 9151d6e56d..a7a955bead 100644 --- a/esphome/components/animation/__init__.py +++ b/esphome/components/animation/__init__.py @@ -157,7 +157,7 @@ async def to_code(config): pixels = list(frame.getdata()) if len(pixels) != height * width: raise core.EsphomeError( - f"Unexpected number of pixels in {path} frame {frameIndex}: ({len(pixels)} != {height*width})" + f"Unexpected number of pixels in {path} frame {frameIndex}: ({len(pixels)} != {height * width})" ) for pix, a in pixels: if transparent: @@ -180,7 +180,7 @@ async def to_code(config): pixels = list(frame.getdata()) if len(pixels) != height * width: raise core.EsphomeError( - f"Unexpected number of pixels in {path} frame {frameIndex}: ({len(pixels)} != {height*width})" + f"Unexpected number of pixels in {path} frame {frameIndex}: ({len(pixels)} != {height * width})" ) for pix in pixels: data[pos] = pix[0] @@ -203,7 +203,7 @@ async def to_code(config): pixels = list(frame.getdata()) if len(pixels) != height * width: raise core.EsphomeError( - f"Unexpected number of pixels in {path} frame {frameIndex}: ({len(pixels)} != {height*width})" + f"Unexpected number of pixels in {path} frame {frameIndex}: ({len(pixels)} != {height * width})" ) for r, g, b, a in pixels: if transparent: @@ -232,7 +232,7 @@ async def to_code(config): pixels = list(frame.getdata()) if len(pixels) != height * width: raise core.EsphomeError( - f"Unexpected number of pixels in {path} frame {frameIndex}: ({len(pixels)} != {height*width})" + f"Unexpected number of pixels in {path} frame {frameIndex}: ({len(pixels)} != {height * width})" ) for r, g, b, a in pixels: R = r >> 3 diff --git a/esphome/components/api/api.proto b/esphome/components/api/api.proto index b8073abc19..774ca7ed9b 100644 --- a/esphome/components/api/api.proto +++ b/esphome/components/api/api.proto @@ -1147,6 +1147,9 @@ message MediaPlayerCommandRequest { bool has_media_url = 6; string media_url = 7; + + bool has_announcement = 8; + bool announcement = 9; } // ==================== BLUETOOTH ==================== diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index b31212bbdb..2804dba31f 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -1002,7 +1002,11 @@ bool APIConnection::send_media_player_state(media_player::MediaPlayer *media_pla MediaPlayerStateResponse resp{}; resp.key = media_player->get_object_id_hash(); - resp.state = static_cast(media_player->state); + + media_player::MediaPlayerState report_state = media_player->state == media_player::MEDIA_PLAYER_STATE_ANNOUNCING + ? media_player::MEDIA_PLAYER_STATE_PLAYING + : media_player->state; + resp.state = static_cast(report_state); resp.volume = media_player->volume; resp.muted = media_player->is_muted(); return this->send_media_player_state_response(resp); @@ -1038,6 +1042,9 @@ void APIConnection::media_player_command(const MediaPlayerCommandRequest &msg) { if (msg.has_media_url) { call.set_media_url(msg.media_url); } + if (msg.has_announcement) { + call.set_announcement(msg.announcement); + } call.perform(); } #endif diff --git a/esphome/components/api/api_pb2.cpp b/esphome/components/api/api_pb2.cpp index 6ec1870d72..a48087e348 100644 --- a/esphome/components/api/api_pb2.cpp +++ b/esphome/components/api/api_pb2.cpp @@ -5253,6 +5253,14 @@ bool MediaPlayerCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt val this->has_media_url = value.as_bool(); return true; } + case 8: { + this->has_announcement = value.as_bool(); + return true; + } + case 9: { + this->announcement = value.as_bool(); + return true; + } default: return false; } @@ -5289,6 +5297,8 @@ void MediaPlayerCommandRequest::encode(ProtoWriteBuffer buffer) const { buffer.encode_float(5, this->volume); buffer.encode_bool(6, this->has_media_url); buffer.encode_string(7, this->media_url); + buffer.encode_bool(8, this->has_announcement); + buffer.encode_bool(9, this->announcement); } #ifdef HAS_PROTO_MESSAGE_DUMP void MediaPlayerCommandRequest::dump_to(std::string &out) const { @@ -5323,6 +5333,14 @@ void MediaPlayerCommandRequest::dump_to(std::string &out) const { 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 diff --git a/esphome/components/api/api_pb2.h b/esphome/components/api/api_pb2.h index 14fd95df37..807b150d82 100644 --- a/esphome/components/api/api_pb2.h +++ b/esphome/components/api/api_pb2.h @@ -1298,6 +1298,8 @@ class MediaPlayerCommandRequest : public ProtoMessage { float volume{0.0f}; bool has_media_url{false}; std::string media_url{}; + bool has_announcement{false}; + bool announcement{false}; void encode(ProtoWriteBuffer buffer) const override; #ifdef HAS_PROTO_MESSAGE_DUMP void dump_to(std::string &out) const override; diff --git a/esphome/components/bedjet/__init__.py b/esphome/components/bedjet/__init__.py index 395a5f25e4..a4b8a50eab 100644 --- a/esphome/components/bedjet/__init__.py +++ b/esphome/components/bedjet/__init__.py @@ -31,7 +31,7 @@ CONFIG_SCHEMA = ( BEDJET_CLIENT_SCHEMA = cv.Schema( { - cv.Required(CONF_BEDJET_ID): cv.use_id(BedJetHub), + cv.GenerateID(CONF_BEDJET_ID): cv.use_id(BedJetHub), } ) diff --git a/esphome/components/bedjet/bedjet_codec.cpp b/esphome/components/bedjet/bedjet_codec.cpp index 735393ffcb..7e90621235 100644 --- a/esphome/components/bedjet/bedjet_codec.cpp +++ b/esphome/components/bedjet/bedjet_codec.cpp @@ -157,5 +157,11 @@ bool BedjetCodec::compare(const uint8_t *data, uint16_t length) { return explicit_fields_changed; } +/// Converts a BedJet temp step into degrees Celsius. +float bedjet_temp_to_c(uint8_t temp) { + // BedJet temp is "C*2"; to get C, divide by 2. + return temp / 2.0f; +} + } // namespace bedjet } // namespace esphome diff --git a/esphome/components/bedjet/bedjet_codec.h b/esphome/components/bedjet/bedjet_codec.h index 3a41313ada..527e757d7f 100644 --- a/esphome/components/bedjet/bedjet_codec.h +++ b/esphome/components/bedjet/bedjet_codec.h @@ -187,5 +187,8 @@ class BedjetCodec { BedjetStatusPacket buf_; }; +/// Converts a BedJet temp step into degrees Celsius. +float bedjet_temp_to_c(uint8_t temp); + } // namespace bedjet } // namespace esphome diff --git a/esphome/components/bedjet/bedjet_const.h b/esphome/components/bedjet/bedjet_const.h index 27a75b2671..7cac1b61ff 100644 --- a/esphome/components/bedjet/bedjet_const.h +++ b/esphome/components/bedjet/bedjet_const.h @@ -40,6 +40,14 @@ enum BedjetHeatMode { HEAT_MODE_EXTENDED, }; +// Which temperature to use as the climate entity's current temperature reading +enum BedjetTemperatureSource { + // Use the temperature of the air the BedJet is putting out + TEMPERATURE_SOURCE_OUTLET, + // Use the ambient temperature of the room the BedJet is in + TEMPERATURE_SOURCE_AMBIENT +}; + enum BedjetButton : uint8_t { /// Turn BedJet off BTN_OFF = 0x1, diff --git a/esphome/components/bedjet/climate/__init__.py b/esphome/components/bedjet/climate/__init__.py index b12622868f..e454b0922b 100644 --- a/esphome/components/bedjet/climate/__init__.py +++ b/esphome/components/bedjet/climate/__init__.py @@ -7,6 +7,7 @@ from esphome.const import ( CONF_HEAT_MODE, CONF_ID, CONF_RECEIVE_TIMEOUT, + CONF_TEMPERATURE_SOURCE, CONF_TIME_ID, ) from .. import ( @@ -21,10 +22,15 @@ DEPENDENCIES = ["bedjet"] BedJetClimate = bedjet_ns.class_("BedJetClimate", climate.Climate, cg.PollingComponent) BedjetHeatMode = bedjet_ns.enum("BedjetHeatMode") +BedjetTemperatureSource = bedjet_ns.enum("BedjetTemperatureSource") BEDJET_HEAT_MODES = { "heat": BedjetHeatMode.HEAT_MODE_HEAT, "extended": BedjetHeatMode.HEAT_MODE_EXTENDED, } +BEDJET_TEMPERATURE_SOURCES = { + "outlet": BedjetTemperatureSource.TEMPERATURE_SOURCE_OUTLET, + "ambient": BedjetTemperatureSource.TEMPERATURE_SOURCE_AMBIENT, +} CONFIG_SCHEMA = ( climate.CLIMATE_SCHEMA.extend( @@ -33,6 +39,9 @@ CONFIG_SCHEMA = ( cv.Optional(CONF_HEAT_MODE, default="heat"): cv.enum( BEDJET_HEAT_MODES, lower=True ), + cv.Optional(CONF_TEMPERATURE_SOURCE, default="ambient"): cv.enum( + BEDJET_TEMPERATURE_SOURCES, lower=True + ), } ) .extend(cv.polling_component_schema("60s")) @@ -63,3 +72,4 @@ async def to_code(config): await register_bedjet_child(var, config) cg.add(var.set_heating_mode(config[CONF_HEAT_MODE])) + cg.add(var.set_temperature_source(config[CONF_TEMPERATURE_SOURCE])) diff --git a/esphome/components/bedjet/climate/bedjet_climate.cpp b/esphome/components/bedjet/climate/bedjet_climate.cpp index 431cf614e9..854129f816 100644 --- a/esphome/components/bedjet/climate/bedjet_climate.cpp +++ b/esphome/components/bedjet/climate/bedjet_climate.cpp @@ -8,12 +8,6 @@ namespace bedjet { using namespace esphome::climate; -/// Converts a BedJet temp step into degrees Celsius. -float bedjet_temp_to_c(const uint8_t temp) { - // BedJet temp is "C*2"; to get C, divide by 2. - return temp / 2.0f; -} - static const std::string *bedjet_fan_step_to_fan_mode(const uint8_t fan_step) { if (fan_step < BEDJET_FAN_SPEED_COUNT) return &BEDJET_FAN_STEP_NAME_STRINGS[fan_step]; @@ -236,9 +230,14 @@ void BedJetClimate::on_status(const BedjetStatusPacket *data) { if (converted_temp > 0) this->target_temperature = converted_temp; - converted_temp = bedjet_temp_to_c(data->ambient_temp_step); - if (converted_temp > 0) + if (this->temperature_source_ == TEMPERATURE_SOURCE_OUTLET) { + converted_temp = bedjet_temp_to_c(data->actual_temp_step); + } else { + converted_temp = bedjet_temp_to_c(data->ambient_temp_step); + } + if (converted_temp > 0) { this->current_temperature = converted_temp; + } const auto *fan_mode_name = bedjet_fan_step_to_fan_mode(data->fan_step); if (fan_mode_name != nullptr) { diff --git a/esphome/components/bedjet/climate/bedjet_climate.h b/esphome/components/bedjet/climate/bedjet_climate.h index 48c50d842f..7eaa735a3f 100644 --- a/esphome/components/bedjet/climate/bedjet_climate.h +++ b/esphome/components/bedjet/climate/bedjet_climate.h @@ -28,6 +28,8 @@ class BedJetClimate : public climate::Climate, public BedJetClient, public Polli /** Sets the default strategy to use for climate::CLIMATE_MODE_HEAT. */ void set_heating_mode(BedjetHeatMode mode) { this->heating_mode_ = mode; } + /** Sets the temperature source to use for the climate entity's current temperature */ + void set_temperature_source(BedjetTemperatureSource source) { this->temperature_source_ = source; } climate::ClimateTraits traits() override { auto traits = climate::ClimateTraits(); @@ -74,6 +76,7 @@ class BedJetClimate : public climate::Climate, public BedJetClient, public Polli void control(const climate::ClimateCall &call) override; BedjetHeatMode heating_mode_ = HEAT_MODE_HEAT; + BedjetTemperatureSource temperature_source_ = TEMPERATURE_SOURCE_AMBIENT; void reset_state_(); bool update_status_(); diff --git a/esphome/components/bedjet/sensor/__init__.py b/esphome/components/bedjet/sensor/__init__.py new file mode 100644 index 0000000000..756b31de53 --- /dev/null +++ b/esphome/components/bedjet/sensor/__init__.py @@ -0,0 +1,55 @@ +import logging + +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.components import sensor +from esphome.const import ( + CONF_ID, + DEVICE_CLASS_TEMPERATURE, + STATE_CLASS_MEASUREMENT, + UNIT_CELSIUS, +) +from .. import ( + BEDJET_CLIENT_SCHEMA, + bedjet_ns, + register_bedjet_child, +) + +_LOGGER = logging.getLogger(__name__) +CODEOWNERS = ["@jhansche", "@javawizard"] +DEPENDENCIES = ["bedjet"] + +CONF_OUTLET_TEMPERATURE = "outlet_temperature" +CONF_AMBIENT_TEMPERATURE = "ambient_temperature" + +BedjetSensor = bedjet_ns.class_("BedjetSensor", cg.Component) + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(BedjetSensor), + cv.Optional(CONF_OUTLET_TEMPERATURE): sensor.sensor_schema( + unit_of_measurement=UNIT_CELSIUS, + device_class=DEVICE_CLASS_TEMPERATURE, + state_class=STATE_CLASS_MEASUREMENT, + ), + cv.Optional(CONF_AMBIENT_TEMPERATURE): sensor.sensor_schema( + unit_of_measurement=UNIT_CELSIUS, + device_class=DEVICE_CLASS_TEMPERATURE, + state_class=STATE_CLASS_MEASUREMENT, + ), + } +).extend(BEDJET_CLIENT_SCHEMA) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) + await register_bedjet_child(var, config) + + if outlet_temperature_sensor := config.get(CONF_OUTLET_TEMPERATURE): + sensor_var = await sensor.new_sensor(outlet_temperature_sensor) + cg.add(var.set_outlet_temperature_sensor(sensor_var)) + + if ambient_temperature_sensor := config.get(CONF_AMBIENT_TEMPERATURE): + sensor_var = await sensor.new_sensor(ambient_temperature_sensor) + cg.add(var.set_ambient_temperature_sensor(sensor_var)) diff --git a/esphome/components/bedjet/sensor/bedjet_sensor.cpp b/esphome/components/bedjet/sensor/bedjet_sensor.cpp new file mode 100644 index 0000000000..2fda8c927f --- /dev/null +++ b/esphome/components/bedjet/sensor/bedjet_sensor.cpp @@ -0,0 +1,34 @@ +#include "bedjet_sensor.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace bedjet { + +std::string BedjetSensor::describe() { return "BedJet Sensor"; } + +void BedjetSensor::dump_config() { + ESP_LOGCONFIG(TAG, "BedJet Sensor:"); + LOG_SENSOR(" ", "Outlet Temperature", this->outlet_temperature_sensor_); + LOG_SENSOR(" ", "Ambient Temperature", this->ambient_temperature_sensor_); +} + +void BedjetSensor::on_bedjet_state(bool is_ready) {} + +void BedjetSensor::on_status(const BedjetStatusPacket *data) { + if (this->outlet_temperature_sensor_ != nullptr) { + float converted_temp = bedjet_temp_to_c(data->actual_temp_step); + if (converted_temp > 0) { + this->outlet_temperature_sensor_->publish_state(converted_temp); + } + } + + if (this->ambient_temperature_sensor_ != nullptr) { + float converted_temp = bedjet_temp_to_c(data->ambient_temp_step); + if (converted_temp > 0) { + this->ambient_temperature_sensor_->publish_state(converted_temp); + } + } +} + +} // namespace bedjet +} // namespace esphome diff --git a/esphome/components/bedjet/sensor/bedjet_sensor.h b/esphome/components/bedjet/sensor/bedjet_sensor.h new file mode 100644 index 0000000000..8cbaa863ee --- /dev/null +++ b/esphome/components/bedjet/sensor/bedjet_sensor.h @@ -0,0 +1,32 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/sensor/sensor.h" +#include "esphome/components/bedjet/bedjet_child.h" +#include "esphome/components/bedjet/bedjet_codec.h" + +namespace esphome { +namespace bedjet { + +class BedjetSensor : public BedJetClient, public Component { + public: + void dump_config() override; + + void on_status(const BedjetStatusPacket *data) override; + void on_bedjet_state(bool is_ready) override; + std::string describe() override; + + void set_outlet_temperature_sensor(sensor::Sensor *outlet_temperature_sensor) { + this->outlet_temperature_sensor_ = outlet_temperature_sensor; + } + void set_ambient_temperature_sensor(sensor::Sensor *ambient_temperature_sensor) { + this->ambient_temperature_sensor_ = ambient_temperature_sensor; + } + + protected: + sensor::Sensor *outlet_temperature_sensor_{nullptr}; + sensor::Sensor *ambient_temperature_sensor_{nullptr}; +}; + +} // namespace bedjet +} // namespace esphome diff --git a/esphome/components/beken_spi_led_strip/__init__.py b/esphome/components/beken_spi_led_strip/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/esphome/components/beken_spi_led_strip/led_strip.cpp b/esphome/components/beken_spi_led_strip/led_strip.cpp new file mode 100644 index 0000000000..04c8649b90 --- /dev/null +++ b/esphome/components/beken_spi_led_strip/led_strip.cpp @@ -0,0 +1,384 @@ +#include "led_strip.h" + +#ifdef USE_BK72XX + +#include "esphome/core/helpers.h" +#include "esphome/core/log.h" + +extern "C" { +#include "rtos_pub.h" +#include "spi.h" +#include "arm_arch.h" +#include "general_dma_pub.h" +#include "gpio_pub.h" +#include "icu_pub.h" +#undef SPI_DAT +#undef SPI_BASE +}; + +static const uint32_t SPI_TX_DMA_CHANNEL = GDMA_CHANNEL_3; + +// TODO: Check if SPI_PERI_CLK_DCO depends on the chip variant +static const uint32_t SPI_PERI_CLK_26M = 26000000; +static const uint32_t SPI_PERI_CLK_DCO = 120000000; + +static const uint32_t SPI_BASE = 0x00802700; +static const uint32_t SPI_DAT = SPI_BASE + 3 * 4; +static const uint32_t SPI_CONFIG = SPI_BASE + 1 * 4; + +static const uint32_t SPI_TX_EN = 1 << 0; +static const uint32_t CTRL_NSSMD_3 = 1 << 17; +static const uint32_t SPI_TX_FINISH_EN = 1 << 2; +static const uint32_t SPI_RX_FINISH_EN = 1 << 3; + +namespace esphome { +namespace beken_spi_led_strip { + +static const char *const TAG = "beken_spi_led_strip"; + +struct spi_data_t { + SemaphoreHandle_t dma_tx_semaphore; + volatile bool tx_in_progress; + bool first_run; +}; + +static spi_data_t *spi_data = nullptr; + +static void set_spi_ctrl_register(unsigned long bit, bool val) { + uint32_t value = REG_READ(SPI_CTRL); + if (val == 0) { + value &= ~bit; + } else if (val == 1) { + value |= bit; + } + REG_WRITE(SPI_CTRL, value); +} + +static void set_spi_config_register(unsigned long bit, bool val) { + uint32_t value = REG_READ(SPI_CONFIG); + if (val == 0) { + value &= ~bit; + } else if (val == 1) { + value |= bit; + } + REG_WRITE(SPI_CONFIG, value); +} + +void spi_dma_tx_enable(bool enable) { + GDMA_CFG_ST en_cfg; + set_spi_config_register(SPI_TX_EN, enable ? 1 : 0); + en_cfg.channel = SPI_TX_DMA_CHANNEL; + en_cfg.param = enable ? 1 : 0; + sddev_control(GDMA_DEV_NAME, CMD_GDMA_SET_DMA_ENABLE, &en_cfg); +} + +static void spi_set_clock(uint32_t max_hz) { + int source_clk = 0; + int spi_clk = 0; + int div = 0; + uint32_t param; + if (max_hz > 4333000) { + if (max_hz > 30000000) { + spi_clk = 30000000; + } else { + spi_clk = max_hz; + } + sddev_control(ICU_DEV_NAME, CMD_CLK_PWR_DOWN, ¶m); + source_clk = SPI_PERI_CLK_DCO; + param = PCLK_POSI_SPI; + sddev_control(ICU_DEV_NAME, CMD_CONF_PCLK_DCO, ¶m); + param = PWD_SPI_CLK_BIT; + sddev_control(ICU_DEV_NAME, CMD_CLK_PWR_UP, ¶m); + } else { + spi_clk = max_hz; +#if CFG_XTAL_FREQUENCE + source_clk = CFG_XTAL_FREQUENCE; +#else + source_clk = SPI_PERI_CLK_26M; +#endif + param = PCLK_POSI_SPI; + sddev_control(ICU_DEV_NAME, CMD_CONF_PCLK_26M, ¶m); + } + div = ((source_clk >> 1) / spi_clk); + if (div < 2) { + div = 2; + } else if (div >= 255) { + div = 255; + } + param = REG_READ(SPI_CTRL); + param &= ~(SPI_CKR_MASK << SPI_CKR_POSI); + param |= (div << SPI_CKR_POSI); + REG_WRITE(SPI_CTRL, param); + ESP_LOGD(TAG, "target frequency: %d, actual frequency: %d", max_hz, source_clk / 2 / div); +} + +void spi_dma_tx_finish_callback(unsigned int param) { + spi_data->tx_in_progress = false; + xSemaphoreGive(spi_data->dma_tx_semaphore); + spi_dma_tx_enable(0); +} + +void BekenSPILEDStripLightOutput::setup() { + ESP_LOGCONFIG(TAG, "Setting up Beken SPI LED Strip..."); + + size_t buffer_size = this->get_buffer_size_(); + size_t dma_buffer_size = (buffer_size * 8) + (2 * 64); + + ExternalRAMAllocator allocator(ExternalRAMAllocator::ALLOW_FAILURE); + this->buf_ = allocator.allocate(buffer_size); + if (this->buf_ == nullptr) { + ESP_LOGE(TAG, "Cannot allocate LED buffer!"); + this->mark_failed(); + return; + } + + this->effect_data_ = allocator.allocate(this->num_leds_); + if (this->effect_data_ == nullptr) { + ESP_LOGE(TAG, "Cannot allocate effect data!"); + this->mark_failed(); + return; + } + + this->dma_buf_ = allocator.allocate(dma_buffer_size); + if (this->dma_buf_ == nullptr) { + ESP_LOGE(TAG, "Cannot allocate DMA buffer!"); + this->mark_failed(); + return; + } + + memset(this->buf_, 0, buffer_size); + memset(this->effect_data_, 0, this->num_leds_); + memset(this->dma_buf_, 0, dma_buffer_size); + + uint32_t value = PCLK_POSI_SPI; + sddev_control(ICU_DEV_NAME, CMD_CONF_PCLK_26M, &value); + + value = PWD_SPI_CLK_BIT; + sddev_control(ICU_DEV_NAME, CMD_CLK_PWR_UP, &value); + + if (spi_data != nullptr) { + ESP_LOGE(TAG, "SPI device already initialized!"); + this->mark_failed(); + return; + } + + spi_data = (spi_data_t *) calloc(1, sizeof(spi_data_t)); + if (spi_data == nullptr) { + ESP_LOGE(TAG, "Cannot allocate spi_data!"); + this->mark_failed(); + return; + } + + spi_data->dma_tx_semaphore = xSemaphoreCreateBinary(); + if (spi_data->dma_tx_semaphore == nullptr) { + ESP_LOGE(TAG, "TX Semaphore init faild!"); + this->mark_failed(); + return; + } + + spi_data->first_run = true; + + set_spi_ctrl_register(MSTEN, 0); + set_spi_ctrl_register(BIT_WDTH, 0); + spi_set_clock(this->spi_frequency_); + set_spi_ctrl_register(CKPOL, 0); + set_spi_ctrl_register(CKPHA, 0); + set_spi_ctrl_register(MSTEN, 1); + set_spi_ctrl_register(SPIEN, 1); + + set_spi_ctrl_register(TXINT_EN, 0); + set_spi_ctrl_register(RXINT_EN, 0); + set_spi_config_register(SPI_TX_FINISH_EN, 1); + set_spi_config_register(SPI_RX_FINISH_EN, 1); + set_spi_ctrl_register(RXOVR_EN, 0); + set_spi_ctrl_register(TXOVR_EN, 0); + + value = REG_READ(SPI_CTRL); + value &= ~CTRL_NSSMD_3; + value |= (1 << 17); + REG_WRITE(SPI_CTRL, value); + + value = GFUNC_MODE_SPI_DMA; + sddev_control(GPIO_DEV_NAME, CMD_GPIO_ENABLE_SECOND, &value); + set_spi_ctrl_register(SPI_S_CS_UP_INT_EN, 0); + + GDMA_CFG_ST en_cfg; + GDMACFG_TPYES_ST init_cfg; + memset(&init_cfg, 0, sizeof(GDMACFG_TPYES_ST)); + + init_cfg.dstdat_width = 8; + init_cfg.srcdat_width = 32; + init_cfg.dstptr_incr = 0; + init_cfg.srcptr_incr = 1; + init_cfg.src_start_addr = this->dma_buf_; + init_cfg.dst_start_addr = (void *) SPI_DAT; // SPI_DMA_REG4_TXFIFO + init_cfg.channel = SPI_TX_DMA_CHANNEL; + init_cfg.prio = 0; // 10 + init_cfg.u.type4.src_loop_start_addr = this->dma_buf_; + init_cfg.u.type4.src_loop_end_addr = this->dma_buf_ + dma_buffer_size; + init_cfg.half_fin_handler = nullptr; + init_cfg.fin_handler = spi_dma_tx_finish_callback; + init_cfg.src_module = GDMA_X_SRC_DTCM_RD_REQ; + init_cfg.dst_module = GDMA_X_DST_GSPI_TX_REQ; // GDMA_X_DST_HSSPI_TX_REQ + sddev_control(GDMA_DEV_NAME, CMD_GDMA_CFG_TYPE4, (void *) &init_cfg); + en_cfg.channel = SPI_TX_DMA_CHANNEL; + en_cfg.param = dma_buffer_size; + sddev_control(GDMA_DEV_NAME, CMD_GDMA_SET_TRANS_LENGTH, (void *) &en_cfg); + en_cfg.channel = SPI_TX_DMA_CHANNEL; + en_cfg.param = 0; + sddev_control(GDMA_DEV_NAME, CMD_GDMA_CFG_WORK_MODE, (void *) &en_cfg); + en_cfg.channel = SPI_TX_DMA_CHANNEL; + en_cfg.param = 0; + sddev_control(GDMA_DEV_NAME, CMD_GDMA_CFG_SRCADDR_LOOP, &en_cfg); + + spi_dma_tx_enable(0); + + value = REG_READ(SPI_CONFIG); + value &= ~(0xFFF << 8); + value |= ((dma_buffer_size & 0xFFF) << 8); + REG_WRITE(SPI_CONFIG, value); +} + +void BekenSPILEDStripLightOutput::set_led_params(uint8_t bit0, uint8_t bit1, uint32_t spi_frequency) { + this->bit0_ = bit0; + this->bit1_ = bit1; + this->spi_frequency_ = spi_frequency; +} + +void BekenSPILEDStripLightOutput::write_state(light::LightState *state) { + // protect from refreshing too often + uint32_t now = micros(); + if (*this->max_refresh_rate_ != 0 && (now - this->last_refresh_) < *this->max_refresh_rate_) { + // try again next loop iteration, so that this change won't get lost + this->schedule_show(); + return; + } + this->last_refresh_ = now; + this->mark_shown_(); + + ESP_LOGVV(TAG, "Writing RGB values to bus..."); + + if (spi_data == nullptr) { + ESP_LOGE(TAG, "SPI not initialized"); + this->status_set_warning(); + return; + } + + if (!spi_data->first_run && !xSemaphoreTake(spi_data->dma_tx_semaphore, 10 / portTICK_PERIOD_MS)) { + ESP_LOGE(TAG, "Timed out waiting for semaphore"); + return; + } + + if (spi_data->tx_in_progress) { + ESP_LOGE(TAG, "tx_in_progress is set"); + this->status_set_warning(); + return; + } + + spi_data->tx_in_progress = true; + + size_t buffer_size = this->get_buffer_size_(); + size_t size = 0; + uint8_t *psrc = this->buf_; + uint8_t *pdest = this->dma_buf_ + 64; + // The 64 byte padding is a workaround for a SPI DMA bug where the + // output doesn't exactly start at the beginning of dma_buf_ + + while (size < buffer_size) { + uint8_t b = *psrc; + for (int i = 0; i < 8; i++) { + *pdest++ = b & (1 << (7 - i)) ? this->bit1_ : this->bit0_; + } + size++; + psrc++; + } + + spi_data->first_run = false; + spi_dma_tx_enable(1); + + this->status_clear_warning(); +} + +light::ESPColorView BekenSPILEDStripLightOutput::get_view_internal(int32_t index) const { + int32_t r = 0, g = 0, b = 0; + switch (this->rgb_order_) { + case ORDER_RGB: + r = 0; + g = 1; + b = 2; + break; + case ORDER_RBG: + r = 0; + g = 2; + b = 1; + break; + case ORDER_GRB: + r = 1; + g = 0; + b = 2; + break; + case ORDER_GBR: + r = 2; + g = 0; + b = 1; + break; + case ORDER_BGR: + r = 2; + g = 1; + b = 0; + break; + case ORDER_BRG: + r = 1; + g = 2; + b = 0; + break; + } + uint8_t multiplier = this->is_rgbw_ || this->is_wrgb_ ? 4 : 3; + uint8_t white = this->is_wrgb_ ? 0 : 3; + + return {this->buf_ + (index * multiplier) + r + this->is_wrgb_, + this->buf_ + (index * multiplier) + g + this->is_wrgb_, + this->buf_ + (index * multiplier) + b + this->is_wrgb_, + this->is_rgbw_ || this->is_wrgb_ ? this->buf_ + (index * multiplier) + white : nullptr, + &this->effect_data_[index], + &this->correction_}; +} + +void BekenSPILEDStripLightOutput::dump_config() { + ESP_LOGCONFIG(TAG, "Beken SPI LED Strip:"); + ESP_LOGCONFIG(TAG, " Pin: %u", this->pin_); + const char *rgb_order; + switch (this->rgb_order_) { + case ORDER_RGB: + rgb_order = "RGB"; + break; + case ORDER_RBG: + rgb_order = "RBG"; + break; + case ORDER_GRB: + rgb_order = "GRB"; + break; + case ORDER_GBR: + rgb_order = "GBR"; + break; + case ORDER_BGR: + rgb_order = "BGR"; + break; + case ORDER_BRG: + rgb_order = "BRG"; + break; + default: + rgb_order = "UNKNOWN"; + break; + } + ESP_LOGCONFIG(TAG, " RGB Order: %s", rgb_order); + ESP_LOGCONFIG(TAG, " Max refresh rate: %" PRIu32, *this->max_refresh_rate_); + ESP_LOGCONFIG(TAG, " Number of LEDs: %u", this->num_leds_); +} + +float BekenSPILEDStripLightOutput::get_setup_priority() const { return setup_priority::HARDWARE; } + +} // namespace beken_spi_led_strip +} // namespace esphome + +#endif // USE_BK72XX diff --git a/esphome/components/beken_spi_led_strip/led_strip.h b/esphome/components/beken_spi_led_strip/led_strip.h new file mode 100644 index 0000000000..705f9102a9 --- /dev/null +++ b/esphome/components/beken_spi_led_strip/led_strip.h @@ -0,0 +1,85 @@ +#pragma once + +#ifdef USE_BK72XX + +#include "esphome/components/light/addressable_light.h" +#include "esphome/components/light/light_output.h" +#include "esphome/core/color.h" +#include "esphome/core/component.h" +#include "esphome/core/helpers.h" + +namespace esphome { +namespace beken_spi_led_strip { + +enum RGBOrder : uint8_t { + ORDER_RGB, + ORDER_RBG, + ORDER_GRB, + ORDER_GBR, + ORDER_BGR, + ORDER_BRG, +}; + +class BekenSPILEDStripLightOutput : public light::AddressableLight { + public: + void setup() override; + void write_state(light::LightState *state) override; + float get_setup_priority() const override; + + int32_t size() const override { return this->num_leds_; } + light::LightTraits get_traits() override { + auto traits = light::LightTraits(); + if (this->is_rgbw_ || this->is_wrgb_) { + traits.set_supported_color_modes({light::ColorMode::RGB_WHITE, light::ColorMode::WHITE}); + } else { + traits.set_supported_color_modes({light::ColorMode::RGB}); + } + return traits; + } + + void set_pin(uint8_t pin) { this->pin_ = pin; } + void set_num_leds(uint16_t num_leds) { this->num_leds_ = num_leds; } + void set_is_rgbw(bool is_rgbw) { this->is_rgbw_ = is_rgbw; } + void set_is_wrgb(bool is_wrgb) { this->is_wrgb_ = is_wrgb; } + + /// Set a maximum refresh rate in µs as some lights do not like being updated too often. + void set_max_refresh_rate(uint32_t interval_us) { this->max_refresh_rate_ = interval_us; } + + void set_led_params(uint8_t bit0, uint8_t bit1, uint32_t spi_frequency); + + void set_rgb_order(RGBOrder rgb_order) { this->rgb_order_ = rgb_order; } + + void clear_effect_data() override { + for (int i = 0; i < this->size(); i++) + this->effect_data_[i] = 0; + } + + void dump_config() override; + + protected: + light::ESPColorView get_view_internal(int32_t index) const override; + + size_t get_buffer_size_() const { return this->num_leds_ * (this->is_rgbw_ || this->is_wrgb_ ? 4 : 3); } + + uint8_t *buf_{nullptr}; + uint8_t *effect_data_{nullptr}; + uint8_t *dma_buf_{nullptr}; + + uint8_t pin_; + uint16_t num_leds_; + bool is_rgbw_; + bool is_wrgb_; + + uint32_t spi_frequency_{6666666}; + uint8_t bit0_{0xE0}; + uint8_t bit1_{0xFC}; + RGBOrder rgb_order_; + + uint32_t last_refresh_{0}; + optional max_refresh_rate_{}; +}; + +} // namespace beken_spi_led_strip +} // namespace esphome + +#endif // USE_BK72XX diff --git a/esphome/components/beken_spi_led_strip/light.py b/esphome/components/beken_spi_led_strip/light.py new file mode 100644 index 0000000000..2a1aa05c79 --- /dev/null +++ b/esphome/components/beken_spi_led_strip/light.py @@ -0,0 +1,134 @@ +from dataclasses import dataclass + +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome import pins +from esphome.components import libretiny, light +from esphome.const import ( + CONF_CHIPSET, + CONF_IS_RGBW, + CONF_MAX_REFRESH_RATE, + CONF_NUM_LEDS, + CONF_OUTPUT_ID, + CONF_PIN, + CONF_RGB_ORDER, +) + +CODEOWNERS = ["@Mat931"] +DEPENDENCIES = ["libretiny"] + +beken_spi_led_strip_ns = cg.esphome_ns.namespace("beken_spi_led_strip") +BekenSPILEDStripLightOutput = beken_spi_led_strip_ns.class_( + "BekenSPILEDStripLightOutput", light.AddressableLight +) + +RGBOrder = beken_spi_led_strip_ns.enum("RGBOrder") + +RGB_ORDERS = { + "RGB": RGBOrder.ORDER_RGB, + "RBG": RGBOrder.ORDER_RBG, + "GRB": RGBOrder.ORDER_GRB, + "GBR": RGBOrder.ORDER_GBR, + "BGR": RGBOrder.ORDER_BGR, + "BRG": RGBOrder.ORDER_BRG, +} + + +@dataclass +class LEDStripTimings: + bit0: int + bit1: int + spi_frequency: int + + +CHIPSETS = { + "WS2812": LEDStripTimings( + 0b11100000, 0b11111100, 6666666 + ), # Clock divider: 9, Bit time: 1350ns + "SK6812": LEDStripTimings( + 0b11000000, 0b11111000, 7500000 + ), # Clock divider: 8, Bit time: 1200ns + "APA106": LEDStripTimings( + 0b11000000, 0b11111110, 5454545 + ), # Clock divider: 11, Bit time: 1650ns + "SM16703": LEDStripTimings( + 0b11000000, 0b11111110, 7500000 + ), # Clock divider: 8, Bit time: 1200ns +} + + +CONF_IS_WRGB = "is_wrgb" + +SUPPORTED_PINS = { + libretiny.const.FAMILY_BK7231N: [16], + libretiny.const.FAMILY_BK7231T: [16], + libretiny.const.FAMILY_BK7251: [16], +} + + +def _validate_pin(value): + family = libretiny.get_libretiny_family() + if family not in SUPPORTED_PINS: + raise cv.Invalid(f"Chip family {family} is not supported.") + if value not in SUPPORTED_PINS[family]: + supported_pin_info = ", ".join(f"{x}" for x in SUPPORTED_PINS[family]) + raise cv.Invalid( + f"Pin {value} is not supported on the {family}. Supported pins: {supported_pin_info}" + ) + return value + + +def _validate_num_leds(value): + max_num_leds = 165 # 170 + if value[CONF_IS_RGBW] or value[CONF_IS_WRGB]: + max_num_leds = 123 # 127 + if value[CONF_NUM_LEDS] > max_num_leds: + raise cv.Invalid( + f"The maximum number of LEDs for this configuration is {max_num_leds}.", + path=CONF_NUM_LEDS, + ) + return value + + +CONFIG_SCHEMA = cv.All( + light.ADDRESSABLE_LIGHT_SCHEMA.extend( + { + cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(BekenSPILEDStripLightOutput), + cv.Required(CONF_PIN): cv.All( + pins.internal_gpio_output_pin_number, _validate_pin + ), + cv.Required(CONF_NUM_LEDS): cv.positive_not_null_int, + cv.Required(CONF_RGB_ORDER): cv.enum(RGB_ORDERS, upper=True), + cv.Optional(CONF_MAX_REFRESH_RATE): cv.positive_time_period_microseconds, + cv.Required(CONF_CHIPSET): cv.one_of(*CHIPSETS, upper=True), + cv.Optional(CONF_IS_RGBW, default=False): cv.boolean, + cv.Optional(CONF_IS_WRGB, default=False): cv.boolean, + } + ), + _validate_num_leds, +) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_OUTPUT_ID]) + await light.register_light(var, config) + await cg.register_component(var, config) + + cg.add(var.set_num_leds(config[CONF_NUM_LEDS])) + cg.add(var.set_pin(config[CONF_PIN])) + + if CONF_MAX_REFRESH_RATE in config: + cg.add(var.set_max_refresh_rate(config[CONF_MAX_REFRESH_RATE])) + + chipset = CHIPSETS[config[CONF_CHIPSET]] + cg.add( + var.set_led_params( + chipset.bit0, + chipset.bit1, + chipset.spi_frequency, + ) + ) + + cg.add(var.set_rgb_order(config[CONF_RGB_ORDER])) + cg.add(var.set_is_rgbw(config[CONF_IS_RGBW])) + cg.add(var.set_is_wrgb(config[CONF_IS_WRGB])) diff --git a/esphome/components/binary_sensor/automation.cpp b/esphome/components/binary_sensor/automation.cpp index 7ac201b2db..c2e76246aa 100644 --- a/esphome/components/binary_sensor/automation.cpp +++ b/esphome/components/binary_sensor/automation.cpp @@ -98,6 +98,11 @@ void binary_sensor::MultiClickTrigger::schedule_is_not_valid_(uint32_t max_lengt this->schedule_cooldown_(); }); } +void binary_sensor::MultiClickTrigger::cancel() { + ESP_LOGV(TAG, "Multi Click: Sequence explicitly cancelled."); + this->is_valid_ = false; + this->schedule_cooldown_(); +} void binary_sensor::MultiClickTrigger::trigger_() { ESP_LOGV(TAG, "Multi Click: Hooray, multi click is valid. Triggering!"); this->at_index_.reset(); diff --git a/esphome/components/binary_sensor/automation.h b/esphome/components/binary_sensor/automation.h index a5e9d208a1..12b07a05e3 100644 --- a/esphome/components/binary_sensor/automation.h +++ b/esphome/components/binary_sensor/automation.h @@ -105,6 +105,8 @@ class MultiClickTrigger : public Trigger<>, public Component { void set_invalid_cooldown(uint32_t invalid_cooldown) { this->invalid_cooldown_ = invalid_cooldown; } + void cancel(); + protected: void on_state_(bool state); void schedule_cooldown_(); diff --git a/esphome/components/datetime/__init__.py b/esphome/components/datetime/__init__.py index 3d08e4a6d0..262f1e2315 100644 --- a/esphome/components/datetime/__init__.py +++ b/esphome/components/datetime/__init__.py @@ -156,7 +156,7 @@ async def new_datetime(config, *args): return var -@coroutine_with_priority(40.0) +@coroutine_with_priority(100.0) async def to_code(config): cg.add_define("USE_DATETIME") cg.add_global(datetime_ns.using) diff --git a/esphome/components/ens160/__init__.py b/esphome/components/ens160/__init__.py index d26770a89d..e69de29bb2 100644 --- a/esphome/components/ens160/__init__.py +++ b/esphome/components/ens160/__init__.py @@ -1 +0,0 @@ -CODEOWNERS = ["@vincentscode"] diff --git a/esphome/components/ens160/sensor.py b/esphome/components/ens160/sensor.py index 6572c4e397..f666b530b3 100644 --- a/esphome/components/ens160/sensor.py +++ b/esphome/components/ens160/sensor.py @@ -1,87 +1,7 @@ -import esphome.codegen as cg import esphome.config_validation as cv -from esphome.components import i2c, sensor -from esphome.const import ( - CONF_COMPENSATION, - CONF_ECO2, - CONF_HUMIDITY, - CONF_ID, - CONF_TEMPERATURE, - CONF_TVOC, - DEVICE_CLASS_AQI, - DEVICE_CLASS_CARBON_DIOXIDE, - DEVICE_CLASS_VOLATILE_ORGANIC_COMPOUNDS_PARTS, - ICON_CHEMICAL_WEAPON, - ICON_MOLECULE_CO2, - ICON_RADIATOR, - STATE_CLASS_MEASUREMENT, - UNIT_PARTS_PER_BILLION, - UNIT_PARTS_PER_MILLION, + +CODEOWNERS = ["@latonita"] + +CONFIG_SCHEMA = CONFIG_SCHEMA = cv.invalid( + "The ens160 sensor component has been renamed to ens160_i2c." ) - -CODEOWNERS = ["@vincentscode"] -DEPENDENCIES = ["i2c"] - -ens160_ns = cg.esphome_ns.namespace("ens160") -ENS160Component = ens160_ns.class_( - "ENS160Component", cg.PollingComponent, i2c.I2CDevice, sensor.Sensor -) - -CONF_AQI = "aqi" -UNIT_INDEX = "index" - -CONFIG_SCHEMA = ( - cv.Schema( - { - cv.GenerateID(): cv.declare_id(ENS160Component), - cv.Required(CONF_ECO2): sensor.sensor_schema( - unit_of_measurement=UNIT_PARTS_PER_MILLION, - icon=ICON_MOLECULE_CO2, - accuracy_decimals=0, - device_class=DEVICE_CLASS_CARBON_DIOXIDE, - state_class=STATE_CLASS_MEASUREMENT, - ), - cv.Required(CONF_TVOC): sensor.sensor_schema( - unit_of_measurement=UNIT_PARTS_PER_BILLION, - icon=ICON_RADIATOR, - accuracy_decimals=0, - device_class=DEVICE_CLASS_VOLATILE_ORGANIC_COMPOUNDS_PARTS, - state_class=STATE_CLASS_MEASUREMENT, - ), - cv.Required(CONF_AQI): sensor.sensor_schema( - icon=ICON_CHEMICAL_WEAPON, - accuracy_decimals=0, - device_class=DEVICE_CLASS_AQI, - state_class=STATE_CLASS_MEASUREMENT, - ), - cv.Optional(CONF_COMPENSATION): cv.Schema( - { - cv.Required(CONF_TEMPERATURE): cv.use_id(sensor.Sensor), - cv.Required(CONF_HUMIDITY): cv.use_id(sensor.Sensor), - } - ), - } - ) - .extend(cv.polling_component_schema("60s")) - .extend(i2c.i2c_device_schema(0x53)) -) - - -async def to_code(config): - var = cg.new_Pvariable(config[CONF_ID]) - await cg.register_component(var, config) - await i2c.register_i2c_device(var, config) - - sens = await sensor.new_sensor(config[CONF_ECO2]) - cg.add(var.set_co2(sens)) - sens = await sensor.new_sensor(config[CONF_TVOC]) - cg.add(var.set_tvoc(sens)) - sens = await sensor.new_sensor(config[CONF_AQI]) - cg.add(var.set_aqi(sens)) - - if CONF_COMPENSATION in config: - compensation_config = config[CONF_COMPENSATION] - sens = await cg.get_variable(compensation_config[CONF_TEMPERATURE]) - cg.add(var.set_temperature(sens)) - sens = await cg.get_variable(compensation_config[CONF_HUMIDITY]) - cg.add(var.set_humidity(sens)) diff --git a/esphome/components/ens160_base/__init__.py b/esphome/components/ens160_base/__init__.py new file mode 100644 index 0000000000..eb6d0880af --- /dev/null +++ b/esphome/components/ens160_base/__init__.py @@ -0,0 +1,78 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.components import sensor +from esphome.const import ( + CONF_COMPENSATION, + CONF_ECO2, + CONF_HUMIDITY, + CONF_ID, + CONF_TEMPERATURE, + CONF_TVOC, + DEVICE_CLASS_AQI, + DEVICE_CLASS_CARBON_DIOXIDE, + DEVICE_CLASS_VOLATILE_ORGANIC_COMPOUNDS_PARTS, + ICON_CHEMICAL_WEAPON, + ICON_MOLECULE_CO2, + ICON_RADIATOR, + STATE_CLASS_MEASUREMENT, + UNIT_PARTS_PER_BILLION, + UNIT_PARTS_PER_MILLION, +) + +CODEOWNERS = ["@vincentscode", "@latonita"] + +ens160_ns = cg.esphome_ns.namespace("ens160_base") + +CONF_AQI = "aqi" +UNIT_INDEX = "index" + +CONFIG_SCHEMA_BASE = cv.Schema( + { + cv.Required(CONF_ECO2): sensor.sensor_schema( + unit_of_measurement=UNIT_PARTS_PER_MILLION, + icon=ICON_MOLECULE_CO2, + accuracy_decimals=0, + device_class=DEVICE_CLASS_CARBON_DIOXIDE, + state_class=STATE_CLASS_MEASUREMENT, + ), + cv.Required(CONF_TVOC): sensor.sensor_schema( + unit_of_measurement=UNIT_PARTS_PER_BILLION, + icon=ICON_RADIATOR, + accuracy_decimals=0, + device_class=DEVICE_CLASS_VOLATILE_ORGANIC_COMPOUNDS_PARTS, + state_class=STATE_CLASS_MEASUREMENT, + ), + cv.Required(CONF_AQI): sensor.sensor_schema( + icon=ICON_CHEMICAL_WEAPON, + accuracy_decimals=0, + device_class=DEVICE_CLASS_AQI, + state_class=STATE_CLASS_MEASUREMENT, + ), + cv.Optional(CONF_COMPENSATION): cv.Schema( + { + cv.Required(CONF_TEMPERATURE): cv.use_id(sensor.Sensor), + cv.Required(CONF_HUMIDITY): cv.use_id(sensor.Sensor), + } + ), + } +).extend(cv.polling_component_schema("60s")) + + +async def to_code_base(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) + + sens = await sensor.new_sensor(config[CONF_ECO2]) + cg.add(var.set_co2(sens)) + sens = await sensor.new_sensor(config[CONF_TVOC]) + cg.add(var.set_tvoc(sens)) + sens = await sensor.new_sensor(config[CONF_AQI]) + cg.add(var.set_aqi(sens)) + + if compensation_config := config.get(CONF_COMPENSATION): + sens = await cg.get_variable(compensation_config[CONF_TEMPERATURE]) + cg.add(var.set_temperature(sens)) + sens = await cg.get_variable(compensation_config[CONF_HUMIDITY]) + cg.add(var.set_humidity(sens)) + + return var diff --git a/esphome/components/ens160/ens160.cpp b/esphome/components/ens160_base/ens160_base.cpp similarity index 99% rename from esphome/components/ens160/ens160.cpp rename to esphome/components/ens160_base/ens160_base.cpp index c7a6ccbb73..71082c58c2 100644 --- a/esphome/components/ens160/ens160.cpp +++ b/esphome/components/ens160_base/ens160_base.cpp @@ -5,12 +5,12 @@ // Implementation based on: // https://github.com/sciosense/ENS160_driver -#include "ens160.h" +#include "ens160_base.h" #include "esphome/core/log.h" #include "esphome/core/hal.h" namespace esphome { -namespace ens160 { +namespace ens160_base { static const char *const TAG = "ens160"; @@ -303,7 +303,6 @@ void ENS160Component::dump_config() { ESP_LOGI(TAG, "Firmware Version: %d.%d.%d", this->firmware_ver_major_, this->firmware_ver_minor_, this->firmware_ver_build_); - LOG_I2C_DEVICE(this); LOG_UPDATE_INTERVAL(this); LOG_SENSOR(" ", "CO2 Sensor:", this->co2_); LOG_SENSOR(" ", "TVOC Sensor:", this->tvoc_); @@ -317,5 +316,5 @@ void ENS160Component::dump_config() { } } -} // namespace ens160 +} // namespace ens160_base } // namespace esphome diff --git a/esphome/components/ens160/ens160.h b/esphome/components/ens160_base/ens160_base.h similarity index 76% rename from esphome/components/ens160/ens160.h rename to esphome/components/ens160_base/ens160_base.h index 88bc8e3501..729225a5ae 100644 --- a/esphome/components/ens160/ens160.h +++ b/esphome/components/ens160_base/ens160_base.h @@ -2,12 +2,11 @@ #include "esphome/core/component.h" #include "esphome/components/sensor/sensor.h" -#include "esphome/components/i2c/i2c.h" namespace esphome { -namespace ens160 { +namespace ens160_base { -class ENS160Component : public PollingComponent, public i2c::I2CDevice, public sensor::Sensor { +class ENS160Component : public PollingComponent, public sensor::Sensor { public: void set_co2(sensor::Sensor *co2) { co2_ = co2; } void set_tvoc(sensor::Sensor *tvoc) { tvoc_ = tvoc; } @@ -44,6 +43,11 @@ class ENS160Component : public PollingComponent, public i2c::I2CDevice, public s bool warming_up_{false}; bool initial_startup_{false}; + virtual bool read_byte(uint8_t a_register, uint8_t *data) = 0; + virtual bool write_byte(uint8_t a_register, uint8_t data) = 0; + virtual bool read_bytes(uint8_t a_register, uint8_t *data, size_t len) = 0; + virtual bool write_bytes(uint8_t a_register, uint8_t *data, size_t len) = 0; + uint8_t firmware_ver_major_{0}; uint8_t firmware_ver_minor_{0}; uint8_t firmware_ver_build_{0}; @@ -56,5 +60,5 @@ class ENS160Component : public PollingComponent, public i2c::I2CDevice, public s sensor::Sensor *temperature_{nullptr}; }; -} // namespace ens160 +} // namespace ens160_base } // namespace esphome diff --git a/esphome/components/ens160_i2c/__init__.py b/esphome/components/ens160_i2c/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/esphome/components/ens160_i2c/ens160_i2c.cpp b/esphome/components/ens160_i2c/ens160_i2c.cpp new file mode 100644 index 0000000000..7163a5ad6e --- /dev/null +++ b/esphome/components/ens160_i2c/ens160_i2c.cpp @@ -0,0 +1,32 @@ +#include +#include + +#include "ens160_i2c.h" +#include "esphome/components/i2c/i2c.h" +#include "../ens160_base/ens160_base.h" + +namespace esphome { +namespace ens160_i2c { + +static const char *const TAG = "ens160_i2c.sensor"; + +bool ENS160I2CComponent::read_byte(uint8_t a_register, uint8_t *data) { + return I2CDevice::read_byte(a_register, data); +}; +bool ENS160I2CComponent::write_byte(uint8_t a_register, uint8_t data) { + return I2CDevice::write_byte(a_register, data); +}; +bool ENS160I2CComponent::read_bytes(uint8_t a_register, uint8_t *data, size_t len) { + return I2CDevice::read_bytes(a_register, data, len); +}; +bool ENS160I2CComponent::write_bytes(uint8_t a_register, uint8_t *data, size_t len) { + return I2CDevice::write_bytes(a_register, data, len); +}; + +void ENS160I2CComponent::dump_config() { + ENS160Component::dump_config(); + LOG_I2C_DEVICE(this); +} + +} // namespace ens160_i2c +} // namespace esphome diff --git a/esphome/components/ens160_i2c/ens160_i2c.h b/esphome/components/ens160_i2c/ens160_i2c.h new file mode 100644 index 0000000000..2df32f27bf --- /dev/null +++ b/esphome/components/ens160_i2c/ens160_i2c.h @@ -0,0 +1,19 @@ +#pragma once + +#include "esphome/components/ens160_base/ens160_base.h" +#include "esphome/components/i2c/i2c.h" + +namespace esphome { +namespace ens160_i2c { + +class ENS160I2CComponent : public esphome::ens160_base::ENS160Component, public i2c::I2CDevice { + void dump_config() override; + + bool read_byte(uint8_t a_register, uint8_t *data) override; + bool write_byte(uint8_t a_register, uint8_t data) override; + bool read_bytes(uint8_t a_register, uint8_t *data, size_t len) override; + bool write_bytes(uint8_t a_register, uint8_t *data, size_t len) override; +}; + +} // namespace ens160_i2c +} // namespace esphome diff --git a/esphome/components/ens160_i2c/sensor.py b/esphome/components/ens160_i2c/sensor.py new file mode 100644 index 0000000000..96cbbaa7e9 --- /dev/null +++ b/esphome/components/ens160_i2c/sensor.py @@ -0,0 +1,22 @@ +import esphome.codegen as cg +from esphome.components import i2c +from ..ens160_base import to_code_base, cv, CONFIG_SCHEMA_BASE + +AUTO_LOAD = ["ens160_base"] +CODEOWNERS = ["@latonita"] +DEPENDENCIES = ["i2c"] + +ens160_ns = cg.esphome_ns.namespace("ens160_i2c") + +ENS160I2CComponent = ens160_ns.class_( + "ENS160I2CComponent", cg.PollingComponent, i2c.I2CDevice +) + +CONFIG_SCHEMA = CONFIG_SCHEMA_BASE.extend( + i2c.i2c_device_schema(default_address=0x52) +).extend({cv.GenerateID(): cv.declare_id(ENS160I2CComponent)}) + + +async def to_code(config): + var = await to_code_base(config) + await i2c.register_i2c_device(var, config) diff --git a/esphome/components/ens160_spi/__init__.py b/esphome/components/ens160_spi/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/esphome/components/ens160_spi/ens160_spi.cpp b/esphome/components/ens160_spi/ens160_spi.cpp new file mode 100644 index 0000000000..fba2fdf0e4 --- /dev/null +++ b/esphome/components/ens160_spi/ens160_spi.cpp @@ -0,0 +1,59 @@ +#include +#include + +#include "ens160_spi.h" +#include + +namespace esphome { +namespace ens160_spi { + +static const char *const TAG = "ens160_spi.sensor"; + +inline uint8_t reg_read(uint8_t reg) { return (reg << 1) | 0x01; } + +inline uint8_t reg_write(uint8_t reg) { return (reg << 1) & 0xFE; } + +void ENS160SPIComponent::setup() { + this->spi_setup(); + ENS160Component::setup(); +}; + +void ENS160SPIComponent::dump_config() { + ENS160Component::dump_config(); + LOG_PIN(" CS Pin: ", this->cs_); +} + +bool ENS160SPIComponent::read_byte(uint8_t a_register, uint8_t *data) { + this->enable(); + this->transfer_byte(reg_read(a_register)); + *data = this->transfer_byte(0); + this->disable(); + return true; +} + +bool ENS160SPIComponent::write_byte(uint8_t a_register, uint8_t data) { + this->enable(); + this->transfer_byte(reg_write(a_register)); + this->transfer_byte(data); + this->disable(); + return true; +} + +bool ENS160SPIComponent::read_bytes(uint8_t a_register, uint8_t *data, size_t len) { + this->enable(); + this->transfer_byte(reg_read(a_register)); + this->read_array(data, len); + this->disable(); + return true; +} + +bool ENS160SPIComponent::write_bytes(uint8_t a_register, uint8_t *data, size_t len) { + this->enable(); + this->transfer_byte(reg_write(a_register)); + this->transfer_array(data, len); + this->disable(); + return true; +} + +} // namespace ens160_spi +} // namespace esphome diff --git a/esphome/components/ens160_spi/ens160_spi.h b/esphome/components/ens160_spi/ens160_spi.h new file mode 100644 index 0000000000..3371f37ffd --- /dev/null +++ b/esphome/components/ens160_spi/ens160_spi.h @@ -0,0 +1,22 @@ +#pragma once + +#include "esphome/components/ens160_base/ens160_base.h" +#include "esphome/components/spi/spi.h" + +namespace esphome { +namespace ens160_spi { + +class ENS160SPIComponent : public esphome::ens160_base::ENS160Component, + public spi::SPIDevice { + void setup() override; + void dump_config() override; + + bool read_byte(uint8_t a_register, uint8_t *data) override; + bool write_byte(uint8_t a_register, uint8_t data) override; + bool read_bytes(uint8_t a_register, uint8_t *data, size_t len) override; + bool write_bytes(uint8_t a_register, uint8_t *data, size_t len) override; +}; + +} // namespace ens160_spi +} // namespace esphome diff --git a/esphome/components/ens160_spi/sensor.py b/esphome/components/ens160_spi/sensor.py new file mode 100644 index 0000000000..552697fe1b --- /dev/null +++ b/esphome/components/ens160_spi/sensor.py @@ -0,0 +1,22 @@ +import esphome.codegen as cg +from esphome.components import spi +from ..ens160_base import to_code_base, cv, CONFIG_SCHEMA_BASE + +AUTO_LOAD = ["ens160_base"] +CODEOWNERS = ["@latonita"] +DEPENDENCIES = ["spi"] + +ens160_spi_ns = cg.esphome_ns.namespace("ens160_spi") + +ENS160SPIComponent = ens160_spi_ns.class_( + "ENS160SPIComponent", cg.PollingComponent, spi.SPIDevice +) + +CONFIG_SCHEMA = CONFIG_SCHEMA_BASE.extend(spi.spi_device_schema()).extend( + {cv.GenerateID(): cv.declare_id(ENS160SPIComponent)} +) + + +async def to_code(config): + var = await to_code_base(config) + await spi.register_spi_device(var, config) diff --git a/esphome/components/esp32/gpio.py b/esphome/components/esp32/gpio.py index 16f99f2b15..0d9cb5daf0 100644 --- a/esphome/components/esp32/gpio.py +++ b/esphome/components/esp32/gpio.py @@ -1,5 +1,6 @@ from dataclasses import dataclass from typing import Any +import logging from esphome.const import ( CONF_ID, @@ -8,6 +9,7 @@ from esphome.const import ( CONF_NUMBER, CONF_OPEN_DRAIN, CONF_OUTPUT, + CONF_IGNORE_PIN_VALIDATION_ERROR, CONF_IGNORE_STRAPPING_WARNING, PLATFORM_ESP32, ) @@ -42,6 +44,9 @@ from .gpio_esp32_h2 import esp32_h2_validate_gpio_pin, esp32_h2_validate_support ESP32InternalGPIOPin = esp32_ns.class_("ESP32InternalGPIOPin", cg.InternalGPIOPin) +_LOGGER = logging.getLogger(__name__) + + def _lookup_pin(value): board = CORE.data[KEY_ESP32][KEY_BOARD] board_pins = boards.ESP32_BOARD_PINS.get(board, {}) @@ -111,7 +116,7 @@ _esp32_validations = { } -def validate_gpio_pin(value): +def gpio_pin_number_validator(value): value = _translate_pin(value) board = CORE.data[KEY_ESP32][KEY_BOARD] board_pins = boards.ESP32_BOARD_PINS.get(board, {}) @@ -127,7 +132,33 @@ def validate_gpio_pin(value): if variant not in _esp32_validations: raise cv.Invalid(f"Unsupported ESP32 variant {variant}") - return _esp32_validations[variant].pin_validation(value) + return value + + +def validate_gpio_pin(pin): + variant = CORE.data[KEY_ESP32][KEY_VARIANT] + if variant not in _esp32_validations: + raise cv.Invalid(f"Unsupported ESP32 variant {variant}") + + ignore_pin_validation_warning = pin[CONF_IGNORE_PIN_VALIDATION_ERROR] + try: + pin[CONF_NUMBER] = _esp32_validations[variant].pin_validation(pin[CONF_NUMBER]) + except cv.Invalid as exc: + if not ignore_pin_validation_warning: + raise + + _LOGGER.warning( + "Ignoring validation error on pin %d; error: %s", + pin[CONF_NUMBER], + exc, + ) + else: + # Throw an exception if used for a pin that would not have resulted + # in a validation error anyway! + if ignore_pin_validation_warning: + raise cv.Invalid(f"GPIO{pin[CONF_NUMBER]} is not a reserved pin") + + return pin def validate_supports(value): @@ -158,9 +189,11 @@ DRIVE_STRENGTHS = { gpio_num_t = cg.global_ns.enum("gpio_num_t") CONF_DRIVE_STRENGTH = "drive_strength" + ESP32_PIN_SCHEMA = cv.All( - pins.gpio_base_schema(ESP32InternalGPIOPin, validate_gpio_pin).extend( + pins.gpio_base_schema(ESP32InternalGPIOPin, gpio_pin_number_validator).extend( { + cv.Optional(CONF_IGNORE_PIN_VALIDATION_ERROR, default=False): cv.boolean, cv.Optional(CONF_IGNORE_STRAPPING_WARNING, default=False): cv.boolean, cv.Optional(CONF_DRIVE_STRENGTH, default="20mA"): cv.All( cv.float_with_unit("current", "mA", optional_unit=True), @@ -168,6 +201,7 @@ ESP32_PIN_SCHEMA = cv.All( ), } ), + validate_gpio_pin, validate_supports, ) diff --git a/esphome/components/esp32_ble/ble.cpp b/esphome/components/esp32_ble/ble.cpp index 3797f3221e..ceb6516a02 100644 --- a/esphome/components/esp32_ble/ble.cpp +++ b/esphome/components/esp32_ble/ble.cpp @@ -1,6 +1,11 @@ #ifdef USE_ESP32 #include "ble.h" + +#ifdef USE_ESP32_VARIANT_ESP32C6 +#include "const_esp32c6.h" +#endif // USE_ESP32_VARIANT_ESP32C6 + #include "esphome/core/application.h" #include "esphome/core/log.h" @@ -114,7 +119,11 @@ bool ESP32BLE::ble_setup_() { if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_ENABLED) { // start bt controller if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE) { +#ifdef USE_ESP32_VARIANT_ESP32C6 + esp_bt_controller_config_t cfg = BT_CONTROLLER_CONFIG; +#else esp_bt_controller_config_t cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); +#endif err = esp_bt_controller_init(&cfg); if (err != ESP_OK) { ESP_LOGE(TAG, "esp_bt_controller_init failed: %s", esp_err_to_name(err)); diff --git a/esphome/components/esp32_ble/const_esp32c6.h b/esphome/components/esp32_ble/const_esp32c6.h new file mode 100644 index 0000000000..69f9adcf6b --- /dev/null +++ b/esphome/components/esp32_ble/const_esp32c6.h @@ -0,0 +1,67 @@ +#pragma once + +#ifdef USE_ESP32_VARIANT_ESP32C6 + +#include + +namespace esphome { +namespace esp32_ble { + +static const esp_bt_controller_config_t BT_CONTROLLER_CONFIG = { + .config_version = CONFIG_VERSION, + .ble_ll_resolv_list_size = CONFIG_BT_LE_LL_RESOLV_LIST_SIZE, + .ble_hci_evt_hi_buf_count = DEFAULT_BT_LE_HCI_EVT_HI_BUF_COUNT, + .ble_hci_evt_lo_buf_count = DEFAULT_BT_LE_HCI_EVT_LO_BUF_COUNT, + .ble_ll_sync_list_cnt = DEFAULT_BT_LE_MAX_PERIODIC_ADVERTISER_LIST, + .ble_ll_sync_cnt = DEFAULT_BT_LE_MAX_PERIODIC_SYNCS, + .ble_ll_rsp_dup_list_count = CONFIG_BT_LE_LL_DUP_SCAN_LIST_COUNT, + .ble_ll_adv_dup_list_count = CONFIG_BT_LE_LL_DUP_SCAN_LIST_COUNT, + .ble_ll_tx_pwr_dbm = BLE_LL_TX_PWR_DBM_N, + .rtc_freq = RTC_FREQ_N, + .ble_ll_sca = CONFIG_BT_LE_LL_SCA, + .ble_ll_scan_phy_number = BLE_LL_SCAN_PHY_NUMBER_N, + .ble_ll_conn_def_auth_pyld_tmo = BLE_LL_CONN_DEF_AUTH_PYLD_TMO_N, + .ble_ll_jitter_usecs = BLE_LL_JITTER_USECS_N, + .ble_ll_sched_max_adv_pdu_usecs = BLE_LL_SCHED_MAX_ADV_PDU_USECS_N, + .ble_ll_sched_direct_adv_max_usecs = BLE_LL_SCHED_DIRECT_ADV_MAX_USECS_N, + .ble_ll_sched_adv_max_usecs = BLE_LL_SCHED_ADV_MAX_USECS_N, + .ble_scan_rsp_data_max_len = DEFAULT_BT_LE_SCAN_RSP_DATA_MAX_LEN_N, + .ble_ll_cfg_num_hci_cmd_pkts = BLE_LL_CFG_NUM_HCI_CMD_PKTS_N, + .ble_ll_ctrl_proc_timeout_ms = BLE_LL_CTRL_PROC_TIMEOUT_MS_N, + .nimble_max_connections = DEFAULT_BT_LE_MAX_CONNECTIONS, + .ble_whitelist_size = DEFAULT_BT_NIMBLE_WHITELIST_SIZE, // NOLINT + .ble_acl_buf_size = DEFAULT_BT_LE_ACL_BUF_SIZE, + .ble_acl_buf_count = DEFAULT_BT_LE_ACL_BUF_COUNT, + .ble_hci_evt_buf_size = DEFAULT_BT_LE_HCI_EVT_BUF_SIZE, + .ble_multi_adv_instances = DEFAULT_BT_LE_MAX_EXT_ADV_INSTANCES, + .ble_ext_adv_max_size = DEFAULT_BT_LE_EXT_ADV_MAX_SIZE, + .controller_task_stack_size = NIMBLE_LL_STACK_SIZE, + .controller_task_prio = ESP_TASK_BT_CONTROLLER_PRIO, + .controller_run_cpu = 0, + .enable_qa_test = RUN_QA_TEST, + .enable_bqb_test = RUN_BQB_TEST, + .enable_uart_hci = HCI_UART_EN, + .ble_hci_uart_port = DEFAULT_BT_LE_HCI_UART_PORT, + .ble_hci_uart_baud = DEFAULT_BT_LE_HCI_UART_BAUD, + .ble_hci_uart_data_bits = DEFAULT_BT_LE_HCI_UART_DATA_BITS, + .ble_hci_uart_stop_bits = DEFAULT_BT_LE_HCI_UART_STOP_BITS, + .ble_hci_uart_flow_ctrl = DEFAULT_BT_LE_HCI_UART_FLOW_CTRL, + .ble_hci_uart_uart_parity = DEFAULT_BT_LE_HCI_UART_PARITY, + .enable_tx_cca = DEFAULT_BT_LE_TX_CCA_ENABLED, + .cca_rssi_thresh = 256 - DEFAULT_BT_LE_CCA_RSSI_THRESH, + .sleep_en = NIMBLE_SLEEP_ENABLE, + .coex_phy_coded_tx_rx_time_limit = DEFAULT_BT_LE_COEX_PHY_CODED_TX_RX_TLIM_EFF, + .dis_scan_backoff = NIMBLE_DISABLE_SCAN_BACKOFF, + .ble_scan_classify_filter_enable = 1, + .main_xtal_freq = CONFIG_XTAL_FREQ, + .version_num = (uint8_t) efuse_hal_chip_revision(), + .cpu_freq_mhz = CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ, + .ignore_wl_for_direct_adv = 0, + .enable_pcl = DEFAULT_BT_LE_POWER_CONTROL_ENABLED, + .config_magic = CONFIG_MAGIC, +}; + +} // namespace esp32_ble +} // namespace esphome + +#endif // USE_ESP32_VARIANT_ESP32C6 diff --git a/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp b/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp index 4ae7929ded..d154d4e519 100644 --- a/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp +++ b/esphome/components/esp32_ble_tracker/esp32_ble_tracker.cpp @@ -18,7 +18,7 @@ #include #ifdef USE_OTA -#include "esphome/components/ota/ota_component.h" +#include "esphome/components/ota/ota_backend.h" #endif #ifdef USE_ARDUINO @@ -61,11 +61,12 @@ void ESP32BLETracker::setup() { this->scanner_idle_ = true; #ifdef USE_OTA - ota::global_ota_component->add_on_state_callback([this](ota::OTAState state, float progress, uint8_t error) { - if (state == ota::OTA_STARTED) { - this->stop_scan(); - } - }); + ota::get_global_ota_callback()->add_on_state_callback( + [this](ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) { + if (state == ota::OTA_STARTED) { + this->stop_scan(); + } + }); #endif } diff --git a/esphome/components/esp32_rmt_led_strip/light.py b/esphome/components/esp32_rmt_led_strip/light.py index 1c15a468d9..4c8472b8d2 100644 --- a/esphome/components/esp32_rmt_led_strip/light.py +++ b/esphome/components/esp32_rmt_led_strip/light.py @@ -6,6 +6,7 @@ from esphome import pins from esphome.components import esp32_rmt, light from esphome.const import ( CONF_CHIPSET, + CONF_IS_RGBW, CONF_MAX_REFRESH_RATE, CONF_NUM_LEDS, CONF_OUTPUT_ID, @@ -52,7 +53,6 @@ CHIPSETS = { } -CONF_IS_RGBW = "is_rgbw" CONF_IS_WRGB = "is_wrgb" CONF_BIT0_HIGH = "bit0_high" CONF_BIT0_LOW = "bit0_low" diff --git a/esphome/components/esp32_touch/__init__.py b/esphome/components/esp32_touch/__init__.py index 0180d18104..fc7bf200e4 100644 --- a/esphome/components/esp32_touch/__init__.py +++ b/esphome/components/esp32_touch/__init__.py @@ -150,7 +150,7 @@ TOUCH_PAD_WATERPROOF_SHIELD_DRIVER = { def validate_touch_pad(value): - value = gpio.validate_gpio_pin(value) + value = gpio.gpio_pin_number_validator(value) variant = get_esp32_variant() if variant not in TOUCH_PADS: raise cv.Invalid(f"ESP32 variant {variant} does not support touch pads.") diff --git a/esphome/components/esphome/ota/__init__.py b/esphome/components/esphome/ota/__init__.py new file mode 100644 index 0000000000..abe9323b53 --- /dev/null +++ b/esphome/components/esphome/ota/__init__.py @@ -0,0 +1,72 @@ +from esphome.cpp_generator import RawExpression +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.components.ota import BASE_OTA_SCHEMA, ota_to_code, OTAComponent +from esphome.const import ( + CONF_ID, + CONF_NUM_ATTEMPTS, + CONF_OTA, + CONF_PASSWORD, + CONF_PORT, + CONF_REBOOT_TIMEOUT, + CONF_SAFE_MODE, + CONF_VERSION, + KEY_PAST_SAFE_MODE, +) +from esphome.core import CORE, coroutine_with_priority + + +CODEOWNERS = ["@esphome/core"] +AUTO_LOAD = ["md5", "socket"] +DEPENDENCIES = ["network"] + +esphome = cg.esphome_ns.namespace("esphome") +ESPHomeOTAComponent = esphome.class_("ESPHomeOTAComponent", OTAComponent) + + +CONFIG_SCHEMA = ( + cv.Schema( + { + cv.GenerateID(): cv.declare_id(ESPHomeOTAComponent), + cv.Optional(CONF_SAFE_MODE, default=True): cv.boolean, + cv.Optional(CONF_VERSION, default=2): cv.one_of(1, 2, int=True), + cv.SplitDefault( + CONF_PORT, + esp8266=8266, + esp32=3232, + rp2040=2040, + bk72xx=8892, + rtl87xx=8892, + ): cv.port, + cv.Optional(CONF_PASSWORD): cv.string, + cv.Optional( + CONF_REBOOT_TIMEOUT, default="5min" + ): cv.positive_time_period_milliseconds, + cv.Optional(CONF_NUM_ATTEMPTS, default="10"): cv.positive_not_null_int, + } + ) + .extend(BASE_OTA_SCHEMA) + .extend(cv.COMPONENT_SCHEMA) +) + + +@coroutine_with_priority(50.0) +async def to_code(config): + CORE.data[CONF_OTA] = {} + + var = cg.new_Pvariable(config[CONF_ID]) + await ota_to_code(var, config) + cg.add(var.set_port(config[CONF_PORT])) + if CONF_PASSWORD in config: + cg.add(var.set_auth_password(config[CONF_PASSWORD])) + cg.add_define("USE_OTA_PASSWORD") + cg.add_define("USE_OTA_VERSION", config[CONF_VERSION]) + + await cg.register_component(var, config) + + if config[CONF_SAFE_MODE]: + condition = var.should_enter_safe_mode( + config[CONF_NUM_ATTEMPTS], config[CONF_REBOOT_TIMEOUT] + ) + cg.add(RawExpression(f"if ({condition}) return")) + CORE.data[CONF_OTA][KEY_PAST_SAFE_MODE] = True diff --git a/esphome/components/ota/ota_component.cpp b/esphome/components/esphome/ota/ota_esphome.cpp similarity index 66% rename from esphome/components/ota/ota_component.cpp rename to esphome/components/esphome/ota/ota_esphome.cpp index 15af14ff1a..f2f1cfc6a8 100644 --- a/esphome/components/ota/ota_component.cpp +++ b/esphome/components/esphome/ota/ota_esphome.cpp @@ -1,55 +1,34 @@ -#include "ota_component.h" -#include "ota_backend.h" -#include "ota_backend_arduino_esp32.h" -#include "ota_backend_arduino_esp8266.h" -#include "ota_backend_arduino_rp2040.h" -#include "ota_backend_arduino_libretiny.h" -#include "ota_backend_esp_idf.h" +#include "ota_esphome.h" -#include "esphome/core/log.h" -#include "esphome/core/application.h" -#include "esphome/core/hal.h" -#include "esphome/core/util.h" #include "esphome/components/md5/md5.h" #include "esphome/components/network/util.h" +#include "esphome/components/ota/ota_backend.h" +#include "esphome/components/ota/ota_backend_arduino_esp32.h" +#include "esphome/components/ota/ota_backend_arduino_esp8266.h" +#include "esphome/components/ota/ota_backend_arduino_libretiny.h" +#include "esphome/components/ota/ota_backend_arduino_rp2040.h" +#include "esphome/components/ota/ota_backend_esp_idf.h" +#include "esphome/core/application.h" +#include "esphome/core/hal.h" +#include "esphome/core/log.h" +#include "esphome/core/util.h" #include #include namespace esphome { -namespace ota { -static const char *const TAG = "ota"; +static const char *const TAG = "esphome.ota"; static constexpr u_int16_t OTA_BLOCK_SIZE = 8192; -OTAComponent *global_ota_component = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) - -std::unique_ptr make_ota_backend() { -#ifdef USE_ARDUINO -#ifdef USE_ESP8266 - return make_unique(); -#endif // USE_ESP8266 -#ifdef USE_ESP32 - return make_unique(); -#endif // USE_ESP32 -#endif // USE_ARDUINO -#ifdef USE_ESP_IDF - return make_unique(); -#endif // USE_ESP_IDF -#ifdef USE_RP2040 - return make_unique(); -#endif // USE_RP2040 -#ifdef USE_LIBRETINY - return make_unique(); +void ESPHomeOTAComponent::setup() { +#ifdef USE_OTA_STATE_CALLBACK + ota::register_ota_platform(this); #endif -} -OTAComponent::OTAComponent() { global_ota_component = this; } - -void OTAComponent::setup() { server_ = socket::socket_ip(SOCK_STREAM, 0); if (server_ == nullptr) { - ESP_LOGW(TAG, "Could not create socket."); + ESP_LOGW(TAG, "Could not create socket"); this->mark_failed(); return; } @@ -88,41 +67,39 @@ void OTAComponent::setup() { this->mark_failed(); return; } - - this->dump_config(); } -void OTAComponent::dump_config() { - ESP_LOGCONFIG(TAG, "Over-The-Air Updates:"); +void ESPHomeOTAComponent::dump_config() { + ESP_LOGCONFIG(TAG, "Over-The-Air updates:"); ESP_LOGCONFIG(TAG, " Address: %s:%u", network::get_use_address().c_str(), this->port_); + ESP_LOGCONFIG(TAG, " Version: %d", USE_OTA_VERSION); #ifdef USE_OTA_PASSWORD if (!this->password_.empty()) { - ESP_LOGCONFIG(TAG, " Using Password."); + ESP_LOGCONFIG(TAG, " Password configured"); } #endif - ESP_LOGCONFIG(TAG, " OTA version: %d.", USE_OTA_VERSION); if (this->has_safe_mode_ && this->safe_mode_rtc_value_ > 1 && - this->safe_mode_rtc_value_ != esphome::ota::OTAComponent::ENTER_SAFE_MODE_MAGIC) { - ESP_LOGW(TAG, "Last Boot was an unhandled reset, will proceed to safe mode in %" PRIu32 " restarts", + this->safe_mode_rtc_value_ != ESPHomeOTAComponent::ENTER_SAFE_MODE_MAGIC) { + ESP_LOGW(TAG, "Last reset occurred too quickly; safe mode will be invoked in %" PRIu32 " restarts", this->safe_mode_num_attempts_ - this->safe_mode_rtc_value_); } } -void OTAComponent::loop() { +void ESPHomeOTAComponent::loop() { this->handle_(); if (this->has_safe_mode_ && (millis() - this->safe_mode_start_time_) > this->safe_mode_enable_time_) { this->has_safe_mode_ = false; // successful boot, reset counter - ESP_LOGI(TAG, "Boot seems successful, resetting boot loop counter."); + ESP_LOGI(TAG, "Boot seems successful; resetting boot loop counter"); this->clean_rtc(); } } static const uint8_t FEATURE_SUPPORTS_COMPRESSION = 0x01; -void OTAComponent::handle_() { - OTAResponseTypes error_code = OTA_RESPONSE_ERROR_UNKNOWN; +void ESPHomeOTAComponent::handle_() { + ota::OTAResponseTypes error_code = ota::OTA_RESPONSE_ERROR_UNKNOWN; bool update_started = false; size_t total = 0; uint32_t last_progress = 0; @@ -130,7 +107,7 @@ void OTAComponent::handle_() { char *sbuf = reinterpret_cast(buf); size_t ota_size; uint8_t ota_features; - std::unique_ptr backend; + std::unique_ptr backend; (void) ota_features; #if USE_OTA_VERSION == 2 size_t size_acknowledged = 0; @@ -147,54 +124,54 @@ void OTAComponent::handle_() { int enable = 1; int err = client_->setsockopt(IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(int)); if (err != 0) { - ESP_LOGW(TAG, "Socket could not enable tcp nodelay, errno: %d", errno); + ESP_LOGW(TAG, "Socket could not enable TCP nodelay, errno %d", errno); return; } - ESP_LOGD(TAG, "Starting OTA Update from %s...", this->client_->getpeername().c_str()); + ESP_LOGD(TAG, "Starting update from %s...", this->client_->getpeername().c_str()); this->status_set_warning(); #ifdef USE_OTA_STATE_CALLBACK - this->state_callback_.call(OTA_STARTED, 0.0f, 0); + this->state_callback_.call(ota::OTA_STARTED, 0.0f, 0); #endif if (!this->readall_(buf, 5)) { - ESP_LOGW(TAG, "Reading magic bytes failed!"); + ESP_LOGW(TAG, "Reading magic bytes failed"); goto error; // NOLINT(cppcoreguidelines-avoid-goto) } // 0x6C, 0x26, 0xF7, 0x5C, 0x45 if (buf[0] != 0x6C || buf[1] != 0x26 || buf[2] != 0xF7 || buf[3] != 0x5C || buf[4] != 0x45) { ESP_LOGW(TAG, "Magic bytes do not match! 0x%02X-0x%02X-0x%02X-0x%02X-0x%02X", buf[0], buf[1], buf[2], buf[3], buf[4]); - error_code = OTA_RESPONSE_ERROR_MAGIC; + error_code = ota::OTA_RESPONSE_ERROR_MAGIC; goto error; // NOLINT(cppcoreguidelines-avoid-goto) } // Send OK and version - 2 bytes - buf[0] = OTA_RESPONSE_OK; + buf[0] = ota::OTA_RESPONSE_OK; buf[1] = USE_OTA_VERSION; this->writeall_(buf, 2); - backend = make_ota_backend(); + backend = ota::make_ota_backend(); // Read features - 1 byte if (!this->readall_(buf, 1)) { - ESP_LOGW(TAG, "Reading features failed!"); + ESP_LOGW(TAG, "Reading features failed"); goto error; // NOLINT(cppcoreguidelines-avoid-goto) } ota_features = buf[0]; // NOLINT - ESP_LOGV(TAG, "OTA features is 0x%02X", ota_features); + ESP_LOGV(TAG, "Features: 0x%02X", ota_features); // Acknowledge header - 1 byte - buf[0] = OTA_RESPONSE_HEADER_OK; + buf[0] = ota::OTA_RESPONSE_HEADER_OK; if ((ota_features & FEATURE_SUPPORTS_COMPRESSION) != 0 && backend->supports_compression()) { - buf[0] = OTA_RESPONSE_SUPPORTS_COMPRESSION; + buf[0] = ota::OTA_RESPONSE_SUPPORTS_COMPRESSION; } this->writeall_(buf, 1); #ifdef USE_OTA_PASSWORD if (!this->password_.empty()) { - buf[0] = OTA_RESPONSE_REQUEST_AUTH; + buf[0] = ota::OTA_RESPONSE_REQUEST_AUTH; this->writeall_(buf, 1); md5::MD5Digest md5{}; md5.init(); @@ -206,7 +183,7 @@ void OTAComponent::handle_() { // Send nonce, 32 bytes hex MD5 if (!this->writeall_(reinterpret_cast(sbuf), 32)) { - ESP_LOGW(TAG, "Auth: Writing nonce failed!"); + ESP_LOGW(TAG, "Auth: Writing nonce failed"); goto error; // NOLINT(cppcoreguidelines-avoid-goto) } @@ -218,7 +195,7 @@ void OTAComponent::handle_() { // Receive cnonce, 32 bytes hex MD5 if (!this->readall_(buf, 32)) { - ESP_LOGW(TAG, "Auth: Reading cnonce failed!"); + ESP_LOGW(TAG, "Auth: Reading cnonce failed"); goto error; // NOLINT(cppcoreguidelines-avoid-goto) } sbuf[32] = '\0'; @@ -233,7 +210,7 @@ void OTAComponent::handle_() { // Receive result, 32 bytes hex MD5 if (!this->readall_(buf + 64, 32)) { - ESP_LOGW(TAG, "Auth: Reading response failed!"); + ESP_LOGW(TAG, "Auth: Reading response failed"); goto error; // NOLINT(cppcoreguidelines-avoid-goto) } sbuf[64 + 32] = '\0'; @@ -244,20 +221,20 @@ void OTAComponent::handle_() { matches = matches && buf[i] == buf[64 + i]; if (!matches) { - ESP_LOGW(TAG, "Auth failed! Passwords do not match!"); - error_code = OTA_RESPONSE_ERROR_AUTH_INVALID; + ESP_LOGW(TAG, "Auth failed! Passwords do not match"); + error_code = ota::OTA_RESPONSE_ERROR_AUTH_INVALID; goto error; // NOLINT(cppcoreguidelines-avoid-goto) } } #endif // USE_OTA_PASSWORD // Acknowledge auth OK - 1 byte - buf[0] = OTA_RESPONSE_AUTH_OK; + buf[0] = ota::OTA_RESPONSE_AUTH_OK; this->writeall_(buf, 1); // Read size, 4 bytes MSB first if (!this->readall_(buf, 4)) { - ESP_LOGW(TAG, "Reading size failed!"); + ESP_LOGW(TAG, "Reading size failed"); goto error; // NOLINT(cppcoreguidelines-avoid-goto) } ota_size = 0; @@ -265,20 +242,20 @@ void OTAComponent::handle_() { ota_size <<= 8; ota_size |= buf[i]; } - ESP_LOGV(TAG, "OTA size is %u bytes", ota_size); + ESP_LOGV(TAG, "Size is %u bytes", ota_size); error_code = backend->begin(ota_size); - if (error_code != OTA_RESPONSE_OK) + if (error_code != ota::OTA_RESPONSE_OK) goto error; // NOLINT(cppcoreguidelines-avoid-goto) update_started = true; // Acknowledge prepare OK - 1 byte - buf[0] = OTA_RESPONSE_UPDATE_PREPARE_OK; + buf[0] = ota::OTA_RESPONSE_UPDATE_PREPARE_OK; this->writeall_(buf, 1); // Read binary MD5, 32 bytes if (!this->readall_(buf, 32)) { - ESP_LOGW(TAG, "Reading binary MD5 checksum failed!"); + ESP_LOGW(TAG, "Reading binary MD5 checksum failed"); goto error; // NOLINT(cppcoreguidelines-avoid-goto) } sbuf[32] = '\0'; @@ -286,7 +263,7 @@ void OTAComponent::handle_() { backend->set_update_md5(sbuf); // Acknowledge MD5 OK - 1 byte - buf[0] = OTA_RESPONSE_BIN_MD5_OK; + buf[0] = ota::OTA_RESPONSE_BIN_MD5_OK; this->writeall_(buf, 1); while (total < ota_size) { @@ -299,7 +276,7 @@ void OTAComponent::handle_() { delay(1); continue; } - ESP_LOGW(TAG, "Error receiving data for update, errno: %d", errno); + ESP_LOGW(TAG, "Error receiving data for update, errno %d", errno); goto error; // NOLINT(cppcoreguidelines-avoid-goto) } else if (read == 0) { // $ man recv @@ -310,14 +287,14 @@ void OTAComponent::handle_() { } error_code = backend->write(buf, read); - if (error_code != OTA_RESPONSE_OK) { + if (error_code != ota::OTA_RESPONSE_OK) { ESP_LOGW(TAG, "Error writing binary data to flash!, error_code: %d", error_code); goto error; // NOLINT(cppcoreguidelines-avoid-goto) } total += read; #if USE_OTA_VERSION == 2 while (size_acknowledged + OTA_BLOCK_SIZE <= total || (total == ota_size && size_acknowledged < ota_size)) { - buf[0] = OTA_RESPONSE_CHUNK_OK; + buf[0] = ota::OTA_RESPONSE_CHUNK_OK; this->writeall_(buf, 1); size_acknowledged += OTA_BLOCK_SIZE; } @@ -327,9 +304,9 @@ void OTAComponent::handle_() { if (now - last_progress > 1000) { last_progress = now; float percentage = (total * 100.0f) / ota_size; - ESP_LOGD(TAG, "OTA in progress: %0.1f%%", percentage); + ESP_LOGD(TAG, "Progress: %0.1f%%", percentage); #ifdef USE_OTA_STATE_CALLBACK - this->state_callback_.call(OTA_IN_PROGRESS, percentage, 0); + this->state_callback_.call(ota::OTA_IN_PROGRESS, percentage, 0); #endif // feed watchdog and give other tasks a chance to run App.feed_wdt(); @@ -338,32 +315,32 @@ void OTAComponent::handle_() { } // Acknowledge receive OK - 1 byte - buf[0] = OTA_RESPONSE_RECEIVE_OK; + buf[0] = ota::OTA_RESPONSE_RECEIVE_OK; this->writeall_(buf, 1); error_code = backend->end(); - if (error_code != OTA_RESPONSE_OK) { - ESP_LOGW(TAG, "Error ending OTA!, error_code: %d", error_code); + if (error_code != ota::OTA_RESPONSE_OK) { + ESP_LOGW(TAG, "Error ending update! error_code: %d", error_code); goto error; // NOLINT(cppcoreguidelines-avoid-goto) } // Acknowledge Update end OK - 1 byte - buf[0] = OTA_RESPONSE_UPDATE_END_OK; + buf[0] = ota::OTA_RESPONSE_UPDATE_END_OK; this->writeall_(buf, 1); // Read ACK - if (!this->readall_(buf, 1) || buf[0] != OTA_RESPONSE_OK) { - ESP_LOGW(TAG, "Reading back acknowledgement failed!"); + if (!this->readall_(buf, 1) || buf[0] != ota::OTA_RESPONSE_OK) { + ESP_LOGW(TAG, "Reading back acknowledgement failed"); // do not go to error, this is not fatal } this->client_->close(); this->client_ = nullptr; delay(10); - ESP_LOGI(TAG, "OTA update finished!"); + ESP_LOGI(TAG, "Update complete"); this->status_clear_warning(); #ifdef USE_OTA_STATE_CALLBACK - this->state_callback_.call(OTA_COMPLETED, 100.0f, 0); + this->state_callback_.call(ota::OTA_COMPLETED, 100.0f, 0); #endif delay(100); // NOLINT App.safe_reboot(); @@ -380,11 +357,11 @@ error: this->status_momentary_error("onerror", 5000); #ifdef USE_OTA_STATE_CALLBACK - this->state_callback_.call(OTA_ERROR, 0.0f, static_cast(error_code)); + this->state_callback_.call(ota::OTA_ERROR, 0.0f, static_cast(error_code)); #endif } -bool OTAComponent::readall_(uint8_t *buf, size_t len) { +bool ESPHomeOTAComponent::readall_(uint8_t *buf, size_t len) { uint32_t start = millis(); uint32_t at = 0; while (len - at > 0) { @@ -401,7 +378,7 @@ bool OTAComponent::readall_(uint8_t *buf, size_t len) { delay(1); continue; } - ESP_LOGW(TAG, "Failed to read %d bytes of data, errno: %d", len, errno); + ESP_LOGW(TAG, "Failed to read %d bytes of data, errno %d", len, errno); return false; } else if (read == 0) { ESP_LOGW(TAG, "Remote closed connection"); @@ -415,7 +392,7 @@ bool OTAComponent::readall_(uint8_t *buf, size_t len) { return true; } -bool OTAComponent::writeall_(const uint8_t *buf, size_t len) { +bool ESPHomeOTAComponent::writeall_(const uint8_t *buf, size_t len) { uint32_t start = millis(); uint32_t at = 0; while (len - at > 0) { @@ -432,7 +409,7 @@ bool OTAComponent::writeall_(const uint8_t *buf, size_t len) { delay(1); continue; } - ESP_LOGW(TAG, "Failed to write %d bytes of data, errno: %d", len, errno); + ESP_LOGW(TAG, "Failed to write %d bytes of data, errno %d", len, errno); return false; } else { at += written; @@ -443,31 +420,31 @@ bool OTAComponent::writeall_(const uint8_t *buf, size_t len) { return true; } -float OTAComponent::get_setup_priority() const { return setup_priority::AFTER_WIFI; } -uint16_t OTAComponent::get_port() const { return this->port_; } -void OTAComponent::set_port(uint16_t port) { this->port_ = port; } +float ESPHomeOTAComponent::get_setup_priority() const { return setup_priority::AFTER_WIFI; } +uint16_t ESPHomeOTAComponent::get_port() const { return this->port_; } +void ESPHomeOTAComponent::set_port(uint16_t port) { this->port_ = port; } -void OTAComponent::set_safe_mode_pending(const bool &pending) { +void ESPHomeOTAComponent::set_safe_mode_pending(const bool &pending) { if (!this->has_safe_mode_) return; uint32_t current_rtc = this->read_rtc_(); - if (pending && current_rtc != esphome::ota::OTAComponent::ENTER_SAFE_MODE_MAGIC) { - ESP_LOGI(TAG, "Device will enter safe mode on next boot."); - this->write_rtc_(esphome::ota::OTAComponent::ENTER_SAFE_MODE_MAGIC); + if (pending && current_rtc != ESPHomeOTAComponent::ENTER_SAFE_MODE_MAGIC) { + ESP_LOGI(TAG, "Device will enter safe mode on next boot"); + this->write_rtc_(ESPHomeOTAComponent::ENTER_SAFE_MODE_MAGIC); } - if (!pending && current_rtc == esphome::ota::OTAComponent::ENTER_SAFE_MODE_MAGIC) { + if (!pending && current_rtc == ESPHomeOTAComponent::ENTER_SAFE_MODE_MAGIC) { ESP_LOGI(TAG, "Safe mode pending has been cleared"); this->clean_rtc(); } } -bool OTAComponent::get_safe_mode_pending() { - return this->has_safe_mode_ && this->read_rtc_() == esphome::ota::OTAComponent::ENTER_SAFE_MODE_MAGIC; +bool ESPHomeOTAComponent::get_safe_mode_pending() { + return this->has_safe_mode_ && this->read_rtc_() == ESPHomeOTAComponent::ENTER_SAFE_MODE_MAGIC; } -bool OTAComponent::should_enter_safe_mode(uint8_t num_attempts, uint32_t enable_time) { +bool ESPHomeOTAComponent::should_enter_safe_mode(uint8_t num_attempts, uint32_t enable_time) { this->has_safe_mode_ = true; this->safe_mode_start_time_ = millis(); this->safe_mode_enable_time_ = enable_time; @@ -475,24 +452,24 @@ bool OTAComponent::should_enter_safe_mode(uint8_t num_attempts, uint32_t enable_ this->rtc_ = global_preferences->make_preference(233825507UL, false); this->safe_mode_rtc_value_ = this->read_rtc_(); - bool is_manual_safe_mode = this->safe_mode_rtc_value_ == esphome::ota::OTAComponent::ENTER_SAFE_MODE_MAGIC; + bool is_manual_safe_mode = this->safe_mode_rtc_value_ == ESPHomeOTAComponent::ENTER_SAFE_MODE_MAGIC; if (is_manual_safe_mode) { ESP_LOGI(TAG, "Safe mode has been entered manually"); } else { - ESP_LOGCONFIG(TAG, "There have been %" PRIu32 " suspected unsuccessful boot attempts.", this->safe_mode_rtc_value_); + ESP_LOGCONFIG(TAG, "There have been %" PRIu32 " suspected unsuccessful boot attempts", this->safe_mode_rtc_value_); } if (this->safe_mode_rtc_value_ >= num_attempts || is_manual_safe_mode) { this->clean_rtc(); if (!is_manual_safe_mode) { - ESP_LOGE(TAG, "Boot loop detected. Proceeding to safe mode."); + ESP_LOGE(TAG, "Boot loop detected. Proceeding to safe mode"); } this->status_set_error(); this->set_timeout(enable_time, []() { - ESP_LOGE(TAG, "No OTA attempt made, restarting."); + ESP_LOGE(TAG, "No OTA attempt made, restarting"); App.reboot(); }); @@ -500,7 +477,7 @@ bool OTAComponent::should_enter_safe_mode(uint8_t num_attempts, uint32_t enable_ delay(300); // NOLINT App.setup(); - ESP_LOGI(TAG, "Waiting for OTA attempt."); + ESP_LOGI(TAG, "Waiting for OTA attempt"); return true; } else { @@ -509,27 +486,23 @@ bool OTAComponent::should_enter_safe_mode(uint8_t num_attempts, uint32_t enable_ return false; } } -void OTAComponent::write_rtc_(uint32_t val) { + +void ESPHomeOTAComponent::write_rtc_(uint32_t val) { this->rtc_.save(&val); global_preferences->sync(); } -uint32_t OTAComponent::read_rtc_() { + +uint32_t ESPHomeOTAComponent::read_rtc_() { uint32_t val; if (!this->rtc_.load(&val)) return 0; return val; } -void OTAComponent::clean_rtc() { this->write_rtc_(0); } -void OTAComponent::on_safe_shutdown() { - if (this->has_safe_mode_ && this->read_rtc_() != esphome::ota::OTAComponent::ENTER_SAFE_MODE_MAGIC) + +void ESPHomeOTAComponent::clean_rtc() { this->write_rtc_(0); } + +void ESPHomeOTAComponent::on_safe_shutdown() { + if (this->has_safe_mode_ && this->read_rtc_() != ESPHomeOTAComponent::ENTER_SAFE_MODE_MAGIC) this->clean_rtc(); } - -#ifdef USE_OTA_STATE_CALLBACK -void OTAComponent::add_on_state_callback(std::function &&callback) { - this->state_callback_.add(std::move(callback)); -} -#endif - -} // namespace ota } // namespace esphome diff --git a/esphome/components/ota/ota_component.h b/esphome/components/esphome/ota/ota_esphome.h similarity index 50% rename from esphome/components/ota/ota_component.h rename to esphome/components/esphome/ota/ota_esphome.h index c20f4f0709..e8f36f05ca 100644 --- a/esphome/components/ota/ota_component.h +++ b/esphome/components/esphome/ota/ota_esphome.h @@ -1,49 +1,16 @@ #pragma once -#include "esphome/components/socket/socket.h" -#include "esphome/core/component.h" -#include "esphome/core/preferences.h" -#include "esphome/core/helpers.h" #include "esphome/core/defines.h" +#include "esphome/core/helpers.h" +#include "esphome/core/preferences.h" +#include "esphome/components/ota/ota_backend.h" +#include "esphome/components/socket/socket.h" namespace esphome { -namespace ota { -enum OTAResponseTypes { - OTA_RESPONSE_OK = 0x00, - OTA_RESPONSE_REQUEST_AUTH = 0x01, - - OTA_RESPONSE_HEADER_OK = 0x40, - OTA_RESPONSE_AUTH_OK = 0x41, - OTA_RESPONSE_UPDATE_PREPARE_OK = 0x42, - OTA_RESPONSE_BIN_MD5_OK = 0x43, - OTA_RESPONSE_RECEIVE_OK = 0x44, - OTA_RESPONSE_UPDATE_END_OK = 0x45, - OTA_RESPONSE_SUPPORTS_COMPRESSION = 0x46, - OTA_RESPONSE_CHUNK_OK = 0x47, - - OTA_RESPONSE_ERROR_MAGIC = 0x80, - OTA_RESPONSE_ERROR_UPDATE_PREPARE = 0x81, - OTA_RESPONSE_ERROR_AUTH_INVALID = 0x82, - OTA_RESPONSE_ERROR_WRITING_FLASH = 0x83, - OTA_RESPONSE_ERROR_UPDATE_END = 0x84, - OTA_RESPONSE_ERROR_INVALID_BOOTSTRAPPING = 0x85, - OTA_RESPONSE_ERROR_WRONG_CURRENT_FLASH_CONFIG = 0x86, - OTA_RESPONSE_ERROR_WRONG_NEW_FLASH_CONFIG = 0x87, - OTA_RESPONSE_ERROR_ESP8266_NOT_ENOUGH_SPACE = 0x88, - OTA_RESPONSE_ERROR_ESP32_NOT_ENOUGH_SPACE = 0x89, - OTA_RESPONSE_ERROR_NO_UPDATE_PARTITION = 0x8A, - OTA_RESPONSE_ERROR_MD5_MISMATCH = 0x8B, - OTA_RESPONSE_ERROR_RP2040_NOT_ENOUGH_SPACE = 0x8C, - OTA_RESPONSE_ERROR_UNKNOWN = 0xFF, -}; - -enum OTAState { OTA_COMPLETED = 0, OTA_STARTED, OTA_IN_PROGRESS, OTA_ERROR }; - -/// OTAComponent provides a simple way to integrate Over-the-Air updates into your app using ArduinoOTA. -class OTAComponent : public Component { +/// ESPHomeOTAComponent provides a simple way to integrate Over-the-Air updates into your app using ArduinoOTA. +class ESPHomeOTAComponent : public ota::OTAComponent { public: - OTAComponent(); #ifdef USE_OTA_PASSWORD void set_auth_password(const std::string &password) { password_ = password; } #endif // USE_OTA_PASSWORD @@ -57,10 +24,6 @@ class OTAComponent : public Component { void set_safe_mode_pending(const bool &pending); bool get_safe_mode_pending(); -#ifdef USE_OTA_STATE_CALLBACK - void add_on_state_callback(std::function &&callback); -#endif - // ========== INTERNAL METHODS ========== // (In most use cases you won't need these) void setup() override; @@ -91,22 +54,15 @@ class OTAComponent : public Component { std::unique_ptr server_; std::unique_ptr client_; - bool has_safe_mode_{false}; ///< stores whether safe mode can be enabled. - uint32_t safe_mode_start_time_; ///< stores when safe mode was enabled. - uint32_t safe_mode_enable_time_{60000}; ///< The time safe mode should be on for. + bool has_safe_mode_{false}; ///< stores whether safe mode can be enabled + uint32_t safe_mode_start_time_; ///< stores when safe mode was enabled + uint32_t safe_mode_enable_time_{60000}; ///< The time safe mode should be on for uint32_t safe_mode_rtc_value_; uint8_t safe_mode_num_attempts_; ESPPreferenceObject rtc_; static const uint32_t ENTER_SAFE_MODE_MAGIC = 0x5afe5afe; ///< a magic number to indicate that safe mode should be entered on next boot - -#ifdef USE_OTA_STATE_CALLBACK - CallbackManager state_callback_{}; -#endif }; -extern OTAComponent *global_ota_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) - -} // namespace ota } // namespace esphome diff --git a/esphome/components/i2c/i2c_bus_esp_idf.cpp b/esphome/components/i2c/i2c_bus_esp_idf.cpp index cbb748cca1..3a9c229778 100644 --- a/esphome/components/i2c/i2c_bus_esp_idf.cpp +++ b/esphome/components/i2c/i2c_bus_esp_idf.cpp @@ -56,7 +56,7 @@ void IDFI2CBus::setup() { this->mark_failed(); return; } else { - ESP_LOGV(TAG, "i2c_timeout set to %d ticks (%d us)", timeout_ * 80, timeout_); + ESP_LOGV(TAG, "i2c_timeout set to %" PRIu32 " ticks (%" PRIu32 " us)", timeout_ * 80, timeout_); } } err = i2c_driver_install(port_, I2C_MODE_MASTER, 0, 0, ESP_INTR_FLAG_IRAM); diff --git a/esphome/components/i2s_audio/media_player/i2s_audio_media_player.cpp b/esphome/components/i2s_audio/media_player/i2s_audio_media_player.cpp index 6e07983920..1890e27bdf 100644 --- a/esphome/components/i2s_audio/media_player/i2s_audio_media_player.cpp +++ b/esphome/components/i2s_audio/media_player/i2s_audio_media_player.cpp @@ -10,6 +10,11 @@ namespace i2s_audio { static const char *const TAG = "audio"; void I2SAudioMediaPlayer::control(const media_player::MediaPlayerCall &call) { + media_player::MediaPlayerState play_state = media_player::MEDIA_PLAYER_STATE_PLAYING; + if (call.get_announcement().has_value()) { + play_state = call.get_announcement().value() ? media_player::MEDIA_PLAYER_STATE_ANNOUNCING + : media_player::MEDIA_PLAYER_STATE_PLAYING; + } if (call.get_media_url().has_value()) { this->current_url_ = call.get_media_url(); if (this->i2s_state_ != I2S_STATE_STOPPED && this->audio_ != nullptr) { @@ -17,7 +22,7 @@ void I2SAudioMediaPlayer::control(const media_player::MediaPlayerCall &call) { this->audio_->stopSong(); } this->audio_->connecttohost(this->current_url_.value().c_str()); - this->state = media_player::MEDIA_PLAYER_STATE_PLAYING; + this->state = play_state; } else { this->start(); } @@ -35,7 +40,7 @@ void I2SAudioMediaPlayer::control(const media_player::MediaPlayerCall &call) { case media_player::MEDIA_PLAYER_COMMAND_PLAY: if (!this->audio_->isRunning()) this->audio_->pauseResume(); - this->state = media_player::MEDIA_PLAYER_STATE_PLAYING; + this->state = play_state; break; case media_player::MEDIA_PLAYER_COMMAND_PAUSE: if (this->audio_->isRunning()) @@ -126,7 +131,9 @@ void I2SAudioMediaPlayer::loop() { void I2SAudioMediaPlayer::play_() { this->audio_->loop(); - if (this->state == media_player::MEDIA_PLAYER_STATE_PLAYING && !this->audio_->isRunning()) { + if ((this->state == media_player::MEDIA_PLAYER_STATE_PLAYING || + this->state == media_player::MEDIA_PLAYER_STATE_ANNOUNCING) && + !this->audio_->isRunning()) { this->stop(); } } @@ -164,6 +171,10 @@ void I2SAudioMediaPlayer::start_() { if (this->current_url_.has_value()) { this->audio_->connecttohost(this->current_url_.value().c_str()); this->state = media_player::MEDIA_PLAYER_STATE_PLAYING; + if (this->is_announcement_.has_value()) { + this->state = this->is_announcement_.value() ? media_player::MEDIA_PLAYER_STATE_ANNOUNCING + : media_player::MEDIA_PLAYER_STATE_PLAYING; + } this->publish_state(); } } diff --git a/esphome/components/i2s_audio/media_player/i2s_audio_media_player.h b/esphome/components/i2s_audio/media_player/i2s_audio_media_player.h index 092e6de8e8..d7d9b1f74a 100644 --- a/esphome/components/i2s_audio/media_player/i2s_audio_media_player.h +++ b/esphome/components/i2s_audio/media_player/i2s_audio_media_player.h @@ -78,6 +78,7 @@ class I2SAudioMediaPlayer : public Component, public media_player::MediaPlayer, HighFrequencyLoopRequester high_freq_; optional current_url_{}; + optional is_announcement_{}; }; } // namespace i2s_audio diff --git a/esphome/components/ina2xx_base/__init__.py b/esphome/components/ina2xx_base/__init__.py new file mode 100644 index 0000000000..35b5baa83e --- /dev/null +++ b/esphome/components/ina2xx_base/__init__.py @@ -0,0 +1,255 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.components import sensor +from esphome.const import ( + CONF_BUS_VOLTAGE, + CONF_CURRENT, + CONF_ENERGY, + CONF_MAX_CURRENT, + CONF_MODEL, + CONF_NAME, + CONF_POWER, + CONF_SHUNT_RESISTANCE, + CONF_SHUNT_VOLTAGE, + CONF_TEMPERATURE, + DEVICE_CLASS_CURRENT, + DEVICE_CLASS_ENERGY, + DEVICE_CLASS_POWER, + DEVICE_CLASS_TEMPERATURE, + DEVICE_CLASS_VOLTAGE, + STATE_CLASS_MEASUREMENT, + UNIT_AMPERE, + UNIT_CELSIUS, + UNIT_VOLT, + UNIT_WATT_HOURS, + UNIT_WATT, +) + +CODEOWNERS = ["@latonita"] + +CONF_ADC_AVERAGING = "adc_averaging" +CONF_ADC_RANGE = "adc_range" +CONF_ADC_TIME = "adc_time" +CONF_CHARGE = "charge" +CONF_CHARGE_COULOMBS = "charge_coulombs" +CONF_ENERGY_JOULES = "energy_joules" +CONF_TEMPERATURE_COEFFICIENT = "temperature_coefficient" +UNIT_AMPERE_HOURS = "Ah" +UNIT_COULOMB = "C" +UNIT_JOULE = "J" +UNIT_MILLIVOLT = "mV" + +ina2xx_base_ns = cg.esphome_ns.namespace("ina2xx_base") +INA2XX = ina2xx_base_ns.class_("INA2XX", cg.PollingComponent) + +AdcTime = ina2xx_base_ns.enum("AdcTime") +ADC_TIMES = { + 50: AdcTime.ADC_TIME_50US, + 84: AdcTime.ADC_TIME_84US, + 150: AdcTime.ADC_TIME_150US, + 280: AdcTime.ADC_TIME_280US, + 540: AdcTime.ADC_TIME_540US, + 1052: AdcTime.ADC_TIME_1052US, + 2074: AdcTime.ADC_TIME_2074US, + 4120: AdcTime.ADC_TIME_4120US, +} + +AdcAvgSamples = ina2xx_base_ns.enum("AdcAvgSamples") +ADC_SAMPLES = { + 1: AdcAvgSamples.ADC_AVG_SAMPLES_1, + 4: AdcAvgSamples.ADC_AVG_SAMPLES_4, + 16: AdcAvgSamples.ADC_AVG_SAMPLES_16, + 64: AdcAvgSamples.ADC_AVG_SAMPLES_64, + 128: AdcAvgSamples.ADC_AVG_SAMPLES_128, + 256: AdcAvgSamples.ADC_AVG_SAMPLES_256, + 512: AdcAvgSamples.ADC_AVG_SAMPLES_512, + 1024: AdcAvgSamples.ADC_AVG_SAMPLES_1024, +} + +SENSOR_MODEL_OPTIONS = { + CONF_ENERGY: ["INA228", "INA229"], + CONF_ENERGY_JOULES: ["INA228", "INA229"], + CONF_CHARGE: ["INA228", "INA229"], + CONF_CHARGE_COULOMBS: ["INA228", "INA229"], +} + + +def validate_model_config(config): + model = config[CONF_MODEL] + + for key in config: + if key in SENSOR_MODEL_OPTIONS: + if model not in SENSOR_MODEL_OPTIONS[key]: + raise cv.Invalid( + f"Device model '{model}' does not support '{key}' sensor" + ) + + tempco = config[CONF_TEMPERATURE_COEFFICIENT] + if tempco > 0 and model not in ["INA228", "INA229"]: + raise cv.Invalid( + f"Device model '{model}' does not support temperature coefficient" + ) + + return config + + +def validate_adc_time(value): + value = cv.positive_time_period_microseconds(value).total_microseconds + return cv.enum(ADC_TIMES, int=True)(value) + + +INA2XX_SCHEMA = cv.Schema( + { + cv.Required(CONF_SHUNT_RESISTANCE): cv.All(cv.resistance, cv.Range(min=0.0)), + cv.Required(CONF_MAX_CURRENT): cv.All(cv.current, cv.Range(min=0.0)), + cv.Optional(CONF_ADC_RANGE, default=0): cv.int_range(min=0, max=1), + cv.Optional(CONF_ADC_TIME, default="4120 us"): cv.Any( + validate_adc_time, + { + cv.Optional(CONF_BUS_VOLTAGE, default="4120 us"): validate_adc_time, + cv.Optional(CONF_SHUNT_VOLTAGE, default="4120 us"): validate_adc_time, + cv.Optional(CONF_TEMPERATURE, default="4120 us"): validate_adc_time, + }, + ), + cv.Optional(CONF_ADC_AVERAGING, default=128): cv.enum(ADC_SAMPLES, int=True), + cv.Optional(CONF_TEMPERATURE_COEFFICIENT, default=0): cv.int_range( + min=0, max=16383 + ), + cv.Optional(CONF_SHUNT_VOLTAGE): cv.maybe_simple_value( + sensor.sensor_schema( + unit_of_measurement=UNIT_MILLIVOLT, + accuracy_decimals=5, + device_class=DEVICE_CLASS_VOLTAGE, + state_class=STATE_CLASS_MEASUREMENT, + ), + key=CONF_NAME, + ), + cv.Optional(CONF_BUS_VOLTAGE): cv.maybe_simple_value( + sensor.sensor_schema( + unit_of_measurement=UNIT_VOLT, + accuracy_decimals=5, + device_class=DEVICE_CLASS_VOLTAGE, + state_class=STATE_CLASS_MEASUREMENT, + ), + key=CONF_NAME, + ), + cv.Optional(CONF_TEMPERATURE): cv.maybe_simple_value( + sensor.sensor_schema( + unit_of_measurement=UNIT_CELSIUS, + accuracy_decimals=5, + device_class=DEVICE_CLASS_TEMPERATURE, + state_class=STATE_CLASS_MEASUREMENT, + ), + key=CONF_NAME, + ), + cv.Optional(CONF_CURRENT): cv.maybe_simple_value( + sensor.sensor_schema( + unit_of_measurement=UNIT_AMPERE, + accuracy_decimals=8, + device_class=DEVICE_CLASS_CURRENT, + state_class=STATE_CLASS_MEASUREMENT, + ), + key=CONF_NAME, + ), + cv.Optional(CONF_POWER): cv.maybe_simple_value( + sensor.sensor_schema( + unit_of_measurement=UNIT_WATT, + accuracy_decimals=6, + device_class=DEVICE_CLASS_POWER, + state_class=STATE_CLASS_MEASUREMENT, + ), + key=CONF_NAME, + ), + cv.Optional(CONF_ENERGY): cv.maybe_simple_value( + sensor.sensor_schema( + unit_of_measurement=UNIT_WATT_HOURS, + accuracy_decimals=8, + device_class=DEVICE_CLASS_ENERGY, + state_class=STATE_CLASS_MEASUREMENT, + ), + key=CONF_NAME, + ), + cv.Optional(CONF_ENERGY_JOULES): cv.maybe_simple_value( + sensor.sensor_schema( + unit_of_measurement=UNIT_JOULE, + accuracy_decimals=8, + state_class=STATE_CLASS_MEASUREMENT, + ), + key=CONF_NAME, + ), + cv.Optional(CONF_CHARGE): cv.maybe_simple_value( + sensor.sensor_schema( + unit_of_measurement=UNIT_AMPERE_HOURS, + accuracy_decimals=8, + state_class=STATE_CLASS_MEASUREMENT, + ), + key=CONF_NAME, + ), + cv.Optional(CONF_CHARGE_COULOMBS): cv.maybe_simple_value( + sensor.sensor_schema( + unit_of_measurement=UNIT_COULOMB, + accuracy_decimals=8, + state_class=STATE_CLASS_MEASUREMENT, + ), + key=CONF_NAME, + ), + } +).extend(cv.polling_component_schema("60s")) + + +async def setup_ina2xx(var, config): + await cg.register_component(var, config) + + cg.add(var.set_model(config[CONF_MODEL])) + + cg.add(var.set_shunt_resistance_ohm(config[CONF_SHUNT_RESISTANCE])) + cg.add(var.set_max_current_a(config[CONF_MAX_CURRENT])) + cg.add(var.set_adc_range(config[CONF_ADC_RANGE])) + cg.add(var.set_adc_avg_samples(config[CONF_ADC_AVERAGING])) + cg.add(var.set_shunt_tempco(config[CONF_TEMPERATURE_COEFFICIENT])) + + adc_time_config = config[CONF_ADC_TIME] + if isinstance(adc_time_config, dict): + cg.add(var.set_adc_time_bus_voltage(adc_time_config[CONF_BUS_VOLTAGE])) + cg.add(var.set_adc_time_shunt_voltage(adc_time_config[CONF_SHUNT_VOLTAGE])) + cg.add(var.set_adc_time_die_temperature(adc_time_config[CONF_TEMPERATURE])) + else: + cg.add(var.set_adc_time_bus_voltage(adc_time_config)) + cg.add(var.set_adc_time_shunt_voltage(adc_time_config)) + cg.add(var.set_adc_time_die_temperature(adc_time_config)) + + if conf := config.get(CONF_SHUNT_VOLTAGE): + sens = await sensor.new_sensor(conf) + cg.add(var.set_shunt_voltage_sensor(sens)) + + if conf := config.get(CONF_BUS_VOLTAGE): + sens = await sensor.new_sensor(conf) + cg.add(var.set_bus_voltage_sensor(sens)) + + if conf := config.get(CONF_TEMPERATURE): + sens = await sensor.new_sensor(conf) + cg.add(var.set_die_temperature_sensor(sens)) + + if conf := config.get(CONF_CURRENT): + sens = await sensor.new_sensor(conf) + cg.add(var.set_current_sensor(sens)) + + if conf := config.get(CONF_POWER): + sens = await sensor.new_sensor(conf) + cg.add(var.set_power_sensor(sens)) + + if conf := config.get(CONF_ENERGY): + sens = await sensor.new_sensor(conf) + cg.add(var.set_energy_sensor_wh(sens)) + + if conf := config.get(CONF_ENERGY_JOULES): + sens = await sensor.new_sensor(conf) + cg.add(var.set_energy_sensor_j(sens)) + + if conf := config.get(CONF_CHARGE): + sens = await sensor.new_sensor(conf) + cg.add(var.set_charge_sensor_ah(sens)) + + if conf := config.get(CONF_CHARGE_COULOMBS): + sens = await sensor.new_sensor(conf) + cg.add(var.set_charge_sensor_c(sens)) diff --git a/esphome/components/ina2xx_base/ina2xx_base.cpp b/esphome/components/ina2xx_base/ina2xx_base.cpp new file mode 100644 index 0000000000..5d947d0537 --- /dev/null +++ b/esphome/components/ina2xx_base/ina2xx_base.cpp @@ -0,0 +1,604 @@ +#include "ina2xx_base.h" +#include "esphome/core/log.h" +#include "esphome/core/hal.h" +#include "esphome/core/helpers.h" +#include +#include + +namespace esphome { +namespace ina2xx_base { + +static const char *const TAG = "ina2xx"; + +#define OKFAILED(b) ((b) ? "OK" : "FAILED") + +static const uint16_t ADC_TIMES[8] = {50, 84, 150, 280, 540, 1052, 2074, 4120}; +static const uint16_t ADC_SAMPLES[8] = {1, 4, 16, 64, 128, 256, 512, 1024}; + +static const char *get_device_name(INAModel model) { + switch (model) { + case INAModel::INA_228: + return "INA228"; + case INAModel::INA_229: + return "INA229"; + case INAModel::INA_238: + return "INA238"; + case INAModel::INA_239: + return "INA239"; + case INAModel::INA_237: + return "INA237"; + default: + return "UNKNOWN"; + } +}; + +static bool check_model_and_device_match(INAModel model, uint16_t dev_id) { + switch (model) { + case INAModel::INA_228: + return dev_id == 0x228; + case INAModel::INA_229: + return dev_id == 0x229; + case INAModel::INA_238: + return dev_id == 0x238; + case INAModel::INA_239: + return dev_id == 0x239; + case INAModel::INA_237: + return dev_id == 0x237; + default: + return false; + } +} + +void INA2XX::setup() { + ESP_LOGCONFIG(TAG, "Setting up INA2xx..."); + + if (!this->reset_config_()) { + ESP_LOGE(TAG, "Reset failed, check connection"); + this->mark_failed(); + return; + } + delay(2); + + if (!this->check_device_model_()) { + ESP_LOGE(TAG, "Device not supported or model selected improperly in yaml file"); + this->mark_failed(); + return; + } + delay(1); + + this->configure_adc_range_(); + delay(1); + + this->configure_adc_(); + delay(1); + + this->configure_shunt_(); + delay(1); + + this->configure_shunt_tempco_(); + delay(1); + + this->state_ = State::IDLE; +} + +float INA2XX::get_setup_priority() const { return setup_priority::DATA; } + +void INA2XX::update() { + ESP_LOGD(TAG, "Updating"); + if (this->is_ready() && this->state_ == State::IDLE) { + ESP_LOGD(TAG, "Initiating new data collection"); + this->state_ = State::DATA_COLLECTION_1; + return; + } +} + +void INA2XX::loop() { + if (this->is_ready()) { + switch (this->state_) { + case State::NOT_INITIALIZED: + case State::IDLE: + break; + + case State::DATA_COLLECTION_1: + this->full_loop_is_okay_ = true; + + if (this->shunt_voltage_sensor_ != nullptr) { + float shunt_voltage{0}; + this->full_loop_is_okay_ &= this->read_shunt_voltage_mv_(shunt_voltage); + this->shunt_voltage_sensor_->publish_state(shunt_voltage); + } + this->state_ = State::DATA_COLLECTION_2; + break; + + case State::DATA_COLLECTION_2: + if (this->bus_voltage_sensor_ != nullptr) { + float bus_voltage{0}; + this->full_loop_is_okay_ &= this->read_bus_voltage_(bus_voltage); + this->bus_voltage_sensor_->publish_state(bus_voltage); + } + this->state_ = State::DATA_COLLECTION_3; + break; + + case State::DATA_COLLECTION_3: + if (this->die_temperature_sensor_ != nullptr) { + float die_temperature{0}; + this->full_loop_is_okay_ &= this->read_die_temp_c_(die_temperature); + this->die_temperature_sensor_->publish_state(die_temperature); + } + this->state_ = State::DATA_COLLECTION_4; + break; + + case State::DATA_COLLECTION_4: + if (this->current_sensor_ != nullptr) { + float current{0}; + this->full_loop_is_okay_ &= this->read_current_a_(current); + this->current_sensor_->publish_state(current); + } + this->state_ = State::DATA_COLLECTION_5; + break; + + case State::DATA_COLLECTION_5: + if (this->power_sensor_ != nullptr) { + float power{0}; + this->full_loop_is_okay_ &= this->read_power_w_(power); + this->power_sensor_->publish_state(power); + } + this->state_ = State::DATA_COLLECTION_6; + break; + + case State::DATA_COLLECTION_6: + if (this->ina_model_ == INAModel::INA_228 || this->ina_model_ == INAModel::INA_229) { + if (this->energy_sensor_j_ != nullptr || this->energy_sensor_wh_ != nullptr || + this->charge_sensor_c_ != nullptr || this->charge_sensor_ah_ != nullptr) { + this->read_diagnostics_and_act_(); + } + if (this->energy_sensor_j_ != nullptr || this->energy_sensor_wh_ != nullptr) { + double energy_j{0}, energy_wh{0}; + this->full_loop_is_okay_ &= this->read_energy_(energy_j, energy_wh); + if (this->energy_sensor_j_ != nullptr) + this->energy_sensor_j_->publish_state(energy_j); + if (this->energy_sensor_wh_ != nullptr) + this->energy_sensor_wh_->publish_state(energy_wh); + } + } + this->state_ = State::DATA_COLLECTION_7; + break; + + case State::DATA_COLLECTION_7: + if (this->ina_model_ == INAModel::INA_228 || this->ina_model_ == INAModel::INA_229) { + if (this->charge_sensor_c_ != nullptr || this->charge_sensor_ah_ != nullptr) { + double charge_c{0}, charge_ah{0}; + this->full_loop_is_okay_ &= this->read_charge_(charge_c, charge_ah); + if (this->charge_sensor_c_ != nullptr) + this->charge_sensor_c_->publish_state(charge_c); + if (this->charge_sensor_ah_ != nullptr) + this->charge_sensor_ah_->publish_state(charge_ah); + } + } + this->state_ = State::DATA_COLLECTION_8; + break; + + case State::DATA_COLLECTION_8: + if (this->full_loop_is_okay_) { + this->status_clear_warning(); + } else { + this->status_set_warning(); + } + this->state_ = State::IDLE; + break; + + default: + ESP_LOGW(TAG, "Unknown state of the component, might be due to memory corruption"); + break; + } + } +} + +void INA2XX::dump_config() { + ESP_LOGCONFIG(TAG, "INA2xx:"); + ESP_LOGCONFIG(TAG, " Device model = %s", get_device_name(this->ina_model_)); + + if (this->device_mismatch_) { + ESP_LOGE(TAG, " Device model mismatch. Found device with ID = %x. Please check your configuration.", + this->dev_id_); + } + if (this->is_failed()) { + ESP_LOGE(TAG, "Communication with INA2xx failed!"); + } + LOG_UPDATE_INTERVAL(this); + ESP_LOGCONFIG(TAG, " Shunt resistance = %f Ohm", this->shunt_resistance_ohm_); + ESP_LOGCONFIG(TAG, " Max current = %f A", this->max_current_a_); + ESP_LOGCONFIG(TAG, " Shunt temp coeff = %d ppm/°C", this->shunt_tempco_ppm_c_); + ESP_LOGCONFIG(TAG, " ADCRANGE = %d (%s)", (uint8_t) this->adc_range_, this->adc_range_ ? "±40.96 mV" : "±163.84 mV"); + ESP_LOGCONFIG(TAG, " CURRENT_LSB = %f", this->current_lsb_); + ESP_LOGCONFIG(TAG, " SHUNT_CAL = %d", this->shunt_cal_); + + ESP_LOGCONFIG(TAG, " ADC Samples = %d; ADC times: Bus = %d μs, Shunt = %d μs, Temp = %d μs", + ADC_SAMPLES[0b111 & (uint8_t) this->adc_avg_samples_], + ADC_TIMES[0b111 & (uint8_t) this->adc_time_bus_voltage_], + ADC_TIMES[0b111 & (uint8_t) this->adc_time_shunt_voltage_], + ADC_TIMES[0b111 & (uint8_t) this->adc_time_die_temperature_]); + + ESP_LOGCONFIG(TAG, " Device is %s", get_device_name(this->ina_model_)); + + LOG_SENSOR(" ", "Shunt Voltage", this->shunt_voltage_sensor_); + LOG_SENSOR(" ", "Bus Voltage", this->bus_voltage_sensor_); + LOG_SENSOR(" ", "Die Temperature", this->die_temperature_sensor_); + LOG_SENSOR(" ", "Current", this->current_sensor_); + LOG_SENSOR(" ", "Power", this->power_sensor_); + + if (this->ina_model_ == INAModel::INA_228 || this->ina_model_ == INAModel::INA_229) { + LOG_SENSOR(" ", "Energy J", this->energy_sensor_j_); + LOG_SENSOR(" ", "Energy Wh", this->energy_sensor_wh_); + LOG_SENSOR(" ", "Charge C", this->charge_sensor_c_); + LOG_SENSOR(" ", "Charge Ah", this->charge_sensor_ah_); + } +} + +bool INA2XX::reset_energy_counters() { + if (this->ina_model_ != INAModel::INA_228 && this->ina_model_ != INAModel::INA_229) { + return false; + } + ESP_LOGV(TAG, "reset_energy_counters"); + + ConfigurationRegister cfg{0}; + auto ret = this->read_unsigned_16_(RegisterMap::REG_CONFIG, cfg.raw_u16); + cfg.RSTACC = true; + cfg.ADCRANGE = this->adc_range_; + ret = ret && this->write_unsigned_16_(RegisterMap::REG_CONFIG, cfg.raw_u16); + + this->energy_overflows_count_ = 0; + this->charge_overflows_count_ = 0; + return ret; +} + +bool INA2XX::reset_config_() { + ESP_LOGV(TAG, "Reset"); + ConfigurationRegister cfg{0}; + cfg.RST = true; + return this->write_unsigned_16_(RegisterMap::REG_CONFIG, cfg.raw_u16); +} + +bool INA2XX::check_device_model_() { + constexpr uint16_t manufacturer_ti = 0x5449; // "TI" + + uint16_t manufacturer_id{0}, rev_id{0}; + this->read_unsigned_16_(RegisterMap::REG_MANUFACTURER_ID, manufacturer_id); + if (!this->read_unsigned_16_(RegisterMap::REG_DEVICE_ID, this->dev_id_)) { + this->dev_id_ = 0; + ESP_LOGV(TAG, "Can't read device ID"); + }; + rev_id = this->dev_id_ & 0x0F; + this->dev_id_ >>= 4; + ESP_LOGI(TAG, "Manufacturer: 0x%04X, Device ID: 0x%04X, Revision: %d", manufacturer_id, this->dev_id_, rev_id); + + if (manufacturer_id != manufacturer_ti) { + ESP_LOGE(TAG, "Manufacturer ID doesn't match original 0x5449"); + this->device_mismatch_ = true; + return false; + } + + if (this->dev_id_ == 0x228 || this->dev_id_ == 0x229) { + ESP_LOGI(TAG, "Supported device found: INA%x, 85-V, 20-Bit, Ultra-Precise Power/Energy/Charge Monitor", + this->dev_id_); + } else if (this->dev_id_ == 0x238 || this->dev_id_ == 0x239) { + ESP_LOGI(TAG, "Supported device found: INA%x, 85-V, 16-Bit, High-Precision Power Monitor", this->dev_id_); + } else if (this->dev_id_ == 0x0 || this->dev_id_ == 0xFF) { + ESP_LOGI(TAG, "We assume device is: INA237 85-V, 16-Bit, Precision Power Monitor"); + this->dev_id_ = 0x237; + } else { + ESP_LOGE(TAG, "Unknown device ID %x.", this->dev_id_); + this->device_mismatch_ = true; + return false; + } + + // Check user-selected model agains what we have found. Mark as failed if selected model != found model + if (!check_model_and_device_match(this->ina_model_, this->dev_id_)) { + ESP_LOGE(TAG, "Selected model %s doesn't match found device INA%x", get_device_name(this->ina_model_), + this->dev_id_); + this->device_mismatch_ = true; + return false; + } + + // setup device coefficients + if (this->ina_model_ == INAModel::INA_228 || this->ina_model_ == INAModel::INA_229) { + this->cfg_.vbus_lsb = 0.0001953125f; + this->cfg_.v_shunt_lsb_range0 = 0.0003125f; + this->cfg_.v_shunt_lsb_range1 = 0.000078125f; + this->cfg_.shunt_cal_scale = 13107.2f * 1000000.0f; + this->cfg_.current_lsb_scale_factor = -19; + this->cfg_.die_temp_lsb = 0.0078125f; + this->cfg_.power_coeff = 3.2f; + this->cfg_.energy_coeff = 16.0f * 3.2f; + } else { + this->cfg_.vbus_lsb = 0.0031250000f; + this->cfg_.v_shunt_lsb_range0 = 0.0050000f; + this->cfg_.v_shunt_lsb_range1 = 0.001250000f; + this->cfg_.shunt_cal_scale = 819.2f * 1000000.0f; + this->cfg_.current_lsb_scale_factor = -15; + this->cfg_.die_temp_lsb = 0.1250000f; + this->cfg_.power_coeff = 0.2f; + this->cfg_.energy_coeff = 0.0f; // N/A + } + + return true; +} + +bool INA2XX::configure_adc_range_() { + ESP_LOGV(TAG, "Setting ADCRANGE = %d", (uint8_t) this->adc_range_); + ConfigurationRegister cfg{0}; + auto ret = this->read_unsigned_16_(RegisterMap::REG_CONFIG, cfg.raw_u16); + cfg.ADCRANGE = this->adc_range_; + ret = ret && this->write_unsigned_16_(RegisterMap::REG_CONFIG, cfg.raw_u16); + + return ret; +} + +bool INA2XX::configure_adc_() { + bool ret{false}; + AdcConfigurationRegister adc_cfg{0}; + adc_cfg.MODE = 0x0F; // Fh = Continuous bus voltage, shunt voltage and temperature + adc_cfg.VBUSCT = this->adc_time_bus_voltage_; + adc_cfg.VSHCT = this->adc_time_shunt_voltage_; + adc_cfg.VTCT = this->adc_time_die_temperature_; + adc_cfg.AVG = this->adc_avg_samples_; + ret = this->write_unsigned_16_(RegisterMap::REG_ADC_CONFIG, adc_cfg.raw_u16); + return ret; +} + +bool INA2XX::configure_shunt_() { + this->current_lsb_ = ldexp(this->max_current_a_, this->cfg_.current_lsb_scale_factor); + this->shunt_cal_ = (uint16_t) (this->cfg_.shunt_cal_scale * this->current_lsb_ * this->shunt_resistance_ohm_); + if (this->adc_range_) + this->shunt_cal_ *= 4; + + if (this->shunt_cal_ & 0x8000) { + // cant be more than 15 bits + ESP_LOGW(TAG, "Shunt value too high"); + } + this->shunt_cal_ &= 0x7FFF; + ESP_LOGV(TAG, "Given Rshunt=%f Ohm and Max_current=%.3f", this->shunt_resistance_ohm_, this->max_current_a_); + ESP_LOGV(TAG, "New CURRENT_LSB=%f, SHUNT_CAL=%u", this->current_lsb_, this->shunt_cal_); + return this->write_unsigned_16_(RegisterMap::REG_SHUNT_CAL, this->shunt_cal_); +} + +bool INA2XX::configure_shunt_tempco_() { + // Only for 228/229 + // unsigned 14-bit value + // 0x0000 = 0 ppm/°C + // 0x3FFF = 16383 ppm/°C + if ((this->ina_model_ == INAModel::INA_228 || this->ina_model_ == INAModel::INA_229) && + this->shunt_tempco_ppm_c_ > 0) { + return this->write_unsigned_16_(RegisterMap::REG_SHUNT_TEMPCO, this->shunt_tempco_ppm_c_ & 0x3FFF); + } + return true; +} + +bool INA2XX::read_shunt_voltage_mv_(float &volt_out) { + // Two's complement value + // 228, 229 - 24bit: 20(23-4) + 4(3-0) res + // 237, 238, 239 - 16bit + + bool ret{false}; + float volt_reading{0}; + uint64_t raw{0}; + if (this->ina_model_ == INAModel::INA_228 || this->ina_model_ == INAModel::INA_229) { + ret = this->read_unsigned_(RegisterMap::REG_VSHUNT, 3, raw); + raw >>= 4; + volt_reading = this->two_complement_(raw, 20); + } else { + ret = this->read_unsigned_(RegisterMap::REG_VSHUNT, 2, raw); + volt_reading = this->two_complement_(raw, 16); + } + + if (ret) { + volt_out = (this->adc_range_ ? this->cfg_.v_shunt_lsb_range1 : this->cfg_.v_shunt_lsb_range0) * volt_reading; + } + + ESP_LOGV(TAG, "read_shunt_voltage_mv_ ret=%s, shunt_cal=%d, reading_lsb=%f", OKFAILED(ret), this->shunt_cal_, + volt_reading); + + return ret; +} + +bool INA2XX::read_bus_voltage_(float &volt_out) { + // Two's complement value + // 228, 229 - 24bit: 20(23-4) + 4(3-0) res + // 237, 238, 239 - 16bit + + bool ret{false}; + float volt_reading{0}; + uint64_t raw{0}; + if (this->ina_model_ == INAModel::INA_228 || this->ina_model_ == INAModel::INA_229) { + ret = this->read_unsigned_(RegisterMap::REG_VBUS, 3, raw); + raw >>= 4; + volt_reading = this->two_complement_(raw, 20); + } else { + ret = this->read_unsigned_(RegisterMap::REG_VBUS, 2, raw); + volt_reading = this->two_complement_(raw, 16); + } + if (ret) { + volt_out = this->cfg_.vbus_lsb * (float) volt_reading; + } + + ESP_LOGV(TAG, "read_bus_voltage_ ret=%s, reading_lsb=%f", OKFAILED(ret), volt_reading); + return ret; +} + +bool INA2XX::read_die_temp_c_(float &temp_out) { + // Two's complement value + // 228, 229 - 16bit + // 237, 238, 239 - 16bit: 12(15-4) + 4(3-0) res + + bool ret{false}; + float temp_reading{0}; + uint64_t raw{0}; + + if (this->ina_model_ == INAModel::INA_228 || this->ina_model_ == INAModel::INA_229) { + ret = this->read_unsigned_(RegisterMap::REG_DIETEMP, 2, raw); + temp_reading = this->two_complement_(raw, 16); + } else { + ret = this->read_unsigned_(RegisterMap::REG_DIETEMP, 2, raw); + raw >>= 4; + temp_reading = this->two_complement_(raw, 12); + } + if (ret) { + temp_out = this->cfg_.die_temp_lsb * (float) temp_reading; + } + + ESP_LOGV(TAG, "read_die_temp_c_ ret=%s, reading_lsb=%f", OKFAILED(ret), temp_reading); + return ret; +} + +bool INA2XX::read_current_a_(float &s_out) { + // Two's complement value + // 228, 229 - 24bit: 20(23-4) + 4(3-0) res + // 237, 238, 239 - 16bit + bool ret{false}; + float amps_reading{0}; + uint64_t raw{0}; + + if (this->ina_model_ == INAModel::INA_228 || this->ina_model_ == INAModel::INA_229) { + ret = this->read_unsigned_(RegisterMap::REG_CURRENT, 3, raw); + raw >>= 4; + amps_reading = this->two_complement_(raw, 20); + } else { + ret = this->read_unsigned_(RegisterMap::REG_CURRENT, 2, raw); + amps_reading = this->two_complement_(raw, 16); + } + + ESP_LOGV(TAG, "read_current_a_ ret=%s. current_lsb=%f. reading_lsb=%f", OKFAILED(ret), this->current_lsb_, + amps_reading); + if (ret) { + amps_out = this->current_lsb_ * (float) amps_reading; + } + + return ret; +} + +bool INA2XX::read_power_w_(float &power_out) { + // Unsigned value + // 228, 229 - 24bit + // 237, 238, 239 - 24bit + uint64_t power_reading{0}; + auto ret = this->read_unsigned_((uint8_t) RegisterMap::REG_POWER, 3, power_reading); + + ESP_LOGV(TAG, "read_power_w_ ret=%s, reading_lsb=%d", OKFAILED(ret), (uint32_t) power_reading); + if (ret) { + power_out = this->cfg_.power_coeff * this->current_lsb_ * (float) power_reading; + } + + return ret; +} + +bool INA2XX::read_energy_(double &joules_out, double &watt_hours_out) { + // Unsigned value + // 228, 229 - 40bit + // 237, 238, 239 - not available + if (this->ina_model_ != INAModel::INA_228 && this->ina_model_ != INAModel::INA_229) { + joules_out = 0; + return false; + } + uint64_t joules_reading = 0; + uint64_t previous_energy = this->energy_overflows_count_ * (((uint64_t) 1) << 40); + auto ret = this->read_unsigned_((uint8_t) RegisterMap::REG_ENERGY, 5, joules_reading); + + ESP_LOGV(TAG, "read_energy_j_ ret=%s, reading_lsb=0x%" PRIX64 ", current_lsb=%f, overflow_cnt=%d", OKFAILED(ret), + joules_reading, this->current_lsb_, this->energy_overflows_count_); + if (ret) { + joules_out = this->cfg_.energy_coeff * this->current_lsb_ * (double) joules_reading + (double) previous_energy; + watt_hours_out = joules_out / 3600.0; + } + return ret; +} + +bool INA2XX::read_charge_(double &coulombs_out, double &_hours_out) { + // Two's complement value + // 228, 229 - 40bit + // 237, 238, 239 - not available + if (this->ina_model_ != INAModel::INA_228 && this->ina_model_ != INAModel::INA_229) { + coulombs_out = 0; + return false; + } + + // and what to do with this? datasheet doesnt tell us what if charge is negative + uint64_t previous_charge = this->charge_overflows_count_ * (((uint64_t) 1) << 39); + double coulombs_reading = 0; + uint64_t raw{0}; + auto ret = this->read_unsigned_((uint8_t) RegisterMap::REG_CHARGE, 5, raw); + coulombs_reading = this->two_complement_(raw, 40); + + ESP_LOGV(TAG, "read_charge_c_ ret=%d, curr_charge=%f + 39-bit overflow_cnt=%d", ret, coulombs_reading, + this->charge_overflows_count_); + if (ret) { + coulombs_out = this->current_lsb_ * (double) coulombs_reading + (double) previous_charge; + amp_hours_out = coulombs_out / 3600.0; + } + return ret; +} + +bool INA2XX::read_diagnostics_and_act_() { + if (this->ina_model_ != INAModel::INA_228 && this->ina_model_ != INAModel::INA_229) { + return false; + } + + DiagnosticRegister diag{0}; + auto ret = this->read_unsigned_16_(RegisterMap::REG_DIAG_ALRT, diag.raw_u16); + ESP_LOGV(TAG, "read_diagnostics_and_act_ ret=%s, 0x%04X", OKFAILED(ret), diag.raw_u16); + + if (diag.ENERGYOF) { + this->energy_overflows_count_++; // 40-bit overflow + } + + if (diag.CHARGEOF) { + this->charge_overflows_count_++; // 39-bit overflow + } + + return ret; +} + +bool INA2XX::write_unsigned_16_(uint8_t reg, uint16_t val) { + uint16_t data_out = byteswap(val); + auto ret = this->write_ina_register(reg, (uint8_t *) &data_out, 2); + if (!ret) { + ESP_LOGV(TAG, "write_unsigned_16_ FAILED reg=0x%02X, val=0x%04X", reg, val); + } + return ret; +} + +bool INA2XX::read_unsigned_(uint8_t reg, uint8_t reg_size, uint64_t &data_out) { + static uint8_t rx_buf[5] = {0}; // max buffer size + + if (reg_size > 5) { + return false; + } + + auto ret = this->read_ina_register(reg, rx_buf, reg_size); + + // Combine bytes + data_out = rx_buf[0]; + for (uint8_t i = 1; i < reg_size; i++) { + data_out = (data_out << 8) | rx_buf[i]; + } + ESP_LOGV(TAG, "read_unsigned_ reg=0x%02X, ret=%s, len=%d, val=0x%" PRIX64, reg, OKFAILED(ret), reg_size, data_out); + + return ret; +} + +bool INA2XX::read_unsigned_16_(uint8_t reg, uint16_t &out) { + uint16_t data_in{0}; + auto ret = this->read_ina_register(reg, (uint8_t *) &data_in, 2); + out = byteswap(data_in); + ESP_LOGV(TAG, "read_unsigned_16_ 0x%02X, ret= %s, val=0x%04X", reg, OKFAILED(ret), out); + return ret; +} + +int64_t INA2XX::two_complement_(uint64_t value, uint8_t bits) { + if (value > (1ULL << (bits - 1))) { + return (int64_t) (value - (1ULL << bits)); + } else { + return (int64_t) value; + } +} +} // namespace ina2xx_base +} // namespace esphome diff --git a/esphome/components/ina2xx_base/ina2xx_base.h b/esphome/components/ina2xx_base/ina2xx_base.h new file mode 100644 index 0000000000..261c5321bf --- /dev/null +++ b/esphome/components/ina2xx_base/ina2xx_base.h @@ -0,0 +1,253 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/sensor/sensor.h" + +namespace esphome { +namespace ina2xx_base { + +enum RegisterMap : uint8_t { + REG_CONFIG = 0x00, + REG_ADC_CONFIG = 0x01, + REG_SHUNT_CAL = 0x02, + REG_SHUNT_TEMPCO = 0x03, + REG_VSHUNT = 0x04, + REG_VBUS = 0x05, + REG_DIETEMP = 0x06, + REG_CURRENT = 0x07, + REG_POWER = 0x08, + REG_ENERGY = 0x09, + REG_CHARGE = 0x0A, + REG_DIAG_ALRT = 0x0B, + REG_SOVL = 0x0C, + REG_SUVL = 0x0D, + REG_BOVL = 0x0E, + REG_BUVL = 0x0F, + REG_TEMP_LIMIT = 0x10, + REG_PWR_LIMIT = 0x11, + REG_MANUFACTURER_ID = 0x3E, + REG_DEVICE_ID = 0x3F +}; + +enum AdcRange : uint16_t { + ADC_RANGE_0 = 0, + ADC_RANGE_1 = 1, +}; + +enum AdcTime : uint16_t { + ADC_TIME_50US = 0, + ADC_TIME_84US = 1, + ADC_TIME_150US = 2, + ADC_TIME_280US = 3, + ADC_TIME_540US = 4, + ADC_TIME_1052US = 5, + ADC_TIME_2074US = 6, + ADC_TIME_4120US = 7, +}; + +enum AdcAvgSamples : uint16_t { + ADC_AVG_SAMPLES_1 = 0, + ADC_AVG_SAMPLES_4 = 1, + ADC_AVG_SAMPLES_16 = 2, + ADC_AVG_SAMPLES_64 = 3, + ADC_AVG_SAMPLES_128 = 4, + ADC_AVG_SAMPLES_256 = 5, + ADC_AVG_SAMPLES_512 = 6, + ADC_AVG_SAMPLES_1024 = 7, +}; + +union ConfigurationRegister { + uint16_t raw_u16; + struct { + uint16_t reserved_0_3 : 4; // Reserved + AdcRange ADCRANGE : 1; // Shunt measurement range 0: ±163.84 mV, 1: ±40.96 mV + bool TEMPCOMP : 1; // Temperature compensation enable + uint16_t CONVDLY : 8; // Sets the Delay for initial ADC conversion in steps of 2 ms. + bool RSTACC : 1; // Reset counters + bool RST : 1; // Full device reset + } __attribute__((packed)); +}; + +union AdcConfigurationRegister { + uint16_t raw_u16; + struct { + AdcAvgSamples AVG : 3; + AdcTime VTCT : 3; // Voltage conversion time + AdcTime VSHCT : 3; // Shunt voltage conversion time + AdcTime VBUSCT : 3; // Bus voltage conversion time + uint16_t MODE : 4; + } __attribute__((packed)); +}; + +union TempCompensationRegister { + uint16_t raw_u16; + struct { + uint16_t TEMPCO : 14; + uint16_t reserved : 2; + } __attribute__((packed)); +}; + +union DiagnosticRegister { + uint16_t raw_u16; + struct { + bool MEMSTAT : 1; + bool CNVRF : 1; + bool POL : 1; + bool BUSUL : 1; + bool BUSOL : 1; + bool SHNTUL : 1; + bool SHNTOL : 1; + bool TMPOL : 1; + bool RESERVED1 : 1; + bool MATHOF : 1; + bool CHARGEOF : 1; + bool ENERGYOF : 1; + bool APOL : 1; + bool SLOWALERT : 1; + bool CNVR : 1; + bool ALATCH : 1; + } __attribute__((packed)); +}; + +enum INAModel : uint8_t { INA_UNKNOWN = 0, INA_228, INA_229, INA_238, INA_239, INA_237 }; + +class INA2XX : public PollingComponent { + public: + void setup() override; + float get_setup_priority() const override; + void update() override; + void loop() override; + void dump_config() override; + + void set_shunt_resistance_ohm(float shunt_resistance_ohm) { this->shunt_resistance_ohm_ = shunt_resistance_ohm; } + void set_max_current_a(float max_current_a) { this->max_current_a_ = max_current_a; } + void set_adc_range(uint8_t range) { this->adc_range_ = (range == 0) ? AdcRange::ADC_RANGE_0 : AdcRange::ADC_RANGE_1; } + void set_adc_time_bus_voltage(AdcTime time) { this->adc_time_bus_voltage_ = time; } + void set_adc_time_shunt_voltage(AdcTime time) { this->adc_time_shunt_voltage_ = time; } + void set_adc_time_die_temperature(AdcTime time) { this->adc_time_die_temperature_ = time; } + void set_adc_avg_samples(AdcAvgSamples samples) { this->adc_avg_samples_ = samples; } + void set_shunt_tempco(uint16_t coeff) { this->shunt_tempco_ppm_c_ = coeff; } + + void set_shunt_voltage_sensor(sensor::Sensor *sensor) { this->shunt_voltage_sensor_ = sensor; } + void set_bus_voltage_sensor(sensor::Sensor *sensor) { this->bus_voltage_sensor_ = sensor; } + void set_die_temperature_sensor(sensor::Sensor *sensor) { this->die_temperature_sensor_ = sensor; } + void set_current_sensor(sensor::Sensor *sensor) { this->current_sensor_ = sensor; } + void set_power_sensor(sensor::Sensor *sensor) { this->power_sensor_ = sensor; } + void set_energy_sensor_j(sensor::Sensor *sensor) { this->energy_sensor_j_ = sensor; } + void set_energy_sensor_wh(sensor::Sensor *sensor) { this->energy_sensor_wh_ = sensor; } + void set_charge_sensor_c(sensor::Sensor *sensor) { this->charge_sensor_c_ = sensor; } + void set_charge_sensor_ah(sensor::Sensor *sensor) { this->charge_sensor_ah_ = sensor; } + + void set_model(INAModel model) { this->ina_model_ = model; } + + bool reset_energy_counters(); + + protected: + bool reset_config_(); + bool check_device_model_(); + bool configure_adc_(); + + bool configure_shunt_(); + bool configure_shunt_tempco_(); + bool configure_adc_range_(); + + bool read_shunt_voltage_mv_(float &volt_out); + bool read_bus_voltage_(float &volt_out); + bool read_die_temp_c_(float &temp); + bool read_current_a_(float &s_out); + bool read_power_w_(float &power_out); + bool read_energy_(double &joules_out, double &watt_hours_out); + bool read_charge_(double &coulombs_out, double &_hours_out); + + bool read_diagnostics_and_act_(); + + // + // User configuration + // + float shunt_resistance_ohm_; + float max_current_a_; + AdcRange adc_range_{AdcRange::ADC_RANGE_0}; + AdcTime adc_time_bus_voltage_{AdcTime::ADC_TIME_4120US}; + AdcTime adc_time_shunt_voltage_{AdcTime::ADC_TIME_4120US}; + AdcTime adc_time_die_temperature_{AdcTime::ADC_TIME_4120US}; + AdcAvgSamples adc_avg_samples_{AdcAvgSamples::ADC_AVG_SAMPLES_128}; + uint16_t shunt_tempco_ppm_c_{0}; + + // + // Calculated coefficients + // + uint16_t shunt_cal_{0}; + float current_lsb_{0}; + + uint32_t energy_overflows_count_{0}; + uint32_t charge_overflows_count_{0}; + + // + // Sensor objects + // + sensor::Sensor *shunt_voltage_sensor_{nullptr}; + sensor::Sensor *bus_voltage_sensor_{nullptr}; + sensor::Sensor *die_temperature_sensor_{nullptr}; + sensor::Sensor *current_sensor_{nullptr}; + sensor::Sensor *power_sensor_{nullptr}; + sensor::Sensor *energy_sensor_j_{nullptr}; + sensor::Sensor *energy_sensor_wh_{nullptr}; + sensor::Sensor *charge_sensor_c_{nullptr}; + sensor::Sensor *charge_sensor_ah_{nullptr}; + + // + // FSM states + // + enum class State : uint8_t { + NOT_INITIALIZED = 0x0, + IDLE, + DATA_COLLECTION_1, + DATA_COLLECTION_2, + DATA_COLLECTION_3, + DATA_COLLECTION_4, + DATA_COLLECTION_5, + DATA_COLLECTION_6, + DATA_COLLECTION_7, + DATA_COLLECTION_8, + } state_{State::NOT_INITIALIZED}; + + bool full_loop_is_okay_{true}; + + // + // Device model + // + INAModel ina_model_{INAModel::INA_UNKNOWN}; + uint16_t dev_id_{0}; + bool device_mismatch_{false}; + + // + // Device specific parameters + // + struct { + float vbus_lsb; + float v_shunt_lsb_range0; + float v_shunt_lsb_range1; + float shunt_cal_scale; + int8_t current_lsb_scale_factor; + float die_temp_lsb; + float power_coeff; + float energy_coeff; + } cfg_; + + // + // Register read/write + // + bool read_unsigned_(uint8_t reg, uint8_t reg_size, uint64_t &data_out); + bool read_unsigned_16_(uint8_t reg, uint16_t &out); + bool write_unsigned_16_(uint8_t reg, uint16_t val); + + int64_t two_complement_(uint64_t value, uint8_t bits); + + // + // Interface-specific implementation + // + virtual bool read_ina_register(uint8_t a_register, uint8_t *data, size_t len) = 0; + virtual bool write_ina_register(uint8_t a_register, const uint8_t *data, size_t len) = 0; +}; +} // namespace ina2xx_base +} // namespace esphome diff --git a/esphome/components/ina2xx_i2c/__init__.py b/esphome/components/ina2xx_i2c/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/esphome/components/ina2xx_i2c/ina2xx_i2c.cpp b/esphome/components/ina2xx_i2c/ina2xx_i2c.cpp new file mode 100644 index 0000000000..d28525635d --- /dev/null +++ b/esphome/components/ina2xx_i2c/ina2xx_i2c.cpp @@ -0,0 +1,39 @@ +#include "ina2xx_i2c.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace ina2xx_i2c { + +static const char *const TAG = "ina2xx_i2c"; + +void INA2XXI2C::setup() { + auto err = this->write(nullptr, 0); + if (err != i2c::ERROR_OK) { + this->mark_failed(); + return; + } + INA2XX::setup(); +} + +void INA2XXI2C::dump_config() { + INA2XX::dump_config(); + LOG_I2C_DEVICE(this); +} + +bool INA2XXI2C::read_ina_register(uint8_t reg, uint8_t *data, size_t len) { + auto ret = this->read_register(reg, data, len, false); + if (ret != i2c::ERROR_OK) { + ESP_LOGE(TAG, "read_ina_register_ failed. Reg=0x%02X Err=%d", reg, ret); + } + return ret == i2c::ERROR_OK; +} + +bool INA2XXI2C::write_ina_register(uint8_t reg, const uint8_t *data, size_t len) { + auto ret = this->write_register(reg, data, len); + if (ret != i2c::ERROR_OK) { + ESP_LOGE(TAG, "write_register failed. Reg=0x%02X Err=%d", reg, ret); + } + return ret == i2c::ERROR_OK; +} +} // namespace ina2xx_i2c +} // namespace esphome diff --git a/esphome/components/ina2xx_i2c/ina2xx_i2c.h b/esphome/components/ina2xx_i2c/ina2xx_i2c.h new file mode 100644 index 0000000000..c90b9bf190 --- /dev/null +++ b/esphome/components/ina2xx_i2c/ina2xx_i2c.h @@ -0,0 +1,21 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/ina2xx_base/ina2xx_base.h" +#include "esphome/components/i2c/i2c.h" + +namespace esphome { +namespace ina2xx_i2c { + +class INA2XXI2C : public ina2xx_base::INA2XX, public i2c::I2CDevice { + public: + void setup() override; + void dump_config() override; + + protected: + bool read_ina_register(uint8_t reg, uint8_t *data, size_t len) override; + bool write_ina_register(uint8_t reg, const uint8_t *data, size_t len) override; +}; + +} // namespace ina2xx_i2c +} // namespace esphome diff --git a/esphome/components/ina2xx_i2c/sensor.py b/esphome/components/ina2xx_i2c/sensor.py new file mode 100644 index 0000000000..57ddcef17a --- /dev/null +++ b/esphome/components/ina2xx_i2c/sensor.py @@ -0,0 +1,34 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.components import ina2xx_base, i2c +from esphome.const import CONF_ID, CONF_MODEL + +AUTO_LOAD = ["ina2xx_base"] +CODEOWNERS = ["@latonita"] +DEPENDENCIES = ["i2c"] + +ina2xx_i2c = cg.esphome_ns.namespace("ina2xx_i2c") +INA2XX_I2C = ina2xx_i2c.class_("INA2XXI2C", ina2xx_base.INA2XX, i2c.I2CDevice) + +INAModel = ina2xx_base.ina2xx_base_ns.enum("INAModel") +INA_MODELS = { + "INA228": INAModel.INA_228, + "INA238": INAModel.INA_238, + "INA237": INAModel.INA_237, +} + +CONFIG_SCHEMA = cv.All( + ina2xx_base.INA2XX_SCHEMA.extend( + { + cv.GenerateID(): cv.declare_id(INA2XX_I2C), + cv.Required(CONF_MODEL): cv.enum(INA_MODELS, upper=True), + } + ).extend(i2c.i2c_device_schema(0x40)), + ina2xx_base.validate_model_config, +) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await ina2xx_base.setup_ina2xx(var, config) + await i2c.register_i2c_device(var, config) diff --git a/esphome/components/ina2xx_spi/__init__.py b/esphome/components/ina2xx_spi/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/esphome/components/ina2xx_spi/ina2xx_spi.cpp b/esphome/components/ina2xx_spi/ina2xx_spi.cpp new file mode 100644 index 0000000000..3e04a87665 --- /dev/null +++ b/esphome/components/ina2xx_spi/ina2xx_spi.cpp @@ -0,0 +1,38 @@ +#include "ina2xx_spi.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace ina2xx_spi { + +static const char *const TAG = "ina2xx_spi"; + +void INA2XXSPI::setup() { + this->spi_setup(); + INA2XX::setup(); +} + +void INA2XXSPI::dump_config() { + INA2XX::dump_config(); + LOG_PIN(" CS Pin: ", this->cs_); +} + +bool INA2XXSPI::read_ina_register(uint8_t reg, uint8_t *data, size_t len) { + reg = (reg << 2); // top 6 bits + reg |= 0x01; // read + this->enable(); + this->write_byte(reg); + this->read_array(data, len); + this->disable(); + return true; +} + +bool INA2XXSPI::write_ina_register(uint8_t reg, const uint8_t *data, size_t len) { + reg = (reg << 2); // top 6 bits + this->enable(); + this->write_byte(reg); + this->write_array(data, len); + this->disable(); + return true; +} +} // namespace ina2xx_spi +} // namespace esphome diff --git a/esphome/components/ina2xx_spi/ina2xx_spi.h b/esphome/components/ina2xx_spi/ina2xx_spi.h new file mode 100644 index 0000000000..3b21518d34 --- /dev/null +++ b/esphome/components/ina2xx_spi/ina2xx_spi.h @@ -0,0 +1,22 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/ina2xx_base/ina2xx_base.h" +#include "esphome/components/spi/spi.h" + +namespace esphome { +namespace ina2xx_spi { + +class INA2XXSPI : public ina2xx_base::INA2XX, + public spi::SPIDevice { + public: + void setup() override; + void dump_config() override; + + protected: + bool read_ina_register(uint8_t reg, uint8_t *data, size_t len) override; + bool write_ina_register(uint8_t reg, const uint8_t *data, size_t len) override; +}; +} // namespace ina2xx_spi +} // namespace esphome diff --git a/esphome/components/ina2xx_spi/sensor.py b/esphome/components/ina2xx_spi/sensor.py new file mode 100644 index 0000000000..e7ae51d516 --- /dev/null +++ b/esphome/components/ina2xx_spi/sensor.py @@ -0,0 +1,33 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.components import ina2xx_base, spi +from esphome.const import CONF_ID, CONF_MODEL + +AUTO_LOAD = ["ina2xx_base"] +CODEOWNERS = ["@latonita"] +DEPENDENCIES = ["spi"] + +ina2xx_spi = cg.esphome_ns.namespace("ina2xx_spi") +INA2XX_SPI = ina2xx_spi.class_("INA2XXSPI", ina2xx_base.INA2XX, spi.SPIDevice) + +INAModel = ina2xx_base.ina2xx_base_ns.enum("INAModel") +INA_MODELS = { + "INA229": INAModel.INA_229, + "INA239": INAModel.INA_239, +} + +CONFIG_SCHEMA = cv.All( + ina2xx_base.INA2XX_SCHEMA.extend( + { + cv.GenerateID(): cv.declare_id(INA2XX_SPI), + cv.Required(CONF_MODEL): cv.enum(INA_MODELS, upper=True), + } + ).extend(spi.spi_device_schema(cs_pin_required=True)), + ina2xx_base.validate_model_config, +) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await ina2xx_base.setup_ina2xx(var, config) + await spi.register_spi_device(var, config) diff --git a/esphome/components/media_player/__init__.py b/esphome/components/media_player/__init__.py index 5db78150bb..320014e355 100644 --- a/esphome/components/media_player/__init__.py +++ b/esphome/components/media_player/__init__.py @@ -51,12 +51,16 @@ VolumeSetAction = media_player_ns.class_( CONF_ON_PLAY = "on_play" CONF_ON_PAUSE = "on_pause" +CONF_ON_ANNOUNCEMENT = "on_announcement" CONF_MEDIA_URL = "media_url" StateTrigger = media_player_ns.class_("StateTrigger", automation.Trigger.template()) IdleTrigger = media_player_ns.class_("IdleTrigger", automation.Trigger.template()) PlayTrigger = media_player_ns.class_("PlayTrigger", automation.Trigger.template()) PauseTrigger = media_player_ns.class_("PauseTrigger", automation.Trigger.template()) +AnnoucementTrigger = media_player_ns.class_( + "AnnouncementTrigger", automation.Trigger.template() +) IsIdleCondition = media_player_ns.class_("IsIdleCondition", automation.Condition) IsPlayingCondition = media_player_ns.class_("IsPlayingCondition", automation.Condition) @@ -75,6 +79,9 @@ async def setup_media_player_core_(var, config): for conf in config.get(CONF_ON_PAUSE, []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) await automation.build_automation(trigger, [], conf) + for conf in config.get(CONF_ON_ANNOUNCEMENT, []): + trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) + await automation.build_automation(trigger, [], conf) async def register_media_player(var, config): @@ -106,6 +113,11 @@ MEDIA_PLAYER_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend( cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(PauseTrigger), } ), + cv.Optional(CONF_ON_ANNOUNCEMENT): automation.validate_automation( + { + cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(AnnoucementTrigger), + } + ), } ) diff --git a/esphome/components/media_player/automation.h b/esphome/components/media_player/automation.h index 261e93775c..fc3ce7a764 100644 --- a/esphome/components/media_player/automation.h +++ b/esphome/components/media_player/automation.h @@ -52,6 +52,7 @@ class StateTrigger : public Trigger<> { MEDIA_PLAYER_SIMPLE_STATE_TRIGGER(IdleTrigger, IDLE) MEDIA_PLAYER_SIMPLE_STATE_TRIGGER(PlayTrigger, PLAYING) MEDIA_PLAYER_SIMPLE_STATE_TRIGGER(PauseTrigger, PAUSED) +MEDIA_PLAYER_SIMPLE_STATE_TRIGGER(AnnouncementTrigger, ANNOUNCING) template class IsIdleCondition : public Condition, public Parented { public: diff --git a/esphome/components/media_player/media_player.cpp b/esphome/components/media_player/media_player.cpp index 81cb6ca751..586345ac9f 100644 --- a/esphome/components/media_player/media_player.cpp +++ b/esphome/components/media_player/media_player.cpp @@ -15,6 +15,8 @@ const char *media_player_state_to_string(MediaPlayerState state) { return "PLAYING"; case MEDIA_PLAYER_STATE_PAUSED: return "PAUSED"; + case MEDIA_PLAYER_STATE_ANNOUNCING: + return "ANNOUNCING"; case MEDIA_PLAYER_STATE_NONE: default: return "UNKNOWN"; @@ -68,6 +70,9 @@ void MediaPlayerCall::perform() { if (this->volume_.has_value()) { ESP_LOGD(TAG, " Volume: %.2f", this->volume_.value()); } + if (this->announcement_.has_value()) { + ESP_LOGD(TAG, " Announcement: %s", this->announcement_.value() ? "yes" : "no"); + } this->parent_->control(*this); } @@ -108,6 +113,11 @@ MediaPlayerCall &MediaPlayerCall::set_volume(float volume) { return *this; } +MediaPlayerCall &MediaPlayerCall::set_announcement(bool announce) { + this->announcement_ = announce; + return *this; +} + void MediaPlayer::add_on_state_callback(std::function &&callback) { this->state_callback_.add(std::move(callback)); } diff --git a/esphome/components/media_player/media_player.h b/esphome/components/media_player/media_player.h index 88114d5337..77746e1808 100644 --- a/esphome/components/media_player/media_player.h +++ b/esphome/components/media_player/media_player.h @@ -10,7 +10,8 @@ enum MediaPlayerState : uint8_t { MEDIA_PLAYER_STATE_NONE = 0, MEDIA_PLAYER_STATE_IDLE = 1, MEDIA_PLAYER_STATE_PLAYING = 2, - MEDIA_PLAYER_STATE_PAUSED = 3 + MEDIA_PLAYER_STATE_PAUSED = 3, + MEDIA_PLAYER_STATE_ANNOUNCING = 4 }; const char *media_player_state_to_string(MediaPlayerState state); @@ -51,12 +52,14 @@ class MediaPlayerCall { MediaPlayerCall &set_media_url(const std::string &url); MediaPlayerCall &set_volume(float volume); + MediaPlayerCall &set_announcement(bool announce); void perform(); const optional &get_command() const { return command_; } const optional &get_media_url() const { return media_url_; } const optional &get_volume() const { return volume_; } + const optional &get_announcement() const { return announcement_; } protected: void validate_(); @@ -64,6 +67,7 @@ class MediaPlayerCall { optional command_; optional media_url_; optional volume_; + optional announcement_; }; class MediaPlayer : public EntityBase { diff --git a/esphome/components/nextion/nextion_upload_idf.cpp b/esphome/components/nextion/nextion_upload_idf.cpp index 448b6fc0ff..b5bb5478c1 100644 --- a/esphome/components/nextion/nextion_upload_idf.cpp +++ b/esphome/components/nextion/nextion_upload_idf.cpp @@ -260,7 +260,7 @@ bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) { // Tells the Nextion the content length of the tft file and baud rate it will be sent at // Once the Nextion accepts the command it will wait until the file is successfully uploaded // If it fails for any reason a power cycle of the display will be needed - sprintf(command, "whmi-wris %d,%" PRIu32 ",1", this->content_length_, baud_rate); + sprintf(command, "whmi-wris %" PRIu32 ",%" PRIu32 ",1", this->content_length_, baud_rate); // Clear serial receive buffer ESP_LOGV(TAG, "Clear serial receive buffer"); diff --git a/esphome/components/number/__init__.py b/esphome/components/number/__init__.py index 6d7ec97c90..8c3b15d22d 100644 --- a/esphome/components/number/__init__.py +++ b/esphome/components/number/__init__.py @@ -293,7 +293,7 @@ async def number_in_range_to_code(config, condition_id, template_arg, args): return var -@coroutine_with_priority(40.0) +@coroutine_with_priority(100.0) async def to_code(config): cg.add_define("USE_NUMBER") cg.add_global(number_ns.using) diff --git a/esphome/components/ota/__init__.py b/esphome/components/ota/__init__.py index 3c845490dc..3d2956931c 100644 --- a/esphome/components/ota/__init__.py +++ b/esphome/components/ota/__init__.py @@ -1,71 +1,67 @@ -from esphome.cpp_generator import RawExpression import esphome.codegen as cg import esphome.config_validation as cv from esphome import automation -from esphome.const import ( - CONF_ID, - CONF_NUM_ATTEMPTS, - CONF_PASSWORD, - CONF_PORT, - CONF_REBOOT_TIMEOUT, - CONF_SAFE_MODE, - CONF_TRIGGER_ID, - CONF_OTA, - KEY_PAST_SAFE_MODE, - CONF_VERSION, -) from esphome.core import CORE, coroutine_with_priority -CODEOWNERS = ["@esphome/core"] -DEPENDENCIES = ["network"] -AUTO_LOAD = ["socket", "md5"] +from esphome.const import CONF_ESPHOME, CONF_OTA, CONF_PLATFORM, CONF_TRIGGER_ID -CONF_ON_STATE_CHANGE = "on_state_change" +CODEOWNERS = ["@esphome/core"] +AUTO_LOAD = ["md5"] + +IS_PLATFORM_COMPONENT = True + +CONF_ON_ABORT = "on_abort" CONF_ON_BEGIN = "on_begin" -CONF_ON_PROGRESS = "on_progress" CONF_ON_END = "on_end" CONF_ON_ERROR = "on_error" +CONF_ON_PROGRESS = "on_progress" +CONF_ON_STATE_CHANGE = "on_state_change" + ota_ns = cg.esphome_ns.namespace("ota") -OTAState = ota_ns.enum("OTAState") OTAComponent = ota_ns.class_("OTAComponent", cg.Component) +OTAState = ota_ns.enum("OTAState") +OTAAbortTrigger = ota_ns.class_("OTAAbortTrigger", automation.Trigger.template()) +OTAEndTrigger = ota_ns.class_("OTAEndTrigger", automation.Trigger.template()) +OTAErrorTrigger = ota_ns.class_("OTAErrorTrigger", automation.Trigger.template()) +OTAProgressTrigger = ota_ns.class_("OTAProgressTrigger", automation.Trigger.template()) +OTAStartTrigger = ota_ns.class_("OTAStartTrigger", automation.Trigger.template()) OTAStateChangeTrigger = ota_ns.class_( "OTAStateChangeTrigger", automation.Trigger.template() ) -OTAStartTrigger = ota_ns.class_("OTAStartTrigger", automation.Trigger.template()) -OTAProgressTrigger = ota_ns.class_("OTAProgressTrigger", automation.Trigger.template()) -OTAEndTrigger = ota_ns.class_("OTAEndTrigger", automation.Trigger.template()) -OTAErrorTrigger = ota_ns.class_("OTAErrorTrigger", automation.Trigger.template()) -CONFIG_SCHEMA = cv.Schema( +def _ota_final_validate(config): + if len(config) < 1: + raise cv.Invalid( + f"At least one platform must be specified for '{CONF_OTA}'; add '{CONF_PLATFORM}: {CONF_ESPHOME}' for original OTA functionality" + ) + + +FINAL_VALIDATE_SCHEMA = _ota_final_validate + +BASE_OTA_SCHEMA = cv.Schema( { - cv.GenerateID(): cv.declare_id(OTAComponent), - cv.Optional(CONF_SAFE_MODE, default=True): cv.boolean, - cv.Optional(CONF_VERSION, default=2): cv.one_of(1, 2, int=True), - cv.SplitDefault( - CONF_PORT, - esp8266=8266, - esp32=3232, - rp2040=2040, - bk72xx=8892, - rtl87xx=8892, - ): cv.port, - cv.Optional(CONF_PASSWORD): cv.string, - cv.Optional( - CONF_REBOOT_TIMEOUT, default="5min" - ): cv.positive_time_period_milliseconds, - cv.Optional(CONF_NUM_ATTEMPTS, default="10"): cv.positive_not_null_int, cv.Optional(CONF_ON_STATE_CHANGE): automation.validate_automation( { cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAStateChangeTrigger), } ), + cv.Optional(CONF_ON_ABORT): automation.validate_automation( + { + cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAAbortTrigger), + } + ), cv.Optional(CONF_ON_BEGIN): automation.validate_automation( { cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAStartTrigger), } ), + cv.Optional(CONF_ON_END): automation.validate_automation( + { + cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAEndTrigger), + } + ), cv.Optional(CONF_ON_ERROR): automation.validate_automation( { cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAErrorTrigger), @@ -76,35 +72,13 @@ CONFIG_SCHEMA = cv.Schema( cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAProgressTrigger), } ), - cv.Optional(CONF_ON_END): automation.validate_automation( - { - cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAEndTrigger), - } - ), } -).extend(cv.COMPONENT_SCHEMA) +) -@coroutine_with_priority(50.0) +@coroutine_with_priority(51.0) async def to_code(config): - CORE.data[CONF_OTA] = {} - - var = cg.new_Pvariable(config[CONF_ID]) - cg.add(var.set_port(config[CONF_PORT])) cg.add_define("USE_OTA") - if CONF_PASSWORD in config: - cg.add(var.set_auth_password(config[CONF_PASSWORD])) - cg.add_define("USE_OTA_PASSWORD") - cg.add_define("USE_OTA_VERSION", config[CONF_VERSION]) - - await cg.register_component(var, config) - - if config[CONF_SAFE_MODE]: - condition = var.should_enter_safe_mode( - config[CONF_NUM_ATTEMPTS], config[CONF_REBOOT_TIMEOUT] - ) - cg.add(RawExpression(f"if ({condition}) return")) - CORE.data[CONF_OTA][KEY_PAST_SAFE_MODE] = True if CORE.is_esp32 and CORE.using_arduino: cg.add_library("Update", None) @@ -112,11 +86,17 @@ async def to_code(config): if CORE.is_rp2040 and CORE.using_arduino: cg.add_library("Updater", None) + +async def ota_to_code(var, config): use_state_callback = False for conf in config.get(CONF_ON_STATE_CHANGE, []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) await automation.build_automation(trigger, [(OTAState, "state")], conf) use_state_callback = True + for conf in config.get(CONF_ON_ABORT, []): + trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) + await automation.build_automation(trigger, [], conf) + use_state_callback = True for conf in config.get(CONF_ON_BEGIN, []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) await automation.build_automation(trigger, [], conf) diff --git a/esphome/components/ota/automation.h b/esphome/components/ota/automation.h index 0c77a18ce1..4605193480 100644 --- a/esphome/components/ota/automation.h +++ b/esphome/components/ota/automation.h @@ -1,11 +1,8 @@ #pragma once - -#include "esphome/core/defines.h" #ifdef USE_OTA_STATE_CALLBACK +#include "ota_backend.h" -#include "esphome/core/component.h" #include "esphome/core/automation.h" -#include "esphome/components/ota/ota_component.h" namespace esphome { namespace ota { @@ -54,6 +51,17 @@ class OTAEndTrigger : public Trigger<> { } }; +class OTAAbortTrigger : public Trigger<> { + public: + explicit OTAAbortTrigger(OTAComponent *parent) { + parent->add_on_state_callback([this, parent](OTAState state, float progress, uint8_t error) { + if (state == OTA_ABORT && !parent->is_failed()) { + trigger(); + } + }); + } +}; + class OTAErrorTrigger : public Trigger { public: explicit OTAErrorTrigger(OTAComponent *parent) { @@ -67,5 +75,4 @@ class OTAErrorTrigger : public Trigger { } // namespace ota } // namespace esphome - -#endif // USE_OTA_STATE_CALLBACK +#endif diff --git a/esphome/components/ota/ota_backend.cpp b/esphome/components/ota/ota_backend.cpp new file mode 100644 index 0000000000..30de4ec4b3 --- /dev/null +++ b/esphome/components/ota/ota_backend.cpp @@ -0,0 +1,20 @@ +#include "ota_backend.h" + +namespace esphome { +namespace ota { + +#ifdef USE_OTA_STATE_CALLBACK +OTAGlobalCallback *global_ota_callback{nullptr}; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) + +OTAGlobalCallback *get_global_ota_callback() { + if (global_ota_callback == nullptr) { + global_ota_callback = new OTAGlobalCallback(); // NOLINT(cppcoreguidelines-owning-memory) + } + return global_ota_callback; +} + +void register_ota_platform(OTAComponent *ota_caller) { get_global_ota_callback()->register_ota(ota_caller); } +#endif + +} // namespace ota +} // namespace esphome diff --git a/esphome/components/ota/ota_backend.h b/esphome/components/ota/ota_backend.h index 5c5b61a278..bc8ab46643 100644 --- a/esphome/components/ota/ota_backend.h +++ b/esphome/components/ota/ota_backend.h @@ -1,9 +1,53 @@ #pragma once -#include "ota_component.h" + +#include "esphome/core/component.h" +#include "esphome/core/defines.h" +#include "esphome/core/helpers.h" + +#ifdef USE_OTA_STATE_CALLBACK +#include "esphome/core/automation.h" +#endif namespace esphome { namespace ota { +enum OTAResponseTypes { + OTA_RESPONSE_OK = 0x00, + OTA_RESPONSE_REQUEST_AUTH = 0x01, + + OTA_RESPONSE_HEADER_OK = 0x40, + OTA_RESPONSE_AUTH_OK = 0x41, + OTA_RESPONSE_UPDATE_PREPARE_OK = 0x42, + OTA_RESPONSE_BIN_MD5_OK = 0x43, + OTA_RESPONSE_RECEIVE_OK = 0x44, + OTA_RESPONSE_UPDATE_END_OK = 0x45, + OTA_RESPONSE_SUPPORTS_COMPRESSION = 0x46, + OTA_RESPONSE_CHUNK_OK = 0x47, + + OTA_RESPONSE_ERROR_MAGIC = 0x80, + OTA_RESPONSE_ERROR_UPDATE_PREPARE = 0x81, + OTA_RESPONSE_ERROR_AUTH_INVALID = 0x82, + OTA_RESPONSE_ERROR_WRITING_FLASH = 0x83, + OTA_RESPONSE_ERROR_UPDATE_END = 0x84, + OTA_RESPONSE_ERROR_INVALID_BOOTSTRAPPING = 0x85, + OTA_RESPONSE_ERROR_WRONG_CURRENT_FLASH_CONFIG = 0x86, + OTA_RESPONSE_ERROR_WRONG_NEW_FLASH_CONFIG = 0x87, + OTA_RESPONSE_ERROR_ESP8266_NOT_ENOUGH_SPACE = 0x88, + OTA_RESPONSE_ERROR_ESP32_NOT_ENOUGH_SPACE = 0x89, + OTA_RESPONSE_ERROR_NO_UPDATE_PARTITION = 0x8A, + OTA_RESPONSE_ERROR_MD5_MISMATCH = 0x8B, + OTA_RESPONSE_ERROR_RP2040_NOT_ENOUGH_SPACE = 0x8C, + OTA_RESPONSE_ERROR_UNKNOWN = 0xFF, +}; + +enum OTAState { + OTA_COMPLETED = 0, + OTA_STARTED, + OTA_IN_PROGRESS, + OTA_ABORT, + OTA_ERROR, +}; + class OTABackend { public: virtual ~OTABackend() = default; @@ -15,5 +59,38 @@ class OTABackend { virtual bool supports_compression() = 0; }; +class OTAComponent : public Component { +#ifdef USE_OTA_STATE_CALLBACK + public: + void add_on_state_callback(std::function &&callback) { + this->state_callback_.add(std::move(callback)); + } + + protected: + CallbackManager state_callback_{}; +#endif +}; + +#ifdef USE_OTA_STATE_CALLBACK +class OTAGlobalCallback { + public: + void register_ota(OTAComponent *ota_caller) { + ota_caller->add_on_state_callback([this, ota_caller](OTAState state, float progress, uint8_t error) { + this->state_callback_.call(state, progress, error, ota_caller); + }); + } + void add_on_state_callback(std::function &&callback) { + this->state_callback_.add(std::move(callback)); + } + + protected: + CallbackManager state_callback_{}; +}; + +OTAGlobalCallback *get_global_ota_callback(); +void register_ota_platform(OTAComponent *ota_caller); +#endif +std::unique_ptr make_ota_backend(); + } // namespace ota } // namespace esphome diff --git a/esphome/components/ota/ota_backend_arduino_esp32.cpp b/esphome/components/ota/ota_backend_arduino_esp32.cpp index 4759737dbd..62c6a72388 100644 --- a/esphome/components/ota/ota_backend_arduino_esp32.cpp +++ b/esphome/components/ota/ota_backend_arduino_esp32.cpp @@ -1,8 +1,7 @@ -#include "esphome/core/defines.h" #ifdef USE_ESP32_FRAMEWORK_ARDUINO +#include "esphome/core/defines.h" #include "ota_backend_arduino_esp32.h" -#include "ota_component.h" #include "ota_backend.h" #include @@ -10,6 +9,8 @@ namespace esphome { namespace ota { +std::unique_ptr make_ota_backend() { return make_unique(); } + OTAResponseTypes ArduinoESP32OTABackend::begin(size_t image_size) { bool ret = Update.begin(image_size, U_FLASH); if (ret) { diff --git a/esphome/components/ota/ota_backend_arduino_esp32.h b/esphome/components/ota/ota_backend_arduino_esp32.h index f86a70d678..ac7fe9f14f 100644 --- a/esphome/components/ota/ota_backend_arduino_esp32.h +++ b/esphome/components/ota/ota_backend_arduino_esp32.h @@ -1,10 +1,10 @@ #pragma once -#include "esphome/core/defines.h" #ifdef USE_ESP32_FRAMEWORK_ARDUINO - -#include "ota_component.h" #include "ota_backend.h" +#include "esphome/core/defines.h" +#include "esphome/core/helpers.h" + namespace esphome { namespace ota { diff --git a/esphome/components/ota/ota_backend_arduino_esp8266.cpp b/esphome/components/ota/ota_backend_arduino_esp8266.cpp index 23dc0d4e21..b317075bd0 100644 --- a/esphome/components/ota/ota_backend_arduino_esp8266.cpp +++ b/esphome/components/ota/ota_backend_arduino_esp8266.cpp @@ -1,10 +1,9 @@ -#include "esphome/core/defines.h" #ifdef USE_ARDUINO #ifdef USE_ESP8266 - -#include "ota_backend_arduino_esp8266.h" -#include "ota_component.h" #include "ota_backend.h" +#include "ota_backend_arduino_esp8266.h" + +#include "esphome/core/defines.h" #include "esphome/components/esp8266/preferences.h" #include @@ -12,6 +11,8 @@ namespace esphome { namespace ota { +std::unique_ptr make_ota_backend() { return make_unique(); } + OTAResponseTypes ArduinoESP8266OTABackend::begin(size_t image_size) { bool ret = Update.begin(image_size, U_FLASH); if (ret) { diff --git a/esphome/components/ota/ota_backend_arduino_esp8266.h b/esphome/components/ota/ota_backend_arduino_esp8266.h index 7937c665b0..7f44d7c965 100644 --- a/esphome/components/ota/ota_backend_arduino_esp8266.h +++ b/esphome/components/ota/ota_backend_arduino_esp8266.h @@ -1,10 +1,9 @@ #pragma once -#include "esphome/core/defines.h" #ifdef USE_ARDUINO #ifdef USE_ESP8266 - -#include "ota_component.h" #include "ota_backend.h" + +#include "esphome/core/defines.h" #include "esphome/core/macros.h" namespace esphome { diff --git a/esphome/components/ota/ota_backend_arduino_libretiny.cpp b/esphome/components/ota/ota_backend_arduino_libretiny.cpp index dbf6c97988..df4e774ebc 100644 --- a/esphome/components/ota/ota_backend_arduino_libretiny.cpp +++ b/esphome/components/ota/ota_backend_arduino_libretiny.cpp @@ -1,15 +1,16 @@ -#include "esphome/core/defines.h" #ifdef USE_LIBRETINY - -#include "ota_backend_arduino_libretiny.h" -#include "ota_component.h" #include "ota_backend.h" +#include "ota_backend_arduino_libretiny.h" + +#include "esphome/core/defines.h" #include namespace esphome { namespace ota { +std::unique_ptr make_ota_backend() { return make_unique(); } + OTAResponseTypes ArduinoLibreTinyOTABackend::begin(size_t image_size) { bool ret = Update.begin(image_size, U_FLASH); if (ret) { diff --git a/esphome/components/ota/ota_backend_arduino_libretiny.h b/esphome/components/ota/ota_backend_arduino_libretiny.h index 79656bb353..11deb6e2f2 100644 --- a/esphome/components/ota/ota_backend_arduino_libretiny.h +++ b/esphome/components/ota/ota_backend_arduino_libretiny.h @@ -1,10 +1,9 @@ #pragma once -#include "esphome/core/defines.h" #ifdef USE_LIBRETINY - -#include "ota_component.h" #include "ota_backend.h" +#include "esphome/core/defines.h" + namespace esphome { namespace ota { diff --git a/esphome/components/ota/ota_backend_arduino_rp2040.cpp b/esphome/components/ota/ota_backend_arduino_rp2040.cpp index 260387cec1..4448b0c95e 100644 --- a/esphome/components/ota/ota_backend_arduino_rp2040.cpp +++ b/esphome/components/ota/ota_backend_arduino_rp2040.cpp @@ -1,17 +1,18 @@ -#include "esphome/core/defines.h" #ifdef USE_ARDUINO #ifdef USE_RP2040 - -#include "esphome/components/rp2040/preferences.h" #include "ota_backend.h" #include "ota_backend_arduino_rp2040.h" -#include "ota_component.h" + +#include "esphome/components/rp2040/preferences.h" +#include "esphome/core/defines.h" #include namespace esphome { namespace ota { +std::unique_ptr make_ota_backend() { return make_unique(); } + OTAResponseTypes ArduinoRP2040OTABackend::begin(size_t image_size) { bool ret = Update.begin(image_size, U_FLASH); if (ret) { diff --git a/esphome/components/ota/ota_backend_arduino_rp2040.h b/esphome/components/ota/ota_backend_arduino_rp2040.h index 5aa2ec9435..b189964ab3 100644 --- a/esphome/components/ota/ota_backend_arduino_rp2040.h +++ b/esphome/components/ota/ota_backend_arduino_rp2040.h @@ -1,11 +1,10 @@ #pragma once -#include "esphome/core/defines.h" #ifdef USE_ARDUINO #ifdef USE_RP2040 - -#include "esphome/core/macros.h" #include "ota_backend.h" -#include "ota_component.h" + +#include "esphome/core/defines.h" +#include "esphome/core/macros.h" namespace esphome { namespace ota { diff --git a/esphome/components/ota/ota_backend_esp_idf.cpp b/esphome/components/ota/ota_backend_esp_idf.cpp index 319a1482f1..6f45fb75e4 100644 --- a/esphome/components/ota/ota_backend_esp_idf.cpp +++ b/esphome/components/ota/ota_backend_esp_idf.cpp @@ -1,12 +1,11 @@ -#include "esphome/core/defines.h" #ifdef USE_ESP_IDF - -#include - #include "ota_backend_esp_idf.h" -#include "ota_component.h" -#include + #include "esphome/components/md5/md5.h" +#include "esphome/core/defines.h" + +#include +#include #if ESP_IDF_VERSION_MAJOR >= 5 #include @@ -15,6 +14,8 @@ namespace esphome { namespace ota { +std::unique_ptr make_ota_backend() { return make_unique(); } + OTAResponseTypes IDFOTABackend::begin(size_t image_size) { this->partition_ = esp_ota_get_next_update_partition(nullptr); if (this->partition_ == nullptr) { diff --git a/esphome/components/ota/ota_backend_esp_idf.h b/esphome/components/ota/ota_backend_esp_idf.h index af09d0d693..ed66d9b970 100644 --- a/esphome/components/ota/ota_backend_esp_idf.h +++ b/esphome/components/ota/ota_backend_esp_idf.h @@ -1,11 +1,11 @@ #pragma once -#include "esphome/core/defines.h" #ifdef USE_ESP_IDF - -#include "ota_component.h" #include "ota_backend.h" -#include + #include "esphome/components/md5/md5.h" +#include "esphome/core/defines.h" + +#include namespace esphome { namespace ota { diff --git a/esphome/components/prometheus/prometheus_handler.cpp b/esphome/components/prometheus/prometheus_handler.cpp index 68bca95a21..09913bd713 100644 --- a/esphome/components/prometheus/prometheus_handler.cpp +++ b/esphome/components/prometheus/prometheus_handler.cpp @@ -65,8 +65,8 @@ std::string PrometheusHandler::relabel_name_(EntityBase *obj) { // Type-specific implementation #ifdef USE_SENSOR void PrometheusHandler::sensor_type_(AsyncResponseStream *stream) { - stream->print(F("#TYPE esphome_sensor_value GAUGE\n")); - stream->print(F("#TYPE esphome_sensor_failed GAUGE\n")); + stream->print(F("#TYPE esphome_sensor_value gauge\n")); + stream->print(F("#TYPE esphome_sensor_failed gauge\n")); } void PrometheusHandler::sensor_row_(AsyncResponseStream *stream, sensor::Sensor *obj) { if (obj->is_internal() && !this->include_internal_) @@ -102,8 +102,8 @@ void PrometheusHandler::sensor_row_(AsyncResponseStream *stream, sensor::Sensor // Type-specific implementation #ifdef USE_BINARY_SENSOR void PrometheusHandler::binary_sensor_type_(AsyncResponseStream *stream) { - stream->print(F("#TYPE esphome_binary_sensor_value GAUGE\n")); - stream->print(F("#TYPE esphome_binary_sensor_failed GAUGE\n")); + stream->print(F("#TYPE esphome_binary_sensor_value gauge\n")); + stream->print(F("#TYPE esphome_binary_sensor_failed gauge\n")); } void PrometheusHandler::binary_sensor_row_(AsyncResponseStream *stream, binary_sensor::BinarySensor *obj) { if (obj->is_internal() && !this->include_internal_) @@ -136,10 +136,10 @@ void PrometheusHandler::binary_sensor_row_(AsyncResponseStream *stream, binary_s #ifdef USE_FAN void PrometheusHandler::fan_type_(AsyncResponseStream *stream) { - stream->print(F("#TYPE esphome_fan_value GAUGE\n")); - stream->print(F("#TYPE esphome_fan_failed GAUGE\n")); - stream->print(F("#TYPE esphome_fan_speed GAUGE\n")); - stream->print(F("#TYPE esphome_fan_oscillation GAUGE\n")); + stream->print(F("#TYPE esphome_fan_value gauge\n")); + stream->print(F("#TYPE esphome_fan_failed gauge\n")); + stream->print(F("#TYPE esphome_fan_speed gauge\n")); + stream->print(F("#TYPE esphome_fan_oscillation gauge\n")); } void PrometheusHandler::fan_row_(AsyncResponseStream *stream, fan::Fan *obj) { if (obj->is_internal() && !this->include_internal_) @@ -182,9 +182,9 @@ void PrometheusHandler::fan_row_(AsyncResponseStream *stream, fan::Fan *obj) { #ifdef USE_LIGHT void PrometheusHandler::light_type_(AsyncResponseStream *stream) { - stream->print(F("#TYPE esphome_light_state GAUGE\n")); - stream->print(F("#TYPE esphome_light_color GAUGE\n")); - stream->print(F("#TYPE esphome_light_effect_active GAUGE\n")); + stream->print(F("#TYPE esphome_light_state gauge\n")); + stream->print(F("#TYPE esphome_light_color gauge\n")); + stream->print(F("#TYPE esphome_light_effect_active gauge\n")); } void PrometheusHandler::light_row_(AsyncResponseStream *stream, light::LightState *obj) { if (obj->is_internal() && !this->include_internal_) @@ -259,8 +259,8 @@ void PrometheusHandler::light_row_(AsyncResponseStream *stream, light::LightStat #ifdef USE_COVER void PrometheusHandler::cover_type_(AsyncResponseStream *stream) { - stream->print(F("#TYPE esphome_cover_value GAUGE\n")); - stream->print(F("#TYPE esphome_cover_failed GAUGE\n")); + stream->print(F("#TYPE esphome_cover_value gauge\n")); + stream->print(F("#TYPE esphome_cover_failed gauge\n")); } void PrometheusHandler::cover_row_(AsyncResponseStream *stream, cover::Cover *obj) { if (obj->is_internal() && !this->include_internal_) @@ -302,8 +302,8 @@ void PrometheusHandler::cover_row_(AsyncResponseStream *stream, cover::Cover *ob #ifdef USE_SWITCH void PrometheusHandler::switch_type_(AsyncResponseStream *stream) { - stream->print(F("#TYPE esphome_switch_value GAUGE\n")); - stream->print(F("#TYPE esphome_switch_failed GAUGE\n")); + stream->print(F("#TYPE esphome_switch_value gauge\n")); + stream->print(F("#TYPE esphome_switch_failed gauge\n")); } void PrometheusHandler::switch_row_(AsyncResponseStream *stream, switch_::Switch *obj) { if (obj->is_internal() && !this->include_internal_) @@ -326,8 +326,8 @@ void PrometheusHandler::switch_row_(AsyncResponseStream *stream, switch_::Switch #ifdef USE_LOCK void PrometheusHandler::lock_type_(AsyncResponseStream *stream) { - stream->print(F("#TYPE esphome_lock_value GAUGE\n")); - stream->print(F("#TYPE esphome_lock_failed GAUGE\n")); + stream->print(F("#TYPE esphome_lock_value gauge\n")); + stream->print(F("#TYPE esphome_lock_failed gauge\n")); } void PrometheusHandler::lock_row_(AsyncResponseStream *stream, lock::Lock *obj) { if (obj->is_internal() && !this->include_internal_) diff --git a/esphome/components/remote_base/__init__.py b/esphome/components/remote_base/__init__.py index 8a1d50d1c6..9d49026aa3 100644 --- a/esphome/components/remote_base/__init__.py +++ b/esphome/components/remote_base/__init__.py @@ -1913,3 +1913,41 @@ async def abbwelcome_action(var, config, args): cg.add(var.set_data_template(template_)) else: cg.add(var.set_data_static(data_)) + + +# Mirage +( + MirageData, + MirageBinarySensor, + MirageTrigger, + MirageAction, + MirageDumper, +) = declare_protocol("Mirage") + +MIRAGE_SCHEMA = cv.Schema( + { + cv.Required(CONF_CODE): cv.All([cv.hex_uint8_t], cv.Length(min=14, max=14)), + } +) + + +@register_binary_sensor("mirage", MirageBinarySensor, MIRAGE_SCHEMA) +def mirage_binary_sensor(var, config): + cg.add(var.set_code(config[CONF_CODE])) + + +@register_trigger("mirage", MirageTrigger, MirageData) +def mirage_trigger(var, config): + pass + + +@register_dumper("mirage", MirageDumper) +def mirage_dumper(var, config): + pass + + +@register_action("mirage", MirageAction, MIRAGE_SCHEMA) +async def mirage_action(var, config, args): + vec_ = cg.std_vector.template(cg.uint8) + template_ = await cg.templatable(config[CONF_CODE], args, vec_, vec_) + cg.add(var.set_code(template_)) diff --git a/esphome/components/remote_base/mirage_protocol.cpp b/esphome/components/remote_base/mirage_protocol.cpp new file mode 100644 index 0000000000..10d644a1cd --- /dev/null +++ b/esphome/components/remote_base/mirage_protocol.cpp @@ -0,0 +1,84 @@ +#include "mirage_protocol.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace remote_base { + +static const char *const TAG = "remote.mirage"; + +constexpr uint32_t HEADER_MARK_US = 8360; +constexpr uint32_t HEADER_SPACE_US = 4248; +constexpr uint32_t BIT_MARK_US = 554; +constexpr uint32_t BIT_ONE_SPACE_US = 1592; +constexpr uint32_t BIT_ZERO_SPACE_US = 545; + +constexpr unsigned int MIRAGE_IR_PACKET_BIT_SIZE = 120; + +void MirageProtocol::encode(RemoteTransmitData *dst, const MirageData &data) { + ESP_LOGI(TAG, "Transive Mirage: %s", format_hex_pretty(data.data).c_str()); + dst->set_carrier_frequency(38000); + dst->reserve(5 + ((data.data.size() + 1) * 2)); + dst->mark(HEADER_MARK_US); + dst->space(HEADER_SPACE_US); + dst->mark(BIT_MARK_US); + uint8_t checksum = 0; + for (uint8_t item : data.data) { + this->encode_byte_(dst, item); + checksum += (item >> 4) + (item & 0xF); + } + this->encode_byte_(dst, checksum); +} + +void MirageProtocol::encode_byte_(RemoteTransmitData *dst, uint8_t item) { + for (uint8_t b = 0; b < 8; b++) { + if (item & (1UL << b)) { + dst->space(BIT_ONE_SPACE_US); + } else { + dst->space(BIT_ZERO_SPACE_US); + } + dst->mark(BIT_MARK_US); + } +} + +optional MirageProtocol::decode(RemoteReceiveData src) { + if (!src.expect_item(HEADER_MARK_US, HEADER_SPACE_US)) { + return {}; + } + if (!src.expect_mark(BIT_MARK_US)) { + return {}; + } + size_t size = src.size() - src.get_index() - 1; + if (size < MIRAGE_IR_PACKET_BIT_SIZE * 2) + return {}; + size = MIRAGE_IR_PACKET_BIT_SIZE * 2; + uint8_t checksum = 0; + MirageData out; + while (size > 0) { + uint8_t data = 0; + for (uint8_t b = 0; b < 8; b++) { + if (src.expect_space(BIT_ONE_SPACE_US)) { + data |= (1UL << b); + } else if (!src.expect_space(BIT_ZERO_SPACE_US)) { + return {}; + } + if (!src.expect_mark(BIT_MARK_US)) { + return {}; + } + size -= 2; + } + if (size > 0) { + checksum += (data >> 4) + (data & 0xF); + out.data.push_back(data); + } else if (checksum != data) { + return {}; + } + } + return out; +} + +void MirageProtocol::dump(const MirageData &data) { + ESP_LOGI(TAG, "Received Mirage: %s", format_hex_pretty(data.data).c_str()); +} + +} // namespace remote_base +} // namespace esphome diff --git a/esphome/components/remote_base/mirage_protocol.h b/esphome/components/remote_base/mirage_protocol.h new file mode 100644 index 0000000000..4257f7fa00 --- /dev/null +++ b/esphome/components/remote_base/mirage_protocol.h @@ -0,0 +1,39 @@ +#pragma once + +#include "esphome/core/component.h" +#include "remote_base.h" + +namespace esphome { +namespace remote_base { + +struct MirageData { + std::vector data; + + bool operator==(const MirageData &rhs) const { return data == rhs.data; } +}; + +class MirageProtocol : public RemoteProtocol { + public: + void encode(RemoteTransmitData *dst, const MirageData &data) override; + optional decode(RemoteReceiveData src) override; + void dump(const MirageData &data) override; + + protected: + void encode_byte_(RemoteTransmitData *dst, uint8_t item); +}; + +DECLARE_REMOTE_PROTOCOL(Mirage) + +template class MirageAction : public RemoteTransmitterActionBase { + public: + TEMPLATABLE_VALUE(std::vector, code) + + void encode(RemoteTransmitData *dst, Ts... x) override { + MirageData data{}; + data.data = this->code_.value(x...); + MirageProtocol().encode(dst, data); + } +}; + +} // namespace remote_base +} // namespace esphome diff --git a/esphome/components/rp2040_pio_led_strip/led_strip.cpp b/esphome/components/rp2040_pio_led_strip/led_strip.cpp index c04419a9bf..3e5e82898d 100644 --- a/esphome/components/rp2040_pio_led_strip/led_strip.cpp +++ b/esphome/components/rp2040_pio_led_strip/led_strip.cpp @@ -6,6 +6,7 @@ #include "esphome/core/log.h" #include +#include #include #include @@ -14,6 +15,15 @@ namespace rp2040_pio_led_strip { static const char *TAG = "rp2040_pio_led_strip"; +static uint8_t num_instance_[2] = {0, 0}; +static std::map chipset_offsets_ = { + {CHIPSET_WS2812, 0}, {CHIPSET_WS2812B, 0}, {CHIPSET_SK6812, 0}, {CHIPSET_SM16703, 0}, {CHIPSET_CUSTOM, 0}, +}; +static std::map conf_count_ = { + {CHIPSET_WS2812, false}, {CHIPSET_WS2812B, false}, {CHIPSET_SK6812, false}, + {CHIPSET_SM16703, false}, {CHIPSET_CUSTOM, false}, +}; + void RP2040PIOLEDStripLightOutput::setup() { ESP_LOGCONFIG(TAG, "Setting up RP2040 LED Strip..."); @@ -34,24 +44,71 @@ void RP2040PIOLEDStripLightOutput::setup() { return; } + // Initialize the PIO program + // Select PIO instance to use (0 or 1) - this->pio_ = pio0; if (this->pio_ == nullptr) { ESP_LOGE(TAG, "Failed to claim PIO instance"); this->mark_failed(); return; } - // Load the assembled program into the PIO and get its location in the PIO's instruction memory - uint offset = pio_add_program(this->pio_, this->program_); + // if there are multiple strips, we can reuse the same PIO program and save space + // but there are only 4 state machines on each PIO so we can only have 4 strips per PIO + uint offset = 0; + + if (num_instance_[this->pio_ == pio0 ? 0 : 1] > 4) { + ESP_LOGE(TAG, "Too many instances of PIO program"); + this->mark_failed(); + return; + } + // keep track of how many instances of the PIO program are running on each PIO + num_instance_[this->pio_ == pio0 ? 0 : 1]++; + + // if there are multiple strips of the same chipset, we can reuse the same PIO program and save space + if (this->conf_count_[this->chipset_]) { + offset = chipset_offsets_[this->chipset_]; + } else { + // Load the assembled program into the PIO and get its location in the PIO's instruction memory and save it + offset = pio_add_program(this->pio_, this->program_); + chipset_offsets_[this->chipset_] = offset; + conf_count_[this->chipset_] = true; + } // Configure the state machine's PIO, and start it this->sm_ = pio_claim_unused_sm(this->pio_, true); if (this->sm_ < 0) { + // in theory this code should never be reached ESP_LOGE(TAG, "Failed to claim PIO state machine"); this->mark_failed(); return; } + + // Initalize the DMA channel (Note: There are 12 DMA channels and 8 state machines so we won't run out) + + this->dma_chan_ = dma_claim_unused_channel(true); + if (this->dma_chan_ < 0) { + ESP_LOGE(TAG, "Failed to claim DMA channel"); + this->mark_failed(); + return; + } + + this->dma_config_ = dma_channel_get_default_config(this->dma_chan_); + channel_config_set_transfer_data_size( + &this->dma_config_, + DMA_SIZE_8); // 8 bit transfers (could be 32 but the pio program would need to be changed to handle junk data) + channel_config_set_read_increment(&this->dma_config_, true); // increment the read address + channel_config_set_write_increment(&this->dma_config_, false); // don't increment the write address + channel_config_set_dreq(&this->dma_config_, + pio_get_dreq(this->pio_, this->sm_, true)); // set the DREQ to the state machine's TX FIFO + + dma_channel_configure(this->dma_chan_, &this->dma_config_, + &this->pio_->txf[this->sm_], // write to the state machine's TX FIFO + this->buf_, // read from memory + this->is_rgbw_ ? num_leds_ * 4 : num_leds_ * 3, // number of bytes to transfer + false // don't start yet + ); + this->init_(this->pio_, this->sm_, offset, this->pin_, this->max_refresh_rate_); } @@ -68,16 +125,8 @@ void RP2040PIOLEDStripLightOutput::write_state(light::LightState *state) { return; } - // assemble bits in buffer to 32 bit words with ex for GBR: 0bGGGGGGGGRRRRRRRRBBBBBBBB00000000 - for (int i = 0; i < this->num_leds_; i++) { - uint8_t multiplier = this->is_rgbw_ ? 4 : 3; - uint8_t c1 = this->buf_[(i * multiplier) + 0]; - uint8_t c2 = this->buf_[(i * multiplier) + 1]; - uint8_t c3 = this->buf_[(i * multiplier) + 2]; - uint8_t w = this->is_rgbw_ ? this->buf_[(i * 4) + 3] : 0; - uint32_t color = encode_uint32(c1, c2, c3, w); - pio_sm_put_blocking(this->pio_, this->sm_, color); - } + // the bits are already in the correct order for the pio program so we can just copy the buffer using DMA + dma_channel_transfer_from_buffer_now(this->dma_chan_, this->buf_, this->get_buffer_size_()); } light::ESPColorView RP2040PIOLEDStripLightOutput::get_view_internal(int32_t index) const { diff --git a/esphome/components/rp2040_pio_led_strip/led_strip.h b/esphome/components/rp2040_pio_led_strip/led_strip.h index 25ef9ca55f..9976842f02 100644 --- a/esphome/components/rp2040_pio_led_strip/led_strip.h +++ b/esphome/components/rp2040_pio_led_strip/led_strip.h @@ -9,9 +9,11 @@ #include "esphome/components/light/addressable_light.h" #include "esphome/components/light/light_output.h" +#include #include #include #include +#include namespace esphome { namespace rp2040_pio_led_strip { @@ -25,6 +27,15 @@ enum RGBOrder : uint8_t { ORDER_BRG, }; +enum Chipset : uint8_t { + CHIPSET_WS2812, + CHIPSET_WS2812B, + CHIPSET_SK6812, + CHIPSET_SM16703, + CHIPSET_APA102, + CHIPSET_CUSTOM = 0xFF, +}; + inline const char *rgb_order_to_string(RGBOrder order) { switch (order) { case ORDER_RGB: @@ -69,6 +80,7 @@ class RP2040PIOLEDStripLightOutput : public light::AddressableLight { void set_program(const pio_program_t *program) { this->program_ = program; } void set_init_function(init_fn init) { this->init_ = init; } + void set_chipset(Chipset chipset) { this->chipset_ = chipset; }; void set_rgb_order(RGBOrder rgb_order) { this->rgb_order_ = rgb_order; } void clear_effect_data() override { for (int i = 0; i < this->size(); i++) { @@ -92,14 +104,22 @@ class RP2040PIOLEDStripLightOutput : public light::AddressableLight { pio_hw_t *pio_; uint sm_; + uint dma_chan_; + dma_channel_config dma_config_; RGBOrder rgb_order_{ORDER_RGB}; + Chipset chipset_{CHIPSET_CUSTOM}; uint32_t last_refresh_{0}; float max_refresh_rate_; const pio_program_t *program_; init_fn init_; + + private: + inline static int num_instance_[2]; + inline static std::map conf_count_; + inline static std::map chipset_offsets_; }; } // namespace rp2040_pio_led_strip diff --git a/esphome/components/rp2040_pio_led_strip/light.py b/esphome/components/rp2040_pio_led_strip/light.py index 6c51b57e97..8dd2549ad4 100644 --- a/esphome/components/rp2040_pio_led_strip/light.py +++ b/esphome/components/rp2040_pio_led_strip/light.py @@ -5,6 +5,7 @@ from esphome.components import light, rp2040 from esphome.const import ( CONF_CHIPSET, CONF_ID, + CONF_IS_RGBW, CONF_NUM_LEDS, CONF_OUTPUT_ID, CONF_PIN, @@ -67,12 +68,15 @@ static inline void rp2040_pio_led_strip_driver_{id}_init(PIO pio, uint sm, uint pio_sm_config c = rp2040_pio_led_strip_{id}_program_get_default_config(offset); sm_config_set_set_pins(&c, pin, 1); - sm_config_set_out_shift(&c, false, true, {32 if rgbw else 24}); + sm_config_set_out_shift(&c, false, true, 8); sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); - int cycles_per_bit = 69; - float div = 2.409; - sm_config_set_clkdiv(&c, div); + // target frequency is 57.5MHz + long clk = clock_get_hz(clk_sys); + long target_freq = 57500000; + int n = 2; + int f = round(((clk / target_freq) - n ) * 256); + sm_config_set_clkdiv_int_frac(&c, n, f); pio_sm_init(pio, sm, offset, &c); @@ -85,8 +89,9 @@ static inline void rp2040_pio_led_strip_driver_{id}_init(PIO pio, uint sm, uint .wrap_target awaiting_data: ; Wait for data in FIFO queue + ; out null, 24 ; discard the byte lane replication of the FIFO since we only need 8 bits (not needed????) pull block ; this will block until there is data in the FIFO queue and then it will pull it into the shift register - set y, {31 if rgbw else 23} ; set y to the number of bits to write counting 0, (23 if RGB, 31 if RGBW) + set y, 7 ; set y to the number of bits to write counting 0, (always 7 because we are doing one word at a time) mainloop: ; go through each bit in the shift register and jump to the appropriate label @@ -94,7 +99,15 @@ mainloop: out x, 1 jmp !x, writezero - jmp writeone + +writeone: + ; Write T1H and T1L bits to the output pin + set pins, 1 [{t1h}] +{nops_t1h} + set pins, 0 [{t1l}] +{nops_t1l} + jmp y--, mainloop + jmp awaiting_data writezero: ; Write T0H and T0L bits to the output pin @@ -105,14 +118,7 @@ writezero: jmp y--, mainloop jmp awaiting_data -writeone: - ; Write T1H and T1L bits to the output pin - set pins, 1 [{t1h}] -{nops_t1h} - set pins, 0 [{t1l}] -{nops_t1l} - jmp y--, mainloop - jmp awaiting_data + .wrap""" @@ -138,7 +144,15 @@ RP2040PIOLEDStripLightOutput = rp2040_pio_led_strip_ns.class_( RGBOrder = rp2040_pio_led_strip_ns.enum("RGBOrder") -Chipsets = rp2040_pio_led_strip_ns.enum("Chipset") +Chipset = rp2040_pio_led_strip_ns.enum("Chipset") + +CHIPSETS = { + "WS2812": Chipset.CHIPSET_WS2812, + "WS2812B": Chipset.CHIPSET_WS2812B, + "SK6812": Chipset.CHIPSET_SK6812, + "SM16703": Chipset.CHIPSET_SM16703, + "CUSTOM": Chipset.CHIPSET_CUSTOM, +} @dataclass @@ -158,14 +172,13 @@ RGB_ORDERS = { "BRG": RGBOrder.ORDER_BRG, } -CHIPSETS = { - "WS2812": LEDStripTimings(20, 43, 41, 31), - "WS2812B": LEDStripTimings(23, 46, 46, 23), - "SK6812": LEDStripTimings(17, 52, 31, 31), +CHIPSET_TIMINGS = { + "WS2812": LEDStripTimings(20, 40, 46, 34), + "WS2812B": LEDStripTimings(23, 49, 46, 26), + "SK6812": LEDStripTimings(17, 52, 34, 34), "SM16703": LEDStripTimings(17, 52, 52, 17), } -CONF_IS_RGBW = "is_rgbw" CONF_BIT0_HIGH = "bit0_high" CONF_BIT0_LOW = "bit0_low" CONF_BIT1_HIGH = "bit1_high" @@ -192,7 +205,7 @@ CONFIG_SCHEMA = cv.All( cv.Required(CONF_NUM_LEDS): cv.positive_not_null_int, cv.Required(CONF_RGB_ORDER): cv.enum(RGB_ORDERS, upper=True), cv.Required(CONF_PIO): cv.one_of(0, 1, int=True), - cv.Optional(CONF_CHIPSET): cv.one_of(*CHIPSETS, upper=True), + cv.Optional(CONF_CHIPSET): cv.enum(CHIPSETS, upper=True), cv.Optional(CONF_IS_RGBW, default=False): cv.boolean, cv.Inclusive( CONF_BIT0_HIGH, @@ -238,7 +251,8 @@ async def to_code(config): key = f"led_strip_{id}" - if CONF_CHIPSET in config: + if chipset := config.get(CONF_CHIPSET): + cg.add(var.set_chipset(chipset)) _LOGGER.info("Generating PIO assembly code") rp2040.add_pio_file( __name__, @@ -246,13 +260,14 @@ async def to_code(config): generate_assembly_code( id, config[CONF_IS_RGBW], - CHIPSETS[config[CONF_CHIPSET]].T0H, - CHIPSETS[config[CONF_CHIPSET]].T0L, - CHIPSETS[config[CONF_CHIPSET]].T1H, - CHIPSETS[config[CONF_CHIPSET]].T1L, + CHIPSET_TIMINGS[chipset].T0H, + CHIPSET_TIMINGS[chipset].T0L, + CHIPSET_TIMINGS[chipset].T1H, + CHIPSET_TIMINGS[chipset].T1L, ), ) else: + cg.add(var.set_chipset(Chipset.CHIPSET_CUSTOM)) _LOGGER.info("Generating custom PIO assembly code") rp2040.add_pio_file( __name__, diff --git a/esphome/components/safe_mode/button/__init__.py b/esphome/components/safe_mode/button/__init__.py index 307e4e372e..bd51d2e038 100644 --- a/esphome/components/safe_mode/button/__init__.py +++ b/esphome/components/safe_mode/button/__init__.py @@ -1,18 +1,17 @@ import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import button -from esphome.components.ota import OTAComponent +from esphome.components.esphome.ota import ESPHomeOTAComponent from esphome.const import ( - CONF_ID, - CONF_OTA, + CONF_ESPHOME, DEVICE_CLASS_RESTART, ENTITY_CATEGORY_CONFIG, ICON_RESTART_ALERT, ) +from .. import safe_mode_ns -DEPENDENCIES = ["ota"] +DEPENDENCIES = ["ota.esphome"] -safe_mode_ns = cg.esphome_ns.namespace("safe_mode") SafeModeButton = safe_mode_ns.class_("SafeModeButton", button.Button, cg.Component) CONFIG_SCHEMA = ( @@ -22,15 +21,14 @@ CONFIG_SCHEMA = ( entity_category=ENTITY_CATEGORY_CONFIG, icon=ICON_RESTART_ALERT, ) - .extend({cv.GenerateID(CONF_OTA): cv.use_id(OTAComponent)}) + .extend({cv.GenerateID(CONF_ESPHOME): cv.use_id(ESPHomeOTAComponent)}) .extend(cv.COMPONENT_SCHEMA) ) async def to_code(config): - var = cg.new_Pvariable(config[CONF_ID]) + var = await button.new_button(config) await cg.register_component(var, config) - await button.register_button(var, config) - ota = await cg.get_variable(config[CONF_OTA]) + ota = await cg.get_variable(config[CONF_ESPHOME]) cg.add(var.set_ota(ota)) diff --git a/esphome/components/safe_mode/button/safe_mode_button.cpp b/esphome/components/safe_mode/button/safe_mode_button.cpp index 2b8654de46..d513b79c12 100644 --- a/esphome/components/safe_mode/button/safe_mode_button.cpp +++ b/esphome/components/safe_mode/button/safe_mode_button.cpp @@ -8,7 +8,7 @@ namespace safe_mode { static const char *const TAG = "safe_mode.button"; -void SafeModeButton::set_ota(ota::OTAComponent *ota) { this->ota_ = ota; } +void SafeModeButton::set_ota(esphome::ESPHomeOTAComponent *ota) { this->ota_ = ota; } void SafeModeButton::press_action() { ESP_LOGI(TAG, "Restarting device in safe mode..."); diff --git a/esphome/components/safe_mode/button/safe_mode_button.h b/esphome/components/safe_mode/button/safe_mode_button.h index 63e0d1755e..a306735b7f 100644 --- a/esphome/components/safe_mode/button/safe_mode_button.h +++ b/esphome/components/safe_mode/button/safe_mode_button.h @@ -1,8 +1,8 @@ #pragma once -#include "esphome/core/component.h" -#include "esphome/components/ota/ota_component.h" #include "esphome/components/button/button.h" +#include "esphome/components/esphome/ota/ota_esphome.h" +#include "esphome/core/component.h" namespace esphome { namespace safe_mode { @@ -10,10 +10,10 @@ namespace safe_mode { class SafeModeButton : public button::Button, public Component { public: void dump_config() override; - void set_ota(ota::OTAComponent *ota); + void set_ota(esphome::ESPHomeOTAComponent *ota); protected: - ota::OTAComponent *ota_; + esphome::ESPHomeOTAComponent *ota_; void press_action() override; }; diff --git a/esphome/components/safe_mode/switch/__init__.py b/esphome/components/safe_mode/switch/__init__.py index a6fcdfbece..0f8e500482 100644 --- a/esphome/components/safe_mode/switch/__init__.py +++ b/esphome/components/safe_mode/switch/__init__.py @@ -1,26 +1,26 @@ import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import switch -from esphome.components.ota import OTAComponent +from esphome.components.esphome.ota import ESPHomeOTAComponent from esphome.const import ( - CONF_OTA, + CONF_ESPHOME, ENTITY_CATEGORY_CONFIG, ICON_RESTART_ALERT, ) from .. import safe_mode_ns -DEPENDENCIES = ["ota"] +DEPENDENCIES = ["ota.esphome"] SafeModeSwitch = safe_mode_ns.class_("SafeModeSwitch", switch.Switch, cg.Component) CONFIG_SCHEMA = ( switch.switch_schema( SafeModeSwitch, - icon=ICON_RESTART_ALERT, - entity_category=ENTITY_CATEGORY_CONFIG, block_inverted=True, + entity_category=ENTITY_CATEGORY_CONFIG, + icon=ICON_RESTART_ALERT, ) - .extend({cv.GenerateID(CONF_OTA): cv.use_id(OTAComponent)}) + .extend({cv.GenerateID(CONF_ESPHOME): cv.use_id(ESPHomeOTAComponent)}) .extend(cv.COMPONENT_SCHEMA) ) @@ -29,5 +29,5 @@ async def to_code(config): var = await switch.new_switch(config) await cg.register_component(var, config) - ota = await cg.get_variable(config[CONF_OTA]) + ota = await cg.get_variable(config[CONF_ESPHOME]) cg.add(var.set_ota(ota)) diff --git a/esphome/components/safe_mode/switch/safe_mode_switch.cpp b/esphome/components/safe_mode/switch/safe_mode_switch.cpp index a3979eec06..71408df140 100644 --- a/esphome/components/safe_mode/switch/safe_mode_switch.cpp +++ b/esphome/components/safe_mode/switch/safe_mode_switch.cpp @@ -1,14 +1,14 @@ #include "safe_mode_switch.h" +#include "esphome/core/application.h" #include "esphome/core/hal.h" #include "esphome/core/log.h" -#include "esphome/core/application.h" namespace esphome { namespace safe_mode { static const char *const TAG = "safe_mode_switch"; -void SafeModeSwitch::set_ota(ota::OTAComponent *ota) { this->ota_ = ota; } +void SafeModeSwitch::set_ota(esphome::ESPHomeOTAComponent *ota) { this->ota_ = ota; } void SafeModeSwitch::write_state(bool state) { // Acknowledge diff --git a/esphome/components/safe_mode/switch/safe_mode_switch.h b/esphome/components/safe_mode/switch/safe_mode_switch.h index 2772db3d84..5bd15a44de 100644 --- a/esphome/components/safe_mode/switch/safe_mode_switch.h +++ b/esphome/components/safe_mode/switch/safe_mode_switch.h @@ -1,8 +1,8 @@ #pragma once -#include "esphome/core/component.h" -#include "esphome/components/ota/ota_component.h" +#include "esphome/components/esphome/ota/ota_esphome.h" #include "esphome/components/switch/switch.h" +#include "esphome/core/component.h" namespace esphome { namespace safe_mode { @@ -10,10 +10,10 @@ namespace safe_mode { class SafeModeSwitch : public switch_::Switch, public Component { public: void dump_config() override; - void set_ota(ota::OTAComponent *ota); + void set_ota(esphome::ESPHomeOTAComponent *ota); protected: - ota::OTAComponent *ota_; + esphome::ESPHomeOTAComponent *ota_; void write_state(bool state) override; }; diff --git a/esphome/components/select/__init__.py b/esphome/components/select/__init__.py index 7ad14f2440..1d234d5617 100644 --- a/esphome/components/select/__init__.py +++ b/esphome/components/select/__init__.py @@ -113,7 +113,7 @@ async def new_select(config, *, options: list[str]): return var -@coroutine_with_priority(40.0) +@coroutine_with_priority(100.0) async def to_code(config): cg.add_define("USE_SELECT") cg.add_global(select_ns.using) diff --git a/esphome/components/sensor/__init__.py b/esphome/components/sensor/__init__.py index ece232e1a6..ef5c4cc645 100644 --- a/esphome/components/sensor/__init__.py +++ b/esphome/components/sensor/__init__.py @@ -912,7 +912,7 @@ def _lstsq(a, b): return _mat_dot(_mat_dot(x, a_t), b) -@coroutine_with_priority(40.0) +@coroutine_with_priority(100.0) async def to_code(config): cg.add_define("USE_SENSOR") cg.add_global(sensor_ns.using) diff --git a/esphome/components/substitutions/__init__.py b/esphome/components/substitutions/__init__.py index 2d3a79ccae..fa52200d46 100644 --- a/esphome/components/substitutions/__init__.py +++ b/esphome/components/substitutions/__init__.py @@ -4,7 +4,7 @@ import esphome.config_validation as cv from esphome import core from esphome.const import CONF_SUBSTITUTIONS, VALID_SUBSTITUTIONS_CHARACTERS from esphome.yaml_util import ESPHomeDataBase, make_data_base -from esphome.config_helpers import merge_config +from esphome.config_helpers import merge_config, Extend, Remove CODEOWNERS = ["@esphome/core"] _LOGGER = logging.getLogger(__name__) @@ -105,7 +105,7 @@ def _substitute_item(substitutions, item, path, ignore_missing): sub = _expand_substitutions(substitutions, item, path, ignore_missing) if sub != item: return sub - elif isinstance(item, core.Lambda): + elif isinstance(item, (core.Lambda, Extend, Remove)): sub = _expand_substitutions(substitutions, item.value, path, ignore_missing) if sub != item: item.value = sub diff --git a/esphome/components/template/datetime/__init__.py b/esphome/components/template/datetime/__init__.py index 0c9447116f..746ab8a6f3 100644 --- a/esphome/components/template/datetime/__init__.py +++ b/esphome/components/template/datetime/__init__.py @@ -17,7 +17,6 @@ from esphome.const import ( CONF_YEAR, ) -from esphome.core import coroutine_with_priority from .. import template_ns CODEOWNERS = ["@rfdarter"] @@ -100,7 +99,6 @@ CONFIG_SCHEMA = cv.All( ) -@coroutine_with_priority(-100.0) async def to_code(config): var = await datetime.new_datetime(config) diff --git a/esphome/components/text/__init__.py b/esphome/components/text/__init__.py index c0140ff082..4ca055a730 100644 --- a/esphome/components/text/__init__.py +++ b/esphome/components/text/__init__.py @@ -108,7 +108,7 @@ async def new_text( return var -@coroutine_with_priority(40.0) +@coroutine_with_priority(100.0) async def to_code(config): cg.add_define("USE_TEXT") cg.add_global(text_ns.using) diff --git a/esphome/components/voice_assistant/voice_assistant.cpp b/esphome/components/voice_assistant/voice_assistant.cpp index e68e00948e..109e52f8eb 100644 --- a/esphome/components/voice_assistant/voice_assistant.cpp +++ b/esphome/components/voice_assistant/voice_assistant.cpp @@ -152,7 +152,7 @@ void VoiceAssistant::loop() { } else #endif { - this->set_state_(State::START_PIPELINE, State::START_MICROPHONE); + this->set_state_(State::START_MICROPHONE, State::START_PIPELINE); } } else { this->high_freq_.stop(); @@ -318,7 +318,7 @@ void VoiceAssistant::loop() { #endif #ifdef USE_MEDIA_PLAYER if (this->media_player_ != nullptr) { - playing = (this->media_player_->state == media_player::MediaPlayerState::MEDIA_PLAYER_STATE_PLAYING); + playing = (this->media_player_->state == media_player::MediaPlayerState::MEDIA_PLAYER_STATE_ANNOUNCING); } #endif if (playing) { @@ -514,7 +514,7 @@ void VoiceAssistant::request_start(bool continuous, bool silence_detection) { } else #endif { - this->set_state_(State::START_PIPELINE, State::START_MICROPHONE); + this->set_state_(State::START_MICROPHONE, State::START_PIPELINE); } } } @@ -640,7 +640,7 @@ void VoiceAssistant::on_event(const api::VoiceAssistantEventResponse &msg) { this->defer([this, url]() { #ifdef USE_MEDIA_PLAYER if (this->media_player_ != nullptr) { - this->media_player_->make_call().set_media_url(url).perform(); + this->media_player_->make_call().set_media_url(url).set_announcement(true).perform(); } #endif this->tts_end_trigger_->trigger(url); diff --git a/esphome/components/web_server/__init__.py b/esphome/components/web_server/__init__.py index bbd5bc662e..fa614fb5a6 100644 --- a/esphome/components/web_server/__init__.py +++ b/esphome/components/web_server/__init__.py @@ -35,19 +35,19 @@ WebServer = web_server_ns.class_("WebServer", cg.Component, cg.Controller) def default_url(config): config = config.copy() if config[CONF_VERSION] == 1: - if not (CONF_CSS_URL in config): + if CONF_CSS_URL not in config: config[CONF_CSS_URL] = "https://esphome.io/_static/webserver-v1.min.css" - if not (CONF_JS_URL in config): + if CONF_JS_URL not in config: config[CONF_JS_URL] = "https://esphome.io/_static/webserver-v1.min.js" if config[CONF_VERSION] == 2: - if not (CONF_CSS_URL in config): + if CONF_CSS_URL not in config: config[CONF_CSS_URL] = "" - if not (CONF_JS_URL in config): + if CONF_JS_URL not in config: config[CONF_JS_URL] = "https://oi.esphome.io/v2/www.js" if config[CONF_VERSION] == 3: - if not (CONF_CSS_URL in config): + if CONF_CSS_URL not in config: config[CONF_CSS_URL] = "" - if not (CONF_JS_URL in config): + if CONF_JS_URL not in config: config[CONF_JS_URL] = "https://oi.esphome.io/v3/www.js" return config diff --git a/esphome/components/wifi/__init__.py b/esphome/components/wifi/__init__.py index e0a17e9a2a..3b9e00956f 100644 --- a/esphome/components/wifi/__init__.py +++ b/esphome/components/wifi/__init__.py @@ -33,6 +33,7 @@ from esphome.const import ( CONF_KEY, CONF_USERNAME, CONF_EAP, + CONF_TTLS_PHASE_2, CONF_ON_CONNECT, CONF_ON_DISCONNECT, ) @@ -98,6 +99,14 @@ STA_MANUAL_IP_SCHEMA = AP_MANUAL_IP_SCHEMA.extend( } ) +TTLS_PHASE_2 = { + "pap": cg.global_ns.ESP_EAP_TTLS_PHASE2_PAP, + "chap": cg.global_ns.ESP_EAP_TTLS_PHASE2_CHAP, + "mschap": cg.global_ns.ESP_EAP_TTLS_PHASE2_MSCHAP, + "mschapv2": cg.global_ns.ESP_EAP_TTLS_PHASE2_MSCHAPV2, + "eap": cg.global_ns.ESP_EAP_TTLS_PHASE2_EAP, +} + EAP_AUTH_SCHEMA = cv.All( cv.Schema( { @@ -105,6 +114,9 @@ EAP_AUTH_SCHEMA = cv.All( cv.Optional(CONF_USERNAME): cv.string_strict, cv.Optional(CONF_PASSWORD): cv.string_strict, cv.Optional(CONF_CERTIFICATE_AUTHORITY): wpa2_eap.validate_certificate, + cv.Optional(CONF_TTLS_PHASE_2): cv.All( + cv.enum(TTLS_PHASE_2), cv.only_with_esp_idf + ), cv.Inclusive( CONF_CERTIFICATE, "certificate_and_key" ): wpa2_eap.validate_certificate, @@ -338,6 +350,7 @@ def eap_auth(config): ("ca_cert", ca_cert), ("client_cert", client_cert), ("client_key", key), + ("ttls_phase_2", config.get(CONF_TTLS_PHASE_2, TTLS_PHASE_2["mschapv2"])), ) diff --git a/esphome/components/wifi/wifi_component.cpp b/esphome/components/wifi/wifi_component.cpp index 7e245d3e86..2f34f2b05b 100644 --- a/esphome/components/wifi/wifi_component.cpp +++ b/esphome/components/wifi/wifi_component.cpp @@ -1,5 +1,14 @@ #include "wifi_component.h" #include +#include + +#ifdef USE_ESP_IDF +#if (ESP_IDF_VERSION_MAJOR >= 5 && ESP_IDF_VERSION_MINOR >= 1) +#include +#else +#include +#endif +#endif #if defined(USE_ESP32) || defined(USE_ESP_IDF) #include @@ -318,6 +327,16 @@ void WiFiComponent::start_connecting(const WiFiAP &ap, bool two) { ESP_LOGV(TAG, " Identity: " LOG_SECRET("'%s'"), eap_config.identity.c_str()); ESP_LOGV(TAG, " Username: " LOG_SECRET("'%s'"), eap_config.username.c_str()); ESP_LOGV(TAG, " Password: " LOG_SECRET("'%s'"), eap_config.password.c_str()); +#ifdef USE_ESP_IDF +#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE + std::map phase2types = {{ESP_EAP_TTLS_PHASE2_PAP, "pap"}, + {ESP_EAP_TTLS_PHASE2_CHAP, "chap"}, + {ESP_EAP_TTLS_PHASE2_MSCHAP, "mschap"}, + {ESP_EAP_TTLS_PHASE2_MSCHAPV2, "mschapv2"}, + {ESP_EAP_TTLS_PHASE2_EAP, "eap"}}; + ESP_LOGV(TAG, " TTLS Phase 2: " LOG_SECRET("'%s'"), phase2types[eap_config.ttls_phase_2].c_str()); +#endif +#endif bool ca_cert_present = eap_config.ca_cert != nullptr && strlen(eap_config.ca_cert); bool client_cert_present = eap_config.client_cert != nullptr && strlen(eap_config.client_cert); bool client_key_present = eap_config.client_key != nullptr && strlen(eap_config.client_key); diff --git a/esphome/components/wifi/wifi_component.h b/esphome/components/wifi/wifi_component.h index 133fa2970c..0b077819ae 100644 --- a/esphome/components/wifi/wifi_component.h +++ b/esphome/components/wifi/wifi_component.h @@ -19,6 +19,10 @@ #include #endif +#if defined(USE_ESP_IDF) && defined(USE_WIFI_WPA2_EAP) +#include +#endif + #ifdef USE_ESP8266 #include #include @@ -102,6 +106,10 @@ struct EAPAuth { // used for EAP-TLS const char *client_cert; const char *client_key; +// used for EAP-TTLS +#ifdef USE_ESP_IDF + esp_eap_ttls_phase2_types ttls_phase_2; +#endif }; #endif // USE_WIFI_WPA2_EAP diff --git a/esphome/components/wifi/wifi_component_esp32_arduino.cpp b/esphome/components/wifi/wifi_component_esp32_arduino.cpp index 44d77b4eed..ef7a624cd5 100644 --- a/esphome/components/wifi/wifi_component_esp32_arduino.cpp +++ b/esphome/components/wifi/wifi_component_esp32_arduino.cpp @@ -2,6 +2,7 @@ #ifdef USE_ESP32_FRAMEWORK_ARDUINO +#include #include #include @@ -24,45 +25,73 @@ namespace wifi { static const char *const TAG = "wifi_esp32"; +static esp_netif_t *s_sta_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) +#ifdef USE_WIFI_AP +static esp_netif_t *s_ap_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) +#endif // USE_WIFI_AP + static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) +void WiFiComponent::wifi_pre_setup_() { + auto f = std::bind(&WiFiComponent::wifi_event_callback_, this, std::placeholders::_1, std::placeholders::_2); + WiFi.onEvent(f); + WiFi.persistent(false); + // Make sure WiFi is in clean state before anything starts + this->wifi_mode_(false, false); +} + bool WiFiComponent::wifi_mode_(optional sta, optional ap) { - uint8_t current_mode = WiFiClass::getMode(); - bool current_sta = current_mode & 0b01; - bool current_ap = current_mode & 0b10; - bool enable_sta = sta.value_or(current_sta); - bool enable_ap = ap.value_or(current_ap); - if (current_sta == enable_sta && current_ap == enable_ap) + wifi_mode_t current_mode = WiFiClass::getMode(); + bool current_sta = current_mode == WIFI_MODE_STA || current_mode == WIFI_MODE_APSTA; + bool current_ap = current_mode == WIFI_MODE_AP || current_mode == WIFI_MODE_APSTA; + + bool set_sta = sta.value_or(current_sta); + bool set_ap = ap.value_or(current_ap); + + wifi_mode_t set_mode; + if (set_sta && set_ap) { + set_mode = WIFI_MODE_APSTA; + } else if (set_sta && !set_ap) { + set_mode = WIFI_MODE_STA; + } else if (!set_sta && set_ap) { + set_mode = WIFI_MODE_AP; + } else { + set_mode = WIFI_MODE_NULL; + } + + if (current_mode == set_mode) return true; - if (enable_sta && !current_sta) { + if (set_sta && !current_sta) { ESP_LOGV(TAG, "Enabling STA."); - } else if (!enable_sta && current_sta) { + } else if (!set_sta && current_sta) { ESP_LOGV(TAG, "Disabling STA."); } - if (enable_ap && !current_ap) { + if (set_ap && !current_ap) { ESP_LOGV(TAG, "Enabling AP."); - } else if (!enable_ap && current_ap) { + } else if (!set_ap && current_ap) { ESP_LOGV(TAG, "Disabling AP."); } - uint8_t mode = 0; - if (enable_sta) - mode |= 0b01; - if (enable_ap) - mode |= 0b10; - bool ret = WiFiClass::mode(static_cast(mode)); + bool ret = WiFiClass::mode(set_mode); if (!ret) { ESP_LOGW(TAG, "Setting WiFi mode failed!"); + return false; } + // WiFiClass::mode above calls esp_netif_create_default_wifi_sta() and + // esp_netif_create_default_wifi_ap(), which creates the interfaces. + if (set_sta) + s_sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); +#ifdef USE_WIFI_AP + if (set_ap) + s_ap_netif = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF"); +#endif + return ret; } -bool WiFiComponent::wifi_apply_output_power_(float output_power) { - int8_t val = static_cast(output_power * 4); - return esp_wifi_set_max_tx_power(val) == ESP_OK; -} + bool WiFiComponent::wifi_sta_pre_setup_() { if (!this->wifi_mode_(true, {})) return false; @@ -71,6 +100,12 @@ bool WiFiComponent::wifi_sta_pre_setup_() { delay(10); return true; } + +bool WiFiComponent::wifi_apply_output_power_(float output_power) { + int8_t val = static_cast(output_power * 4); + return esp_wifi_set_max_tx_power(val) == ESP_OK; +} + bool WiFiComponent::wifi_apply_power_save_() { wifi_ps_type_t power_save; switch (this->power_save_) { @@ -87,99 +122,7 @@ bool WiFiComponent::wifi_apply_power_save_() { } return esp_wifi_set_ps(power_save) == ESP_OK; } -bool WiFiComponent::wifi_sta_ip_config_(optional manual_ip) { - // enable STA - if (!this->wifi_mode_(true, {})) - return false; - tcpip_adapter_dhcp_status_t dhcp_status; - tcpip_adapter_dhcpc_get_status(TCPIP_ADAPTER_IF_STA, &dhcp_status); - if (!manual_ip.has_value()) { - // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly, - // the built-in SNTP client has a memory leak in certain situations. Disable this feature. - // https://github.com/esphome/issues/issues/2299 - sntp_servermode_dhcp(false); - - // Use DHCP client - if (dhcp_status != TCPIP_ADAPTER_DHCP_STARTED) { - esp_err_t err = tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA); - if (err != ESP_OK) { - ESP_LOGV(TAG, "Starting DHCP client failed! %d", err); - } - return err == ESP_OK; - } - return true; - } - - tcpip_adapter_ip_info_t info; - memset(&info, 0, sizeof(info)); - info.ip = manual_ip->static_ip; - info.gw = manual_ip->gateway; - info.netmask = manual_ip->subnet; - - esp_err_t dhcp_stop_ret = tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); - if (dhcp_stop_ret != ESP_OK && dhcp_stop_ret != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) { - ESP_LOGV(TAG, "Stopping DHCP client failed! %s", esp_err_to_name(dhcp_stop_ret)); - } - - esp_err_t wifi_set_info_ret = tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_STA, &info); - if (wifi_set_info_ret != ESP_OK) { - ESP_LOGV(TAG, "Setting manual IP info failed! %s", esp_err_to_name(wifi_set_info_ret)); - } - - ip_addr_t dns; -// TODO: is this needed? -#if LWIP_IPV6 - dns.type = IPADDR_TYPE_V4; -#endif /* LWIP_IPV6 */ - if (manual_ip->dns1.is_set()) { - dns = manual_ip->dns1; - dns_setserver(0, &dns); - } - if (manual_ip->dns2.is_set()) { - dns = manual_ip->dns2; - dns_setserver(1, &dns); - } - - return true; -} - -network::IPAddresses WiFiComponent::wifi_sta_ip_addresses() { - if (!this->has_sta()) - return {}; - network::IPAddresses addresses; - tcpip_adapter_ip_info_t ip; - esp_err_t err = tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip); - if (err != ESP_OK) { - ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err)); - // TODO: do something smarter - // return false; - } else { - addresses[0] = network::IPAddress(&ip.ip); - } -#if USE_NETWORK_IPV6 - ip6_addr_t ipv6; - err = tcpip_adapter_get_ip6_global(TCPIP_ADAPTER_IF_STA, &ipv6); - if (err != ESP_OK) { - ESP_LOGV(TAG, "esp_netif_get_ip6_gobal failed: %s", esp_err_to_name(err)); - } else { - addresses[1] = network::IPAddress(&ipv6); - } - err = tcpip_adapter_get_ip6_linklocal(TCPIP_ADAPTER_IF_STA, &ipv6); - if (err != ESP_OK) { - ESP_LOGV(TAG, "esp_netif_get_ip6_linklocal failed: %s", esp_err_to_name(err)); - } else { - addresses[2] = network::IPAddress(&ipv6); - } -#endif /* USE_NETWORK_IPV6 */ - - return addresses; -} - -bool WiFiComponent::wifi_apply_hostname_() { - // setting is done in SYSTEM_EVENT_STA_START callback - return true; -} bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) { // enable STA if (!this->wifi_mode_(true, {})) @@ -233,19 +176,24 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) { wifi_config_t current_conf; esp_err_t err; - esp_wifi_get_config(WIFI_IF_STA, ¤t_conf); + err = esp_wifi_get_config(WIFI_IF_STA, ¤t_conf); + if (err != ERR_OK) { + ESP_LOGW(TAG, "esp_wifi_get_config failed: %s", esp_err_to_name(err)); + // can continue + } if (memcmp(¤t_conf, &conf, sizeof(wifi_config_t)) != 0) { // NOLINT err = esp_wifi_disconnect(); if (err != ESP_OK) { - ESP_LOGV(TAG, "esp_wifi_disconnect failed! %d", err); + ESP_LOGV(TAG, "esp_wifi_disconnect failed: %s", esp_err_to_name(err)); return false; } } err = esp_wifi_set_config(WIFI_IF_STA, &conf); if (err != ESP_OK) { - ESP_LOGV(TAG, "esp_wifi_set_config failed! %d", err); + ESP_LOGV(TAG, "esp_wifi_set_config failed: %s", esp_err_to_name(err)); + return false; } if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) { @@ -304,12 +252,98 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) { err = esp_wifi_connect(); if (err != ESP_OK) { - ESP_LOGW(TAG, "esp_wifi_connect failed! %d", err); + ESP_LOGW(TAG, "esp_wifi_connect failed: %s", esp_err_to_name(err)); return false; } return true; } + +bool WiFiComponent::wifi_sta_ip_config_(optional manual_ip) { + // enable STA + if (!this->wifi_mode_(true, {})) + return false; + + esp_netif_dhcp_status_t dhcp_status; + esp_err_t err = esp_netif_dhcpc_get_status(s_sta_netif, &dhcp_status); + if (err != ESP_OK) { + ESP_LOGV(TAG, "esp_netif_dhcpc_get_status failed: %s", esp_err_to_name(err)); + return false; + } + + if (!manual_ip.has_value()) { + // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly, + // the built-in SNTP client has a memory leak in certain situations. Disable this feature. + // https://github.com/esphome/issues/issues/2299 + sntp_servermode_dhcp(false); + + // No manual IP is set; use DHCP client + if (dhcp_status != ESP_NETIF_DHCP_STARTED) { + err = esp_netif_dhcpc_start(s_sta_netif); + if (err != ESP_OK) { + ESP_LOGV(TAG, "Starting DHCP client failed! %d", err); + } + return err == ESP_OK; + } + return true; + } + + esp_netif_ip_info_t info; // struct of ip4_addr_t with ip, netmask, gw + info.ip = manual_ip->static_ip; + info.gw = manual_ip->gateway; + info.netmask = manual_ip->subnet; + err = esp_netif_dhcpc_stop(s_sta_netif); + if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) { + ESP_LOGV(TAG, "Stopping DHCP client failed! %s", esp_err_to_name(err)); + } + + err = esp_netif_set_ip_info(s_sta_netif, &info); + if (err != ESP_OK) { + ESP_LOGV(TAG, "Setting manual IP info failed! %s", esp_err_to_name(err)); + } + + esp_netif_dns_info_t dns; + if (manual_ip->dns1.is_set()) { + dns.ip = manual_ip->dns1; + esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns); + } + if (manual_ip->dns2.is_set()) { + dns.ip = manual_ip->dns2; + esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_BACKUP, &dns); + } + + return true; +} + +network::IPAddresses WiFiComponent::wifi_sta_ip_addresses() { + if (!this->has_sta()) + return {}; + network::IPAddresses addresses; + esp_netif_ip_info_t ip; + esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip); + if (err != ESP_OK) { + ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err)); + // TODO: do something smarter + // return false; + } else { + addresses[0] = network::IPAddress(&ip.ip); + } +#if USE_NETWORK_IPV6 + struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES]; + uint8_t count = 0; + count = esp_netif_get_all_ip6(s_sta_netif, if_ip6s); + assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES); + for (int i = 0; i < count; i++) { + addresses[i + 1] = network::IPAddress(&if_ip6s[i]); + } +#endif /* USE_NETWORK_IPV6 */ + return addresses; +} + +bool WiFiComponent::wifi_apply_hostname_() { + // setting is done in SYSTEM_EVENT_STA_START callback + return true; +} const char *get_auth_mode_str(uint8_t mode) { switch (mode) { case WIFI_AUTH_OPEN: @@ -324,6 +358,12 @@ const char *get_auth_mode_str(uint8_t mode) { return "WPA/WPA2 PSK"; case WIFI_AUTH_WPA2_ENTERPRISE: return "WPA2 Enterprise"; + case WIFI_AUTH_WPA3_PSK: + return "WPA3 PSK"; + case WIFI_AUTH_WPA2_WPA3_PSK: + return "WPA2/WPA3 PSK"; + case WIFI_AUTH_WAPI_PSK: + return "WAPI PSK"; default: return "UNKNOWN"; } @@ -409,12 +449,16 @@ const char *get_disconnect_reason_str(uint8_t reason) { return "Handshake Failed"; case WIFI_REASON_CONNECTION_FAIL: return "Connection Failed"; + case WIFI_REASON_ROAMING: + return "Station Roaming"; case WIFI_REASON_UNSPECIFIED: default: return "Unspecified"; } } +void WiFiComponent::wifi_loop_() {} + #define ESPHOME_EVENT_ID_WIFI_READY ARDUINO_EVENT_WIFI_READY #define ESPHOME_EVENT_ID_WIFI_SCAN_DONE ARDUINO_EVENT_WIFI_SCAN_DONE #define ESPHOME_EVENT_ID_WIFI_STA_START ARDUINO_EVENT_WIFI_STA_START @@ -450,7 +494,11 @@ void WiFiComponent::wifi_event_callback_(esphome_wifi_event_id_t event, esphome_ } case ESPHOME_EVENT_ID_WIFI_STA_START: { ESP_LOGV(TAG, "Event: WiFi STA start"); - tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, App.get_name().c_str()); + // apply hostname + esp_err_t err = esp_netif_set_hostname(s_sta_netif, App.get_name().c_str()); + if (err != ERR_OK) { + ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err)); + } break; } case ESPHOME_EVENT_ID_WIFI_STA_STOP: { @@ -573,22 +621,19 @@ void WiFiComponent::wifi_event_callback_(esphome_wifi_event_id_t event, esphome_ break; } } -void WiFiComponent::wifi_pre_setup_() { - auto f = std::bind(&WiFiComponent::wifi_event_callback_, this, std::placeholders::_1, std::placeholders::_2); - WiFi.onEvent(f); - WiFi.persistent(false); - // Make sure WiFi is in clean state before anything starts - this->wifi_mode_(false, false); -} + WiFiSTAConnectStatus WiFiComponent::wifi_sta_connect_status_() { auto status = WiFiClass::status(); if (status == WL_CONNECT_FAILED || status == WL_CONNECTION_LOST) { return WiFiSTAConnectStatus::ERROR_CONNECT_FAILED; - } else if (status == WL_NO_SSID_AVAIL) { + } + if (status == WL_NO_SSID_AVAIL) { return WiFiSTAConnectStatus::ERROR_NETWORK_NOT_FOUND; - } else if (s_sta_connecting) { + } + if (s_sta_connecting) { return WiFiSTAConnectStatus::CONNECTING; - } else if (status == WL_CONNECTED) { + } + if (status == WL_CONNECTED) { return WiFiSTAConnectStatus::CONNECTED; } return WiFiSTAConnectStatus::IDLE; @@ -638,8 +683,7 @@ bool WiFiComponent::wifi_ap_ip_config_(optional manual_ip) { if (!this->wifi_mode_({}, true)) return false; - tcpip_adapter_ip_info_t info; - memset(&info, 0, sizeof(info)); + esp_netif_ip_info_t info; if (manual_ip.has_value()) { info.ip = manual_ip->static_ip; info.gw = manual_ip->gateway; @@ -649,17 +693,16 @@ bool WiFiComponent::wifi_ap_ip_config_(optional manual_ip) { info.gw = network::IPAddress(192, 168, 4, 1); info.netmask = network::IPAddress(255, 255, 255, 0); } - tcpip_adapter_dhcp_status_t dhcp_status; - tcpip_adapter_dhcps_get_status(TCPIP_ADAPTER_IF_AP, &dhcp_status); - err = tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP); - if (err != ESP_OK) { - ESP_LOGV(TAG, "tcpip_adapter_dhcps_stop failed! %d", err); + + err = esp_netif_dhcpc_stop(s_ap_netif); + if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) { + ESP_LOGV(TAG, "esp_netif_dhcpc_stop failed: %s", esp_err_to_name(err)); return false; } - err = tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_AP, &info); + err = esp_netif_set_ip_info(s_ap_netif, &info); if (err != ESP_OK) { - ESP_LOGV(TAG, "tcpip_adapter_set_ip_info failed! %d", err); + ESP_LOGV(TAG, "esp_netif_set_ip_info failed! %d", err); return false; } @@ -672,17 +715,17 @@ bool WiFiComponent::wifi_ap_ip_config_(optional manual_ip) { start_address += 100; lease.end_ip = start_address; ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str().c_str()); - err = tcpip_adapter_dhcps_option(TCPIP_ADAPTER_OP_SET, TCPIP_ADAPTER_REQUESTED_IP_ADDRESS, &lease, sizeof(lease)); + err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_REQUESTED_IP_ADDRESS, &lease, sizeof(lease)); if (err != ESP_OK) { - ESP_LOGV(TAG, "tcpip_adapter_dhcps_option failed! %d", err); + ESP_LOGV(TAG, "esp_netif_dhcps_option failed! %d", err); return false; } - err = tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_AP); + err = esp_netif_dhcps_start(s_ap_netif); if (err != ESP_OK) { - ESP_LOGV(TAG, "tcpip_adapter_dhcps_start failed! %d", err); + ESP_LOGV(TAG, "esp_netif_dhcps_start failed! %d", err); return false; } @@ -710,6 +753,7 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) { strncpy(reinterpret_cast(conf.ap.password), ap.get_password().c_str(), sizeof(conf.ap.password)); } + // pairwise cipher of SoftAP, group cipher will be derived using this. conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP; esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf); @@ -729,8 +773,8 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) { } network::IPAddress WiFiComponent::wifi_soft_ap_ip() { - tcpip_adapter_ip_info_t ip; - tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip); + esp_netif_ip_info_t ip; + esp_netif_get_ip_info(s_ap_netif, &ip); return network::IPAddress(&ip.ip); } #endif // USE_WIFI_AP @@ -752,7 +796,6 @@ int32_t WiFiComponent::wifi_channel_() { return WiFi.channel(); } network::IPAddress WiFiComponent::wifi_subnet_mask_() { return network::IPAddress(WiFi.subnetMask()); } network::IPAddress WiFiComponent::wifi_gateway_ip_() { return network::IPAddress(WiFi.gatewayIP()); } network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { return network::IPAddress(WiFi.dnsIP(num)); } -void WiFiComponent::wifi_loop_() {} } // namespace wifi } // namespace esphome diff --git a/esphome/components/wifi/wifi_component_esp_idf.cpp b/esphome/components/wifi/wifi_component_esp_idf.cpp index ebb2fb92ea..bc575e6a2d 100644 --- a/esphome/components/wifi/wifi_component_esp_idf.cpp +++ b/esphome/components/wifi/wifi_component_esp_idf.cpp @@ -2,18 +2,18 @@ #ifdef USE_ESP_IDF -#include -#include -#include +#include +#include #include #include #include -#include -#include +#include +#include +#include +#include #include #include -#include #ifdef USE_WIFI_WPA2_EAP #include #endif @@ -22,13 +22,14 @@ #include "dhcpserver/dhcpserver.h" #endif // USE_WIFI_AP -#include "lwip/err.h" +#include "lwip/apps/sntp.h" #include "lwip/dns.h" +#include "lwip/err.h" +#include "esphome/core/application.h" +#include "esphome/core/hal.h" #include "esphome/core/helpers.h" #include "esphome/core/log.h" -#include "esphome/core/hal.h" -#include "esphome/core/application.h" #include "esphome/core/util.h" namespace esphome { @@ -196,8 +197,8 @@ bool WiFiComponent::wifi_mode_(optional sta, optional ap) { bool current_sta = current_mode == WIFI_MODE_STA || current_mode == WIFI_MODE_APSTA; bool current_ap = current_mode == WIFI_MODE_AP || current_mode == WIFI_MODE_APSTA; - bool set_sta = sta.has_value() ? *sta : current_sta; - bool set_ap = ap.has_value() ? *ap : current_ap; + bool set_sta = sta.value_or(current_sta); + bool set_ap = ap.value_or(current_ap); wifi_mode_t set_mode; if (set_sta && set_ap) { @@ -396,6 +397,11 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) { if (err != ESP_OK) { ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_password failed! %d", err); } + // set TTLS Phase 2, defaults to MSCHAPV2 + err = esp_wifi_sta_wpa2_ent_set_ttls_phase2_method(eap.ttls_phase_2); + if (err != ESP_OK) { + ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_ttls_phase2_method failed! %d", err); + } } err = esp_wifi_sta_wpa2_ent_enable(); if (err != ESP_OK) { @@ -433,6 +439,11 @@ bool WiFiComponent::wifi_sta_ip_config_(optional manual_ip) { } if (!manual_ip.has_value()) { + // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly, + // the built-in SNTP client has a memory leak in certain situations. Disable this feature. + // https://github.com/esphome/issues/issues/2299 + sntp_servermode_dhcp(false); + // No manual IP is set; use DHCP client if (dhcp_status != ESP_NETIF_DHCP_STARTED) { err = esp_netif_dhcpc_start(s_sta_netif); @@ -450,13 +461,12 @@ bool WiFiComponent::wifi_sta_ip_config_(optional manual_ip) { info.netmask = manual_ip->subnet; err = esp_netif_dhcpc_stop(s_sta_netif); if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) { - ESP_LOGV(TAG, "esp_netif_dhcpc_stop failed: %s", esp_err_to_name(err)); - return false; + ESP_LOGV(TAG, "Stopping DHCP client failed! %s", esp_err_to_name(err)); } + err = esp_netif_set_ip_info(s_sta_netif, &info); if (err != ESP_OK) { - ESP_LOGV(TAG, "esp_netif_set_ip_info failed: %s", esp_err_to_name(err)); - return false; + ESP_LOGV(TAG, "Setting manual IP info failed! %s", esp_err_to_name(err)); } esp_netif_dns_info_t dns; @@ -790,7 +800,7 @@ bool WiFiComponent::wifi_scan_start_(bool passive) { return false; } - scan_done_ = false; + this->scan_done_ = false; return true; } @@ -813,13 +823,13 @@ bool WiFiComponent::wifi_ap_ip_config_(optional manual_ip) { info.netmask = network::IPAddress(255, 255, 255, 0); } - err = esp_netif_dhcpc_stop(s_sta_netif); + err = esp_netif_dhcpc_stop(s_ap_netif); if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) { ESP_LOGV(TAG, "esp_netif_dhcpc_stop failed: %s", esp_err_to_name(err)); return false; } - err = esp_netif_set_ip_info(s_sta_netif, &info); + err = esp_netif_set_ip_info(s_ap_netif, &info); if (err != ESP_OK) { ESP_LOGV(TAG, "esp_netif_set_ip_info failed! %d", err); return false; @@ -834,14 +844,14 @@ bool WiFiComponent::wifi_ap_ip_config_(optional manual_ip) { start_address += 100; lease.end_ip = start_address; ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str().c_str()); - err = esp_netif_dhcps_option(s_sta_netif, ESP_NETIF_OP_SET, ESP_NETIF_REQUESTED_IP_ADDRESS, &lease, sizeof(lease)); + err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_REQUESTED_IP_ADDRESS, &lease, sizeof(lease)); if (err != ESP_OK) { ESP_LOGV(TAG, "esp_netif_dhcps_option failed! %d", err); return false; } - err = esp_netif_dhcps_start(s_sta_netif); + err = esp_netif_dhcps_start(s_ap_netif); if (err != ESP_OK) { ESP_LOGV(TAG, "esp_netif_dhcps_start failed! %d", err); @@ -888,25 +898,26 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) { return true; } -#endif // USE_WIFI_AP network::IPAddress WiFiComponent::wifi_soft_ap_ip() { esp_netif_ip_info_t ip; - esp_netif_get_ip_info(s_sta_netif, &ip); + esp_netif_get_ip_info(s_ap_netif, &ip); return network::IPAddress(&ip.ip); } +#endif // USE_WIFI_AP + bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); } bssid_t WiFiComponent::wifi_bssid() { + bssid_t bssid{}; wifi_ap_record_t info; esp_err_t err = esp_wifi_sta_get_ap_info(&info); - bssid_t res{}; if (err != ESP_OK) { ESP_LOGW(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err)); - return res; + return bssid; } - std::copy(info.bssid, info.bssid + 6, res.begin()); - return res; + std::copy(info.bssid, info.bssid + 6, bssid.begin()); + return bssid; } std::string WiFiComponent::wifi_ssid() { wifi_ap_record_t info{}; @@ -964,4 +975,4 @@ network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { } // namespace wifi } // namespace esphome -#endif +#endif // USE_ESP_IDF diff --git a/esphome/config.py b/esphome/config.py index 4f340225fe..2b231fc402 100644 --- a/esphome/config.py +++ b/esphome/config.py @@ -34,7 +34,7 @@ from esphome.voluptuous_schema import ExtraKeysInvalid from esphome.log import color, Fore import esphome.final_validate as fv import esphome.config_validation as cv -from esphome.types import ConfigType, ConfigPathType, ConfigFragmentType +from esphome.types import ConfigType, ConfigFragmentType _LOGGER = logging.getLogger(__name__) @@ -213,7 +213,7 @@ class Config(OrderedDict, fv.FinalValidateConfig): return doc_range def get_nested_item( - self, path: ConfigPathType, raise_error: bool = False + self, path: ConfigPath, raise_error: bool = False ) -> ConfigFragmentType: data = self for item_index in path: @@ -244,7 +244,7 @@ class Config(OrderedDict, fv.FinalValidateConfig): return path raise KeyError(f"ID {id} not found in configuration") - def get_config_for_path(self, path: ConfigPathType) -> ConfigFragmentType: + def get_config_for_path(self, path: ConfigPath) -> ConfigFragmentType: return self.get_nested_item(path, raise_error=True) @property @@ -885,6 +885,9 @@ def _get_parent_name(path, config): # Sub-item break return domain + # When processing a list, skip back over the index + while len(path) > 1 and isinstance(path[-1], int): + path = path[:-1] return path[-1] @@ -1106,7 +1109,14 @@ def read_config(command_line_substitutions): if errline: errstr += f" {errline}" safe_print(errstr) - safe_print(indent(dump_dict(res, path)[0])) + split_dump = dump_dict(res, path)[0].splitlines() + # find the last error message + i = len(split_dump) - 1 + while i > 10 and "\033[" not in split_dump[i]: + i = i - 1 + # discard lines more than 4 beyond the last error + i = min(i + 4, len(split_dump)) + safe_print(indent("\n".join(split_dump[:i]))) for err in res.errors: safe_print(color(Fore.BOLD_RED, err.msg)) diff --git a/esphome/config_helpers.py b/esphome/config_helpers.py index 7b47e097c8..b5e0b26143 100644 --- a/esphome/config_helpers.py +++ b/esphome/config_helpers.py @@ -8,6 +8,9 @@ class Extend: def __str__(self): return f"!extend {self.value}" + def __repr__(self): + return f"Extend({self.value})" + def __eq__(self, b): """ Check if two Extend objects contain the same ID. @@ -24,6 +27,9 @@ class Remove: def __str__(self): return f"!remove {self.value}" + def __repr__(self): + return f"Remove({self.value})" + def __eq__(self, b): """ Check if two Remove objects contain the same ID. @@ -50,14 +56,19 @@ def merge_config(full_old, full_new): return new res = old.copy() ids = { - v[CONF_ID]: i + v_id: i for i, v in enumerate(res) - if CONF_ID in v and isinstance(v[CONF_ID], str) + if (v_id := v.get(CONF_ID)) and isinstance(v_id, str) } + extend_ids = { + v_id.value: i + for i, v in enumerate(res) + if (v_id := v.get(CONF_ID)) and isinstance(v_id, Extend) + } + ids_to_delete = [] for v in new: - if CONF_ID in v: - new_id = v[CONF_ID] + if new_id := v.get(CONF_ID): if isinstance(new_id, Extend): new_id = new_id.value if new_id in ids: @@ -69,6 +80,14 @@ def merge_config(full_old, full_new): if new_id in ids: ids_to_delete.append(ids[new_id]) continue + elif ( + new_id in extend_ids + ): # When a package is extending a non-packaged item + extend_res = res[extend_ids[new_id]] + extend_res[CONF_ID] = new_id + new_v = merge(v, extend_res) + res[extend_ids[new_id]] = new_v + continue else: ids[new_id] = len(res) res.append(v) diff --git a/esphome/const.py b/esphome/const.py index 542183d3b2..616b686052 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -367,6 +367,7 @@ CONF_IDLE_TIME = "idle_time" CONF_IF = "if" CONF_IGNORE_EFUSE_MAC_CRC = "ignore_efuse_mac_crc" CONF_IGNORE_OUT_OF_RANGE = "ignore_out_of_range" +CONF_IGNORE_PIN_VALIDATION_ERROR = "ignore_pin_validation_error" CONF_IGNORE_STRAPPING_WARNING = "ignore_strapping_warning" CONF_IIR_FILTER = "iir_filter" CONF_ILLUMINANCE = "illuminance" @@ -399,6 +400,7 @@ CONF_INVERT_COLORS = "invert_colors" CONF_INVERTED = "inverted" CONF_IP_ADDRESS = "ip_address" CONF_IRQ_PIN = "irq_pin" +CONF_IS_RGBW = "is_rgbw" CONF_JS_INCLUDE = "js_include" CONF_JS_URL = "js_url" CONF_JVC = "jvc" @@ -855,6 +857,7 @@ CONF_TRANSFORM = "transform" CONF_TRANSITION_LENGTH = "transition_length" CONF_TRIGGER_ID = "trigger_id" CONF_TRIGGER_PIN = "trigger_pin" +CONF_TTLS_PHASE_2 = "ttls_phase_2" CONF_TUNE_ANTENNA = "tune_antenna" CONF_TURN_OFF_ACTION = "turn_off_action" CONF_TURN_ON_ACTION = "turn_on_action" diff --git a/esphome/core/config.py b/esphome/core/config.py index 2d87796987..80b731b905 100644 --- a/esphome/core/config.py +++ b/esphome/core/config.py @@ -394,7 +394,7 @@ async def to_code(config): if project_conf := config.get(CONF_PROJECT): cg.add_define("ESPHOME_PROJECT_NAME", project_conf[CONF_NAME]) cg.add_define("ESPHOME_PROJECT_VERSION", project_conf[CONF_VERSION]) - cg.add_define("ESPHOME_PROJECT_VERSION_30", project_conf[CONF_VERSION][:30]) + cg.add_define("ESPHOME_PROJECT_VERSION_30", project_conf[CONF_VERSION][:29]) for conf in project_conf.get(CONF_ON_UPDATE, []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID]) await cg.register_component(trigger, conf) diff --git a/esphome/cpp_helpers.py b/esphome/cpp_helpers.py index 4b3716e223..ce494e5d9d 100644 --- a/esphome/cpp_helpers.py +++ b/esphome/cpp_helpers.py @@ -3,14 +3,16 @@ import logging from esphome.const import ( CONF_DISABLED_BY_DEFAULT, CONF_ENTITY_CATEGORY, + CONF_ESPHOME, CONF_ICON, CONF_INTERNAL, CONF_NAME, - CONF_SETUP_PRIORITY, - CONF_UPDATE_INTERVAL, - CONF_TYPE_ID, CONF_OTA, + CONF_PLATFORM, CONF_SAFE_MODE, + CONF_SETUP_PRIORITY, + CONF_TYPE_ID, + CONF_UPDATE_INTERVAL, KEY_PAST_SAFE_MODE, ) @@ -139,9 +141,16 @@ async def build_registry_list(registry, config): async def past_safe_mode(): - safe_mode_enabled = ( - CONF_OTA in CORE.config and CORE.config[CONF_OTA][CONF_SAFE_MODE] - ) + ota_conf = {} + for ota_item in CORE.config.get(CONF_OTA, []): + if ota_item[CONF_PLATFORM] == CONF_ESPHOME: + ota_conf = ota_item + break + + if not ota_conf: + return + + safe_mode_enabled = ota_conf[CONF_SAFE_MODE] if not safe_mode_enabled: return diff --git a/esphome/pins.py b/esphome/pins.py index d02ad357a0..5ccb696738 100644 --- a/esphome/pins.py +++ b/esphome/pins.py @@ -327,6 +327,8 @@ def gpio_base_schema( cv.Optional(CONF_MODE, default={}): cv.All(mode_dict, mode_validator), } ) + if invertable: return schema.extend({cv.Optional(CONF_INVERTED, default=False): cv.boolean}) + return schema diff --git a/esphome/wizard.py b/esphome/wizard.py index 4ec366bbb9..9680ade044 100644 --- a/esphome/wizard.py +++ b/esphome/wizard.py @@ -153,10 +153,11 @@ def wizard_file(**kwargs): # Configure OTA config += "\nota:\n" + config += " - platform: esphome\n" if "ota_password" in kwargs: - config += f" password: \"{kwargs['ota_password']}\"" + config += f" password: \"{kwargs['ota_password']}\"" elif "password" in kwargs: - config += f" password: \"{kwargs['password']}\"" + config += f" password: \"{kwargs['password']}\"" # Configuring wifi config += "\n\nwifi:\n" diff --git a/pylintrc b/pylintrc deleted file mode 100644 index b70e5c7da9..0000000000 --- a/pylintrc +++ /dev/null @@ -1,30 +0,0 @@ -[MASTER] -reports=no -ignore=api_pb2.py - -disable= - format, - missing-docstring, - fixme, - unused-argument, - global-statement, - too-few-public-methods, - too-many-lines, - too-many-locals, - too-many-ancestors, - too-many-branches, - too-many-statements, - too-many-arguments, - too-many-return-statements, - too-many-instance-attributes, - duplicate-code, - invalid-name, - cyclic-import, - redefined-builtin, - undefined-loop-variable, - useless-object-inheritance, - stop-iteration-return, - import-outside-toplevel, - # Broken - unsupported-membership-test, - unsubscriptable-object, diff --git a/pyproject.toml b/pyproject.toml index a49abb7b3d..fe558f695f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,107 @@ +[build-system] +requires = ["setuptools==69.2.0", "wheel~=0.43.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "esphome" +license = {text = "MIT"} +description = "Make creating custom firmwares for ESP32/ESP8266 super easy." +readme = "README.md" +authors = [ + {name = "The ESPHome Authors", email = "esphome@nabucasa.com"} +] +keywords = ["home", "automation"] +classifiers = [ + "Environment :: Console", + "Intended Audience :: Developers", + "Intended Audience :: End Users/Desktop", + "License :: OSI Approved :: MIT License", + "Programming Language :: C++", + "Programming Language :: Python :: 3", + "Topic :: Home Automation", +] +requires-python = ">=3.9.0" + +dynamic = ["dependencies", "optional-dependencies", "version"] + +[project.urls] +"Documentation" = "https://esphome.io" +"Source Code" = "https://github.com/esphome/esphome" +"Bug Tracker" = "https://github.com/esphome/issues/issues" +"Feature Request Tracker" = "https://github.com/esphome/feature-requests/issues" +"Discord" = "https://discord.gg/KhAMKrd" +"Forum" = "https://community.home-assistant.io/c/esphome" +"Twitter" = "https://twitter.com/esphome_" + +[project.scripts] +esphome = "esphome.__main__:main" + +[tool.setuptools] +platforms = ["any"] +zip-safe = false +include-package-data = true + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} +optional-dependencies.dev = { file = ["requirements_dev.txt"] } +optional-dependencies.test = { file = ["requirements_test.txt"] } +optional-dependencies.displays = { file = ["requirements_optional.txt"] } +version = {attr = "esphome.const.__version__"} + +[tool.setuptools.packages.find] +include = ["esphome*"] + [tool.black] target-version = ["py39", "py310"] exclude = 'generated' + +[tool.pytest.ini_options] +testpaths = [ + "tests", +] +addopts = [ + "--cov=esphome", + "--cov-branch", +] + +[tool.pylint.MAIN] +py-version = "3.9" +ignore = [ + "api_pb2.py", +] +persistent = false + +[tool.pylint.REPORTS] +score = false + +[tool.pylint."MESSAGES CONTROL"] +disable = [ + "format", + "missing-docstring", + "fixme", + "unused-argument", + "global-statement", + "too-few-public-methods", + "too-many-lines", + "too-many-locals", + "too-many-ancestors", + "too-many-branches", + "too-many-statements", + "too-many-arguments", + "too-many-return-statements", + "too-many-instance-attributes", + "duplicate-code", + "invalid-name", + "cyclic-import", + "redefined-builtin", + "undefined-loop-variable", + "useless-object-inheritance", + "stop-iteration-return", + "import-outside-toplevel", + # Broken + "unsupported-membership-test", + "unsubscriptable-object", +] + +[tool.pylint.FORMAT] +expected-line-ending-format = "LF" diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index a91a2ea200..0000000000 --- a/pytest.ini +++ /dev/null @@ -1,4 +0,0 @@ -[pytest] -addopts = - --cov=esphome - --cov-branch diff --git a/requirements.txt b/requirements.txt index 698ae56447..05e46ca31e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,7 +12,7 @@ pyserial==3.5 platformio==6.1.15 # When updating platformio, also update Dockerfile esptool==4.7.0 click==8.1.7 -esphome-dashboard==20240412.0 +esphome-dashboard==20240429.1 aioesphomeapi==24.3.0 zeroconf==0.132.2 python-magic==0.4.27 diff --git a/requirements_test.txt b/requirements_test.txt index 78820765f4..ae833841ca 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -5,7 +5,7 @@ pyupgrade==3.15.2 # also change in .pre-commit-config.yaml when updating pre-commit # Unit tests -pytest==8.1.1 +pytest==8.2.0 pytest-cov==4.1.0 pytest-mock==3.14.0 pytest-asyncio==0.23.6 diff --git a/script/build_codeowners.py b/script/build_codeowners.py index 22f3c1b4bc..6bc558d351 100755 --- a/script/build_codeowners.py +++ b/script/build_codeowners.py @@ -28,7 +28,7 @@ BASE = """ # the integration's code owner is automatically notified. # Core Code -setup.py @esphome/core +pyproject.toml @esphome/core esphome/*.py @esphome/core esphome/core/* @esphome/core diff --git a/script/ci-custom.py b/script/ci-custom.py index 704962fa97..e2ee81f742 100755 --- a/script/ci-custom.py +++ b/script/ci-custom.py @@ -229,7 +229,6 @@ def lint_ext_check(fname): "docker/ha-addon-rootfs/**", "docker/*.py", "script/*", - "setup.py", ] ) def lint_executable_bit(fname): diff --git a/script/run-in-env.sh b/script/run-in-env.sh new file mode 100755 index 0000000000..2e05fe1d17 --- /dev/null +++ b/script/run-in-env.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env sh +set -eu + +my_path=$(git rev-parse --show-toplevel) + +for venv in venv .venv .; do + if [ -f "${my_path}/${venv}/bin/activate" ]; then + . "${my_path}/${venv}/bin/activate" + break + fi +done + +exec "$@" diff --git a/script/setup b/script/setup index f286b4672a..71573a9352 100755 --- a/script/setup +++ b/script/setup @@ -10,17 +10,17 @@ if [ ! -n "$DEVCONTAINER" ] && [ ! -n "$VIRTUAL_ENV" ] && [ ! "$ESPHOME_NO_VENV" if [ -f venv/Scripts/activate ]; then location="venv/Scripts/activate" fi - source $location; + source $location fi # Avoid unsafe git error when running inside devcontainer -if [ -n "$DEVCONTAINER" ];then +if [ -n "$DEVCONTAINER" ]; then git config --global --add safe.directory "$PWD" fi pip3 install -r requirements.txt -r requirements_optional.txt -r requirements_test.txt -r requirements_dev.txt pip3 install setuptools wheel -pip3 install --no-use-pep517 -e . +pip3 install -e --config-settings editable_mode=compat ".[dev,test,displays]" pre-commit install diff --git a/setup.py b/setup.py deleted file mode 100755 index 95453960ff..0000000000 --- a/setup.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python3 -"""esphome setup script.""" -import os - -from setuptools import setup, find_packages - -from esphome import const - -PROJECT_NAME = "esphome" -PROJECT_PACKAGE_NAME = "esphome" -PROJECT_LICENSE = "MIT" -PROJECT_AUTHOR = "ESPHome" -PROJECT_COPYRIGHT = "2019, ESPHome" -PROJECT_URL = "https://esphome.io/" -PROJECT_EMAIL = "esphome@nabucasa.com" - -PROJECT_GITHUB_USERNAME = "esphome" -PROJECT_GITHUB_REPOSITORY = "esphome" - -PYPI_URL = f"https://pypi.python.org/pypi/{PROJECT_PACKAGE_NAME}" -GITHUB_PATH = f"{PROJECT_GITHUB_USERNAME}/{PROJECT_GITHUB_REPOSITORY}" -GITHUB_URL = f"https://github.com/{GITHUB_PATH}" - -DOWNLOAD_URL = f"{GITHUB_URL}/archive/{const.__version__}.zip" - -here = os.path.abspath(os.path.dirname(__file__)) - -with open(os.path.join(here, "requirements.txt")) as requirements_txt: - REQUIRES = requirements_txt.read().splitlines() - -with open(os.path.join(here, "README.md")) as readme: - LONG_DESCRIPTION = readme.read() - -# If you have problems importing platformio and esptool as modules you can set -# $ESPHOME_USE_SUBPROCESS to make ESPHome call their executables instead. -# This means they have to be in your $PATH. -if "ESPHOME_USE_SUBPROCESS" in os.environ: - # Remove platformio and esptool from requirements - REQUIRES = [ - req - for req in REQUIRES - if not any(req.startswith(prefix) for prefix in ["platformio", "esptool"]) - ] - -CLASSIFIERS = [ - "Environment :: Console", - "Intended Audience :: Developers", - "Intended Audience :: End Users/Desktop", - "License :: OSI Approved :: MIT License", - "Programming Language :: C++", - "Programming Language :: Python :: 3", - "Topic :: Home Automation", -] - -setup( - name=PROJECT_PACKAGE_NAME, - version=const.__version__, - license=PROJECT_LICENSE, - url=GITHUB_URL, - project_urls={ - "Bug Tracker": "https://github.com/esphome/issues/issues", - "Feature Request Tracker": "https://github.com/esphome/feature-requests/issues", - "Source Code": "https://github.com/esphome/esphome", - "Documentation": "https://esphome.io", - "Twitter": "https://twitter.com/esphome_", - }, - download_url=DOWNLOAD_URL, - author=PROJECT_AUTHOR, - author_email=PROJECT_EMAIL, - description="Make creating custom firmwares for ESP32/ESP8266 super easy.", - long_description=LONG_DESCRIPTION, - long_description_content_type="text/markdown", - include_package_data=True, - zip_safe=False, - platforms="any", - test_suite="tests", - python_requires=">=3.9.0", - install_requires=REQUIRES, - keywords=["home", "automation"], - entry_points={"console_scripts": ["esphome = esphome.__main__:main"]}, - packages=find_packages(include="esphome.*"), -) diff --git a/tests/components/bedjet/common.yaml b/tests/components/bedjet/common.yaml index c2be04a49a..1563fc9dae 100644 --- a/tests/components/bedjet/common.yaml +++ b/tests/components/bedjet/common.yaml @@ -26,8 +26,16 @@ climate: name: My Bedjet bedjet_id: bedjet_hub heat_mode: extended + temperature_source: ambient fan: - platform: bedjet name: My Bedjet fan bedjet_id: bedjet_hub + +sensor: + - platform: bedjet + ambient_temperature: + name: My BedJet Ambient Temperature + outlet_temperature: + name: My BedJet Outlet Temperature diff --git a/tests/components/beken_spi_led_strip/test.bk72xx.yaml b/tests/components/beken_spi_led_strip/test.bk72xx.yaml new file mode 100644 index 0000000000..15409caeaf --- /dev/null +++ b/tests/components/beken_spi_led_strip/test.bk72xx.yaml @@ -0,0 +1,7 @@ +light: + - platform: beken_spi_led_strip + rgb_order: GRB + pin: P16 + num_leds: 30 + chipset: ws2812 + name: "My Light" diff --git a/tests/components/ens160/test.esp32-c3-idf.yaml b/tests/components/ens160/test.esp32-c3-idf.yaml deleted file mode 100644 index 29f48e812f..0000000000 --- a/tests/components/ens160/test.esp32-c3-idf.yaml +++ /dev/null @@ -1,13 +0,0 @@ -i2c: - - id: i2c_ens160 - scl: 5 - sda: 4 - -sensor: - - platform: ens160 - eco2: - name: ENS160 eCO2 - tvoc: - name: ENS160 Total Volatile Organic Compounds - aqi: - name: ENS160 Air Quality Index diff --git a/tests/components/ens160/test.esp32-c3.yaml b/tests/components/ens160/test.esp32-c3.yaml deleted file mode 100644 index 29f48e812f..0000000000 --- a/tests/components/ens160/test.esp32-c3.yaml +++ /dev/null @@ -1,13 +0,0 @@ -i2c: - - id: i2c_ens160 - scl: 5 - sda: 4 - -sensor: - - platform: ens160 - eco2: - name: ENS160 eCO2 - tvoc: - name: ENS160 Total Volatile Organic Compounds - aqi: - name: ENS160 Air Quality Index diff --git a/tests/components/ens160/test.esp32-idf.yaml b/tests/components/ens160/test.esp32-idf.yaml deleted file mode 100644 index 23f7674aef..0000000000 --- a/tests/components/ens160/test.esp32-idf.yaml +++ /dev/null @@ -1,13 +0,0 @@ -i2c: - - id: i2c_ens160 - scl: 16 - sda: 17 - -sensor: - - platform: ens160 - eco2: - name: ENS160 eCO2 - tvoc: - name: ENS160 Total Volatile Organic Compounds - aqi: - name: ENS160 Air Quality Index diff --git a/tests/components/ens160/test.esp32.yaml b/tests/components/ens160/test.esp32.yaml deleted file mode 100644 index 23f7674aef..0000000000 --- a/tests/components/ens160/test.esp32.yaml +++ /dev/null @@ -1,13 +0,0 @@ -i2c: - - id: i2c_ens160 - scl: 16 - sda: 17 - -sensor: - - platform: ens160 - eco2: - name: ENS160 eCO2 - tvoc: - name: ENS160 Total Volatile Organic Compounds - aqi: - name: ENS160 Air Quality Index diff --git a/tests/components/ens160/test.esp8266.yaml b/tests/components/ens160/test.esp8266.yaml deleted file mode 100644 index 29f48e812f..0000000000 --- a/tests/components/ens160/test.esp8266.yaml +++ /dev/null @@ -1,13 +0,0 @@ -i2c: - - id: i2c_ens160 - scl: 5 - sda: 4 - -sensor: - - platform: ens160 - eco2: - name: ENS160 eCO2 - tvoc: - name: ENS160 Total Volatile Organic Compounds - aqi: - name: ENS160 Air Quality Index diff --git a/tests/components/ens160/test.rp2040.yaml b/tests/components/ens160/test.rp2040.yaml deleted file mode 100644 index 29f48e812f..0000000000 --- a/tests/components/ens160/test.rp2040.yaml +++ /dev/null @@ -1,13 +0,0 @@ -i2c: - - id: i2c_ens160 - scl: 5 - sda: 4 - -sensor: - - platform: ens160 - eco2: - name: ENS160 eCO2 - tvoc: - name: ENS160 Total Volatile Organic Compounds - aqi: - name: ENS160 Air Quality Index diff --git a/tests/components/ens160_i2c/common.yaml b/tests/components/ens160_i2c/common.yaml new file mode 100644 index 0000000000..39a5b35067 --- /dev/null +++ b/tests/components/ens160_i2c/common.yaml @@ -0,0 +1,15 @@ +i2c: + - id: i2c_ens160 + scl: ${scl_pin} + sda: ${sda_pin} + +sensor: + - platform: ens160_i2c + i2c_id: i2c_ens160 + address: 0x53 + eco2: + name: "ENS160 eCO2" + tvoc: + name: "ENS160 Total Volatile Organic Compounds" + aqi: + name: "ENS160 Air Quality Index" diff --git a/tests/components/ens160_i2c/test.esp32-c3-idf.yaml b/tests/components/ens160_i2c/test.esp32-c3-idf.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ens160_i2c/test.esp32-c3-idf.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ens160_i2c/test.esp32-c3.yaml b/tests/components/ens160_i2c/test.esp32-c3.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ens160_i2c/test.esp32-c3.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ens160_i2c/test.esp32-idf.yaml b/tests/components/ens160_i2c/test.esp32-idf.yaml new file mode 100644 index 0000000000..63c3bd6afd --- /dev/null +++ b/tests/components/ens160_i2c/test.esp32-idf.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO16 + sda_pin: GPIO17 + +<<: !include common.yaml diff --git a/tests/components/ens160_i2c/test.esp32.yaml b/tests/components/ens160_i2c/test.esp32.yaml new file mode 100644 index 0000000000..63c3bd6afd --- /dev/null +++ b/tests/components/ens160_i2c/test.esp32.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO16 + sda_pin: GPIO17 + +<<: !include common.yaml diff --git a/tests/components/ens160_i2c/test.esp8266.yaml b/tests/components/ens160_i2c/test.esp8266.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ens160_i2c/test.esp8266.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ens160_i2c/test.rp2040.yaml b/tests/components/ens160_i2c/test.rp2040.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ens160_i2c/test.rp2040.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ens160_spi/common.yaml b/tests/components/ens160_spi/common.yaml new file mode 100644 index 0000000000..7250ead228 --- /dev/null +++ b/tests/components/ens160_spi/common.yaml @@ -0,0 +1,17 @@ +spi: + - id: spi_ens160 + clk_pin: ${clk_pin} + mosi_pin: ${mosi_pin} + miso_pin: ${miso_pin} + +sensor: + - platform: ens160_spi + spi_id: spi_ens160 + cs_pin: ${cs_pin} + eco2: + name: "ENS160 eCO2" + tvoc: + name: "ENS160 Total Volatile Organic Compounds" + aqi: + name: "ENS160 Air Quality Index" + diff --git a/tests/components/ens160_spi/test.esp32-c3-idf.yaml b/tests/components/ens160_spi/test.esp32-c3-idf.yaml new file mode 100644 index 0000000000..2415ba5dc6 --- /dev/null +++ b/tests/components/ens160_spi/test.esp32-c3-idf.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO6 + mosi_pin: GPIO7 + miso_pin: GPIO5 + cs_pin: GPIO8 + +<<: !include common.yaml diff --git a/tests/components/ens160_spi/test.esp32-c3.yaml b/tests/components/ens160_spi/test.esp32-c3.yaml new file mode 100644 index 0000000000..2415ba5dc6 --- /dev/null +++ b/tests/components/ens160_spi/test.esp32-c3.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO6 + mosi_pin: GPIO7 + miso_pin: GPIO5 + cs_pin: GPIO8 + +<<: !include common.yaml diff --git a/tests/components/ens160_spi/test.esp32-idf.yaml b/tests/components/ens160_spi/test.esp32-idf.yaml new file mode 100644 index 0000000000..54e027a614 --- /dev/null +++ b/tests/components/ens160_spi/test.esp32-idf.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO16 + mosi_pin: GPIO17 + miso_pin: GPIO15 + cs_pin: GPIO5 + +<<: !include common.yaml diff --git a/tests/components/ens160_spi/test.esp32.yaml b/tests/components/ens160_spi/test.esp32.yaml new file mode 100644 index 0000000000..54e027a614 --- /dev/null +++ b/tests/components/ens160_spi/test.esp32.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO16 + mosi_pin: GPIO17 + miso_pin: GPIO15 + cs_pin: GPIO5 + +<<: !include common.yaml diff --git a/tests/components/ens160_spi/test.esp8266.yaml b/tests/components/ens160_spi/test.esp8266.yaml new file mode 100644 index 0000000000..dbd158d030 --- /dev/null +++ b/tests/components/ens160_spi/test.esp8266.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO14 + mosi_pin: GPIO13 + miso_pin: GPIO12 + cs_pin: GPIO15 + +<<: !include common.yaml diff --git a/tests/components/ens160_spi/test.rp2040.yaml b/tests/components/ens160_spi/test.rp2040.yaml new file mode 100644 index 0000000000..f6c3f1eeca --- /dev/null +++ b/tests/components/ens160_spi/test.rp2040.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO2 + mosi_pin: GPIO3 + miso_pin: GPIO4 + cs_pin: GPIO5 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_i2c/common.yaml b/tests/components/ina2xx_i2c/common.yaml new file mode 100644 index 0000000000..320b680b6b --- /dev/null +++ b/tests/components/ina2xx_i2c/common.yaml @@ -0,0 +1,20 @@ +i2c: + - id: i2c_ina2xx + scl: ${scl_pin} + sda: ${sda_pin} + +sensor: + - platform: ina2xx_i2c + i2c_id: i2c_ina2xx + address: 0x40 + model: INA228 + shunt_resistance: 0.001130 ohm + max_current: 40 A + adc_range: 1 + temperature_coefficient: 50 + shunt_voltage: "INA2xx Shunt Voltage" + bus_voltage: "INA2xx Bus Voltage" + current: "INA2xx Current" + power: "INA2xx Power" + energy: "INA2xx Energy" + charge: "INA2xx Charge" diff --git a/tests/components/ina2xx_i2c/test.esp32-c3-idf.yaml b/tests/components/ina2xx_i2c/test.esp32-c3-idf.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ina2xx_i2c/test.esp32-c3-idf.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_i2c/test.esp32-c3.yaml b/tests/components/ina2xx_i2c/test.esp32-c3.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ina2xx_i2c/test.esp32-c3.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_i2c/test.esp32-idf.yaml b/tests/components/ina2xx_i2c/test.esp32-idf.yaml new file mode 100644 index 0000000000..63c3bd6afd --- /dev/null +++ b/tests/components/ina2xx_i2c/test.esp32-idf.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO16 + sda_pin: GPIO17 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_i2c/test.esp32.yaml b/tests/components/ina2xx_i2c/test.esp32.yaml new file mode 100644 index 0000000000..63c3bd6afd --- /dev/null +++ b/tests/components/ina2xx_i2c/test.esp32.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO16 + sda_pin: GPIO17 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_i2c/test.esp8266.yaml b/tests/components/ina2xx_i2c/test.esp8266.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ina2xx_i2c/test.esp8266.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_i2c/test.rp2040.yaml b/tests/components/ina2xx_i2c/test.rp2040.yaml new file mode 100644 index 0000000000..ee2c29ca4e --- /dev/null +++ b/tests/components/ina2xx_i2c/test.rp2040.yaml @@ -0,0 +1,5 @@ +substitutions: + scl_pin: GPIO5 + sda_pin: GPIO4 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_spi/common.yaml b/tests/components/ina2xx_spi/common.yaml new file mode 100644 index 0000000000..3eab7e6f0a --- /dev/null +++ b/tests/components/ina2xx_spi/common.yaml @@ -0,0 +1,21 @@ +spi: + - id: spi_ina2xx + clk_pin: ${clk_pin} + mosi_pin: ${mosi_pin} + miso_pin: ${miso_pin} + +sensor: + - platform: ina2xx_spi + spi_id: spi_ina2xx + cs_pin: ${cs_pin} + model: INA229 + shunt_resistance: 0.001130 ohm + max_current: 40 A + adc_range: 1 + temperature_coefficient: 50 + shunt_voltage: "INA2xx Shunt Voltage" + bus_voltage: "INA2xx Bus Voltage" + current: "INA2xx Current" + power: "INA2xx Power" + energy: "INA2xx Energy" + charge: "INA2xx Charge" diff --git a/tests/components/ina2xx_spi/test.esp32-c3-idf.yaml b/tests/components/ina2xx_spi/test.esp32-c3-idf.yaml new file mode 100644 index 0000000000..2415ba5dc6 --- /dev/null +++ b/tests/components/ina2xx_spi/test.esp32-c3-idf.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO6 + mosi_pin: GPIO7 + miso_pin: GPIO5 + cs_pin: GPIO8 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_spi/test.esp32-c3.yaml b/tests/components/ina2xx_spi/test.esp32-c3.yaml new file mode 100644 index 0000000000..2415ba5dc6 --- /dev/null +++ b/tests/components/ina2xx_spi/test.esp32-c3.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO6 + mosi_pin: GPIO7 + miso_pin: GPIO5 + cs_pin: GPIO8 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_spi/test.esp32-idf.yaml b/tests/components/ina2xx_spi/test.esp32-idf.yaml new file mode 100644 index 0000000000..54e027a614 --- /dev/null +++ b/tests/components/ina2xx_spi/test.esp32-idf.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO16 + mosi_pin: GPIO17 + miso_pin: GPIO15 + cs_pin: GPIO5 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_spi/test.esp32.yaml b/tests/components/ina2xx_spi/test.esp32.yaml new file mode 100644 index 0000000000..54e027a614 --- /dev/null +++ b/tests/components/ina2xx_spi/test.esp32.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO16 + mosi_pin: GPIO17 + miso_pin: GPIO15 + cs_pin: GPIO5 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_spi/test.esp8266.yaml b/tests/components/ina2xx_spi/test.esp8266.yaml new file mode 100644 index 0000000000..dbd158d030 --- /dev/null +++ b/tests/components/ina2xx_spi/test.esp8266.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO14 + mosi_pin: GPIO13 + miso_pin: GPIO12 + cs_pin: GPIO15 + +<<: !include common.yaml diff --git a/tests/components/ina2xx_spi/test.rp2040.yaml b/tests/components/ina2xx_spi/test.rp2040.yaml new file mode 100644 index 0000000000..f6c3f1eeca --- /dev/null +++ b/tests/components/ina2xx_spi/test.rp2040.yaml @@ -0,0 +1,7 @@ +substitutions: + clk_pin: GPIO2 + mosi_pin: GPIO3 + miso_pin: GPIO4 + cs_pin: GPIO5 + +<<: !include common.yaml diff --git a/tests/components/ota/common.yaml b/tests/components/ota/common.yaml index 367454995f..4910e2d891 100644 --- a/tests/components/ota/common.yaml +++ b/tests/components/ota/common.yaml @@ -3,28 +3,29 @@ wifi: password: password1 ota: - safe_mode: true - password: "superlongpasswordthatnoonewillknow" - port: 3286 - reboot_timeout: 2min - num_attempts: 5 - on_begin: - then: - - logger.log: "OTA start" - on_progress: - then: - - logger.log: - format: "OTA progress %0.1f%%" - args: ["x"] - on_end: - then: - - logger.log: "OTA end" - on_error: - then: - - logger.log: - format: "OTA update error %d" - args: ["x"] - on_state_change: - then: - lambda: >- - ESP_LOGD("ota", "State %d", state); + - platform: esphome + safe_mode: true + password: "superlongpasswordthatnoonewillknow" + port: 3286 + reboot_timeout: 2min + num_attempts: 5 + on_begin: + then: + - logger.log: "OTA start" + on_progress: + then: + - logger.log: + format: "OTA progress %0.1f%%" + args: ["x"] + on_end: + then: + - logger.log: "OTA end" + on_error: + then: + - logger.log: + format: "OTA update error %d" + args: ["x"] + on_state_change: + then: + lambda: >- + ESP_LOGD("ota", "State %d", state); diff --git a/tests/components/remote_receiver/esp32-common.yaml b/tests/components/remote_receiver/esp32-common.yaml index 0e71143fc3..c2b5a2cf19 100644 --- a/tests/components/remote_receiver/esp32-common.yaml +++ b/tests/components/remote_receiver/esp32-common.yaml @@ -143,6 +143,10 @@ remote_receiver: - logger.log: format: "on_toshiba_ac: %llu %llu" args: ["x.rc_code_1", "x.rc_code_2"] + on_mirage: + then: + - lambda: |- + ESP_LOGD("mirage", "Mirage data: %s", format_hex(x.data).c_str()); binary_sensor: - platform: remote_receiver diff --git a/tests/components/remote_receiver/test.esp8266.yaml b/tests/components/remote_receiver/test.esp8266.yaml index e96f031e90..27d36d4a16 100644 --- a/tests/components/remote_receiver/test.esp8266.yaml +++ b/tests/components/remote_receiver/test.esp8266.yaml @@ -142,6 +142,10 @@ remote_receiver: - logger.log: format: "on_toshiba_ac: %llu %llu" args: ["x.rc_code_1", "x.rc_code_2"] + on_mirage: + then: + - lambda: |- + ESP_LOGD("mirage", "Mirage data: %s", format_hex(x.data).c_str()); binary_sensor: - platform: remote_receiver diff --git a/tests/components/remote_transmitter/common-buttons.yaml b/tests/components/remote_transmitter/common-buttons.yaml index 27683b387f..e727017e85 100644 --- a/tests/components/remote_transmitter/common-buttons.yaml +++ b/tests/components/remote_transmitter/common-buttons.yaml @@ -176,6 +176,11 @@ button: 0x00, 0x05, ] + - platform: template + name: Mirage + on_press: + remote_transmitter.transmit_mirage: + code: [0x56, 0x77, 0x00, 0x00, 0x22, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - platform: template name: Dooya on_press: diff --git a/tests/components/safe_mode/common.yaml b/tests/components/safe_mode/common.yaml index df0abd9aec..1dfc516254 100644 --- a/tests/components/safe_mode/common.yaml +++ b/tests/components/safe_mode/common.yaml @@ -3,6 +3,8 @@ wifi: password: password1 ota: + - platform: esphome + safe_mode: true button: - platform: safe_mode diff --git a/tests/dummy_main.cpp b/tests/dummy_main.cpp index da5c6d10d0..3ba4c8bd07 100644 --- a/tests/dummy_main.cpp +++ b/tests/dummy_main.cpp @@ -5,7 +5,7 @@ #include #include -#include +#include #include #include @@ -25,7 +25,7 @@ void setup() { ap.set_password("password1"); wifi->add_sta(ap); - auto *ota = new ota::OTAComponent(); // NOLINT + auto *ota = new esphome::ESPHomeOTAComponent(); // NOLINT ota->set_port(8266); App.setup(); diff --git a/tests/test1.yaml b/tests/test1.yaml index 79b836da4a..dc46b55c44 100644 --- a/tests/test1.yaml +++ b/tests/test1.yaml @@ -265,29 +265,30 @@ uart: baud_rate: 9600 ota: - safe_mode: true - password: "superlongpasswordthatnoonewillknow" - port: 3286 - reboot_timeout: 2min - num_attempts: 5 - on_state_change: - then: - lambda: >- - ESP_LOGD("ota", "State %d", state); - on_begin: - then: - logger.log: OTA begin - on_progress: - then: - lambda: >- - ESP_LOGD("ota", "Got progress %f", x); - on_end: - then: - logger.log: OTA end - on_error: - then: - lambda: >- - ESP_LOGD("ota", "Got error code %d", x); + - platform: esphome + safe_mode: true + password: "superlongpasswordthatnoonewillknow" + port: 3286 + reboot_timeout: 2min + num_attempts: 5 + on_state_change: + then: + lambda: >- + ESP_LOGD("ota", "State %d", state); + on_begin: + then: + logger.log: OTA begin + on_progress: + then: + lambda: >- + ESP_LOGD("ota", "Got progress %f", x); + on_end: + then: + logger.log: OTA end + on_error: + then: + lambda: >- + ESP_LOGD("ota", "Got error code %d", x); logger: baud_rate: 0 diff --git a/tests/test11.5.yaml b/tests/test11.5.yaml index 13de7f1929..758f295a6c 100644 --- a/tests/test11.5.yaml +++ b/tests/test11.5.yaml @@ -31,6 +31,7 @@ network: api: ota: + - platform: esphome logger: diff --git a/tests/test2.yaml b/tests/test2.yaml index 2fdef72c08..54ff4807a3 100644 --- a/tests/test2.yaml +++ b/tests/test2.yaml @@ -1,10 +1,12 @@ --- esphome: name: $devicename - platform: ESP32 - board: nodemcu-32s build_path: build/test2 +esp32: + board: esp32dev + flash_size: 8MB + globals: - id: my_global_string type: std::string @@ -78,9 +80,10 @@ uart: - lambda: UARTDebug::log_hex(direction, bytes, ':'); ota: - safe_mode: true - port: 3286 - num_attempts: 15 + - platform: esphome + safe_mode: true + port: 3286 + num_attempts: 15 logger: level: DEBUG diff --git a/tests/test3.1.yaml b/tests/test3.1.yaml index 2bddd6f4d7..a7d8dcb3f4 100644 --- a/tests/test3.1.yaml +++ b/tests/test3.1.yaml @@ -49,7 +49,8 @@ spi: number: GPIO14 ota: - version: 2 + - platform: esphome + version: 2 logger: @@ -244,13 +245,6 @@ sensor: name: "ADE7953 Reactive Power B" update_interval: 1s - - platform: ens160 - eco2: - name: "ENS160 eCO2" - tvoc: - name: "ENS160 Total Volatile Organic Compounds" - aqi: - name: "ENS160 Air Quality Index" - platform: tmp102 name: TMP102 Temperature - platform: hm3301 diff --git a/tests/test3.yaml b/tests/test3.yaml index 61d814385b..7554d4bcb2 100644 --- a/tests/test3.yaml +++ b/tests/test3.yaml @@ -328,9 +328,10 @@ vbus: uart_id: uart_4 ota: - safe_mode: true - port: 3286 - reboot_timeout: 15min + - platform: esphome + safe_mode: true + port: 3286 + reboot_timeout: 15min logger: hardware_uart: UART1 diff --git a/tests/test4.yaml b/tests/test4.yaml index 993ce126a8..86beee81c6 100644 --- a/tests/test4.yaml +++ b/tests/test4.yaml @@ -103,8 +103,9 @@ uart: parity: EVEN ota: - safe_mode: true - port: 3286 + - platform: esphome + safe_mode: true + port: 3286 logger: level: DEBUG diff --git a/tests/test5.yaml b/tests/test5.yaml index afd3359098..f7a34d5a1b 100644 --- a/tests/test5.yaml +++ b/tests/test5.yaml @@ -28,6 +28,7 @@ network: api: ota: + - platform: esphome logger: diff --git a/tests/test6.yaml b/tests/test6.yaml index 2c5aa30aad..b1103eb126 100644 --- a/tests/test6.yaml +++ b/tests/test6.yaml @@ -22,6 +22,7 @@ network: api: ota: + - platform: esphome logger: diff --git a/tests/test8.yaml b/tests/test8.yaml index 5a8ae77468..fcc93c6154 100644 --- a/tests/test8.yaml +++ b/tests/test8.yaml @@ -38,6 +38,11 @@ light: id: rgb_led name: "RGB LED" data_rate: 8MHz + - platform: binary + name: "Red Info Light" + output: board_info_ed + entity_category: diagnostic + restore_mode: ALWAYS_OFF spi: id: spi_id_1 @@ -73,6 +78,14 @@ i2c: scl: GPIO18 sda: GPIO8 +output: + - platform: gpio + id: board_info_ed + pin: + # This pin is reserved on the ESP32S3! + number: 26 + ignore_pin_validation_error: true + touchscreen: - platform: tt21100 display: displ8 diff --git a/tests/test9.1.yaml b/tests/test9.1.yaml index f7455b7668..2d205ef4e6 100644 --- a/tests/test9.1.yaml +++ b/tests/test9.1.yaml @@ -12,6 +12,7 @@ esphome: logger: ota: + - platform: esphome captive_portal: diff --git a/tests/test9.yaml b/tests/test9.yaml index d660b4f24a..5017ccc5ed 100644 --- a/tests/test9.yaml +++ b/tests/test9.yaml @@ -12,6 +12,7 @@ esphome: logger: ota: + - platform: esphome captive_portal: diff --git a/tests/test_build_components/build_components_base.bk72xx.yaml b/tests/test_build_components/build_components_base.bk72xx.yaml index 9fd9431826..9a4e15d5cf 100644 --- a/tests/test_build_components/build_components_base.bk72xx.yaml +++ b/tests/test_build_components/build_components_base.bk72xx.yaml @@ -3,7 +3,7 @@ esphome: friendly_name: $component_name bk72xx: - board: cb3s + board: generic-bk7231n-qfn32-tuya logger: level: VERY_VERBOSE