From 43a020641b89b86b7082f956e3c335de38bd97b0 Mon Sep 17 00:00:00 2001
From: Lennart <18233294+lennart-k@users.noreply.github.com>
Date: Sun, 20 Oct 2024 21:16:08 +0200
Subject: [PATCH 01/74] Fix broken ibeacon_uuid config in ble_rssi (#7640)
---
esphome/components/ble_rssi/sensor.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/esphome/components/ble_rssi/sensor.py b/esphome/components/ble_rssi/sensor.py
index e3ba1abfd7..c4e767aa21 100644
--- a/esphome/components/ble_rssi/sensor.py
+++ b/esphome/components/ble_rssi/sensor.py
@@ -45,7 +45,7 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(CONF_SERVICE_UUID): esp32_ble_tracker.bt_uuid,
cv.Optional(CONF_IBEACON_MAJOR): cv.uint16_t,
cv.Optional(CONF_IBEACON_MINOR): cv.uint16_t,
- cv.Optional(CONF_IBEACON_UUID): cv.uuid,
+ cv.Optional(CONF_IBEACON_UUID): esp32_ble_tracker.bt_uuid,
}
)
.extend(esp32_ble_tracker.ESP_BLE_DEVICE_SCHEMA)
@@ -79,7 +79,7 @@ async def to_code(config):
cg.add(var.set_service_uuid128(uuid128))
if ibeacon_uuid := config.get(CONF_IBEACON_UUID):
- ibeacon_uuid = esp32_ble_tracker.as_hex_array(str(ibeacon_uuid))
+ ibeacon_uuid = esp32_ble_tracker.as_reversed_hex_array(ibeacon_uuid)
cg.add(var.set_ibeacon_uuid(ibeacon_uuid))
if (ibeacon_major := config.get(CONF_IBEACON_MAJOR)) is not None:
From f7543a7b8dd1b5f8984c4dc84fc087df3f392784 Mon Sep 17 00:00:00 2001
From: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Date: Mon, 21 Oct 2024 11:28:52 +1300
Subject: [PATCH 02/74] Update Pull request template (#7620)
---
.github/PULL_REQUEST_TEMPLATE.md | 15 +++++++--------
1 file changed, 7 insertions(+), 8 deletions(-)
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 3bf9c4e1f6..5703d39be1 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -7,11 +7,16 @@
- [ ] Bugfix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
+- [ ] Code quality improvements to existing code or addition of tests
- [ ] Other
-**Related issue or feature (if applicable):** fixes
+**Related issue or feature (if applicable):**
-**Pull request in [esphome-docs](https://github.com/esphome/esphome-docs) with documentation (if applicable):** esphome/esphome-docs#
+- fixes
+
+**Pull request in [esphome-docs](https://github.com/esphome/esphome-docs) with documentation (if applicable):**
+
+- esphome/esphome-docs#
## Test Environment
@@ -23,12 +28,6 @@
- [ ] RTL87xx
## Example entry for `config.yaml`:
-
```yaml
# Example config.yaml
From 657527655d380554edfdd3274d7b1d5ac1b4a32a Mon Sep 17 00:00:00 2001
From: Samuel Sieb
Date: Sun, 20 Oct 2024 17:40:43 -0700
Subject: [PATCH 03/74] auto-load preferences (#7642)
Co-authored-by: Samuel Sieb
---
esphome/components/host/__init__.py | 2 +-
esphome/components/libretiny/__init__.py | 2 +-
esphome/components/rp2040/__init__.py | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/esphome/components/host/__init__.py b/esphome/components/host/__init__.py
index e83bf2dba8..eb8cfbd984 100644
--- a/esphome/components/host/__init__.py
+++ b/esphome/components/host/__init__.py
@@ -16,7 +16,7 @@ from .const import KEY_HOST
from .gpio import host_pin_to_code # noqa
CODEOWNERS = ["@esphome/core", "@clydebarrow"]
-AUTO_LOAD = ["network"]
+AUTO_LOAD = ["network", "preferences"]
def set_core_data(config):
diff --git a/esphome/components/libretiny/__init__.py b/esphome/components/libretiny/__init__.py
index cc7fae7e70..b29d2e309c 100644
--- a/esphome/components/libretiny/__init__.py
+++ b/esphome/components/libretiny/__init__.py
@@ -46,7 +46,7 @@ from .const import (
_LOGGER = logging.getLogger(__name__)
CODEOWNERS = ["@kuba2k2"]
-AUTO_LOAD = []
+AUTO_LOAD = ["preferences"]
def _detect_variant(value):
diff --git a/esphome/components/rp2040/__init__.py b/esphome/components/rp2040/__init__.py
index 925acb629d..f59962477f 100644
--- a/esphome/components/rp2040/__init__.py
+++ b/esphome/components/rp2040/__init__.py
@@ -26,7 +26,7 @@ from .gpio import rp2040_pin_to_code # noqa
_LOGGER = logging.getLogger(__name__)
CODEOWNERS = ["@jesserockz"]
-AUTO_LOAD = []
+AUTO_LOAD = ["preferences"]
def set_core_data(config):
From 5e8794175dceb777f928a2966c4c5e9a977c2acc Mon Sep 17 00:00:00 2001
From: Keith Burzinski
Date: Mon, 21 Oct 2024 17:46:41 -0500
Subject: [PATCH 04/74] [wifi] Support custom MAC on Arduino, too (#7644)
---
esphome/components/esp32/__init__.py | 12 ++++++++++--
.../components/wifi/wifi_component_esp32_arduino.cpp | 5 +++++
2 files changed, 15 insertions(+), 2 deletions(-)
diff --git a/esphome/components/esp32/__init__.py b/esphome/components/esp32/__init__.py
index 8a73f2020d..61fbb53e3a 100644
--- a/esphome/components/esp32/__init__.py
+++ b/esphome/components/esp32/__init__.py
@@ -395,6 +395,13 @@ ARDUINO_FRAMEWORK_SCHEMA = cv.All(
cv.Optional(CONF_VERSION, default="recommended"): cv.string_strict,
cv.Optional(CONF_SOURCE): cv.string_strict,
cv.Optional(CONF_PLATFORM_VERSION): _parse_platform_version,
+ cv.Optional(CONF_ADVANCED, default={}): cv.Schema(
+ {
+ cv.Optional(
+ CONF_IGNORE_EFUSE_CUSTOM_MAC, default=False
+ ): cv.boolean,
+ }
+ ),
}
),
_arduino_check_versions,
@@ -494,6 +501,9 @@ async def to_code(config):
conf = config[CONF_FRAMEWORK]
cg.add_platformio_option("platform", conf[CONF_PLATFORM_VERSION])
+ if CONF_ADVANCED in conf and conf[CONF_ADVANCED][CONF_IGNORE_EFUSE_CUSTOM_MAC]:
+ cg.add_define("USE_ESP32_IGNORE_EFUSE_CUSTOM_MAC")
+
add_extra_script(
"post",
"post_build.py",
@@ -540,8 +550,6 @@ async def to_code(config):
for name, value in conf[CONF_SDKCONFIG_OPTIONS].items():
add_idf_sdkconfig_option(name, RawSdkconfigValue(value))
- if conf[CONF_ADVANCED][CONF_IGNORE_EFUSE_CUSTOM_MAC]:
- cg.add_define("USE_ESP32_IGNORE_EFUSE_CUSTOM_MAC")
if conf[CONF_ADVANCED].get(CONF_IGNORE_EFUSE_MAC_CRC):
add_idf_sdkconfig_option("CONFIG_ESP_MAC_IGNORE_MAC_CRC_ERROR", True)
if (framework_ver.major, framework_ver.minor) >= (4, 4):
diff --git a/esphome/components/wifi/wifi_component_esp32_arduino.cpp b/esphome/components/wifi/wifi_component_esp32_arduino.cpp
index b8724838c8..ef4308b28c 100644
--- a/esphome/components/wifi/wifi_component_esp32_arduino.cpp
+++ b/esphome/components/wifi/wifi_component_esp32_arduino.cpp
@@ -34,6 +34,11 @@ static esp_netif_t *s_ap_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non
static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
void WiFiComponent::wifi_pre_setup_() {
+ uint8_t mac[6];
+ if (has_custom_mac_address()) {
+ get_mac_address_raw(mac);
+ set_mac_address(mac);
+ }
auto f = std::bind(&WiFiComponent::wifi_event_callback_, this, std::placeholders::_1, std::placeholders::_2);
WiFi.onEvent(f);
WiFi.persistent(false);
From c8d0cde329a83dd042412651c033dd133c9a3330 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 22 Oct 2024 09:49:12 +1100
Subject: [PATCH 05/74] [config] Ensure user-supplied build flags don't get
silently overwritten (#7622)
---
esphome/core/config.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/esphome/core/config.py b/esphome/core/config.py
index f4253bee87..8c130eb6db 100644
--- a/esphome/core/config.py
+++ b/esphome/core/config.py
@@ -318,6 +318,8 @@ async def add_includes(includes):
async def _add_platformio_options(pio_options):
# Add includes at the very end, so that they override everything
for key, val in pio_options.items():
+ if key == "build_flags" and not isinstance(val, list):
+ val = [val]
cg.add_platformio_option(key, val)
From 612e2c164406fe0d4670b8af68478c3b3644c47e Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 22 Oct 2024 09:50:16 +1100
Subject: [PATCH 06/74] [lvgl] Defer display rotation reset until setup().
(Bugfix) (#7627)
---
esphome/components/lvgl/lvgl_esphome.cpp | 19 ++++++-------------
1 file changed, 6 insertions(+), 13 deletions(-)
diff --git a/esphome/components/lvgl/lvgl_esphome.cpp b/esphome/components/lvgl/lvgl_esphome.cpp
index 413b039af0..c8f7848a4f 100644
--- a/esphome/components/lvgl/lvgl_esphome.cpp
+++ b/esphome/components/lvgl/lvgl_esphome.cpp
@@ -84,6 +84,7 @@ lv_event_code_t lv_api_event; // NOLINT
lv_event_code_t lv_update_event; // NOLINT
void LvglComponent::dump_config() {
ESP_LOGCONFIG(TAG, "LVGL:");
+ ESP_LOGCONFIG(TAG, " Display width/height: %d x %d", this->disp_drv_.hor_res, this->disp_drv_.ver_res);
ESP_LOGCONFIG(TAG, " Rotation: %d", this->rotation);
ESP_LOGCONFIG(TAG, " Draw rounding: %d", (int) this->draw_rounding);
}
@@ -426,19 +427,8 @@ LvglComponent::LvglComponent(std::vector displays, float buf
this->disp_drv_.full_refresh = this->full_refresh_;
this->disp_drv_.flush_cb = static_flush_cb;
this->disp_drv_.rounder_cb = rounder_cb;
- // reset the display rotation since we will handle all rotations
- display->set_rotation(display::DISPLAY_ROTATION_0_DEGREES);
- switch (this->rotation) {
- default:
- this->disp_drv_.hor_res = (lv_coord_t) display->get_width();
- this->disp_drv_.ver_res = (lv_coord_t) display->get_height();
- break;
- case display::DISPLAY_ROTATION_90_DEGREES:
- case display::DISPLAY_ROTATION_270_DEGREES:
- this->disp_drv_.ver_res = (lv_coord_t) display->get_width();
- this->disp_drv_.hor_res = (lv_coord_t) display->get_height();
- break;
- }
+ this->disp_drv_.hor_res = (lv_coord_t) display->get_width();
+ this->disp_drv_.ver_res = (lv_coord_t) display->get_height();
this->disp_ = lv_disp_drv_register(&this->disp_drv_);
}
@@ -459,6 +449,9 @@ void LvglComponent::setup() {
esp_log_printf_(LVGL_LOG_LEVEL, TAG, 0, "%.*s", (int) strlen(buf) - 1, buf);
});
#endif
+ // Rotation will be handled by our drawing function, so reset the display rotation.
+ for (auto *display : this->displays_)
+ display->set_rotation(display::DISPLAY_ROTATION_0_DEGREES);
this->show_page(0, LV_SCR_LOAD_ANIM_NONE, 0);
lv_disp_trig_activity(this->disp_);
ESP_LOGCONFIG(TAG, "LVGL Setup complete");
From 40ad6befa83f23674d09bf70198eb8761fa69c81 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 22 Oct 2024 09:51:40 +1100
Subject: [PATCH 07/74] [lvgl] Remove states from style definitions (Bugfix)
(#7645)
---
esphome/components/lvgl/__init__.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/esphome/components/lvgl/__init__.py b/esphome/components/lvgl/__init__.py
index beaf279a9a..215fdecdb5 100644
--- a/esphome/components/lvgl/__init__.py
+++ b/esphome/components/lvgl/__init__.py
@@ -33,7 +33,7 @@ from .schemas import (
FLEX_OBJ_SCHEMA,
GRID_CELL_SCHEMA,
LAYOUT_SCHEMAS,
- STATE_SCHEMA,
+ STYLE_SCHEMA,
WIDGET_TYPES,
any_widget_schema,
container_schema,
@@ -342,7 +342,7 @@ CONFIG_SCHEMA = (
),
cv.Optional(df.CONF_STYLE_DEFINITIONS): cv.ensure_list(
cv.Schema({cv.Required(CONF_ID): cv.declare_id(lv_style_t)})
- .extend(STATE_SCHEMA)
+ .extend(STYLE_SCHEMA)
.extend(
{
cv.Optional(df.CONF_GRID_CELL_X_ALIGN): grid_alignments,
From dc42427c604ed14ab94270df8148fad22e101ee4 Mon Sep 17 00:00:00 2001
From: Michael Hansen
Date: Mon, 21 Oct 2024 18:14:07 -0500
Subject: [PATCH 08/74] Move setting global voice assistant to constructor
(#7630)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
---
esphome/components/voice_assistant/voice_assistant.cpp | 8 ++------
esphome/components/voice_assistant/voice_assistant.h | 3 ++-
2 files changed, 4 insertions(+), 7 deletions(-)
diff --git a/esphome/components/voice_assistant/voice_assistant.cpp b/esphome/components/voice_assistant/voice_assistant.cpp
index a2210f188d..0b53e74ba3 100644
--- a/esphome/components/voice_assistant/voice_assistant.cpp
+++ b/esphome/components/voice_assistant/voice_assistant.cpp
@@ -23,6 +23,8 @@ static const size_t SEND_BUFFER_SIZE = INPUT_BUFFER_SIZE * sizeof(int16_t);
static const size_t RECEIVE_SIZE = 1024;
static const size_t SPEAKER_BUFFER_SIZE = 16 * RECEIVE_SIZE;
+VoiceAssistant::VoiceAssistant() { global_voice_assistant = this; }
+
float VoiceAssistant::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
bool VoiceAssistant::start_udp_socket_() {
@@ -68,12 +70,6 @@ bool VoiceAssistant::start_udp_socket_() {
return true;
}
-void VoiceAssistant::setup() {
- ESP_LOGCONFIG(TAG, "Setting up Voice Assistant...");
-
- global_voice_assistant = this;
-}
-
bool VoiceAssistant::allocate_buffers_() {
if (this->send_buffer_ != nullptr) {
return true; // Already allocated
diff --git a/esphome/components/voice_assistant/voice_assistant.h b/esphome/components/voice_assistant/voice_assistant.h
index 56ada0e75a..870e2acdaa 100644
--- a/esphome/components/voice_assistant/voice_assistant.h
+++ b/esphome/components/voice_assistant/voice_assistant.h
@@ -91,7 +91,8 @@ struct Configuration {
class VoiceAssistant : public Component {
public:
- void setup() override;
+ VoiceAssistant();
+
void loop() override;
float get_setup_priority() const override;
void start_streaming();
From 7004053538c16544740e5e866395e9f94da1a63a Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Thu, 17 Oct 2024 11:32:22 +1100
Subject: [PATCH 09/74] [config] Fix crash with empty substitutions block
(#7612)
---
esphome/config.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/esphome/config.py b/esphome/config.py
index a2d0d15477..7d48569d2d 100644
--- a/esphome/config.py
+++ b/esphome/config.py
@@ -782,7 +782,7 @@ def validate_config(
from esphome.components import substitutions
result[CONF_SUBSTITUTIONS] = {
- **config.get(CONF_SUBSTITUTIONS, {}),
+ **(config.get(CONF_SUBSTITUTIONS) or {}),
**command_line_substitutions,
}
result.add_output_path([CONF_SUBSTITUTIONS], CONF_SUBSTITUTIONS)
From 3dd34f66284ff8c5b0a69e70d57f6273d3395544 Mon Sep 17 00:00:00 2001
From: Lennart <18233294+lennart-k@users.noreply.github.com>
Date: Sun, 20 Oct 2024 21:16:08 +0200
Subject: [PATCH 10/74] Fix broken ibeacon_uuid config in ble_rssi (#7640)
---
esphome/components/ble_rssi/sensor.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/esphome/components/ble_rssi/sensor.py b/esphome/components/ble_rssi/sensor.py
index e3ba1abfd7..c4e767aa21 100644
--- a/esphome/components/ble_rssi/sensor.py
+++ b/esphome/components/ble_rssi/sensor.py
@@ -45,7 +45,7 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(CONF_SERVICE_UUID): esp32_ble_tracker.bt_uuid,
cv.Optional(CONF_IBEACON_MAJOR): cv.uint16_t,
cv.Optional(CONF_IBEACON_MINOR): cv.uint16_t,
- cv.Optional(CONF_IBEACON_UUID): cv.uuid,
+ cv.Optional(CONF_IBEACON_UUID): esp32_ble_tracker.bt_uuid,
}
)
.extend(esp32_ble_tracker.ESP_BLE_DEVICE_SCHEMA)
@@ -79,7 +79,7 @@ async def to_code(config):
cg.add(var.set_service_uuid128(uuid128))
if ibeacon_uuid := config.get(CONF_IBEACON_UUID):
- ibeacon_uuid = esp32_ble_tracker.as_hex_array(str(ibeacon_uuid))
+ ibeacon_uuid = esp32_ble_tracker.as_reversed_hex_array(ibeacon_uuid)
cg.add(var.set_ibeacon_uuid(ibeacon_uuid))
if (ibeacon_major := config.get(CONF_IBEACON_MAJOR)) is not None:
From 10791db82e7784f2e8b22a69ca8ad01223f8f1d7 Mon Sep 17 00:00:00 2001
From: Samuel Sieb
Date: Sun, 20 Oct 2024 17:40:43 -0700
Subject: [PATCH 11/74] auto-load preferences (#7642)
Co-authored-by: Samuel Sieb
---
esphome/components/host/__init__.py | 2 +-
esphome/components/libretiny/__init__.py | 2 +-
esphome/components/rp2040/__init__.py | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/esphome/components/host/__init__.py b/esphome/components/host/__init__.py
index e83bf2dba8..eb8cfbd984 100644
--- a/esphome/components/host/__init__.py
+++ b/esphome/components/host/__init__.py
@@ -16,7 +16,7 @@ from .const import KEY_HOST
from .gpio import host_pin_to_code # noqa
CODEOWNERS = ["@esphome/core", "@clydebarrow"]
-AUTO_LOAD = ["network"]
+AUTO_LOAD = ["network", "preferences"]
def set_core_data(config):
diff --git a/esphome/components/libretiny/__init__.py b/esphome/components/libretiny/__init__.py
index cc7fae7e70..b29d2e309c 100644
--- a/esphome/components/libretiny/__init__.py
+++ b/esphome/components/libretiny/__init__.py
@@ -46,7 +46,7 @@ from .const import (
_LOGGER = logging.getLogger(__name__)
CODEOWNERS = ["@kuba2k2"]
-AUTO_LOAD = []
+AUTO_LOAD = ["preferences"]
def _detect_variant(value):
diff --git a/esphome/components/rp2040/__init__.py b/esphome/components/rp2040/__init__.py
index 925acb629d..f59962477f 100644
--- a/esphome/components/rp2040/__init__.py
+++ b/esphome/components/rp2040/__init__.py
@@ -26,7 +26,7 @@ from .gpio import rp2040_pin_to_code # noqa
_LOGGER = logging.getLogger(__name__)
CODEOWNERS = ["@jesserockz"]
-AUTO_LOAD = []
+AUTO_LOAD = ["preferences"]
def set_core_data(config):
From 748256b3eef8bcce7472983bd5d6f48dd55362cb Mon Sep 17 00:00:00 2001
From: Keith Burzinski
Date: Mon, 21 Oct 2024 17:46:41 -0500
Subject: [PATCH 12/74] [wifi] Support custom MAC on Arduino, too (#7644)
---
esphome/components/esp32/__init__.py | 12 ++++++++++--
.../components/wifi/wifi_component_esp32_arduino.cpp | 5 +++++
2 files changed, 15 insertions(+), 2 deletions(-)
diff --git a/esphome/components/esp32/__init__.py b/esphome/components/esp32/__init__.py
index 8a73f2020d..61fbb53e3a 100644
--- a/esphome/components/esp32/__init__.py
+++ b/esphome/components/esp32/__init__.py
@@ -395,6 +395,13 @@ ARDUINO_FRAMEWORK_SCHEMA = cv.All(
cv.Optional(CONF_VERSION, default="recommended"): cv.string_strict,
cv.Optional(CONF_SOURCE): cv.string_strict,
cv.Optional(CONF_PLATFORM_VERSION): _parse_platform_version,
+ cv.Optional(CONF_ADVANCED, default={}): cv.Schema(
+ {
+ cv.Optional(
+ CONF_IGNORE_EFUSE_CUSTOM_MAC, default=False
+ ): cv.boolean,
+ }
+ ),
}
),
_arduino_check_versions,
@@ -494,6 +501,9 @@ async def to_code(config):
conf = config[CONF_FRAMEWORK]
cg.add_platformio_option("platform", conf[CONF_PLATFORM_VERSION])
+ if CONF_ADVANCED in conf and conf[CONF_ADVANCED][CONF_IGNORE_EFUSE_CUSTOM_MAC]:
+ cg.add_define("USE_ESP32_IGNORE_EFUSE_CUSTOM_MAC")
+
add_extra_script(
"post",
"post_build.py",
@@ -540,8 +550,6 @@ async def to_code(config):
for name, value in conf[CONF_SDKCONFIG_OPTIONS].items():
add_idf_sdkconfig_option(name, RawSdkconfigValue(value))
- if conf[CONF_ADVANCED][CONF_IGNORE_EFUSE_CUSTOM_MAC]:
- cg.add_define("USE_ESP32_IGNORE_EFUSE_CUSTOM_MAC")
if conf[CONF_ADVANCED].get(CONF_IGNORE_EFUSE_MAC_CRC):
add_idf_sdkconfig_option("CONFIG_ESP_MAC_IGNORE_MAC_CRC_ERROR", True)
if (framework_ver.major, framework_ver.minor) >= (4, 4):
diff --git a/esphome/components/wifi/wifi_component_esp32_arduino.cpp b/esphome/components/wifi/wifi_component_esp32_arduino.cpp
index b8724838c8..ef4308b28c 100644
--- a/esphome/components/wifi/wifi_component_esp32_arduino.cpp
+++ b/esphome/components/wifi/wifi_component_esp32_arduino.cpp
@@ -34,6 +34,11 @@ static esp_netif_t *s_ap_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non
static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
void WiFiComponent::wifi_pre_setup_() {
+ uint8_t mac[6];
+ if (has_custom_mac_address()) {
+ get_mac_address_raw(mac);
+ set_mac_address(mac);
+ }
auto f = std::bind(&WiFiComponent::wifi_event_callback_, this, std::placeholders::_1, std::placeholders::_2);
WiFi.onEvent(f);
WiFi.persistent(false);
From c26c96b8f469a3071c14ef91b5e7aa073a3aa9ca Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 22 Oct 2024 09:49:12 +1100
Subject: [PATCH 13/74] [config] Ensure user-supplied build flags don't get
silently overwritten (#7622)
---
esphome/core/config.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/esphome/core/config.py b/esphome/core/config.py
index f4253bee87..8c130eb6db 100644
--- a/esphome/core/config.py
+++ b/esphome/core/config.py
@@ -318,6 +318,8 @@ async def add_includes(includes):
async def _add_platformio_options(pio_options):
# Add includes at the very end, so that they override everything
for key, val in pio_options.items():
+ if key == "build_flags" and not isinstance(val, list):
+ val = [val]
cg.add_platformio_option(key, val)
From 3ebdd62c672dba8fa7d4c4ebd021750394c76596 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 22 Oct 2024 09:51:40 +1100
Subject: [PATCH 14/74] [lvgl] Remove states from style definitions (Bugfix)
(#7645)
---
esphome/components/lvgl/__init__.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/esphome/components/lvgl/__init__.py b/esphome/components/lvgl/__init__.py
index ce3843567b..1a587edb57 100644
--- a/esphome/components/lvgl/__init__.py
+++ b/esphome/components/lvgl/__init__.py
@@ -33,7 +33,7 @@ from .schemas import (
FLEX_OBJ_SCHEMA,
GRID_CELL_SCHEMA,
LAYOUT_SCHEMAS,
- STATE_SCHEMA,
+ STYLE_SCHEMA,
WIDGET_TYPES,
any_widget_schema,
container_schema,
@@ -323,7 +323,7 @@ CONFIG_SCHEMA = (
),
cv.Optional(df.CONF_STYLE_DEFINITIONS): cv.ensure_list(
cv.Schema({cv.Required(CONF_ID): cv.declare_id(lv_style_t)})
- .extend(STATE_SCHEMA)
+ .extend(STYLE_SCHEMA)
.extend(
{
cv.Optional(df.CONF_GRID_CELL_X_ALIGN): grid_alignments,
From d95b370998527e279ac3a9c3376ede984929cd5d Mon Sep 17 00:00:00 2001
From: Michael Hansen
Date: Mon, 21 Oct 2024 18:14:07 -0500
Subject: [PATCH 15/74] Move setting global voice assistant to constructor
(#7630)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
---
esphome/components/voice_assistant/voice_assistant.cpp | 8 ++------
esphome/components/voice_assistant/voice_assistant.h | 3 ++-
2 files changed, 4 insertions(+), 7 deletions(-)
diff --git a/esphome/components/voice_assistant/voice_assistant.cpp b/esphome/components/voice_assistant/voice_assistant.cpp
index a2210f188d..0b53e74ba3 100644
--- a/esphome/components/voice_assistant/voice_assistant.cpp
+++ b/esphome/components/voice_assistant/voice_assistant.cpp
@@ -23,6 +23,8 @@ static const size_t SEND_BUFFER_SIZE = INPUT_BUFFER_SIZE * sizeof(int16_t);
static const size_t RECEIVE_SIZE = 1024;
static const size_t SPEAKER_BUFFER_SIZE = 16 * RECEIVE_SIZE;
+VoiceAssistant::VoiceAssistant() { global_voice_assistant = this; }
+
float VoiceAssistant::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
bool VoiceAssistant::start_udp_socket_() {
@@ -68,12 +70,6 @@ bool VoiceAssistant::start_udp_socket_() {
return true;
}
-void VoiceAssistant::setup() {
- ESP_LOGCONFIG(TAG, "Setting up Voice Assistant...");
-
- global_voice_assistant = this;
-}
-
bool VoiceAssistant::allocate_buffers_() {
if (this->send_buffer_ != nullptr) {
return true; // Already allocated
diff --git a/esphome/components/voice_assistant/voice_assistant.h b/esphome/components/voice_assistant/voice_assistant.h
index 56ada0e75a..870e2acdaa 100644
--- a/esphome/components/voice_assistant/voice_assistant.h
+++ b/esphome/components/voice_assistant/voice_assistant.h
@@ -91,7 +91,8 @@ struct Configuration {
class VoiceAssistant : public Component {
public:
- void setup() override;
+ VoiceAssistant();
+
void loop() override;
float get_setup_priority() const override;
void start_streaming();
From 735c04cd6995e1cd220440af0fb79100a0b638f2 Mon Sep 17 00:00:00 2001
From: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Date: Tue, 22 Oct 2024 12:57:17 +1300
Subject: [PATCH 16/74] Bump version to 2024.10.1
---
esphome/const.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/esphome/const.py b/esphome/const.py
index 5061b1a439..5fa457b25a 100644
--- a/esphome/const.py
+++ b/esphome/const.py
@@ -1,6 +1,6 @@
"""Constants used by esphome."""
-__version__ = "2024.10.0"
+__version__ = "2024.10.1"
ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_"
VALID_SUBSTITUTIONS_CHARACTERS = (
From 8bb4316956a39a8c7141a9504f56ee0f5c32812a Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 22 Oct 2024 14:03:32 +1100
Subject: [PATCH 17/74] [lvgl] light schema should require `widget:` not `led:`
(Bugfix) (#7649)
---
esphome/components/lvgl/light/__init__.py | 8 ++++----
tests/components/lvgl/common.yaml | 2 +-
2 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/esphome/components/lvgl/light/__init__.py b/esphome/components/lvgl/light/__init__.py
index a0eeded349..8031ae8221 100644
--- a/esphome/components/lvgl/light/__init__.py
+++ b/esphome/components/lvgl/light/__init__.py
@@ -2,9 +2,9 @@ import esphome.codegen as cg
from esphome.components import light
from esphome.components.light import LightOutput
import esphome.config_validation as cv
-from esphome.const import CONF_GAMMA_CORRECT, CONF_LED, CONF_OUTPUT_ID
+from esphome.const import CONF_GAMMA_CORRECT, CONF_OUTPUT_ID
-from ..defines import CONF_LVGL_ID
+from ..defines import CONF_LVGL_ID, CONF_WIDGET
from ..lvcode import LvContext
from ..schemas import LVGL_SCHEMA
from ..types import LvType, lvgl_ns
@@ -15,7 +15,7 @@ LVLight = lvgl_ns.class_("LVLight", LightOutput)
CONFIG_SCHEMA = light.RGB_LIGHT_SCHEMA.extend(
{
cv.Optional(CONF_GAMMA_CORRECT, default=0.0): cv.positive_float,
- cv.Required(CONF_LED): cv.use_id(lv_led_t),
+ cv.Required(CONF_WIDGET): cv.use_id(lv_led_t),
cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(LVLight),
}
).extend(LVGL_SCHEMA)
@@ -26,7 +26,7 @@ async def to_code(config):
await light.register_light(var, config)
paren = await cg.get_variable(config[CONF_LVGL_ID])
- widget = await get_widgets(config, CONF_LED)
+ widget = await get_widgets(config, CONF_WIDGET)
widget = widget[0]
await wait_for_widgets()
async with LvContext(paren) as ctx:
diff --git a/tests/components/lvgl/common.yaml b/tests/components/lvgl/common.yaml
index 5dcf30e0c1..cebc3caaa7 100644
--- a/tests/components/lvgl/common.yaml
+++ b/tests/components/lvgl/common.yaml
@@ -93,7 +93,7 @@ light:
- platform: lvgl
name: LVGL LED
id: lv_light
- led: lv_led
+ widget: lv_led
binary_sensor:
- platform: lvgl
From ff48f53989f7886c167364e04df72f79039a9bac Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 22 Oct 2024 14:05:39 +1100
Subject: [PATCH 18/74] [image] Fix compile time problem with host image not
using lvgl (#7654)
---
esphome/components/image/image.h | 7 +------
esphome/components/lvgl/lvgl_proxy.h | 17 +++++++++++++++++
2 files changed, 18 insertions(+), 6 deletions(-)
create mode 100644 esphome/components/lvgl/lvgl_proxy.h
diff --git a/esphome/components/image/image.h b/esphome/components/image/image.h
index ae5a7a814d..a8a8aab2c2 100644
--- a/esphome/components/image/image.h
+++ b/esphome/components/image/image.h
@@ -3,12 +3,7 @@
#include "esphome/components/display/display.h"
#ifdef USE_LVGL
-// required for clang-tidy
-#ifndef LV_CONF_H
-#define LV_CONF_SKIP 1 // NOLINT
-#endif // LV_CONF_H
-
-#include
+#include "esphome/components/lvgl/lvgl_proxy.h"
#endif // USE_LVGL
namespace esphome {
diff --git a/esphome/components/lvgl/lvgl_proxy.h b/esphome/components/lvgl/lvgl_proxy.h
new file mode 100644
index 0000000000..0ccd80e541
--- /dev/null
+++ b/esphome/components/lvgl/lvgl_proxy.h
@@ -0,0 +1,17 @@
+#pragma once
+/**
+* This header is for use in components that might or might not use LVGL. There is a platformio bug where
+the mere mention of a header file, even if ifdefed, causes the build to fail. This is a workaround, since if this
+file is included in the build, LVGL is always included.
+*/
+#ifdef USE_LVGL
+// required for clang-tidy
+#ifndef LV_CONF_H
+#define LV_CONF_SKIP 1 // NOLINT
+#endif // LV_CONF_H
+
+#include
+namespace esphome {
+namespace lvgl {} // namespace lvgl
+} // namespace esphome
+#endif // USE_LVGL
From 3ac730fb2f5b7231e77d5d7c3822e7cc59fb4e59 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 22 Oct 2024 14:06:58 +1100
Subject: [PATCH 19/74] [lvgl] Fix rotation code for 90deg (Bugfix) (#7653)
---
esphome/components/lvgl/lvgl_esphome.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/esphome/components/lvgl/lvgl_esphome.cpp b/esphome/components/lvgl/lvgl_esphome.cpp
index c8f7848a4f..70cfb859de 100644
--- a/esphome/components/lvgl/lvgl_esphome.cpp
+++ b/esphome/components/lvgl/lvgl_esphome.cpp
@@ -146,7 +146,7 @@ void LvglComponent::draw_buffer_(const lv_area_t *area, lv_color_t *ptr) {
lv_color_t *dst = this->rotate_buf_;
switch (this->rotation) {
case display::DISPLAY_ROTATION_90_DEGREES:
- for (lv_coord_t x = height - 1; x-- != 0;) {
+ for (lv_coord_t x = height; x-- != 0;) {
for (lv_coord_t y = 0; y != width; y++) {
dst[y * height + x] = *ptr++;
}
From 6330177d24b82060afec7628d6152fea6b54f963 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 22 Oct 2024 14:10:09 +1100
Subject: [PATCH 20/74] [lvgl] Allow strings to be interpreted as integers
(Bugfix) (#7652)
---
esphome/components/lvgl/lv_validation.py | 6 ++----
tests/components/lvgl/lvgl-package.yaml | 4 ++--
2 files changed, 4 insertions(+), 6 deletions(-)
diff --git a/esphome/components/lvgl/lv_validation.py b/esphome/components/lvgl/lv_validation.py
index fd840cc417..9af25a4e90 100644
--- a/esphome/components/lvgl/lv_validation.py
+++ b/esphome/components/lvgl/lv_validation.py
@@ -274,10 +274,8 @@ def size_validator(value):
return ["SIZE_CONTENT", "number of pixels", "percentage"]
if isinstance(value, str) and value.lower().endswith("px"):
value = cv.int_(value[:-2])
- if isinstance(value, str) and not value.endswith("%"):
- if value.upper() == "SIZE_CONTENT":
- return "LV_SIZE_CONTENT"
- raise cv.Invalid("must be 'size_content', a percentage or an integer (pixels)")
+ if isinstance(value, str) and value.upper() == "SIZE_CONTENT":
+ return "LV_SIZE_CONTENT"
return pixels_or_percent_validator(value)
diff --git a/tests/components/lvgl/lvgl-package.yaml b/tests/components/lvgl/lvgl-package.yaml
index cef76396c2..7fd824a87b 100644
--- a/tests/components/lvgl/lvgl-package.yaml
+++ b/tests/components/lvgl/lvgl-package.yaml
@@ -422,7 +422,7 @@ lvgl:
id: lv_image
src: cat_image
align: top_left
- y: 50
+ y: "50"
- tileview:
id: tileview_id
scrollbar_mode: active
@@ -461,7 +461,7 @@ lvgl:
bg_opa: transp
knob:
radius: 1
- width: 4
+ width: "4"
height: 10%
bg_color: 0x000000
width: 100%
From 2597975ae00dde096522b80824dbf9915a0d2fd7 Mon Sep 17 00:00:00 2001
From: Edward Firmo <94725493+edwardtfn@users.noreply.github.com>
Date: Tue, 22 Oct 2024 05:29:16 +0200
Subject: [PATCH 21/74] [rtttl] Add `get_gain()` (#7647)
---
esphome/components/rtttl/rtttl.cpp | 5 ++++-
esphome/components/rtttl/rtttl.h | 1 +
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/esphome/components/rtttl/rtttl.cpp b/esphome/components/rtttl/rtttl.cpp
index 495b5c1c8a..db4cc731e4 100644
--- a/esphome/components/rtttl/rtttl.cpp
+++ b/esphome/components/rtttl/rtttl.cpp
@@ -26,7 +26,10 @@ inline double deg2rad(double degrees) {
return degrees * PI_ON_180;
}
-void Rtttl::dump_config() { ESP_LOGCONFIG(TAG, "Rtttl"); }
+void Rtttl::dump_config() {
+ ESP_LOGCONFIG(TAG, "Rtttl:");
+ ESP_LOGCONFIG(TAG, " Gain: %f", gain_);
+}
void Rtttl::play(std::string rtttl) {
if (this->state_ != State::STATE_STOPPED && this->state_ != State::STATE_STOPPING) {
diff --git a/esphome/components/rtttl/rtttl.h b/esphome/components/rtttl/rtttl.h
index 3cb6e3f5fb..10c290c5fb 100644
--- a/esphome/components/rtttl/rtttl.h
+++ b/esphome/components/rtttl/rtttl.h
@@ -39,6 +39,7 @@ class Rtttl : public Component {
#ifdef USE_SPEAKER
void set_speaker(speaker::Speaker *speaker) { this->speaker_ = speaker; }
#endif
+ float get_gain() { return gain_; }
void set_gain(float gain) {
if (gain < 0.1f)
gain = 0.1f;
From a932ca2f64213e2af34c4d2e25f7f82766e98ccb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Rodrigo=20Mart=C3=ADn?=
Date: Tue, 22 Oct 2024 05:38:25 +0200
Subject: [PATCH 22/74] feat(MQTT): Add subscribe QoS to discovery (#7648)
---
esphome/components/mqtt/__init__.py | 3 +++
esphome/components/mqtt/mqtt_component.cpp | 6 ++++++
esphome/components/mqtt/mqtt_component.h | 4 ++++
esphome/components/mqtt/mqtt_const.h | 2 ++
esphome/config_validation.py | 4 +++-
esphome/const.py | 1 +
tests/components/mqtt/common.yaml | 1 +
7 files changed, 20 insertions(+), 1 deletion(-)
diff --git a/esphome/components/mqtt/__init__.py b/esphome/components/mqtt/__init__.py
index 336d928f71..8851581ea0 100644
--- a/esphome/components/mqtt/__init__.py
+++ b/esphome/components/mqtt/__init__.py
@@ -41,6 +41,7 @@ from esphome.const import (
CONF_SHUTDOWN_MESSAGE,
CONF_SSL_FINGERPRINTS,
CONF_STATE_TOPIC,
+ CONF_SUBSCRIBE_QOS,
CONF_TOPIC,
CONF_TOPIC_PREFIX,
CONF_TRIGGER_ID,
@@ -518,6 +519,8 @@ async def register_mqtt_component(var, config):
cg.add(var.set_qos(config[CONF_QOS]))
if CONF_RETAIN in config:
cg.add(var.set_retain(config[CONF_RETAIN]))
+ if CONF_SUBSCRIBE_QOS in config:
+ cg.add(var.set_subscribe_qos(config[CONF_SUBSCRIBE_QOS]))
if not config.get(CONF_DISCOVERY, True):
cg.add(var.disable_discovery())
if CONF_STATE_TOPIC in config:
diff --git a/esphome/components/mqtt/mqtt_component.cpp b/esphome/components/mqtt/mqtt_component.cpp
index 295fbba5e5..3b9d367a7b 100644
--- a/esphome/components/mqtt/mqtt_component.cpp
+++ b/esphome/components/mqtt/mqtt_component.cpp
@@ -16,6 +16,8 @@ static const char *const TAG = "mqtt.component";
void MQTTComponent::set_qos(uint8_t qos) { this->qos_ = qos; }
+void MQTTComponent::set_subscribe_qos(uint8_t qos) { this->subscribe_qos_ = qos; }
+
void MQTTComponent::set_retain(bool retain) { this->retain_ = retain; }
std::string MQTTComponent::get_discovery_topic_(const MQTTDiscoveryInfo &discovery_info) const {
@@ -76,6 +78,10 @@ bool MQTTComponent::send_discovery_() {
config.command_topic = true;
this->send_discovery(root, config);
+ // Set subscription QoS (default is 0)
+ if (this->subscribe_qos_ != 0) {
+ root[MQTT_QOS] = this->subscribe_qos_;
+ }
// Fields from EntityBase
if (this->get_entity()->has_own_name()) {
diff --git a/esphome/components/mqtt/mqtt_component.h b/esphome/components/mqtt/mqtt_component.h
index 147840d11f..01ba98ad40 100644
--- a/esphome/components/mqtt/mqtt_component.h
+++ b/esphome/components/mqtt/mqtt_component.h
@@ -89,6 +89,9 @@ class MQTTComponent : public Component {
void disable_discovery();
bool is_discovery_enabled() const;
+ /// Set the QOS for subscribe messages (used in discovery).
+ void set_subscribe_qos(uint8_t qos);
+
/// Override this method to return the component type (e.g. "light", "sensor", ...)
virtual std::string component_type() const = 0;
@@ -204,6 +207,7 @@ class MQTTComponent : public Component {
bool command_retain_{false};
bool retain_{true};
uint8_t qos_{0};
+ uint8_t subscribe_qos_{0};
bool discovery_enabled_{true};
bool resend_state_{false};
};
diff --git a/esphome/components/mqtt/mqtt_const.h b/esphome/components/mqtt/mqtt_const.h
index 71f169fbe8..c1c40c4b6d 100644
--- a/esphome/components/mqtt/mqtt_const.h
+++ b/esphome/components/mqtt/mqtt_const.h
@@ -180,6 +180,7 @@ constexpr const char *const MQTT_PRESET_MODE_COMMAND_TOPIC = "pr_mode_cmd_t";
constexpr const char *const MQTT_PRESET_MODE_STATE_TOPIC = "pr_mode_stat_t";
constexpr const char *const MQTT_PRESET_MODE_VALUE_TEMPLATE = "pr_mode_val_tpl";
constexpr const char *const MQTT_PRESET_MODES = "pr_modes";
+constexpr const char *const MQTT_QOS = "qos";
constexpr const char *const MQTT_RED_TEMPLATE = "r_tpl";
constexpr const char *const MQTT_RETAIN = "ret";
constexpr const char *const MQTT_RGB_COMMAND_TEMPLATE = "rgb_cmd_tpl";
@@ -441,6 +442,7 @@ constexpr const char *const MQTT_PRESET_MODE_COMMAND_TOPIC = "preset_mode_comman
constexpr const char *const MQTT_PRESET_MODE_STATE_TOPIC = "preset_mode_state_topic";
constexpr const char *const MQTT_PRESET_MODE_VALUE_TEMPLATE = "preset_mode_value_template";
constexpr const char *const MQTT_PRESET_MODES = "preset_modes";
+constexpr const char *const MQTT_QOS = "qos";
constexpr const char *const MQTT_RED_TEMPLATE = "red_template";
constexpr const char *const MQTT_RETAIN = "retain";
constexpr const char *const MQTT_RGB_COMMAND_TEMPLATE = "rgb_command_template";
diff --git a/esphome/config_validation.py b/esphome/config_validation.py
index a7525a62dd..98b81ec328 100644
--- a/esphome/config_validation.py
+++ b/esphome/config_validation.py
@@ -40,6 +40,7 @@ from esphome.const import (
CONF_SECOND,
CONF_SETUP_PRIORITY,
CONF_STATE_TOPIC,
+ CONF_SUBSCRIBE_QOS,
CONF_TOPIC,
CONF_TYPE,
CONF_TYPE_ID,
@@ -1893,9 +1894,10 @@ MQTT_COMPONENT_AVAILABILITY_SCHEMA = Schema(
MQTT_COMPONENT_SCHEMA = Schema(
{
- Optional(CONF_QOS): All(requires_component("mqtt"), int_range(min=0, max=2)),
+ Optional(CONF_QOS): All(requires_component("mqtt"), mqtt_qos),
Optional(CONF_RETAIN): All(requires_component("mqtt"), boolean),
Optional(CONF_DISCOVERY): All(requires_component("mqtt"), boolean),
+ Optional(CONF_SUBSCRIBE_QOS): All(requires_component("mqtt"), mqtt_qos),
Optional(CONF_STATE_TOPIC): All(requires_component("mqtt"), publish_topic),
Optional(CONF_AVAILABILITY): All(
requires_component("mqtt"), Any(None, MQTT_COMPONENT_AVAILABILITY_SCHEMA)
diff --git a/esphome/const.py b/esphome/const.py
index a3a4318d69..54ebb2815f 100644
--- a/esphome/const.py
+++ b/esphome/const.py
@@ -819,6 +819,7 @@ CONF_STOP = "stop"
CONF_STOP_ACTION = "stop_action"
CONF_STORE_BASELINE = "store_baseline"
CONF_SUBNET = "subnet"
+CONF_SUBSCRIBE_QOS = "subscribe_qos"
CONF_SUBSTITUTIONS = "substitutions"
CONF_SUM = "sum"
CONF_SUPPLEMENTAL_COOLING_ACTION = "supplemental_cooling_action"
diff --git a/tests/components/mqtt/common.yaml b/tests/components/mqtt/common.yaml
index f7a727ab2f..5ed6335d65 100644
--- a/tests/components/mqtt/common.yaml
+++ b/tests/components/mqtt/common.yaml
@@ -227,6 +227,7 @@ datetime:
type: date
state_topic: some/topic/date
qos: 2
+ subscribe_qos: 2
set_action:
- logger.log: "set_value"
on_value:
From 7c0543862ad593916e1230d1dc2f2dec8e61c507 Mon Sep 17 00:00:00 2001
From: Kyle Cascade
Date: Mon, 21 Oct 2024 21:11:23 -0700
Subject: [PATCH 23/74] Humanized the missing MQTT log topic error message
(#7634)
---
esphome/mqtt.py | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/esphome/mqtt.py b/esphome/mqtt.py
index c1c45799cc..d55fb0202d 100644
--- a/esphome/mqtt.py
+++ b/esphome/mqtt.py
@@ -209,6 +209,12 @@ def show_logs(config, topic=None, username=None, password=None, client_id=None):
elif CONF_MQTT in config:
conf = config[CONF_MQTT]
if CONF_LOG_TOPIC in conf:
+ if config[CONF_MQTT][CONF_LOG_TOPIC] is None:
+ _LOGGER.error("MQTT log topic set to null, can't start MQTT logs")
+ return 1
+ if CONF_TOPIC not in config[CONF_MQTT][CONF_LOG_TOPIC]:
+ _LOGGER.error("MQTT log topic not available, can't start MQTT logs")
+ return 1
topic = config[CONF_MQTT][CONF_LOG_TOPIC][CONF_TOPIC]
elif CONF_TOPIC_PREFIX in config[CONF_MQTT]:
topic = f"{config[CONF_MQTT][CONF_TOPIC_PREFIX]}/debug"
From 68844c48698c6983a3d22498dbe70ee20c9835bf Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Wed, 23 Oct 2024 10:16:55 +1100
Subject: [PATCH 24/74] [lvgl] Some properties were not templatable (Bugfix)
(#7655)
---
esphome/components/lvgl/lv_validation.py | 4 ++++
esphome/components/lvgl/schemas.py | 14 +++++++-------
tests/components/lvgl/lvgl-package.yaml | 7 +++++++
3 files changed, 18 insertions(+), 7 deletions(-)
diff --git a/esphome/components/lvgl/lv_validation.py b/esphome/components/lvgl/lv_validation.py
index 9af25a4e90..b91b0905df 100644
--- a/esphome/components/lvgl/lv_validation.py
+++ b/esphome/components/lvgl/lv_validation.py
@@ -267,6 +267,9 @@ def angle(value):
return int(cv.float_range(0.0, 360.0)(cv.angle(value)) * 10)
+lv_angle = LValidator(angle, uint32)
+
+
@schema_extractor("one_of")
def size_validator(value):
"""A size in one axis - one of "size_content", a number (pixels) or a percentage"""
@@ -401,6 +404,7 @@ class TextValidator(LValidator):
lv_text = TextValidator()
lv_float = LValidator(cv.float_, cg.float_)
lv_int = LValidator(cv.int_, cg.int_)
+lv_positive_int = LValidator(cv.positive_int, cg.int_)
lv_brightness = LValidator(cv.percentage, cg.float_, retmapper=lambda x: int(x * 255))
diff --git a/esphome/components/lvgl/schemas.py b/esphome/components/lvgl/schemas.py
index 7599d64416..bb14c11ddd 100644
--- a/esphome/components/lvgl/schemas.py
+++ b/esphome/components/lvgl/schemas.py
@@ -91,7 +91,7 @@ STYLE_PROPS = {
"arc_opa": lvalid.opacity,
"arc_color": lvalid.lv_color,
"arc_rounded": lvalid.lv_bool,
- "arc_width": cv.positive_int,
+ "arc_width": lvalid.lv_positive_int,
"anim_time": lvalid.lv_milliseconds,
"bg_color": lvalid.lv_color,
"bg_grad": lv_gradient,
@@ -111,7 +111,7 @@ STYLE_PROPS = {
"border_side": df.LvConstant(
"LV_BORDER_SIDE_", "NONE", "TOP", "BOTTOM", "LEFT", "RIGHT", "INTERNAL"
).several_of,
- "border_width": cv.positive_int,
+ "border_width": lvalid.lv_positive_int,
"clip_corner": lvalid.lv_bool,
"color_filter_opa": lvalid.opacity,
"height": lvalid.size,
@@ -134,11 +134,11 @@ STYLE_PROPS = {
"pad_right": lvalid.pixels,
"pad_top": lvalid.pixels,
"shadow_color": lvalid.lv_color,
- "shadow_ofs_x": cv.int_,
- "shadow_ofs_y": cv.int_,
+ "shadow_ofs_x": lvalid.lv_int,
+ "shadow_ofs_y": lvalid.lv_int,
"shadow_opa": lvalid.opacity,
- "shadow_spread": cv.int_,
- "shadow_width": cv.positive_int,
+ "shadow_spread": lvalid.lv_int,
+ "shadow_width": lvalid.lv_positive_int,
"text_align": df.LvConstant(
"LV_TEXT_ALIGN_", "LEFT", "CENTER", "RIGHT", "AUTO"
).one_of,
@@ -150,7 +150,7 @@ STYLE_PROPS = {
"text_letter_space": cv.positive_int,
"text_line_space": cv.positive_int,
"text_opa": lvalid.opacity,
- "transform_angle": lvalid.angle,
+ "transform_angle": lvalid.lv_angle,
"transform_height": lvalid.pixels_or_percent,
"transform_pivot_x": lvalid.pixels_or_percent,
"transform_pivot_y": lvalid.pixels_or_percent,
diff --git a/tests/components/lvgl/lvgl-package.yaml b/tests/components/lvgl/lvgl-package.yaml
index 7fd824a87b..4962a71596 100644
--- a/tests/components/lvgl/lvgl-package.yaml
+++ b/tests/components/lvgl/lvgl-package.yaml
@@ -323,6 +323,13 @@ lvgl:
id: button_button
width: 20%
height: 10%
+ transform_angle: !lambda return 180*100;
+ arc_width: !lambda return 4;
+ border_width: !lambda return 6;
+ shadow_ofs_x: !lambda return 6;
+ shadow_ofs_y: !lambda return 6;
+ shadow_spread: !lambda return 6;
+ shadow_width: !lambda return 6;
pressed:
bg_color: light_blue
checkable: true
From dd8d25e43f6d30f93391aeee207a912dd52907d4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?G=C3=A1bor=20Poczkodi?=
Date: Wed, 23 Oct 2024 05:23:10 +0200
Subject: [PATCH 25/74] i2c_device (#7641)
---
CODEOWNERS | 1 +
esphome/components/i2c_device/__init__.py | 26 +++++++++++++++++++
esphome/components/i2c_device/i2c_device.cpp | 17 ++++++++++++
esphome/components/i2c_device/i2c_device.h | 18 +++++++++++++
.../components/i2c_device/test.esp32-ard.yaml | 8 ++++++
.../i2c_device/test.esp32-c3-ard.yaml | 8 ++++++
.../i2c_device/test.esp32-c3-idf.yaml | 8 ++++++
.../components/i2c_device/test.esp32-idf.yaml | 8 ++++++
.../i2c_device/test.esp8266-ard.yaml | 8 ++++++
.../i2c_device/test.rp2040-ard.yaml | 8 ++++++
10 files changed, 110 insertions(+)
create mode 100644 esphome/components/i2c_device/__init__.py
create mode 100644 esphome/components/i2c_device/i2c_device.cpp
create mode 100644 esphome/components/i2c_device/i2c_device.h
create mode 100644 tests/components/i2c_device/test.esp32-ard.yaml
create mode 100644 tests/components/i2c_device/test.esp32-c3-ard.yaml
create mode 100644 tests/components/i2c_device/test.esp32-c3-idf.yaml
create mode 100644 tests/components/i2c_device/test.esp32-idf.yaml
create mode 100644 tests/components/i2c_device/test.esp8266-ard.yaml
create mode 100644 tests/components/i2c_device/test.rp2040-ard.yaml
diff --git a/CODEOWNERS b/CODEOWNERS
index 53300d6740..616b18293d 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -198,6 +198,7 @@ esphome/components/htu31d/* @betterengineering
esphome/components/hydreon_rgxx/* @functionpointer
esphome/components/hyt271/* @Philippe12
esphome/components/i2c/* @esphome/core
+esphome/components/i2c_device/* @gabest11
esphome/components/i2s_audio/* @jesserockz
esphome/components/i2s_audio/media_player/* @jesserockz
esphome/components/i2s_audio/microphone/* @jesserockz
diff --git a/esphome/components/i2c_device/__init__.py b/esphome/components/i2c_device/__init__.py
new file mode 100644
index 0000000000..e145ba56f8
--- /dev/null
+++ b/esphome/components/i2c_device/__init__.py
@@ -0,0 +1,26 @@
+import esphome.codegen as cg
+import esphome.config_validation as cv
+from esphome.components import i2c
+from esphome.const import CONF_ID
+
+DEPENDENCIES = ["i2c"]
+CODEOWNERS = ["@gabest11"]
+MULTI_CONF = True
+
+i2c_device_ns = cg.esphome_ns.namespace("i2c_device")
+
+I2CDeviceComponent = i2c_device_ns.class_(
+ "I2CDeviceComponent", cg.Component, i2c.I2CDevice
+)
+
+CONFIG_SCHEMA = cv.Schema(
+ {
+ cv.GenerateID(CONF_ID): cv.declare_id(I2CDeviceComponent),
+ }
+).extend(i2c.i2c_device_schema(None))
+
+
+async def to_code(config):
+ var = cg.new_Pvariable(config[CONF_ID])
+ await cg.register_component(var, config)
+ await i2c.register_i2c_device(var, config)
diff --git a/esphome/components/i2c_device/i2c_device.cpp b/esphome/components/i2c_device/i2c_device.cpp
new file mode 100644
index 0000000000..455c68fbed
--- /dev/null
+++ b/esphome/components/i2c_device/i2c_device.cpp
@@ -0,0 +1,17 @@
+#include "i2c_device.h"
+#include "esphome/core/log.h"
+#include "esphome/core/hal.h"
+#include
+
+namespace esphome {
+namespace i2c_device {
+
+static const char *const TAG = "i2c_device";
+
+void I2CDeviceComponent::dump_config() {
+ ESP_LOGCONFIG(TAG, "I2CDevice");
+ LOG_I2C_DEVICE(this);
+}
+
+} // namespace i2c_device
+} // namespace esphome
diff --git a/esphome/components/i2c_device/i2c_device.h b/esphome/components/i2c_device/i2c_device.h
new file mode 100644
index 0000000000..ab118e3e89
--- /dev/null
+++ b/esphome/components/i2c_device/i2c_device.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include "esphome/core/component.h"
+#include "esphome/components/i2c/i2c.h"
+
+namespace esphome {
+namespace i2c_device {
+
+class I2CDeviceComponent : public Component, public i2c::I2CDevice {
+ public:
+ void dump_config() override;
+ float get_setup_priority() const override { return setup_priority::DATA; }
+
+ protected:
+};
+
+} // namespace i2c_device
+} // namespace esphome
diff --git a/tests/components/i2c_device/test.esp32-ard.yaml b/tests/components/i2c_device/test.esp32-ard.yaml
new file mode 100644
index 0000000000..6169d113f8
--- /dev/null
+++ b/tests/components/i2c_device/test.esp32-ard.yaml
@@ -0,0 +1,8 @@
+i2c:
+ - id: i2c_i2c
+ scl: 16
+ sda: 17
+
+i2c_device:
+ id: i2cdev
+ address: 0x2C
diff --git a/tests/components/i2c_device/test.esp32-c3-ard.yaml b/tests/components/i2c_device/test.esp32-c3-ard.yaml
new file mode 100644
index 0000000000..5d53d12208
--- /dev/null
+++ b/tests/components/i2c_device/test.esp32-c3-ard.yaml
@@ -0,0 +1,8 @@
+i2c:
+ - id: i2c_i2c
+ scl: 5
+ sda: 4
+
+i2c_device:
+ id: i2cdev
+ address: 0x2C
diff --git a/tests/components/i2c_device/test.esp32-c3-idf.yaml b/tests/components/i2c_device/test.esp32-c3-idf.yaml
new file mode 100644
index 0000000000..5d53d12208
--- /dev/null
+++ b/tests/components/i2c_device/test.esp32-c3-idf.yaml
@@ -0,0 +1,8 @@
+i2c:
+ - id: i2c_i2c
+ scl: 5
+ sda: 4
+
+i2c_device:
+ id: i2cdev
+ address: 0x2C
diff --git a/tests/components/i2c_device/test.esp32-idf.yaml b/tests/components/i2c_device/test.esp32-idf.yaml
new file mode 100644
index 0000000000..6169d113f8
--- /dev/null
+++ b/tests/components/i2c_device/test.esp32-idf.yaml
@@ -0,0 +1,8 @@
+i2c:
+ - id: i2c_i2c
+ scl: 16
+ sda: 17
+
+i2c_device:
+ id: i2cdev
+ address: 0x2C
diff --git a/tests/components/i2c_device/test.esp8266-ard.yaml b/tests/components/i2c_device/test.esp8266-ard.yaml
new file mode 100644
index 0000000000..5d53d12208
--- /dev/null
+++ b/tests/components/i2c_device/test.esp8266-ard.yaml
@@ -0,0 +1,8 @@
+i2c:
+ - id: i2c_i2c
+ scl: 5
+ sda: 4
+
+i2c_device:
+ id: i2cdev
+ address: 0x2C
diff --git a/tests/components/i2c_device/test.rp2040-ard.yaml b/tests/components/i2c_device/test.rp2040-ard.yaml
new file mode 100644
index 0000000000..5d53d12208
--- /dev/null
+++ b/tests/components/i2c_device/test.rp2040-ard.yaml
@@ -0,0 +1,8 @@
+i2c:
+ - id: i2c_i2c
+ scl: 5
+ sda: 4
+
+i2c_device:
+ id: i2cdev
+ address: 0x2C
From fdebf041967549866f438431284c0690bec3d6da Mon Sep 17 00:00:00 2001
From: Kevin Ahrendt
Date: Wed, 23 Oct 2024 13:25:31 -0400
Subject: [PATCH 26/74] [voice_assistant] Bugfix: Fix crash on start (#7662)
---
.../voice_assistant/voice_assistant.cpp | 54 +++++++++++--------
.../voice_assistant/voice_assistant.h | 6 +--
2 files changed, 34 insertions(+), 26 deletions(-)
diff --git a/esphome/components/voice_assistant/voice_assistant.cpp b/esphome/components/voice_assistant/voice_assistant.cpp
index 0b53e74ba3..6f164f69d3 100644
--- a/esphome/components/voice_assistant/voice_assistant.cpp
+++ b/esphome/components/voice_assistant/voice_assistant.cpp
@@ -433,16 +433,18 @@ void VoiceAssistant::loop() {
#ifdef USE_SPEAKER
void VoiceAssistant::write_speaker_() {
- if (this->speaker_buffer_size_ > 0) {
- size_t write_chunk = std::min(this->speaker_buffer_size_, 4 * 1024);
- size_t written = this->speaker_->play(this->speaker_buffer_, write_chunk);
- if (written > 0) {
- memmove(this->speaker_buffer_, this->speaker_buffer_ + written, this->speaker_buffer_size_ - written);
- this->speaker_buffer_size_ -= written;
- this->speaker_buffer_index_ -= written;
- this->set_timeout("speaker-timeout", 5000, [this]() { this->speaker_->stop(); });
- } else {
- ESP_LOGV(TAG, "Speaker buffer full, trying again next loop");
+ if ((this->speaker_ != nullptr) && (this->speaker_buffer_ != nullptr)) {
+ if (this->speaker_buffer_size_ > 0) {
+ size_t write_chunk = std::min(this->speaker_buffer_size_, 4 * 1024);
+ size_t written = this->speaker_->play(this->speaker_buffer_, write_chunk);
+ if (written > 0) {
+ memmove(this->speaker_buffer_, this->speaker_buffer_ + written, this->speaker_buffer_size_ - written);
+ this->speaker_buffer_size_ -= written;
+ this->speaker_buffer_index_ -= written;
+ this->set_timeout("speaker-timeout", 5000, [this]() { this->speaker_->stop(); });
+ } else {
+ ESP_LOGV(TAG, "Speaker buffer full, trying again next loop");
+ }
}
}
}
@@ -772,16 +774,20 @@ void VoiceAssistant::on_event(const api::VoiceAssistantEventResponse &msg) {
}
case api::enums::VOICE_ASSISTANT_TTS_STREAM_START: {
#ifdef USE_SPEAKER
- this->wait_for_stream_end_ = true;
- ESP_LOGD(TAG, "TTS stream start");
- this->defer([this] { this->tts_stream_start_trigger_->trigger(); });
+ if (this->speaker_ != nullptr) {
+ this->wait_for_stream_end_ = true;
+ ESP_LOGD(TAG, "TTS stream start");
+ this->defer([this] { this->tts_stream_start_trigger_->trigger(); });
+ }
#endif
break;
}
case api::enums::VOICE_ASSISTANT_TTS_STREAM_END: {
#ifdef USE_SPEAKER
- this->stream_ended_ = true;
- ESP_LOGD(TAG, "TTS stream end");
+ if (this->speaker_ != nullptr) {
+ this->stream_ended_ = true;
+ ESP_LOGD(TAG, "TTS stream end");
+ }
#endif
break;
}
@@ -802,14 +808,16 @@ void VoiceAssistant::on_event(const api::VoiceAssistantEventResponse &msg) {
void VoiceAssistant::on_audio(const api::VoiceAssistantAudio &msg) {
#ifdef USE_SPEAKER // We should never get to this function if there is no speaker anyway
- if (this->speaker_buffer_index_ + msg.data.length() < SPEAKER_BUFFER_SIZE) {
- memcpy(this->speaker_buffer_ + this->speaker_buffer_index_, msg.data.data(), msg.data.length());
- this->speaker_buffer_index_ += msg.data.length();
- this->speaker_buffer_size_ += msg.data.length();
- this->speaker_bytes_received_ += msg.data.length();
- ESP_LOGV(TAG, "Received audio: %u bytes from API", msg.data.length());
- } else {
- ESP_LOGE(TAG, "Cannot receive audio, buffer is full");
+ if ((this->speaker_ != nullptr) && (this->speaker_buffer_ != nullptr)) {
+ if (this->speaker_buffer_index_ + msg.data.length() < SPEAKER_BUFFER_SIZE) {
+ memcpy(this->speaker_buffer_ + this->speaker_buffer_index_, msg.data.data(), msg.data.length());
+ this->speaker_buffer_index_ += msg.data.length();
+ this->speaker_buffer_size_ += msg.data.length();
+ this->speaker_bytes_received_ += msg.data.length();
+ ESP_LOGV(TAG, "Received audio: %u bytes from API", msg.data.length());
+ } else {
+ ESP_LOGE(TAG, "Cannot receive audio, buffer is full");
+ }
}
#endif
}
diff --git a/esphome/components/voice_assistant/voice_assistant.h b/esphome/components/voice_assistant/voice_assistant.h
index 870e2acdaa..0016d3157c 100644
--- a/esphome/components/voice_assistant/voice_assistant.h
+++ b/esphome/components/voice_assistant/voice_assistant.h
@@ -250,7 +250,7 @@ class VoiceAssistant : public Component {
#ifdef USE_SPEAKER
void write_speaker_();
speaker::Speaker *speaker_{nullptr};
- uint8_t *speaker_buffer_;
+ uint8_t *speaker_buffer_{nullptr};
size_t speaker_buffer_index_{0};
size_t speaker_buffer_size_{0};
size_t speaker_bytes_received_{0};
@@ -282,8 +282,8 @@ class VoiceAssistant : public Component {
float volume_multiplier_;
uint32_t conversation_timeout_;
- uint8_t *send_buffer_;
- int16_t *input_buffer_;
+ uint8_t *send_buffer_{nullptr};
+ int16_t *input_buffer_{nullptr};
bool continuous_{false};
bool silence_detection_;
From 833565feb985e91c9512774a363ea2e5ca79d267 Mon Sep 17 00:00:00 2001
From: Kyle Cascade
Date: Mon, 21 Oct 2024 21:11:23 -0700
Subject: [PATCH 27/74] Humanized the missing MQTT log topic error message
(#7634)
---
esphome/mqtt.py | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/esphome/mqtt.py b/esphome/mqtt.py
index c1c45799cc..d55fb0202d 100644
--- a/esphome/mqtt.py
+++ b/esphome/mqtt.py
@@ -209,6 +209,12 @@ def show_logs(config, topic=None, username=None, password=None, client_id=None):
elif CONF_MQTT in config:
conf = config[CONF_MQTT]
if CONF_LOG_TOPIC in conf:
+ if config[CONF_MQTT][CONF_LOG_TOPIC] is None:
+ _LOGGER.error("MQTT log topic set to null, can't start MQTT logs")
+ return 1
+ if CONF_TOPIC not in config[CONF_MQTT][CONF_LOG_TOPIC]:
+ _LOGGER.error("MQTT log topic not available, can't start MQTT logs")
+ return 1
topic = config[CONF_MQTT][CONF_LOG_TOPIC][CONF_TOPIC]
elif CONF_TOPIC_PREFIX in config[CONF_MQTT]:
topic = f"{config[CONF_MQTT][CONF_TOPIC_PREFIX]}/debug"
From 8d90d256bf2518c46676a0a7dfe37ef3dd1868c8 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Wed, 23 Oct 2024 10:16:55 +1100
Subject: [PATCH 28/74] [lvgl] Some properties were not templatable (Bugfix)
(#7655)
---
esphome/components/lvgl/lv_validation.py | 4 ++++
esphome/components/lvgl/schemas.py | 14 +++++++-------
tests/components/lvgl/lvgl-package.yaml | 7 +++++++
3 files changed, 18 insertions(+), 7 deletions(-)
diff --git a/esphome/components/lvgl/lv_validation.py b/esphome/components/lvgl/lv_validation.py
index fd840cc417..a58fbc33e0 100644
--- a/esphome/components/lvgl/lv_validation.py
+++ b/esphome/components/lvgl/lv_validation.py
@@ -267,6 +267,9 @@ def angle(value):
return int(cv.float_range(0.0, 360.0)(cv.angle(value)) * 10)
+lv_angle = LValidator(angle, uint32)
+
+
@schema_extractor("one_of")
def size_validator(value):
"""A size in one axis - one of "size_content", a number (pixels) or a percentage"""
@@ -403,6 +406,7 @@ class TextValidator(LValidator):
lv_text = TextValidator()
lv_float = LValidator(cv.float_, cg.float_)
lv_int = LValidator(cv.int_, cg.int_)
+lv_positive_int = LValidator(cv.positive_int, cg.int_)
lv_brightness = LValidator(cv.percentage, cg.float_, retmapper=lambda x: int(x * 255))
diff --git a/esphome/components/lvgl/schemas.py b/esphome/components/lvgl/schemas.py
index 780057623a..0d5a609a2d 100644
--- a/esphome/components/lvgl/schemas.py
+++ b/esphome/components/lvgl/schemas.py
@@ -91,7 +91,7 @@ STYLE_PROPS = {
"arc_opa": lvalid.opacity,
"arc_color": lvalid.lv_color,
"arc_rounded": lvalid.lv_bool,
- "arc_width": cv.positive_int,
+ "arc_width": lvalid.lv_positive_int,
"anim_time": lvalid.lv_milliseconds,
"bg_color": lvalid.lv_color,
"bg_grad": lv_gradient,
@@ -111,7 +111,7 @@ STYLE_PROPS = {
"border_side": df.LvConstant(
"LV_BORDER_SIDE_", "NONE", "TOP", "BOTTOM", "LEFT", "RIGHT", "INTERNAL"
).several_of,
- "border_width": cv.positive_int,
+ "border_width": lvalid.lv_positive_int,
"clip_corner": lvalid.lv_bool,
"color_filter_opa": lvalid.opacity,
"height": lvalid.size,
@@ -134,11 +134,11 @@ STYLE_PROPS = {
"pad_right": lvalid.pixels,
"pad_top": lvalid.pixels,
"shadow_color": lvalid.lv_color,
- "shadow_ofs_x": cv.int_,
- "shadow_ofs_y": cv.int_,
+ "shadow_ofs_x": lvalid.lv_int,
+ "shadow_ofs_y": lvalid.lv_int,
"shadow_opa": lvalid.opacity,
- "shadow_spread": cv.int_,
- "shadow_width": cv.positive_int,
+ "shadow_spread": lvalid.lv_int,
+ "shadow_width": lvalid.lv_positive_int,
"text_align": df.LvConstant(
"LV_TEXT_ALIGN_", "LEFT", "CENTER", "RIGHT", "AUTO"
).one_of,
@@ -150,7 +150,7 @@ STYLE_PROPS = {
"text_letter_space": cv.positive_int,
"text_line_space": cv.positive_int,
"text_opa": lvalid.opacity,
- "transform_angle": lvalid.angle,
+ "transform_angle": lvalid.lv_angle,
"transform_height": lvalid.pixels_or_percent,
"transform_pivot_x": lvalid.pixels_or_percent,
"transform_pivot_y": lvalid.pixels_or_percent,
diff --git a/tests/components/lvgl/lvgl-package.yaml b/tests/components/lvgl/lvgl-package.yaml
index 1770c1bfbc..2e05cf10d3 100644
--- a/tests/components/lvgl/lvgl-package.yaml
+++ b/tests/components/lvgl/lvgl-package.yaml
@@ -299,6 +299,13 @@ lvgl:
id: button_button
width: 20%
height: 10%
+ transform_angle: !lambda return 180*100;
+ arc_width: !lambda return 4;
+ border_width: !lambda return 6;
+ shadow_ofs_x: !lambda return 6;
+ shadow_ofs_y: !lambda return 6;
+ shadow_spread: !lambda return 6;
+ shadow_width: !lambda return 6;
pressed:
bg_color: light_blue
checkable: true
From 156ad773c91edca8b14a8518363287e027ef8147 Mon Sep 17 00:00:00 2001
From: Kevin Ahrendt
Date: Wed, 23 Oct 2024 13:25:31 -0400
Subject: [PATCH 29/74] [voice_assistant] Bugfix: Fix crash on start (#7662)
---
.../voice_assistant/voice_assistant.cpp | 54 +++++++++++--------
.../voice_assistant/voice_assistant.h | 6 +--
2 files changed, 34 insertions(+), 26 deletions(-)
diff --git a/esphome/components/voice_assistant/voice_assistant.cpp b/esphome/components/voice_assistant/voice_assistant.cpp
index 0b53e74ba3..6f164f69d3 100644
--- a/esphome/components/voice_assistant/voice_assistant.cpp
+++ b/esphome/components/voice_assistant/voice_assistant.cpp
@@ -433,16 +433,18 @@ void VoiceAssistant::loop() {
#ifdef USE_SPEAKER
void VoiceAssistant::write_speaker_() {
- if (this->speaker_buffer_size_ > 0) {
- size_t write_chunk = std::min(this->speaker_buffer_size_, 4 * 1024);
- size_t written = this->speaker_->play(this->speaker_buffer_, write_chunk);
- if (written > 0) {
- memmove(this->speaker_buffer_, this->speaker_buffer_ + written, this->speaker_buffer_size_ - written);
- this->speaker_buffer_size_ -= written;
- this->speaker_buffer_index_ -= written;
- this->set_timeout("speaker-timeout", 5000, [this]() { this->speaker_->stop(); });
- } else {
- ESP_LOGV(TAG, "Speaker buffer full, trying again next loop");
+ if ((this->speaker_ != nullptr) && (this->speaker_buffer_ != nullptr)) {
+ if (this->speaker_buffer_size_ > 0) {
+ size_t write_chunk = std::min(this->speaker_buffer_size_, 4 * 1024);
+ size_t written = this->speaker_->play(this->speaker_buffer_, write_chunk);
+ if (written > 0) {
+ memmove(this->speaker_buffer_, this->speaker_buffer_ + written, this->speaker_buffer_size_ - written);
+ this->speaker_buffer_size_ -= written;
+ this->speaker_buffer_index_ -= written;
+ this->set_timeout("speaker-timeout", 5000, [this]() { this->speaker_->stop(); });
+ } else {
+ ESP_LOGV(TAG, "Speaker buffer full, trying again next loop");
+ }
}
}
}
@@ -772,16 +774,20 @@ void VoiceAssistant::on_event(const api::VoiceAssistantEventResponse &msg) {
}
case api::enums::VOICE_ASSISTANT_TTS_STREAM_START: {
#ifdef USE_SPEAKER
- this->wait_for_stream_end_ = true;
- ESP_LOGD(TAG, "TTS stream start");
- this->defer([this] { this->tts_stream_start_trigger_->trigger(); });
+ if (this->speaker_ != nullptr) {
+ this->wait_for_stream_end_ = true;
+ ESP_LOGD(TAG, "TTS stream start");
+ this->defer([this] { this->tts_stream_start_trigger_->trigger(); });
+ }
#endif
break;
}
case api::enums::VOICE_ASSISTANT_TTS_STREAM_END: {
#ifdef USE_SPEAKER
- this->stream_ended_ = true;
- ESP_LOGD(TAG, "TTS stream end");
+ if (this->speaker_ != nullptr) {
+ this->stream_ended_ = true;
+ ESP_LOGD(TAG, "TTS stream end");
+ }
#endif
break;
}
@@ -802,14 +808,16 @@ void VoiceAssistant::on_event(const api::VoiceAssistantEventResponse &msg) {
void VoiceAssistant::on_audio(const api::VoiceAssistantAudio &msg) {
#ifdef USE_SPEAKER // We should never get to this function if there is no speaker anyway
- if (this->speaker_buffer_index_ + msg.data.length() < SPEAKER_BUFFER_SIZE) {
- memcpy(this->speaker_buffer_ + this->speaker_buffer_index_, msg.data.data(), msg.data.length());
- this->speaker_buffer_index_ += msg.data.length();
- this->speaker_buffer_size_ += msg.data.length();
- this->speaker_bytes_received_ += msg.data.length();
- ESP_LOGV(TAG, "Received audio: %u bytes from API", msg.data.length());
- } else {
- ESP_LOGE(TAG, "Cannot receive audio, buffer is full");
+ if ((this->speaker_ != nullptr) && (this->speaker_buffer_ != nullptr)) {
+ if (this->speaker_buffer_index_ + msg.data.length() < SPEAKER_BUFFER_SIZE) {
+ memcpy(this->speaker_buffer_ + this->speaker_buffer_index_, msg.data.data(), msg.data.length());
+ this->speaker_buffer_index_ += msg.data.length();
+ this->speaker_buffer_size_ += msg.data.length();
+ this->speaker_bytes_received_ += msg.data.length();
+ ESP_LOGV(TAG, "Received audio: %u bytes from API", msg.data.length());
+ } else {
+ ESP_LOGE(TAG, "Cannot receive audio, buffer is full");
+ }
}
#endif
}
diff --git a/esphome/components/voice_assistant/voice_assistant.h b/esphome/components/voice_assistant/voice_assistant.h
index 870e2acdaa..0016d3157c 100644
--- a/esphome/components/voice_assistant/voice_assistant.h
+++ b/esphome/components/voice_assistant/voice_assistant.h
@@ -250,7 +250,7 @@ class VoiceAssistant : public Component {
#ifdef USE_SPEAKER
void write_speaker_();
speaker::Speaker *speaker_{nullptr};
- uint8_t *speaker_buffer_;
+ uint8_t *speaker_buffer_{nullptr};
size_t speaker_buffer_index_{0};
size_t speaker_buffer_size_{0};
size_t speaker_bytes_received_{0};
@@ -282,8 +282,8 @@ class VoiceAssistant : public Component {
float volume_multiplier_;
uint32_t conversation_timeout_;
- uint8_t *send_buffer_;
- int16_t *input_buffer_;
+ uint8_t *send_buffer_{nullptr};
+ int16_t *input_buffer_{nullptr};
bool continuous_{false};
bool silence_detection_;
From 127acfde6482ebb7e44894af0c17660263166fce Mon Sep 17 00:00:00 2001
From: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Date: Thu, 24 Oct 2024 07:15:40 +1300
Subject: [PATCH 30/74] Bump version to 2024.10.2
---
esphome/const.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/esphome/const.py b/esphome/const.py
index 5fa457b25a..032a4c79a0 100644
--- a/esphome/const.py
+++ b/esphome/const.py
@@ -1,6 +1,6 @@
"""Constants used by esphome."""
-__version__ = "2024.10.1"
+__version__ = "2024.10.2"
ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_"
VALID_SUBSTITUTIONS_CHARACTERS = (
From 4289e00ad0ee3f466a60d9044c97157a8070a047 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Thu, 24 Oct 2024 08:06:45 +1300
Subject: [PATCH 31/74] Bump actions/cache from 4.1.1 to 4.1.2 in
/.github/actions/restore-python (#7659)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
.github/actions/restore-python/action.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/actions/restore-python/action.yml b/.github/actions/restore-python/action.yml
index 1f5812691e..c6978f68c5 100644
--- a/.github/actions/restore-python/action.yml
+++ b/.github/actions/restore-python/action.yml
@@ -22,7 +22,7 @@ runs:
python-version: ${{ inputs.python-version }}
- name: Restore Python virtual environment
id: cache-venv
- uses: actions/cache/restore@v4.1.1
+ uses: actions/cache/restore@v4.1.2
with:
path: venv
# yamllint disable-line rule:line-length
From 2feffddc550c0241aede210bb273b8e0001084f2 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Thu, 24 Oct 2024 08:06:53 +1300
Subject: [PATCH 32/74] Bump actions/cache from 4.1.1 to 4.1.2 (#7660)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
.github/workflows/ci.yml | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 178b914a1c..0d2f1c877d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -46,7 +46,7 @@ jobs:
python-version: ${{ env.DEFAULT_PYTHON }}
- name: Restore Python virtual environment
id: cache-venv
- uses: actions/cache@v4.1.1
+ uses: actions/cache@v4.1.2
with:
path: venv
# yamllint disable-line rule:line-length
@@ -302,14 +302,14 @@ jobs:
- name: Cache platformio
if: github.ref == 'refs/heads/dev'
- uses: actions/cache@v4.1.1
+ uses: actions/cache@v4.1.2
with:
path: ~/.platformio
key: platformio-${{ matrix.pio_cache_key }}
- name: Cache platformio
if: github.ref != 'refs/heads/dev'
- uses: actions/cache/restore@v4.1.1
+ uses: actions/cache/restore@v4.1.2
with:
path: ~/.platformio
key: platformio-${{ matrix.pio_cache_key }}
From bff0e81ed3863ee960d1612fd64bec78fe34c03b Mon Sep 17 00:00:00 2001
From: Kevin Ahrendt
Date: Wed, 23 Oct 2024 16:37:38 -0400
Subject: [PATCH 33/74] [speaker, i2s_audio] Support audio_dac component, mute
actions, and improved logging (#7664)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
---
CODEOWNERS | 4 +-
.../components/i2s_audio/speaker/__init__.py | 2 +-
.../i2s_audio/speaker/i2s_audio_speaker.cpp | 72 +++++++++++++++----
.../i2s_audio/speaker/i2s_audio_speaker.h | 14 ++--
esphome/components/speaker/__init__.py | 31 ++++++--
esphome/components/speaker/automation.h | 20 ++++++
esphome/components/speaker/speaker.h | 42 ++++++++++-
tests/components/speaker/test.esp32-ard.yaml | 2 +
.../components/speaker/test.esp32-c3-ard.yaml | 2 +
.../components/speaker/test.esp32-c3-idf.yaml | 2 +
tests/components/speaker/test.esp32-idf.yaml | 15 +++-
11 files changed, 177 insertions(+), 29 deletions(-)
diff --git a/CODEOWNERS b/CODEOWNERS
index 616b18293d..f96e43d5b7 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -202,7 +202,7 @@ esphome/components/i2c_device/* @gabest11
esphome/components/i2s_audio/* @jesserockz
esphome/components/i2s_audio/media_player/* @jesserockz
esphome/components/i2s_audio/microphone/* @jesserockz
-esphome/components/i2s_audio/speaker/* @jesserockz
+esphome/components/i2s_audio/speaker/* @jesserockz @kahrendt
esphome/components/iaqcore/* @yozik04
esphome/components/ili9xxx/* @clydebarrow @nielsnl68
esphome/components/improv_base/* @esphome/core
@@ -377,7 +377,7 @@ esphome/components/smt100/* @piechade
esphome/components/sn74hc165/* @jesserockz
esphome/components/socket/* @esphome/core
esphome/components/sonoff_d1/* @anatoly-savchenkov
-esphome/components/speaker/* @jesserockz
+esphome/components/speaker/* @jesserockz @kahrendt
esphome/components/spi/* @clydebarrow @esphome/core
esphome/components/spi_device/* @clydebarrow
esphome/components/spi_led_strip/* @clydebarrow
diff --git a/esphome/components/i2s_audio/speaker/__init__.py b/esphome/components/i2s_audio/speaker/__init__.py
index 9fdaced64c..dd43d6cb39 100644
--- a/esphome/components/i2s_audio/speaker/__init__.py
+++ b/esphome/components/i2s_audio/speaker/__init__.py
@@ -17,7 +17,7 @@ from .. import (
)
AUTO_LOAD = ["audio"]
-CODEOWNERS = ["@jesserockz"]
+CODEOWNERS = ["@jesserockz", "@kahrendt"]
DEPENDENCIES = ["i2s_audio"]
I2SAudioSpeaker = i2s_audio_ns.class_(
diff --git a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp
index 4fc489d0a3..cf6c3bbbba 100644
--- a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp
+++ b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.cpp
@@ -32,6 +32,7 @@ enum SpeakerEventGroupBits : uint32_t {
STATE_RUNNING = (1 << 11),
STATE_STOPPING = (1 << 12),
STATE_STOPPED = (1 << 13),
+ ERR_INVALID_FORMAT = (1 << 14),
ERR_TASK_FAILED_TO_START = (1 << 15),
ERR_ESP_INVALID_STATE = (1 << 16),
ERR_ESP_INVALID_ARG = (1 << 17),
@@ -104,16 +105,6 @@ void I2SAudioSpeaker::setup() {
void I2SAudioSpeaker::loop() {
uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
- if (event_group_bits & SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START) {
- this->status_set_error("Failed to start speaker task");
- }
-
- if (event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS) {
- uint32_t error_bits = event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS;
- ESP_LOGW(TAG, "Error writing to I2S: %s", esp_err_to_name(err_bit_to_esp_err(error_bits)));
- this->status_set_warning();
- }
-
if (event_group_bits & SpeakerEventGroupBits::STATE_STARTING) {
ESP_LOGD(TAG, "Starting Speaker");
this->state_ = speaker::STATE_STARTING;
@@ -139,12 +130,64 @@ void I2SAudioSpeaker::loop() {
this->speaker_task_handle_ = nullptr;
}
}
+
+ if (event_group_bits & SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START) {
+ this->status_set_error("Failed to start speaker task");
+ xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START);
+ }
+
+ if (event_group_bits & SpeakerEventGroupBits::ERR_INVALID_FORMAT) {
+ this->status_set_error("Failed to adjust I2S bus to match the incoming audio");
+ ESP_LOGE(TAG,
+ "Incompatible audio format: sample rate = %" PRIu32 ", channels = %" PRIu8 ", bits per sample = %" PRIu8,
+ this->audio_stream_info_.sample_rate, this->audio_stream_info_.channels,
+ this->audio_stream_info_.bits_per_sample);
+ }
+
+ if (event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS) {
+ uint32_t error_bits = event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS;
+ ESP_LOGW(TAG, "Error writing to I2S: %s", esp_err_to_name(err_bit_to_esp_err(error_bits)));
+ this->status_set_warning();
+ }
}
void I2SAudioSpeaker::set_volume(float volume) {
this->volume_ = volume;
- ssize_t decibel_index = remap(volume, 0.0f, 1.0f, 0, Q15_VOLUME_SCALING_FACTORS.size() - 1);
- this->q15_volume_factor_ = Q15_VOLUME_SCALING_FACTORS[decibel_index];
+#ifdef USE_AUDIO_DAC
+ if (this->audio_dac_ != nullptr) {
+ if (volume > 0.0) {
+ this->audio_dac_->set_mute_off();
+ }
+ this->audio_dac_->set_volume(volume);
+ } else
+#endif
+ {
+ // Fallback to software volume control by using a Q15 fixed point scaling factor
+ ssize_t decibel_index = remap(volume, 0.0f, 1.0f, 0, Q15_VOLUME_SCALING_FACTORS.size() - 1);
+ this->q15_volume_factor_ = Q15_VOLUME_SCALING_FACTORS[decibel_index];
+ }
+}
+
+void I2SAudioSpeaker::set_mute_state(bool mute_state) {
+ this->mute_state_ = mute_state;
+#ifdef USE_AUDIO_DAC
+ if (this->audio_dac_) {
+ if (mute_state) {
+ this->audio_dac_->set_mute_on();
+ } else {
+ this->audio_dac_->set_mute_off();
+ }
+ } else
+#endif
+ {
+ if (mute_state) {
+ // Fallback to software volume control and scale by 0
+ this->q15_volume_factor_ = 0;
+ } else {
+ // Revert to previous volume when unmuting
+ this->set_volume(this->volume_);
+ }
+ }
}
size_t I2SAudioSpeaker::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
@@ -275,6 +318,9 @@ void I2SAudioSpeaker::speaker_task(void *params) {
i2s_zero_dma_buffer(this_speaker->parent_->get_port());
}
}
+ } else {
+ // Couldn't configure the I2S port to be compatible with the incoming audio
+ xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_INVALID_FORMAT);
}
i2s_zero_dma_buffer(this_speaker->parent_->get_port());
@@ -288,7 +334,7 @@ void I2SAudioSpeaker::speaker_task(void *params) {
}
void I2SAudioSpeaker::start() {
- if (this->is_failed())
+ if (this->is_failed() || this->status_has_error())
return;
if ((this->state_ == speaker::STATE_STARTING) || (this->state_ == speaker::STATE_RUNNING))
return;
diff --git a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h
index 245f97d1e7..3c512d4d4d 100644
--- a/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h
+++ b/esphome/components/i2s_audio/speaker/i2s_audio_speaker.h
@@ -49,11 +49,17 @@ class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Comp
bool has_buffered_data() const override;
- /// @brief Sets the volume of the speaker. It is implemented as a software volume control.
- /// Overrides the default setter to convert the floating point volume to a Q15 fixed-point factor.
- /// @param volume
+ /// @brief Sets the volume of the speaker. Uses the speaker's configured audio dac component. If unavailble, it is
+ /// implemented as a software volume control. Overrides the default setter to convert the floating point volume to a
+ /// Q15 fixed-point factor.
+ /// @param volume between 0.0 and 1.0
void set_volume(float volume) override;
- float get_volume() override { return this->volume_; }
+
+ /// @brief Mutes or unmute the speaker. Uses the speaker's configured audio dac component. If unavailble, it is
+ /// implemented as a software volume control. Overrides the default setter to convert the floating point volume to a
+ /// Q15 fixed-point factor.
+ /// @param mute_state true for muting, false for unmuting
+ void set_mute_state(bool mute_state) override;
protected:
/// @brief Function for the FreeRTOS task handling audio output.
diff --git a/esphome/components/speaker/__init__.py b/esphome/components/speaker/__init__.py
index 1bbc0b02ef..7a668dc2f3 100644
--- a/esphome/components/speaker/__init__.py
+++ b/esphome/components/speaker/__init__.py
@@ -1,15 +1,18 @@
from esphome import automation
from esphome.automation import maybe_simple_id
import esphome.codegen as cg
+from esphome.components import audio_dac
import esphome.config_validation as cv
from esphome.const import CONF_DATA, CONF_ID, CONF_VOLUME
from esphome.core import CORE
from esphome.coroutine import coroutine_with_priority
-CODEOWNERS = ["@jesserockz"]
+CODEOWNERS = ["@jesserockz", "@kahrendt"]
IS_PLATFORM_COMPONENT = True
+CONF_AUDIO_DAC = "audio_dac"
+
speaker_ns = cg.esphome_ns.namespace("speaker")
Speaker = speaker_ns.class_("Speaker")
@@ -26,6 +29,12 @@ FinishAction = speaker_ns.class_(
VolumeSetAction = speaker_ns.class_(
"VolumeSetAction", automation.Action, cg.Parented.template(Speaker)
)
+MuteOnAction = speaker_ns.class_(
+ "MuteOnAction", automation.Action, cg.Parented.template(Speaker)
+)
+MuteOffAction = speaker_ns.class_(
+ "MuteOffAction", automation.Action, cg.Parented.template(Speaker)
+)
IsPlayingCondition = speaker_ns.class_("IsPlayingCondition", automation.Condition)
@@ -33,7 +42,9 @@ IsStoppedCondition = speaker_ns.class_("IsStoppedCondition", automation.Conditio
async def setup_speaker_core_(var, config):
- pass
+ if audio_dac_config := config.get(CONF_AUDIO_DAC):
+ aud_dac = await cg.get_variable(audio_dac_config)
+ cg.add(var.set_audio_dac(aud_dac))
async def register_speaker(var, config):
@@ -42,8 +53,11 @@ async def register_speaker(var, config):
await setup_speaker_core_(var, config)
-SPEAKER_SCHEMA = cv.Schema({})
-
+SPEAKER_SCHEMA = cv.Schema(
+ {
+ cv.Optional(CONF_AUDIO_DAC): cv.use_id(audio_dac.AudioDac),
+ }
+)
SPEAKER_AUTOMATION_SCHEMA = maybe_simple_id({cv.GenerateID(): cv.use_id(Speaker)})
@@ -113,6 +127,15 @@ async def speaker_volume_set_action(config, action_id, template_arg, args):
return var
+@automation.register_action(
+ "speaker.mute_off", MuteOffAction, SPEAKER_AUTOMATION_SCHEMA
+)
+@automation.register_action("speaker.mute_on", MuteOnAction, SPEAKER_AUTOMATION_SCHEMA)
+async def speaker_mute_action_to_code(config, action_id, template_arg, args):
+ paren = await cg.get_variable(config[CONF_ID])
+ return cg.new_Pvariable(action_id, template_arg, paren)
+
+
@coroutine_with_priority(100.0)
async def to_code(config):
cg.add_global(speaker_ns.using)
diff --git a/esphome/components/speaker/automation.h b/esphome/components/speaker/automation.h
index 9efda011f2..c083796eea 100644
--- a/esphome/components/speaker/automation.h
+++ b/esphome/components/speaker/automation.h
@@ -39,6 +39,26 @@ template class VolumeSetAction : public Action, public Pa
void play(Ts... x) override { this->parent_->set_volume(this->volume_.value(x...)); }
};
+template class MuteOnAction : public Action {
+ public:
+ explicit MuteOnAction(Speaker *speaker) : speaker_(speaker) {}
+
+ void play(Ts... x) override { this->speaker_->set_mute_state(true); }
+
+ protected:
+ Speaker *speaker_;
+};
+
+template class MuteOffAction : public Action {
+ public:
+ explicit MuteOffAction(Speaker *speaker) : speaker_(speaker) {}
+
+ void play(Ts... x) override { this->speaker_->set_mute_state(false); }
+
+ protected:
+ Speaker *speaker_;
+};
+
template class StopAction : public Action, public Parented {
public:
void play(Ts... x) override { this->parent_->stop(); }
diff --git a/esphome/components/speaker/speaker.h b/esphome/components/speaker/speaker.h
index 9390e4edb7..96843e2d5a 100644
--- a/esphome/components/speaker/speaker.h
+++ b/esphome/components/speaker/speaker.h
@@ -8,7 +8,12 @@
#include
#endif
+#include "esphome/core/defines.h"
+
#include "esphome/components/audio/audio.h"
+#ifdef USE_AUDIO_DAC
+#include "esphome/components/audio_dac/audio_dac.h"
+#endif
namespace esphome {
namespace speaker {
@@ -56,9 +61,35 @@ class Speaker {
bool is_running() const { return this->state_ == STATE_RUNNING; }
bool is_stopped() const { return this->state_ == STATE_STOPPED; }
- // Volume control must be implemented by each speaker component, otherwise it will have no effect.
- virtual void set_volume(float volume) { this->volume_ = volume; };
- virtual float get_volume() { return this->volume_; }
+ // Volume control is handled by a configured audio dac component. Individual speaker components can
+ // override and implement in software if an audio dac isn't available.
+ virtual void set_volume(float volume) {
+ this->volume_ = volume;
+#ifdef USE_AUDIO_DAC
+ if (this->audio_dac_ != nullptr) {
+ this->audio_dac_->set_volume(volume);
+ }
+#endif
+ };
+ float get_volume() { return this->volume_; }
+
+ virtual void set_mute_state(bool mute_state) {
+ this->mute_state_ = mute_state;
+#ifdef USE_AUDIO_DAC
+ if (this->audio_dac_) {
+ if (mute_state) {
+ this->audio_dac_->set_mute_on();
+ } else {
+ this->audio_dac_->set_mute_off();
+ }
+ }
+#endif
+ }
+ bool get_mute_state() { return this->mute_state_; }
+
+#ifdef USE_AUDIO_DAC
+ void set_audio_dac(audio_dac::AudioDac *audio_dac) { this->audio_dac_ = audio_dac; }
+#endif
void set_audio_stream_info(const audio::AudioStreamInfo &audio_stream_info) {
this->audio_stream_info_ = audio_stream_info;
@@ -68,6 +99,11 @@ class Speaker {
State state_{STATE_STOPPED};
audio::AudioStreamInfo audio_stream_info_;
float volume_{1.0f};
+ bool mute_state_{false};
+
+#ifdef USE_AUDIO_DAC
+ audio_dac::AudioDac *audio_dac_{nullptr};
+#endif
};
} // namespace speaker
diff --git a/tests/components/speaker/test.esp32-ard.yaml b/tests/components/speaker/test.esp32-ard.yaml
index 9a24d00f68..396b4d95ea 100644
--- a/tests/components/speaker/test.esp32-ard.yaml
+++ b/tests/components/speaker/test.esp32-ard.yaml
@@ -1,6 +1,8 @@
esphome:
on_boot:
then:
+ - speaker.mute_on:
+ - speaker.mute_off:
- if:
condition: speaker.is_stopped
then:
diff --git a/tests/components/speaker/test.esp32-c3-ard.yaml b/tests/components/speaker/test.esp32-c3-ard.yaml
index f28014337c..636aeba766 100644
--- a/tests/components/speaker/test.esp32-c3-ard.yaml
+++ b/tests/components/speaker/test.esp32-c3-ard.yaml
@@ -1,6 +1,8 @@
esphome:
on_boot:
then:
+ - speaker.mute_on:
+ - speaker.mute_off:
- if:
condition: speaker.is_stopped
then:
diff --git a/tests/components/speaker/test.esp32-c3-idf.yaml b/tests/components/speaker/test.esp32-c3-idf.yaml
index f28014337c..636aeba766 100644
--- a/tests/components/speaker/test.esp32-c3-idf.yaml
+++ b/tests/components/speaker/test.esp32-c3-idf.yaml
@@ -1,6 +1,8 @@
esphome:
on_boot:
then:
+ - speaker.mute_on:
+ - speaker.mute_off:
- if:
condition: speaker.is_stopped
then:
diff --git a/tests/components/speaker/test.esp32-idf.yaml b/tests/components/speaker/test.esp32-idf.yaml
index 9a24d00f68..b69440b133 100644
--- a/tests/components/speaker/test.esp32-idf.yaml
+++ b/tests/components/speaker/test.esp32-idf.yaml
@@ -1,6 +1,8 @@
esphome:
on_boot:
then:
+ - speaker.mute_on:
+ - speaker.mute_off:
- if:
condition: speaker.is_stopped
then:
@@ -17,8 +19,17 @@ i2s_audio:
i2s_bclk_pin: 17
i2s_mclk_pin: 15
+i2c:
+ scl: 12
+ sda: 10
+
+audio_dac:
+ - platform: aic3204
+ id: internal_dac
+
speaker:
- platform: i2s_audio
- id: speaker_id
+ id: speaker_with_audio_dac_id
+ audio_dac: internal_dac
dac_type: external
- i2s_dout_pin: 13
+ i2s_dout_pin: 14
From 9acc21e81a393a409236f29aeaf195cedb1ea472 Mon Sep 17 00:00:00 2001
From: tomaszduda23
Date: Wed, 23 Oct 2024 23:04:59 +0200
Subject: [PATCH 34/74] unified way how all platforms handle copy_files (#7614)
Co-authored-by: Tomasz Duda
---
esphome/components/rp2040/__init__.py | 9 ++++++---
esphome/writer.py | 25 +++++++------------------
2 files changed, 13 insertions(+), 21 deletions(-)
diff --git a/esphome/components/rp2040/__init__.py b/esphome/components/rp2040/__init__.py
index f59962477f..d612631a4c 100644
--- a/esphome/components/rp2040/__init__.py
+++ b/esphome/components/rp2040/__init__.py
@@ -17,7 +17,7 @@ from esphome.const import (
PLATFORM_RP2040,
)
from esphome.core import CORE, EsphomeError, coroutine_with_priority
-from esphome.helpers import copy_file_if_changed, mkdir_p, write_file
+from esphome.helpers import copy_file_if_changed, mkdir_p, write_file, read_file
from .const import KEY_BOARD, KEY_PIO_FILES, KEY_RP2040, rp2040_ns
@@ -230,11 +230,14 @@ def generate_pio_files() -> bool:
# Called by writer.py
-def copy_files() -> bool:
+def copy_files():
dir = os.path.dirname(__file__)
post_build_file = os.path.join(dir, "post_build.py.script")
copy_file_if_changed(
post_build_file,
CORE.relative_build_path("post_build.py"),
)
- return generate_pio_files()
+ if generate_pio_files():
+ path = CORE.relative_src_path("esphome.h")
+ content = read_file(path).rstrip("\n")
+ write_file(path, content + '\n#include "pio_includes.h"\n')
diff --git a/esphome/writer.py b/esphome/writer.py
index 79ee72996c..90446ae4b1 100644
--- a/esphome/writer.py
+++ b/esphome/writer.py
@@ -1,3 +1,4 @@
+import importlib
import logging
import os
from pathlib import Path
@@ -299,25 +300,13 @@ def copy_src_tree():
CORE.relative_src_path("esphome", "core", "version.h"), generate_version_h()
)
- if CORE.is_esp32:
- from esphome.components.esp32 import copy_files
-
+ platform = "esphome.components." + CORE.target_platform
+ try:
+ module = importlib.import_module(platform)
+ copy_files = getattr(module, "copy_files")
copy_files()
-
- elif CORE.is_esp8266:
- from esphome.components.esp8266 import copy_files
-
- copy_files()
-
- elif CORE.is_rp2040:
- from esphome.components.rp2040 import copy_files
-
- (pio) = copy_files()
- if pio:
- write_file_if_changed(
- CORE.relative_src_path("esphome.h"),
- ESPHOME_H_FORMAT.format(include_s + '\n#include "pio_includes.h"'),
- )
+ except AttributeError:
+ pass
def generate_defines_h():
From 5b5c2fe71b8307aa692d3def1268837a1b26de51 Mon Sep 17 00:00:00 2001
From: Aaron Solochek
Date: Wed, 23 Oct 2024 17:25:53 -0700
Subject: [PATCH 35/74] updating ESP32 board definitions (#7650)
---
esphome/components/esp32/boards.py | 200 ++++++++++++++++++++++++++++-
1 file changed, 199 insertions(+), 1 deletion(-)
diff --git a/esphome/components/esp32/boards.py b/esphome/components/esp32/boards.py
index 60abcd447c..02744ecb6f 100644
--- a/esphome/components/esp32/boards.py
+++ b/esphome/components/esp32/boards.py
@@ -103,6 +103,173 @@ ESP32_BOARD_PINS = {
"LED": 13,
"LED_BUILTIN": 13,
},
+ "adafruit_feather_esp32s3": {
+ "BUTTON": 0,
+ "A0": 18,
+ "A1": 17,
+ "A2": 16,
+ "A3": 15,
+ "A4": 14,
+ "A5": 8,
+ "SCK": 36,
+ "MOSI": 35,
+ "MISO": 37,
+ "RX": 38,
+ "TX": 39,
+ "SCL": 4,
+ "SDA": 3,
+ "NEOPIXEL": 33,
+ "PIN_NEOPIXEL": 33,
+ "NEOPIXEL_POWER": 21,
+ "I2C_POWER": 7,
+ "LED": 13,
+ "LED_BUILTIN": 13,
+ },
+ "adafruit_feather_esp32s3_nopsram": {
+ "BUTTON": 0,
+ "A0": 18,
+ "A1": 17,
+ "A2": 16,
+ "A3": 15,
+ "A4": 14,
+ "A5": 8,
+ "SCK": 36,
+ "MOSI": 35,
+ "MISO": 37,
+ "RX": 38,
+ "TX": 39,
+ "SCL": 4,
+ "SDA": 3,
+ "NEOPIXEL": 33,
+ "PIN_NEOPIXEL": 33,
+ "NEOPIXEL_POWER": 21,
+ "I2C_POWER": 7,
+ "LED": 13,
+ "LED_BUILTIN": 13,
+ },
+ "adafruit_feather_esp32s3_tft": {
+ "BUTTON": 0,
+ "A0": 18,
+ "A1": 17,
+ "A2": 16,
+ "A3": 15,
+ "A4": 14,
+ "A5": 8,
+ "SCK": 36,
+ "MOSI": 35,
+ "MISO": 37,
+ "RX": 2,
+ "TX": 1,
+ "SCL": 41,
+ "SDA": 42,
+ "NEOPIXEL": 33,
+ "PIN_NEOPIXEL": 33,
+ "NEOPIXEL_POWER": 34,
+ "TFT_I2C_POWER": 21,
+ "TFT_CS": 7,
+ "TFT_DC": 39,
+ "TFT_RESET": 40,
+ "TFT_BACKLIGHT": 45,
+ "LED": 13,
+ "LED_BUILTIN": 13,
+ },
+ "adafruit_funhouse_esp32s2": {
+ "BUTTON_UP": 5,
+ "BUTTON_DOWN": 3,
+ "BUTTON_SELECT": 4,
+ "DOTSTAR_DATA": 14,
+ "DOTSTAR_CLOCK": 15,
+ "PIR_SENSE": 16,
+ "A0": 17,
+ "A1": 2,
+ "A2": 1,
+ "CAP6": 6,
+ "CAP7": 7,
+ "CAP8": 8,
+ "CAP9": 9,
+ "CAP10": 10,
+ "CAP11": 11,
+ "CAP12": 12,
+ "CAP13": 13,
+ "SPEAKER": 42,
+ "LED": 37,
+ "LIGHT": 18,
+ "TFT_MOSI": 35,
+ "TFT_SCK": 36,
+ "TFT_CS": 40,
+ "TFT_DC": 39,
+ "TFT_RESET": 41,
+ "TFT_BACKLIGHT": 21,
+ "RED_LED": 31,
+ "BUTTON": 0,
+ },
+ "adafruit_itsybitsy_esp32": {
+ "A0": 25,
+ "A1": 26,
+ "A2": 4,
+ "A3": 38,
+ "A4": 37,
+ "A5": 36,
+ "SCK": 19,
+ "MOSI": 21,
+ "MISO": 22,
+ "SCL": 27,
+ "SDA": 15,
+ "TX": 20,
+ "RX": 8,
+ "NEOPIXEL": 0,
+ "PIN_NEOPIXEL": 0,
+ "NEOPIXEL_POWER": 2,
+ "BUTTON": 35,
+ },
+ "adafruit_magtag29_esp32s2": {
+ "A1": 18,
+ "BUTTON_A": 15,
+ "BUTTON_B": 14,
+ "BUTTON_C": 12,
+ "BUTTON_D": 11,
+ "SDA": 33,
+ "SCL": 34,
+ "SPEAKER": 17,
+ "SPEAKER_ENABLE": 16,
+ "VOLTAGE_MONITOR": 4,
+ "ACCELEROMETER_INT": 9,
+ "ACCELEROMETER_INTERRUPT": 9,
+ "LIGHT": 3,
+ "NEOPIXEL": 1,
+ "PIN_NEOPIXEL": 1,
+ "NEOPIXEL_POWER": 21,
+ "EPD_BUSY": 5,
+ "EPD_RESET": 6,
+ "EPD_DC": 7,
+ "EPD_CS": 8,
+ "EPD_MOSI": 35,
+ "EPD_SCK": 36,
+ "EPD_MISO": 37,
+ "BUTTON": 0,
+ "LED": 13,
+ "LED_BUILTIN": 13,
+ },
+ "adafruit_metro_esp32s2": {
+ "A0": 17,
+ "A1": 18,
+ "A2": 1,
+ "A3": 2,
+ "A4": 3,
+ "A5": 4,
+ "RX": 38,
+ "TX": 37,
+ "SCL": 34,
+ "SDA": 33,
+ "MISO": 37,
+ "SCK": 36,
+ "MOSI": 35,
+ "NEOPIXEL": 45,
+ "PIN_NEOPIXEL": 45,
+ "LED": 42,
+ "LED_BUILTIN": 42,
+ "BUTTON": 0,
+ },
"adafruit_qtpy_esp32c3": {
"A0": 4,
"A1": 3,
@@ -141,6 +308,26 @@ ESP32_BOARD_PINS = {
"BUTTON": 0,
"SWITCH": 0,
},
+ "adafruit_qtpy_esp32s3_nopsram": {
+ "A0": 18,
+ "A1": 17,
+ "A2": 9,
+ "A3": 8,
+ "SDA": 7,
+ "SCL": 6,
+ "MOSI": 35,
+ "MISO": 37,
+ "SCK": 36,
+ "RX": 16,
+ "TX": 5,
+ "SDA1": 41,
+ "SCL1": 40,
+ "NEOPIXEL": 39,
+ "PIN_NEOPIXEL": 39,
+ "NEOPIXEL_POWER": 38,
+ "BUTTON": 0,
+ "SWITCH": 0,
+ },
"adafruit_qtpy_esp32": {
"A0": 26,
"A1": 25,
@@ -1068,7 +1255,18 @@ ESP32_BOARD_PINS = {
"_VBAT": 35,
},
"wemosbat": {"LED": 16},
- "wesp32": {"MISO": 32, "SCL": 4, "SDA": 15},
+ "wesp32": {
+ "MISO": 32,
+ "MOSI": 23,
+ "SCK": 18,
+ "SCL": 4,
+ "SDA": 15,
+ "MISO1": 12,
+ "MOSI1": 13,
+ "SCK1": 14,
+ "SCL1": 5,
+ "SDA1": 33,
+ },
"widora-air": {
"A1": 39,
"A2": 35,
From ca5c73d170c57a256688f51c09b38dac70b1fe6e Mon Sep 17 00:00:00 2001
From: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Date: Fri, 25 Oct 2024 07:55:14 +1300
Subject: [PATCH 36/74] Support ignoring discovered devices from the dashboard
(#7665)
---
esphome/dashboard/core.py | 25 ++++++++++++++++++++
esphome/dashboard/web_server.py | 42 +++++++++++++++++++++++++++++++++
esphome/storage_json.py | 4 ++++
3 files changed, 71 insertions(+)
diff --git a/esphome/dashboard/core.py b/esphome/dashboard/core.py
index eec0777da6..563ca1506d 100644
--- a/esphome/dashboard/core.py
+++ b/esphome/dashboard/core.py
@@ -5,10 +5,14 @@ from collections.abc import Coroutine
import contextlib
from dataclasses import dataclass
from functools import partial
+import json
import logging
+from pathlib import Path
import threading
from typing import TYPE_CHECKING, Any, Callable
+from esphome.storage_json import ignored_devices_storage_path
+
from ..zeroconf import DiscoveredImport
from .dns import DNSCache
from .entries import DashboardEntries
@@ -20,6 +24,8 @@ if TYPE_CHECKING:
_LOGGER = logging.getLogger(__name__)
+IGNORED_DEVICES_STORAGE_PATH = "ignored-devices.json"
+
@dataclass
class Event:
@@ -74,6 +80,7 @@ class ESPHomeDashboard:
"settings",
"dns_cache",
"_background_tasks",
+ "ignored_devices",
)
def __init__(self) -> None:
@@ -89,12 +96,30 @@ class ESPHomeDashboard:
self.settings = DashboardSettings()
self.dns_cache = DNSCache()
self._background_tasks: set[asyncio.Task] = set()
+ self.ignored_devices: set[str] = set()
async def async_setup(self) -> None:
"""Setup the dashboard."""
self.loop = asyncio.get_running_loop()
self.ping_request = asyncio.Event()
self.entries = DashboardEntries(self)
+ self.load_ignored_devices()
+
+ def load_ignored_devices(self) -> None:
+ storage_path = Path(ignored_devices_storage_path())
+ try:
+ with storage_path.open("r", encoding="utf-8") as f_handle:
+ data = json.load(f_handle)
+ self.ignored_devices = set(data.get("ignored_devices", set()))
+ except FileNotFoundError:
+ pass
+
+ def save_ignored_devices(self) -> None:
+ storage_path = Path(ignored_devices_storage_path())
+ with storage_path.open("w", encoding="utf-8") as f_handle:
+ json.dump(
+ {"ignored_devices": sorted(self.ignored_devices)}, indent=2, fp=f_handle
+ )
async def async_run(self) -> None:
"""Run the dashboard."""
diff --git a/esphome/dashboard/web_server.py b/esphome/dashboard/web_server.py
index e4b7b8d342..1a8b2ab83a 100644
--- a/esphome/dashboard/web_server.py
+++ b/esphome/dashboard/web_server.py
@@ -541,6 +541,46 @@ class ImportRequestHandler(BaseHandler):
self.finish()
+class IgnoreDeviceRequestHandler(BaseHandler):
+ @authenticated
+ def post(self) -> None:
+ dashboard = DASHBOARD
+ try:
+ args = json.loads(self.request.body.decode())
+ device_name = args["name"]
+ ignore = args["ignore"]
+ except (json.JSONDecodeError, KeyError):
+ self.set_status(400)
+ self.set_header("content-type", "application/json")
+ self.write(json.dumps({"error": "Invalid payload"}))
+ return
+
+ ignored_device = next(
+ (
+ res
+ for res in dashboard.import_result.values()
+ if res.device_name == device_name
+ ),
+ None,
+ )
+
+ if ignored_device is None:
+ self.set_status(404)
+ self.set_header("content-type", "application/json")
+ self.write(json.dumps({"error": "Device not found"}))
+ return
+
+ if ignore:
+ dashboard.ignored_devices.add(ignored_device.device_name)
+ else:
+ dashboard.ignored_devices.discard(ignored_device.device_name)
+
+ dashboard.save_ignored_devices()
+
+ self.set_status(204)
+ self.finish()
+
+
class DownloadListRequestHandler(BaseHandler):
@authenticated
@bind_config
@@ -688,6 +728,7 @@ class ListDevicesHandler(BaseHandler):
"project_name": res.project_name,
"project_version": res.project_version,
"network": res.network,
+ "ignored": res.device_name in dashboard.ignored_devices,
}
for res in dashboard.import_result.values()
if res.device_name not in configured
@@ -1156,6 +1197,7 @@ def make_app(debug=get_bool_env(ENV_DEV)) -> tornado.web.Application:
(f"{rel}prometheus-sd", PrometheusServiceDiscoveryHandler),
(f"{rel}boards/([a-z0-9]+)", BoardsRequestHandler),
(f"{rel}version", EsphomeVersionHandler),
+ (f"{rel}ignore-device", IgnoreDeviceRequestHandler),
],
**app_settings,
)
diff --git a/esphome/storage_json.py b/esphome/storage_json.py
index 2d12ee01a0..97cf9ceadd 100644
--- a/esphome/storage_json.py
+++ b/esphome/storage_json.py
@@ -28,6 +28,10 @@ def esphome_storage_path() -> str:
return os.path.join(CORE.data_dir, "esphome.json")
+def ignored_devices_storage_path() -> str:
+ return os.path.join(CORE.data_dir, "ignored-devices.json")
+
+
def trash_storage_path() -> str:
return CORE.relative_config_path("trash")
From 4fa3c6915ca7aaba27d001415aee5b613db33565 Mon Sep 17 00:00:00 2001
From: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Date: Fri, 25 Oct 2024 08:10:30 +1300
Subject: [PATCH 37/74] Bump esphome-dashboard to 20241025.0 (#7669)
---
requirements.txt | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/requirements.txt b/requirements.txt
index c03a9f181a..8cc26e4da0 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -12,7 +12,7 @@ pyserial==3.5
platformio==6.1.16 # When updating platformio, also update Dockerfile
esptool==4.7.0
click==8.1.7
-esphome-dashboard==20240620.0
+esphome-dashboard==20241025.0
aioesphomeapi==24.6.2
zeroconf==0.132.2
puremagic==1.27
From c20e1975d1acd9c99fefd1a1da7e446a2e403bc7 Mon Sep 17 00:00:00 2001
From: tomaszduda23
Date: Thu, 24 Oct 2024 23:25:19 +0200
Subject: [PATCH 38/74] unified way how all platforms handle get_download_types
(#7617)
Co-authored-by: Tomasz Duda
---
esphome/dashboard/web_server.py | 27 ++++++++++-----------------
1 file changed, 10 insertions(+), 17 deletions(-)
diff --git a/esphome/dashboard/web_server.py b/esphome/dashboard/web_server.py
index 1a8b2ab83a..9aeece9aab 100644
--- a/esphome/dashboard/web_server.py
+++ b/esphome/dashboard/web_server.py
@@ -7,6 +7,7 @@ import datetime
import functools
import gzip
import hashlib
+import importlib
import json
import logging
import os
@@ -595,26 +596,18 @@ class DownloadListRequestHandler(BaseHandler):
downloads = []
platform: str = storage_json.target_platform.lower()
- if platform == const.PLATFORM_RP2040:
- from esphome.components.rp2040 import get_download_types as rp2040_types
- downloads = rp2040_types(storage_json)
- elif platform == const.PLATFORM_ESP8266:
- from esphome.components.esp8266 import get_download_types as esp8266_types
-
- downloads = esp8266_types(storage_json)
- elif platform.upper() in ESP32_VARIANTS:
- from esphome.components.esp32 import get_download_types as esp32_types
-
- downloads = esp32_types(storage_json)
+ if platform.upper() in ESP32_VARIANTS:
+ platform = "esp32"
elif platform in (const.PLATFORM_RTL87XX, const.PLATFORM_BK72XX):
- from esphome.components.libretiny import (
- get_download_types as libretiny_types,
- )
+ platform = "libretiny"
- downloads = libretiny_types(storage_json)
- else:
- raise ValueError(f"Unknown platform {platform}")
+ try:
+ module = importlib.import_module(f"esphome.components.{platform}")
+ get_download_types = getattr(module, "get_download_types")
+ except AttributeError as exc:
+ raise ValueError(f"Unknown platform {platform}") from exc
+ downloads = get_download_types(storage_json)
self.set_status(200)
self.set_header("content-type", "application/json")
From 4101d5dad15a5f3162ada989a536bf2cb6da0307 Mon Sep 17 00:00:00 2001
From: Kevin Ahrendt
Date: Thu, 24 Oct 2024 17:26:39 -0400
Subject: [PATCH 39/74] [media_player] Add new media player conditions (#7667)
---
esphome/components/media_player/__init__.py | 11 +++++++++++
esphome/components/media_player/automation.h | 10 ++++++++++
esphome/components/media_player/media_player.cpp | 4 ++++
tests/components/media_player/common.yaml | 4 ++++
4 files changed, 29 insertions(+)
diff --git a/esphome/components/media_player/__init__.py b/esphome/components/media_player/__init__.py
index 423cb065dc..a46b30db29 100644
--- a/esphome/components/media_player/__init__.py
+++ b/esphome/components/media_player/__init__.py
@@ -21,6 +21,7 @@ media_player_ns = cg.esphome_ns.namespace("media_player")
MediaPlayer = media_player_ns.class_("MediaPlayer")
+
PlayAction = media_player_ns.class_(
"PlayAction", automation.Action, cg.Parented.template(MediaPlayer)
)
@@ -60,7 +61,11 @@ AnnoucementTrigger = media_player_ns.class_(
"AnnouncementTrigger", automation.Trigger.template()
)
IsIdleCondition = media_player_ns.class_("IsIdleCondition", automation.Condition)
+IsPausedCondition = media_player_ns.class_("IsPausedCondition", automation.Condition)
IsPlayingCondition = media_player_ns.class_("IsPlayingCondition", automation.Condition)
+IsAnnouncingCondition = media_player_ns.class_(
+ "IsAnnouncingCondition", automation.Condition
+)
async def setup_media_player_core_(var, config):
@@ -159,9 +164,15 @@ async def media_player_play_media_action(config, action_id, template_arg, args):
@automation.register_condition(
"media_player.is_idle", IsIdleCondition, MEDIA_PLAYER_ACTION_SCHEMA
)
+@automation.register_condition(
+ "media_player.is_paused", IsPausedCondition, MEDIA_PLAYER_ACTION_SCHEMA
+)
@automation.register_condition(
"media_player.is_playing", IsPlayingCondition, MEDIA_PLAYER_ACTION_SCHEMA
)
+@automation.register_condition(
+ "media_player.is_announcing", IsAnnouncingCondition, MEDIA_PLAYER_ACTION_SCHEMA
+)
async def media_player_action(config, action_id, template_arg, args):
var = cg.new_Pvariable(action_id, template_arg)
await cg.register_parented(var, config[CONF_ID])
diff --git a/esphome/components/media_player/automation.h b/esphome/components/media_player/automation.h
index f0e0a5dd31..7b9220c4a5 100644
--- a/esphome/components/media_player/automation.h
+++ b/esphome/components/media_player/automation.h
@@ -68,5 +68,15 @@ template class IsPlayingCondition : public Condition, pub
bool check(Ts... x) override { return this->parent_->state == MediaPlayerState::MEDIA_PLAYER_STATE_PLAYING; }
};
+template class IsPausedCondition : public Condition, public Parented {
+ public:
+ bool check(Ts... x) override { return this->parent_->state == MediaPlayerState::MEDIA_PLAYER_STATE_PAUSED; }
+};
+
+template class IsAnnouncingCondition : public Condition, public Parented {
+ public:
+ bool check(Ts... x) override { return this->parent_->state == MediaPlayerState::MEDIA_PLAYER_STATE_ANNOUNCING; }
+};
+
} // namespace media_player
} // namespace esphome
diff --git a/esphome/components/media_player/media_player.cpp b/esphome/components/media_player/media_player.cpp
index 586345ac9f..b5190d8573 100644
--- a/esphome/components/media_player/media_player.cpp
+++ b/esphome/components/media_player/media_player.cpp
@@ -37,6 +37,10 @@ const char *media_player_command_to_string(MediaPlayerCommand command) {
return "UNMUTE";
case MEDIA_PLAYER_COMMAND_TOGGLE:
return "TOGGLE";
+ case MEDIA_PLAYER_COMMAND_VOLUME_UP:
+ return "VOLUME_UP";
+ case MEDIA_PLAYER_COMMAND_VOLUME_DOWN:
+ return "VOLUME_DOWN";
default:
return "UNKNOWN";
}
diff --git a/tests/components/media_player/common.yaml b/tests/components/media_player/common.yaml
index 24b85cd474..af0d5c7765 100644
--- a/tests/components/media_player/common.yaml
+++ b/tests/components/media_player/common.yaml
@@ -27,6 +27,10 @@ media_player:
media_player.is_idle:
- wait_until:
media_player.is_playing:
+ - wait_until:
+ media_player.is_announcing:
+ - wait_until:
+ media_player.is_paused:
- media_player.volume_up:
- media_player.volume_down:
- media_player.volume_set: 50%
From 7dbda12008830ba576c2e6cddca87fab112999c6 Mon Sep 17 00:00:00 2001
From: tomaszduda23
Date: Thu, 24 Oct 2024 23:55:58 +0200
Subject: [PATCH 40/74] [code-quality] weikai.h (#7601)
---
esphome/components/weikai/weikai.h | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/esphome/components/weikai/weikai.h b/esphome/components/weikai/weikai.h
index 042c729162..175a067b27 100644
--- a/esphome/components/weikai/weikai.h
+++ b/esphome/components/weikai/weikai.h
@@ -209,7 +209,7 @@ class WeikaiComponent : public Component {
/// @brief store the name for the component
/// @param name the name as defined by the python code generator
- void set_name(std::string name) { this->name_ = std::move(name); }
+ void set_name(std::string &&name) { this->name_ = std::move(name); }
/// @brief Get the name of the component
/// @return the name
@@ -308,7 +308,7 @@ class WeikaiChannel : public uart::UARTComponent {
/// @brief The name as generated by the Python code generator
/// @param name of the channel
- void set_channel_name(std::string name) { this->name_ = std::move(name); }
+ void set_channel_name(std::string &&name) { this->name_ = std::move(name); }
/// @brief Get the channel name
/// @return the name
From 34a8eaddb227738ed1d22d43025a9af56ad5d4a0 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Fri, 25 Oct 2024 10:56:48 +1300
Subject: [PATCH 41/74] Bump actions/setup-python from 5.2.0 to 5.3.0 in
/.github/actions/restore-python (#7671)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
.github/actions/restore-python/action.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/actions/restore-python/action.yml b/.github/actions/restore-python/action.yml
index c6978f68c5..06c54578f5 100644
--- a/.github/actions/restore-python/action.yml
+++ b/.github/actions/restore-python/action.yml
@@ -17,7 +17,7 @@ runs:
steps:
- name: Set up Python ${{ inputs.python-version }}
id: python
- uses: actions/setup-python@v5.2.0
+ uses: actions/setup-python@v5.3.0
with:
python-version: ${{ inputs.python-version }}
- name: Restore Python virtual environment
From 09f9d915773c9ad2d15d60a60f6886f9da553da5 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Fri, 25 Oct 2024 10:57:09 +1300
Subject: [PATCH 42/74] Bump actions/setup-python from 5.2.0 to 5.3.0 (#7670)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
---
.github/workflows/ci-api-proto.yml | 2 +-
.github/workflows/ci-docker.yml | 2 +-
.github/workflows/ci.yml | 2 +-
.github/workflows/release.yml | 4 ++--
.github/workflows/sync-device-classes.yml | 2 +-
5 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/.github/workflows/ci-api-proto.yml b/.github/workflows/ci-api-proto.yml
index 8112c4e0ff..a6b2e2b2b3 100644
--- a/.github/workflows/ci-api-proto.yml
+++ b/.github/workflows/ci-api-proto.yml
@@ -23,7 +23,7 @@ jobs:
- name: Checkout
uses: actions/checkout@v4.1.7
- name: Set up Python
- uses: actions/setup-python@v5.2.0
+ uses: actions/setup-python@v5.3.0
with:
python-version: "3.11"
diff --git a/.github/workflows/ci-docker.yml b/.github/workflows/ci-docker.yml
index f003e5d24c..435a58498e 100644
--- a/.github/workflows/ci-docker.yml
+++ b/.github/workflows/ci-docker.yml
@@ -42,7 +42,7 @@ jobs:
steps:
- uses: actions/checkout@v4.1.7
- name: Set up Python
- uses: actions/setup-python@v5.2.0
+ uses: actions/setup-python@v5.3.0
with:
python-version: "3.9"
- name: Set up Docker Buildx
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0d2f1c877d..82a55d0e2a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -41,7 +41,7 @@ jobs:
run: echo key="${{ hashFiles('requirements.txt', 'requirements_optional.txt', 'requirements_test.txt') }}" >> $GITHUB_OUTPUT
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
id: python
- uses: actions/setup-python@v5.2.0
+ uses: actions/setup-python@v5.3.0
with:
python-version: ${{ env.DEFAULT_PYTHON }}
- name: Restore Python virtual environment
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 26a213f170..5072bec222 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -53,7 +53,7 @@ jobs:
steps:
- uses: actions/checkout@v4.1.7
- name: Set up Python
- uses: actions/setup-python@v5.2.0
+ uses: actions/setup-python@v5.3.0
with:
python-version: "3.x"
- name: Set up python environment
@@ -85,7 +85,7 @@ jobs:
steps:
- uses: actions/checkout@v4.1.7
- name: Set up Python
- uses: actions/setup-python@v5.2.0
+ uses: actions/setup-python@v5.3.0
with:
python-version: "3.9"
diff --git a/.github/workflows/sync-device-classes.yml b/.github/workflows/sync-device-classes.yml
index c066ae9fb4..7a46d596a1 100644
--- a/.github/workflows/sync-device-classes.yml
+++ b/.github/workflows/sync-device-classes.yml
@@ -22,7 +22,7 @@ jobs:
path: lib/home-assistant
- name: Setup Python
- uses: actions/setup-python@v5.2.0
+ uses: actions/setup-python@v5.3.0
with:
python-version: 3.12
From 33fdbbe30c4d9643300483bf2dfd85d992e2cf86 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Fri, 25 Oct 2024 09:05:25 +1100
Subject: [PATCH 43/74] [image][online_image][animation] Fix transparency in
RGB565 (#7631)
---
esphome/components/animation/__init__.py | 13 +++---
esphome/components/animation/animation.cpp | 2 +-
esphome/components/image/__init__.py | 13 +++---
esphome/components/image/image.cpp | 28 ++++++-------
esphome/components/image/image.h | 37 ++++++++---------
.../components/online_image/online_image.cpp | 10 +----
.../components/online_image/online_image.h | 8 +---
tests/components/image/common.yaml | 38 ++++++++++++++++++
tests/components/image/test.esp32-ard.yaml | 40 +------------------
tests/components/image/test.esp32-c3-ard.yaml | 39 +-----------------
tests/components/image/test.esp32-c3-idf.yaml | 39 +-----------------
tests/components/image/test.esp32-idf.yaml | 39 +-----------------
tests/components/image/test.esp8266-ard.yaml | 39 +-----------------
tests/components/image/test.host.yaml | 8 ++++
tests/components/image/test.rp2040-ard.yaml | 39 +-----------------
15 files changed, 101 insertions(+), 291 deletions(-)
create mode 100644 tests/components/image/common.yaml
create mode 100644 tests/components/image/test.host.yaml
diff --git a/esphome/components/animation/__init__.py b/esphome/components/animation/__init__.py
index eb3d09ac96..5a308855de 100644
--- a/esphome/components/animation/__init__.py
+++ b/esphome/components/animation/__init__.py
@@ -271,7 +271,8 @@ async def to_code(config):
pos += 1
elif config[CONF_TYPE] in ["RGB565", "TRANSPARENT_IMAGE"]:
- data = [0 for _ in range(height * width * 2 * frames)]
+ bytes_per_pixel = 3 if transparent else 2
+ data = [0 for _ in range(height * width * bytes_per_pixel * frames)]
pos = 0
for frameIndex in range(frames):
image.seek(frameIndex)
@@ -288,17 +289,13 @@ async def to_code(config):
G = g >> 2
B = b >> 3
rgb = (R << 11) | (G << 5) | B
-
- if transparent:
- if rgb == 0x0020:
- rgb = 0
- if a < 0x80:
- rgb = 0x0020
-
data[pos] = rgb >> 8
pos += 1
data[pos] = rgb & 0xFF
pos += 1
+ if transparent:
+ data[pos] = a
+ pos += 1
elif config[CONF_TYPE] in ["BINARY", "TRANSPARENT_BINARY"]:
width8 = ((width + 7) // 8) * 8
diff --git a/esphome/components/animation/animation.cpp b/esphome/components/animation/animation.cpp
index 7e0efa97e0..1375dfe07e 100644
--- a/esphome/components/animation/animation.cpp
+++ b/esphome/components/animation/animation.cpp
@@ -62,7 +62,7 @@ void Animation::set_frame(int frame) {
}
void Animation::update_data_start_() {
- const uint32_t image_size = image_type_to_width_stride(this->width_, this->type_) * this->height_;
+ const uint32_t image_size = this->get_width_stride() * this->height_;
this->data_start_ = this->animation_data_start_ + image_size * this->current_frame_;
}
diff --git a/esphome/components/image/__init__.py b/esphome/components/image/__init__.py
index c72417bcda..8742540067 100644
--- a/esphome/components/image/__init__.py
+++ b/esphome/components/image/__init__.py
@@ -361,24 +361,21 @@ async def to_code(config):
elif config[CONF_TYPE] in ["RGB565"]:
image = image.convert("RGBA")
pixels = list(image.getdata())
- data = [0 for _ in range(height * width * 2)]
+ bytes_per_pixel = 3 if transparent else 2
+ data = [0 for _ in range(height * width * bytes_per_pixel)]
pos = 0
for r, g, b, a in pixels:
R = r >> 3
G = g >> 2
B = b >> 3
rgb = (R << 11) | (G << 5) | B
-
- if transparent:
- if rgb == 0x0020:
- rgb = 0
- if a < 0x80:
- rgb = 0x0020
-
data[pos] = rgb >> 8
pos += 1
data[pos] = rgb & 0xFF
pos += 1
+ if transparent:
+ data[pos] = a
+ pos += 1
elif config[CONF_TYPE] in ["BINARY", "TRANSPARENT_BINARY"]:
if transparent:
diff --git a/esphome/components/image/image.cpp b/esphome/components/image/image.cpp
index ded4c60d25..ca2f659fb0 100644
--- a/esphome/components/image/image.cpp
+++ b/esphome/components/image/image.cpp
@@ -88,7 +88,7 @@ lv_img_dsc_t *Image::get_lv_img_dsc() {
this->dsc_.header.reserved = 0;
this->dsc_.header.w = this->width_;
this->dsc_.header.h = this->height_;
- this->dsc_.data_size = image_type_to_width_stride(this->dsc_.header.w * this->dsc_.header.h, this->get_type());
+ this->dsc_.data_size = this->get_width_stride() * this->get_height();
switch (this->get_type()) {
case IMAGE_TYPE_BINARY:
this->dsc_.header.cf = LV_IMG_CF_ALPHA_1BIT;
@@ -104,17 +104,17 @@ lv_img_dsc_t *Image::get_lv_img_dsc() {
case IMAGE_TYPE_RGB565:
#if LV_COLOR_DEPTH == 16
- this->dsc_.header.cf = this->has_transparency() ? LV_IMG_CF_TRUE_COLOR_CHROMA_KEYED : LV_IMG_CF_TRUE_COLOR;
+ this->dsc_.header.cf = this->has_transparency() ? LV_IMG_CF_TRUE_COLOR_ALPHA : LV_IMG_CF_TRUE_COLOR;
#else
this->dsc_.header.cf = LV_IMG_CF_RGB565;
#endif
break;
- case image::IMAGE_TYPE_RGBA:
+ case IMAGE_TYPE_RGBA:
#if LV_COLOR_DEPTH == 32
this->dsc_.header.cf = LV_IMG_CF_TRUE_COLOR;
#else
- this->dsc_.header.cf = LV_IMG_CF_RGBA8888;
+ this->dsc_.header.cf = LV_IMG_CF_TRUE_COLOR_ALPHA;
#endif
break;
}
@@ -147,21 +147,21 @@ Color Image::get_rgb24_pixel_(int x, int y) const {
return color;
}
Color Image::get_rgb565_pixel_(int x, int y) const {
- const uint32_t pos = (x + y * this->width_) * 2;
- uint16_t rgb565 =
- progmem_read_byte(this->data_start_ + pos + 0) << 8 | progmem_read_byte(this->data_start_ + pos + 1);
+ const uint8_t *pos = this->data_start_;
+ if (this->transparent_) {
+ pos += (x + y * this->width_) * 3;
+ } else {
+ pos += (x + y * this->width_) * 2;
+ }
+ uint16_t rgb565 = encode_uint16(progmem_read_byte(pos), progmem_read_byte(pos + 1));
auto r = (rgb565 & 0xF800) >> 11;
auto g = (rgb565 & 0x07E0) >> 5;
auto b = rgb565 & 0x001F;
- Color color = Color((r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2));
- if (rgb565 == 0x0020 && transparent_) {
- // darkest green has been defined as transparent color for transparent RGB565 images.
- color.w = 0;
- } else {
- color.w = 0xFF;
- }
+ auto a = this->transparent_ ? progmem_read_byte(pos + 2) : 0xFF;
+ Color color = Color((r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2), a);
return color;
}
+
Color Image::get_grayscale_pixel_(int x, int y) const {
const uint32_t pos = (x + y * this->width_);
const uint8_t gray = progmem_read_byte(this->data_start_ + pos);
diff --git a/esphome/components/image/image.h b/esphome/components/image/image.h
index a8a8aab2c2..40370d18da 100644
--- a/esphome/components/image/image.h
+++ b/esphome/components/image/image.h
@@ -17,24 +17,6 @@ enum ImageType {
IMAGE_TYPE_RGBA = 4,
};
-inline int image_type_to_bpp(ImageType type) {
- switch (type) {
- case IMAGE_TYPE_BINARY:
- return 1;
- case IMAGE_TYPE_GRAYSCALE:
- return 8;
- case IMAGE_TYPE_RGB565:
- return 16;
- case IMAGE_TYPE_RGB24:
- return 24;
- case IMAGE_TYPE_RGBA:
- return 32;
- }
- return 0;
-}
-
-inline int image_type_to_width_stride(int width, ImageType type) { return (width * image_type_to_bpp(type) + 7u) / 8u; }
-
class Image : public display::BaseImage {
public:
Image(const uint8_t *data_start, int width, int height, ImageType type);
@@ -44,6 +26,25 @@ class Image : public display::BaseImage {
const uint8_t *get_data_start() const { return this->data_start_; }
ImageType get_type() const;
+ int get_bpp() const {
+ switch (this->type_) {
+ case IMAGE_TYPE_BINARY:
+ return 1;
+ case IMAGE_TYPE_GRAYSCALE:
+ return 8;
+ case IMAGE_TYPE_RGB565:
+ return this->transparent_ ? 24 : 16;
+ case IMAGE_TYPE_RGB24:
+ return 24;
+ case IMAGE_TYPE_RGBA:
+ return 32;
+ }
+ return 0;
+ }
+
+ /// Return the stride of the image in bytes, that is, the distance in bytes
+ /// between two consecutive rows of pixels.
+ uint32_t get_width_stride() const { return (this->width_ * this->get_bpp() + 7u) / 8u; }
void draw(int x, int y, display::Display *display, Color color_on, Color color_off) override;
void set_transparency(bool transparent) { transparent_ = transparent; }
diff --git a/esphome/components/online_image/online_image.cpp b/esphome/components/online_image/online_image.cpp
index 480bad6aca..1786809dfa 100644
--- a/esphome/components/online_image/online_image.cpp
+++ b/esphome/components/online_image/online_image.cpp
@@ -215,16 +215,10 @@ void OnlineImage::draw_pixel_(int x, int y, Color color) {
}
case ImageType::IMAGE_TYPE_RGB565: {
uint16_t col565 = display::ColorUtil::color_to_565(color);
- if (this->has_transparency()) {
- if (col565 == 0x0020) {
- col565 = 0;
- }
- if (color.w < 0x80) {
- col565 = 0x0020;
- }
- }
this->buffer_[pos + 0] = static_cast((col565 >> 8) & 0xFF);
this->buffer_[pos + 1] = static_cast(col565 & 0xFF);
+ if (this->has_transparency())
+ this->buffer_[pos + 2] = color.w;
break;
}
case ImageType::IMAGE_TYPE_RGBA: {
diff --git a/esphome/components/online_image/online_image.h b/esphome/components/online_image/online_image.h
index 51c11478cd..017402a088 100644
--- a/esphome/components/online_image/online_image.h
+++ b/esphome/components/online_image/online_image.h
@@ -86,13 +86,9 @@ class OnlineImage : public PollingComponent,
Allocator allocator_{Allocator::Flags::ALLOW_FAILURE};
uint32_t get_buffer_size_() const { return get_buffer_size_(this->buffer_width_, this->buffer_height_); }
- int get_buffer_size_(int width, int height) const {
- return std::ceil(image::image_type_to_bpp(this->type_) * width * height / 8.0);
- }
+ int get_buffer_size_(int width, int height) const { return (this->get_bpp() * width + 7u) / 8u * height; }
- int get_position_(int x, int y) const {
- return ((x + y * this->buffer_width_) * image::image_type_to_bpp(this->type_)) / 8;
- }
+ int get_position_(int x, int y) const { return (x + y * this->buffer_width_) * this->get_bpp() / 8; }
ESPHOME_ALWAYS_INLINE bool auto_resize_() const { return this->fixed_width_ == 0 || this->fixed_height_ == 0; }
diff --git a/tests/components/image/common.yaml b/tests/components/image/common.yaml
new file mode 100644
index 0000000000..313da6bc0b
--- /dev/null
+++ b/tests/components/image/common.yaml
@@ -0,0 +1,38 @@
+image:
+ - id: binary_image
+ file: ../../pnglogo.png
+ type: BINARY
+ dither: FloydSteinberg
+ - id: transparent_transparent_image
+ file: ../../pnglogo.png
+ type: TRANSPARENT_BINARY
+ - id: rgba_image
+ file: ../../pnglogo.png
+ type: RGBA
+ resize: 50x50
+ - id: rgb24_image
+ file: ../../pnglogo.png
+ type: RGB24
+ use_transparency: yes
+ - id: rgb565_image
+ file: ../../pnglogo.png
+ type: RGB565
+ use_transparency: no
+ - id: web_svg_image
+ file: https://raw.githubusercontent.com/esphome/esphome-docs/a62d7ab193c1a464ed791670170c7d518189109b/images/logo.svg
+ resize: 256x48
+ type: TRANSPARENT_BINARY
+ - id: web_tiff_image
+ file: https://upload.wikimedia.org/wikipedia/commons/b/b6/SIPI_Jelly_Beans_4.1.07.tiff
+ type: RGB24
+ resize: 48x48
+ - id: web_redirect_image
+ file: https://avatars.githubusercontent.com/u/3060199?s=48&v=4
+ type: RGB24
+ resize: 48x48
+ - id: mdi_alert
+ file: mdi:alert-circle-outline
+ resize: 50x50
+ - id: another_alert_icon
+ file: mdi:alert-outline
+ type: BINARY
diff --git a/tests/components/image/test.esp32-ard.yaml b/tests/components/image/test.esp32-ard.yaml
index 9dd44d177f..818e720221 100644
--- a/tests/components/image/test.esp32-ard.yaml
+++ b/tests/components/image/test.esp32-ard.yaml
@@ -13,41 +13,5 @@ display:
reset_pin: 21
invert_colors: true
-image:
- - id: binary_image
- file: ../../pnglogo.png
- type: BINARY
- dither: FloydSteinberg
- - id: transparent_transparent_image
- file: ../../pnglogo.png
- type: TRANSPARENT_BINARY
- - id: rgba_image
- file: ../../pnglogo.png
- type: RGBA
- resize: 50x50
- - id: rgb24_image
- file: ../../pnglogo.png
- type: RGB24
- use_transparency: yes
- - id: rgb565_image
- file: ../../pnglogo.png
- type: RGB565
- use_transparency: no
- - id: web_svg_image
- file: https://raw.githubusercontent.com/esphome/esphome-docs/a62d7ab193c1a464ed791670170c7d518189109b/images/logo.svg
- resize: 256x48
- type: TRANSPARENT_BINARY
- - id: web_tiff_image
- file: https://upload.wikimedia.org/wikipedia/commons/b/b6/SIPI_Jelly_Beans_4.1.07.tiff
- type: RGB24
- resize: 48x48
- - id: web_redirect_image
- file: https://avatars.githubusercontent.com/u/3060199?s=48&v=4
- type: RGB24
- resize: 48x48
- - id: mdi_alert
- file: mdi:alert-circle-outline
- resize: 50x50
- - id: another_alert_icon
- file: mdi:alert-outline
- type: BINARY
+<<: !include common.yaml
+
diff --git a/tests/components/image/test.esp32-c3-ard.yaml b/tests/components/image/test.esp32-c3-ard.yaml
index c0b2779773..4dae9cd5ec 100644
--- a/tests/components/image/test.esp32-c3-ard.yaml
+++ b/tests/components/image/test.esp32-c3-ard.yaml
@@ -13,41 +13,4 @@ display:
reset_pin: 10
invert_colors: true
-image:
- - id: binary_image
- file: ../../pnglogo.png
- type: BINARY
- dither: FloydSteinberg
- - id: transparent_transparent_image
- file: ../../pnglogo.png
- type: TRANSPARENT_BINARY
- - id: rgba_image
- file: ../../pnglogo.png
- type: RGBA
- resize: 50x50
- - id: rgb24_image
- file: ../../pnglogo.png
- type: RGB24
- use_transparency: yes
- - id: rgb565_image
- file: ../../pnglogo.png
- type: RGB565
- use_transparency: no
- - id: web_svg_image
- file: https://raw.githubusercontent.com/esphome/esphome-docs/a62d7ab193c1a464ed791670170c7d518189109b/images/logo.svg
- resize: 256x48
- type: TRANSPARENT_BINARY
- - id: web_tiff_image
- file: https://upload.wikimedia.org/wikipedia/commons/b/b6/SIPI_Jelly_Beans_4.1.07.tiff
- type: RGB24
- resize: 48x48
- - id: web_redirect_image
- file: https://avatars.githubusercontent.com/u/3060199?s=48&v=4
- type: RGB24
- resize: 48x48
- - id: mdi_alert
- file: mdi:alert-circle-outline
- resize: 50x50
- - id: another_alert_icon
- file: mdi:alert-outline
- type: BINARY
+<<: !include common.yaml
diff --git a/tests/components/image/test.esp32-c3-idf.yaml b/tests/components/image/test.esp32-c3-idf.yaml
index c0b2779773..4dae9cd5ec 100644
--- a/tests/components/image/test.esp32-c3-idf.yaml
+++ b/tests/components/image/test.esp32-c3-idf.yaml
@@ -13,41 +13,4 @@ display:
reset_pin: 10
invert_colors: true
-image:
- - id: binary_image
- file: ../../pnglogo.png
- type: BINARY
- dither: FloydSteinberg
- - id: transparent_transparent_image
- file: ../../pnglogo.png
- type: TRANSPARENT_BINARY
- - id: rgba_image
- file: ../../pnglogo.png
- type: RGBA
- resize: 50x50
- - id: rgb24_image
- file: ../../pnglogo.png
- type: RGB24
- use_transparency: yes
- - id: rgb565_image
- file: ../../pnglogo.png
- type: RGB565
- use_transparency: no
- - id: web_svg_image
- file: https://raw.githubusercontent.com/esphome/esphome-docs/a62d7ab193c1a464ed791670170c7d518189109b/images/logo.svg
- resize: 256x48
- type: TRANSPARENT_BINARY
- - id: web_tiff_image
- file: https://upload.wikimedia.org/wikipedia/commons/b/b6/SIPI_Jelly_Beans_4.1.07.tiff
- type: RGB24
- resize: 48x48
- - id: web_redirect_image
- file: https://avatars.githubusercontent.com/u/3060199?s=48&v=4
- type: RGB24
- resize: 48x48
- - id: mdi_alert
- file: mdi:alert-circle-outline
- resize: 50x50
- - id: another_alert_icon
- file: mdi:alert-outline
- type: BINARY
+<<: !include common.yaml
diff --git a/tests/components/image/test.esp32-idf.yaml b/tests/components/image/test.esp32-idf.yaml
index e903afea1f..814f16c36c 100644
--- a/tests/components/image/test.esp32-idf.yaml
+++ b/tests/components/image/test.esp32-idf.yaml
@@ -13,41 +13,4 @@ display:
reset_pin: 21
invert_colors: true
-image:
- - id: binary_image
- file: ../../pnglogo.png
- type: BINARY
- dither: FloydSteinberg
- - id: transparent_transparent_image
- file: ../../pnglogo.png
- type: TRANSPARENT_BINARY
- - id: rgba_image
- file: ../../pnglogo.png
- type: RGBA
- resize: 50x50
- - id: rgb24_image
- file: ../../pnglogo.png
- type: RGB24
- use_transparency: yes
- - id: rgb565_image
- file: ../../pnglogo.png
- type: RGB565
- use_transparency: no
- - id: web_svg_image
- file: https://raw.githubusercontent.com/esphome/esphome-docs/a62d7ab193c1a464ed791670170c7d518189109b/images/logo.svg
- resize: 256x48
- type: TRANSPARENT_BINARY
- - id: web_tiff_image
- file: https://upload.wikimedia.org/wikipedia/commons/b/b6/SIPI_Jelly_Beans_4.1.07.tiff
- type: RGB24
- resize: 48x48
- - id: web_redirect_image
- file: https://avatars.githubusercontent.com/u/3060199?s=48&v=4
- type: RGB24
- resize: 48x48
- - id: mdi_alert
- file: mdi:alert-circle-outline
- resize: 50x50
- - id: another_alert_icon
- file: mdi:alert-outline
- type: BINARY
+<<: !include common.yaml
diff --git a/tests/components/image/test.esp8266-ard.yaml b/tests/components/image/test.esp8266-ard.yaml
index 5a96ed9497..f963022ff4 100644
--- a/tests/components/image/test.esp8266-ard.yaml
+++ b/tests/components/image/test.esp8266-ard.yaml
@@ -13,41 +13,4 @@ display:
reset_pin: 16
invert_colors: true
-image:
- - id: binary_image
- file: ../../pnglogo.png
- type: BINARY
- dither: FloydSteinberg
- - id: transparent_transparent_image
- file: ../../pnglogo.png
- type: TRANSPARENT_BINARY
- - id: rgba_image
- file: ../../pnglogo.png
- type: RGBA
- resize: 50x50
- - id: rgb24_image
- file: ../../pnglogo.png
- type: RGB24
- use_transparency: yes
- - id: rgb565_image
- file: ../../pnglogo.png
- type: RGB565
- use_transparency: no
- - id: web_svg_image
- file: https://raw.githubusercontent.com/esphome/esphome-docs/a62d7ab193c1a464ed791670170c7d518189109b/images/logo.svg
- resize: 256x48
- type: TRANSPARENT_BINARY
- - id: web_tiff_image
- file: https://upload.wikimedia.org/wikipedia/commons/b/b6/SIPI_Jelly_Beans_4.1.07.tiff
- type: RGB24
- resize: 48x48
- - id: web_redirect_image
- file: https://avatars.githubusercontent.com/u/3060199?s=48&v=4
- type: RGB24
- resize: 48x48
- - id: mdi_alert
- file: mdi:alert-circle-outline
- resize: 50x50
- - id: another_alert_icon
- file: mdi:alert-outline
- type: BINARY
+<<: !include common.yaml
diff --git a/tests/components/image/test.host.yaml b/tests/components/image/test.host.yaml
new file mode 100644
index 0000000000..29509db66c
--- /dev/null
+++ b/tests/components/image/test.host.yaml
@@ -0,0 +1,8 @@
+display:
+ - platform: sdl
+ auto_clear_enabled: false
+ dimensions:
+ width: 480
+ height: 480
+
+<<: !include common.yaml
diff --git a/tests/components/image/test.rp2040-ard.yaml b/tests/components/image/test.rp2040-ard.yaml
index 4c40ca464f..5167c99a7d 100644
--- a/tests/components/image/test.rp2040-ard.yaml
+++ b/tests/components/image/test.rp2040-ard.yaml
@@ -13,41 +13,4 @@ display:
reset_pin: 22
invert_colors: true
-image:
- - id: binary_image
- file: ../../pnglogo.png
- type: BINARY
- dither: FloydSteinberg
- - id: transparent_transparent_image
- file: ../../pnglogo.png
- type: TRANSPARENT_BINARY
- - id: rgba_image
- file: ../../pnglogo.png
- type: RGBA
- resize: 50x50
- - id: rgb24_image
- file: ../../pnglogo.png
- type: RGB24
- use_transparency: yes
- - id: rgb565_image
- file: ../../pnglogo.png
- type: RGB565
- use_transparency: no
- - id: web_svg_image
- file: https://raw.githubusercontent.com/esphome/esphome-docs/a62d7ab193c1a464ed791670170c7d518189109b/images/logo.svg
- resize: 256x48
- type: TRANSPARENT_BINARY
- - id: web_tiff_image
- file: https://upload.wikimedia.org/wikipedia/commons/b/b6/SIPI_Jelly_Beans_4.1.07.tiff
- type: RGB24
- resize: 48x48
- - id: web_redirect_image
- file: https://avatars.githubusercontent.com/u/3060199?s=48&v=4
- type: RGB24
- resize: 48x48
- - id: mdi_alert
- file: mdi:alert-circle-outline
- resize: 50x50
- - id: another_alert_icon
- file: mdi:alert-outline
- type: BINARY
+<<: !include common.yaml
From 21cb941bbe7afb7096ee342fae2c88bdaa27d28b Mon Sep 17 00:00:00 2001
From: Oleg Tarasov
Date: Fri, 25 Oct 2024 05:00:28 +0300
Subject: [PATCH 44/74] Add OpenTherm component (part 2.1: sensor platform)
(#7529)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
---
esphome/components/opentherm/__init__.py | 20 +-
esphome/components/opentherm/const.py | 5 +
esphome/components/opentherm/generate.py | 140 ++++++
esphome/components/opentherm/hub.cpp | 108 ++++-
esphome/components/opentherm/hub.h | 19 +-
esphome/components/opentherm/opentherm.cpp | 3 +
esphome/components/opentherm/opentherm.h | 3 +-
.../components/opentherm/opentherm_macros.h | 91 ++++
esphome/components/opentherm/schema.py | 438 ++++++++++++++++++
.../components/opentherm/sensor/__init__.py | 35 ++
esphome/components/opentherm/validate.py | 31 ++
tests/components/opentherm/common.yaml | 77 ++-
12 files changed, 933 insertions(+), 37 deletions(-)
create mode 100644 esphome/components/opentherm/const.py
create mode 100644 esphome/components/opentherm/generate.py
create mode 100644 esphome/components/opentherm/opentherm_macros.h
create mode 100644 esphome/components/opentherm/schema.py
create mode 100644 esphome/components/opentherm/sensor/__init__.py
create mode 100644 esphome/components/opentherm/validate.py
diff --git a/esphome/components/opentherm/__init__.py b/esphome/components/opentherm/__init__.py
index 23443a4028..ee19818a29 100644
--- a/esphome/components/opentherm/__init__.py
+++ b/esphome/components/opentherm/__init__.py
@@ -1,9 +1,10 @@
from typing import Any
-from esphome import pins
import esphome.codegen as cg
import esphome.config_validation as cv
+from esphome import pins
from esphome.const import CONF_ID, PLATFORM_ESP32, PLATFORM_ESP8266
+from . import generate
CODEOWNERS = ["@olegtarasov"]
MULTI_CONF = True
@@ -15,15 +16,14 @@ CONF_DHW_ENABLE = "dhw_enable"
CONF_COOLING_ENABLE = "cooling_enable"
CONF_OTC_ACTIVE = "otc_active"
CONF_CH2_ACTIVE = "ch2_active"
+CONF_SUMMER_MODE_ACTIVE = "summer_mode_active"
+CONF_DHW_BLOCK = "dhw_block"
CONF_SYNC_MODE = "sync_mode"
-opentherm_ns = cg.esphome_ns.namespace("opentherm")
-OpenthermHub = opentherm_ns.class_("OpenthermHub", cg.Component)
-
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
- cv.GenerateID(): cv.declare_id(OpenthermHub),
+ cv.GenerateID(): cv.declare_id(generate.OpenthermHub),
cv.Required(CONF_IN_PIN): pins.internal_gpio_input_pin_schema,
cv.Required(CONF_OUT_PIN): pins.internal_gpio_output_pin_schema,
cv.Optional(CONF_CH_ENABLE, True): cv.boolean,
@@ -31,6 +31,8 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(CONF_COOLING_ENABLE, False): cv.boolean,
cv.Optional(CONF_OTC_ACTIVE, False): cv.boolean,
cv.Optional(CONF_CH2_ACTIVE, False): cv.boolean,
+ cv.Optional(CONF_SUMMER_MODE_ACTIVE, False): cv.boolean,
+ cv.Optional(CONF_DHW_BLOCK, False): cv.boolean,
cv.Optional(CONF_SYNC_MODE, False): cv.boolean,
}
).extend(cv.COMPONENT_SCHEMA),
@@ -39,8 +41,6 @@ CONFIG_SCHEMA = cv.All(
async def to_code(config: dict[str, Any]) -> None:
- # Create the hub, passing the two callbacks defined below
- # Since the hub is used in the callbacks, we need to define it first
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
@@ -53,5 +53,7 @@ async def to_code(config: dict[str, Any]) -> None:
non_sensors = {CONF_ID, CONF_IN_PIN, CONF_OUT_PIN}
for key, value in config.items():
- if key not in non_sensors:
- cg.add(getattr(var, f"set_{key}")(value))
+ if key in non_sensors:
+ continue
+
+ cg.add(getattr(var, f"set_{key}")(value))
diff --git a/esphome/components/opentherm/const.py b/esphome/components/opentherm/const.py
new file mode 100644
index 0000000000..1f997c5d9c
--- /dev/null
+++ b/esphome/components/opentherm/const.py
@@ -0,0 +1,5 @@
+OPENTHERM = "opentherm"
+
+CONF_OPENTHERM_ID = "opentherm_id"
+
+SENSOR = "sensor"
diff --git a/esphome/components/opentherm/generate.py b/esphome/components/opentherm/generate.py
new file mode 100644
index 0000000000..6a97835a57
--- /dev/null
+++ b/esphome/components/opentherm/generate.py
@@ -0,0 +1,140 @@
+from collections.abc import Awaitable
+from typing import Any, Callable
+
+import esphome.codegen as cg
+from esphome.const import CONF_ID
+from . import const
+from .schema import TSchema
+
+opentherm_ns = cg.esphome_ns.namespace("opentherm")
+OpenthermHub = opentherm_ns.class_("OpenthermHub", cg.Component)
+
+
+def define_has_component(component_type: str, keys: list[str]) -> None:
+ cg.add_define(
+ f"OPENTHERM_{component_type.upper()}_LIST(F, sep)",
+ cg.RawExpression(
+ " sep ".join(map(lambda key: f"F({key}_{component_type.lower()})", keys))
+ ),
+ )
+ for key in keys:
+ cg.add_define(f"OPENTHERM_HAS_{component_type.upper()}_{key}")
+
+
+def define_message_handler(
+ component_type: str, keys: list[str], schemas: dict[str, TSchema]
+) -> None:
+ # The macros defined here should be able to generate things like this:
+ # // Parsing a message and publishing to sensors
+ # case MessageId::Message:
+ # // Can have multiple sensors here, for example for a Status message with multiple flags
+ # this->thing_binary_sensor->publish_state(parse_flag8_lb_0(response));
+ # this->other_binary_sensor->publish_state(parse_flag8_lb_1(response));
+ # break;
+ # // Building a message for a write request
+ # case MessageId::Message: {
+ # unsigned int data = 0;
+ # data = write_flag8_lb_0(some_input_switch->state, data); // Where input_sensor can also be a number/output/switch
+ # data = write_u8_hb(some_number->state, data);
+ # return opentherm_->build_request_(MessageType::WriteData, MessageId::Message, data);
+ # }
+
+ messages: dict[str, list[tuple[str, str]]] = {}
+ for key in keys:
+ msg = schemas[key].message
+ if msg not in messages:
+ messages[msg] = []
+ messages[msg].append((key, schemas[key].message_data))
+
+ cg.add_define(
+ f"OPENTHERM_{component_type.upper()}_MESSAGE_HANDLERS(MESSAGE, ENTITY, entity_sep, postscript, msg_sep)",
+ cg.RawExpression(
+ " msg_sep ".join(
+ [
+ f"MESSAGE({msg}) "
+ + " entity_sep ".join(
+ [
+ f"ENTITY({key}_{component_type.lower()}, {msg_data})"
+ for key, msg_data in keys
+ ]
+ )
+ + " postscript"
+ for msg, keys in messages.items()
+ ]
+ )
+ ),
+ )
+
+
+def define_readers(component_type: str, keys: list[str]) -> None:
+ for key in keys:
+ cg.add_define(
+ f"OPENTHERM_READ_{key}",
+ cg.RawExpression(f"this->{key}_{component_type.lower()}->state"),
+ )
+
+
+def add_messages(hub: cg.MockObj, keys: list[str], schemas: dict[str, TSchema]):
+ messages: set[tuple[str, bool]] = set()
+ for key in keys:
+ messages.add((schemas[key].message, schemas[key].keep_updated))
+ for msg, keep_updated in messages:
+ msg_expr = cg.RawExpression(f"esphome::opentherm::MessageId::{msg}")
+ if keep_updated:
+ cg.add(hub.add_repeating_message(msg_expr))
+ else:
+ cg.add(hub.add_initial_message(msg_expr))
+
+
+def add_property_set(var: cg.MockObj, config_key: str, config: dict[str, Any]) -> None:
+ if config_key in config:
+ cg.add(getattr(var, f"set_{config_key}")(config[config_key]))
+
+
+Create = Callable[[dict[str, Any], str, cg.MockObj], Awaitable[cg.Pvariable]]
+
+
+def create_only_conf(
+ create: Callable[[dict[str, Any]], Awaitable[cg.Pvariable]]
+) -> Create:
+ return lambda conf, _key, _hub: create(conf)
+
+
+async def component_to_code(
+ component_type: str,
+ schemas: dict[str, TSchema],
+ type: cg.MockObjClass,
+ create: Create,
+ config: dict[str, Any],
+) -> list[str]:
+ """Generate the code for each configured component in the schema of a component type.
+
+ Parameters:
+ - component_type: The type of component, e.g. "sensor" or "binary_sensor"
+ - schema_: The schema for that component type, a list of available components
+ - type: The type of the component, e.g. sensor.Sensor or OpenthermOutput
+ - create: A constructor function for the component, which receives the config,
+ the key and the hub and should asynchronously return the new component
+ - config: The configuration for this component type
+
+ Returns: The list of keys for the created components
+ """
+ cg.add_define(f"OPENTHERM_USE_{component_type.upper()}")
+
+ hub = await cg.get_variable(config[const.CONF_OPENTHERM_ID])
+
+ keys: list[str] = []
+ for key, conf in config.items():
+ if not isinstance(conf, dict):
+ continue
+ id = conf[CONF_ID]
+ if id and id.type == type:
+ entity = await create(conf, key, hub)
+ cg.add(getattr(hub, f"set_{key}_{component_type.lower()}")(entity))
+ keys.append(key)
+
+ define_has_component(component_type, keys)
+ define_message_handler(component_type, keys, schemas)
+ add_messages(hub, keys, schemas)
+
+ return keys
diff --git a/esphome/components/opentherm/hub.cpp b/esphome/components/opentherm/hub.cpp
index c26fbced32..770bbd82b7 100644
--- a/esphome/components/opentherm/hub.cpp
+++ b/esphome/components/opentherm/hub.cpp
@@ -7,50 +7,114 @@ namespace esphome {
namespace opentherm {
static const char *const TAG = "opentherm";
+namespace message_data {
+bool parse_flag8_lb_0(OpenthermData &data) { return read_bit(data.valueLB, 0); }
+bool parse_flag8_lb_1(OpenthermData &data) { return read_bit(data.valueLB, 1); }
+bool parse_flag8_lb_2(OpenthermData &data) { return read_bit(data.valueLB, 2); }
+bool parse_flag8_lb_3(OpenthermData &data) { return read_bit(data.valueLB, 3); }
+bool parse_flag8_lb_4(OpenthermData &data) { return read_bit(data.valueLB, 4); }
+bool parse_flag8_lb_5(OpenthermData &data) { return read_bit(data.valueLB, 5); }
+bool parse_flag8_lb_6(OpenthermData &data) { return read_bit(data.valueLB, 6); }
+bool parse_flag8_lb_7(OpenthermData &data) { return read_bit(data.valueLB, 7); }
+bool parse_flag8_hb_0(OpenthermData &data) { return read_bit(data.valueHB, 0); }
+bool parse_flag8_hb_1(OpenthermData &data) { return read_bit(data.valueHB, 1); }
+bool parse_flag8_hb_2(OpenthermData &data) { return read_bit(data.valueHB, 2); }
+bool parse_flag8_hb_3(OpenthermData &data) { return read_bit(data.valueHB, 3); }
+bool parse_flag8_hb_4(OpenthermData &data) { return read_bit(data.valueHB, 4); }
+bool parse_flag8_hb_5(OpenthermData &data) { return read_bit(data.valueHB, 5); }
+bool parse_flag8_hb_6(OpenthermData &data) { return read_bit(data.valueHB, 6); }
+bool parse_flag8_hb_7(OpenthermData &data) { return read_bit(data.valueHB, 7); }
+uint8_t parse_u8_lb(OpenthermData &data) { return data.valueLB; }
+uint8_t parse_u8_hb(OpenthermData &data) { return data.valueHB; }
+int8_t parse_s8_lb(OpenthermData &data) { return (int8_t) data.valueLB; }
+int8_t parse_s8_hb(OpenthermData &data) { return (int8_t) data.valueHB; }
+uint16_t parse_u16(OpenthermData &data) { return data.u16(); }
+int16_t parse_s16(OpenthermData &data) { return data.s16(); }
+float parse_f88(OpenthermData &data) { return data.f88(); }
-OpenthermData OpenthermHub::build_request_(MessageId request_id) {
+void write_flag8_lb_0(const bool value, OpenthermData &data) { data.valueLB = write_bit(data.valueLB, 0, value); }
+void write_flag8_lb_1(const bool value, OpenthermData &data) { data.valueLB = write_bit(data.valueLB, 1, value); }
+void write_flag8_lb_2(const bool value, OpenthermData &data) { data.valueLB = write_bit(data.valueLB, 2, value); }
+void write_flag8_lb_3(const bool value, OpenthermData &data) { data.valueLB = write_bit(data.valueLB, 3, value); }
+void write_flag8_lb_4(const bool value, OpenthermData &data) { data.valueLB = write_bit(data.valueLB, 4, value); }
+void write_flag8_lb_5(const bool value, OpenthermData &data) { data.valueLB = write_bit(data.valueLB, 5, value); }
+void write_flag8_lb_6(const bool value, OpenthermData &data) { data.valueLB = write_bit(data.valueLB, 6, value); }
+void write_flag8_lb_7(const bool value, OpenthermData &data) { data.valueLB = write_bit(data.valueLB, 7, value); }
+void write_flag8_hb_0(const bool value, OpenthermData &data) { data.valueHB = write_bit(data.valueHB, 0, value); }
+void write_flag8_hb_1(const bool value, OpenthermData &data) { data.valueHB = write_bit(data.valueHB, 1, value); }
+void write_flag8_hb_2(const bool value, OpenthermData &data) { data.valueHB = write_bit(data.valueHB, 2, value); }
+void write_flag8_hb_3(const bool value, OpenthermData &data) { data.valueHB = write_bit(data.valueHB, 3, value); }
+void write_flag8_hb_4(const bool value, OpenthermData &data) { data.valueHB = write_bit(data.valueHB, 4, value); }
+void write_flag8_hb_5(const bool value, OpenthermData &data) { data.valueHB = write_bit(data.valueHB, 5, value); }
+void write_flag8_hb_6(const bool value, OpenthermData &data) { data.valueHB = write_bit(data.valueHB, 6, value); }
+void write_flag8_hb_7(const bool value, OpenthermData &data) { data.valueHB = write_bit(data.valueHB, 7, value); }
+void write_u8_lb(const uint8_t value, OpenthermData &data) { data.valueLB = value; }
+void write_u8_hb(const uint8_t value, OpenthermData &data) { data.valueHB = value; }
+void write_s8_lb(const int8_t value, OpenthermData &data) { data.valueLB = (uint8_t) value; }
+void write_s8_hb(const int8_t value, OpenthermData &data) { data.valueHB = (uint8_t) value; }
+void write_u16(const uint16_t value, OpenthermData &data) { data.u16(value); }
+void write_s16(const int16_t value, OpenthermData &data) { data.s16(value); }
+void write_f88(const float value, OpenthermData &data) { data.f88(value); }
+
+} // namespace message_data
+
+OpenthermData OpenthermHub::build_request_(MessageId request_id) const {
OpenthermData data;
data.type = 0;
data.id = 0;
data.valueHB = 0;
data.valueLB = 0;
- // First, handle the status request. This requires special logic, because we
- // wouldn't want to inadvertently disable domestic hot water, for example.
- // It is also included in the macro-generated code below, but that will
- // never be executed, because we short-circuit it here.
+ // We need this special logic for STATUS message because we have two options for specifying boiler modes:
+ // with static config values in the hub, or with separate switches.
if (request_id == MessageId::STATUS) {
- bool const ch_enabled = this->ch_enable;
- bool dhw_enabled = this->dhw_enable;
- bool cooling_enabled = this->cooling_enable;
- bool otc_enabled = this->otc_active;
- bool ch2_enabled = this->ch2_active;
+ // NOLINTBEGIN
+ bool const ch_enabled = this->ch_enable && OPENTHERM_READ_ch_enable && OPENTHERM_READ_t_set > 0.0;
+ bool const dhw_enabled = this->dhw_enable && OPENTHERM_READ_dhw_enable;
+ bool const cooling_enabled =
+ this->cooling_enable && OPENTHERM_READ_cooling_enable && OPENTHERM_READ_cooling_control > 0.0;
+ bool const otc_enabled = this->otc_active && OPENTHERM_READ_otc_active;
+ bool const ch2_enabled = this->ch2_active && OPENTHERM_READ_ch2_active && OPENTHERM_READ_t_set_ch2 > 0.0;
+ bool const summer_mode_is_active = this->summer_mode_active && OPENTHERM_READ_summer_mode_active;
+ bool const dhw_blocked = this->dhw_block && OPENTHERM_READ_dhw_block;
+ // NOLINTEND
data.type = MessageType::READ_DATA;
data.id = MessageId::STATUS;
- data.valueHB = ch_enabled | (dhw_enabled << 1) | (cooling_enabled << 2) | (otc_enabled << 3) | (ch2_enabled << 4);
+ data.valueHB = ch_enabled | (dhw_enabled << 1) | (cooling_enabled << 2) | (otc_enabled << 3) | (ch2_enabled << 4) |
+ (summer_mode_is_active << 5) | (dhw_blocked << 6);
+
+ return data;
+ }
// Disable incomplete switch statement warnings, because the cases in each
// switch are generated based on the configured sensors and inputs.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch"
- // TODO: This is a placeholder for an auto-generated switch statement which builds request structure based on
- // which sensors are enabled in config.
+ switch (request_id) { OPENTHERM_SENSOR_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_READ_MESSAGE, OPENTHERM_IGNORE, , , ) }
#pragma GCC diagnostic pop
- return data;
- }
- return OpenthermData();
+ // And if we get here, a message was requested which somehow wasn't handled.
+ // This shouldn't happen due to the way the defines are configured, so we
+ // log an error and just return a 0 message.
+ ESP_LOGE(TAG, "Tried to create a request with unknown id %d. This should never happen, so please open an issue.",
+ request_id);
+ return {};
}
-OpenthermHub::OpenthermHub() : Component() {}
+OpenthermHub::OpenthermHub() : Component(), in_pin_{}, out_pin_{} {}
void OpenthermHub::process_response(OpenthermData &data) {
ESP_LOGD(TAG, "Received OpenTherm response with id %d (%s)", data.id,
this->opentherm_->message_id_to_str((MessageId) data.id));
ESP_LOGD(TAG, "%s", this->opentherm_->debug_data(data).c_str());
+
+ switch (data.id) {
+ OPENTHERM_SENSOR_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_RESPONSE_MESSAGE, OPENTHERM_MESSAGE_RESPONSE_ENTITY, ,
+ OPENTHERM_MESSAGE_RESPONSE_POSTSCRIPT, )
+ }
}
void OpenthermHub::setup() {
@@ -254,15 +318,17 @@ void OpenthermHub::handle_timeout_error_() {
this->stop_opentherm_();
}
-#define ID(x) x
-#define SHOW2(x) #x
-#define SHOW(x) SHOW2(x)
-
void OpenthermHub::dump_config() {
ESP_LOGCONFIG(TAG, "OpenTherm:");
LOG_PIN(" In: ", this->in_pin_);
LOG_PIN(" Out: ", this->out_pin_);
ESP_LOGCONFIG(TAG, " Sync mode: %d", this->sync_mode_);
+ ESP_LOGCONFIG(TAG, " Sensors: %s", SHOW(OPENTHERM_SENSOR_LIST(ID, )));
+ ESP_LOGCONFIG(TAG, " Binary sensors: %s", SHOW(OPENTHERM_BINARY_SENSOR_LIST(ID, )));
+ ESP_LOGCONFIG(TAG, " Switches: %s", SHOW(OPENTHERM_SWITCH_LIST(ID, )));
+ ESP_LOGCONFIG(TAG, " Input sensors: %s", SHOW(OPENTHERM_INPUT_SENSOR_LIST(ID, )));
+ ESP_LOGCONFIG(TAG, " Outputs: %s", SHOW(OPENTHERM_OUTPUT_LIST(ID, )));
+ ESP_LOGCONFIG(TAG, " Numbers: %s", SHOW(OPENTHERM_NUMBER_LIST(ID, )));
ESP_LOGCONFIG(TAG, " Initial requests:");
for (auto type : this->initial_messages_) {
ESP_LOGCONFIG(TAG, " - %d", type);
diff --git a/esphome/components/opentherm/hub.h b/esphome/components/opentherm/hub.h
index ce9f09fe33..3b90cdf427 100644
--- a/esphome/components/opentherm/hub.h
+++ b/esphome/components/opentherm/hub.h
@@ -7,11 +7,17 @@
#include "opentherm.h"
+#ifdef OPENTHERM_USE_SENSOR
+#include "esphome/components/sensor/sensor.h"
+#endif
+
#include
#include
#include
#include
+#include "opentherm_macros.h"
+
namespace esphome {
namespace opentherm {
@@ -23,6 +29,8 @@ class OpenthermHub : public Component {
// The OpenTherm interface
std::unique_ptr opentherm_;
+ OPENTHERM_SENSOR_LIST(OPENTHERM_DECLARE_SENSOR, )
+
// The set of initial messages to send on starting communication with the boiler
std::unordered_set initial_messages_;
// and the repeating messages which are sent repeatedly to update various sensors
@@ -44,7 +52,7 @@ class OpenthermHub : public Component {
bool sync_mode_ = false;
// Create OpenTherm messages based on the message id
- OpenthermData build_request_(MessageId request_id);
+ OpenthermData build_request_(MessageId request_id) const;
void handle_protocol_write_error_();
void handle_protocol_read_error_();
void handle_timeout_error_();
@@ -78,6 +86,8 @@ class OpenthermHub : public Component {
void set_in_pin(InternalGPIOPin *in_pin) { this->in_pin_ = in_pin; }
void set_out_pin(InternalGPIOPin *out_pin) { this->out_pin_ = out_pin; }
+ OPENTHERM_SENSOR_LIST(OPENTHERM_SET_SENSOR, )
+
// Add a request to the set of initial requests
void add_initial_message(MessageId message_id) { this->initial_messages_.insert(message_id); }
// Add a request to the set of repeating requests. Note that a large number of repeating
@@ -86,9 +96,10 @@ class OpenthermHub : public Component {
// will be processed.
void add_repeating_message(MessageId message_id) { this->repeating_messages_.insert(message_id); }
- // There are five status variables, which can either be set as a simple variable,
+ // There are seven status variables, which can either be set as a simple variable,
// or using a switch. ch_enable and dhw_enable default to true, the others to false.
- bool ch_enable = true, dhw_enable = true, cooling_enable = false, otc_active = false, ch2_active = false;
+ bool ch_enable = true, dhw_enable = true, cooling_enable = false, otc_active = false, ch2_active = false,
+ summer_mode_active = false, dhw_block = false;
// Setters for the status variables
void set_ch_enable(bool value) { this->ch_enable = value; }
@@ -96,6 +107,8 @@ class OpenthermHub : public Component {
void set_cooling_enable(bool value) { this->cooling_enable = value; }
void set_otc_active(bool value) { this->otc_active = value; }
void set_ch2_active(bool value) { this->ch2_active = value; }
+ void set_summer_mode_active(bool value) { this->summer_mode_active = value; }
+ void set_dhw_block(bool value) { this->dhw_block = value; }
void set_sync_mode(bool sync_mode) { this->sync_mode_ = sync_mode; }
float get_setup_priority() const override { return setup_priority::HARDWARE; }
diff --git a/esphome/components/opentherm/opentherm.cpp b/esphome/components/opentherm/opentherm.cpp
index b830cc01d3..4a23bb94cf 100644
--- a/esphome/components/opentherm/opentherm.cpp
+++ b/esphome/components/opentherm/opentherm.cpp
@@ -283,6 +283,9 @@ bool OpenTherm::init_esp32_timer_() {
.clk_src = TIMER_SRC_CLK_DEFAULT,
#endif
.divider = 80,
+#if defined(SOC_TIMER_GROUP_SUPPORT_XTAL) && ESP_IDF_VERSION_MAJOR < 5
+ .clk_src = TIMER_SRC_CLK_APB
+#endif
};
esp_err_t result;
diff --git a/esphome/components/opentherm/opentherm.h b/esphome/components/opentherm/opentherm.h
index 609cfb6243..23f4b39a1a 100644
--- a/esphome/components/opentherm/opentherm.h
+++ b/esphome/components/opentherm/opentherm.h
@@ -20,7 +20,6 @@
namespace esphome {
namespace opentherm {
-// TODO: Account for immutable semantics change in hub.cpp when doing later installments of OpenTherm PR
template constexpr T read_bit(T value, uint8_t bit) { return (value >> bit) & 0x01; }
template constexpr T set_bit(T value, uint8_t bit) { return value |= (1UL << bit); }
@@ -28,7 +27,7 @@ template constexpr T set_bit(T value, uint8_t bit) { return value |= (1
template constexpr T clear_bit(T value, uint8_t bit) { return value &= ~(1UL << bit); }
template constexpr T write_bit(T value, uint8_t bit, uint8_t bit_value) {
- return bit_value ? setBit(value, bit) : clearBit(value, bit);
+ return bit_value ? set_bit(value, bit) : clear_bit(value, bit);
}
enum OperationMode {
diff --git a/esphome/components/opentherm/opentherm_macros.h b/esphome/components/opentherm/opentherm_macros.h
new file mode 100644
index 0000000000..0389e975ff
--- /dev/null
+++ b/esphome/components/opentherm/opentherm_macros.h
@@ -0,0 +1,91 @@
+#pragma once
+namespace esphome {
+namespace opentherm {
+
+// ===== hub.h macros =====
+
+// *_LIST macros will be generated in defines.h if at least one sensor from each platform is used.
+// These lists will look like this:
+// #define OPENTHERM_BINARY_SENSOR_LIST(F, sep) F(sensor_1) sep F(sensor_2)
+// These lists will be used in hub.h to define sensor fields (passing macros like OPENTHERM_DECLARE_SENSOR as F)
+// and setters (passing macros like OPENTHERM_SET_SENSOR as F) (see below)
+// In order for things not to break, we define empty lists here in case some platforms are not used in config.
+#ifndef OPENTHERM_SENSOR_LIST
+#define OPENTHERM_SENSOR_LIST(F, sep)
+#endif
+
+// Use macros to create fields for every entity specified in the ESPHome configuration
+#define OPENTHERM_DECLARE_SENSOR(entity) sensor::Sensor *entity;
+
+// Setter macros
+#define OPENTHERM_SET_SENSOR(entity) \
+ void set_##entity(sensor::Sensor *sensor) { this->entity = sensor; }
+
+// ===== hub.cpp macros =====
+
+// *_MESSAGE_HANDLERS are generated in defines.h and look like this:
+// OPENTHERM_NUMBER_MESSAGE_HANDLERS(MESSAGE, ENTITY, entity_sep, postscript, msg_sep) MESSAGE(COOLING_CONTROL)
+// ENTITY(cooling_control_number, f88) postscript msg_sep They contain placeholders for message part and entities parts,
+// since one message can contain multiple entities. MESSAGE part is substituted with OPENTHERM_MESSAGE_WRITE_MESSAGE,
+// OPENTHERM_MESSAGE_READ_MESSAGE or OPENTHERM_MESSAGE_RESPONSE_MESSAGE. ENTITY part is substituted with
+// OPENTHERM_MESSAGE_WRITE_ENTITY or OPENTHERM_MESSAGE_RESPONSE_ENTITY. OPENTHERM_IGNORE is used for sensor read
+// requests since no data needs to be sent or processed, just the data id.
+
+// In order for things not to break, we define empty lists here in case some platforms are not used in config.
+#ifndef OPENTHERM_SENSOR_MESSAGE_HANDLERS
+#define OPENTHERM_SENSOR_MESSAGE_HANDLERS(MESSAGE, ENTITY, entity_sep, postscript, msg_sep)
+#endif
+
+// Read data request builder
+#define OPENTHERM_MESSAGE_READ_MESSAGE(msg) \
+ case MessageId::msg: \
+ data.type = MessageType::READ_DATA; \
+ data.id = request_id; \
+ return data;
+
+// Data processing builders
+#define OPENTHERM_MESSAGE_RESPONSE_MESSAGE(msg) case MessageId::msg:
+#define OPENTHERM_MESSAGE_RESPONSE_ENTITY(key, msg_data) this->key->publish_state(message_data::parse_##msg_data(data));
+#define OPENTHERM_MESSAGE_RESPONSE_POSTSCRIPT break;
+
+#define OPENTHERM_IGNORE(x, y)
+
+// Default macros for STATUS entities
+#ifndef OPENTHERM_READ_ch_enable
+#define OPENTHERM_READ_ch_enable true
+#endif
+#ifndef OPENTHERM_READ_dhw_enable
+#define OPENTHERM_READ_dhw_enable true
+#endif
+#ifndef OPENTHERM_READ_t_set
+#define OPENTHERM_READ_t_set 0.0
+#endif
+#ifndef OPENTHERM_READ_cooling_enable
+#define OPENTHERM_READ_cooling_enable false
+#endif
+#ifndef OPENTHERM_READ_cooling_control
+#define OPENTHERM_READ_cooling_control 0.0
+#endif
+#ifndef OPENTHERM_READ_otc_active
+#define OPENTHERM_READ_otc_active false
+#endif
+#ifndef OPENTHERM_READ_ch2_active
+#define OPENTHERM_READ_ch2_active false
+#endif
+#ifndef OPENTHERM_READ_t_set_ch2
+#define OPENTHERM_READ_t_set_ch2 0.0
+#endif
+#ifndef OPENTHERM_READ_summer_mode_active
+#define OPENTHERM_READ_summer_mode_active false
+#endif
+#ifndef OPENTHERM_READ_dhw_block
+#define OPENTHERM_READ_dhw_block false
+#endif
+
+// These macros utilize the structure of *_LIST macros in order
+#define ID(x) x
+#define SHOW_INNER(x) #x
+#define SHOW(x) SHOW_INNER(x)
+
+} // namespace opentherm
+} // namespace esphome
diff --git a/esphome/components/opentherm/schema.py b/esphome/components/opentherm/schema.py
new file mode 100644
index 0000000000..6ed0029437
--- /dev/null
+++ b/esphome/components/opentherm/schema.py
@@ -0,0 +1,438 @@
+# This file contains a schema for all supported sensors, binary sensors and
+# inputs of the OpenTherm component.
+
+from dataclasses import dataclass
+from typing import Optional, TypeVar
+
+from esphome.const import (
+ UNIT_CELSIUS,
+ UNIT_EMPTY,
+ UNIT_KILOWATT,
+ UNIT_MICROAMP,
+ UNIT_PERCENT,
+ UNIT_REVOLUTIONS_PER_MINUTE,
+ DEVICE_CLASS_CURRENT,
+ DEVICE_CLASS_EMPTY,
+ DEVICE_CLASS_PRESSURE,
+ DEVICE_CLASS_TEMPERATURE,
+ STATE_CLASS_MEASUREMENT,
+ STATE_CLASS_NONE,
+ STATE_CLASS_TOTAL_INCREASING,
+)
+
+
+@dataclass
+class EntitySchema:
+ description: str
+ """Description of the item, based on the OpenTherm spec"""
+
+ message: str
+ """OpenTherm message id used to read or write the value"""
+
+ keep_updated: bool
+ """Whether the value should be read or write repeatedly (True) or only during
+ the initialization phase (False)
+ """
+
+ message_data: str
+ """Instructions on how to interpret the data in the message
+ - flag8_[hb|lb]_[0-7]: data is a byte of single bit flags,
+ this flag is set in the high (hb) or low byte (lb),
+ at position 0 to 7
+ - u8_[hb|lb]: data is an unsigned 8-bit integer,
+ in the high (hb) or low byte (lb)
+ - s8_[hb|lb]: data is an signed 8-bit integer,
+ in the high (hb) or low byte (lb)
+ - f88: data is a signed fixed point value with
+ 1 sign bit, 7 integer bits, 8 fractional bits
+ - u16: data is an unsigned 16-bit integer
+ - s16: data is a signed 16-bit integer
+ """
+
+
+TSchema = TypeVar("TSchema", bound=EntitySchema)
+
+
+@dataclass
+class SensorSchema(EntitySchema):
+ accuracy_decimals: int
+ state_class: str
+ unit_of_measurement: Optional[str] = None
+ icon: Optional[str] = None
+ device_class: Optional[str] = None
+ disabled_by_default: bool = False
+
+
+SENSORS: dict[str, SensorSchema] = {
+ "rel_mod_level": SensorSchema(
+ description="Relative modulation level",
+ unit_of_measurement=UNIT_PERCENT,
+ accuracy_decimals=2,
+ icon="mdi:percent",
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="MODULATION_LEVEL",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "ch_pressure": SensorSchema(
+ description="Water pressure in CH circuit",
+ unit_of_measurement="bar",
+ accuracy_decimals=2,
+ device_class=DEVICE_CLASS_PRESSURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="CH_WATER_PRESSURE",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "dhw_flow_rate": SensorSchema(
+ description="Water flow rate in DHW circuit",
+ unit_of_measurement="l/min",
+ accuracy_decimals=2,
+ icon="mdi:waves-arrow-right",
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="DHW_FLOW_RATE",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "t_boiler": SensorSchema(
+ description="Boiler water temperature",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=2,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="FEED_TEMP",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "t_dhw": SensorSchema(
+ description="DHW temperature",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=2,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="DHW_TEMP",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "t_outside": SensorSchema(
+ description="Outside temperature",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=2,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="OUTSIDE_TEMP",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "t_ret": SensorSchema(
+ description="Return water temperature",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=2,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="RETURN_WATER_TEMP",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "t_storage": SensorSchema(
+ description="Solar storage temperature",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=2,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="SOLAR_STORE_TEMP",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "t_collector": SensorSchema(
+ description="Solar collector temperature",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=0,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="SOLAR_COLLECT_TEMP",
+ keep_updated=True,
+ message_data="s16",
+ ),
+ "t_flow_ch2": SensorSchema(
+ description="Flow water temperature CH2 circuit",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=2,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="FEED_TEMP_CH2",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "t_dhw2": SensorSchema(
+ description="Domestic hot water temperature 2",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=2,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="DHW2_TEMP",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "t_exhaust": SensorSchema(
+ description="Boiler exhaust temperature",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=0,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="EXHAUST_TEMP",
+ keep_updated=True,
+ message_data="s16",
+ ),
+ "fan_speed": SensorSchema(
+ description="Boiler fan speed",
+ unit_of_measurement=UNIT_REVOLUTIONS_PER_MINUTE,
+ accuracy_decimals=0,
+ device_class=DEVICE_CLASS_EMPTY,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="FAN_SPEED",
+ keep_updated=True,
+ message_data="u16",
+ ),
+ "flame_current": SensorSchema(
+ description="Boiler flame current",
+ unit_of_measurement=UNIT_MICROAMP,
+ accuracy_decimals=0,
+ device_class=DEVICE_CLASS_CURRENT,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="FLAME_CURRENT",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "burner_starts": SensorSchema(
+ description="Number of starts burner",
+ accuracy_decimals=0,
+ icon="mdi:gas-burner",
+ state_class=STATE_CLASS_TOTAL_INCREASING,
+ message="BURNER_STARTS",
+ keep_updated=True,
+ message_data="u16",
+ ),
+ "ch_pump_starts": SensorSchema(
+ description="Number of starts CH pump",
+ accuracy_decimals=0,
+ icon="mdi:pump",
+ state_class=STATE_CLASS_TOTAL_INCREASING,
+ message="CH_PUMP_STARTS",
+ keep_updated=True,
+ message_data="u16",
+ ),
+ "dhw_pump_valve_starts": SensorSchema(
+ description="Number of starts DHW pump/valve",
+ accuracy_decimals=0,
+ icon="mdi:water-pump",
+ state_class=STATE_CLASS_TOTAL_INCREASING,
+ message="DHW_PUMP_STARTS",
+ keep_updated=True,
+ message_data="u16",
+ ),
+ "dhw_burner_starts": SensorSchema(
+ description="Number of starts burner during DHW mode",
+ accuracy_decimals=0,
+ icon="mdi:gas-burner",
+ state_class=STATE_CLASS_TOTAL_INCREASING,
+ message="DHW_BURNER_STARTS",
+ keep_updated=True,
+ message_data="u16",
+ ),
+ "burner_operation_hours": SensorSchema(
+ description="Number of hours that burner is in operation",
+ accuracy_decimals=0,
+ icon="mdi:clock-outline",
+ state_class=STATE_CLASS_TOTAL_INCREASING,
+ message="BURNER_HOURS",
+ keep_updated=True,
+ message_data="u16",
+ ),
+ "ch_pump_operation_hours": SensorSchema(
+ description="Number of hours that CH pump has been running",
+ accuracy_decimals=0,
+ icon="mdi:clock-outline",
+ state_class=STATE_CLASS_TOTAL_INCREASING,
+ message="CH_PUMP_HOURS",
+ keep_updated=True,
+ message_data="u16",
+ ),
+ "dhw_pump_valve_operation_hours": SensorSchema(
+ description="Number of hours that DHW pump has been running or DHW valve has been opened",
+ accuracy_decimals=0,
+ icon="mdi:clock-outline",
+ state_class=STATE_CLASS_TOTAL_INCREASING,
+ message="DHW_PUMP_HOURS",
+ keep_updated=True,
+ message_data="u16",
+ ),
+ "dhw_burner_operation_hours": SensorSchema(
+ description="Number of hours that burner is in operation during DHW mode",
+ accuracy_decimals=0,
+ icon="mdi:clock-outline",
+ state_class=STATE_CLASS_TOTAL_INCREASING,
+ message="DHW_BURNER_HOURS",
+ keep_updated=True,
+ message_data="u16",
+ ),
+ "t_dhw_set_ub": SensorSchema(
+ description="Upper bound for adjustment of DHW setpoint",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=0,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="DHW_BOUNDS",
+ keep_updated=False,
+ message_data="s8_hb",
+ ),
+ "t_dhw_set_lb": SensorSchema(
+ description="Lower bound for adjustment of DHW setpoint",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=0,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="DHW_BOUNDS",
+ keep_updated=False,
+ message_data="s8_lb",
+ ),
+ "max_t_set_ub": SensorSchema(
+ description="Upper bound for adjustment of max CH setpoint",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=0,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="CH_BOUNDS",
+ keep_updated=False,
+ message_data="s8_hb",
+ ),
+ "max_t_set_lb": SensorSchema(
+ description="Lower bound for adjustment of max CH setpoint",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=0,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="CH_BOUNDS",
+ keep_updated=False,
+ message_data="s8_lb",
+ ),
+ "t_dhw_set": SensorSchema(
+ description="Domestic hot water temperature setpoint",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=2,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="DHW_SETPOINT",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "max_t_set": SensorSchema(
+ description="Maximum allowable CH water setpoint",
+ unit_of_measurement=UNIT_CELSIUS,
+ accuracy_decimals=2,
+ device_class=DEVICE_CLASS_TEMPERATURE,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="MAX_CH_SETPOINT",
+ keep_updated=True,
+ message_data="f88",
+ ),
+ "oem_fault_code": SensorSchema(
+ description="OEM fault code",
+ unit_of_measurement=UNIT_EMPTY,
+ accuracy_decimals=0,
+ state_class=STATE_CLASS_NONE,
+ message="FAULT_FLAGS",
+ keep_updated=True,
+ message_data="u8_lb",
+ ),
+ "oem_diagnostic_code": SensorSchema(
+ description="OEM diagnostic code",
+ unit_of_measurement=UNIT_EMPTY,
+ accuracy_decimals=0,
+ state_class=STATE_CLASS_NONE,
+ message="OEM_DIAGNOSTIC",
+ keep_updated=True,
+ message_data="u16",
+ ),
+ "max_capacity": SensorSchema(
+ description="Maximum boiler capacity (KW)",
+ unit_of_measurement=UNIT_KILOWATT,
+ accuracy_decimals=0,
+ state_class=STATE_CLASS_MEASUREMENT,
+ disabled_by_default=True,
+ message="MAX_BOILER_CAPACITY",
+ keep_updated=False,
+ message_data="u8_hb",
+ ),
+ "min_mod_level": SensorSchema(
+ description="Minimum modulation level",
+ unit_of_measurement=UNIT_PERCENT,
+ accuracy_decimals=0,
+ icon="mdi:percent",
+ disabled_by_default=True,
+ state_class=STATE_CLASS_MEASUREMENT,
+ message="MAX_BOILER_CAPACITY",
+ keep_updated=False,
+ message_data="u8_lb",
+ ),
+ "opentherm_version_device": SensorSchema(
+ description="Version of OpenTherm implemented by device",
+ unit_of_measurement=UNIT_EMPTY,
+ accuracy_decimals=0,
+ state_class=STATE_CLASS_NONE,
+ disabled_by_default=True,
+ message="OT_VERSION_DEVICE",
+ keep_updated=False,
+ message_data="f88",
+ ),
+ "device_type": SensorSchema(
+ description="Device product type",
+ unit_of_measurement=UNIT_EMPTY,
+ accuracy_decimals=0,
+ state_class=STATE_CLASS_NONE,
+ disabled_by_default=True,
+ message="VERSION_DEVICE",
+ keep_updated=False,
+ message_data="u8_hb",
+ ),
+ "device_version": SensorSchema(
+ description="Device product version",
+ unit_of_measurement=UNIT_EMPTY,
+ accuracy_decimals=0,
+ state_class=STATE_CLASS_NONE,
+ disabled_by_default=True,
+ message="VERSION_DEVICE",
+ keep_updated=False,
+ message_data="u8_lb",
+ ),
+ "device_id": SensorSchema(
+ description="Device ID code",
+ unit_of_measurement=UNIT_EMPTY,
+ accuracy_decimals=0,
+ state_class=STATE_CLASS_NONE,
+ disabled_by_default=True,
+ message="DEVICE_CONFIG",
+ keep_updated=False,
+ message_data="u8_lb",
+ ),
+ "otc_hc_ratio_ub": SensorSchema(
+ description="OTC heat curve ratio upper bound",
+ unit_of_measurement=UNIT_EMPTY,
+ accuracy_decimals=0,
+ state_class=STATE_CLASS_NONE,
+ disabled_by_default=True,
+ message="OTC_CURVE_BOUNDS",
+ keep_updated=False,
+ message_data="u8_hb",
+ ),
+ "otc_hc_ratio_lb": SensorSchema(
+ description="OTC heat curve ratio lower bound",
+ unit_of_measurement=UNIT_EMPTY,
+ accuracy_decimals=0,
+ state_class=STATE_CLASS_NONE,
+ disabled_by_default=True,
+ message="OTC_CURVE_BOUNDS",
+ keep_updated=False,
+ message_data="u8_lb",
+ ),
+}
diff --git a/esphome/components/opentherm/sensor/__init__.py b/esphome/components/opentherm/sensor/__init__.py
new file mode 100644
index 0000000000..20224e0eda
--- /dev/null
+++ b/esphome/components/opentherm/sensor/__init__.py
@@ -0,0 +1,35 @@
+from typing import Any
+
+import esphome.config_validation as cv
+from esphome.components import sensor
+from .. import const, schema, validate, generate
+
+DEPENDENCIES = [const.OPENTHERM]
+COMPONENT_TYPE = const.SENSOR
+
+
+def get_entity_validation_schema(entity: schema.SensorSchema) -> cv.Schema:
+ return sensor.sensor_schema(
+ unit_of_measurement=entity.unit_of_measurement
+ or sensor._UNDEF, # pylint: disable=protected-access
+ accuracy_decimals=entity.accuracy_decimals,
+ device_class=entity.device_class
+ or sensor._UNDEF, # pylint: disable=protected-access
+ icon=entity.icon or sensor._UNDEF, # pylint: disable=protected-access
+ state_class=entity.state_class,
+ )
+
+
+CONFIG_SCHEMA = validate.create_component_schema(
+ schema.SENSORS, get_entity_validation_schema
+)
+
+
+async def to_code(config: dict[str, Any]) -> None:
+ await generate.component_to_code(
+ COMPONENT_TYPE,
+ schema.SENSORS,
+ sensor.Sensor,
+ generate.create_only_conf(sensor.new_sensor),
+ config,
+ )
diff --git a/esphome/components/opentherm/validate.py b/esphome/components/opentherm/validate.py
new file mode 100644
index 0000000000..d4507672a5
--- /dev/null
+++ b/esphome/components/opentherm/validate.py
@@ -0,0 +1,31 @@
+from typing import Callable
+
+from voluptuous import Schema
+
+import esphome.config_validation as cv
+
+from . import const, schema, generate
+from .schema import TSchema
+
+
+def create_entities_schema(
+ entities: dict[str, schema.EntitySchema],
+ get_entity_validation_schema: Callable[[TSchema], cv.Schema],
+) -> Schema:
+ entity_schema = {}
+ for key, entity in entities.items():
+ entity_schema[cv.Optional(key)] = get_entity_validation_schema(entity)
+ return cv.Schema(entity_schema)
+
+
+def create_component_schema(
+ entities: dict[str, schema.EntitySchema],
+ get_entity_validation_schema: Callable[[TSchema], cv.Schema],
+) -> Schema:
+ return (
+ cv.Schema(
+ {cv.GenerateID(const.CONF_OPENTHERM_ID): cv.use_id(generate.OpenthermHub)}
+ )
+ .extend(create_entities_schema(entities, get_entity_validation_schema))
+ .extend(cv.COMPONENT_SCHEMA)
+ )
diff --git a/tests/components/opentherm/common.yaml b/tests/components/opentherm/common.yaml
index 4148b280d0..27cbae280a 100644
--- a/tests/components/opentherm/common.yaml
+++ b/tests/components/opentherm/common.yaml
@@ -1,3 +1,76 @@
+api:
+wifi:
+ ap:
+ ssid: "Thermostat"
+ password: "MySecretThemostat"
+
opentherm:
- in_pin: 1
- out_pin: 2
+ in_pin: 4
+ out_pin: 5
+ ch_enable: true
+ dhw_enable: false
+ cooling_enable: false
+ otc_active: false
+ ch2_active: true
+ summer_mode_active: true
+ dhw_block: true
+ sync_mode: true
+
+sensor:
+ - platform: opentherm
+ rel_mod_level:
+ name: "Boiler Relative modulation level"
+ ch_pressure:
+ name: "Boiler Water pressure in CH circuit"
+ dhw_flow_rate:
+ name: "Boiler Water flow rate in DHW circuit"
+ t_boiler:
+ name: "Boiler water temperature"
+ t_dhw:
+ name: "Boiler DHW temperature"
+ t_outside:
+ name: "Boiler Outside temperature"
+ t_ret:
+ name: "Boiler Return water temperature"
+ t_storage:
+ name: "Boiler Solar storage temperature"
+ t_collector:
+ name: "Boiler Solar collector temperature"
+ t_flow_ch2:
+ name: "Boiler Flow water temperature CH2 circuit"
+ t_dhw2:
+ name: "Boiler Domestic hot water temperature 2"
+ t_exhaust:
+ name: "Boiler Exhaust temperature"
+ burner_starts:
+ name: "Boiler Number of starts burner"
+ ch_pump_starts:
+ name: "Boiler Number of starts CH pump"
+ dhw_pump_valve_starts:
+ name: "Boiler Number of starts DHW pump/valve"
+ dhw_burner_starts:
+ name: "Boiler Number of starts burner during DHW mode"
+ burner_operation_hours:
+ name: "Boiler Number of hours that burner is in operation (i.e. flame on)"
+ ch_pump_operation_hours:
+ name: "Boiler Number of hours that CH pump has been running"
+ dhw_pump_valve_operation_hours:
+ name: "Boiler Number of hours that DHW pump has been running or DHW valve has been opened"
+ dhw_burner_operation_hours:
+ name: "Boiler Number of hours that burner is in operation during DHW mode"
+ t_dhw_set_ub:
+ name: "Boiler Upper bound for adjustement of DHW setpoint"
+ t_dhw_set_lb:
+ name: "Boiler Lower bound for adjustement of DHW setpoint"
+ max_t_set_ub:
+ name: "Boiler Upper bound for adjustement of max CH setpoint"
+ max_t_set_lb:
+ name: "Boiler Lower bound for adjustement of max CH setpoint"
+ t_dhw_set:
+ name: "Boiler Domestic hot water temperature setpoint"
+ max_t_set:
+ name: "Boiler Maximum allowable CH water setpoint"
+ otc_hc_ratio_ub:
+ name: "OTC heat curve ratio upper bound"
+ otc_hc_ratio_lb:
+ name: "OTC heat curve ratio lower bound"
From 34de2bbe992b842ad8017daa94ba6500ffb26d1c Mon Sep 17 00:00:00 2001
From: SeByDocKy
Date: Sat, 26 Oct 2024 23:54:57 +0200
Subject: [PATCH 45/74] gp8403 : Add the possibility to use substitution for
channel selection (#7681)
---
esphome/components/gp8403/output/__init__.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/esphome/components/gp8403/output/__init__.py b/esphome/components/gp8403/output/__init__.py
index 1cf95ac6e5..7f17faa1b1 100644
--- a/esphome/components/gp8403/output/__init__.py
+++ b/esphome/components/gp8403/output/__init__.py
@@ -16,7 +16,7 @@ CONFIG_SCHEMA = output.FLOAT_OUTPUT_SCHEMA.extend(
{
cv.GenerateID(): cv.declare_id(GP8403Output),
cv.GenerateID(CONF_GP8403_ID): cv.use_id(GP8403),
- cv.Required(CONF_CHANNEL): cv.one_of(0, 1),
+ cv.Required(CONF_CHANNEL): cv.int_range(min=0, max=1),
}
).extend(cv.COMPONENT_SCHEMA)
From 1e2497748d3a18847df868ac8f4b893800426652 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Sun, 27 Oct 2024 13:17:09 +1100
Subject: [PATCH 46/74] [rpi_dpi_rgb] Fix get_width and height (Bugfix) (#7675)
Co-authored-by: clydeps
---
.../components/rpi_dpi_rgb/rpi_dpi_rgb.cpp | 20 +++++++++++++++++++
esphome/components/rpi_dpi_rgb/rpi_dpi_rgb.h | 5 +++--
2 files changed, 23 insertions(+), 2 deletions(-)
diff --git a/esphome/components/rpi_dpi_rgb/rpi_dpi_rgb.cpp b/esphome/components/rpi_dpi_rgb/rpi_dpi_rgb.cpp
index 655b469b91..ba09171649 100644
--- a/esphome/components/rpi_dpi_rgb/rpi_dpi_rgb.cpp
+++ b/esphome/components/rpi_dpi_rgb/rpi_dpi_rgb.cpp
@@ -84,6 +84,26 @@ void RpiDpiRgb::draw_pixels_at(int x_start, int y_start, int w, int h, const uin
ESP_LOGE(TAG, "lcd_lcd_panel_draw_bitmap failed: %s", esp_err_to_name(err));
}
+int RpiDpiRgb::get_width() {
+ switch (this->rotation_) {
+ case display::DISPLAY_ROTATION_90_DEGREES:
+ case display::DISPLAY_ROTATION_270_DEGREES:
+ return this->get_height_internal();
+ default:
+ return this->get_width_internal();
+ }
+}
+
+int RpiDpiRgb::get_height() {
+ switch (this->rotation_) {
+ case display::DISPLAY_ROTATION_90_DEGREES:
+ case display::DISPLAY_ROTATION_270_DEGREES:
+ return this->get_width_internal();
+ default:
+ return this->get_height_internal();
+ }
+}
+
void RpiDpiRgb::draw_pixel_at(int x, int y, Color color) {
if (!this->get_clipping().inside(x, y))
return; // NOLINT
diff --git a/esphome/components/rpi_dpi_rgb/rpi_dpi_rgb.h b/esphome/components/rpi_dpi_rgb/rpi_dpi_rgb.h
index 10f77a2624..7525040cd1 100644
--- a/esphome/components/rpi_dpi_rgb/rpi_dpi_rgb.h
+++ b/esphome/components/rpi_dpi_rgb/rpi_dpi_rgb.h
@@ -24,6 +24,7 @@ class RpiDpiRgb : public display::Display {
void update() override { this->do_update_(); }
void setup() override;
void loop() override;
+ float get_setup_priority() const override { return setup_priority::HARDWARE; }
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;
void draw_pixel_at(int x, int y, Color color) override;
@@ -44,8 +45,8 @@ class RpiDpiRgb : public display::Display {
this->width_ = width;
this->height_ = height;
}
- int get_width() override { return this->width_; }
- int get_height() override { return this->height_; }
+ int get_width() override;
+ int get_height() override;
void set_hsync_back_porch(uint16_t hsync_back_porch) { this->hsync_back_porch_ = hsync_back_porch; }
void set_hsync_front_porch(uint16_t hsync_front_porch) { this->hsync_front_porch_ = hsync_front_porch; }
void set_hsync_pulse_width(uint16_t hsync_pulse_width) { this->hsync_pulse_width_ = hsync_pulse_width; }
From 22f30d42a668e89b64318b1d8bf6c5cde38e2b21 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 29 Oct 2024 09:05:51 +1100
Subject: [PATCH 47/74] [lvgl] Implement qrcode (#7623)
---
esphome/components/lvgl/__init__.py | 2 +
esphome/components/lvgl/widgets/qrcode.py | 54 +++++++++++++++++++++++
tests/components/lvgl/lvgl-package.yaml | 12 +++++
3 files changed, 68 insertions(+)
create mode 100644 esphome/components/lvgl/widgets/qrcode.py
diff --git a/esphome/components/lvgl/__init__.py b/esphome/components/lvgl/__init__.py
index 215fdecdb5..4a1a26cc0b 100644
--- a/esphome/components/lvgl/__init__.py
+++ b/esphome/components/lvgl/__init__.py
@@ -71,6 +71,7 @@ from .widgets.meter import meter_spec
from .widgets.msgbox import MSGBOX_SCHEMA, msgboxes_to_code
from .widgets.obj import obj_spec
from .widgets.page import add_pages, generate_page_triggers, page_spec
+from .widgets.qrcode import qr_code_spec
from .widgets.roller import roller_spec
from .widgets.slider import slider_spec
from .widgets.spinbox import spinbox_spec
@@ -109,6 +110,7 @@ for w_type in (
spinbox_spec,
keyboard_spec,
tileview_spec,
+ qr_code_spec,
):
WIDGET_TYPES[w_type.name] = w_type
diff --git a/esphome/components/lvgl/widgets/qrcode.py b/esphome/components/lvgl/widgets/qrcode.py
new file mode 100644
index 0000000000..742b538938
--- /dev/null
+++ b/esphome/components/lvgl/widgets/qrcode.py
@@ -0,0 +1,54 @@
+import esphome.codegen as cg
+import esphome.config_validation as cv
+from esphome.const import CONF_SIZE, CONF_TEXT
+from esphome.cpp_generator import MockObjClass
+
+from ..defines import CONF_MAIN, literal
+from ..lv_validation import color, color_retmapper, lv_text
+from ..lvcode import LocalVariable, lv, lv_expr
+from ..schemas import TEXT_SCHEMA
+from ..types import WidgetType, lv_obj_t
+from . import Widget
+
+CONF_QRCODE = "qrcode"
+CONF_DARK_COLOR = "dark_color"
+CONF_LIGHT_COLOR = "light_color"
+
+QRCODE_SCHEMA = TEXT_SCHEMA.extend(
+ {
+ cv.Optional(CONF_DARK_COLOR, default="black"): color,
+ cv.Optional(CONF_LIGHT_COLOR, default="white"): color,
+ cv.Required(CONF_SIZE): cv.int_,
+ }
+)
+
+
+class QrCodeType(WidgetType):
+ def __init__(self):
+ super().__init__(
+ CONF_QRCODE,
+ lv_obj_t,
+ (CONF_MAIN,),
+ QRCODE_SCHEMA,
+ modify_schema=TEXT_SCHEMA,
+ )
+
+ def get_uses(self):
+ return ("canvas", "img")
+
+ def obj_creator(self, parent: MockObjClass, config: dict):
+ dark_color = color_retmapper(config[CONF_DARK_COLOR])
+ light_color = color_retmapper(config[CONF_LIGHT_COLOR])
+ size = config[CONF_SIZE]
+ return lv_expr.call("qrcode_create", parent, size, dark_color, light_color)
+
+ async def to_code(self, w: Widget, config):
+ if (value := config.get(CONF_TEXT)) is not None:
+ value = await lv_text.process(value)
+ with LocalVariable(
+ "qr_text", cg.const_char_ptr, value, modifier=""
+ ) as str_obj:
+ lv.qrcode_update(w.obj, str_obj, literal(f"strlen({str_obj})"))
+
+
+qr_code_spec = QrCodeType()
diff --git a/tests/components/lvgl/lvgl-package.yaml b/tests/components/lvgl/lvgl-package.yaml
index 4962a71596..9bfbb5fc95 100644
--- a/tests/components/lvgl/lvgl-package.yaml
+++ b/tests/components/lvgl/lvgl-package.yaml
@@ -458,6 +458,18 @@ lvgl:
- id: page2
widgets:
+ - qrcode:
+ id: lv_qr
+ align: left_mid
+ size: 100
+ light_color: whitesmoke
+ dark_color: steelblue
+ text: esphome.io
+ on_click:
+ lvgl.qrcode.update:
+ id: lv_qr
+ text: homeassistant.io
+
- slider:
min_value: 0
max_value: 255
From 858d97ccefff68f92af1c8f722738424ff2db791 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 29 Oct 2024 09:08:29 +1100
Subject: [PATCH 48/74] [bytebuffer] Rework ByteBuffer using templates (#7638)
---
CODEOWNERS | 1 +
esphome/components/bytebuffer/__init__.py | 5 +
esphome/components/bytebuffer/bytebuffer.h | 421 ++++++++++++++++++
esphome/core/bytebuffer.cpp | 167 -------
esphome/core/bytebuffer.h | 144 ------
tests/components/bytebuffer/common.yaml | 161 +++++++
.../components/bytebuffer/test.esp32-ard.yaml | 1 +
.../bytebuffer/test.esp32-c3-ard.yaml | 1 +
.../bytebuffer/test.esp32-c3-idf.yaml | 1 +
.../components/bytebuffer/test.esp32-idf.yaml | 1 +
.../bytebuffer/test.esp8266-ard.yaml | 1 +
tests/components/bytebuffer/test.host.yaml | 1 +
.../bytebuffer/test.rp2040-ard.yaml | 1 +
13 files changed, 595 insertions(+), 311 deletions(-)
create mode 100644 esphome/components/bytebuffer/__init__.py
create mode 100644 esphome/components/bytebuffer/bytebuffer.h
delete mode 100644 esphome/core/bytebuffer.cpp
delete mode 100644 esphome/core/bytebuffer.h
create mode 100644 tests/components/bytebuffer/common.yaml
create mode 100644 tests/components/bytebuffer/test.esp32-ard.yaml
create mode 100644 tests/components/bytebuffer/test.esp32-c3-ard.yaml
create mode 100644 tests/components/bytebuffer/test.esp32-c3-idf.yaml
create mode 100644 tests/components/bytebuffer/test.esp32-idf.yaml
create mode 100644 tests/components/bytebuffer/test.esp8266-ard.yaml
create mode 100644 tests/components/bytebuffer/test.host.yaml
create mode 100644 tests/components/bytebuffer/test.rp2040-ard.yaml
diff --git a/CODEOWNERS b/CODEOWNERS
index f96e43d5b7..5eb1f863f2 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -85,6 +85,7 @@ esphome/components/bmp581/* @kahrendt
esphome/components/bp1658cj/* @Cossid
esphome/components/bp5758d/* @Cossid
esphome/components/button/* @esphome/core
+esphome/components/bytebuffer/* @clydebarrow
esphome/components/canbus/* @danielschramm @mvturnho
esphome/components/cap1188/* @mreditor97
esphome/components/captive_portal/* @OttoWinter
diff --git a/esphome/components/bytebuffer/__init__.py b/esphome/components/bytebuffer/__init__.py
new file mode 100644
index 0000000000..3c7c695118
--- /dev/null
+++ b/esphome/components/bytebuffer/__init__.py
@@ -0,0 +1,5 @@
+CODEOWNERS = ["@clydebarrow"]
+
+# Allows bytebuffer to be configured in yaml, to allow use of the C++ api.
+
+CONFIG_SCHEMA = {}
diff --git a/esphome/components/bytebuffer/bytebuffer.h b/esphome/components/bytebuffer/bytebuffer.h
new file mode 100644
index 0000000000..030484ce32
--- /dev/null
+++ b/esphome/components/bytebuffer/bytebuffer.h
@@ -0,0 +1,421 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+#include "esphome/core/helpers.h"
+
+namespace esphome {
+namespace bytebuffer {
+
+enum Endian { LITTLE, BIG };
+
+/**
+ * A class modelled on the Java ByteBuffer class. It wraps a vector of bytes and permits putting and getting
+ * items of various sizes, with an automatically incremented position.
+ *
+ * There are three variables maintained pointing into the buffer:
+ *
+ * capacity: the maximum amount of data that can be stored - set on construction and cannot be changed
+ * limit: the limit of the data currently available to get or put
+ * position: the current insert or extract position
+ *
+ * 0 <= position <= limit <= capacity
+ *
+ * In addition a mark can be set to the current position with mark(). A subsequent call to reset() will restore
+ * the position to the mark.
+ *
+ * The buffer can be marked to be little-endian (default) or big-endian. All subsequent operations will use that order.
+ *
+ * The flip() operation will reset the position to 0 and limit to the current position. This is useful for reading
+ * data from a buffer after it has been written.
+ *
+ * The code is defined here in the header file rather than in a .cpp file, so that it does not get compiled if not used.
+ * The templated functions ensure that only those typed functions actually used are compiled. The functions
+ * are implicitly inline-able which will aid performance.
+ */
+class ByteBuffer {
+ public:
+ // Default constructor (compatibility with TEMPLATABLE_VALUE)
+ // Creates a zero-length ByteBuffer which is little use to anybody.
+ ByteBuffer() : ByteBuffer(std::vector()) {}
+
+ /**
+ * Create a new Bytebuffer with the given capacity
+ */
+ ByteBuffer(size_t capacity, Endian endianness = LITTLE)
+ : data_(std::vector(capacity)), endianness_(endianness), limit_(capacity){};
+
+ // templated functions to implement putting and getting data of various types. There are two flavours of all
+ // functions - one that uses the position as the offset, and updates the position accordingly, and one that
+ // takes an explicit offset and does not update the position.
+ // Separate temnplates are provided for types that fit into 32 bits and those that are bigger. These delegate
+ // the actual put/get to common code based around those sizes.
+ // This reduces the code size and execution time for smaller types. A similar structure for e.g. 16 bits is unlikely
+ // to provide any further benefit given that all target platforms are native 32 bit.
+
+ template
+ T get(typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
+ // integral types that fit into 32 bit
+ return static_cast(this->get_uint32_(sizeof(T)));
+ }
+
+ template
+ T get(size_t offset, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
+ return static_cast(this->get_uint32_(offset, sizeof(T)));
+ }
+
+ template
+ void put(const T &value, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
+ this->put_uint32_(static_cast(value), sizeof(T));
+ }
+
+ template
+ void put(const T &value, size_t offset, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
+ this->put_uint32_(static_cast(value), offset, sizeof(T));
+ }
+
+ // integral types that do not fit into 32 bit (basically only 64 bit types)
+ template
+ T get(typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
+ return static_cast(this->get_uint64_(sizeof(T)));
+ }
+
+ template
+ T get(size_t offset, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
+ return static_cast(this->get_uint64_(offset, sizeof(T)));
+ }
+
+ template
+ void put(const T &value, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
+ this->put_uint64_(value, sizeof(T));
+ }
+
+ template
+ void put(const T &value, size_t offset, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
+ this->put_uint64_(static_cast(value), offset, sizeof(T));
+ }
+
+ // floating point types. Caters for 32 and 64 bit floating point.
+ template
+ T get(typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) == sizeof(uint32_t)), T>::type * = 0) {
+ return bit_cast(this->get_uint32_(sizeof(T)));
+ }
+
+ template
+ T get(typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
+ return bit_cast(this->get_uint64_(sizeof(T)));
+ }
+
+ template
+ T get(size_t offset, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) == sizeof(uint32_t)), T>::type * = 0) {
+ return bit_cast(this->get_uint32_(offset, sizeof(T)));
+ }
+
+ template
+ T get(size_t offset, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
+ return bit_cast(this->get_uint64_(offset, sizeof(T)));
+ }
+ template
+ void put(const T &value, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
+ this->put_uint32_(bit_cast(value), sizeof(T));
+ }
+
+ template
+ void put(const T &value, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
+ this->put_uint64_(bit_cast(value), sizeof(T));
+ }
+
+ template
+ void put(const T &value, size_t offset, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
+ this->put_uint32_(bit_cast(value), offset, sizeof(T));
+ }
+
+ template
+ void put(const T &value, size_t offset, typename std::enable_if::value, T>::type * = 0,
+ typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
+ this->put_uint64_(bit_cast(value), offset, sizeof(T));
+ }
+
+ template static ByteBuffer wrap(T value, Endian endianness = LITTLE) {
+ ByteBuffer buffer = ByteBuffer(sizeof(T), endianness);
+ buffer.put(value);
+ buffer.flip();
+ return buffer;
+ }
+
+ static ByteBuffer wrap(std::vector const &data, Endian endianness = LITTLE) {
+ ByteBuffer buffer = {data};
+ buffer.endianness_ = endianness;
+ return buffer;
+ }
+
+ static ByteBuffer wrap(const uint8_t *ptr, size_t len, Endian endianness = LITTLE) {
+ return wrap(std::vector(ptr, ptr + len), endianness);
+ }
+
+ // convenience functions with explicit types named..
+ void put_float(float value) { this->put(value); }
+ void put_double(double value) { this->put(value); }
+
+ uint8_t get_uint8() { return this->data_[this->position_++]; }
+ // Get a 16 bit unsigned value, increment by 2
+ uint16_t get_uint16() { return this->get(); }
+ // Get a 24 bit unsigned value, increment by 3
+ uint32_t get_uint24() { return this->get_uint32_(3); };
+ // Get a 32 bit unsigned value, increment by 4
+ uint32_t get_uint32() { return this->get(); };
+ // Get a 64 bit unsigned value, increment by 8
+ uint64_t get_uint64() { return this->get(); };
+ // Signed versions of the get functions
+ uint8_t get_int8() { return static_cast(this->get_uint8()); };
+ int16_t get_int16() { return this->get(); }
+ int32_t get_int32() { return this->get(); }
+ int64_t get_int64() { return this->get(); }
+ // Get a float value, increment by 4
+ float get_float() { return this->get(); }
+ // Get a double value, increment by 8
+ double get_double() { return this->get(); }
+
+ // Get a bool value, increment by 1
+ bool get_bool() { return static_cast(this->get_uint8()); }
+
+ uint32_t get_int24(size_t offset) {
+ auto value = this->get_uint24(offset);
+ uint32_t mask = (~static_cast(0)) << 23;
+ if ((value & mask) != 0)
+ value |= mask;
+ return value;
+ }
+
+ uint32_t get_int24() {
+ auto value = this->get_uint24();
+ uint32_t mask = (~static_cast(0)) << 23;
+ if ((value & mask) != 0)
+ value |= mask;
+ return value;
+ }
+ std::vector get_vector(size_t length, size_t offset) {
+ auto start = this->data_.begin() + offset;
+ return {start, start + length};
+ }
+
+ std::vector get_vector(size_t length) {
+ auto result = this->get_vector(length, this->position_);
+ this->position_ += length;
+ return result;
+ }
+
+ // Convenience named functions
+ void put_uint8(uint8_t value) { this->data_[this->position_++] = value; }
+ void put_uint16(uint16_t value) { this->put(value); }
+ void put_uint24(uint32_t value) { this->put_uint32_(value, 3); }
+ void put_uint32(uint32_t value) { this->put(value); }
+ void put_uint64(uint64_t value) { this->put(value); }
+ // Signed versions of the put functions
+ void put_int8(int8_t value) { this->put_uint8(static_cast(value)); }
+ void put_int16(int16_t value) { this->put(value); }
+ void put_int24(int32_t value) { this->put_uint32_(value, 3); }
+ void put_int32(int32_t value) { this->put(value); }
+ void put_int64(int64_t value) { this->put(value); }
+ // Extra put functions
+ void put_bool(bool value) { this->put_uint8(value); }
+
+ // versions of the above with an offset, these do not update the position
+
+ uint64_t get_uint64(size_t offset) { return this->get(offset); }
+ uint32_t get_uint24(size_t offset) { return this->get_uint32_(offset, 3); };
+ double get_double(size_t offset) { return get(offset); }
+
+ // Get one byte from the buffer, increment position by 1
+ uint8_t get_uint8(size_t offset) { return this->data_[offset]; }
+ // Get a 16 bit unsigned value, increment by 2
+ uint16_t get_uint16(size_t offset) { return get(offset); }
+ // Get a 24 bit unsigned value, increment by 3
+ uint32_t get_uint32(size_t offset) { return this->get(offset); };
+ // Get a 64 bit unsigned value, increment by 8
+ uint8_t get_int8(size_t offset) { return get(offset); }
+ int16_t get_int16(size_t offset) { return get(offset); }
+ int32_t get_int32(size_t offset) { return get(offset); }
+ int64_t get_int64(size_t offset) { return get(offset); }
+ // Get a float value, increment by 4
+ float get_float(size_t offset) { return get(offset); }
+ // Get a double value, increment by 8
+
+ // Get a bool value, increment by 1
+ bool get_bool(size_t offset) { return this->get_uint8(offset); }
+
+ void put_uint8(uint8_t value, size_t offset) { this->data_[offset] = value; }
+ void put_uint16(uint16_t value, size_t offset) { this->put(value, offset); }
+ void put_uint24(uint32_t value, size_t offset) { this->put(value, offset); }
+ void put_uint32(uint32_t value, size_t offset) { this->put(value, offset); }
+ void put_uint64(uint64_t value, size_t offset) { this->put(value, offset); }
+ // Signed versions of the put functions
+ void put_int8(int8_t value, size_t offset) { this->put_uint8(static_cast(value), offset); }
+ void put_int16(int16_t value, size_t offset) { this->put(value, offset); }
+ void put_int24(int32_t value, size_t offset) { this->put_uint32_(value, offset, 3); }
+ void put_int32(int32_t value, size_t offset) { this->put(value, offset); }
+ void put_int64(int64_t value, size_t offset) { this->put(value, offset); }
+ // Extra put functions
+ void put_float(float value, size_t offset) { this->put(value, offset); }
+ void put_double(double value, size_t offset) { this->put(value, offset); }
+ void put_bool(bool value, size_t offset) { this->put_uint8(value, offset); }
+ void put(const std::vector &value, size_t offset) {
+ std::copy(value.begin(), value.end(), this->data_.begin() + offset);
+ }
+ void put_vector(const std::vector &value, size_t offset) { this->put(value, offset); }
+ void put(const std::vector &value) {
+ this->put_vector(value, this->position_);
+ this->position_ += value.size();
+ }
+ void put_vector(const std::vector &value) { this->put(value); }
+
+ // Getters
+
+ inline size_t get_capacity() const { return this->data_.size(); }
+ inline size_t get_position() const { return this->position_; }
+ inline size_t get_limit() const { return this->limit_; }
+ inline size_t get_remaining() const { return this->get_limit() - this->get_position(); }
+ inline Endian get_endianness() const { return this->endianness_; }
+ inline void mark() { this->mark_ = this->position_; }
+ inline void big_endian() { this->endianness_ = BIG; }
+ inline void little_endian() { this->endianness_ = LITTLE; }
+ // retrieve a pointer to the underlying data.
+ std::vector get_data() { return this->data_; };
+
+ void get_bytes(void *dest, size_t length) {
+ std::copy(this->data_.begin() + this->position_, this->data_.begin() + this->position_ + length, (uint8_t *) dest);
+ this->position_ += length;
+ }
+
+ void get_bytes(void *dest, size_t length, size_t offset) {
+ std::copy(this->data_.begin() + offset, this->data_.begin() + offset + length, (uint8_t *) dest);
+ }
+
+ void rewind() { this->position_ = 0; }
+ void reset() { this->position_ = this->mark_; }
+
+ void set_limit(size_t limit) { this->limit_ = limit; }
+ void set_position(size_t position) { this->position_ = position; }
+ void clear() {
+ this->limit_ = this->get_capacity();
+ this->position_ = 0;
+ }
+ void flip() {
+ this->limit_ = this->position_;
+ this->position_ = 0;
+ }
+
+ protected:
+ uint64_t get_uint64_(size_t offset, size_t length) const {
+ uint64_t value = 0;
+ if (this->endianness_ == LITTLE) {
+ offset += length;
+ while (length-- != 0) {
+ value <<= 8;
+ value |= this->data_[--offset];
+ }
+ } else {
+ while (length-- != 0) {
+ value <<= 8;
+ value |= this->data_[offset++];
+ }
+ }
+ return value;
+ }
+
+ uint64_t get_uint64_(size_t length) {
+ auto result = this->get_uint64_(this->position_, length);
+ this->position_ += length;
+ return result;
+ }
+ uint32_t get_uint32_(size_t offset, size_t length) const {
+ uint32_t value = 0;
+ if (this->endianness_ == LITTLE) {
+ offset += length;
+ while (length-- != 0) {
+ value <<= 8;
+ value |= this->data_[--offset];
+ }
+ } else {
+ while (length-- != 0) {
+ value <<= 8;
+ value |= this->data_[offset++];
+ }
+ }
+ return value;
+ }
+
+ uint32_t get_uint32_(size_t length) {
+ auto result = this->get_uint32_(this->position_, length);
+ this->position_ += length;
+ return result;
+ }
+
+ /// Putters
+
+ void put_uint64_(uint64_t value, size_t length) {
+ this->put_uint64_(value, this->position_, length);
+ this->position_ += length;
+ }
+ void put_uint32_(uint32_t value, size_t length) {
+ this->put_uint32_(value, this->position_, length);
+ this->position_ += length;
+ }
+
+ void put_uint64_(uint64_t value, size_t offset, size_t length) {
+ if (this->endianness_ == LITTLE) {
+ while (length-- != 0) {
+ this->data_[offset++] = static_cast(value);
+ value >>= 8;
+ }
+ } else {
+ offset += length;
+ while (length-- != 0) {
+ this->data_[--offset] = static_cast(value);
+ value >>= 8;
+ }
+ }
+ }
+
+ void put_uint32_(uint32_t value, size_t offset, size_t length) {
+ if (this->endianness_ == LITTLE) {
+ while (length-- != 0) {
+ this->data_[offset++] = static_cast(value);
+ value >>= 8;
+ }
+ } else {
+ offset += length;
+ while (length-- != 0) {
+ this->data_[--offset] = static_cast(value);
+ value >>= 8;
+ }
+ }
+ }
+ ByteBuffer(std::vector const &data) : data_(data), limit_(data.size()) {}
+
+ std::vector data_;
+ Endian endianness_{LITTLE};
+ size_t position_{0};
+ size_t mark_{0};
+ size_t limit_{0};
+};
+
+} // namespace bytebuffer
+} // namespace esphome
diff --git a/esphome/core/bytebuffer.cpp b/esphome/core/bytebuffer.cpp
deleted file mode 100644
index 9dd32bf87a..0000000000
--- a/esphome/core/bytebuffer.cpp
+++ /dev/null
@@ -1,167 +0,0 @@
-#include "bytebuffer.h"
-#include
-#include "esphome/core/helpers.h"
-
-#include
-#include
-
-namespace esphome {
-
-ByteBuffer ByteBuffer::wrap(const uint8_t *ptr, size_t len, Endian endianness) {
- // there is a double copy happening here, could be optimized but at cost of clarity.
- std::vector data(ptr, ptr + len);
- ByteBuffer buffer = {data};
- buffer.endianness_ = endianness;
- return buffer;
-}
-
-ByteBuffer ByteBuffer::wrap(std::vector const &data, Endian endianness) {
- ByteBuffer buffer = {data};
- buffer.endianness_ = endianness;
- return buffer;
-}
-
-ByteBuffer ByteBuffer::wrap(uint8_t value) {
- ByteBuffer buffer = ByteBuffer(1);
- buffer.put_uint8(value);
- buffer.flip();
- return buffer;
-}
-
-ByteBuffer ByteBuffer::wrap(uint16_t value, Endian endianness) {
- ByteBuffer buffer = ByteBuffer(2, endianness);
- buffer.put_uint16(value);
- buffer.flip();
- return buffer;
-}
-
-ByteBuffer ByteBuffer::wrap(uint32_t value, Endian endianness) {
- ByteBuffer buffer = ByteBuffer(4, endianness);
- buffer.put_uint32(value);
- buffer.flip();
- return buffer;
-}
-
-ByteBuffer ByteBuffer::wrap(uint64_t value, Endian endianness) {
- ByteBuffer buffer = ByteBuffer(8, endianness);
- buffer.put_uint64(value);
- buffer.flip();
- return buffer;
-}
-
-ByteBuffer ByteBuffer::wrap(float value, Endian endianness) {
- ByteBuffer buffer = ByteBuffer(sizeof(float), endianness);
- buffer.put_float(value);
- buffer.flip();
- return buffer;
-}
-
-ByteBuffer ByteBuffer::wrap(double value, Endian endianness) {
- ByteBuffer buffer = ByteBuffer(sizeof(double), endianness);
- buffer.put_double(value);
- buffer.flip();
- return buffer;
-}
-
-void ByteBuffer::set_limit(size_t limit) {
- assert(limit <= this->get_capacity());
- this->limit_ = limit;
-}
-void ByteBuffer::set_position(size_t position) {
- assert(position <= this->get_limit());
- this->position_ = position;
-}
-void ByteBuffer::clear() {
- this->limit_ = this->get_capacity();
- this->position_ = 0;
-}
-void ByteBuffer::flip() {
- this->limit_ = this->position_;
- this->position_ = 0;
-}
-
-/// Getters
-uint8_t ByteBuffer::get_uint8() {
- assert(this->get_remaining() >= 1);
- return this->data_[this->position_++];
-}
-uint64_t ByteBuffer::get_uint(size_t length) {
- assert(this->get_remaining() >= length);
- uint64_t value = 0;
- if (this->endianness_ == LITTLE) {
- this->position_ += length;
- auto index = this->position_;
- while (length-- != 0) {
- value <<= 8;
- value |= this->data_[--index];
- }
- } else {
- while (length-- != 0) {
- value <<= 8;
- value |= this->data_[this->position_++];
- }
- }
- return value;
-}
-
-uint32_t ByteBuffer::get_int24() {
- auto value = this->get_uint24();
- uint32_t mask = (~static_cast(0)) << 23;
- if ((value & mask) != 0)
- value |= mask;
- return value;
-}
-float ByteBuffer::get_float() {
- assert(this->get_remaining() >= sizeof(float));
- return bit_cast(this->get_uint32());
-}
-double ByteBuffer::get_double() {
- assert(this->get_remaining() >= sizeof(double));
- return bit_cast(this->get_uint64());
-}
-
-std::vector ByteBuffer::get_vector(size_t length) {
- assert(this->get_remaining() >= length);
- auto start = this->data_.begin() + this->position_;
- this->position_ += length;
- return {start, start + length};
-}
-
-/// Putters
-void ByteBuffer::put_uint8(uint8_t value) {
- assert(this->get_remaining() >= 1);
- this->data_[this->position_++] = value;
-}
-
-void ByteBuffer::put_uint(uint64_t value, size_t length) {
- assert(this->get_remaining() >= length);
- if (this->endianness_ == LITTLE) {
- while (length-- != 0) {
- this->data_[this->position_++] = static_cast(value);
- value >>= 8;
- }
- } else {
- this->position_ += length;
- auto index = this->position_;
- while (length-- != 0) {
- this->data_[--index] = static_cast(value);
- value >>= 8;
- }
- }
-}
-void ByteBuffer::put_float(float value) {
- static_assert(sizeof(float) == sizeof(uint32_t), "Float sizes other than 32 bit not supported");
- assert(this->get_remaining() >= sizeof(float));
- this->put_uint32(bit_cast(value));
-}
-void ByteBuffer::put_double(double value) {
- static_assert(sizeof(double) == sizeof(uint64_t), "Double sizes other than 64 bit not supported");
- assert(this->get_remaining() >= sizeof(double));
- this->put_uint64(bit_cast(value));
-}
-void ByteBuffer::put_vector(const std::vector &value) {
- assert(this->get_remaining() >= value.size());
- std::copy(value.begin(), value.end(), this->data_.begin() + this->position_);
- this->position_ += value.size();
-}
-} // namespace esphome
diff --git a/esphome/core/bytebuffer.h b/esphome/core/bytebuffer.h
deleted file mode 100644
index d44d01f275..0000000000
--- a/esphome/core/bytebuffer.h
+++ /dev/null
@@ -1,144 +0,0 @@
-#pragma once
-
-#include
-#include
-#include
-#include
-
-namespace esphome {
-
-enum Endian { LITTLE, BIG };
-
-/**
- * A class modelled on the Java ByteBuffer class. It wraps a vector of bytes and permits putting and getting
- * items of various sizes, with an automatically incremented position.
- *
- * There are three variables maintained pointing into the buffer:
- *
- * capacity: the maximum amount of data that can be stored - set on construction and cannot be changed
- * limit: the limit of the data currently available to get or put
- * position: the current insert or extract position
- *
- * 0 <= position <= limit <= capacity
- *
- * In addition a mark can be set to the current position with mark(). A subsequent call to reset() will restore
- * the position to the mark.
- *
- * The buffer can be marked to be little-endian (default) or big-endian. All subsequent operations will use that order.
- *
- * The flip() operation will reset the position to 0 and limit to the current position. This is useful for reading
- * data from a buffer after it has been written.
- *
- */
-class ByteBuffer {
- public:
- // Default constructor (compatibility with TEMPLATABLE_VALUE)
- ByteBuffer() : ByteBuffer(std::vector()) {}
- /**
- * Create a new Bytebuffer with the given capacity
- */
- ByteBuffer(size_t capacity, Endian endianness = LITTLE)
- : data_(std::vector(capacity)), endianness_(endianness), limit_(capacity){};
- /**
- * Wrap an existing vector in a ByteBufffer
- */
- static ByteBuffer wrap(std::vector const &data, Endian endianness = LITTLE);
- /**
- * Wrap an existing array in a ByteBuffer. Note that this will create a copy of the data.
- */
- static ByteBuffer wrap(const uint8_t *ptr, size_t len, Endian endianness = LITTLE);
- // Convenience functions to create a ByteBuffer from a value
- static ByteBuffer wrap(uint8_t value);
- static ByteBuffer wrap(uint16_t value, Endian endianness = LITTLE);
- static ByteBuffer wrap(uint32_t value, Endian endianness = LITTLE);
- static ByteBuffer wrap(uint64_t value, Endian endianness = LITTLE);
- static ByteBuffer wrap(int8_t value) { return wrap(static_cast(value)); }
- static ByteBuffer wrap(int16_t value, Endian endianness = LITTLE) {
- return wrap(static_cast(value), endianness);
- }
- static ByteBuffer wrap(int32_t value, Endian endianness = LITTLE) {
- return wrap(static_cast(value), endianness);
- }
- static ByteBuffer wrap(int64_t value, Endian endianness = LITTLE) {
- return wrap(static_cast(value), endianness);
- }
- static ByteBuffer wrap(float value, Endian endianness = LITTLE);
- static ByteBuffer wrap(double value, Endian endianness = LITTLE);
- static ByteBuffer wrap(bool value) { return wrap(static_cast(value)); }
-
- // Get an integral value from the buffer, increment position by length
- uint64_t get_uint(size_t length);
- // Get one byte from the buffer, increment position by 1
- uint8_t get_uint8();
- // Get a 16 bit unsigned value, increment by 2
- uint16_t get_uint16() { return static_cast(this->get_uint(sizeof(uint16_t))); };
- // Get a 24 bit unsigned value, increment by 3
- uint32_t get_uint24() { return static_cast(this->get_uint(3)); };
- // Get a 32 bit unsigned value, increment by 4
- uint32_t get_uint32() { return static_cast(this->get_uint(sizeof(uint32_t))); };
- // Get a 64 bit unsigned value, increment by 8
- uint64_t get_uint64() { return this->get_uint(sizeof(uint64_t)); };
- // Signed versions of the get functions
- uint8_t get_int8() { return static_cast(this->get_uint8()); };
- int16_t get_int16() { return static_cast(this->get_uint(sizeof(int16_t))); }
- uint32_t get_int24();
- int32_t get_int32() { return static_cast(this->get_uint(sizeof(int32_t))); }
- int64_t get_int64() { return static_cast(this->get_uint(sizeof(int64_t))); }
- // Get a float value, increment by 4
- float get_float();
- // Get a double value, increment by 8
- double get_double();
- // Get a bool value, increment by 1
- bool get_bool() { return this->get_uint8(); }
- // Get vector of bytes, increment by length
- std::vector get_vector(size_t length);
-
- // Put values into the buffer, increment the position accordingly
- // put any integral value, length represents the number of bytes
- void put_uint(uint64_t value, size_t length);
- void put_uint8(uint8_t value);
- void put_uint16(uint16_t value) { this->put_uint(value, sizeof(uint16_t)); }
- void put_uint24(uint32_t value) { this->put_uint(value, 3); }
- void put_uint32(uint32_t value) { this->put_uint(value, sizeof(uint32_t)); }
- void put_uint64(uint64_t value) { this->put_uint(value, sizeof(uint64_t)); }
- // Signed versions of the put functions
- void put_int8(int8_t value) { this->put_uint8(static_cast(value)); }
- void put_int16(int32_t value) { this->put_uint(static_cast(value), sizeof(uint16_t)); }
- void put_int24(int32_t value) { this->put_uint(static_cast(value), 3); }
- void put_int32(int32_t value) { this->put_uint(static_cast(value), sizeof(uint32_t)); }
- void put_int64(int64_t value) { this->put_uint(static_cast(value), sizeof(uint64_t)); }
- // Extra put functions
- void put_float(float value);
- void put_double(double value);
- void put_bool(bool value) { this->put_uint8(value); }
- void put_vector(const std::vector &value);
-
- inline size_t get_capacity() const { return this->data_.size(); }
- inline size_t get_position() const { return this->position_; }
- inline size_t get_limit() const { return this->limit_; }
- inline size_t get_remaining() const { return this->get_limit() - this->get_position(); }
- inline Endian get_endianness() const { return this->endianness_; }
- inline void mark() { this->mark_ = this->position_; }
- inline void big_endian() { this->endianness_ = BIG; }
- inline void little_endian() { this->endianness_ = LITTLE; }
- void set_limit(size_t limit);
- void set_position(size_t position);
- // set position to 0, limit to capacity.
- void clear();
- // set limit to current position, postition to zero. Used when swapping from write to read operations.
- void flip();
- // retrieve a pointer to the underlying data.
- std::vector get_data() { return this->data_; };
- void rewind() { this->position_ = 0; }
- void reset() { this->position_ = this->mark_; }
-
- protected:
- ByteBuffer(std::vector const &data) : data_(data), limit_(data.size()) {}
- std::vector data_;
- Endian endianness_{LITTLE};
- size_t position_{0};
- size_t mark_{0};
- size_t limit_{0};
-};
-
-} // namespace esphome
diff --git a/tests/components/bytebuffer/common.yaml b/tests/components/bytebuffer/common.yaml
new file mode 100644
index 0000000000..177f487e1e
--- /dev/null
+++ b/tests/components/bytebuffer/common.yaml
@@ -0,0 +1,161 @@
+bytebuffer:
+
+esphome:
+ on_boot:
+ - lambda: |-
+ using namespace bytebuffer;
+ auto buf = ByteBuffer(16);
+ assert(buf.get_endianness() == LITTLE);
+ assert(buf.get_remaining() == 16);
+ buf.set_limit(10);
+ assert(buf.get_capacity() == 16);
+ buf.put_uint8(1);
+ assert(buf.get_remaining() == 9);
+ buf.put_uint16(0xABCD);
+ auto da = buf.get_data();
+ assert(buf.get_uint8(0) == 1);
+ auto x = buf.get_uint16(1);
+ assert(buf.get_uint16(1) == 0xABCD);
+ assert(buf.get_remaining() == 7);
+ buf.put_uint32(0x12345678UL);
+ assert(buf.get_uint32(3) == 0x12345678UL);
+ assert(buf.get_remaining() == 3);
+ assert(buf.get_data()[1] == 0xCD);
+ assert(buf.get_data()[2] == 0xAB);
+ assert(buf.get_data()[3] == 0x78);
+ assert(buf.get_data()[4] == 0x56);
+ assert(buf.get_data()[5] == 0x34);
+ assert(buf.get_data()[6] == 0x12);
+ buf.flip();
+ assert(buf.get_capacity() == 16);
+ assert(buf.get_uint32(3) == 0x12345678UL);
+ assert(buf.get_uint8(0) == 1);
+ assert(buf.get_uint16(1) == 0xABCD);
+ buf.put_uint16(0x1234, 1);
+ assert(buf.get_uint16(1) == 0x1234);
+ assert(buf.get_remaining() == 7);
+ assert(buf.get_uint8() == 1);
+ assert(buf.get_uint16() == 0x1234);
+ assert(buf.get_uint32() == 0x12345678ul);
+ assert(buf.get_remaining() == 0);
+ assert(buf.get_remaining() == 0);
+ buf.rewind();
+ buf.big_endian();
+ assert(buf.get_remaining() == 7);
+ assert(buf.get_uint8() == 1);
+ assert(buf.get_uint16() == 0x3412);
+ buf.mark();
+ assert(buf.get_uint32() == 0x78563412ul);
+ assert(buf.get_remaining() == 0);
+ buf.reset();
+ assert(buf.get_remaining() == 4);
+ assert(buf.get_uint32() == 0x78563412ul);
+ auto buf1 = ByteBuffer::wrap(buf.get_data().data(), buf.get_limit());
+ buf.clear();
+ assert(buf.get_position() == 0);
+ assert(buf.get_capacity() == 16);
+ assert(buf.get_limit() == 16);
+ assert(buf1.get_remaining() == 7);
+ assert(buf1.get_capacity() == 7);
+ buf1.set_position(3);
+ assert(buf1.get_uint32() == 0x12345678ul);
+ buf1.clear();
+ assert(buf1.get_limit() == 7);
+ assert(buf1.get_capacity() == 7);
+ assert(buf1.get_position() == 0);
+ float f = 1.2345;
+ buf1.put_float(f);
+ buf1.flip();
+ assert(buf1.get_remaining() == 4);
+ assert(buf1.get_float() == f);
+ buf1.clear();
+ buf1.put_uint16(-32760);
+ buf1.put_uint24(-302760);
+ buf1.flip();
+ assert(buf1.get_int16() == -32760);
+ assert(buf1.get_int24() == -302760);
+ uint8_t arr[4] = {0x10, 0x20, 0x30, 0x40};
+ buf1 = ByteBuffer::wrap(arr, 4);
+ assert(buf1.get_capacity() == 4);
+ assert(buf1.get_limit() == 4);
+ assert(buf1.get_position() == 0);
+ assert(buf1.get_uint32() == 0x40302010UL);
+ assert(buf1.get_position() == 4);
+ assert(buf1.get_remaining() == 0);
+ std::vector vec{};
+ vec.push_back(0x10);
+ vec.push_back(0x20);
+ vec.push_back(0x30);
+ vec.push_back(0x40);
+ buf1 = ByteBuffer::wrap(vec);
+ assert(buf1.get_capacity() == 4);
+ assert(buf1.get_limit() == 4);
+ assert(buf1.get_position() == 0);
+ buf1.mark();
+ buf1.reset();
+ assert(buf1.get_uint32() == 0x40302010UL);
+ buf = ByteBuffer::wrap(true);
+ assert(buf.get_bool() == true);
+ buf = ByteBuffer::wrap((uint8_t)0xFE);
+ assert(buf.get_uint8() == 0xFE);
+ buf = ByteBuffer::wrap((uint16_t)0xA5A6, BIG);
+ assert(buf.get_remaining() == 2);
+ assert(buf.get_position() == 0);
+ assert(buf.get_capacity() == 2);
+ assert(buf.get_endianness() == BIG);
+ assert(buf.get_data()[0] == 0xA5);
+ assert(buf.get_uint16() == 0xA5A6);
+ buf.flip();
+ buf.little_endian();
+ assert(buf.get_uint16() == 0xA6A5);
+ buf = ByteBuffer::wrap(f, BIG);
+ assert(buf.get_float() == f);
+ double d = 1.2345678E7;
+ buf = ByteBuffer::wrap(d, BIG);
+ assert(buf.get_double() == d);
+ buf = ByteBuffer::wrap({1, 2, 3, 4}, BIG);
+ assert(buf.get_endianness() == BIG);
+ assert(buf.get_remaining() == 4);
+ assert(buf.get_data()[2] == 3);
+ buf.little_endian();
+ assert(buf.get_data()[2] == 3);
+ assert(buf.get_uint16() == 0x0201);
+ buf.big_endian();
+ assert(buf.get_uint16() == 0x0304);
+ buf.rewind();
+ vec = buf.get_vector(3);
+ assert(buf.get_remaining() == 1);
+ assert(vec[0] == 1);
+ assert(vec.size() == 3);
+ buf = ByteBuffer(10);
+ buf.put_vector(vec);
+ assert(buf.get_remaining() == 7);
+ buf.flip();
+ assert(buf.get_remaining() == 3);
+ assert(buf.get_uint24() == 0x030201);
+ buf = ByteBuffer(64);
+ buf.put_uint8(1, 1);
+ buf.put_uint16(16, 2);
+ buf.put_uint32(1232, 4);
+ buf.put_uint64(123432ul, 8);
+ buf.put_float(1.2f, 16);
+ buf.put_int24(0x678, 20);
+
+ assert(buf.get_uint8(1) == 1);
+ assert(buf.get(1) == 1);
+ assert(buf.get_uint16(2) == 16);
+ assert(buf.get(2) == 16);
+ assert(buf.get_uint32(4) == 1232);
+ assert(buf.get(4) == 1232);
+ assert(buf.get_uint64(8) == 123432ul);
+ assert(buf.get(8) == 123432ul);
+ assert(buf.get_float(16) == 1.2f);
+ assert(buf.get(16) == 1.2f);
+ assert(buf.get_int24(20) == 0x678);
+ buf.clear();
+ buf.put(1.234, 10);
+ double dx = buf.get(10);
+ assert(dx == 1.234);
+ buf.put((uint16_t)1, 10);
+ assert(buf.get_uint16(10) == 1);
+ ESP_LOGD("bytebuffer", "******************** All tests succeeded");
diff --git a/tests/components/bytebuffer/test.esp32-ard.yaml b/tests/components/bytebuffer/test.esp32-ard.yaml
new file mode 100644
index 0000000000..380ca87628
--- /dev/null
+++ b/tests/components/bytebuffer/test.esp32-ard.yaml
@@ -0,0 +1 @@
+!include common.yaml
diff --git a/tests/components/bytebuffer/test.esp32-c3-ard.yaml b/tests/components/bytebuffer/test.esp32-c3-ard.yaml
new file mode 100644
index 0000000000..380ca87628
--- /dev/null
+++ b/tests/components/bytebuffer/test.esp32-c3-ard.yaml
@@ -0,0 +1 @@
+!include common.yaml
diff --git a/tests/components/bytebuffer/test.esp32-c3-idf.yaml b/tests/components/bytebuffer/test.esp32-c3-idf.yaml
new file mode 100644
index 0000000000..380ca87628
--- /dev/null
+++ b/tests/components/bytebuffer/test.esp32-c3-idf.yaml
@@ -0,0 +1 @@
+!include common.yaml
diff --git a/tests/components/bytebuffer/test.esp32-idf.yaml b/tests/components/bytebuffer/test.esp32-idf.yaml
new file mode 100644
index 0000000000..380ca87628
--- /dev/null
+++ b/tests/components/bytebuffer/test.esp32-idf.yaml
@@ -0,0 +1 @@
+!include common.yaml
diff --git a/tests/components/bytebuffer/test.esp8266-ard.yaml b/tests/components/bytebuffer/test.esp8266-ard.yaml
new file mode 100644
index 0000000000..380ca87628
--- /dev/null
+++ b/tests/components/bytebuffer/test.esp8266-ard.yaml
@@ -0,0 +1 @@
+!include common.yaml
diff --git a/tests/components/bytebuffer/test.host.yaml b/tests/components/bytebuffer/test.host.yaml
new file mode 100644
index 0000000000..380ca87628
--- /dev/null
+++ b/tests/components/bytebuffer/test.host.yaml
@@ -0,0 +1 @@
+!include common.yaml
diff --git a/tests/components/bytebuffer/test.rp2040-ard.yaml b/tests/components/bytebuffer/test.rp2040-ard.yaml
new file mode 100644
index 0000000000..380ca87628
--- /dev/null
+++ b/tests/components/bytebuffer/test.rp2040-ard.yaml
@@ -0,0 +1 @@
+!include common.yaml
From 88627095fbc049ca342325be22d72e66e9b9c28a Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 29 Oct 2024 11:12:32 +1100
Subject: [PATCH 49/74] [http_request] Always return defined server response
status (#7689)
---
esphome/components/http_request/http_request_arduino.cpp | 3 +--
esphome/components/http_request/http_request_idf.cpp | 3 +--
esphome/components/http_request/ota/ota_http_request.cpp | 2 +-
esphome/components/http_request/update/http_request_update.cpp | 2 +-
4 files changed, 4 insertions(+), 6 deletions(-)
diff --git a/esphome/components/http_request/http_request_arduino.cpp b/esphome/components/http_request/http_request_arduino.cpp
index 2148d92ad2..f000082034 100644
--- a/esphome/components/http_request/http_request_arduino.cpp
+++ b/esphome/components/http_request/http_request_arduino.cpp
@@ -116,8 +116,7 @@ std::shared_ptr HttpRequestArduino::start(std::string url, std::s
if (container->status_code < 200 || container->status_code >= 300) {
ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code);
this->status_momentary_error("failed", 1000);
- container->end();
- return nullptr;
+ // Still return the container, so it can be used to get the status code and error message
}
int content_length = container->client_.getSize();
diff --git a/esphome/components/http_request/http_request_idf.cpp b/esphome/components/http_request/http_request_idf.cpp
index 3819f5544e..e47e1d488e 100644
--- a/esphome/components/http_request/http_request_idf.cpp
+++ b/esphome/components/http_request/http_request_idf.cpp
@@ -172,8 +172,7 @@ std::shared_ptr HttpRequestIDF::start(std::string url, std::strin
ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code);
this->status_momentary_error("failed", 1000);
- esp_http_client_cleanup(client);
- return nullptr;
+ return container;
}
int HttpContainerIDF::read(uint8_t *buf, size_t max_len) {
diff --git a/esphome/components/http_request/ota/ota_http_request.cpp b/esphome/components/http_request/ota/ota_http_request.cpp
index 1553de0bc1..f7c941da18 100644
--- a/esphome/components/http_request/ota/ota_http_request.cpp
+++ b/esphome/components/http_request/ota/ota_http_request.cpp
@@ -106,7 +106,7 @@ uint8_t OtaHttpRequestComponent::do_ota_() {
auto container = this->parent_->get(url_with_auth);
- if (container == nullptr) {
+ if (container == nullptr || container->status_code != 200) {
return OTA_CONNECTION_ERROR;
}
diff --git a/esphome/components/http_request/update/http_request_update.cpp b/esphome/components/http_request/update/http_request_update.cpp
index 059148e7e5..4d913f2158 100644
--- a/esphome/components/http_request/update/http_request_update.cpp
+++ b/esphome/components/http_request/update/http_request_update.cpp
@@ -31,7 +31,7 @@ void HttpRequestUpdate::setup() {
void HttpRequestUpdate::update() {
auto container = this->request_parent_->get(this->source_url_);
- if (container == nullptr) {
+ if (container == nullptr || container->status_code != 200) {
std::string msg = str_sprintf("Failed to fetch manifest from %s", this->source_url_.c_str());
this->status_set_error(msg.c_str());
return;
From 63e4d4b493ec6c704ac6d41273b4190614726578 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 29 Oct 2024 13:56:32 +1100
Subject: [PATCH 50/74] [font] Fix failure with bitmap fonts (#7691)
---
esphome/components/font/__init__.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/esphome/components/font/__init__.py b/esphome/components/font/__init__.py
index dacd0779b1..a3f11df50e 100644
--- a/esphome/components/font/__init__.py
+++ b/esphome/components/font/__init__.py
@@ -344,7 +344,7 @@ class TrueTypeFontWrapper:
return offset_x, offset_y
def getmask(self, glyph, **kwargs):
- return self.font.getmask(glyph, **kwargs)
+ return self.font.getmask(str(glyph), **kwargs)
def getmetrics(self, glyphs):
return self.font.getmetrics()
@@ -359,7 +359,7 @@ class BitmapFontWrapper:
return 0, 0
def getmask(self, glyph, **kwargs):
- return self.font.getmask(glyph, **kwargs)
+ return self.font.getmask(str(glyph), **kwargs)
def getmetrics(self, glyphs):
max_height = 0
From df750d0d11ce31e793de06d0e00663c8e23a3680 Mon Sep 17 00:00:00 2001
From: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
Date: Tue, 29 Oct 2024 14:05:58 +1100
Subject: [PATCH 51/74] [http_request] Add enum for status codes (#7690)
---
.../components/http_request/http_request.h | 57 +++++++++++++++++++
.../http_request/http_request_arduino.cpp | 2 +-
.../http_request/http_request_idf.cpp | 17 ++----
.../http_request/ota/ota_http_request.cpp | 2 +-
.../update/http_request_update.cpp | 2 +-
5 files changed, 65 insertions(+), 15 deletions(-)
diff --git a/esphome/components/http_request/http_request.h b/esphome/components/http_request/http_request.h
index c01baf8644..d87d9b8a45 100644
--- a/esphome/components/http_request/http_request.h
+++ b/esphome/components/http_request/http_request.h
@@ -22,6 +22,63 @@ struct Header {
const char *value;
};
+// Some common HTTP status codes
+enum HttpStatus {
+ HTTP_STATUS_OK = 200,
+ HTTP_STATUS_NO_CONTENT = 204,
+ HTTP_STATUS_PARTIAL_CONTENT = 206,
+
+ /* 3xx - Redirection */
+ HTTP_STATUS_MULTIPLE_CHOICES = 300,
+ HTTP_STATUS_MOVED_PERMANENTLY = 301,
+ HTTP_STATUS_FOUND = 302,
+ HTTP_STATUS_SEE_OTHER = 303,
+ HTTP_STATUS_NOT_MODIFIED = 304,
+ HTTP_STATUS_TEMPORARY_REDIRECT = 307,
+ HTTP_STATUS_PERMANENT_REDIRECT = 308,
+
+ /* 4XX - CLIENT ERROR */
+ HTTP_STATUS_BAD_REQUEST = 400,
+ HTTP_STATUS_UNAUTHORIZED = 401,
+ HTTP_STATUS_FORBIDDEN = 403,
+ HTTP_STATUS_NOT_FOUND = 404,
+ HTTP_STATUS_METHOD_NOT_ALLOWED = 405,
+ HTTP_STATUS_NOT_ACCEPTABLE = 406,
+ HTTP_STATUS_LENGTH_REQUIRED = 411,
+
+ /* 5xx - Server Error */
+ HTTP_STATUS_INTERNAL_ERROR = 500
+};
+
+/**
+ * @brief Returns true if the HTTP status code is a redirect.
+ *
+ * @param status the HTTP status code to check
+ * @return true if the status code is a redirect, false otherwise
+ */
+inline bool is_redirect(int const status) {
+ switch (status) {
+ case HTTP_STATUS_MOVED_PERMANENTLY:
+ case HTTP_STATUS_FOUND:
+ case HTTP_STATUS_SEE_OTHER:
+ case HTTP_STATUS_TEMPORARY_REDIRECT:
+ case HTTP_STATUS_PERMANENT_REDIRECT:
+ return true;
+ default:
+ return false;
+ }
+}
+
+/**
+ * @brief Checks if the given HTTP status code indicates a successful request.
+ *
+ * A successful request is one where the status code is in the range 200-299
+ *
+ * @param status the HTTP status code to check
+ * @return true if the status code indicates a successful request, false otherwise
+ */
+inline bool is_success(int const status) { return status >= HTTP_STATUS_OK && status < HTTP_STATUS_MULTIPLE_CHOICES; }
+
class HttpRequestComponent;
class HttpContainer : public Parented {
diff --git a/esphome/components/http_request/http_request_arduino.cpp b/esphome/components/http_request/http_request_arduino.cpp
index f000082034..af1eb6f459 100644
--- a/esphome/components/http_request/http_request_arduino.cpp
+++ b/esphome/components/http_request/http_request_arduino.cpp
@@ -113,7 +113,7 @@ std::shared_ptr HttpRequestArduino::start(std::string url, std::s
return nullptr;
}
- if (container->status_code < 200 || container->status_code >= 300) {
+ if (!is_success(container->status_code)) {
ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code);
this->status_momentary_error("failed", 1000);
// Still return the container, so it can be used to get the status code and error message
diff --git a/esphome/components/http_request/http_request_idf.cpp b/esphome/components/http_request/http_request_idf.cpp
index e47e1d488e..c6c567b620 100644
--- a/esphome/components/http_request/http_request_idf.cpp
+++ b/esphome/components/http_request/http_request_idf.cpp
@@ -6,7 +6,6 @@
#include "esphome/components/watchdog/watchdog.h"
#include "esphome/core/application.h"
-#include "esphome/core/defines.h"
#include "esphome/core/log.h"
#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
@@ -118,20 +117,14 @@ std::shared_ptr HttpRequestIDF::start(std::string url, std::strin
return nullptr;
}
- auto is_ok = [](int code) { return code >= HttpStatus_Ok && code < HttpStatus_MultipleChoices; };
-
container->content_length = esp_http_client_fetch_headers(client);
container->status_code = esp_http_client_get_status_code(client);
- if (is_ok(container->status_code)) {
+ if (is_success(container->status_code)) {
container->duration_ms = millis() - start;
return container;
}
if (this->follow_redirects_) {
- auto is_redirect = [](int code) {
- return code == HttpStatus_MovedPermanently || code == HttpStatus_Found || code == HttpStatus_SeeOther ||
- code == HttpStatus_TemporaryRedirect || code == HttpStatus_PermanentRedirect;
- };
auto num_redirects = this->redirect_limit_;
while (is_redirect(container->status_code) && num_redirects > 0) {
err = esp_http_client_set_redirection(client);
@@ -142,9 +135,9 @@ std::shared_ptr HttpRequestIDF::start(std::string url, std::strin
return nullptr;
}
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
- char url[256]{};
- if (esp_http_client_get_url(client, url, sizeof(url) - 1) == ESP_OK) {
- ESP_LOGV(TAG, "redirecting to url: %s", url);
+ char redirect_url[256]{};
+ if (esp_http_client_get_url(client, redirect_url, sizeof(redirect_url) - 1) == ESP_OK) {
+ ESP_LOGV(TAG, "redirecting to url: %s", redirect_url);
}
#endif
err = esp_http_client_open(client, 0);
@@ -157,7 +150,7 @@ std::shared_ptr HttpRequestIDF::start(std::string url, std::strin
container->content_length = esp_http_client_fetch_headers(client);
container->status_code = esp_http_client_get_status_code(client);
- if (is_ok(container->status_code)) {
+ if (is_success(container->status_code)) {
container->duration_ms = millis() - start;
return container;
}
diff --git a/esphome/components/http_request/ota/ota_http_request.cpp b/esphome/components/http_request/ota/ota_http_request.cpp
index f7c941da18..cec30d72ec 100644
--- a/esphome/components/http_request/ota/ota_http_request.cpp
+++ b/esphome/components/http_request/ota/ota_http_request.cpp
@@ -106,7 +106,7 @@ uint8_t OtaHttpRequestComponent::do_ota_() {
auto container = this->parent_->get(url_with_auth);
- if (container == nullptr || container->status_code != 200) {
+ if (container == nullptr || container->status_code != HTTP_STATUS_OK) {
return OTA_CONNECTION_ERROR;
}
diff --git a/esphome/components/http_request/update/http_request_update.cpp b/esphome/components/http_request/update/http_request_update.cpp
index 4d913f2158..0e0966c22b 100644
--- a/esphome/components/http_request/update/http_request_update.cpp
+++ b/esphome/components/http_request/update/http_request_update.cpp
@@ -31,7 +31,7 @@ void HttpRequestUpdate::setup() {
void HttpRequestUpdate::update() {
auto container = this->request_parent_->get(this->source_url_);
- if (container == nullptr || container->status_code != 200) {
+ if (container == nullptr || container->status_code != HTTP_STATUS_OK) {
std::string msg = str_sprintf("Failed to fetch manifest from %s", this->source_url_.c_str());
this->status_set_error(msg.c_str());
return;
From 302ba2874e12960c76a624fa6066bf5df1ffac2e Mon Sep 17 00:00:00 2001
From: Satoshi YAMADA
Date: Tue, 29 Oct 2024 12:08:08 +0900
Subject: [PATCH 52/74] Support W5500 SPI-Ethernet polling mode if framework is
supported (#7503)
---
esphome/components/ethernet/__init__.py | 56 ++++++++++++++++++-
.../ethernet/ethernet_component.cpp | 15 ++++-
.../components/ethernet/ethernet_component.h | 8 ++-
esphome/const.py | 1 +
4 files changed, 77 insertions(+), 3 deletions(-)
diff --git a/esphome/components/ethernet/__init__.py b/esphome/components/ethernet/__init__.py
index 475d60df53..dca37b8dc2 100644
--- a/esphome/components/ethernet/__init__.py
+++ b/esphome/components/ethernet/__init__.py
@@ -1,3 +1,4 @@
+import logging
from esphome import pins
import esphome.codegen as cg
from esphome.components.esp32 import add_idf_sdkconfig_option, get_esp32_variant
@@ -23,6 +24,7 @@ from esphome.const import (
CONF_MISO_PIN,
CONF_MOSI_PIN,
CONF_PAGE_ID,
+ CONF_POLLING_INTERVAL,
CONF_RESET_PIN,
CONF_SPI,
CONF_STATIC_IP,
@@ -30,13 +32,16 @@ from esphome.const import (
CONF_TYPE,
CONF_USE_ADDRESS,
CONF_VALUE,
+ KEY_CORE,
+ KEY_FRAMEWORK_VERSION,
)
-from esphome.core import CORE, coroutine_with_priority
+from esphome.core import CORE, TimePeriodMilliseconds, coroutine_with_priority
import esphome.final_validate as fv
CONFLICTS_WITH = ["wifi"]
DEPENDENCIES = ["esp32"]
AUTO_LOAD = ["network"]
+LOGGER = logging.getLogger(__name__)
ethernet_ns = cg.esphome_ns.namespace("ethernet")
PHYRegister = ethernet_ns.struct("PHYRegister")
@@ -63,6 +68,7 @@ ETHERNET_TYPES = {
}
SPI_ETHERNET_TYPES = ["W5500"]
+SPI_ETHERNET_DEFAULT_POLLING_INTERVAL = TimePeriodMilliseconds(milliseconds=10)
emac_rmii_clock_mode_t = cg.global_ns.enum("emac_rmii_clock_mode_t")
emac_rmii_clock_gpio_t = cg.global_ns.enum("emac_rmii_clock_gpio_t")
@@ -100,6 +106,24 @@ EthernetComponent = ethernet_ns.class_("EthernetComponent", cg.Component)
ManualIP = ethernet_ns.struct("ManualIP")
+def _is_framework_spi_polling_mode_supported():
+ # SPI Ethernet without IRQ feature is added in
+ # esp-idf >= (5.3+ ,5.2.1+, 5.1.4) and arduino-esp32 >= 3.0.0
+ framework_version = CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]
+ if CORE.using_esp_idf:
+ if framework_version >= cv.Version(5, 3, 0):
+ return True
+ if cv.Version(5, 3, 0) > framework_version >= cv.Version(5, 2, 1):
+ return True
+ if cv.Version(5, 2, 0) > framework_version >= cv.Version(5, 1, 4):
+ return True
+ return False
+ if CORE.using_arduino:
+ return framework_version >= cv.Version(3, 0, 0)
+ # fail safe: Unknown framework
+ return False
+
+
def _validate(config):
if CONF_USE_ADDRESS not in config:
if CONF_MANUAL_IP in config:
@@ -107,6 +131,27 @@ def _validate(config):
else:
use_address = CORE.name + config[CONF_DOMAIN]
config[CONF_USE_ADDRESS] = use_address
+ if config[CONF_TYPE] in SPI_ETHERNET_TYPES:
+ if _is_framework_spi_polling_mode_supported():
+ if CONF_POLLING_INTERVAL in config and CONF_INTERRUPT_PIN in config:
+ raise cv.Invalid(
+ f"Cannot specify more than one of {CONF_INTERRUPT_PIN}, {CONF_POLLING_INTERVAL}"
+ )
+ if CONF_POLLING_INTERVAL not in config and CONF_INTERRUPT_PIN not in config:
+ config[CONF_POLLING_INTERVAL] = SPI_ETHERNET_DEFAULT_POLLING_INTERVAL
+ else:
+ if CONF_POLLING_INTERVAL in config:
+ raise cv.Invalid(
+ "In this version of the framework "
+ f"({CORE.target_framework} {CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]}), "
+ f"'{CONF_POLLING_INTERVAL}' is not supported."
+ )
+ if CONF_INTERRUPT_PIN not in config:
+ raise cv.Invalid(
+ "In this version of the framework "
+ f"({CORE.target_framework} {CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]}), "
+ f"'{CONF_INTERRUPT_PIN}' is a required option for [ethernet]."
+ )
return config
@@ -157,6 +202,11 @@ SPI_SCHEMA = BASE_SCHEMA.extend(
cv.Optional(CONF_CLOCK_SPEED, default="26.67MHz"): cv.All(
cv.frequency, cv.int_range(int(8e6), int(80e6))
),
+ # Set default value (SPI_ETHERNET_DEFAULT_POLLING_INTERVAL) at _validate()
+ cv.Optional(CONF_POLLING_INTERVAL): cv.All(
+ cv.positive_time_period_milliseconds,
+ cv.Range(min=TimePeriodMilliseconds(milliseconds=1)),
+ ),
}
),
)
@@ -234,6 +284,10 @@ async def to_code(config):
cg.add(var.set_cs_pin(config[CONF_CS_PIN]))
if CONF_INTERRUPT_PIN in config:
cg.add(var.set_interrupt_pin(config[CONF_INTERRUPT_PIN]))
+ else:
+ cg.add(var.set_polling_interval(config[CONF_POLLING_INTERVAL]))
+ if _is_framework_spi_polling_mode_supported():
+ cg.add_define("USE_ETHERNET_SPI_POLLING_SUPPORT")
if CONF_RESET_PIN in config:
cg.add(var.set_reset_pin(config[CONF_RESET_PIN]))
cg.add(var.set_clock_speed(config[CONF_CLOCK_SPEED]))
diff --git a/esphome/components/ethernet/ethernet_component.cpp b/esphome/components/ethernet/ethernet_component.cpp
index 00c7ae4ab8..08f5fa6642 100644
--- a/esphome/components/ethernet/ethernet_component.cpp
+++ b/esphome/components/ethernet/ethernet_component.cpp
@@ -116,6 +116,9 @@ void EthernetComponent::setup() {
eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(spi_handle);
#endif
w5500_config.int_gpio_num = this->interrupt_pin_;
+#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
+ w5500_config.poll_period_ms = this->polling_interval_;
+#endif
phy_config.phy_addr = this->phy_addr_spi_;
phy_config.reset_gpio_num = this->reset_pin_;
@@ -327,7 +330,14 @@ void EthernetComponent::dump_config() {
ESP_LOGCONFIG(TAG, " MISO Pin: %u", this->miso_pin_);
ESP_LOGCONFIG(TAG, " MOSI Pin: %u", this->mosi_pin_);
ESP_LOGCONFIG(TAG, " CS Pin: %u", this->cs_pin_);
- ESP_LOGCONFIG(TAG, " IRQ Pin: %u", this->interrupt_pin_);
+#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
+ if (this->polling_interval_ != 0) {
+ ESP_LOGCONFIG(TAG, " Polling Interval: %lu ms", this->polling_interval_);
+ } else
+#endif
+ {
+ ESP_LOGCONFIG(TAG, " IRQ Pin: %d", this->interrupt_pin_);
+ }
ESP_LOGCONFIG(TAG, " Reset Pin: %d", this->reset_pin_);
ESP_LOGCONFIG(TAG, " Clock Speed: %d MHz", this->clock_speed_ / 1000000);
#else
@@ -536,6 +546,9 @@ void EthernetComponent::set_cs_pin(uint8_t cs_pin) { this->cs_pin_ = cs_pin; }
void EthernetComponent::set_interrupt_pin(uint8_t interrupt_pin) { this->interrupt_pin_ = interrupt_pin; }
void EthernetComponent::set_reset_pin(uint8_t reset_pin) { this->reset_pin_ = reset_pin; }
void EthernetComponent::set_clock_speed(int clock_speed) { this->clock_speed_ = clock_speed; }
+#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
+void EthernetComponent::set_polling_interval(uint32_t polling_interval) { this->polling_interval_ = polling_interval; }
+#endif
#else
void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; }
void EthernetComponent::set_power_pin(int power_pin) { this->power_pin_ = power_pin; }
diff --git a/esphome/components/ethernet/ethernet_component.h b/esphome/components/ethernet/ethernet_component.h
index 5ee430c046..fb178431d5 100644
--- a/esphome/components/ethernet/ethernet_component.h
+++ b/esphome/components/ethernet/ethernet_component.h
@@ -67,6 +67,9 @@ class EthernetComponent : public Component {
void set_interrupt_pin(uint8_t interrupt_pin);
void set_reset_pin(uint8_t reset_pin);
void set_clock_speed(int clock_speed);
+#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
+ void set_polling_interval(uint32_t polling_interval);
+#endif
#else
void set_phy_addr(uint8_t phy_addr);
void set_power_pin(int power_pin);
@@ -108,10 +111,13 @@ class EthernetComponent : public Component {
uint8_t miso_pin_;
uint8_t mosi_pin_;
uint8_t cs_pin_;
- uint8_t interrupt_pin_;
+ int interrupt_pin_{-1};
int reset_pin_{-1};
int phy_addr_spi_{-1};
int clock_speed_;
+#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
+ uint32_t polling_interval_{0};
+#endif
#else
uint8_t phy_addr_{0};
int power_pin_{-1};
diff --git a/esphome/const.py b/esphome/const.py
index 54ebb2815f..c39061631b 100644
--- a/esphome/const.py
+++ b/esphome/const.py
@@ -666,6 +666,7 @@ CONF_PMC_1_0 = "pmc_1_0"
CONF_PMC_10_0 = "pmc_10_0"
CONF_PMC_2_5 = "pmc_2_5"
CONF_PMC_4_0 = "pmc_4_0"
+CONF_POLLING_INTERVAL = "polling_interval"
CONF_PORT = "port"
CONF_POSITION = "position"
CONF_POSITION_ACTION = "position_action"
From 444c0fc67f4284e42e00ad61466febe999122690 Mon Sep 17 00:00:00 2001
From: Jordan Zucker
Date: Mon, 28 Oct 2024 20:09:22 -0700
Subject: [PATCH 53/74] Add asdf to gitignore (and dockerignore) (#7686)
---
.dockerignore | 3 +++
.gitignore | 3 +++
2 files changed, 6 insertions(+)
diff --git a/.dockerignore b/.dockerignore
index 9f14b98059..7998ff877f 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -75,6 +75,9 @@ target/
# pyenv
.python-version
+# asdf
+.tool-versions
+
# celery beat schedule file
celerybeat-schedule
diff --git a/.gitignore b/.gitignore
index 79820249ac..ad38e26fdd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -75,6 +75,9 @@ cov.xml
# pyenv
.python-version
+# asdf
+.tool-versions
+
# Environments
.env
.venv
From 90b076eccd67253fb9ce612251130a76039e549d Mon Sep 17 00:00:00 2001
From: Jordan Zucker
Date: Mon, 28 Oct 2024 20:43:02 -0700
Subject: [PATCH 54/74] Add more prometheus metrics (#7683)
---
.../prometheus/prometheus_handler.cpp | 43 +++++++++++++++++++
.../prometheus/prometheus_handler.h | 7 +++
tests/components/prometheus/common.yaml | 14 ++++++
3 files changed, 64 insertions(+)
diff --git a/esphome/components/prometheus/prometheus_handler.cpp b/esphome/components/prometheus/prometheus_handler.cpp
index 3e9cf81e6e..63b3fdf53f 100644
--- a/esphome/components/prometheus/prometheus_handler.cpp
+++ b/esphome/components/prometheus/prometheus_handler.cpp
@@ -50,6 +50,12 @@ void PrometheusHandler::handleRequest(AsyncWebServerRequest *req) {
this->lock_row_(stream, obj);
#endif
+#ifdef USE_TEXT_SENSOR
+ this->text_sensor_type_(stream);
+ for (auto *obj : App.get_text_sensors())
+ this->text_sensor_row_(stream, obj);
+#endif
+
req->send(stream);
}
@@ -349,6 +355,43 @@ void PrometheusHandler::lock_row_(AsyncResponseStream *stream, lock::Lock *obj)
}
#endif
+// Type-specific implementation
+#ifdef USE_TEXT_SENSOR
+void PrometheusHandler::text_sensor_type_(AsyncResponseStream *stream) {
+ stream->print(F("#TYPE esphome_text_sensor_value gauge\n"));
+ stream->print(F("#TYPE esphome_text_sensor_failed gauge\n"));
+}
+void PrometheusHandler::text_sensor_row_(AsyncResponseStream *stream, text_sensor::TextSensor *obj) {
+ if (obj->is_internal() && !this->include_internal_)
+ return;
+ if (obj->has_state()) {
+ // We have a valid value, output this value
+ stream->print(F("esphome_text_sensor_failed{id=\""));
+ stream->print(relabel_id_(obj).c_str());
+ stream->print(F("\",name=\""));
+ stream->print(relabel_name_(obj).c_str());
+ stream->print(F("\"} 0\n"));
+ // Data itself
+ stream->print(F("esphome_text_sensor_value{id=\""));
+ stream->print(relabel_id_(obj).c_str());
+ stream->print(F("\",name=\""));
+ stream->print(relabel_name_(obj).c_str());
+ stream->print(F("\",value=\""));
+ stream->print(obj->state.c_str());
+ stream->print(F("\"} "));
+ stream->print(F("1.0"));
+ stream->print(F("\n"));
+ } else {
+ // Invalid state
+ stream->print(F("esphome_text_sensor_failed{id=\""));
+ stream->print(relabel_id_(obj).c_str());
+ stream->print(F("\",name=\""));
+ stream->print(relabel_name_(obj).c_str());
+ stream->print(F("\"} 1\n"));
+ }
+}
+#endif
+
} // namespace prometheus
} // namespace esphome
#endif
diff --git a/esphome/components/prometheus/prometheus_handler.h b/esphome/components/prometheus/prometheus_handler.h
index f5e49a1419..512e1bee4f 100644
--- a/esphome/components/prometheus/prometheus_handler.h
+++ b/esphome/components/prometheus/prometheus_handler.h
@@ -110,6 +110,13 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
void lock_row_(AsyncResponseStream *stream, lock::Lock *obj);
#endif
+#ifdef USE_TEXT_SENSOR
+ /// Return the type for prometheus
+ void text_sensor_type_(AsyncResponseStream *stream);
+ /// Return the lock Values state as prometheus data point
+ void text_sensor_row_(AsyncResponseStream *stream, text_sensor::TextSensor *obj);
+#endif
+
web_server_base::WebServerBase *base_;
bool include_internal_{false};
std::map relabel_map_id_;
diff --git a/tests/components/prometheus/common.yaml b/tests/components/prometheus/common.yaml
index c8ce17da88..7aa509f8b2 100644
--- a/tests/components/prometheus/common.yaml
+++ b/tests/components/prometheus/common.yaml
@@ -13,9 +13,23 @@ sensor:
}
update_interval: 60s
+text_sensor:
+ - platform: template
+ id: template_text_sensor1
+ lambda: |-
+ if (millis() > 10000) {
+ return {"Hello World"};
+ } else {
+ return {"Goodbye (cruel) World"};
+ }
+ update_interval: 60s
+
prometheus:
include_internal: true
relabel:
template_sensor1:
id: hellow_world
name: Hello World
+ template_text_sensor1:
+ id: hello_text
+ name: Text Substitution
From 0dab280440de853d57d750463b3be4e065fd480d Mon Sep 17 00:00:00 2001
From: Sean Brogan
Date: Mon, 28 Oct 2024 20:49:06 -0700
Subject: [PATCH 55/74] Mopeka Pro Check improvement to allow user to configure
the sensor reporting for lower quality readings (#7475)
---
.../mopeka_pro_check/mopeka_pro_check.cpp | 63 ++++++++++++-------
.../mopeka_pro_check/mopeka_pro_check.h | 11 +++-
esphome/components/mopeka_pro_check/sensor.py | 41 ++++++++++++
tests/components/mopeka_pro_check/common.yaml | 17 +++++
4 files changed, 108 insertions(+), 24 deletions(-)
diff --git a/esphome/components/mopeka_pro_check/mopeka_pro_check.cpp b/esphome/components/mopeka_pro_check/mopeka_pro_check.cpp
index f79e40bb4e..9527f09f59 100644
--- a/esphome/components/mopeka_pro_check/mopeka_pro_check.cpp
+++ b/esphome/components/mopeka_pro_check/mopeka_pro_check.cpp
@@ -17,6 +17,8 @@ void MopekaProCheck::dump_config() {
LOG_SENSOR(" ", "Temperature", this->temperature_);
LOG_SENSOR(" ", "Battery Level", this->battery_level_);
LOG_SENSOR(" ", "Reading Distance", this->distance_);
+ LOG_SENSOR(" ", "Read Quality", this->read_quality_);
+ LOG_SENSOR(" ", "Ignored Reads", this->ignored_reads_);
}
/**
@@ -66,34 +68,49 @@ bool MopekaProCheck::parse_device(const esp32_ble_tracker::ESPBTDevice &device)
this->battery_level_->publish_state(level);
}
+ // Get the quality value
+ SensorReadQuality quality_value = this->parse_read_quality_(manu_data.data);
+ if (this->read_quality_ != nullptr) {
+ this->read_quality_->publish_state(static_cast(quality_value));
+ }
+
+ // Determine if we have a good enough quality of read to report level and distance
+ // sensors. This sensor is reported regardless of distance or level sensors being enabled
+ if (quality_value < this->min_signal_quality_) {
+ ESP_LOGW(TAG, "Read Quality too low to report distance or level");
+ this->ignored_read_count_++;
+ } else {
+ // reset to zero since read quality was sufficient
+ this->ignored_read_count_ = 0;
+ }
+ // Report number of contiguous ignored reads if sensor defined
+ if (this->ignored_reads_ != nullptr) {
+ this->ignored_reads_->publish_state(this->ignored_read_count_);
+ }
+
// Get distance and level if either are sensors
if ((this->distance_ != nullptr) || (this->level_ != nullptr)) {
uint32_t distance_value = this->parse_distance_(manu_data.data);
- SensorReadQuality quality_value = this->parse_read_quality_(manu_data.data);
ESP_LOGD(TAG, "Distance Sensor: Quality (0x%X) Distance (%" PRId32 "mm)", quality_value, distance_value);
- if (quality_value < QUALITY_HIGH) {
- ESP_LOGW(TAG, "Poor read quality.");
- }
- if (quality_value < QUALITY_MED) {
- // if really bad reading set to 0
- ESP_LOGW(TAG, "Setting distance to 0");
- distance_value = 0;
- }
- // update distance sensor
- if (this->distance_ != nullptr) {
- this->distance_->publish_state(distance_value);
- }
-
- // update level sensor
- if (this->level_ != nullptr) {
- uint8_t tank_level = 0;
- if (distance_value >= this->full_mm_) {
- tank_level = 100; // cap at 100%
- } else if (distance_value > this->empty_mm_) {
- tank_level = ((100.0f / (this->full_mm_ - this->empty_mm_)) * (distance_value - this->empty_mm_));
+ // only update distance and level sensors if read quality was sufficient. This can be determined by
+ // if the ignored_read_count is zero.
+ if (this->ignored_read_count_ == 0) {
+ // update distance sensor
+ if (this->distance_ != nullptr) {
+ this->distance_->publish_state(distance_value);
+ }
+
+ // update level sensor
+ if (this->level_ != nullptr) {
+ uint8_t tank_level = 0;
+ if (distance_value >= this->full_mm_) {
+ tank_level = 100; // cap at 100%
+ } else if (distance_value > this->empty_mm_) {
+ tank_level = ((100.0f / (this->full_mm_ - this->empty_mm_)) * (distance_value - this->empty_mm_));
+ }
+ this->level_->publish_state(tank_level);
}
- this->level_->publish_state(tank_level);
}
}
@@ -131,6 +148,8 @@ uint32_t MopekaProCheck::parse_distance_(const std::vector &message) {
uint8_t MopekaProCheck::parse_temperature_(const std::vector &message) { return (message[2] & 0x7F) - 40; }
SensorReadQuality MopekaProCheck::parse_read_quality_(const std::vector &message) {
+ // Since a 8 bit value is being shifted and truncated to 2 bits all possible values are defined as enumeration
+ // value and the static cast is safe.
return static_cast(message[4] >> 6);
}
diff --git a/esphome/components/mopeka_pro_check/mopeka_pro_check.h b/esphome/components/mopeka_pro_check/mopeka_pro_check.h
index 8b4d47e4c6..c58406ac18 100644
--- a/esphome/components/mopeka_pro_check/mopeka_pro_check.h
+++ b/esphome/components/mopeka_pro_check/mopeka_pro_check.h
@@ -24,9 +24,9 @@ enum SensorType {
};
// Sensor read quality. If sensor is poorly placed or tank level
-// gets too low the read quality will show and the distanace
+// gets too low the read quality will show and the distance
// measurement may be inaccurate.
-enum SensorReadQuality { QUALITY_HIGH = 0x3, QUALITY_MED = 0x2, QUALITY_LOW = 0x1, QUALITY_NONE = 0x0 };
+enum SensorReadQuality { QUALITY_HIGH = 0x3, QUALITY_MED = 0x2, QUALITY_LOW = 0x1, QUALITY_ZERO = 0x0 };
class MopekaProCheck : public Component, public esp32_ble_tracker::ESPBTDeviceListener {
public:
@@ -35,11 +35,14 @@ class MopekaProCheck : public Component, public esp32_ble_tracker::ESPBTDeviceLi
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override;
void dump_config() override;
float get_setup_priority() const override { return setup_priority::DATA; }
+ void set_min_signal_quality(SensorReadQuality min) { this->min_signal_quality_ = min; };
void set_level(sensor::Sensor *level) { level_ = level; };
void set_temperature(sensor::Sensor *temperature) { temperature_ = temperature; };
void set_battery_level(sensor::Sensor *bat) { battery_level_ = bat; };
void set_distance(sensor::Sensor *distance) { distance_ = distance; };
+ void set_signal_quality(sensor::Sensor *rq) { read_quality_ = rq; };
+ void set_ignored_reads(sensor::Sensor *ir) { ignored_reads_ = ir; };
void set_tank_full(float full) { full_mm_ = full; };
void set_tank_empty(float empty) { empty_mm_ = empty; };
@@ -49,9 +52,13 @@ class MopekaProCheck : public Component, public esp32_ble_tracker::ESPBTDeviceLi
sensor::Sensor *temperature_{nullptr};
sensor::Sensor *distance_{nullptr};
sensor::Sensor *battery_level_{nullptr};
+ sensor::Sensor *read_quality_{nullptr};
+ sensor::Sensor *ignored_reads_{nullptr};
uint32_t full_mm_;
uint32_t empty_mm_;
+ uint32_t ignored_read_count_ = 0;
+ SensorReadQuality min_signal_quality_ = QUALITY_MED;
uint8_t parse_battery_level_(const std::vector &message);
uint32_t parse_distance_(const std::vector &message);
diff --git a/esphome/components/mopeka_pro_check/sensor.py b/esphome/components/mopeka_pro_check/sensor.py
index 0ba33e94de..95ade53013 100644
--- a/esphome/components/mopeka_pro_check/sensor.py
+++ b/esphome/components/mopeka_pro_check/sensor.py
@@ -5,9 +5,12 @@ from esphome.const import (
CONF_DISTANCE,
CONF_MAC_ADDRESS,
CONF_ID,
+ ICON_COUNTER,
ICON_THERMOMETER,
ICON_RULER,
+ ICON_SIGNAL,
UNIT_PERCENT,
+ UNIT_EMPTY,
CONF_LEVEL,
CONF_TEMPERATURE,
DEVICE_CLASS_TEMPERATURE,
@@ -16,11 +19,15 @@ from esphome.const import (
STATE_CLASS_MEASUREMENT,
CONF_BATTERY_LEVEL,
DEVICE_CLASS_BATTERY,
+ ENTITY_CATEGORY_DIAGNOSTIC,
)
CONF_TANK_TYPE = "tank_type"
CONF_CUSTOM_DISTANCE_FULL = "custom_distance_full"
CONF_CUSTOM_DISTANCE_EMPTY = "custom_distance_empty"
+CONF_SIGNAL_QUALITY = "signal_quality"
+CONF_MINIMUM_SIGNAL_QUALITY = "minimum_signal_quality"
+CONF_IGNORED_READS = "ignored_reads"
ICON_PROPANE_TANK = "mdi:propane-tank"
@@ -56,6 +63,14 @@ MopekaProCheck = mopeka_pro_check_ns.class_(
"MopekaProCheck", esp32_ble_tracker.ESPBTDeviceListener, cg.Component
)
+SensorReadQuality = mopeka_pro_check_ns.enum("SensorReadQuality")
+SIGNAL_QUALITIES = {
+ "ZERO": SensorReadQuality.QUALITY_ZERO,
+ "LOW": SensorReadQuality.QUALITY_LOW,
+ "MEDIUM": SensorReadQuality.QUALITY_MED,
+ "HIGH": SensorReadQuality.QUALITY_HIGH,
+}
+
CONFIG_SCHEMA = (
cv.Schema(
{
@@ -89,6 +104,21 @@ CONFIG_SCHEMA = (
device_class=DEVICE_CLASS_BATTERY,
state_class=STATE_CLASS_MEASUREMENT,
),
+ cv.Optional(CONF_SIGNAL_QUALITY): sensor.sensor_schema(
+ unit_of_measurement=UNIT_EMPTY,
+ icon=ICON_SIGNAL,
+ accuracy_decimals=0,
+ state_class=STATE_CLASS_MEASUREMENT,
+ ),
+ cv.Optional(CONF_IGNORED_READS): sensor.sensor_schema(
+ unit_of_measurement=UNIT_EMPTY,
+ icon=ICON_COUNTER,
+ accuracy_decimals=0,
+ entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
+ ),
+ cv.Optional(CONF_MINIMUM_SIGNAL_QUALITY, default="MEDIUM"): cv.enum(
+ SIGNAL_QUALITIES, upper=True
+ ),
}
)
.extend(esp32_ble_tracker.ESP_BLE_DEVICE_SCHEMA)
@@ -119,6 +149,11 @@ async def to_code(config):
cg.add(var.set_tank_empty(CONF_SUPPORTED_TANKS_MAP[t][0]))
cg.add(var.set_tank_full(CONF_SUPPORTED_TANKS_MAP[t][1]))
+ if (
+ minimum_signal_quality := config.get(CONF_MINIMUM_SIGNAL_QUALITY, None)
+ ) is not None:
+ cg.add(var.set_min_signal_quality(minimum_signal_quality))
+
if CONF_TEMPERATURE in config:
sens = await sensor.new_sensor(config[CONF_TEMPERATURE])
cg.add(var.set_temperature(sens))
@@ -131,3 +166,9 @@ async def to_code(config):
if CONF_BATTERY_LEVEL in config:
sens = await sensor.new_sensor(config[CONF_BATTERY_LEVEL])
cg.add(var.set_battery_level(sens))
+ if CONF_SIGNAL_QUALITY in config:
+ sens = await sensor.new_sensor(config[CONF_SIGNAL_QUALITY])
+ cg.add(var.set_signal_quality(sens))
+ if CONF_IGNORED_READS in config:
+ sens = await sensor.new_sensor(config[CONF_IGNORED_READS])
+ cg.add(var.set_ignored_reads(sens))
diff --git a/tests/components/mopeka_pro_check/common.yaml b/tests/components/mopeka_pro_check/common.yaml
index 147cbcb9de..3533ecf631 100644
--- a/tests/components/mopeka_pro_check/common.yaml
+++ b/tests/components/mopeka_pro_check/common.yaml
@@ -14,3 +14,20 @@ sensor:
name: Propane test distance
battery_level:
name: Propane test battery level
+
+ - platform: mopeka_pro_check
+ mac_address: AA:BB:CC:DD:EE:FF
+ tank_type: 20LB_V
+ temperature:
+ name: "Propane test2 temp"
+ level:
+ name: "Propane test2 level"
+ distance:
+ name: "Propane test2 distance"
+ battery_level:
+ name: "Propane test2 battery level"
+ signal_quality:
+ name: "propane test2 read quality"
+ ignored_reads:
+ name: "propane test2 ignored reads"
+ minimum_signal_quality: "LOW"
From aa0e155e22c422c789feeb0b1be9495f703fc8fa Mon Sep 17 00:00:00 2001
From: Bonne Eggleston
Date: Mon, 28 Oct 2024 20:52:39 -0700
Subject: [PATCH 56/74] Fixes modbus timing error (#7674)
---
esphome/components/modbus/modbus.cpp | 36 ++++++++++++++++++----------
1 file changed, 24 insertions(+), 12 deletions(-)
diff --git a/esphome/components/modbus/modbus.cpp b/esphome/components/modbus/modbus.cpp
index f8dd4c18b9..8544b50261 100644
--- a/esphome/components/modbus/modbus.cpp
+++ b/esphome/components/modbus/modbus.cpp
@@ -15,23 +15,33 @@ void Modbus::setup() {
void Modbus::loop() {
const uint32_t now = millis();
- if (now - this->last_modbus_byte_ > 50) {
- this->rx_buffer_.clear();
- this->last_modbus_byte_ = now;
- }
- // stop blocking new send commands after send_wait_time_ ms regardless if a response has been received since then
- if (now - this->last_send_ > send_wait_time_) {
- waiting_for_response = 0;
- }
-
while (this->available()) {
uint8_t byte;
this->read_byte(&byte);
if (this->parse_modbus_byte_(byte)) {
this->last_modbus_byte_ = now;
} else {
+ size_t at = this->rx_buffer_.size();
+ if (at > 0) {
+ ESP_LOGV(TAG, "Clearing buffer of %d bytes - parse failed", at);
+ this->rx_buffer_.clear();
+ }
+ }
+ }
+
+ if (now - this->last_modbus_byte_ > 50) {
+ size_t at = this->rx_buffer_.size();
+ if (at > 0) {
+ ESP_LOGV(TAG, "Clearing buffer of %d bytes - timeout", at);
this->rx_buffer_.clear();
}
+
+ // stop blocking new send commands after sent_wait_time_ ms after response received
+ if (now - this->last_send_ > send_wait_time_) {
+ if (waiting_for_response > 0)
+ ESP_LOGV(TAG, "Stop waiting for response from %d", waiting_for_response);
+ waiting_for_response = 0;
+ }
}
}
@@ -39,7 +49,7 @@ bool Modbus::parse_modbus_byte_(uint8_t byte) {
size_t at = this->rx_buffer_.size();
this->rx_buffer_.push_back(byte);
const uint8_t *raw = &this->rx_buffer_[0];
- ESP_LOGV(TAG, "Modbus received Byte %d (0X%x)", byte, byte);
+ ESP_LOGVV(TAG, "Modbus received Byte %d (0X%x)", byte, byte);
// Byte 0: modbus address (match all)
if (at == 0)
return true;
@@ -144,8 +154,10 @@ bool Modbus::parse_modbus_byte_(uint8_t byte) {
ESP_LOGW(TAG, "Got Modbus frame from unknown address 0x%02X! ", address);
}
- // return false to reset buffer
- return false;
+ // reset buffer
+ ESP_LOGV(TAG, "Clearing buffer of %d bytes - parse succeeded", at);
+ this->rx_buffer_.clear();
+ return true;
}
void Modbus::dump_config() {
From abbd7faa641220fc3cbc2e77f76f3bfcf41546ab Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Rodrigo=20Mart=C3=ADn?=
Date: Tue, 29 Oct 2024 04:56:50 +0100
Subject: [PATCH 57/74] fix(WiFi): Fix strncpy missing NULL terminator
[-Werror=stringop-truncation] (#7668)
---
esphome/components/wifi/wifi_component.cpp | 4 ++--
esphome/components/wifi/wifi_component_esp32_arduino.cpp | 8 ++++----
esphome/components/wifi/wifi_component_esp8266.cpp | 8 ++++----
esphome/components/wifi/wifi_component_esp_idf.cpp | 4 ++--
4 files changed, 12 insertions(+), 12 deletions(-)
diff --git a/esphome/components/wifi/wifi_component.cpp b/esphome/components/wifi/wifi_component.cpp
index 583a27466a..8788711d5a 100644
--- a/esphome/components/wifi/wifi_component.cpp
+++ b/esphome/components/wifi/wifi_component.cpp
@@ -297,8 +297,8 @@ void WiFiComponent::set_sta(const WiFiAP &ap) {
void WiFiComponent::clear_sta() { this->sta_.clear(); }
void WiFiComponent::save_wifi_sta(const std::string &ssid, const std::string &password) {
SavedWifiSettings save{};
- strncpy(save.ssid, ssid.c_str(), sizeof(save.ssid));
- strncpy(save.password, password.c_str(), sizeof(save.password));
+ snprintf(save.ssid, sizeof(save.ssid), "%s", ssid.c_str());
+ snprintf(save.password, sizeof(save.password), "%s", password.c_str());
this->pref_.save(&save);
// ensure it's written immediately
global_preferences->sync();
diff --git a/esphome/components/wifi/wifi_component_esp32_arduino.cpp b/esphome/components/wifi/wifi_component_esp32_arduino.cpp
index ef4308b28c..88648093c6 100644
--- a/esphome/components/wifi/wifi_component_esp32_arduino.cpp
+++ b/esphome/components/wifi/wifi_component_esp32_arduino.cpp
@@ -137,8 +137,8 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t
wifi_config_t conf;
memset(&conf, 0, sizeof(conf));
- strncpy(reinterpret_cast(conf.sta.ssid), ap.get_ssid().c_str(), sizeof(conf.sta.ssid));
- strncpy(reinterpret_cast(conf.sta.password), ap.get_password().c_str(), sizeof(conf.sta.password));
+ snprintf(reinterpret_cast(conf.sta.ssid), sizeof(conf.sta.ssid), "%s", ap.get_ssid().c_str());
+ snprintf(reinterpret_cast(conf.sta.password), sizeof(conf.sta.password), "%s", ap.get_password().c_str());
// The weakest authmode to accept in the fast scan mode
if (ap.get_password().empty()) {
@@ -746,7 +746,7 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
wifi_config_t conf;
memset(&conf, 0, sizeof(conf));
- strncpy(reinterpret_cast(conf.ap.ssid), ap.get_ssid().c_str(), sizeof(conf.ap.ssid));
+ snprintf(reinterpret_cast(conf.ap.ssid), sizeof(conf.ap.ssid), "%s", ap.get_ssid().c_str());
conf.ap.channel = ap.get_channel().value_or(1);
conf.ap.ssid_hidden = ap.get_ssid().size();
conf.ap.max_connection = 5;
@@ -757,7 +757,7 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
*conf.ap.password = 0;
} else {
conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
- strncpy(reinterpret_cast(conf.ap.password), ap.get_password().c_str(), sizeof(conf.ap.password));
+ snprintf(reinterpret_cast(conf.ap.password), sizeof(conf.ap.password), "%s", ap.get_password().c_str());
}
// pairwise cipher of SoftAP, group cipher will be derived using this.
diff --git a/esphome/components/wifi/wifi_component_esp8266.cpp b/esphome/components/wifi/wifi_component_esp8266.cpp
index 92f80c1e52..4568895950 100644
--- a/esphome/components/wifi/wifi_component_esp8266.cpp
+++ b/esphome/components/wifi/wifi_component_esp8266.cpp
@@ -236,8 +236,8 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
struct station_config conf {};
memset(&conf, 0, sizeof(conf));
- strncpy(reinterpret_cast(conf.ssid), ap.get_ssid().c_str(), sizeof(conf.ssid));
- strncpy(reinterpret_cast(conf.password), ap.get_password().c_str(), sizeof(conf.password));
+ snprintf(reinterpret_cast(conf.ssid), sizeof(conf.ssid), "%s", ap.get_ssid().c_str());
+ snprintf(reinterpret_cast(conf.password), sizeof(conf.password), "%s", ap.get_password().c_str());
if (ap.get_bssid().has_value()) {
conf.bssid_set = 1;
@@ -775,7 +775,7 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
return false;
struct softap_config conf {};
- strncpy(reinterpret_cast(conf.ssid), ap.get_ssid().c_str(), sizeof(conf.ssid));
+ snprintf(reinterpret_cast(conf.ssid), sizeof(conf.ssid), "%s", ap.get_ssid().c_str());
conf.ssid_len = static_cast(ap.get_ssid().size());
conf.channel = ap.get_channel().value_or(1);
conf.ssid_hidden = ap.get_hidden();
@@ -787,7 +787,7 @@ bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
*conf.password = 0;
} else {
conf.authmode = AUTH_WPA2_PSK;
- strncpy(reinterpret_cast(conf.password), ap.get_password().c_str(), sizeof(conf.password));
+ snprintf(reinterpret_cast(conf.password), sizeof(conf.password), "%s", ap.get_password().c_str());
}
ETS_UART_INTR_DISABLE();
diff --git a/esphome/components/wifi/wifi_component_esp_idf.cpp b/esphome/components/wifi/wifi_component_esp_idf.cpp
index 0f2e181e31..13870136d4 100644
--- a/esphome/components/wifi/wifi_component_esp_idf.cpp
+++ b/esphome/components/wifi/wifi_component_esp_idf.cpp
@@ -289,8 +289,8 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t
wifi_config_t conf;
memset(&conf, 0, sizeof(conf));
- strncpy(reinterpret_cast(conf.sta.ssid), ap.get_ssid().c_str(), sizeof(conf.sta.ssid));
- strncpy(reinterpret_cast(conf.sta.password), ap.get_password().c_str(), sizeof(conf.sta.password));
+ snprintf(reinterpret_cast(conf.sta.ssid), sizeof(conf.sta.ssid), "%s", ap.get_ssid().c_str());
+ snprintf(reinterpret_cast(conf.sta.password), sizeof(conf.sta.password), "%s", ap.get_password().c_str());
// The weakest authmode to accept in the fast scan mode
if (ap.get_password().empty()) {
From 71e1e3b5f8575a3c075b90dbf573c95927a9bb0a Mon Sep 17 00:00:00 2001
From: tomaszduda23
Date: Tue, 29 Oct 2024 04:58:36 +0100
Subject: [PATCH 58/74] let make new platform implementation in external
components (#7615)
Co-authored-by: Tomasz Duda
---
esphome/core/helpers.cpp | 57 ++++++++++++++++++++++++----------------
esphome/core/helpers.h | 4 +++
2 files changed, 39 insertions(+), 22 deletions(-)
diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp
index dca35819ff..8f94f624f1 100644
--- a/esphome/core/helpers.cpp
+++ b/esphome/core/helpers.cpp
@@ -10,6 +10,7 @@
#include