1
0
mirror of https://github.com/esphome/esphome.git synced 2025-03-26 04:28:17 +00:00

Merge branch 'esphome:dev' into dev

This commit is contained in:
Oliver Kleinecke 2025-02-05 14:28:54 +01:00 committed by GitHub
commit faefa25cc9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1459 changed files with 12810 additions and 26771 deletions

View File

@ -278,6 +278,7 @@ esphome/components/mics_4514/* @jesserockz
esphome/components/midea/* @dudanov
esphome/components/midea_ir/* @dudanov
esphome/components/mitsubishi/* @RubyBailey
esphome/components/mixer/speaker/* @kahrendt
esphome/components/mlx90393/* @functionpointer
esphome/components/mlx90614/* @jesserockz
esphome/components/mmc5603/* @benhoff
@ -344,6 +345,7 @@ esphome/components/radon_eye_rd200/* @jeffeb3
esphome/components/rc522/* @glmnet
esphome/components/rc522_i2c/* @glmnet
esphome/components/rc522_spi/* @glmnet
esphome/components/resampler/speaker/* @kahrendt
esphome/components/restart/* @esphome/core
esphome/components/rf_bridge/* @jesserockz
esphome/components/rgbct/* @jesserockz
@ -356,7 +358,7 @@ esphome/components/rtttl/* @glmnet
esphome/components/safe_mode/* @jsuanet @kbx81 @paulmonigatti
esphome/components/scd4x/* @martgras @sjtrny
esphome/components/script/* @esphome/core
esphome/components/sdl/* @clydebarrow
esphome/components/sdl/* @bdm310 @clydebarrow
esphome/components/sdm_meter/* @jesserockz @polyfaces
esphome/components/sdp3x/* @Azimath
esphome/components/seeed_mr24hpc1/* @limengdu
@ -498,5 +500,6 @@ esphome/components/xiaomi_mhoc401/* @vevsvevs
esphome/components/xiaomi_rtcgq02lm/* @jesserockz
esphome/components/xl9535/* @mreditor97
esphome/components/xpt2046/touchscreen/* @nielsnl68 @numo68
esphome/components/xxtea/* @clydebarrow
esphome/components/zhlt01/* @cfeenstra1024
esphome/components/zio_ultrasonic/* @kahrendt

View File

@ -280,8 +280,7 @@ FileDecoderState AudioDecoder::decode_mp3_() {
if (err) {
switch (err) {
case esp_audio_libs::helix_decoder::ERR_MP3_OUT_OF_MEMORY:
return FileDecoderState::FAILED;
break;
// Intentional fallthrough
case esp_audio_libs::helix_decoder::ERR_MP3_NULL_POINTER:
return FileDecoderState::FAILED;
break;

View File

@ -5,12 +5,13 @@
#include "audio.h"
#include "audio_transfer_buffer.h"
#include "esphome/core/defines.h"
#include "esphome/core/ring_buffer.h"
#ifdef USE_SPEAKER
#include "esphome/components/speaker/speaker.h"
#endif
#include "esphome/core/ring_buffer.h"
#include "esp_err.h"
#include <resampler.h> // esp-audio-libs

View File

@ -39,6 +39,10 @@ void IDFI2CBus::setup() {
conf.scl_io_num = scl_pin_;
conf.scl_pullup_en = scl_pullup_enabled_;
conf.master.clk_speed = frequency_;
#ifdef USE_ESP32_VARIANT_ESP32S2
// workaround for https://github.com/esphome/issues/issues/6718
conf.clk_flags = I2C_SCLK_SRC_FLAG_AWARE_DFS;
#endif
esp_err_t err = i2c_param_config(port_, &conf);
if (err != ESP_OK) {
ESP_LOGW(TAG, "i2c_param_config failed: %s", esp_err_to_name(err));

View File

@ -61,7 +61,14 @@ from .types import (
lv_style_t,
lvgl_ns,
)
from .widgets import Widget, add_widgets, get_scr_act, set_obj_properties, styles_used
from .widgets import (
LvScrActType,
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
@ -318,7 +325,7 @@ async def to_code(configs):
config[df.CONF_RESUME_ON_INPUT],
)
await cg.register_component(lv_component, config)
Widget.create(config[CONF_ID], lv_component, obj_spec, config)
Widget.create(config[CONF_ID], lv_component, LvScrActType(), config)
lv_scr_act = get_scr_act(lv_component)
async with LvContext():
@ -389,75 +396,87 @@ def add_hello_world(config):
FINAL_VALIDATE_SCHEMA = final_validation
LVGL_SCHEMA = (
cv.polling_component_schema("1s")
.extend(obj_schema(obj_spec))
.extend(
{
cv.GenerateID(CONF_ID): cv.declare_id(LvglComponent),
cv.GenerateID(df.CONF_DISPLAYS): display_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.LV_LOG_LEVELS, upper=True
),
cv.Optional(df.CONF_BYTE_ORDER, default="big_endian"): cv.one_of(
"big_endian", "little_endian"
),
cv.Optional(df.CONF_STYLE_DEFINITIONS): cv.ensure_list(
cv.Schema({cv.Required(CONF_ID): cv.declare_id(lv_style_t)})
.extend(STYLE_SCHEMA)
.extend(
LVGL_SCHEMA = cv.All(
container_schema(
obj_spec,
cv.polling_component_schema("1s")
.extend(
{
cv.GenerateID(CONF_ID): cv.declare_id(LvglComponent),
cv.GenerateID(df.CONF_DISPLAYS): display_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.LV_LOG_LEVELS, upper=True
),
cv.Optional(df.CONF_BYTE_ORDER, default="big_endian"): cv.one_of(
"big_endian", "little_endian"
),
cv.Optional(df.CONF_STYLE_DEFINITIONS): cv.ensure_list(
cv.Schema({cv.Required(CONF_ID): cv.declare_id(lv_style_t)})
.extend(STYLE_SCHEMA)
.extend(
{
cv.Optional(df.CONF_GRID_CELL_X_ALIGN): grid_alignments,
cv.Optional(df.CONF_GRID_CELL_Y_ALIGN): grid_alignments,
cv.Optional(df.CONF_PAD_ROW): lvalid.pixels,
cv.Optional(df.CONF_PAD_COLUMN): lvalid.pixels,
}
)
),
cv.Optional(CONF_ON_IDLE): validate_automation(
{
cv.Optional(df.CONF_GRID_CELL_X_ALIGN): grid_alignments,
cv.Optional(df.CONF_GRID_CELL_Y_ALIGN): grid_alignments,
cv.Optional(df.CONF_PAD_ROW): lvalid.pixels,
cv.Optional(df.CONF_PAD_COLUMN): lvalid.pixels,
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(IdleTrigger),
cv.Required(CONF_TIMEOUT): cv.templatable(
cv.positive_time_period_milliseconds
),
}
)
),
cv.Optional(CONF_ON_IDLE): validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(IdleTrigger),
cv.Required(CONF_TIMEOUT): cv.templatable(
cv.positive_time_period_milliseconds
),
}
),
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)
),
cv.Optional(df.CONF_MSGBOXES): cv.ensure_list(MSGBOX_SCHEMA),
cv.Optional(df.CONF_PAGE_WRAP, default=True): lv_bool,
cv.Optional(df.CONF_TOP_LAYER): container_schema(obj_spec),
cv.Optional(df.CONF_TRANSPARENCY_KEY, default=0x000400): lvalid.lv_color,
cv.Optional(df.CONF_THEME): cv.Schema(
{cv.Optional(name): obj_schema(w) for name, w in WIDGET_TYPES.items()}
),
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)
),
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)
),
cv.Optional(df.CONF_MSGBOXES): cv.ensure_list(MSGBOX_SCHEMA),
cv.Optional(df.CONF_PAGE_WRAP, default=True): lv_bool,
cv.Optional(df.CONF_TOP_LAYER): container_schema(obj_spec),
cv.Optional(
df.CONF_TRANSPARENCY_KEY, default=0x000400
): lvalid.lv_color,
cv.Optional(df.CONF_THEME): cv.Schema(
{
cv.Optional(name): obj_schema(w)
for name, w in WIDGET_TYPES.items()
}
),
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),
),
cv.has_at_most_one_key(CONF_PAGES, df.CONF_LAYOUT),
add_hello_world,
)

View File

@ -146,6 +146,8 @@ TYPE_FLEX = "flex"
TYPE_GRID = "grid"
TYPE_NONE = "none"
DIRECTIONS = LvConstant("LV_DIR_", "LEFT", "RIGHT", "BOTTOM", "TOP")
LV_FONTS = list(f"montserrat_{s}" for s in range(8, 50, 2)) + [
"dejavu_16_persian_hebrew",
"simsun_16_cjk",
@ -169,9 +171,13 @@ LV_EVENT_MAP = {
"CANCEL": "CANCEL",
"ALL_EVENTS": "ALL",
"CHANGE": "VALUE_CHANGED",
"GESTURE": "GESTURE",
}
LV_EVENT_TRIGGERS = tuple(f"on_{x.lower()}" for x in LV_EVENT_MAP)
SWIPE_TRIGGERS = tuple(
f"on_swipe_{x.lower()}" for x in DIRECTIONS.choices + ("up", "down")
)
LV_ANIM = LvConstant(
@ -250,7 +256,6 @@ KEYBOARD_MODES = LvConstant(
"NUMBER",
)
ROLLER_MODES = LvConstant("LV_ROLLER_MODE_", "NORMAL", "INFINITE")
DIRECTIONS = LvConstant("LV_DIR_", "LEFT", "RIGHT", "BOTTOM", "TOP")
TILE_DIRECTIONS = DIRECTIONS.extend("HOR", "VER", "ALL")
CHILD_ALIGNMENTS = LvConstant(
"LV_ALIGN_",

View File

@ -211,10 +211,9 @@ def part_schema(parts):
def automation_schema(typ: LvType):
events = df.LV_EVENT_TRIGGERS + df.SWIPE_TRIGGERS
if typ.has_on_value:
events = df.LV_EVENT_TRIGGERS + (CONF_ON_VALUE,)
else:
events = df.LV_EVENT_TRIGGERS
events = events + (CONF_ON_VALUE,)
args = typ.get_arg_type() if isinstance(typ, LvType) else []
args.append(lv_event_t_ptr)
return {

View File

@ -7,8 +7,10 @@ from .defines import (
CONF_ALIGN_TO,
CONF_X,
CONF_Y,
DIRECTIONS,
LV_EVENT_MAP,
LV_EVENT_TRIGGERS,
SWIPE_TRIGGERS,
literal,
)
from .lvcode import (
@ -23,7 +25,7 @@ from .lvcode import (
lvgl_static,
)
from .types import LV_EVENT
from .widgets import widget_map
from .widgets import LvScrActType, get_scr_act, widget_map
async def generate_triggers():
@ -33,6 +35,9 @@ async def generate_triggers():
"""
for w in widget_map.values():
if isinstance(w.type, LvScrActType):
w = get_scr_act(w.var)
if w.config:
for event, conf in {
event: conf
@ -43,6 +48,24 @@ async def generate_triggers():
w.add_flag("LV_OBJ_FLAG_CLICKABLE")
event = literal("LV_EVENT_" + LV_EVENT_MAP[event[3:].upper()])
await add_trigger(conf, w, event)
for event, conf in {
event: conf
for event, conf in w.config.items()
if event in SWIPE_TRIGGERS
}.items():
conf = conf[0]
dir = event[9:].upper()
dir = {"UP": "TOP", "DOWN": "BOTTOM"}.get(dir, dir)
dir = DIRECTIONS.mapper(dir)
w.clear_flag("LV_OBJ_FLAG_SCROLLABLE")
selected = literal(
f"lv_indev_get_gesture_dir(lv_indev_get_act()) == {dir}"
)
await add_trigger(
conf, w, literal("LV_EVENT_GESTURE"), is_selected=selected
)
for conf in w.config.get(CONF_ON_VALUE, ()):
await add_trigger(
conf,
@ -61,13 +84,14 @@ async def generate_triggers():
lv.obj_align_to(w.obj, target, align, x, y)
async def add_trigger(conf, w, *events):
async def add_trigger(conf, w, *events, is_selected=None):
is_selected = is_selected or w.is_selected()
tid = conf[CONF_TRIGGER_ID]
trigger = cg.new_Pvariable(tid)
args = w.get_args() + [(lv_event_t_ptr, "event")]
value = w.get_values()
await automation.build_automation(trigger, args, conf)
async with LambdaContext(EVENT_ARG, where=tid) as context:
with LvConditional(w.is_selected()):
with LvConditional(is_selected):
lv_add(trigger.trigger(*value, literal("event")))
lv_add(lvgl_static.add_event_cb(w.obj, await context.get_lambda(), *events))

View File

View File

@ -0,0 +1,172 @@
from esphome import automation
import esphome.codegen as cg
from esphome.components import audio, esp32, speaker
import esphome.config_validation as cv
from esphome.const import (
CONF_BITS_PER_SAMPLE,
CONF_BUFFER_DURATION,
CONF_DURATION,
CONF_ID,
CONF_NEVER,
CONF_NUM_CHANNELS,
CONF_OUTPUT_SPEAKER,
CONF_SAMPLE_RATE,
CONF_TASK_STACK_IN_PSRAM,
CONF_TIMEOUT,
PLATFORM_ESP32,
)
from esphome.core.entity_helpers import inherit_property_from
import esphome.final_validate as fv
AUTO_LOAD = ["audio"]
CODEOWNERS = ["@kahrendt"]
mixer_speaker_ns = cg.esphome_ns.namespace("mixer_speaker")
MixerSpeaker = mixer_speaker_ns.class_("MixerSpeaker", cg.Component)
SourceSpeaker = mixer_speaker_ns.class_("SourceSpeaker", cg.Component, speaker.Speaker)
CONF_DECIBEL_REDUCTION = "decibel_reduction"
CONF_QUEUE_MODE = "queue_mode"
CONF_SOURCE_SPEAKERS = "source_speakers"
DuckingApplyAction = mixer_speaker_ns.class_(
"DuckingApplyAction", automation.Action, cg.Parented.template(SourceSpeaker)
)
SOURCE_SPEAKER_SCHEMA = speaker.SPEAKER_SCHEMA.extend(
{
cv.GenerateID(): cv.declare_id(SourceSpeaker),
cv.Optional(
CONF_BUFFER_DURATION, default="100ms"
): 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),
),
cv.Optional(CONF_BITS_PER_SAMPLE, default=16): cv.int_range(16, 16),
}
)
def _set_stream_limits(config):
audio.set_stream_limits(
min_bits_per_sample=16,
max_bits_per_sample=16,
)(config)
return config
def _validate_source_speaker(config):
fconf = fv.full_config.get()
# Get ID for the output speaker and add it to the source speakrs config to easily inherit properties
path = fconf.get_path_for_id(config[CONF_ID])[:-3]
path.append(CONF_OUTPUT_SPEAKER)
output_speaker_id = fconf.get_config_for_path(path)
config[CONF_OUTPUT_SPEAKER] = output_speaker_id
inherit_property_from(CONF_NUM_CHANNELS, CONF_OUTPUT_SPEAKER)(config)
inherit_property_from(CONF_SAMPLE_RATE, CONF_OUTPUT_SPEAKER)(config)
audio.final_validate_audio_schema(
"mixer",
audio_device=CONF_OUTPUT_SPEAKER,
bits_per_sample=config.get(CONF_BITS_PER_SAMPLE),
channels=config.get(CONF_NUM_CHANNELS),
sample_rate=config.get(CONF_SAMPLE_RATE),
)(config)
return config
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(MixerSpeaker),
cv.Required(CONF_OUTPUT_SPEAKER): cv.use_id(speaker.Speaker),
cv.Required(CONF_SOURCE_SPEAKERS): cv.All(
cv.ensure_list(SOURCE_SPEAKER_SCHEMA),
cv.Length(min=2, max=8),
[_set_stream_limits],
),
cv.Optional(CONF_NUM_CHANNELS): cv.int_range(min=1, max=2),
cv.Optional(CONF_QUEUE_MODE, default=False): cv.boolean,
cv.SplitDefault(CONF_TASK_STACK_IN_PSRAM, esp32_idf=False): cv.All(
cv.boolean, cv.only_with_esp_idf
),
}
),
cv.only_on([PLATFORM_ESP32]),
)
FINAL_VALIDATE_SCHEMA = cv.All(
cv.Schema(
{
cv.Optional(CONF_SOURCE_SPEAKERS): [_validate_source_speaker],
},
extra=cv.ALLOW_EXTRA,
),
inherit_property_from(CONF_NUM_CHANNELS, CONF_OUTPUT_SPEAKER),
)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
spkr = await cg.get_variable(config[CONF_OUTPUT_SPEAKER])
cg.add(var.set_output_channels(config[CONF_NUM_CHANNELS]))
cg.add(var.set_output_speaker(spkr))
cg.add(var.set_queue_mode(config[CONF_QUEUE_MODE]))
if task_stack_in_psram := config.get(CONF_TASK_STACK_IN_PSRAM):
cg.add(var.set_task_stack_in_psram(task_stack_in_psram))
if task_stack_in_psram:
if config[CONF_TASK_STACK_IN_PSRAM]:
esp32.add_idf_sdkconfig_option(
"CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY", True
)
for speaker_config in config[CONF_SOURCE_SPEAKERS]:
source_speaker = cg.new_Pvariable(speaker_config[CONF_ID])
cg.add(source_speaker.set_buffer_duration(speaker_config[CONF_BUFFER_DURATION]))
if speaker_config[CONF_TIMEOUT] != CONF_NEVER:
cg.add(source_speaker.set_timeout(speaker_config[CONF_TIMEOUT]))
await cg.register_component(source_speaker, speaker_config)
await cg.register_parented(source_speaker, config[CONF_ID])
await speaker.register_speaker(source_speaker, speaker_config)
cg.add(var.add_source_speaker(source_speaker))
@automation.register_action(
"mixer_speaker.apply_ducking",
DuckingApplyAction,
cv.Schema(
{
cv.GenerateID(): cv.use_id(SourceSpeaker),
cv.Required(CONF_DECIBEL_REDUCTION): cv.templatable(
cv.int_range(min=0, max=51)
),
cv.Optional(CONF_DURATION, default="0.0s"): cv.templatable(
cv.positive_time_period_milliseconds
),
}
),
)
async def ducking_set_to_code(config, action_id, template_arg, args):
var = cg.new_Pvariable(action_id, template_arg)
await cg.register_parented(var, config[CONF_ID])
decibel_reduction = await cg.templatable(
config[CONF_DECIBEL_REDUCTION], args, cg.uint8
)
cg.add(var.set_decibel_reduction(decibel_reduction))
duration = await cg.templatable(config[CONF_DURATION], args, cg.uint32)
cg.add(var.set_duration(duration))
return var

View File

@ -0,0 +1,19 @@
#pragma once
#include "mixer_speaker.h"
#ifdef USE_ESP32
namespace esphome {
namespace mixer_speaker {
template<typename... Ts> class DuckingApplyAction : public Action<Ts...>, public Parented<SourceSpeaker> {
TEMPLATABLE_VALUE(uint8_t, decibel_reduction)
TEMPLATABLE_VALUE(uint32_t, duration)
void play(Ts... x) override {
this->parent_->apply_ducking(this->decibel_reduction_.value(x...), this->duration_.value(x...));
}
};
} // namespace mixer_speaker
} // namespace esphome
#endif

View File

@ -0,0 +1,624 @@
#include "mixer_speaker.h"
#ifdef USE_ESP32
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <algorithm>
#include <cstring>
namespace esphome {
namespace mixer_speaker {
static const UBaseType_t MIXER_TASK_PRIORITY = 10;
static const uint32_t TRANSFER_BUFFER_DURATION_MS = 50;
static const uint32_t TASK_DELAY_MS = 25;
static const size_t TASK_STACK_SIZE = 4096;
static const int16_t MAX_AUDIO_SAMPLE_VALUE = INT16_MAX;
static const int16_t MIN_AUDIO_SAMPLE_VALUE = INT16_MIN;
static const char *const TAG = "speaker_mixer";
// Gives the Q15 fixed point scaling factor to reduce by 0 dB, 1dB, ..., 50 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> DECIBEL_REDUCTION_TABLE = {
32767, 29201, 26022, 23189, 20665, 18415, 16410, 14624, 13032, 11613, 10349, 9222, 8218, 7324, 6527, 5816, 5183,
4619, 4116, 3668, 3269, 2913, 2596, 2313, 2061, 1837, 1637, 1459, 1300, 1158, 1032, 920, 820, 731,
651, 580, 517, 461, 411, 366, 326, 291, 259, 231, 206, 183, 163, 146, 130, 116, 103};
enum MixerEventGroupBits : uint32_t {
COMMAND_STOP = (1 << 0), // stops the mixer task
STATE_STARTING = (1 << 10),
STATE_RUNNING = (1 << 11),
STATE_STOPPING = (1 << 12),
STATE_STOPPED = (1 << 13),
ERR_ESP_NO_MEM = (1 << 19),
ALL_BITS = 0x00FFFFFF, // All valid FreeRTOS event group bits
};
void SourceSpeaker::dump_config() {
ESP_LOGCONFIG(TAG, "Mixer Source Speaker");
ESP_LOGCONFIG(TAG, " Buffer Duration: %" PRIu32 " ms", this->buffer_duration_ms_);
if (this->timeout_ms_.has_value()) {
ESP_LOGCONFIG(TAG, " Timeout: %" PRIu32 " ms", this->timeout_ms_.value());
} else {
ESP_LOGCONFIG(TAG, " Timeout: never");
}
}
void SourceSpeaker::setup() {
this->parent_->get_output_speaker()->add_audio_output_callback(
[this](uint32_t new_playback_ms, uint32_t remainder_us, uint32_t pending_ms, uint32_t write_timestamp) {
uint32_t personal_playback_ms = std::min(new_playback_ms, this->pending_playback_ms_);
if (personal_playback_ms > 0) {
this->pending_playback_ms_ -= personal_playback_ms;
this->audio_output_callback_(personal_playback_ms, remainder_us, this->pending_playback_ms_, write_timestamp);
}
});
}
void SourceSpeaker::loop() {
switch (this->state_) {
case speaker::STATE_STARTING: {
esp_err_t err = this->start_();
if (err == ESP_OK) {
this->state_ = speaker::STATE_RUNNING;
this->stop_gracefully_ = false;
this->last_seen_data_ms_ = millis();
this->status_clear_error();
} else {
switch (err) {
case ESP_ERR_NO_MEM:
this->status_set_error("Failed to start mixer: not enough memory");
break;
case ESP_ERR_NOT_SUPPORTED:
this->status_set_error("Failed to start mixer: unsupported bits per sample");
break;
case ESP_ERR_INVALID_ARG:
this->status_set_error("Failed to start mixer: audio stream isn't compatible with the other audio stream.");
break;
case ESP_ERR_INVALID_STATE:
this->status_set_error("Failed to start mixer: mixer task failed to start");
break;
default:
this->status_set_error("Failed to start mixer");
break;
}
this->state_ = speaker::STATE_STOPPING;
}
break;
}
case speaker::STATE_RUNNING:
if (!this->transfer_buffer_->has_buffered_data()) {
if ((this->timeout_ms_.has_value() && ((millis() - this->last_seen_data_ms_) > this->timeout_ms_.value())) ||
this->stop_gracefully_) {
this->state_ = speaker::STATE_STOPPING;
}
}
break;
case speaker::STATE_STOPPING:
this->stop_();
this->stop_gracefully_ = false;
this->state_ = speaker::STATE_STOPPED;
break;
case speaker::STATE_STOPPED:
break;
}
}
size_t SourceSpeaker::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
if (this->is_stopped()) {
this->start();
}
size_t bytes_written = 0;
if (this->ring_buffer_.use_count() == 1) {
std::shared_ptr<RingBuffer> temp_ring_buffer = this->ring_buffer_.lock();
bytes_written = temp_ring_buffer->write_without_replacement(data, length, ticks_to_wait);
if (bytes_written > 0) {
this->last_seen_data_ms_ = millis();
}
}
return bytes_written;
}
void SourceSpeaker::start() { this->state_ = speaker::STATE_STARTING; }
esp_err_t SourceSpeaker::start_() {
const size_t ring_buffer_size = this->audio_stream_info_.ms_to_bytes(this->buffer_duration_ms_);
if (this->transfer_buffer_.use_count() == 0) {
this->transfer_buffer_ =
audio::AudioSourceTransferBuffer::create(this->audio_stream_info_.ms_to_bytes(TRANSFER_BUFFER_DURATION_MS));
if (this->transfer_buffer_ == nullptr) {
return ESP_ERR_NO_MEM;
}
std::shared_ptr<RingBuffer> temp_ring_buffer;
if (!this->ring_buffer_.use_count()) {
temp_ring_buffer = RingBuffer::create(ring_buffer_size);
this->ring_buffer_ = temp_ring_buffer;
}
if (!this->ring_buffer_.use_count()) {
return ESP_ERR_NO_MEM;
} else {
this->transfer_buffer_->set_source(temp_ring_buffer);
}
}
return this->parent_->start(this->audio_stream_info_);
}
void SourceSpeaker::stop() {
if (this->state_ != speaker::STATE_STOPPED) {
this->state_ = speaker::STATE_STOPPING;
}
}
void SourceSpeaker::stop_() {
this->transfer_buffer_.reset(); // deallocates the transfer buffer
}
void SourceSpeaker::finish() { this->stop_gracefully_ = true; }
bool SourceSpeaker::has_buffered_data() const {
return ((this->transfer_buffer_.use_count() > 0) && this->transfer_buffer_->has_buffered_data());
}
void SourceSpeaker::set_mute_state(bool mute_state) {
this->mute_state_ = mute_state;
this->parent_->get_output_speaker()->set_mute_state(mute_state);
}
void SourceSpeaker::set_volume(float volume) {
this->volume_ = volume;
this->parent_->get_output_speaker()->set_volume(volume);
}
size_t SourceSpeaker::process_data_from_source(TickType_t ticks_to_wait) {
if (!this->transfer_buffer_.use_count()) {
return 0;
}
// Store current offset, as these samples are already ducked
const size_t current_length = this->transfer_buffer_->available();
size_t bytes_read = this->transfer_buffer_->transfer_data_from_source(ticks_to_wait);
uint32_t samples_to_duck = this->audio_stream_info_.bytes_to_samples(bytes_read);
if (samples_to_duck > 0) {
int16_t *current_buffer = reinterpret_cast<int16_t *>(this->transfer_buffer_->get_buffer_start() + current_length);
duck_samples(current_buffer, samples_to_duck, &this->current_ducking_db_reduction_,
&this->ducking_transition_samples_remaining_, this->samples_per_ducking_step_,
this->db_change_per_ducking_step_);
}
return bytes_read;
}
void SourceSpeaker::apply_ducking(uint8_t decibel_reduction, uint32_t duration) {
if (this->target_ducking_db_reduction_ != decibel_reduction) {
this->current_ducking_db_reduction_ = this->target_ducking_db_reduction_;
this->target_ducking_db_reduction_ = decibel_reduction;
uint8_t total_ducking_steps = 0;
if (this->target_ducking_db_reduction_ > this->current_ducking_db_reduction_) {
// The dB reduction level is increasing (which results in quieter audio)
total_ducking_steps = this->target_ducking_db_reduction_ - this->current_ducking_db_reduction_ - 1;
this->db_change_per_ducking_step_ = 1;
} else {
// The dB reduction level is decreasing (which results in louder audio)
total_ducking_steps = this->current_ducking_db_reduction_ - this->target_ducking_db_reduction_ - 1;
this->db_change_per_ducking_step_ = -1;
}
if ((duration > 0) && (total_ducking_steps > 0)) {
this->ducking_transition_samples_remaining_ = this->audio_stream_info_.ms_to_samples(duration);
this->samples_per_ducking_step_ = this->ducking_transition_samples_remaining_ / total_ducking_steps;
this->ducking_transition_samples_remaining_ =
this->samples_per_ducking_step_ * total_ducking_steps; // Adjust for integer division rounding
this->current_ducking_db_reduction_ += this->db_change_per_ducking_step_;
} else {
this->ducking_transition_samples_remaining_ = 0;
this->current_ducking_db_reduction_ = this->target_ducking_db_reduction_;
}
}
}
void SourceSpeaker::duck_samples(int16_t *input_buffer, uint32_t input_samples_to_duck,
int8_t *current_ducking_db_reduction, uint32_t *ducking_transition_samples_remaining,
uint32_t samples_per_ducking_step, int8_t db_change_per_ducking_step) {
if (*ducking_transition_samples_remaining > 0) {
// Ducking level is still transitioning
// Takes the ceiling of input_samples_to_duck/samples_per_ducking_step
uint32_t ducking_steps_in_batch =
input_samples_to_duck / samples_per_ducking_step + (input_samples_to_duck % samples_per_ducking_step != 0);
for (uint32_t i = 0; i < ducking_steps_in_batch; ++i) {
uint32_t samples_left_in_step = *ducking_transition_samples_remaining % samples_per_ducking_step;
if (samples_left_in_step == 0) {
samples_left_in_step = samples_per_ducking_step;
}
uint32_t samples_to_duck = std::min(input_samples_to_duck, samples_left_in_step);
samples_to_duck = std::min(samples_to_duck, *ducking_transition_samples_remaining);
// Ensure we only point to valid index in the Q15 scaling factor table
uint8_t safe_db_reduction_index =
clamp<uint8_t>(*current_ducking_db_reduction, 0, DECIBEL_REDUCTION_TABLE.size() - 1);
int16_t q15_scale_factor = DECIBEL_REDUCTION_TABLE[safe_db_reduction_index];
audio::scale_audio_samples(input_buffer, input_buffer, q15_scale_factor, samples_to_duck);
if (samples_left_in_step - samples_to_duck == 0) {
// After scaling the current samples, we are ready to transition to the next step
*current_ducking_db_reduction += db_change_per_ducking_step;
}
input_buffer += samples_to_duck;
*ducking_transition_samples_remaining -= samples_to_duck;
input_samples_to_duck -= samples_to_duck;
}
}
if ((*current_ducking_db_reduction > 0) && (input_samples_to_duck > 0)) {
// Audio is ducked, but its not in the middle of a transition step
uint8_t safe_db_reduction_index =
clamp<uint8_t>(*current_ducking_db_reduction, 0, DECIBEL_REDUCTION_TABLE.size() - 1);
int16_t q15_scale_factor = DECIBEL_REDUCTION_TABLE[safe_db_reduction_index];
audio::scale_audio_samples(input_buffer, input_buffer, q15_scale_factor, input_samples_to_duck);
}
}
void MixerSpeaker::dump_config() {
ESP_LOGCONFIG(TAG, "Speaker Mixer:");
ESP_LOGCONFIG(TAG, " Number of output channels: %u", this->output_channels_);
}
void MixerSpeaker::setup() {
this->event_group_ = xEventGroupCreate();
if (this->event_group_ == nullptr) {
ESP_LOGE(TAG, "Failed to create event group");
this->mark_failed();
return;
}
}
void MixerSpeaker::loop() {
uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
if (event_group_bits & MixerEventGroupBits::STATE_STARTING) {
ESP_LOGD(TAG, "Starting speaker mixer");
xEventGroupClearBits(this->event_group_, MixerEventGroupBits::STATE_STARTING);
}
if (event_group_bits & MixerEventGroupBits::ERR_ESP_NO_MEM) {
this->status_set_error("Failed to allocate the mixer's internal buffer");
xEventGroupClearBits(this->event_group_, MixerEventGroupBits::ERR_ESP_NO_MEM);
}
if (event_group_bits & MixerEventGroupBits::STATE_RUNNING) {
ESP_LOGD(TAG, "Started speaker mixer");
this->status_clear_error();
xEventGroupClearBits(this->event_group_, MixerEventGroupBits::STATE_RUNNING);
}
if (event_group_bits & MixerEventGroupBits::STATE_STOPPING) {
ESP_LOGD(TAG, "Stopping speaker mixer");
xEventGroupClearBits(this->event_group_, MixerEventGroupBits::STATE_STOPPING);
}
if (event_group_bits & MixerEventGroupBits::STATE_STOPPED) {
if (this->delete_task_() == ESP_OK) {
xEventGroupClearBits(this->event_group_, MixerEventGroupBits::ALL_BITS);
}
}
if (this->task_handle_ != nullptr) {
bool all_stopped = true;
for (auto &speaker : this->source_speakers_) {
all_stopped &= speaker->is_stopped();
}
if (all_stopped) {
this->stop();
}
}
}
esp_err_t MixerSpeaker::start(audio::AudioStreamInfo &stream_info) {
if (!this->audio_stream_info_.has_value()) {
if (stream_info.get_bits_per_sample() != 16) {
// Audio streams that don't have 16 bits per sample are not supported
return ESP_ERR_NOT_SUPPORTED;
}
this->audio_stream_info_ = audio::AudioStreamInfo(stream_info.get_bits_per_sample(), this->output_channels_,
stream_info.get_sample_rate());
this->output_speaker_->set_audio_stream_info(this->audio_stream_info_.value());
} else {
if (!this->queue_mode_ && (stream_info.get_sample_rate() != this->audio_stream_info_.value().get_sample_rate())) {
// The two audio streams must have the same sample rate to mix properly if not in queue mode
return ESP_ERR_INVALID_ARG;
}
}
return this->start_task_();
}
esp_err_t MixerSpeaker::start_task_() {
if (this->task_stack_buffer_ == nullptr) {
if (this->task_stack_in_psram_) {
RAMAllocator<StackType_t> stack_allocator(RAMAllocator<StackType_t>::ALLOC_EXTERNAL);
this->task_stack_buffer_ = stack_allocator.allocate(TASK_STACK_SIZE);
} else {
RAMAllocator<StackType_t> stack_allocator(RAMAllocator<StackType_t>::ALLOC_INTERNAL);
this->task_stack_buffer_ = stack_allocator.allocate(TASK_STACK_SIZE);
}
}
if (this->task_stack_buffer_ == nullptr) {
return ESP_ERR_NO_MEM;
}
if (this->task_handle_ == nullptr) {
this->task_handle_ = xTaskCreateStatic(audio_mixer_task, "mixer", TASK_STACK_SIZE, (void *) this,
MIXER_TASK_PRIORITY, this->task_stack_buffer_, &this->task_stack_);
}
if (this->task_handle_ == nullptr) {
return ESP_ERR_INVALID_STATE;
}
return ESP_OK;
}
esp_err_t MixerSpeaker::delete_task_() {
if (!this->task_created_) {
this->task_handle_ = nullptr;
if (this->task_stack_buffer_ != nullptr) {
if (this->task_stack_in_psram_) {
RAMAllocator<StackType_t> stack_allocator(RAMAllocator<StackType_t>::ALLOC_EXTERNAL);
stack_allocator.deallocate(this->task_stack_buffer_, TASK_STACK_SIZE);
} else {
RAMAllocator<StackType_t> stack_allocator(RAMAllocator<StackType_t>::ALLOC_INTERNAL);
stack_allocator.deallocate(this->task_stack_buffer_, TASK_STACK_SIZE);
}
this->task_stack_buffer_ = nullptr;
}
return ESP_OK;
}
return ESP_ERR_INVALID_STATE;
}
void MixerSpeaker::stop() { xEventGroupSetBits(this->event_group_, MixerEventGroupBits::COMMAND_STOP); }
void MixerSpeaker::copy_frames(const int16_t *input_buffer, audio::AudioStreamInfo input_stream_info,
int16_t *output_buffer, audio::AudioStreamInfo output_stream_info,
uint32_t frames_to_transfer) {
uint8_t input_channels = input_stream_info.get_channels();
uint8_t output_channels = output_stream_info.get_channels();
const uint8_t max_input_channel_index = input_channels - 1;
if (input_channels == output_channels) {
size_t bytes_to_copy = input_stream_info.frames_to_bytes(frames_to_transfer);
memcpy(output_buffer, input_buffer, bytes_to_copy);
return;
}
for (uint32_t frame_index = 0; frame_index < frames_to_transfer; ++frame_index) {
for (uint8_t output_channel_index = 0; output_channel_index < output_channels; ++output_channel_index) {
uint8_t input_channel_index = std::min(output_channel_index, max_input_channel_index);
output_buffer[output_channels * frame_index + output_channel_index] =
input_buffer[input_channels * frame_index + input_channel_index];
}
}
}
void MixerSpeaker::mix_audio_samples(const int16_t *primary_buffer, audio::AudioStreamInfo primary_stream_info,
const int16_t *secondary_buffer, audio::AudioStreamInfo secondary_stream_info,
int16_t *output_buffer, audio::AudioStreamInfo output_stream_info,
uint32_t frames_to_mix) {
const uint8_t primary_channels = primary_stream_info.get_channels();
const uint8_t secondary_channels = secondary_stream_info.get_channels();
const uint8_t output_channels = output_stream_info.get_channels();
const uint8_t max_primary_channel_index = primary_channels - 1;
const uint8_t max_secondary_channel_index = secondary_channels - 1;
for (uint32_t frames_index = 0; frames_index < frames_to_mix; ++frames_index) {
for (uint8_t output_channel_index = 0; output_channel_index < output_channels; ++output_channel_index) {
const uint32_t secondary_channel_index = std::min(output_channel_index, max_secondary_channel_index);
const int32_t secondary_sample = secondary_buffer[frames_index * secondary_channels + secondary_channel_index];
const uint32_t primary_channel_index = std::min(output_channel_index, max_primary_channel_index);
const int32_t primary_sample =
static_cast<int32_t>(primary_buffer[frames_index * primary_channels + primary_channel_index]);
const int32_t added_sample = secondary_sample + primary_sample;
output_buffer[frames_index * output_channels + output_channel_index] =
static_cast<int16_t>(clamp<int32_t>(added_sample, MIN_AUDIO_SAMPLE_VALUE, MAX_AUDIO_SAMPLE_VALUE));
}
}
}
void MixerSpeaker::audio_mixer_task(void *params) {
MixerSpeaker *this_mixer = (MixerSpeaker *) params;
xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_STARTING);
this_mixer->task_created_ = true;
std::unique_ptr<audio::AudioSinkTransferBuffer> output_transfer_buffer = audio::AudioSinkTransferBuffer::create(
this_mixer->audio_stream_info_.value().ms_to_bytes(TRANSFER_BUFFER_DURATION_MS));
if (output_transfer_buffer == nullptr) {
xEventGroupSetBits(this_mixer->event_group_,
MixerEventGroupBits::STATE_STOPPED | MixerEventGroupBits::ERR_ESP_NO_MEM);
this_mixer->task_created_ = false;
vTaskDelete(nullptr);
}
output_transfer_buffer->set_sink(this_mixer->output_speaker_);
xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_RUNNING);
bool sent_finished = false;
while (true) {
uint32_t event_group_bits = xEventGroupGetBits(this_mixer->event_group_);
if (event_group_bits & MixerEventGroupBits::COMMAND_STOP) {
break;
}
output_transfer_buffer->transfer_data_to_sink(pdMS_TO_TICKS(TASK_DELAY_MS));
const uint32_t output_frames_free =
this_mixer->audio_stream_info_.value().bytes_to_frames(output_transfer_buffer->free());
std::vector<SourceSpeaker *> speakers_with_data;
std::vector<std::shared_ptr<audio::AudioSourceTransferBuffer>> transfer_buffers_with_data;
for (auto &speaker : this_mixer->source_speakers_) {
if (speaker->get_transfer_buffer().use_count() > 0) {
std::shared_ptr<audio::AudioSourceTransferBuffer> transfer_buffer = speaker->get_transfer_buffer().lock();
speaker->process_data_from_source(0); // Transfers and ducks audio from source ring buffers
if ((transfer_buffer->available() > 0) && !speaker->get_pause_state()) {
// Store the locked transfer buffers in their own vector to avoid releasing ownership until after the loop
transfer_buffers_with_data.push_back(transfer_buffer);
speakers_with_data.push_back(speaker);
}
}
}
if (transfer_buffers_with_data.empty()) {
// No audio available for transferring, block task temporarily
delay(TASK_DELAY_MS);
continue;
}
uint32_t frames_to_mix = output_frames_free;
if ((transfer_buffers_with_data.size() == 1) || this_mixer->queue_mode_) {
// Only one speaker has audio data, just copy samples over
audio::AudioStreamInfo active_stream_info = speakers_with_data[0]->get_audio_stream_info();
if (active_stream_info.get_sample_rate() ==
this_mixer->output_speaker_->get_audio_stream_info().get_sample_rate()) {
// Speaker's sample rate matches the output speaker's, copy directly
const uint32_t frames_available_in_buffer =
active_stream_info.bytes_to_frames(transfer_buffers_with_data[0]->available());
frames_to_mix = std::min(frames_to_mix, frames_available_in_buffer);
copy_frames(reinterpret_cast<int16_t *>(transfer_buffers_with_data[0]->get_buffer_start()), active_stream_info,
reinterpret_cast<int16_t *>(output_transfer_buffer->get_buffer_end()),
this_mixer->audio_stream_info_.value(), frames_to_mix);
// Update source speaker buffer length
transfer_buffers_with_data[0]->decrease_buffer_length(active_stream_info.frames_to_bytes(frames_to_mix));
speakers_with_data[0]->accumulated_frames_read_ += frames_to_mix;
// Add new audio duration to the source speaker pending playback
speakers_with_data[0]->pending_playback_ms_ +=
active_stream_info.frames_to_milliseconds_with_remainder(&speakers_with_data[0]->accumulated_frames_read_);
// Update output transfer buffer length
output_transfer_buffer->increase_buffer_length(
this_mixer->audio_stream_info_.value().frames_to_bytes(frames_to_mix));
} else {
// Speaker's stream info doesn't match the output speaker's, so it's a new source speaker
if (!this_mixer->output_speaker_->is_stopped()) {
if (!sent_finished) {
this_mixer->output_speaker_->finish();
sent_finished = true; // Avoid repeatedly sending the finish command
}
} else {
// Speaker has finished writing the current audio, update the stream information and restart the speaker
this_mixer->audio_stream_info_ =
audio::AudioStreamInfo(active_stream_info.get_bits_per_sample(), this_mixer->output_channels_,
active_stream_info.get_sample_rate());
this_mixer->output_speaker_->set_audio_stream_info(this_mixer->audio_stream_info_.value());
this_mixer->output_speaker_->start();
sent_finished = false;
}
}
} else {
// Determine how many frames to mix
for (int i = 0; i < transfer_buffers_with_data.size(); ++i) {
const uint32_t frames_available_in_buffer =
speakers_with_data[i]->get_audio_stream_info().bytes_to_frames(transfer_buffers_with_data[i]->available());
frames_to_mix = std::min(frames_to_mix, frames_available_in_buffer);
}
int16_t *primary_buffer = reinterpret_cast<int16_t *>(transfer_buffers_with_data[0]->get_buffer_start());
audio::AudioStreamInfo primary_stream_info = speakers_with_data[0]->get_audio_stream_info();
// Mix two streams together
for (int i = 1; i < transfer_buffers_with_data.size(); ++i) {
mix_audio_samples(primary_buffer, primary_stream_info,
reinterpret_cast<int16_t *>(transfer_buffers_with_data[i]->get_buffer_start()),
speakers_with_data[i]->get_audio_stream_info(),
reinterpret_cast<int16_t *>(output_transfer_buffer->get_buffer_end()),
this_mixer->audio_stream_info_.value(), frames_to_mix);
speakers_with_data[i]->pending_playback_ms_ +=
speakers_with_data[i]->get_audio_stream_info().frames_to_milliseconds_with_remainder(
&speakers_with_data[i]->accumulated_frames_read_);
if (i != transfer_buffers_with_data.size() - 1) {
// Need to mix more streams together, point primary buffer and stream info to the already mixed output
primary_buffer = reinterpret_cast<int16_t *>(output_transfer_buffer->get_buffer_end());
primary_stream_info = this_mixer->audio_stream_info_.value();
}
}
// Update source transfer buffer lengths and add new audio durations to the source speaker pending playbacks
for (int i = 0; i < transfer_buffers_with_data.size(); ++i) {
transfer_buffers_with_data[i]->decrease_buffer_length(
speakers_with_data[i]->get_audio_stream_info().frames_to_bytes(frames_to_mix));
speakers_with_data[i]->accumulated_frames_read_ += frames_to_mix;
speakers_with_data[i]->pending_playback_ms_ +=
speakers_with_data[i]->get_audio_stream_info().frames_to_milliseconds_with_remainder(
&speakers_with_data[i]->accumulated_frames_read_);
}
// Update output transfer buffer length
output_transfer_buffer->increase_buffer_length(
this_mixer->audio_stream_info_.value().frames_to_bytes(frames_to_mix));
}
}
xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_STOPPING);
output_transfer_buffer.reset();
xEventGroupSetBits(this_mixer->event_group_, MixerEventGroupBits::STATE_STOPPED);
this_mixer->task_created_ = false;
vTaskDelete(nullptr);
}
} // namespace mixer_speaker
} // namespace esphome
#endif

View File

@ -0,0 +1,207 @@
#pragma once
#ifdef USE_ESP32
#include "esphome/components/audio/audio.h"
#include "esphome/components/audio/audio_transfer_buffer.h"
#include "esphome/components/speaker/speaker.h"
#include "esphome/core/component.h"
#include <freertos/event_groups.h>
#include <freertos/FreeRTOS.h>
namespace esphome {
namespace mixer_speaker {
/* Classes for mixing several source speaker audio streams and writing it to another speaker component.
* - Volume controls are passed through to the output speaker
* - Directly handles pausing at the SourceSpeaker level; pause state is not passed through to the output speaker.
* - Audio sent to the SourceSpeaker's must have 16 bits per sample.
* - Audio sent to the SourceSpeaker can have any number of channels. They are duplicated or ignored as needed to match
* the number of channels required for the output speaker.
* - In queue mode, the audio sent to the SoureSpeakers can have different sample rates.
* - In non-queue mode, the audio sent to the SourceSpeakers must have the same sample rates.
* - SourceSpeaker has an internal ring buffer. It also allocates a shared_ptr for an AudioTranserBuffer object.
* - Audio Data Flow:
* - Audio data played on a SourceSpeaker first writes to its internal ring buffer.
* - MixerSpeaker task temporarily takes shared ownership of each SourceSpeaker's AudioTransferBuffer.
* - MixerSpeaker calls SourceSpeaker's `process_data_from_source`, which tranfers audio from the SourceSpeaker's
* ring buffer to its AudioTransferBuffer. Audio ducking is applied at this step.
* - In queue mode, MixerSpeaker prioritizes the earliest configured SourceSpeaker with audio data. Audio data is
* sent to the output speaker.
* - In non-queue mode, MixerSpeaker adds all the audio data in each SourceSpeaker into one stream that is written
* to the output speaker.
*/
class MixerSpeaker;
class SourceSpeaker : public speaker::Speaker, public Component {
public:
void dump_config() override;
void setup() override;
void loop() override;
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 this->play(data, length, 0); }
void start() override;
void stop() override;
void finish() override;
bool has_buffered_data() const override;
/// @brief Mute state changes are passed to the parent's output speaker
void set_mute_state(bool mute_state) override;
/// @brief Volume state changes are passed to the parent's output speaker
void set_volume(float volume) override;
void set_pause_state(bool pause_state) override { this->pause_state_ = pause_state; }
bool get_pause_state() const override { return this->pause_state_; }
/// @brief Transfers audio from the ring buffer into the transfer buffer. Ducks audio while transferring.
/// @param ticks_to_wait FreeRTOS ticks to wait while waiting to read from the ring buffer.
/// @return Number of bytes transferred from the ring buffer.
size_t process_data_from_source(TickType_t ticks_to_wait);
/// @brief Sets the ducking level for the source speaker.
/// @param decibel_reduction (uint8_t) The dB reduction level. For example, 0 is no change, 10 is a reduction by 10 dB
/// @param duration (uint32_t) The number of milliseconds to transition from the current level to the new level
void apply_ducking(uint8_t decibel_reduction, uint32_t duration);
void set_buffer_duration(uint32_t buffer_duration_ms) { this->buffer_duration_ms_ = buffer_duration_ms; }
void set_parent(MixerSpeaker *parent) { this->parent_ = parent; }
void set_timeout(uint32_t ms) { this->timeout_ms_ = ms; }
std::weak_ptr<audio::AudioSourceTransferBuffer> get_transfer_buffer() { return this->transfer_buffer_; }
protected:
friend class MixerSpeaker;
esp_err_t start_();
void stop_();
/// @brief Ducks audio samples by a specified amount. When changing the ducking amount, it can transition gradually
/// over a specified amount of samples.
/// @param input_buffer buffer with audio samples to be ducked in place
/// @param input_samples_to_duck number of samples to process in ``input_buffer``
/// @param current_ducking_db_reduction pointer to the current dB reduction
/// @param ducking_transition_samples_remaining pointer to the total number of samples left before the the
/// transition is finished
/// @param samples_per_ducking_step total number of samples per ducking step for the transition
/// @param db_change_per_ducking_step the change in dB reduction per step
static void duck_samples(int16_t *input_buffer, uint32_t input_samples_to_duck, int8_t *current_ducking_db_reduction,
uint32_t *ducking_transition_samples_remaining, uint32_t samples_per_ducking_step,
int8_t db_change_per_ducking_step);
MixerSpeaker *parent_;
std::shared_ptr<audio::AudioSourceTransferBuffer> transfer_buffer_;
std::weak_ptr<RingBuffer> ring_buffer_;
uint32_t buffer_duration_ms_;
uint32_t last_seen_data_ms_{0};
optional<uint32_t> timeout_ms_;
bool stop_gracefully_{false};
bool pause_state_{false};
int8_t target_ducking_db_reduction_{0};
int8_t current_ducking_db_reduction_{0};
int8_t db_change_per_ducking_step_{1};
uint32_t ducking_transition_samples_remaining_{0};
uint32_t samples_per_ducking_step_{0};
uint32_t accumulated_frames_read_{0};
uint32_t pending_playback_ms_{0};
};
class MixerSpeaker : public Component {
public:
void dump_config() override;
void setup() override;
void loop() override;
void add_source_speaker(SourceSpeaker *source_speaker) { this->source_speakers_.push_back(source_speaker); }
/// @brief Starts the mixer task. Called by a source speaker giving the current audio stream information
/// @param stream_info The calling source speakers audio stream information
/// @return ESP_ERR_NOT_SUPPORTED if the incoming stream is incompatible due to unsupported bits per sample
/// ESP_ERR_INVALID_ARG if the incoming stream is incompatible to be mixed with the other input audio stream
/// ESP_ERR_NO_MEM if there isn't enough memory for the task's stack
/// ESP_ERR_INVALID_STATE if the task fails to start
/// ESP_OK if the incoming stream is compatible and the mixer task starts
esp_err_t start(audio::AudioStreamInfo &stream_info);
void stop();
void set_output_channels(uint8_t output_channels) { this->output_channels_ = output_channels; }
void set_output_speaker(speaker::Speaker *speaker) { this->output_speaker_ = speaker; }
void set_queue_mode(bool queue_mode) { this->queue_mode_ = queue_mode; }
void set_task_stack_in_psram(bool task_stack_in_psram) { this->task_stack_in_psram_ = task_stack_in_psram; }
speaker::Speaker *get_output_speaker() const { return this->output_speaker_; }
protected:
/// @brief Copies audio frames from the input buffer to the output buffer taking into account the number of channels
/// in each stream. If the output stream has more channels, the input samples are duplicated. If the output stream has
/// less channels, the extra channel input samples are dropped.
/// @param input_buffer
/// @param input_stream_info
/// @param output_buffer
/// @param output_stream_info
/// @param frames_to_transfer number of frames (consisting of a sample for each channel) to copy from the input buffer
static void copy_frames(const int16_t *input_buffer, audio::AudioStreamInfo input_stream_info, int16_t *output_buffer,
audio::AudioStreamInfo output_stream_info, uint32_t frames_to_transfer);
/// @brief Mixes the primary and secondary streams taking into account the number of channels in each stream. Primary
/// and secondary samples are duplicated or dropped as necessary to ensure the output stream has the configured number
/// of channels. Output samples are clamped to the corresponding int16 min or max values if the mixed sample
/// overflows.
/// @param primary_buffer (int16_t *) samples buffer for the primary stream
/// @param primary_stream_info stream info for the primary stream
/// @param secondary_buffer (int16_t *) samples buffer for secondary stream
/// @param secondary_stream_info stream info for the secondary stream
/// @param output_buffer (int16_t *) buffer for the mixed samples
/// @param output_stream_info stream info for the output buffer
/// @param frames_to_mix number of frames in the primary and secondary buffers to mix together
static void mix_audio_samples(const int16_t *primary_buffer, audio::AudioStreamInfo primary_stream_info,
const int16_t *secondary_buffer, audio::AudioStreamInfo secondary_stream_info,
int16_t *output_buffer, audio::AudioStreamInfo output_stream_info,
uint32_t frames_to_mix);
static void audio_mixer_task(void *params);
/// @brief Starts the mixer task after allocating memory for the task stack.
/// @return ESP_ERR_NO_MEM if there isn't enough memory for the task's stack
/// ESP_ERR_INVALID_STATE if the task didn't start
/// ESP_OK if successful
esp_err_t start_task_();
/// @brief If the task is stopped, it sets the task handle to the nullptr and deallocates its stack
/// @return ESP_OK if the task was stopped, ESP_ERR_INVALID_STATE otherwise.
esp_err_t delete_task_();
EventGroupHandle_t event_group_{nullptr};
std::vector<SourceSpeaker *> source_speakers_;
speaker::Speaker *output_speaker_{nullptr};
uint8_t output_channels_;
bool queue_mode_;
bool task_stack_in_psram_{false};
bool task_created_{false};
TaskHandle_t task_handle_{nullptr};
StaticTask_t task_stack_;
StackType_t *task_stack_buffer_{nullptr};
optional<audio::AudioStreamInfo> audio_stream_info_;
};
} // namespace mixer_speaker
} // namespace esphome
#endif

