Merge pull request #7789 from esphome/bump-2024.11.0

2024.11.0
This commit is contained in:
Jesse Hills 2024-11-21 06:42:54 +13:00 committed by GitHub
commit 9a7d5dcad8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
338 changed files with 16720 additions and 3318 deletions

View File

@ -75,6 +75,9 @@ target/
# pyenv
.python-version
# asdf
.tool-versions
# celery beat schedule file
celerybeat-schedule

View File

@ -7,11 +7,16 @@
- [ ] Bugfix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Code quality improvements to existing code or addition of tests
- [ ] Other
**Related issue or feature (if applicable):** fixes <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
@ -23,12 +28,6 @@
- [ ] RTL87xx
## 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
# Example config.yaml

View File

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

View File

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

View File

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

View File

@ -41,12 +41,12 @@ jobs:
run: echo key="${{ hashFiles('requirements.txt', 'requirements_optional.txt', 'requirements_test.txt') }}" >> $GITHUB_OUTPUT
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
id: python
uses: actions/setup-python@v5.2.0
uses: actions/setup-python@v5.3.0
with:
python-version: ${{ env.DEFAULT_PYTHON }}
- name: Restore Python virtual environment
id: cache-venv
uses: actions/cache@v4.1.1
uses: actions/cache@v4.1.2
with:
path: venv
# yamllint disable-line rule:line-length
@ -302,14 +302,14 @@ jobs:
- name: Cache platformio
if: github.ref == 'refs/heads/dev'
uses: actions/cache@v4.1.1
uses: actions/cache@v4.1.2
with:
path: ~/.platformio
key: platformio-${{ matrix.pio_cache_key }}
- name: Cache platformio
if: github.ref != 'refs/heads/dev'
uses: actions/cache/restore@v4.1.1
uses: actions/cache/restore@v4.1.2
with:
path: ~/.platformio
key: platformio-${{ matrix.pio_cache_key }}

View File

@ -53,7 +53,7 @@ jobs:
steps:
- uses: actions/checkout@v4.1.7
- name: Set up Python
uses: actions/setup-python@v5.2.0
uses: actions/setup-python@v5.3.0
with:
python-version: "3.x"
- name: Set up python environment
@ -65,7 +65,7 @@ jobs:
pip3 install build
python3 -m build
- name: Publish
uses: pypa/gh-action-pypi-publish@v1.10.3
uses: pypa/gh-action-pypi-publish@v1.12.2
deploy-docker:
name: Build ESPHome ${{ matrix.platform }}
@ -85,7 +85,7 @@ jobs:
steps:
- uses: actions/checkout@v4.1.7
- name: Set up Python
uses: actions/setup-python@v5.2.0
uses: actions/setup-python@v5.3.0
with:
python-version: "3.9"
@ -141,7 +141,7 @@ jobs:
echo name=$(cat /tmp/platform) >> $GITHUB_OUTPUT
- name: Upload digests
uses: actions/upload-artifact@v4.4.2
uses: actions/upload-artifact@v4.4.3
with:
name: digests-${{ steps.sanitize.outputs.name }}
path: /tmp/digests

View File

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

3
.gitignore vendored
View File

@ -75,6 +75,9 @@ cov.xml
# pyenv
.python-version
# asdf
.tool-versions
# Environments
.env
.venv

View File

@ -48,7 +48,9 @@ esphome/components/at581x/* @X-Ryl669
esphome/components/atc_mithermometer/* @ahpohl
esphome/components/atm90e26/* @danieltwagner
esphome/components/atm90e32/* @circuitsetup @descipher
esphome/components/audio/* @kahrendt
esphome/components/audio_dac/* @kbx81
esphome/components/axs15231/* @clydebarrow
esphome/components/b_parasite/* @rbaron
esphome/components/ballu/* @bazuchan
esphome/components/bang_bang/* @OttoWinter
@ -83,6 +85,7 @@ esphome/components/bmp581/* @kahrendt
esphome/components/bp1658cj/* @Cossid
esphome/components/bp5758d/* @Cossid
esphome/components/button/* @esphome/core
esphome/components/bytebuffer/* @clydebarrow
esphome/components/canbus/* @danielschramm @mvturnho
esphome/components/cap1188/* @mreditor97
esphome/components/captive_portal/* @OttoWinter
@ -128,6 +131,7 @@ esphome/components/ens160_base/* @latonita @vincentscode
esphome/components/ens160_i2c/* @latonita
esphome/components/ens160_spi/* @latonita
esphome/components/ens210/* @itn3rd77
esphome/components/es8311/* @kahrendt @kroimon
esphome/components/esp32/* @esphome/core
esphome/components/esp32_ble/* @Rapsssito @jesserockz
esphome/components/esp32_ble_client/* @jesserockz
@ -196,10 +200,11 @@ esphome/components/htu31d/* @betterengineering
esphome/components/hydreon_rgxx/* @functionpointer
esphome/components/hyt271/* @Philippe12
esphome/components/i2c/* @esphome/core
esphome/components/i2c_device/* @gabest11
esphome/components/i2s_audio/* @jesserockz
esphome/components/i2s_audio/media_player/* @jesserockz
esphome/components/i2s_audio/microphone/* @jesserockz
esphome/components/i2s_audio/speaker/* @jesserockz
esphome/components/i2s_audio/speaker/* @jesserockz @kahrendt
esphome/components/iaqcore/* @yozik04
esphome/components/ili9xxx/* @clydebarrow @nielsnl68
esphome/components/improv_base/* @esphome/core
@ -237,6 +242,7 @@ esphome/components/ltr_als_ps/* @latonita
esphome/components/lvgl/* @clydebarrow
esphome/components/m5stack_8angle/* @rnauber
esphome/components/matrix_keypad/* @ssieb
esphome/components/max17043/* @blacknell
esphome/components/max31865/* @DAVe3283
esphome/components/max44009/* @berfenger
esphome/components/max6956/* @looping40
@ -324,7 +330,7 @@ esphome/components/pvvx_mithermometer/* @pasiz
esphome/components/pylontech/* @functionpointer
esphome/components/qmp6988/* @andrewpc
esphome/components/qr_code/* @wjtje
esphome/components/qspi_amoled/* @clydebarrow
esphome/components/qspi_dbi/* @clydebarrow
esphome/components/qwiic_pir/* @kahrendt
esphome/components/radon_eye_ble/* @jeffeb3
esphome/components/radon_eye_rd200/* @jeffeb3
@ -373,7 +379,7 @@ esphome/components/smt100/* @piechade
esphome/components/sn74hc165/* @jesserockz
esphome/components/socket/* @esphome/core
esphome/components/sonoff_d1/* @anatoly-savchenkov
esphome/components/speaker/* @jesserockz
esphome/components/speaker/* @jesserockz @kahrendt
esphome/components/spi/* @clydebarrow @esphome/core
esphome/components/spi_device/* @clydebarrow
esphome/components/spi_led_strip/* @clydebarrow
@ -403,6 +409,7 @@ esphome/components/sun/* @OttoWinter
esphome/components/sun_gtil2/* @Mat931
esphome/components/switch/* @esphome/core
esphome/components/t6615/* @tylermenezes
esphome/components/tc74/* @sethgirvan
esphome/components/tca9548a/* @andreashergert1984
esphome/components/tca9555/* @mobrembski
esphome/components/tcl112/* @glmnet

View File

@ -32,33 +32,14 @@ RUN \
python3-setuptools=66.1.1-1 \
python3-venv=3.11.2-1+b1 \
python3-wheel=0.38.4-2 \
iputils-ping=3:20221126-1 \
iputils-ping=3:20221126-1+deb12u1 \
git=1:2.39.5-0+deb12u1 \
curl=7.88.1-10+deb12u7 \
curl=7.88.1-10+deb12u8 \
openssh-client=1:9.2p1-2+deb12u3 \
python3-cffi=1.15.1-5 \
libcairo2=1.16.0-7 \
libmagic1=1:5.44-3 \
patch=2.7.6-7 \
&& ( \
( \
[ "$TARGETARCH$TARGETVARIANT" = "armv7" ] && \
apt-get install -y --no-install-recommends \
build-essential=12.9 \
python3-dev=3.11.2-1+b1 \
zlib1g-dev=1:1.2.13.dfsg-1 \
libjpeg-dev=1:2.1.5-2 \
libfreetype-dev=2.12.1+dfsg-5+deb12u3 \
libssl-dev=3.0.14-1~deb12u2 \
libffi-dev=3.4.4-1 \
libopenjp2-7=2.5.0-2 \
libtiff6=4.5.0-6+deb12u1 \
cargo=0.66.0+ds1-1 \
pkg-config=1.8.1-1 \
gcc-arm-linux-gnueabihf=4:12.2.0-3 \
) \
|| [ "$TARGETARCH$TARGETVARIANT" != "armv7" ] \
) \
&& rm -rf \
/tmp/* \
/var/{cache,log}/* \
@ -86,7 +67,7 @@ RUN \
pip3 install \
--break-system-packages --no-cache-dir \
# Keep platformio version in sync with requirements.txt
platformio==6.1.15 \
platformio==6.1.16 \
# Change some platformio settings
&& platformio settings set enable_telemetry No \
&& platformio settings set check_platformio_interval 1000000 \
@ -97,15 +78,48 @@ RUN \
# tmpfs is for https://github.com/rust-lang/cargo/issues/8719
COPY requirements.txt requirements_optional.txt /
RUN --mount=type=tmpfs,target=/root/.cargo if [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]; then \
curl -L https://www.piwheels.org/cp311/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl -o /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl \
&& pip3 install --break-system-packages --no-cache-dir /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl \
&& rm /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl \
&& export PIP_EXTRA_INDEX_URL="https://www.piwheels.org/simple"; \
fi; \
CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse CARGO_HOME=/root/.cargo \
pip3 install \
--break-system-packages --no-cache-dir -r /requirements.txt -r /requirements_optional.txt
RUN --mount=type=tmpfs,target=/root/.cargo <<END-OF-RUN
# Fail on any non-zero status
set -e
if [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]
then
curl -L https://www.piwheels.org/cp311/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl -o /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl
pip3 install --break-system-packages --no-cache-dir /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl
rm /tmp/cryptography-43.0.0-cp37-abi3-linux_armv7l.whl
export PIP_EXTRA_INDEX_URL="https://www.piwheels.org/simple";
fi
# install build tools in case wheels are not available
BUILD_DEPS="
build-essential=12.9
python3-dev=3.11.2-1+b1
zlib1g-dev=1:1.2.13.dfsg-1
libjpeg-dev=1:2.1.5-2
libfreetype-dev=2.12.1+dfsg-5+deb12u3
libssl-dev=3.0.15-1~deb12u1
libffi-dev=3.4.4-1
libopenjp2-7=2.5.0-2
libtiff6=4.5.0-6+deb12u1
cargo=0.66.0+ds1-1
pkg-config=1.8.1-1
"
if [ "$TARGETARCH$TARGETVARIANT" = "arm64" ] || [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]
then
apt-get update
apt-get install -y --no-install-recommends $BUILD_DEPS
fi
CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse CARGO_HOME=/root/.cargo
pip3 install --break-system-packages --no-cache-dir -r /requirements.txt -r /requirements_optional.txt
if [ "$TARGETARCH$TARGETVARIANT" = "arm64" ] || [ "$TARGETARCH$TARGETVARIANT" = "armv7" ]
then
apt-get remove -y --purge --auto-remove $BUILD_DEPS
rm -rf /tmp/* /var/{cache,log}/* /var/lib/apt/lists/*
fi
END-OF-RUN
COPY script/platformio_install_deps.py platformio.ini /
RUN /platformio_install_deps.py /platformio.ini --libraries

View File

@ -20,6 +20,8 @@ from esphome.const import (
CONF_DEASSERT_RTS_DTR,
CONF_DISABLED,
CONF_ESPHOME,
CONF_LEVEL,
CONF_LOG_TOPIC,
CONF_LOGGER,
CONF_MDNS,
CONF_MQTT,
@ -30,6 +32,7 @@ from esphome.const import (
CONF_PLATFORMIO_OPTIONS,
CONF_PORT,
CONF_SUBSTITUTIONS,
CONF_TOPIC,
PLATFORM_BK72XX,
PLATFORM_ESP32,
PLATFORM_ESP8266,
@ -38,7 +41,7 @@ from esphome.const import (
SECRETS_FILES,
)
from esphome.core import CORE, EsphomeError, coroutine
from esphome.helpers import indent, is_ip_address, get_bool_env
from esphome.helpers import get_bool_env, indent, is_ip_address
from esphome.log import Fore, color, setup_log
from esphome.util import (
get_serial_ports,
@ -95,8 +98,12 @@ def choose_upload_log_host(
options.append((f"Over The Air ({CORE.address})", CORE.address))
if default == "OTA":
return CORE.address
if show_mqtt and CONF_MQTT in CORE.config:
options.append((f"MQTT ({CORE.config['mqtt'][CONF_BROKER]})", "MQTT"))
if (
show_mqtt
and (mqtt_config := CORE.config.get(CONF_MQTT))
and mqtt_logging_enabled(mqtt_config)
):
options.append((f"MQTT ({mqtt_config[CONF_BROKER]})", "MQTT"))
if default == "OTA":
return "MQTT"
if default is not None:
@ -106,6 +113,17 @@ def choose_upload_log_host(
return choose_prompt(options, purpose=purpose)
def mqtt_logging_enabled(mqtt_config):
log_topic = mqtt_config[CONF_LOG_TOPIC]
if log_topic is None:
return False
if CONF_TOPIC not in log_topic:
return False
if log_topic.get(CONF_LEVEL, None) == "NONE":
return False
return True
def get_port_type(port):
if port.startswith("/") or port.startswith("COM"):
return "SERIAL"
@ -378,7 +396,7 @@ def show_logs(config, args, port):
port = mqtt.get_esphome_device_ip(
config, args.username, args.password, args.client_id
)
)[0]
from esphome.components.api.client import run_logs

View File

@ -1,6 +1,8 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import (
CONF_ALL,
CONF_ANY,
CONF_AUTOMATION_ID,
CONF_CONDITION,
CONF_COUNT,
@ -73,6 +75,13 @@ def validate_potentially_and_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)
LambdaAction = cg.esphome_ns.class_("LambdaAction", 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)
@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)
async def not_condition_to_code(config, condition_id, 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,
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_ELSE): validate_action_list,
},
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):
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)
if CONF_THEN in config:
actions = await build_action_list(config[CONF_THEN], template_arg, args)

View File

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

View File

@ -62,7 +62,7 @@ void Animation::set_frame(int frame) {
}
void Animation::update_data_start_() {
const uint32_t image_size = image_type_to_width_stride(this->width_, this->type_) * this->height_;
const uint32_t image_size = this->get_width_stride() * this->height_;
this->data_start_ = this->animation_data_start_ + image_size * this->current_frame_;
}

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

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

View File

@ -204,11 +204,11 @@ void BME68xBSEC2Component::update_subscription_() {
}
void BME68xBSEC2Component::run_() {
this->op_mode_ = this->bsec_settings_.op_mode;
int64_t curr_time_ns = this->get_time_ns_();
if (curr_time_ns < this->next_call_ns_) {
if (curr_time_ns < this->bsec_settings_.next_call) {
return;
}
this->op_mode_ = this->bsec_settings_.op_mode;
uint8_t status;
ESP_LOGV(TAG, "Performing sensor run");
@ -219,57 +219,60 @@ void BME68xBSEC2Component::run_() {
ESP_LOGW(TAG, "Failed to fetch sensor control settings (BSEC2 error code %d)", this->bsec_status_);
return;
}
this->next_call_ns_ = this->bsec_settings_.next_call;
if (this->bsec_settings_.trigger_measurement) {
bme68x_get_conf(&bme68x_conf, &this->bme68x_);
switch (this->bsec_settings_.op_mode) {
case BME68X_FORCED_MODE:
bme68x_get_conf(&bme68x_conf, &this->bme68x_);
bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling;
bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling;
bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling;
bme68x_set_conf(&bme68x_conf, &this->bme68x_);
bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling;
bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling;
bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling;
bme68x_set_conf(&bme68x_conf, &this->bme68x_);
this->bme68x_heatr_conf_.enable = BME68X_ENABLE;
this->bme68x_heatr_conf_.heatr_temp = this->bsec_settings_.heater_temperature;
this->bme68x_heatr_conf_.heatr_dur = this->bsec_settings_.heater_duration;
// status = bme68x_set_op_mode(this->bsec_settings_.op_mode, &this->bme68x_);
status = bme68x_set_heatr_conf(BME68X_FORCED_MODE, &this->bme68x_heatr_conf_, &this->bme68x_);
status = bme68x_set_op_mode(BME68X_FORCED_MODE, &this->bme68x_);
this->op_mode_ = BME68X_FORCED_MODE;
ESP_LOGV(TAG, "Using forced mode");
break;
case BME68X_PARALLEL_MODE:
if (this->op_mode_ != this->bsec_settings_.op_mode) {
bme68x_get_conf(&bme68x_conf, &this->bme68x_);
bme68x_conf.os_hum = this->bsec_settings_.humidity_oversampling;
bme68x_conf.os_temp = this->bsec_settings_.temperature_oversampling;
bme68x_conf.os_pres = this->bsec_settings_.pressure_oversampling;
bme68x_set_conf(&bme68x_conf, &this->bme68x_);
switch (this->bsec_settings_.op_mode) {
case BME68X_FORCED_MODE:
this->bme68x_heatr_conf_.enable = BME68X_ENABLE;
this->bme68x_heatr_conf_.heatr_temp = this->bsec_settings_.heater_temperature;
this->bme68x_heatr_conf_.heatr_dur = this->bsec_settings_.heater_duration;
this->bme68x_heatr_conf_.heatr_temp_prof = this->bsec_settings_.heater_temperature_profile;
this->bme68x_heatr_conf_.heatr_dur_prof = this->bsec_settings_.heater_duration_profile;
this->bme68x_heatr_conf_.profile_len = this->bsec_settings_.heater_profile_len;
this->bme68x_heatr_conf_.shared_heatr_dur =
BSEC_TOTAL_HEAT_DUR -
(bme68x_get_meas_dur(BME68X_PARALLEL_MODE, &bme68x_conf, &this->bme68x_) / INT64_C(1000));
status = bme68x_set_op_mode(this->bsec_settings_.op_mode, &this->bme68x_);
status = bme68x_set_heatr_conf(BME68X_FORCED_MODE, &this->bme68x_heatr_conf_, &this->bme68x_);
status = bme68x_set_op_mode(BME68X_FORCED_MODE, &this->bme68x_);
this->op_mode_ = BME68X_FORCED_MODE;
this->sleep_mode_ = false;
ESP_LOGV(TAG, "Using forced mode");
status = bme68x_set_heatr_conf(BME68X_PARALLEL_MODE, &this->bme68x_heatr_conf_, &this->bme68x_);
break;
case BME68X_PARALLEL_MODE:
if (this->op_mode_ != this->bsec_settings_.op_mode) {
this->bme68x_heatr_conf_.enable = BME68X_ENABLE;
this->bme68x_heatr_conf_.heatr_temp_prof = this->bsec_settings_.heater_temperature_profile;
this->bme68x_heatr_conf_.heatr_dur_prof = this->bsec_settings_.heater_duration_profile;
this->bme68x_heatr_conf_.profile_len = this->bsec_settings_.heater_profile_len;
this->bme68x_heatr_conf_.shared_heatr_dur =
BSEC_TOTAL_HEAT_DUR -
(bme68x_get_meas_dur(BME68X_PARALLEL_MODE, &bme68x_conf, &this->bme68x_) / INT64_C(1000));
status = bme68x_set_heatr_conf(BME68X_PARALLEL_MODE, &this->bme68x_heatr_conf_, &this->bme68x_);
status = bme68x_set_op_mode(BME68X_PARALLEL_MODE, &this->bme68x_);
this->op_mode_ = BME68X_PARALLEL_MODE;
this->sleep_mode_ = false;
ESP_LOGV(TAG, "Using parallel mode");
}
break;
case BME68X_SLEEP_MODE:
if (!this->sleep_mode_) {
bme68x_set_op_mode(BME68X_SLEEP_MODE, &this->bme68x_);
this->sleep_mode_ = true;
ESP_LOGV(TAG, "Using sleep mode");
}
break;
}
status = bme68x_set_op_mode(BME68X_PARALLEL_MODE, &this->bme68x_);
this->op_mode_ = BME68X_PARALLEL_MODE;
ESP_LOGV(TAG, "Using parallel mode");
}
break;
case BME68X_SLEEP_MODE:
if (this->op_mode_ != this->bsec_settings_.op_mode) {
bme68x_set_op_mode(BME68X_SLEEP_MODE, &this->bme68x_);
this->op_mode_ = BME68X_SLEEP_MODE;
ESP_LOGV(TAG, "Using sleep mode");
}
break;
}
if (this->bsec_settings_.trigger_measurement && this->bsec_settings_.op_mode != BME68X_SLEEP_MODE) {
uint32_t meas_dur = 0;
meas_dur = bme68x_get_meas_dur(this->op_mode_, &bme68x_conf, &this->bme68x_);
ESP_LOGV(TAG, "Queueing read in %uus", meas_dur);

View File

@ -113,13 +113,11 @@ class BME68xBSEC2Component : public Component {
struct bme68x_heatr_conf bme68x_heatr_conf_;
uint8_t op_mode_; // operating mode of sensor
bool sleep_mode_;
bsec_library_return_t bsec_status_{BSEC_OK};
int8_t bme68x_status_{BME68X_OK};
int64_t last_time_ms_{0};
uint32_t millis_overflow_counter_{0};
int64_t next_call_ns_{0};
std::queue<std::function<void()>> queue_;

View File

@ -0,0 +1,5 @@
CODEOWNERS = ["@clydebarrow"]
# Allows bytebuffer to be configured in yaml, to allow use of the C++ api.
CONFIG_SCHEMA = {}

View File

@ -0,0 +1,421 @@
#pragma once
#include <utility>
#include <vector>
#include <cinttypes>
#include <cstddef>
#include "esphome/core/helpers.h"
namespace esphome {
namespace bytebuffer {
enum Endian { LITTLE, BIG };
/**
* A class modelled on the Java ByteBuffer class. It wraps a vector of bytes and permits putting and getting
* items of various sizes, with an automatically incremented position.
*
* There are three variables maintained pointing into the buffer:
*
* capacity: the maximum amount of data that can be stored - set on construction and cannot be changed
* limit: the limit of the data currently available to get or put
* position: the current insert or extract position
*
* 0 <= position <= limit <= capacity
*
* In addition a mark can be set to the current position with mark(). A subsequent call to reset() will restore
* the position to the mark.
*
* The buffer can be marked to be little-endian (default) or big-endian. All subsequent operations will use that order.
*
* The flip() operation will reset the position to 0 and limit to the current position. This is useful for reading
* data from a buffer after it has been written.
*
* The code is defined here in the header file rather than in a .cpp file, so that it does not get compiled if not used.
* The templated functions ensure that only those typed functions actually used are compiled. The functions
* are implicitly inline-able which will aid performance.
*/
class ByteBuffer {
public:
// Default constructor (compatibility with TEMPLATABLE_VALUE)
// Creates a zero-length ByteBuffer which is little use to anybody.
ByteBuffer() : ByteBuffer(std::vector<uint8_t>()) {}
/**
* Create a new Bytebuffer with the given capacity
*/
ByteBuffer(size_t capacity, Endian endianness = LITTLE)
: data_(std::vector<uint8_t>(capacity)), endianness_(endianness), limit_(capacity){};
// templated functions to implement putting and getting data of various types. There are two flavours of all
// functions - one that uses the position as the offset, and updates the position accordingly, and one that
// takes an explicit offset and does not update the position.
// Separate temnplates are provided for types that fit into 32 bits and those that are bigger. These delegate
// the actual put/get to common code based around those sizes.
// This reduces the code size and execution time for smaller types. A similar structure for e.g. 16 bits is unlikely
// to provide any further benefit given that all target platforms are native 32 bit.
template<typename T>
T get(typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
// integral types that fit into 32 bit
return static_cast<T>(this->get_uint32_(sizeof(T)));
}
template<typename T>
T get(size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
return static_cast<T>(this->get_uint32_(offset, sizeof(T)));
}
template<typename T>
void put(const T &value, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
this->put_uint32_(static_cast<uint32_t>(value), sizeof(T));
}
template<typename T>
void put(const T &value, size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
this->put_uint32_(static_cast<uint32_t>(value), offset, sizeof(T));
}
// integral types that do not fit into 32 bit (basically only 64 bit types)
template<typename T>
T get(typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
return static_cast<T>(this->get_uint64_(sizeof(T)));
}
template<typename T>
T get(size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
return static_cast<T>(this->get_uint64_(offset, sizeof(T)));
}
template<typename T>
void put(const T &value, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
this->put_uint64_(value, sizeof(T));
}
template<typename T>
void put(const T &value, size_t offset, typename std::enable_if<std::is_integral<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
this->put_uint64_(static_cast<uint64_t>(value), offset, sizeof(T));
}
// floating point types. Caters for 32 and 64 bit floating point.
template<typename T>
T get(typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint32_t)), T>::type * = 0) {
return bit_cast<T>(this->get_uint32_(sizeof(T)));
}
template<typename T>
T get(typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
return bit_cast<T>(this->get_uint64_(sizeof(T)));
}
template<typename T>
T get(size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint32_t)), T>::type * = 0) {
return bit_cast<T>(this->get_uint32_(offset, sizeof(T)));
}
template<typename T>
T get(size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
return bit_cast<T>(this->get_uint64_(offset, sizeof(T)));
}
template<typename T>
void put(const T &value, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
this->put_uint32_(bit_cast<uint32_t>(value), sizeof(T));
}
template<typename T>
void put(const T &value, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
this->put_uint64_(bit_cast<uint64_t>(value), sizeof(T));
}
template<typename T>
void put(const T &value, size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) <= sizeof(uint32_t)), T>::type * = 0) {
this->put_uint32_(bit_cast<uint32_t>(value), offset, sizeof(T));
}
template<typename T>
void put(const T &value, size_t offset, typename std::enable_if<std::is_floating_point<T>::value, T>::type * = 0,
typename std::enable_if<(sizeof(T) == sizeof(uint64_t)), T>::type * = 0) {
this->put_uint64_(bit_cast<uint64_t>(value), offset, sizeof(T));
}
template<typename T> static ByteBuffer wrap(T value, Endian endianness = LITTLE) {
ByteBuffer buffer = ByteBuffer(sizeof(T), endianness);
buffer.put(value);
buffer.flip();
return buffer;
}
static ByteBuffer wrap(std::vector<uint8_t> const &data, Endian endianness = LITTLE) {
ByteBuffer buffer = {data};
buffer.endianness_ = endianness;
return buffer;
}
static ByteBuffer wrap(const uint8_t *ptr, size_t len, Endian endianness = LITTLE) {
return wrap(std::vector<uint8_t>(ptr, ptr + len), endianness);
}
// convenience functions with explicit types named..
void put_float(float value) { this->put(value); }
void put_double(double value) { this->put(value); }
uint8_t get_uint8() { return this->data_[this->position_++]; }
// Get a 16 bit unsigned value, increment by 2
uint16_t get_uint16() { return this->get<uint16_t>(); }
// Get a 24 bit unsigned value, increment by 3
uint32_t get_uint24() { return this->get_uint32_(3); };
// Get a 32 bit unsigned value, increment by 4
uint32_t get_uint32() { return this->get<uint32_t>(); };
// Get a 64 bit unsigned value, increment by 8
uint64_t get_uint64() { return this->get<uint64_t>(); };
// Signed versions of the get functions
uint8_t get_int8() { return static_cast<int8_t>(this->get_uint8()); };
int16_t get_int16() { return this->get<uint16_t>(); }
int32_t get_int32() { return this->get<int32_t>(); }
int64_t get_int64() { return this->get<int64_t>(); }
// Get a float value, increment by 4
float get_float() { return this->get<float>(); }
// Get a double value, increment by 8
double get_double() { return this->get<double>(); }
// Get a bool value, increment by 1
bool get_bool() { return static_cast<bool>(this->get_uint8()); }
uint32_t get_int24(size_t offset) {
auto value = this->get_uint24(offset);
uint32_t mask = (~static_cast<uint32_t>(0)) << 23;
if ((value & mask) != 0)
value |= mask;
return value;
}
uint32_t get_int24() {
auto value = this->get_uint24();
uint32_t mask = (~static_cast<uint32_t>(0)) << 23;
if ((value & mask) != 0)
value |= mask;
return value;
}
std::vector<uint8_t> get_vector(size_t length, size_t offset) {
auto start = this->data_.begin() + offset;
return {start, start + length};
}
std::vector<uint8_t> get_vector(size_t length) {
auto result = this->get_vector(length, this->position_);
this->position_ += length;
return result;
}
// Convenience named functions
void put_uint8(uint8_t value) { this->data_[this->position_++] = value; }
void put_uint16(uint16_t value) { this->put(value); }
void put_uint24(uint32_t value) { this->put_uint32_(value, 3); }
void put_uint32(uint32_t value) { this->put(value); }
void put_uint64(uint64_t value) { this->put(value); }
// Signed versions of the put functions
void put_int8(int8_t value) { this->put_uint8(static_cast<uint8_t>(value)); }
void put_int16(int16_t value) { this->put(value); }
void put_int24(int32_t value) { this->put_uint32_(value, 3); }
void put_int32(int32_t value) { this->put(value); }
void put_int64(int64_t value) { this->put(value); }
// Extra put functions
void put_bool(bool value) { this->put_uint8(value); }
// versions of the above with an offset, these do not update the position
uint64_t get_uint64(size_t offset) { return this->get<uint64_t>(offset); }
uint32_t get_uint24(size_t offset) { return this->get_uint32_(offset, 3); };
double get_double(size_t offset) { return get<double>(offset); }
// Get one byte from the buffer, increment position by 1
uint8_t get_uint8(size_t offset) { return this->data_[offset]; }
// Get a 16 bit unsigned value, increment by 2
uint16_t get_uint16(size_t offset) { return get<uint16_t>(offset); }
// Get a 24 bit unsigned value, increment by 3
uint32_t get_uint32(size_t offset) { return this->get<uint32_t>(offset); };
// Get a 64 bit unsigned value, increment by 8
uint8_t get_int8(size_t offset) { return get<int8_t>(offset); }
int16_t get_int16(size_t offset) { return get<int16_t>(offset); }
int32_t get_int32(size_t offset) { return get<int32_t>(offset); }
int64_t get_int64(size_t offset) { return get<int64_t>(offset); }
// Get a float value, increment by 4
float get_float(size_t offset) { return get<float>(offset); }
// Get a double value, increment by 8
// Get a bool value, increment by 1
bool get_bool(size_t offset) { return this->get_uint8(offset); }
void put_uint8(uint8_t value, size_t offset) { this->data_[offset] = value; }
void put_uint16(uint16_t value, size_t offset) { this->put(value, offset); }
void put_uint24(uint32_t value, size_t offset) { this->put(value, offset); }
void put_uint32(uint32_t value, size_t offset) { this->put(value, offset); }
void put_uint64(uint64_t value, size_t offset) { this->put(value, offset); }
// Signed versions of the put functions
void put_int8(int8_t value, size_t offset) { this->put_uint8(static_cast<uint8_t>(value), offset); }
void put_int16(int16_t value, size_t offset) { this->put(value, offset); }
void put_int24(int32_t value, size_t offset) { this->put_uint32_(value, offset, 3); }
void put_int32(int32_t value, size_t offset) { this->put(value, offset); }
void put_int64(int64_t value, size_t offset) { this->put(value, offset); }
// Extra put functions
void put_float(float value, size_t offset) { this->put(value, offset); }
void put_double(double value, size_t offset) { this->put(value, offset); }
void put_bool(bool value, size_t offset) { this->put_uint8(value, offset); }
void put(const std::vector<uint8_t> &value, size_t offset) {
std::copy(value.begin(), value.end(), this->data_.begin() + offset);
}
void put_vector(const std::vector<uint8_t> &value, size_t offset) { this->put(value, offset); }
void put(const std::vector<uint8_t> &value) {
this->put_vector(value, this->position_);
this->position_ += value.size();
}
void put_vector(const std::vector<uint8_t> &value) { this->put(value); }
// Getters
inline size_t get_capacity() const { return this->data_.size(); }
inline size_t get_position() const { return this->position_; }
inline size_t get_limit() const { return this->limit_; }
inline size_t get_remaining() const { return this->get_limit() - this->get_position(); }
inline Endian get_endianness() const { return this->endianness_; }
inline void mark() { this->mark_ = this->position_; }
inline void big_endian() { this->endianness_ = BIG; }
inline void little_endian() { this->endianness_ = LITTLE; }
// retrieve a pointer to the underlying data.
std::vector<uint8_t> get_data() { return this->data_; };
void get_bytes(void *dest, size_t length) {
std::copy(this->data_.begin() + this->position_, this->data_.begin() + this->position_ + length, (uint8_t *) dest);
this->position_ += length;
}
void get_bytes(void *dest, size_t length, size_t offset) {
std::copy(this->data_.begin() + offset, this->data_.begin() + offset + length, (uint8_t *) dest);
}
void rewind() { this->position_ = 0; }
void reset() { this->position_ = this->mark_; }
void set_limit(size_t limit) { this->limit_ = limit; }
void set_position(size_t position) { this->position_ = position; }
void clear() {
this->limit_ = this->get_capacity();
this->position_ = 0;
}
void flip() {
this->limit_ = this->position_;
this->position_ = 0;
}
protected:
uint64_t get_uint64_(size_t offset, size_t length) const {
uint64_t value = 0;
if (this->endianness_ == LITTLE) {
offset += length;
while (length-- != 0) {
value <<= 8;
value |= this->data_[--offset];
}
} else {
while (length-- != 0) {
value <<= 8;
value |= this->data_[offset++];
}
}
return value;
}
uint64_t get_uint64_(size_t length) {
auto result = this->get_uint64_(this->position_, length);
this->position_ += length;
return result;
}
uint32_t get_uint32_(size_t offset, size_t length) const {
uint32_t value = 0;
if (this->endianness_ == LITTLE) {
offset += length;
while (length-- != 0) {
value <<= 8;
value |= this->data_[--offset];
}
} else {
while (length-- != 0) {
value <<= 8;
value |= this->data_[offset++];
}
}
return value;
}
uint32_t get_uint32_(size_t length) {
auto result = this->get_uint32_(this->position_, length);
this->position_ += length;
return result;
}
/// Putters
void put_uint64_(uint64_t value, size_t length) {
this->put_uint64_(value, this->position_, length);
this->position_ += length;
}
void put_uint32_(uint32_t value, size_t length) {
this->put_uint32_(value, this->position_, length);
this->position_ += length;
}
void put_uint64_(uint64_t value, size_t offset, size_t length) {
if (this->endianness_ == LITTLE) {
while (length-- != 0) {
this->data_[offset++] = static_cast<uint8_t>(value);
value >>= 8;
}
} else {
offset += length;
while (length-- != 0) {
this->data_[--offset] = static_cast<uint8_t>(value);
value >>= 8;
}
}
}
void put_uint32_(uint32_t value, size_t offset, size_t length) {
if (this->endianness_ == LITTLE) {
while (length-- != 0) {
this->data_[offset++] = static_cast<uint8_t>(value);
value >>= 8;
}
} else {
offset += length;
while (length-- != 0) {
this->data_[--offset] = static_cast<uint8_t>(value);
value >>= 8;
}
}
}
ByteBuffer(std::vector<uint8_t> const &data) : data_(data), limit_(data.size()) {}
std::vector<uint8_t> data_;
Endian endianness_{LITTLE};
size_t position_{0};
size_t mark_{0};
size_t limit_{0};
};
} // namespace bytebuffer
} // namespace esphome

