Merge branch 'dev' into mcuboot_support

This commit is contained in:
tomaszduda23 2024-10-28 21:20:28 +01:00 committed by GitHub
commit 1f7bd7ed3a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
210 changed files with 4760 additions and 2139 deletions

View file

@ -7,11 +7,16 @@
- [ ] Bugfix (non-breaking change which fixes an issue) - [ ] Bugfix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality) - [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] 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 - [ ] Other
**Related issue or feature (if applicable):** fixes <link to issue> **Related issue or feature (if applicable):**
**Pull request in [esphome-docs](https://github.com/esphome/esphome-docs) with documentation (if applicable):** esphome/esphome-docs#<esphome-docs PR number goes here> - fixes <link to issue>
**Pull request in [esphome-docs](https://github.com/esphome/esphome-docs) with documentation (if applicable):**
- esphome/esphome-docs#<esphome-docs PR number goes here>
## Test Environment ## Test Environment
@ -23,12 +28,6 @@
- [ ] RTL87xx - [ ] RTL87xx
## Example entry for `config.yaml`: ## Example entry for `config.yaml`:
<!--
Supplying a configuration snippet, makes it easier for a maintainer to test
your PR. Furthermore, for new integrations, it gives an impression of how
the configuration would look like.
Note: Remove this section if this PR does not have an example entry.
-->
```yaml ```yaml
# Example config.yaml # Example config.yaml

View file

@ -17,12 +17,12 @@ runs:
steps: steps:
- name: Set up Python ${{ inputs.python-version }} - name: Set up Python ${{ inputs.python-version }}
id: python id: python
uses: actions/setup-python@v5.2.0 uses: actions/setup-python@v5.3.0
with: with:
python-version: ${{ inputs.python-version }} python-version: ${{ inputs.python-version }}
- name: Restore Python virtual environment - name: Restore Python virtual environment
id: cache-venv id: cache-venv
uses: actions/cache/restore@v4.0.2 uses: actions/cache/restore@v4.1.2
with: with:
path: venv path: venv
# yamllint disable-line rule:line-length # yamllint disable-line rule:line-length

View file

@ -23,7 +23,7 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v4.1.7 uses: actions/checkout@v4.1.7
- name: Set up Python - name: Set up Python
uses: actions/setup-python@v5.2.0 uses: actions/setup-python@v5.3.0
with: with:
python-version: "3.11" python-version: "3.11"

View file

@ -42,7 +42,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v4.1.7 - uses: actions/checkout@v4.1.7
- name: Set up Python - name: Set up Python
uses: actions/setup-python@v5.2.0 uses: actions/setup-python@v5.3.0
with: with:
python-version: "3.9" python-version: "3.9"
- name: Set up Docker Buildx - name: Set up Docker Buildx

View file

@ -41,12 +41,12 @@ jobs:
run: echo key="${{ hashFiles('requirements.txt', 'requirements_optional.txt', 'requirements_test.txt') }}" >> $GITHUB_OUTPUT run: echo key="${{ hashFiles('requirements.txt', 'requirements_optional.txt', 'requirements_test.txt') }}" >> $GITHUB_OUTPUT
- name: Set up Python ${{ env.DEFAULT_PYTHON }} - name: Set up Python ${{ env.DEFAULT_PYTHON }}
id: python id: python
uses: actions/setup-python@v5.2.0 uses: actions/setup-python@v5.3.0
with: with:
python-version: ${{ env.DEFAULT_PYTHON }} python-version: ${{ env.DEFAULT_PYTHON }}
- name: Restore Python virtual environment - name: Restore Python virtual environment
id: cache-venv id: cache-venv
uses: actions/cache@v4.0.2 uses: actions/cache@v4.1.2
with: with:
path: venv path: venv
# yamllint disable-line rule:line-length # yamllint disable-line rule:line-length
@ -302,20 +302,22 @@ jobs:
- name: Cache platformio - name: Cache platformio
if: github.ref == 'refs/heads/dev' if: github.ref == 'refs/heads/dev'
uses: actions/cache@v4.0.2 uses: actions/cache@v4.1.2
with: with:
path: ~/.platformio path: ~/.platformio
key: platformio-${{ matrix.pio_cache_key }} key: platformio-${{ matrix.pio_cache_key }}
- name: Cache platformio - name: Cache platformio
if: github.ref != 'refs/heads/dev' if: github.ref != 'refs/heads/dev'
uses: actions/cache/restore@v4.0.2 uses: actions/cache/restore@v4.1.2
with: with:
path: ~/.platformio path: ~/.platformio
key: platformio-${{ matrix.pio_cache_key }} key: platformio-${{ matrix.pio_cache_key }}
- name: Install clang-tidy - name: Install clang-tidy
run: sudo apt-get install clang-tidy-14 run: |
sudo apt-get update
sudo apt-get install clang-tidy-14
- name: Register problem matchers - name: Register problem matchers
run: | run: |
@ -397,7 +399,9 @@ jobs:
file: ${{ fromJson(needs.list-components.outputs.components) }} file: ${{ fromJson(needs.list-components.outputs.components) }}
steps: steps:
- name: Install dependencies - name: Install dependencies
run: sudo apt-get install libsdl2-dev run: |
sudo apt-get update
sudo apt-get install libsdl2-dev
- name: Check out code from GitHub - name: Check out code from GitHub
uses: actions/checkout@v4.1.7 uses: actions/checkout@v4.1.7
@ -451,7 +455,9 @@ jobs:
run: echo ${{ matrix.components }} run: echo ${{ matrix.components }}
- name: Install dependencies - name: Install dependencies
run: sudo apt-get install libsdl2-dev run: |
sudo apt-get update
sudo apt-get install libsdl2-dev
- name: Check out code from GitHub - name: Check out code from GitHub
uses: actions/checkout@v4.1.7 uses: actions/checkout@v4.1.7

View file

@ -53,7 +53,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v4.1.7 - uses: actions/checkout@v4.1.7
- name: Set up Python - name: Set up Python
uses: actions/setup-python@v5.2.0 uses: actions/setup-python@v5.3.0
with: with:
python-version: "3.x" python-version: "3.x"
- name: Set up python environment - name: Set up python environment
@ -85,7 +85,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v4.1.7 - uses: actions/checkout@v4.1.7
- name: Set up Python - name: Set up Python
uses: actions/setup-python@v5.2.0 uses: actions/setup-python@v5.3.0
with: with:
python-version: "3.9" python-version: "3.9"
@ -141,7 +141,7 @@ jobs:
echo name=$(cat /tmp/platform) >> $GITHUB_OUTPUT echo name=$(cat /tmp/platform) >> $GITHUB_OUTPUT
- name: Upload digests - name: Upload digests
uses: actions/upload-artifact@v4.4.0 uses: actions/upload-artifact@v4.4.3
with: with:
name: digests-${{ steps.sanitize.outputs.name }} name: digests-${{ steps.sanitize.outputs.name }}
path: /tmp/digests path: /tmp/digests

View file

@ -22,7 +22,7 @@ jobs:
path: lib/home-assistant path: lib/home-assistant
- name: Setup Python - name: Setup Python
uses: actions/setup-python@v5.2.0 uses: actions/setup-python@v5.3.0
with: with:
python-version: 3.12 python-version: 3.12

View file

@ -48,7 +48,9 @@ esphome/components/at581x/* @X-Ryl669
esphome/components/atc_mithermometer/* @ahpohl esphome/components/atc_mithermometer/* @ahpohl
esphome/components/atm90e26/* @danieltwagner esphome/components/atm90e26/* @danieltwagner
esphome/components/atm90e32/* @circuitsetup @descipher esphome/components/atm90e32/* @circuitsetup @descipher
esphome/components/audio/* @kahrendt
esphome/components/audio_dac/* @kbx81 esphome/components/audio_dac/* @kbx81
esphome/components/axs15231/* @clydebarrow
esphome/components/b_parasite/* @rbaron esphome/components/b_parasite/* @rbaron
esphome/components/ballu/* @bazuchan esphome/components/ballu/* @bazuchan
esphome/components/bang_bang/* @OttoWinter esphome/components/bang_bang/* @OttoWinter
@ -196,10 +198,11 @@ esphome/components/htu31d/* @betterengineering
esphome/components/hydreon_rgxx/* @functionpointer esphome/components/hydreon_rgxx/* @functionpointer
esphome/components/hyt271/* @Philippe12 esphome/components/hyt271/* @Philippe12
esphome/components/i2c/* @esphome/core esphome/components/i2c/* @esphome/core
esphome/components/i2c_device/* @gabest11
esphome/components/i2s_audio/* @jesserockz esphome/components/i2s_audio/* @jesserockz
esphome/components/i2s_audio/media_player/* @jesserockz esphome/components/i2s_audio/media_player/* @jesserockz
esphome/components/i2s_audio/microphone/* @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/iaqcore/* @yozik04
esphome/components/ili9xxx/* @clydebarrow @nielsnl68 esphome/components/ili9xxx/* @clydebarrow @nielsnl68
esphome/components/improv_base/* @esphome/core esphome/components/improv_base/* @esphome/core
@ -237,6 +240,7 @@ esphome/components/ltr_als_ps/* @latonita
esphome/components/lvgl/* @clydebarrow esphome/components/lvgl/* @clydebarrow
esphome/components/m5stack_8angle/* @rnauber esphome/components/m5stack_8angle/* @rnauber
esphome/components/matrix_keypad/* @ssieb esphome/components/matrix_keypad/* @ssieb
esphome/components/max17043/* @blacknell
esphome/components/max31865/* @DAVe3283 esphome/components/max31865/* @DAVe3283
esphome/components/max44009/* @berfenger esphome/components/max44009/* @berfenger
esphome/components/max6956/* @looping40 esphome/components/max6956/* @looping40
@ -324,7 +328,7 @@ esphome/components/pvvx_mithermometer/* @pasiz
esphome/components/pylontech/* @functionpointer esphome/components/pylontech/* @functionpointer
esphome/components/qmp6988/* @andrewpc esphome/components/qmp6988/* @andrewpc
esphome/components/qr_code/* @wjtje esphome/components/qr_code/* @wjtje
esphome/components/qspi_amoled/* @clydebarrow esphome/components/qspi_dbi/* @clydebarrow
esphome/components/qwiic_pir/* @kahrendt esphome/components/qwiic_pir/* @kahrendt
esphome/components/radon_eye_ble/* @jeffeb3 esphome/components/radon_eye_ble/* @jeffeb3
esphome/components/radon_eye_rd200/* @jeffeb3 esphome/components/radon_eye_rd200/* @jeffeb3
@ -373,7 +377,7 @@ esphome/components/smt100/* @piechade
esphome/components/sn74hc165/* @jesserockz esphome/components/sn74hc165/* @jesserockz
esphome/components/socket/* @esphome/core esphome/components/socket/* @esphome/core
esphome/components/sonoff_d1/* @anatoly-savchenkov esphome/components/sonoff_d1/* @anatoly-savchenkov
esphome/components/speaker/* @jesserockz esphome/components/speaker/* @jesserockz @kahrendt
esphome/components/spi/* @clydebarrow @esphome/core esphome/components/spi/* @clydebarrow @esphome/core
esphome/components/spi_device/* @clydebarrow esphome/components/spi_device/* @clydebarrow
esphome/components/spi_led_strip/* @clydebarrow esphome/components/spi_led_strip/* @clydebarrow
@ -403,6 +407,7 @@ esphome/components/sun/* @OttoWinter
esphome/components/sun_gtil2/* @Mat931 esphome/components/sun_gtil2/* @Mat931
esphome/components/switch/* @esphome/core esphome/components/switch/* @esphome/core
esphome/components/t6615/* @tylermenezes esphome/components/t6615/* @tylermenezes
esphome/components/tc74/* @sethgirvan
esphome/components/tca9548a/* @andreashergert1984 esphome/components/tca9548a/* @andreashergert1984
esphome/components/tca9555/* @mobrembski esphome/components/tca9555/* @mobrembski
esphome/components/tcl112/* @glmnet esphome/components/tcl112/* @glmnet

View file

@ -86,7 +86,7 @@ RUN \
pip3 install \ pip3 install \
--break-system-packages --no-cache-dir \ --break-system-packages --no-cache-dir \
# Keep platformio version in sync with requirements.txt # Keep platformio version in sync with requirements.txt
platformio==6.1.15 \ platformio==6.1.16 \
# Change some platformio settings # Change some platformio settings
&& platformio settings set enable_telemetry No \ && platformio settings set enable_telemetry No \
&& platformio settings set check_platformio_interval 1000000 \ && platformio settings set check_platformio_interval 1000000 \

View file

@ -1,6 +1,8 @@
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_ALL,
CONF_ANY,
CONF_AUTOMATION_ID, CONF_AUTOMATION_ID,
CONF_CONDITION, CONF_CONDITION,
CONF_COUNT, CONF_COUNT,
@ -73,6 +75,13 @@ def validate_potentially_and_condition(value):
return validate_condition(value) return validate_condition(value)
def validate_potentially_or_condition(value):
if isinstance(value, list):
with cv.remove_prepend_path(["or"]):
return validate_condition({"or": value})
return validate_condition(value)
DelayAction = cg.esphome_ns.class_("DelayAction", Action, cg.Component) DelayAction = cg.esphome_ns.class_("DelayAction", Action, cg.Component)
LambdaAction = cg.esphome_ns.class_("LambdaAction", Action) LambdaAction = cg.esphome_ns.class_("LambdaAction", Action)
IfAction = cg.esphome_ns.class_("IfAction", Action) IfAction = cg.esphome_ns.class_("IfAction", Action)
@ -166,6 +175,18 @@ async def or_condition_to_code(config, condition_id, template_arg, args):
return cg.new_Pvariable(condition_id, template_arg, conditions) return cg.new_Pvariable(condition_id, template_arg, conditions)
@register_condition("all", AndCondition, validate_condition_list)
async def all_condition_to_code(config, condition_id, template_arg, args):
conditions = await build_condition_list(config, template_arg, args)
return cg.new_Pvariable(condition_id, template_arg, conditions)
@register_condition("any", OrCondition, validate_condition_list)
async def any_condition_to_code(config, condition_id, template_arg, args):
conditions = await build_condition_list(config, template_arg, args)
return cg.new_Pvariable(condition_id, template_arg, conditions)
@register_condition("not", NotCondition, validate_potentially_and_condition) @register_condition("not", NotCondition, validate_potentially_and_condition)
async def not_condition_to_code(config, condition_id, template_arg, args): async def not_condition_to_code(config, condition_id, template_arg, args):
condition = await build_condition(config, template_arg, args) condition = await build_condition(config, template_arg, args)
@ -223,15 +244,21 @@ async def delay_action_to_code(config, action_id, template_arg, args):
IfAction, IfAction,
cv.All( cv.All(
{ {
cv.Required(CONF_CONDITION): validate_potentially_and_condition, cv.Exclusive(
CONF_CONDITION, CONF_CONDITION
): validate_potentially_and_condition,
cv.Exclusive(CONF_ANY, CONF_CONDITION): validate_potentially_or_condition,
cv.Exclusive(CONF_ALL, CONF_CONDITION): validate_potentially_and_condition,
cv.Optional(CONF_THEN): validate_action_list, cv.Optional(CONF_THEN): validate_action_list,
cv.Optional(CONF_ELSE): validate_action_list, cv.Optional(CONF_ELSE): validate_action_list,
}, },
cv.has_at_least_one_key(CONF_THEN, CONF_ELSE), cv.has_at_least_one_key(CONF_THEN, CONF_ELSE),
cv.has_at_least_one_key(CONF_CONDITION, CONF_ANY, CONF_ALL),
), ),
) )
async def if_action_to_code(config, action_id, template_arg, args): async def if_action_to_code(config, action_id, template_arg, args):
conditions = await build_condition(config[CONF_CONDITION], template_arg, args) cond_conf = next(el for el in config if el in (CONF_ANY, CONF_ALL, CONF_CONDITION))
conditions = await build_condition(config[cond_conf], template_arg, args)
var = cg.new_Pvariable(action_id, template_arg, conditions) var = cg.new_Pvariable(action_id, template_arg, conditions)
if CONF_THEN in config: if CONF_THEN in config:
actions = await build_action_list(config[CONF_THEN], template_arg, args) actions = await build_action_list(config[CONF_THEN], template_arg, args)

View file

@ -271,7 +271,8 @@ async def to_code(config):
pos += 1 pos += 1
elif config[CONF_TYPE] in ["RGB565", "TRANSPARENT_IMAGE"]: 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 pos = 0
for frameIndex in range(frames): for frameIndex in range(frames):
image.seek(frameIndex) image.seek(frameIndex)
@ -288,17 +289,13 @@ async def to_code(config):
G = g >> 2 G = g >> 2
B = b >> 3 B = b >> 3
rgb = (R << 11) | (G << 5) | B rgb = (R << 11) | (G << 5) | B
if transparent:
if rgb == 0x0020:
rgb = 0
if a < 0x80:
rgb = 0x0020
data[pos] = rgb >> 8 data[pos] = rgb >> 8
pos += 1 pos += 1
data[pos] = rgb & 0xFF data[pos] = rgb & 0xFF
pos += 1 pos += 1
if transparent:
data[pos] = a
pos += 1
elif config[CONF_TYPE] in ["BINARY", "TRANSPARENT_BINARY"]: elif config[CONF_TYPE] in ["BINARY", "TRANSPARENT_BINARY"]:
width8 = ((width + 7) // 8) * 8 width8 = ((width + 7) // 8) * 8

View file

@ -62,7 +62,7 @@ void Animation::set_frame(int frame) {
} }
void Animation::update_data_start_() { 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_; this->data_start_ = this->animation_data_start_ + image_size * this->current_frame_;
} }

View file

@ -0,0 +1,9 @@
import esphome.codegen as cg
import esphome.config_validation as cv
CODEOWNERS = ["@kahrendt"]
audio_ns = cg.esphome_ns.namespace("audio")
CONFIG_SCHEMA = cv.All(
cv.Schema({}),
)

View file

@ -0,0 +1,21 @@
#pragma once
#include <cstdint>
#include <stddef.h>
namespace esphome {
namespace audio {
struct AudioStreamInfo {
bool operator==(const AudioStreamInfo &rhs) const {
return (channels == rhs.channels) && (bits_per_sample == rhs.bits_per_sample) && (sample_rate == rhs.sample_rate);
}
bool operator!=(const AudioStreamInfo &rhs) const { return !operator==(rhs); }
size_t get_bytes_per_sample() const { return bits_per_sample / 8; }
uint8_t channels = 1;
uint8_t bits_per_sample = 16;
uint32_t sample_rate = 16000;
};
} // namespace audio
} // namespace esphome

View file

@ -0,0 +1,6 @@
import esphome.codegen as cg
CODEOWNERS = ["@clydebarrow"]
DEPENDENCIES = ["i2c"]
axs15231_ns = cg.esphome_ns.namespace("axs15231")

View file

@ -0,0 +1,36 @@
from esphome import pins
import esphome.codegen as cg
from esphome.components import i2c, touchscreen
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_RESET_PIN
from .. import axs15231_ns
AXS15231Touchscreen = axs15231_ns.class_(
"AXS15231Touchscreen",
touchscreen.Touchscreen,
i2c.I2CDevice,
)
CONFIG_SCHEMA = (
touchscreen.touchscreen_schema("50ms")
.extend(
{
cv.GenerateID(): cv.declare_id(AXS15231Touchscreen),
cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
}
)
.extend(i2c.i2c_device_schema(0x3B))
)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await touchscreen.register_touchscreen(var, config)
await i2c.register_i2c_device(var, config)
if interrupt_pin := config.get(CONF_INTERRUPT_PIN):
cg.add(var.set_interrupt_pin(await cg.gpio_pin_expression(interrupt_pin)))
if reset_pin := config.get(CONF_RESET_PIN):
cg.add(var.set_reset_pin(await cg.gpio_pin_expression(reset_pin)))

View file

@ -0,0 +1,64 @@
#include "axs15231_touchscreen.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome {
namespace axs15231 {
static const char *const TAG = "ax15231.touchscreen";
constexpr static const uint8_t AXS_READ_TOUCHPAD[11] = {0xb5, 0xab, 0xa5, 0x5a, 0x0, 0x0, 0x0, 0x8};
#define ERROR_CHECK(err) \
if ((err) != i2c::ERROR_OK) { \
this->status_set_warning("Failed to communicate"); \
return; \
}
void AXS15231Touchscreen::setup() {
ESP_LOGCONFIG(TAG, "Setting up AXS15231 Touchscreen...");
if (this->reset_pin_ != nullptr) {
this->reset_pin_->setup();
this->reset_pin_->digital_write(false);
delay(5);
this->reset_pin_->digital_write(true);
delay(10);
}
if (this->interrupt_pin_ != nullptr) {
this->interrupt_pin_->pin_mode(gpio::FLAG_INPUT);
this->interrupt_pin_->setup();
this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_FALLING_EDGE);
}
this->x_raw_max_ = this->display_->get_native_width();
this->y_raw_max_ = this->display_->get_native_height();
ESP_LOGCONFIG(TAG, "AXS15231 Touchscreen setup complete");
}
void AXS15231Touchscreen::update_touches() {
i2c::ErrorCode err;
uint8_t data[8]{};
err = this->write(AXS_READ_TOUCHPAD, sizeof(AXS_READ_TOUCHPAD), false);
ERROR_CHECK(err);
err = this->read(data, sizeof(data));
ERROR_CHECK(err);
this->status_clear_warning();
if (data[0] != 0) // no touches
return;
uint16_t x = encode_uint16(data[2] & 0xF, data[3]);
uint16_t y = encode_uint16(data[4] & 0xF, data[5]);
this->add_raw_touch_position_(0, x, y);
}
void AXS15231Touchscreen::dump_config() {
ESP_LOGCONFIG(TAG, "AXS15231 Touchscreen:");
LOG_I2C_DEVICE(this);
LOG_PIN(" Interrupt Pin: ", this->interrupt_pin_);
LOG_PIN(" Reset Pin: ", this->reset_pin_);
ESP_LOGCONFIG(TAG, " Width: %d", this->x_raw_max_);
ESP_LOGCONFIG(TAG, " Height: %d", this->y_raw_max_);
}
} // namespace axs15231
} // namespace esphome

View file

@ -0,0 +1,27 @@
#pragma once
#include "esphome/components/i2c/i2c.h"
#include "esphome/components/touchscreen/touchscreen.h"
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
namespace esphome {
namespace axs15231 {
class AXS15231Touchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice {
public:
void setup() override;
void dump_config() override;
void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; }
void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; }
protected:
void update_touches() override;
InternalGPIOPin *interrupt_pin_{};
GPIOPin *reset_pin_{};
};
} // namespace axs15231
} // namespace esphome

View file

@ -45,7 +45,7 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(CONF_SERVICE_UUID): esp32_ble_tracker.bt_uuid, cv.Optional(CONF_SERVICE_UUID): esp32_ble_tracker.bt_uuid,
cv.Optional(CONF_IBEACON_MAJOR): cv.uint16_t, cv.Optional(CONF_IBEACON_MAJOR): cv.uint16_t,
cv.Optional(CONF_IBEACON_MINOR): 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) .extend(esp32_ble_tracker.ESP_BLE_DEVICE_SCHEMA)
@ -79,7 +79,7 @@ async def to_code(config):
cg.add(var.set_service_uuid128(uuid128)) cg.add(var.set_service_uuid128(uuid128))
if ibeacon_uuid := config.get(CONF_IBEACON_UUID): 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)) cg.add(var.set_ibeacon_uuid(ibeacon_uuid))
if (ibeacon_major := config.get(CONF_IBEACON_MAJOR)) is not None: if (ibeacon_major := config.get(CONF_IBEACON_MAJOR)) is not None:

View file

@ -16,7 +16,7 @@ CODEOWNERS = ["@neffs", "@kbx81"]
DOMAIN = "bme68x_bsec2" DOMAIN = "bme68x_bsec2"
BSEC2_LIBRARY_VERSION = "v1.7.2502" BSEC2_LIBRARY_VERSION = "v1.8.2610"
CONF_ALGORITHM_OUTPUT = "algorithm_output" CONF_ALGORITHM_OUTPUT = "algorithm_output"
CONF_BME68X_BSEC2_ID = "bme68x_bsec2_id" CONF_BME68X_BSEC2_ID = "bme68x_bsec2_id"

View file

@ -244,7 +244,7 @@ void CSE7766Component::dump_config() {
LOG_SENSOR(" ", "Apparent Power", this->apparent_power_sensor_); LOG_SENSOR(" ", "Apparent Power", this->apparent_power_sensor_);
LOG_SENSOR(" ", "Reactive Power", this->reactive_power_sensor_); LOG_SENSOR(" ", "Reactive Power", this->reactive_power_sensor_);
LOG_SENSOR(" ", "Power Factor", this->power_factor_sensor_); LOG_SENSOR(" ", "Power Factor", this->power_factor_sensor_);
this->check_uart_settings(4800); this->check_uart_settings(4800, 1, uart::UART_CONFIG_PARITY_EVEN);
} }
} // namespace cse7766 } // namespace cse7766

View file

@ -1,11 +1,10 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins from esphome import pins
import esphome.codegen as cg
from esphome.components import i2c, touchscreen from esphome.components import i2c, touchscreen
from esphome.const import CONF_INTERRUPT_PIN, CONF_ID, CONF_RESET_PIN import esphome.config_validation as cv
from .. import cst816_ns from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_RESET_PIN
from .. import cst816_ns
CST816Touchscreen = cst816_ns.class_( CST816Touchscreen = cst816_ns.class_(
"CST816Touchscreen", "CST816Touchscreen",
@ -14,11 +13,14 @@ CST816Touchscreen = cst816_ns.class_(
) )
CST816ButtonListener = cst816_ns.class_("CST816ButtonListener") CST816ButtonListener = cst816_ns.class_("CST816ButtonListener")
CONF_SKIP_PROBE = "skip_probe"
CONFIG_SCHEMA = touchscreen.TOUCHSCREEN_SCHEMA.extend( CONFIG_SCHEMA = touchscreen.TOUCHSCREEN_SCHEMA.extend(
{ {
cv.GenerateID(): cv.declare_id(CST816Touchscreen), cv.GenerateID(): cv.declare_id(CST816Touchscreen),
cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema, cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema, cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
cv.Optional(CONF_SKIP_PROBE, default=False): cv.boolean,
} }
).extend(i2c.i2c_device_schema(0x15)) ).extend(i2c.i2c_device_schema(0x15))
@ -28,6 +30,7 @@ async def to_code(config):
await touchscreen.register_touchscreen(var, config) await touchscreen.register_touchscreen(var, config)
await i2c.register_i2c_device(var, config) await i2c.register_i2c_device(var, config)
cg.add(var.set_skip_probe(config[CONF_SKIP_PROBE]))
if interrupt_pin := config.get(CONF_INTERRUPT_PIN): if interrupt_pin := config.get(CONF_INTERRUPT_PIN):
cg.add(var.set_interrupt_pin(await cg.gpio_pin_expression(interrupt_pin))) cg.add(var.set_interrupt_pin(await cg.gpio_pin_expression(interrupt_pin)))
if reset_pin := config.get(CONF_RESET_PIN): if reset_pin := config.get(CONF_RESET_PIN):

View file

@ -8,11 +8,7 @@ void CST816Touchscreen::continue_setup_() {
this->interrupt_pin_->setup(); this->interrupt_pin_->setup();
this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_FALLING_EDGE); this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_FALLING_EDGE);
} }
if (!this->read_byte(REG_CHIP_ID, &this->chip_id_)) { if (this->read_byte(REG_CHIP_ID, &this->chip_id_)) {
this->mark_failed();
esph_log_e(TAG, "Failed to read chip id");
return;
}
switch (this->chip_id_) { switch (this->chip_id_) {
case CST820_CHIP_ID: case CST820_CHIP_ID:
case CST826_CHIP_ID: case CST826_CHIP_ID:
@ -23,17 +19,22 @@ void CST816Touchscreen::continue_setup_() {
break; break;
default: default:
this->mark_failed(); this->mark_failed();
esph_log_e(TAG, "Unknown chip ID 0x%02X", this->chip_id_); this->status_set_error(str_sprintf("Unknown chip ID 0x%02X", this->chip_id_).c_str());
return; return;
} }
this->write_byte(REG_IRQ_CTL, IRQ_EN_MOTION); this->write_byte(REG_IRQ_CTL, IRQ_EN_MOTION);
} else if (!this->skip_probe_) {
this->status_set_error("Failed to read chip id");
this->mark_failed();
return;
}
if (this->x_raw_max_ == this->x_raw_min_) { if (this->x_raw_max_ == this->x_raw_min_) {
this->x_raw_max_ = this->display_->get_native_width(); this->x_raw_max_ = this->display_->get_native_width();
} }
if (this->y_raw_max_ == this->y_raw_min_) { if (this->y_raw_max_ == this->y_raw_min_) {
this->y_raw_max_ = this->display_->get_native_height(); this->y_raw_max_ = this->display_->get_native_height();
} }
esph_log_config(TAG, "CST816 Touchscreen setup complete"); ESP_LOGCONFIG(TAG, "CST816 Touchscreen setup complete");
} }
void CST816Touchscreen::update_button_state_(bool state) { void CST816Touchscreen::update_button_state_(bool state) {
@ -45,7 +46,7 @@ void CST816Touchscreen::update_button_state_(bool state) {
} }
void CST816Touchscreen::setup() { void CST816Touchscreen::setup() {
esph_log_config(TAG, "Setting up CST816 Touchscreen..."); ESP_LOGCONFIG(TAG, "Setting up CST816 Touchscreen...");
if (this->reset_pin_ != nullptr) { if (this->reset_pin_ != nullptr) {
this->reset_pin_->setup(); this->reset_pin_->setup();
this->reset_pin_->digital_write(true); this->reset_pin_->digital_write(true);
@ -73,7 +74,7 @@ void CST816Touchscreen::update_touches() {
uint16_t x = encode_uint16(data[REG_XPOS_HIGH] & 0xF, data[REG_XPOS_LOW]); uint16_t x = encode_uint16(data[REG_XPOS_HIGH] & 0xF, data[REG_XPOS_LOW]);
uint16_t y = encode_uint16(data[REG_YPOS_HIGH] & 0xF, data[REG_YPOS_LOW]); uint16_t y = encode_uint16(data[REG_YPOS_HIGH] & 0xF, data[REG_YPOS_LOW]);
esph_log_v(TAG, "Read touch %d/%d", x, y); ESP_LOGV(TAG, "Read touch %d/%d", x, y);
if (x >= this->x_raw_max_) { if (x >= this->x_raw_max_) {
this->update_button_state_(true); this->update_button_state_(true);
} else { } else {

View file

@ -45,6 +45,7 @@ class CST816Touchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice
void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; } void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; }
void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; } void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; }
void set_skip_probe(bool skip_probe) { this->skip_probe_ = skip_probe; }
protected: protected:
void continue_setup_(); void continue_setup_();
@ -53,6 +54,7 @@ class CST816Touchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice
InternalGPIOPin *interrupt_pin_{}; InternalGPIOPin *interrupt_pin_{};
GPIOPin *reset_pin_{}; GPIOPin *reset_pin_{};
uint8_t chip_id_{}; uint8_t chip_id_{};
bool skip_probe_{}; // if set, do not expect to be able to probe the controller on the i2c bus.
std::vector<CST816ButtonListener *> button_listeners_; std::vector<CST816ButtonListener *> button_listeners_;
bool button_touched_{}; bool button_touched_{};
}; };

View file

@ -36,7 +36,8 @@ std::string DebugComponent::get_reset_reason_() {
break; break;
#if defined(USE_ESP32_VARIANT_ESP32) #if defined(USE_ESP32_VARIANT_ESP32)
case SW_RESET: case SW_RESET:
#elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) #elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || \
defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32C6)
case RTC_SW_SYS_RESET: case RTC_SW_SYS_RESET:
#endif #endif
reset_reason = "Software Reset Digital Core"; reset_reason = "Software Reset Digital Core";
@ -72,14 +73,16 @@ std::string DebugComponent::get_reset_reason_() {
case TGWDT_CPU_RESET: case TGWDT_CPU_RESET:
reset_reason = "Timer Group Reset CPU"; reset_reason = "Timer Group Reset CPU";
break; break;
#elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) #elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || \
defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32C6)
case TG0WDT_CPU_RESET: case TG0WDT_CPU_RESET:
reset_reason = "Timer Group 0 Reset CPU"; reset_reason = "Timer Group 0 Reset CPU";
break; break;
#endif #endif
#if defined(USE_ESP32_VARIANT_ESP32) #if defined(USE_ESP32_VARIANT_ESP32)
case SW_CPU_RESET: case SW_CPU_RESET:
#elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) #elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || \
defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32C6)
case RTC_SW_CPU_RESET: case RTC_SW_CPU_RESET:
#endif #endif
reset_reason = "Software Reset CPU"; reset_reason = "Software Reset CPU";
@ -98,27 +101,32 @@ std::string DebugComponent::get_reset_reason_() {
case RTCWDT_RTC_RESET: case RTCWDT_RTC_RESET:
reset_reason = "RTC Watch Dog Reset Digital Core And RTC Module"; reset_reason = "RTC Watch Dog Reset Digital Core And RTC Module";
break; break;
#if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) #if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) || \
defined(USE_ESP32_VARIANT_ESP32C6)
case TG1WDT_CPU_RESET: case TG1WDT_CPU_RESET:
reset_reason = "Timer Group 1 Reset CPU"; reset_reason = "Timer Group 1 Reset CPU";
break; break;
case SUPER_WDT_RESET: case SUPER_WDT_RESET:
reset_reason = "Super Watchdog Reset Digital Core And RTC Module"; reset_reason = "Super Watchdog Reset Digital Core And RTC Module";
break; break;
case GLITCH_RTC_RESET:
reset_reason = "Glitch Reset Digital Core And RTC Module";
break;
case EFUSE_RESET: case EFUSE_RESET:
reset_reason = "eFuse Reset Digital Core"; reset_reason = "eFuse Reset Digital Core";
break; break;
#endif #endif
#if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S3) #if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
case GLITCH_RTC_RESET:
reset_reason = "Glitch Reset Digital Core And RTC Module";
break;
#endif
#if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32C6)
case USB_UART_CHIP_RESET: case USB_UART_CHIP_RESET:
reset_reason = "USB UART Reset Digital Core"; reset_reason = "USB UART Reset Digital Core";
break; break;
case USB_JTAG_CHIP_RESET: case USB_JTAG_CHIP_RESET:
reset_reason = "USB JTAG Reset Digital Core"; reset_reason = "USB JTAG Reset Digital Core";
break; break;
#endif
#if defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S3)
case POWER_GLITCH_RESET: case POWER_GLITCH_RESET:
reset_reason = "Power Glitch Reset Digital Core And RTC Module"; reset_reason = "Power Glitch Reset Digital Core And RTC Module";
break; break;

View file

@ -156,6 +156,148 @@ void Display::filled_circle(int center_x, int center_y, int radius, Color color)
} }
} while (dx <= 0); } while (dx <= 0);
} }
void Display::filled_ring(int center_x, int center_y, int radius1, int radius2, Color color) {
int rmax = radius1 > radius2 ? radius1 : radius2;
int rmin = radius1 < radius2 ? radius1 : radius2;
int dxmax = -int32_t(rmax), dxmin = -int32_t(rmin);
int dymax = 0, dymin = 0;
int errmax = 2 - 2 * rmax, errmin = 2 - 2 * rmin;
int e2max, e2min;
do {
// 8 dots for borders
this->draw_pixel_at(center_x - dxmax, center_y + dymax, color);
this->draw_pixel_at(center_x + dxmax, center_y + dymax, color);
this->draw_pixel_at(center_x - dxmin, center_y + dymin, color);
this->draw_pixel_at(center_x + dxmin, center_y + dymin, color);
this->draw_pixel_at(center_x + dxmax, center_y - dymax, color);
this->draw_pixel_at(center_x - dxmax, center_y - dymax, color);
this->draw_pixel_at(center_x + dxmin, center_y - dymin, color);
this->draw_pixel_at(center_x - dxmin, center_y - dymin, color);
if (dymin < rmin) {
// two parts - four lines
int hline_width = -(dxmax - dxmin) + 1;
this->horizontal_line(center_x + dxmax, center_y + dymax, hline_width, color);
this->horizontal_line(center_x - dxmin, center_y + dymax, hline_width, color);
this->horizontal_line(center_x + dxmax, center_y - dymax, hline_width, color);
this->horizontal_line(center_x - dxmin, center_y - dymax, hline_width, color);
} else {
// one part - top and bottom
int hline_width = 2 * (-dxmax) + 1;
this->horizontal_line(center_x + dxmax, center_y + dymax, hline_width, color);
this->horizontal_line(center_x + dxmax, center_y - dymax, hline_width, color);
}
e2max = errmax;
// tune external
if (e2max < dymax) {
errmax += ++dymax * 2 + 1;
if (-dxmax == dymax && e2max <= dxmax) {
e2max = 0;
}
}
if (e2max > dxmax) {
errmax += ++dxmax * 2 + 1;
}
// tune internal
while (dymin < dymax && dymin < rmin) {
e2min = errmin;
if (e2min < dymin) {
errmin += ++dymin * 2 + 1;
if (-dxmin == dymin && e2min <= dxmin) {
e2min = 0;
}
}
if (e2min > dxmin) {
errmin += ++dxmin * 2 + 1;
}
}
} while (dxmax <= 0);
}
void Display::filled_gauge(int center_x, int center_y, int radius1, int radius2, int progress, Color color) {
int rmax = radius1 > radius2 ? radius1 : radius2;
int rmin = radius1 < radius2 ? radius1 : radius2;
int dxmax = -int32_t(rmax), dxmin = -int32_t(rmin), upd_dxmax, upd_dxmin;
int dymax = 0, dymin = 0;
int errmax = 2 - 2 * rmax, errmin = 2 - 2 * rmin;
int e2max, e2min;
progress = std::max(0, std::min(progress, 100)); // 0..100
int draw_progress = progress > 50 ? (100 - progress) : progress;
float tan_a = (progress == 50) ? 65535 : tan(float(draw_progress) * M_PI / 100); // slope
do {
// outer dots
this->draw_pixel_at(center_x + dxmax, center_y - dymax, color);
this->draw_pixel_at(center_x - dxmax, center_y - dymax, color);
if (dymin < rmin) { // side parts
int lhline_width = -(dxmax - dxmin) + 1;
if (progress >= 50) {
if (float(dymax) < float(-dxmax) * tan_a) {
upd_dxmax = ceil(float(dymax) / tan_a);
} else {
upd_dxmax = -dxmax;
}
this->horizontal_line(center_x + dxmax, center_y - dymax, lhline_width, color); // left
if (!dymax)
this->horizontal_line(center_x - dxmin, center_y, lhline_width, color); // right horizontal border
if (upd_dxmax > -dxmin) { // right
int rhline_width = (upd_dxmax + dxmin) + 1;
this->horizontal_line(center_x - dxmin, center_y - dymax,
rhline_width > lhline_width ? lhline_width : rhline_width, color);
}
} else {
if (float(dymin) > float(-dxmin) * tan_a) {
upd_dxmin = ceil(float(dymin) / tan_a);
} else {
upd_dxmin = -dxmin;
}
lhline_width = -(dxmax + upd_dxmin) + 1;
if (!dymax)
this->horizontal_line(center_x - dxmin, center_y, lhline_width, color); // right horizontal border
if (lhline_width > 0)
this->horizontal_line(center_x + dxmax, center_y - dymax, lhline_width, color);
}
} else { // top part
int hline_width = 2 * (-dxmax) + 1;
if (progress >= 50) {
if (dymax < float(-dxmax) * tan_a) {
upd_dxmax = ceil(float(dymax) / tan_a);
hline_width = -dxmax + upd_dxmax + 1;
}
} else {
if (dymax < float(-dxmax) * tan_a) {
upd_dxmax = ceil(float(dymax) / tan_a);
hline_width = -dxmax - upd_dxmax + 1;
} else
hline_width = 0;
}
if (hline_width > 0)
this->horizontal_line(center_x + dxmax, center_y - dymax, hline_width, color);
}
e2max = errmax;
if (e2max < dymax) {
errmax += ++dymax * 2 + 1;
if (-dxmax == dymax && e2max <= dxmax) {
e2max = 0;
}
}
if (e2max > dxmax) {
errmax += ++dxmax * 2 + 1;
}
while (dymin <= dymax && dymin <= rmin && dxmin <= 0) {
this->draw_pixel_at(center_x + dxmin, center_y - dymin, color);
this->draw_pixel_at(center_x - dxmin, center_y - dymin, color);
e2min = errmin;
if (e2min < dymin) {
errmin += ++dymin * 2 + 1;
if (-dxmin == dymin && e2min <= dxmin) {
e2min = 0;
}
}
if (e2min > dxmin) {
errmin += ++dxmin * 2 + 1;
}
}
} while (dxmax <= 0);
}
void HOT Display::triangle(int x1, int y1, int x2, int y2, int x3, int y3, Color color) { void HOT Display::triangle(int x1, int y1, int x2, int y2, int x3, int y3, Color color) {
this->line(x1, y1, x2, y2, color); this->line(x1, y1, x2, y2, color);
this->line(x1, y1, x3, y3, color); this->line(x1, y1, x3, y3, color);

View file

@ -285,6 +285,13 @@ class Display : public PollingComponent {
/// Fill a circle centered around [center_x,center_y] with the radius radius with the given color. /// Fill a circle centered around [center_x,center_y] with the radius radius with the given color.
void filled_circle(int center_x, int center_y, int radius, Color color = COLOR_ON); void filled_circle(int center_x, int center_y, int radius, Color color = COLOR_ON);
/// Fill a ring centered around [center_x,center_y] between two circles with the radius1 and radius2 with the given
/// color.
void filled_ring(int center_x, int center_y, int radius1, int radius2, Color color = COLOR_ON);
/// Fill a half-ring "gauge" centered around [center_x,center_y] between two circles with the radius1 and radius2
/// with he given color and filled up to 'progress' percent
void filled_gauge(int center_x, int center_y, int radius1, int radius2, int progress, Color color = COLOR_ON);
/// Draw the outline of a triangle contained between the points [x1,y1], [x2,y2] and [x3,y3] with the given color. /// Draw the outline of a triangle contained between the points [x1,y1], [x2,y2] and [x3,y3] with the given color.
void triangle(int x1, int y1, int x2, int y2, int x3, int y3, Color color = COLOR_ON); void triangle(int x1, int y1, int x2, int y2, int x3, int y3, Color color = COLOR_ON);

View file

@ -395,6 +395,13 @@ ARDUINO_FRAMEWORK_SCHEMA = cv.All(
cv.Optional(CONF_VERSION, default="recommended"): cv.string_strict, cv.Optional(CONF_VERSION, default="recommended"): cv.string_strict,
cv.Optional(CONF_SOURCE): cv.string_strict, cv.Optional(CONF_SOURCE): cv.string_strict,
cv.Optional(CONF_PLATFORM_VERSION): _parse_platform_version, 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, _arduino_check_versions,
@ -494,6 +501,9 @@ async def to_code(config):
conf = config[CONF_FRAMEWORK] conf = config[CONF_FRAMEWORK]
cg.add_platformio_option("platform", conf[CONF_PLATFORM_VERSION]) 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( add_extra_script(
"post", "post",
"post_build.py", "post_build.py",
@ -540,8 +550,6 @@ async def to_code(config):
for name, value in conf[CONF_SDKCONFIG_OPTIONS].items(): for name, value in conf[CONF_SDKCONFIG_OPTIONS].items():
add_idf_sdkconfig_option(name, RawSdkconfigValue(value)) 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): if conf[CONF_ADVANCED].get(CONF_IGNORE_EFUSE_MAC_CRC):
add_idf_sdkconfig_option("CONFIG_ESP_MAC_IGNORE_MAC_CRC_ERROR", True) add_idf_sdkconfig_option("CONFIG_ESP_MAC_IGNORE_MAC_CRC_ERROR", True)
if (framework_ver.major, framework_ver.minor) >= (4, 4): if (framework_ver.major, framework_ver.minor) >= (4, 4):

View file

@ -103,6 +103,173 @@ ESP32_BOARD_PINS = {
"LED": 13, "LED": 13,
"LED_BUILTIN": 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": { "adafruit_qtpy_esp32c3": {
"A0": 4, "A0": 4,
"A1": 3, "A1": 3,
@ -141,6 +308,26 @@ ESP32_BOARD_PINS = {
"BUTTON": 0, "BUTTON": 0,
"SWITCH": 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": { "adafruit_qtpy_esp32": {
"A0": 26, "A0": 26,
"A1": 25, "A1": 25,
@ -1068,7 +1255,18 @@ ESP32_BOARD_PINS = {
"_VBAT": 35, "_VBAT": 35,
}, },
"wemosbat": {"LED": 16}, "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": { "widora-air": {
"A1": 39, "A1": 39,
"A2": 35, "A2": 35,

View file

@ -40,6 +40,9 @@ static const esp_bt_controller_config_t BT_CONTROLLER_CONFIG = {
.controller_run_cpu = 0, .controller_run_cpu = 0,
.enable_qa_test = RUN_QA_TEST, .enable_qa_test = RUN_QA_TEST,
.enable_bqb_test = RUN_BQB_TEST, .enable_bqb_test = RUN_BQB_TEST,
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 3, 1)
// The following fields have been removed since ESP IDF version 5.3.1, see commit:
// https://github.com/espressif/esp-idf/commit/e761c1de8f9c0777829d597b4d5a33bb070a30a8
.enable_uart_hci = HCI_UART_EN, .enable_uart_hci = HCI_UART_EN,
.ble_hci_uart_port = DEFAULT_BT_LE_HCI_UART_PORT, .ble_hci_uart_port = DEFAULT_BT_LE_HCI_UART_PORT,
.ble_hci_uart_baud = DEFAULT_BT_LE_HCI_UART_BAUD, .ble_hci_uart_baud = DEFAULT_BT_LE_HCI_UART_BAUD,
@ -47,6 +50,7 @@ static const esp_bt_controller_config_t BT_CONTROLLER_CONFIG = {
.ble_hci_uart_stop_bits = DEFAULT_BT_LE_HCI_UART_STOP_BITS, .ble_hci_uart_stop_bits = DEFAULT_BT_LE_HCI_UART_STOP_BITS,
.ble_hci_uart_flow_ctrl = DEFAULT_BT_LE_HCI_UART_FLOW_CTRL, .ble_hci_uart_flow_ctrl = DEFAULT_BT_LE_HCI_UART_FLOW_CTRL,
.ble_hci_uart_uart_parity = DEFAULT_BT_LE_HCI_UART_PARITY, .ble_hci_uart_uart_parity = DEFAULT_BT_LE_HCI_UART_PARITY,
#endif
.enable_tx_cca = DEFAULT_BT_LE_TX_CCA_ENABLED, .enable_tx_cca = DEFAULT_BT_LE_TX_CCA_ENABLED,
.cca_rssi_thresh = 256 - DEFAULT_BT_LE_CCA_RSSI_THRESH, .cca_rssi_thresh = 256 - DEFAULT_BT_LE_CCA_RSSI_THRESH,
.sleep_en = NIMBLE_SLEEP_ENABLE, .sleep_en = NIMBLE_SLEEP_ENABLE,
@ -58,6 +62,9 @@ static const esp_bt_controller_config_t BT_CONTROLLER_CONFIG = {
.cpu_freq_mhz = CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ, .cpu_freq_mhz = CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ,
.ignore_wl_for_direct_adv = 0, .ignore_wl_for_direct_adv = 0,
.enable_pcl = DEFAULT_BT_LE_POWER_CONTROL_ENABLED, .enable_pcl = DEFAULT_BT_LE_POWER_CONTROL_ENABLED,
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 3)
.csa2_select = DEFAULT_BT_LE_50_FEATURE_SUPPORT,
#endif
.config_magic = CONFIG_MAGIC, .config_magic = CONFIG_MAGIC,
}; };

View file

@ -22,7 +22,7 @@ void ESP32RMTLEDStripLightOutput::setup() {
size_t buffer_size = this->get_buffer_size_(); size_t buffer_size = this->get_buffer_size_();
ExternalRAMAllocator<uint8_t> allocator(ExternalRAMAllocator<uint8_t>::ALLOW_FAILURE); RAMAllocator<uint8_t> allocator(this->use_psram_ ? 0 : RAMAllocator<uint8_t>::ALLOC_INTERNAL);
this->buf_ = allocator.allocate(buffer_size); this->buf_ = allocator.allocate(buffer_size);
if (this->buf_ == nullptr) { if (this->buf_ == nullptr) {
ESP_LOGE(TAG, "Cannot allocate LED buffer!"); ESP_LOGE(TAG, "Cannot allocate LED buffer!");
@ -37,7 +37,7 @@ void ESP32RMTLEDStripLightOutput::setup() {
return; return;
} }
ExternalRAMAllocator<rmt_item32_t> rmt_allocator(ExternalRAMAllocator<rmt_item32_t>::ALLOW_FAILURE); RAMAllocator<rmt_item32_t> rmt_allocator(this->use_psram_ ? 0 : RAMAllocator<rmt_item32_t>::ALLOC_INTERNAL);
this->rmt_buf_ = rmt_allocator.allocate(buffer_size * 8 + this->rmt_buf_ = rmt_allocator.allocate(buffer_size * 8 +
1); // 8 bits per byte, 1 rmt_item32_t per bit + 1 rmt_item32_t for reset 1); // 8 bits per byte, 1 rmt_item32_t per bit + 1 rmt_item32_t for reset

View file

@ -45,6 +45,7 @@ class ESP32RMTLEDStripLightOutput : public light::AddressableLight {
void set_num_leds(uint16_t num_leds) { this->num_leds_ = num_leds; } void set_num_leds(uint16_t num_leds) { this->num_leds_ = num_leds; }
void set_is_rgbw(bool is_rgbw) { this->is_rgbw_ = is_rgbw; } void set_is_rgbw(bool is_rgbw) { this->is_rgbw_ = is_rgbw; }
void set_is_wrgb(bool is_wrgb) { this->is_wrgb_ = is_wrgb; } void set_is_wrgb(bool is_wrgb) { this->is_wrgb_ = is_wrgb; }
void set_use_psram(bool use_psram) { this->use_psram_ = use_psram; }
/// Set a maximum refresh rate in µs as some lights do not like being updated too often. /// Set a maximum refresh rate in µs as some lights do not like being updated too often.
void set_max_refresh_rate(uint32_t interval_us) { this->max_refresh_rate_ = interval_us; } void set_max_refresh_rate(uint32_t interval_us) { this->max_refresh_rate_ = interval_us; }
@ -75,6 +76,7 @@ class ESP32RMTLEDStripLightOutput : public light::AddressableLight {
uint16_t num_leds_; uint16_t num_leds_;
bool is_rgbw_; bool is_rgbw_;
bool is_wrgb_; bool is_wrgb_;
bool use_psram_;
rmt_item32_t bit0_, bit1_, reset_; rmt_item32_t bit0_, bit1_, reset_;
RGBOrder rgb_order_; RGBOrder rgb_order_;

View file

@ -55,7 +55,7 @@ CHIPSETS = {
"SM16703": LEDStripTimings(300, 900, 900, 300, 0, 0), "SM16703": LEDStripTimings(300, 900, 900, 300, 0, 0),
} }
CONF_USE_PSRAM = "use_psram"
CONF_IS_WRGB = "is_wrgb" CONF_IS_WRGB = "is_wrgb"
CONF_BIT0_HIGH = "bit0_high" CONF_BIT0_HIGH = "bit0_high"
CONF_BIT0_LOW = "bit0_low" CONF_BIT0_LOW = "bit0_low"
@ -77,6 +77,7 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(CONF_CHIPSET): cv.one_of(*CHIPSETS, upper=True), cv.Optional(CONF_CHIPSET): cv.one_of(*CHIPSETS, upper=True),
cv.Optional(CONF_IS_RGBW, default=False): cv.boolean, cv.Optional(CONF_IS_RGBW, default=False): cv.boolean,
cv.Optional(CONF_IS_WRGB, default=False): cv.boolean, cv.Optional(CONF_IS_WRGB, default=False): cv.boolean,
cv.Optional(CONF_USE_PSRAM, default=True): cv.boolean,
cv.Inclusive( cv.Inclusive(
CONF_BIT0_HIGH, CONF_BIT0_HIGH,
"custom", "custom",
@ -145,6 +146,7 @@ async def to_code(config):
cg.add(var.set_rgb_order(config[CONF_RGB_ORDER])) cg.add(var.set_rgb_order(config[CONF_RGB_ORDER]))
cg.add(var.set_is_rgbw(config[CONF_IS_RGBW])) cg.add(var.set_is_rgbw(config[CONF_IS_RGBW]))
cg.add(var.set_is_wrgb(config[CONF_IS_WRGB])) cg.add(var.set_is_wrgb(config[CONF_IS_WRGB]))
cg.add(var.set_use_psram(config[CONF_USE_PSRAM]))
cg.add( cg.add(
var.set_rmt_channel( var.set_rmt_channel(

View file

@ -1,6 +1,6 @@
from esphome import automation from esphome import automation
import esphome.codegen as cg import esphome.codegen as cg
from esphome.components import mqtt from esphome.components import mqtt, web_server
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_DEVICE_CLASS, CONF_DEVICE_CLASS,
@ -11,6 +11,7 @@ from esphome.const import (
CONF_MQTT_ID, CONF_MQTT_ID,
CONF_ON_EVENT, CONF_ON_EVENT,
CONF_TRIGGER_ID, CONF_TRIGGER_ID,
CONF_WEB_SERVER,
DEVICE_CLASS_BUTTON, DEVICE_CLASS_BUTTON,
DEVICE_CLASS_DOORBELL, DEVICE_CLASS_DOORBELL,
DEVICE_CLASS_EMPTY, DEVICE_CLASS_EMPTY,
@ -40,7 +41,10 @@ EventTrigger = event_ns.class_("EventTrigger", automation.Trigger.template())
validate_device_class = cv.one_of(*DEVICE_CLASSES, lower=True, space="_") validate_device_class = cv.one_of(*DEVICE_CLASSES, lower=True, space="_")
EVENT_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend(cv.MQTT_COMPONENT_SCHEMA).extend( EVENT_SCHEMA = (
cv.ENTITY_BASE_SCHEMA.extend(web_server.WEBSERVER_SORTING_SCHEMA)
.extend(cv.MQTT_COMPONENT_SCHEMA)
.extend(
{ {
cv.OnlyWith(CONF_MQTT_ID, "mqtt"): cv.declare_id(mqtt.MQTTEventComponent), cv.OnlyWith(CONF_MQTT_ID, "mqtt"): cv.declare_id(mqtt.MQTTEventComponent),
cv.GenerateID(): cv.declare_id(Event), cv.GenerateID(): cv.declare_id(Event),
@ -52,6 +56,7 @@ EVENT_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend(cv.MQTT_COMPONENT_SCHEMA).extend(
), ),
} }
) )
)
_UNDEF = object() _UNDEF = object()
@ -97,6 +102,9 @@ async def setup_event_core_(var, config, *, event_types: list[str]):
mqtt_ = cg.new_Pvariable(mqtt_id, var) mqtt_ = cg.new_Pvariable(mqtt_id, var)
await mqtt.register_mqtt_component(mqtt_, config) await mqtt.register_mqtt_component(mqtt_, config)
if web_server_config := config.get(CONF_WEB_SERVER):
await web_server.add_entity_config(var, web_server_config)
async def register_event(var, config, *, event_types: list[str]): async def register_event(var, config, *, event_types: list[str]):
if not CORE.has_id(config[CONF_ID]): if not CORE.has_id(config[CONF_ID]):

View file

@ -98,13 +98,13 @@ def validate_pillow_installed(value):
except ImportError as err: except ImportError as err:
raise cv.Invalid( raise cv.Invalid(
"Please install the pillow python package to use this feature. " "Please install the pillow python package to use this feature. "
'(pip install "pillow==10.2.0")' '(pip install "pillow==10.4.0")'
) from err ) from err
if version.parse(PIL.__version__) != version.parse("10.2.0"): if version.parse(PIL.__version__) != version.parse("10.4.0"):
raise cv.Invalid( raise cv.Invalid(
"Please update your pillow installation to 10.2.0. " "Please update your pillow installation to 10.4.0. "
'(pip install "pillow==10.2.0")' '(pip install "pillow==10.4.0")'
) )
return value return value

View file

@ -16,7 +16,7 @@ CONFIG_SCHEMA = output.FLOAT_OUTPUT_SCHEMA.extend(
{ {
cv.GenerateID(): cv.declare_id(GP8403Output), cv.GenerateID(): cv.declare_id(GP8403Output),
cv.GenerateID(CONF_GP8403_ID): cv.use_id(GP8403), 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) ).extend(cv.COMPONENT_SCHEMA)

View file

@ -16,7 +16,7 @@ from .const import KEY_HOST
from .gpio import host_pin_to_code # noqa from .gpio import host_pin_to_code # noqa
CODEOWNERS = ["@esphome/core", "@clydebarrow"] CODEOWNERS = ["@esphome/core", "@clydebarrow"]
AUTO_LOAD = ["network"] AUTO_LOAD = ["network", "preferences"]
def set_core_data(config): def set_core_data(config):

View file

@ -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)

View file

@ -0,0 +1,17 @@
#include "i2c_device.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#include <cinttypes>
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

View file

@ -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

View file

@ -16,7 +16,8 @@ from .. import (
register_i2s_audio_component, register_i2s_audio_component,
) )
CODEOWNERS = ["@jesserockz"] AUTO_LOAD = ["audio"]
CODEOWNERS = ["@jesserockz", "@kahrendt"]
DEPENDENCIES = ["i2s_audio"] DEPENDENCIES = ["i2s_audio"]
I2SAudioSpeaker = i2s_audio_ns.class_( I2SAudioSpeaker = i2s_audio_ns.class_(
@ -72,7 +73,7 @@ BASE_SCHEMA = (
.extend( .extend(
{ {
cv.Optional( cv.Optional(
CONF_TIMEOUT, default="100ms" CONF_TIMEOUT, default="500ms"
): cv.positive_time_period_milliseconds, ): cv.positive_time_period_milliseconds,
} }
) )

View file

@ -4,6 +4,8 @@
#include <driver/i2s.h> #include <driver/i2s.h>
#include "esphome/components/audio/audio.h"
#include "esphome/core/application.h" #include "esphome/core/application.h"
#include "esphome/core/hal.h" #include "esphome/core/hal.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
@ -11,186 +13,342 @@
namespace esphome { namespace esphome {
namespace i2s_audio { namespace i2s_audio {
static const size_t BUFFER_COUNT = 20; static const size_t DMA_BUFFER_SIZE = 512;
static const size_t DMA_BUFFERS_COUNT = 4;
static const size_t FRAMES_IN_ALL_DMA_BUFFERS = DMA_BUFFER_SIZE * DMA_BUFFERS_COUNT;
static const size_t RING_BUFFER_SAMPLES = 8192;
static const size_t TASK_DELAY_MS = 10;
static const size_t TASK_STACK_SIZE = 4096;
static const ssize_t TASK_PRIORITY = 23;
static const char *const TAG = "i2s_audio.speaker"; static const char *const TAG = "i2s_audio.speaker";
enum SpeakerEventGroupBits : uint32_t {
COMMAND_START = (1 << 0), // Starts the main task purpose
COMMAND_STOP = (1 << 1), // stops the main task
COMMAND_STOP_GRACEFULLY = (1 << 2), // Stops the task once all data has been written
MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE = (1 << 5), // Locks the ring buffer when not set
STATE_STARTING = (1 << 10),
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),
ERR_ESP_INVALID_SIZE = (1 << 18),
ERR_ESP_NO_MEM = (1 << 19),
ERR_ESP_FAIL = (1 << 20),
ALL_ERR_ESP_BITS = ERR_ESP_INVALID_STATE | ERR_ESP_INVALID_ARG | ERR_ESP_INVALID_SIZE | ERR_ESP_NO_MEM | ERR_ESP_FAIL,
ALL_BITS = 0x00FFFFFF, // All valid FreeRTOS event group bits
};
// Translates a SpeakerEventGroupBits ERR_ESP bit to the coressponding esp_err_t
static esp_err_t err_bit_to_esp_err(uint32_t bit) {
switch (bit) {
case SpeakerEventGroupBits::ERR_ESP_INVALID_STATE:
return ESP_ERR_INVALID_STATE;
case SpeakerEventGroupBits::ERR_ESP_INVALID_ARG:
return ESP_ERR_INVALID_ARG;
case SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE:
return ESP_ERR_INVALID_SIZE;
case SpeakerEventGroupBits::ERR_ESP_NO_MEM:
return ESP_ERR_NO_MEM;
default:
return ESP_FAIL;
}
}
/// @brief Multiplies the input array of Q15 numbers by a Q15 constant factor
///
/// Based on `dsps_mulc_s16_ansi` from the esp-dsp library:
/// https://github.com/espressif/esp-dsp/blob/master/modules/math/mulc/fixed/dsps_mulc_s16_ansi.c
/// (accessed on 2024-09-30).
/// @param input Array of Q15 numbers
/// @param output Array of Q15 numbers
/// @param len Length of array
/// @param c Q15 constant factor
static void q15_multiplication(const int16_t *input, int16_t *output, size_t len, int16_t c) {
for (int i = 0; i < len; i++) {
int32_t acc = (int32_t) input[i] * (int32_t) c;
output[i] = (int16_t) (acc >> 15);
}
}
// Lists the Q15 fixed point scaling factor for volume reduction.
// Has 100 values representing silence and a reduction [49, 48.5, ... 0.5, 0] dB.
// dB to PCM scaling factor formula: floating_point_scale_factor = 2^(-db/6.014)
// float to Q15 fixed point formula: q15_scale_factor = floating_point_scale_factor * 2^(15)
static const std::vector<int16_t> Q15_VOLUME_SCALING_FACTORS = {
0, 116, 122, 130, 137, 146, 154, 163, 173, 183, 194, 206, 218, 231, 244,
259, 274, 291, 308, 326, 345, 366, 388, 411, 435, 461, 488, 517, 548, 580,
615, 651, 690, 731, 774, 820, 868, 920, 974, 1032, 1094, 1158, 1227, 1300, 1377,
1459, 1545, 1637, 1734, 1837, 1946, 2061, 2184, 2313, 2450, 2596, 2750, 2913, 3085, 3269,
3462, 3668, 3885, 4116, 4360, 4619, 4893, 5183, 5490, 5816, 6161, 6527, 6914, 7324, 7758,
8218, 8706, 9222, 9770, 10349, 10963, 11613, 12302, 13032, 13805, 14624, 15491, 16410, 17384, 18415,
19508, 20665, 21891, 23189, 24565, 26022, 27566, 29201, 30933, 32767};
void I2SAudioSpeaker::setup() { void I2SAudioSpeaker::setup() {
ESP_LOGCONFIG(TAG, "Setting up I2S Audio Speaker..."); ESP_LOGCONFIG(TAG, "Setting up I2S Audio Speaker...");
this->buffer_queue_ = xQueueCreate(BUFFER_COUNT, sizeof(DataEvent)); if (this->event_group_ == nullptr) {
if (this->buffer_queue_ == nullptr) { this->event_group_ = xEventGroupCreate();
ESP_LOGE(TAG, "Failed to create buffer queue");
this->mark_failed();
return;
} }
this->event_queue_ = xQueueCreate(BUFFER_COUNT, sizeof(TaskEvent)); if (this->event_group_ == nullptr) {
if (this->event_queue_ == nullptr) { ESP_LOGE(TAG, "Failed to create event group");
ESP_LOGE(TAG, "Failed to create event queue");
this->mark_failed(); this->mark_failed();
return; return;
} }
} }
void I2SAudioSpeaker::start() { void I2SAudioSpeaker::loop() {
if (this->is_failed()) { uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
ESP_LOGE(TAG, "Cannot start audio, speaker failed to setup");
return; if (event_group_bits & SpeakerEventGroupBits::STATE_STARTING) {
} ESP_LOGD(TAG, "Starting Speaker");
if (this->task_created_) {
ESP_LOGW(TAG, "Called start while task has been already created.");
return;
}
this->state_ = speaker::STATE_STARTING; this->state_ = speaker::STATE_STARTING;
xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::STATE_STARTING);
} }
void I2SAudioSpeaker::start_() { if (event_group_bits & SpeakerEventGroupBits::STATE_RUNNING) {
if (this->task_created_) { ESP_LOGD(TAG, "Started Speaker");
return; this->state_ = speaker::STATE_RUNNING;
xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::STATE_RUNNING);
this->status_clear_warning();
this->status_clear_error();
}
if (event_group_bits & SpeakerEventGroupBits::STATE_STOPPING) {
ESP_LOGD(TAG, "Stopping Speaker");
this->state_ = speaker::STATE_STOPPING;
xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::STATE_STOPPING);
}
if (event_group_bits & SpeakerEventGroupBits::STATE_STOPPED) {
if (!this->task_created_) {
ESP_LOGD(TAG, "Stopped Speaker");
this->state_ = speaker::STATE_STOPPED;
xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::ALL_BITS);
this->speaker_task_handle_ = nullptr;
} }
if (!this->parent_->try_lock()) {
return; // Waiting for another i2s component to return lock
} }
xTaskCreate(I2SAudioSpeaker::player_task, "speaker_task", 8192, (void *) this, 1, &this->player_task_handle_); if (event_group_bits & SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START) {
this->task_created_ = true; this->status_set_error("Failed to start speaker task");
xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START);
} }
template<typename a, typename b> const uint8_t *convert_data_format(const a *from, b *to, size_t &bytes, bool repeat) { if (event_group_bits & SpeakerEventGroupBits::ERR_INVALID_FORMAT) {
if (sizeof(a) == sizeof(b) && !repeat) { this->status_set_error("Failed to adjust I2S bus to match the incoming audio");
return reinterpret_cast<const uint8_t *>(from); ESP_LOGE(TAG,
} "Incompatible audio format: sample rate = %" PRIu32 ", channels = %" PRIu8 ", bits per sample = %" PRIu8,
const b *result = to; this->audio_stream_info_.sample_rate, this->audio_stream_info_.channels,
for (size_t i = 0; i < bytes; i += sizeof(a)) { this->audio_stream_info_.bits_per_sample);
b value = static_cast<b>(*from++) << (sizeof(b) - sizeof(a)) * 8;
*to++ = value;
if (repeat)
*to++ = value;
}
bytes *= (sizeof(b) / sizeof(a)) * (repeat ? 2 : 1); // NOLINT
return reinterpret_cast<const uint8_t *>(result);
} }
void I2SAudioSpeaker::player_task(void *params) { if (event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS) {
I2SAudioSpeaker *this_speaker = (I2SAudioSpeaker *) params; 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)));
TaskEvent event; this->status_set_warning();
event.type = TaskEventType::STARTING;
xQueueSend(this_speaker->event_queue_, &event, portMAX_DELAY);
i2s_driver_config_t config = {
.mode = (i2s_mode_t) (this_speaker->i2s_mode_ | I2S_MODE_TX),
.sample_rate = this_speaker->sample_rate_,
.bits_per_sample = this_speaker->bits_per_sample_,
.channel_format = this_speaker->channel_,
.communication_format = this_speaker->i2s_comm_fmt_,
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
.dma_buf_count = 8,
.dma_buf_len = 256,
.use_apll = this_speaker->use_apll_,
.tx_desc_auto_clear = true,
.fixed_mclk = 0,
.mclk_multiple = I2S_MCLK_MULTIPLE_256,
.bits_per_chan = this_speaker->bits_per_channel_,
};
#if SOC_I2S_SUPPORTS_DAC
if (this_speaker->internal_dac_mode_ != I2S_DAC_CHANNEL_DISABLE) {
config.mode = (i2s_mode_t) (config.mode | I2S_MODE_DAC_BUILT_IN);
} }
}
void I2SAudioSpeaker::set_volume(float volume) {
this->volume_ = volume;
#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 #endif
{
esp_err_t err = i2s_driver_install(this_speaker->parent_->get_port(), &config, 0, nullptr); // Fallback to software volume control by using a Q15 fixed point scaling factor
if (err != ESP_OK) { ssize_t decibel_index = remap<ssize_t, float>(volume, 0.0f, 1.0f, 0, Q15_VOLUME_SCALING_FACTORS.size() - 1);
event.type = TaskEventType::WARNING; this->q15_volume_factor_ = Q15_VOLUME_SCALING_FACTORS[decibel_index];
event.err = err;
xQueueSend(this_speaker->event_queue_, &event, 0);
event.type = TaskEventType::STOPPED;
xQueueSend(this_speaker->event_queue_, &event, 0);
while (true) {
delay(10);
} }
} }
#if SOC_I2S_SUPPORTS_DAC void I2SAudioSpeaker::set_mute_state(bool mute_state) {
if (this_speaker->internal_dac_mode_ == I2S_DAC_CHANNEL_DISABLE) { this->mute_state_ = mute_state;
#endif #ifdef USE_AUDIO_DAC
i2s_pin_config_t pin_config = this_speaker->parent_->get_pin_config(); if (this->audio_dac_) {
pin_config.data_out_num = this_speaker->dout_pin_; if (mute_state) {
this->audio_dac_->set_mute_on();
i2s_set_pin(this_speaker->parent_->get_port(), &pin_config);
#if SOC_I2S_SUPPORTS_DAC
} else { } else {
i2s_set_dac_mode(this_speaker->internal_dac_mode_); this->audio_dac_->set_mute_off();
} }
} else
#endif #endif
{
DataEvent data_event; if (mute_state) {
// Fallback to software volume control and scale by 0
event.type = TaskEventType::STARTED; this->q15_volume_factor_ = 0;
xQueueSend(this_speaker->event_queue_, &event, portMAX_DELAY); } else {
// Revert to previous volume when unmuting
int32_t buffer[BUFFER_SIZE]; this->set_volume(this->volume_);
while (true) {
if (xQueueReceive(this_speaker->buffer_queue_, &data_event, this_speaker->timeout_ / portTICK_PERIOD_MS) !=
pdTRUE) {
break; // End of audio from main thread
} }
if (data_event.stop) { }
// Stop signal from main thread }
xQueueReset(this_speaker->buffer_queue_); // Flush queue
size_t I2SAudioSpeaker::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
if (this->is_failed()) {
ESP_LOGE(TAG, "Cannot play audio, speaker failed to setup");
return 0;
}
if (this->state_ != speaker::STATE_RUNNING && this->state_ != speaker::STATE_STARTING) {
this->start();
}
// Wait for the ring buffer to be available
uint32_t event_bits =
xEventGroupWaitBits(this->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE, pdFALSE,
pdFALSE, pdMS_TO_TICKS(TASK_DELAY_MS));
if (event_bits & SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE) {
// Ring buffer is available to write
// Lock the ring buffer, write to it, then unlock it
xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE);
size_t bytes_written = this->audio_ring_buffer_->write_without_replacement((void *) data, length, ticks_to_wait);
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE);
return bytes_written;
}
return 0;
}
bool I2SAudioSpeaker::has_buffered_data() const {
if (this->audio_ring_buffer_ != nullptr) {
return this->audio_ring_buffer_->available() > 0;
}
return false;
}
void I2SAudioSpeaker::speaker_task(void *params) {
I2SAudioSpeaker *this_speaker = (I2SAudioSpeaker *) params;
uint32_t event_group_bits =
xEventGroupWaitBits(this_speaker->event_group_,
SpeakerEventGroupBits::COMMAND_START | SpeakerEventGroupBits::COMMAND_STOP |
SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY, // Bit message to read
pdTRUE, // Clear the bits on exit
pdFALSE, // Don't wait for all the bits,
portMAX_DELAY); // Block indefinitely until a bit is set
if (event_group_bits & (SpeakerEventGroupBits::COMMAND_STOP | SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY)) {
// Received a stop signal before the task was requested to start
this_speaker->delete_task_(0);
}
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STARTING);
audio::AudioStreamInfo audio_stream_info = this_speaker->audio_stream_info_;
const ssize_t bytes_per_sample = audio_stream_info.get_bytes_per_sample();
const uint8_t number_of_channels = audio_stream_info.channels;
const size_t dma_buffers_size = FRAMES_IN_ALL_DMA_BUFFERS * bytes_per_sample * number_of_channels;
if (this_speaker->send_esp_err_to_event_group_(
this_speaker->allocate_buffers_(dma_buffers_size, RING_BUFFER_SAMPLES * bytes_per_sample))) {
// Failed to allocate buffers
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
this_speaker->delete_task_(dma_buffers_size);
}
if (this_speaker->send_esp_err_to_event_group_(this_speaker->start_i2s_driver_())) {
// Failed to start I2S driver
this_speaker->delete_task_(dma_buffers_size);
} else {
// Ring buffer is allocated, so indicate its can be written to
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE);
}
if (!this_speaker->send_esp_err_to_event_group_(this_speaker->reconfigure_i2s_stream_info_(audio_stream_info))) {
// Successfully set the I2S stream info, ready to write audio data to the I2S port
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_RUNNING);
bool stop_gracefully = false;
uint32_t last_data_received_time = millis();
while ((millis() - last_data_received_time) <= this_speaker->timeout_) {
event_group_bits = xEventGroupGetBits(this_speaker->event_group_);
if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP) {
break; break;
} }
if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY) {
stop_gracefully = true;
}
const uint8_t *data = data_event.data; size_t bytes_to_read = dma_buffers_size;
size_t remaining = data_event.len; size_t bytes_read = this_speaker->audio_ring_buffer_->read((void *) this_speaker->data_buffer_, bytes_to_read,
switch (this_speaker->bits_per_sample_) { pdMS_TO_TICKS(TASK_DELAY_MS));
case I2S_BITS_PER_SAMPLE_8BIT:
case I2S_BITS_PER_SAMPLE_16BIT: { if (bytes_read > 0) {
data = convert_data_format(reinterpret_cast<const int16_t *>(data), reinterpret_cast<int16_t *>(buffer), last_data_received_time = millis();
remaining, this_speaker->channel_ == I2S_CHANNEL_FMT_ALL_LEFT); size_t bytes_written = 0;
if ((audio_stream_info.bits_per_sample == 16) && (this_speaker->q15_volume_factor_ < INT16_MAX)) {
// Scale samples by the volume factor in place
q15_multiplication((int16_t *) this_speaker->data_buffer_, (int16_t *) this_speaker->data_buffer_,
bytes_read / sizeof(int16_t), this_speaker->q15_volume_factor_);
}
if (audio_stream_info.bits_per_sample == (uint8_t) this_speaker->bits_per_sample_) {
i2s_write(this_speaker->parent_->get_port(), this_speaker->data_buffer_, bytes_read, &bytes_written,
portMAX_DELAY);
} else if (audio_stream_info.bits_per_sample < (uint8_t) this_speaker->bits_per_sample_) {
i2s_write_expand(this_speaker->parent_->get_port(), this_speaker->data_buffer_, bytes_read,
audio_stream_info.bits_per_sample, this_speaker->bits_per_sample_, &bytes_written,
portMAX_DELAY);
}
if (bytes_written != bytes_read) {
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE);
}
} else {
// No data received
if (stop_gracefully) {
break; break;
} }
case I2S_BITS_PER_SAMPLE_24BIT:
case I2S_BITS_PER_SAMPLE_32BIT: {
data = convert_data_format(reinterpret_cast<const int16_t *>(data), reinterpret_cast<int32_t *>(buffer),
remaining, this_speaker->channel_ == I2S_CHANNEL_FMT_ALL_LEFT);
break;
}
}
while (remaining != 0) {
size_t bytes_written;
esp_err_t err =
i2s_write(this_speaker->parent_->get_port(), data, remaining, &bytes_written, (32 / portTICK_PERIOD_MS));
if (err != ESP_OK) {
event = {.type = TaskEventType::WARNING, .err = err};
if (xQueueSend(this_speaker->event_queue_, &event, 10 / portTICK_PERIOD_MS) != pdTRUE) {
ESP_LOGW(TAG, "Failed to send WARNING event");
}
continue;
}
data += bytes_written;
remaining -= bytes_written;
}
}
event.type = TaskEventType::STOPPING;
if (xQueueSend(this_speaker->event_queue_, &event, 10 / portTICK_PERIOD_MS) != pdTRUE) {
ESP_LOGW(TAG, "Failed to send STOPPING event");
}
i2s_zero_dma_buffer(this_speaker->parent_->get_port()); 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());
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STOPPING);
i2s_stop(this_speaker->parent_->get_port());
i2s_driver_uninstall(this_speaker->parent_->get_port()); i2s_driver_uninstall(this_speaker->parent_->get_port());
event.type = TaskEventType::STOPPED; this_speaker->parent_->unlock();
if (xQueueSend(this_speaker->event_queue_, &event, 10 / portTICK_PERIOD_MS) != pdTRUE) { this_speaker->delete_task_(dma_buffers_size);
ESP_LOGW(TAG, "Failed to send STOPPED event");
} }
while (true) { void I2SAudioSpeaker::start() {
delay(10); if (this->is_failed() || this->status_has_error())
return;
if ((this->state_ == speaker::STATE_STARTING) || (this->state_ == speaker::STATE_RUNNING))
return;
if (this->speaker_task_handle_ == nullptr) {
xTaskCreate(I2SAudioSpeaker::speaker_task, "speaker_task", TASK_STACK_SIZE, (void *) this, TASK_PRIORITY,
&this->speaker_task_handle_);
}
if (this->speaker_task_handle_ != nullptr) {
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_START);
this->task_created_ = true;
} else {
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START);
} }
} }
@ -203,92 +361,169 @@ void I2SAudioSpeaker::stop_(bool wait_on_empty) {
return; return;
if (this->state_ == speaker::STATE_STOPPED) if (this->state_ == speaker::STATE_STOPPED)
return; return;
if (this->state_ == speaker::STATE_STARTING) {
this->state_ = speaker::STATE_STOPPED;
return;
}
this->state_ = speaker::STATE_STOPPING;
DataEvent data;
data.stop = true;
if (wait_on_empty) { if (wait_on_empty) {
xQueueSend(this->buffer_queue_, &data, portMAX_DELAY); xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY);
} else { } else {
xQueueSendToFront(this->buffer_queue_, &data, portMAX_DELAY); xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP);
} }
} }
void I2SAudioSpeaker::watch_() { bool I2SAudioSpeaker::send_esp_err_to_event_group_(esp_err_t err) {
TaskEvent event; switch (err) {
if (xQueueReceive(this->event_queue_, &event, 0) == pdTRUE) { case ESP_OK:
switch (event.type) { return false;
case TaskEventType::STARTING: case ESP_ERR_INVALID_STATE:
ESP_LOGD(TAG, "Starting I2S Audio Speaker"); xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_STATE);
break; return true;
case TaskEventType::STARTED: case ESP_ERR_INVALID_ARG:
ESP_LOGD(TAG, "Started I2S Audio Speaker"); xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_ARG);
this->state_ = speaker::STATE_RUNNING; return true;
this->status_clear_warning(); case ESP_ERR_INVALID_SIZE:
break; xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE);
case TaskEventType::STOPPING: return true;
ESP_LOGD(TAG, "Stopping I2S Audio Speaker"); case ESP_ERR_NO_MEM:
break; xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
case TaskEventType::STOPPED: return true;
this->state_ = speaker::STATE_STOPPED; default:
vTaskDelete(this->player_task_handle_); xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_FAIL);
this->task_created_ = false; return true;
this->player_task_handle_ = nullptr; }
}
esp_err_t I2SAudioSpeaker::allocate_buffers_(size_t data_buffer_size, size_t ring_buffer_size) {
if (this->data_buffer_ == nullptr) {
// Allocate data buffer for temporarily storing audio from the ring buffer before writing to the I2S bus
ExternalRAMAllocator<uint8_t> allocator(ExternalRAMAllocator<uint8_t>::ALLOW_FAILURE);
this->data_buffer_ = allocator.allocate(data_buffer_size);
}
if (this->data_buffer_ == nullptr) {
return ESP_ERR_NO_MEM;
}
if (this->audio_ring_buffer_ == nullptr) {
// Allocate ring buffer
this->audio_ring_buffer_ = RingBuffer::create(ring_buffer_size);
}
if (this->audio_ring_buffer_ == nullptr) {
return ESP_ERR_NO_MEM;
}
return ESP_OK;
}
esp_err_t I2SAudioSpeaker::start_i2s_driver_() {
if (!this->parent_->try_lock()) {
return ESP_ERR_INVALID_STATE;
}
i2s_driver_config_t config = {
.mode = (i2s_mode_t) (this->i2s_mode_ | I2S_MODE_TX),
.sample_rate = this->sample_rate_,
.bits_per_sample = this->bits_per_sample_,
.channel_format = this->channel_,
.communication_format = this->i2s_comm_fmt_,
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
.dma_buf_count = DMA_BUFFERS_COUNT,
.dma_buf_len = DMA_BUFFER_SIZE,
.use_apll = this->use_apll_,
.tx_desc_auto_clear = true,
.fixed_mclk = I2S_PIN_NO_CHANGE,
.mclk_multiple = I2S_MCLK_MULTIPLE_256,
.bits_per_chan = this->bits_per_channel_,
#if SOC_I2S_SUPPORTS_TDM
.chan_mask = (i2s_channel_t) (I2S_TDM_ACTIVE_CH0 | I2S_TDM_ACTIVE_CH1),
.total_chan = 2,
.left_align = false,
.big_edin = false,
.bit_order_msb = false,
.skip_msk = false,
#endif
};
#if SOC_I2S_SUPPORTS_DAC
if (this->internal_dac_mode_ != I2S_DAC_CHANNEL_DISABLE) {
config.mode = (i2s_mode_t) (config.mode | I2S_MODE_DAC_BUILT_IN);
}
#endif
esp_err_t err = i2s_driver_install(this->parent_->get_port(), &config, 0, nullptr);
if (err != ESP_OK) {
// Failed to install the driver, so unlock the I2S port
this->parent_->unlock(); this->parent_->unlock();
xQueueReset(this->buffer_queue_); return err;
ESP_LOGD(TAG, "Stopped I2S Audio Speaker");
break;
case TaskEventType::WARNING:
ESP_LOGW(TAG, "Error writing to I2S: %s", esp_err_to_name(event.err));
this->status_set_warning();
break;
}
}
} }
void I2SAudioSpeaker::loop() { #if SOC_I2S_SUPPORTS_DAC
switch (this->state_) { if (this->internal_dac_mode_ == I2S_DAC_CHANNEL_DISABLE) {
case speaker::STATE_STARTING: #endif
this->start_(); i2s_pin_config_t pin_config = this->parent_->get_pin_config();
[[fallthrough]]; pin_config.data_out_num = this->dout_pin_;
case speaker::STATE_RUNNING:
case speaker::STATE_STOPPING: err = i2s_set_pin(this->parent_->get_port(), &pin_config);
this->watch_(); #if SOC_I2S_SUPPORTS_DAC
break; } else {
case speaker::STATE_STOPPED: i2s_set_dac_mode(this->internal_dac_mode_);
break;
} }
#endif
if (err != ESP_OK) {
// Failed to set the data out pin, so uninstall the driver and unlock the I2S port
i2s_driver_uninstall(this->parent_->get_port());
this->parent_->unlock();
} }
size_t I2SAudioSpeaker::play(const uint8_t *data, size_t length) { return err;
if (this->is_failed()) {
ESP_LOGE(TAG, "Cannot play audio, speaker failed to setup");
return 0;
}
if (this->state_ != speaker::STATE_RUNNING && this->state_ != speaker::STATE_STARTING) {
this->start();
}
size_t remaining = length;
size_t index = 0;
while (remaining > 0) {
DataEvent event;
event.stop = false;
size_t to_send_length = std::min(remaining, BUFFER_SIZE);
event.len = to_send_length;
memcpy(event.data, data + index, to_send_length);
if (xQueueSend(this->buffer_queue_, &event, 0) != pdTRUE) {
return index;
}
remaining -= to_send_length;
index += to_send_length;
}
return index;
} }
bool I2SAudioSpeaker::has_buffered_data() const { return uxQueueMessagesWaiting(this->buffer_queue_) > 0; } esp_err_t I2SAudioSpeaker::reconfigure_i2s_stream_info_(audio::AudioStreamInfo &audio_stream_info) {
if (this->i2s_mode_ & I2S_MODE_MASTER) {
// ESP controls for the the I2S bus, so adjust the sample rate and bits per sample to match the incoming audio
this->sample_rate_ = audio_stream_info.sample_rate;
this->bits_per_sample_ = (i2s_bits_per_sample_t) audio_stream_info.bits_per_sample;
} else if (this->sample_rate_ != audio_stream_info.sample_rate) {
// Can't reconfigure I2S bus, so the sample rate must match the configured value
return ESP_ERR_INVALID_ARG;
}
if ((i2s_bits_per_sample_t) audio_stream_info.bits_per_sample > this->bits_per_sample_) {
// Currently can't handle the case when the incoming audio has more bits per sample than the configured value
return ESP_ERR_INVALID_ARG;
}
if (audio_stream_info.channels == 1) {
return i2s_set_clk(this->parent_->get_port(), this->sample_rate_, this->bits_per_sample_, I2S_CHANNEL_MONO);
} else if (audio_stream_info.channels == 2) {
return i2s_set_clk(this->parent_->get_port(), this->sample_rate_, this->bits_per_sample_, I2S_CHANNEL_STEREO);
}
return ESP_ERR_INVALID_ARG;
}
void I2SAudioSpeaker::delete_task_(size_t buffer_size) {
if (this->audio_ring_buffer_ != nullptr) {
xEventGroupWaitBits(this->event_group_,
MESSAGE_RING_BUFFER_AVAILABLE_TO_WRITE, // Bit message to read
pdFALSE, // Don't clear the bits on exit
pdTRUE, // Don't wait for all the bits,
portMAX_DELAY); // Block indefinitely until a command bit is set
this->audio_ring_buffer_.reset(); // Deallocates the ring buffer stored in the unique_ptr
this->audio_ring_buffer_ = nullptr;
}
if (this->data_buffer_ != nullptr) {
ExternalRAMAllocator<uint8_t> allocator(ExternalRAMAllocator<uint8_t>::ALLOW_FAILURE);
allocator.deallocate(this->data_buffer_, buffer_size);
this->data_buffer_ = nullptr;
}
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::STATE_STOPPED);
this->task_created_ = false;
vTaskDelete(nullptr);
}
} // namespace i2s_audio } // namespace i2s_audio
} // namespace esphome } // namespace esphome

View file

@ -5,38 +5,21 @@
#include "../i2s_audio.h" #include "../i2s_audio.h"
#include <driver/i2s.h> #include <driver/i2s.h>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <freertos/event_groups.h>
#include <freertos/FreeRTOS.h>
#include "esphome/components/audio/audio.h"
#include "esphome/components/speaker/speaker.h" #include "esphome/components/speaker/speaker.h"
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/core/gpio.h" #include "esphome/core/gpio.h"
#include "esphome/core/helpers.h" #include "esphome/core/helpers.h"
#include "esphome/core/ring_buffer.h"
namespace esphome { namespace esphome {
namespace i2s_audio { namespace i2s_audio {
static const size_t BUFFER_SIZE = 1024;
enum class TaskEventType : uint8_t {
STARTING = 0,
STARTED,
STOPPING,
STOPPED,
WARNING = 255,
};
struct TaskEvent {
TaskEventType type;
esp_err_t err;
};
struct DataEvent {
bool stop;
size_t len;
uint8_t data[BUFFER_SIZE];
};
class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Component { class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Component {
public: public:
float get_setup_priority() const override { return esphome::setup_priority::LATE; } float get_setup_priority() const override { return esphome::setup_priority::LATE; }
@ -55,25 +38,95 @@ class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Comp
void stop() override; void stop() override;
void finish() override; void finish() override;
size_t play(const uint8_t *data, size_t length) override; /// @brief Plays the provided audio data.
/// Starts the speaker task, if necessary. Writes the audio data to the ring buffer.
/// @param data Audio data in the format set by the parent speaker classes ``set_audio_stream_info`` method.
/// @param length The length of the audio data in bytes.
/// @param ticks_to_wait The FreeRTOS ticks to wait before writing as much data as possible to the ring buffer.
/// @return The number of bytes that were actually written to the ring buffer.
size_t play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) override;
size_t play(const uint8_t *data, size_t length) override { return play(data, length, 0); }
bool has_buffered_data() const override; bool has_buffered_data() const override;
/// @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;
/// @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: protected:
void start_(); /// @brief Function for the FreeRTOS task handling audio output.
/// After receiving the COMMAND_START signal, allocates space for the buffers, starts the I2S driver, and reads
/// audio from the ring buffer and writes audio to the I2S port. Stops immmiately after receiving the COMMAND_STOP
/// signal and stops only after the ring buffer is empty after receiving the COMMAND_STOP_GRACEFULLY signal. Stops if
/// the ring buffer hasn't read data for more than timeout_ milliseconds. When stopping, it deallocates the buffers,
/// stops the I2S driver, unlocks the I2S port, and deletes the task. It communicates the state and any errors via
/// event_group_.
/// @param params I2SAudioSpeaker component
static void speaker_task(void *params);
/// @brief Sends a stop command to the speaker task via event_group_.
/// @param wait_on_empty If false, sends the COMMAND_STOP signal. If true, sends the COMMAND_STOP_GRACEFULLY signal.
void stop_(bool wait_on_empty); void stop_(bool wait_on_empty);
void watch_();
static void player_task(void *params); /// @brief Sets the corresponding ERR_ESP event group bits.
/// @param err esp_err_t error code.
/// @return True if an ERR_ESP bit is set and false if err == ESP_OK
bool send_esp_err_to_event_group_(esp_err_t err);
TaskHandle_t player_task_handle_{nullptr}; /// @brief Allocates the data buffer and ring buffer
QueueHandle_t buffer_queue_; /// @param data_buffer_size Number of bytes to allocate for the data buffer.
QueueHandle_t event_queue_; /// @param ring_buffer_size Number of bytes to allocate for the ring buffer.
/// @return ESP_ERR_NO_MEM if either buffer fails to allocate
/// ESP_OK if successful
esp_err_t allocate_buffers_(size_t data_buffer_size, size_t ring_buffer_size);
/// @brief Starts the ESP32 I2S driver.
/// Attempts to lock the I2S port, starts the I2S driver, and sets the data out pin. If it fails, it will unlock
/// the I2S port and uninstall the driver, if necessary.
/// @return ESP_ERR_INVALID_STATE if the I2S port is already locked.
/// ESP_ERR_INVALID_ARG if installing the driver or setting the data out pin fails due to a parameter error.
/// ESP_ERR_NO_MEM if the driver fails to install due to a memory allocation error.
/// ESP_FAIL if setting the data out pin fails due to an IO error
/// ESP_OK if successful
esp_err_t start_i2s_driver_();
/// @brief Adjusts the I2S driver configuration to match the incoming audio stream.
/// Modifies I2S driver's sample rate, bits per sample, and number of channel settings. If the I2S is in secondary
/// mode, it only modifies the number of channels.
/// @param audio_stream_info Describes the incoming audio stream
/// @return ESP_ERR_INVALID_ARG if there is a parameter error, if there is more than 2 channels in the stream, or if
/// the audio settings are incompatible with the configuration.
/// ESP_ERR_NO_MEM if the driver fails to reconfigure due to a memory allocation error.
/// ESP_OK if successful.
esp_err_t reconfigure_i2s_stream_info_(audio::AudioStreamInfo &audio_stream_info);
/// @brief Deletes the speaker's task.
/// Deallocates the data_buffer_ and audio_ring_buffer_, if necessary, and deletes the task. Should only be called by
/// the speaker_task itself.
/// @param buffer_size The allocated size of the data_buffer_.
void delete_task_(size_t buffer_size);
TaskHandle_t speaker_task_handle_{nullptr};
EventGroupHandle_t event_group_{nullptr};
uint8_t *data_buffer_;
std::unique_ptr<RingBuffer> audio_ring_buffer_;
uint32_t timeout_;
uint8_t dout_pin_;
uint32_t timeout_{0};
uint8_t dout_pin_{0};
bool task_created_{false}; bool task_created_{false};
int16_t q15_volume_factor_{INT16_MAX};
#if SOC_I2S_SUPPORTS_DAC #if SOC_I2S_SUPPORTS_DAC
i2s_dac_mode_t internal_dac_mode_{I2S_DAC_CHANNEL_DISABLE}; i2s_dac_mode_t internal_dac_mode_{I2S_DAC_CHANNEL_DISABLE};
#endif #endif

View file

@ -10,6 +10,7 @@ from esphome.const import (
CONF_DIMENSIONS, CONF_DIMENSIONS,
CONF_HEIGHT, CONF_HEIGHT,
CONF_ID, CONF_ID,
CONF_INIT_SEQUENCE,
CONF_INVERT_COLORS, CONF_INVERT_COLORS,
CONF_LAMBDA, CONF_LAMBDA,
CONF_MIRROR_X, CONF_MIRROR_X,
@ -89,7 +90,6 @@ CONF_LED_PIN = "led_pin"
CONF_COLOR_PALETTE_IMAGES = "color_palette_images" CONF_COLOR_PALETTE_IMAGES = "color_palette_images"
CONF_INVERT_DISPLAY = "invert_display" CONF_INVERT_DISPLAY = "invert_display"
CONF_PIXEL_MODE = "pixel_mode" CONF_PIXEL_MODE = "pixel_mode"
CONF_INIT_SEQUENCE = "init_sequence"
def cmd(c, *args): def cmd(c, *args):

View file

@ -89,6 +89,7 @@ class ILI9XXXDisplay : public display::DisplayBuffer,
void dump_config() override; void dump_config() override;
void setup() override; void setup() override;
void on_shutdown() override { this->command(ILI9XXX_SLPIN); }
display::DisplayType get_display_type() override { return display::DisplayType::DISPLAY_TYPE_COLOR; } display::DisplayType get_display_type() override { return display::DisplayType::DISPLAY_TYPE_COLOR; }
void draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, display::ColorOrder order, void draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, display::ColorOrder order,

View file

@ -361,24 +361,21 @@ async def to_code(config):
elif config[CONF_TYPE] in ["RGB565"]: elif config[CONF_TYPE] in ["RGB565"]:
image = image.convert("RGBA") image = image.convert("RGBA")
pixels = list(image.getdata()) 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 pos = 0
for r, g, b, a in pixels: for r, g, b, a in pixels:
R = r >> 3 R = r >> 3
G = g >> 2 G = g >> 2
B = b >> 3 B = b >> 3
rgb = (R << 11) | (G << 5) | B rgb = (R << 11) | (G << 5) | B
if transparent:
if rgb == 0x0020:
rgb = 0
if a < 0x80:
rgb = 0x0020
data[pos] = rgb >> 8 data[pos] = rgb >> 8
pos += 1 pos += 1
data[pos] = rgb & 0xFF data[pos] = rgb & 0xFF
pos += 1 pos += 1
if transparent:
data[pos] = a
pos += 1
elif config[CONF_TYPE] in ["BINARY", "TRANSPARENT_BINARY"]: elif config[CONF_TYPE] in ["BINARY", "TRANSPARENT_BINARY"]:
if transparent: if transparent:

View file

@ -88,7 +88,7 @@ lv_img_dsc_t *Image::get_lv_img_dsc() {
this->dsc_.header.reserved = 0; this->dsc_.header.reserved = 0;
this->dsc_.header.w = this->width_; this->dsc_.header.w = this->width_;
this->dsc_.header.h = this->height_; 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()) { switch (this->get_type()) {
case IMAGE_TYPE_BINARY: case IMAGE_TYPE_BINARY:
this->dsc_.header.cf = LV_IMG_CF_ALPHA_1BIT; 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: case IMAGE_TYPE_RGB565:
#if LV_COLOR_DEPTH == 16 #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 #else
this->dsc_.header.cf = LV_IMG_CF_RGB565; this->dsc_.header.cf = LV_IMG_CF_RGB565;
#endif #endif
break; break;
case image::IMAGE_TYPE_RGBA: case IMAGE_TYPE_RGBA:
#if LV_COLOR_DEPTH == 32 #if LV_COLOR_DEPTH == 32
this->dsc_.header.cf = LV_IMG_CF_TRUE_COLOR; this->dsc_.header.cf = LV_IMG_CF_TRUE_COLOR;
#else #else
this->dsc_.header.cf = LV_IMG_CF_RGBA8888; this->dsc_.header.cf = LV_IMG_CF_TRUE_COLOR_ALPHA;
#endif #endif
break; break;
} }
@ -147,21 +147,21 @@ Color Image::get_rgb24_pixel_(int x, int y) const {
return color; return color;
} }
Color Image::get_rgb565_pixel_(int x, int y) const { Color Image::get_rgb565_pixel_(int x, int y) const {
const uint32_t pos = (x + y * this->width_) * 2; const uint8_t *pos = this->data_start_;
uint16_t rgb565 = if (this->transparent_) {
progmem_read_byte(this->data_start_ + pos + 0) << 8 | progmem_read_byte(this->data_start_ + pos + 1); 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 r = (rgb565 & 0xF800) >> 11;
auto g = (rgb565 & 0x07E0) >> 5; auto g = (rgb565 & 0x07E0) >> 5;
auto b = rgb565 & 0x001F; auto b = rgb565 & 0x001F;
Color color = Color((r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2)); auto a = this->transparent_ ? progmem_read_byte(pos + 2) : 0xFF;
if (rgb565 == 0x0020 && transparent_) { Color color = Color((r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2), a);
// darkest green has been defined as transparent color for transparent RGB565 images.
color.w = 0;
} else {
color.w = 0xFF;
}
return color; return color;
} }
Color Image::get_grayscale_pixel_(int x, int y) const { Color Image::get_grayscale_pixel_(int x, int y) const {
const uint32_t pos = (x + y * this->width_); const uint32_t pos = (x + y * this->width_);
const uint8_t gray = progmem_read_byte(this->data_start_ + pos); const uint8_t gray = progmem_read_byte(this->data_start_ + pos);

View file

@ -3,12 +3,7 @@
#include "esphome/components/display/display.h" #include "esphome/components/display/display.h"
#ifdef USE_LVGL #ifdef USE_LVGL
// required for clang-tidy #include "esphome/components/lvgl/lvgl_proxy.h"
#ifndef LV_CONF_H
#define LV_CONF_SKIP 1 // NOLINT
#endif // LV_CONF_H
#include <lvgl.h>
#endif // USE_LVGL #endif // USE_LVGL
namespace esphome { namespace esphome {
@ -22,24 +17,6 @@ enum ImageType {
IMAGE_TYPE_RGBA = 4, 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 { class Image : public display::BaseImage {
public: public:
Image(const uint8_t *data_start, int width, int height, ImageType type); Image(const uint8_t *data_start, int width, int height, ImageType type);
@ -49,6 +26,25 @@ class Image : public display::BaseImage {
const uint8_t *get_data_start() const { return this->data_start_; } const uint8_t *get_data_start() const { return this->data_start_; }
ImageType get_type() const; 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 draw(int x, int y, display::Display *display, Color color_on, Color color_off) override;
void set_transparency(bool transparent) { transparent_ = transparent; } void set_transparency(bool transparent) { transparent_ = transparent; }

View file

@ -7,7 +7,8 @@
extern "C" { extern "C" {
uint8_t temprature_sens_read(); uint8_t temprature_sens_read();
} }
#elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) #elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || \
defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
#include "driver/temp_sensor.h" #include "driver/temp_sensor.h"
#endif // USE_ESP32_VARIANT #endif // USE_ESP32_VARIANT
#endif // USE_ESP32 #endif // USE_ESP32
@ -34,7 +35,8 @@ void InternalTemperatureSensor::update() {
ESP_LOGV(TAG, "Raw temperature value: %d", raw); ESP_LOGV(TAG, "Raw temperature value: %d", raw);
temperature = (raw - 32) / 1.8f; temperature = (raw - 32) / 1.8f;
success = (raw != 128); success = (raw != 128);
#elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) #elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || \
defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
temp_sensor_config_t tsens = TSENS_CONFIG_DEFAULT(); temp_sensor_config_t tsens = TSENS_CONFIG_DEFAULT();
temp_sensor_set_config(tsens); temp_sensor_set_config(tsens);
temp_sensor_start(); temp_sensor_start();

View file

@ -46,7 +46,7 @@ from .const import (
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
CODEOWNERS = ["@kuba2k2"] CODEOWNERS = ["@kuba2k2"]
AUTO_LOAD = [] AUTO_LOAD = ["preferences"]
def _detect_variant(value): def _detect_variant(value):

View file

@ -3,27 +3,39 @@ import esphome.codegen as cg
from esphome.components import mqtt, power_supply, web_server from esphome.components import mqtt, power_supply, web_server
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import ( from esphome.const import (
CONF_BLUE,
CONF_BRIGHTNESS,
CONF_COLD_WHITE,
CONF_COLD_WHITE_COLOR_TEMPERATURE, CONF_COLD_WHITE_COLOR_TEMPERATURE,
CONF_COLOR_BRIGHTNESS,
CONF_COLOR_CORRECT, CONF_COLOR_CORRECT,
CONF_COLOR_MODE,
CONF_COLOR_TEMPERATURE,
CONF_DEFAULT_TRANSITION_LENGTH, CONF_DEFAULT_TRANSITION_LENGTH,
CONF_EFFECTS, CONF_EFFECTS,
CONF_FLASH_TRANSITION_LENGTH, CONF_FLASH_TRANSITION_LENGTH,
CONF_GAMMA_CORRECT, CONF_GAMMA_CORRECT,
CONF_GREEN,
CONF_ID, CONF_ID,
CONF_INITIAL_STATE,
CONF_MQTT_ID, CONF_MQTT_ID,
CONF_ON_STATE, CONF_ON_STATE,
CONF_ON_TURN_OFF, CONF_ON_TURN_OFF,
CONF_ON_TURN_ON, CONF_ON_TURN_ON,
CONF_POWER_SUPPLY, CONF_POWER_SUPPLY,
CONF_RED,
CONF_RESTORE_MODE, CONF_RESTORE_MODE,
CONF_STATE,
CONF_TRIGGER_ID, CONF_TRIGGER_ID,
CONF_WARM_WHITE,
CONF_WARM_WHITE_COLOR_TEMPERATURE, CONF_WARM_WHITE_COLOR_TEMPERATURE,
CONF_WEB_SERVER, CONF_WEB_SERVER,
CONF_WHITE,
) )
from esphome.core import coroutine_with_priority from esphome.core import coroutine_with_priority
from esphome.cpp_helpers import setup_entity from esphome.cpp_helpers import setup_entity
from .automation import light_control_to_code # noqa from .automation import LIGHT_STATE_SCHEMA
from .effects import ( from .effects import (
ADDRESSABLE_EFFECTS, ADDRESSABLE_EFFECTS,
BINARY_EFFECTS, BINARY_EFFECTS,
@ -35,8 +47,10 @@ from .effects import (
from .types import ( # noqa from .types import ( # noqa
AddressableLight, AddressableLight,
AddressableLightState, AddressableLightState,
ColorMode,
LightOutput, LightOutput,
LightState, LightState,
LightStateRTCState,
LightStateTrigger, LightStateTrigger,
LightTurnOffTrigger, LightTurnOffTrigger,
LightTurnOnTrigger, LightTurnOnTrigger,
@ -85,6 +99,7 @@ LIGHT_SCHEMA = (
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(LightStateTrigger), cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(LightStateTrigger),
} }
), ),
cv.Optional(CONF_INITIAL_STATE): LIGHT_STATE_SCHEMA,
} }
) )
) )
@ -145,6 +160,22 @@ async def setup_light_core_(light_var, output_var, config):
cg.add(light_var.set_restore_mode(config[CONF_RESTORE_MODE])) cg.add(light_var.set_restore_mode(config[CONF_RESTORE_MODE]))
if (initial_state_config := config.get(CONF_INITIAL_STATE)) is not None:
initial_state = LightStateRTCState(
initial_state_config.get(CONF_COLOR_MODE, ColorMode.UNKNOWN),
initial_state_config.get(CONF_STATE, False),
initial_state_config.get(CONF_BRIGHTNESS, 1.0),
initial_state_config.get(CONF_COLOR_BRIGHTNESS, 1.0),
initial_state_config.get(CONF_RED, 1.0),
initial_state_config.get(CONF_GREEN, 1.0),
initial_state_config.get(CONF_BLUE, 1.0),
initial_state_config.get(CONF_WHITE, 1.0),
initial_state_config.get(CONF_COLOR_TEMPERATURE, 1.0),
initial_state_config.get(CONF_COLD_WHITE, 1.0),
initial_state_config.get(CONF_WARM_WHITE, 1.0),
)
cg.add(light_var.set_initial_state(initial_state))
if ( if (
default_transition_length := config.get(CONF_DEFAULT_TRANSITION_LENGTH) default_transition_length := config.get(CONF_DEFAULT_TRANSITION_LENGTH)
) is not None: ) is not None:

View file

@ -1,41 +1,42 @@
from esphome import automation
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome import automation
from esphome.const import ( from esphome.const import (
CONF_ID,
CONF_COLOR_MODE,
CONF_TRANSITION_LENGTH,
CONF_STATE,
CONF_FLASH_LENGTH,
CONF_EFFECT,
CONF_BRIGHTNESS,
CONF_COLOR_BRIGHTNESS,
CONF_RED,
CONF_GREEN,
CONF_BLUE, CONF_BLUE,
CONF_WHITE, CONF_BRIGHTNESS,
CONF_COLOR_TEMPERATURE, CONF_BRIGHTNESS_LIMITS,
CONF_COLD_WHITE, CONF_COLD_WHITE,
CONF_WARM_WHITE, CONF_COLOR_BRIGHTNESS,
CONF_COLOR_MODE,
CONF_COLOR_TEMPERATURE,
CONF_EFFECT,
CONF_FLASH_LENGTH,
CONF_GREEN,
CONF_ID,
CONF_LIMIT_MODE,
CONF_MAX_BRIGHTNESS,
CONF_MIN_BRIGHTNESS,
CONF_RANGE_FROM, CONF_RANGE_FROM,
CONF_RANGE_TO, CONF_RANGE_TO,
CONF_BRIGHTNESS_LIMITS, CONF_RED,
CONF_LIMIT_MODE, CONF_STATE,
CONF_MIN_BRIGHTNESS, CONF_TRANSITION_LENGTH,
CONF_MAX_BRIGHTNESS, CONF_WARM_WHITE,
CONF_WHITE,
) )
from .types import ( from .types import (
ColorMode,
COLOR_MODES, COLOR_MODES,
LIMIT_MODES, LIMIT_MODES,
DimRelativeAction,
ToggleAction,
LightState,
LightControlAction,
AddressableLightState, AddressableLightState,
AddressableSet, AddressableSet,
LightIsOnCondition, ColorMode,
DimRelativeAction,
LightControlAction,
LightIsOffCondition, LightIsOffCondition,
LightIsOnCondition,
LightState,
ToggleAction,
) )
@ -62,18 +63,10 @@ async def light_toggle_to_code(config, action_id, template_arg, args):
return var return var
LIGHT_CONTROL_ACTION_SCHEMA = cv.Schema( LIGHT_STATE_SCHEMA = cv.Schema(
{ {
cv.Required(CONF_ID): cv.use_id(LightState),
cv.Optional(CONF_COLOR_MODE): cv.enum(COLOR_MODES, upper=True, space="_"), cv.Optional(CONF_COLOR_MODE): cv.enum(COLOR_MODES, upper=True, space="_"),
cv.Optional(CONF_STATE): cv.templatable(cv.boolean), cv.Optional(CONF_STATE): cv.templatable(cv.boolean),
cv.Exclusive(CONF_TRANSITION_LENGTH, "transformer"): cv.templatable(
cv.positive_time_period_milliseconds
),
cv.Exclusive(CONF_FLASH_LENGTH, "transformer"): cv.templatable(
cv.positive_time_period_milliseconds
),
cv.Exclusive(CONF_EFFECT, "transformer"): cv.templatable(cv.string),
cv.Optional(CONF_BRIGHTNESS): cv.templatable(cv.percentage), cv.Optional(CONF_BRIGHTNESS): cv.templatable(cv.percentage),
cv.Optional(CONF_COLOR_BRIGHTNESS): cv.templatable(cv.percentage), cv.Optional(CONF_COLOR_BRIGHTNESS): cv.templatable(cv.percentage),
cv.Optional(CONF_RED): cv.templatable(cv.percentage), cv.Optional(CONF_RED): cv.templatable(cv.percentage),
@ -85,6 +78,20 @@ LIGHT_CONTROL_ACTION_SCHEMA = cv.Schema(
cv.Optional(CONF_WARM_WHITE): cv.templatable(cv.percentage), cv.Optional(CONF_WARM_WHITE): cv.templatable(cv.percentage),
} }
) )
LIGHT_CONTROL_ACTION_SCHEMA = LIGHT_STATE_SCHEMA.extend(
{
cv.Required(CONF_ID): cv.use_id(LightState),
cv.Exclusive(CONF_TRANSITION_LENGTH, "transformer"): cv.templatable(
cv.positive_time_period_milliseconds
),
cv.Exclusive(CONF_FLASH_LENGTH, "transformer"): cv.templatable(
cv.positive_time_period_milliseconds
),
cv.Exclusive(CONF_EFFECT, "transformer"): cv.templatable(cv.string),
}
)
LIGHT_TURN_OFF_ACTION_SCHEMA = automation.maybe_simple_id( LIGHT_TURN_OFF_ACTION_SCHEMA = automation.maybe_simple_id(
{ {
cv.Required(CONF_ID): cv.use_id(LightState), cv.Required(CONF_ID): cv.use_id(LightState),

View file

@ -1,59 +1,59 @@
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor from esphome import automation
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome import automation
from esphome.const import ( from esphome.const import (
CONF_NAME,
CONF_LAMBDA,
CONF_UPDATE_INTERVAL,
CONF_TRANSITION_LENGTH,
CONF_COLORS,
CONF_STATE,
CONF_DURATION,
CONF_BRIGHTNESS,
CONF_COLOR_MODE,
CONF_COLOR_BRIGHTNESS,
CONF_RED,
CONF_GREEN,
CONF_BLUE,
CONF_WHITE,
CONF_COLOR_TEMPERATURE,
CONF_COLD_WHITE,
CONF_WARM_WHITE,
CONF_ALPHA, CONF_ALPHA,
CONF_BLUE,
CONF_BRIGHTNESS,
CONF_COLD_WHITE,
CONF_COLOR_BRIGHTNESS,
CONF_COLOR_MODE,
CONF_COLOR_TEMPERATURE,
CONF_COLORS,
CONF_DURATION,
CONF_GREEN,
CONF_INTENSITY, CONF_INTENSITY,
CONF_SPEED, CONF_LAMBDA,
CONF_WIDTH,
CONF_NUM_LEDS,
CONF_RANDOM,
CONF_SEQUENCE,
CONF_MAX_BRIGHTNESS, CONF_MAX_BRIGHTNESS,
CONF_MIN_BRIGHTNESS, CONF_MIN_BRIGHTNESS,
CONF_NAME,
CONF_NUM_LEDS,
CONF_RANDOM,
CONF_RED,
CONF_SEQUENCE,
CONF_SPEED,
CONF_STATE,
CONF_TRANSITION_LENGTH,
CONF_UPDATE_INTERVAL,
CONF_WARM_WHITE,
CONF_WHITE,
CONF_WIDTH,
) )
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor
from esphome.util import Registry from esphome.util import Registry
from .types import ( from .types import (
ColorMode,
COLOR_MODES, COLOR_MODES,
AddressableColorWipeEffect,
AddressableColorWipeEffectColor,
AddressableFireworksEffect,
AddressableFlickerEffect,
AddressableLambdaLightEffect,
AddressableLightRef,
AddressableRainbowLightEffect,
AddressableRandomTwinkleEffect,
AddressableScanEffect,
AddressableTwinkleEffect,
AutomationLightEffect,
Color,
ColorMode,
FlickerLightEffect,
LambdaLightEffect, LambdaLightEffect,
LightColorValues,
PulseLightEffect, PulseLightEffect,
RandomLightEffect, RandomLightEffect,
StrobeLightEffect, StrobeLightEffect,
StrobeLightEffectColor, StrobeLightEffectColor,
LightColorValues,
AddressableLightRef,
AddressableLambdaLightEffect,
FlickerLightEffect,
AddressableRainbowLightEffect,
AddressableColorWipeEffect,
AddressableColorWipeEffectColor,
AddressableScanEffect,
AddressableTwinkleEffect,
AddressableRandomTwinkleEffect,
AddressableFireworksEffect,
AddressableFlickerEffect,
AutomationLightEffect,
Color,
) )
CONF_ADD_LED_INTERVAL = "add_led_interval" CONF_ADD_LED_INTERVAL = "add_led_interval"

View file

@ -1,6 +1,7 @@
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include "light_state.h"
#include "light_output.h" #include "light_output.h"
#include "light_state.h"
#include "transformers.h" #include "transformers.h"
namespace esphome { namespace esphome {
@ -16,21 +17,6 @@ LightCall LightState::turn_off() { return this->make_call().set_state(false); }
LightCall LightState::toggle() { return this->make_call().set_state(!this->remote_values.is_on()); } LightCall LightState::toggle() { return this->make_call().set_state(!this->remote_values.is_on()); }
LightCall LightState::make_call() { return LightCall(this); } LightCall LightState::make_call() { return LightCall(this); }
struct LightStateRTCState {
ColorMode color_mode{ColorMode::UNKNOWN};
bool state{false};
float brightness{1.0f};
float color_brightness{1.0f};
float red{1.0f};
float green{1.0f};
float blue{1.0f};
float white{1.0f};
float color_temp{1.0f};
float cold_white{1.0f};
float warm_white{1.0f};
uint32_t effect{0};
};
void LightState::setup() { void LightState::setup() {
ESP_LOGCONFIG(TAG, "Setting up light '%s'...", this->get_name().c_str()); ESP_LOGCONFIG(TAG, "Setting up light '%s'...", this->get_name().c_str());
@ -48,6 +34,9 @@ void LightState::setup() {
auto call = this->make_call(); auto call = this->make_call();
LightStateRTCState recovered{}; LightStateRTCState recovered{};
if (this->initial_state_.has_value()) {
recovered = *this->initial_state_;
}
switch (this->restore_mode_) { switch (this->restore_mode_) {
case LIGHT_RESTORE_DEFAULT_OFF: case LIGHT_RESTORE_DEFAULT_OFF:
case LIGHT_RESTORE_DEFAULT_ON: case LIGHT_RESTORE_DEFAULT_ON:
@ -175,6 +164,7 @@ void LightState::set_flash_transition_length(uint32_t flash_transition_length) {
uint32_t LightState::get_flash_transition_length() const { return this->flash_transition_length_; } uint32_t LightState::get_flash_transition_length() const { return this->flash_transition_length_; }
void LightState::set_gamma_correct(float gamma_correct) { this->gamma_correct_ = gamma_correct; } void LightState::set_gamma_correct(float gamma_correct) { this->gamma_correct_ = gamma_correct; }
void LightState::set_restore_mode(LightRestoreMode restore_mode) { this->restore_mode_ = restore_mode; } void LightState::set_restore_mode(LightRestoreMode restore_mode) { this->restore_mode_ = restore_mode; }
void LightState::set_initial_state(const LightStateRTCState &initial_state) { this->initial_state_ = initial_state; }
bool LightState::supports_effects() { return !this->effects_.empty(); } bool LightState::supports_effects() { return !this->effects_.empty(); }
const std::vector<LightEffect *> &LightState::get_effects() const { return this->effects_; } const std::vector<LightEffect *> &LightState::get_effects() const { return this->effects_; }
void LightState::add_effects(const std::vector<LightEffect *> &effects) { void LightState::add_effects(const std::vector<LightEffect *> &effects) {

View file

@ -28,6 +28,35 @@ enum LightRestoreMode {
LIGHT_RESTORE_AND_ON, LIGHT_RESTORE_AND_ON,
}; };
struct LightStateRTCState {
LightStateRTCState(ColorMode color_mode, bool state, float brightness, float color_brightness, float red, float green,
float blue, float white, float color_temp, float cold_white, float warm_white)
: color_mode(color_mode),
state(state),
brightness(brightness),
color_brightness(color_brightness),
red(red),
green(green),
blue(blue),
white(white),
color_temp(color_temp),
cold_white(cold_white),
warm_white(warm_white) {}
LightStateRTCState() = default;
ColorMode color_mode{ColorMode::UNKNOWN};
bool state{false};
float brightness{1.0f};
float color_brightness{1.0f};
float red{1.0f};
float green{1.0f};
float blue{1.0f};
float white{1.0f};
float color_temp{1.0f};
float cold_white{1.0f};
float warm_white{1.0f};
uint32_t effect{0};
};
/** This class represents the communication layer between the front-end MQTT layer and the /** This class represents the communication layer between the front-end MQTT layer and the
* hardware output layer. * hardware output layer.
*/ */
@ -116,6 +145,9 @@ class LightState : public EntityBase, public Component {
/// Set the restore mode of this light /// Set the restore mode of this light
void set_restore_mode(LightRestoreMode restore_mode); void set_restore_mode(LightRestoreMode restore_mode);
/// Set the initial state of this light
void set_initial_state(const LightStateRTCState &initial_state);
/// Return whether the light has any effects that meet the trait requirements. /// Return whether the light has any effects that meet the trait requirements.
bool supports_effects(); bool supports_effects();
@ -212,6 +244,8 @@ class LightState : public EntityBase, public Component {
float gamma_correct_{}; float gamma_correct_{};
/// Restore mode of the light. /// Restore mode of the light.
LightRestoreMode restore_mode_; LightRestoreMode restore_mode_;
/// Initial state of the light.
optional<LightStateRTCState> initial_state_{};
/// List of effects for this light. /// List of effects for this light.
std::vector<LightEffect *> effects_; std::vector<LightEffect *> effects_;

View file

@ -1,5 +1,5 @@
import esphome.codegen as cg
from esphome import automation from esphome import automation
import esphome.codegen as cg
# Base # Base
light_ns = cg.esphome_ns.namespace("light") light_ns = cg.esphome_ns.namespace("light")
@ -12,6 +12,8 @@ AddressableLightRef = AddressableLight.operator("ref")
Color = cg.esphome_ns.class_("Color") Color = cg.esphome_ns.class_("Color")
LightColorValues = light_ns.class_("LightColorValues") LightColorValues = light_ns.class_("LightColorValues")
LightStateRTCState = light_ns.struct("LightStateRTCState")
# Color modes # Color modes
ColorMode = light_ns.enum("ColorMode", is_class=True) ColorMode = light_ns.enum("ColorMode", is_class=True)
COLOR_MODES = { COLOR_MODES = {

View file

@ -10,8 +10,12 @@
#ifdef USE_LOGGER_USB_SERIAL_JTAG #ifdef USE_LOGGER_USB_SERIAL_JTAG
#include <driver/usb_serial_jtag.h> #include <driver/usb_serial_jtag.h>
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 3, 0)
#include <esp_vfs_dev.h> #include <esp_vfs_dev.h>
#include <esp_vfs_usb_serial_jtag.h> #include <esp_vfs_usb_serial_jtag.h>
#else
#include <driver/usb_serial_jtag_vfs.h>
#endif
#endif #endif
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
@ -36,10 +40,17 @@ static const char *const TAG = "logger";
static void init_usb_serial_jtag_() { static void init_usb_serial_jtag_() {
setvbuf(stdin, NULL, _IONBF, 0); // Disable buffering on stdin setvbuf(stdin, NULL, _IONBF, 0); // Disable buffering on stdin
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 3, 0)
// Minicom, screen, idf_monitor send CR when ENTER key is pressed // Minicom, screen, idf_monitor send CR when ENTER key is pressed
esp_vfs_dev_usb_serial_jtag_set_rx_line_endings(ESP_LINE_ENDINGS_CR); esp_vfs_dev_usb_serial_jtag_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
// Move the caret to the beginning of the next line on '\n' // Move the caret to the beginning of the next line on '\n'
esp_vfs_dev_usb_serial_jtag_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF); esp_vfs_dev_usb_serial_jtag_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
#else
// Minicom, screen, idf_monitor send CR when ENTER key is pressed
usb_serial_jtag_vfs_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
// Move the caret to the beginning of the next line on '\n'
usb_serial_jtag_vfs_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
#endif
// Enable non-blocking mode on stdin and stdout // Enable non-blocking mode on stdin and stdout
fcntl(fileno(stdout), F_SETFL, 0); fcntl(fileno(stdout), F_SETFL, 0);
@ -57,7 +68,11 @@ static void init_usb_serial_jtag_() {
} }
// Tell vfs to use usb-serial-jtag driver // Tell vfs to use usb-serial-jtag driver
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 3, 0)
esp_vfs_usb_serial_jtag_use_driver(); esp_vfs_usb_serial_jtag_use_driver();
#else
usb_serial_jtag_vfs_use_driver();
#endif
} }
#endif #endif

View file

@ -22,7 +22,7 @@ from esphome.helpers import write_file_if_changed
from . import defines as df, helpers, lv_validation as lvalid from . import defines as df, helpers, lv_validation as lvalid
from .automation import disp_update, focused_widgets, update_to_code from .automation import disp_update, focused_widgets, update_to_code
from .defines import CONF_WIDGETS, add_define from .defines import add_define
from .encoders import ENCODERS_CONFIG, encoders_to_code, initial_focus_to_code from .encoders import ENCODERS_CONFIG, encoders_to_code, initial_focus_to_code
from .gradient import GRADIENT_SCHEMA, gradients_to_code from .gradient import GRADIENT_SCHEMA, gradients_to_code
from .hello_world import get_hello_world from .hello_world import get_hello_world
@ -33,7 +33,7 @@ from .schemas import (
FLEX_OBJ_SCHEMA, FLEX_OBJ_SCHEMA,
GRID_CELL_SCHEMA, GRID_CELL_SCHEMA,
LAYOUT_SCHEMAS, LAYOUT_SCHEMAS,
STATE_SCHEMA, STYLE_SCHEMA,
WIDGET_TYPES, WIDGET_TYPES,
any_widget_schema, any_widget_schema,
container_schema, container_schema,
@ -48,12 +48,13 @@ from .types import (
FontEngine, FontEngine,
IdleTrigger, IdleTrigger,
ObjUpdateAction, ObjUpdateAction,
PauseTrigger,
lv_font_t, lv_font_t,
lv_group_t, lv_group_t,
lv_style_t, lv_style_t,
lvgl_ns, lvgl_ns,
) )
from .widgets import Widget, add_widgets, lv_scr_act, set_obj_properties, styles_used from .widgets import Widget, add_widgets, get_scr_act, set_obj_properties, styles_used
from .widgets.animimg import animimg_spec from .widgets.animimg import animimg_spec
from .widgets.arc import arc_spec from .widgets.arc import arc_spec
from .widgets.button import button_spec from .widgets.button import button_spec
@ -185,7 +186,7 @@ def final_validation(config):
async def to_code(config): async def to_code(config):
cg.add_library("lvgl/lvgl", "8.4.0") cg.add_library("lvgl/lvgl", "8.4.0")
CORE.add_define("USE_LVGL") cg.add_define("USE_LVGL")
# suppress default enabling of extra widgets # suppress default enabling of extra widgets
add_define("_LV_KCONFIG_PRESENT") add_define("_LV_KCONFIG_PRESENT")
# Always enable - lots of things use it. # Always enable - lots of things use it.
@ -199,7 +200,13 @@ async def to_code(config):
add_define("LV_MEM_CUSTOM_REALLOC", "lv_custom_mem_realloc") add_define("LV_MEM_CUSTOM_REALLOC", "lv_custom_mem_realloc")
add_define("LV_MEM_CUSTOM_INCLUDE", '"esphome/components/lvgl/lvgl_hal.h"') add_define("LV_MEM_CUSTOM_INCLUDE", '"esphome/components/lvgl/lvgl_hal.h"')
add_define("LV_LOG_LEVEL", f"LV_LOG_LEVEL_{config[df.CONF_LOG_LEVEL]}") add_define(
"LV_LOG_LEVEL", f"LV_LOG_LEVEL_{df.LV_LOG_LEVELS[config[df.CONF_LOG_LEVEL]]}"
)
cg.add_define(
"LVGL_LOG_LEVEL",
cg.RawExpression(f"ESPHOME_LOG_LEVEL_{config[df.CONF_LOG_LEVEL]}"),
)
add_define("LV_COLOR_DEPTH", config[df.CONF_COLOR_DEPTH]) add_define("LV_COLOR_DEPTH", config[df.CONF_COLOR_DEPTH])
for font in helpers.lv_fonts_used: for font in helpers.lv_fonts_used:
add_define(f"LV_FONT_{font.upper()}") add_define(f"LV_FONT_{font.upper()}")
@ -213,15 +220,9 @@ async def to_code(config):
"LV_COLOR_CHROMA_KEY", "LV_COLOR_CHROMA_KEY",
await lvalid.lv_color.process(config[df.CONF_TRANSPARENCY_KEY]), await lvalid.lv_color.process(config[df.CONF_TRANSPARENCY_KEY]),
) )
CORE.add_build_flag("-Isrc") cg.add_build_flag("-Isrc")
cg.add_global(lvgl_ns.using) cg.add_global(lvgl_ns.using)
lv_component = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(lv_component, config)
Widget.create(config[CONF_ID], lv_component, obj_spec, config)
for display in config[df.CONF_DISPLAYS]:
cg.add(lv_component.add_display(await cg.get_variable(display)))
frac = config[CONF_BUFFER_SIZE] frac = config[CONF_BUFFER_SIZE]
if frac >= 0.75: if frac >= 0.75:
frac = 1 frac = 1
@ -231,8 +232,17 @@ async def to_code(config):
frac = 4 frac = 4
else: else:
frac = 8 frac = 8
cg.add(lv_component.set_buffer_frac(int(frac))) displays = [await cg.get_variable(display) for display in config[df.CONF_DISPLAYS]]
cg.add(lv_component.set_full_refresh(config[df.CONF_FULL_REFRESH])) lv_component = cg.new_Pvariable(
config[CONF_ID],
displays,
frac,
config[df.CONF_FULL_REFRESH],
config[df.CONF_DRAW_ROUNDING],
config[df.CONF_RESUME_ON_INPUT],
)
await cg.register_component(lv_component, config)
Widget.create(config[CONF_ID], lv_component, obj_spec, config)
for font in helpers.esphome_fonts_used: for font in helpers.esphome_fonts_used:
await cg.get_variable(font) await cg.get_variable(font)
@ -254,6 +264,7 @@ async def to_code(config):
else: else:
add_define("LV_FONT_DEFAULT", await lvalid.lv_font.process(default_font)) add_define("LV_FONT_DEFAULT", await lvalid.lv_font.process(default_font))
lv_scr_act = get_scr_act(lv_component)
async with LvContext(lv_component): async with LvContext(lv_component):
await touchscreens_to_code(lv_component, config) await touchscreens_to_code(lv_component, config)
await encoders_to_code(lv_component, config) await encoders_to_code(lv_component, config)
@ -263,31 +274,38 @@ async def to_code(config):
await set_obj_properties(lv_scr_act, config) await set_obj_properties(lv_scr_act, config)
await add_widgets(lv_scr_act, config) await add_widgets(lv_scr_act, config)
await add_pages(lv_component, config) await add_pages(lv_component, config)
await add_top_layer(config) await add_top_layer(lv_component, config)
await msgboxes_to_code(config) await msgboxes_to_code(lv_component, config)
await disp_update(f"{lv_component}->get_disp()", config) await disp_update(lv_component.get_disp(), config)
# At this point only the setup code should be generated # Set this directly since we are limited in how many methods can be added to the Widget class.
assert LvContext.added_lambda_count == 1 Widget.widgets_completed = True
Widget.set_completed()
async with LvContext(lv_component): async with LvContext(lv_component):
await generate_triggers(lv_component) await generate_triggers(lv_component)
await generate_page_triggers(lv_component, config) await generate_page_triggers(lv_component, config)
await initial_focus_to_code(config)
for conf in config.get(CONF_ON_IDLE, ()): for conf in config.get(CONF_ON_IDLE, ()):
templ = await cg.templatable(conf[CONF_TIMEOUT], [], cg.uint32) templ = await cg.templatable(conf[CONF_TIMEOUT], [], cg.uint32)
idle_trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], lv_component, templ) idle_trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], lv_component, templ)
await build_automation(idle_trigger, [], conf) await build_automation(idle_trigger, [], conf)
await initial_focus_to_code(config) for conf in config.get(df.CONF_ON_PAUSE, ()):
pause_trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], lv_component, True)
await build_automation(pause_trigger, [], conf)
for conf in config.get(df.CONF_ON_RESUME, ()):
resume_trigger = cg.new_Pvariable(
conf[CONF_TRIGGER_ID], lv_component, False
)
await build_automation(resume_trigger, [], conf)
for comp in helpers.lvgl_components_required: for comp in helpers.lvgl_components_required:
CORE.add_define(f"USE_LVGL_{comp.upper()}") cg.add_define(f"USE_LVGL_{comp.upper()}")
if "transform_angle" in styles_used: if "transform_angle" in styles_used:
add_define("LV_COLOR_SCREEN_TRANSP", "1") add_define("LV_COLOR_SCREEN_TRANSP", "1")
for use in helpers.lv_uses: for use in helpers.lv_uses:
add_define(f"LV_USE_{use.upper()}") add_define(f"LV_USE_{use.upper()}")
lv_conf_h_file = CORE.relative_src_path(LV_CONF_FILENAME) lv_conf_h_file = CORE.relative_src_path(LV_CONF_FILENAME)
write_file_if_changed(lv_conf_h_file, generate_lv_conf_h()) write_file_if_changed(lv_conf_h_file, generate_lv_conf_h())
CORE.add_build_flag("-DLV_CONF_H=1") cg.add_build_flag("-DLV_CONF_H=1")
CORE.add_build_flag(f'-DLV_CONF_PATH="{LV_CONF_FILENAME}"') cg.add_build_flag(f'-DLV_CONF_PATH="{LV_CONF_FILENAME}"')
def display_schema(config): def display_schema(config):
@ -296,9 +314,9 @@ def display_schema(config):
def add_hello_world(config): def add_hello_world(config):
if CONF_WIDGETS not in config and CONF_PAGES not in config: if df.CONF_WIDGETS not in config and CONF_PAGES not in config:
LOGGER.info("No pages or widgets configured, creating default hello_world page") LOGGER.info("No pages or widgets configured, creating default hello_world page")
config[CONF_WIDGETS] = cv.ensure_list(WIDGET_SCHEMA)(get_hello_world()) config[df.CONF_WIDGETS] = cv.ensure_list(WIDGET_SCHEMA)(get_hello_world())
return config return config
@ -314,16 +332,17 @@ CONFIG_SCHEMA = (
cv.Optional(df.CONF_COLOR_DEPTH, default=16): cv.one_of(16), cv.Optional(df.CONF_COLOR_DEPTH, default=16): cv.one_of(16),
cv.Optional(df.CONF_DEFAULT_FONT, default="montserrat_14"): lvalid.lv_font, cv.Optional(df.CONF_DEFAULT_FONT, default="montserrat_14"): lvalid.lv_font,
cv.Optional(df.CONF_FULL_REFRESH, default=False): cv.boolean, cv.Optional(df.CONF_FULL_REFRESH, default=False): cv.boolean,
cv.Optional(df.CONF_DRAW_ROUNDING, default=2): cv.positive_int,
cv.Optional(CONF_BUFFER_SIZE, default="100%"): cv.percentage, cv.Optional(CONF_BUFFER_SIZE, default="100%"): cv.percentage,
cv.Optional(df.CONF_LOG_LEVEL, default="WARN"): cv.one_of( cv.Optional(df.CONF_LOG_LEVEL, default="WARN"): cv.one_of(
*df.LOG_LEVELS, upper=True *df.LV_LOG_LEVELS, upper=True
), ),
cv.Optional(df.CONF_BYTE_ORDER, default="big_endian"): cv.one_of( cv.Optional(df.CONF_BYTE_ORDER, default="big_endian"): cv.one_of(
"big_endian", "little_endian" "big_endian", "little_endian"
), ),
cv.Optional(df.CONF_STYLE_DEFINITIONS): cv.ensure_list( cv.Optional(df.CONF_STYLE_DEFINITIONS): cv.ensure_list(
cv.Schema({cv.Required(CONF_ID): cv.declare_id(lv_style_t)}) cv.Schema({cv.Required(CONF_ID): cv.declare_id(lv_style_t)})
.extend(STATE_SCHEMA) .extend(STYLE_SCHEMA)
.extend( .extend(
{ {
cv.Optional(df.CONF_GRID_CELL_X_ALIGN): grid_alignments, cv.Optional(df.CONF_GRID_CELL_X_ALIGN): grid_alignments,
@ -341,6 +360,16 @@ CONFIG_SCHEMA = (
), ),
} }
), ),
cv.Optional(df.CONF_ON_PAUSE): validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(PauseTrigger),
}
),
cv.Optional(df.CONF_ON_RESUME): validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(PauseTrigger),
}
),
cv.Exclusive(df.CONF_WIDGETS, CONF_PAGES): cv.ensure_list(WIDGET_SCHEMA), cv.Exclusive(df.CONF_WIDGETS, CONF_PAGES): cv.ensure_list(WIDGET_SCHEMA),
cv.Exclusive(CONF_PAGES, CONF_PAGES): cv.ensure_list( cv.Exclusive(CONF_PAGES, CONF_PAGES): cv.ensure_list(
container_schema(page_spec) container_schema(page_spec)
@ -356,6 +385,7 @@ CONFIG_SCHEMA = (
cv.Optional(df.CONF_TOUCHSCREENS, default=None): touchscreen_schema, cv.Optional(df.CONF_TOUCHSCREENS, default=None): touchscreen_schema,
cv.Optional(df.CONF_ENCODERS, default=None): ENCODERS_CONFIG, cv.Optional(df.CONF_ENCODERS, default=None): ENCODERS_CONFIG,
cv.GenerateID(df.CONF_DEFAULT_GROUP): cv.declare_id(lv_group_t), cv.GenerateID(df.CONF_DEFAULT_GROUP): cv.declare_id(lv_group_t),
cv.Optional(df.CONF_RESUME_ON_INPUT, default=True): cv.boolean,
} }
) )
.extend(DISP_BG_SCHEMA) .extend(DISP_BG_SCHEMA)