View File

@ -1,6 +1,6 @@
from esphome.const import CONF_ID
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import CONF_ID
CODEOWNERS = ["@esphome/core"]
@ -11,9 +11,7 @@ CONF_FLASH_WRITE_INTERVAL = "flash_write_interval"
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(IntervalSyncer),
cv.Optional(
CONF_FLASH_WRITE_INTERVAL, default="60s"
): cv.positive_time_period_milliseconds,
cv.Optional(CONF_FLASH_WRITE_INTERVAL, default="60s"): cv.update_interval,
}
).extend(cv.COMPONENT_SCHEMA)

View File

@ -8,15 +8,22 @@ namespace preferences {
class IntervalSyncer : public Component {
public:
void set_write_interval(uint32_t write_interval) { write_interval_ = write_interval; }
void set_write_interval(uint32_t write_interval) { this->write_interval_ = write_interval; }
void setup() override {
set_interval(write_interval_, []() { global_preferences->sync(); });
if (this->write_interval_ != 0) {
set_interval(this->write_interval_, []() { global_preferences->sync(); });
}
}
void loop() override {
if (this->write_interval_ == 0) {
global_preferences->sync();
}
}
void on_shutdown() override { global_preferences->sync(); }
float get_setup_priority() const override { return setup_priority::BUS; }
protected:
uint32_t write_interval_;
uint32_t write_interval_{60000};
};
} // namespace preferences