View File

@ -119,10 +119,21 @@ visual_temperature = cv.float_with_unit(
)
def single_visual_temperature(value):
if isinstance(value, dict):
return value
VISUAL_TEMPERATURE_STEP_SCHEMA = cv.Schema(
{
cv.Required(CONF_TARGET_TEMPERATURE): visual_temperature,
cv.Required(CONF_CURRENT_TEMPERATURE): visual_temperature,
}
)
def visual_temperature_step(value):
# Allow defining target/current temperature steps separately
if isinstance(value, dict):
return VISUAL_TEMPERATURE_STEP_SCHEMA(value)
# Otherwise, use the single value for both properties
value = visual_temperature(value)
return VISUAL_TEMPERATURE_STEP_SCHEMA(
{
@ -141,16 +152,6 @@ ControlTrigger = climate_ns.class_(
"ControlTrigger", automation.Trigger.template(ClimateCall.operator("ref"))
)
VISUAL_TEMPERATURE_STEP_SCHEMA = cv.Any(
single_visual_temperature,
cv.Schema(
{
cv.Required(CONF_TARGET_TEMPERATURE): visual_temperature,
cv.Required(CONF_CURRENT_TEMPERATURE): visual_temperature,
}
),
)
CLIMATE_SCHEMA = (
cv.ENTITY_BASE_SCHEMA.extend(web_server.WEBSERVER_SORTING_SCHEMA)
.extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA)
@ -162,7 +163,7 @@ CLIMATE_SCHEMA = (
{
cv.Optional(CONF_MIN_TEMPERATURE): cv.temperature,
cv.Optional(CONF_MAX_TEMPERATURE): cv.temperature,
cv.Optional(CONF_TEMPERATURE_STEP): VISUAL_TEMPERATURE_STEP_SCHEMA,
cv.Optional(CONF_TEMPERATURE_STEP): visual_temperature_step,
cv.Optional(CONF_MIN_HUMIDITY): cv.percentage_int,
cv.Optional(CONF_MAX_HUMIDITY): cv.percentage_int,
}

View File

@ -70,8 +70,6 @@ def _validate_time_present(config):
_DATETIME_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend(
web_server.WEBSERVER_SORTING_SCHEMA,
cv.MQTT_COMMAND_COMPONENT_SCHEMA,
cv.Schema(
{
cv.Optional(CONF_ON_VALUE): automation.validate_automation(
@ -81,7 +79,9 @@ _DATETIME_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend(
),
cv.Optional(CONF_TIME_ID): cv.use_id(time.RealTimeClock),
}
),
)
.extend(web_server.WEBSERVER_SORTING_SCHEMA)
.extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA)
).add_extra(_validate_time_present)

View File

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

View File

@ -6,7 +6,104 @@ namespace dfplayer {
static const char *const TAG = "dfplayer";
void DFPlayer::next() {
this->ack_set_is_playing_ = true;
ESP_LOGD(TAG, "Playing next track");
this->send_cmd_(0x01);
}
void DFPlayer::previous() {
this->ack_set_is_playing_ = true;
ESP_LOGD(TAG, "Playing previous track");
this->send_cmd_(0x02);
}
void DFPlayer::play_mp3(uint16_t file) {
this->ack_set_is_playing_ = true;
ESP_LOGD(TAG, "Playing file %d in mp3 folder", file);
this->send_cmd_(0x12, file);
}
void DFPlayer::play_file(uint16_t file) {
this->ack_set_is_playing_ = true;
ESP_LOGD(TAG, "Playing file %d", file);
this->send_cmd_(0x03, file);
}
void DFPlayer::play_file_loop(uint16_t file) {
this->ack_set_is_playing_ = true;
ESP_LOGD(TAG, "Playing file %d in loop", file);
this->send_cmd_(0x08, file);
}
void DFPlayer::play_folder_loop(uint16_t folder) {
this->ack_set_is_playing_ = true;
ESP_LOGD(TAG, "Playing folder %d in loop", folder);
this->send_cmd_(0x17, folder);
}
void DFPlayer::volume_up() {
ESP_LOGD(TAG, "Increasing volume");
this->send_cmd_(0x04);
}
void DFPlayer::volume_down() {
ESP_LOGD(TAG, "Decreasing volume");
this->send_cmd_(0x05);
}
void DFPlayer::set_device(Device device) {
ESP_LOGD(TAG, "Setting device to %d", device);
this->send_cmd_(0x09, device);
}
void DFPlayer::set_volume(uint8_t volume) {
ESP_LOGD(TAG, "Setting volume to %d", volume);
this->send_cmd_(0x06, volume);
}
void DFPlayer::set_eq(EqPreset preset) {
ESP_LOGD(TAG, "Setting EQ to %d", preset);
this->send_cmd_(0x07, preset);
}
void DFPlayer::sleep() {
this->ack_reset_is_playing_ = true;
ESP_LOGD(TAG, "Putting DFPlayer to sleep");
this->send_cmd_(0x0A);
}
void DFPlayer::reset() {
this->ack_reset_is_playing_ = true;
ESP_LOGD(TAG, "Resetting DFPlayer");
this->send_cmd_(0x0C);
}
void DFPlayer::start() {
this->ack_set_is_playing_ = true;
ESP_LOGD(TAG, "Starting playback");
this->send_cmd_(0x0D);
}
void DFPlayer::pause() {
this->ack_reset_is_playing_ = true;
ESP_LOGD(TAG, "Pausing playback");
this->send_cmd_(0x0E);
}
void DFPlayer::stop() {
this->ack_reset_is_playing_ = true;
ESP_LOGD(TAG, "Stopping playback");
this->send_cmd_(0x16);
}
void DFPlayer::random() {
this->ack_set_is_playing_ = true;
ESP_LOGD(TAG, "Playing random file");
this->send_cmd_(0x18);
}
void DFPlayer::play_folder(uint16_t folder, uint16_t file) {
ESP_LOGD(TAG, "Playing file %d in folder %d", file, folder);
if (folder < 100 && file < 256) {
this->ack_set_is_playing_ = true;
this->send_cmd_(0x0F, (uint8_t) folder, (uint8_t) file);
@ -29,7 +126,7 @@ void DFPlayer::send_cmd_(uint8_t cmd, uint16_t argument) {
this->sent_cmd_ = cmd;
ESP_LOGD(TAG, "Send Command %#02x arg %#04x", cmd, argument);
ESP_LOGV(TAG, "Send Command %#02x arg %#04x", cmd, argument);
this->write_array(buffer, 10);
}
@ -101,9 +198,37 @@ void DFPlayer::loop() {
ESP_LOGV(TAG, "Nack");
this->ack_set_is_playing_ = false;
this->ack_reset_is_playing_ = false;
if (argument == 6) {
ESP_LOGV(TAG, "File not found");
this->is_playing_ = false;
switch (argument) {
case 0x01:
ESP_LOGE(TAG, "Module is busy or uninitialized");
break;
case 0x02:
ESP_LOGE(TAG, "Module is in sleep mode");
break;
case 0x03:
ESP_LOGE(TAG, "Serial receive error");
break;
case 0x04:
ESP_LOGE(TAG, "Checksum incorrect");
break;
case 0x05:
ESP_LOGE(TAG, "Specified track is out of current track scope");
this->is_playing_ = false;
break;
case 0x06:
ESP_LOGE(TAG, "Specified track is not found");
this->is_playing_ = false;
break;
case 0x07:
ESP_LOGE(TAG, "Insertion error (an inserting operation only can be done when a track is being played)");
break;
case 0x08:
ESP_LOGE(TAG, "SD card reading failed (SD card pulled out or damaged)");
break;
case 0x09:
ESP_LOGE(TAG, "Entered into sleep mode");
this->is_playing_ = false;
break;
}
break;
case 0x41:
@ -113,12 +238,13 @@ void DFPlayer::loop() {
this->ack_set_is_playing_ = false;
this->ack_reset_is_playing_ = false;
break;
case 0x3D: // Playback finished
case 0x3D:
ESP_LOGV(TAG, "Playback finished");
this->is_playing_ = false;
this->on_finished_playback_callback_.call();
break;
default:
ESP_LOGD(TAG, "Command %#02x arg %#04x", cmd, argument);
ESP_LOGV(TAG, "Received unknown cmd %#02x arg %#04x", cmd, argument);
}
this->sent_cmd_ = 0;
this->read_pos_ = 0;

View File

@ -23,64 +23,30 @@ enum Device {
TF_CARD = 2,
};
// See the datasheet here:
// https://github.com/DFRobot/DFRobotDFPlayerMini/blob/master/doc/FN-M16P%2BEmbedded%2BMP3%2BAudio%2BModule%2BDatasheet.pdf
class DFPlayer : public uart::UARTDevice, public Component {
public:
void loop() override;
void next() {
this->ack_set_is_playing_ = true;
this->send_cmd_(0x01);
}
void previous() {
this->ack_set_is_playing_ = true;
this->send_cmd_(0x02);
}
void play_mp3(uint16_t file) {
this->ack_set_is_playing_ = true;
this->send_cmd_(0x12, file);
}
void play_file(uint16_t file) {
this->ack_set_is_playing_ = true;
this->send_cmd_(0x03, file);
}
void play_file_loop(uint16_t file) {
this->ack_set_is_playing_ = true;
this->send_cmd_(0x08, file);
}
void next();
void previous();
void play_mp3(uint16_t file);
void play_file(uint16_t file);
void play_file_loop(uint16_t file);
void play_folder(uint16_t folder, uint16_t file);
void play_folder_loop(uint16_t folder) {
this->ack_set_is_playing_ = true;
this->send_cmd_(0x17, folder);
}
void volume_up() { this->send_cmd_(0x04); }
void volume_down() { this->send_cmd_(0x05); }
void set_device(Device device) { this->send_cmd_(0x09, device); }
void set_volume(uint8_t volume) { this->send_cmd_(0x06, volume); }
void set_eq(EqPreset preset) { this->send_cmd_(0x07, preset); }
void sleep() {
this->ack_reset_is_playing_ = true;
this->send_cmd_(0x0A);
}
void reset() {
this->ack_reset_is_playing_ = true;
this->send_cmd_(0x0C);
}
void start() {
this->ack_set_is_playing_ = true;
this->send_cmd_(0x0D);
}
void pause() {
this->ack_reset_is_playing_ = true;
this->send_cmd_(0x0E);
}
void stop() {
this->ack_reset_is_playing_ = true;
this->send_cmd_(0x16);
}
void random() {
this->ack_set_is_playing_ = true;
this->send_cmd_(0x18);
}
void play_folder_loop(uint16_t folder);
void volume_up();
void volume_down();
void set_device(Device device);
void set_volume(uint8_t volume);
void set_eq(EqPreset preset);
void sleep();
void reset();
void start();
void pause();
void stop();
void random();
bool is_playing() { return is_playing_; }
void dump_config() override;

View File

@ -156,6 +156,148 @@ void Display::filled_circle(int center_x, int center_y, int radius, Color color)
}
} 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) {
this->line(x1, y1, x2, y2, 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.
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.
void triangle(int x1, int y1, int x2, int y2, int x3, int y3, Color color = COLOR_ON);

View File

View File

@ -0,0 +1,70 @@
import esphome.codegen as cg
from esphome.components import i2c
from esphome.components.audio_dac import AudioDac
import esphome.config_validation as cv
from esphome.const import CONF_BITS_PER_SAMPLE, CONF_ID, CONF_SAMPLE_RATE
CODEOWNERS = ["@kroimon", "@kahrendt"]
DEPENDENCIES = ["i2c"]
es8311_ns = cg.esphome_ns.namespace("es8311")
ES8311 = es8311_ns.class_("ES8311", AudioDac, cg.Component, i2c.I2CDevice)
CONF_MIC_GAIN = "mic_gain"
CONF_USE_MCLK = "use_mclk"
CONF_USE_MICROPHONE = "use_microphone"
es8311_resolution = es8311_ns.enum("ES8311Resolution")
ES8311_BITS_PER_SAMPLE_ENUM = {
16: es8311_resolution.ES8311_RESOLUTION_16,
24: es8311_resolution.ES8311_RESOLUTION_24,
32: es8311_resolution.ES8311_RESOLUTION_32,
}
es8311_mic_gain = es8311_ns.enum("ES8311MicGain")
ES8311_MIC_GAIN_ENUM = {
"MIN": es8311_mic_gain.ES8311_MIC_GAIN_MIN,
"0DB": es8311_mic_gain.ES8311_MIC_GAIN_0DB,
"6DB": es8311_mic_gain.ES8311_MIC_GAIN_6DB,
"12DB": es8311_mic_gain.ES8311_MIC_GAIN_12DB,
"18DB": es8311_mic_gain.ES8311_MIC_GAIN_18DB,
"24DB": es8311_mic_gain.ES8311_MIC_GAIN_24DB,
"30DB": es8311_mic_gain.ES8311_MIC_GAIN_30DB,
"36DB": es8311_mic_gain.ES8311_MIC_GAIN_36DB,
"42DB": es8311_mic_gain.ES8311_MIC_GAIN_42DB,
"MAX": es8311_mic_gain.ES8311_MIC_GAIN_MAX,
}
_validate_bits = cv.float_with_unit("bits", "bit")
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(ES8311),
cv.Optional(CONF_BITS_PER_SAMPLE, default="16bit"): cv.All(
_validate_bits, cv.enum(ES8311_BITS_PER_SAMPLE_ENUM)
),
cv.Optional(CONF_MIC_GAIN, default="42DB"): cv.enum(
ES8311_MIC_GAIN_ENUM, upper=True
),
cv.Optional(CONF_SAMPLE_RATE, default=16000): cv.int_range(min=1),
cv.Optional(CONF_USE_MCLK, default=True): cv.boolean,
cv.Optional(CONF_USE_MICROPHONE, default=False): cv.boolean,
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(i2c.i2c_device_schema(0x18))
)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
await i2c.register_i2c_device(var, config)
cg.add(var.set_bits_per_sample(config[CONF_BITS_PER_SAMPLE]))
cg.add(var.set_mic_gain(config[CONF_MIC_GAIN]))
cg.add(var.set_sample_frequency(config[CONF_SAMPLE_RATE]))
cg.add(var.set_use_mclk(config[CONF_USE_MCLK]))
cg.add(var.set_use_mic(config[CONF_USE_MICROPHONE]))

View File

@ -0,0 +1,227 @@
#include "es8311.h"
#include "es8311_const.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#include <cinttypes>
namespace esphome {
namespace es8311 {
static const char *const TAG = "es8311";
// Mark the component as failed; use only in setup
#define ES8311_ERROR_FAILED(func) \
if (!(func)) { \
this->mark_failed(); \
return; \
}
// Return false; use outside of setup
#define ES8311_ERROR_CHECK(func) \
if (!(func)) { \
return false; \
}
void ES8311::setup() {
ESP_LOGCONFIG(TAG, "Setting up ES8311...");
// Reset
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG00_RESET, 0x1F));
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG00_RESET, 0x00));
ES8311_ERROR_FAILED(this->configure_clock_());
ES8311_ERROR_FAILED(this->configure_format_());
ES8311_ERROR_FAILED(this->configure_mic_());
// Set initial volume
this->set_volume(0.75); // 0.75 = 0xBF = 0dB
// Power up analog circuitry
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG0D_SYSTEM, 0x01));
// Enable analog PGA, enable ADC modulator
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG0E_SYSTEM, 0x02));
// Power up DAC
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG12_SYSTEM, 0x00));
// Enable output to HP drive
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG13_SYSTEM, 0x10));
// ADC Equalizer bypass, cancel DC offset in digital domain
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG1C_ADC, 0x6A));
// Bypass DAC equalizer
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG37_DAC, 0x08));
// Power On
ES8311_ERROR_FAILED(this->write_byte(ES8311_REG00_RESET, 0x80));
}
void ES8311::dump_config() {
ESP_LOGCONFIG(TAG, "ES8311 Audio Codec:");
ESP_LOGCONFIG(TAG, " Use MCLK: %s", YESNO(this->use_mclk_));
ESP_LOGCONFIG(TAG, " Use Microphone: %s", YESNO(this->use_mic_));
ESP_LOGCONFIG(TAG, " DAC Bits per Sample: %" PRIu8, this->resolution_out_);
ESP_LOGCONFIG(TAG, " Sample Rate: %" PRIu32, this->sample_frequency_);
if (this->is_failed()) {
ESP_LOGCONFIG(TAG, " Failed to initialize!");
return;
}
}
bool ES8311::set_volume(float volume) {
volume = clamp(volume, 0.0f, 1.0f);
uint8_t reg32 = remap<uint8_t, float>(volume, 0.0f, 1.0f, 0, 255);
return this->write_byte(ES8311_REG32_DAC, reg32);
}
float ES8311::volume() {
uint8_t reg32;
this->read_byte(ES8311_REG32_DAC, &reg32);
return remap<float, uint8_t>(reg32, 0, 255, 0.0f, 1.0f);
}
uint8_t ES8311::calculate_resolution_value(ES8311Resolution resolution) {
switch (resolution) {
case ES8311_RESOLUTION_16:
return (3 << 2);
case ES8311_RESOLUTION_18:
return (2 << 2);
case ES8311_RESOLUTION_20:
return (1 << 2);
case ES8311_RESOLUTION_24:
return (0 << 2);
case ES8311_RESOLUTION_32:
return (4 << 2);
default:
return 0;
}
}
const ES8311Coefficient *ES8311::get_coefficient(uint32_t mclk, uint32_t rate) {
for (const auto &coefficient : ES8311_COEFFICIENTS) {
if (coefficient.mclk == mclk && coefficient.rate == rate)
return &coefficient;
}
return nullptr;
}
bool ES8311::configure_clock_() {
// Register 0x01: select clock source for internal MCLK and determine its frequency
uint8_t reg01 = 0x3F; // Enable all clocks
uint32_t mclk_frequency = this->sample_frequency_ * this->mclk_multiple_;
if (!this->use_mclk_) {
reg01 |= BIT(7); // Use SCLK
mclk_frequency = this->sample_frequency_ * (int) this->resolution_out_ * 2;
}
if (this->mclk_inverted_) {
reg01 |= BIT(6); // Invert MCLK pin
}
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG01_CLK_MANAGER, reg01));
// Get clock coefficients from coefficient table
auto *coefficient = get_coefficient(mclk_frequency, this->sample_frequency_);
if (coefficient == nullptr) {
ESP_LOGE(TAG, "Unable to configure sample rate %" PRIu32 "Hz with %" PRIu32 "Hz MCLK", this->sample_frequency_,
mclk_frequency);
return false;
}
// Register 0x02
uint8_t reg02;
ES8311_ERROR_CHECK(this->read_byte(ES8311_REG02_CLK_MANAGER, &reg02));
reg02 &= 0x07;
reg02 |= (coefficient->pre_div - 1) << 5;
reg02 |= coefficient->pre_mult << 3;
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG02_CLK_MANAGER, reg02));
// Register 0x03
const uint8_t reg03 = (coefficient->fs_mode << 6) | coefficient->adc_osr;
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG03_CLK_MANAGER, reg03));
// Register 0x04
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG04_CLK_MANAGER, coefficient->dac_osr));
// Register 0x05
const uint8_t reg05 = ((coefficient->adc_div - 1) << 4) | (coefficient->dac_div - 1);
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG05_CLK_MANAGER, reg05));
// Register 0x06
uint8_t reg06;
ES8311_ERROR_CHECK(this->read_byte(ES8311_REG06_CLK_MANAGER, &reg06));
if (this->sclk_inverted_) {
reg06 |= BIT(5);
} else {
reg06 &= ~BIT(5);
}
reg06 &= 0xE0;
if (coefficient->bclk_div < 19) {
reg06 |= (coefficient->bclk_div - 1) << 0;
} else {
reg06 |= (coefficient->bclk_div) << 0;
}
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG06_CLK_MANAGER, reg06));
// Register 0x07
uint8_t reg07;
ES8311_ERROR_CHECK(this->read_byte(ES8311_REG07_CLK_MANAGER, &reg07));
reg07 &= 0xC0;
reg07 |= coefficient->lrck_h << 0;
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG07_CLK_MANAGER, reg07));
// Register 0x08
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG08_CLK_MANAGER, coefficient->lrck_l));
// Successfully configured the clock
return true;
}
bool ES8311::configure_format_() {
// Configure I2S mode and format
uint8_t reg00;
ES8311_ERROR_CHECK(this->read_byte(ES8311_REG00_RESET, &reg00));
reg00 &= 0xBF;
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG00_RESET, reg00));
// Configure SDP in resolution
uint8_t reg09 = calculate_resolution_value(this->resolution_in_);
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG09_SDPIN, reg09));
// Configure SDP out resolution
uint8_t reg0a = calculate_resolution_value(this->resolution_out_);
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG0A_SDPOUT, reg0a));
// Successfully configured the format
return true;
}
bool ES8311::configure_mic_() {
uint8_t reg14 = 0x1A; // Enable analog MIC and max PGA gain
if (this->use_mic_) {
reg14 |= BIT(6); // Enable PDM digital microphone
}
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG14_SYSTEM, reg14));
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG16_ADC, this->mic_gain_)); // ADC gain scale up
ES8311_ERROR_CHECK(this->write_byte(ES8311_REG17_ADC, 0xC8)); // Set ADC gain
// Successfully configured the microphones
return true;
}
bool ES8311::set_mute_state_(bool mute_state) {
uint8_t reg31;
this->is_muted_ = mute_state;
if (!this->read_byte(ES8311_REG31_DAC, &reg31)) {
return false;
}
if (mute_state) {
reg31 |= BIT(6) | BIT(5);
} else {
reg31 &= ~(BIT(6) | BIT(5));
}
return this->write_byte(ES8311_REG31_DAC, reg31);
}
} // namespace es8311
} // namespace esphome