View file

@ -5,7 +5,7 @@ from esphome import automation
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import CONF_ACTION, CONF_GROUP, CONF_ID, CONF_TIMEOUT from esphome.const import CONF_ACTION, CONF_GROUP, CONF_ID, CONF_TIMEOUT
from esphome.cpp_generator import RawExpression, get_variable from esphome.cpp_generator import get_variable
from esphome.cpp_types import nullptr from esphome.cpp_types import nullptr
from .defines import ( from .defines import (
@ -23,7 +23,6 @@ from .lvcode import (
UPDATE_EVENT, UPDATE_EVENT,
LambdaContext, LambdaContext,
LocalVariable, LocalVariable,
LvConditional,
LvglComponent, LvglComponent,
ReturnStatement, ReturnStatement,
add_line_marks, add_line_marks,
@ -47,8 +46,8 @@ from .types import (
) )
from .widgets import ( from .widgets import (
Widget, Widget,
get_scr_act,
get_widgets, get_widgets,
lv_scr_act,
set_obj_properties, set_obj_properties,
wait_for_widgets, wait_for_widgets,
) )
@ -66,8 +65,6 @@ async def action_to_code(
): ):
await wait_for_widgets() await wait_for_widgets()
async with LambdaContext(parameters=args, where=action_id) as context: async with LambdaContext(parameters=args, where=action_id) as context:
with LvConditional(lv_expr.is_pre_initialise()):
context.add(RawExpression("return"))
for widget in widgets: for widget in widgets:
await action(widget) await action(widget)
var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda()) var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda())
@ -126,7 +123,7 @@ async def lvgl_is_idle(config, condition_id, template_arg, args):
async def disp_update(disp, config: dict): async def disp_update(disp, config: dict):
if CONF_DISP_BG_COLOR not in config and CONF_DISP_BG_IMAGE not in config: if CONF_DISP_BG_COLOR not in config and CONF_DISP_BG_IMAGE not in config:
return return
with LocalVariable("lv_disp_tmp", lv_disp_t, literal(disp)) as disp_temp: with LocalVariable("lv_disp_tmp", lv_disp_t, disp) as disp_temp:
if (bg_color := config.get(CONF_DISP_BG_COLOR)) is not None: if (bg_color := config.get(CONF_DISP_BG_COLOR)) is not None:
lv.disp_set_bg_color(disp_temp, await lv_color.process(bg_color)) lv.disp_set_bg_color(disp_temp, await lv_color.process(bg_color))
if bg_image := config.get(CONF_DISP_BG_IMAGE): if bg_image := config.get(CONF_DISP_BG_IMAGE):
@ -136,15 +133,24 @@ async def disp_update(disp, config: dict):
@automation.register_action( @automation.register_action(
"lvgl.widget.redraw", "lvgl.widget.redraw",
ObjUpdateAction, ObjUpdateAction,
cv.Any(
cv.maybe_simple_value(
{
cv.Required(CONF_ID): cv.use_id(lv_obj_t),
cv.GenerateID(CONF_LVGL_ID): cv.use_id(LvglComponent),
},
key=CONF_ID,
),
cv.Schema( cv.Schema(
{ {
cv.Optional(CONF_ID): cv.use_id(lv_obj_t),
cv.GenerateID(CONF_LVGL_ID): cv.use_id(LvglComponent), cv.GenerateID(CONF_LVGL_ID): cv.use_id(LvglComponent),
} }
), ),
),
) )
async def obj_invalidate_to_code(config, action_id, template_arg, args): async def obj_invalidate_to_code(config, action_id, template_arg, args):
widgets = await get_widgets(config) or [lv_scr_act] lv_comp = await cg.get_variable(config[CONF_LVGL_ID])
widgets = await get_widgets(config) or [get_scr_act(lv_comp)]
async def do_invalidate(widget: Widget): async def do_invalidate(widget: Widget):
lv_obj.invalidate(widget.obj) lv_obj.invalidate(widget.obj)
@ -164,7 +170,7 @@ async def obj_invalidate_to_code(config, action_id, template_arg, args):
async def lvgl_update_to_code(config, action_id, template_arg, args): async def lvgl_update_to_code(config, action_id, template_arg, args):
widgets = await get_widgets(config) widgets = await get_widgets(config)
w = widgets[0] w = widgets[0]
disp = f"{w.obj}->get_disp()" disp = literal(f"{w.obj}->get_disp()")
async with LambdaContext(LVGL_COMP_ARG, where=action_id) as context: async with LambdaContext(LVGL_COMP_ARG, where=action_id) as context:
await disp_update(disp, config) await disp_update(disp, config)
var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda()) var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda())