View File

@ -77,6 +77,12 @@ void PrometheusHandler::handleRequest(AsyncWebServerRequest *req) {
this->media_player_row_(stream, obj, area, node, friendly_name);
#endif
#ifdef USE_UPDATE
this->update_entity_type_(stream);
for (auto *obj : App.get_updates())
this->update_entity_row_(stream, obj, area, node, friendly_name);
#endif
req->send(stream);
}
@ -679,6 +685,91 @@ void PrometheusHandler::media_player_row_(AsyncResponseStream *stream, media_pla
}
#endif
#ifdef USE_UPDATE
void PrometheusHandler::update_entity_type_(AsyncResponseStream *stream) {
stream->print(F("#TYPE esphome_update_entity_state gauge\n"));
stream->print(F("#TYPE esphome_update_entity_info gauge\n"));
stream->print(F("#TYPE esphome_update_entity_failed gauge\n"));
}
void PrometheusHandler::handle_update_state_(AsyncResponseStream *stream, update::UpdateState state) {
switch (state) {
case update::UpdateState::UPDATE_STATE_UNKNOWN:
stream->print("unknown");
break;
case update::UpdateState::UPDATE_STATE_NO_UPDATE:
stream->print("none");
break;
case update::UpdateState::UPDATE_STATE_AVAILABLE:
stream->print("available");
break;
case update::UpdateState::UPDATE_STATE_INSTALLING:
stream->print("installing");
break;
default:
stream->print("invalid");
break;
}
}
void PrometheusHandler::update_entity_row_(AsyncResponseStream *stream, update::UpdateEntity *obj, std::string &area,
std::string &node, std::string &friendly_name) {
if (obj->is_internal() && !this->include_internal_)
return;
if (obj->has_state()) {
// We have a valid value, output this value
stream->print(F("esphome_update_entity_failed{id=\""));
stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 0\n"));
// First update state
stream->print(F("esphome_update_entity_state{id=\""));
stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str());
stream->print(F("\",value=\""));
handle_update_state_(stream, obj->state);
stream->print(F("\"} "));
stream->print(F("1.0"));
stream->print(F("\n"));
// Next update info
stream->print(F("esphome_update_entity_info{id=\""));
stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str());
stream->print(F("\",current_version=\""));
stream->print(obj->update_info.current_version.c_str());
stream->print(F("\",latest_version=\""));
stream->print(obj->update_info.latest_version.c_str());
stream->print(F("\",title=\""));
stream->print(obj->update_info.title.c_str());
stream->print(F("\"} "));
stream->print(F("1.0"));
stream->print(F("\n"));
} else {
// Invalid state
stream->print(F("esphome_update_entity_failed{id=\""));
stream->print(relabel_id_(obj).c_str());
add_area_label_(stream, area);
add_node_label_(stream, node);
add_friendly_name_label_(stream, friendly_name);
stream->print(F("\",name=\""));
stream->print(relabel_name_(obj).c_str());
stream->print(F("\"} 1\n"));
}
}
#endif
} // namespace prometheus
} // namespace esphome
#endif

