mirror of
https://github.com/esphome/esphome.git
synced 2026-01-20 09:59:11 -07:00
Compare commits
83 Commits
scheduler_
...
broken_tar
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8622bf1de0 | ||
|
|
0420c00ec3 | ||
|
|
329b38fa29 | ||
|
|
4b44c7384b | ||
|
|
a593965372 | ||
|
|
4743e5592a | ||
|
|
464607011c | ||
|
|
16fe8f9e9e | ||
|
|
436d2c44e8 | ||
|
|
b213555dd2 | ||
|
|
b6336f9e63 | ||
|
|
fb7800a22f | ||
|
|
2c0f4d8f80 | ||
|
|
e96c37965c | ||
|
|
72c74bc0b3 | ||
|
|
443f9c3f57 | ||
|
|
88a2e75989 | ||
|
|
e1afd65fae | ||
|
|
27e031c257 | ||
|
|
74f509c754 | ||
|
|
f9aa48295c | ||
|
|
861ed8dd41 | ||
|
|
750f4ea797 | ||
|
|
6945b44af5 | ||
|
|
fcae13836c | ||
|
|
3eaa9f164b | ||
|
|
4c31961ae9 | ||
|
|
7a20c85eec | ||
|
|
9f60aed9b0 | ||
|
|
801d1135ab | ||
|
|
d635892ecf | ||
|
|
7e486b1c25 | ||
|
|
eda743ee48 | ||
|
|
5144154f91 | ||
|
|
4466c4c69f | ||
|
|
c7382fc494 | ||
|
|
95efb37045 | ||
|
|
2515f1c080 | ||
|
|
53ddd1a1cd | ||
|
|
93a85d7979 | ||
|
|
159194587b | ||
|
|
ffb3e2eb0a | ||
|
|
c5cc91f6f0 | ||
|
|
e36e6fbc3f | ||
|
|
1134251c32 | ||
|
|
68a7634228 | ||
|
|
3d5d89ff00 | ||
|
|
f015130f2e | ||
|
|
acda5bcd5a | ||
|
|
4b5435fd93 | ||
|
|
05826d5ead | ||
|
|
e7a3cccb4d | ||
|
|
1f271e7c10 | ||
|
|
aeedfdcaf3 | ||
|
|
f20aaf3981 | ||
|
|
75c41b11d1 | ||
|
|
3c7d6b7fc6 | ||
|
|
7eae0a4972 | ||
|
|
6220427524 | ||
|
|
6716194e47 | ||
|
|
a517e0ec80 | ||
|
|
10b54df771 | ||
|
|
bbb71b5359 | ||
|
|
1fa7adbe8d | ||
|
|
7421f31160 | ||
|
|
78bef42473 | ||
|
|
7f7c913a85 | ||
|
|
1a308583b3 | ||
|
|
27fcff2092 | ||
|
|
f4d1c9df71 | ||
|
|
7fd79fdded | ||
|
|
19fa768730 | ||
|
|
ca1d17562a | ||
|
|
42811edeb4 | ||
|
|
22481d9c0e | ||
|
|
8f20abebf6 | ||
|
|
7077488dc7 | ||
|
|
ef34239064 | ||
|
|
44148c0c6b | ||
|
|
1b53fcf634 | ||
|
|
b18e3d943a | ||
|
|
f0673f6304 | ||
|
|
320ba30d50 |
@@ -276,12 +276,12 @@ This document provides essential context for AI models interacting with this pro
|
||||
## 7. Specific Instructions for AI Collaboration
|
||||
|
||||
* **Contribution Workflow (Pull Request Process):**
|
||||
1. **Fork & Branch:** Create a new branch in your fork.
|
||||
1. **Fork & Branch:** Create a new branch based on the `dev` branch (always use `git checkout -b <branch-name> dev` to ensure you're branching from `dev`, not the currently checked out branch).
|
||||
2. **Make Changes:** Adhere to all coding conventions and patterns.
|
||||
3. **Test:** Create component tests for all supported platforms and run the full test suite locally.
|
||||
4. **Lint:** Run `pre-commit` to ensure code is compliant.
|
||||
5. **Commit:** Commit your changes. There is no strict format for commit messages.
|
||||
6. **Pull Request:** Submit a PR against the `dev` branch. The Pull Request title should have a prefix of the component being worked on (e.g., `[display] Fix bug`, `[abc123] Add new component`). Update documentation, examples, and add `CODEOWNERS` entries as needed. Pull requests should always be made with the PULL_REQUEST_TEMPLATE.md template filled out correctly.
|
||||
6. **Pull Request:** Submit a PR against the `dev` branch. The Pull Request title should have a prefix of the component being worked on (e.g., `[display] Fix bug`, `[abc123] Add new component`). Update documentation, examples, and add `CODEOWNERS` entries as needed. Pull requests should always be made using the `.github/PULL_REQUEST_TEMPLATE.md` template - fill out all sections completely without removing any parts of the template.
|
||||
|
||||
* **Documentation Contributions:**
|
||||
* Documentation is hosted in the separate `esphome/esphome-docs` repository.
|
||||
|
||||
@@ -1 +1 @@
|
||||
29270eecb86ffa07b2b1d2a4ca56dd7f84762ddc89c6248dbf3f012eca8780b6
|
||||
766420905c06eeb6c5f360f68fd965e5ddd9c4a5db6b823263d3ad3accb64a07
|
||||
|
||||
16
.github/workflows/ci.yml
vendored
16
.github/workflows/ci.yml
vendored
@@ -959,13 +959,13 @@ jobs:
|
||||
- memory-impact-comment
|
||||
if: always()
|
||||
steps:
|
||||
- name: Success
|
||||
if: ${{ !(contains(needs.*.result, 'failure')) }}
|
||||
run: exit 0
|
||||
- name: Failure
|
||||
if: ${{ contains(needs.*.result, 'failure') }}
|
||||
- name: Check job results
|
||||
env:
|
||||
JSON_DOC: ${{ toJSON(needs) }}
|
||||
NEEDS_JSON: ${{ toJSON(needs) }}
|
||||
run: |
|
||||
echo $JSON_DOC | jq
|
||||
exit 1
|
||||
# memory-impact-target-branch is allowed to fail without blocking CI.
|
||||
# This job builds the target branch (dev/beta/release) which may fail because:
|
||||
# 1. The target branch has a build issue independent of this PR
|
||||
# 2. This PR fixes a build issue on the target branch
|
||||
# In either case, we only care that the PR branch builds successfully.
|
||||
echo "$NEEDS_JSON" | jq -e 'del(.["memory-impact-target-branch"]) | all(.result != "failure")'
|
||||
|
||||
4
.github/workflows/codeql.yml
vendored
4
.github/workflows/codeql.yml
vendored
@@ -58,7 +58,7 @@ jobs:
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@fe4161a26a8629af62121b670040955b330f9af2 # v4.31.6
|
||||
uses: github/codeql-action/init@cf1bb45a277cb3c205638b2cd5c984db1c46a412 # v4.31.7
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
@@ -86,6 +86,6 @@ jobs:
|
||||
exit 1
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@fe4161a26a8629af62121b670040955b330f9af2 # v4.31.6
|
||||
uses: github/codeql-action/analyze@cf1bb45a277cb3c205638b2cd5c984db1c46a412 # v4.31.7
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
|
||||
2
.github/workflows/sync-device-classes.yml
vendored
2
.github/workflows/sync-device-classes.yml
vendored
@@ -41,7 +41,7 @@ jobs:
|
||||
python script/run-in-env.py pre-commit run --all-files
|
||||
|
||||
- name: Commit changes
|
||||
uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 # v7.0.9
|
||||
uses: peter-evans/create-pull-request@22a9089034f40e5a961c8808d113e2c98fb63676 # v7.0.11
|
||||
with:
|
||||
commit-message: "Synchronise Device Classes from Home Assistant"
|
||||
committer: esphomebot <esphome@openhomefoundation.org>
|
||||
|
||||
@@ -212,6 +212,7 @@ esphome/components/he60r/* @clydebarrow
|
||||
esphome/components/heatpumpir/* @rob-deutsch
|
||||
esphome/components/hitachi_ac424/* @sourabhjaiswal
|
||||
esphome/components/hlk_fm22x/* @OnFreund
|
||||
esphome/components/hlw8032/* @rici4kubicek
|
||||
esphome/components/hm3301/* @freekode
|
||||
esphome/components/hmac_md5/* @dwmw2
|
||||
esphome/components/homeassistant/* @esphome/core @OttoWinter
|
||||
@@ -227,6 +228,7 @@ esphome/components/hte501/* @Stock-M
|
||||
esphome/components/http_request/ota/* @oarcher
|
||||
esphome/components/http_request/update/* @jesserockz
|
||||
esphome/components/htu31d/* @betterengineering
|
||||
esphome/components/hub75/* @stuartparmenter
|
||||
esphome/components/hydreon_rgxx/* @functionpointer
|
||||
esphome/components/hyt271/* @Philippe12
|
||||
esphome/components/i2c/* @esphome/core
|
||||
@@ -306,7 +308,7 @@ esphome/components/md5/* @esphome/core
|
||||
esphome/components/mdns/* @esphome/core
|
||||
esphome/components/media_player/* @jesserockz
|
||||
esphome/components/micro_wake_word/* @jesserockz @kahrendt
|
||||
esphome/components/micronova/* @jorre05
|
||||
esphome/components/micronova/* @edenhaus @jorre05
|
||||
esphome/components/microphone/* @jesserockz @kahrendt
|
||||
esphome/components/mics_4514/* @jesserockz
|
||||
esphome/components/midea/* @dudanov
|
||||
@@ -522,6 +524,7 @@ esphome/components/ufire_ise/* @pvizeli
|
||||
esphome/components/ultrasonic/* @OttoWinter
|
||||
esphome/components/update/* @jesserockz
|
||||
esphome/components/uponor_smatrix/* @kroimon
|
||||
esphome/components/usb_cdc_acm/* @kbx81
|
||||
esphome/components/usb_host/* @clydebarrow
|
||||
esphome/components/usb_uart/* @clydebarrow
|
||||
esphome/components/valve/* @esphome/core
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
We welcome contributions to the ESPHome suite of code and documentation!
|
||||
|
||||
Please read our [contributing guide](https://esphome.io/guides/contributing.html) if you wish to contribute to the
|
||||
Please read our [contributing guide](https://developers.esphome.io/contributing/code/) if you wish to contribute to the
|
||||
project and be sure to join us on [Discord](https://discord.gg/KhAMKrd).
|
||||
|
||||
**See also:**
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
<a href="https://esphome.io/">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://esphome.io/_static/logo-text-on-dark.svg", alt="ESPHome Logo">
|
||||
<img src="https://esphome.io/_static/logo-text-on-light.svg" alt="ESPHome Logo">
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://media.esphome.io/logo/logo-text-on-dark.svg">
|
||||
<img src="https://media.esphome.io/logo/logo-text-on-light.svg" alt="ESPHome Logo">
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
|
||||
@@ -163,7 +163,7 @@ float AbsoluteHumidityComponent::es_wobus(float t) {
|
||||
}
|
||||
|
||||
// From https://www.environmentalbiophysics.org/chalk-talk-how-to-calculate-absolute-humidity/
|
||||
// H/T to https://esphome.io/cookbook/bme280_environment.html
|
||||
// H/T to https://esphome.io/cookbook/bme280_environment/
|
||||
// H/T to https://carnotcycle.wordpress.com/2012/08/04/how-to-convert-relative-humidity-to-absolute-humidity/
|
||||
float AbsoluteHumidityComponent::vapor_density(float es, float hr, float ta) {
|
||||
// es = saturated vapor pressure (kPa)
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.esp32 import VARIANT_ESP32P4, get_esp32_variant
|
||||
from esphome.components.esp32.const import (
|
||||
from esphome.components.esp32 import (
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C2,
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
get_esp32_variant,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ANALOG, CONF_INPUT, CONF_NUMBER, PLATFORM_ESP8266
|
||||
@@ -99,6 +101,13 @@ ESP32_VARIANT_ADC1_PIN_TO_CHANNEL = {
|
||||
5: adc_channel_t.ADC_CHANNEL_5,
|
||||
6: adc_channel_t.ADC_CHANNEL_6,
|
||||
},
|
||||
# https://docs.espressif.com/projects/esp-idf/en/latest/esp32c61/api-reference/peripherals/gpio.html
|
||||
VARIANT_ESP32C61: {
|
||||
1: adc_channel_t.ADC_CHANNEL_0,
|
||||
3: adc_channel_t.ADC_CHANNEL_1,
|
||||
4: adc_channel_t.ADC_CHANNEL_2,
|
||||
5: adc_channel_t.ADC_CHANNEL_3,
|
||||
},
|
||||
# https://github.com/espressif/esp-idf/blob/master/components/soc/esp32h2/include/soc/adc_channel.h
|
||||
VARIANT_ESP32H2: {
|
||||
1: adc_channel_t.ADC_CHANNEL_0,
|
||||
@@ -174,6 +183,8 @@ ESP32_VARIANT_ADC2_PIN_TO_CHANNEL = {
|
||||
VARIANT_ESP32C5: {}, # no ADC2
|
||||
# https://github.com/espressif/esp-idf/blob/master/components/soc/esp32c6/include/soc/adc_channel.h
|
||||
VARIANT_ESP32C6: {}, # no ADC2
|
||||
# ESP32-C61 has no ADC2
|
||||
VARIANT_ESP32C61: {}, # no ADC2
|
||||
# https://github.com/espressif/esp-idf/blob/master/components/soc/esp32h2/include/soc/adc_channel.h
|
||||
VARIANT_ESP32H2: {}, # no ADC2
|
||||
# https://github.com/espressif/esp-idf/blob/master/components/soc/esp32p4/include/soc/adc_channel.h
|
||||
|
||||
@@ -42,10 +42,11 @@ void ADCSensor::setup() {
|
||||
adc_oneshot_unit_init_cfg_t init_config = {}; // Zero initialize
|
||||
init_config.unit_id = this->adc_unit_;
|
||||
init_config.ulp_mode = ADC_ULP_MODE_DISABLE;
|
||||
#if USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || USE_ESP32_VARIANT_ESP32C6 || USE_ESP32_VARIANT_ESP32H2
|
||||
#if USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || USE_ESP32_VARIANT_ESP32C6 || \
|
||||
USE_ESP32_VARIANT_ESP32C61 || USE_ESP32_VARIANT_ESP32H2
|
||||
init_config.clk_src = ADC_DIGI_CLK_SRC_DEFAULT;
|
||||
#endif // USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || USE_ESP32_VARIANT_ESP32C6 ||
|
||||
// USE_ESP32_VARIANT_ESP32H2
|
||||
// USE_ESP32_VARIANT_ESP32C61 || USE_ESP32_VARIANT_ESP32H2
|
||||
esp_err_t err = adc_oneshot_new_unit(&init_config, &ADCSensor::shared_adc_handles[this->adc_unit_]);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Error initializing %s: %d", LOG_STR_ARG(adc_unit_to_str(this->adc_unit_)), err);
|
||||
@@ -74,7 +75,7 @@ void ADCSensor::setup() {
|
||||
adc_cali_handle_t handle = nullptr;
|
||||
|
||||
#if USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || USE_ESP32_VARIANT_ESP32C6 || \
|
||||
USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
USE_ESP32_VARIANT_ESP32C61 || USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
// RISC-V variants and S3 use curve fitting calibration
|
||||
adc_cali_curve_fitting_config_t cali_config = {}; // Zero initialize first
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
|
||||
@@ -111,7 +112,7 @@ void ADCSensor::setup() {
|
||||
ESP_LOGW(TAG, "Line fitting calibration failed with error %d, will use uncalibrated readings", err);
|
||||
this->setup_flags_.calibration_complete = false;
|
||||
}
|
||||
#endif // USE_ESP32_VARIANT_ESP32C3 || ESP32C5 || ESP32C6 || ESP32H2 || ESP32P4 || ESP32S3
|
||||
#endif // USE_ESP32_VARIANT_ESP32C3 || ESP32C5 || ESP32C6 || ESP32C61 || ESP32H2 || ESP32P4 || ESP32S3
|
||||
}
|
||||
|
||||
this->setup_flags_.init_complete = true;
|
||||
@@ -186,11 +187,11 @@ float ADCSensor::sample_fixed_attenuation_() {
|
||||
ESP_LOGW(TAG, "ADC calibration conversion failed with error %d, disabling calibration", err);
|
||||
if (this->calibration_handle_ != nullptr) {
|
||||
#if USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || USE_ESP32_VARIANT_ESP32C6 || \
|
||||
USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
USE_ESP32_VARIANT_ESP32C61 || USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
adc_cali_delete_scheme_curve_fitting(this->calibration_handle_);
|
||||
#else // Other ESP32 variants use line fitting calibration
|
||||
adc_cali_delete_scheme_line_fitting(this->calibration_handle_);
|
||||
#endif // USE_ESP32_VARIANT_ESP32C3 || ESP32C5 || ESP32C6 || ESP32H2 || ESP32P4 || ESP32S3
|
||||
#endif // USE_ESP32_VARIANT_ESP32C3 || ESP32C5 || ESP32C6 || ESP32C61 || ESP32H2 || ESP32P4 || ESP32S3
|
||||
this->calibration_handle_ = nullptr;
|
||||
}
|
||||
}
|
||||
@@ -219,7 +220,7 @@ float ADCSensor::sample_autorange_() {
|
||||
if (this->calibration_handle_ != nullptr) {
|
||||
// Delete old calibration handle
|
||||
#if USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || USE_ESP32_VARIANT_ESP32C6 || \
|
||||
USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
USE_ESP32_VARIANT_ESP32C61 || USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
adc_cali_delete_scheme_curve_fitting(this->calibration_handle_);
|
||||
#else
|
||||
adc_cali_delete_scheme_line_fitting(this->calibration_handle_);
|
||||
@@ -231,7 +232,7 @@ float ADCSensor::sample_autorange_() {
|
||||
adc_cali_handle_t handle = nullptr;
|
||||
|
||||
#if USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || USE_ESP32_VARIANT_ESP32C6 || \
|
||||
USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
USE_ESP32_VARIANT_ESP32C61 || USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
adc_cali_curve_fitting_config_t cali_config = {};
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
|
||||
cali_config.chan = this->channel_;
|
||||
@@ -266,7 +267,7 @@ float ADCSensor::sample_autorange_() {
|
||||
ESP_LOGW(TAG, "ADC read failed in autorange with error %d", err);
|
||||
if (handle != nullptr) {
|
||||
#if USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || USE_ESP32_VARIANT_ESP32C6 || \
|
||||
USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
USE_ESP32_VARIANT_ESP32C61 || USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
adc_cali_delete_scheme_curve_fitting(handle);
|
||||
#else
|
||||
adc_cali_delete_scheme_line_fitting(handle);
|
||||
@@ -288,7 +289,7 @@ float ADCSensor::sample_autorange_() {
|
||||
}
|
||||
// Clean up calibration handle
|
||||
#if USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || USE_ESP32_VARIANT_ESP32C6 || \
|
||||
USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
USE_ESP32_VARIANT_ESP32C61 || USE_ESP32_VARIANT_ESP32H2 || USE_ESP32_VARIANT_ESP32P4 || USE_ESP32_VARIANT_ESP32S3
|
||||
adc_cali_delete_scheme_curve_fitting(handle);
|
||||
#else
|
||||
adc_cali_delete_scheme_line_fitting(handle);
|
||||
|
||||
@@ -27,12 +27,13 @@ from esphome.const import (
|
||||
CONF_SERVICE,
|
||||
CONF_SERVICES,
|
||||
CONF_TAG,
|
||||
CONF_THEN,
|
||||
CONF_TRIGGER_ID,
|
||||
CONF_VARIABLES,
|
||||
)
|
||||
from esphome.core import CORE, ID, CoroPriority, coroutine_with_priority
|
||||
from esphome.cpp_generator import TemplateArgsType
|
||||
from esphome.types import ConfigType
|
||||
from esphome.core import CORE, ID, CoroPriority, EsphomeError, coroutine_with_priority
|
||||
from esphome.cpp_generator import MockObj, TemplateArgsType
|
||||
from esphome.types import ConfigFragmentType, ConfigType
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -63,17 +64,21 @@ HomeAssistantActionResponseTrigger = api_ns.class_(
|
||||
"HomeAssistantActionResponseTrigger", automation.Trigger
|
||||
)
|
||||
APIConnectedCondition = api_ns.class_("APIConnectedCondition", Condition)
|
||||
APIRespondAction = api_ns.class_("APIRespondAction", automation.Action)
|
||||
APIUnregisterServiceCallAction = api_ns.class_(
|
||||
"APIUnregisterServiceCallAction", automation.Action
|
||||
)
|
||||
|
||||
UserServiceTrigger = api_ns.class_("UserServiceTrigger", automation.Trigger)
|
||||
ListEntitiesServicesArgument = api_ns.class_("ListEntitiesServicesArgument")
|
||||
SERVICE_ARG_NATIVE_TYPES = {
|
||||
"bool": bool,
|
||||
SERVICE_ARG_NATIVE_TYPES: dict[str, MockObj] = {
|
||||
"bool": cg.bool_,
|
||||
"int": cg.int32,
|
||||
"float": float,
|
||||
"float": cg.float_,
|
||||
"string": cg.std_string,
|
||||
"bool[]": cg.FixedVector.template(bool).operator("const").operator("ref"),
|
||||
"bool[]": cg.FixedVector.template(cg.bool_).operator("const").operator("ref"),
|
||||
"int[]": cg.FixedVector.template(cg.int32).operator("const").operator("ref"),
|
||||
"float[]": cg.FixedVector.template(float).operator("const").operator("ref"),
|
||||
"float[]": cg.FixedVector.template(cg.float_).operator("const").operator("ref"),
|
||||
"string[]": cg.FixedVector.template(cg.std_string)
|
||||
.operator("const")
|
||||
.operator("ref"),
|
||||
@@ -102,6 +107,85 @@ def validate_encryption_key(value):
|
||||
return value
|
||||
|
||||
|
||||
CONF_SUPPORTS_RESPONSE = "supports_response"
|
||||
|
||||
# Enum values in api::enums namespace
|
||||
enums_ns = api_ns.namespace("enums")
|
||||
SUPPORTS_RESPONSE_OPTIONS = {
|
||||
"none": enums_ns.SUPPORTS_RESPONSE_NONE,
|
||||
"optional": enums_ns.SUPPORTS_RESPONSE_OPTIONAL,
|
||||
"only": enums_ns.SUPPORTS_RESPONSE_ONLY,
|
||||
"status": enums_ns.SUPPORTS_RESPONSE_STATUS,
|
||||
}
|
||||
|
||||
|
||||
def _auto_detect_supports_response(config: ConfigType) -> ConfigType:
|
||||
"""Auto-detect supports_response based on api.respond usage in the action's then block.
|
||||
|
||||
- If api.respond with data found: set to "optional" (unless user explicitly set)
|
||||
- If api.respond without data found: set to "status" (unless user explicitly set)
|
||||
- If no api.respond found: set to "none" (unless user explicitly set)
|
||||
"""
|
||||
|
||||
def scan_actions(items: ConfigFragmentType) -> tuple[bool, bool]:
|
||||
"""Recursively scan actions for api.respond.
|
||||
|
||||
Returns: (found, has_data) tuple - has_data is True if ANY api.respond has data
|
||||
"""
|
||||
found_any = False
|
||||
has_data_any = False
|
||||
|
||||
if isinstance(items, list):
|
||||
for item in items:
|
||||
found, has_data = scan_actions(item)
|
||||
if found:
|
||||
found_any = True
|
||||
has_data_any = has_data_any or has_data
|
||||
elif isinstance(items, dict):
|
||||
# Check if this is an api.respond action
|
||||
if "api.respond" in items:
|
||||
respond_config = items["api.respond"]
|
||||
has_data = isinstance(respond_config, dict) and "data" in respond_config
|
||||
return True, has_data
|
||||
# Recursively check all values
|
||||
for value in items.values():
|
||||
found, has_data = scan_actions(value)
|
||||
if found:
|
||||
found_any = True
|
||||
has_data_any = has_data_any or has_data
|
||||
|
||||
return found_any, has_data_any
|
||||
|
||||
then = config.get(CONF_THEN, [])
|
||||
action_name = config.get(CONF_ACTION)
|
||||
found, has_data = scan_actions(then)
|
||||
|
||||
# If user explicitly set supports_response, validate and use that
|
||||
if CONF_SUPPORTS_RESPONSE in config:
|
||||
user_value = config[CONF_SUPPORTS_RESPONSE]
|
||||
# Validate: "only" requires api.respond with data
|
||||
if user_value == "only" and not has_data:
|
||||
raise cv.Invalid(
|
||||
f"Action '{action_name}' has supports_response=only but no api.respond "
|
||||
"action with 'data:' was found. Use 'status' for responses without data, "
|
||||
"or add 'data:' to your api.respond action."
|
||||
)
|
||||
return config
|
||||
|
||||
# Auto-detect based on api.respond usage
|
||||
if found:
|
||||
config[CONF_SUPPORTS_RESPONSE] = "optional" if has_data else "status"
|
||||
else:
|
||||
config[CONF_SUPPORTS_RESPONSE] = "none"
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def _validate_supports_response(value):
|
||||
"""Validate supports_response after auto-detection has set the value."""
|
||||
return cv.enum(SUPPORTS_RESPONSE_OPTIONS, lower=True)(value)
|
||||
|
||||
|
||||
ACTIONS_SCHEMA = automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(UserServiceTrigger),
|
||||
@@ -112,10 +196,20 @@ ACTIONS_SCHEMA = automation.validate_automation(
|
||||
cv.validate_id_name: cv.one_of(*SERVICE_ARG_NATIVE_TYPES, lower=True),
|
||||
}
|
||||
),
|
||||
# No default - auto-detected by _auto_detect_supports_response
|
||||
cv.Optional(CONF_SUPPORTS_RESPONSE): cv.enum(
|
||||
SUPPORTS_RESPONSE_OPTIONS, lower=True
|
||||
),
|
||||
},
|
||||
cv.All(
|
||||
cv.has_exactly_one_key(CONF_SERVICE, CONF_ACTION),
|
||||
cv.rename_key(CONF_SERVICE, CONF_ACTION),
|
||||
_auto_detect_supports_response,
|
||||
# Re-validate supports_response after auto-detection sets it
|
||||
cv.Schema(
|
||||
{cv.Required(CONF_SUPPORTS_RESPONSE): _validate_supports_response},
|
||||
extra=cv.ALLOW_EXTRA,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -152,7 +246,7 @@ def _validate_api_config(config: ConfigType) -> ConfigType:
|
||||
_LOGGER.warning(
|
||||
"API 'password' authentication has been deprecated since May 2022 and will be removed in version 2026.1.0. "
|
||||
"Please migrate to the 'encryption' configuration. "
|
||||
"See https://esphome.io/components/api.html#configuration-variables"
|
||||
"See https://esphome.io/components/api/#configuration-variables"
|
||||
)
|
||||
|
||||
return config
|
||||
@@ -242,7 +336,7 @@ CONFIG_SCHEMA = cv.All(
|
||||
|
||||
|
||||
@coroutine_with_priority(CoroPriority.WEB)
|
||||
async def to_code(config):
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
|
||||
@@ -279,20 +373,61 @@ async def to_code(config):
|
||||
# Collect all triggers first, then register all at once with initializer_list
|
||||
triggers: list[cg.Pvariable] = []
|
||||
for conf in actions:
|
||||
template_args = []
|
||||
func_args = []
|
||||
service_arg_names = []
|
||||
func_args: list[tuple[MockObj, str]] = []
|
||||
service_template_args: list[MockObj] = [] # User service argument types
|
||||
|
||||
# Determine supports_response mode
|
||||
# cv.enum returns the key with enum_value attribute containing the MockObj
|
||||
supports_response_key = conf[CONF_SUPPORTS_RESPONSE]
|
||||
supports_response = supports_response_key.enum_value
|
||||
is_none = supports_response_key == "none"
|
||||
is_optional = supports_response_key == "optional"
|
||||
|
||||
# Add call_id and return_response based on supports_response mode
|
||||
# These must match the C++ Trigger template arguments
|
||||
# - none: no extra args
|
||||
# - status: call_id only (for reporting success/error without data)
|
||||
# - only: call_id only (response always expected with data)
|
||||
# - optional: call_id + return_response (client decides)
|
||||
if not is_none:
|
||||
# call_id is present for "optional", "only", and "status"
|
||||
func_args.append((cg.uint32, "call_id"))
|
||||
# return_response only present for "optional"
|
||||
if is_optional:
|
||||
func_args.append((cg.bool_, "return_response"))
|
||||
|
||||
service_arg_names: list[str] = []
|
||||
for name, var_ in conf[CONF_VARIABLES].items():
|
||||
native = SERVICE_ARG_NATIVE_TYPES[var_]
|
||||
template_args.append(native)
|
||||
service_template_args.append(native)
|
||||
func_args.append((native, name))
|
||||
service_arg_names.append(name)
|
||||
templ = cg.TemplateArguments(*template_args)
|
||||
# Template args: supports_response mode, then user service arg types
|
||||
templ = cg.TemplateArguments(supports_response, *service_template_args)
|
||||
trigger = cg.new_Pvariable(
|
||||
conf[CONF_TRIGGER_ID], templ, conf[CONF_ACTION], service_arg_names
|
||||
conf[CONF_TRIGGER_ID],
|
||||
templ,
|
||||
conf[CONF_ACTION],
|
||||
service_arg_names,
|
||||
)
|
||||
triggers.append(trigger)
|
||||
await automation.build_automation(trigger, func_args, conf)
|
||||
auto = await automation.build_automation(trigger, func_args, conf)
|
||||
|
||||
# For non-none response modes, automatically append unregister action
|
||||
# This ensures the call is unregistered after all actions complete (including async ones)
|
||||
if not is_none:
|
||||
arg_types = [arg[0] for arg in func_args]
|
||||
action_templ = cg.TemplateArguments(*arg_types)
|
||||
unregister_id = ID(
|
||||
f"{conf[CONF_TRIGGER_ID]}__unregister",
|
||||
is_declaration=True,
|
||||
type=APIUnregisterServiceCallAction.template(action_templ),
|
||||
)
|
||||
unregister_action = cg.new_Pvariable(
|
||||
unregister_id,
|
||||
var,
|
||||
)
|
||||
cg.add(auto.add_actions([unregister_action]))
|
||||
# Register all services at once - single allocation, no reallocations
|
||||
cg.add(var.initialize_user_services(triggers))
|
||||
|
||||
@@ -538,6 +673,80 @@ async def homeassistant_tag_scanned_to_code(config, action_id, template_arg, arg
|
||||
return var
|
||||
|
||||
|
||||
CONF_SUCCESS = "success"
|
||||
CONF_ERROR_MESSAGE = "error_message"
|
||||
|
||||
|
||||
def _validate_api_respond_data(config):
|
||||
"""Set flag during validation so AUTO_LOAD can include json component."""
|
||||
if CONF_DATA in config:
|
||||
CORE.data.setdefault(DOMAIN, {})[CONF_CAPTURE_RESPONSE] = True
|
||||
return config
|
||||
|
||||
|
||||
API_RESPOND_ACTION_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.use_id(APIServer),
|
||||
cv.Optional(CONF_SUCCESS, default=True): cv.templatable(cv.boolean),
|
||||
cv.Optional(CONF_ERROR_MESSAGE, default=""): cv.templatable(cv.string),
|
||||
cv.Optional(CONF_DATA): cv.lambda_,
|
||||
}
|
||||
),
|
||||
_validate_api_respond_data,
|
||||
)
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
"api.respond",
|
||||
APIRespondAction,
|
||||
API_RESPOND_ACTION_SCHEMA,
|
||||
)
|
||||
async def api_respond_to_code(
|
||||
config: ConfigType,
|
||||
action_id: ID,
|
||||
template_arg: cg.TemplateArguments,
|
||||
args: TemplateArgsType,
|
||||
) -> MockObj:
|
||||
# Validate that api.respond is used inside an API action context.
|
||||
# We can't easily validate this at config time since the schema validation
|
||||
# doesn't have access to the parent action context. Validating here in to_code
|
||||
# is still much better than a cryptic C++ compile error.
|
||||
has_call_id = any(name == "call_id" for _, name in args)
|
||||
if not has_call_id:
|
||||
raise EsphomeError(
|
||||
"api.respond can only be used inside an API action's 'then:' block. "
|
||||
"The 'call_id' variable is required to send a response."
|
||||
)
|
||||
|
||||
cg.add_define("USE_API_USER_DEFINED_ACTION_RESPONSES")
|
||||
serv = await cg.get_variable(config[CONF_ID])
|
||||
var = cg.new_Pvariable(action_id, template_arg, serv)
|
||||
|
||||
# Check if we're in optional mode (has return_response arg)
|
||||
is_optional = any(name == "return_response" for _, name in args)
|
||||
if is_optional:
|
||||
cg.add(var.set_is_optional_mode(True))
|
||||
|
||||
templ = await cg.templatable(config[CONF_SUCCESS], args, cg.bool_)
|
||||
cg.add(var.set_success(templ))
|
||||
|
||||
templ = await cg.templatable(config[CONF_ERROR_MESSAGE], args, cg.std_string)
|
||||
cg.add(var.set_error_message(templ))
|
||||
|
||||
if CONF_DATA in config:
|
||||
cg.add_define("USE_API_USER_DEFINED_ACTION_RESPONSES_JSON")
|
||||
# Lambda populates the JsonObject root - no return value needed
|
||||
lambda_ = await cg.process_lambda(
|
||||
config[CONF_DATA],
|
||||
args + [(cg.JsonObject, "root")],
|
||||
return_type=cg.void,
|
||||
)
|
||||
cg.add(var.set_data(lambda_))
|
||||
|
||||
return var
|
||||
|
||||
|
||||
API_CONNECTED_CONDITION_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.use_id(APIServer),
|
||||
|
||||
@@ -855,6 +855,14 @@ enum ServiceArgType {
|
||||
SERVICE_ARG_TYPE_FLOAT_ARRAY = 6;
|
||||
SERVICE_ARG_TYPE_STRING_ARRAY = 7;
|
||||
}
|
||||
enum SupportsResponseType {
|
||||
SUPPORTS_RESPONSE_NONE = 0;
|
||||
SUPPORTS_RESPONSE_OPTIONAL = 1;
|
||||
SUPPORTS_RESPONSE_ONLY = 2;
|
||||
// Status-only response - reports success/error without data payload
|
||||
// Value is higher to avoid conflicts with future Home Assistant values
|
||||
SUPPORTS_RESPONSE_STATUS = 100;
|
||||
}
|
||||
message ListEntitiesServicesArgument {
|
||||
option (ifdef) = "USE_API_USER_DEFINED_ACTIONS";
|
||||
string name = 1;
|
||||
@@ -868,6 +876,7 @@ message ListEntitiesServicesResponse {
|
||||
string name = 1;
|
||||
fixed32 key = 2;
|
||||
repeated ListEntitiesServicesArgument args = 3 [(fixed_vector) = true];
|
||||
SupportsResponseType supports_response = 4;
|
||||
}
|
||||
message ExecuteServiceArgument {
|
||||
option (ifdef) = "USE_API_USER_DEFINED_ACTIONS";
|
||||
@@ -890,6 +899,21 @@ message ExecuteServiceRequest {
|
||||
|
||||
fixed32 key = 1;
|
||||
repeated ExecuteServiceArgument args = 2 [(fixed_vector) = true];
|
||||
uint32 call_id = 3 [(field_ifdef) = "USE_API_USER_DEFINED_ACTION_RESPONSES"];
|
||||
bool return_response = 4 [(field_ifdef) = "USE_API_USER_DEFINED_ACTION_RESPONSES"];
|
||||
}
|
||||
|
||||
// Message sent by ESPHome to Home Assistant with service execution response data
|
||||
message ExecuteServiceResponse {
|
||||
option (id) = 131;
|
||||
option (source) = SOURCE_SERVER;
|
||||
option (no_delay) = true;
|
||||
option (ifdef) = "USE_API_USER_DEFINED_ACTION_RESPONSES";
|
||||
|
||||
uint32 call_id = 1; // Matches the call_id from ExecuteServiceRequest
|
||||
bool success = 2; // Whether the service execution succeeded
|
||||
string error_message = 3; // Error message if success = false
|
||||
bytes response_data = 4 [(pointer_to_buffer) = true, (field_ifdef) = "USE_API_USER_DEFINED_ACTION_RESPONSES_JSON"];
|
||||
}
|
||||
|
||||
// ==================== CAMERA ====================
|
||||
@@ -1171,7 +1195,7 @@ message SelectCommandRequest {
|
||||
option (base_class) = "CommandProtoMessage";
|
||||
|
||||
fixed32 key = 1;
|
||||
string state = 2;
|
||||
string state = 2 [(pointer_to_buffer) = true];
|
||||
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
|
||||
}
|
||||
|
||||
|
||||
@@ -6,11 +6,17 @@
|
||||
#ifdef USE_API_PLAINTEXT
|
||||
#include "api_frame_helper_plaintext.h"
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTIONS
|
||||
#include "user_services.h"
|
||||
#endif
|
||||
#include <cerrno>
|
||||
#include <cinttypes>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <utility>
|
||||
#ifdef USE_ESP8266
|
||||
#include <pgmspace.h>
|
||||
#endif
|
||||
#include "esphome/components/network/util.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/entity_base.h"
|
||||
@@ -899,7 +905,7 @@ uint16_t APIConnection::try_send_select_info(EntityBase *entity, APIConnection *
|
||||
}
|
||||
void APIConnection::select_command(const SelectCommandRequest &msg) {
|
||||
ENTITY_COMMAND_MAKE_CALL(select::Select, select, select)
|
||||
call.set_option(msg.state);
|
||||
call.set_option(reinterpret_cast<const char *>(msg.state), msg.state_len);
|
||||
call.perform();
|
||||
}
|
||||
#endif
|
||||
@@ -1468,35 +1474,64 @@ bool APIConnection::send_device_info_response(const DeviceInfoRequest &msg) {
|
||||
|
||||
resp.set_compilation_time(App.get_compilation_time_ref());
|
||||
|
||||
// Compile-time StringRef constants for manufacturers
|
||||
// Manufacturer string - define once, handle ESP8266 PROGMEM separately
|
||||
#if defined(USE_ESP8266) || defined(USE_ESP32)
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Espressif");
|
||||
#define ESPHOME_MANUFACTURER "Espressif"
|
||||
#elif defined(USE_RP2040)
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Raspberry Pi");
|
||||
#define ESPHOME_MANUFACTURER "Raspberry Pi"
|
||||
#elif defined(USE_BK72XX)
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Beken");
|
||||
#define ESPHOME_MANUFACTURER "Beken"
|
||||
#elif defined(USE_LN882X)
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Lightning");
|
||||
#define ESPHOME_MANUFACTURER "Lightning"
|
||||
#elif defined(USE_NRF52)
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Nordic Semiconductor");
|
||||
#define ESPHOME_MANUFACTURER "Nordic Semiconductor"
|
||||
#elif defined(USE_RTL87XX)
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Realtek");
|
||||
#define ESPHOME_MANUFACTURER "Realtek"
|
||||
#elif defined(USE_HOST)
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit("Host");
|
||||
#define ESPHOME_MANUFACTURER "Host"
|
||||
#endif
|
||||
resp.set_manufacturer(MANUFACTURER);
|
||||
|
||||
#ifdef USE_ESP8266
|
||||
// ESP8266 requires PROGMEM for flash storage, copy to stack for memcpy compatibility
|
||||
static const char MANUFACTURER_PROGMEM[] PROGMEM = ESPHOME_MANUFACTURER;
|
||||
char manufacturer_buf[sizeof(MANUFACTURER_PROGMEM)];
|
||||
memcpy_P(manufacturer_buf, MANUFACTURER_PROGMEM, sizeof(MANUFACTURER_PROGMEM));
|
||||
resp.set_manufacturer(StringRef(manufacturer_buf, sizeof(MANUFACTURER_PROGMEM) - 1));
|
||||
#else
|
||||
static constexpr auto MANUFACTURER = StringRef::from_lit(ESPHOME_MANUFACTURER);
|
||||
resp.set_manufacturer(MANUFACTURER);
|
||||
#endif
|
||||
#undef ESPHOME_MANUFACTURER
|
||||
|
||||
#ifdef USE_ESP8266
|
||||
static const char MODEL_PROGMEM[] PROGMEM = ESPHOME_BOARD;
|
||||
char model_buf[sizeof(MODEL_PROGMEM)];
|
||||
memcpy_P(model_buf, MODEL_PROGMEM, sizeof(MODEL_PROGMEM));
|
||||
resp.set_model(StringRef(model_buf, sizeof(MODEL_PROGMEM) - 1));
|
||||
#else
|
||||
static constexpr auto MODEL = StringRef::from_lit(ESPHOME_BOARD);
|
||||
resp.set_model(MODEL);
|
||||
#endif
|
||||
#ifdef USE_DEEP_SLEEP
|
||||
resp.has_deep_sleep = deep_sleep::global_has_deep_sleep;
|
||||
#endif
|
||||
#ifdef ESPHOME_PROJECT_NAME
|
||||
#ifdef USE_ESP8266
|
||||
static const char PROJECT_NAME_PROGMEM[] PROGMEM = ESPHOME_PROJECT_NAME;
|
||||
static const char PROJECT_VERSION_PROGMEM[] PROGMEM = ESPHOME_PROJECT_VERSION;
|
||||
char project_name_buf[sizeof(PROJECT_NAME_PROGMEM)];
|
||||
char project_version_buf[sizeof(PROJECT_VERSION_PROGMEM)];
|
||||
memcpy_P(project_name_buf, PROJECT_NAME_PROGMEM, sizeof(PROJECT_NAME_PROGMEM));
|
||||
memcpy_P(project_version_buf, PROJECT_VERSION_PROGMEM, sizeof(PROJECT_VERSION_PROGMEM));
|
||||
resp.set_project_name(StringRef(project_name_buf, sizeof(PROJECT_NAME_PROGMEM) - 1));
|
||||
resp.set_project_version(StringRef(project_version_buf, sizeof(PROJECT_VERSION_PROGMEM) - 1));
|
||||
#else
|
||||
static constexpr auto PROJECT_NAME = StringRef::from_lit(ESPHOME_PROJECT_NAME);
|
||||
static constexpr auto PROJECT_VERSION = StringRef::from_lit(ESPHOME_PROJECT_VERSION);
|
||||
resp.set_project_name(PROJECT_NAME);
|
||||
resp.set_project_version(PROJECT_VERSION);
|
||||
#endif
|
||||
#endif
|
||||
#ifdef USE_WEBSERVER
|
||||
resp.webserver_port = USE_WEBSERVER_PORT;
|
||||
#endif
|
||||
@@ -1545,7 +1580,12 @@ bool APIConnection::send_device_info_response(const DeviceInfoRequest &msg) {
|
||||
#ifdef USE_API_HOMEASSISTANT_STATES
|
||||
void APIConnection::on_home_assistant_state_response(const HomeAssistantStateResponse &msg) {
|
||||
for (auto &it : this->parent_->get_state_subs()) {
|
||||
if (it.entity_id == msg.entity_id && it.attribute.value() == msg.attribute) {
|
||||
// Compare entity_id and attribute with message fields
|
||||
bool entity_match = (strcmp(it.entity_id, msg.entity_id.c_str()) == 0);
|
||||
bool attribute_match = (it.attribute != nullptr && strcmp(it.attribute, msg.attribute.c_str()) == 0) ||
|
||||
(it.attribute == nullptr && msg.attribute.empty());
|
||||
|
||||
if (entity_match && attribute_match) {
|
||||
it.callback(msg.state);
|
||||
}
|
||||
}
|
||||
@@ -1554,15 +1594,54 @@ void APIConnection::on_home_assistant_state_response(const HomeAssistantStateRes
|
||||
#ifdef USE_API_USER_DEFINED_ACTIONS
|
||||
void APIConnection::execute_service(const ExecuteServiceRequest &msg) {
|
||||
bool found = false;
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
// Register the call and get a unique server-generated action_call_id
|
||||
// This avoids collisions when multiple clients use the same call_id
|
||||
uint32_t action_call_id = 0;
|
||||
if (msg.call_id != 0) {
|
||||
action_call_id = this->parent_->register_active_action_call(msg.call_id, this);
|
||||
}
|
||||
// Use the overload that passes action_call_id separately (avoids copying msg)
|
||||
for (auto *service : this->parent_->get_user_services()) {
|
||||
if (service->execute_service(msg, action_call_id)) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
#else
|
||||
for (auto *service : this->parent_->get_user_services()) {
|
||||
if (service->execute_service(msg)) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (!found) {
|
||||
ESP_LOGV(TAG, "Could not find service");
|
||||
}
|
||||
// Note: For services with supports_response != none, the call is unregistered
|
||||
// by an automatically appended APIUnregisterServiceCallAction at the end of
|
||||
// the action list. This ensures async actions (delays, waits) complete first.
|
||||
}
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
void APIConnection::send_execute_service_response(uint32_t call_id, bool success, const std::string &error_message) {
|
||||
ExecuteServiceResponse resp;
|
||||
resp.call_id = call_id;
|
||||
resp.success = success;
|
||||
resp.set_error_message(StringRef(error_message));
|
||||
this->send_message(resp, ExecuteServiceResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
void APIConnection::send_execute_service_response(uint32_t call_id, bool success, const std::string &error_message,
|
||||
const uint8_t *response_data, size_t response_data_len) {
|
||||
ExecuteServiceResponse resp;
|
||||
resp.call_id = call_id;
|
||||
resp.success = success;
|
||||
resp.set_error_message(StringRef(error_message));
|
||||
resp.response_data = response_data;
|
||||
resp.response_data_len = response_data_len;
|
||||
this->send_message(resp, ExecuteServiceResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
#endif
|
||||
|
||||
#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
|
||||
@@ -1662,13 +1741,13 @@ void APIConnection::DeferredBatch::add_item(EntityBase *entity, MessageCreator c
|
||||
for (auto &item : items) {
|
||||
if (item.entity == entity && item.message_type == message_type) {
|
||||
// Replace with new creator
|
||||
item.creator = std::move(creator);
|
||||
item.creator = creator;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// No existing item found, add new one
|
||||
items.emplace_back(entity, std::move(creator), message_type, estimated_size);
|
||||
items.emplace_back(entity, creator, message_type, estimated_size);
|
||||
}
|
||||
|
||||
void APIConnection::DeferredBatch::add_item_front(EntityBase *entity, MessageCreator creator, uint8_t message_type,
|
||||
@@ -1677,7 +1756,7 @@ void APIConnection::DeferredBatch::add_item_front(EntityBase *entity, MessageCre
|
||||
// This avoids expensive vector::insert which shifts all elements
|
||||
// Note: We only ever have one high-priority message at a time (ping OR disconnect)
|
||||
// If we're disconnecting, pings are blocked, so this simple swap is sufficient
|
||||
items.emplace_back(entity, std::move(creator), message_type, estimated_size);
|
||||
items.emplace_back(entity, creator, message_type, estimated_size);
|
||||
if (items.size() > 1) {
|
||||
// Swap the new high-priority item to the front
|
||||
std::swap(items.front(), items.back());
|
||||
@@ -1885,8 +1964,8 @@ void APIConnection::process_state_subscriptions_() {
|
||||
SubscribeHomeAssistantStateResponse resp;
|
||||
resp.set_entity_id(StringRef(it.entity_id));
|
||||
|
||||
// Avoid string copy by directly using the optional's value if it exists
|
||||
resp.set_attribute(it.attribute.has_value() ? StringRef(it.attribute.value()) : StringRef(""));
|
||||
// Avoid string copy by using the const char* pointer if it exists
|
||||
resp.set_attribute(it.attribute != nullptr ? StringRef(it.attribute) : StringRef(""));
|
||||
|
||||
resp.once = it.once;
|
||||
if (this->send_message(resp, SubscribeHomeAssistantStateResponse::MESSAGE_TYPE)) {
|
||||
|
||||
@@ -223,6 +223,13 @@ class APIConnection final : public APIServerConnection {
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTIONS
|
||||
void execute_service(const ExecuteServiceRequest &msg) override;
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
void send_execute_service_response(uint32_t call_id, bool success, const std::string &error_message);
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
void send_execute_service_response(uint32_t call_id, bool success, const std::string &error_message,
|
||||
const uint8_t *response_data, size_t response_data_len);
|
||||
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
#endif
|
||||
#ifdef USE_API_NOISE
|
||||
bool send_noise_encryption_set_key_response(const NoiseEncryptionSetKeyRequest &msg) override;
|
||||
@@ -505,28 +512,9 @@ class APIConnection final : public APIServerConnection {
|
||||
|
||||
class MessageCreator {
|
||||
public:
|
||||
// Constructor for function pointer
|
||||
MessageCreator(MessageCreatorPtr ptr) { data_.function_ptr = ptr; }
|
||||
|
||||
// Constructor for const char * (Event types - no allocation needed)
|
||||
explicit MessageCreator(const char *str_value) { data_.const_char_ptr = str_value; }
|
||||
|
||||
// Delete copy operations - MessageCreator should only be moved
|
||||
MessageCreator(const MessageCreator &other) = delete;
|
||||
MessageCreator &operator=(const MessageCreator &other) = delete;
|
||||
|
||||
// Move constructor
|
||||
MessageCreator(MessageCreator &&other) noexcept : data_(other.data_) { other.data_.function_ptr = nullptr; }
|
||||
|
||||
// Move assignment
|
||||
MessageCreator &operator=(MessageCreator &&other) noexcept {
|
||||
if (this != &other) {
|
||||
data_ = other.data_;
|
||||
other.data_.function_ptr = nullptr;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Call operator - uses message_type to determine union type
|
||||
uint16_t operator()(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single,
|
||||
uint8_t message_type) const;
|
||||
@@ -535,7 +523,7 @@ class APIConnection final : public APIServerConnection {
|
||||
union Data {
|
||||
MessageCreatorPtr function_ptr;
|
||||
const char *const_char_ptr;
|
||||
} data_; // 4 bytes on 32-bit, 8 bytes on 64-bit - same as before
|
||||
} data_; // 4 bytes on 32-bit, 8 bytes on 64-bit
|
||||
};
|
||||
|
||||
// Generic batching mechanism for both state updates and entity info
|
||||
@@ -548,7 +536,7 @@ class APIConnection final : public APIServerConnection {
|
||||
|
||||
// Constructor for creating BatchItem
|
||||
BatchItem(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size)
|
||||
: entity(entity), creator(std::move(creator)), message_type(message_type), estimated_size(estimated_size) {}
|
||||
: entity(entity), creator(creator), message_type(message_type), estimated_size(estimated_size) {}
|
||||
};
|
||||
|
||||
std::vector<BatchItem> items;
|
||||
@@ -716,12 +704,12 @@ class APIConnection final : public APIServerConnection {
|
||||
}
|
||||
|
||||
// Fall back to scheduled batching
|
||||
return this->schedule_message_(entity, std::move(creator), message_type, estimated_size);
|
||||
return this->schedule_message_(entity, creator, message_type, estimated_size);
|
||||
}
|
||||
|
||||
// Helper function to schedule a deferred message with known message type
|
||||
bool schedule_message_(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size) {
|
||||
this->deferred_batch_.add_item(entity, std::move(creator), message_type, estimated_size);
|
||||
this->deferred_batch_.add_item(entity, creator, message_type, estimated_size);
|
||||
return this->schedule_batch_();
|
||||
}
|
||||
|
||||
|
||||
@@ -1010,11 +1010,13 @@ void ListEntitiesServicesResponse::encode(ProtoWriteBuffer buffer) const {
|
||||
for (auto &it : this->args) {
|
||||
buffer.encode_message(3, it, true);
|
||||
}
|
||||
buffer.encode_uint32(4, static_cast<uint32_t>(this->supports_response));
|
||||
}
|
||||
void ListEntitiesServicesResponse::calculate_size(ProtoSize &size) const {
|
||||
size.add_length(1, this->name_ref_.size());
|
||||
size.add_fixed32(1, this->key);
|
||||
size.add_repeated_message(1, this->args);
|
||||
size.add_uint32(1, static_cast<uint32_t>(this->supports_response));
|
||||
}
|
||||
bool ExecuteServiceArgument::decode_varint(uint32_t field_id, ProtoVarInt value) {
|
||||
switch (field_id) {
|
||||
@@ -1075,6 +1077,23 @@ void ExecuteServiceArgument::decode(const uint8_t *buffer, size_t length) {
|
||||
this->string_array.init(count_string_array);
|
||||
ProtoDecodableMessage::decode(buffer, length);
|
||||
}
|
||||
bool ExecuteServiceRequest::decode_varint(uint32_t field_id, ProtoVarInt value) {
|
||||
switch (field_id) {
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
case 3:
|
||||
this->call_id = value.as_uint32();
|
||||
break;
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
case 4:
|
||||
this->return_response = value.as_bool();
|
||||
break;
|
||||
#endif
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool ExecuteServiceRequest::decode_length(uint32_t field_id, ProtoLengthDelimited value) {
|
||||
switch (field_id) {
|
||||
case 2:
|
||||
@@ -1102,6 +1121,24 @@ void ExecuteServiceRequest::decode(const uint8_t *buffer, size_t length) {
|
||||
ProtoDecodableMessage::decode(buffer, length);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
void ExecuteServiceResponse::encode(ProtoWriteBuffer buffer) const {
|
||||
buffer.encode_uint32(1, this->call_id);
|
||||
buffer.encode_bool(2, this->success);
|
||||
buffer.encode_string(3, this->error_message_ref_);
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
buffer.encode_bytes(4, this->response_data, this->response_data_len);
|
||||
#endif
|
||||
}
|
||||
void ExecuteServiceResponse::calculate_size(ProtoSize &size) const {
|
||||
size.add_uint32(1, this->call_id);
|
||||
size.add_bool(1, this->success);
|
||||
size.add_length(1, this->error_message_ref_.size());
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
size.add_length(4, this->response_data_len);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_CAMERA
|
||||
void ListEntitiesCameraResponse::encode(ProtoWriteBuffer buffer) const {
|
||||
buffer.encode_string(1, this->object_id_ref_);
|
||||
@@ -1532,9 +1569,12 @@ bool SelectCommandRequest::decode_varint(uint32_t field_id, ProtoVarInt value) {
|
||||
}
|
||||
bool SelectCommandRequest::decode_length(uint32_t field_id, ProtoLengthDelimited value) {
|
||||
switch (field_id) {
|
||||
case 2:
|
||||
this->state = value.as_string();
|
||||
case 2: {
|
||||
// Use raw data directly to avoid allocation
|
||||
this->state = value.data();
|
||||
this->state_len = value.size();
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -75,6 +75,12 @@ enum ServiceArgType : uint32_t {
|
||||
SERVICE_ARG_TYPE_FLOAT_ARRAY = 6,
|
||||
SERVICE_ARG_TYPE_STRING_ARRAY = 7,
|
||||
};
|
||||
enum SupportsResponseType : uint32_t {
|
||||
SUPPORTS_RESPONSE_NONE = 0,
|
||||
SUPPORTS_RESPONSE_OPTIONAL = 1,
|
||||
SUPPORTS_RESPONSE_ONLY = 2,
|
||||
SUPPORTS_RESPONSE_STATUS = 100,
|
||||
};
|
||||
#endif
|
||||
#ifdef USE_CLIMATE
|
||||
enum ClimateMode : uint32_t {
|
||||
@@ -1257,7 +1263,7 @@ class ListEntitiesServicesArgument final : public ProtoMessage {
|
||||
class ListEntitiesServicesResponse final : public ProtoMessage {
|
||||
public:
|
||||
static constexpr uint8_t MESSAGE_TYPE = 41;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 48;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 50;
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
const char *message_name() const override { return "list_entities_services_response"; }
|
||||
#endif
|
||||
@@ -1265,6 +1271,7 @@ class ListEntitiesServicesResponse final : public ProtoMessage {
|
||||
void set_name(const StringRef &ref) { this->name_ref_ = ref; }
|
||||
uint32_t key{0};
|
||||
FixedVector<ListEntitiesServicesArgument> args{};
|
||||
enums::SupportsResponseType supports_response{};
|
||||
void encode(ProtoWriteBuffer buffer) const override;
|
||||
void calculate_size(ProtoSize &size) const override;
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
@@ -1297,12 +1304,18 @@ class ExecuteServiceArgument final : public ProtoDecodableMessage {
|
||||
class ExecuteServiceRequest final : public ProtoDecodableMessage {
|
||||
public:
|
||||
static constexpr uint8_t MESSAGE_TYPE = 42;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 39;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 45;
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
const char *message_name() const override { return "execute_service_request"; }
|
||||
#endif
|
||||
uint32_t key{0};
|
||||
FixedVector<ExecuteServiceArgument> args{};
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
uint32_t call_id{0};
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
bool return_response{false};
|
||||
#endif
|
||||
void decode(const uint8_t *buffer, size_t length) override;
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
void dump_to(std::string &out) const override;
|
||||
@@ -1311,6 +1324,32 @@ class ExecuteServiceRequest final : public ProtoDecodableMessage {
|
||||
protected:
|
||||
bool decode_32bit(uint32_t field_id, Proto32Bit value) override;
|
||||
bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override;
|
||||
bool decode_varint(uint32_t field_id, ProtoVarInt value) override;
|
||||
};
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
class ExecuteServiceResponse final : public ProtoMessage {
|
||||
public:
|
||||
static constexpr uint8_t MESSAGE_TYPE = 131;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 34;
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
const char *message_name() const override { return "execute_service_response"; }
|
||||
#endif
|
||||
uint32_t call_id{0};
|
||||
bool success{false};
|
||||
StringRef error_message_ref_{};
|
||||
void set_error_message(const StringRef &ref) { this->error_message_ref_ = ref; }
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
const uint8_t *response_data{nullptr};
|
||||
uint16_t response_data_len{0};
|
||||
#endif
|
||||
void encode(ProtoWriteBuffer buffer) const override;
|
||||
void calculate_size(ProtoSize &size) const override;
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
void dump_to(std::string &out) const override;
|
||||
#endif
|
||||
|
||||
protected:
|
||||
};
|
||||
#endif
|
||||
#ifdef USE_CAMERA
|
||||
@@ -1565,11 +1604,12 @@ class SelectStateResponse final : public StateResponseProtoMessage {
|
||||
class SelectCommandRequest final : public CommandProtoMessage {
|
||||
public:
|
||||
static constexpr uint8_t MESSAGE_TYPE = 54;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 18;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 28;
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
const char *message_name() const override { return "select_command_request"; }
|
||||
#endif
|
||||
std::string state{};
|
||||
const uint8_t *state{nullptr};
|
||||
uint16_t state_len{0};
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
void dump_to(std::string &out) const override;
|
||||
#endif
|
||||
|
||||
@@ -231,6 +231,20 @@ template<> const char *proto_enum_to_string<enums::ServiceArgType>(enums::Servic
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
template<> const char *proto_enum_to_string<enums::SupportsResponseType>(enums::SupportsResponseType value) {
|
||||
switch (value) {
|
||||
case enums::SUPPORTS_RESPONSE_NONE:
|
||||
return "SUPPORTS_RESPONSE_NONE";
|
||||
case enums::SUPPORTS_RESPONSE_OPTIONAL:
|
||||
return "SUPPORTS_RESPONSE_OPTIONAL";
|
||||
case enums::SUPPORTS_RESPONSE_ONLY:
|
||||
return "SUPPORTS_RESPONSE_ONLY";
|
||||
case enums::SUPPORTS_RESPONSE_STATUS:
|
||||
return "SUPPORTS_RESPONSE_STATUS";
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_CLIMATE
|
||||
template<> const char *proto_enum_to_string<enums::ClimateMode>(enums::ClimateMode value) {
|
||||
@@ -1194,6 +1208,7 @@ void ListEntitiesServicesResponse::dump_to(std::string &out) const {
|
||||
it.dump_to(out);
|
||||
out.append("\n");
|
||||
}
|
||||
dump_field(out, "supports_response", static_cast<enums::SupportsResponseType>(this->supports_response));
|
||||
}
|
||||
void ExecuteServiceArgument::dump_to(std::string &out) const {
|
||||
MessageDumpHelper helper(out, "ExecuteServiceArgument");
|
||||
@@ -1223,6 +1238,25 @@ void ExecuteServiceRequest::dump_to(std::string &out) const {
|
||||
it.dump_to(out);
|
||||
out.append("\n");
|
||||
}
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
dump_field(out, "call_id", this->call_id);
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
dump_field(out, "return_response", this->return_response);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
void ExecuteServiceResponse::dump_to(std::string &out) const {
|
||||
MessageDumpHelper helper(out, "ExecuteServiceResponse");
|
||||
dump_field(out, "call_id", this->call_id);
|
||||
dump_field(out, "success", this->success);
|
||||
dump_field(out, "error_message", this->error_message_ref_);
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
out.append(" response_data: ");
|
||||
out.append(format_hex_pretty(this->response_data, this->response_data_len));
|
||||
out.append("\n");
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_CAMERA
|
||||
@@ -1419,7 +1453,9 @@ void SelectStateResponse::dump_to(std::string &out) const {
|
||||
void SelectCommandRequest::dump_to(std::string &out) const {
|
||||
MessageDumpHelper helper(out, "SelectCommandRequest");
|
||||
dump_field(out, "key", this->key);
|
||||
dump_field(out, "state", this->state);
|
||||
out.append(" state: ");
|
||||
out.append(format_hex_pretty(this->state, this->state_len));
|
||||
out.append("\n");
|
||||
#ifdef USE_DEVICES
|
||||
dump_field(out, "device_id", this->device_id);
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
#include "api_connection.h"
|
||||
#include "esphome/components/network/util.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/controller_registry.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/util.h"
|
||||
@@ -186,6 +186,9 @@ void APIServer::loop() {
|
||||
// Rare case: handle disconnection
|
||||
#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
|
||||
this->client_disconnected_trigger_->trigger(client->client_info_.name, client->client_info_.peername);
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
this->unregister_active_action_calls_for_connection(client.get());
|
||||
#endif
|
||||
ESP_LOGV(TAG, "Remove connection %s", client->client_info_.name.c_str());
|
||||
|
||||
@@ -416,25 +419,56 @@ void APIServer::handle_action_response(uint32_t call_id, bool success, const std
|
||||
#endif // USE_API_HOMEASSISTANT_SERVICES
|
||||
|
||||
#ifdef USE_API_HOMEASSISTANT_STATES
|
||||
// Helper to add subscription (reduces duplication)
|
||||
void APIServer::add_state_subscription_(const char *entity_id, const char *attribute,
|
||||
std::function<void(std::string)> f, bool once) {
|
||||
this->state_subs_.push_back(HomeAssistantStateSubscription{
|
||||
.entity_id = entity_id, .attribute = attribute, .callback = std::move(f), .once = once,
|
||||
// entity_id_dynamic_storage and attribute_dynamic_storage remain nullptr (no heap allocation)
|
||||
});
|
||||
}
|
||||
|
||||
// Helper to add subscription with heap-allocated strings (reduces duplication)
|
||||
void APIServer::add_state_subscription_(std::string entity_id, optional<std::string> attribute,
|
||||
std::function<void(std::string)> f, bool once) {
|
||||
HomeAssistantStateSubscription sub;
|
||||
// Allocate heap storage for the strings
|
||||
sub.entity_id_dynamic_storage = std::make_unique<std::string>(std::move(entity_id));
|
||||
sub.entity_id = sub.entity_id_dynamic_storage->c_str();
|
||||
|
||||
if (attribute.has_value()) {
|
||||
sub.attribute_dynamic_storage = std::make_unique<std::string>(std::move(attribute.value()));
|
||||
sub.attribute = sub.attribute_dynamic_storage->c_str();
|
||||
} else {
|
||||
sub.attribute = nullptr;
|
||||
}
|
||||
|
||||
sub.callback = std::move(f);
|
||||
sub.once = once;
|
||||
this->state_subs_.push_back(std::move(sub));
|
||||
}
|
||||
|
||||
// New const char* overload (for internal components - zero allocation)
|
||||
void APIServer::subscribe_home_assistant_state(const char *entity_id, const char *attribute,
|
||||
std::function<void(std::string)> f) {
|
||||
this->add_state_subscription_(entity_id, attribute, std::move(f), false);
|
||||
}
|
||||
|
||||
void APIServer::get_home_assistant_state(const char *entity_id, const char *attribute,
|
||||
std::function<void(std::string)> f) {
|
||||
this->add_state_subscription_(entity_id, attribute, std::move(f), true);
|
||||
}
|
||||
|
||||
// Existing std::string overload (for custom_api_device.h - heap allocation)
|
||||
void APIServer::subscribe_home_assistant_state(std::string entity_id, optional<std::string> attribute,
|
||||
std::function<void(std::string)> f) {
|
||||
this->state_subs_.push_back(HomeAssistantStateSubscription{
|
||||
.entity_id = std::move(entity_id),
|
||||
.attribute = std::move(attribute),
|
||||
.callback = std::move(f),
|
||||
.once = false,
|
||||
});
|
||||
this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), false);
|
||||
}
|
||||
|
||||
void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
|
||||
std::function<void(std::string)> f) {
|
||||
this->state_subs_.push_back(HomeAssistantStateSubscription{
|
||||
.entity_id = std::move(entity_id),
|
||||
.attribute = std::move(attribute),
|
||||
.callback = std::move(f),
|
||||
.once = true,
|
||||
});
|
||||
};
|
||||
this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), true);
|
||||
}
|
||||
|
||||
const std::vector<APIServer::HomeAssistantStateSubscription> &APIServer::get_state_subs() const {
|
||||
return this->state_subs_;
|
||||
@@ -585,5 +619,84 @@ bool APIServer::teardown() {
|
||||
return this->clients_.empty();
|
||||
}
|
||||
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
// Timeout for action calls - matches aioesphomeapi client timeout (default 30s)
|
||||
// Can be overridden via USE_API_ACTION_CALL_TIMEOUT_MS define for testing
|
||||
#ifndef USE_API_ACTION_CALL_TIMEOUT_MS
|
||||
#define USE_API_ACTION_CALL_TIMEOUT_MS 30000 // NOLINT
|
||||
#endif
|
||||
|
||||
uint32_t APIServer::register_active_action_call(uint32_t client_call_id, APIConnection *conn) {
|
||||
uint32_t action_call_id = this->next_action_call_id_++;
|
||||
// Handle wraparound (skip 0 as it means "no call")
|
||||
if (this->next_action_call_id_ == 0) {
|
||||
this->next_action_call_id_ = 1;
|
||||
}
|
||||
this->active_action_calls_.push_back({action_call_id, client_call_id, conn});
|
||||
|
||||
// Schedule automatic cleanup after timeout (client will have given up by then)
|
||||
this->set_timeout(str_sprintf("action_call_%u", action_call_id), USE_API_ACTION_CALL_TIMEOUT_MS,
|
||||
[this, action_call_id]() {
|
||||
ESP_LOGD(TAG, "Action call %u timed out", action_call_id);
|
||||
this->unregister_active_action_call(action_call_id);
|
||||
});
|
||||
|
||||
return action_call_id;
|
||||
}
|
||||
|
||||
void APIServer::unregister_active_action_call(uint32_t action_call_id) {
|
||||
// Cancel the timeout for this action call
|
||||
this->cancel_timeout(str_sprintf("action_call_%u", action_call_id));
|
||||
|
||||
// Swap-and-pop is more efficient than remove_if for unordered vectors
|
||||
for (size_t i = 0; i < this->active_action_calls_.size(); i++) {
|
||||
if (this->active_action_calls_[i].action_call_id == action_call_id) {
|
||||
std::swap(this->active_action_calls_[i], this->active_action_calls_.back());
|
||||
this->active_action_calls_.pop_back();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void APIServer::unregister_active_action_calls_for_connection(APIConnection *conn) {
|
||||
// Remove all active action calls for disconnected connection using swap-and-pop
|
||||
for (size_t i = 0; i < this->active_action_calls_.size();) {
|
||||
if (this->active_action_calls_[i].connection == conn) {
|
||||
// Cancel the timeout for this action call
|
||||
this->cancel_timeout(str_sprintf("action_call_%u", this->active_action_calls_[i].action_call_id));
|
||||
|
||||
std::swap(this->active_action_calls_[i], this->active_action_calls_.back());
|
||||
this->active_action_calls_.pop_back();
|
||||
// Don't increment i - need to check the swapped element
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void APIServer::send_action_response(uint32_t action_call_id, bool success, const std::string &error_message) {
|
||||
for (auto &call : this->active_action_calls_) {
|
||||
if (call.action_call_id == action_call_id) {
|
||||
call.connection->send_execute_service_response(call.client_call_id, success, error_message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
ESP_LOGW(TAG, "Cannot send response: no active call found for action_call_id %u", action_call_id);
|
||||
}
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
void APIServer::send_action_response(uint32_t action_call_id, bool success, const std::string &error_message,
|
||||
const uint8_t *response_data, size_t response_data_len) {
|
||||
for (auto &call : this->active_action_calls_) {
|
||||
if (call.action_call_id == action_call_id) {
|
||||
call.connection->send_execute_service_response(call.client_call_id, success, error_message, response_data,
|
||||
response_data_len);
|
||||
return;
|
||||
}
|
||||
}
|
||||
ESP_LOGW(TAG, "Cannot send response: no active call found for action_call_id %u", action_call_id);
|
||||
}
|
||||
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
|
||||
} // namespace esphome::api
|
||||
#endif
|
||||
|
||||
@@ -12,9 +12,6 @@
|
||||
#include "esphome/core/log.h"
|
||||
#include "list_entities.h"
|
||||
#include "subscribe_state.h"
|
||||
#ifdef USE_API_USER_DEFINED_ACTIONS
|
||||
#include "user_services.h"
|
||||
#endif
|
||||
#ifdef USE_LOGGER
|
||||
#include "esphome/components/logger/logger.h"
|
||||
#endif
|
||||
@@ -22,11 +19,15 @@
|
||||
#include "esphome/components/camera/camera.h"
|
||||
#endif
|
||||
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
namespace esphome::api {
|
||||
|
||||
#ifdef USE_API_USER_DEFINED_ACTIONS
|
||||
// Forward declaration - full definition in user_services.h
|
||||
class UserServiceDescriptor;
|
||||
#endif
|
||||
|
||||
#ifdef USE_API_NOISE
|
||||
struct SavedNoisePsk {
|
||||
psk_t psk;
|
||||
@@ -154,6 +155,19 @@ class APIServer : public Component,
|
||||
// Only compile push_back method when custom_services: true (external components)
|
||||
void register_user_service(UserServiceDescriptor *descriptor) { this->user_services_.push_back(descriptor); }
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
// Action call context management - supports concurrent calls from multiple clients
|
||||
// Returns server-generated action_call_id to avoid collisions when clients use same call_id
|
||||
uint32_t register_active_action_call(uint32_t client_call_id, APIConnection *conn);
|
||||
void unregister_active_action_call(uint32_t action_call_id);
|
||||
void unregister_active_action_calls_for_connection(APIConnection *conn);
|
||||
// Send response for a specific action call (uses action_call_id, sends client_call_id in response)
|
||||
void send_action_response(uint32_t action_call_id, bool success, const std::string &error_message);
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
void send_action_response(uint32_t action_call_id, bool success, const std::string &error_message,
|
||||
const uint8_t *response_data, size_t response_data_len);
|
||||
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
#endif
|
||||
#ifdef USE_HOMEASSISTANT_TIME
|
||||
void request_time();
|
||||
@@ -176,16 +190,27 @@ class APIServer : public Component,
|
||||
|
||||
#ifdef USE_API_HOMEASSISTANT_STATES
|
||||
struct HomeAssistantStateSubscription {
|
||||
std::string entity_id;
|
||||
optional<std::string> attribute;
|
||||
const char *entity_id; // Pointer to flash (internal) or heap (external)
|
||||
const char *attribute; // Pointer to flash or nullptr (nullptr means no attribute)
|
||||
std::function<void(std::string)> callback;
|
||||
bool once;
|
||||
|
||||
// Dynamic storage for external components using std::string API (custom_api_device.h)
|
||||
// These are only allocated when using the std::string overload (nullptr for const char* overload)
|
||||
std::unique_ptr<std::string> entity_id_dynamic_storage;
|
||||
std::unique_ptr<std::string> attribute_dynamic_storage;
|
||||
};
|
||||
|
||||
// New const char* overload (for internal components - zero allocation)
|
||||
void subscribe_home_assistant_state(const char *entity_id, const char *attribute, std::function<void(std::string)> f);
|
||||
void get_home_assistant_state(const char *entity_id, const char *attribute, std::function<void(std::string)> f);
|
||||
|
||||
// Existing std::string overload (for custom_api_device.h - heap allocation)
|
||||
void subscribe_home_assistant_state(std::string entity_id, optional<std::string> attribute,
|
||||
std::function<void(std::string)> f);
|
||||
void get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
|
||||
std::function<void(std::string)> f);
|
||||
|
||||
const std::vector<HomeAssistantStateSubscription> &get_state_subs() const;
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTIONS
|
||||
@@ -206,6 +231,13 @@ class APIServer : public Component,
|
||||
bool update_noise_psk_(const SavedNoisePsk &new_psk, const LogString *save_log_msg, const LogString *fail_log_msg,
|
||||
const psk_t &active_psk, bool make_active);
|
||||
#endif // USE_API_NOISE
|
||||
#ifdef USE_API_HOMEASSISTANT_STATES
|
||||
// Helper methods to reduce code duplication
|
||||
void add_state_subscription_(const char *entity_id, const char *attribute, std::function<void(std::string)> f,
|
||||
bool once);
|
||||
void add_state_subscription_(std::string entity_id, optional<std::string> attribute,
|
||||
std::function<void(std::string)> f, bool once);
|
||||
#endif // USE_API_HOMEASSISTANT_STATES
|
||||
// Pointers and pointer-like types first (4 bytes each)
|
||||
std::unique_ptr<socket::Socket> socket_ = nullptr;
|
||||
#ifdef USE_API_CLIENT_CONNECTED_TRIGGER
|
||||
@@ -230,6 +262,17 @@ class APIServer : public Component,
|
||||
#endif
|
||||
#ifdef USE_API_USER_DEFINED_ACTIONS
|
||||
std::vector<UserServiceDescriptor *> user_services_;
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
// Active action calls - supports concurrent calls from multiple clients
|
||||
// Uses server-generated action_call_id to avoid collisions when multiple clients use same call_id
|
||||
struct ActiveActionCall {
|
||||
uint32_t action_call_id; // Server-generated unique ID (passed to actions)
|
||||
uint32_t client_call_id; // Client's original call_id (used in response)
|
||||
APIConnection *connection;
|
||||
};
|
||||
std::vector<ActiveActionCall> active_action_calls_;
|
||||
uint32_t next_action_call_id_{1}; // Counter for generating unique action_call_ids
|
||||
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
#endif
|
||||
#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
|
||||
struct PendingActionResponse {
|
||||
|
||||
@@ -16,7 +16,10 @@ template<typename T, typename... Ts> class CustomAPIDeviceService : public UserS
|
||||
: UserServiceDynamic<Ts...>(name, arg_names), obj_(obj), callback_(callback) {}
|
||||
|
||||
protected:
|
||||
void execute(Ts... x) override { (this->obj_->*this->callback_)(x...); } // NOLINT
|
||||
// CustomAPIDevice services don't support action responses - ignore call_id and return_response
|
||||
void execute(uint32_t /*call_id*/, bool /*return_response*/, Ts... x) override {
|
||||
(this->obj_->*this->callback_)(x...); // NOLINT
|
||||
}
|
||||
|
||||
T *obj_;
|
||||
void (T::*callback_)(Ts...);
|
||||
|
||||
@@ -12,10 +12,17 @@
|
||||
#endif
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/string_ref.h"
|
||||
|
||||
namespace esphome::api {
|
||||
|
||||
template<typename... X> class TemplatableStringValue : public TemplatableValue<std::string, X...> {
|
||||
// Verify that const char* uses the base class STATIC_STRING optimization (no heap allocation)
|
||||
// rather than being wrapped in a lambda. The base class constructor for const char* is more
|
||||
// specialized than the templated constructor here, so it should be selected.
|
||||
static_assert(std::is_constructible_v<TemplatableValue<std::string, X...>, const char *>,
|
||||
"Base class must have const char* constructor for STATIC_STRING optimization");
|
||||
|
||||
private:
|
||||
// Helper to convert value to string - handles the case where value is already a string
|
||||
template<typename T> static std::string value_to_string(T &&val) { return to_string(std::forward<T>(val)); }
|
||||
@@ -46,23 +53,25 @@ template<typename... Ts> class TemplatableKeyValuePair {
|
||||
|
||||
// Keys are always string literals from YAML dictionary keys (e.g., "code", "event")
|
||||
// and never templatable values or lambdas. Only the value parameter can be a lambda/template.
|
||||
// Using pass-by-value with std::move allows optimal performance for both lvalues and rvalues.
|
||||
template<typename T> TemplatableKeyValuePair(std::string key, T value) : key(std::move(key)), value(value) {}
|
||||
// Using const char* avoids std::string heap allocation - keys remain in flash.
|
||||
template<typename T> TemplatableKeyValuePair(const char *key, T value) : key(key), value(value) {}
|
||||
|
||||
std::string key;
|
||||
const char *key{nullptr};
|
||||
TemplatableStringValue<Ts...> value;
|
||||
};
|
||||
|
||||
#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
|
||||
// Represents the response data from a Home Assistant action
|
||||
// Note: This class holds a StringRef to the error_message from the protobuf message.
|
||||
// The protobuf message must outlive the ActionResponse (which is guaranteed since
|
||||
// the callback is invoked synchronously while the message is on the stack).
|
||||
class ActionResponse {
|
||||
public:
|
||||
ActionResponse(bool success, std::string error_message = "")
|
||||
: success_(success), error_message_(std::move(error_message)) {}
|
||||
ActionResponse(bool success, const std::string &error_message) : success_(success), error_message_(error_message) {}
|
||||
|
||||
#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
|
||||
ActionResponse(bool success, std::string error_message, const uint8_t *data, size_t data_len)
|
||||
: success_(success), error_message_(std::move(error_message)) {
|
||||
ActionResponse(bool success, const std::string &error_message, const uint8_t *data, size_t data_len)
|
||||
: success_(success), error_message_(error_message) {
|
||||
if (data == nullptr || data_len == 0)
|
||||
return;
|
||||
this->json_document_ = json::parse_json(data, data_len);
|
||||
@@ -70,7 +79,8 @@ class ActionResponse {
|
||||
#endif
|
||||
|
||||
bool is_success() const { return this->success_; }
|
||||
const std::string &get_error_message() const { return this->error_message_; }
|
||||
// Returns reference to error message - can be implicitly converted to std::string if needed
|
||||
const StringRef &get_error_message() const { return this->error_message_; }
|
||||
|
||||
#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
|
||||
// Get data as parsed JSON object (const version returns read-only view)
|
||||
@@ -79,7 +89,7 @@ class ActionResponse {
|
||||
|
||||
protected:
|
||||
bool success_;
|
||||
std::string error_message_;
|
||||
StringRef error_message_;
|
||||
#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
|
||||
JsonDocument json_document_;
|
||||
#endif
|
||||
@@ -105,14 +115,15 @@ template<typename... Ts> class HomeAssistantServiceCallAction : public Action<Ts
|
||||
|
||||
// Keys are always string literals from the Python code generation (e.g., cg.add(var.add_data("tag_id", templ))).
|
||||
// The value parameter can be a lambda/template, but keys are never templatable.
|
||||
template<typename K, typename V> void add_data(K &&key, V &&value) {
|
||||
this->add_kv_(this->data_, std::forward<K>(key), std::forward<V>(value));
|
||||
// Using const char* for keys avoids std::string heap allocation - keys remain in flash.
|
||||
template<typename V> void add_data(const char *key, V &&value) {
|
||||
this->add_kv_(this->data_, key, std::forward<V>(value));
|
||||
}
|
||||
template<typename K, typename V> void add_data_template(K &&key, V &&value) {
|
||||
this->add_kv_(this->data_template_, std::forward<K>(key), std::forward<V>(value));
|
||||
template<typename V> void add_data_template(const char *key, V &&value) {
|
||||
this->add_kv_(this->data_template_, key, std::forward<V>(value));
|
||||
}
|
||||
template<typename K, typename V> void add_variable(K &&key, V &&value) {
|
||||
this->add_kv_(this->variables_, std::forward<K>(key), std::forward<V>(value));
|
||||
template<typename V> void add_variable(const char *key, V &&value) {
|
||||
this->add_kv_(this->variables_, key, std::forward<V>(value));
|
||||
}
|
||||
|
||||
#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
|
||||
@@ -185,10 +196,11 @@ template<typename... Ts> class HomeAssistantServiceCallAction : public Action<Ts
|
||||
}
|
||||
|
||||
protected:
|
||||
// Helper to add key-value pairs to FixedVectors with perfect forwarding to avoid copies
|
||||
template<typename K, typename V> void add_kv_(FixedVector<TemplatableKeyValuePair<Ts...>> &vec, K &&key, V &&value) {
|
||||
// Helper to add key-value pairs to FixedVectors
|
||||
// Keys are always string literals (const char*), values can be lambdas/templates
|
||||
template<typename V> void add_kv_(FixedVector<TemplatableKeyValuePair<Ts...>> &vec, const char *key, V &&value) {
|
||||
auto &kv = vec.emplace_back();
|
||||
kv.key = std::forward<K>(key);
|
||||
kv.key = key;
|
||||
kv.value = std::forward<V>(value);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/util.h"
|
||||
#ifdef USE_API_USER_DEFINED_ACTIONS
|
||||
#include "user_services.h"
|
||||
#endif
|
||||
|
||||
namespace esphome::api {
|
||||
|
||||
|
||||
@@ -1,20 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/automation.h"
|
||||
#include "api_pb2.h"
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/core/component.h"
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
#include "esphome/components/json/json_util.h"
|
||||
#endif
|
||||
|
||||
#ifdef USE_API_USER_DEFINED_ACTIONS
|
||||
namespace esphome::api {
|
||||
|
||||
// Forward declaration - full definition in api_server.h
|
||||
class APIServer;
|
||||
|
||||
class UserServiceDescriptor {
|
||||
public:
|
||||
virtual ListEntitiesServicesResponse encode_list_service_response() = 0;
|
||||
|
||||
virtual bool execute_service(const ExecuteServiceRequest &req) = 0;
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
// Overload that accepts server-generated action_call_id (avoids client call_id collisions)
|
||||
virtual bool execute_service(const ExecuteServiceRequest &req, uint32_t action_call_id) = 0;
|
||||
#endif
|
||||
|
||||
bool is_internal() { return false; }
|
||||
};
|
||||
@@ -27,8 +38,9 @@ template<typename T> enums::ServiceArgType to_service_arg_type();
|
||||
// Stores only pointers to string literals in flash - no heap allocation
|
||||
template<typename... Ts> class UserServiceBase : public UserServiceDescriptor {
|
||||
public:
|
||||
UserServiceBase(const char *name, const std::array<const char *, sizeof...(Ts)> &arg_names)
|
||||
: name_(name), arg_names_(arg_names) {
|
||||
UserServiceBase(const char *name, const std::array<const char *, sizeof...(Ts)> &arg_names,
|
||||
enums::SupportsResponseType supports_response = enums::SUPPORTS_RESPONSE_NONE)
|
||||
: name_(name), arg_names_(arg_names), supports_response_(supports_response) {
|
||||
this->key_ = fnv1_hash(name);
|
||||
}
|
||||
|
||||
@@ -36,6 +48,7 @@ template<typename... Ts> class UserServiceBase : public UserServiceDescriptor {
|
||||
ListEntitiesServicesResponse msg;
|
||||
msg.set_name(StringRef(this->name_));
|
||||
msg.key = this->key_;
|
||||
msg.supports_response = this->supports_response_;
|
||||
std::array<enums::ServiceArgType, sizeof...(Ts)> arg_types = {to_service_arg_type<Ts>()...};
|
||||
msg.args.init(sizeof...(Ts));
|
||||
for (size_t i = 0; i < sizeof...(Ts); i++) {
|
||||
@@ -51,21 +64,37 @@ template<typename... Ts> class UserServiceBase : public UserServiceDescriptor {
|
||||
return false;
|
||||
if (req.args.size() != sizeof...(Ts))
|
||||
return false;
|
||||
this->execute_(req.args, std::make_index_sequence<sizeof...(Ts)>{});
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
this->execute_(req.args, req.call_id, req.return_response, std::make_index_sequence<sizeof...(Ts)>{});
|
||||
#else
|
||||
this->execute_(req.args, 0, false, std::make_index_sequence<sizeof...(Ts)>{});
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
bool execute_service(const ExecuteServiceRequest &req, uint32_t action_call_id) override {
|
||||
if (req.key != this->key_)
|
||||
return false;
|
||||
if (req.args.size() != sizeof...(Ts))
|
||||
return false;
|
||||
this->execute_(req.args, action_call_id, req.return_response, std::make_index_sequence<sizeof...(Ts)>{});
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
protected:
|
||||
virtual void execute(Ts... x) = 0;
|
||||
virtual void execute(uint32_t call_id, bool return_response, Ts... x) = 0;
|
||||
template<typename ArgsContainer, size_t... S>
|
||||
void execute_(const ArgsContainer &args, std::index_sequence<S...> type) {
|
||||
this->execute((get_execute_arg_value<Ts>(args[S]))...);
|
||||
void execute_(const ArgsContainer &args, uint32_t call_id, bool return_response, std::index_sequence<S...> /*type*/) {
|
||||
this->execute(call_id, return_response, (get_execute_arg_value<Ts>(args[S]))...);
|
||||
}
|
||||
|
||||
// Pointers to string literals in flash - no heap allocation
|
||||
const char *name_;
|
||||
std::array<const char *, sizeof...(Ts)> arg_names_;
|
||||
uint32_t key_{0};
|
||||
enums::SupportsResponseType supports_response_{enums::SUPPORTS_RESPONSE_NONE};
|
||||
};
|
||||
|
||||
// Separate class for custom_api_device services (rare case)
|
||||
@@ -81,6 +110,7 @@ template<typename... Ts> class UserServiceDynamic : public UserServiceDescriptor
|
||||
ListEntitiesServicesResponse msg;
|
||||
msg.set_name(StringRef(this->name_));
|
||||
msg.key = this->key_;
|
||||
msg.supports_response = enums::SUPPORTS_RESPONSE_NONE; // Dynamic services don't support responses yet
|
||||
std::array<enums::ServiceArgType, sizeof...(Ts)> arg_types = {to_service_arg_type<Ts>()...};
|
||||
msg.args.init(sizeof...(Ts));
|
||||
for (size_t i = 0; i < sizeof...(Ts); i++) {
|
||||
@@ -96,15 +126,31 @@ template<typename... Ts> class UserServiceDynamic : public UserServiceDescriptor
|
||||
return false;
|
||||
if (req.args.size() != sizeof...(Ts))
|
||||
return false;
|
||||
this->execute_(req.args, std::make_index_sequence<sizeof...(Ts)>{});
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
this->execute_(req.args, req.call_id, req.return_response, std::make_index_sequence<sizeof...(Ts)>{});
|
||||
#else
|
||||
this->execute_(req.args, 0, false, std::make_index_sequence<sizeof...(Ts)>{});
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
// Dynamic services don't support responses yet, but need to implement the interface
|
||||
bool execute_service(const ExecuteServiceRequest &req, uint32_t action_call_id) override {
|
||||
if (req.key != this->key_)
|
||||
return false;
|
||||
if (req.args.size() != sizeof...(Ts))
|
||||
return false;
|
||||
this->execute_(req.args, action_call_id, req.return_response, std::make_index_sequence<sizeof...(Ts)>{});
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
protected:
|
||||
virtual void execute(Ts... x) = 0;
|
||||
virtual void execute(uint32_t call_id, bool return_response, Ts... x) = 0;
|
||||
template<typename ArgsContainer, size_t... S>
|
||||
void execute_(const ArgsContainer &args, std::index_sequence<S...> type) {
|
||||
this->execute((get_execute_arg_value<Ts>(args[S]))...);
|
||||
void execute_(const ArgsContainer &args, uint32_t call_id, bool return_response, std::index_sequence<S...> /*type*/) {
|
||||
this->execute(call_id, return_response, (get_execute_arg_value<Ts>(args[S]))...);
|
||||
}
|
||||
|
||||
// Heap-allocated strings for runtime-generated names
|
||||
@@ -113,15 +159,149 @@ template<typename... Ts> class UserServiceDynamic : public UserServiceDescriptor
|
||||
uint32_t key_{0};
|
||||
};
|
||||
|
||||
template<typename... Ts> class UserServiceTrigger : public UserServiceBase<Ts...>, public Trigger<Ts...> {
|
||||
// Primary template declaration
|
||||
template<enums::SupportsResponseType Mode, typename... Ts> class UserServiceTrigger;
|
||||
|
||||
// Specialization for NONE - no extra trigger arguments
|
||||
template<typename... Ts>
|
||||
class UserServiceTrigger<enums::SUPPORTS_RESPONSE_NONE, Ts...> : public UserServiceBase<Ts...>, public Trigger<Ts...> {
|
||||
public:
|
||||
// Constructor for static names (YAML-defined services - used by code generator)
|
||||
UserServiceTrigger(const char *name, const std::array<const char *, sizeof...(Ts)> &arg_names)
|
||||
: UserServiceBase<Ts...>(name, arg_names) {}
|
||||
: UserServiceBase<Ts...>(name, arg_names, enums::SUPPORTS_RESPONSE_NONE) {}
|
||||
|
||||
protected:
|
||||
void execute(Ts... x) override { this->trigger(x...); } // NOLINT
|
||||
void execute(uint32_t /*call_id*/, bool /*return_response*/, Ts... x) override { this->trigger(x...); }
|
||||
};
|
||||
|
||||
// Specialization for OPTIONAL - call_id and return_response trigger arguments
|
||||
template<typename... Ts>
|
||||
class UserServiceTrigger<enums::SUPPORTS_RESPONSE_OPTIONAL, Ts...> : public UserServiceBase<Ts...>,
|
||||
public Trigger<uint32_t, bool, Ts...> {
|
||||
public:
|
||||
UserServiceTrigger(const char *name, const std::array<const char *, sizeof...(Ts)> &arg_names)
|
||||
: UserServiceBase<Ts...>(name, arg_names, enums::SUPPORTS_RESPONSE_OPTIONAL) {}
|
||||
|
||||
protected:
|
||||
void execute(uint32_t call_id, bool return_response, Ts... x) override {
|
||||
this->trigger(call_id, return_response, x...);
|
||||
}
|
||||
};
|
||||
|
||||
// Specialization for ONLY - just call_id trigger argument
|
||||
template<typename... Ts>
|
||||
class UserServiceTrigger<enums::SUPPORTS_RESPONSE_ONLY, Ts...> : public UserServiceBase<Ts...>,
|
||||
public Trigger<uint32_t, Ts...> {
|
||||
public:
|
||||
UserServiceTrigger(const char *name, const std::array<const char *, sizeof...(Ts)> &arg_names)
|
||||
: UserServiceBase<Ts...>(name, arg_names, enums::SUPPORTS_RESPONSE_ONLY) {}
|
||||
|
||||
protected:
|
||||
void execute(uint32_t call_id, bool /*return_response*/, Ts... x) override { this->trigger(call_id, x...); }
|
||||
};
|
||||
|
||||
// Specialization for STATUS - just call_id trigger argument (reports success/error without data)
|
||||
template<typename... Ts>
|
||||
class UserServiceTrigger<enums::SUPPORTS_RESPONSE_STATUS, Ts...> : public UserServiceBase<Ts...>,
|
||||
public Trigger<uint32_t, Ts...> {
|
||||
public:
|
||||
UserServiceTrigger(const char *name, const std::array<const char *, sizeof...(Ts)> &arg_names)
|
||||
: UserServiceBase<Ts...>(name, arg_names, enums::SUPPORTS_RESPONSE_STATUS) {}
|
||||
|
||||
protected:
|
||||
void execute(uint32_t call_id, bool /*return_response*/, Ts... x) override { this->trigger(call_id, x...); }
|
||||
};
|
||||
|
||||
} // namespace esphome::api
|
||||
#endif // USE_API_USER_DEFINED_ACTIONS
|
||||
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
// Include full definition of APIServer for template implementation
|
||||
// Must be outside namespace to avoid including STL headers inside namespace
|
||||
#include "api_server.h"
|
||||
|
||||
namespace esphome::api {
|
||||
|
||||
template<typename... Ts> class APIRespondAction : public Action<Ts...> {
|
||||
public:
|
||||
explicit APIRespondAction(APIServer *parent) : parent_(parent) {}
|
||||
|
||||
template<typename V> void set_success(V success) { this->success_ = success; }
|
||||
template<typename V> void set_error_message(V error) { this->error_message_ = error; }
|
||||
void set_is_optional_mode(bool is_optional) { this->is_optional_mode_ = is_optional; }
|
||||
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
void set_data(std::function<void(Ts..., JsonObject)> func) {
|
||||
this->json_builder_ = std::move(func);
|
||||
this->has_data_ = true;
|
||||
}
|
||||
#endif
|
||||
|
||||
void play(const Ts &...x) override {
|
||||
// Extract call_id from first argument - it's always first for optional/only/status modes
|
||||
auto args = std::make_tuple(x...);
|
||||
uint32_t call_id = std::get<0>(args);
|
||||
|
||||
bool success = this->success_.value(x...);
|
||||
std::string error_message = this->error_message_.value(x...);
|
||||
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
if (this->has_data_) {
|
||||
// For optional mode, check return_response (second arg) to decide if client wants data
|
||||
// Use nested if constexpr to avoid compile error when tuple doesn't have enough elements
|
||||
// (std::tuple_element_t is evaluated before the && short-circuit, so we must nest)
|
||||
if constexpr (sizeof...(Ts) >= 2) {
|
||||
if constexpr (std::is_same_v<std::tuple_element_t<1, std::tuple<Ts...>>, bool>) {
|
||||
if (this->is_optional_mode_) {
|
||||
bool return_response = std::get<1>(args);
|
||||
if (!return_response) {
|
||||
// Client doesn't want response data, just send success/error
|
||||
this->parent_->send_action_response(call_id, success, error_message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Build and send JSON response
|
||||
json::JsonBuilder builder;
|
||||
this->json_builder_(x..., builder.root());
|
||||
std::string json_str = builder.serialize();
|
||||
this->parent_->send_action_response(call_id, success, error_message,
|
||||
reinterpret_cast<const uint8_t *>(json_str.data()), json_str.size());
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
this->parent_->send_action_response(call_id, success, error_message);
|
||||
}
|
||||
|
||||
protected:
|
||||
APIServer *parent_;
|
||||
TemplatableValue<bool, Ts...> success_{true};
|
||||
TemplatableValue<std::string, Ts...> error_message_{""};
|
||||
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
|
||||
std::function<void(Ts..., JsonObject)> json_builder_;
|
||||
bool has_data_{false};
|
||||
#endif
|
||||
bool is_optional_mode_{false};
|
||||
};
|
||||
|
||||
// Action to unregister a service call after execution completes
|
||||
// Automatically appended to the end of action lists for non-none response modes
|
||||
template<typename... Ts> class APIUnregisterServiceCallAction : public Action<Ts...> {
|
||||
public:
|
||||
explicit APIUnregisterServiceCallAction(APIServer *parent) : parent_(parent) {}
|
||||
|
||||
void play(const Ts &...x) override {
|
||||
// Extract call_id from first argument - same convention as APIRespondAction
|
||||
auto args = std::make_tuple(x...);
|
||||
uint32_t call_id = std::get<0>(args);
|
||||
if (call_id != 0) {
|
||||
this->parent_->unregister_active_action_call(call_id);
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
APIServer *parent_;
|
||||
};
|
||||
|
||||
} // namespace esphome::api
|
||||
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
|
||||
|
||||
@@ -44,7 +44,7 @@ CONFIG_SCHEMA = (
|
||||
cv.Optional(ble_client.CONF_BLE_CLIENT_ID): cv.invalid(
|
||||
"The 'ble_client_id' option has been removed. Please migrate "
|
||||
"to the new `bedjet_id` option in the `bedjet` component.\n"
|
||||
"See https://esphome.io/components/climate/bedjet.html"
|
||||
"See https://esphome.io/components/climate/bedjet/"
|
||||
),
|
||||
cv.Optional(CONF_TIME_ID): cv.invalid(
|
||||
"The 'time_id' option has been moved to the `bedjet` component."
|
||||
|
||||
@@ -34,13 +34,20 @@ void BinarySensor::publish_initial_state(bool new_state) {
|
||||
void BinarySensor::send_state_internal(bool new_state) {
|
||||
// copy the new state to the visible property for backwards compatibility, before any callbacks
|
||||
this->state = new_state;
|
||||
// Note that set_state_ de-dups and will only trigger callbacks if the state has actually changed
|
||||
if (this->set_state_(new_state)) {
|
||||
ESP_LOGD(TAG, "'%s': New state is %s", this->get_name().c_str(), ONOFF(new_state));
|
||||
// Note that set_new_state_ de-dups and will only trigger callbacks if the state has actually changed
|
||||
this->set_new_state(new_state);
|
||||
}
|
||||
|
||||
bool BinarySensor::set_new_state(const optional<bool> &new_state) {
|
||||
if (StatefulEntityBase::set_new_state(new_state)) {
|
||||
// weirdly, this file could be compiled even without USE_BINARY_SENSOR defined
|
||||
#if defined(USE_BINARY_SENSOR) && defined(USE_CONTROLLER_REGISTRY)
|
||||
ControllerRegistry::notify_binary_sensor_update(this);
|
||||
#endif
|
||||
ESP_LOGD(TAG, "'%s': %s", this->get_name().c_str(), ONOFFMAYBE(new_state));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void BinarySensor::add_filter(Filter *filter) {
|
||||
|
||||
@@ -61,6 +61,8 @@ class BinarySensor : public StatefulEntityBase<bool>, public EntityBase_DeviceCl
|
||||
|
||||
protected:
|
||||
Filter *filter_list_{nullptr};
|
||||
|
||||
bool set_new_state(const optional<bool> &new_state) override;
|
||||
};
|
||||
|
||||
class BinarySensorInitiallyOff : public BinarySensor {
|
||||
|
||||
@@ -69,7 +69,7 @@ CONFIG_SCHEMA = cv.All(
|
||||
cv.only_on_esp8266,
|
||||
cv.All(
|
||||
cv.only_on_esp32,
|
||||
esp32.only_on_variant(supported=[esp32.const.VARIANT_ESP32]),
|
||||
esp32.only_on_variant(supported=[esp32.VARIANT_ESP32]),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -152,12 +152,12 @@ CONFIG_MAP = {
|
||||
CONF_OUTPUT_POWER: cv.float_range(min=-30.0, max=11.0),
|
||||
CONF_RX_ATTENUATION: cv.enum(RX_ATTENUATION, upper=False),
|
||||
CONF_DC_BLOCKING_FILTER: cv.boolean,
|
||||
CONF_FREQUENCY: cv.float_range(min=300000.0, max=928000.0),
|
||||
CONF_IF_FREQUENCY: cv.float_range(min=25, max=788),
|
||||
CONF_FILTER_BANDWIDTH: cv.float_range(min=58.0, max=812.0),
|
||||
CONF_FREQUENCY: cv.All(cv.frequency, cv.float_range(min=300000000, max=928000000)),
|
||||
CONF_IF_FREQUENCY: cv.All(cv.frequency, cv.float_range(min=25000, max=788000)),
|
||||
CONF_FILTER_BANDWIDTH: cv.All(cv.frequency, cv.float_range(min=58000, max=812000)),
|
||||
CONF_CHANNEL: cv.uint8_t,
|
||||
CONF_CHANNEL_SPACING: cv.float_range(min=25, max=405),
|
||||
CONF_FSK_DEVIATION: cv.float_range(min=1.5, max=381),
|
||||
CONF_CHANNEL_SPACING: cv.All(cv.frequency, cv.float_range(min=25000, max=405000)),
|
||||
CONF_FSK_DEVIATION: cv.All(cv.frequency, cv.float_range(min=1500, max=381000)),
|
||||
CONF_MSK_DEVIATION: cv.int_range(min=1, max=8),
|
||||
CONF_SYMBOL_RATE: cv.float_range(min=600, max=500000),
|
||||
CONF_SYNC_MODE: cv.enum(SYNC_MODE, upper=False),
|
||||
|
||||
@@ -160,18 +160,17 @@ void CC1101Component::dump_config() {
|
||||
"4-FSK", "UNUSED", "UNUSED", "MSK"};
|
||||
int32_t freq = static_cast<int32_t>(this->state_.FREQ2 << 16 | this->state_.FREQ1 << 8 | this->state_.FREQ0) *
|
||||
XTAL_FREQUENCY / (1 << 16);
|
||||
float symbol_rate =
|
||||
(((256.0f + this->state_.DRATE_M) * (1 << this->state_.DRATE_E)) / (1 << 28)) * XTAL_FREQUENCY * 1000.0f;
|
||||
float symbol_rate = (((256.0f + this->state_.DRATE_M) * (1 << this->state_.DRATE_E)) / (1 << 28)) * XTAL_FREQUENCY;
|
||||
float bw = XTAL_FREQUENCY / (8.0f * (4 + this->state_.CHANBW_M) * (1 << this->state_.CHANBW_E));
|
||||
ESP_LOGCONFIG(TAG, "CC1101:");
|
||||
LOG_PIN(" CS Pin: ", this->cs_);
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Chip ID: 0x%04X\n"
|
||||
" Frequency: %" PRId32 " kHz\n"
|
||||
" Frequency: %" PRId32 " Hz\n"
|
||||
" Channel: %u\n"
|
||||
" Modulation: %s\n"
|
||||
" Symbol Rate: %.0f baud\n"
|
||||
" Filter Bandwidth: %.1f kHz\n"
|
||||
" Filter Bandwidth: %.1f Hz\n"
|
||||
" Output Power: %.1f dBm",
|
||||
this->chip_id_, freq, this->state_.CHANNR, MODULATION_NAMES[this->state_.MOD_FORMAT & 0x07],
|
||||
symbol_rate, bw, this->output_power_effective_);
|
||||
@@ -289,13 +288,13 @@ void CC1101Component::set_output_power(float value) {
|
||||
int32_t freq = static_cast<int32_t>(this->state_.FREQ2 << 16 | this->state_.FREQ1 << 8 | this->state_.FREQ0) *
|
||||
XTAL_FREQUENCY / (1 << 16);
|
||||
uint8_t a = 0xC0;
|
||||
if (freq >= 300000 && freq <= 348000) {
|
||||
if (freq >= 300000000 && freq <= 348000000) {
|
||||
a = PowerTableItem::find(PA_TABLE_315, sizeof(PA_TABLE_315) / sizeof(PA_TABLE_315[0]), value);
|
||||
} else if (freq >= 378000 && freq <= 464000) {
|
||||
} else if (freq >= 378000000 && freq <= 464000000) {
|
||||
a = PowerTableItem::find(PA_TABLE_433, sizeof(PA_TABLE_433) / sizeof(PA_TABLE_433[0]), value);
|
||||
} else if (freq >= 779000 && freq < 900000) {
|
||||
} else if (freq >= 779000000 && freq < 900000000) {
|
||||
a = PowerTableItem::find(PA_TABLE_868, sizeof(PA_TABLE_868) / sizeof(PA_TABLE_868[0]), value);
|
||||
} else if (freq >= 900000 && freq <= 928000) {
|
||||
} else if (freq >= 900000000 && freq <= 928000000) {
|
||||
a = PowerTableItem::find(PA_TABLE_915, sizeof(PA_TABLE_915) / sizeof(PA_TABLE_915[0]), value);
|
||||
}
|
||||
|
||||
@@ -401,7 +400,7 @@ void CC1101Component::set_msk_deviation(uint8_t value) {
|
||||
void CC1101Component::set_symbol_rate(float value) {
|
||||
uint8_t e;
|
||||
uint32_t m;
|
||||
split_float(value * (1 << 28) / (XTAL_FREQUENCY * 1000), 8, e, m);
|
||||
split_float(value * (1 << 28) / XTAL_FREQUENCY, 8, e, m);
|
||||
this->state_.DRATE_E = e;
|
||||
this->state_.DRATE_M = static_cast<uint8_t>(m);
|
||||
if (this->initialized_) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
namespace esphome::cc1101 {
|
||||
|
||||
static constexpr float XTAL_FREQUENCY = 26000;
|
||||
static constexpr float XTAL_FREQUENCY = 26000000;
|
||||
|
||||
static constexpr uint8_t BUS_BURST = 0x40;
|
||||
static constexpr uint8_t BUS_READ = 0x80;
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
from esphome import automation, pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import esp32, time
|
||||
from esphome.components.esp32 import get_esp32_variant
|
||||
from esphome.components.esp32.const import (
|
||||
from esphome.components.esp32 import (
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C2,
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
get_esp32_variant,
|
||||
)
|
||||
from esphome.config_helpers import filter_source_files_from_platform
|
||||
import esphome.config_validation as cv
|
||||
@@ -54,8 +57,11 @@ WAKEUP_PINS = {
|
||||
],
|
||||
VARIANT_ESP32C2: [0, 1, 2, 3, 4, 5],
|
||||
VARIANT_ESP32C3: [0, 1, 2, 3, 4, 5],
|
||||
VARIANT_ESP32C5: [0, 1, 2, 3, 4, 5, 6, 7],
|
||||
VARIANT_ESP32C6: [0, 1, 2, 3, 4, 5, 6, 7],
|
||||
VARIANT_ESP32C61: [0, 1, 2, 3, 4, 5, 6],
|
||||
VARIANT_ESP32H2: [7, 8, 9, 10, 11, 12, 13, 14],
|
||||
VARIANT_ESP32P4: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
|
||||
VARIANT_ESP32S2: [
|
||||
0,
|
||||
1,
|
||||
@@ -122,8 +128,11 @@ def _validate_ex1_wakeup_mode(value):
|
||||
if value == "ANY_LOW":
|
||||
esp32.only_on_variant(
|
||||
supported=[
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
],
|
||||
@@ -218,7 +227,9 @@ CONFIG_SCHEMA = cv.All(
|
||||
unsupported=[
|
||||
VARIANT_ESP32C2,
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
],
|
||||
msg_prefix="Wakeup from touch",
|
||||
|
||||
@@ -81,7 +81,7 @@ class DeepSleepComponent : public Component {
|
||||
#endif
|
||||
|
||||
#if !defined(USE_ESP32_VARIANT_ESP32C2) && !defined(USE_ESP32_VARIANT_ESP32C3) && \
|
||||
!defined(USE_ESP32_VARIANT_ESP32C6) && !defined(USE_ESP32_VARIANT_ESP32H2)
|
||||
!defined(USE_ESP32_VARIANT_ESP32C6) && !defined(USE_ESP32_VARIANT_ESP32C61) && !defined(USE_ESP32_VARIANT_ESP32H2)
|
||||
void set_touch_wakeup(bool touch_wakeup);
|
||||
#endif
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ namespace deep_sleep {
|
||||
// | ESP32-C3 | | | | ✓ |
|
||||
// | ESP32-C5 | | (✓) | | (✓) |
|
||||
// | ESP32-C6 | | ✓ | | ✓ |
|
||||
// | ESP32-C61 | | ✓ | | ✓ |
|
||||
// | ESP32-H2 | | ✓ | | |
|
||||
//
|
||||
// Notes:
|
||||
@@ -55,7 +56,7 @@ void DeepSleepComponent::set_ext1_wakeup(Ext1Wakeup ext1_wakeup) { this->ext1_wa
|
||||
#endif
|
||||
|
||||
#if !defined(USE_ESP32_VARIANT_ESP32C2) && !defined(USE_ESP32_VARIANT_ESP32C3) && \
|
||||
!defined(USE_ESP32_VARIANT_ESP32C6) && !defined(USE_ESP32_VARIANT_ESP32H2)
|
||||
!defined(USE_ESP32_VARIANT_ESP32C6) && !defined(USE_ESP32_VARIANT_ESP32C61) && !defined(USE_ESP32_VARIANT_ESP32H2)
|
||||
void DeepSleepComponent::set_touch_wakeup(bool touch_wakeup) { this->touch_wakeup_ = touch_wakeup; }
|
||||
#endif
|
||||
|
||||
@@ -121,8 +122,9 @@ void DeepSleepComponent::deep_sleep_() {
|
||||
}
|
||||
#endif
|
||||
|
||||
// GPIO wakeup - C2, C3, C6 only
|
||||
#if defined(USE_ESP32_VARIANT_ESP32C2) || defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6)
|
||||
// GPIO wakeup - C2, C3, C6, C61 only
|
||||
#if defined(USE_ESP32_VARIANT_ESP32C2) || defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32C61)
|
||||
if (this->wakeup_pin_ != nullptr) {
|
||||
const auto gpio_pin = gpio_num_t(this->wakeup_pin_->get_pin());
|
||||
if (this->wakeup_pin_->get_flags() & gpio::FLAG_PULLUP) {
|
||||
@@ -155,7 +157,7 @@ void DeepSleepComponent::deep_sleep_() {
|
||||
|
||||
// Touch wakeup - ESP32, S2, S3 only
|
||||
#if !defined(USE_ESP32_VARIANT_ESP32C2) && !defined(USE_ESP32_VARIANT_ESP32C3) && \
|
||||
!defined(USE_ESP32_VARIANT_ESP32C6) && !defined(USE_ESP32_VARIANT_ESP32H2)
|
||||
!defined(USE_ESP32_VARIANT_ESP32C6) && !defined(USE_ESP32_VARIANT_ESP32C61) && !defined(USE_ESP32_VARIANT_ESP32H2)
|
||||
if (this->touch_wakeup_.has_value() && *(this->touch_wakeup_)) {
|
||||
esp_sleep_enable_touchpad_wakeup();
|
||||
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
|
||||
|
||||
@@ -59,6 +59,7 @@ from .const import ( # noqa
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
@@ -126,6 +127,7 @@ CPU_FREQUENCIES = {
|
||||
VARIANT_ESP32C3: get_cpu_frequencies(80, 160),
|
||||
VARIANT_ESP32C5: get_cpu_frequencies(80, 160, 240),
|
||||
VARIANT_ESP32C6: get_cpu_frequencies(80, 120, 160),
|
||||
VARIANT_ESP32C61: get_cpu_frequencies(80, 120, 160),
|
||||
VARIANT_ESP32H2: get_cpu_frequencies(16, 32, 48, 64, 96),
|
||||
VARIANT_ESP32P4: get_cpu_frequencies(40, 360, 400),
|
||||
VARIANT_ESP32S2: get_cpu_frequencies(80, 160, 240),
|
||||
@@ -762,7 +764,7 @@ def _show_framework_migration_message(name: str, variant: str) -> None:
|
||||
+ "Need help? Check out the migration guide:\n"
|
||||
+ color(
|
||||
AnsiFore.BLUE,
|
||||
"https://esphome.io/guides/esp32_arduino_to_idf.html",
|
||||
"https://esphome.io/guides/esp32_arduino_to_idf/",
|
||||
)
|
||||
)
|
||||
_LOGGER.warning(message)
|
||||
|
||||
@@ -4,6 +4,7 @@ from .const import (
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
@@ -17,6 +18,7 @@ STANDARD_BOARDS = {
|
||||
VARIANT_ESP32C3: "esp32-c3-devkitm-1",
|
||||
VARIANT_ESP32C5: "esp32-c5-devkitc-1",
|
||||
VARIANT_ESP32C6: "esp32-c6-devkitm-1",
|
||||
VARIANT_ESP32C61: "esp32-c61-devkitc1-n8r2",
|
||||
VARIANT_ESP32H2: "esp32-h2-devkitm-1",
|
||||
VARIANT_ESP32P4: "esp32-p4-evboard",
|
||||
VARIANT_ESP32S2: "esp32-s2-kaluga-1",
|
||||
@@ -1216,6 +1218,28 @@ ESP32_BOARD_PINS = {
|
||||
"LED_BUILTINB": 4,
|
||||
},
|
||||
"sensesiot_weizen": {},
|
||||
"seeed_xiao_esp32c6": {
|
||||
"D0": 0,
|
||||
"D1": 1,
|
||||
"D2": 2,
|
||||
"D3": 21,
|
||||
"D4": 22,
|
||||
"D5": 23,
|
||||
"D6": 16,
|
||||
"D7": 17,
|
||||
"D8": 19,
|
||||
"D9": 20,
|
||||
"D10": 18,
|
||||
"MTDO": 7,
|
||||
"MTCK": 6,
|
||||
"MTDI": 5,
|
||||
"MTMS": 4,
|
||||
"BOOT": 9,
|
||||
"LED": 8,
|
||||
"LED_BUILTIN": 8,
|
||||
"RF_SWITCH_EN": 3,
|
||||
"RF_ANT_SELECT": 14,
|
||||
},
|
||||
"sg-o_airMon": {},
|
||||
"sparkfun_lora_gateway_1-channel": {"MISO": 12, "MOSI": 13, "SCK": 14, "SS": 16},
|
||||
"tinypico": {},
|
||||
|
||||
@@ -17,6 +17,7 @@ VARIANT_ESP32C2 = "ESP32C2"
|
||||
VARIANT_ESP32C3 = "ESP32C3"
|
||||
VARIANT_ESP32C5 = "ESP32C5"
|
||||
VARIANT_ESP32C6 = "ESP32C6"
|
||||
VARIANT_ESP32C61 = "ESP32C61"
|
||||
VARIANT_ESP32H2 = "ESP32H2"
|
||||
VARIANT_ESP32P4 = "ESP32P4"
|
||||
VARIANT_ESP32S2 = "ESP32S2"
|
||||
@@ -27,6 +28,7 @@ VARIANTS = [
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
@@ -39,6 +41,7 @@ VARIANT_FRIENDLY = {
|
||||
VARIANT_ESP32C3: "ESP32-C3",
|
||||
VARIANT_ESP32C5: "ESP32-C5",
|
||||
VARIANT_ESP32C6: "ESP32-C6",
|
||||
VARIANT_ESP32C61: "ESP32-C61",
|
||||
VARIANT_ESP32H2: "ESP32-H2",
|
||||
VARIANT_ESP32P4: "ESP32-P4",
|
||||
VARIANT_ESP32S2: "ESP32-S2",
|
||||
|
||||
@@ -29,6 +29,7 @@ from .const import (
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
@@ -40,6 +41,7 @@ from .gpio_esp32_c2 import esp32_c2_validate_gpio_pin, esp32_c2_validate_support
|
||||
from .gpio_esp32_c3 import esp32_c3_validate_gpio_pin, esp32_c3_validate_supports
|
||||
from .gpio_esp32_c5 import esp32_c5_validate_gpio_pin, esp32_c5_validate_supports
|
||||
from .gpio_esp32_c6 import esp32_c6_validate_gpio_pin, esp32_c6_validate_supports
|
||||
from .gpio_esp32_c61 import esp32_c61_validate_gpio_pin, esp32_c61_validate_supports
|
||||
from .gpio_esp32_h2 import esp32_h2_validate_gpio_pin, esp32_h2_validate_supports
|
||||
from .gpio_esp32_p4 import esp32_p4_validate_gpio_pin, esp32_p4_validate_supports
|
||||
from .gpio_esp32_s2 import esp32_s2_validate_gpio_pin, esp32_s2_validate_supports
|
||||
@@ -110,6 +112,10 @@ _esp32_validations = {
|
||||
pin_validation=esp32_c6_validate_gpio_pin,
|
||||
usage_validation=esp32_c6_validate_supports,
|
||||
),
|
||||
VARIANT_ESP32C61: ESP32ValidationFunctions(
|
||||
pin_validation=esp32_c61_validate_gpio_pin,
|
||||
usage_validation=esp32_c61_validate_supports,
|
||||
),
|
||||
VARIANT_ESP32H2: ESP32ValidationFunctions(
|
||||
pin_validation=esp32_h2_validate_gpio_pin,
|
||||
usage_validation=esp32_h2_validate_supports,
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import logging
|
||||
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_INPUT, CONF_MODE, CONF_NUMBER
|
||||
from esphome.const import CONF_INPUT, CONF_MODE, CONF_NUMBER, CONF_SCL, CONF_SDA
|
||||
from esphome.pins import check_strapping_pin
|
||||
|
||||
# https://github.com/espressif/esp-idf/blob/master/components/esp_hal_i2c/esp32c5/include/hal/i2c_ll.h
|
||||
_ESP32C5_I2C_LP_PINS = {"SDA": 2, "SCL": 3}
|
||||
|
||||
_ESP32C5_SPI_PSRAM_PINS = {
|
||||
16: "SPICS0",
|
||||
17: "SPIQ",
|
||||
@@ -43,3 +46,13 @@ def esp32_c5_validate_supports(value):
|
||||
|
||||
check_strapping_pin(value, _ESP32C5_STRAPPING_PINS, _LOGGER)
|
||||
return value
|
||||
|
||||
|
||||
def esp32_c5_validate_lp_i2c(value):
|
||||
lp_sda_pin = _ESP32C5_I2C_LP_PINS["SDA"]
|
||||
lp_scl_pin = _ESP32C5_I2C_LP_PINS["SCL"]
|
||||
if int(value[CONF_SDA]) != lp_sda_pin or int(value[CONF_SCL]) != lp_scl_pin:
|
||||
raise cv.Invalid(
|
||||
f"Low power i2c interface is only supported on GPIO{lp_sda_pin} SDA and GPIO{lp_scl_pin} SCL for ESP32-C5"
|
||||
)
|
||||
return value
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import logging
|
||||
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_INPUT, CONF_MODE, CONF_NUMBER
|
||||
from esphome.const import CONF_INPUT, CONF_MODE, CONF_NUMBER, CONF_SCL, CONF_SDA
|
||||
from esphome.pins import check_strapping_pin
|
||||
|
||||
# https://github.com/espressif/esp-idf/blob/master/components/esp_hal_i2c/esp32c6/include/hal/i2c_ll.h
|
||||
_ESP32C6_I2C_LP_PINS = {"SDA": 6, "SCL": 7}
|
||||
|
||||
_ESP32C6_SPI_PSRAM_PINS = {
|
||||
24: "SPICS0",
|
||||
25: "SPIQ",
|
||||
@@ -43,3 +46,13 @@ def esp32_c6_validate_supports(value):
|
||||
|
||||
check_strapping_pin(value, _ESP32C6_STRAPPING_PINS, _LOGGER)
|
||||
return value
|
||||
|
||||
|
||||
def esp32_c6_validate_lp_i2c(value):
|
||||
lp_sda_pin = _ESP32C6_I2C_LP_PINS["SDA"]
|
||||
lp_scl_pin = _ESP32C6_I2C_LP_PINS["SCL"]
|
||||
if int(value[CONF_SDA]) != lp_sda_pin or int(value[CONF_SCL]) != lp_scl_pin:
|
||||
raise cv.Invalid(
|
||||
f"Low power i2c interface is only supported on GPIO{lp_sda_pin} SDA and GPIO{lp_scl_pin} SCL for ESP32-C6"
|
||||
)
|
||||
return value
|
||||
|
||||
46
esphome/components/esp32/gpio_esp32_c61.py
Normal file
46
esphome/components/esp32/gpio_esp32_c61.py
Normal file
@@ -0,0 +1,46 @@
|
||||
import logging
|
||||
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_INPUT, CONF_MODE, CONF_NUMBER
|
||||
from esphome.pins import check_strapping_pin
|
||||
|
||||
# GPIO14-17, GPIO19-21 are used for SPI flash/PSRAM
|
||||
_ESP32C61_SPI_PSRAM_PINS = {
|
||||
14: "SPICS0",
|
||||
15: "SPICLK",
|
||||
16: "SPID",
|
||||
17: "SPIQ",
|
||||
19: "SPIWP",
|
||||
20: "SPIHD",
|
||||
21: "VDD_SPI",
|
||||
}
|
||||
|
||||
_ESP32C61_STRAPPING_PINS = {8, 9}
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def esp32_c61_validate_gpio_pin(value):
|
||||
if value < 0 or value > 29:
|
||||
raise cv.Invalid(f"Invalid pin number: {value} (must be 0-29)")
|
||||
if value in _ESP32C61_SPI_PSRAM_PINS:
|
||||
raise cv.Invalid(
|
||||
f"This pin cannot be used on ESP32-C61s and is already used by the SPI/PSRAM interface (function: {_ESP32C61_SPI_PSRAM_PINS[value]})"
|
||||
)
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def esp32_c61_validate_supports(value):
|
||||
num = value[CONF_NUMBER]
|
||||
mode = value[CONF_MODE]
|
||||
is_input = mode[CONF_INPUT]
|
||||
|
||||
if num < 0 or num > 29:
|
||||
raise cv.Invalid(f"Invalid pin number: {num} (must be 0-29)")
|
||||
if is_input:
|
||||
# All ESP32-C61 pins support input mode
|
||||
pass
|
||||
|
||||
check_strapping_pin(value, _ESP32C61_STRAPPING_PINS, _LOGGER)
|
||||
return value
|
||||
@@ -1,9 +1,12 @@
|
||||
import logging
|
||||
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_INPUT, CONF_MODE, CONF_NUMBER
|
||||
from esphome.const import CONF_INPUT, CONF_MODE, CONF_NUMBER, CONF_SCL, CONF_SDA
|
||||
from esphome.pins import check_strapping_pin
|
||||
|
||||
# https://documentation.espressif.com/esp32-p4-chip-revision-v1.3_datasheet_en.pdf
|
||||
_ESP32P4_LP_PINS = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
|
||||
|
||||
_ESP32P4_USB_JTAG_PINS = {24, 25}
|
||||
|
||||
_ESP32P4_STRAPPING_PINS = {34, 35, 36, 37, 38}
|
||||
@@ -36,3 +39,14 @@ def esp32_p4_validate_supports(value):
|
||||
pass
|
||||
check_strapping_pin(value, _ESP32P4_STRAPPING_PINS, _LOGGER)
|
||||
return value
|
||||
|
||||
|
||||
def esp32_p4_validate_lp_i2c(value):
|
||||
if (
|
||||
int(value[CONF_SDA]) not in _ESP32P4_LP_PINS
|
||||
or int(value[CONF_SCL]) not in _ESP32P4_LP_PINS
|
||||
):
|
||||
raise cv.Invalid(
|
||||
f"Low power i2c interface for ESP32-P4 is only supported on low power interface GPIO{min(_ESP32P4_LP_PINS)} - GPIO{max(_ESP32P4_LP_PINS)}"
|
||||
)
|
||||
return value
|
||||
|
||||
@@ -4,15 +4,17 @@ from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import canbus
|
||||
from esphome.components.canbus import CONF_BIT_RATE, CanbusComponent, CanSpeed
|
||||
from esphome.components.esp32 import get_esp32_variant
|
||||
from esphome.components.esp32.const import (
|
||||
from esphome.components.esp32 import (
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
get_esp32_variant,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
@@ -58,14 +60,18 @@ CAN_SPEEDS_ESP32_S2 = {
|
||||
|
||||
CAN_SPEEDS_ESP32_S3 = {**CAN_SPEEDS_ESP32_S2}
|
||||
CAN_SPEEDS_ESP32_C3 = {**CAN_SPEEDS_ESP32_S2}
|
||||
CAN_SPEEDS_ESP32_C5 = {**CAN_SPEEDS_ESP32_S2}
|
||||
CAN_SPEEDS_ESP32_C6 = {**CAN_SPEEDS_ESP32_S2}
|
||||
CAN_SPEEDS_ESP32_C61 = {**CAN_SPEEDS_ESP32_S2}
|
||||
CAN_SPEEDS_ESP32_H2 = {**CAN_SPEEDS_ESP32_S2}
|
||||
CAN_SPEEDS_ESP32_P4 = {**CAN_SPEEDS_ESP32_S2}
|
||||
|
||||
CAN_SPEEDS = {
|
||||
VARIANT_ESP32: CAN_SPEEDS_ESP32,
|
||||
VARIANT_ESP32C3: CAN_SPEEDS_ESP32_C3,
|
||||
VARIANT_ESP32C5: CAN_SPEEDS_ESP32_C5,
|
||||
VARIANT_ESP32C6: CAN_SPEEDS_ESP32_C6,
|
||||
VARIANT_ESP32C61: CAN_SPEEDS_ESP32_C61,
|
||||
VARIANT_ESP32H2: CAN_SPEEDS_ESP32_H2,
|
||||
VARIANT_ESP32P4: CAN_SPEEDS_ESP32_P4,
|
||||
VARIANT_ESP32S2: CAN_SPEEDS_ESP32_S2,
|
||||
|
||||
@@ -16,8 +16,9 @@ static const char *const TAG = "esp32_can";
|
||||
|
||||
static bool get_bitrate(canbus::CanSpeed bitrate, twai_timing_config_t *t_config) {
|
||||
switch (bitrate) {
|
||||
#if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32H2) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
#if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32C61) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
case canbus::CAN_1KBPS:
|
||||
*t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_1KBITS();
|
||||
return true;
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import output
|
||||
from esphome.components.esp32 import get_esp32_variant
|
||||
from esphome.components.esp32.const import VARIANT_ESP32, VARIANT_ESP32S2
|
||||
from esphome.components.esp32 import VARIANT_ESP32, VARIANT_ESP32S2, get_esp32_variant
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_NUMBER, CONF_PIN
|
||||
|
||||
|
||||
@@ -40,8 +40,8 @@ CONFIG_SCHEMA = cv.All(
|
||||
),
|
||||
esp32.only_on_variant(
|
||||
supported=[
|
||||
esp32.const.VARIANT_ESP32H2,
|
||||
esp32.const.VARIANT_ESP32P4,
|
||||
esp32.VARIANT_ESP32H2,
|
||||
esp32.VARIANT_ESP32P4,
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
@@ -9,7 +9,7 @@ def validate_clock_resolution():
|
||||
cv.only_on_esp32(value)
|
||||
value = cv.int_(value)
|
||||
variant = esp32.get_esp32_variant()
|
||||
if variant == esp32.const.VARIANT_ESP32H2 and value > 32000000:
|
||||
if variant == esp32.VARIANT_ESP32H2 and value > 32000000:
|
||||
raise cv.Invalid(
|
||||
f"ESP32 variant {variant} has a max clock_resolution of 32000000."
|
||||
)
|
||||
|
||||
@@ -91,7 +91,7 @@ CONFIG_SCHEMA = cv.All(
|
||||
cv.Optional(CONF_IS_WRGB, default=False): cv.boolean,
|
||||
cv.Optional(CONF_USE_DMA): cv.All(
|
||||
esp32.only_on_variant(
|
||||
supported=[esp32.const.VARIANT_ESP32P4, esp32.const.VARIANT_ESP32S3]
|
||||
supported=[esp32.VARIANT_ESP32P4, esp32.VARIANT_ESP32S3]
|
||||
),
|
||||
cv.boolean,
|
||||
),
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import esp32
|
||||
from esphome.components.esp32 import get_esp32_variant, gpio
|
||||
from esphome.components.esp32.const import (
|
||||
from esphome.components.esp32 import (
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
get_esp32_variant,
|
||||
gpio,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
@@ -255,9 +256,9 @@ CONFIG_SCHEMA = cv.All(
|
||||
cv.has_none_or_all_keys(CONF_WATERPROOF_GUARD_RING, CONF_WATERPROOF_SHIELD_DRIVER),
|
||||
esp32.only_on_variant(
|
||||
supported=[
|
||||
esp32.const.VARIANT_ESP32,
|
||||
esp32.const.VARIANT_ESP32S2,
|
||||
esp32.const.VARIANT_ESP32S3,
|
||||
esp32.VARIANT_ESP32,
|
||||
esp32.VARIANT_ESP32S2,
|
||||
esp32.VARIANT_ESP32S3,
|
||||
]
|
||||
),
|
||||
validate_variant_vars,
|
||||
|
||||
@@ -3,16 +3,17 @@ import logging
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.esp32 import (
|
||||
add_idf_component,
|
||||
add_idf_sdkconfig_option,
|
||||
get_esp32_variant,
|
||||
)
|
||||
from esphome.components.esp32.const import (
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
add_idf_component,
|
||||
add_idf_sdkconfig_option,
|
||||
get_esp32_variant,
|
||||
)
|
||||
from esphome.components.network import ip_address_literal
|
||||
from esphome.components.spi import CONF_INTERFACE_INDEX, get_spi_interface
|
||||
@@ -303,7 +304,14 @@ def _final_validate_spi(config):
|
||||
return
|
||||
if spi_configs := fv.full_config.get().get(CONF_SPI):
|
||||
variant = get_esp32_variant()
|
||||
if variant in (VARIANT_ESP32C3, VARIANT_ESP32S2, VARIANT_ESP32S3):
|
||||
if variant in (
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
):
|
||||
spi_host = "SPI2_HOST"
|
||||
else:
|
||||
spi_host = "SPI3_HOST"
|
||||
|
||||
@@ -87,8 +87,8 @@ void EthernetComponent::setup() {
|
||||
.intr_flags = 0,
|
||||
};
|
||||
|
||||
#if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32S2) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
#if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C5) || defined(USE_ESP32_VARIANT_ESP32C6) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32C61) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
auto host = SPI2_HOST;
|
||||
#else
|
||||
auto host = SPI3_HOST;
|
||||
|
||||
1
esphome/components/hlw8032/__init__.py
Normal file
1
esphome/components/hlw8032/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
CODEOWNERS = ["@rici4kubicek"]
|
||||
194
esphome/components/hlw8032/hlw8032.cpp
Normal file
194
esphome/components/hlw8032/hlw8032.cpp
Normal file
@@ -0,0 +1,194 @@
|
||||
#include "hlw8032.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include <cinttypes>
|
||||
|
||||
namespace esphome::hlw8032 {
|
||||
|
||||
static const char *const TAG = "hlw8032";
|
||||
|
||||
static constexpr uint8_t STATE_REG_OFFSET = 0;
|
||||
static constexpr uint8_t VOLTAGE_PARAM_OFFSET = 2;
|
||||
static constexpr uint8_t VOLTAGE_REG_OFFSET = 5;
|
||||
static constexpr uint8_t CURRENT_PARAM_OFFSET = 8;
|
||||
static constexpr uint8_t CURRENT_REG_OFFSET = 11;
|
||||
static constexpr uint8_t POWER_PARAM_OFFSET = 14;
|
||||
static constexpr uint8_t POWER_REG_OFFSET = 17;
|
||||
static constexpr uint8_t DATA_UPDATE_REG_OFFSET = 20;
|
||||
static constexpr uint8_t CHECKSUM_REG_OFFSET = 23;
|
||||
static constexpr uint8_t PARAM_REG_USABLE_BIT = (1 << 0);
|
||||
static constexpr uint8_t POWER_OVERFLOW_BIT = (1 << 1);
|
||||
static constexpr uint8_t CURRENT_OVERFLOW_BIT = (1 << 2);
|
||||
static constexpr uint8_t VOLTAGE_OVERFLOW_BIT = (1 << 3);
|
||||
static constexpr uint8_t HAVE_POWER_BIT = (1 << 4);
|
||||
static constexpr uint8_t HAVE_CURRENT_BIT = (1 << 5);
|
||||
static constexpr uint8_t HAVE_VOLTAGE_BIT = (1 << 6);
|
||||
static constexpr uint8_t CHECK_REG = 0x5A;
|
||||
static constexpr uint8_t STATE_REG_CORRECTION_FUNC_NORMAL = 0x55;
|
||||
static constexpr uint8_t STATE_REG_CORRECTION_FUNC_FAIL = 0xAA;
|
||||
static constexpr uint8_t STATE_REG_CORRECTION_MASK = 0xF0;
|
||||
static constexpr uint8_t STATE_REG_OVERFLOW_MASK = 0xF;
|
||||
static constexpr uint8_t PACKET_LENGTH = 24;
|
||||
|
||||
void HLW8032Component::loop() {
|
||||
while (this->available()) {
|
||||
uint8_t data = this->read();
|
||||
if (!this->header_found_) {
|
||||
if ((data == STATE_REG_CORRECTION_FUNC_NORMAL) || (data == STATE_REG_CORRECTION_FUNC_FAIL) ||
|
||||
(data & STATE_REG_CORRECTION_MASK) == STATE_REG_CORRECTION_MASK) {
|
||||
this->header_found_ = true;
|
||||
this->raw_data_[0] = data;
|
||||
}
|
||||
} else if (data == CHECK_REG) {
|
||||
this->raw_data_[1] = data;
|
||||
this->raw_data_index_ = 2;
|
||||
this->check_ = 0;
|
||||
} else if (this->raw_data_index_ >= 2 && this->raw_data_index_ < PACKET_LENGTH) {
|
||||
this->raw_data_[this->raw_data_index_++] = data;
|
||||
if (this->raw_data_index_ < PACKET_LENGTH) {
|
||||
this->check_ += data;
|
||||
} else if (this->raw_data_index_ == PACKET_LENGTH) {
|
||||
if (this->check_ == this->raw_data_[CHECKSUM_REG_OFFSET]) {
|
||||
this->parse_data_();
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Invalid checksum: 0x%02X != 0x%02X", this->check_, this->raw_data_[CHECKSUM_REG_OFFSET]);
|
||||
}
|
||||
this->raw_data_index_ = 0;
|
||||
this->header_found_ = false;
|
||||
memset(this->raw_data_, 0, PACKET_LENGTH);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t HLW8032Component::read_uint24_(uint8_t offset) {
|
||||
return encode_uint24(this->raw_data_[offset], this->raw_data_[offset + 1], this->raw_data_[offset + 2]);
|
||||
}
|
||||
|
||||
void HLW8032Component::parse_data_() {
|
||||
// Parse header
|
||||
uint8_t state_reg = this->raw_data_[STATE_REG_OFFSET];
|
||||
|
||||
if (state_reg == STATE_REG_CORRECTION_FUNC_FAIL) {
|
||||
ESP_LOGE(TAG, "The chip's function of error correction fails.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse data frame
|
||||
uint32_t voltage_parameter = this->read_uint24_(VOLTAGE_PARAM_OFFSET);
|
||||
uint32_t voltage_reg = this->read_uint24_(VOLTAGE_REG_OFFSET);
|
||||
uint32_t current_parameter = this->read_uint24_(CURRENT_PARAM_OFFSET);
|
||||
uint32_t current_reg = this->read_uint24_(CURRENT_REG_OFFSET);
|
||||
uint32_t power_parameter = this->read_uint24_(POWER_PARAM_OFFSET);
|
||||
uint32_t power_reg = this->read_uint24_(POWER_REG_OFFSET);
|
||||
uint8_t data_update_register = this->raw_data_[DATA_UPDATE_REG_OFFSET];
|
||||
|
||||
bool have_power = data_update_register & HAVE_POWER_BIT;
|
||||
bool have_current = data_update_register & HAVE_CURRENT_BIT;
|
||||
bool have_voltage = data_update_register & HAVE_VOLTAGE_BIT;
|
||||
|
||||
bool power_cycle_exceeds_range = false;
|
||||
bool parameter_regs_usable = true;
|
||||
|
||||
if ((state_reg & STATE_REG_CORRECTION_MASK) == STATE_REG_CORRECTION_MASK) {
|
||||
if (state_reg & STATE_REG_OVERFLOW_MASK) {
|
||||
if (state_reg & VOLTAGE_OVERFLOW_BIT) {
|
||||
have_voltage = false;
|
||||
}
|
||||
if (state_reg & CURRENT_OVERFLOW_BIT) {
|
||||
have_current = false;
|
||||
}
|
||||
if (state_reg & POWER_OVERFLOW_BIT) {
|
||||
have_power = false;
|
||||
}
|
||||
if (state_reg & PARAM_REG_USABLE_BIT) {
|
||||
parameter_regs_usable = false;
|
||||
}
|
||||
|
||||
ESP_LOGW(TAG,
|
||||
"Reports: (0x%02X)\n"
|
||||
" Voltage REG overflows: %s\n"
|
||||
" Current REG overflows: %s\n"
|
||||
" Power REG overflows: %s\n"
|
||||
" Voltage/Current/Power Parameter REGs not usable: %s\n",
|
||||
state_reg, YESNO(!have_voltage), YESNO(!have_current), YESNO(!have_power),
|
||||
YESNO(!parameter_regs_usable));
|
||||
|
||||
if (!parameter_regs_usable) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
power_cycle_exceeds_range = have_power;
|
||||
}
|
||||
|
||||
ESP_LOGVV(TAG,
|
||||
"Parsed data:\n"
|
||||
" Voltage: Parameter REG 0x%06" PRIX32 ", REG 0x%06" PRIX32 "\n"
|
||||
" Current: Parameter REG 0x%06" PRIX32 ", REG 0x%06" PRIX32 "\n"
|
||||
" Power: Parameter REG 0x%06" PRIX32 ", REG 0x%06" PRIX32 "\n"
|
||||
" Data Update: REG 0x%02" PRIX8 "\n",
|
||||
voltage_parameter, voltage_reg, current_parameter, current_reg, power_parameter, power_reg,
|
||||
data_update_register);
|
||||
|
||||
const float current_multiplier = 1 / (this->current_resistor_ * 1000);
|
||||
|
||||
float voltage = 0.0f;
|
||||
if (have_voltage && voltage_reg) {
|
||||
voltage = float(voltage_parameter) * this->voltage_divider_ / float(voltage_reg);
|
||||
}
|
||||
if (this->voltage_sensor_ != nullptr) {
|
||||
this->voltage_sensor_->publish_state(voltage);
|
||||
}
|
||||
|
||||
float power = 0.0f;
|
||||
if (have_power && power_reg && !power_cycle_exceeds_range) {
|
||||
power = (float(power_parameter) / float(power_reg)) * this->voltage_divider_ * current_multiplier;
|
||||
}
|
||||
if (this->power_sensor_ != nullptr) {
|
||||
this->power_sensor_->publish_state(power);
|
||||
}
|
||||
|
||||
float current = 0.0f;
|
||||
if (have_current && current_reg) {
|
||||
current = float(current_parameter) * current_multiplier / float(current_reg);
|
||||
}
|
||||
if (this->current_sensor_ != nullptr) {
|
||||
this->current_sensor_->publish_state(current);
|
||||
}
|
||||
|
||||
float pf = NAN;
|
||||
const float apparent_power = voltage * current;
|
||||
if (have_voltage && have_current) {
|
||||
if (have_power || power_cycle_exceeds_range) {
|
||||
if (apparent_power > 0) {
|
||||
pf = power / apparent_power;
|
||||
if (pf < 0 || pf > 1) {
|
||||
ESP_LOGD(TAG, "Impossible power factor: %.4f not in interval [0, 1]", pf);
|
||||
pf = NAN;
|
||||
}
|
||||
} else if (apparent_power == 0 && power == 0) {
|
||||
// No load, report ideal power factor
|
||||
pf = 1.0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this->apparent_power_sensor_ != nullptr) {
|
||||
this->apparent_power_sensor_->publish_state(apparent_power);
|
||||
}
|
||||
if (this->power_factor_sensor_ != nullptr) {
|
||||
this->power_factor_sensor_->publish_state(pf);
|
||||
}
|
||||
}
|
||||
|
||||
void HLW8032Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"Configuration:\n"
|
||||
" Current resistor: %.1f mΩ\n"
|
||||
" Voltage Divider: %.3f",
|
||||
this->current_resistor_ * 1000.0f, this->voltage_divider_);
|
||||
LOG_SENSOR(" ", "Voltage", this->voltage_sensor_);
|
||||
LOG_SENSOR(" ", "Current", this->current_sensor_);
|
||||
LOG_SENSOR(" ", "Power", this->power_sensor_);
|
||||
LOG_SENSOR(" ", "Apparent Power", this->apparent_power_sensor_);
|
||||
LOG_SENSOR(" ", "Power Factor", this->power_factor_sensor_);
|
||||
}
|
||||
} // namespace esphome::hlw8032
|
||||
44
esphome/components/hlw8032/hlw8032.h
Normal file
44
esphome/components/hlw8032/hlw8032.h
Normal file
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
#include "esphome/components/uart/uart.h"
|
||||
|
||||
namespace esphome::hlw8032 {
|
||||
|
||||
class HLW8032Component : public Component, public uart::UARTDevice {
|
||||
public:
|
||||
void loop() override;
|
||||
void dump_config() override;
|
||||
|
||||
void set_current_resistor(float current_resistor) { this->current_resistor_ = current_resistor; }
|
||||
void set_voltage_divider(float voltage_divider) { this->voltage_divider_ = voltage_divider; }
|
||||
void set_voltage_sensor(sensor::Sensor *voltage_sensor) { this->voltage_sensor_ = voltage_sensor; }
|
||||
void set_current_sensor(sensor::Sensor *current_sensor) { this->current_sensor_ = current_sensor; }
|
||||
void set_power_sensor(sensor::Sensor *power_sensor) { this->power_sensor_ = power_sensor; }
|
||||
void set_apparent_power_sensor(sensor::Sensor *apparent_power_sensor) {
|
||||
this->apparent_power_sensor_ = apparent_power_sensor;
|
||||
}
|
||||
void set_power_factor_sensor(sensor::Sensor *power_factor_sensor) {
|
||||
this->power_factor_sensor_ = power_factor_sensor;
|
||||
}
|
||||
|
||||
protected:
|
||||
void parse_data_();
|
||||
uint32_t read_uint24_(uint8_t offset);
|
||||
|
||||
sensor::Sensor *voltage_sensor_{nullptr};
|
||||
sensor::Sensor *current_sensor_{nullptr};
|
||||
sensor::Sensor *power_sensor_{nullptr};
|
||||
sensor::Sensor *apparent_power_sensor_{nullptr};
|
||||
sensor::Sensor *power_factor_sensor_{nullptr};
|
||||
|
||||
float current_resistor_{0.001f};
|
||||
float voltage_divider_{1.720f};
|
||||
uint8_t raw_data_[24]{};
|
||||
uint8_t check_{0};
|
||||
uint8_t raw_data_index_{0};
|
||||
bool header_found_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::hlw8032
|
||||
93
esphome/components/hlw8032/sensor.py
Normal file
93
esphome/components/hlw8032/sensor.py
Normal file
@@ -0,0 +1,93 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import sensor, uart
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_APPARENT_POWER,
|
||||
CONF_CURRENT,
|
||||
CONF_CURRENT_RESISTOR,
|
||||
CONF_ID,
|
||||
CONF_POWER,
|
||||
CONF_POWER_FACTOR,
|
||||
CONF_VOLTAGE,
|
||||
CONF_VOLTAGE_DIVIDER,
|
||||
DEVICE_CLASS_APPARENT_POWER,
|
||||
DEVICE_CLASS_CURRENT,
|
||||
DEVICE_CLASS_POWER,
|
||||
DEVICE_CLASS_POWER_FACTOR,
|
||||
DEVICE_CLASS_VOLTAGE,
|
||||
STATE_CLASS_MEASUREMENT,
|
||||
UNIT_AMPERE,
|
||||
UNIT_VOLT,
|
||||
UNIT_VOLT_AMPS,
|
||||
UNIT_WATT,
|
||||
)
|
||||
|
||||
DEPENDENCIES = ["uart"]
|
||||
|
||||
hlw8032_ns = cg.esphome_ns.namespace("hlw8032")
|
||||
HLW8032Component = hlw8032_ns.class_("HLW8032Component", cg.Component, uart.UARTDevice)
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(HLW8032Component),
|
||||
cv.Optional(CONF_VOLTAGE): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_VOLT,
|
||||
accuracy_decimals=1,
|
||||
device_class=DEVICE_CLASS_VOLTAGE,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_CURRENT): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_AMPERE,
|
||||
accuracy_decimals=2,
|
||||
device_class=DEVICE_CLASS_CURRENT,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_POWER): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_WATT,
|
||||
accuracy_decimals=1,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_APPARENT_POWER): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_VOLT_AMPS,
|
||||
accuracy_decimals=1,
|
||||
device_class=DEVICE_CLASS_APPARENT_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_POWER_FACTOR): sensor.sensor_schema(
|
||||
accuracy_decimals=2,
|
||||
device_class=DEVICE_CLASS_POWER_FACTOR,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_CURRENT_RESISTOR, default=0.001): cv.resistance,
|
||||
cv.Optional(CONF_VOLTAGE_DIVIDER, default=1.720): cv.positive_float,
|
||||
}
|
||||
).extend(uart.UART_DEVICE_SCHEMA)
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = uart.final_validate_device_schema(
|
||||
"hlw8032", baud_rate=4800, require_rx=True, data_bits=8, parity="EVEN"
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
await uart.register_uart_device(var, config)
|
||||
|
||||
if voltage_config := config.get(CONF_VOLTAGE):
|
||||
sens = await sensor.new_sensor(voltage_config)
|
||||
cg.add(var.set_voltage_sensor(sens))
|
||||
if current_config := config.get(CONF_CURRENT):
|
||||
sens = await sensor.new_sensor(current_config)
|
||||
cg.add(var.set_current_sensor(sens))
|
||||
if power_config := config.get(CONF_POWER):
|
||||
sens = await sensor.new_sensor(power_config)
|
||||
cg.add(var.set_power_sensor(sens))
|
||||
if apparent_power_config := config.get(CONF_APPARENT_POWER):
|
||||
sens = await sensor.new_sensor(apparent_power_config)
|
||||
cg.add(var.set_apparent_power_sensor(sens))
|
||||
if power_factor_config := config.get(CONF_POWER_FACTOR):
|
||||
sens = await sensor.new_sensor(power_factor_config)
|
||||
cg.add(var.set_power_factor_sensor(sens))
|
||||
cg.add(var.set_current_resistor(config[CONF_CURRENT_RESISTOR]))
|
||||
cg.add(var.set_voltage_divider(config[CONF_VOLTAGE_DIVIDER]))
|
||||
@@ -19,11 +19,10 @@ void HomeassistantBinarySensor::setup() {
|
||||
case PARSE_ON:
|
||||
case PARSE_OFF:
|
||||
bool new_state = val == PARSE_ON;
|
||||
if (this->attribute_.has_value()) {
|
||||
ESP_LOGD(TAG, "'%s::%s': Got attribute state %s", this->entity_id_.c_str(),
|
||||
this->attribute_.value().c_str(), ONOFF(new_state));
|
||||
if (this->attribute_ != nullptr) {
|
||||
ESP_LOGD(TAG, "'%s::%s': Got attribute state %s", this->entity_id_, this->attribute_, ONOFF(new_state));
|
||||
} else {
|
||||
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_.c_str(), ONOFF(new_state));
|
||||
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
|
||||
}
|
||||
if (this->initial_) {
|
||||
this->publish_initial_state(new_state);
|
||||
@@ -37,9 +36,9 @@ void HomeassistantBinarySensor::setup() {
|
||||
}
|
||||
void HomeassistantBinarySensor::dump_config() {
|
||||
LOG_BINARY_SENSOR("", "Homeassistant Binary Sensor", this);
|
||||
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_.c_str());
|
||||
if (this->attribute_.has_value()) {
|
||||
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_.value().c_str());
|
||||
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
|
||||
if (this->attribute_ != nullptr) {
|
||||
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_);
|
||||
}
|
||||
}
|
||||
float HomeassistantBinarySensor::get_setup_priority() const { return setup_priority::AFTER_WIFI; }
|
||||
|
||||
@@ -8,15 +8,15 @@ namespace homeassistant {
|
||||
|
||||
class HomeassistantBinarySensor : public binary_sensor::BinarySensor, public Component {
|
||||
public:
|
||||
void set_entity_id(const std::string &entity_id) { entity_id_ = entity_id; }
|
||||
void set_attribute(const std::string &attribute) { attribute_ = attribute; }
|
||||
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
|
||||
void set_attribute(const char *attribute) { this->attribute_ = attribute; }
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
float get_setup_priority() const override;
|
||||
|
||||
protected:
|
||||
std::string entity_id_;
|
||||
optional<std::string> attribute_;
|
||||
const char *entity_id_{nullptr};
|
||||
const char *attribute_{nullptr};
|
||||
bool initial_{true};
|
||||
};
|
||||
|
||||
|
||||
@@ -12,21 +12,21 @@ static const char *const TAG = "homeassistant.number";
|
||||
void HomeassistantNumber::state_changed_(const std::string &state) {
|
||||
auto number_value = parse_number<float>(state);
|
||||
if (!number_value.has_value()) {
|
||||
ESP_LOGW(TAG, "'%s': Can't convert '%s' to number!", this->entity_id_.c_str(), state.c_str());
|
||||
ESP_LOGW(TAG, "'%s': Can't convert '%s' to number!", this->entity_id_, state.c_str());
|
||||
this->publish_state(NAN);
|
||||
return;
|
||||
}
|
||||
if (this->state == number_value.value()) {
|
||||
return;
|
||||
}
|
||||
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_.c_str(), state.c_str());
|
||||
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, state.c_str());
|
||||
this->publish_state(number_value.value());
|
||||
}
|
||||
|
||||
void HomeassistantNumber::min_retrieved_(const std::string &min) {
|
||||
auto min_value = parse_number<float>(min);
|
||||
if (!min_value.has_value()) {
|
||||
ESP_LOGE(TAG, "'%s': Can't convert 'min' value '%s' to number!", this->entity_id_.c_str(), min.c_str());
|
||||
ESP_LOGE(TAG, "'%s': Can't convert 'min' value '%s' to number!", this->entity_id_, min.c_str());
|
||||
return;
|
||||
}
|
||||
ESP_LOGD(TAG, "'%s': Min retrieved: %s", get_name().c_str(), min.c_str());
|
||||
@@ -36,7 +36,7 @@ void HomeassistantNumber::min_retrieved_(const std::string &min) {
|
||||
void HomeassistantNumber::max_retrieved_(const std::string &max) {
|
||||
auto max_value = parse_number<float>(max);
|
||||
if (!max_value.has_value()) {
|
||||
ESP_LOGE(TAG, "'%s': Can't convert 'max' value '%s' to number!", this->entity_id_.c_str(), max.c_str());
|
||||
ESP_LOGE(TAG, "'%s': Can't convert 'max' value '%s' to number!", this->entity_id_, max.c_str());
|
||||
return;
|
||||
}
|
||||
ESP_LOGD(TAG, "'%s': Max retrieved: %s", get_name().c_str(), max.c_str());
|
||||
@@ -46,7 +46,7 @@ void HomeassistantNumber::max_retrieved_(const std::string &max) {
|
||||
void HomeassistantNumber::step_retrieved_(const std::string &step) {
|
||||
auto step_value = parse_number<float>(step);
|
||||
if (!step_value.has_value()) {
|
||||
ESP_LOGE(TAG, "'%s': Can't convert 'step' value '%s' to number!", this->entity_id_.c_str(), step.c_str());
|
||||
ESP_LOGE(TAG, "'%s': Can't convert 'step' value '%s' to number!", this->entity_id_, step.c_str());
|
||||
return;
|
||||
}
|
||||
ESP_LOGD(TAG, "'%s': Step Retrieved %s", get_name().c_str(), step.c_str());
|
||||
@@ -55,22 +55,19 @@ void HomeassistantNumber::step_retrieved_(const std::string &step) {
|
||||
|
||||
void HomeassistantNumber::setup() {
|
||||
api::global_api_server->subscribe_home_assistant_state(
|
||||
this->entity_id_, nullopt, std::bind(&HomeassistantNumber::state_changed_, this, std::placeholders::_1));
|
||||
this->entity_id_, nullptr, std::bind(&HomeassistantNumber::state_changed_, this, std::placeholders::_1));
|
||||
|
||||
api::global_api_server->get_home_assistant_state(
|
||||
this->entity_id_, optional<std::string>("min"),
|
||||
std::bind(&HomeassistantNumber::min_retrieved_, this, std::placeholders::_1));
|
||||
this->entity_id_, "min", std::bind(&HomeassistantNumber::min_retrieved_, this, std::placeholders::_1));
|
||||
api::global_api_server->get_home_assistant_state(
|
||||
this->entity_id_, optional<std::string>("max"),
|
||||
std::bind(&HomeassistantNumber::max_retrieved_, this, std::placeholders::_1));
|
||||
this->entity_id_, "max", std::bind(&HomeassistantNumber::max_retrieved_, this, std::placeholders::_1));
|
||||
api::global_api_server->get_home_assistant_state(
|
||||
this->entity_id_, optional<std::string>("step"),
|
||||
std::bind(&HomeassistantNumber::step_retrieved_, this, std::placeholders::_1));
|
||||
this->entity_id_, "step", std::bind(&HomeassistantNumber::step_retrieved_, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
void HomeassistantNumber::dump_config() {
|
||||
LOG_NUMBER("", "Homeassistant Number", this);
|
||||
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_.c_str());
|
||||
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
|
||||
}
|
||||
|
||||
float HomeassistantNumber::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
|
||||
|
||||
@@ -11,7 +11,7 @@ namespace homeassistant {
|
||||
|
||||
class HomeassistantNumber : public number::Number, public Component {
|
||||
public:
|
||||
void set_entity_id(const std::string &entity_id) { this->entity_id_ = entity_id; }
|
||||
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
|
||||
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
@@ -25,7 +25,7 @@ class HomeassistantNumber : public number::Number, public Component {
|
||||
|
||||
void control(float value) override;
|
||||
|
||||
std::string entity_id_;
|
||||
const char *entity_id_{nullptr};
|
||||
};
|
||||
} // namespace homeassistant
|
||||
} // namespace esphome
|
||||
|
||||
@@ -12,25 +12,24 @@ void HomeassistantSensor::setup() {
|
||||
this->entity_id_, this->attribute_, [this](const std::string &state) {
|
||||
auto val = parse_number<float>(state);
|
||||
if (!val.has_value()) {
|
||||
ESP_LOGW(TAG, "'%s': Can't convert '%s' to number!", this->entity_id_.c_str(), state.c_str());
|
||||
ESP_LOGW(TAG, "'%s': Can't convert '%s' to number!", this->entity_id_, state.c_str());
|
||||
this->publish_state(NAN);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this->attribute_.has_value()) {
|
||||
ESP_LOGD(TAG, "'%s::%s': Got attribute state %.2f", this->entity_id_.c_str(),
|
||||
this->attribute_.value().c_str(), *val);
|
||||
if (this->attribute_ != nullptr) {
|
||||
ESP_LOGD(TAG, "'%s::%s': Got attribute state %.2f", this->entity_id_, this->attribute_, *val);
|
||||
} else {
|
||||
ESP_LOGD(TAG, "'%s': Got state %.2f", this->entity_id_.c_str(), *val);
|
||||
ESP_LOGD(TAG, "'%s': Got state %.2f", this->entity_id_, *val);
|
||||
}
|
||||
this->publish_state(*val);
|
||||
});
|
||||
}
|
||||
void HomeassistantSensor::dump_config() {
|
||||
LOG_SENSOR("", "Homeassistant Sensor", this);
|
||||
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_.c_str());
|
||||
if (this->attribute_.has_value()) {
|
||||
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_.value().c_str());
|
||||
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
|
||||
if (this->attribute_ != nullptr) {
|
||||
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_);
|
||||
}
|
||||
}
|
||||
float HomeassistantSensor::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
|
||||
|
||||
@@ -8,15 +8,15 @@ namespace homeassistant {
|
||||
|
||||
class HomeassistantSensor : public sensor::Sensor, public Component {
|
||||
public:
|
||||
void set_entity_id(const std::string &entity_id) { entity_id_ = entity_id; }
|
||||
void set_attribute(const std::string &attribute) { attribute_ = attribute; }
|
||||
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
|
||||
void set_attribute(const char *attribute) { this->attribute_ = attribute; }
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
float get_setup_priority() const override;
|
||||
|
||||
protected:
|
||||
std::string entity_id_;
|
||||
optional<std::string> attribute_;
|
||||
const char *entity_id_{nullptr};
|
||||
const char *attribute_{nullptr};
|
||||
};
|
||||
|
||||
} // namespace homeassistant
|
||||
|
||||
@@ -10,7 +10,7 @@ static const char *const TAG = "homeassistant.switch";
|
||||
using namespace esphome::switch_;
|
||||
|
||||
void HomeassistantSwitch::setup() {
|
||||
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, nullopt, [this](const std::string &state) {
|
||||
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, nullptr, [this](const std::string &state) {
|
||||
auto val = parse_on_off(state.c_str());
|
||||
switch (val) {
|
||||
case PARSE_NONE:
|
||||
@@ -20,7 +20,7 @@ void HomeassistantSwitch::setup() {
|
||||
case PARSE_ON:
|
||||
case PARSE_OFF:
|
||||
bool new_state = val == PARSE_ON;
|
||||
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_.c_str(), ONOFF(new_state));
|
||||
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
|
||||
this->publish_state(new_state);
|
||||
break;
|
||||
}
|
||||
@@ -29,7 +29,7 @@ void HomeassistantSwitch::setup() {
|
||||
|
||||
void HomeassistantSwitch::dump_config() {
|
||||
LOG_SWITCH("", "Homeassistant Switch", this);
|
||||
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_.c_str());
|
||||
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
|
||||
}
|
||||
|
||||
float HomeassistantSwitch::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
|
||||
|
||||
@@ -8,14 +8,14 @@ namespace homeassistant {
|
||||
|
||||
class HomeassistantSwitch : public switch_::Switch, public Component {
|
||||
public:
|
||||
void set_entity_id(const std::string &entity_id) { this->entity_id_ = entity_id; }
|
||||
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
float get_setup_priority() const override;
|
||||
|
||||
protected:
|
||||
void write_state(bool state) override;
|
||||
std::string entity_id_;
|
||||
const char *entity_id_{nullptr};
|
||||
};
|
||||
|
||||
} // namespace homeassistant
|
||||
|
||||
@@ -10,20 +10,19 @@ static const char *const TAG = "homeassistant.text_sensor";
|
||||
void HomeassistantTextSensor::setup() {
|
||||
api::global_api_server->subscribe_home_assistant_state(
|
||||
this->entity_id_, this->attribute_, [this](const std::string &state) {
|
||||
if (this->attribute_.has_value()) {
|
||||
ESP_LOGD(TAG, "'%s::%s': Got attribute state '%s'", this->entity_id_.c_str(),
|
||||
this->attribute_.value().c_str(), state.c_str());
|
||||
if (this->attribute_ != nullptr) {
|
||||
ESP_LOGD(TAG, "'%s::%s': Got attribute state '%s'", this->entity_id_, this->attribute_, state.c_str());
|
||||
} else {
|
||||
ESP_LOGD(TAG, "'%s': Got state '%s'", this->entity_id_.c_str(), state.c_str());
|
||||
ESP_LOGD(TAG, "'%s': Got state '%s'", this->entity_id_, state.c_str());
|
||||
}
|
||||
this->publish_state(state);
|
||||
});
|
||||
}
|
||||
void HomeassistantTextSensor::dump_config() {
|
||||
LOG_TEXT_SENSOR("", "Homeassistant Text Sensor", this);
|
||||
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_.c_str());
|
||||
if (this->attribute_.has_value()) {
|
||||
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_.value().c_str());
|
||||
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
|
||||
if (this->attribute_ != nullptr) {
|
||||
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_);
|
||||
}
|
||||
}
|
||||
float HomeassistantTextSensor::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
|
||||
|
||||
@@ -8,15 +8,15 @@ namespace homeassistant {
|
||||
|
||||
class HomeassistantTextSensor : public text_sensor::TextSensor, public Component {
|
||||
public:
|
||||
void set_entity_id(const std::string &entity_id) { entity_id_ = entity_id; }
|
||||
void set_attribute(const std::string &attribute) { attribute_ = attribute; }
|
||||
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
|
||||
void set_attribute(const char *attribute) { this->attribute_ = attribute; }
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
float get_setup_priority() const override;
|
||||
|
||||
protected:
|
||||
std::string entity_id_;
|
||||
optional<std::string> attribute_;
|
||||
const char *entity_id_{nullptr};
|
||||
const char *attribute_{nullptr};
|
||||
};
|
||||
|
||||
} // namespace homeassistant
|
||||
|
||||
6
esphome/components/hub75/__init__.py
Normal file
6
esphome/components/hub75/__init__.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from esphome.cpp_generator import MockObj
|
||||
|
||||
CODEOWNERS = ["@stuartparmenter"]
|
||||
|
||||
# Use fully-qualified namespace to avoid collision with external hub75 library's global ::hub75 namespace
|
||||
hub75_ns = MockObj("::esphome::hub75", "::")
|
||||
80
esphome/components/hub75/boards/__init__.py
Normal file
80
esphome/components/hub75/boards/__init__.py
Normal file
@@ -0,0 +1,80 @@
|
||||
"""Board presets for HUB75 displays.
|
||||
|
||||
Each board preset defines standard pin mappings for HUB75 controller boards.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import importlib
|
||||
import pkgutil
|
||||
from typing import ClassVar
|
||||
|
||||
|
||||
class BoardRegistry:
|
||||
"""Global registry for board configurations."""
|
||||
|
||||
_boards: ClassVar[dict[str, "BoardConfig"]] = {}
|
||||
|
||||
@classmethod
|
||||
def register(cls, board: "BoardConfig") -> None:
|
||||
"""Register a board configuration."""
|
||||
cls._boards[board.name] = board
|
||||
|
||||
@classmethod
|
||||
def get_boards(cls) -> dict[str, "BoardConfig"]:
|
||||
"""Return all registered boards."""
|
||||
return cls._boards
|
||||
|
||||
|
||||
@dataclass
|
||||
class BoardConfig:
|
||||
"""Board configuration storing HUB75 pin mappings."""
|
||||
|
||||
name: str
|
||||
r1_pin: int
|
||||
g1_pin: int
|
||||
b1_pin: int
|
||||
r2_pin: int
|
||||
g2_pin: int
|
||||
b2_pin: int
|
||||
a_pin: int
|
||||
b_pin: int
|
||||
c_pin: int
|
||||
d_pin: int
|
||||
e_pin: int | None
|
||||
lat_pin: int
|
||||
oe_pin: int
|
||||
clk_pin: int
|
||||
ignore_strapping_pins: tuple[str, ...] = () # e.g., ("a_pin", "clk_pin")
|
||||
|
||||
# Derived field for pin lookup
|
||||
pins: dict[str, int | None] = field(default_factory=dict, init=False, repr=False)
|
||||
|
||||
def __post_init__(self):
|
||||
"""Initialize derived fields and register board."""
|
||||
self.name = self.name.lower()
|
||||
self.pins = {
|
||||
"r1": self.r1_pin,
|
||||
"g1": self.g1_pin,
|
||||
"b1": self.b1_pin,
|
||||
"r2": self.r2_pin,
|
||||
"g2": self.g2_pin,
|
||||
"b2": self.b2_pin,
|
||||
"a": self.a_pin,
|
||||
"b": self.b_pin,
|
||||
"c": self.c_pin,
|
||||
"d": self.d_pin,
|
||||
"e": self.e_pin,
|
||||
"lat": self.lat_pin,
|
||||
"oe": self.oe_pin,
|
||||
"clk": self.clk_pin,
|
||||
}
|
||||
BoardRegistry.register(self)
|
||||
|
||||
def get_pin(self, pin_name: str) -> int | None:
|
||||
"""Get pin number for a given pin name."""
|
||||
return self.pins.get(pin_name)
|
||||
|
||||
|
||||
# Dynamically import all board definition modules
|
||||
for module_info in pkgutil.iter_modules(__path__):
|
||||
importlib.import_module(f".{module_info.name}", package=__package__)
|
||||
23
esphome/components/hub75/boards/adafruit.py
Normal file
23
esphome/components/hub75/boards/adafruit.py
Normal file
@@ -0,0 +1,23 @@
|
||||
"""Adafruit Matrix Portal board definitions."""
|
||||
|
||||
from . import BoardConfig
|
||||
|
||||
# Adafruit Matrix Portal S3
|
||||
BoardConfig(
|
||||
"adafruit-matrix-portal-s3",
|
||||
r1_pin=42,
|
||||
g1_pin=41,
|
||||
b1_pin=40,
|
||||
r2_pin=38,
|
||||
g2_pin=39,
|
||||
b2_pin=37,
|
||||
a_pin=45,
|
||||
b_pin=36,
|
||||
c_pin=48,
|
||||
d_pin=35,
|
||||
e_pin=21,
|
||||
lat_pin=47,
|
||||
oe_pin=14,
|
||||
clk_pin=2,
|
||||
ignore_strapping_pins=("a_pin",), # GPIO45 is a strapping pin
|
||||
)
|
||||
41
esphome/components/hub75/boards/apollo.py
Normal file
41
esphome/components/hub75/boards/apollo.py
Normal file
@@ -0,0 +1,41 @@
|
||||
"""Apollo Automation M1 board definitions."""
|
||||
|
||||
from . import BoardConfig
|
||||
|
||||
# Apollo Automation M1 Rev4
|
||||
BoardConfig(
|
||||
"apollo-automation-m1-rev4",
|
||||
r1_pin=42,
|
||||
g1_pin=41,
|
||||
b1_pin=40,
|
||||
r2_pin=38,
|
||||
g2_pin=39,
|
||||
b2_pin=37,
|
||||
a_pin=45,
|
||||
b_pin=36,
|
||||
c_pin=48,
|
||||
d_pin=35,
|
||||
e_pin=21,
|
||||
lat_pin=47,
|
||||
oe_pin=14,
|
||||
clk_pin=2,
|
||||
)
|
||||
|
||||
# Apollo Automation M1 Rev6
|
||||
BoardConfig(
|
||||
"apollo-automation-m1-rev6",
|
||||
r1_pin=1,
|
||||
g1_pin=5,
|
||||
b1_pin=6,
|
||||
r2_pin=7,
|
||||
g2_pin=13,
|
||||
b2_pin=9,
|
||||
a_pin=16,
|
||||
b_pin=48,
|
||||
c_pin=47,
|
||||
d_pin=21,
|
||||
e_pin=38,
|
||||
lat_pin=8,
|
||||
oe_pin=4,
|
||||
clk_pin=18,
|
||||
)
|
||||
22
esphome/components/hub75/boards/huidu.py
Normal file
22
esphome/components/hub75/boards/huidu.py
Normal file
@@ -0,0 +1,22 @@
|
||||
"""Huidu board definitions."""
|
||||
|
||||
from . import BoardConfig
|
||||
|
||||
# Huidu HD-WF2
|
||||
BoardConfig(
|
||||
"huidu-hd-wf2",
|
||||
r1_pin=2,
|
||||
g1_pin=6,
|
||||
b1_pin=10,
|
||||
r2_pin=3,
|
||||
g2_pin=7,
|
||||
b2_pin=11,
|
||||
a_pin=39,
|
||||
b_pin=38,
|
||||
c_pin=37,
|
||||
d_pin=36,
|
||||
e_pin=21,
|
||||
lat_pin=33,
|
||||
oe_pin=35,
|
||||
clk_pin=34,
|
||||
)
|
||||
24
esphome/components/hub75/boards/trinity.py
Normal file
24
esphome/components/hub75/boards/trinity.py
Normal file
@@ -0,0 +1,24 @@
|
||||
"""ESP32 Trinity board definitions."""
|
||||
|
||||
from . import BoardConfig
|
||||
|
||||
# ESP32 Trinity
|
||||
# https://esp32trinity.com/
|
||||
# Pin assignments from: https://github.com/witnessmenow/ESP32-Trinity/blob/master/FAQ.md
|
||||
BoardConfig(
|
||||
"esp32-trinity",
|
||||
r1_pin=25,
|
||||
g1_pin=26,
|
||||
b1_pin=27,
|
||||
r2_pin=14,
|
||||
g2_pin=12,
|
||||
b2_pin=13,
|
||||
a_pin=23,
|
||||
b_pin=19,
|
||||
c_pin=5,
|
||||
d_pin=17,
|
||||
e_pin=18,
|
||||
lat_pin=4,
|
||||
oe_pin=15,
|
||||
clk_pin=16,
|
||||
)
|
||||
578
esphome/components/hub75/display.py
Normal file
578
esphome/components/hub75/display.py
Normal file
@@ -0,0 +1,578 @@
|
||||
from typing import Any
|
||||
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import display
|
||||
from esphome.components.esp32 import add_idf_component
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_AUTO_CLEAR_ENABLED,
|
||||
CONF_BIT_DEPTH,
|
||||
CONF_BOARD,
|
||||
CONF_BRIGHTNESS,
|
||||
CONF_CLK_PIN,
|
||||
CONF_GAMMA_CORRECT,
|
||||
CONF_ID,
|
||||
CONF_LAMBDA,
|
||||
CONF_OE_PIN,
|
||||
CONF_UPDATE_INTERVAL,
|
||||
)
|
||||
import esphome.final_validate as fv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import boards, hub75_ns
|
||||
|
||||
DEPENDENCIES = ["esp32"]
|
||||
CODEOWNERS = ["@stuartparmenter"]
|
||||
|
||||
# Load all board presets
|
||||
BOARDS = boards.BoardRegistry.get_boards()
|
||||
|
||||
# Constants
|
||||
CONF_HUB75_ID = "hub75_id"
|
||||
|
||||
# Panel dimensions
|
||||
CONF_PANEL_WIDTH = "panel_width"
|
||||
CONF_PANEL_HEIGHT = "panel_height"
|
||||
|
||||
# Multi-panel layout
|
||||
CONF_LAYOUT_ROWS = "layout_rows"
|
||||
CONF_LAYOUT_COLS = "layout_cols"
|
||||
CONF_LAYOUT = "layout"
|
||||
|
||||
# Panel hardware
|
||||
CONF_SCAN_WIRING = "scan_wiring"
|
||||
CONF_SHIFT_DRIVER = "shift_driver"
|
||||
|
||||
# RGB pins
|
||||
CONF_R1_PIN = "r1_pin"
|
||||
CONF_G1_PIN = "g1_pin"
|
||||
CONF_B1_PIN = "b1_pin"
|
||||
CONF_R2_PIN = "r2_pin"
|
||||
CONF_G2_PIN = "g2_pin"
|
||||
CONF_B2_PIN = "b2_pin"
|
||||
|
||||
# Address pins
|
||||
CONF_A_PIN = "a_pin"
|
||||
CONF_B_PIN = "b_pin"
|
||||
CONF_C_PIN = "c_pin"
|
||||
CONF_D_PIN = "d_pin"
|
||||
CONF_E_PIN = "e_pin"
|
||||
|
||||
# Control pins
|
||||
CONF_LAT_PIN = "lat_pin"
|
||||
|
||||
NEVER = 4294967295 # uint32_t max - value used when update_interval is "never"
|
||||
|
||||
# Pin mapping from config keys to board keys
|
||||
PIN_MAPPING = {
|
||||
CONF_R1_PIN: "r1",
|
||||
CONF_G1_PIN: "g1",
|
||||
CONF_B1_PIN: "b1",
|
||||
CONF_R2_PIN: "r2",
|
||||
CONF_G2_PIN: "g2",
|
||||
CONF_B2_PIN: "b2",
|
||||
CONF_A_PIN: "a",
|
||||
CONF_B_PIN: "b",
|
||||
CONF_C_PIN: "c",
|
||||
CONF_D_PIN: "d",
|
||||
CONF_E_PIN: "e",
|
||||
CONF_LAT_PIN: "lat",
|
||||
CONF_OE_PIN: "oe",
|
||||
CONF_CLK_PIN: "clk",
|
||||
}
|
||||
|
||||
# Required pins (E pin is optional)
|
||||
REQUIRED_PINS = [key for key in PIN_MAPPING if key != CONF_E_PIN]
|
||||
|
||||
# Configuration
|
||||
CONF_CLOCK_SPEED = "clock_speed"
|
||||
CONF_LATCH_BLANKING = "latch_blanking"
|
||||
CONF_CLOCK_PHASE = "clock_phase"
|
||||
CONF_DOUBLE_BUFFER = "double_buffer"
|
||||
CONF_MIN_REFRESH_RATE = "min_refresh_rate"
|
||||
|
||||
# Map to hub75 library enums (in global namespace)
|
||||
ShiftDriver = cg.global_ns.enum("ShiftDriver", is_class=True)
|
||||
SHIFT_DRIVERS = {
|
||||
"GENERIC": ShiftDriver.GENERIC,
|
||||
"FM6126A": ShiftDriver.FM6126A,
|
||||
"ICN2038S": ShiftDriver.ICN2038S,
|
||||
"FM6124": ShiftDriver.FM6124,
|
||||
"MBI5124": ShiftDriver.MBI5124,
|
||||
"DP3246": ShiftDriver.DP3246,
|
||||
}
|
||||
|
||||
PanelLayout = cg.global_ns.enum("PanelLayout", is_class=True)
|
||||
PANEL_LAYOUTS = {
|
||||
"HORIZONTAL": PanelLayout.HORIZONTAL,
|
||||
"TOP_LEFT_DOWN": PanelLayout.TOP_LEFT_DOWN,
|
||||
"TOP_RIGHT_DOWN": PanelLayout.TOP_RIGHT_DOWN,
|
||||
"BOTTOM_LEFT_UP": PanelLayout.BOTTOM_LEFT_UP,
|
||||
"BOTTOM_RIGHT_UP": PanelLayout.BOTTOM_RIGHT_UP,
|
||||
"TOP_LEFT_DOWN_ZIGZAG": PanelLayout.TOP_LEFT_DOWN_ZIGZAG,
|
||||
"TOP_RIGHT_DOWN_ZIGZAG": PanelLayout.TOP_RIGHT_DOWN_ZIGZAG,
|
||||
"BOTTOM_LEFT_UP_ZIGZAG": PanelLayout.BOTTOM_LEFT_UP_ZIGZAG,
|
||||
"BOTTOM_RIGHT_UP_ZIGZAG": PanelLayout.BOTTOM_RIGHT_UP_ZIGZAG,
|
||||
}
|
||||
|
||||
ScanPattern = cg.global_ns.enum("ScanPattern", is_class=True)
|
||||
SCAN_PATTERNS = {
|
||||
"STANDARD_TWO_SCAN": ScanPattern.STANDARD_TWO_SCAN,
|
||||
"FOUR_SCAN_16PX_HIGH": ScanPattern.FOUR_SCAN_16PX_HIGH,
|
||||
"FOUR_SCAN_32PX_HIGH": ScanPattern.FOUR_SCAN_32PX_HIGH,
|
||||
"FOUR_SCAN_64PX_HIGH": ScanPattern.FOUR_SCAN_64PX_HIGH,
|
||||
}
|
||||
|
||||
Hub75ClockSpeed = cg.global_ns.enum("Hub75ClockSpeed", is_class=True)
|
||||
CLOCK_SPEEDS = {
|
||||
"8MHZ": Hub75ClockSpeed.HZ_8M,
|
||||
"10MHZ": Hub75ClockSpeed.HZ_10M,
|
||||
"16MHZ": Hub75ClockSpeed.HZ_16M,
|
||||
"20MHZ": Hub75ClockSpeed.HZ_20M,
|
||||
}
|
||||
|
||||
HUB75Display = hub75_ns.class_("HUB75Display", cg.PollingComponent, display.Display)
|
||||
Hub75Config = cg.global_ns.struct("Hub75Config")
|
||||
Hub75Pins = cg.global_ns.struct("Hub75Pins")
|
||||
|
||||
|
||||
def _merge_board_pins(config: ConfigType) -> ConfigType:
|
||||
"""Merge board preset pins with explicit pin overrides."""
|
||||
board_name = config.get(CONF_BOARD)
|
||||
|
||||
if board_name is None:
|
||||
# No board specified - validate that all required pins are present
|
||||
errs = [
|
||||
cv.Invalid(
|
||||
f"Required pin '{pin_name}' is missing. "
|
||||
f"Either specify a board preset or provide all pin mappings manually.",
|
||||
path=[pin_name],
|
||||
)
|
||||
for pin_name in REQUIRED_PINS
|
||||
if pin_name not in config
|
||||
]
|
||||
|
||||
if errs:
|
||||
raise cv.MultipleInvalid(errs)
|
||||
|
||||
# E_PIN is optional
|
||||
return config
|
||||
|
||||
# Get board configuration
|
||||
if board_name not in BOARDS:
|
||||
raise cv.Invalid(
|
||||
f"Unknown board '{board_name}'. Available boards: {', '.join(sorted(BOARDS.keys()))}"
|
||||
)
|
||||
|
||||
board = BOARDS[board_name]
|
||||
|
||||
# Merge board pins with explicit overrides
|
||||
# Explicit pins in config take precedence over board defaults
|
||||
for conf_key, board_key in PIN_MAPPING.items():
|
||||
if conf_key in config or (board_pin := board.get_pin(board_key)) is None:
|
||||
continue
|
||||
# Create pin config
|
||||
pin_config = {"number": board_pin}
|
||||
if conf_key in board.ignore_strapping_pins:
|
||||
pin_config["ignore_strapping_warning"] = True
|
||||
|
||||
# Validate through pin schema to add required fields (id, etc.)
|
||||
config[conf_key] = pins.gpio_output_pin_schema(pin_config)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def _validate_config(config: ConfigType) -> ConfigType:
|
||||
"""Validate driver and layout requirements."""
|
||||
errs: list[cv.Invalid] = []
|
||||
|
||||
# MBI5124 requires inverted clock phase
|
||||
driver = config.get(CONF_SHIFT_DRIVER, "GENERIC")
|
||||
if driver == "MBI5124" and not config.get(CONF_CLOCK_PHASE, False):
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
"MBI5124 shift driver requires 'clock_phase: true' to be set",
|
||||
path=[CONF_CLOCK_PHASE],
|
||||
)
|
||||
)
|
||||
|
||||
# Prevent conflicting min_refresh_rate + update_interval configuration
|
||||
# min_refresh_rate is auto-calculated from update_interval unless using LVGL mode
|
||||
update_interval = config.get(CONF_UPDATE_INTERVAL)
|
||||
if CONF_MIN_REFRESH_RATE in config and update_interval is not None:
|
||||
# Handle both integer (NEVER) and time object cases
|
||||
interval_ms = (
|
||||
update_interval
|
||||
if isinstance(update_interval, int)
|
||||
else update_interval.total_milliseconds
|
||||
)
|
||||
if interval_ms != NEVER:
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
"Cannot set both 'min_refresh_rate' and 'update_interval' (except 'never'). "
|
||||
"Refresh rate is auto-calculated from update_interval. "
|
||||
"Remove 'min_refresh_rate' or use 'update_interval: never' for LVGL mode.",
|
||||
path=[CONF_MIN_REFRESH_RATE],
|
||||
)
|
||||
)
|
||||
|
||||
# Validate layout configuration (validate effective config including C++ defaults)
|
||||
layout = config.get(CONF_LAYOUT, "HORIZONTAL")
|
||||
layout_rows = config.get(CONF_LAYOUT_ROWS, 1)
|
||||
layout_cols = config.get(CONF_LAYOUT_COLS, 1)
|
||||
is_zigzag = "ZIGZAG" in layout
|
||||
|
||||
# Single panel (1x1) should use HORIZONTAL
|
||||
if layout_rows == 1 and layout_cols == 1 and layout != "HORIZONTAL":
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
f"Single panel (layout_rows=1, layout_cols=1) should use 'layout: HORIZONTAL' (got {layout})",
|
||||
path=[CONF_LAYOUT],
|
||||
)
|
||||
)
|
||||
|
||||
# HORIZONTAL layout requires single row
|
||||
if layout == "HORIZONTAL" and layout_rows != 1:
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
f"HORIZONTAL layout requires 'layout_rows: 1' (got {layout_rows}). "
|
||||
"For multi-row grids, use TOP_LEFT_DOWN or other grid layouts.",
|
||||
path=[CONF_LAYOUT_ROWS],
|
||||
)
|
||||
)
|
||||
|
||||
# Grid layouts (non-HORIZONTAL) require more than one panel
|
||||
if layout != "HORIZONTAL" and layout_rows == 1 and layout_cols == 1:
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
f"Grid layout '{layout}' requires multiple panels (layout_rows > 1 or layout_cols > 1)",
|
||||
path=[CONF_LAYOUT],
|
||||
)
|
||||
)
|
||||
|
||||
# Serpentine layouts (non-ZIGZAG) require multiple rows
|
||||
# Serpentine physically rotates alternate rows upside down (Y-coordinate inversion)
|
||||
# Single-row chains should use HORIZONTAL or ZIGZAG variants
|
||||
if not is_zigzag and layout != "HORIZONTAL" and layout_rows == 1:
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
f"Serpentine layout '{layout}' requires layout_rows > 1 "
|
||||
f"(got layout_rows={layout_rows}). "
|
||||
"Serpentine wiring physically rotates alternate rows upside down. "
|
||||
"For single-row chains, use 'layout: HORIZONTAL' or add '_ZIGZAG' suffix.",
|
||||
path=[CONF_LAYOUT_ROWS],
|
||||
)
|
||||
)
|
||||
|
||||
# ZIGZAG layouts require actual grid (both rows AND cols > 1)
|
||||
if is_zigzag and (layout_rows == 1 or layout_cols == 1):
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
f"ZIGZAG layout '{layout}' requires both layout_rows > 1 AND layout_cols > 1 "
|
||||
f"(got rows={layout_rows}, cols={layout_cols}). "
|
||||
"For single row/column chains, use non-zigzag layouts or HORIZONTAL.",
|
||||
path=[CONF_LAYOUT],
|
||||
)
|
||||
)
|
||||
|
||||
if errs:
|
||||
raise cv.MultipleInvalid(errs)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def _final_validate(config: ConfigType) -> ConfigType:
|
||||
"""Validate requirements when using HUB75 display."""
|
||||
# Local imports to avoid circular dependencies
|
||||
from esphome.components.esp32 import get_esp32_variant
|
||||
from esphome.components.esp32.const import VARIANT_ESP32P4
|
||||
from esphome.components.lvgl import DOMAIN as LVGL_DOMAIN
|
||||
from esphome.components.psram import DOMAIN as PSRAM_DOMAIN
|
||||
|
||||
full_config = fv.full_config.get()
|
||||
errs: list[cv.Invalid] = []
|
||||
|
||||
# ESP32-P4 requires PSRAM
|
||||
variant = get_esp32_variant()
|
||||
if variant == VARIANT_ESP32P4 and PSRAM_DOMAIN not in full_config:
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
"HUB75 display on ESP32-P4 requires PSRAM. Add 'psram:' to your configuration.",
|
||||
path=[CONF_ID],
|
||||
)
|
||||
)
|
||||
|
||||
# LVGL-specific validation
|
||||
if LVGL_DOMAIN in full_config:
|
||||
# Check update_interval (converted from "never" to NEVER constant)
|
||||
update_interval = config.get(CONF_UPDATE_INTERVAL)
|
||||
if update_interval is not None:
|
||||
# Handle both integer (NEVER) and time object cases
|
||||
interval_ms = (
|
||||
update_interval
|
||||
if isinstance(update_interval, int)
|
||||
else update_interval.total_milliseconds
|
||||
)
|
||||
if interval_ms != NEVER:
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
"HUB75 display with LVGL must have 'update_interval: never'. "
|
||||
"LVGL manages its own refresh timing.",
|
||||
path=[CONF_UPDATE_INTERVAL],
|
||||
)
|
||||
)
|
||||
|
||||
# Check auto_clear_enabled
|
||||
auto_clear = config[CONF_AUTO_CLEAR_ENABLED]
|
||||
if auto_clear is not False:
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
f"HUB75 display with LVGL must have 'auto_clear_enabled: false' (got '{auto_clear}'). "
|
||||
"LVGL manages screen clearing.",
|
||||
path=[CONF_AUTO_CLEAR_ENABLED],
|
||||
)
|
||||
)
|
||||
|
||||
# Check double_buffer (C++ default: false)
|
||||
double_buffer = config.get(CONF_DOUBLE_BUFFER, False)
|
||||
if double_buffer is not False:
|
||||
errs.append(
|
||||
cv.Invalid(
|
||||
f"HUB75 display with LVGL must have 'double_buffer: false' (got '{double_buffer}'). "
|
||||
"LVGL uses its own buffering strategy.",
|
||||
path=[CONF_DOUBLE_BUFFER],
|
||||
)
|
||||
)
|
||||
|
||||
if errs:
|
||||
raise cv.MultipleInvalid(errs)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = cv.Schema(_final_validate)
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
display.FULL_DISPLAY_SCHEMA.extend(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(HUB75Display),
|
||||
# Board preset (optional - provides default pin mappings)
|
||||
cv.Optional(CONF_BOARD): cv.one_of(*BOARDS.keys(), lower=True),
|
||||
# Panel dimensions
|
||||
cv.Required(CONF_PANEL_WIDTH): cv.positive_int,
|
||||
cv.Required(CONF_PANEL_HEIGHT): cv.positive_int,
|
||||
# Multi-panel layout
|
||||
cv.Optional(CONF_LAYOUT_ROWS): cv.positive_int,
|
||||
cv.Optional(CONF_LAYOUT_COLS): cv.positive_int,
|
||||
cv.Optional(CONF_LAYOUT): cv.enum(PANEL_LAYOUTS, upper=True, space="_"),
|
||||
# Panel hardware configuration
|
||||
cv.Optional(CONF_SCAN_WIRING): cv.enum(
|
||||
SCAN_PATTERNS, upper=True, space="_"
|
||||
),
|
||||
cv.Optional(CONF_SHIFT_DRIVER): cv.enum(SHIFT_DRIVERS, upper=True),
|
||||
# Display configuration
|
||||
cv.Optional(CONF_DOUBLE_BUFFER): cv.boolean,
|
||||
cv.Optional(CONF_BRIGHTNESS): cv.int_range(min=0, max=255),
|
||||
cv.Optional(CONF_BIT_DEPTH): cv.int_range(min=6, max=12),
|
||||
cv.Optional(CONF_GAMMA_CORRECT): cv.enum(
|
||||
{"LINEAR": 0, "CIE1931": 1, "GAMMA_2_2": 2}, upper=True
|
||||
),
|
||||
cv.Optional(CONF_MIN_REFRESH_RATE): cv.int_range(min=40, max=200),
|
||||
# RGB data pins
|
||||
cv.Optional(CONF_R1_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_G1_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_B1_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_R2_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_G2_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_B2_PIN): pins.gpio_output_pin_schema,
|
||||
# Address pins
|
||||
cv.Optional(CONF_A_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_B_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_C_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_D_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_E_PIN): pins.gpio_output_pin_schema,
|
||||
# Control pins
|
||||
cv.Optional(CONF_LAT_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_OE_PIN): pins.gpio_output_pin_schema,
|
||||
cv.Optional(CONF_CLK_PIN): pins.gpio_output_pin_schema,
|
||||
# Timing configuration
|
||||
cv.Optional(CONF_CLOCK_SPEED): cv.enum(CLOCK_SPEEDS, upper=True),
|
||||
cv.Optional(CONF_LATCH_BLANKING): cv.positive_int,
|
||||
cv.Optional(CONF_CLOCK_PHASE): cv.boolean,
|
||||
}
|
||||
),
|
||||
_merge_board_pins,
|
||||
_validate_config,
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_REFRESH_RATE = 60 # Hz
|
||||
|
||||
|
||||
def _calculate_min_refresh_rate(config: ConfigType) -> int:
|
||||
"""Calculate minimum refresh rate for the display.
|
||||
|
||||
Priority:
|
||||
1. Explicit min_refresh_rate setting (user override)
|
||||
2. Derived from update_interval (ms to Hz conversion)
|
||||
3. Default 60 Hz (for LVGL or unspecified interval)
|
||||
"""
|
||||
if CONF_MIN_REFRESH_RATE in config:
|
||||
return config[CONF_MIN_REFRESH_RATE]
|
||||
|
||||
update_interval = config.get(CONF_UPDATE_INTERVAL)
|
||||
if update_interval is None:
|
||||
return DEFAULT_REFRESH_RATE
|
||||
|
||||
# update_interval can be TimePeriod object or NEVER constant (int)
|
||||
interval_ms = (
|
||||
update_interval
|
||||
if isinstance(update_interval, int)
|
||||
else update_interval.total_milliseconds
|
||||
)
|
||||
|
||||
# "never" or zero means external refresh (e.g., LVGL)
|
||||
if interval_ms in (NEVER, 0):
|
||||
return DEFAULT_REFRESH_RATE
|
||||
|
||||
# Convert ms interval to Hz, clamped to valid range [40, 200]
|
||||
return max(40, min(200, int(round(1000 / interval_ms))))
|
||||
|
||||
|
||||
def _build_pins_struct(
|
||||
pin_expressions: dict[str, Any], e_pin_num: int | cg.RawExpression
|
||||
) -> cg.StructInitializer:
|
||||
"""Build Hub75Pins struct from pin expressions."""
|
||||
|
||||
def pin_cast(pin):
|
||||
return cg.RawExpression(f"static_cast<int8_t>({pin.get_pin()})")
|
||||
|
||||
return cg.StructInitializer(
|
||||
Hub75Pins,
|
||||
("r1", pin_cast(pin_expressions["r1"])),
|
||||
("g1", pin_cast(pin_expressions["g1"])),
|
||||
("b1", pin_cast(pin_expressions["b1"])),
|
||||
("r2", pin_cast(pin_expressions["r2"])),
|
||||
("g2", pin_cast(pin_expressions["g2"])),
|
||||
("b2", pin_cast(pin_expressions["b2"])),
|
||||
("a", pin_cast(pin_expressions["a"])),
|
||||
("b", pin_cast(pin_expressions["b"])),
|
||||
("c", pin_cast(pin_expressions["c"])),
|
||||
("d", pin_cast(pin_expressions["d"])),
|
||||
("e", e_pin_num),
|
||||
("lat", pin_cast(pin_expressions["lat"])),
|
||||
("oe", pin_cast(pin_expressions["oe"])),
|
||||
("clk", pin_cast(pin_expressions["clk"])),
|
||||
)
|
||||
|
||||
|
||||
def _append_config_fields(
|
||||
config: ConfigType,
|
||||
field_mapping: list[tuple[str, str]],
|
||||
config_fields: list[tuple[str, Any]],
|
||||
) -> None:
|
||||
"""Append config fields from mapping if present in config."""
|
||||
for conf_key, struct_field in field_mapping:
|
||||
if conf_key in config:
|
||||
config_fields.append((struct_field, config[conf_key]))
|
||||
|
||||
|
||||
def _build_config_struct(
|
||||
config: ConfigType, pins_struct: cg.StructInitializer, min_refresh: int
|
||||
) -> cg.StructInitializer:
|
||||
"""Build Hub75Config struct from config.
|
||||
|
||||
Fields must be added in declaration order (see hub75_types.h) to satisfy
|
||||
C++ designated initializer requirements. The order is:
|
||||
1. fields_before_pins (panel_width through layout)
|
||||
2. pins
|
||||
3. output_clock_speed
|
||||
4. min_refresh_rate
|
||||
5. fields_after_min_refresh (latch_blanking through brightness)
|
||||
"""
|
||||
fields_before_pins = [
|
||||
(CONF_PANEL_WIDTH, "panel_width"),
|
||||
(CONF_PANEL_HEIGHT, "panel_height"),
|
||||
# scan_pattern - auto-calculated, not set
|
||||
(CONF_SCAN_WIRING, "scan_wiring"),
|
||||
(CONF_SHIFT_DRIVER, "shift_driver"),
|
||||
(CONF_LAYOUT_ROWS, "layout_rows"),
|
||||
(CONF_LAYOUT_COLS, "layout_cols"),
|
||||
(CONF_LAYOUT, "layout"),
|
||||
]
|
||||
fields_after_min_refresh = [
|
||||
(CONF_LATCH_BLANKING, "latch_blanking"),
|
||||
(CONF_DOUBLE_BUFFER, "double_buffer"),
|
||||
(CONF_CLOCK_PHASE, "clk_phase_inverted"),
|
||||
(CONF_BRIGHTNESS, "brightness"),
|
||||
]
|
||||
|
||||
config_fields: list[tuple[str, Any]] = []
|
||||
|
||||
_append_config_fields(config, fields_before_pins, config_fields)
|
||||
|
||||
config_fields.append(("pins", pins_struct))
|
||||
|
||||
if CONF_CLOCK_SPEED in config:
|
||||
config_fields.append(("output_clock_speed", config[CONF_CLOCK_SPEED]))
|
||||
|
||||
config_fields.append(("min_refresh_rate", min_refresh))
|
||||
|
||||
_append_config_fields(config, fields_after_min_refresh, config_fields)
|
||||
|
||||
return cg.StructInitializer(Hub75Config, *config_fields)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
add_idf_component(
|
||||
name="esphome/esp-hub75",
|
||||
ref="0.1.6",
|
||||
)
|
||||
|
||||
# Set compile-time configuration via defines
|
||||
if CONF_BIT_DEPTH in config:
|
||||
cg.add_define("HUB75_BIT_DEPTH", config[CONF_BIT_DEPTH])
|
||||
|
||||
if CONF_GAMMA_CORRECT in config:
|
||||
cg.add_define("HUB75_GAMMA_MODE", config[CONF_GAMMA_CORRECT])
|
||||
|
||||
# Await all pin expressions
|
||||
pin_expressions = {
|
||||
"r1": await cg.gpio_pin_expression(config[CONF_R1_PIN]),
|
||||
"g1": await cg.gpio_pin_expression(config[CONF_G1_PIN]),
|
||||
"b1": await cg.gpio_pin_expression(config[CONF_B1_PIN]),
|
||||
"r2": await cg.gpio_pin_expression(config[CONF_R2_PIN]),
|
||||
"g2": await cg.gpio_pin_expression(config[CONF_G2_PIN]),
|
||||
"b2": await cg.gpio_pin_expression(config[CONF_B2_PIN]),
|
||||
"a": await cg.gpio_pin_expression(config[CONF_A_PIN]),
|
||||
"b": await cg.gpio_pin_expression(config[CONF_B_PIN]),
|
||||
"c": await cg.gpio_pin_expression(config[CONF_C_PIN]),
|
||||
"d": await cg.gpio_pin_expression(config[CONF_D_PIN]),
|
||||
"lat": await cg.gpio_pin_expression(config[CONF_LAT_PIN]),
|
||||
"oe": await cg.gpio_pin_expression(config[CONF_OE_PIN]),
|
||||
"clk": await cg.gpio_pin_expression(config[CONF_CLK_PIN]),
|
||||
}
|
||||
|
||||
# E pin is optional
|
||||
if CONF_E_PIN in config:
|
||||
e_pin = await cg.gpio_pin_expression(config[CONF_E_PIN])
|
||||
e_pin_num = cg.RawExpression(f"static_cast<int8_t>({e_pin.get_pin()})")
|
||||
else:
|
||||
e_pin_num = -1
|
||||
|
||||
# Build structs
|
||||
min_refresh = _calculate_min_refresh_rate(config)
|
||||
pins_struct = _build_pins_struct(pin_expressions, e_pin_num)
|
||||
hub75_config = _build_config_struct(config, pins_struct, min_refresh)
|
||||
|
||||
# Create display and register
|
||||
var = cg.new_Pvariable(config[CONF_ID], hub75_config)
|
||||
await display.register_display(var, config)
|
||||
|
||||
if CONF_LAMBDA in config:
|
||||
lambda_ = await cg.process_lambda(
|
||||
config[CONF_LAMBDA], [(display.DisplayRef, "it")], return_type=cg.void
|
||||
)
|
||||
cg.add(var.set_writer(lambda_))
|
||||
192
esphome/components/hub75/hub75.cpp
Normal file
192
esphome/components/hub75/hub75.cpp
Normal file
@@ -0,0 +1,192 @@
|
||||
#include "hub75_component.h"
|
||||
#include "esphome/core/application.h"
|
||||
|
||||
#ifdef USE_ESP32
|
||||
|
||||
namespace esphome::hub75 {
|
||||
|
||||
static const char *const TAG = "hub75";
|
||||
|
||||
// ========================================
|
||||
// Constructor
|
||||
// ========================================
|
||||
|
||||
HUB75Display::HUB75Display(const Hub75Config &config) : config_(config) {
|
||||
// Initialize runtime state from config
|
||||
this->brightness_ = config.brightness;
|
||||
this->enabled_ = (config.brightness > 0);
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Core Component methods
|
||||
// ========================================
|
||||
|
||||
void HUB75Display::setup() {
|
||||
ESP_LOGCONFIG(TAG, "Setting up HUB75Display...");
|
||||
|
||||
// Create driver with pre-configured config
|
||||
driver_ = new Hub75Driver(config_);
|
||||
if (!driver_->begin()) {
|
||||
ESP_LOGE(TAG, "Failed to initialize HUB75 driver!");
|
||||
return;
|
||||
}
|
||||
|
||||
this->enabled_ = true;
|
||||
}
|
||||
|
||||
void HUB75Display::dump_config() {
|
||||
LOG_DISPLAY("", "HUB75", this);
|
||||
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Panel: %dx%d pixels\n"
|
||||
" Layout: %dx%d panels\n"
|
||||
" Virtual Display: %dx%d pixels",
|
||||
config_.panel_width, config_.panel_height, config_.layout_cols, config_.layout_rows,
|
||||
config_.panel_width * config_.layout_cols, config_.panel_height * config_.layout_rows);
|
||||
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Scan Wiring: %d\n"
|
||||
" Shift Driver: %d",
|
||||
static_cast<int>(config_.scan_wiring), static_cast<int>(config_.shift_driver));
|
||||
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Pins: R1:%i, G1:%i, B1:%i, R2:%i, G2:%i, B2:%i\n"
|
||||
" Pins: A:%i, B:%i, C:%i, D:%i, E:%i\n"
|
||||
" Pins: LAT:%i, OE:%i, CLK:%i",
|
||||
config_.pins.r1, config_.pins.g1, config_.pins.b1, config_.pins.r2, config_.pins.g2, config_.pins.b2,
|
||||
config_.pins.a, config_.pins.b, config_.pins.c, config_.pins.d, config_.pins.e, config_.pins.lat,
|
||||
config_.pins.oe, config_.pins.clk);
|
||||
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Clock Speed: %u MHz\n"
|
||||
" Latch Blanking: %i\n"
|
||||
" Clock Phase: %s\n"
|
||||
" Min Refresh Rate: %i Hz\n"
|
||||
" Bit Depth: %i\n"
|
||||
" Double Buffer: %s",
|
||||
static_cast<uint32_t>(config_.output_clock_speed) / 1000000, config_.latch_blanking,
|
||||
TRUEFALSE(config_.clk_phase_inverted), config_.min_refresh_rate, HUB75_BIT_DEPTH,
|
||||
YESNO(config_.double_buffer));
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Display/PollingComponent methods
|
||||
// ========================================
|
||||
|
||||
void HUB75Display::update() {
|
||||
if (!driver_) [[unlikely]]
|
||||
return;
|
||||
if (!this->enabled_) [[unlikely]]
|
||||
return;
|
||||
|
||||
this->do_update_();
|
||||
|
||||
if (config_.double_buffer) {
|
||||
driver_->flip_buffer();
|
||||
}
|
||||
}
|
||||
|
||||
void HUB75Display::fill(Color color) {
|
||||
if (!driver_) [[unlikely]]
|
||||
return;
|
||||
if (!this->enabled_) [[unlikely]]
|
||||
return;
|
||||
|
||||
// Special case: black (off) - use fast hardware clear
|
||||
if (!color.is_on()) {
|
||||
driver_->clear();
|
||||
return;
|
||||
}
|
||||
|
||||
// For non-black colors, fall back to base class (pixel-by-pixel)
|
||||
Display::fill(color);
|
||||
}
|
||||
|
||||
void HOT HUB75Display::draw_pixel_at(int x, int y, Color color) {
|
||||
if (!driver_) [[unlikely]]
|
||||
return;
|
||||
if (!this->enabled_) [[unlikely]]
|
||||
return;
|
||||
|
||||
if (x >= this->get_width_internal() || x < 0 || y >= this->get_height_internal() || y < 0) [[unlikely]]
|
||||
return;
|
||||
|
||||
driver_->set_pixel(x, y, color.r, color.g, color.b);
|
||||
App.feed_wdt();
|
||||
}
|
||||
|
||||
void HOT HUB75Display::draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, ColorOrder order,
|
||||
ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) {
|
||||
if (!driver_) [[unlikely]]
|
||||
return;
|
||||
if (!this->enabled_) [[unlikely]]
|
||||
return;
|
||||
|
||||
// Map ESPHome enums to hub75 enums
|
||||
Hub75PixelFormat format;
|
||||
Hub75ColorOrder color_order = Hub75ColorOrder::RGB;
|
||||
int bytes_per_pixel;
|
||||
|
||||
// Determine format based on bitness
|
||||
if (bitness == ColorBitness::COLOR_BITNESS_565) {
|
||||
format = Hub75PixelFormat::RGB565;
|
||||
bytes_per_pixel = 2;
|
||||
} else if (bitness == ColorBitness::COLOR_BITNESS_888) {
|
||||
#ifdef USE_LVGL
|
||||
#if LV_COLOR_DEPTH == 32
|
||||
// 32-bit: 4 bytes per pixel with padding byte (LVGL mode)
|
||||
format = Hub75PixelFormat::RGB888_32;
|
||||
bytes_per_pixel = 4;
|
||||
|
||||
// Map ESPHome ColorOrder to Hub75ColorOrder
|
||||
// ESPHome ColorOrder is typically BGR for little-endian 32-bit
|
||||
color_order = (order == ColorOrder::COLOR_ORDER_RGB) ? Hub75ColorOrder::RGB : Hub75ColorOrder::BGR;
|
||||
#elif LV_COLOR_DEPTH == 24
|
||||
// 24-bit: 3 bytes per pixel, tightly packed
|
||||
format = Hub75PixelFormat::RGB888;
|
||||
bytes_per_pixel = 3;
|
||||
// Note: 24-bit is always RGB order in LVGL
|
||||
#else
|
||||
ESP_LOGE(TAG, "Unsupported LV_COLOR_DEPTH: %d", LV_COLOR_DEPTH);
|
||||
return;
|
||||
#endif
|
||||
#else
|
||||
// Non-LVGL mode: standard 24-bit RGB888
|
||||
format = Hub75PixelFormat::RGB888;
|
||||
bytes_per_pixel = 3;
|
||||
color_order = (order == ColorOrder::COLOR_ORDER_RGB) ? Hub75ColorOrder::RGB : Hub75ColorOrder::BGR;
|
||||
#endif
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Unsupported bitness: %d", static_cast<int>(bitness));
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if buffer is tightly packed (no stride)
|
||||
const int stride_px = x_offset + w + x_pad;
|
||||
const bool is_packed = (x_offset == 0 && x_pad == 0 && y_offset == 0);
|
||||
|
||||
if (is_packed) {
|
||||
// Tightly packed buffer - single bulk call for best performance
|
||||
driver_->draw_pixels(x_start, y_start, w, h, ptr, format, color_order, big_endian);
|
||||
} else {
|
||||
// Buffer has stride (padding between rows) - draw row by row
|
||||
for (int yy = 0; yy < h; ++yy) {
|
||||
const size_t row_offset = ((y_offset + yy) * stride_px + x_offset) * bytes_per_pixel;
|
||||
const uint8_t *row_ptr = ptr + row_offset;
|
||||
|
||||
driver_->draw_pixels(x_start, y_start + yy, w, 1, row_ptr, format, color_order, big_endian);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void HUB75Display::set_brightness(int brightness) {
|
||||
this->brightness_ = brightness;
|
||||
this->enabled_ = (brightness > 0);
|
||||
if (this->driver_ != nullptr) {
|
||||
this->driver_->set_brightness(brightness);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace esphome::hub75
|
||||
|
||||
#endif
|
||||
55
esphome/components/hub75/hub75_component.h
Normal file
55
esphome/components/hub75/hub75_component.h
Normal file
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef USE_ESP32
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "esphome/components/display/display_buffer.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "hub75.h" // hub75 library
|
||||
|
||||
namespace esphome::hub75 {
|
||||
|
||||
using esphome::display::ColorBitness;
|
||||
using esphome::display::ColorOrder;
|
||||
|
||||
class HUB75Display : public display::Display {
|
||||
public:
|
||||
// Constructor accepting config
|
||||
explicit HUB75Display(const Hub75Config &config);
|
||||
|
||||
// Core Component methods
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
float get_setup_priority() const override { return setup_priority::PROCESSOR; }
|
||||
|
||||
// Display/PollingComponent methods
|
||||
void update() override;
|
||||
display::DisplayType get_display_type() override { return display::DisplayType::DISPLAY_TYPE_COLOR; }
|
||||
void fill(Color color) override;
|
||||
void draw_pixel_at(int x, int y, Color color) override;
|
||||
void draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, display::ColorOrder order,
|
||||
display::ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) override;
|
||||
|
||||
// Brightness control (runtime mutable)
|
||||
void set_brightness(int brightness);
|
||||
|
||||
protected:
|
||||
// Display internal methods
|
||||
int get_width_internal() override { return config_.panel_width * config_.layout_cols; }
|
||||
int get_height_internal() override { return config_.panel_height * config_.layout_rows; }
|
||||
|
||||
// Member variables
|
||||
Hub75Driver *driver_{nullptr};
|
||||
Hub75Config config_; // Immutable configuration
|
||||
|
||||
// Runtime state (mutable)
|
||||
int brightness_{128};
|
||||
bool enabled_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::hub75
|
||||
|
||||
#endif
|
||||
@@ -2,6 +2,23 @@ import logging
|
||||
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import esp32
|
||||
from esphome.components.esp32 import (
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C2,
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
get_esp32_variant,
|
||||
)
|
||||
from esphome.components.esp32.gpio_esp32_c5 import esp32_c5_validate_lp_i2c
|
||||
from esphome.components.esp32.gpio_esp32_c6 import esp32_c6_validate_lp_i2c
|
||||
from esphome.components.esp32.gpio_esp32_p4 import esp32_p4_validate_lp_i2c
|
||||
from esphome.components.zephyr import (
|
||||
zephyr_add_overlay,
|
||||
zephyr_add_prj_conf,
|
||||
@@ -16,6 +33,7 @@ from esphome.const import (
|
||||
CONF_I2C,
|
||||
CONF_I2C_ID,
|
||||
CONF_ID,
|
||||
CONF_LOW_POWER_MODE,
|
||||
CONF_SCAN,
|
||||
CONF_SCL,
|
||||
CONF_SDA,
|
||||
@@ -40,6 +58,25 @@ IDFI2CBus = i2c_ns.class_("IDFI2CBus", InternalI2CBus, cg.Component)
|
||||
ZephyrI2CBus = i2c_ns.class_("ZephyrI2CBus", I2CBus, cg.Component)
|
||||
I2CDevice = i2c_ns.class_("I2CDevice")
|
||||
|
||||
ESP32_I2C_CAPABILITIES = {
|
||||
# https://github.com/espressif/esp-idf/blob/master/components/soc/esp32/include/soc/soc_caps.h
|
||||
VARIANT_ESP32: {"NUM": 2, "HP": 2},
|
||||
VARIANT_ESP32C2: {"NUM": 1, "HP": 1},
|
||||
VARIANT_ESP32C3: {"NUM": 1, "HP": 1},
|
||||
VARIANT_ESP32C5: {"NUM": 2, "HP": 1, "LP": 1},
|
||||
VARIANT_ESP32C6: {"NUM": 2, "HP": 1, "LP": 1},
|
||||
VARIANT_ESP32C61: {"NUM": 1, "HP": 1},
|
||||
VARIANT_ESP32H2: {"NUM": 2, "HP": 2},
|
||||
VARIANT_ESP32P4: {"NUM": 3, "HP": 2, "LP": 1},
|
||||
VARIANT_ESP32S2: {"NUM": 2, "HP": 2},
|
||||
VARIANT_ESP32S3: {"NUM": 2, "HP": 2},
|
||||
}
|
||||
VALIDATE_LP_I2C = {
|
||||
VARIANT_ESP32C5: esp32_c5_validate_lp_i2c,
|
||||
VARIANT_ESP32C6: esp32_c6_validate_lp_i2c,
|
||||
VARIANT_ESP32P4: esp32_p4_validate_lp_i2c,
|
||||
}
|
||||
LP_I2C_VARIANT = list(VALIDATE_LP_I2C.keys())
|
||||
|
||||
CONF_SDA_PULLUP_ENABLED = "sda_pullup_enabled"
|
||||
CONF_SCL_PULLUP_ENABLED = "scl_pullup_enabled"
|
||||
@@ -91,6 +128,13 @@ CONFIG_SCHEMA = cv.All(
|
||||
cv.positive_time_period,
|
||||
),
|
||||
cv.Optional(CONF_SCAN, default=True): cv.boolean,
|
||||
cv.Optional(CONF_LOW_POWER_MODE): cv.All(
|
||||
cv.only_on_esp32,
|
||||
esp32.only_on_variant(
|
||||
supported=LP_I2C_VARIANT, msg_prefix="Low power i2c"
|
||||
),
|
||||
cv.boolean,
|
||||
),
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA),
|
||||
cv.only_on([PLATFORM_ESP32, PLATFORM_ESP8266, PLATFORM_RP2040, PLATFORM_NRF52]),
|
||||
@@ -102,6 +146,31 @@ def _final_validate(config):
|
||||
full_config = fv.full_config.get()[CONF_I2C]
|
||||
if CORE.using_zephyr and len(full_config) > 1:
|
||||
raise cv.Invalid("Second i2c is not implemented on Zephyr yet")
|
||||
if CORE.using_esp_idf and get_esp32_variant() in ESP32_I2C_CAPABILITIES:
|
||||
variant = get_esp32_variant()
|
||||
max_num = ESP32_I2C_CAPABILITIES[variant]["NUM"]
|
||||
if len(full_config) > max_num:
|
||||
raise cv.Invalid(
|
||||
f"The maximum number of i2c interfaces for {variant} is {max_num}"
|
||||
)
|
||||
if variant in LP_I2C_VARIANT:
|
||||
max_lp_num = ESP32_I2C_CAPABILITIES[variant]["LP"]
|
||||
max_hp_num = ESP32_I2C_CAPABILITIES[variant]["HP"]
|
||||
lp_num = sum(
|
||||
CONF_LOW_POWER_MODE in conf and conf[CONF_LOW_POWER_MODE]
|
||||
for conf in full_config
|
||||
)
|
||||
hp_num = len(full_config) - lp_num
|
||||
if CONF_LOW_POWER_MODE in config and config[CONF_LOW_POWER_MODE]:
|
||||
VALIDATE_LP_I2C[variant](config)
|
||||
if lp_num > max_lp_num:
|
||||
raise cv.Invalid(
|
||||
f"The maximum number of low power i2c interfaces for {variant} is {max_lp_num}"
|
||||
)
|
||||
if hp_num > max_hp_num:
|
||||
raise cv.Invalid(
|
||||
f"The maximum number of high power i2c interfaces for {variant} is {max_hp_num}"
|
||||
)
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = _final_validate
|
||||
@@ -155,6 +224,8 @@ async def to_code(config):
|
||||
cg.add(var.set_timeout(int(config[CONF_TIMEOUT].total_microseconds)))
|
||||
if CORE.using_arduino and not CORE.is_esp32:
|
||||
cg.add_library("Wire", None)
|
||||
if CONF_LOW_POWER_MODE in config:
|
||||
cg.add(var.set_lp_mode(bool(config[CONF_LOW_POWER_MODE])))
|
||||
|
||||
|
||||
def i2c_device_schema(default_address):
|
||||
|
||||
@@ -16,13 +16,10 @@ namespace i2c {
|
||||
static const char *const TAG = "i2c.idf";
|
||||
|
||||
void IDFI2CBus::setup() {
|
||||
static i2c_port_t next_port = I2C_NUM_0;
|
||||
this->port_ = next_port;
|
||||
if (this->port_ == I2C_NUM_MAX) {
|
||||
ESP_LOGE(TAG, "No more than %u buses supported", I2C_NUM_MAX);
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
static i2c_port_t next_hp_port = I2C_NUM_0;
|
||||
#if SOC_LP_I2C_SUPPORTED
|
||||
static i2c_port_t next_lp_port = LP_I2C_NUM_0;
|
||||
#endif
|
||||
|
||||
if (this->timeout_ > 13000) {
|
||||
ESP_LOGW(TAG, "Using max allowed timeout: 13 ms");
|
||||
@@ -31,23 +28,35 @@ void IDFI2CBus::setup() {
|
||||
|
||||
this->recover_();
|
||||
|
||||
next_port = (i2c_port_t) (next_port + 1);
|
||||
|
||||
i2c_master_bus_config_t bus_conf{};
|
||||
memset(&bus_conf, 0, sizeof(bus_conf));
|
||||
bus_conf.sda_io_num = gpio_num_t(sda_pin_);
|
||||
bus_conf.scl_io_num = gpio_num_t(scl_pin_);
|
||||
bus_conf.i2c_port = this->port_;
|
||||
bus_conf.glitch_ignore_cnt = 7;
|
||||
#if SOC_LP_I2C_SUPPORTED
|
||||
if (this->port_ < SOC_HP_I2C_NUM) {
|
||||
bus_conf.clk_source = I2C_CLK_SRC_DEFAULT;
|
||||
} else {
|
||||
if (this->lp_mode_) {
|
||||
if ((next_lp_port - LP_I2C_NUM_0) == SOC_LP_I2C_NUM) {
|
||||
ESP_LOGE(TAG, "No more than %u LP buses supported", SOC_LP_I2C_NUM);
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
this->port_ = next_lp_port;
|
||||
next_lp_port = (i2c_port_t) (next_lp_port + 1);
|
||||
bus_conf.lp_source_clk = LP_I2C_SCLK_DEFAULT;
|
||||
}
|
||||
#else
|
||||
bus_conf.clk_source = I2C_CLK_SRC_DEFAULT;
|
||||
} else {
|
||||
#endif
|
||||
if (next_hp_port == SOC_HP_I2C_NUM) {
|
||||
ESP_LOGE(TAG, "No more than %u HP buses supported", SOC_HP_I2C_NUM);
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
this->port_ = next_hp_port;
|
||||
next_hp_port = (i2c_port_t) (next_hp_port + 1);
|
||||
bus_conf.clk_source = I2C_CLK_SRC_DEFAULT;
|
||||
#if SOC_LP_I2C_SUPPORTED
|
||||
}
|
||||
#endif
|
||||
bus_conf.i2c_port = this->port_;
|
||||
bus_conf.flags.enable_internal_pullup = sda_pullup_enabled_ || scl_pullup_enabled_;
|
||||
esp_err_t err = i2c_new_master_bus(&bus_conf, &this->bus_);
|
||||
if (err != ESP_OK) {
|
||||
|
||||
@@ -30,6 +30,9 @@ class IDFI2CBus : public InternalI2CBus, public Component {
|
||||
void set_scl_pullup_enabled(bool scl_pullup_enabled) { this->scl_pullup_enabled_ = scl_pullup_enabled; }
|
||||
void set_frequency(uint32_t frequency) { this->frequency_ = frequency; }
|
||||
void set_timeout(uint32_t timeout) { this->timeout_ = timeout; }
|
||||
#if SOC_LP_I2C_SUPPORTED
|
||||
void set_lp_mode(bool lp_mode) { this->lp_mode_ = lp_mode; }
|
||||
#endif
|
||||
|
||||
int get_port() const override { return this->port_; }
|
||||
|
||||
@@ -48,6 +51,9 @@ class IDFI2CBus : public InternalI2CBus, public Component {
|
||||
uint32_t frequency_{};
|
||||
uint32_t timeout_ = 0;
|
||||
bool initialized_ = false;
|
||||
#if SOC_LP_I2C_SUPPORTED
|
||||
bool lp_mode_ = false;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace i2c
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.esp32 import add_idf_sdkconfig_option, get_esp32_variant
|
||||
from esphome.components.esp32.const import (
|
||||
from esphome.components.esp32 import (
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
add_idf_sdkconfig_option,
|
||||
get_esp32_variant,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_BITS_PER_SAMPLE, CONF_CHANNEL, CONF_ID, CONF_SAMPLE_RATE
|
||||
@@ -71,6 +73,7 @@ I2S_PORTS = {
|
||||
VARIANT_ESP32C3: 1,
|
||||
VARIANT_ESP32C5: 1,
|
||||
VARIANT_ESP32C6: 1,
|
||||
VARIANT_ESP32C61: 1,
|
||||
VARIANT_ESP32H2: 1,
|
||||
VARIANT_ESP32P4: 3,
|
||||
VARIANT_ESP32S2: 1,
|
||||
|
||||
@@ -40,7 +40,7 @@ INTERNAL_DAC_OPTIONS = {
|
||||
|
||||
EXTERNAL_DAC_OPTIONS = [CONF_MONO, CONF_STEREO]
|
||||
|
||||
NO_INTERNAL_DAC_VARIANTS = [esp32.const.VARIANT_ESP32S2]
|
||||
NO_INTERNAL_DAC_VARIANTS = [esp32.VARIANT_ESP32S2]
|
||||
|
||||
I2C_COMM_FMT_OPTIONS = ["lsb", "msb"]
|
||||
|
||||
|
||||
@@ -37,8 +37,8 @@ I2SAudioMicrophone = i2s_audio_ns.class_(
|
||||
"I2SAudioMicrophone", I2SAudioIn, microphone.Microphone, cg.Component
|
||||
)
|
||||
|
||||
INTERNAL_ADC_VARIANTS = [esp32.const.VARIANT_ESP32]
|
||||
PDM_VARIANTS = [esp32.const.VARIANT_ESP32, esp32.const.VARIANT_ESP32S3]
|
||||
INTERNAL_ADC_VARIANTS = [esp32.VARIANT_ESP32]
|
||||
PDM_VARIANTS = [esp32.VARIANT_ESP32, esp32.VARIANT_ESP32S3]
|
||||
|
||||
|
||||
def _validate_esp32_variant(config):
|
||||
|
||||
@@ -62,7 +62,7 @@ I2C_COMM_FMT_OPTIONS = {
|
||||
"pcm_long": i2s_comm_format_t.I2S_COMM_FORMAT_PCM_LONG,
|
||||
}
|
||||
|
||||
INTERNAL_DAC_VARIANTS = [esp32.const.VARIANT_ESP32]
|
||||
INTERNAL_DAC_VARIANTS = [esp32.VARIANT_ESP32]
|
||||
|
||||
|
||||
def _set_num_channels_from_config(config):
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import improv_base
|
||||
from esphome.components.esp32 import get_esp32_variant
|
||||
from esphome.components.esp32.const import VARIANT_ESP32S3
|
||||
from esphome.components.esp32 import VARIANT_ESP32S3, get_esp32_variant
|
||||
from esphome.components.logger import USB_CDC
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_BAUD_RATE, CONF_HARDWARE_UART, CONF_ID, CONF_LOGGER
|
||||
|
||||
@@ -70,9 +70,10 @@ optional<uint8_t> ImprovSerialComponent::read_byte_() {
|
||||
case logger::UART_SELECTION_UART0:
|
||||
case logger::UART_SELECTION_UART1:
|
||||
#if !defined(USE_ESP32_VARIANT_ESP32C3) && !defined(USE_ESP32_VARIANT_ESP32C6) && \
|
||||
!defined(USE_ESP32_VARIANT_ESP32S2) && !defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
!defined(USE_ESP32_VARIANT_ESP32C61) && !defined(USE_ESP32_VARIANT_ESP32S2) && !defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
case logger::UART_SELECTION_UART2:
|
||||
#endif // !USE_ESP32_VARIANT_ESP32C3 && !USE_ESP32_VARIANT_ESP32S2 && !USE_ESP32_VARIANT_ESP32S3
|
||||
#endif // !USE_ESP32_VARIANT_ESP32C3 && !USE_ESP32_VARIANT_ESP32C6 && !USE_ESP32_VARIANT_ESP32C61 &&
|
||||
// !USE_ESP32_VARIANT_ESP32S2 && !USE_ESP32_VARIANT_ESP32S3
|
||||
if (this->uart_num_ >= 0) {
|
||||
size_t available;
|
||||
uart_get_buffered_data_len(this->uart_num_, &available);
|
||||
@@ -137,7 +138,7 @@ void ImprovSerialComponent::write_data_(const uint8_t *data, const size_t size)
|
||||
case logger::UART_SELECTION_UART0:
|
||||
case logger::UART_SELECTION_UART1:
|
||||
#if !defined(USE_ESP32_VARIANT_ESP32C3) && !defined(USE_ESP32_VARIANT_ESP32C6) && \
|
||||
!defined(USE_ESP32_VARIANT_ESP32S2) && !defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
!defined(USE_ESP32_VARIANT_ESP32C61) && !defined(USE_ESP32_VARIANT_ESP32S2) && !defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
case logger::UART_SELECTION_UART2:
|
||||
#endif
|
||||
uart_write_bytes(this->uart_num_, this->tx_header_, header_tx_len);
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
|
||||
#ifdef USE_ESP32
|
||||
#include <driver/uart.h>
|
||||
#if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32H2) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
#if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32C61) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
#include <driver/usb_serial_jtag.h>
|
||||
#include <hal/usb_serial_jtag_ll.h>
|
||||
#endif
|
||||
|
||||
@@ -8,8 +8,8 @@ extern "C" {
|
||||
uint8_t temprature_sens_read();
|
||||
}
|
||||
#elif defined(USE_ESP32_VARIANT_ESP32C2) || defined(USE_ESP32_VARIANT_ESP32C3) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32P4) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32C61) || defined(USE_ESP32_VARIANT_ESP32H2) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
#include "driver/temperature_sensor.h"
|
||||
#endif // USE_ESP32_VARIANT
|
||||
#endif // USE_ESP32
|
||||
@@ -28,8 +28,8 @@ namespace internal_temperature {
|
||||
static const char *const TAG = "internal_temperature";
|
||||
#ifdef USE_ESP32
|
||||
#if defined(USE_ESP32_VARIANT_ESP32C2) || defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
defined(USE_ESP32_VARIANT_ESP32C61) || defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32P4) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
static temperature_sensor_handle_t tsensNew = NULL;
|
||||
#endif // USE_ESP32_VARIANT
|
||||
#endif // USE_ESP32
|
||||
@@ -44,8 +44,8 @@ void InternalTemperatureSensor::update() {
|
||||
temperature = (raw - 32) / 1.8f;
|
||||
success = (raw != 128);
|
||||
#elif defined(USE_ESP32_VARIANT_ESP32C2) || defined(USE_ESP32_VARIANT_ESP32C3) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32P4) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32C61) || defined(USE_ESP32_VARIANT_ESP32H2) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
esp_err_t result = temperature_sensor_get_celsius(tsensNew, &temperature);
|
||||
success = (result == ESP_OK);
|
||||
if (!success) {
|
||||
@@ -82,8 +82,8 @@ void InternalTemperatureSensor::update() {
|
||||
void InternalTemperatureSensor::setup() {
|
||||
#ifdef USE_ESP32
|
||||
#if defined(USE_ESP32_VARIANT_ESP32C2) || defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S2) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
defined(USE_ESP32_VARIANT_ESP32C61) || defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32P4) || \
|
||||
defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
temperature_sensor_config_t tsens_config = TEMPERATURE_SENSOR_CONFIG_DEFAULT(-10, 80);
|
||||
|
||||
esp_err_t result = temperature_sensor_install(&tsens_config, &tsensNew);
|
||||
|
||||
@@ -2,5 +2,5 @@ import esphome.config_validation as cv
|
||||
|
||||
CONFIG_SCHEMA = cv.invalid(
|
||||
"The kalman_combinator sensor has moved.\nPlease use the combination platform instead with type: kalman.\n"
|
||||
"See https://esphome.io/components/sensor/combination.html"
|
||||
"See https://esphome.io/components/sensor/combination/"
|
||||
)
|
||||
|
||||
@@ -70,7 +70,7 @@ class AddressableLight : public LightOutput, public Component {
|
||||
this->state_parent_ = state;
|
||||
}
|
||||
void update_state(LightState *state) override;
|
||||
void schedule_show() { this->state_parent_->next_write_ = true; }
|
||||
void schedule_show() { this->state_parent_->schedule_write_(); }
|
||||
|
||||
#ifdef USE_POWER_SUPPLY
|
||||
void set_power_supply(power_supply::PowerSupply *power_supply) { this->power_.set_parent(power_supply); }
|
||||
|
||||
@@ -305,8 +305,7 @@ void LightState::set_immediately_(const LightColorValues &target, bool set_remot
|
||||
this->remote_values = target;
|
||||
}
|
||||
this->output_->update_state(this);
|
||||
this->next_write_ = true;
|
||||
this->enable_loop();
|
||||
this->schedule_write_();
|
||||
}
|
||||
|
||||
void LightState::disable_loop_if_idle_() {
|
||||
|
||||
@@ -277,6 +277,12 @@ class LightState : public EntityBase, public Component {
|
||||
/// Disable loop if neither transformer nor effect is active
|
||||
void disable_loop_if_idle_();
|
||||
|
||||
/// Schedule a write to the light output and enable the loop to process it
|
||||
void schedule_write_() {
|
||||
this->next_write_ = true;
|
||||
this->enable_loop();
|
||||
}
|
||||
|
||||
/// Store the output to allow effects to have more access.
|
||||
LightOutput *output_;
|
||||
/// The currently active transformer for this light (transition/flash).
|
||||
|
||||
@@ -3,17 +3,19 @@ import re
|
||||
from esphome import automation
|
||||
from esphome.automation import LambdaAction, StatelessLambdaAction
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.esp32 import add_idf_sdkconfig_option, get_esp32_variant
|
||||
from esphome.components.esp32.const import (
|
||||
from esphome.components.esp32 import (
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C2,
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
add_idf_sdkconfig_option,
|
||||
get_esp32_variant,
|
||||
)
|
||||
from esphome.components.libretiny import get_libretiny_component, get_libretiny_family
|
||||
from esphome.components.libretiny.const import (
|
||||
@@ -104,6 +106,7 @@ UART_SELECTION_ESP32 = {
|
||||
VARIANT_ESP32C3: [UART0, UART1, USB_CDC, USB_SERIAL_JTAG],
|
||||
VARIANT_ESP32C5: [UART0, UART1, USB_CDC, USB_SERIAL_JTAG],
|
||||
VARIANT_ESP32C6: [UART0, UART1, USB_CDC, USB_SERIAL_JTAG],
|
||||
VARIANT_ESP32C61: [UART0, UART1, USB_CDC, USB_SERIAL_JTAG],
|
||||
VARIANT_ESP32H2: [UART0, UART1, USB_CDC, USB_SERIAL_JTAG],
|
||||
VARIANT_ESP32P4: [UART0, UART1, USB_CDC, USB_SERIAL_JTAG],
|
||||
VARIANT_ESP32S2: [UART0, UART1, USB_CDC],
|
||||
|
||||
@@ -29,15 +29,18 @@ class LVGLNumber : public number::Number, public Component {
|
||||
this->publish_state(value);
|
||||
}
|
||||
|
||||
void on_value() { this->publish_state(this->value_lambda_()); }
|
||||
void on_value() { this->publish_(this->value_lambda_()); }
|
||||
|
||||
protected:
|
||||
void control(float value) override {
|
||||
this->control_lambda_(value);
|
||||
void publish_(float value) {
|
||||
this->publish_state(value);
|
||||
if (this->restore_)
|
||||
this->pref_.save(&value);
|
||||
}
|
||||
void control(float value) override {
|
||||
this->control_lambda_(value);
|
||||
this->publish_(value);
|
||||
}
|
||||
std::function<void(float)> control_lambda_;
|
||||
std::function<float()> value_lambda_;
|
||||
lv_event_code_t event_;
|
||||
|
||||
@@ -184,10 +184,8 @@ async def to_code(config):
|
||||
|
||||
# Calculate compile-time dynamic TXT value count
|
||||
# Dynamic values are those that cannot be stored in flash at compile time
|
||||
# Note: MAC address is now stored in a fixed char[13] buffer, not dynamic storage
|
||||
dynamic_txt_count = 0
|
||||
if "api" in CORE.config:
|
||||
# Always: get_mac_address()
|
||||
dynamic_txt_count += 1
|
||||
# User-provided templatable TXT values (only lambdas, not static strings)
|
||||
dynamic_txt_count += sum(
|
||||
1
|
||||
@@ -196,8 +194,10 @@ async def to_code(config):
|
||||
if cg.is_template(txt_value)
|
||||
)
|
||||
|
||||
# Ensure at least 1 to avoid zero-size array
|
||||
cg.add_define("MDNS_DYNAMIC_TXT_COUNT", max(1, dynamic_txt_count))
|
||||
# Only add define if we actually need dynamic storage
|
||||
if dynamic_txt_count > 0:
|
||||
cg.add_define("USE_MDNS_DYNAMIC_TXT")
|
||||
cg.add_define("MDNS_DYNAMIC_TXT_COUNT", dynamic_txt_count)
|
||||
|
||||
# Enable storage if verbose logging is enabled (for dump_config)
|
||||
if get_logger_level() in ("VERBOSE", "VERY_VERBOSE"):
|
||||
|
||||
@@ -35,7 +35,7 @@ MDNS_STATIC_CONST_CHAR(SERVICE_TCP, "_tcp");
|
||||
// Wrap build-time defines into flash storage
|
||||
MDNS_STATIC_CONST_CHAR(VALUE_VERSION, ESPHOME_VERSION);
|
||||
|
||||
void MDNSComponent::compile_records_(StaticVector<MDNSService, MDNS_SERVICE_COUNT> &services) {
|
||||
void MDNSComponent::compile_records_(StaticVector<MDNSService, MDNS_SERVICE_COUNT> &services, char *mac_address_buf) {
|
||||
// IMPORTANT: The #ifdef blocks below must match COMPONENTS_WITH_MDNS_SERVICES
|
||||
// in mdns/__init__.py. If you add a new service here, update both locations.
|
||||
|
||||
@@ -86,7 +86,9 @@ void MDNSComponent::compile_records_(StaticVector<MDNSService, MDNS_SERVICE_COUN
|
||||
txt_records.push_back({MDNS_STR(TXT_FRIENDLY_NAME), MDNS_STR(friendly_name.c_str())});
|
||||
}
|
||||
txt_records.push_back({MDNS_STR(TXT_VERSION), MDNS_STR(VALUE_VERSION)});
|
||||
txt_records.push_back({MDNS_STR(TXT_MAC), MDNS_STR(this->add_dynamic_txt_value(get_mac_address()))});
|
||||
|
||||
// MAC address: passed from caller (either member buffer or stack buffer depending on USE_MDNS_STORE_SERVICES)
|
||||
txt_records.push_back({MDNS_STR(TXT_MAC), MDNS_STR(mac_address_buf)});
|
||||
|
||||
#ifdef USE_ESP8266
|
||||
MDNS_STATIC_CONST_CHAR(PLATFORM_ESP8266, "ESP8266");
|
||||
|
||||
@@ -60,22 +60,58 @@ class MDNSComponent : public Component {
|
||||
|
||||
void on_shutdown() override;
|
||||
|
||||
#ifdef USE_MDNS_DYNAMIC_TXT
|
||||
/// Add a dynamic TXT value and return pointer to it for use in MDNSTXTRecord
|
||||
const char *add_dynamic_txt_value(const std::string &value) {
|
||||
this->dynamic_txt_values_.push_back(value);
|
||||
return this->dynamic_txt_values_[this->dynamic_txt_values_.size() - 1].c_str();
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Storage for runtime-generated TXT values (MAC address, user lambdas)
|
||||
protected:
|
||||
/// Helper to set up services and MAC buffers, then call platform-specific registration
|
||||
using PlatformRegisterFn = void (*)(MDNSComponent *, StaticVector<MDNSService, MDNS_SERVICE_COUNT> &);
|
||||
|
||||
void setup_buffers_and_register_(PlatformRegisterFn platform_register) {
|
||||
#ifdef USE_MDNS_STORE_SERVICES
|
||||
auto &services = this->services_;
|
||||
#else
|
||||
StaticVector<MDNSService, MDNS_SERVICE_COUNT> services_storage;
|
||||
auto &services = services_storage;
|
||||
#endif
|
||||
|
||||
#ifdef USE_API
|
||||
#ifdef USE_MDNS_STORE_SERVICES
|
||||
get_mac_address_into_buffer(this->mac_address_);
|
||||
char *mac_ptr = this->mac_address_;
|
||||
#else
|
||||
char mac_address[MAC_ADDRESS_BUFFER_SIZE];
|
||||
get_mac_address_into_buffer(mac_address);
|
||||
char *mac_ptr = mac_address;
|
||||
#endif
|
||||
#else
|
||||
char *mac_ptr = nullptr;
|
||||
#endif
|
||||
|
||||
this->compile_records_(services, mac_ptr);
|
||||
platform_register(this, services);
|
||||
}
|
||||
|
||||
#ifdef USE_MDNS_DYNAMIC_TXT
|
||||
/// Storage for runtime-generated TXT values from user lambdas
|
||||
/// Pre-sized at compile time via MDNS_DYNAMIC_TXT_COUNT to avoid heap allocations.
|
||||
/// Static/compile-time values (version, board, etc.) are stored directly in flash and don't use this.
|
||||
StaticVector<std::string, MDNS_DYNAMIC_TXT_COUNT> dynamic_txt_values_;
|
||||
#endif
|
||||
|
||||
protected:
|
||||
#if defined(USE_API) && defined(USE_MDNS_STORE_SERVICES)
|
||||
/// Fixed buffer for MAC address (only needed when services are stored)
|
||||
char mac_address_[MAC_ADDRESS_BUFFER_SIZE];
|
||||
#endif
|
||||
#ifdef USE_MDNS_STORE_SERVICES
|
||||
StaticVector<MDNSService, MDNS_SERVICE_COUNT> services_{};
|
||||
#endif
|
||||
void compile_records_(StaticVector<MDNSService, MDNS_SERVICE_COUNT> &services);
|
||||
void compile_records_(StaticVector<MDNSService, MDNS_SERVICE_COUNT> &services, char *mac_address_buf);
|
||||
};
|
||||
|
||||
} // namespace esphome::mdns
|
||||
|
||||
@@ -11,19 +11,11 @@ namespace esphome::mdns {
|
||||
|
||||
static const char *const TAG = "mdns";
|
||||
|
||||
void MDNSComponent::setup() {
|
||||
#ifdef USE_MDNS_STORE_SERVICES
|
||||
this->compile_records_(this->services_);
|
||||
const auto &services = this->services_;
|
||||
#else
|
||||
StaticVector<MDNSService, MDNS_SERVICE_COUNT> services;
|
||||
this->compile_records_(services);
|
||||
#endif
|
||||
|
||||
static void register_esp32(MDNSComponent *comp, StaticVector<MDNSService, MDNS_SERVICE_COUNT> &services) {
|
||||
esp_err_t err = mdns_init();
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "Init failed: %s", esp_err_to_name(err));
|
||||
this->mark_failed();
|
||||
comp->mark_failed();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -50,6 +42,8 @@ void MDNSComponent::setup() {
|
||||
}
|
||||
}
|
||||
|
||||
void MDNSComponent::setup() { this->setup_buffers_and_register_(register_esp32); }
|
||||
|
||||
void MDNSComponent::on_shutdown() {
|
||||
mdns_free();
|
||||
delay(40); // Allow the mdns packets announcing service removal to be sent
|
||||
|
||||
@@ -11,15 +11,7 @@
|
||||
|
||||
namespace esphome::mdns {
|
||||
|
||||
void MDNSComponent::setup() {
|
||||
#ifdef USE_MDNS_STORE_SERVICES
|
||||
this->compile_records_(this->services_);
|
||||
const auto &services = this->services_;
|
||||
#else
|
||||
StaticVector<MDNSService, MDNS_SERVICE_COUNT> services;
|
||||
this->compile_records_(services);
|
||||
#endif
|
||||
|
||||
static void register_esp8266(MDNSComponent *, StaticVector<MDNSService, MDNS_SERVICE_COUNT> &services) {
|
||||
MDNS.begin(App.get_name().c_str());
|
||||
|
||||
for (const auto &service : services) {
|
||||
@@ -44,6 +36,8 @@ void MDNSComponent::setup() {
|
||||
}
|
||||
}
|
||||
|
||||
void MDNSComponent::setup() { this->setup_buffers_and_register_(register_esp8266); }
|
||||
|
||||
void MDNSComponent::loop() { MDNS.update(); }
|
||||
|
||||
void MDNSComponent::on_shutdown() {
|
||||
|
||||
@@ -9,6 +9,15 @@
|
||||
namespace esphome::mdns {
|
||||
|
||||
void MDNSComponent::setup() {
|
||||
#ifdef USE_MDNS_STORE_SERVICES
|
||||
#ifdef USE_API
|
||||
get_mac_address_into_buffer(this->mac_address_);
|
||||
char *mac_ptr = this->mac_address_;
|
||||
#else
|
||||
char *mac_ptr = nullptr;
|
||||
#endif
|
||||
this->compile_records_(this->services_, mac_ptr);
|
||||
#endif
|
||||
// Host platform doesn't have actual mDNS implementation
|
||||
}
|
||||
|
||||
|
||||
@@ -11,15 +11,7 @@
|
||||
|
||||
namespace esphome::mdns {
|
||||
|
||||
void MDNSComponent::setup() {
|
||||
#ifdef USE_MDNS_STORE_SERVICES
|
||||
this->compile_records_(this->services_);
|
||||
const auto &services = this->services_;
|
||||
#else
|
||||
StaticVector<MDNSService, MDNS_SERVICE_COUNT> services;
|
||||
this->compile_records_(services);
|
||||
#endif
|
||||
|
||||
static void register_libretiny(MDNSComponent *, StaticVector<MDNSService, MDNS_SERVICE_COUNT> &services) {
|
||||
MDNS.begin(App.get_name().c_str());
|
||||
|
||||
for (const auto &service : services) {
|
||||
@@ -43,6 +35,8 @@ void MDNSComponent::setup() {
|
||||
}
|
||||
}
|
||||
|
||||
void MDNSComponent::setup() { this->setup_buffers_and_register_(register_libretiny); }
|
||||
|
||||
void MDNSComponent::on_shutdown() {}
|
||||
|
||||
} // namespace esphome::mdns
|
||||
|
||||
@@ -11,15 +11,7 @@
|
||||
|
||||
namespace esphome::mdns {
|
||||
|
||||
void MDNSComponent::setup() {
|
||||
#ifdef USE_MDNS_STORE_SERVICES
|
||||
this->compile_records_(this->services_);
|
||||
const auto &services = this->services_;
|
||||
#else
|
||||
StaticVector<MDNSService, MDNS_SERVICE_COUNT> services;
|
||||
this->compile_records_(services);
|
||||
#endif
|
||||
|
||||
static void register_rp2040(MDNSComponent *, StaticVector<MDNSService, MDNS_SERVICE_COUNT> &services) {
|
||||
MDNS.begin(App.get_name().c_str());
|
||||
|
||||
for (const auto &service : services) {
|
||||
@@ -43,6 +35,8 @@ void MDNSComponent::setup() {
|
||||
}
|
||||
}
|
||||
|
||||
void MDNSComponent::setup() { this->setup_buffers_and_register_(register_rp2040); }
|
||||
|
||||
void MDNSComponent::loop() { MDNS.update(); }
|
||||
|
||||
void MDNSComponent::on_shutdown() {
|
||||
|
||||
@@ -4,59 +4,73 @@ from esphome.components import uart
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID
|
||||
|
||||
CODEOWNERS = ["@jorre05"]
|
||||
CODEOWNERS = ["@jorre05", "@edenhaus"]
|
||||
|
||||
DEPENDENCIES = ["uart"]
|
||||
|
||||
CONF_MICRONOVA_ID = "micronova_id"
|
||||
DOMAIN = "micronova"
|
||||
CONF_MICRONOVA_ID = f"{DOMAIN}_id"
|
||||
CONF_ENABLE_RX_PIN = "enable_rx_pin"
|
||||
CONF_MEMORY_LOCATION = "memory_location"
|
||||
CONF_MEMORY_ADDRESS = "memory_address"
|
||||
DEFAULT_POLLING_INTERVAL = "60s"
|
||||
|
||||
micronova_ns = cg.esphome_ns.namespace("micronova")
|
||||
micronova_ns = cg.esphome_ns.namespace(DOMAIN)
|
||||
|
||||
MicroNovaFunctions = micronova_ns.enum("MicroNovaFunctions", is_class=True)
|
||||
MICRONOVA_FUNCTIONS_ENUM = {
|
||||
"STOVE_FUNCTION_SWITCH": MicroNovaFunctions.STOVE_FUNCTION_SWITCH,
|
||||
"STOVE_FUNCTION_ROOM_TEMPERATURE": MicroNovaFunctions.STOVE_FUNCTION_ROOM_TEMPERATURE,
|
||||
"STOVE_FUNCTION_THERMOSTAT_TEMPERATURE": MicroNovaFunctions.STOVE_FUNCTION_THERMOSTAT_TEMPERATURE,
|
||||
"STOVE_FUNCTION_FUMES_TEMPERATURE": MicroNovaFunctions.STOVE_FUNCTION_FUMES_TEMPERATURE,
|
||||
"STOVE_FUNCTION_STOVE_POWER": MicroNovaFunctions.STOVE_FUNCTION_STOVE_POWER,
|
||||
"STOVE_FUNCTION_FAN_SPEED": MicroNovaFunctions.STOVE_FUNCTION_FAN_SPEED,
|
||||
"STOVE_FUNCTION_STOVE_STATE": MicroNovaFunctions.STOVE_FUNCTION_STOVE_STATE,
|
||||
"STOVE_FUNCTION_MEMORY_ADDRESS_SENSOR": MicroNovaFunctions.STOVE_FUNCTION_MEMORY_ADDRESS_SENSOR,
|
||||
"STOVE_FUNCTION_WATER_TEMPERATURE": MicroNovaFunctions.STOVE_FUNCTION_WATER_TEMPERATURE,
|
||||
"STOVE_FUNCTION_WATER_PRESSURE": MicroNovaFunctions.STOVE_FUNCTION_WATER_PRESSURE,
|
||||
"STOVE_FUNCTION_POWER_LEVEL": MicroNovaFunctions.STOVE_FUNCTION_POWER_LEVEL,
|
||||
"STOVE_FUNCTION_CUSTOM": MicroNovaFunctions.STOVE_FUNCTION_CUSTOM,
|
||||
}
|
||||
MicroNova = micronova_ns.class_("MicroNova", cg.Component, uart.UARTDevice)
|
||||
MicroNovaListener = micronova_ns.class_("MicroNovaListener", cg.PollingComponent)
|
||||
|
||||
MicroNova = micronova_ns.class_("MicroNova", cg.PollingComponent, uart.UARTDevice)
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(MicroNova),
|
||||
cv.Required(CONF_ENABLE_RX_PIN): pins.gpio_output_pin_schema,
|
||||
}
|
||||
).extend(uart.UART_DEVICE_SCHEMA)
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(MicroNova),
|
||||
cv.Required(CONF_ENABLE_RX_PIN): pins.gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
.extend(uart.UART_DEVICE_SCHEMA)
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
FINAL_VALIDATE_SCHEMA = uart.final_validate_device_schema(
|
||||
DOMAIN,
|
||||
baud_rate=1200,
|
||||
require_rx=True,
|
||||
require_tx=True,
|
||||
data_bits=8,
|
||||
parity="NONE",
|
||||
stop_bits=2,
|
||||
)
|
||||
|
||||
|
||||
def MICRONOVA_LISTENER_SCHEMA(default_memory_location, default_memory_address):
|
||||
return cv.Schema(
|
||||
def MICRONOVA_ADDRESS_SCHEMA(
|
||||
*,
|
||||
default_memory_location: int | None = None,
|
||||
default_memory_address: int | None = None,
|
||||
is_polling_component: bool,
|
||||
):
|
||||
location_key = (
|
||||
cv.Optional(CONF_MEMORY_LOCATION, default=default_memory_location)
|
||||
if default_memory_location is not None
|
||||
else cv.Required(CONF_MEMORY_LOCATION)
|
||||
)
|
||||
address_key = (
|
||||
cv.Optional(CONF_MEMORY_ADDRESS, default=default_memory_address)
|
||||
if default_memory_address is not None
|
||||
else cv.Required(CONF_MEMORY_ADDRESS)
|
||||
)
|
||||
schema = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(CONF_MICRONOVA_ID): cv.use_id(MicroNova),
|
||||
cv.Optional(
|
||||
CONF_MEMORY_LOCATION, default=default_memory_location
|
||||
): cv.hex_int_range(),
|
||||
cv.Optional(
|
||||
CONF_MEMORY_ADDRESS, default=default_memory_address
|
||||
): cv.hex_int_range(),
|
||||
location_key: cv.hex_int_range(min=0x00, max=0x79),
|
||||
address_key: cv.hex_int_range(min=0x00, max=0xFF),
|
||||
}
|
||||
)
|
||||
if is_polling_component:
|
||||
schema = schema.extend(cv.polling_component_schema(DEFAULT_POLLING_INTERVAL))
|
||||
return schema
|
||||
|
||||
|
||||
async def to_code_micronova_listener(mv, var, config):
|
||||
await cg.register_component(var, config)
|
||||
cg.add(mv.register_micronova_listener(var))
|
||||
cg.add(var.set_memory_location(config[CONF_MEMORY_LOCATION]))
|
||||
cg.add(var.set_memory_address(config[CONF_MEMORY_ADDRESS]))
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user