View file

@ -189,14 +189,14 @@ LV_ANIM = LvConstant(
LV_GRAD_DIR = LvConstant("LV_GRAD_DIR_", "NONE", "HOR", "VER") LV_GRAD_DIR = LvConstant("LV_GRAD_DIR_", "NONE", "HOR", "VER")
LV_DITHER = LvConstant("LV_DITHER_", "NONE", "ORDERED", "ERR_DIFF") LV_DITHER = LvConstant("LV_DITHER_", "NONE", "ORDERED", "ERR_DIFF")
LOG_LEVELS = ( LV_LOG_LEVELS = {
"TRACE", "VERBOSE": "TRACE",
"INFO", "DEBUG": "TRACE",
"WARN", "INFO": "INFO",
"ERROR", "WARN": "WARN",
"USER", "ERROR": "ERROR",
"NONE", "NONE": "NONE",
) }
LV_LONG_MODES = LvConstant( LV_LONG_MODES = LvConstant(
"LV_LABEL_LONG_", "LV_LABEL_LONG_",
@ -408,6 +408,7 @@ CONF_DEFAULT_FONT = "default_font"
CONF_DEFAULT_GROUP = "default_group" CONF_DEFAULT_GROUP = "default_group"
CONF_DIR = "dir" CONF_DIR = "dir"
CONF_DISPLAYS = "displays" CONF_DISPLAYS = "displays"
CONF_DRAW_ROUNDING = "draw_rounding"
CONF_EDITING = "editing" CONF_EDITING = "editing"
CONF_ENCODERS = "encoders" CONF_ENCODERS = "encoders"
CONF_END_ANGLE = "end_angle" CONF_END_ANGLE = "end_angle"
@ -451,6 +452,8 @@ CONF_OFFSET_X = "offset_x"
CONF_OFFSET_Y = "offset_y" CONF_OFFSET_Y = "offset_y"
CONF_ONE_CHECKED = "one_checked" CONF_ONE_CHECKED = "one_checked"
CONF_ONE_LINE = "one_line" CONF_ONE_LINE = "one_line"
CONF_ON_PAUSE = "on_pause"
CONF_ON_RESUME = "on_resume"
CONF_ON_SELECT = "on_select" CONF_ON_SELECT = "on_select"
CONF_OPA = "opa" CONF_OPA = "opa"
CONF_NEXT = "next" CONF_NEXT = "next"
@ -466,6 +469,7 @@ CONF_POINTS = "points"
CONF_PREVIOUS = "previous" CONF_PREVIOUS = "previous"
CONF_REPEAT_COUNT = "repeat_count" CONF_REPEAT_COUNT = "repeat_count"
CONF_RECOLOR = "recolor" CONF_RECOLOR = "recolor"
CONF_RESUME_ON_INPUT = "resume_on_input"
CONF_RIGHT_BUTTON = "right_button" CONF_RIGHT_BUTTON = "right_button"
CONF_ROLLOVER = "rollover" CONF_ROLLOVER = "rollover"
CONF_ROOT_BACK_BTN = "root_back_btn" CONF_ROOT_BACK_BTN = "root_back_btn"
@ -473,6 +477,7 @@ CONF_ROWS = "rows"
CONF_SCALE_LINES = "scale_lines" CONF_SCALE_LINES = "scale_lines"
CONF_SCROLLBAR_MODE = "scrollbar_mode" CONF_SCROLLBAR_MODE = "scrollbar_mode"
CONF_SELECTED_INDEX = "selected_index" CONF_SELECTED_INDEX = "selected_index"
CONF_SELECTED_TEXT = "selected_text"
CONF_SHOW_SNOW = "show_snow" CONF_SHOW_SNOW = "show_snow"
CONF_SPIN_TIME = "spin_time" CONF_SPIN_TIME = "spin_time"
CONF_SRC = "src" CONF_SRC = "src"

View file

@ -2,9 +2,9 @@ import esphome.codegen as cg
from esphome.components import light from esphome.components import light
from esphome.components.light import LightOutput from esphome.components.light import LightOutput
import esphome.config_validation as cv 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 ..lvcode import LvContext
from ..schemas import LVGL_SCHEMA from ..schemas import LVGL_SCHEMA
from ..types import LvType, lvgl_ns from ..types import LvType, lvgl_ns
@ -15,7 +15,7 @@ LVLight = lvgl_ns.class_("LVLight", LightOutput)
CONFIG_SCHEMA = light.RGB_LIGHT_SCHEMA.extend( CONFIG_SCHEMA = light.RGB_LIGHT_SCHEMA.extend(
{ {
cv.Optional(CONF_GAMMA_CORRECT, default=0.0): cv.positive_float, 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), cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(LVLight),
} }
).extend(LVGL_SCHEMA) ).extend(LVGL_SCHEMA)
@ -26,7 +26,7 @@ async def to_code(config):
await light.register_light(var, config) await light.register_light(var, config)
paren = await cg.get_variable(config[CONF_LVGL_ID]) 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] widget = widget[0]
await wait_for_widgets() await wait_for_widgets()
async with LvContext(paren) as ctx: async with LvContext(paren) as ctx:

View file

@ -267,6 +267,9 @@ def angle(value):
return int(cv.float_range(0.0, 360.0)(cv.angle(value)) * 10) return int(cv.float_range(0.0, 360.0)(cv.angle(value)) * 10)
lv_angle = LValidator(angle, uint32)
@schema_extractor("one_of") @schema_extractor("one_of")
def size_validator(value): def size_validator(value):
"""A size in one axis - one of "size_content", a number (pixels) or a percentage""" """A size in one axis - one of "size_content", a number (pixels) or a percentage"""
@ -274,10 +277,8 @@ def size_validator(value):
return ["SIZE_CONTENT", "number of pixels", "percentage"] return ["SIZE_CONTENT", "number of pixels", "percentage"]
if isinstance(value, str) and value.lower().endswith("px"): if isinstance(value, str) and value.lower().endswith("px"):
value = cv.int_(value[:-2]) value = cv.int_(value[:-2])
if isinstance(value, str) and not value.endswith("%"): if isinstance(value, str) and value.upper() == "SIZE_CONTENT":
if value.upper() == "SIZE_CONTENT":
return "LV_SIZE_CONTENT" return "LV_SIZE_CONTENT"
raise cv.Invalid("must be 'size_content', a percentage or an integer (pixels)")
return pixels_or_percent_validator(value) return pixels_or_percent_validator(value)
@ -403,6 +404,7 @@ class TextValidator(LValidator):
lv_text = TextValidator() lv_text = TextValidator()
lv_float = LValidator(cv.float_, cg.float_) lv_float = LValidator(cv.float_, cg.float_)
lv_int = LValidator(cv.int_, cg.int_) 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)) lv_brightness = LValidator(cv.percentage, cg.float_, retmapper=lambda x: int(x * 255))