View File

@ -75,7 +75,7 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
#ifdef USE_BINARY_SENSOR
/// Return the type for prometheus
void binary_sensor_type_(AsyncResponseStream *stream);
/// Return the sensor state as prometheus data point
/// Return the binary sensor state as prometheus data point
void binary_sensor_row_(AsyncResponseStream *stream, binary_sensor::BinarySensor *obj, std::string &area,
std::string &node, std::string &friendly_name);
#endif
@ -83,7 +83,7 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
#ifdef USE_FAN
/// Return the type for prometheus
void fan_type_(AsyncResponseStream *stream);
/// Return the sensor state as prometheus data point
/// Return the fan state as prometheus data point
void fan_row_(AsyncResponseStream *stream, fan::Fan *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif
@ -91,7 +91,7 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
#ifdef USE_LIGHT
/// Return the type for prometheus
void light_type_(AsyncResponseStream *stream);
/// Return the Light Values state as prometheus data point
/// Return the light values state as prometheus data point
void light_row_(AsyncResponseStream *stream, light::LightState *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif
@ -99,7 +99,7 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
#ifdef USE_COVER
/// Return the type for prometheus
void cover_type_(AsyncResponseStream *stream);
/// Return the switch Values state as prometheus data point
/// Return the cover values state as prometheus data point
void cover_row_(AsyncResponseStream *stream, cover::Cover *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif
@ -107,7 +107,7 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
#ifdef USE_SWITCH
/// Return the type for prometheus
void switch_type_(AsyncResponseStream *stream);
/// Return the switch Values state as prometheus data point
/// Return the switch values state as prometheus data point
void switch_row_(AsyncResponseStream *stream, switch_::Switch *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif
@ -115,7 +115,7 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
#ifdef USE_LOCK
/// Return the type for prometheus
void lock_type_(AsyncResponseStream *stream);
/// Return the lock Values state as prometheus data point
/// Return the lock values state as prometheus data point
void lock_row_(AsyncResponseStream *stream, lock::Lock *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif
@ -123,7 +123,7 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
#ifdef USE_TEXT_SENSOR
/// Return the type for prometheus
void text_sensor_type_(AsyncResponseStream *stream);
/// Return the lock Values state as prometheus data point
/// Return the text sensor values state as prometheus data point
void text_sensor_row_(AsyncResponseStream *stream, text_sensor::TextSensor *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif
@ -131,7 +131,7 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
#ifdef USE_NUMBER
/// Return the type for prometheus
void number_type_(AsyncResponseStream *stream);
/// Return the sensor state as prometheus data point
/// Return the number state as prometheus data point
void number_row_(AsyncResponseStream *stream, number::Number *obj, std::string &area, std::string &node,
std::string &friendly_name);
#endif
@ -147,11 +147,20 @@ class PrometheusHandler : public AsyncWebHandler, public Component {
#ifdef USE_MEDIA_PLAYER
/// Return the type for prometheus
void media_player_type_(AsyncResponseStream *stream);
/// Return the select state as prometheus data point
/// Return the media player state as prometheus data point
void media_player_row_(AsyncResponseStream *stream, media_player::MediaPlayer *obj, std::string &area,
std::string &node, std::string &friendly_name);
#endif
#ifdef USE_UPDATE
/// Return the type for prometheus
void update_entity_type_(AsyncResponseStream *stream);
/// Return the update state and info as prometheus data point
void update_entity_row_(AsyncResponseStream *stream, update::UpdateEntity *obj, std::string &area, std::string &node,
std::string &friendly_name);
void handle_update_state_(AsyncResponseStream *stream, update::UpdateState state);
#endif
web_server_base::WebServerBase *base_;
bool include_internal_{false};
std::map<EntityBase *, std::string> relabel_map_id_;

View File

View File

@ -0,0 +1,103 @@
import esphome.codegen as cg
from esphome.components import audio, esp32, speaker
import esphome.config_validation as cv
from esphome.const import (
CONF_BITS_PER_SAMPLE,
CONF_BUFFER_DURATION,
CONF_FILTERS,
CONF_ID,
CONF_NUM_CHANNELS,
CONF_OUTPUT_SPEAKER,
CONF_SAMPLE_RATE,
CONF_TASK_STACK_IN_PSRAM,
PLATFORM_ESP32,
)
from esphome.core.entity_helpers import inherit_property_from
AUTO_LOAD = ["audio"]
CODEOWNERS = ["@kahrendt"]
resampler_ns = cg.esphome_ns.namespace("resampler")
ResamplerSpeaker = resampler_ns.class_(
"ResamplerSpeaker", cg.Component, speaker.Speaker
)
CONF_TAPS = "taps"
def _set_stream_limits(config):
audio.set_stream_limits(
min_bits_per_sample=16,
max_bits_per_sample=32,
)(config)
return config
def _validate_audio_compatability(config):
inherit_property_from(CONF_BITS_PER_SAMPLE, CONF_OUTPUT_SPEAKER)(config)
inherit_property_from(CONF_NUM_CHANNELS, CONF_OUTPUT_SPEAKER)(config)
inherit_property_from(CONF_SAMPLE_RATE, CONF_OUTPUT_SPEAKER)(config)
audio.final_validate_audio_schema(
"source_speaker",
audio_device=CONF_OUTPUT_SPEAKER,
bits_per_sample=config.get(CONF_BITS_PER_SAMPLE),
channels=config.get(CONF_NUM_CHANNELS),
sample_rate=config.get(CONF_SAMPLE_RATE),
)(config)
def _validate_taps(taps):
value = cv.int_range(min=16, max=128)(taps)
if value % 4 != 0:
raise cv.Invalid("Number of taps must be divisible by 4")
return value
CONFIG_SCHEMA = cv.All(
speaker.SPEAKER_SCHEMA.extend(
{
cv.GenerateID(): cv.declare_id(ResamplerSpeaker),
cv.Required(CONF_OUTPUT_SPEAKER): cv.use_id(speaker.Speaker),
cv.Optional(
CONF_BUFFER_DURATION, default="100ms"
): cv.positive_time_period_milliseconds,
cv.SplitDefault(CONF_TASK_STACK_IN_PSRAM, esp32_idf=False): cv.All(
cv.boolean, cv.only_with_esp_idf
),
cv.Optional(CONF_FILTERS, default=16): cv.int_range(min=2, max=1024),
cv.Optional(CONF_TAPS, default=16): _validate_taps,
}
).extend(cv.COMPONENT_SCHEMA),
cv.only_on([PLATFORM_ESP32]),
_set_stream_limits,
)
FINAL_VALIDATE_SCHEMA = _validate_audio_compatability
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
await speaker.register_speaker(var, config)
output_spkr = await cg.get_variable(config[CONF_OUTPUT_SPEAKER])
cg.add(var.set_output_speaker(output_spkr))
cg.add(var.set_buffer_duration(config[CONF_BUFFER_DURATION]))
if task_stack_in_psram := config.get(CONF_TASK_STACK_IN_PSRAM):
cg.add(var.set_task_stack_in_psram(task_stack_in_psram))
if task_stack_in_psram:
if config[CONF_TASK_STACK_IN_PSRAM]:
esp32.add_idf_sdkconfig_option(
"CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY", True
)
cg.add(var.set_target_bits_per_sample(config[CONF_BITS_PER_SAMPLE]))
cg.add(var.set_target_sample_rate(config[CONF_SAMPLE_RATE]))
cg.add(var.set_filters(config[CONF_FILTERS]))
cg.add(var.set_taps(config[CONF_TAPS]))

View File

@ -0,0 +1,318 @@
#include "resampler_speaker.h"
#ifdef USE_ESP32
#include "esphome/components/audio/audio_resampler.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <algorithm>
#include <cstring>
namespace esphome {
namespace resampler {
static const UBaseType_t RESAMPLER_TASK_PRIORITY = 1;
static const uint32_t TRANSFER_BUFFER_DURATION_MS = 50;
static const uint32_t TASK_DELAY_MS = 20;
static const uint32_t TASK_STACK_SIZE = 3072;
static const char *const TAG = "resampler_speaker";
enum ResamplingEventGroupBits : uint32_t {
COMMAND_STOP = (1 << 0), // stops the resampler task
STATE_STARTING = (1 << 10),
STATE_RUNNING = (1 << 11),
STATE_STOPPING = (1 << 12),
STATE_STOPPED = (1 << 13),
ERR_ESP_NO_MEM = (1 << 19),
ERR_ESP_NOT_SUPPORTED = (1 << 20),
ERR_ESP_FAIL = (1 << 21),
ALL_BITS = 0x00FFFFFF, // All valid FreeRTOS event group bits
};
void ResamplerSpeaker::setup() {
this->event_group_ = xEventGroupCreate();
if (this->event_group_ == nullptr) {
ESP_LOGE(TAG, "Failed to create event group");
this->mark_failed();
return;
}
this->output_speaker_->add_audio_output_callback(
[this](uint32_t new_playback_ms, uint32_t remainder_us, uint32_t pending_ms, uint32_t write_timestamp) {
int32_t adjustment = this->playback_differential_ms_;
this->playback_differential_ms_ -= adjustment;
int32_t adjusted_playback_ms = static_cast<int32_t>(new_playback_ms) + adjustment;
this->audio_output_callback_(adjusted_playback_ms, remainder_us, pending_ms, write_timestamp);
});
}
void ResamplerSpeaker::loop() {
uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
if (event_group_bits & ResamplingEventGroupBits::STATE_STARTING) {
ESP_LOGD(TAG, "Starting resampler task");
xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::STATE_STARTING);
}
if (event_group_bits & ResamplingEventGroupBits::ERR_ESP_NO_MEM) {
this->status_set_error("Resampler task failed to allocate the internal buffers");
xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::ERR_ESP_NO_MEM);
this->state_ = speaker::STATE_STOPPING;
}
if (event_group_bits & ResamplingEventGroupBits::ERR_ESP_NOT_SUPPORTED) {
this->status_set_error("Cannot resample due to an unsupported audio stream");
xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::ERR_ESP_NOT_SUPPORTED);
this->state_ = speaker::STATE_STOPPING;
}
if (event_group_bits & ResamplingEventGroupBits::ERR_ESP_FAIL) {
this->status_set_error("Resampler task failed");
xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::ERR_ESP_FAIL);
this->state_ = speaker::STATE_STOPPING;
}
if (event_group_bits & ResamplingEventGroupBits::STATE_RUNNING) {
ESP_LOGD(TAG, "Started resampler task");
this->status_clear_error();
xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::STATE_RUNNING);
}
if (event_group_bits & ResamplingEventGroupBits::STATE_STOPPING) {
ESP_LOGD(TAG, "Stopping resampler task");
xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::STATE_STOPPING);
}
if (event_group_bits & ResamplingEventGroupBits::STATE_STOPPED) {
if (this->delete_task_() == ESP_OK) {
ESP_LOGD(TAG, "Stopped resampler task");
xEventGroupClearBits(this->event_group_, ResamplingEventGroupBits::ALL_BITS);
}
}
switch (this->state_) {
case speaker::STATE_STARTING: {
esp_err_t err = this->start_();
if (err == ESP_OK) {
this->status_clear_error();
this->state_ = speaker::STATE_RUNNING;
} else {
switch (err) {
case ESP_ERR_INVALID_STATE:
this->status_set_error("Failed to start resampler: resampler task failed to start");
break;
case ESP_ERR_NO_MEM:
this->status_set_error("Failed to start resampler: not enough memory for task stack");
default:
this->status_set_error("Failed to start resampler");
break;
}
this->state_ = speaker::STATE_STOPPING;
}
break;
}
case speaker::STATE_RUNNING:
if (this->output_speaker_->is_stopped()) {
this->state_ = speaker::STATE_STOPPING;
}
break;
case speaker::STATE_STOPPING:
this->stop_();
this->state_ = speaker::STATE_STOPPED;
break;
case speaker::STATE_STOPPED:
break;
}
}
size_t ResamplerSpeaker::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
if (this->is_stopped()) {
this->start();
}
size_t bytes_written = 0;
if ((this->output_speaker_->is_running()) && (!this->requires_resampling_())) {
bytes_written = this->output_speaker_->play(data, length, ticks_to_wait);
} else {
if (this->ring_buffer_.use_count() == 1) {
std::shared_ptr<RingBuffer> temp_ring_buffer = this->ring_buffer_.lock();
bytes_written = temp_ring_buffer->write_without_replacement(data, length, ticks_to_wait);
}
}
return bytes_written;
}
void ResamplerSpeaker::start() { this->state_ = speaker::STATE_STARTING; }
esp_err_t ResamplerSpeaker::start_() {
this->target_stream_info_ = audio::AudioStreamInfo(
this->target_bits_per_sample_, this->audio_stream_info_.get_channels(), this->target_sample_rate_);
this->output_speaker_->set_audio_stream_info(this->target_stream_info_);
this->output_speaker_->start();
if (this->requires_resampling_()) {
// Start the resampler task to handle converting sample rates
return this->start_task_();
}
return ESP_OK;
}
esp_err_t ResamplerSpeaker::start_task_() {
if (this->task_stack_buffer_ == nullptr) {
if (this->task_stack_in_psram_) {
RAMAllocator<StackType_t> stack_allocator(RAMAllocator<StackType_t>::ALLOC_EXTERNAL);
this->task_stack_buffer_ = stack_allocator.allocate(TASK_STACK_SIZE);
} else {
RAMAllocator<StackType_t> stack_allocator(RAMAllocator<StackType_t>::ALLOC_INTERNAL);
this->task_stack_buffer_ = stack_allocator.allocate(TASK_STACK_SIZE);
}
}
if (this->task_stack_buffer_ == nullptr) {
return ESP_ERR_NO_MEM;
}
if (this->task_handle_ == nullptr) {
this->task_handle_ = xTaskCreateStatic(resample_task, "sample", TASK_STACK_SIZE, (void *) this,
RESAMPLER_TASK_PRIORITY, this->task_stack_buffer_, &this->task_stack_);
}
if (this->task_handle_ == nullptr) {
return ESP_ERR_INVALID_STATE;
}
return ESP_OK;
}
void ResamplerSpeaker::stop() { this->state_ = speaker::STATE_STOPPING; }
void ResamplerSpeaker::stop_() {
if (this->task_handle_ != nullptr) {
xEventGroupSetBits(this->event_group_, ResamplingEventGroupBits::COMMAND_STOP);
}
this->output_speaker_->stop();
}
esp_err_t ResamplerSpeaker::delete_task_() {
if (!this->task_created_) {
this->task_handle_ = nullptr;
if (this->task_stack_buffer_ != nullptr) {
if (this->task_stack_in_psram_) {
RAMAllocator<StackType_t> stack_allocator(RAMAllocator<StackType_t>::ALLOC_EXTERNAL);
stack_allocator.deallocate(this->task_stack_buffer_, TASK_STACK_SIZE);
} else {
RAMAllocator<StackType_t> stack_allocator(RAMAllocator<StackType_t>::ALLOC_INTERNAL);
stack_allocator.deallocate(this->task_stack_buffer_, TASK_STACK_SIZE);
}
this->task_stack_buffer_ = nullptr;
}
return ESP_OK;
}
return ESP_ERR_INVALID_STATE;
}
void ResamplerSpeaker::finish() { this->output_speaker_->finish(); }
bool ResamplerSpeaker::has_buffered_data() const {
bool has_ring_buffer_data = false;
if (this->requires_resampling_() && (this->ring_buffer_.use_count() > 0)) {
has_ring_buffer_data = (this->ring_buffer_.lock()->available() > 0);
}
return (has_ring_buffer_data || this->output_speaker_->has_buffered_data());
}
void ResamplerSpeaker::set_mute_state(bool mute_state) {
this->mute_state_ = mute_state;
this->output_speaker_->set_mute_state(mute_state);
}
void ResamplerSpeaker::set_volume(float volume) {
this->volume_ = volume;
this->output_speaker_->set_volume(volume);
}
bool ResamplerSpeaker::requires_resampling_() const {
return (this->audio_stream_info_.get_sample_rate() != this->target_sample_rate_) ||
(this->audio_stream_info_.get_bits_per_sample() != this->target_bits_per_sample_);
}
void ResamplerSpeaker::resample_task(void *params) {
ResamplerSpeaker *this_resampler = (ResamplerSpeaker *) params;
this_resampler->task_created_ = true;
xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::STATE_STARTING);
std::unique_ptr<audio::AudioResampler> resampler =
make_unique<audio::AudioResampler>(this_resampler->audio_stream_info_.ms_to_bytes(TRANSFER_BUFFER_DURATION_MS),
this_resampler->target_stream_info_.ms_to_bytes(TRANSFER_BUFFER_DURATION_MS));
esp_err_t err = resampler->start(this_resampler->audio_stream_info_, this_resampler->target_stream_info_,
this_resampler->taps_, this_resampler->filters_);
if (err == ESP_OK) {
std::shared_ptr<RingBuffer> temp_ring_buffer =
RingBuffer::create(this_resampler->audio_stream_info_.ms_to_bytes(this_resampler->buffer_duration_ms_));
if (temp_ring_buffer.use_count() == 0) {
err = ESP_ERR_NO_MEM;
} else {
this_resampler->ring_buffer_ = temp_ring_buffer;
resampler->add_source(this_resampler->ring_buffer_);
this_resampler->output_speaker_->set_audio_stream_info(this_resampler->target_stream_info_);
resampler->add_sink(this_resampler->output_speaker_);
}
}
if (err == ESP_OK) {
xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::STATE_RUNNING);
} else if (err == ESP_ERR_NO_MEM) {
xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::ERR_ESP_NO_MEM);
} else if (err == ESP_ERR_NOT_SUPPORTED) {
xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::ERR_ESP_NOT_SUPPORTED);
}
this_resampler->playback_differential_ms_ = 0;
while (err == ESP_OK) {
uint32_t event_bits = xEventGroupGetBits(this_resampler->event_group_);
if (event_bits & ResamplingEventGroupBits::COMMAND_STOP) {
break;
}
// Stop gracefully if the decoder is done
int32_t ms_differential = 0;
audio::AudioResamplerState resampler_state = resampler->resample(false, &ms_differential);
this_resampler->playback_differential_ms_ += ms_differential;
if (resampler_state == audio::AudioResamplerState::FINISHED) {
break;
} else if (resampler_state == audio::AudioResamplerState::FAILED) {
xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::ERR_ESP_FAIL);
break;
}
}
xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::STATE_STOPPING);
resampler.reset();
xEventGroupSetBits(this_resampler->event_group_, ResamplingEventGroupBits::STATE_STOPPED);
this_resampler->task_created_ = false;
vTaskDelete(nullptr);
}
} // namespace resampler
} // namespace esphome
#endif