View File

@ -0,0 +1,135 @@
#pragma once
#include "esphome/components/audio_dac/audio_dac.h"
#include "esphome/components/i2c/i2c.h"
#include "esphome/core/component.h"
namespace esphome {
namespace es8311 {
enum ES8311MicGain {
ES8311_MIC_GAIN_MIN = -1,
ES8311_MIC_GAIN_0DB,
ES8311_MIC_GAIN_6DB,
ES8311_MIC_GAIN_12DB,
ES8311_MIC_GAIN_18DB,
ES8311_MIC_GAIN_24DB,
ES8311_MIC_GAIN_30DB,
ES8311_MIC_GAIN_36DB,
ES8311_MIC_GAIN_42DB,
ES8311_MIC_GAIN_MAX
};
enum ES8311Resolution : uint8_t {
ES8311_RESOLUTION_16 = 16,
ES8311_RESOLUTION_18 = 18,
ES8311_RESOLUTION_20 = 20,
ES8311_RESOLUTION_24 = 24,
ES8311_RESOLUTION_32 = 32
};
struct ES8311Coefficient {
uint32_t mclk; // mclk frequency
uint32_t rate; // sample rate
uint8_t pre_div; // the pre divider with range from 1 to 8
uint8_t pre_mult; // the pre multiplier with x1, x2, x4 and x8 selection
uint8_t adc_div; // adcclk divider
uint8_t dac_div; // dacclk divider
uint8_t fs_mode; // single speed (0) or double speed (1)
uint8_t lrck_h; // adc lrck divider and dac lrck divider
uint8_t lrck_l; //
uint8_t bclk_div; // sclk divider
uint8_t adc_osr; // adc osr
uint8_t dac_osr; // dac osr
};
class ES8311 : public audio_dac::AudioDac, public Component, public i2c::I2CDevice {
public:
/////////////////////////
// Component overrides //
/////////////////////////
void setup() override;
float get_setup_priority() const override { return setup_priority::DATA; }
void dump_config() override;
////////////////////////
// AudioDac overrides //
////////////////////////
/// @brief Writes the volume out to the DAC
/// @param volume floating point between 0.0 and 1.0
/// @return True if successful and false otherwise
bool set_volume(float volume) override;
/// @brief Gets the current volume out from the DAC
/// @return floating point between 0.0 and 1.0
float volume() override;
/// @brief Disables mute for audio out
/// @return True if successful and false otherwise
bool set_mute_off() override { return this->set_mute_state_(false); }
/// @brief Enables mute for audio out
/// @return True if successful and false otherwise
bool set_mute_on() override { return this->set_mute_state_(true); }
bool is_muted() override { return this->is_muted_; }
//////////////////////////////////
// ES8311 configuration setters //
//////////////////////////////////
void set_use_mclk(bool use_mclk) { this->use_mclk_ = use_mclk; }
void set_bits_per_sample(ES8311Resolution resolution) {
this->resolution_in_ = resolution;
this->resolution_out_ = resolution;
}
void set_sample_frequency(uint32_t sample_frequency) { this->sample_frequency_ = sample_frequency; }
void set_use_mic(bool use_mic) { this->use_mic_ = use_mic; }
void set_mic_gain(ES8311MicGain mic_gain) { this->mic_gain_ = mic_gain; }
protected:
/// @brief Computes the register value for the configured resolution (bits per sample)
/// @param resolution bits per sample enum for both audio in and audio out
/// @return register value
static uint8_t calculate_resolution_value(ES8311Resolution resolution);
/// @brief Retrieves the appropriate registers values for the configured mclk and rate
/// @param mclk mlck frequency in Hz
/// @param rate sample rate frequency in Hz
/// @return ES8311Coeffecient containing appropriate register values to configure the ES8311 or nullptr if impossible
static const ES8311Coefficient *get_coefficient(uint32_t mclk, uint32_t rate);
/// @brief Configures the ES8311 registers for the chosen sample rate
/// @return True if successful and false otherwise
bool configure_clock_();
/// @brief Configures the ES8311 registers for the chosen bits per sample
/// @return True if successful and false otherwise
bool configure_format_();
/// @brief Configures the ES8311 microphone registers
/// @return True if successful and false otherwise
bool configure_mic_();
/// @brief Mutes or unmute the DAC audio out
/// @param mute_state True to mute, false to unmute
/// @return
bool set_mute_state_(bool mute_state);
bool use_mic_;
ES8311MicGain mic_gain_;
bool use_mclk_; // true = use dedicated MCLK pin, false = use SCLK
bool sclk_inverted_{false}; // SCLK is inverted
bool mclk_inverted_{false}; // MCLK is inverted (ignored if use_mclk_ == false)
uint32_t mclk_multiple_{256}; // MCLK frequency is sample rate * mclk_multiple_ (ignored if use_mclk_ == false)
uint32_t sample_frequency_; // in Hz
ES8311Resolution resolution_in_;
ES8311Resolution resolution_out_;
};
} // namespace es8311
} // namespace esphome

View File