View file

@ -183,17 +183,11 @@ class LvContext(LambdaContext):
super().__init__(parameters=self.args) super().__init__(parameters=self.args)
self.lv_component = lv_component self.lv_component = lv_component
async def add_init_lambda(self):
if self.code_list:
cg.add(self.lv_component.add_init_lambda(await self.get_lambda()))
LvContext.added_lambda_count += 1
async def __aexit__(self, exc_type, exc_val, exc_tb): async def __aexit__(self, exc_type, exc_val, exc_tb):
await super().__aexit__(exc_type, exc_val, exc_tb) await super().__aexit__(exc_type, exc_val, exc_tb)
await self.add_init_lambda()
def add(self, expression: Union[Expression, Statement]): def add(self, expression: Union[Expression, Statement]):
self.code_list.append(self.indented_statement(expression)) cg.add(expression)
return expression return expression
def __call__(self, *args): def __call__(self, *args):

View file

@ -5,16 +5,12 @@
#include "lvgl_hal.h" #include "lvgl_hal.h"
#include "lvgl_esphome.h" #include "lvgl_esphome.h"
#include <numeric>
namespace esphome { namespace esphome {
namespace lvgl { namespace lvgl {
static const char *const TAG = "lvgl"; static const char *const TAG = "lvgl";
#if LV_USE_LOG
static void log_cb(const char *buf) {
esp_log_printf_(ESPHOME_LOG_LEVEL_INFO, TAG, 0, "%.*s", (int) strlen(buf) - 1, buf);
}
#endif // LV_USE_LOG
static const char *const EVENT_NAMES[] = { static const char *const EVENT_NAMES[] = {
"NONE", "NONE",
"PRESSED", "PRESSED",
@ -69,30 +65,39 @@ std::string lv_event_code_name_for(uint8_t event_code) {
} }
return str_sprintf("%2d", event_code); return str_sprintf("%2d", event_code);
} }
static void rounder_cb(lv_disp_drv_t *disp_drv, lv_area_t *area) { static void rounder_cb(lv_disp_drv_t *disp_drv, lv_area_t *area) {
// make sure all coordinates are even // cater for display driver chips with special requirements for bounds of partial
if (area->x1 & 1) // draw areas. Extend the draw area to satisfy:
area->x1--; // * Coordinates must be a multiple of draw_rounding
if (!(area->x2 & 1)) auto *comp = static_cast<LvglComponent *>(disp_drv->user_data);
area->x2++; auto draw_rounding = comp->draw_rounding;
if (area->y1 & 1) // round down the start coordinates
area->y1--; area->x1 = area->x1 / draw_rounding * draw_rounding;
if (!(area->y2 & 1)) area->y1 = area->y1 / draw_rounding * draw_rounding;
area->y2++; // round up the end coordinates
area->x2 = (area->x2 + draw_rounding) / draw_rounding * draw_rounding - 1;
area->y2 = (area->y2 + draw_rounding) / draw_rounding * draw_rounding - 1;
} }
lv_event_code_t lv_api_event; // NOLINT lv_event_code_t lv_api_event; // NOLINT
lv_event_code_t lv_update_event; // NOLINT lv_event_code_t lv_update_event; // NOLINT
void LvglComponent::dump_config() { ESP_LOGCONFIG(TAG, "LVGL:"); } 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);
}
void LvglComponent::set_paused(bool paused, bool show_snow) { void LvglComponent::set_paused(bool paused, bool show_snow) {
this->paused_ = paused; this->paused_ = paused;
this->show_snow_ = show_snow; this->show_snow_ = show_snow;
this->snow_line_ = 0;
if (!paused && lv_scr_act() != nullptr) { if (!paused && lv_scr_act() != nullptr) {
lv_disp_trig_activity(this->disp_); // resets the inactivity time lv_disp_trig_activity(this->disp_); // resets the inactivity time
lv_obj_invalidate(lv_scr_act()); lv_obj_invalidate(lv_scr_act());
} }
this->pause_callbacks_.call(paused);
} }
void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event) { void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event) {
lv_obj_add_event_cb(obj, callback, event, this); lv_obj_add_event_cb(obj, callback, event, this);
} }
@ -133,18 +138,63 @@ void LvglComponent::show_prev_page(lv_scr_load_anim_t anim, uint32_t time) {
} while (this->pages_[this->current_page_]->skip); // skip empty pages() } while (this->pages_[this->current_page_]->skip); // skip empty pages()
this->show_page(this->current_page_, anim, time); this->show_page(this->current_page_, anim, time);
} }
void LvglComponent::draw_buffer_(const lv_area_t *area, const uint8_t *ptr) { void LvglComponent::draw_buffer_(const lv_area_t *area, lv_color_t *ptr) {
auto width = lv_area_get_width(area);
auto height = lv_area_get_height(area);
auto x1 = area->x1;
auto y1 = area->y1;
lv_color_t *dst = this->rotate_buf_;
switch (this->rotation) {
case display::DISPLAY_ROTATION_90_DEGREES:
for (lv_coord_t x = height; x-- != 0;) {
for (lv_coord_t y = 0; y != width; y++) {
dst[y * height + x] = *ptr++;
}
}
y1 = x1;
x1 = this->disp_drv_.ver_res - area->y1 - height;
width = height;
height = lv_area_get_width(area);
break;
case display::DISPLAY_ROTATION_180_DEGREES:
for (lv_coord_t y = height; y-- != 0;) {
for (lv_coord_t x = width; x-- != 0;) {
dst[y * width + x] = *ptr++;
}
}
x1 = this->disp_drv_.hor_res - x1 - width;
y1 = this->disp_drv_.ver_res - y1 - height;
break;
case display::DISPLAY_ROTATION_270_DEGREES:
for (lv_coord_t x = 0; x != height; x++) {
for (lv_coord_t y = width; y-- != 0;) {
dst[y * height + x] = *ptr++;
}
}
x1 = y1;
y1 = this->disp_drv_.hor_res - area->x1 - width;
width = height;
height = lv_area_get_width(area);
break;
default:
dst = ptr;
break;
}
for (auto *display : this->displays_) { for (auto *display : this->displays_) {
display->draw_pixels_at(area->x1, area->y1, lv_area_get_width(area), lv_area_get_height(area), ptr, ESP_LOGV(TAG, "draw buffer x1=%d, y1=%d, width=%d, height=%d", x1, y1, width, height);
display::COLOR_ORDER_RGB, LV_BITNESS, LV_COLOR_16_SWAP); display->draw_pixels_at(x1, y1, width, height, (const uint8_t *) dst, display::COLOR_ORDER_RGB, LV_BITNESS,
LV_COLOR_16_SWAP);
} }
} }
void LvglComponent::flush_cb_(lv_disp_drv_t *disp_drv, const lv_area_t *area, lv_color_t *color_p) { void LvglComponent::flush_cb_(lv_disp_drv_t *disp_drv, const lv_area_t *area, lv_color_t *color_p) {
if (!this->paused_) { if (!this->paused_) {
auto now = millis(); auto now = millis();
this->draw_buffer_(area, (const uint8_t *) color_p); this->draw_buffer_(area, color_p);
ESP_LOGV(TAG, "flush_cb, area=%d/%d, %d/%d took %dms", area->x1, area->y1, lv_area_get_width(area), ESP_LOGVV(TAG, "flush_cb, area=%d/%d, %d/%d took %dms", area->x1, area->y1, lv_area_get_width(area),
lv_area_get_height(area), (int) (millis() - now)); lv_area_get_height(area), (int) (millis() - now));
} }
lv_disp_flush_ready(disp_drv); lv_disp_flush_ready(disp_drv);
@ -160,6 +210,13 @@ IdleTrigger::IdleTrigger(LvglComponent *parent, TemplatableValue<uint32_t> timeo
}); });
} }
PauseTrigger::PauseTrigger(LvglComponent *parent, TemplatableValue<bool> paused) : paused_(std::move(paused)) {
parent->add_on_pause_callback([this](bool pausing) {
if (this->paused_.value() == pausing)
this->trigger();
});
}
#ifdef USE_LVGL_TOUCHSCREEN #ifdef USE_LVGL_TOUCHSCREEN
LVTouchListener::LVTouchListener(uint16_t long_press_time, uint16_t long_press_repeat_time) { LVTouchListener::LVTouchListener(uint16_t long_press_time, uint16_t long_press_repeat_time) {
lv_indev_drv_init(&this->drv_); lv_indev_drv_init(&this->drv_);
@ -203,6 +260,39 @@ LVEncoderListener::LVEncoderListener(lv_indev_type_t type, uint16_t lpt, uint16_
} }
#endif // USE_LVGL_KEY_LISTENER #endif // USE_LVGL_KEY_LISTENER
#if defined(USE_LVGL_DROPDOWN) || defined(LV_USE_ROLLER)
std::string LvSelectable::get_selected_text() {
auto selected = this->get_selected_index();
if (selected >= this->options_.size())
return "";
return this->options_[selected];
}
static std::string join_string(std::vector<std::string> options) {
return std::accumulate(
options.begin(), options.end(), std::string(),
[](const std::string &a, const std::string &b) -> std::string { return a + (a.length() > 0 ? "\n" : "") + b; });
}
void LvSelectable::set_selected_text(const std::string &text, lv_anim_enable_t anim) {
auto index = std::find(this->options_.begin(), this->options_.end(), text);
if (index != this->options_.end()) {
this->set_selected_index(index - this->options_.begin(), anim);
lv_event_send(this->obj, lv_api_event, nullptr);
}
}
void LvSelectable::set_options(std::vector<std::string> options) {
auto index = this->get_selected_index();
if (index >= options.size())
index = options.size() - 1;
this->options_ = std::move(options);
this->set_option_string(join_string(this->options_).c_str());
lv_event_send(this->obj, LV_EVENT_REFRESH, nullptr);
this->set_selected_index(index, LV_ANIM_OFF);
}
#endif // USE_LVGL_DROPDOWN || LV_USE_ROLLER
#ifdef USE_LVGL_BUTTONMATRIX #ifdef USE_LVGL_BUTTONMATRIX
void LvButtonMatrixType::set_obj(lv_obj_t *lv_obj) { void LvButtonMatrixType::set_obj(lv_obj_t *lv_obj) {
LvCompound::set_obj(lv_obj); LvCompound::set_obj(lv_obj);
@ -261,45 +351,75 @@ void LvKeyboardType::set_obj(lv_obj_t *lv_obj) {
#endif // USE_LVGL_KEYBOARD #endif // USE_LVGL_KEYBOARD
void LvglComponent::write_random_() { void LvglComponent::write_random_() {
// length of 2 lines in 32 bit units int iterations = 6 - lv_disp_get_inactive_time(this->disp_) / 60000;
// we write 2 lines for the benefit of displays that won't write one line at a time. if (iterations <= 0)
size_t line_len = this->disp_drv_.hor_res * LV_COLOR_DEPTH / 8 / 4 * 2; iterations = 1;
while (iterations-- != 0) {
auto col = random_uint32() % this->disp_drv_.hor_res;
col = col / this->draw_rounding * this->draw_rounding;
auto row = random_uint32() % this->disp_drv_.ver_res;
row = row / this->draw_rounding * this->draw_rounding;
auto size = (random_uint32() % 32) / this->draw_rounding * this->draw_rounding - 1;
lv_area_t area;
area.x1 = col;
area.y1 = row;
area.x2 = col + size;
area.y2 = row + size;
if (area.x2 >= this->disp_drv_.hor_res)
area.x2 = this->disp_drv_.hor_res - 1;
if (area.y2 >= this->disp_drv_.ver_res)
area.y2 = this->disp_drv_.ver_res - 1;
size_t line_len = lv_area_get_width(&area) * lv_area_get_height(&area) / 2;
for (size_t i = 0; i != line_len; i++) { for (size_t i = 0; i != line_len; i++) {
((uint32_t *) (this->draw_buf_.buf1))[i] = random_uint32(); ((uint32_t *) (this->draw_buf_.buf1))[i] = random_uint32();
} }
lv_area_t area; this->draw_buffer_(&area, (lv_color_t *) this->draw_buf_.buf1);
area.x1 = 0;
area.x2 = this->disp_drv_.hor_res - 1;
if (this->snow_line_ == this->disp_drv_.ver_res / 2) {
area.y1 = static_cast<lv_coord_t>(random_uint32() % (this->disp_drv_.ver_res / 2) * 2);
} else {
area.y1 = this->snow_line_++ * 2;
} }
// write 2 lines
area.y2 = area.y1 + 1;
this->draw_buffer_(&area, (const uint8_t *) this->draw_buf_.buf1);
} }
void LvglComponent::setup() { /**
ESP_LOGCONFIG(TAG, "LVGL Setup starts"); * @class LvglComponent
#if LV_USE_LOG * @brief Component for rendering LVGL.
lv_log_register_print_cb(log_cb); *
#endif * This component renders LVGL widgets on a display. Some initialisation must be done in the constructor
* since LVGL needs to be initialised before any widgets can be created.
*
* @param displays a list of displays to render onto. All displays must have the same
* resolution.
* @param buffer_frac the fraction of the display resolution to use for the LVGL
* draw buffer. A higher value will make animations smoother but
* also increase memory usage.
* @param full_refresh if true, the display will be fully refreshed on every frame.
* If false, only changed areas will be updated.
* @param draw_rounding the rounding to use when drawing. A value of 1 will draw
* without any rounding, a value of 2 will round to the nearest
* multiple of 2, and so on.
* @param resume_on_input if true, this component will resume rendering when the user
* presses a key or clicks on the screen.
*/
LvglComponent::LvglComponent(std::vector<display::Display *> displays, float buffer_frac, bool full_refresh,
int draw_rounding, bool resume_on_input)
: draw_rounding(draw_rounding),
displays_(std::move(displays)),
buffer_frac_(buffer_frac),
full_refresh_(full_refresh),
resume_on_input_(resume_on_input) {
lv_init(); lv_init();
lv_update_event = static_cast<lv_event_code_t>(lv_event_register_id()); lv_update_event = static_cast<lv_event_code_t>(lv_event_register_id());
lv_api_event = static_cast<lv_event_code_t>(lv_event_register_id()); lv_api_event = static_cast<lv_event_code_t>(lv_event_register_id());
auto *display = this->displays_[0]; auto *display = this->displays_[0];
size_t buffer_pixels = display->get_width() * display->get_height() / this->buffer_frac_; size_t buffer_pixels = display->get_width() * display->get_height() / this->buffer_frac_;
auto buf_bytes = buffer_pixels * LV_COLOR_DEPTH / 8; auto buf_bytes = buffer_pixels * LV_COLOR_DEPTH / 8;
auto *buf = lv_custom_mem_alloc(buf_bytes); this->rotation = display->get_rotation();
if (buf == nullptr) { if (this->rotation != display::DISPLAY_ROTATION_0_DEGREES) {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_ERROR this->rotate_buf_ = static_cast<lv_color_t *>(lv_custom_mem_alloc(buf_bytes)); // NOLINT
ESP_LOGE(TAG, "Malloc failed to allocate %zu bytes", buf_bytes); if (this->rotate_buf_ == nullptr)
#endif
this->mark_failed();
this->status_set_error("Memory allocation failure");
return; return;
} }
auto *buf = lv_custom_mem_alloc(buf_bytes); // NOLINT
if (buf == nullptr)
return;
lv_disp_draw_buf_init(&this->draw_buf_, buf, nullptr, buffer_pixels); lv_disp_draw_buf_init(&this->draw_buf_, buf, nullptr, buffer_pixels);
lv_disp_drv_init(&this->disp_drv_); lv_disp_drv_init(&this->disp_drv_);
this->disp_drv_.draw_buf = &this->draw_buf_; this->disp_drv_.draw_buf = &this->draw_buf_;
@ -307,33 +427,36 @@ void LvglComponent::setup() {
this->disp_drv_.full_refresh = this->full_refresh_; this->disp_drv_.full_refresh = this->full_refresh_;
this->disp_drv_.flush_cb = static_flush_cb; this->disp_drv_.flush_cb = static_flush_cb;
this->disp_drv_.rounder_cb = rounder_cb; this->disp_drv_.rounder_cb = rounder_cb;
switch (display->get_rotation()) {
case display::DISPLAY_ROTATION_0_DEGREES:
break;
case display::DISPLAY_ROTATION_90_DEGREES:
this->disp_drv_.sw_rotate = true;
this->disp_drv_.rotated = LV_DISP_ROT_90;
break;
case display::DISPLAY_ROTATION_180_DEGREES:
this->disp_drv_.sw_rotate = true;
this->disp_drv_.rotated = LV_DISP_ROT_180;
break;
case display::DISPLAY_ROTATION_270_DEGREES:
this->disp_drv_.sw_rotate = true;
this->disp_drv_.rotated = LV_DISP_ROT_270;
break;
}
display->set_rotation(display::DISPLAY_ROTATION_0_DEGREES);
this->disp_drv_.hor_res = (lv_coord_t) display->get_width(); this->disp_drv_.hor_res = (lv_coord_t) display->get_width();
this->disp_drv_.ver_res = (lv_coord_t) display->get_height(); this->disp_drv_.ver_res = (lv_coord_t) display->get_height();
ESP_LOGV(TAG, "sw_rotate = %d, rotated=%d", this->disp_drv_.sw_rotate, this->disp_drv_.rotated);
this->disp_ = lv_disp_drv_register(&this->disp_drv_); this->disp_ = lv_disp_drv_register(&this->disp_drv_);
for (const auto &v : this->init_lambdas_) }
v(this);
void LvglComponent::setup() {
if (this->draw_buf_.buf1 == nullptr) {
this->mark_failed();
this->status_set_error("Memory allocation failure");
return;
}
ESP_LOGCONFIG(TAG, "LVGL Setup starts");
#if LV_USE_LOG
lv_log_register_print_cb([](const char *buf) {
auto next = strchr(buf, ')');
if (next != nullptr)
buf = next + 1;
while (isspace(*buf))
buf++;
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); this->show_page(0, LV_SCR_LOAD_ANIM_NONE, 0);
lv_disp_trig_activity(this->disp_); lv_disp_trig_activity(this->disp_);
ESP_LOGCONFIG(TAG, "LVGL Setup complete"); ESP_LOGCONFIG(TAG, "LVGL Setup complete");
} }
void LvglComponent::update() { void LvglComponent::update() {
// update indicators // update indicators
if (this->paused_) { if (this->paused_) {
@ -348,13 +471,6 @@ void LvglComponent::loop() {
} }
lv_timer_handler_run_in_period(5); lv_timer_handler_run_in_period(5);
} }
bool lv_is_pre_initialise() {
if (!lv_is_initialized()) {
ESP_LOGE(TAG, "LVGL call before component is initialised");
return true;
}
return false;
}
#ifdef USE_LVGL_ANIMIMG #ifdef USE_LVGL_ANIMIMG
void lv_animimg_stop(lv_obj_t *obj) { void lv_animimg_stop(lv_obj_t *obj) {

View file

@ -4,6 +4,9 @@
#ifdef USE_BINARY_SENSOR #ifdef USE_BINARY_SENSOR
#include "esphome/components/binary_sensor/binary_sensor.h" #include "esphome/components/binary_sensor/binary_sensor.h"
#endif // USE_BINARY_SENSOR #endif // USE_BINARY_SENSOR
#ifdef USE_LVGL_IMAGE
#include "esphome/components/image/image.h"
#endif // USE_LVGL_IMAGE
#ifdef USE_LVGL_ROTARY_ENCODER #ifdef USE_LVGL_ROTARY_ENCODER
#include "esphome/components/rotary_encoder/rotary_encoder.h" #include "esphome/components/rotary_encoder/rotary_encoder.h"
#endif // USE_LVGL_ROTARY_ENCODER #endif // USE_LVGL_ROTARY_ENCODER
@ -18,11 +21,9 @@
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include <lvgl.h> #include <lvgl.h>
#include <vector>
#include <map> #include <map>
#ifdef USE_LVGL_IMAGE #include <utility>
#include "esphome/components/image/image.h" #include <vector>
#endif // USE_LVGL_IMAGE
#ifdef USE_LVGL_FONT #ifdef USE_LVGL_FONT
#include "esphome/components/font/font.h" #include "esphome/components/font/font.h"
@ -41,7 +42,6 @@ namespace lvgl {
extern lv_event_code_t lv_api_event; // NOLINT extern lv_event_code_t lv_api_event; // NOLINT
extern lv_event_code_t lv_update_event; // NOLINT extern lv_event_code_t lv_update_event; // NOLINT
extern std::string lv_event_code_name_for(uint8_t event_code); extern std::string lv_event_code_name_for(uint8_t event_code);
extern bool lv_is_pre_initialise();
#if LV_COLOR_DEPTH == 16 #if LV_COLOR_DEPTH == 16
static const display::ColorBitness LV_BITNESS = display::ColorBitness::COLOR_BITNESS_565; static const display::ColorBitness LV_BITNESS = display::ColorBitness::COLOR_BITNESS_565;
#elif LV_COLOR_DEPTH == 32 #elif LV_COLOR_DEPTH == 32
@ -50,6 +50,14 @@ static const display::ColorBitness LV_BITNESS = display::ColorBitness::COLOR_BIT
static const display::ColorBitness LV_BITNESS = display::ColorBitness::COLOR_BITNESS_332; static const display::ColorBitness LV_BITNESS = display::ColorBitness::COLOR_BITNESS_332;
#endif // LV_COLOR_DEPTH #endif // LV_COLOR_DEPTH
#ifdef USE_LVGL_IMAGE
// Shortcut / overload, so that the source of an image can easily be updated
// from within a lambda.
inline void lv_img_set_src(lv_obj_t *obj, esphome::image::Image *image) {
lv_img_set_src(obj, image->get_lv_img_dsc());
}
#endif // USE_LVGL_IMAGE
// Parent class for things that wrap an LVGL object // Parent class for things that wrap an LVGL object
class LvCompound { class LvCompound {
public: public:
@ -110,6 +118,8 @@ class LvglComponent : public PollingComponent {
constexpr static const char *const TAG = "lvgl"; constexpr static const char *const TAG = "lvgl";
public: public:
LvglComponent(std::vector<display::Display *> displays, float buffer_frac, bool full_refresh, int draw_rounding,
bool resume_on_input);
static void static_flush_cb(lv_disp_drv_t *disp_drv, const lv_area_t *area, lv_color_t *color_p); static void static_flush_cb(lv_disp_drv_t *disp_drv, const lv_area_t *area, lv_color_t *color_p);
float get_setup_priority() const override { return setup_priority::PROCESSOR; } float get_setup_priority() const override { return setup_priority::PROCESSOR; }
@ -119,19 +129,27 @@ class LvglComponent : public PollingComponent {
void add_on_idle_callback(std::function<void(uint32_t)> &&callback) { void add_on_idle_callback(std::function<void(uint32_t)> &&callback) {
this->idle_callbacks_.add(std::move(callback)); this->idle_callbacks_.add(std::move(callback));
} }
void add_display(display::Display *display) { this->displays_.push_back(display); } void add_on_pause_callback(std::function<void(bool)> &&callback) { this->pause_callbacks_.add(std::move(callback)); }
void add_init_lambda(const std::function<void(LvglComponent *)> &lamb) { this->init_lambdas_.push_back(lamb); }
void dump_config() override; void dump_config() override;
void set_full_refresh(bool full_refresh) { this->full_refresh_ = full_refresh; }
bool is_idle(uint32_t idle_ms) { return lv_disp_get_inactive_time(this->disp_) > idle_ms; } bool is_idle(uint32_t idle_ms) { return lv_disp_get_inactive_time(this->disp_) > idle_ms; }
void set_buffer_frac(size_t frac) { this->buffer_frac_ = frac; }
lv_disp_t *get_disp() { return this->disp_; } lv_disp_t *get_disp() { return this->disp_; }
lv_obj_t *get_scr_act() { return lv_disp_get_scr_act(this->disp_); }
// Pause or resume the display.
// @param paused If true, pause the display. If false, resume the display.
// @param show_snow If true, show the snow effect when paused.
void set_paused(bool paused, bool show_snow); void set_paused(bool paused, bool show_snow);
bool is_paused() const { return this->paused_; }
// If the display is paused and we have resume_on_input_ set to true, resume the display.
void maybe_wakeup() {
if (this->paused_ && this->resume_on_input_) {
this->set_paused(false, false);
}
}
void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event); void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event);
void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, lv_event_code_t event2); void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, lv_event_code_t event2);
void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, lv_event_code_t event2, void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, lv_event_code_t event2,
lv_event_code_t event3); lv_event_code_t event3);
bool is_paused() const { return this->paused_; }
void add_page(LvPageType *page); void add_page(LvPageType *page);
void show_page(size_t index, lv_scr_load_anim_t anim, uint32_t time); void show_page(size_t index, lv_scr_load_anim_t anim, uint32_t time);
void show_next_page(lv_scr_load_anim_t anim, uint32_t time); void show_next_page(lv_scr_load_anim_t anim, uint32_t time);
@ -144,12 +162,21 @@ class LvglComponent : public PollingComponent {
lv_group_focus_obj(mark); lv_group_focus_obj(mark);
} }
} }
// rounding factor to align bounds of update area when drawing
size_t draw_rounding{2};
display::DisplayRotation rotation{display::DISPLAY_ROTATION_0_DEGREES};
protected: protected:
void write_random_(); void write_random_();
void draw_buffer_(const lv_area_t *area, const uint8_t *ptr); void draw_buffer_(const lv_area_t *area, lv_color_t *ptr);
void flush_cb_(lv_disp_drv_t *disp_drv, const lv_area_t *area, lv_color_t *color_p); void flush_cb_(lv_disp_drv_t *disp_drv, const lv_area_t *area, lv_color_t *color_p);
std::vector<display::Display *> displays_{}; std::vector<display::Display *> displays_{};
size_t buffer_frac_{1};
bool full_refresh_{};
bool resume_on_input_{};
lv_disp_draw_buf_t draw_buf_{}; lv_disp_draw_buf_t draw_buf_{};
lv_disp_drv_t disp_drv_{}; lv_disp_drv_t disp_drv_{};
lv_disp_t *disp_{}; lv_disp_t *disp_{};
@ -157,14 +184,12 @@ class LvglComponent : public PollingComponent {
std::vector<LvPageType *> pages_{}; std::vector<LvPageType *> pages_{};
size_t current_page_{0}; size_t current_page_{0};
bool show_snow_{}; bool show_snow_{};
lv_coord_t snow_line_{};
bool page_wrap_{true}; bool page_wrap_{true};
std::map<lv_group_t *, lv_obj_t *> focus_marks_{}; std::map<lv_group_t *, lv_obj_t *> focus_marks_{};
std::vector<std::function<void(LvglComponent *lv_component)>> init_lambdas_;
CallbackManager<void(uint32_t)> idle_callbacks_{}; CallbackManager<void(uint32_t)> idle_callbacks_{};
size_t buffer_frac_{1}; CallbackManager<void(bool)> pause_callbacks_{};
bool full_refresh_{}; lv_color_t *rotate_buf_{};
}; };
class IdleTrigger : public Trigger<> { class IdleTrigger : public Trigger<> {
@ -176,6 +201,14 @@ class IdleTrigger : public Trigger<> {
bool is_idle_{}; bool is_idle_{};
}; };
class PauseTrigger : public Trigger<> {
public:
explicit PauseTrigger(LvglComponent *parent, TemplatableValue<bool> paused);
protected:
TemplatableValue<bool> paused_;
};
template<typename... Ts> class LvglAction : public Action<Ts...>, public Parented<LvglComponent> { template<typename... Ts> class LvglAction : public Action<Ts...>, public Parented<LvglComponent> {
public: public:
explicit LvglAction(std::function<void(LvglComponent *)> &&lamb) : action_(std::move(lamb)) {} explicit LvglAction(std::function<void(LvglComponent *)> &&lamb) : action_(std::move(lamb)) {}
@ -200,7 +233,10 @@ class LVTouchListener : public touchscreen::TouchListener, public Parented<LvglC
public: public:
LVTouchListener(uint16_t long_press_time, uint16_t long_press_repeat_time); LVTouchListener(uint16_t long_press_time, uint16_t long_press_repeat_time);
void update(const touchscreen::TouchPoints_t &tpoints) override; void update(const touchscreen::TouchPoints_t &tpoints) override;
void release() override { touch_pressed_ = false; } void release() override {
touch_pressed_ = false;
this->parent_->maybe_wakeup();
}
lv_indev_drv_t *get_drv() { return &this->drv_; } lv_indev_drv_t *get_drv() { return &this->drv_; }
protected: protected:
@ -215,6 +251,7 @@ class LVEncoderListener : public Parented<LvglComponent> {
public: public:
LVEncoderListener(lv_indev_type_t type, uint16_t lpt, uint16_t lprt); LVEncoderListener(lv_indev_type_t type, uint16_t lpt, uint16_t lprt);
#ifdef USE_BINARY_SENSOR
void set_left_button(binary_sensor::BinarySensor *left_button) { void set_left_button(binary_sensor::BinarySensor *left_button) {
left_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_LEFT, state); }); left_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_LEFT, state); });
} }
@ -225,6 +262,7 @@ class LVEncoderListener : public Parented<LvglComponent> {
void set_enter_button(binary_sensor::BinarySensor *enter_button) { void set_enter_button(binary_sensor::BinarySensor *enter_button) {
enter_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_ENTER, state); }); enter_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_ENTER, state); });
} }
#endif
#ifdef USE_LVGL_ROTARY_ENCODER #ifdef USE_LVGL_ROTARY_ENCODER
void set_sensor(rotary_encoder::RotaryEncoderSensor *sensor) { void set_sensor(rotary_encoder::RotaryEncoderSensor *sensor) {
@ -236,12 +274,18 @@ class LVEncoderListener : public Parented<LvglComponent> {
if (!this->parent_->is_paused()) { if (!this->parent_->is_paused()) {
this->pressed_ = pressed; this->pressed_ = pressed;
this->key_ = key; this->key_ = key;
} else if (!pressed) {
// maybe wakeup on release if paused
this->parent_->maybe_wakeup();
} }
} }
void set_count(int32_t count) { void set_count(int32_t count) {
if (!this->parent_->is_paused()) if (!this->parent_->is_paused()) {
this->count_ = count; this->count_ = count;
} else {
this->parent_->maybe_wakeup();
}
} }
lv_indev_drv_t *get_drv() { return &this->drv_; } lv_indev_drv_t *get_drv() { return &this->drv_; }
@ -255,6 +299,48 @@ class LVEncoderListener : public Parented<LvglComponent> {
}; };
#endif // USE_LVGL_KEY_LISTENER #endif // USE_LVGL_KEY_LISTENER
#if defined(USE_LVGL_DROPDOWN) || defined(LV_USE_ROLLER)
class LvSelectable : public LvCompound {
public:
virtual size_t get_selected_index() = 0;
virtual void set_selected_index(size_t index, lv_anim_enable_t anim) = 0;
void set_selected_text(const std::string &text, lv_anim_enable_t anim);
std::string get_selected_text();
std::vector<std::string> get_options() { return this->options_; }
void set_options(std::vector<std::string> options);
protected:
virtual void set_option_string(const char *options) = 0;
std::vector<std::string> options_{};
};
#ifdef USE_LVGL_DROPDOWN
class LvDropdownType : public LvSelectable {
public:
size_t get_selected_index() override { return lv_dropdown_get_selected(this->obj); }
void set_selected_index(size_t index, lv_anim_enable_t anim) override { lv_dropdown_set_selected(this->obj, index); }
protected:
void set_option_string(const char *options) override { lv_dropdown_set_options(this->obj, options); }
};
#endif // USE_LVGL_DROPDOWN
#ifdef USE_LVGL_ROLLER
class LvRollerType : public LvSelectable {
public:
size_t get_selected_index() override { return lv_roller_get_selected(this->obj); }
void set_selected_index(size_t index, lv_anim_enable_t anim) override {
lv_roller_set_selected(this->obj, index, anim);
}
void set_mode(lv_roller_mode_t mode) { this->mode_ = mode; }
protected:
void set_option_string(const char *options) override { lv_roller_set_options(this->obj, options, this->mode_); }
lv_roller_mode_t mode_{LV_ROLLER_MODE_NORMAL};
};
#endif
#endif // defined(USE_LVGL_DROPDOWN) || defined(LV_USE_ROLLER)
#ifdef USE_LVGL_BUTTONMATRIX #ifdef USE_LVGL_BUTTONMATRIX
class LvButtonMatrixType : public key_provider::KeyProvider, public LvCompound { class LvButtonMatrixType : public key_provider::KeyProvider, public LvCompound {
public: public:

View file

@ -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 <lvgl.h>
namespace esphome {
namespace lvgl {} // namespace lvgl
} // namespace esphome
#endif // USE_LVGL

View file

@ -91,7 +91,7 @@ STYLE_PROPS = {
"arc_opa": lvalid.opacity, "arc_opa": lvalid.opacity,
"arc_color": lvalid.lv_color, "arc_color": lvalid.lv_color,
"arc_rounded": lvalid.lv_bool, "arc_rounded": lvalid.lv_bool,
"arc_width": cv.positive_int, "arc_width": lvalid.lv_positive_int,
"anim_time": lvalid.lv_milliseconds, "anim_time": lvalid.lv_milliseconds,
"bg_color": lvalid.lv_color, "bg_color": lvalid.lv_color,
"bg_grad": lv_gradient, "bg_grad": lv_gradient,
@ -111,7 +111,7 @@ STYLE_PROPS = {
"border_side": df.LvConstant( "border_side": df.LvConstant(
"LV_BORDER_SIDE_", "NONE", "TOP", "BOTTOM", "LEFT", "RIGHT", "INTERNAL" "LV_BORDER_SIDE_", "NONE", "TOP", "BOTTOM", "LEFT", "RIGHT", "INTERNAL"
).several_of, ).several_of,
"border_width": cv.positive_int, "border_width": lvalid.lv_positive_int,
"clip_corner": lvalid.lv_bool, "clip_corner": lvalid.lv_bool,
"color_filter_opa": lvalid.opacity, "color_filter_opa": lvalid.opacity,
"height": lvalid.size, "height": lvalid.size,
@ -134,11 +134,11 @@ STYLE_PROPS = {
"pad_right": lvalid.pixels, "pad_right": lvalid.pixels,
"pad_top": lvalid.pixels, "pad_top": lvalid.pixels,
"shadow_color": lvalid.lv_color, "shadow_color": lvalid.lv_color,
"shadow_ofs_x": cv.int_, "shadow_ofs_x": lvalid.lv_int,
"shadow_ofs_y": cv.int_, "shadow_ofs_y": lvalid.lv_int,
"shadow_opa": lvalid.opacity, "shadow_opa": lvalid.opacity,
"shadow_spread": cv.int_, "shadow_spread": lvalid.lv_int,
"shadow_width": cv.positive_int, "shadow_width": lvalid.lv_positive_int,
"text_align": df.LvConstant( "text_align": df.LvConstant(
"LV_TEXT_ALIGN_", "LEFT", "CENTER", "RIGHT", "AUTO" "LV_TEXT_ALIGN_", "LEFT", "CENTER", "RIGHT", "AUTO"
).one_of, ).one_of,
@ -150,7 +150,7 @@ STYLE_PROPS = {
"text_letter_space": cv.positive_int, "text_letter_space": cv.positive_int,
"text_line_space": cv.positive_int, "text_line_space": cv.positive_int,
"text_opa": lvalid.opacity, "text_opa": lvalid.opacity,
"transform_angle": lvalid.angle, "transform_angle": lvalid.lv_angle,
"transform_height": lvalid.pixels_or_percent, "transform_height": lvalid.pixels_or_percent,
"transform_pivot_x": lvalid.pixels_or_percent, "transform_pivot_x": lvalid.pixels_or_percent,
"transform_pivot_y": lvalid.pixels_or_percent, "transform_pivot_y": lvalid.pixels_or_percent,
@ -216,7 +216,7 @@ def automation_schema(typ: LvType):
events = df.LV_EVENT_TRIGGERS + (CONF_ON_VALUE,) events = df.LV_EVENT_TRIGGERS + (CONF_ON_VALUE,)
else: else:
events = df.LV_EVENT_TRIGGERS events = df.LV_EVENT_TRIGGERS
args = [typ.get_arg_type()] if isinstance(typ, LvType) else [] args = typ.get_arg_type() if isinstance(typ, LvType) else []
args.append(lv_event_t_ptr) args.append(lv_event_t_ptr)
return { return {
cv.Optional(event): validate_automation( cv.Optional(event): validate_automation(

View file

@ -3,18 +3,10 @@ from esphome.components import select
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import CONF_OPTIONS from esphome.const import CONF_OPTIONS
from ..defines import CONF_ANIMATED, CONF_LVGL_ID, CONF_WIDGET from ..defines import CONF_ANIMATED, CONF_LVGL_ID, CONF_WIDGET, literal
from ..lvcode import ( from ..lvcode import LvContext
API_EVENT,
EVENT_ARG,
UPDATE_EVENT,
LambdaContext,
LvContext,
lv,
lv_add,
)
from ..schemas import LVGL_SCHEMA from ..schemas import LVGL_SCHEMA
from ..types import LV_EVENT, LvSelect, lvgl_ns from ..types import LvSelect, lvgl_ns
from ..widgets import get_widgets, wait_for_widgets from ..widgets import get_widgets, wait_for_widgets
LVGLSelect = lvgl_ns.class_("LVGLSelect", select.Select) LVGLSelect = lvgl_ns.class_("LVGLSelect", select.Select)
@ -38,20 +30,10 @@ async def to_code(config):
selector = await select.new_select(config, options=options) selector = await select.new_select(config, options=options)
paren = await cg.get_variable(config[CONF_LVGL_ID]) paren = await cg.get_variable(config[CONF_LVGL_ID])
await wait_for_widgets() await wait_for_widgets()
async with LambdaContext(EVENT_ARG) as pub_ctx:
pub_ctx.add(selector.publish_index(widget.get_value()))
async with LambdaContext([(cg.uint16, "v")]) as control:
await widget.set_property("selected", "v", animated=config[CONF_ANIMATED])
lv.event_send(widget.obj, API_EVENT, cg.nullptr)
control.add(selector.publish_index(widget.get_value()))
async with LvContext(paren) as ctx: async with LvContext(paren) as ctx:
lv_add(selector.set_control_lambda(await control.get_lambda()))
ctx.add( ctx.add(
paren.add_event_cb( selector.set_widget(
widget.obj, widget.var,
await pub_ctx.get_lambda(), literal("LV_ANIM_ON" if config[CONF_ANIMATED] else "LV_ANIM_OFF"),
LV_EVENT.VALUE_CHANGED,
UPDATE_EVENT,
) )
) )
lv_add(selector.publish_index(widget.get_value()))

View file

@ -6,58 +6,52 @@
#include "esphome/core/automation.h" #include "esphome/core/automation.h"
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/core/preferences.h" #include "esphome/core/preferences.h"
#include "../lvgl.h"
namespace esphome { namespace esphome {
namespace lvgl { namespace lvgl {
static std::vector<std::string> split_string(const std::string &str) {
std::vector<std::string> strings;
auto delimiter = std::string("\n");
std::string::size_type pos;
std::string::size_type prev = 0;
while ((pos = str.find(delimiter, prev)) != std::string::npos) {
strings.push_back(str.substr(prev, pos - prev));
prev = pos + delimiter.size();
}
// To get the last substring (or only, if delimiter is not found)
strings.push_back(str.substr(prev));
return strings;
}
class LVGLSelect : public select::Select { class LVGLSelect : public select::Select {
public: public:
void set_control_lambda(std::function<void(size_t)> lambda) { void set_widget(LvSelectable *widget, lv_anim_enable_t anim = LV_ANIM_OFF) {
this->control_lambda_ = std::move(lambda); this->widget_ = widget;
this->anim_ = anim;
this->set_options_();
lv_obj_add_event_cb(
this->widget_->obj,
[](lv_event_t *e) {
auto *it = static_cast<LVGLSelect *>(e->user_data);
it->set_options_();
},
LV_EVENT_REFRESH, this);
if (this->initial_state_.has_value()) { if (this->initial_state_.has_value()) {
this->control(this->initial_state_.value()); this->control(this->initial_state_.value());
this->initial_state_.reset(); this->initial_state_.reset();
} }
this->publish();
auto lamb = [](lv_event_t *e) {
auto *self = static_cast<LVGLSelect *>(e->user_data);
self->publish();
};
lv_obj_add_event_cb(this->widget_->obj, lamb, LV_EVENT_VALUE_CHANGED, this);
lv_obj_add_event_cb(this->widget_->obj, lamb, lv_update_event, this);
} }
void publish_index(size_t index) { void publish() { this->publish_state(this->widget_->get_selected_text()); }
auto value = this->at(index);
if (value)
this->publish_state(value.value());
}
void set_options(const char *str) { this->traits.set_options(split_string(str)); }
protected: protected:
void control(const std::string &value) override { void control(const std::string &value) override {
if (this->control_lambda_ != nullptr) { if (this->widget_ != nullptr) {
auto index = index_of(value); this->widget_->set_selected_text(value, this->anim_);
if (index)
this->control_lambda_(index.value());
} else { } else {
this->initial_state_ = value.c_str(); this->initial_state_ = value;
} }
} }
void set_options_() { this->traits.set_options(this->widget_->get_options()); }
std::function<void(size_t)> control_lambda_{}; LvSelectable *widget_{};
optional<const char *> initial_state_{}; optional<std::string> initial_state_{};
lv_anim_enable_t anim_{LV_ANIM_OFF};
}; };
} // namespace lvgl } // namespace lvgl

View file

@ -17,8 +17,6 @@ from .types import lv_lambda_t, lv_obj_t, lv_obj_t_ptr
from .widgets import Widget, add_widgets, set_obj_properties, theme_widget_map from .widgets import Widget, add_widgets, set_obj_properties, theme_widget_map
from .widgets.obj import obj_spec from .widgets.obj import obj_spec
TOP_LAYER = literal("lv_disp_get_layer_top(lv_component->get_disp())")
async def styles_to_code(config): async def styles_to_code(config):
"""Convert styles to C__ code.""" """Convert styles to C__ code."""
@ -51,9 +49,10 @@ async def theme_to_code(config):
lv_assign(apply, await context.get_lambda()) lv_assign(apply, await context.get_lambda())
async def add_top_layer(config): async def add_top_layer(lv_component, config):
top_layer = lv.disp_get_layer_top(lv_component.get_disp())
if top_conf := config.get(CONF_TOP_LAYER): if top_conf := config.get(CONF_TOP_LAYER):
with LocalVariable("top_layer", lv_obj_t, TOP_LAYER) as top_layer_obj: with LocalVariable("top_layer", lv_obj_t, top_layer) as top_layer_obj:
top_w = Widget(top_layer_obj, obj_spec, top_conf) top_w = Widget(top_layer_obj, obj_spec, top_conf)
await set_obj_properties(top_w, top_conf) await set_obj_properties(top_w, top_conf)
await add_widgets(top_w, top_conf) await add_widgets(top_w, top_conf)

View file

@ -34,13 +34,13 @@ async def to_code(config):
widget = widget[0] widget = widget[0]
await wait_for_widgets() await wait_for_widgets()
async with LambdaContext([(cg.std_string, "text_value")]) as control: async with LambdaContext([(cg.std_string, "text_value")]) as control:
await widget.set_property("text", "text_value.c_str())") await widget.set_property("text", "text_value.c_str()")
lv.event_send(widget.obj, API_EVENT, None) lv.event_send(widget.obj, API_EVENT, cg.nullptr)
control.add(textvar.publish_state(widget.get_value())) control.add(textvar.publish_state(widget.get_value()))
async with LambdaContext(EVENT_ARG) as lamb: async with LambdaContext(EVENT_ARG) as lamb:
lv_add(textvar.publish_state(widget.get_value())) lv_add(textvar.publish_state(widget.get_value()))
async with LvContext(paren): async with LvContext(paren):
widget.var.set_control_lambda(await control.get_lambda()) lv_add(textvar.set_control_lambda(await control.get_lambda()))
lv_add( lv_add(
paren.add_event_cb( paren.add_event_cb(
widget.obj, widget.obj,

View file

@ -67,9 +67,9 @@ async def add_trigger(conf, lv_component, w, *events):
tid = conf[CONF_TRIGGER_ID] tid = conf[CONF_TRIGGER_ID]
trigger = cg.new_Pvariable(tid) trigger = cg.new_Pvariable(tid)
args = w.get_args() + [(lv_event_t_ptr, "event")] args = w.get_args() + [(lv_event_t_ptr, "event")]
value = w.get_value() value = w.get_values()
await automation.build_automation(trigger, args, conf) await automation.build_automation(trigger, args, conf)
async with LambdaContext(EVENT_ARG, where=tid) as context: async with LambdaContext(EVENT_ARG, where=tid) as context:
with LvConditional(w.is_selected()): with LvConditional(w.is_selected()):
lv_add(trigger.trigger(value, literal("event"))) lv_add(trigger.trigger(*value, literal("event")))
lv_add(lv_component.add_event_cb(w.obj, await context.get_lambda(), *events)) lv_add(lv_component.add_event_cb(w.obj, await context.get_lambda(), *events))

View file

@ -18,7 +18,9 @@ class LvType(cg.MockObjClass):
self.value_property = None self.value_property = None
def get_arg_type(self): def get_arg_type(self):
return self.args[0][0] if len(self.args) else None if len(self.args) == 0:
return None
return [arg[0] for arg in self.args]
class LvNumber(LvType): class LvNumber(LvType):
@ -40,6 +42,7 @@ lv_event_code_t = cg.global_ns.enum("lv_event_code_t")
lv_indev_type_t = cg.global_ns.enum("lv_indev_type_t") lv_indev_type_t = cg.global_ns.enum("lv_indev_type_t")
FontEngine = lvgl_ns.class_("FontEngine") FontEngine = lvgl_ns.class_("FontEngine")
IdleTrigger = lvgl_ns.class_("IdleTrigger", automation.Trigger.template()) IdleTrigger = lvgl_ns.class_("IdleTrigger", automation.Trigger.template())
PauseTrigger = lvgl_ns.class_("PauseTrigger", automation.Trigger.template())
ObjUpdateAction = lvgl_ns.class_("ObjUpdateAction", automation.Action) ObjUpdateAction = lvgl_ns.class_("ObjUpdateAction", automation.Action)
LvglCondition = lvgl_ns.class_("LvglCondition", automation.Condition) LvglCondition = lvgl_ns.class_("LvglCondition", automation.Condition)
LvglAction = lvgl_ns.class_("LvglAction", automation.Action) LvglAction = lvgl_ns.class_("LvglAction", automation.Action)
@ -91,11 +94,13 @@ class LvBoolean(LvType):
class LvSelect(LvType): class LvSelect(LvType):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
parens = kwargs.pop("parents", ()) + (LvCompound,)
super().__init__( super().__init__(
*args, *args,
largs=[(cg.int_, "x")], largs=[(cg.int_, "x"), (cg.std_string, "text")],
lvalue=lambda w: w.get_property("selected"), lvalue=lambda w: [w.var.get_selected_index(), w.var.get_selected_text()],
has_on_value=True, has_on_value=True,
parents=parens,
**kwargs, **kwargs,
) )

View file

@ -55,29 +55,14 @@ theme_widget_map = {}
styles_used = set() styles_used = set()
class LvScrActType(WidgetType):
"""
A "widget" representing the active screen.
"""
def __init__(self):
super().__init__("lv_scr_act()", lv_obj_t, ())
async def to_code(self, w, config: dict):
return []
class Widget: class Widget:
""" """
Represents a Widget. Represents a Widget.
This class has a lot of methods. Adding any more runs foul of lint checks ("too many public methods").
""" """
widgets_completed = False widgets_completed = False
@staticmethod
def set_completed():
Widget.widgets_completed = True
def __init__(self, var, wtype: WidgetType, config: dict = None): def __init__(self, var, wtype: WidgetType, config: dict = None):
self.var = var self.var = var
self.type = wtype self.type = wtype
@ -179,9 +164,20 @@ class Widget:
def get_value(self): def get_value(self):
if isinstance(self.type.w_type, LvType): if isinstance(self.type.w_type, LvType):
return self.type.w_type.value(self) result = self.type.w_type.value(self)
if isinstance(result, list):
return result[0]
return result
return self.obj return self.obj
def get_values(self):
if isinstance(self.type.w_type, LvType):
result = self.type.w_type.value(self)
if isinstance(result, list):
return result
return [result]
return [self.obj]
def get_number_value(self): def get_number_value(self):
value = self.type.mock_obj.get_value(self.obj) value = self.type.mock_obj.get_value(self.obj)
if self.scale == 1.0: if self.scale == 1.0:
@ -213,6 +209,25 @@ class Widget:
widget_map: dict[Any, Widget] = {} widget_map: dict[Any, Widget] = {}
class LvScrActType(WidgetType):
"""
A "widget" representing the active screen.
"""
def __init__(self):
super().__init__("lv_scr_act()", lv_obj_t, ())
async def to_code(self, w, config: dict):
return []
lv_scr_act_spec = LvScrActType()
def get_scr_act(lv_comp: MockObj) -> Widget:
return Widget.create(None, lv_comp.get_scr_act(), lv_scr_act_spec, {})
def get_widget_generator(wid): def get_widget_generator(wid):
""" """
Used to wait for a widget during code generation. Used to wait for a widget during code generation.
@ -443,7 +458,3 @@ async def widget_to_code(w_cnfig, w_type: WidgetType, parent):
await set_obj_properties(w, w_cnfig) await set_obj_properties(w, w_cnfig)
await add_widgets(w, w_cnfig) await add_widgets(w, w_cnfig)
await spec.to_code(w, w_cnfig) await spec.to_code(w, w_cnfig)
lv_scr_act_spec = LvScrActType()
lv_scr_act = Widget.create(None, literal("lv_scr_act()"), lv_scr_act_spec, {})

View file

@ -1,4 +1,3 @@
import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import CONF_OPTIONS from esphome.const import CONF_OPTIONS
@ -9,21 +8,24 @@ from ..defines import (
CONF_SCROLLBAR, CONF_SCROLLBAR,
CONF_SELECTED, CONF_SELECTED,
CONF_SELECTED_INDEX, CONF_SELECTED_INDEX,
CONF_SELECTED_TEXT,
CONF_SYMBOL, CONF_SYMBOL,
DIRECTIONS, DIRECTIONS,
literal, literal,
) )
from ..helpers import lvgl_components_required
from ..lv_validation import lv_int, lv_text, option_string from ..lv_validation import lv_int, lv_text, option_string
from ..lvcode import LocalVariable, lv, lv_expr from ..lvcode import LocalVariable, lv, lv_add, lv_expr
from ..schemas import part_schema from ..schemas import part_schema
from ..types import LvSelect, LvType, lv_obj_t from ..types import LvCompound, LvSelect, LvType, lv_obj_t
from . import Widget, WidgetType, set_obj_properties from . import Widget, WidgetType, set_obj_properties
from .label import CONF_LABEL from .label import CONF_LABEL
CONF_DROPDOWN = "dropdown" CONF_DROPDOWN = "dropdown"
CONF_DROPDOWN_LIST = "dropdown_list" CONF_DROPDOWN_LIST = "dropdown_list"
lv_dropdown_t = LvSelect("lv_dropdown_t") lv_dropdown_t = LvSelect("LvDropdownType", parents=(LvCompound,))
lv_dropdown_list_t = LvType("lv_dropdown_list_t") lv_dropdown_list_t = LvType("lv_dropdown_list_t")
dropdown_list_spec = WidgetType( dropdown_list_spec = WidgetType(
CONF_DROPDOWN_LIST, lv_dropdown_list_t, (CONF_MAIN, CONF_SELECTED, CONF_SCROLLBAR) CONF_DROPDOWN_LIST, lv_dropdown_list_t, (CONF_MAIN, CONF_SELECTED, CONF_SCROLLBAR)
@ -32,7 +34,8 @@ dropdown_list_spec = WidgetType(
DROPDOWN_BASE_SCHEMA = cv.Schema( DROPDOWN_BASE_SCHEMA = cv.Schema(
{ {
cv.Optional(CONF_SYMBOL): lv_text, cv.Optional(CONF_SYMBOL): lv_text,
cv.Optional(CONF_SELECTED_INDEX): cv.templatable(cv.int_), cv.Exclusive(CONF_SELECTED_INDEX, CONF_SELECTED_TEXT): lv_int,
cv.Exclusive(CONF_SELECTED_TEXT, CONF_SELECTED_TEXT): lv_text,
cv.Optional(CONF_DIR, default="BOTTOM"): DIRECTIONS.one_of, cv.Optional(CONF_DIR, default="BOTTOM"): DIRECTIONS.one_of,
cv.Optional(CONF_DROPDOWN_LIST): part_schema(dropdown_list_spec), cv.Optional(CONF_DROPDOWN_LIST): part_schema(dropdown_list_spec),
} }
@ -44,6 +47,12 @@ DROPDOWN_SCHEMA = DROPDOWN_BASE_SCHEMA.extend(
} }
) )
DROPDOWN_UPDATE_SCHEMA = DROPDOWN_BASE_SCHEMA.extend(
{
cv.Optional(CONF_OPTIONS): cv.ensure_list(option_string),
}
)
class DropdownType(WidgetType): class DropdownType(WidgetType):
def __init__(self): def __init__(self):
@ -52,18 +61,21 @@ class DropdownType(WidgetType):
lv_dropdown_t, lv_dropdown_t,
(CONF_MAIN, CONF_INDICATOR), (CONF_MAIN, CONF_INDICATOR),
DROPDOWN_SCHEMA, DROPDOWN_SCHEMA,
DROPDOWN_BASE_SCHEMA, modify_schema=DROPDOWN_UPDATE_SCHEMA,
) )
async def to_code(self, w: Widget, config): async def to_code(self, w: Widget, config):
lvgl_components_required.add(CONF_DROPDOWN)
if options := config.get(CONF_OPTIONS): if options := config.get(CONF_OPTIONS):
text = cg.safe_exp("\n".join(options)) lv_add(w.var.set_options(options))
lv.dropdown_set_options(w.obj, text)
if symbol := config.get(CONF_SYMBOL): if symbol := config.get(CONF_SYMBOL):
lv.dropdown_set_symbol(w.obj, await lv_text.process(symbol)) lv.dropdown_set_symbol(w.var.obj, await lv_text.process(symbol))
if (selected := config.get(CONF_SELECTED_INDEX)) is not None: if (selected := config.get(CONF_SELECTED_INDEX)) is not None:
value = await lv_int.process(selected) value = await lv_int.process(selected)
lv.dropdown_set_selected(w.obj, value) lv_add(w.var.set_selected_index(value, literal("LV_ANIM_OFF")))
if (selected := config.get(CONF_SELECTED_TEXT)) is not None:
value = await lv_text.process(selected)
lv_add(w.var.set_selected_text(value, literal("LV_ANIM_OFF")))
if dirn := config.get(CONF_DIR): if dirn := config.get(CONF_DIR):
lv.dropdown_set_dir(w.obj, literal(dirn)) lv.dropdown_set_dir(w.obj, literal(dirn))
if dlist := config.get(CONF_DROPDOWN_LIST): if dlist := config.get(CONF_DROPDOWN_LIST):

View file

@ -20,6 +20,7 @@ from ..lvcode import (
EVENT_ARG, EVENT_ARG,
LambdaContext, LambdaContext,
LocalVariable, LocalVariable,
lv,
lv_add, lv_add,
lv_assign, lv_assign,
lv_expr, lv_expr,
@ -27,7 +28,6 @@ from ..lvcode import (
lv_Pvariable, lv_Pvariable,
) )
from ..schemas import STYLE_SCHEMA, STYLED_TEXT_SCHEMA, container_schema, part_schema from ..schemas import STYLE_SCHEMA, STYLED_TEXT_SCHEMA, container_schema, part_schema
from ..styles import TOP_LAYER
from ..types import LV_EVENT, char_ptr, lv_obj_t from ..types import LV_EVENT, char_ptr, lv_obj_t
from . import Widget, set_obj_properties from . import Widget, set_obj_properties
from .button import button_spec from .button import button_spec
@ -59,7 +59,7 @@ MSGBOX_SCHEMA = container_schema(
) )
async def msgbox_to_code(conf): async def msgbox_to_code(top_layer, conf):
""" """
Construct a message box. This consists of a full-screen translucent background enclosing a centered container Construct a message box. This consists of a full-screen translucent background enclosing a centered container
with an optional title, body, close button and a button matrix. And any other widgets the user cares to add with an optional title, body, close button and a button matrix. And any other widgets the user cares to add
@ -101,7 +101,7 @@ async def msgbox_to_code(conf):
text = await lv_text.process(conf[CONF_BODY].get(CONF_TEXT, "")) text = await lv_text.process(conf[CONF_BODY].get(CONF_TEXT, ""))
title = await lv_text.process(conf[CONF_TITLE].get(CONF_TEXT, "")) title = await lv_text.process(conf[CONF_TITLE].get(CONF_TEXT, ""))
close_button = conf[CONF_CLOSE_BUTTON] close_button = conf[CONF_CLOSE_BUTTON]
lv_assign(outer, lv_expr.obj_create(TOP_LAYER)) lv_assign(outer, lv_expr.obj_create(top_layer))
lv_obj.set_width(outer, lv_pct(100)) lv_obj.set_width(outer, lv_pct(100))
lv_obj.set_height(outer, lv_pct(100)) lv_obj.set_height(outer, lv_pct(100))
lv_obj.set_style_bg_opa(outer, 128, 0) lv_obj.set_style_bg_opa(outer, 128, 0)
@ -141,6 +141,7 @@ async def msgbox_to_code(conf):
set_btn_data(buttonmatrix.obj, ctrl_list, width_list) set_btn_data(buttonmatrix.obj, ctrl_list, width_list)
async def msgboxes_to_code(config): async def msgboxes_to_code(lv_component, config):
top_layer = lv.disp_get_layer_top(lv_component.get_disp())
for conf in config.get(CONF_MSGBOXES, ()): for conf in config.get(CONF_MSGBOXES, ()):
await msgbox_to_code(conf) await msgbox_to_code(top_layer, conf)

View file

@ -1,7 +1,7 @@
from esphome import automation from esphome import automation
from ..automation import update_to_code from ..automation import update_to_code
from ..defines import CONF_MAIN, CONF_OBJ from ..defines import CONF_MAIN, CONF_OBJ, CONF_SCROLLBAR
from ..schemas import create_modify_schema from ..schemas import create_modify_schema
from ..types import ObjUpdateAction, WidgetType, lv_obj_t from ..types import ObjUpdateAction, WidgetType, lv_obj_t
@ -12,7 +12,9 @@ class ObjType(WidgetType):
""" """
def __init__(self): def __init__(self):
super().__init__(CONF_OBJ, lv_obj_t, (CONF_MAIN,), schema={}, modify_schema={}) super().__init__(
CONF_OBJ, lv_obj_t, (CONF_MAIN, CONF_SCROLLBAR), schema={}, modify_schema={}
)
async def to_code(self, w, config): async def to_code(self, w, config):
return [] return []

View file

@ -1,4 +1,3 @@
import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome.const import CONF_MODE, CONF_OPTIONS from esphome.const import CONF_MODE, CONF_OPTIONS
@ -7,36 +6,40 @@ from ..defines import (
CONF_MAIN, CONF_MAIN,
CONF_SELECTED, CONF_SELECTED,
CONF_SELECTED_INDEX, CONF_SELECTED_INDEX,
CONF_SELECTED_TEXT,
CONF_VISIBLE_ROW_COUNT, CONF_VISIBLE_ROW_COUNT,
ROLLER_MODES, ROLLER_MODES,
literal, literal,
) )
from ..lv_validation import animated, lv_int, option_string from ..helpers import lvgl_components_required
from ..lvcode import lv from ..lv_validation import animated, lv_int, lv_text, option_string
from ..lvcode import lv_add
from ..types import LvSelect from ..types import LvSelect
from . import WidgetType from . import WidgetType
from .label import CONF_LABEL from .label import CONF_LABEL
CONF_ROLLER = "roller" CONF_ROLLER = "roller"
lv_roller_t = LvSelect("lv_roller_t") lv_roller_t = LvSelect("LvRollerType")
ROLLER_BASE_SCHEMA = cv.Schema( ROLLER_BASE_SCHEMA = cv.Schema(
{ {
cv.Optional(CONF_SELECTED_INDEX): cv.templatable(cv.int_), cv.Exclusive(CONF_SELECTED_INDEX, CONF_SELECTED_TEXT): lv_int,
cv.Exclusive(CONF_SELECTED_TEXT, CONF_SELECTED_TEXT): lv_text,
cv.Optional(CONF_VISIBLE_ROW_COUNT): lv_int, cv.Optional(CONF_VISIBLE_ROW_COUNT): lv_int,
cv.Optional(CONF_MODE): ROLLER_MODES.one_of,
} }
) )
ROLLER_SCHEMA = ROLLER_BASE_SCHEMA.extend( ROLLER_SCHEMA = ROLLER_BASE_SCHEMA.extend(
{ {
cv.Required(CONF_OPTIONS): cv.ensure_list(option_string), cv.Required(CONF_OPTIONS): cv.ensure_list(option_string),
cv.Optional(CONF_MODE, default="NORMAL"): ROLLER_MODES.one_of,
} }
) )
ROLLER_MODIFY_SCHEMA = ROLLER_BASE_SCHEMA.extend( ROLLER_MODIFY_SCHEMA = ROLLER_BASE_SCHEMA.extend(
{ {
cv.Optional(CONF_ANIMATED, default=True): animated, cv.Optional(CONF_ANIMATED, default=True): animated,
cv.Optional(CONF_OPTIONS): cv.ensure_list(option_string),
} }
) )
@ -52,15 +55,19 @@ class RollerType(WidgetType):
) )
async def to_code(self, w, config): async def to_code(self, w, config):
lvgl_components_required.add(CONF_ROLLER)
if mode := config.get(CONF_MODE):
mode = await ROLLER_MODES.process(mode)
lv_add(w.var.set_mode(mode))
if options := config.get(CONF_OPTIONS): if options := config.get(CONF_OPTIONS):
mode = await ROLLER_MODES.process(config[CONF_MODE]) lv_add(w.var.set_options(options))
text = cg.safe_exp("\n".join(options)) animopt = literal(config.get(CONF_ANIMATED, "LV_ANIM_OFF"))
lv.roller_set_options(w.obj, text, mode) if (selected := config.get(CONF_SELECTED_INDEX)) is not None:
animopt = literal(config.get(CONF_ANIMATED) or "LV_ANIM_OFF")
if CONF_SELECTED_INDEX in config:
if selected := config[CONF_SELECTED_INDEX]:
value = await lv_int.process(selected) value = await lv_int.process(selected)
lv.roller_set_selected(w.obj, value, animopt) lv_add(w.var.set_selected_index(value, animopt))
if (selected := config.get(CONF_SELECTED_TEXT)) is not None:
value = await lv_text.process(selected)
lv_add(w.var.set_selected_text(value, animopt))
await w.set_property( await w.set_property(
CONF_VISIBLE_ROW_COUNT, CONF_VISIBLE_ROW_COUNT,
await lv_int.process(config.get(CONF_VISIBLE_ROW_COUNT)), await lv_int.process(config.get(CONF_VISIBLE_ROW_COUNT)),

View file

@ -9,6 +9,7 @@ from ..defines import (
CONF_COLUMN, CONF_COLUMN,
CONF_DIR, CONF_DIR,
CONF_MAIN, CONF_MAIN,
CONF_SCROLLBAR,
CONF_TILE_ID, CONF_TILE_ID,
CONF_TILES, CONF_TILES,
TILE_DIRECTIONS, TILE_DIRECTIONS,
@ -56,7 +57,7 @@ class TileviewType(WidgetType):
super().__init__( super().__init__(
CONF_TILEVIEW, CONF_TILEVIEW,
lv_tileview_t, lv_tileview_t,
(CONF_MAIN,), (CONF_MAIN, CONF_SCROLLBAR),
schema=TILEVIEW_SCHEMA, schema=TILEVIEW_SCHEMA,
modify_schema={}, modify_schema={},
) )

View file

@ -0,0 +1 @@
CODEOWNERS = ["@blacknell"]

View file

@ -0,0 +1,20 @@
#pragma once
#include "esphome/core/automation.h"
#include "max17043.h"
namespace esphome {
namespace max17043 {
template<typename... Ts> class SleepAction : public Action<Ts...> {
public:
explicit SleepAction(MAX17043Component *max17043) : max17043_(max17043) {}
void play(Ts... x) override { this->max17043_->sleep_mode(); }
protected:
MAX17043Component *max17043_;
};
} // namespace max17043
} // namespace esphome

View file

@ -0,0 +1,98 @@
#include "max17043.h"
#include "esphome/core/log.h"
namespace esphome {
namespace max17043 {
// MAX174043 is a 1-Cell Fuel Gauge with ModelGauge and Low-Battery Alert
// Consult the datasheet at https://www.analog.com/en/products/max17043.html
static const char *const TAG = "max17043";
static const uint8_t MAX17043_VCELL = 0x02;
static const uint8_t MAX17043_SOC = 0x04;
static const uint8_t MAX17043_CONFIG = 0x0c;
static const uint16_t MAX17043_CONFIG_POWER_UP_DEFAULT = 0x971C;
static const uint16_t MAX17043_CONFIG_SAFE_MASK = 0xFF1F; // mask out sleep bit (7), unused bit (6) and alert bit (4)
static const uint16_t MAX17043_CONFIG_SLEEP_MASK = 0x0080;
void MAX17043Component::update() {
uint16_t raw_voltage, raw_percent;
if (this->voltage_sensor_ != nullptr) {
if (!this->read_byte_16(MAX17043_VCELL, &raw_voltage)) {
this->status_set_warning("Unable to read MAX17043_VCELL");
} else {
float voltage = (1.25 * (float) (raw_voltage >> 4)) / 1000.0;
this->voltage_sensor_->publish_state(voltage);
this->status_clear_warning();
}
}
if (this->battery_remaining_sensor_ != nullptr) {
if (!this->read_byte_16(MAX17043_SOC, &raw_percent)) {
this->status_set_warning("Unable to read MAX17043_SOC");
} else {
float percent = (float) ((raw_percent >> 8) + 0.003906f * (raw_percent & 0x00ff));
this->battery_remaining_sensor_->publish_state(percent);
this->status_clear_warning();
}
}
}
void MAX17043Component::setup() {
ESP_LOGCONFIG(TAG, "Setting up MAX17043...");
uint16_t config_reg;
if (this->write(&MAX17043_CONFIG, 1) != i2c::ERROR_OK) {
this->status_set_warning();
return;
}
if (this->read(reinterpret_cast<uint8_t *>(&config_reg), 2) != i2c::ERROR_OK) {
this->status_set_warning();
return;
}
config_reg = i2c::i2ctohs(config_reg) & MAX17043_CONFIG_SAFE_MASK;
ESP_LOGV(TAG, "MAX17043 CONFIG register reads 0x%X", config_reg);
if (config_reg != MAX17043_CONFIG_POWER_UP_DEFAULT) {
ESP_LOGE(TAG, "Device does not appear to be a MAX17043");
this->status_set_error("unrecognised");
this->mark_failed();
return;
}
// need to write back to config register to reset the sleep bit
if (!this->write_byte_16(MAX17043_CONFIG, MAX17043_CONFIG_POWER_UP_DEFAULT)) {
this->status_set_error("sleep reset failed");
this->mark_failed();
return;
}
}
void MAX17043Component::dump_config() {
ESP_LOGCONFIG(TAG, "MAX17043:");
LOG_I2C_DEVICE(this);
if (this->is_failed()) {
ESP_LOGE(TAG, "Communication with MAX17043 failed");
}
LOG_UPDATE_INTERVAL(this);
LOG_SENSOR(" ", "Battery Voltage", this->voltage_sensor_);
LOG_SENSOR(" ", "Battery Level", this->battery_remaining_sensor_);
}
float MAX17043Component::get_setup_priority() const { return setup_priority::DATA; }
void MAX17043Component::sleep_mode() {
if (!this->is_failed()) {
if (!this->write_byte_16(MAX17043_CONFIG, MAX17043_CONFIG_POWER_UP_DEFAULT | MAX17043_CONFIG_SLEEP_MASK)) {
ESP_LOGW(TAG, "Unable to write the sleep bit to config register");
this->status_set_warning();
}
}
}
} // namespace max17043
} // namespace esphome

View file

@ -0,0 +1,29 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/i2c/i2c.h"
namespace esphome {
namespace max17043 {
class MAX17043Component : public PollingComponent, public i2c::I2CDevice {
public:
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void update() override;
void sleep_mode();
void set_voltage_sensor(sensor::Sensor *voltage_sensor) { voltage_sensor_ = voltage_sensor; }
void set_battery_remaining_sensor(sensor::Sensor *battery_remaining_sensor) {
battery_remaining_sensor_ = battery_remaining_sensor;
}
protected:
sensor::Sensor *voltage_sensor_{nullptr};
sensor::Sensor *battery_remaining_sensor_{nullptr};
};
} // namespace max17043
} // namespace esphome

View file

@ -0,0 +1,77 @@
from esphome import automation
from esphome.automation import maybe_simple_id
import esphome.codegen as cg
from esphome.components import i2c, sensor
import esphome.config_validation as cv
from esphome.const import (
CONF_BATTERY_LEVEL,
CONF_BATTERY_VOLTAGE,
CONF_ID,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_VOLTAGE,
ENTITY_CATEGORY_DIAGNOSTIC,
STATE_CLASS_MEASUREMENT,
UNIT_PERCENT,
UNIT_VOLT,
)
DEPENDENCIES = ["i2c"]
max17043_ns = cg.esphome_ns.namespace("max17043")
MAX17043Component = max17043_ns.class_(
"MAX17043Component", cg.PollingComponent, i2c.I2CDevice
)
# Actions
SleepAction = max17043_ns.class_("SleepAction", automation.Action)
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(MAX17043Component),
cv.Optional(CONF_BATTERY_VOLTAGE): sensor.sensor_schema(
unit_of_measurement=UNIT_VOLT,
accuracy_decimals=3,
device_class=DEVICE_CLASS_VOLTAGE,
state_class=STATE_CLASS_MEASUREMENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
cv.Optional(CONF_BATTERY_LEVEL): sensor.sensor_schema(
unit_of_measurement=UNIT_PERCENT,
accuracy_decimals=3,
device_class=DEVICE_CLASS_BATTERY,
state_class=STATE_CLASS_MEASUREMENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
}
)
.extend(cv.polling_component_schema("60s"))
.extend(i2c.i2c_device_schema(0x36))
)
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)
if voltage_config := config.get(CONF_BATTERY_VOLTAGE):
sens = await sensor.new_sensor(voltage_config)
cg.add(var.set_voltage_sensor(sens))
if CONF_BATTERY_LEVEL in config:
sens = await sensor.new_sensor(config[CONF_BATTERY_LEVEL])
cg.add(var.set_battery_remaining_sensor(sens))
MAX17043_ACTION_SCHEMA = maybe_simple_id(
{
cv.Required(CONF_ID): cv.use_id(MAX17043Component),
}
)
@automation.register_action("max17043.sleep_mode", SleepAction, MAX17043_ACTION_SCHEMA)
async def max17043_sleep_mode_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)

View file

@ -21,6 +21,7 @@ media_player_ns = cg.esphome_ns.namespace("media_player")
MediaPlayer = media_player_ns.class_("MediaPlayer") MediaPlayer = media_player_ns.class_("MediaPlayer")
PlayAction = media_player_ns.class_( PlayAction = media_player_ns.class_(
"PlayAction", automation.Action, cg.Parented.template(MediaPlayer) "PlayAction", automation.Action, cg.Parented.template(MediaPlayer)
) )
@ -60,7 +61,11 @@ AnnoucementTrigger = media_player_ns.class_(
"AnnouncementTrigger", automation.Trigger.template() "AnnouncementTrigger", automation.Trigger.template()
) )
IsIdleCondition = media_player_ns.class_("IsIdleCondition", automation.Condition) IsIdleCondition = media_player_ns.class_("IsIdleCondition", automation.Condition)
IsPausedCondition = media_player_ns.class_("IsPausedCondition", automation.Condition)
IsPlayingCondition = media_player_ns.class_("IsPlayingCondition", 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): 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( @automation.register_condition(
"media_player.is_idle", IsIdleCondition, MEDIA_PLAYER_ACTION_SCHEMA "media_player.is_idle", IsIdleCondition, MEDIA_PLAYER_ACTION_SCHEMA
) )
@automation.register_condition(
"media_player.is_paused", IsPausedCondition, MEDIA_PLAYER_ACTION_SCHEMA
)
@automation.register_condition( @automation.register_condition(
"media_player.is_playing", IsPlayingCondition, MEDIA_PLAYER_ACTION_SCHEMA "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): async def media_player_action(config, action_id, template_arg, args):
var = cg.new_Pvariable(action_id, template_arg) var = cg.new_Pvariable(action_id, template_arg)
await cg.register_parented(var, config[CONF_ID]) await cg.register_parented(var, config[CONF_ID])

View file

@ -68,5 +68,15 @@ template<typename... Ts> class IsPlayingCondition : public Condition<Ts...>, pub
bool check(Ts... x) override { return this->parent_->state == MediaPlayerState::MEDIA_PLAYER_STATE_PLAYING; } bool check(Ts... x) override { return this->parent_->state == MediaPlayerState::MEDIA_PLAYER_STATE_PLAYING; }
}; };
template<typename... Ts> class IsPausedCondition : public Condition<Ts...>, public Parented<MediaPlayer> {
public:
bool check(Ts... x) override { return this->parent_->state == MediaPlayerState::MEDIA_PLAYER_STATE_PAUSED; }
};
template<typename... Ts> class IsAnnouncingCondition : public Condition<Ts...>, public Parented<MediaPlayer> {
public:
bool check(Ts... x) override { return this->parent_->state == MediaPlayerState::MEDIA_PLAYER_STATE_ANNOUNCING; }
};
} // namespace media_player } // namespace media_player
} // namespace esphome } // namespace esphome

View file

@ -37,6 +37,10 @@ const char *media_player_command_to_string(MediaPlayerCommand command) {
return "UNMUTE"; return "UNMUTE";
case MEDIA_PLAYER_COMMAND_TOGGLE: case MEDIA_PLAYER_COMMAND_TOGGLE:
return "TOGGLE"; return "TOGGLE";
case MEDIA_PLAYER_COMMAND_VOLUME_UP:
return "VOLUME_UP";
case MEDIA_PLAYER_COMMAND_VOLUME_DOWN:
return "VOLUME_DOWN";
default: default:
return "UNKNOWN"; return "UNKNOWN";
} }

View file

@ -132,4 +132,4 @@ async def to_code(config):
pin = await cg.gpio_pin_expression(config[CONF_DRDY_PIN]) pin = await cg.gpio_pin_expression(config[CONF_DRDY_PIN])
cg.add(var.set_drdy_gpio(pin)) cg.add(var.set_drdy_gpio(pin))
cg.add_library("functionpointer/arduino-MLX90393", "1.0.0") cg.add_library("functionpointer/arduino-MLX90393", "1.0.2")

View file

@ -41,6 +41,7 @@ from esphome.const import (
CONF_SHUTDOWN_MESSAGE, CONF_SHUTDOWN_MESSAGE,
CONF_SSL_FINGERPRINTS, CONF_SSL_FINGERPRINTS,
CONF_STATE_TOPIC, CONF_STATE_TOPIC,
CONF_SUBSCRIBE_QOS,
CONF_TOPIC, CONF_TOPIC,
CONF_TOPIC_PREFIX, CONF_TOPIC_PREFIX,
CONF_TRIGGER_ID, CONF_TRIGGER_ID,
@ -518,6 +519,8 @@ async def register_mqtt_component(var, config):
cg.add(var.set_qos(config[CONF_QOS])) cg.add(var.set_qos(config[CONF_QOS]))
if CONF_RETAIN in config: if CONF_RETAIN in config:
cg.add(var.set_retain(config[CONF_RETAIN])) 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): if not config.get(CONF_DISCOVERY, True):
cg.add(var.disable_discovery()) cg.add(var.disable_discovery())
if CONF_STATE_TOPIC in config: if CONF_STATE_TOPIC in config:

View file

@ -16,6 +16,8 @@ static const char *const TAG = "mqtt.component";
void MQTTComponent::set_qos(uint8_t qos) { this->qos_ = qos; } 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; } void MQTTComponent::set_retain(bool retain) { this->retain_ = retain; }
std::string MQTTComponent::get_discovery_topic_(const MQTTDiscoveryInfo &discovery_info) const { std::string MQTTComponent::get_discovery_topic_(const MQTTDiscoveryInfo &discovery_info) const {
@ -76,6 +78,10 @@ bool MQTTComponent::send_discovery_() {
config.command_topic = true; config.command_topic = true;
this->send_discovery(root, config); 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 // Fields from EntityBase
if (this->get_entity()->has_own_name()) { if (this->get_entity()->has_own_name()) {

View file

@ -89,6 +89,9 @@ class MQTTComponent : public Component {
void disable_discovery(); void disable_discovery();
bool is_discovery_enabled() const; 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", ...) /// Override this method to return the component type (e.g. "light", "sensor", ...)
virtual std::string component_type() const = 0; virtual std::string component_type() const = 0;
@ -204,6 +207,7 @@ class MQTTComponent : public Component {
bool command_retain_{false}; bool command_retain_{false};
bool retain_{true}; bool retain_{true};
uint8_t qos_{0}; uint8_t qos_{0};
uint8_t subscribe_qos_{0};
bool discovery_enabled_{true}; bool discovery_enabled_{true};
bool resend_state_{false}; bool resend_state_{false};
}; };

View file

@ -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_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_MODE_VALUE_TEMPLATE = "pr_mode_val_tpl";
constexpr const char *const MQTT_PRESET_MODES = "pr_modes"; 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_RED_TEMPLATE = "r_tpl";
constexpr const char *const MQTT_RETAIN = "ret"; constexpr const char *const MQTT_RETAIN = "ret";
constexpr const char *const MQTT_RGB_COMMAND_TEMPLATE = "rgb_cmd_tpl"; 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_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_MODE_VALUE_TEMPLATE = "preset_mode_value_template";
constexpr const char *const MQTT_PRESET_MODES = "preset_modes"; 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_RED_TEMPLATE = "red_template";
constexpr const char *const MQTT_RETAIN = "retain"; constexpr const char *const MQTT_RETAIN = "retain";
constexpr const char *const MQTT_RGB_COMMAND_TEMPLATE = "rgb_command_template"; constexpr const char *const MQTT_RGB_COMMAND_TEMPLATE = "rgb_command_template";

View file

@ -215,16 +215,10 @@ void OnlineImage::draw_pixel_(int x, int y, Color color) {
} }
case ImageType::IMAGE_TYPE_RGB565: { case ImageType::IMAGE_TYPE_RGB565: {
uint16_t col565 = display::ColorUtil::color_to_565(color); 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<uint8_t>((col565 >> 8) & 0xFF); this->buffer_[pos + 0] = static_cast<uint8_t>((col565 >> 8) & 0xFF);
this->buffer_[pos + 1] = static_cast<uint8_t>(col565 & 0xFF); this->buffer_[pos + 1] = static_cast<uint8_t>(col565 & 0xFF);
if (this->has_transparency())
this->buffer_[pos + 2] = color.w;
break; break;
} }
case ImageType::IMAGE_TYPE_RGBA: { case ImageType::IMAGE_TYPE_RGBA: {

View file

@ -86,13 +86,9 @@ class OnlineImage : public PollingComponent,
Allocator allocator_{Allocator::Flags::ALLOW_FAILURE}; Allocator allocator_{Allocator::Flags::ALLOW_FAILURE};
uint32_t get_buffer_size_() const { return get_buffer_size_(this->buffer_width_, this->buffer_height_); } 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 { int get_buffer_size_(int width, int height) const { return (this->get_bpp() * width + 7u) / 8u * height; }
return std::ceil(image::image_type_to_bpp(this->type_) * width * height / 8.0);
}
int get_position_(int x, int y) const { int get_position_(int x, int y) const { return (x + y * this->buffer_width_) * this->get_bpp() / 8; }
return ((x + y * this->buffer_width_) * image::image_type_to_bpp(this->type_)) / 8;
}
ESPHOME_ALWAYS_INLINE bool auto_resize_() const { return this->fixed_width_ == 0 || this->fixed_height_ == 0; } ESPHOME_ALWAYS_INLINE bool auto_resize_() const { return this->fixed_width_ == 0 || this->fixed_height_ == 0; }

View file

@ -1,9 +1,10 @@
from typing import Any from typing import Any
from esphome import pins
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome import pins
from esphome.const import CONF_ID, PLATFORM_ESP32, PLATFORM_ESP8266 from esphome.const import CONF_ID, PLATFORM_ESP32, PLATFORM_ESP8266
from . import generate
CODEOWNERS = ["@olegtarasov"] CODEOWNERS = ["@olegtarasov"]
MULTI_CONF = True MULTI_CONF = True
@ -15,15 +16,14 @@ CONF_DHW_ENABLE = "dhw_enable"
CONF_COOLING_ENABLE = "cooling_enable" CONF_COOLING_ENABLE = "cooling_enable"
CONF_OTC_ACTIVE = "otc_active" CONF_OTC_ACTIVE = "otc_active"
CONF_CH2_ACTIVE = "ch2_active" CONF_CH2_ACTIVE = "ch2_active"
CONF_SUMMER_MODE_ACTIVE = "summer_mode_active"
CONF_DHW_BLOCK = "dhw_block"
CONF_SYNC_MODE = "sync_mode" CONF_SYNC_MODE = "sync_mode"
opentherm_ns = cg.esphome_ns.namespace("opentherm")
OpenthermHub = opentherm_ns.class_("OpenthermHub", cg.Component)
CONFIG_SCHEMA = cv.All( CONFIG_SCHEMA = cv.All(
cv.Schema( 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_IN_PIN): pins.internal_gpio_input_pin_schema,
cv.Required(CONF_OUT_PIN): pins.internal_gpio_output_pin_schema, cv.Required(CONF_OUT_PIN): pins.internal_gpio_output_pin_schema,
cv.Optional(CONF_CH_ENABLE, True): cv.boolean, 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_COOLING_ENABLE, False): cv.boolean,
cv.Optional(CONF_OTC_ACTIVE, False): cv.boolean, cv.Optional(CONF_OTC_ACTIVE, False): cv.boolean,
cv.Optional(CONF_CH2_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, cv.Optional(CONF_SYNC_MODE, False): cv.boolean,
} }
).extend(cv.COMPONENT_SCHEMA), ).extend(cv.COMPONENT_SCHEMA),
@ -39,8 +41,6 @@ CONFIG_SCHEMA = cv.All(
async def to_code(config: dict[str, Any]) -> None: 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]) var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config) 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} non_sensors = {CONF_ID, CONF_IN_PIN, CONF_OUT_PIN}
for key, value in config.items(): for key, value in config.items():
if key not in non_sensors: if key in non_sensors:
continue
cg.add(getattr(var, f"set_{key}")(value)) cg.add(getattr(var, f"set_{key}")(value))

View file

@ -0,0 +1,5 @@
OPENTHERM = "opentherm"
CONF_OPENTHERM_ID = "opentherm_id"
SENSOR = "sensor"

View file

@ -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

View file

@ -7,50 +7,114 @@ namespace esphome {
namespace opentherm { namespace opentherm {
static const char *const TAG = "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; OpenthermData data;
data.type = 0; data.type = 0;
data.id = 0; data.id = 0;
data.valueHB = 0; data.valueHB = 0;
data.valueLB = 0; data.valueLB = 0;
// First, handle the status request. This requires special logic, because we // We need this special logic for STATUS message because we have two options for specifying boiler modes:
// wouldn't want to inadvertently disable domestic hot water, for example. // with static config values in the hub, or with separate switches.
// It is also included in the macro-generated code below, but that will
// never be executed, because we short-circuit it here.
if (request_id == MessageId::STATUS) { if (request_id == MessageId::STATUS) {
bool const ch_enabled = this->ch_enable; // NOLINTBEGIN
bool dhw_enabled = this->dhw_enable; bool const ch_enabled = this->ch_enable && OPENTHERM_READ_ch_enable && OPENTHERM_READ_t_set > 0.0;
bool cooling_enabled = this->cooling_enable; bool const dhw_enabled = this->dhw_enable && OPENTHERM_READ_dhw_enable;
bool otc_enabled = this->otc_active; bool const cooling_enabled =
bool ch2_enabled = this->ch2_active; 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.type = MessageType::READ_DATA;
data.id = MessageId::STATUS; 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 // Disable incomplete switch statement warnings, because the cases in each
// switch are generated based on the configured sensors and inputs. // switch are generated based on the configured sensors and inputs.
#pragma GCC diagnostic push #pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch" #pragma GCC diagnostic ignored "-Wswitch"
// TODO: This is a placeholder for an auto-generated switch statement which builds request structure based on switch (request_id) { OPENTHERM_SENSOR_MESSAGE_HANDLERS(OPENTHERM_MESSAGE_READ_MESSAGE, OPENTHERM_IGNORE, , , ) }
// which sensors are enabled in config.
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
return data; // 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
return OpenthermData(); // 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) { void OpenthermHub::process_response(OpenthermData &data) {
ESP_LOGD(TAG, "Received OpenTherm response with id %d (%s)", data.id, ESP_LOGD(TAG, "Received OpenTherm response with id %d (%s)", data.id,
this->opentherm_->message_id_to_str((MessageId) data.id)); this->opentherm_->message_id_to_str((MessageId) data.id));
ESP_LOGD(TAG, "%s", this->opentherm_->debug_data(data).c_str()); 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() { void OpenthermHub::setup() {
@ -254,15 +318,17 @@ void OpenthermHub::handle_timeout_error_() {
this->stop_opentherm_(); this->stop_opentherm_();
} }
#define ID(x) x
#define SHOW2(x) #x
#define SHOW(x) SHOW2(x)
void OpenthermHub::dump_config() { void OpenthermHub::dump_config() {
ESP_LOGCONFIG(TAG, "OpenTherm:"); ESP_LOGCONFIG(TAG, "OpenTherm:");
LOG_PIN(" In: ", this->in_pin_); LOG_PIN(" In: ", this->in_pin_);
LOG_PIN(" Out: ", this->out_pin_); LOG_PIN(" Out: ", this->out_pin_);
ESP_LOGCONFIG(TAG, " Sync mode: %d", this->sync_mode_); 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:"); ESP_LOGCONFIG(TAG, " Initial requests:");
for (auto type : this->initial_messages_) { for (auto type : this->initial_messages_) {
ESP_LOGCONFIG(TAG, " - %d", type); ESP_LOGCONFIG(TAG, " - %d", type);

View file

@ -7,11 +7,17 @@
#include "opentherm.h" #include "opentherm.h"
#ifdef OPENTHERM_USE_SENSOR
#include "esphome/components/sensor/sensor.h"
#endif
#include <memory> #include <memory>
#include <unordered_map> #include <unordered_map>
#include <unordered_set> #include <unordered_set>
#include <functional> #include <functional>
#include "opentherm_macros.h"
namespace esphome { namespace esphome {
namespace opentherm { namespace opentherm {
@ -23,6 +29,8 @@ class OpenthermHub : public Component {
// The OpenTherm interface // The OpenTherm interface
std::unique_ptr<OpenTherm> opentherm_; std::unique_ptr<OpenTherm> opentherm_;
OPENTHERM_SENSOR_LIST(OPENTHERM_DECLARE_SENSOR, )
// The set of initial messages to send on starting communication with the boiler // The set of initial messages to send on starting communication with the boiler
std::unordered_set<MessageId> initial_messages_; std::unordered_set<MessageId> initial_messages_;
// and the repeating messages which are sent repeatedly to update various sensors // and the repeating messages which are sent repeatedly to update various sensors
@ -44,7 +52,7 @@ class OpenthermHub : public Component {
bool sync_mode_ = false; bool sync_mode_ = false;
// Create OpenTherm messages based on the message id // 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_write_error_();
void handle_protocol_read_error_(); void handle_protocol_read_error_();
void handle_timeout_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_in_pin(InternalGPIOPin *in_pin) { this->in_pin_ = in_pin; }
void set_out_pin(InternalGPIOPin *out_pin) { this->out_pin_ = out_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 // Add a request to the set of initial requests
void add_initial_message(MessageId message_id) { this->initial_messages_.insert(message_id); } 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 // 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. // will be processed.
void add_repeating_message(MessageId message_id) { this->repeating_messages_.insert(message_id); } void add_repeating_message(MessageId message_id) { this->repeating_messages_.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. // 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 // Setters for the status variables
void set_ch_enable(bool value) { this->ch_enable = value; } 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_cooling_enable(bool value) { this->cooling_enable = value; }
void set_otc_active(bool value) { this->otc_active = value; } void set_otc_active(bool value) { this->otc_active = value; }
void set_ch2_active(bool value) { this->ch2_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; } void set_sync_mode(bool sync_mode) { this->sync_mode_ = sync_mode; }
float get_setup_priority() const override { return setup_priority::HARDWARE; } float get_setup_priority() const override { return setup_priority::HARDWARE; }

View file

@ -283,6 +283,9 @@ bool OpenTherm::init_esp32_timer_() {
.clk_src = TIMER_SRC_CLK_DEFAULT, .clk_src = TIMER_SRC_CLK_DEFAULT,
#endif #endif
.divider = 80, .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; esp_err_t result;

Some files were not shown because too many files have changed in this diff Show more