View File

@ -0,0 +1,107 @@
#pragma once
#ifdef USE_ESP32
#include "esphome/components/audio/audio.h"
#include "esphome/components/audio/audio_transfer_buffer.h"
#include "esphome/components/speaker/speaker.h"
#include "esphome/core/component.h"
#include <freertos/event_groups.h>
#include <freertos/FreeRTOS.h>
namespace esphome {
namespace resampler {
class ResamplerSpeaker : public Component, public speaker::Speaker {
public:
float get_setup_priority() const override { return esphome::setup_priority::DATA; }
void setup() override;
void loop() override;
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 this->play(data, length, 0); }
void start() override;
void stop() override;
void finish() override;
void set_pause_state(bool pause_state) override { this->output_speaker_->set_pause_state(pause_state); }
bool get_pause_state() const override { return this->output_speaker_->get_pause_state(); }
bool has_buffered_data() const override;
/// @brief Mute state changes are passed to the parent's output speaker
void set_mute_state(bool mute_state) override;
/// @brief Volume state changes are passed to the parent's output speaker
void set_volume(float volume) override;
void set_output_speaker(speaker::Speaker *speaker) { this->output_speaker_ = speaker; }
void set_task_stack_in_psram(bool task_stack_in_psram) { this->task_stack_in_psram_ = task_stack_in_psram; }
void set_target_bits_per_sample(uint8_t target_bits_per_sample) {
this->target_bits_per_sample_ = target_bits_per_sample;
}
void set_target_sample_rate(uint32_t target_sample_rate) { this->target_sample_rate_ = target_sample_rate; }
void set_filters(uint16_t filters) { this->filters_ = filters; }
void set_taps(uint16_t taps) { this->taps_ = taps; }
void set_buffer_duration(uint32_t buffer_duration_ms) { this->buffer_duration_ms_ = buffer_duration_ms; }
protected:
/// @brief Starts the output speaker after setting the resampled stream info. If resampling is required, it starts the
/// task.
/// @return ESP_OK if resampling is required
/// return value of start_task_() if resampling is required
esp_err_t start_();
/// @brief Starts the resampler task after allocating the task stack
/// @return ESP_OK if successful,
/// ESP_ERR_NO_MEM if the task stack couldn't be allocated
/// ESP_ERR_INVALID_STATE if the task wasn't created
esp_err_t start_task_();
/// @brief Stops the output speaker. If the resampling task is running, it sends the stop command.
void stop_();
/// @brief Deallocates the task stack and resets the pointers.
/// @return ESP_OK if successful
/// ESP_ERR_INVALID_STATE if the task hasn't stopped itself
esp_err_t delete_task_();
inline bool requires_resampling_() const;
static void resample_task(void *params);
EventGroupHandle_t event_group_{nullptr};
std::weak_ptr<RingBuffer> ring_buffer_;
speaker::Speaker *output_speaker_{nullptr};
bool task_stack_in_psram_{false};
bool task_created_{false};
TaskHandle_t task_handle_{nullptr};
StaticTask_t task_stack_;
StackType_t *task_stack_buffer_{nullptr};
audio::AudioStreamInfo target_stream_info_;
uint16_t taps_;
uint16_t filters_;
uint8_t target_bits_per_sample_;
uint32_t target_sample_rate_;
uint32_t buffer_duration_ms_;
int32_t playback_differential_ms_{0};
};
} // namespace resampler
} // namespace esphome
#endif