@ -0,0 +1,195 @@
#pragma once
#include "es8311.h"
namespace esphome {
namespace es8311 {
// ES8311 register addresses
static const uint8_t ES8311_REG00_RESET = 0x00; // Reset
static const uint8_t ES8311_REG01_CLK_MANAGER = 0x01; // Clock Manager: select clk src for mclk, enable clock for codec
static const uint8_t ES8311_REG02_CLK_MANAGER = 0x02; // Clock Manager: clk divider and clk multiplier
static const uint8_t ES8311_REG03_CLK_MANAGER = 0x03; // Clock Manager: adc fsmode and osr
static const uint8_t ES8311_REG04_CLK_MANAGER = 0x04; // Clock Manager: dac osr
static const uint8_t ES8311_REG05_CLK_MANAGER = 0x05; // Clock Manager: clk divider for adc and dac
static const uint8_t ES8311_REG06_CLK_MANAGER = 0x06; // Clock Manager: bclk inverter BIT(5) and divider
static const uint8_t ES8311_REG07_CLK_MANAGER = 0x07; // Clock Manager: tri-state, lrck divider
static const uint8_t ES8311_REG08_CLK_MANAGER = 0x08; // Clock Manager: lrck divider
static const uint8_t ES8311_REG09_SDPIN = 0x09; // Serial Digital Port: DAC
static const uint8_t ES8311_REG0A_SDPOUT = 0x0A; // Serial Digital Port: ADC
static const uint8_t ES8311_REG0B_SYSTEM = 0x0B; // System
static const uint8_t ES8311_REG0C_SYSTEM = 0x0C; // System
static const uint8_t ES8311_REG0D_SYSTEM = 0x0D; // System: power up/down
static const uint8_t ES8311_REG0E_SYSTEM = 0x0E; // System: power up/down
static const uint8_t ES8311_REG0F_SYSTEM = 0x0F; // System: low power
static const uint8_t ES8311_REG10_SYSTEM = 0x10; // System
static const uint8_t ES8311_REG11_SYSTEM = 0x11; // System
static const uint8_t ES8311_REG12_SYSTEM = 0x12; // System: Enable DAC
static const uint8_t ES8311_REG13_SYSTEM = 0x13; // System
static const uint8_t ES8311_REG14_SYSTEM = 0x14; // System: select DMIC, select analog pga gain
static const uint8_t ES8311_REG15_ADC = 0x15; // ADC: adc ramp rate, dmic sense
static const uint8_t ES8311_REG16_ADC = 0x16; // ADC
static const uint8_t ES8311_REG17_ADC = 0x17; // ADC: volume
static const uint8_t ES8311_REG18_ADC = 0x18; // ADC: alc enable and winsize
static const uint8_t ES8311_REG19_ADC = 0x19; // ADC: alc maxlevel
static const uint8_t ES8311_REG1A_ADC = 0x1A; // ADC: alc automute
static const uint8_t ES8311_REG1B_ADC = 0x1B; // ADC: alc automute, adc hpf s1
static const uint8_t ES8311_REG1C_ADC = 0x1C; // ADC: equalizer, hpf s2
static const uint8_t ES8311_REG1D_ADCEQ = 0x1D; // ADCEQ: equalizer B0
static const uint8_t ES8311_REG1E_ADCEQ = 0x1E; // ADCEQ: equalizer B0
static const uint8_t ES8311_REG1F_ADCEQ = 0x1F; // ADCEQ: equalizer B0
static const uint8_t ES8311_REG20_ADCEQ = 0x20; // ADCEQ: equalizer B0
static const uint8_t ES8311_REG21_ADCEQ = 0x21; // ADCEQ: equalizer A1
static const uint8_t ES8311_REG22_ADCEQ = 0x22; // ADCEQ: equalizer A1
static const uint8_t ES8311_REG23_ADCEQ = 0x23; // ADCEQ: equalizer A1
static const uint8_t ES8311_REG24_ADCEQ = 0x24; // ADCEQ: equalizer A1
static const uint8_t ES8311_REG25_ADCEQ = 0x25; // ADCEQ: equalizer A2
static const uint8_t ES8311_REG26_ADCEQ = 0x26; // ADCEQ: equalizer A2
static const uint8_t ES8311_REG27_ADCEQ = 0x27; // ADCEQ: equalizer A2
static const uint8_t ES8311_REG28_ADCEQ = 0x28; // ADCEQ: equalizer A2
static const uint8_t ES8311_REG29_ADCEQ = 0x29; // ADCEQ: equalizer B1
static const uint8_t ES8311_REG2A_ADCEQ = 0x2A; // ADCEQ: equalizer B1
static const uint8_t ES8311_REG2B_ADCEQ = 0x2B; // ADCEQ: equalizer B1
static const uint8_t ES8311_REG2C_ADCEQ = 0x2C; // ADCEQ: equalizer B1
static const uint8_t ES8311_REG2D_ADCEQ = 0x2D; // ADCEQ: equalizer B2
static const uint8_t ES8311_REG2E_ADCEQ = 0x2E; // ADCEQ: equalizer B2
static const uint8_t ES8311_REG2F_ADCEQ = 0x2F; // ADCEQ: equalizer B2
static const uint8_t ES8311_REG30_ADCEQ = 0x30; // ADCEQ: equalizer B2
static const uint8_t ES8311_REG31_DAC = 0x31; // DAC: mute
static const uint8_t ES8311_REG32_DAC = 0x32; // DAC: volume
static const uint8_t ES8311_REG33_DAC = 0x33; // DAC: offset
static const uint8_t ES8311_REG34_DAC = 0x34; // DAC: drc enable, drc winsize
static const uint8_t ES8311_REG35_DAC = 0x35; // DAC: drc maxlevel, minilevel
static const uint8_t ES8311_REG36_DAC = 0x36; // DAC
static const uint8_t ES8311_REG37_DAC = 0x37; // DAC: ramprate
static const uint8_t ES8311_REG38_DACEQ = 0x38; // DACEQ: equalizer B0
static const uint8_t ES8311_REG39_DACEQ = 0x39; // DACEQ: equalizer B0
static const uint8_t ES8311_REG3A_DACEQ = 0x3A; // DACEQ: equalizer B0
static const uint8_t ES8311_REG3B_DACEQ = 0x3B; // DACEQ: equalizer B0
static const uint8_t ES8311_REG3C_DACEQ = 0x3C; // DACEQ: equalizer B1
static const uint8_t ES8311_REG3D_DACEQ = 0x3D; // DACEQ: equalizer B1
static const uint8_t ES8311_REG3E_DACEQ = 0x3E; // DACEQ: equalizer B1
static const uint8_t ES8311_REG3F_DACEQ = 0x3F; // DACEQ: equalizer B1
static const uint8_t ES8311_REG40_DACEQ = 0x40; // DACEQ: equalizer A1
static const uint8_t ES8311_REG41_DACEQ = 0x41; // DACEQ: equalizer A1
static const uint8_t ES8311_REG42_DACEQ = 0x42; // DACEQ: equalizer A1
static const uint8_t ES8311_REG43_DACEQ = 0x43; // DACEQ: equalizer A1
static const uint8_t ES8311_REG44_GPIO = 0x44; // GPIO: dac2adc for test
static const uint8_t ES8311_REG45_GP = 0x45; // GPIO: GP control
static const uint8_t ES8311_REGFA_I2C = 0xFA; // I2C: reset registers
static const uint8_t ES8311_REGFC_FLAG = 0xFC; // Flag
static const uint8_t ES8311_REGFD_CHD1 = 0xFD; // Chip: ID1
static const uint8_t ES8311_REGFE_CHD2 = 0xFE; // Chip: ID2
static const uint8_t ES8311_REGFF_CHVER = 0xFF; // Chip: Version
// ES8311 clock divider coefficients
static const ES8311Coefficient ES8311_COEFFICIENTS[] = {
// clang-format off
// mclk, rate, pre_ pre_ adc_ dac_ fs_ lrck lrck bclk_ adc_ dac_
// div, mult, div, div, mode, _h, _l, div, osr, osr
// 8k
{12288000, 8000, 0x06, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{18432000, 8000, 0x03, 0x02, 0x03, 0x03, 0x00, 0x05, 0xff, 0x18, 0x10, 0x20},
{16384000, 8000, 0x08, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 8192000, 8000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 6144000, 8000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 4096000, 8000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 3072000, 8000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 2048000, 8000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1536000, 8000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1024000, 8000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
// 11.025k
{11289600, 11025, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 5644800, 11025, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 2822400, 11025, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1411200, 11025, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
// 12k
{12288000, 12000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 6144000, 12000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 3072000, 12000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1536000, 12000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
// 16k
{12288000, 16000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{18432000, 16000, 0x03, 0x02, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x20},
{16384000, 16000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 8192000, 16000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 6144000, 16000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 4096000, 16000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 3072000, 16000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 2048000, 16000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1536000, 16000, 0x03, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
{ 1024000, 16000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x20},
// 22.05k
{11289600, 22050, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 5644800, 22050, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 2822400, 22050, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1411200, 22050, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
// 24k
{12288000, 24000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 24000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 6144000, 24000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 3072000, 24000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1536000, 24000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
// 32k
{12288000, 32000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 32000, 0x03, 0x04, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10},
{16384000, 32000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 8192000, 32000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 6144000, 32000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 4096000, 32000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 3072000, 32000, 0x03, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 2048000, 32000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1536000, 32000, 0x03, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
{ 1024000, 32000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
// 44.1k
{11289600, 44100, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 5644800, 44100, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 2822400, 44100, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1411200, 44100, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
// 48k
{12288000, 48000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 48000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 6144000, 48000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 3072000, 48000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1536000, 48000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
// 64k
{12288000, 64000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 64000, 0x03, 0x04, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{16384000, 64000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 8192000, 64000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 6144000, 64000, 0x01, 0x04, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{ 4096000, 64000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 3072000, 64000, 0x01, 0x08, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{ 2048000, 64000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1536000, 64000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0xbf, 0x03, 0x18, 0x18},
{ 1024000, 64000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
// 88.2k
{11289600, 88200, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 5644800, 88200, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 2822400, 88200, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1411200, 88200, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
// 96k
{12288000, 96000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 96000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 6144000, 96000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 3072000, 96000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{ 1536000, 96000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
// clang-format on
};
} // namespace es8311
} // namespace esphome

View File

@ -103,6 +103,173 @@ ESP32_BOARD_PINS = {
"LED": 13,
"LED_BUILTIN": 13,
},
"adafruit_feather_esp32s3": {
"BUTTON": 0,
"A0": 18,
"A1": 17,
"A2": 16,
"A3": 15,
"A4": 14,
"A5": 8,
"SCK": 36,
"MOSI": 35,
"MISO": 37,
"RX": 38,
"TX": 39,
"SCL": 4,
"SDA": 3,
"NEOPIXEL": 33,
"PIN_NEOPIXEL": 33,
"NEOPIXEL_POWER": 21,
"I2C_POWER": 7,
"LED": 13,
"LED_BUILTIN": 13,
},
"adafruit_feather_esp32s3_nopsram": {
"BUTTON": 0,
"A0": 18,
"A1": 17,
"A2": 16,
"A3": 15,
"A4": 14,
"A5": 8,
"SCK": 36,
"MOSI": 35,
"MISO": 37,
"RX": 38,
"TX": 39,
"SCL": 4,
"SDA": 3,
"NEOPIXEL": 33,
"PIN_NEOPIXEL": 33,
"NEOPIXEL_POWER": 21,
"I2C_POWER": 7,
"LED": 13,
"LED_BUILTIN": 13,
},
"adafruit_feather_esp32s3_tft": {
"BUTTON": 0,
"A0": 18,
"A1": 17,
"A2": 16,
"A3": 15,
"A4": 14,
"A5": 8,
"SCK": 36,
"MOSI": 35,
"MISO": 37,
"RX": 2,
"TX": 1,
"SCL": 41,
"SDA": 42,
"NEOPIXEL": 33,
"PIN_NEOPIXEL": 33,
"NEOPIXEL_POWER": 34,
"TFT_I2C_POWER": 21,
"TFT_CS": 7,
"TFT_DC": 39,
"TFT_RESET": 40,
"TFT_BACKLIGHT": 45,
"LED": 13,
"LED_BUILTIN": 13,
},
"adafruit_funhouse_esp32s2": {
"BUTTON_UP": 5,
"BUTTON_DOWN": 3,
"BUTTON_SELECT": 4,
"DOTSTAR_DATA": 14,
"DOTSTAR_CLOCK": 15,
"PIR_SENSE": 16,
"A0": 17,
"A1": 2,
"A2": 1,
"CAP6": 6,
"CAP7": 7,
"CAP8": 8,
"CAP9": 9,
"CAP10": 10,
"CAP11": 11,
"CAP12": 12,
"CAP13": 13,
"SPEAKER": 42,
"LED": 37,
"LIGHT": 18,
"TFT_MOSI": 35,
"TFT_SCK": 36,
"TFT_CS": 40,
"TFT_DC": 39,
"TFT_RESET": 41,
"TFT_BACKLIGHT": 21,
"RED_LED": 31,
"BUTTON": 0,
},
"adafruit_itsybitsy_esp32": {
"A0": 25,
"A1": 26,
"A2": 4,
"A3": 38,
"A4": 37,
"A5": 36,
"SCK": 19,
"MOSI": 21,
"MISO": 22,
"SCL": 27,
"SDA": 15,
"TX": 20,
"RX": 8,
"NEOPIXEL": 0,
"PIN_NEOPIXEL": 0,
"NEOPIXEL_POWER": 2,
"BUTTON": 35,
},
"adafruit_magtag29_esp32s2": {
"A1": 18,
"BUTTON_A": 15,
"BUTTON_B": 14,
"BUTTON_C": 12,
"BUTTON_D": 11,
"SDA": 33,
"SCL": 34,
"SPEAKER": 17,
"SPEAKER_ENABLE": 16,
"VOLTAGE_MONITOR": 4,
"ACCELEROMETER_INT": 9,
"ACCELEROMETER_INTERRUPT": 9,
"LIGHT": 3,
"NEOPIXEL": 1,
"PIN_NEOPIXEL": 1,
"NEOPIXEL_POWER": 21,
"EPD_BUSY": 5,
"EPD_RESET": 6,
"EPD_DC": 7,
"EPD_CS": 8,
"EPD_MOSI": 35,
"EPD_SCK": 36,
"EPD_MISO": 37,
"BUTTON": 0,
"LED": 13,
"LED_BUILTIN": 13,
},
"adafruit_metro_esp32s2": {
"A0": 17,
"A1": 18,
"A2": 1,
"A3": 2,
"A4": 3,
"A5": 4,
"RX": 38,
"TX": 37,
"SCL": 34,
"SDA": 33,
"MISO": 37,
"SCK": 36,
"MOSI": 35,
"NEOPIXEL": 45,
"PIN_NEOPIXEL": 45,
"LED": 42,
"LED_BUILTIN": 42,
"BUTTON": 0,
},
"adafruit_qtpy_esp32c3": {
"A0": 4,
"A1": 3,
@ -141,6 +308,26 @@ ESP32_BOARD_PINS = {
"BUTTON": 0,
"SWITCH": 0,
},
"adafruit_qtpy_esp32s3_nopsram": {
"A0": 18,
"A1": 17,
"A2": 9,
"A3": 8,
"SDA": 7,
"SCL": 6,
"MOSI": 35,
"MISO": 37,
"SCK": 36,
"RX": 16,
"TX": 5,
"SDA1": 41,
"SCL1": 40,
"NEOPIXEL": 39,
"PIN_NEOPIXEL": 39,
"NEOPIXEL_POWER": 38,
"BUTTON": 0,
"SWITCH": 0,
},
"adafruit_qtpy_esp32": {
"A0": 26,
"A1": 25,
@ -1068,7 +1255,18 @@ ESP32_BOARD_PINS = {
"_VBAT": 35,
},
"wemosbat": {"LED": 16},
"wesp32": {"MISO": 32, "SCL": 4, "SDA": 15},
"wesp32": {
"MISO": 32,
"MOSI": 23,
"SCK": 18,
"SCL": 4,
"SDA": 15,
"MISO1": 12,
"MOSI1": 13,
"SCK1": 14,
"SCL1": 5,
"SDA1": 33,
},
"widora-air": {
"A1": 39,
"A2": 35,

View File

@ -67,8 +67,10 @@ def _translate_pin(value):
"This variable only supports pin numbers, not full pin schemas "
"(with inverted and mode)."
)
if isinstance(value, int):
if isinstance(value, int) and not isinstance(value, bool):
return value
if not isinstance(value, str):
raise cv.Invalid(f"Invalid pin number: {value}")
try:
return int(value)
except ValueError:

View File

@ -40,6 +40,9 @@ static const esp_bt_controller_config_t BT_CONTROLLER_CONFIG = {
.controller_run_cpu = 0,
.enable_qa_test = RUN_QA_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,
.ble_hci_uart_port = DEFAULT_BT_LE_HCI_UART_PORT,
.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_flow_ctrl = DEFAULT_BT_LE_HCI_UART_FLOW_CTRL,
.ble_hci_uart_uart_parity = DEFAULT_BT_LE_HCI_UART_PARITY,
#endif
.enable_tx_cca = DEFAULT_BT_LE_TX_CCA_ENABLED,
.cca_rssi_thresh = 256 - DEFAULT_BT_LE_CCA_RSSI_THRESH,
.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,
.ignore_wl_for_direct_adv = 0,
.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,
};

View File

@ -35,7 +35,7 @@ class BLEClientBase : public espbt::ESPBTClient, public Component {
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override;
void connect() override;
esp_err_t pair();
void disconnect();
void disconnect() override;
void release_services();
bool connected() { return this->state_ == espbt::ClientState::ESTABLISHED; }

View File

@ -65,6 +65,9 @@ void ESP32BLETracker::setup() {
[this](ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) {
if (state == ota::OTA_STARTED) {
this->stop_scan();
for (auto *client : this->clients_) {
client->disconnect();
}
}
});
#endif

View File

@ -11,9 +11,9 @@
#ifdef USE_ESP32
#include <esp_bt_defs.h>
#include <esp_gap_ble_api.h>
#include <esp_gattc_api.h>
#include <esp_bt_defs.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
@ -172,6 +172,7 @@ class ESPBTClient : public ESPBTDeviceListener {
esp_ble_gattc_cb_param_t *param) = 0;
virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0;
virtual void connect() = 0;
virtual void disconnect() = 0;
virtual void set_state(ClientState st) { this->state_ = st; }
ClientState state() const { return state_; }
int app_id;

View File

@ -22,7 +22,7 @@ void ESP32RMTLEDStripLightOutput::setup() {
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);
if (this->buf_ == nullptr) {
ESP_LOGE(TAG, "Cannot allocate LED buffer!");
@ -37,7 +37,7 @@ void ESP32RMTLEDStripLightOutput::setup() {
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 +
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_is_rgbw(bool is_rgbw) { this->is_rgbw_ = is_rgbw; }
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.
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_;
bool is_rgbw_;
bool is_wrgb_;
bool use_psram_;
rmt_item32_t bit0_, bit1_, reset_;
RGBOrder rgb_order_;

View File

@ -55,7 +55,7 @@ CHIPSETS = {
"SM16703": LEDStripTimings(300, 900, 900, 300, 0, 0),
}
CONF_USE_PSRAM = "use_psram"
CONF_IS_WRGB = "is_wrgb"
CONF_BIT0_HIGH = "bit0_high"
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_IS_RGBW, default=False): cv.boolean,
cv.Optional(CONF_IS_WRGB, default=False): cv.boolean,
cv.Optional(CONF_USE_PSRAM, default=True): cv.boolean,
cv.Inclusive(
CONF_BIT0_HIGH,
"custom",
@ -145,6 +146,7 @@ async def to_code(config):
cg.add(var.set_rgb_order(config[CONF_RGB_ORDER]))
cg.add(var.set_is_rgbw(config[CONF_IS_RGBW]))
cg.add(var.set_is_wrgb(config[CONF_IS_WRGB]))
cg.add(var.set_use_psram(config[CONF_USE_PSRAM]))
cg.add(
var.set_rmt_channel(

View File

@ -1,6 +1,9 @@
import logging
from dataclasses import dataclass
import logging
from esphome import pins
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import (
CONF_ANALOG,
CONF_ID,
@ -14,10 +17,7 @@ from esphome.const import (
CONF_PULLUP,
PLATFORM_ESP8266,
)
from esphome import pins
from esphome.core import CORE, coroutine_with_priority
import esphome.config_validation as cv
import esphome.codegen as cg
from . import boards
from .const import KEY_BOARD, KEY_ESP8266, KEY_PIN_INITIAL_STATES, esp8266_ns
@ -48,8 +48,10 @@ def _translate_pin(value):
"This variable only supports pin numbers, not full pin schemas "
"(with inverted and mode)."
)
if isinstance(value, int):
if isinstance(value, int) and not isinstance(value, bool):
return value
if not isinstance(value, str):
raise cv.Invalid(f"Invalid pin number: {value}")
try:
return int(value)
except ValueError:

View File

@ -1,3 +1,4 @@
import logging
from esphome import pins
import esphome.codegen as cg
from esphome.components.esp32 import add_idf_sdkconfig_option, get_esp32_variant
@ -23,6 +24,7 @@ from esphome.const import (
CONF_MISO_PIN,
CONF_MOSI_PIN,
CONF_PAGE_ID,
CONF_POLLING_INTERVAL,
CONF_RESET_PIN,
CONF_SPI,
CONF_STATIC_IP,
@ -30,13 +32,16 @@ from esphome.const import (
CONF_TYPE,
CONF_USE_ADDRESS,
CONF_VALUE,
KEY_CORE,
KEY_FRAMEWORK_VERSION,
)
from esphome.core import CORE, coroutine_with_priority
from esphome.core import CORE, TimePeriodMilliseconds, coroutine_with_priority
import esphome.final_validate as fv
CONFLICTS_WITH = ["wifi"]
DEPENDENCIES = ["esp32"]
AUTO_LOAD = ["network"]
LOGGER = logging.getLogger(__name__)
ethernet_ns = cg.esphome_ns.namespace("ethernet")
PHYRegister = ethernet_ns.struct("PHYRegister")
@ -63,6 +68,7 @@ ETHERNET_TYPES = {
}
SPI_ETHERNET_TYPES = ["W5500"]
SPI_ETHERNET_DEFAULT_POLLING_INTERVAL = TimePeriodMilliseconds(milliseconds=10)
emac_rmii_clock_mode_t = cg.global_ns.enum("emac_rmii_clock_mode_t")
emac_rmii_clock_gpio_t = cg.global_ns.enum("emac_rmii_clock_gpio_t")
@ -100,6 +106,24 @@ EthernetComponent = ethernet_ns.class_("EthernetComponent", cg.Component)
ManualIP = ethernet_ns.struct("ManualIP")
def _is_framework_spi_polling_mode_supported():
# SPI Ethernet without IRQ feature is added in
# esp-idf >= (5.3+ ,5.2.1+, 5.1.4) and arduino-esp32 >= 3.0.0
framework_version = CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]
if CORE.using_esp_idf:
if framework_version >= cv.Version(5, 3, 0):
return True
if cv.Version(5, 3, 0) > framework_version >= cv.Version(5, 2, 1):
return True
if cv.Version(5, 2, 0) > framework_version >= cv.Version(5, 1, 4):
return True
return False
if CORE.using_arduino:
return framework_version >= cv.Version(3, 0, 0)
# fail safe: Unknown framework
return False
def _validate(config):
if CONF_USE_ADDRESS not in config:
if CONF_MANUAL_IP in config:
@ -107,6 +131,27 @@ def _validate(config):
else:
use_address = CORE.name + config[CONF_DOMAIN]
config[CONF_USE_ADDRESS] = use_address
if config[CONF_TYPE] in SPI_ETHERNET_TYPES:
if _is_framework_spi_polling_mode_supported():
if CONF_POLLING_INTERVAL in config and CONF_INTERRUPT_PIN in config:
raise cv.Invalid(
f"Cannot specify more than one of {CONF_INTERRUPT_PIN}, {CONF_POLLING_INTERVAL}"
)
if CONF_POLLING_INTERVAL not in config and CONF_INTERRUPT_PIN not in config:
config[CONF_POLLING_INTERVAL] = SPI_ETHERNET_DEFAULT_POLLING_INTERVAL
else:
if CONF_POLLING_INTERVAL in config:
raise cv.Invalid(
"In this version of the framework "
f"({CORE.target_framework} {CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]}), "
f"'{CONF_POLLING_INTERVAL}' is not supported."
)
if CONF_INTERRUPT_PIN not in config:
raise cv.Invalid(
"In this version of the framework "
f"({CORE.target_framework} {CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]}), "
f"'{CONF_INTERRUPT_PIN}' is a required option for [ethernet]."
)
return config
@ -157,6 +202,11 @@ SPI_SCHEMA = BASE_SCHEMA.extend(
cv.Optional(CONF_CLOCK_SPEED, default="26.67MHz"): cv.All(
cv.frequency, cv.int_range(int(8e6), int(80e6))
),
# Set default value (SPI_ETHERNET_DEFAULT_POLLING_INTERVAL) at _validate()
cv.Optional(CONF_POLLING_INTERVAL): cv.All(
cv.positive_time_period_milliseconds,
cv.Range(min=TimePeriodMilliseconds(milliseconds=1)),
),
}
),
)
@ -234,6 +284,10 @@ async def to_code(config):
cg.add(var.set_cs_pin(config[CONF_CS_PIN]))
if CONF_INTERRUPT_PIN in config:
cg.add(var.set_interrupt_pin(config[CONF_INTERRUPT_PIN]))
else:
cg.add(var.set_polling_interval(config[CONF_POLLING_INTERVAL]))
if _is_framework_spi_polling_mode_supported():
cg.add_define("USE_ETHERNET_SPI_POLLING_SUPPORT")
if CONF_RESET_PIN in config:
cg.add(var.set_reset_pin(config[CONF_RESET_PIN]))
cg.add(var.set_clock_speed(config[CONF_CLOCK_SPEED]))

View File

@ -116,6 +116,9 @@ void EthernetComponent::setup() {
eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(spi_handle);
#endif
w5500_config.int_gpio_num = this->interrupt_pin_;
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
w5500_config.poll_period_ms = this->polling_interval_;
#endif
phy_config.phy_addr = this->phy_addr_spi_;
phy_config.reset_gpio_num = this->reset_pin_;
@ -327,7 +330,14 @@ void EthernetComponent::dump_config() {
ESP_LOGCONFIG(TAG, " MISO Pin: %u", this->miso_pin_);
ESP_LOGCONFIG(TAG, " MOSI Pin: %u", this->mosi_pin_);
ESP_LOGCONFIG(TAG, " CS Pin: %u", this->cs_pin_);
ESP_LOGCONFIG(TAG, " IRQ Pin: %u", this->interrupt_pin_);
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
if (this->polling_interval_ != 0) {
ESP_LOGCONFIG(TAG, " Polling Interval: %lu ms", this->polling_interval_);
} else
#endif
{
ESP_LOGCONFIG(TAG, " IRQ Pin: %d", this->interrupt_pin_);
}
ESP_LOGCONFIG(TAG, " Reset Pin: %d", this->reset_pin_);
ESP_LOGCONFIG(TAG, " Clock Speed: %d MHz", this->clock_speed_ / 1000000);
#else
@ -536,6 +546,9 @@ void EthernetComponent::set_cs_pin(uint8_t cs_pin) { this->cs_pin_ = cs_pin; }
void EthernetComponent::set_interrupt_pin(uint8_t interrupt_pin) { this->interrupt_pin_ = interrupt_pin; }
void EthernetComponent::set_reset_pin(uint8_t reset_pin) { this->reset_pin_ = reset_pin; }
void EthernetComponent::set_clock_speed(int clock_speed) { this->clock_speed_ = clock_speed; }
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
void EthernetComponent::set_polling_interval(uint32_t polling_interval) { this->polling_interval_ = polling_interval; }
#endif
#else
void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; }
void EthernetComponent::set_power_pin(int power_pin) { this->power_pin_ = power_pin; }

View File

@ -67,6 +67,9 @@ class EthernetComponent : public Component {
void set_interrupt_pin(uint8_t interrupt_pin);
void set_reset_pin(uint8_t reset_pin);
void set_clock_speed(int clock_speed);
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
void set_polling_interval(uint32_t polling_interval);
#endif
#else
void set_phy_addr(uint8_t phy_addr);
void set_power_pin(int power_pin);
@ -108,10 +111,13 @@ class EthernetComponent : public Component {
uint8_t miso_pin_;
uint8_t mosi_pin_;
uint8_t cs_pin_;
uint8_t interrupt_pin_;
int interrupt_pin_{-1};
int reset_pin_{-1};
int phy_addr_spi_{-1};
int clock_speed_;
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
uint32_t polling_interval_{0};
#endif
#else
uint8_t phy_addr_{0};
int power_pin_{-1};

View File

@ -1,3 +1,4 @@
from collections.abc import Iterable
import functools
import hashlib
import logging
@ -5,6 +6,8 @@ import os
from pathlib import Path
import re
import freetype
import glyphsets
from packaging import version
import requests
@ -43,6 +46,18 @@ GlyphData = font_ns.struct("GlyphData")
CONF_BPP = "bpp"
CONF_EXTRAS = "extras"
CONF_FONTS = "fonts"
CONF_GLYPHSETS = "glyphsets"
CONF_IGNORE_MISSING_GLYPHS = "ignore_missing_glyphs"
# Cache loaded freetype fonts
class FontCache(dict):
def __missing__(self, key):
res = self[key] = freetype.Face(key)
return res
FONT_CACHE = FontCache()
def glyph_comparator(x, y):
@ -59,36 +74,106 @@ def glyph_comparator(x, y):
return -1
if len(x_) > len(y_):
return 1
raise cv.Invalid(f"Found duplicate glyph {x}")
return 0
def validate_glyphs(value):
if isinstance(value, list):
value = cv.Schema([cv.string])(value)
value = cv.Schema([cv.string])(list(value))
def flatten(lists) -> list:
"""
Given a list of lists, flatten it to a single list of all elements of all lists.
This wraps itertools.chain.from_iterable to make it more readable, and return a list
rather than a single use iterable.
"""
from itertools import chain
value.sort(key=functools.cmp_to_key(glyph_comparator))
return value
return list(chain.from_iterable(lists))
font_map = {}
def check_missing_glyphs(file, codepoints: Iterable, warning: bool = False):
"""
Check that the given font file actually contains the requested glyphs
:param file: A Truetype font file
:param codepoints: A list of codepoints to check
:param warning: If true, log a warning instead of raising an exception
"""
def merge_glyphs(config):
glyphs = []
glyphs.extend(config[CONF_GLYPHS])
font_list = [(EFont(config[CONF_FILE], config[CONF_SIZE], config[CONF_GLYPHS]))]
if extras := config.get(CONF_EXTRAS):
extra_fonts = list(
map(
lambda x: EFont(x[CONF_FILE], config[CONF_SIZE], x[CONF_GLYPHS]), extras
)
font = FONT_CACHE[file]
missing = [chr(x) for x in codepoints if font.get_char_index(x) == 0]
if missing:
# Only list up to 10 missing glyphs
missing.sort(key=functools.cmp_to_key(glyph_comparator))
count = len(missing)
missing = missing[:10]
missing_str = "\n ".join(
f"{x} ({x.encode('unicode_escape')})" for x in missing
)
font_list.extend(extra_fonts)
for extra in extras:
glyphs.extend(extra[CONF_GLYPHS])
validate_glyphs(glyphs)
font_map[config[CONF_ID]] = font_list
if count > 10:
missing_str += f"\n and {count - 10} more."
message = f"Font {Path(file).name} is missing {count} glyph{'s' if count != 1 else ''}:\n {missing_str}"
if warning:
_LOGGER.warning(message)
else:
raise cv.Invalid(message)
def validate_glyphs(config):
"""
Check for duplicate codepoints, then check that all requested codepoints actually
have glyphs defined in the appropriate font file.
"""
# Collect all glyph codepoints and flatten to a list of chars
glyphspoints = flatten(
[x[CONF_GLYPHS] for x in config[CONF_EXTRAS]] + config[CONF_GLYPHS]
)
# Convert a list of strings to a list of chars (one char strings)
glyphspoints = flatten([list(x) for x in glyphspoints])
if len(set(glyphspoints)) != len(glyphspoints):
duplicates = {x for x in glyphspoints if glyphspoints.count(x) > 1}
dup_str = ", ".join(f"{x} ({x.encode('unicode_escape')})" for x in duplicates)
raise cv.Invalid(
f"Found duplicate glyph{'s' if len(duplicates) != 1 else ''}: {dup_str}"
)
# convert to codepoints
glyphspoints = {ord(x) for x in glyphspoints}
fileconf = config[CONF_FILE]
setpoints = set(
flatten([glyphsets.unicodes_per_glyphset(x) for x in config[CONF_GLYPHSETS]])
)
# Make setpoints and glyphspoints disjoint
setpoints.difference_update(glyphspoints)
if fileconf[CONF_TYPE] == TYPE_LOCAL_BITMAP:
# Pillow only allows 256 glyphs per bitmap font. Not sure if that is a Pillow limitation
# or a file format limitation
if any(x >= 256 for x in setpoints.copy().union(glyphspoints)):
raise cv.Invalid("Codepoints in bitmap fonts must be in the range 0-255")
else:
# for TT fonts, check that glyphs are actually present
# Check extras against their own font, exclude from parent font codepoints
for extra in config[CONF_EXTRAS]:
points = {ord(x) for x in flatten(extra[CONF_GLYPHS])}
glyphspoints.difference_update(points)
setpoints.difference_update(points)
check_missing_glyphs(extra[CONF_FILE][CONF_PATH], points)
# A named glyph that can't be provided is an error
check_missing_glyphs(fileconf[CONF_PATH], glyphspoints)
# A missing glyph from a set is a warning.
if not config[CONF_IGNORE_MISSING_GLYPHS]:
check_missing_glyphs(fileconf[CONF_PATH], setpoints, warning=True)
# Populate the default after the above checks so that use of the default doesn't trigger errors
if not config[CONF_GLYPHS] and not config[CONF_GLYPHSETS]:
if fileconf[CONF_TYPE] == TYPE_LOCAL_BITMAP:
config[CONF_GLYPHS] = [DEFAULT_GLYPHS]
else:
# set a default glyphset, intersected with what the font actually offers
font = FONT_CACHE[fileconf[CONF_PATH]]
config[CONF_GLYPHS] = [
chr(x)
for x in glyphsets.unicodes_per_glyphset(DEFAULT_GLYPHSET)
if font.get_char_index(x) != 0
]
return config
@ -98,13 +183,13 @@ def validate_pillow_installed(value):
except ImportError as err:
raise cv.Invalid(
"Please install the pillow python package to use this feature. "
'(pip install "pillow==10.2.0")'
'(pip install "pillow==10.4.0")'
) 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(
"Please update your pillow installation to 10.2.0. "
'(pip install "pillow==10.2.0")'
"Please update your pillow installation to 10.4.0. "
'(pip install "pillow==10.4.0")'
)
return value
@ -120,7 +205,7 @@ def validate_truetype_file(value):
)
if not any(map(value.lower().endswith, FONT_EXTENSIONS)):
raise cv.Invalid(f"Only {FONT_EXTENSIONS} files are supported.")
return cv.file_(value)
return CORE.relative_config_path(cv.file_(value))
TYPE_LOCAL = "local"
@ -139,6 +224,10 @@ LOCAL_BITMAP_SCHEMA = cv.Schema(
}
)
FULLPATH_SCHEMA = cv.maybe_simple_value(
{cv.Required(CONF_PATH): cv.string}, key=CONF_PATH
)
CONF_ITALIC = "italic"
FONT_WEIGHTS = {
"thin": 100,
@ -167,13 +256,13 @@ def _compute_local_font_path(value: dict) -> Path:
return base_dir / key
def get_font_path(value, type) -> Path:
if type == TYPE_GFONTS:
def get_font_path(value, font_type) -> Path:
if font_type == TYPE_GFONTS:
name = f"{value[CONF_FAMILY]}@{value[CONF_WEIGHT]}@{value[CONF_ITALIC]}@v1"
return external_files.compute_local_file_dir(DOMAIN) / f"{name}.ttf"
if type == TYPE_WEB:
if font_type == TYPE_WEB:
return _compute_local_font_path(value) / "font.ttf"
return None
assert False
def download_gfont(value):
@ -203,7 +292,7 @@ def download_gfont(value):
_LOGGER.debug("download_gfont: ttf_url=%s", ttf_url)
external_files.download_content(ttf_url, path)
return value
return FULLPATH_SCHEMA(path)
def download_web_font(value):
@ -212,7 +301,7 @@ def download_web_font(value):
external_files.download_content(url, path)
_LOGGER.debug("download_web_font: path=%s", path)
return value
return FULLPATH_SCHEMA(path)
EXTERNAL_FONT_SCHEMA = cv.Schema(
@ -225,7 +314,6 @@ EXTERNAL_FONT_SCHEMA = cv.Schema(
}
)
GFONTS_SCHEMA = cv.All(
EXTERNAL_FONT_SCHEMA.extend(
{
@ -259,10 +347,10 @@ def validate_file_shorthand(value):
}
if weight is not None:
data[CONF_WEIGHT] = weight[1:]
return FILE_SCHEMA(data)
return font_file_schema(data)
if value.startswith("http://") or value.startswith("https://"):
return FILE_SCHEMA(
return font_file_schema(
{
CONF_TYPE: TYPE_WEB,
CONF_URL: value,
@ -270,14 +358,15 @@ def validate_file_shorthand(value):
)
if value.endswith(".pcf") or value.endswith(".bdf"):
return FILE_SCHEMA(
{
CONF_TYPE: TYPE_LOCAL_BITMAP,
CONF_PATH: value,
}
value = convert_bitmap_to_pillow_font(
CORE.relative_config_path(cv.file_(value))
)
return {
CONF_TYPE: TYPE_LOCAL_BITMAP,
CONF_PATH: value,
}
return FILE_SCHEMA(
return font_file_schema(
{
CONF_TYPE: TYPE_LOCAL,
CONF_PATH: value,
@ -295,31 +384,35 @@ TYPED_FILE_SCHEMA = cv.typed_schema(
)
def _file_schema(value):
def font_file_schema(value):
if isinstance(value, str):
return validate_file_shorthand(value)
return TYPED_FILE_SCHEMA(value)
FILE_SCHEMA = cv.All(_file_schema)
# Default if no glyphs or glyphsets are provided
DEFAULT_GLYPHSET = "GF_Latin_Kernel"
# default for bitmap fonts
DEFAULT_GLYPHS = ' !"%()+=,-.:/?0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz<C2><B0>'
DEFAULT_GLYPHS = (
' !"%()+=,-.:/?0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz°'
)
CONF_RAW_GLYPH_ID = "raw_glyph_id"
FONT_SCHEMA = cv.Schema(
{
cv.Required(CONF_ID): cv.declare_id(Font),
cv.Required(CONF_FILE): FILE_SCHEMA,
cv.Optional(CONF_GLYPHS, default=DEFAULT_GLYPHS): validate_glyphs,
cv.Required(CONF_FILE): font_file_schema,
cv.Optional(CONF_GLYPHS, default=[]): cv.ensure_list(cv.string_strict),
cv.Optional(CONF_GLYPHSETS, default=[]): cv.ensure_list(
cv.one_of(*glyphsets.defined_glyphsets())
),
cv.Optional(CONF_IGNORE_MISSING_GLYPHS, default=False): cv.boolean,
cv.Optional(CONF_SIZE, default=20): cv.int_range(min=1),
cv.Optional(CONF_BPP, default=1): cv.one_of(1, 2, 4, 8),
cv.Optional(CONF_EXTRAS): cv.ensure_list(
cv.Optional(CONF_EXTRAS, default=[]): cv.ensure_list(
cv.Schema(
{
cv.Required(CONF_FILE): FILE_SCHEMA,
cv.Required(CONF_GLYPHS): validate_glyphs,
cv.Required(CONF_FILE): font_file_schema,
cv.Required(CONF_GLYPHS): cv.ensure_list(cv.string_strict),
}
)
),
@ -328,7 +421,7 @@ FONT_SCHEMA = cv.Schema(
},
)
CONFIG_SCHEMA = cv.All(validate_pillow_installed, FONT_SCHEMA, merge_glyphs)
CONFIG_SCHEMA = cv.All(validate_pillow_installed, FONT_SCHEMA, validate_glyphs)
# PIL doesn't provide a consistent interface for both TrueType and bitmap
@ -344,7 +437,7 @@ class TrueTypeFontWrapper:
return offset_x, offset_y
def getmask(self, glyph, **kwargs):
return self.font.getmask(glyph, **kwargs)
return self.font.getmask(str(glyph), **kwargs)
def getmetrics(self, glyphs):
return self.font.getmetrics()
@ -359,7 +452,7 @@ class BitmapFontWrapper:
return 0, 0
def getmask(self, glyph, **kwargs):
return self.font.getmask(glyph, **kwargs)
return self.font.getmask(str(glyph), **kwargs)
def getmetrics(self, glyphs):
max_height = 0
@ -367,28 +460,20 @@ class BitmapFontWrapper:
mask = self.getmask(glyph, mode="1")
_, height = mask.size
max_height = max(max_height, height)
return (max_height, 0)
return max_height, 0
class EFont:
def __init__(self, file, size, glyphs):
self.glyphs = glyphs
def __init__(self, file, size, codepoints):
self.codepoints = codepoints
path = file[CONF_PATH]
self.name = Path(path).name
ftype = file[CONF_TYPE]
if ftype == TYPE_LOCAL_BITMAP:
font = load_bitmap_font(CORE.relative_config_path(file[CONF_PATH]))
elif ftype == TYPE_LOCAL:
path = CORE.relative_config_path(file[CONF_PATH])
font = load_ttf_font(path, size)
elif ftype in (TYPE_GFONTS, TYPE_WEB):
path = get_font_path(file, ftype)
font = load_ttf_font(path, size)
self.font = load_bitmap_font(path)
else:
raise cv.Invalid(f"Could not load font: unknown type: {ftype}")
self.font = font
self.ascent, self.descent = font.getmetrics(glyphs)
def has_glyph(self, glyph):
return glyph in self.glyphs
self.font = load_ttf_font(path, size)
self.ascent, self.descent = self.font.getmetrics(codepoints)
def convert_bitmap_to_pillow_font(filepath):
@ -400,6 +485,7 @@ def convert_bitmap_to_pillow_font(filepath):
copy_file_if_changed(filepath, local_bitmap_font_file)
local_pil_font_file = local_bitmap_font_file.with_suffix(".pil")
with open(local_bitmap_font_file, "rb") as fp:
try:
try:
@ -409,28 +495,22 @@ def convert_bitmap_to_pillow_font(filepath):
p = BdfFontFile.BdfFontFile(fp)
# Convert to pillow-formatted fonts, which have a .pil and .pbm extension.
p.save(local_bitmap_font_file)
p.save(local_pil_font_file)
except (SyntaxError, OSError) as err:
raise core.EsphomeError(
f"Failed to parse as bitmap font: '{filepath}': {err}"
)
local_pil_font_file = os.path.splitext(local_bitmap_font_file)[0] + ".pil"
return cv.file_(local_pil_font_file)
return str(local_pil_font_file)
def load_bitmap_font(filepath):
from PIL import ImageFont
# Convert bpf and pcf files to pillow fonts, first.
pil_font_path = convert_bitmap_to_pillow_font(filepath)
try:
font = ImageFont.load(str(pil_font_path))
font = ImageFont.load(str(filepath))
except Exception as e:
raise core.EsphomeError(
f"Failed to load bitmap font file: {pil_font_path} : {e}"
)
raise core.EsphomeError(f"Failed to load bitmap font file: {filepath}: {e}")
return BitmapFontWrapper(font)
@ -441,7 +521,7 @@ def load_ttf_font(path, size):
try:
font = ImageFont.truetype(str(path), size)
except Exception as e:
raise core.EsphomeError(f"Could not load truetype file {path}: {e}")
raise core.EsphomeError(f"Could not load TrueType file {path}: {e}")
return TrueTypeFontWrapper(font)
@ -456,14 +536,35 @@ class GlyphInfo:
async def to_code(config):
glyph_to_font_map = {}
font_list = font_map[config[CONF_ID]]
glyphs = []
for font in font_list:
glyphs.extend(font.glyphs)
for glyph in font.glyphs:
glyph_to_font_map[glyph] = font
glyphs.sort(key=functools.cmp_to_key(glyph_comparator))
"""
Collect all glyph codepoints, construct a map from a codepoint to a font file.
Codepoints are either explicit (glyphs key in top level or extras) or part of a glyphset.
Codepoints listed in extras use the extra font and override codepoints from glyphsets.
Achieve this by processing the base codepoints first, then the extras
"""
# get the codepoints from glyphsets and flatten to a set of chrs.
point_set: set[str] = {
chr(x)
for x in flatten(
[glyphsets.unicodes_per_glyphset(x) for x in config[CONF_GLYPHSETS]]
)
}
# get the codepoints from the glyphs key, flatten to a list of chrs and combine with the points from glyphsets
point_set.update(flatten(config[CONF_GLYPHS]))
size = config[CONF_SIZE]
# Create the codepoint to font file map
base_font = EFont(config[CONF_FILE], size, point_set)
point_font_map: dict[str, EFont] = {c: base_font for c in point_set}
# process extras, updating the map and extending the codepoint list
for extra in config[CONF_EXTRAS]:
extra_points = flatten(extra[CONF_GLYPHS])
point_set.update(extra_points)
extra_font = EFont(extra[CONF_FILE], size, extra_points)
point_font_map.update({c: extra_font for c in extra_points})
codepoints = list(point_set)
codepoints.sort(key=functools.cmp_to_key(glyph_comparator))
glyph_args = {}
data = []
bpp = config[CONF_BPP]
@ -473,10 +574,11 @@ async def to_code(config):
else:
mode = "L"
scale = 256 // (1 << bpp)
for glyph in glyphs:
font = glyph_to_font_map[glyph].font
mask = font.getmask(glyph, mode=mode)
offset_x, offset_y = font.getoffset(glyph)
# create the data array for all glyphs
for codepoint in codepoints:
font = point_font_map[codepoint]
mask = font.font.getmask(codepoint, mode=mode)
offset_x, offset_y = font.font.getoffset(codepoint)
width, height = mask.size
glyph_data = [0] * ((height * width * bpp + 7) // 8)
pos = 0
@ -487,31 +589,34 @@ async def to_code(config):
if pixel & (1 << (bpp - bit_num - 1)):
glyph_data[pos // 8] |= 0x80 >> (pos % 8)
pos += 1
glyph_args[glyph] = GlyphInfo(len(data), offset_x, offset_y, width, height)
glyph_args[codepoint] = GlyphInfo(len(data), offset_x, offset_y, width, height)
data += glyph_data
rhs = [HexInt(x) for x in data]
prog_arr = cg.progmem_array(config[CONF_RAW_DATA_ID], rhs)
# Create the glyph table that points to data in the above array.
glyph_initializer = []
for glyph in glyphs:
for codepoint in codepoints:
glyph_initializer.append(
cg.StructInitializer(
GlyphData,
(
"a_char",
cg.RawExpression(f"(const uint8_t *){cpp_string_escape(glyph)}"),
cg.RawExpression(
f"(const uint8_t *){cpp_string_escape(codepoint)}"
),
),
(
"data",
cg.RawExpression(
f"{str(prog_arr)} + {str(glyph_args[glyph].data_len)}"
f"{str(prog_arr)} + {str(glyph_args[codepoint].data_len)}"
),
),
("offset_x", glyph_args[glyph].offset_x),
("offset_y", glyph_args[glyph].offset_y),
("width", glyph_args[glyph].width),
("height", glyph_args[glyph].height),
("offset_x", glyph_args[codepoint].offset_x),
("offset_y", glyph_args[codepoint].offset_y),
("width", glyph_args[codepoint].width),
("height", glyph_args[codepoint].height),
)
)
@ -521,7 +626,7 @@ async def to_code(config):
config[CONF_ID],
glyphs,
len(glyph_initializer),
font_list[0].ascent,
font_list[0].ascent + font_list[0].descent,
base_font.ascent,
base_font.ascent + base_font.descent,
bpp,
)

View File

@ -16,7 +16,7 @@ CONFIG_SCHEMA = output.FLOAT_OUTPUT_SCHEMA.extend(
{
cv.GenerateID(): cv.declare_id(GP8403Output),
cv.GenerateID(CONF_GP8403_ID): cv.use_id(GP8403),
cv.Required(CONF_CHANNEL): cv.one_of(0, 1),
cv.Required(CONF_CHANNEL): cv.int_range(min=0, max=1),
}
).extend(cv.COMPONENT_SCHEMA)

View File

@ -1,5 +1,8 @@
import logging
from esphome import pins
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import (
CONF_ID,
CONF_INPUT,
@ -11,9 +14,6 @@ from esphome.const import (
CONF_PULLDOWN,
CONF_PULLUP,
)
from esphome import pins
import esphome.config_validation as cv
import esphome.codegen as cg
from .const import host_ns
@ -28,8 +28,10 @@ def _translate_pin(value):
"This variable only supports pin numbers, not full pin schemas "
"(with inverted and mode)."
)
if isinstance(value, int):
if isinstance(value, int) and not isinstance(value, bool):
return value
if not isinstance(value, str):
raise cv.Invalid(f"Invalid pin number: {value}")
try:
return int(value)
except ValueError:

View File

@ -6,6 +6,7 @@ from esphome.const import (
CONF_ESP8266_DISABLE_SSL_SUPPORT,
CONF_ID,
CONF_METHOD,
CONF_ON_ERROR,
CONF_TIMEOUT,
CONF_TRIGGER_ID,
CONF_URL,
@ -185,6 +186,13 @@ HTTP_REQUEST_ACTION_SCHEMA = cv.Schema(
cv.Optional(CONF_ON_RESPONSE): automation.validate_automation(
{cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(HttpRequestResponseTrigger)}
),
cv.Optional(CONF_ON_ERROR): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(
automation.Trigger.template()
)
}
),
cv.Optional(CONF_MAX_RESPONSE_BUFFER_SIZE, default="1kB"): cv.validate_bytes,
}
)
@ -272,5 +280,9 @@ async def http_request_action_to_code(config, action_id, template_arg, args):
],
conf,
)
for conf in config.get(CONF_ON_ERROR, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID])
cg.add(var.register_error_trigger(trigger))
await automation.build_automation(trigger, [], conf)
return var

View File

@ -22,6 +22,63 @@ struct Header {
const char *value;
};
// Some common HTTP status codes
enum HttpStatus {
HTTP_STATUS_OK = 200,
HTTP_STATUS_NO_CONTENT = 204,
HTTP_STATUS_PARTIAL_CONTENT = 206,
/* 3xx - Redirection */
HTTP_STATUS_MULTIPLE_CHOICES = 300,
HTTP_STATUS_MOVED_PERMANENTLY = 301,
HTTP_STATUS_FOUND = 302,
HTTP_STATUS_SEE_OTHER = 303,
HTTP_STATUS_NOT_MODIFIED = 304,
HTTP_STATUS_TEMPORARY_REDIRECT = 307,
HTTP_STATUS_PERMANENT_REDIRECT = 308,
/* 4XX - CLIENT ERROR */
HTTP_STATUS_BAD_REQUEST = 400,
HTTP_STATUS_UNAUTHORIZED = 401,
HTTP_STATUS_FORBIDDEN = 403,
HTTP_STATUS_NOT_FOUND = 404,
HTTP_STATUS_METHOD_NOT_ALLOWED = 405,
HTTP_STATUS_NOT_ACCEPTABLE = 406,
HTTP_STATUS_LENGTH_REQUIRED = 411,
/* 5xx - Server Error */
HTTP_STATUS_INTERNAL_ERROR = 500
};
/**
* @brief Returns true if the HTTP status code is a redirect.
*
* @param status the HTTP status code to check
* @return true if the status code is a redirect, false otherwise
*/
inline bool is_redirect(int const status) {
switch (status) {
case HTTP_STATUS_MOVED_PERMANENTLY:
case HTTP_STATUS_FOUND:
case HTTP_STATUS_SEE_OTHER:
case HTTP_STATUS_TEMPORARY_REDIRECT:
case HTTP_STATUS_PERMANENT_REDIRECT:
return true;
default:
return false;
}
}
/**
* @brief Checks if the given HTTP status code indicates a successful request.
*
* A successful request is one where the status code is in the range 200-299
*
* @param status the HTTP status code to check
* @return true if the status code indicates a successful request, false otherwise
*/
inline bool is_success(int const status) { return status >= HTTP_STATUS_OK && status < HTTP_STATUS_MULTIPLE_CHOICES; }
class HttpRequestComponent;
class HttpContainer : public Parented<HttpRequestComponent> {
@ -78,8 +135,8 @@ class HttpRequestComponent : public Component {
protected:
const char *useragent_{nullptr};
bool follow_redirects_;
uint16_t redirect_limit_;
bool follow_redirects_{};
uint16_t redirect_limit_{};
uint16_t timeout_{4500};
uint32_t watchdog_timeout_{0};
};
@ -100,6 +157,8 @@ template<typename... Ts> class HttpRequestSendAction : public Action<Ts...> {
void register_response_trigger(HttpRequestResponseTrigger *trigger) { this->response_triggers_.push_back(trigger); }
void register_error_trigger(Trigger<> *trigger) { this->error_triggers_.push_back(trigger); }
void set_max_response_buffer_size(size_t max_response_buffer_size) {
this->max_response_buffer_size_ = max_response_buffer_size;
}
@ -129,6 +188,8 @@ template<typename... Ts> class HttpRequestSendAction : public Action<Ts...> {
auto container = this->parent_->start(this->url_.value(x...), this->method_.value(x...), body, headers);
if (container == nullptr) {
for (auto *trigger : this->error_triggers_)
trigger->trigger(x...);
return;
}
@ -180,7 +241,8 @@ template<typename... Ts> class HttpRequestSendAction : public Action<Ts...> {
std::map<const char *, TemplatableValue<const char *, Ts...>> headers_{};
std::map<const char *, TemplatableValue<std::string, Ts...>> json_{};
std::function<void(Ts..., JsonObject)> json_func_{nullptr};
std::vector<HttpRequestResponseTrigger *> response_triggers_;
std::vector<HttpRequestResponseTrigger *> response_triggers_{};
std::vector<Trigger<> *> error_triggers_{};
size_t max_response_buffer_size_{SIZE_MAX};
};

View File

@ -104,7 +104,9 @@ std::shared_ptr<HttpContainer> HttpRequestArduino::start(std::string url, std::s
static const size_t HEADER_COUNT = sizeof(header_keys) / sizeof(header_keys[0]);
container->client_.collectHeaders(header_keys, HEADER_COUNT);
App.feed_wdt();
container->status_code = container->client_.sendRequest(method.c_str(), body.c_str());
App.feed_wdt();
if (container->status_code < 0) {
ESP_LOGW(TAG, "HTTP Request failed; URL: %s; Error: %s", url.c_str(),
HTTPClient::errorToString(container->status_code).c_str());
@ -113,11 +115,10 @@ std::shared_ptr<HttpContainer> HttpRequestArduino::start(std::string url, std::s
return nullptr;
}
if (container->status_code < 200 || container->status_code >= 300) {
if (!is_success(container->status_code)) {
ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code);
this->status_momentary_error("failed", 1000);
container->end();
return nullptr;
// Still return the container, so it can be used to get the status code and error message
}
int content_length = container->client_.getSize();

View File

@ -6,7 +6,6 @@
#include "esphome/components/watchdog/watchdog.h"
#include "esphome/core/application.h"
#include "esphome/core/defines.h"
#include "esphome/core/log.h"
#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
@ -118,20 +117,17 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin
return nullptr;
}
auto is_ok = [](int code) { return code >= HttpStatus_Ok && code < HttpStatus_MultipleChoices; };
App.feed_wdt();
container->content_length = esp_http_client_fetch_headers(client);
App.feed_wdt();
container->status_code = esp_http_client_get_status_code(client);
if (is_ok(container->status_code)) {
App.feed_wdt();
if (is_success(container->status_code)) {
container->duration_ms = millis() - start;
return container;
}
if (this->follow_redirects_) {
auto is_redirect = [](int code) {
return code == HttpStatus_MovedPermanently || code == HttpStatus_Found || code == HttpStatus_SeeOther ||
code == HttpStatus_TemporaryRedirect || code == HttpStatus_PermanentRedirect;
};
auto num_redirects = this->redirect_limit_;
while (is_redirect(container->status_code) && num_redirects > 0) {
err = esp_http_client_set_redirection(client);
@ -142,9 +138,9 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin
return nullptr;
}
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char url[256]{};
if (esp_http_client_get_url(client, url, sizeof(url) - 1) == ESP_OK) {
ESP_LOGV(TAG, "redirecting to url: %s", url);
char redirect_url[256]{};
if (esp_http_client_get_url(client, redirect_url, sizeof(redirect_url) - 1) == ESP_OK) {
ESP_LOGV(TAG, "redirecting to url: %s", redirect_url);
}
#endif
err = esp_http_client_open(client, 0);
@ -155,9 +151,12 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin
return nullptr;
}
App.feed_wdt();
container->content_length = esp_http_client_fetch_headers(client);
App.feed_wdt();
container->status_code = esp_http_client_get_status_code(client);
if (is_ok(container->status_code)) {
App.feed_wdt();
if (is_success(container->status_code)) {
container->duration_ms = millis() - start;
return container;
}
@ -172,8 +171,7 @@ std::shared_ptr<HttpContainer> HttpRequestIDF::start(std::string url, std::strin
ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code);
this->status_momentary_error("failed", 1000);
esp_http_client_cleanup(client);
return nullptr;
return container;
}
int HttpContainerIDF::read(uint8_t *buf, size_t max_len) {

View File

@ -106,7 +106,7 @@ uint8_t OtaHttpRequestComponent::do_ota_() {
auto container = this->parent_->get(url_with_auth);
if (container == nullptr) {
if (container == nullptr || container->status_code != HTTP_STATUS_OK) {
return OTA_CONNECTION_ERROR;
}

View File

@ -31,7 +31,7 @@ void HttpRequestUpdate::setup() {
void HttpRequestUpdate::update() {
auto container = this->request_parent_->get(this->source_url_);
if (container == nullptr) {
if (container == nullptr || container->status_code != HTTP_STATUS_OK) {
std::string msg = str_sprintf("Failed to fetch manifest from %s", this->source_url_.c_str());
this->status_set_error(msg.c_str());
return;

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

@ -8,7 +8,7 @@ from esphome.components.esp32.const import (
VARIANT_ESP32S3,
)
import esphome.config_validation as cv
from esphome.const import CONF_CHANNEL, CONF_ID, CONF_SAMPLE_RATE
from esphome.const import CONF_BITS_PER_SAMPLE, CONF_CHANNEL, CONF_ID, CONF_SAMPLE_RATE
from esphome.cpp_generator import MockObjClass
import esphome.final_validate as fv
@ -25,13 +25,11 @@ CONF_I2S_LRCLK_PIN = "i2s_lrclk_pin"
CONF_I2S_AUDIO = "i2s_audio"
CONF_I2S_AUDIO_ID = "i2s_audio_id"
CONF_BITS_PER_SAMPLE = "bits_per_sample"
CONF_I2S_MODE = "i2s_mode"
CONF_PRIMARY = "primary"
CONF_SECONDARY = "secondary"
CONF_USE_APLL = "use_apll"
CONF_BITS_PER_SAMPLE = "bits_per_sample"
CONF_BITS_PER_CHANNEL = "bits_per_channel"
CONF_MONO = "mono"
CONF_LEFT = "left"

View File

@ -16,16 +16,18 @@ from .. import (
register_i2s_audio_component,
)
CODEOWNERS = ["@jesserockz"]
AUTO_LOAD = ["audio"]
CODEOWNERS = ["@jesserockz", "@kahrendt"]
DEPENDENCIES = ["i2s_audio"]
I2SAudioSpeaker = i2s_audio_ns.class_(
"I2SAudioSpeaker", cg.Component, speaker.Speaker, I2SAudioOut
)
CONF_BUFFER_DURATION = "buffer_duration"
CONF_DAC_TYPE = "dac_type"
CONF_I2S_COMM_FMT = "i2s_comm_fmt"
CONF_NEVER = "never"
i2s_dac_mode_t = cg.global_ns.enum("i2s_dac_mode_t")
INTERNAL_DAC_OPTIONS = {
@ -72,8 +74,12 @@ BASE_SCHEMA = (
.extend(
{
cv.Optional(
CONF_TIMEOUT, default="100ms"
CONF_BUFFER_DURATION, default="500ms"
): cv.positive_time_period_milliseconds,
cv.Optional(CONF_TIMEOUT, default="500ms"): cv.Any(
cv.positive_time_period_milliseconds,
cv.one_of(CONF_NEVER, lower=True),
),
}
)
.extend(cv.COMPONENT_SCHEMA)
@ -115,4 +121,6 @@ async def to_code(config):
else:
cg.add(var.set_dout_pin(config[CONF_I2S_DOUT_PIN]))
cg.add(var.set_i2s_comm_fmt(config[CONF_I2S_COMM_FMT]))
cg.add(var.set_timeout(config[CONF_TIMEOUT]))
if config[CONF_TIMEOUT] != CONF_NEVER:
cg.add(var.set_timeout(config[CONF_TIMEOUT]))
cg.add(var.set_buffer_duration(config[CONF_BUFFER_DURATION]))

View File

@ -4,6 +4,8 @@
#include <driver/i2s.h>
#include "esphome/components/audio/audio.h"
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
@ -11,186 +13,339 @@
namespace esphome {
namespace i2s_audio {
static const size_t BUFFER_COUNT = 20;
static const uint8_t DMA_BUFFER_DURATION_MS = 15;
static const size_t DMA_BUFFERS_COUNT = 4;
static const size_t TASK_DELAY_MS = DMA_BUFFER_DURATION_MS * DMA_BUFFERS_COUNT / 2;
static const size_t TASK_STACK_SIZE = 4096;
static const ssize_t TASK_PRIORITY = 23;
static const size_t I2S_EVENT_QUEUE_COUNT = DMA_BUFFERS_COUNT + 1;
static const char *const TAG = "i2s_audio.speaker";
enum SpeakerEventGroupBits : uint32_t {
COMMAND_START = (1 << 0), // starts the speaker task
COMMAND_STOP = (1 << 1), // stops the speaker task
COMMAND_STOP_GRACEFULLY = (1 << 2), // Stops the speaker task once all data has been written
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() {
ESP_LOGCONFIG(TAG, "Setting up I2S Audio Speaker...");
this->buffer_queue_ = xQueueCreate(BUFFER_COUNT, sizeof(DataEvent));
if (this->buffer_queue_ == nullptr) {
ESP_LOGE(TAG, "Failed to create buffer queue");
this->mark_failed();
return;
}
this->event_group_ = xEventGroupCreate();
this->event_queue_ = xQueueCreate(BUFFER_COUNT, sizeof(TaskEvent));
if (this->event_queue_ == nullptr) {
ESP_LOGE(TAG, "Failed to create event queue");
if (this->event_group_ == nullptr) {
ESP_LOGE(TAG, "Failed to create event group");
this->mark_failed();
return;
}
}
void I2SAudioSpeaker::start() {
void I2SAudioSpeaker::loop() {
uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
if (event_group_bits & SpeakerEventGroupBits::STATE_STARTING) {
ESP_LOGD(TAG, "Starting Speaker");
this->state_ = speaker::STATE_STARTING;
xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::STATE_STARTING);
}
if (event_group_bits & SpeakerEventGroupBits::STATE_RUNNING) {
ESP_LOGD(TAG, "Started Speaker");
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 (event_group_bits & SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START) {
this->status_set_error("Failed to start speaker task");
xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START);
}
if (event_group_bits & SpeakerEventGroupBits::ERR_INVALID_FORMAT) {
this->status_set_error("Failed to adjust I2S bus to match the incoming audio");
ESP_LOGE(TAG,
"Incompatible audio format: sample rate = %" PRIu32 ", channels = %" PRIu8 ", bits per sample = %" PRIu8,
this->audio_stream_info_.sample_rate, this->audio_stream_info_.channels,
this->audio_stream_info_.bits_per_sample);
}
if (event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS) {
uint32_t error_bits = event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS;
ESP_LOGW(TAG, "Error writing to I2S: %s", esp_err_to_name(err_bit_to_esp_err(error_bits)));
this->status_set_warning();
}
}
void I2SAudioSpeaker::set_volume(float volume) {
this->volume_ = volume;
#ifdef USE_AUDIO_DAC
if (this->audio_dac_ != nullptr) {
if (volume > 0.0) {
this->audio_dac_->set_mute_off();
}
this->audio_dac_->set_volume(volume);
} else
#endif
{
// Fallback to software volume control by using a Q15 fixed point scaling factor
ssize_t decibel_index = remap<ssize_t, float>(volume, 0.0f, 1.0f, 0, Q15_VOLUME_SCALING_FACTORS.size() - 1);
this->q15_volume_factor_ = Q15_VOLUME_SCALING_FACTORS[decibel_index];
}
}
void I2SAudioSpeaker::set_mute_state(bool mute_state) {
this->mute_state_ = mute_state;
#ifdef USE_AUDIO_DAC
if (this->audio_dac_) {
if (mute_state) {
this->audio_dac_->set_mute_on();
} else {
this->audio_dac_->set_mute_off();
}
} else
#endif
{
if (mute_state) {
// Fallback to software volume control and scale by 0
this->q15_volume_factor_ = 0;
} else {
// Revert to previous volume when unmuting
this->set_volume(this->volume_);
}
}
}
size_t I2SAudioSpeaker::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
if (this->is_failed()) {
ESP_LOGE(TAG, "Cannot start audio, speaker failed to setup");
return;
ESP_LOGE(TAG, "Cannot play audio, speaker failed to setup");
return 0;
}
if (this->task_created_) {
ESP_LOGW(TAG, "Called start while task has been already created.");
return;
}
this->state_ = speaker::STATE_STARTING;
}
void I2SAudioSpeaker::start_() {
if (this->task_created_) {
return;
}
if (!this->parent_->try_lock()) {
return; // Waiting for another i2s component to return lock
if (this->state_ != speaker::STATE_RUNNING && this->state_ != speaker::STATE_STARTING) {
this->start();
}
xTaskCreate(I2SAudioSpeaker::player_task, "speaker_task", 8192, (void *) this, 1, &this->player_task_handle_);
this->task_created_ = true;
size_t bytes_written = 0;
if ((this->state_ == speaker::STATE_RUNNING) && (this->audio_ring_buffer_.use_count() == 1)) {
// Only one owner of the ring buffer (the speaker task), so the ring buffer is allocated and no other components are
// attempting to write to it.
// Temporarily share ownership of the ring buffer so it won't be deallocated while writing
std::shared_ptr<RingBuffer> temp_ring_buffer = this->audio_ring_buffer_;
bytes_written = temp_ring_buffer->write_without_replacement((void *) data, length, ticks_to_wait);
}
return bytes_written;
}
template<typename a, typename b> const uint8_t *convert_data_format(const a *from, b *to, size_t &bytes, bool repeat) {
if (sizeof(a) == sizeof(b) && !repeat) {
return reinterpret_cast<const uint8_t *>(from);
bool I2SAudioSpeaker::has_buffered_data() const {
if (this->audio_ring_buffer_ != nullptr) {
return this->audio_ring_buffer_->available() > 0;
}
const b *result = to;
for (size_t i = 0; i < bytes; i += sizeof(a)) {
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);
return false;
}
void I2SAudioSpeaker::player_task(void *params) {
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
TaskEvent event;
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);
}
#endif
esp_err_t err = i2s_driver_install(this_speaker->parent_->get_port(), &config, 0, nullptr);
if (err != ESP_OK) {
event.type = TaskEventType::WARNING;
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 (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);
}
#if SOC_I2S_SUPPORTS_DAC
if (this_speaker->internal_dac_mode_ == I2S_DAC_CHANNEL_DISABLE) {
#endif
i2s_pin_config_t pin_config = this_speaker->parent_->get_pin_config();
pin_config.data_out_num = this_speaker->dout_pin_;
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STARTING);
i2s_set_pin(this_speaker->parent_->get_port(), &pin_config);
#if SOC_I2S_SUPPORTS_DAC
} else {
i2s_set_dac_mode(this_speaker->internal_dac_mode_);
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 = DMA_BUFFERS_COUNT * DMA_BUFFER_DURATION_MS * this_speaker->sample_rate_ / 1000 *
bytes_per_sample * number_of_channels;
const size_t ring_buffer_size =
this_speaker->buffer_duration_ms_ * this_speaker->sample_rate_ / 1000 * bytes_per_sample * number_of_channels;
if (this_speaker->send_esp_err_to_event_group_(this_speaker->allocate_buffers_(dma_buffers_size, ring_buffer_size))) {
// Failed to allocate buffers
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
this_speaker->delete_task_(dma_buffers_size);
}
#endif
DataEvent data_event;
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);
}
event.type = TaskEventType::STARTED;
xQueueSend(this_speaker->event_queue_, &event, portMAX_DELAY);
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
int32_t buffer[BUFFER_SIZE];
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_RUNNING);
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
break;
}
bool stop_gracefully = false;
uint32_t last_data_received_time = millis();
bool tx_dma_underflow = false;
const uint8_t *data = data_event.data;
size_t remaining = data_event.len;
switch (this_speaker->bits_per_sample_) {
case I2S_BITS_PER_SAMPLE_8BIT:
case I2S_BITS_PER_SAMPLE_16BIT: {
data = convert_data_format(reinterpret_cast<const int16_t *>(data), reinterpret_cast<int16_t *>(buffer),
remaining, this_speaker->channel_ == I2S_CHANNEL_FMT_ALL_LEFT);
while (!this_speaker->timeout_.has_value() ||
(millis() - last_data_received_time) <= this_speaker->timeout_.value()) {
event_group_bits = xEventGroupGetBits(this_speaker->event_group_);
if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP) {
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;
if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY) {
stop_gracefully = true;
}
}
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");
i2s_event_t i2s_event;
while (xQueueReceive(this_speaker->i2s_event_queue_, &i2s_event, 0)) {
if (i2s_event.type == I2S_EVENT_TX_Q_OVF) {
tx_dma_underflow = true;
}
}
size_t bytes_to_read = dma_buffers_size;
size_t bytes_read = this_speaker->audio_ring_buffer_->read((void *) this_speaker->data_buffer_, bytes_to_read,
pdMS_TO_TICKS(TASK_DELAY_MS));
if (bytes_read > 0) {
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);
}
tx_dma_underflow = false;
last_data_received_time = millis();
} else {
// No data received
if (stop_gracefully && tx_dma_underflow) {
break;
}
continue;
}
data += bytes_written;
remaining -= bytes_written;
}
} else {
// Couldn't configure the I2S port to be compatible with the incoming audio
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_INVALID_FORMAT);
}
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());
xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STOPPING);
i2s_driver_uninstall(this_speaker->parent_->get_port());
event.type = TaskEventType::STOPPED;
if (xQueueSend(this_speaker->event_queue_, &event, 10 / portTICK_PERIOD_MS) != pdTRUE) {
ESP_LOGW(TAG, "Failed to send STOPPED event");
this_speaker->parent_->unlock();
this_speaker->delete_task_(dma_buffers_size);
}
void I2SAudioSpeaker::start() {
if (!this->is_ready() || 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_);
}
while (true) {
delay(10);
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 +358,163 @@ void I2SAudioSpeaker::stop_(bool wait_on_empty) {
return;
if (this->state_ == speaker::STATE_STOPPED)
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) {
xQueueSend(this->buffer_queue_, &data, portMAX_DELAY);
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY);
} else {
xQueueSendToFront(this->buffer_queue_, &data, portMAX_DELAY);
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP);
}
}
void I2SAudioSpeaker::watch_() {
TaskEvent event;
if (xQueueReceive(this->event_queue_, &event, 0) == pdTRUE) {
switch (event.type) {
case TaskEventType::STARTING:
ESP_LOGD(TAG, "Starting I2S Audio Speaker");
break;
case TaskEventType::STARTED:
ESP_LOGD(TAG, "Started I2S Audio Speaker");
this->state_ = speaker::STATE_RUNNING;
this->status_clear_warning();
break;
case TaskEventType::STOPPING:
ESP_LOGD(TAG, "Stopping I2S Audio Speaker");
break;
case TaskEventType::STOPPED:
this->state_ = speaker::STATE_STOPPED;
vTaskDelete(this->player_task_handle_);
this->task_created_ = false;
this->player_task_handle_ = nullptr;
this->parent_->unlock();
xQueueReset(this->buffer_queue_);
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;
}
bool I2SAudioSpeaker::send_esp_err_to_event_group_(esp_err_t err) {
switch (err) {
case ESP_OK:
return false;
case ESP_ERR_INVALID_STATE:
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_STATE);
return true;
case ESP_ERR_INVALID_ARG:
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_ARG);
return true;
case ESP_ERR_INVALID_SIZE:
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE);
return true;
case ESP_ERR_NO_MEM:
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
return true;
default:
xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_FAIL);
return true;
}
}
void I2SAudioSpeaker::loop() {
switch (this->state_) {
case speaker::STATE_STARTING:
this->start_();
[[fallthrough]];
case speaker::STATE_RUNNING:
case speaker::STATE_STOPPING:
this->watch_();
break;
case speaker::STATE_STOPPED:
break;
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_.use_count() == 0) {
// Allocate ring buffer. Uses a shared_ptr to ensure it isn't improperly deallocated.
this->audio_ring_buffer_ = RingBuffer::create(ring_buffer_size);
}
if (this->audio_ring_buffer_ == nullptr) {
return ESP_ERR_NO_MEM;
}
return ESP_OK;
}
size_t I2SAudioSpeaker::play(const uint8_t *data, size_t length) {
if (this->is_failed()) {
ESP_LOGE(TAG, "Cannot play audio, speaker failed to setup");
return 0;
esp_err_t I2SAudioSpeaker::start_i2s_driver_() {
if (!this->parent_->try_lock()) {
return ESP_ERR_INVALID_STATE;
}
if (this->state_ != speaker::STATE_RUNNING && this->state_ != speaker::STATE_STARTING) {
this->start();
int dma_buffer_length = DMA_BUFFER_DURATION_MS * this->sample_rate_ / 1000;
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_length,
.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);
}
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;
#endif
esp_err_t err =
i2s_driver_install(this->parent_->get_port(), &config, I2S_EVENT_QUEUE_COUNT, &this->i2s_event_queue_);
if (err != ESP_OK) {
// Failed to install the driver, so unlock the I2S port
this->parent_->unlock();
return err;
}
return index;
#if SOC_I2S_SUPPORTS_DAC
if (this->internal_dac_mode_ == I2S_DAC_CHANNEL_DISABLE) {
#endif
i2s_pin_config_t pin_config = this->parent_->get_pin_config();
pin_config.data_out_num = this->dout_pin_;
err = i2s_set_pin(this->parent_->get_port(), &pin_config);
#if SOC_I2S_SUPPORTS_DAC
} else {
i2s_set_dac_mode(this->internal_dac_mode_);
}
#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();
}
return err;
}
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) {
this->audio_ring_buffer_.reset(); // Releases onwership of the shared_ptr
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 esphome

View File

@ -5,45 +5,30 @@
#include "../i2s_audio.h"
#include <driver/i2s.h>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <freertos/event_groups.h>
#include <freertos/queue.h>
#include <freertos/FreeRTOS.h>
#include "esphome/components/audio/audio.h"
#include "esphome/components/speaker/speaker.h"
#include "esphome/core/component.h"
#include "esphome/core/gpio.h"
#include "esphome/core/helpers.h"
#include "esphome/core/ring_buffer.h"
namespace esphome {
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 {
public:
float get_setup_priority() const override { return esphome::setup_priority::LATE; }
float get_setup_priority() const override { return esphome::setup_priority::PROCESSOR; }
void setup() override;
void loop() override;
void set_buffer_duration(uint32_t buffer_duration_ms) { this->buffer_duration_ms_ = buffer_duration_ms; }
void set_timeout(uint32_t ms) { this->timeout_ = ms; }
void set_dout_pin(uint8_t pin) { this->dout_pin_ = pin; }
#if SOC_I2S_SUPPORTS_DAC
@ -55,25 +40,99 @@ class I2SAudioSpeaker : public I2SAudioOut, public speaker::Speaker, public Comp
void stop() 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;
/// @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:
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 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};
QueueHandle_t buffer_queue_;
QueueHandle_t event_queue_;
/// @brief Allocates the data buffer and ring buffer
/// @param data_buffer_size Number of bytes to allocate for the data buffer.
/// @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};
QueueHandle_t i2s_event_queue_;
uint8_t *data_buffer_;
std::shared_ptr<RingBuffer> audio_ring_buffer_;
uint32_t buffer_duration_ms_;
optional<uint32_t> timeout_;
uint8_t dout_pin_;
uint32_t timeout_{0};
uint8_t dout_pin_{0};
bool task_created_{false};
int16_t q15_volume_factor_{INT16_MAX};
#if SOC_I2S_SUPPORTS_DAC
i2s_dac_mode_t internal_dac_mode_{I2S_DAC_CHANNEL_DISABLE};
#endif

View File

@ -10,6 +10,7 @@ from esphome.const import (
CONF_DIMENSIONS,
CONF_HEIGHT,
CONF_ID,
CONF_INIT_SEQUENCE,
CONF_INVERT_COLORS,
CONF_LAMBDA,
CONF_MIRROR_X,
@ -89,7 +90,6 @@ CONF_LED_PIN = "led_pin"
CONF_COLOR_PALETTE_IMAGES = "color_palette_images"
CONF_INVERT_DISPLAY = "invert_display"
CONF_PIXEL_MODE = "pixel_mode"
CONF_INIT_SEQUENCE = "init_sequence"
def cmd(c, *args):
@ -196,6 +196,10 @@ CONFIG_SCHEMA = cv.All(
_validate,
)
FINAL_VALIDATE_SCHEMA = spi.final_validate_device_schema(
"ili9xxx", require_miso=False, require_mosi=True
)
async def to_code(config):
rhs = MODELS[config[CONF_MODEL]].new()

View File

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

View File

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

View File

@ -3,12 +3,7 @@
#include "esphome/components/display/display.h"
#ifdef USE_LVGL
// required for clang-tidy
#ifndef LV_CONF_H
#define LV_CONF_SKIP 1 // NOLINT
#endif // LV_CONF_H
#include <lvgl.h>
#include "esphome/components/lvgl/lvgl_proxy.h"
#endif // USE_LVGL
namespace esphome {
@ -22,24 +17,6 @@ enum ImageType {
IMAGE_TYPE_RGBA = 4,
};
inline int image_type_to_bpp(ImageType type) {
switch (type) {
case IMAGE_TYPE_BINARY:
return 1;
case IMAGE_TYPE_GRAYSCALE:
return 8;
case IMAGE_TYPE_RGB565:
return 16;
case IMAGE_TYPE_RGB24:
return 24;
case IMAGE_TYPE_RGBA:
return 32;
}
return 0;
}
inline int image_type_to_width_stride(int width, ImageType type) { return (width * image_type_to_bpp(type) + 7u) / 8u; }
class Image : public display::BaseImage {
public:
Image(const uint8_t *data_start, int width, int height, ImageType type);
@ -49,6 +26,25 @@ class Image : public display::BaseImage {
const uint8_t *get_data_start() const { return this->data_start_; }
ImageType get_type() const;
int get_bpp() const {
switch (this->type_) {
case IMAGE_TYPE_BINARY:
return 1;
case IMAGE_TYPE_GRAYSCALE:
return 8;
case IMAGE_TYPE_RGB565:
return this->transparent_ ? 24 : 16;
case IMAGE_TYPE_RGB24:
return 24;
case IMAGE_TYPE_RGBA:
return 32;
}
return 0;
}
/// Return the stride of the image in bytes, that is, the distance in bytes
/// between two consecutive rows of pixels.
uint32_t get_width_stride() const { return (this->width_ * this->get_bpp() + 7u) / 8u; }
void draw(int x, int y, display::Display *display, Color color_on, Color color_off) override;
void set_transparency(bool transparent) { transparent_ = transparent; }

View File

@ -7,8 +7,14 @@
extern "C" {
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) || defined(USE_ESP32_VARIANT_ESP32H2) || \
defined(USE_ESP32_VARIANT_ESP32C2)
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
#include "driver/temp_sensor.h"
#else
#include "driver/temperature_sensor.h"
#endif // ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
#endif // USE_ESP32_VARIANT
#endif // USE_ESP32
#ifdef USE_RP2040
@ -24,6 +30,13 @@ namespace esphome {
namespace internal_temperature {
static const char *const TAG = "internal_temperature";
#ifdef USE_ESP32
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)) && \
(defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32S2) || \
defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32C2))
static temperature_sensor_handle_t tsensNew = NULL;
#endif // ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) && USE_ESP32_VARIANT
#endif // USE_ESP32
void InternalTemperatureSensor::update() {
float temperature = NAN;
@ -34,7 +47,10 @@ void InternalTemperatureSensor::update() {
ESP_LOGV(TAG, "Raw temperature value: %d", raw);
temperature = (raw - 32) / 1.8f;
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) || defined(USE_ESP32_VARIANT_ESP32H2) || \
defined(USE_ESP32_VARIANT_ESP32C2)
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
temp_sensor_config_t tsens = TSENS_CONFIG_DEFAULT();
temp_sensor_set_config(tsens);
temp_sensor_start();
@ -45,6 +61,13 @@ void InternalTemperatureSensor::update() {
esp_err_t result = temp_sensor_read_celsius(&temperature);
temp_sensor_stop();
success = (result == ESP_OK);
#else
esp_err_t result = temperature_sensor_get_celsius(tsensNew, &temperature);
success = (result == ESP_OK);
if (!success) {
ESP_LOGE(TAG, "Failed to get temperature: %d", result);
}
#endif // ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
#endif // USE_ESP32_VARIANT
#endif // USE_ESP32
#ifdef USE_RP2040
@ -73,6 +96,32 @@ void InternalTemperatureSensor::update() {
}
}
void InternalTemperatureSensor::setup() {
#ifdef USE_ESP32
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)) && \
(defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32S2) || \
defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32C2))
ESP_LOGCONFIG(TAG, "Setting up temperature sensor...");
temperature_sensor_config_t tsens_config = TEMPERATURE_SENSOR_CONFIG_DEFAULT(-10, 80);
esp_err_t result = temperature_sensor_install(&tsens_config, &tsensNew);
if (result != ESP_OK) {
ESP_LOGE(TAG, "Failed to install temperature sensor: %d", result);
this->mark_failed();
return;
}
result = temperature_sensor_enable(tsensNew);
if (result != ESP_OK) {
ESP_LOGE(TAG, "Failed to enable temperature sensor: %d", result);
this->mark_failed();
return;
}
#endif // ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) && USE_ESP32_VARIANT
#endif // USE_ESP32
}
void InternalTemperatureSensor::dump_config() { LOG_SENSOR("", "Internal Temperature Sensor", this); }
} // namespace internal_temperature

View File

@ -8,6 +8,7 @@ namespace internal_temperature {
class InternalTemperatureSensor : public sensor::Sensor, public PollingComponent {
public:
void setup() override;
void dump_config() override;
void update() override;

View File

@ -180,7 +180,7 @@ void LD2420Component::apply_config_action() {
}
void LD2420Component::factory_reset_action() {
ESP_LOGCONFIG(TAG, "Setiing factory defaults...");
ESP_LOGCONFIG(TAG, "Setting factory defaults...");
if (this->set_config_mode(true) == LD2420_ERROR_TIMEOUT) {
ESP_LOGE(TAG, "LD2420 module has failed to respond, check baud rate and serial connections.");
this->mark_failed();

View File

@ -1,8 +1,8 @@
import logging
from esphome import pins
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins
from esphome.const import (
CONF_ANALOG,
CONF_ID,
@ -103,8 +103,10 @@ def _translate_pin(value):
"This variable only supports pin numbers, not full pin schemas "
"(with inverted and mode)."
)
if isinstance(value, int):
if isinstance(value, int) and not isinstance(value, bool):
return value
if not isinstance(value, str):
raise cv.Invalid(f"Invalid pin number: {value}")
try:
return int(value)
except ValueError:

View File

@ -3,27 +3,39 @@ import esphome.codegen as cg
from esphome.components import mqtt, power_supply, web_server
import esphome.config_validation as cv
from esphome.const import (
CONF_BLUE,
CONF_BRIGHTNESS,
CONF_COLD_WHITE,
CONF_COLD_WHITE_COLOR_TEMPERATURE,
CONF_COLOR_BRIGHTNESS,
CONF_COLOR_CORRECT,
CONF_COLOR_MODE,
CONF_COLOR_TEMPERATURE,
CONF_DEFAULT_TRANSITION_LENGTH,
CONF_EFFECTS,
CONF_FLASH_TRANSITION_LENGTH,
CONF_GAMMA_CORRECT,
CONF_GREEN,
CONF_ID,
CONF_INITIAL_STATE,
CONF_MQTT_ID,
CONF_ON_STATE,
CONF_ON_TURN_OFF,
CONF_ON_TURN_ON,
CONF_POWER_SUPPLY,
CONF_RED,
CONF_RESTORE_MODE,
CONF_STATE,
CONF_TRIGGER_ID,
CONF_WARM_WHITE,
CONF_WARM_WHITE_COLOR_TEMPERATURE,
CONF_WEB_SERVER,
CONF_WHITE,
)
from esphome.core import coroutine_with_priority
from esphome.cpp_helpers import setup_entity
from .automation import light_control_to_code # noqa
from .automation import LIGHT_STATE_SCHEMA
from .effects import (
ADDRESSABLE_EFFECTS,
BINARY_EFFECTS,
@ -35,8 +47,10 @@ from .effects import (
from .types import ( # noqa
AddressableLight,
AddressableLightState,
ColorMode,
LightOutput,
LightState,
LightStateRTCState,
LightStateTrigger,
LightTurnOffTrigger,
LightTurnOnTrigger,
@ -85,6 +99,7 @@ LIGHT_SCHEMA = (
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]))
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 (
default_transition_length := config.get(CONF_DEFAULT_TRANSITION_LENGTH)
) is not None:

View File

@ -1,41 +1,42 @@
from esphome import automation
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import automation
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_WHITE,
CONF_COLOR_TEMPERATURE,
CONF_BRIGHTNESS,
CONF_BRIGHTNESS_LIMITS,
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_TO,
CONF_BRIGHTNESS_LIMITS,
CONF_LIMIT_MODE,
CONF_MIN_BRIGHTNESS,
CONF_MAX_BRIGHTNESS,
CONF_RED,
CONF_STATE,
CONF_TRANSITION_LENGTH,
CONF_WARM_WHITE,
CONF_WHITE,
)
from .types import (
ColorMode,
COLOR_MODES,
LIMIT_MODES,
DimRelativeAction,
ToggleAction,
LightState,
LightControlAction,
AddressableLightState,
AddressableSet,
LightIsOnCondition,
ColorMode,
DimRelativeAction,
LightControlAction,
LightIsOffCondition,
LightIsOnCondition,
LightState,
ToggleAction,
)
@ -62,18 +63,10 @@ async def light_toggle_to_code(config, action_id, template_arg, args):
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_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_COLOR_BRIGHTNESS): 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),
}
)
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(
{
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.config_validation as cv
from esphome import automation
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_BLUE,
CONF_BRIGHTNESS,
CONF_COLD_WHITE,
CONF_COLOR_BRIGHTNESS,
CONF_COLOR_MODE,
CONF_COLOR_TEMPERATURE,
CONF_COLORS,
CONF_DURATION,
CONF_GREEN,
CONF_INTENSITY,
CONF_SPEED,
CONF_WIDTH,
CONF_NUM_LEDS,
CONF_RANDOM,
CONF_SEQUENCE,
CONF_LAMBDA,
CONF_MAX_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 .types import (
ColorMode,
COLOR_MODES,
AddressableColorWipeEffect,
AddressableColorWipeEffectColor,
AddressableFireworksEffect,
AddressableFlickerEffect,
AddressableLambdaLightEffect,
AddressableLightRef,
AddressableRainbowLightEffect,
AddressableRandomTwinkleEffect,
AddressableScanEffect,
AddressableTwinkleEffect,
AutomationLightEffect,
Color,
ColorMode,
FlickerLightEffect,
LambdaLightEffect,
LightColorValues,
PulseLightEffect,
RandomLightEffect,
StrobeLightEffect,
StrobeLightEffectColor,
LightColorValues,
AddressableLightRef,
AddressableLambdaLightEffect,
FlickerLightEffect,
AddressableRainbowLightEffect,
AddressableColorWipeEffect,
AddressableColorWipeEffectColor,
AddressableScanEffect,
AddressableTwinkleEffect,
AddressableRandomTwinkleEffect,
AddressableFireworksEffect,
AddressableFlickerEffect,
AutomationLightEffect,
Color,
)
CONF_ADD_LED_INTERVAL = "add_led_interval"

View File

@ -1,6 +1,7 @@
#include "esphome/core/log.h"
#include "light_state.h"
#include "light_output.h"
#include "light_state.h"
#include "transformers.h"
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::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() {
ESP_LOGCONFIG(TAG, "Setting up light '%s'...", this->get_name().c_str());
@ -48,6 +34,9 @@ void LightState::setup() {
auto call = this->make_call();
LightStateRTCState recovered{};
if (this->initial_state_.has_value()) {
recovered = *this->initial_state_;
}
switch (this->restore_mode_) {
case LIGHT_RESTORE_DEFAULT_OFF:
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_; }
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_initial_state(const LightStateRTCState &initial_state) { this->initial_state_ = initial_state; }
bool LightState::supports_effects() { return !this->effects_.empty(); }
const std::vector<LightEffect *> &LightState::get_effects() const { return this->effects_; }
void LightState::add_effects(const std::vector<LightEffect *> &effects) {

View File

@ -28,6 +28,35 @@ enum LightRestoreMode {
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
* hardware output layer.
*/
@ -116,6 +145,9 @@ class LightState : public EntityBase, public Component {
/// Set the restore mode of this light
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.
bool supports_effects();
@ -212,6 +244,8 @@ class LightState : public EntityBase, public Component {
float gamma_correct_{};
/// Restore mode of the light.
LightRestoreMode restore_mode_;
/// Initial state of the light.
optional<LightStateRTCState> initial_state_{};
/// List of effects for this light.
std::vector<LightEffect *> effects_;

View File

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

View File

@ -10,8 +10,12 @@
#ifdef USE_LOGGER_USB_SERIAL_JTAG
#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_usb_serial_jtag.h>
#else
#include <driver/usb_serial_jtag_vfs.h>
#endif
#endif
#include "freertos/FreeRTOS.h"
@ -36,10 +40,17 @@ static const char *const TAG = "logger";
static void init_usb_serial_jtag_() {
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
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'
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
fcntl(fileno(stdout), F_SETFL, 0);
@ -57,7 +68,11 @@ static void init_usb_serial_jtag_() {
}
// 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();
#else
usb_serial_jtag_vfs_use_driver();
#endif
}
#endif

View File

@ -7,6 +7,7 @@ import esphome.config_validation as cv
from esphome.const import (
CONF_AUTO_CLEAR_ENABLED,
CONF_BUFFER_SIZE,
CONF_GROUP,
CONF_ID,
CONF_LAMBDA,
CONF_ON_IDLE,
@ -22,12 +23,18 @@ from esphome.helpers import write_file_if_changed
from . import defines as df, helpers, lv_validation as lvalid
from .automation import disp_update, focused_widgets, update_to_code
from .defines import CONF_WIDGETS, add_define
from .encoders import ENCODERS_CONFIG, encoders_to_code, initial_focus_to_code
from .defines import add_define
from .encoders import (
ENCODERS_CONFIG,
encoders_to_code,
get_default_group,
initial_focus_to_code,
)
from .gradient import GRADIENT_SCHEMA, gradients_to_code
from .hello_world import get_hello_world
from .keypads import KEYPADS_CONFIG, keypads_to_code
from .lv_validation import lv_bool, lv_images_used
from .lvcode import LvContext, LvglComponent
from .lvcode import LvContext, LvglComponent, lvgl_static
from .schemas import (
DISP_BG_SCHEMA,
FLEX_OBJ_SCHEMA,
@ -48,12 +55,13 @@ from .types import (
FontEngine,
IdleTrigger,
ObjUpdateAction,
PauseTrigger,
lv_font_t,
lv_group_t,
lv_style_t,
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.arc import arc_spec
from .widgets.button import button_spec
@ -70,6 +78,7 @@ from .widgets.meter import meter_spec
from .widgets.msgbox import MSGBOX_SCHEMA, msgboxes_to_code
from .widgets.obj import obj_spec
from .widgets.page import add_pages, generate_page_triggers, page_spec
from .widgets.qrcode import qr_code_spec
from .widgets.roller import roller_spec
from .widgets.slider import slider_spec
from .widgets.spinbox import spinbox_spec
@ -108,6 +117,7 @@ for w_type in (
spinbox_spec,
keyboard_spec,
tileview_spec,
qr_code_spec,
):
WIDGET_TYPES[w_type.name] = w_type
@ -149,43 +159,80 @@ def generate_lv_conf_h():
return LV_CONF_H_FORMAT.format("\n".join(definitions))
def final_validation(config):
if pages := config.get(CONF_PAGES):
if all(p[df.CONF_SKIP] for p in pages):
raise cv.Invalid("At least one page must not be skipped")
def multi_conf_validate(configs: list[dict]):
displays = [config[df.CONF_DISPLAYS] for config in configs]
# flatten the display list
display_list = [disp for disps in displays for disp in disps]
if len(display_list) != len(set(display_list)):
raise cv.Invalid("A display ID may be used in only one LVGL instance")
for config in configs:
for item in (df.CONF_ENCODERS, df.CONF_KEYPADS):
for enc in config.get(item, ()):
if CONF_GROUP not in enc:
raise cv.Invalid(
f"'{item}' must have an explicit group set when using multiple LVGL instances"
)
base_config = configs[0]
for config in configs[1:]:
for item in (
df.CONF_LOG_LEVEL,
df.CONF_COLOR_DEPTH,
df.CONF_BYTE_ORDER,
df.CONF_TRANSPARENCY_KEY,
):
if base_config[item] != config[item]:
raise cv.Invalid(
f"Config item '{item}' must be the same for all LVGL instances"
)
def final_validation(configs):
if len(configs) != 1:
multi_conf_validate(configs)
global_config = full_config.get()
for display_id in config[df.CONF_DISPLAYS]:
path = global_config.get_path_for_id(display_id)[:-1]
display = global_config.get_config_for_path(path)
if CONF_LAMBDA in display:
raise cv.Invalid("Using lambda: in display config not compatible with LVGL")
if display[CONF_AUTO_CLEAR_ENABLED]:
raise cv.Invalid(
"Using auto_clear_enabled: true in display config not compatible with LVGL"
)
buffer_frac = config[CONF_BUFFER_SIZE]
if CORE.is_esp32 and buffer_frac > 0.5 and "psram" not in global_config:
LOGGER.warning("buffer_size: may need to be reduced without PSRAM")
for image_id in lv_images_used:
path = global_config.get_path_for_id(image_id)[:-1]
image_conf = global_config.get_config_for_path(path)
if image_conf[CONF_TYPE] in ("RGBA", "RGB24"):
raise cv.Invalid(
"Using RGBA or RGB24 in image config not compatible with LVGL", path
)
for w in focused_widgets:
path = global_config.get_path_for_id(w)
widget_conf = global_config.get_config_for_path(path[:-1])
if df.CONF_ADJUSTABLE in widget_conf and not widget_conf[df.CONF_ADJUSTABLE]:
raise cv.Invalid(
"A non adjustable arc may not be focused",
path,
)
for config in configs:
if pages := config.get(CONF_PAGES):
if all(p[df.CONF_SKIP] for p in pages):
raise cv.Invalid("At least one page must not be skipped")
for display_id in config[df.CONF_DISPLAYS]:
path = global_config.get_path_for_id(display_id)[:-1]
display = global_config.get_config_for_path(path)
if CONF_LAMBDA in display:
raise cv.Invalid(
"Using lambda: in display config not compatible with LVGL"
)
if display[CONF_AUTO_CLEAR_ENABLED]:
raise cv.Invalid(
"Using auto_clear_enabled: true in display config not compatible with LVGL"
)
buffer_frac = config[CONF_BUFFER_SIZE]
if CORE.is_esp32 and buffer_frac > 0.5 and "psram" not in global_config:
LOGGER.warning("buffer_size: may need to be reduced without PSRAM")
for image_id in lv_images_used:
path = global_config.get_path_for_id(image_id)[:-1]
image_conf = global_config.get_config_for_path(path)
if image_conf[CONF_TYPE] in ("RGBA", "RGB24"):
raise cv.Invalid(
"Using RGBA or RGB24 in image config not compatible with LVGL", path
)
for w in focused_widgets:
path = global_config.get_path_for_id(w)
widget_conf = global_config.get_config_for_path(path[:-1])
if (
df.CONF_ADJUSTABLE in widget_conf
and not widget_conf[df.CONF_ADJUSTABLE]
):
raise cv.Invalid(
"A non adjustable arc may not be focused",
path,
)
async def to_code(config):
async def to_code(configs):
config_0 = configs[0]
# Global configuration
cg.add_library("lvgl/lvgl", "8.4.0")
CORE.add_define("USE_LVGL")
cg.add_define("USE_LVGL")
# suppress default enabling of extra widgets
add_define("_LV_KCONFIG_PRESENT")
# Always enable - lots of things use it.
@ -199,45 +246,34 @@ async def to_code(config):
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_LOG_LEVEL", f"LV_LOG_LEVEL_{config[df.CONF_LOG_LEVEL]}")
add_define("LV_COLOR_DEPTH", config[df.CONF_COLOR_DEPTH])
add_define(
"LV_LOG_LEVEL",
f"LV_LOG_LEVEL_{df.LV_LOG_LEVELS[config_0[df.CONF_LOG_LEVEL]]}",
)
cg.add_define(
"LVGL_LOG_LEVEL",
cg.RawExpression(f"ESPHOME_LOG_LEVEL_{config_0[df.CONF_LOG_LEVEL]}"),
)
add_define("LV_COLOR_DEPTH", config_0[df.CONF_COLOR_DEPTH])
for font in helpers.lv_fonts_used:
add_define(f"LV_FONT_{font.upper()}")
if config[df.CONF_COLOR_DEPTH] == 16:
if config_0[df.CONF_COLOR_DEPTH] == 16:
add_define(
"LV_COLOR_16_SWAP",
"1" if config[df.CONF_BYTE_ORDER] == "big_endian" else "0",
"1" if config_0[df.CONF_BYTE_ORDER] == "big_endian" else "0",
)
add_define(
"LV_COLOR_CHROMA_KEY",
await lvalid.lv_color.process(config[df.CONF_TRANSPARENCY_KEY]),
await lvalid.lv_color.process(config_0[df.CONF_TRANSPARENCY_KEY]),
)
CORE.add_build_flag("-Isrc")
cg.add_build_flag("-Isrc")
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]
if frac >= 0.75:
frac = 1
elif frac >= 0.375:
frac = 2
elif frac > 0.19:
frac = 4
else:
frac = 8
cg.add(lv_component.set_buffer_frac(int(frac)))
cg.add(lv_component.set_full_refresh(config[df.CONF_FULL_REFRESH]))
for font in helpers.esphome_fonts_used:
await cg.get_variable(font)
cg.new_Pvariable(ID(f"{font}_engine", True, type=FontEngine), MockObj(font))
default_font = config[df.CONF_DEFAULT_FONT]
default_font = config_0[df.CONF_DEFAULT_FONT]
if not lvalid.is_lv_font(default_font):
add_define(
"LV_FONT_CUSTOM_DECLARE", f"LV_FONT_DECLARE(*{df.DEFAULT_ESPHOME_FONT})"
@ -253,58 +289,103 @@ async def to_code(config):
add_define("LV_FONT_DEFAULT", df.DEFAULT_ESPHOME_FONT)
else:
add_define("LV_FONT_DEFAULT", await lvalid.lv_font.process(default_font))
cg.add(lvgl_static.esphome_lvgl_init())
default_group = get_default_group(config_0)
async with LvContext(lv_component):
await touchscreens_to_code(lv_component, config)
await encoders_to_code(lv_component, config)
await theme_to_code(config)
await styles_to_code(config)
await gradients_to_code(config)
await set_obj_properties(lv_scr_act, config)
await add_widgets(lv_scr_act, config)
await add_pages(lv_component, config)
await add_top_layer(config)
await msgboxes_to_code(config)
await disp_update(f"{lv_component}->get_disp()", config)
# At this point only the setup code should be generated
assert LvContext.added_lambda_count == 1
Widget.set_completed()
async with LvContext(lv_component):
await generate_triggers(lv_component)
await generate_page_triggers(lv_component, config)
for conf in config.get(CONF_ON_IDLE, ()):
templ = await cg.templatable(conf[CONF_TIMEOUT], [], cg.uint32)
idle_trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], lv_component, templ)
await build_automation(idle_trigger, [], conf)
await initial_focus_to_code(config)
for config in configs:
frac = config[CONF_BUFFER_SIZE]
if frac >= 0.75:
frac = 1
elif frac >= 0.375:
frac = 2
elif frac > 0.19:
frac = 4
else:
frac = 8
displays = [
await cg.get_variable(display) for display in config[df.CONF_DISPLAYS]
]
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)
lv_scr_act = get_scr_act(lv_component)
async with LvContext():
await touchscreens_to_code(lv_component, config)
await encoders_to_code(lv_component, config, default_group)
await keypads_to_code(lv_component, config, default_group)
await theme_to_code(config)
await styles_to_code(config)
await gradients_to_code(config)
await set_obj_properties(lv_scr_act, config)
await add_widgets(lv_scr_act, config)
await add_pages(lv_component, config)
await add_top_layer(lv_component, config)
await msgboxes_to_code(lv_component, config)
await disp_update(lv_component.get_disp(), config)
# Set this directly since we are limited in how many methods can be added to the Widget class.
Widget.widgets_completed = True
async with LvContext():
await generate_triggers()
for config in configs:
lv_component = await cg.get_variable(config[CONF_ID])
await generate_page_triggers(config)
await initial_focus_to_code(config)
for conf in config.get(CONF_ON_IDLE, ()):
templ = await cg.templatable(conf[CONF_TIMEOUT], [], cg.uint32)
idle_trigger = cg.new_Pvariable(
conf[CONF_TRIGGER_ID], lv_component, templ
)
await build_automation(idle_trigger, [], conf)
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)
# This must be done after all widgets are created
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:
add_define("LV_COLOR_SCREEN_TRANSP", "1")
for use in helpers.lv_uses:
add_define(f"LV_USE_{use.upper()}")
lv_conf_h_file = CORE.relative_src_path(LV_CONF_FILENAME)
write_file_if_changed(lv_conf_h_file, generate_lv_conf_h())
CORE.add_build_flag("-DLV_CONF_H=1")
CORE.add_build_flag(f'-DLV_CONF_PATH="{LV_CONF_FILENAME}"')
cg.add_build_flag("-DLV_CONF_H=1")
cg.add_build_flag(f'-DLV_CONF_PATH="{LV_CONF_FILENAME}"')
def display_schema(config):
value = cv.ensure_list(cv.use_id(Display))(config)
return value or [cv.use_id(Display)(config)]
value = value or [cv.use_id(Display)(config)]
if len(set(value)) != len(value):
raise cv.Invalid("Display IDs must be unique")
return value
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")
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
FINAL_VALIDATE_SCHEMA = final_validation
CONFIG_SCHEMA = (
LVGL_SCHEMA = (
cv.polling_component_schema("1s")
.extend(obj_schema(obj_spec))
.extend(
@ -314,9 +395,10 @@ CONFIG_SCHEMA = (
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_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(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(
"big_endian", "little_endian"
@ -341,6 +423,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(CONF_PAGES, CONF_PAGES): cv.ensure_list(
container_schema(page_spec)
@ -355,9 +447,24 @@ CONFIG_SCHEMA = (
cv.Optional(df.CONF_GRADIENTS): GRADIENT_SCHEMA,
cv.Optional(df.CONF_TOUCHSCREENS, default=None): touchscreen_schema,
cv.Optional(df.CONF_ENCODERS, default=None): ENCODERS_CONFIG,
cv.Optional(df.CONF_KEYPADS, default=None): KEYPADS_CONFIG,
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)
.add_extra(add_hello_world)
)
def lvgl_config_schema(config):
"""
Can't use cv.ensure_list here because it converts an empty config to an empty list,
rather than a default config.
"""
if not config or isinstance(config, dict):
return [LVGL_SCHEMA(config)]
return cv.Schema([LVGL_SCHEMA])(config)
CONFIG_SCHEMA = lvgl_config_schema

View File

@ -1,11 +1,10 @@
from collections.abc import Awaitable
from typing import Callable
from typing import Any, Callable
from esphome import automation
import esphome.codegen as cg
import esphome.config_validation as cv
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 .defines import (
@ -23,8 +22,6 @@ from .lvcode import (
UPDATE_EVENT,
LambdaContext,
LocalVariable,
LvConditional,
LvglComponent,
ReturnStatement,
add_line_marks,
lv,
@ -47,8 +44,8 @@ from .types import (
)
from .widgets import (
Widget,
get_scr_act,
get_widgets,
lv_scr_act,
set_obj_properties,
wait_for_widgets,
)
@ -59,15 +56,13 @@ focused_widgets = set()
async def action_to_code(
widgets: list[Widget],
action: Callable[[Widget], Awaitable[None]],
action: Callable[[Widget], Any],
action_id,
template_arg,
args,
):
await wait_for_widgets()
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:
await action(widget)
var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda())
@ -126,7 +121,7 @@ async def lvgl_is_idle(config, condition_id, template_arg, args):
async def disp_update(disp, config: dict):
if CONF_DISP_BG_COLOR not in config and CONF_DISP_BG_IMAGE not in config:
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:
lv.disp_set_bg_color(disp_temp, await lv_color.process(bg_color))
if bg_image := config.get(CONF_DISP_BG_IMAGE):
@ -136,15 +131,22 @@ async def disp_update(disp, config: dict):
@automation.register_action(
"lvgl.widget.redraw",
ObjUpdateAction,
cv.Schema(
{
cv.Optional(CONF_ID): cv.use_id(lv_obj_t),
cv.GenerateID(CONF_LVGL_ID): cv.use_id(LvglComponent),
}
cv.Any(
cv.maybe_simple_value(
{
cv.Required(CONF_ID): cv.use_id(lv_obj_t),
},
key=CONF_ID,
),
LVGL_SCHEMA,
),
)
async def obj_invalidate_to_code(config, action_id, template_arg, args):
widgets = await get_widgets(config) or [lv_scr_act]
if CONF_LVGL_ID in config:
lv_comp = await cg.get_variable(config[CONF_LVGL_ID])
widgets = [get_scr_act(lv_comp)]
else:
widgets = await get_widgets(config)
async def do_invalidate(widget: Widget):
lv_obj.invalidate(widget.obj)
@ -155,16 +157,14 @@ async def obj_invalidate_to_code(config, action_id, template_arg, args):
@automation.register_action(
"lvgl.update",
LvglAction,
DISP_BG_SCHEMA.extend(
{
cv.GenerateID(): cv.use_id(LvglComponent),
}
).add_extra(cv.has_at_least_one_key(CONF_DISP_BG_COLOR, CONF_DISP_BG_IMAGE)),
DISP_BG_SCHEMA.extend(LVGL_SCHEMA).add_extra(
cv.has_at_least_one_key(CONF_DISP_BG_COLOR, CONF_DISP_BG_IMAGE)
),
)
async def lvgl_update_to_code(config, action_id, template_arg, args):
widgets = await get_widgets(config)
widgets = await get_widgets(config, CONF_LVGL_ID)
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:
await disp_update(disp, config)
var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda())
@ -175,32 +175,33 @@ async def lvgl_update_to_code(config, action_id, template_arg, args):
@automation.register_action(
"lvgl.pause",
LvglAction,
{
cv.GenerateID(): cv.use_id(LvglComponent),
cv.Optional(CONF_SHOW_SNOW, default=False): lv_bool,
},
LVGL_SCHEMA.extend(
{
cv.Optional(CONF_SHOW_SNOW, default=False): lv_bool,
}
),
)
async def pause_action_to_code(config, action_id, template_arg, args):
lv_comp = await cg.get_variable(config[CONF_LVGL_ID])
async with LambdaContext(LVGL_COMP_ARG) as context:
add_line_marks(where=action_id)
lv_add(lvgl_comp.set_paused(True, config[CONF_SHOW_SNOW]))
var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda())
await cg.register_parented(var, config[CONF_ID])
await cg.register_parented(var, lv_comp)
return var
@automation.register_action(
"lvgl.resume",
LvglAction,
{
cv.GenerateID(): cv.use_id(LvglComponent),
},
LVGL_SCHEMA,
)
async def resume_action_to_code(config, action_id, template_arg, args):
lv_comp = await cg.get_variable(config[CONF_LVGL_ID])
async with LambdaContext(LVGL_COMP_ARG, where=action_id) as context:
lv_add(lvgl_comp.set_paused(False, False))
var = cg.new_Pvariable(action_id, template_arg, await context.get_lambda())
await cg.register_parented(var, config[CONF_ID])
await cg.register_parented(var, lv_comp)
return var
@ -259,14 +260,15 @@ def focused_id(value):
ObjUpdateAction,
cv.Any(
cv.maybe_simple_value(
{
cv.Optional(CONF_GROUP): cv.use_id(lv_group_t),
cv.Required(CONF_ACTION): cv.one_of(
"MARK", "RESTORE", "NEXT", "PREVIOUS", upper=True
),
cv.GenerateID(CONF_LVGL_ID): cv.use_id(LvglComponent),
cv.Optional(CONF_FREEZE, default=False): cv.boolean,
},
LVGL_SCHEMA.extend(
{
cv.Optional(CONF_GROUP): cv.use_id(lv_group_t),
cv.Required(CONF_ACTION): cv.one_of(
"MARK", "RESTORE", "NEXT", "PREVIOUS", upper=True
),
cv.Optional(CONF_FREEZE, default=False): cv.boolean,
}
),
key=CONF_ACTION,
),
cv.maybe_simple_value(

View File

@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components.binary_sensor import (
BinarySensor,
binary_sensor_schema,
@ -6,36 +5,30 @@ from esphome.components.binary_sensor import (
)
import esphome.config_validation as cv
from ..defines import CONF_LVGL_ID, CONF_WIDGET
from ..lvcode import EVENT_ARG, LambdaContext, LvContext
from ..schemas import LVGL_SCHEMA
from ..defines import CONF_WIDGET
from ..lvcode import EVENT_ARG, LambdaContext, LvContext, lvgl_static
from ..types import LV_EVENT, lv_pseudo_button_t
from ..widgets import Widget, get_widgets, wait_for_widgets
CONFIG_SCHEMA = (
binary_sensor_schema(BinarySensor)
.extend(LVGL_SCHEMA)
.extend(
{
cv.Required(CONF_WIDGET): cv.use_id(lv_pseudo_button_t),
}
)
CONFIG_SCHEMA = binary_sensor_schema(BinarySensor).extend(
{
cv.Required(CONF_WIDGET): cv.use_id(lv_pseudo_button_t),
}
)
async def to_code(config):
sensor = await new_binary_sensor(config)
paren = await cg.get_variable(config[CONF_LVGL_ID])
widget = await get_widgets(config, CONF_WIDGET)
widget = widget[0]
assert isinstance(widget, Widget)
await wait_for_widgets()
async with LambdaContext(EVENT_ARG) as pressed_ctx:
pressed_ctx.add(sensor.publish_state(widget.is_pressed()))
async with LvContext(paren) as ctx:
async with LvContext() as ctx:
ctx.add(sensor.publish_initial_state(widget.is_pressed()))
ctx.add(
paren.add_event_cb(
lvgl_static.add_event_cb(
widget.obj,
await pressed_ctx.get_lambda(),
LV_EVENT.PRESSING,

View File

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

View File

@ -17,7 +17,7 @@ from .defines import (
from .helpers import lvgl_components_required, requires_component
from .lvcode import lv, lv_add, lv_assign, lv_expr, lv_Pvariable
from .schemas import ENCODER_SCHEMA
from .types import lv_group_t, lv_indev_type_t
from .types import lv_group_t, lv_indev_type_t, lv_key_t
ENCODERS_CONFIG = cv.ensure_list(
ENCODER_SCHEMA.extend(
@ -39,10 +39,13 @@ ENCODERS_CONFIG = cv.ensure_list(
)
async def encoders_to_code(var, config):
default_group = lv_Pvariable(lv_group_t, config[CONF_DEFAULT_GROUP])
lv_assign(default_group, lv_expr.group_create())
lv.group_set_default(default_group)
def get_default_group(config):
default_group = cg.Pvariable(config[CONF_DEFAULT_GROUP], lv_expr.group_create())
cg.add(lv.group_set_default(default_group))
return default_group
async def encoders_to_code(var, config, default_group):
for enc_conf in config[CONF_ENCODERS]:
lvgl_components_required.add("KEY_LISTENER")
lpt = enc_conf[CONF_LONG_PRESS_TIME].total_milliseconds
@ -54,14 +57,14 @@ async def encoders_to_code(var, config):
if sensor_config := enc_conf.get(CONF_SENSOR):
if isinstance(sensor_config, dict):
b_sensor = await cg.get_variable(sensor_config[CONF_LEFT_BUTTON])
cg.add(listener.set_left_button(b_sensor))
cg.add(listener.add_button(b_sensor, lv_key_t.LV_KEY_LEFT))
b_sensor = await cg.get_variable(sensor_config[CONF_RIGHT_BUTTON])
cg.add(listener.set_right_button(b_sensor))
cg.add(listener.add_button(b_sensor, lv_key_t.LV_KEY_RIGHT))
else:
sensor_config = await cg.get_variable(sensor_config)
lv_add(listener.set_sensor(sensor_config))
b_sensor = await cg.get_variable(enc_conf[CONF_ENTER_BUTTON])
cg.add(listener.set_enter_button(b_sensor))
cg.add(listener.add_button(b_sensor, lv_key_t.LV_KEY_ENTER))
if group := enc_conf.get(CONF_GROUP):
group = lv_Pvariable(lv_group_t, group)
lv_assign(group, lv_expr.group_create())

View File

@ -0,0 +1,77 @@
import esphome.codegen as cg
from esphome.components.binary_sensor import BinarySensor
import esphome.config_validation as cv
from esphome.const import CONF_GROUP, CONF_ID
from .defines import (
CONF_ENCODERS,
CONF_INITIAL_FOCUS,
CONF_KEYPADS,
CONF_LONG_PRESS_REPEAT_TIME,
CONF_LONG_PRESS_TIME,
literal,
)
from .helpers import lvgl_components_required
from .lvcode import lv, lv_assign, lv_expr, lv_Pvariable
from .schemas import ENCODER_SCHEMA
from .types import lv_group_t, lv_indev_type_t
KEYPAD_KEYS = (
"up",
"down",
"right",
"left",
"esc",
"del",
"backspace",
"enter",
"next",
"prev",
"home",
"end",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"#",
"*",
)
KEYPADS_CONFIG = cv.ensure_list(
ENCODER_SCHEMA.extend(
{cv.Optional(key): cv.use_id(BinarySensor) for key in KEYPAD_KEYS}
)
)
async def keypads_to_code(var, config, default_group):
for enc_conf in config[CONF_KEYPADS]:
lvgl_components_required.add("KEY_LISTENER")
lpt = enc_conf[CONF_LONG_PRESS_TIME].total_milliseconds
lprt = enc_conf[CONF_LONG_PRESS_REPEAT_TIME].total_milliseconds
listener = cg.new_Pvariable(
enc_conf[CONF_ID], lv_indev_type_t.LV_INDEV_TYPE_KEYPAD, lpt, lprt
)
await cg.register_parented(listener, var)
for key in [x for x in enc_conf if x in KEYPAD_KEYS]:
b_sensor = await cg.get_variable(enc_conf[key])
cg.add(listener.add_button(b_sensor, literal(f"LV_KEY_{key.upper()}")))
if group := enc_conf.get(CONF_GROUP):
group = lv_Pvariable(lv_group_t, group)
lv_assign(group, lv_expr.group_create())
else:
group = default_group
lv.indev_set_group(lv_expr.indev_drv_register(listener.get_drv()), group)
async def initial_focus_to_code(config):
for enc_conf in config[CONF_ENCODERS]:
if default_focus := enc_conf.get(CONF_INITIAL_FOCUS):
obj = await cg.get_variable(default_focus)
lv.group_focus_obj(obj)

View File

@ -2,11 +2,10 @@ import esphome.codegen as cg
from esphome.components import light
from esphome.components.light import LightOutput
import esphome.config_validation as cv
from esphome.const import CONF_GAMMA_CORRECT, CONF_LED, CONF_OUTPUT_ID
from esphome.const import CONF_GAMMA_CORRECT, CONF_OUTPUT_ID
from ..defines import CONF_LVGL_ID
from ..defines import CONF_WIDGET
from ..lvcode import LvContext
from ..schemas import LVGL_SCHEMA
from ..types import LvType, lvgl_ns
from ..widgets import get_widgets, wait_for_widgets
@ -15,19 +14,18 @@ LVLight = lvgl_ns.class_("LVLight", LightOutput)
CONFIG_SCHEMA = light.RGB_LIGHT_SCHEMA.extend(
{
cv.Optional(CONF_GAMMA_CORRECT, default=0.0): cv.positive_float,
cv.Required(CONF_LED): cv.use_id(lv_led_t),
cv.Required(CONF_WIDGET): cv.use_id(lv_led_t),
cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(LVLight),
}
).extend(LVGL_SCHEMA)
)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_OUTPUT_ID])
await light.register_light(var, config)
paren = await cg.get_variable(config[CONF_LVGL_ID])
widget = await get_widgets(config, CONF_LED)
widget = await get_widgets(config, CONF_WIDGET)
widget = widget[0]
await wait_for_widgets()
async with LvContext(paren) as ctx:
async with LvContext() as ctx:
ctx.add(var.set_obj(widget.obj))

View File

@ -277,10 +277,8 @@ def size_validator(value):
return ["SIZE_CONTENT", "number of pixels", "percentage"]
if isinstance(value, str) and value.lower().endswith("px"):
value = cv.int_(value[:-2])
if isinstance(value, str) and not value.endswith("%"):
if value.upper() == "SIZE_CONTENT":
return "LV_SIZE_CONTENT"
raise cv.Invalid("must be 'size_content', a percentage or an integer (pixels)")
if isinstance(value, str) and value.upper() == "SIZE_CONTENT":
return "LV_SIZE_CONTENT"
return pixels_or_percent_validator(value)

View File

@ -178,22 +178,15 @@ class LvContext(LambdaContext):
added_lambda_count = 0
def __init__(self, lv_component, args=None):
def __init__(self, args=None):
self.args = args or LVGL_COMP_ARG
super().__init__(parameters=self.args)
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):
await super().__aexit__(exc_type, exc_val, exc_tb)
await self.add_init_lambda()
def add(self, expression: Union[Expression, Statement]):
self.code_list.append(self.indented_statement(expression))
cg.add(expression)
return expression
def __call__(self, *args):
@ -304,6 +297,7 @@ lv_expr = LvExpr("lv_")
lv_obj = MockLv("lv_obj_")
# Operations on the LVGL component
lvgl_comp = MockObj(LVGL_COMP, "->")
lvgl_static = MockObj("LvglComponent", "::")
# equivalent to cg.add() for the current code context

View File

@ -5,16 +5,12 @@
#include "lvgl_hal.h"
#include "lvgl_esphome.h"
#include <numeric>
namespace esphome {
namespace 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[] = {
"NONE",
"PRESSED",
@ -69,43 +65,57 @@ std::string lv_event_code_name_for(uint8_t event_code) {
}
return str_sprintf("%2d", event_code);
}
static void rounder_cb(lv_disp_drv_t *disp_drv, lv_area_t *area) {
// make sure all coordinates are even
if (area->x1 & 1)
area->x1--;
if (!(area->x2 & 1))
area->x2++;
if (area->y1 & 1)
area->y1--;
if (!(area->y2 & 1))
area->y2++;
// cater for display driver chips with special requirements for bounds of partial
// draw areas. Extend the draw area to satisfy:
// * Coordinates must be a multiple of draw_rounding
auto *comp = static_cast<LvglComponent *>(disp_drv->user_data);
auto draw_rounding = comp->draw_rounding;
// round down the start coordinates
area->x1 = area->x1 / draw_rounding * draw_rounding;
area->y1 = area->y1 / draw_rounding * draw_rounding;
// 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_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) {
this->paused_ = paused;
this->show_snow_ = show_snow;
this->snow_line_ = 0;
if (!paused && lv_scr_act() != nullptr) {
lv_disp_trig_activity(this->disp_); // resets the inactivity time
lv_obj_invalidate(lv_scr_act());
}
this->pause_callbacks_.call(paused);
}
void LvglComponent::esphome_lvgl_init() {
lv_init();
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());
}
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, nullptr);
}
void LvglComponent::add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1,
lv_event_code_t event2) {
this->add_event_cb(obj, callback, event1);
this->add_event_cb(obj, callback, event2);
add_event_cb(obj, callback, event1);
add_event_cb(obj, callback, event2);
}
void LvglComponent::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) {
this->add_event_cb(obj, callback, event1);
this->add_event_cb(obj, callback, event2);
this->add_event_cb(obj, callback, event3);
add_event_cb(obj, callback, event1);
add_event_cb(obj, callback, event2);
add_event_cb(obj, callback, event3);
}
void LvglComponent::add_page(LvPageType *page) {
this->pages_.push_back(page);
@ -133,19 +143,64 @@ void LvglComponent::show_prev_page(lv_scr_load_anim_t anim, uint32_t time) {
} while (this->pages_[this->current_page_]->skip); // skip empty pages()
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_) {
display->draw_pixels_at(area->x1, area->y1, lv_area_get_width(area), lv_area_get_height(area), ptr,
display::COLOR_ORDER_RGB, LV_BITNESS, LV_COLOR_16_SWAP);
ESP_LOGV(TAG, "draw buffer x1=%d, y1=%d, width=%d, height=%d", x1, y1, width, height);
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) {
if (!this->paused_) {
auto now = millis();
this->draw_buffer_(area, (const uint8_t *) color_p);
ESP_LOGV(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));
this->draw_buffer_(area, color_p);
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_disp_flush_ready(disp_drv);
}
@ -160,9 +215,18 @@ 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
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, LvglComponent *parent) {
this->set_parent(parent);
lv_indev_drv_init(&this->drv_);
this->drv_.disp = parent->get_disp();
this->drv_.long_press_repeat_time = long_press_repeat_time;
this->drv_.long_press_time = long_press_time;
this->drv_.type = LV_INDEV_TYPE_POINTER;
@ -178,6 +242,7 @@ LVTouchListener::LVTouchListener(uint16_t long_press_time, uint16_t long_press_r
}
};
}
void LVTouchListener::update(const touchscreen::TouchPoints_t &tpoints) {
this->touch_pressed_ = !this->parent_->is_paused() && !tpoints.empty();
if (this->touch_pressed_)
@ -203,6 +268,39 @@ LVEncoderListener::LVEncoderListener(lv_indev_type_t type, uint16_t lpt, uint16_
}
#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
void LvButtonMatrixType::set_obj(lv_obj_t *lv_obj) {
LvCompound::set_obj(lv_obj);
@ -261,45 +359,72 @@ void LvKeyboardType::set_obj(lv_obj_t *lv_obj) {
#endif // USE_LVGL_KEYBOARD
void LvglComponent::write_random_() {
// length of 2 lines in 32 bit units
// we write 2 lines for the benefit of displays that won't write one line at a time.
size_t line_len = this->disp_drv_.hor_res * LV_COLOR_DEPTH / 8 / 4 * 2;
for (size_t i = 0; i != line_len; i++) {
((uint32_t *) (this->draw_buf_.buf1))[i] = random_uint32();
int iterations = 6 - lv_disp_get_inactive_time(this->disp_) / 60000;
if (iterations <= 0)
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++) {
((uint32_t *) (this->draw_buf_.buf1))[i] = random_uint32();
}
this->draw_buffer_(&area, (lv_color_t *) this->draw_buf_.buf1);
}
lv_area_t area;
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");
#if LV_USE_LOG
lv_log_register_print_cb(log_cb);
#endif
lv_init();
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());
/**
* @class LvglComponent
* @brief Component for rendering LVGL.
*
* 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) {
auto *display = this->displays_[0];
size_t buffer_pixels = display->get_width() * display->get_height() / this->buffer_frac_;
auto buf_bytes = buffer_pixels * LV_COLOR_DEPTH / 8;
auto *buf = lv_custom_mem_alloc(buf_bytes);
if (buf == nullptr) {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_ERROR
ESP_LOGE(TAG, "Malloc failed to allocate %zu bytes", buf_bytes);
#endif
this->mark_failed();
this->status_set_error("Memory allocation failure");
return;
this->rotation = display->get_rotation();
if (this->rotation != display::DISPLAY_ROTATION_0_DEGREES) {
this->rotate_buf_ = static_cast<lv_color_t *>(lv_custom_mem_alloc(buf_bytes)); // NOLINT
if (this->rotate_buf_ == nullptr)
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_drv_init(&this->disp_drv_);
this->disp_drv_.draw_buf = &this->draw_buf_;
@ -307,33 +432,36 @@ void LvglComponent::setup() {
this->disp_drv_.full_refresh = this->full_refresh_;
this->disp_drv_.flush_cb = static_flush_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_.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_);
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);
lv_disp_trig_activity(this->disp_);
ESP_LOGCONFIG(TAG, "LVGL Setup complete");
}
void LvglComponent::update() {
// update indicators
if (this->paused_) {
@ -348,13 +476,6 @@ void LvglComponent::loop() {
}
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
void lv_animimg_stop(lv_obj_t *obj) {

View File

@ -4,6 +4,9 @@
#ifdef USE_BINARY_SENSOR
#include "esphome/components/binary_sensor/binary_sensor.h"
#endif // USE_BINARY_SENSOR
#ifdef USE_LVGL_IMAGE
#include "esphome/components/image/image.h"
#endif // USE_LVGL_IMAGE
#ifdef USE_LVGL_ROTARY_ENCODER
#include "esphome/components/rotary_encoder/rotary_encoder.h"
#endif // USE_LVGL_ROTARY_ENCODER
@ -18,11 +21,9 @@
#include "esphome/core/component.h"
#include "esphome/core/log.h"
#include <lvgl.h>
#include <vector>
#include <map>
#ifdef USE_LVGL_IMAGE
#include "esphome/components/image/image.h"
#endif // USE_LVGL_IMAGE
#include <utility>
#include <vector>
#ifdef USE_LVGL_FONT
#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_update_event; // NOLINT
extern std::string lv_event_code_name_for(uint8_t event_code);
extern bool lv_is_pre_initialise();
#if LV_COLOR_DEPTH == 16
static const display::ColorBitness LV_BITNESS = display::ColorBitness::COLOR_BITNESS_565;
#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;
#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
class LvCompound {
public:
@ -110,6 +118,8 @@ class LvglComponent : public PollingComponent {
constexpr static const char *const TAG = "lvgl";
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);
float get_setup_priority() const override { return setup_priority::PROCESSOR; }
@ -119,19 +129,31 @@ class LvglComponent : public PollingComponent {
void add_on_idle_callback(std::function<void(uint32_t)> &&callback) {
this->idle_callbacks_.add(std::move(callback));
}
void add_display(display::Display *display) { this->displays_.push_back(display); }
void add_init_lambda(const std::function<void(LvglComponent *)> &lamb) { this->init_lambdas_.push_back(lamb); }
void add_on_pause_callback(std::function<void(bool)> &&callback) { this->pause_callbacks_.add(std::move(callback)); }
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; }
void set_buffer_frac(size_t frac) { this->buffer_frac_ = frac; }
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 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,
lv_event_code_t event3);
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);
}
}
/**
* Initialize the LVGL library and register custom events.
*/
static void esphome_lvgl_init();
static void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event);
static void add_event_cb(lv_obj_t *obj, event_callback_t callback, lv_event_code_t event1, lv_event_code_t event2);
static 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);
void add_page(LvPageType *page);
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);
@ -144,12 +166,21 @@ class LvglComponent : public PollingComponent {
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:
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);
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_drv_t disp_drv_{};
lv_disp_t *disp_{};
@ -157,14 +188,12 @@ class LvglComponent : public PollingComponent {
std::vector<LvPageType *> pages_{};
size_t current_page_{0};
bool show_snow_{};
lv_coord_t snow_line_{};
bool page_wrap_{true};
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_{};
size_t buffer_frac_{1};
bool full_refresh_{};
CallbackManager<void(bool)> pause_callbacks_{};
lv_color_t *rotate_buf_{};
};
class IdleTrigger : public Trigger<> {
@ -176,6 +205,14 @@ class IdleTrigger : public Trigger<> {
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> {
public:
explicit LvglAction(std::function<void(LvglComponent *)> &&lamb) : action_(std::move(lamb)) {}
@ -198,9 +235,12 @@ template<typename... Ts> class LvglCondition : public Condition<Ts...>, public P
#ifdef USE_LVGL_TOUCHSCREEN
class LVTouchListener : public touchscreen::TouchListener, public Parented<LvglComponent> {
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, LvglComponent *parent);
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_; }
protected:
@ -215,16 +255,11 @@ class LVEncoderListener : public Parented<LvglComponent> {
public:
LVEncoderListener(lv_indev_type_t type, uint16_t lpt, uint16_t lprt);
void set_left_button(binary_sensor::BinarySensor *left_button) {
left_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_LEFT, state); });
}
void set_right_button(binary_sensor::BinarySensor *right_button) {
right_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_RIGHT, state); });
}
void set_enter_button(binary_sensor::BinarySensor *enter_button) {
enter_button->add_on_state_callback([this](bool state) { this->event(LV_KEY_ENTER, state); });
#ifdef USE_BINARY_SENSOR
void add_button(binary_sensor::BinarySensor *button, lv_key_t key) {
button->add_on_state_callback([this, key](bool state) { this->event(key, state); });
}
#endif
#ifdef USE_LVGL_ROTARY_ENCODER
void set_sensor(rotary_encoder::RotaryEncoderSensor *sensor) {
@ -236,12 +271,18 @@ class LVEncoderListener : public Parented<LvglComponent> {
if (!this->parent_->is_paused()) {
this->pressed_ = pressed;
this->key_ = key;
} else if (!pressed) {
// maybe wakeup on release if paused
this->parent_->maybe_wakeup();
}
}
void set_count(int32_t count) {
if (!this->parent_->is_paused())
if (!this->parent_->is_paused()) {
this->count_ = count;
} else {
this->parent_->maybe_wakeup();
}
}
lv_indev_drv_t *get_drv() { return &this->drv_; }
@ -255,6 +296,48 @@ class LVEncoderListener : public Parented<LvglComponent> {
};
#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
class LvButtonMatrixType : public key_provider::KeyProvider, public LvCompound {
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

@ -3,7 +3,7 @@ from esphome.components import number
import esphome.config_validation as cv
from esphome.cpp_generator import MockObj
from ..defines import CONF_ANIMATED, CONF_LVGL_ID, CONF_UPDATE_ON_RELEASE, CONF_WIDGET
from ..defines import CONF_ANIMATED, CONF_UPDATE_ON_RELEASE, CONF_WIDGET
from ..lv_validation import animated
from ..lvcode import (
API_EVENT,
@ -13,28 +13,23 @@ from ..lvcode import (
LvContext,
lv,
lv_add,
lvgl_static,
)
from ..schemas import LVGL_SCHEMA
from ..types import LV_EVENT, LvNumber, lvgl_ns
from ..widgets import get_widgets, wait_for_widgets
LVGLNumber = lvgl_ns.class_("LVGLNumber", number.Number)
CONFIG_SCHEMA = (
number.number_schema(LVGLNumber)
.extend(LVGL_SCHEMA)
.extend(
{
cv.Required(CONF_WIDGET): cv.use_id(LvNumber),
cv.Optional(CONF_ANIMATED, default=True): animated,
cv.Optional(CONF_UPDATE_ON_RELEASE, default=False): cv.boolean,
}
)
CONFIG_SCHEMA = number.number_schema(LVGLNumber).extend(
{
cv.Required(CONF_WIDGET): cv.use_id(LvNumber),
cv.Optional(CONF_ANIMATED, default=True): animated,
cv.Optional(CONF_UPDATE_ON_RELEASE, default=False): cv.boolean,
}
)
async def to_code(config):
paren = await cg.get_variable(config[CONF_LVGL_ID])
widget = await get_widgets(config, CONF_WIDGET)
widget = widget[0]
var = await number.new_number(
@ -58,10 +53,10 @@ async def to_code(config):
if not config[CONF_UPDATE_ON_RELEASE]
else LV_EVENT.RELEASED
)
async with LvContext(paren):
async with LvContext():
lv_add(var.set_control_lambda(await control.get_lambda()))
lv_add(
paren.add_event_cb(
lvgl_static.add_event_cb(
widget.obj, await event.get_lambda(), UPDATE_EVENT, event_code
)
)

View File

@ -216,7 +216,7 @@ def automation_schema(typ: LvType):
events = df.LV_EVENT_TRIGGERS + (CONF_ON_VALUE,)
else:
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)
return {
cv.Optional(event): validate_automation(
@ -391,7 +391,9 @@ def container_validator(schema, widget_type: WidgetType):
add_lv_use(ltype)
if value == SCHEMA_EXTRACT:
return result
result = result.extend(LAYOUT_SCHEMAS[ltype.lower()])
result = result.extend(
LAYOUT_SCHEMAS.get(ltype.lower(), LAYOUT_SCHEMAS[df.TYPE_NONE])
)
return result(value)
return validator

View File

@ -1,33 +1,19 @@
import esphome.codegen as cg
from esphome.components import select
import esphome.config_validation as cv
from esphome.const import CONF_OPTIONS
from ..defines import CONF_ANIMATED, CONF_LVGL_ID, CONF_WIDGET
from ..lvcode import (
API_EVENT,
EVENT_ARG,
UPDATE_EVENT,
LambdaContext,
LvContext,
lv,
lv_add,
)
from ..schemas import LVGL_SCHEMA
from ..types import LV_EVENT, LvSelect, lvgl_ns
from ..defines import CONF_ANIMATED, CONF_WIDGET, literal
from ..lvcode import LvContext
from ..types import LvSelect, lvgl_ns
from ..widgets import get_widgets, wait_for_widgets
LVGLSelect = lvgl_ns.class_("LVGLSelect", select.Select)
CONFIG_SCHEMA = (
select.select_schema(LVGLSelect)
.extend(LVGL_SCHEMA)
.extend(
{
cv.Required(CONF_WIDGET): cv.use_id(LvSelect),
cv.Optional(CONF_ANIMATED, default=False): cv.boolean,
}
)
CONFIG_SCHEMA = select.select_schema(LVGLSelect).extend(
{
cv.Required(CONF_WIDGET): cv.use_id(LvSelect),
cv.Optional(CONF_ANIMATED, default=False): cv.boolean,
}
)
@ -36,22 +22,11 @@ async def to_code(config):
widget = widget[0]
options = widget.config.get(CONF_OPTIONS, [])
selector = await select.new_select(config, options=options)
paren = await cg.get_variable(config[CONF_LVGL_ID])
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:
lv_add(selector.set_control_lambda(await control.get_lambda()))
async with LvContext() as ctx:
ctx.add(
paren.add_event_cb(
widget.obj,
await pub_ctx.get_lambda(),
LV_EVENT.VALUE_CHANGED,
UPDATE_EVENT,
selector.set_widget(
widget.var,
literal("LV_ANIM_ON" if config[CONF_ANIMATED] else "LV_ANIM_OFF"),
)
)
lv_add(selector.publish_index(widget.get_value()))

View File

@ -6,58 +6,52 @@
#include "esphome/core/automation.h"
#include "esphome/core/component.h"
#include "esphome/core/preferences.h"
#include "../lvgl.h"
namespace esphome {
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 {
public:
void set_control_lambda(std::function<void(size_t)> lambda) {
this->control_lambda_ = std::move(lambda);
void set_widget(LvSelectable *widget, lv_anim_enable_t anim = LV_ANIM_OFF) {
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()) {
this->control(this->initial_state_.value());
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) {
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)); }
void publish() { this->publish_state(this->widget_->get_selected_text()); }
protected:
void control(const std::string &value) override {
if (this->control_lambda_ != nullptr) {
auto index = index_of(value);
if (index)
this->control_lambda_(index.value());
if (this->widget_ != nullptr) {
this->widget_->set_selected_text(value, this->anim_);
} 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_{};
optional<const char *> initial_state_{};
LvSelectable *widget_{};
optional<std::string> initial_state_{};
lv_anim_enable_t anim_{LV_ANIM_OFF};
};
} // namespace lvgl

View File

@ -1,8 +1,7 @@
import esphome.codegen as cg
from esphome.components.sensor import Sensor, new_sensor, sensor_schema
import esphome.config_validation as cv
from ..defines import CONF_LVGL_ID, CONF_WIDGET
from ..defines import CONF_WIDGET
from ..lvcode import (
API_EVENT,
EVENT_ARG,
@ -11,34 +10,29 @@ from ..lvcode import (
LambdaContext,
LvContext,
lv_add,
lvgl_static,
)
from ..schemas import LVGL_SCHEMA
from ..types import LV_EVENT, LvNumber
from ..widgets import Widget, get_widgets, wait_for_widgets
CONFIG_SCHEMA = (
sensor_schema(Sensor)
.extend(LVGL_SCHEMA)
.extend(
{
cv.Required(CONF_WIDGET): cv.use_id(LvNumber),
}
)
CONFIG_SCHEMA = sensor_schema(Sensor).extend(
{
cv.Required(CONF_WIDGET): cv.use_id(LvNumber),
}
)
async def to_code(config):
sensor = await new_sensor(config)
paren = await cg.get_variable(config[CONF_LVGL_ID])
widget = await get_widgets(config, CONF_WIDGET)
widget = widget[0]
assert isinstance(widget, Widget)
await wait_for_widgets()
async with LambdaContext(EVENT_ARG) as lamb:
lv_add(sensor.publish_state(widget.get_value()))
async with LvContext(paren, LVGL_COMP_ARG):
async with LvContext(LVGL_COMP_ARG):
lv_add(
paren.add_event_cb(
lvgl_static.add_event_cb(
widget.obj,
await lamb.get_lambda(),
LV_EVENT.VALUE_CHANGED,

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.obj import obj_spec
TOP_LAYER = literal("lv_disp_get_layer_top(lv_component->get_disp())")
async def styles_to_code(config):
"""Convert styles to C__ code."""
@ -51,9 +49,10 @@ async def theme_to_code(config):
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):
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)
await set_obj_properties(top_w, top_conf)
await add_widgets(top_w, top_conf)

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