View File

@ -0,0 +1,270 @@
import esphome.codegen as cg
from esphome.components import binary_sensor
from esphome.components.binary_sensor import BinarySensor
import esphome.config_validation as cv
from esphome.const import CONF_KEY
from esphome.core import Lambda
from esphome.cpp_generator import ExpressionStatement, RawExpression
from .display import CONF_SDL_ID, Sdl
CODEOWNERS = ["@bdm310"]
STATE_ARG = "state"
SDL_KEYMAP = {
"SDLK_UNKNOWN": 0,
"SDLK_FIRST": 0,
"SDLK_BACKSPACE": 8,
"SDLK_TAB": 9,
"SDLK_CLEAR": 12,
"SDLK_RETURN": 13,
"SDLK_PAUSE": 19,
"SDLK_ESCAPE": 27,
"SDLK_SPACE": 32,
"SDLK_EXCLAIM": 33,
"SDLK_QUOTEDBL": 34,
"SDLK_HASH": 35,
"SDLK_DOLLAR": 36,
"SDLK_AMPERSAND": 38,
"SDLK_QUOTE": 39,
"SDLK_LEFTPAREN": 40,
"SDLK_RIGHTPAREN": 41,
"SDLK_ASTERISK": 42,
"SDLK_PLUS": 43,
"SDLK_COMMA": 44,
"SDLK_MINUS": 45,
"SDLK_PERIOD": 46,
"SDLK_SLASH": 47,
"SDLK_0": 48,
"SDLK_1": 49,
"SDLK_2": 50,
"SDLK_3": 51,
"SDLK_4": 52,
"SDLK_5": 53,
"SDLK_6": 54,
"SDLK_7": 55,
"SDLK_8": 56,
"SDLK_9": 57,
"SDLK_COLON": 58,
"SDLK_SEMICOLON": 59,
"SDLK_LESS": 60,
"SDLK_EQUALS": 61,
"SDLK_GREATER": 62,
"SDLK_QUESTION": 63,
"SDLK_AT": 64,
"SDLK_LEFTBRACKET": 91,
"SDLK_BACKSLASH": 92,
"SDLK_RIGHTBRACKET": 93,
"SDLK_CARET": 94,
"SDLK_UNDERSCORE": 95,
"SDLK_BACKQUOTE": 96,
"SDLK_a": 97,
"SDLK_b": 98,
"SDLK_c": 99,
"SDLK_d": 100,
"SDLK_e": 101,
"SDLK_f": 102,
"SDLK_g": 103,
"SDLK_h": 104,
"SDLK_i": 105,
"SDLK_j": 106,
"SDLK_k": 107,
"SDLK_l": 108,
"SDLK_m": 109,
"SDLK_n": 110,
"SDLK_o": 111,
"SDLK_p": 112,
"SDLK_q": 113,
"SDLK_r": 114,
"SDLK_s": 115,
"SDLK_t": 116,
"SDLK_u": 117,
"SDLK_v": 118,
"SDLK_w": 119,
"SDLK_x": 120,
"SDLK_y": 121,
"SDLK_z": 122,
"SDLK_DELETE": 127,
"SDLK_WORLD_0": 160,
"SDLK_WORLD_1": 161,
"SDLK_WORLD_2": 162,
"SDLK_WORLD_3": 163,
"SDLK_WORLD_4": 164,
"SDLK_WORLD_5": 165,
"SDLK_WORLD_6": 166,
"SDLK_WORLD_7": 167,
"SDLK_WORLD_8": 168,
"SDLK_WORLD_9": 169,
"SDLK_WORLD_10": 170,
"SDLK_WORLD_11": 171,
"SDLK_WORLD_12": 172,
"SDLK_WORLD_13": 173,
"SDLK_WORLD_14": 174,
"SDLK_WORLD_15": 175,
"SDLK_WORLD_16": 176,
"SDLK_WORLD_17": 177,
"SDLK_WORLD_18": 178,
"SDLK_WORLD_19": 179,
"SDLK_WORLD_20": 180,
"SDLK_WORLD_21": 181,
"SDLK_WORLD_22": 182,
"SDLK_WORLD_23": 183,
"SDLK_WORLD_24": 184,
"SDLK_WORLD_25": 185,
"SDLK_WORLD_26": 186,
"SDLK_WORLD_27": 187,
"SDLK_WORLD_28": 188,
"SDLK_WORLD_29": 189,
"SDLK_WORLD_30": 190,
"SDLK_WORLD_31": 191,
"SDLK_WORLD_32": 192,
"SDLK_WORLD_33": 193,
"SDLK_WORLD_34": 194,
"SDLK_WORLD_35": 195,
"SDLK_WORLD_36": 196,
"SDLK_WORLD_37": 197,
"SDLK_WORLD_38": 198,
"SDLK_WORLD_39": 199,
"SDLK_WORLD_40": 200,
"SDLK_WORLD_41": 201,
"SDLK_WORLD_42": 202,
"SDLK_WORLD_43": 203,
"SDLK_WORLD_44": 204,
"SDLK_WORLD_45": 205,
"SDLK_WORLD_46": 206,
"SDLK_WORLD_47": 207,
"SDLK_WORLD_48": 208,
"SDLK_WORLD_49": 209,
"SDLK_WORLD_50": 210,
"SDLK_WORLD_51": 211,
"SDLK_WORLD_52": 212,
"SDLK_WORLD_53": 213,
"SDLK_WORLD_54": 214,
"SDLK_WORLD_55": 215,
"SDLK_WORLD_56": 216,
"SDLK_WORLD_57": 217,
"SDLK_WORLD_58": 218,
"SDLK_WORLD_59": 219,
"SDLK_WORLD_60": 220,
"SDLK_WORLD_61": 221,
"SDLK_WORLD_62": 222,
"SDLK_WORLD_63": 223,
"SDLK_WORLD_64": 224,
"SDLK_WORLD_65": 225,
"SDLK_WORLD_66": 226,
"SDLK_WORLD_67": 227,
"SDLK_WORLD_68": 228,
"SDLK_WORLD_69": 229,
"SDLK_WORLD_70": 230,
"SDLK_WORLD_71": 231,
"SDLK_WORLD_72": 232,
"SDLK_WORLD_73": 233,
"SDLK_WORLD_74": 234,
"SDLK_WORLD_75": 235,
"SDLK_WORLD_76": 236,
"SDLK_WORLD_77": 237,
"SDLK_WORLD_78": 238,
"SDLK_WORLD_79": 239,
"SDLK_WORLD_80": 240,
"SDLK_WORLD_81": 241,
"SDLK_WORLD_82": 242,
"SDLK_WORLD_83": 243,
"SDLK_WORLD_84": 244,
"SDLK_WORLD_85": 245,
"SDLK_WORLD_86": 246,
"SDLK_WORLD_87": 247,
"SDLK_WORLD_88": 248,
"SDLK_WORLD_89": 249,
"SDLK_WORLD_90": 250,
"SDLK_WORLD_91": 251,
"SDLK_WORLD_92": 252,
"SDLK_WORLD_93": 253,
"SDLK_WORLD_94": 254,
"SDLK_WORLD_95": 255,
"SDLK_KP0": 256,
"SDLK_KP1": 257,
"SDLK_KP2": 258,
"SDLK_KP3": 259,
"SDLK_KP4": 260,
"SDLK_KP5": 261,
"SDLK_KP6": 262,
"SDLK_KP7": 263,
"SDLK_KP8": 264,
"SDLK_KP9": 265,
"SDLK_KP_PERIOD": 266,
"SDLK_KP_DIVIDE": 267,
"SDLK_KP_MULTIPLY": 268,
"SDLK_KP_MINUS": 269,
"SDLK_KP_PLUS": 270,
"SDLK_KP_ENTER": 271,
"SDLK_KP_EQUALS": 272,
"SDLK_UP": 273,
"SDLK_DOWN": 274,
"SDLK_RIGHT": 275,
"SDLK_LEFT": 276,
"SDLK_INSERT": 277,
"SDLK_HOME": 278,
"SDLK_END": 279,
"SDLK_PAGEUP": 280,
"SDLK_PAGEDOWN": 281,
"SDLK_F1": 282,
"SDLK_F2": 283,
"SDLK_F3": 284,
"SDLK_F4": 285,
"SDLK_F5": 286,
"SDLK_F6": 287,
"SDLK_F7": 288,
"SDLK_F8": 289,
"SDLK_F9": 290,
"SDLK_F10": 291,
"SDLK_F11": 292,
"SDLK_F12": 293,
"SDLK_F13": 294,
"SDLK_F14": 295,
"SDLK_F15": 296,
"SDLK_NUMLOCK": 300,
"SDLK_CAPSLOCK": 301,
"SDLK_SCROLLOCK": 302,
"SDLK_RSHIFT": 303,
"SDLK_LSHIFT": 304,
"SDLK_RCTRL": 305,
"SDLK_LCTRL": 306,
"SDLK_RALT": 307,
"SDLK_LALT": 308,
"SDLK_RMETA": 309,
"SDLK_LMETA": 310,
"SDLK_LSUPER": 311,
"SDLK_RSUPER": 312,
"SDLK_MODE": 313,
"SDLK_COMPOSE": 314,
"SDLK_HELP": 315,
"SDLK_PRINT": 316,
"SDLK_SYSREQ": 317,
"SDLK_BREAK": 318,
"SDLK_MENU": 319,
"SDLK_POWER": 320,
"SDLK_EURO": 321,
"SDLK_UNDO": 322,
}
CONFIG_SCHEMA = (
binary_sensor.binary_sensor_schema(BinarySensor)
.extend(
{
cv.Required(CONF_KEY): cv.enum(SDL_KEYMAP),
cv.GenerateID(CONF_SDL_ID): cv.use_id(Sdl),
}
)
.extend(cv.COMPONENT_SCHEMA)
)
async def to_code(config):
var = await binary_sensor.new_binary_sensor(config)
parent = await cg.get_variable(config[CONF_SDL_ID])
listener = Lambda(
str(ExpressionStatement(var.publish_state(RawExpression(STATE_ARG))))
)
listener = await cg.process_lambda(listener, [(cg.bool_, STATE_ARG)])
cg.add(parent.add_key_listener(config[CONF_KEY], listener))

View File

@ -61,6 +61,12 @@ void Sdl::draw_pixel_at(int x, int y, Color color) {
this->y_high_ = y;
}
void Sdl::process_key(uint32_t keycode, bool down) {
auto callback = this->key_callbacks_.find(keycode);
if (callback != this->key_callbacks_.end())
callback->second(down);
}
void Sdl::loop() {
SDL_Event e;
if (SDL_PollEvent(&e)) {
@ -87,6 +93,16 @@ void Sdl::loop() {
}
break;
case SDL_KEYDOWN:
ESP_LOGD(TAG, "keydown %d", e.key.keysym.sym);
this->process_key(e.key.keysym.sym, true);
break;
case SDL_KEYUP:
ESP_LOGD(TAG, "keyup %d", e.key.keysym.sym);
this->process_key(e.key.keysym.sym, false);
break;
case SDL_WINDOWEVENT:
switch (e.window.event) {
case SDL_WINDOWEVENT_SIZE_CHANGED:

View File

@ -7,6 +7,7 @@
#include "esphome/components/display/display.h"
#define SDL_MAIN_HANDLED
#include "SDL.h"
#include <map>
namespace esphome {
namespace sdl {
@ -22,6 +23,7 @@ class Sdl : public display::Display {
void draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, display::ColorOrder order,
display::ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) override;
void draw_pixel_at(int x, int y, Color color) override;
void process_key(uint32_t keycode, bool down);
void set_dimensions(uint16_t width, uint16_t height) {
this->width_ = width;
this->height_ = height;
@ -30,6 +32,12 @@ class Sdl : public display::Display {
int get_height() override { return this->height_; }
float get_setup_priority() const override { return setup_priority::HARDWARE; }
void dump_config() override { LOG_DISPLAY("", "SDL", this); }
void add_key_listener(int32_t keycode, std::function<void(bool)> &&callback) {
if (!this->key_callbacks_.count(keycode)) {
this->key_callbacks_[keycode] = CallbackManager<void(bool)>();
}
this->key_callbacks_[keycode].add(std::move(callback));
}
int mouse_x{};
int mouse_y{};
@ -48,6 +56,7 @@ class Sdl : public display::Display {
uint16_t y_low_{0};
uint16_t x_high_{0};
uint16_t y_high_{0};
std::map<int32_t, CallbackManager<void(bool)>> key_callbacks_{};
};
} // namespace sdl
} // namespace esphome

View File

@ -18,7 +18,7 @@ from esphome.cpp_generator import MockObjClass
CODEOWNERS = ["@clydebarrow"]
DEPENDENCIES = ["network"]
AUTO_LOAD = ["socket"]
AUTO_LOAD = ["socket", "xxtea"]
MULTI_CONF = True
udp_ns = cg.esphome_ns.namespace("udp")

View File

@ -3,6 +3,8 @@
#include "esphome/components/network/util.h"
#include "udp_component.h"
#include "esphome/components/xxtea/xxtea.h"
namespace esphome {
namespace udp {
@ -47,54 +49,7 @@ namespace udp {
*/
static const char *const TAG = "udp";
/**
* XXTEA implementation, using 256 bit key.
*/
static const uint32_t DELTA = 0x9e3779b9;
#define MX ((((z >> 5) ^ (y << 2)) + ((y >> 3) ^ (z << 4))) ^ ((sum ^ y) + (k[(p ^ e) & 7] ^ z)))
/**
* Encrypt a block of data in-place
*/
static void xxtea_encrypt(uint32_t *v, size_t n, const uint32_t *k) {
uint32_t z, y, sum, e;
size_t p;
size_t q = 6 + 52 / n;
sum = 0;
z = v[n - 1];
while (q-- != 0) {
sum += DELTA;
e = (sum >> 2);
for (p = 0; p != n - 1; p++) {
y = v[p + 1];
z = v[p] += MX;
}
y = v[0];
z = v[n - 1] += MX;
}
}
static void xxtea_decrypt(uint32_t *v, size_t n, const uint32_t *k) {
uint32_t z, y, sum, e;
size_t p;
size_t q = 6 + 52 / n;
sum = q * DELTA;
y = v[0];
while (q-- != 0) {
e = (sum >> 2);
for (p = n - 1; p != 0; p--) {
z = v[p - 1];
y = v[p] -= MX;
}
z = v[n - 1];
y = v[0] -= MX;
sum -= DELTA;
}
}
inline static size_t round4(size_t value) { return (value + 3) & ~3; }
static size_t round4(size_t value) { return (value + 3) & ~3; }
union FuData {
uint32_t u32;
@ -312,7 +267,7 @@ void UDPComponent::flush_() {
memcpy(buffer, this->header_.data(), this->header_.size());
memcpy(buffer + header_len, this->data_.data(), this->data_.size());
if (this->is_encrypted_()) {
xxtea_encrypt(buffer + header_len, len, (uint32_t *) this->encryption_key_.data());
xxtea::encrypt(buffer + header_len, len, (uint32_t *) this->encryption_key_.data());
}
auto total_len = (header_len + len) * 4;
this->send_packet_(buffer, total_len);
@ -503,7 +458,7 @@ void UDPComponent::process_(uint8_t *buf, const size_t len) {
#endif
if (!provider.encryption_key.empty()) {
xxtea_decrypt((uint32_t *) buf, (end - buf) / 4, (uint32_t *) provider.encryption_key.data());
xxtea::decrypt((uint32_t *) buf, (end - buf) / 4, (uint32_t *) provider.encryption_key.data());
}
byte = *buf++;
if (byte == ROLLING_CODE_KEY) {

View File

@ -1,11 +1,12 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import sensor
import esphome.config_validation as cv
from esphome.const import (
CONF_EXTERNAL_TEMPERATURE,
CONF_HUMIDITY,
CONF_TEMPERATURE,
CONF_ID,
CONF_TARGET_TEMPERATURE,
CONF_TEMPERATURE,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
STATE_CLASS_MEASUREMENT,
@ -14,10 +15,10 @@ from esphome.const import (
)
from .. import (
uponor_smatrix_ns,
UponorSmatrixDevice,
UPONOR_SMATRIX_DEVICE_SCHEMA,
UponorSmatrixDevice,
register_uponor_smatrix_device,
uponor_smatrix_ns,
)
DEPENDENCIES = ["uponor_smatrix"]
@ -50,6 +51,12 @@ CONFIG_SCHEMA = cv.COMPONENT_SCHEMA.extend(
device_class=DEVICE_CLASS_HUMIDITY,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_TARGET_TEMPERATURE): sensor.sensor_schema(
unit_of_measurement=UNIT_CELSIUS,
accuracy_decimals=1,
device_class=DEVICE_CLASS_TEMPERATURE,
state_class=STATE_CLASS_MEASUREMENT,
),
}
).extend(UPONOR_SMATRIX_DEVICE_SCHEMA)
@ -68,3 +75,6 @@ async def to_code(config):
if humidity_config := config.get(CONF_HUMIDITY):
sens = await sensor.new_sensor(humidity_config)
cg.add(var.set_humidity_sensor(sens))
if target_temperature_config := config.get(CONF_TARGET_TEMPERATURE):
sens = await sensor.new_sensor(target_temperature_config)
cg.add(var.set_target_temperature_sensor(sens))

View File

@ -12,6 +12,7 @@ void UponorSmatrixSensor::dump_config() {
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
LOG_SENSOR(" ", "External Temperature", this->external_temperature_sensor_);
LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
LOG_SENSOR(" ", "Target Temperature", this->target_temperature_sensor_);
}
void UponorSmatrixSensor::on_device_data(const UponorSmatrixData *data, size_t data_len) {
@ -29,6 +30,10 @@ void UponorSmatrixSensor::on_device_data(const UponorSmatrixData *data, size_t d
if (this->humidity_sensor_ != nullptr)
this->humidity_sensor_->publish_state(data[i].value & 0x00FF);
break;
case UPONOR_ID_TARGET_TEMP:
if (this->target_temperature_sensor_ != nullptr)
this->target_temperature_sensor_->publish_state(raw_to_celsius(data[i].value));
break;
}
}
}

View File

@ -11,6 +11,7 @@ class UponorSmatrixSensor : public sensor::Sensor, public Component, public Upon
SUB_SENSOR(temperature)
SUB_SENSOR(external_temperature)
SUB_SENSOR(humidity)
SUB_SENSOR(target_temperature)
public:
void dump_config() override;

View File

@ -0,0 +1,3 @@
"""ESPHome XXTEA encryption component."""
CODEOWNERS = ["@clydebarrow"]

View File

@ -0,0 +1,46 @@
#include "xxtea.h"
namespace esphome {
namespace xxtea {
static const uint32_t DELTA = 0x9e3779b9;
#define MX ((((z >> 5) ^ (y << 2)) + ((y >> 3) ^ (z << 4))) ^ ((sum ^ y) + (k[(p ^ e) & 7] ^ z)))
void encrypt(uint32_t *v, size_t n, const uint32_t *k) {
uint32_t z, y, sum, e;
size_t p;
size_t q = 6 + 52 / n;
sum = 0;
z = v[n - 1];
while (q-- != 0) {
sum += DELTA;
e = (sum >> 2);
for (p = 0; p != n - 1; p++) {
y = v[p + 1];
z = v[p] += MX;
}
y = v[0];
z = v[n - 1] += MX;
}
}
void decrypt(uint32_t *v, size_t n, const uint32_t *k) {
uint32_t z, y, sum, e;
size_t p;
size_t q = 6 + 52 / n;
sum = q * DELTA;
y = v[0];
while (q-- != 0) {
e = (sum >> 2);
for (p = n - 1; p != 0; p--) {
z = v[p - 1];
y = v[p] -= MX;
}
z = v[n - 1];
y = v[0] -= MX;
sum -= DELTA;
}
}
} // namespace xxtea
} // namespace esphome

View File

@ -0,0 +1,26 @@
#pragma once
#include <cstdint>
#include <cstddef>
namespace esphome {
namespace xxtea {
/**
* Encrypt a block of data in-place using XXTEA algorithm with 256-bit key
* @param v Data to encrypt (as array of 32-bit words)
* @param n Number of 32-bit words in data
* @param k Key (array of 8 32-bit words)
*/
void encrypt(uint32_t *v, size_t n, const uint32_t *k);
/**
* Decrypt a block of data in-place using XXTEA algorithm with 256-bit key
* @param v Data to decrypt (as array of 32-bit words)
* @param n Number of 32-bit words in data
* @param k Key (array of 8 32-bit words)
*/
void decrypt(uint32_t *v, size_t n, const uint32_t *k);
} // namespace xxtea
} // namespace esphome

View File

@ -16,6 +16,8 @@
// Feature flags
#define USE_ALARM_CONTROL_PANEL
#define USE_AUDIO_FLAC_SUPPORT
#define USE_AUDIO_MP3_SUPPORT
#define USE_API
#define USE_API_NOISE
#define USE_API_PLAINTEXT

View File

@ -0,0 +1,11 @@
uart:
- id: uart_a02yyuw
tx_pin: ${tx_pin}
rx_pin: ${rx_pin}
baud_rate: 9600
sensor:
- platform: a02yyuw
id: a02yyuw_sensor
name: a02yyuw Distance
uart_id: uart_a02yyuw

View File

@ -1,13 +1,5 @@
uart:
- id: uart_a02yyuw
tx_pin:
number: 17
rx_pin:
number: 16
baud_rate: 9600
substitutions:
tx_pin: GPIO17
rx_pin: GPIO16
sensor:
- platform: a02yyuw
id: a02yyuw_sensor
name: a02yyuw Distance
uart_id: uart_a02yyuw
<<: !include common.yaml

View File

@ -1,13 +1,5 @@
uart:
- id: uart_a02yyuw
tx_pin:
number: 4
rx_pin:
number: 5
baud_rate: 9600
substitutions:
tx_pin: GPIO4
rx_pin: GPIO5
sensor:
- platform: a02yyuw
id: a02yyuw_sensor
name: a02yyuw Distance
uart_id: uart_a02yyuw
<<: !include common.yaml

View File

@ -1,13 +1,5 @@
uart:
- id: uart_a02yyuw
tx_pin:
number: 4
rx_pin:
number: 5
baud_rate: 9600
substitutions:
tx_pin: GPIO4
rx_pin: GPIO5
sensor:
- platform: a02yyuw
id: a02yyuw_sensor
name: a02yyuw Distance
uart_id: uart_a02yyuw
<<: !include common.yaml

View File

@ -1,13 +1,5 @@
uart:
- id: uart_a02yyuw
tx_pin:
number: 17
rx_pin:
number: 16
baud_rate: 9600
substitutions:
tx_pin: GPIO17
rx_pin: GPIO16
sensor:
- platform: a02yyuw
id: a02yyuw_sensor
name: a02yyuw Distance
uart_id: uart_a02yyuw
<<: !include common.yaml

View File

@ -1,13 +1,5 @@
uart:
- id: uart_a02yyuw
tx_pin:
number: 4
rx_pin:
number: 5
baud_rate: 9600
substitutions:
tx_pin: GPIO4
rx_pin: GPIO5
sensor:
- platform: a02yyuw
id: a02yyuw_sensor
name: a02yyuw Distance
uart_id: uart_a02yyuw
<<: !include common.yaml

View File

@ -1,13 +1,5 @@
uart:
- id: uart_a02yyuw
tx_pin:
number: 4
rx_pin:
number: 5
baud_rate: 9600
substitutions:
tx_pin: GPIO4
rx_pin: GPIO5
sensor:
- platform: a02yyuw
id: a02yyuw_sensor
name: a02yyuw Distance
uart_id: uart_a02yyuw
<<: !include common.yaml

View File

@ -0,0 +1,9 @@
stepper:
- platform: a4988
id: a4988_stepper
step_pin: ${step_pin}
dir_pin: ${dir_pin}
sleep_pin: ${sleep_pin}
max_speed: 250 steps/s
acceleration: 100 steps/s^2
deceleration: 200 steps/s^2

View File

@ -1,12 +1,6 @@
stepper:
- platform: a4988
id: a4988_stepper
step_pin:
number: 22
dir_pin:
number: 23
sleep_pin:
number: 25
max_speed: 250 steps/s
acceleration: 100 steps/s^2
deceleration: 200 steps/s^2
substitutions:
step_pin: GPIO22
dir_pin: GPIO23
sleep_pin: GPIO25
<<: !include common.yaml

View File

@ -1,12 +1,6 @@
stepper:
- platform: a4988
id: a4988_stepper
step_pin:
number: 2
dir_pin:
number: 3
sleep_pin:
number: 5
max_speed: 250 steps/s
acceleration: 100 steps/s^2
deceleration: 200 steps/s^2
substitutions:
step_pin: GPIO2
dir_pin: GPIO3
sleep_pin: GPIO5
<<: !include common.yaml

View File

@ -1,12 +1,6 @@
stepper:
- platform: a4988
id: a4988_stepper
step_pin:
number: 2
dir_pin:
number: 3
sleep_pin:
number: 5
max_speed: 250 steps/s
acceleration: 100 steps/s^2
deceleration: 200 steps/s^2
substitutions:
step_pin: GPIO2
dir_pin: GPIO3
sleep_pin: GPIO5
<<: !include common.yaml

View File

@ -1,12 +1,6 @@
stepper:
- platform: a4988
id: a4988_stepper
step_pin:
number: 22
dir_pin:
number: 23
sleep_pin:
number: 25
max_speed: 250 steps/s
acceleration: 100 steps/s^2
deceleration: 200 steps/s^2
substitutions:
step_pin: GPIO22
dir_pin: GPIO23
sleep_pin: GPIO25
<<: !include common.yaml

View File

@ -1,12 +1,6 @@
stepper:
- platform: a4988
id: a4988_stepper
step_pin:
number: 1
dir_pin:
number: 2
sleep_pin:
number: 5
max_speed: 250 steps/s
acceleration: 100 steps/s^2
deceleration: 200 steps/s^2
substitutions:
step_pin: GPIO1
dir_pin: GPIO2
sleep_pin: GPIO5
<<: !include common.yaml

View File

@ -1,12 +1,6 @@
stepper:
- platform: a4988
id: a4988_stepper
step_pin:
number: 2
dir_pin:
number: 3
sleep_pin:
number: 5
max_speed: 250 steps/s
acceleration: 100 steps/s^2
deceleration: 200 steps/s^2
substitutions:
step_pin: GPIO2
dir_pin: GPIO3
sleep_pin: GPIO5
<<: !include common.yaml

View File

@ -0,0 +1,5 @@
output:
- platform: ac_dimmer
id: ac_dimmer_1
gate_pin: ${gate_pin}
zero_cross_pin: ${zero_cross_pin}

View File

@ -1,7 +1,5 @@
output:
- platform: ac_dimmer
id: ac_dimmer_1
gate_pin:
number: 12
zero_cross_pin:
number: 13
substitutions:
gate_pin: GPIO18
zero_cross_pin: GPIO19
<<: !include common.yaml

View File

@ -1,7 +1,5 @@
output:
- platform: ac_dimmer
id: ac_dimmer_1
gate_pin:
number: 5
zero_cross_pin:
number: 6
substitutions:
gate_pin: GPIO5
zero_cross_pin: GPIO4
<<: !include common.yaml

View File

@ -1,7 +1,5 @@
output:
- platform: ac_dimmer
id: ac_dimmer_1
gate_pin:
number: 5
zero_cross_pin:
number: 4
substitutions:
gate_pin: GPIO5
zero_cross_pin: GPIO4
<<: !include common.yaml

View File

@ -1,7 +1,5 @@
output:
- platform: ac_dimmer
id: ac_dimmer_1
gate_pin:
number: 5
zero_cross_pin:
number: 6
substitutions:
gate_pin: GPIO5
zero_cross_pin: GPIO4
<<: !include common.yaml

View File

@ -2,4 +2,4 @@ sensor:
- platform: adc
id: my_sensor
pin: 4
attenuation: 11db
attenuation: 12db

View File

@ -2,4 +2,4 @@ sensor:
- platform: adc
id: my_sensor
pin: 1
attenuation: 11db
attenuation: 12db

View File

@ -2,4 +2,4 @@ sensor:
- platform: adc
id: my_sensor
pin: 1
attenuation: 11db
attenuation: 12db

View File

@ -0,0 +1,14 @@
spi:
- id: spi_adc128s102
clk_pin: ${clk_pin}
mosi_pin: ${mosi_pin}
miso_pin: ${miso_pin}
adc128s102:
cs_pin: ${cs_pin}
id: adc128s102_adc
sensor:
- platform: adc128s102
id: adc128s102_channel_0
channel: 0

View File

@ -1,14 +1,7 @@
spi:
- id: spi_adc128s102
clk_pin: 16
mosi_pin: 17
miso_pin: 15
substitutions:
clk_pin: GPIO16
mosi_pin: GPIO17
miso_pin: GPIO15
cs_pin: GPIO12
adc128s102:
cs_pin: 12
id: adc128s102_adc
sensor:
- platform: adc128s102
id: adc128s102_channel_0
channel: 0
<<: !include common.yaml

View File

@ -1,14 +1,7 @@
spi:
- id: spi_adc128s102
clk_pin: 6
mosi_pin: 7
miso_pin: 5
substitutions:
clk_pin: GPIO6
mosi_pin: GPIO7
miso_pin: GPIO5
cs_pin: GPIO2
adc128s102:
cs_pin: 8
id: adc128s102_adc
sensor:
- platform: adc128s102
id: adc128s102_channel_0
channel: 0
<<: !include common.yaml

View File

@ -1,14 +1,7 @@
spi:
- id: spi_adc128s102
clk_pin: 6
mosi_pin: 7
miso_pin: 5
substitutions:
clk_pin: GPIO6
mosi_pin: GPIO7
miso_pin: GPIO5
cs_pin: GPIO2
adc128s102:
cs_pin: 8
id: adc128s102_adc
sensor:
- platform: adc128s102
id: adc128s102_channel_0
channel: 0
<<: !include common.yaml

View File

@ -1,14 +1,7 @@
spi:
- id: spi_adc128s102
clk_pin: 16
mosi_pin: 17
miso_pin: 15
substitutions:
clk_pin: GPIO16
mosi_pin: GPIO17
miso_pin: GPIO15
cs_pin: GPIO12
adc128s102:
cs_pin: 12
id: adc128s102_adc
sensor:
- platform: adc128s102
id: adc128s102_channel_0
channel: 0
<<: !include common.yaml

View File

@ -1,14 +1,7 @@
spi:
- id: spi_adc128s102
clk_pin: 14
mosi_pin: 13
miso_pin: 12
substitutions:
clk_pin: GPIO14
mosi_pin: GPIO13
miso_pin: GPIO12
cs_pin: GPIO15
adc128s102:
cs_pin: 15
id: adc128s102_adc
sensor:
- platform: adc128s102
id: adc128s102_channel_0
channel: 0
<<: !include common.yaml

View File

@ -1,14 +1,7 @@
spi:
- id: spi_adc128s102
clk_pin: 2
mosi_pin: 3
miso_pin: 4
substitutions:
clk_pin: GPIO2
mosi_pin: GPIO3
miso_pin: GPIO4
cs_pin: GPIO5
adc128s102:
cs_pin: 5
id: adc128s102_adc
sensor:
- platform: adc128s102
id: adc128s102_channel_0
channel: 0
<<: !include common.yaml

View File

@ -5,7 +5,7 @@ light:
chipset: ws2812
rgb_order: GRB
num_leds: 256
pin: 2
pin: ${pin}
rmt_channel: 0
display:

View File

@ -3,7 +3,7 @@ light:
id: led_matrix_32x8
name: led_matrix_32x8
chipset: WS2812B
pin: 2
pin: ${pin}
num_leds: 256
rgb_order: GRB
default_transition_length: 0s

View File

@ -5,7 +5,7 @@ light:
chipset: ws2812
rgb_order: GRB
num_leds: 256
pin: 2
pin: ${pin}
display:
- platform: addressable_light

View File

@ -0,0 +1,4 @@
substitutions:
pin: GPIO2
<<: !include common-ard-esp32_rmt_led_strip.yaml

View File

@ -0,0 +1,4 @@
substitutions:
pin: GPIO2
<<: !include common-ard-esp32_rmt_led_strip.yaml

View File

@ -0,0 +1,4 @@
substitutions:
pin: GPIO2
<<: !include common-idf-esp32_rmt_led_strip.yaml

View File

@ -0,0 +1,4 @@
substitutions:
pin: GPIO2
<<: !include common-idf-esp32_rmt_led_strip.yaml

View File

@ -0,0 +1,4 @@
substitutions:
pin: GPIO2
<<: !include common-ard-fastled.yaml

View File

@ -1,30 +0,0 @@
light:
- platform: esp32_rmt_led_strip
id: led_matrix_32x8
default_transition_length: 500ms
chipset: ws2812
rgb_order: GRB
num_leds: 256
pin: 2
display:
- platform: addressable_light
id: led_matrix_32x8_display
addressable_light_id: led_matrix_32x8
width: 32
height: 8
pixel_mapper: |-
if (x % 2 == 0) {
return (x * 8) + y;
}
return (x * 8) + (7 - y);
lambda: |-
Color red = Color(0xFF0000);
Color green = Color(0x00FF00);
Color blue = Color(0x0000FF);
it.rectangle(0, 0, it.get_width(), it.get_height(), red);
it.rectangle(1, 1, it.get_width()-2, it.get_height()-2, green);
it.rectangle(2, 2, it.get_width()-4, it.get_height()-4, blue);
it.rectangle(3, 3, it.get_width()-6, it.get_height()-6, red);
rotation: 0°
update_interval: 16ms

View File

@ -0,0 +1,34 @@
i2c:
- id: i2c_ade7953
scl: ${scl_pin}
sda: ${sda_pin}
sensor:
- platform: ade7953_i2c
irq_pin: ${irq_pin}
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s

View File

@ -1,34 +1,6 @@
i2c:
- id: i2c_ade7953
scl: 16
sda: 17
substitutions:
scl_pin: GPIO16
sda_pin: GPIO17
irq_pin: GPIO15
sensor:
- platform: ade7953_i2c
irq_pin: 15
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -1,34 +1,6 @@
i2c:
- id: i2c_ade7953
scl: 5
sda: 4
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
irq_pin: GPIO6
sensor:
- platform: ade7953_i2c
irq_pin: 6
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -1,34 +1,6 @@
i2c:
- id: i2c_ade7953
scl: 5
sda: 4
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
irq_pin: GPIO6
sensor:
- platform: ade7953_i2c
irq_pin: 6
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -1,34 +1,6 @@
i2c:
- id: i2c_ade7953
scl: 16
sda: 17
substitutions:
scl_pin: GPIO16
sda_pin: GPIO17
irq_pin: GPIO15
sensor:
- platform: ade7953_i2c
irq_pin: 15
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -1,34 +1,6 @@
i2c:
- id: i2c_ade7953
scl: 5
sda: 4
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
irq_pin: GPIO15
sensor:
- platform: ade7953_i2c
irq_pin: 15
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -1,34 +1,6 @@
i2c:
- id: i2c_ade7953
scl: 5
sda: 4
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
irq_pin: GPIO6
sensor:
- platform: ade7953_i2c
irq_pin: 6
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -0,0 +1,36 @@
spi:
- id: spi_ade7953
clk_pin: ${clk_pin}
mosi_pin: ${mosi_pin}
miso_pin: ${miso_pin}
sensor:
- platform: ade7953_spi
cs_pin: ${cs_pin}
irq_pin: ${irq_pin}
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s

View File

@ -1,36 +1,8 @@
spi:
- id: spi_ade7953
clk_pin: 16
mosi_pin: 17
miso_pin: 15
substitutions:
clk_pin: GPIO16
mosi_pin: GPIO17
miso_pin: GPIO15
irq_pin: GPIO13
cs_pin: GPIO5
sensor:
- platform: ade7953_spi
cs_pin: 5
irq_pin: 13
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -1,36 +1,8 @@
spi:
- id: spi_ade7953
clk_pin: 6
mosi_pin: 7
miso_pin: 5
substitutions:
clk_pin: GPIO6
mosi_pin: GPIO7
miso_pin: GPIO5
irq_pin: GPIO9
cs_pin: GPIO8
sensor:
- platform: ade7953_spi
cs_pin: 8
irq_pin: 9
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -1,36 +1,8 @@
spi:
- id: spi_ade7953
clk_pin: 6
mosi_pin: 7
miso_pin: 5
substitutions:
clk_pin: GPIO6
mosi_pin: GPIO7
miso_pin: GPIO5
irq_pin: GPIO9
cs_pin: GPIO8
sensor:
- platform: ade7953_spi
cs_pin: 8
irq_pin: 9
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -1,36 +1,8 @@
spi:
- id: spi_ade7953
clk_pin: 16
mosi_pin: 17
miso_pin: 15
substitutions:
clk_pin: GPIO16
mosi_pin: GPIO17
miso_pin: GPIO15
irq_pin: GPIO13
cs_pin: GPIO5
sensor:
- platform: ade7953_spi
cs_pin: 5
irq_pin: 13
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -1,36 +1,8 @@
spi:
- id: spi_ade7953
clk_pin: 14
mosi_pin: 13
miso_pin: 12
substitutions:
clk_pin: GPIO14
mosi_pin: GPIO13
miso_pin: GPIO12
irq_pin: GPIO5
cs_pin: GPIO15
sensor:
- platform: ade7953_spi
cs_pin: 15
irq_pin: 5
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -1,36 +1,8 @@
spi:
- id: spi_ade7953
clk_pin: 2
mosi_pin: 3
miso_pin: 4
substitutions:
clk_pin: GPIO2
mosi_pin: GPIO3
miso_pin: GPIO4
irq_pin: GPIO5
cs_pin: GPIO6
sensor:
- platform: ade7953_spi
cs_pin: 5
irq_pin: 6
voltage:
name: ADE7953 Voltage
id: ade7953_voltage
current_a:
name: ADE7953 Current A
id: ade7953_current_a
current_b:
name: ADE7953 Current B
id: ade7953_current_b
power_factor_a:
name: ADE7953 Power Factor A
power_factor_b:
name: ADE7953 Power Factor B
apparent_power_a:
name: ADE7953 Apparent Power A
apparent_power_b:
name: ADE7953 Apparent Power B
active_power_a:
name: ADE7953 Active Power A
active_power_b:
name: ADE7953 Active Power B
reactive_power_a:
name: ADE7953 Reactive Power A
reactive_power_b:
name: ADE7953 Reactive Power B
update_interval: 1s
<<: !include common.yaml

View File

@ -0,0 +1,14 @@
i2c:
- id: i2c_ads1115
scl: ${scl_pin}
sda: ${sda_pin}
ads1115:
address: 0x48
sensor:
- platform: ads1115
multiplexer: A0_A1
gain: 1.024
sample_rate: 128
id: ads1115_sensor

View File

@ -1,14 +1,5 @@
i2c:
- id: i2c_ads1115
scl: 16
sda: 17
substitutions:
scl_pin: GPIO16
sda_pin: GPIO17
ads1115:
address: 0x48
sensor:
- platform: ads1115
multiplexer: A0_A1
gain: 1.024
sample_rate: 128
id: ads1115_sensor
<<: !include common.yaml

View File

@ -1,14 +1,5 @@
i2c:
- id: i2c_ads1115
scl: 5
sda: 4
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
ads1115:
address: 0x48
sensor:
- platform: ads1115
multiplexer: A0_A1
gain: 1.024
sample_rate: 128
id: ads1115_sensor
<<: !include common.yaml

View File

@ -1,14 +1,5 @@
i2c:
- id: i2c_ads1115
scl: 5
sda: 4
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
ads1115:
address: 0x48
sensor:
- platform: ads1115
multiplexer: A0_A1
gain: 1.024
sample_rate: 128
id: ads1115_sensor
<<: !include common.yaml

View File

@ -1,14 +1,5 @@
i2c:
- id: i2c_ads1115
scl: 16
sda: 17
substitutions:
scl_pin: GPIO16
sda_pin: GPIO17
ads1115:
address: 0x48
sensor:
- platform: ads1115
multiplexer: A0_A1
gain: 1.024
sample_rate: 128
id: ads1115_sensor
<<: !include common.yaml

View File

@ -1,14 +1,5 @@
i2c:
- id: i2c_ads1115
scl: 5
sda: 4
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
ads1115:
address: 0x48
sensor:
- platform: ads1115
multiplexer: A0_A1
gain: 1.024
sample_rate: 128
id: ads1115_sensor
<<: !include common.yaml

View File

@ -1,14 +1,5 @@
i2c:
- id: i2c_ads1115
scl: 5
sda: 4
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
ads1115:
address: 0x48
sensor:
- platform: ads1115
multiplexer: A0_A1
gain: 1.024
sample_rate: 128
id: ads1115_sensor
<<: !include common.yaml

View File

@ -0,0 +1,12 @@
i2c:
- id: i2c_ags10
scl: ${scl_pin}
sda: ${sda_pin}
frequency: 10kHz
sensor:
- platform: ags10
id: ags10_1
tvoc:
name: AGS10 TVOC
update_interval: 60s

View File

@ -1,12 +1,5 @@
i2c:
- id: i2c_ags10
scl: 16
sda: 17
frequency: 10kHz
substitutions:
scl_pin: GPIO16
sda_pin: GPIO17
sensor:
- platform: ags10
id: ags10_1
tvoc:
name: AGS10 TVOC
update_interval: 60s
<<: !include common.yaml

View File

@ -1,12 +1,5 @@
i2c:
- id: i2c_ags10
scl: 5
sda: 4
frequency: 10kHz
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
sensor:
- platform: ags10
id: ags10_1
tvoc:
name: AGS10 TVOC
update_interval: 60s
<<: !include common.yaml

View File

@ -1,12 +1,5 @@
i2c:
- id: i2c_ags10
scl: 5
sda: 4
frequency: 10kHz
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
sensor:
- platform: ags10
id: ags10_1
tvoc:
name: AGS10 TVOC
update_interval: 60s
<<: !include common.yaml

View File

@ -1,12 +1,5 @@
i2c:
- id: i2c_ags10
scl: 16
sda: 17
frequency: 10kHz
substitutions:
scl_pin: GPIO16
sda_pin: GPIO17
sensor:
- platform: ags10
id: ags10_1
tvoc:
name: AGS10 TVOC
update_interval: 60s
<<: !include common.yaml

View File

@ -1,12 +1,5 @@
i2c:
- id: i2c_ags10
scl: 5
sda: 4
frequency: 10kHz
substitutions:
scl_pin: GPIO5
sda_pin: GPIO4
sensor:
- platform: ags10
id: ags10_1
tvoc:
name: AGS10 TVOC
update_interval: 60s
<<: !include common.yaml

View File

@ -0,0 +1,11 @@
i2c:
- id: i2c_aht10
scl: ${scl_pin}
sda: ${sda_pin}
sensor:
- platform: aht10
temperature:
name: Temperature
humidity:
name: Humidity

View File

@ -1,11 +1,5 @@
i2c:
- id: i2c_aht10
scl: 16
sda: 17
substitutions:
scl_pin: GPIO16
sda_pin: GPIO17
sensor:
- platform: aht10
temperature:
name: Temperature
humidity:
name: Humidity
<<: !include common.yaml

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