mirror of
https://github.com/esphome/esphome.git
synced 2026-10-14 02:02:51 +00:00
Merge remote-tracking branch 'origin/dev' into climate-custom-modes-const-vector
# Conflicts: # tests/integration/integration_test_durations.json
This commit is contained in:
@@ -42,8 +42,8 @@ function generateReviewMessages(finalLabels, originalLabelCount, deprecatedInfo,
|
||||
let message = `${TOO_BIG_MARKER}\n### 📦 Pull Request Size\n\n`;
|
||||
|
||||
message +=
|
||||
`Hey @${prAuthor}, thanks for the contribution! Just a heads up, ` +
|
||||
`this PR is on the large side `;
|
||||
`Hey @${prAuthor}, thanks for the contribution. This PR is on the ` +
|
||||
`large side `;
|
||||
|
||||
if (tooManyLabels && tooManyChanges) {
|
||||
message +=
|
||||
@@ -57,16 +57,31 @@ function generateReviewMessages(finalLabels, originalLabelCount, deprecatedInfo,
|
||||
}
|
||||
|
||||
message += `, which makes it harder for maintainers to review.\n\n`;
|
||||
let condition;
|
||||
if (tooManyLabels && tooManyChanges) {
|
||||
condition =
|
||||
`is at most ${TOO_BIG_THRESHOLD} lines (excluding tests) and touches ` +
|
||||
`at most ${MAX_LABELS} components/areas`;
|
||||
} else if (tooManyLabels) {
|
||||
condition = `touches at most ${MAX_LABELS} components/areas`;
|
||||
} else {
|
||||
condition = `is at most ${TOO_BIG_THRESHOLD} lines (excluding tests)`;
|
||||
}
|
||||
message +=
|
||||
`Smaller, focused PRs tend to be reviewed much faster since they ` +
|
||||
`fit into the short gaps between other maintainer work; large ones ` +
|
||||
`often have to wait for a rare long uninterrupted block of time. ` +
|
||||
`If you can break this up into smaller pieces that can be reviewed ` +
|
||||
`independently, it will almost certainly land faster overall.\n\n`;
|
||||
`**This PR will not be reviewed until it ${condition}.** We know ` +
|
||||
`that is not what you want to hear after this much work, and we want ` +
|
||||
`to be upfront so you do not wait for a review that is not coming: ` +
|
||||
`please split the change. The label is removed automatically once ` +
|
||||
`the PR ${condition}.\n\n`;
|
||||
message +=
|
||||
`Before putting more time in, it's also worth popping into ` +
|
||||
`\`#devs\` on [Discord](https://esphome.io/chat) so we can help ` +
|
||||
`you scope things and flag anything already in flight.\n\n`;
|
||||
`There is no exception you can request. Rarely, a maintainer agrees in ` +
|
||||
`\`#devs\` on [Discord](https://esphome.io/chat) to review a change that ` +
|
||||
`genuinely cannot be split as one piece and adds the \`mega-pr\` label, ` +
|
||||
`but that is rare enough that you should plan on splitting rather than ` +
|
||||
`wait for it. Smaller, focused PRs are picked up much faster because ` +
|
||||
`they fit into the short gaps between other maintainer work. For a new ` +
|
||||
`component, the first PR brings the hub and a single platform (for ` +
|
||||
`example \`sensor\`); each further platform is its own PR on top of it.\n\n`;
|
||||
message +=
|
||||
`For more details (including how to split the work up), see: ` +
|
||||
`https://developers.esphome.io/contributing/submitting-your-work/` +
|
||||
@@ -214,6 +229,7 @@ async function handleMaintainerAccessComment(github, context, maintainerAccess)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
generateReviewMessages,
|
||||
handleReviews,
|
||||
handleMaintainerAccessComment
|
||||
};
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
const { describe, it } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { generateReviewMessages } = require('../reviews');
|
||||
|
||||
const MAX_LABELS = 15;
|
||||
const TOO_BIG_THRESHOLD = 1000;
|
||||
|
||||
function tooBigMessage(labelCount, additions) {
|
||||
const files = [{ filename: 'esphome/components/a/a.cpp', additions, deletions: 0 }];
|
||||
const messages = generateReviewMessages(['too-big'], labelCount, null, files, additions, 0, 'someone', MAX_LABELS, TOO_BIG_THRESHOLD);
|
||||
assert.equal(messages.length, 1);
|
||||
return messages[0];
|
||||
}
|
||||
|
||||
describe('too-big review message', () => {
|
||||
it('names the line cap when the PR is too long', () => {
|
||||
const message = tooBigMessage(3, 1500);
|
||||
assert.match(message, /will not be reviewed until it is at most 1000 lines \(excluding tests\)\./);
|
||||
assert.match(message, /removed automatically once the PR is at most 1000 lines/);
|
||||
assert.doesNotMatch(message, /components\/areas\./);
|
||||
});
|
||||
|
||||
it('names the area cap when the PR touches too many areas but is short', () => {
|
||||
const message = tooBigMessage(20, 200);
|
||||
assert.match(message, /will not be reviewed until it touches at most 15 components\/areas\./);
|
||||
assert.doesNotMatch(message, /until it is at most 1000 lines/);
|
||||
});
|
||||
|
||||
it('names both caps when both are exceeded', () => {
|
||||
const message = tooBigMessage(20, 1500);
|
||||
assert.match(message, /is at most 1000 lines \(excluding tests\) and touches at most 15 components\/areas\./);
|
||||
});
|
||||
|
||||
it('tells new-component authors to bring one platform first', () => {
|
||||
assert.match(tooBigMessage(3, 1500), /hub and a single platform/);
|
||||
assert.match(tooBigMessage(3, 1500), /mega-pr/);
|
||||
});
|
||||
});
|
||||
+10
-2
@@ -156,6 +156,7 @@ esphome/components/ds1307/* @badbadc0ffee
|
||||
esphome/components/ds1603l/* @JakeLC15
|
||||
esphome/components/ds2484/* @mrk-its
|
||||
esphome/components/ds248x/* @tomwellnitz
|
||||
esphome/components/ds3231/* @linkedupbits
|
||||
esphome/components/dsmr/* @glmnet @PolarGoose
|
||||
esphome/components/duty_time/* @dudanov
|
||||
esphome/components/ee895/* @Stock-M
|
||||
@@ -183,6 +184,7 @@ esphome/components/esp32_camera_web_server/* @ayufan
|
||||
esphome/components/esp32_can/* @Sympatron
|
||||
esphome/components/esp32_hosted/* @swoboda1337
|
||||
esphome/components/esp32_hosted/update/* @swoboda1337
|
||||
esphome/components/esp32_power_management/* @rwrozelle
|
||||
esphome/components/esp32_rmt/* @jesserockz
|
||||
esphome/components/esp32_rmt_led_strip/* @jesserockz
|
||||
esphome/components/esp8266/* @esphome/core
|
||||
@@ -303,6 +305,7 @@ esphome/components/ld2410/* @regevbr @sebcaps
|
||||
esphome/components/ld2412/* @Rihan9
|
||||
esphome/components/ld2420/* @descipher
|
||||
esphome/components/ld2450/* @hareeshmu
|
||||
esphome/components/ld2460/* @jesusvallejo
|
||||
esphome/components/ld24xx/* @kbx81
|
||||
esphome/components/ld6002b/* @hepter
|
||||
esphome/components/ledc/* @OttoWinter
|
||||
@@ -311,6 +314,9 @@ esphome/components/libretiny_pwm/* @kuba2k2
|
||||
esphome/components/light/* @esphome/core
|
||||
esphome/components/lightwaverf/* @max246
|
||||
esphome/components/lilygo_t5_47/touchscreen/* @jesserockz
|
||||
esphome/components/lis2dw12/* @latonita
|
||||
esphome/components/lis2dw12_i2c/* @latonita
|
||||
esphome/components/lis2dw12_spi/* @latonita
|
||||
esphome/components/lm75b/* @beormund
|
||||
esphome/components/ln882h_ble/* @Bl00d-B0b
|
||||
esphome/components/ln882h_ble_tracker/* @Bl00d-B0b
|
||||
@@ -347,7 +353,6 @@ esphome/components/mcp4461/* @p1ngb4ck
|
||||
esphome/components/mcp4728/* @berfenger
|
||||
esphome/components/mcp47a1/* @jesserockz
|
||||
esphome/components/mcp9600/* @mreditor97
|
||||
esphome/components/mcp9808/* @k7hpn
|
||||
esphome/components/md5/* @esphome/core
|
||||
esphome/components/mdns/* @esphome/core
|
||||
esphome/components/media_player/* @jesserockz
|
||||
@@ -413,6 +418,7 @@ esphome/components/pca9554/* @bdraco @clydebarrow @hwstar
|
||||
esphome/components/pcf85063/* @brogon
|
||||
esphome/components/pcf8563/* @KoenBreeman
|
||||
esphome/components/pcm5122/* @remcom
|
||||
esphome/components/pd_pioneer_ir/* @martinsah
|
||||
esphome/components/pi4ioe5v6408/* @jesserockz
|
||||
esphome/components/pid/* @OttoWinter
|
||||
esphome/components/pipsolar/* @andreashergert1984
|
||||
@@ -431,6 +437,7 @@ esphome/components/pn7160/* @jesserockz @kbx81
|
||||
esphome/components/pn7160_i2c/* @jesserockz @kbx81
|
||||
esphome/components/pn7160_spi/* @jesserockz @kbx81
|
||||
esphome/components/pn71xx/* @jesserockz @kbx81
|
||||
esphome/components/power_management/* @rwrozelle
|
||||
esphome/components/power_supply/* @esphome/core
|
||||
esphome/components/preferences/* @esphome/core
|
||||
esphome/components/provisioning/* @esphome/core
|
||||
@@ -503,6 +510,7 @@ esphome/components/shelly_dimmer/* @edge90 @rnauber
|
||||
esphome/components/sht3xd/* @mrtoy-me
|
||||
esphome/components/sht4x/* @sjtrny
|
||||
esphome/components/shutdown/* @esphome/core @jsuanet
|
||||
esphome/components/siemens_ira211/* @fonix232
|
||||
esphome/components/sigma_delta_output/* @Cat-Ion
|
||||
esphome/components/sim800l/* @glmnet
|
||||
esphome/components/sm10bit_base/* @Cossid
|
||||
@@ -639,7 +647,7 @@ esphome/components/web_server_idf/* @dentra
|
||||
esphome/components/weikai/* @DrCoolZic
|
||||
esphome/components/weikai_i2c/* @DrCoolZic
|
||||
esphome/components/weikai_spi/* @DrCoolZic
|
||||
esphome/components/whirlpool/* @glmnet
|
||||
esphome/components/whirlpool/* @arpena @glmnet
|
||||
esphome/components/whynter/* @aeonsablaze
|
||||
esphome/components/wiegand/* @ssieb
|
||||
esphome/components/wireguard/* @droscy @lhoracek @thomas0bernard
|
||||
|
||||
+130
-13
@@ -48,8 +48,11 @@ from esphome.const import (
|
||||
CONF_WEB_SERVER,
|
||||
CONF_WIFI,
|
||||
ENV_NOGITIGNORE,
|
||||
KEY_CORE,
|
||||
KEY_ESP32,
|
||||
KEY_TARGET_PLATFORM,
|
||||
KEY_VARIANT,
|
||||
PLATFORM_HOST,
|
||||
SECRETS_FILES,
|
||||
ErrorFormat,
|
||||
Toolchain,
|
||||
@@ -70,6 +73,7 @@ from esphome.util import (
|
||||
get_serial_ports,
|
||||
is_picotool_usb_permission_error,
|
||||
list_yaml_files,
|
||||
read_secret_line,
|
||||
run_external_command,
|
||||
run_external_process,
|
||||
safe_print,
|
||||
@@ -1232,14 +1236,28 @@ def upload_program(
|
||||
config: ConfigType, args: ArgsProtocol, devices: list[str]
|
||||
) -> tuple[int, str | None]:
|
||||
host = devices[0]
|
||||
port_type = get_port_type(host)
|
||||
ota_key = getattr(args, "ota_key", None)
|
||||
if ota_key and port_type in (PortType.SERIAL, PortType.BOOTSEL):
|
||||
_LOGGER.warning(
|
||||
"The presented OTA key only applies to network uploads; ignored for %s",
|
||||
host,
|
||||
)
|
||||
|
||||
platform_upload = platform_hooks.get_platform_hook(
|
||||
CORE.target_platform, "upload_program"
|
||||
)
|
||||
if platform_upload is not None and platform_upload(config, args, host):
|
||||
if ota_key and port_type not in (PortType.SERIAL, PortType.BOOTSEL):
|
||||
# A platform's own network path (nrf52 mcumgr) has no key handshake
|
||||
_LOGGER.warning(
|
||||
"The presented OTA key only applies to the %s OTA platform; "
|
||||
"ignored for %s",
|
||||
CONF_ESPHOME,
|
||||
host,
|
||||
)
|
||||
return 0, host
|
||||
|
||||
port_type = get_port_type(host)
|
||||
|
||||
# MQTT and MQTTIP are also OTA paths; MQTTIP gets resolved to a real IP later by
|
||||
# _resolve_network_devices(). Only SERIAL and BOOTSEL are non-OTA upload paths.
|
||||
is_partition_table = getattr(args, "partition_table", False)
|
||||
@@ -1282,6 +1300,8 @@ def upload_program(
|
||||
network_devices = _resolve_network_devices(devices, config, args)
|
||||
|
||||
if chosen_platform == CONF_WEB_SERVER:
|
||||
if ota_key:
|
||||
raise EsphomeError(OTA_KEY_PLATFORM_ERROR)
|
||||
if is_partition_table or is_bootloader:
|
||||
raise EsphomeError(
|
||||
f"{option_string} is only supported with the esphome OTA platform; "
|
||||
@@ -1295,6 +1315,17 @@ def upload_program(
|
||||
return _upload_via_native_api(config, network_devices, args)
|
||||
|
||||
|
||||
def _ota_upload_platforms(config: ConfigType) -> dict[str, None]:
|
||||
"""The network OTA platforms the config provides, one entry each, in
|
||||
config order; the web_server final-validate hook merges duplicates."""
|
||||
return {
|
||||
ota_platform: None
|
||||
for ota_item in config.get(CONF_OTA, [])
|
||||
if (ota_platform := ota_item.get(CONF_PLATFORM))
|
||||
in (CONF_ESPHOME, CONF_WEB_SERVER)
|
||||
}
|
||||
|
||||
|
||||
def _choose_ota_platform(config: ConfigType, requested: str | None) -> str:
|
||||
"""Pick the OTA platform to use, optionally honoring ``--ota-platform``.
|
||||
|
||||
@@ -1307,16 +1338,7 @@ def _choose_ota_platform(config: ConfigType, requested: str | None) -> str:
|
||||
stream on ESP32/LibreTiny, which inflate it as it arrives.) Falls back to
|
||||
``web_server`` only when that is the only available platform.
|
||||
"""
|
||||
# Use a dict (insertion-ordered) instead of a list so error messages and
|
||||
# membership checks see one entry per platform even if the user has
|
||||
# multiple ``ota:`` items of the same platform; the web_server OTA
|
||||
# platform's final-validate hook merges duplicates anyway.
|
||||
available: dict[str, None] = {}
|
||||
for ota_item in config.get(CONF_OTA, []):
|
||||
ota_platform = ota_item.get(CONF_PLATFORM)
|
||||
if ota_platform in (CONF_ESPHOME, CONF_WEB_SERVER):
|
||||
available[ota_platform] = None
|
||||
|
||||
available = _ota_upload_platforms(config)
|
||||
if not available:
|
||||
raise EsphomeError(
|
||||
f"Cannot upload Over the Air as the {CONF_OTA} configuration is not "
|
||||
@@ -1356,7 +1378,12 @@ def _upload_via_native_api(
|
||||
noise_psk = None
|
||||
plaintext_fallback = False
|
||||
allow_plaintext_upload = False
|
||||
if (encryption_conf := ota_conf.get(CONF_ENCRYPTION)) is not None:
|
||||
if ota_key := getattr(args, "ota_key", None):
|
||||
# The user presents a key the device still runs instead of the
|
||||
# configured one (a key change in progress); an explicit key never
|
||||
# downgrades to plaintext
|
||||
noise_psk = ota_key
|
||||
elif (encryption_conf := ota_conf.get(CONF_ENCRYPTION)) is not None:
|
||||
noise_psk = encryption_conf.get(CONF_KEY)
|
||||
allow_plaintext_upload = bool(
|
||||
encryption_conf.get(espota2.CONF_ALLOW_PLAINTEXT_UPLOAD)
|
||||
@@ -1738,7 +1765,60 @@ def command_compile(args: ArgsProtocol, config: ConfigType) -> int | None:
|
||||
return 0
|
||||
|
||||
|
||||
ENV_OTA_KEY = "ESPHOME_OTA_KEY"
|
||||
OTA_KEY_PLATFORM_ERROR = (
|
||||
f"--prompt-ota-key and {ENV_OTA_KEY} only apply to the {CONF_ESPHOME} OTA "
|
||||
"platform; to flash by serial instead, name the port with --device"
|
||||
)
|
||||
|
||||
|
||||
def _read_ota_key(args: ArgsProtocol, config: ConfigType) -> None:
|
||||
"""Take the key to present to the device for this upload, from the
|
||||
prompt or from ESPHOME_OTA_KEY, before any compile so the prompt is
|
||||
not buried in build output."""
|
||||
prompt = getattr(args, "prompt_ota_key", False)
|
||||
env_key = getattr(args, "env_ota_key", None)
|
||||
if not prompt and env_key is None:
|
||||
return
|
||||
if CORE.data.get(KEY_CORE, {}).get(KEY_TARGET_PLATFORM) == PLATFORM_HOST:
|
||||
_LOGGER.warning("A host program runs locally; the presented OTA key is ignored")
|
||||
return
|
||||
# The HTTP path has no key handshake; decide before prompting or
|
||||
# compiling. A serial target is a serial flash: the key is not even
|
||||
# asked for, and --ota-platform means nothing to it. Every entry must
|
||||
# be serial: a missing port is skipped and the next entry may be a host
|
||||
devices = getattr(args, "device", None) or []
|
||||
serial_target = bool(devices) and all(
|
||||
device == "SERIAL"
|
||||
or get_port_type(device) in (PortType.SERIAL, PortType.BOOTSEL)
|
||||
for device in devices
|
||||
)
|
||||
chosen = (
|
||||
_choose_ota_platform(config, getattr(args, "ota_platform", None))
|
||||
if not serial_target and _ota_upload_platforms(config)
|
||||
else None
|
||||
)
|
||||
if chosen == CONF_WEB_SERVER:
|
||||
raise EsphomeError(OTA_KEY_PLATFORM_ERROR)
|
||||
from esphome.components.noise import validate_encryption_key
|
||||
from esphome.config_validation import Invalid
|
||||
|
||||
if serial_target:
|
||||
_LOGGER.warning(
|
||||
"The presented OTA key only applies to network uploads; ignored for %s",
|
||||
", ".join(devices),
|
||||
)
|
||||
return
|
||||
key = read_secret_line("OTA encryption key: ") if prompt else env_key
|
||||
try:
|
||||
validate_encryption_key(key)
|
||||
except Invalid as err:
|
||||
raise EsphomeError(f"Invalid OTA encryption key: {err}") from err
|
||||
args.ota_key = key
|
||||
|
||||
|
||||
def command_upload(args: ArgsProtocol, config: ConfigType) -> int | None:
|
||||
_read_ota_key(args, config)
|
||||
# Get devices, resolving special identifiers like OTA
|
||||
devices = choose_upload_log_host(
|
||||
default=args.device,
|
||||
@@ -1786,6 +1866,7 @@ def command_run(args: ArgsProtocol, config: ConfigType) -> int | None:
|
||||
# Elsewhere the flag is ignored, so serial stays fine there.
|
||||
_LOGGER.error("--skip-bootloader builds cannot be flashed over serial")
|
||||
return 1
|
||||
_read_ota_key(args, config)
|
||||
exit_code = write_cpp(config)
|
||||
if exit_code != 0:
|
||||
return exit_code
|
||||
@@ -2216,6 +2297,15 @@ def _error_format(value: str) -> ErrorFormat:
|
||||
) from None
|
||||
|
||||
|
||||
ARGUMENT_HELP_PROMPT_OTA_KEY = (
|
||||
"Ask for the OTA encryption key to present to the device instead of using "
|
||||
"the one in the configuration, for a device that still runs a previous key. "
|
||||
"The key is read without echo, or as one line from stdin when that is not "
|
||||
"a terminal; it is never taken from the command line. A calling program "
|
||||
f"can hand the key over in the {ENV_OTA_KEY} environment variable instead."
|
||||
)
|
||||
|
||||
|
||||
def parse_args(argv):
|
||||
options_parser = argparse.ArgumentParser(add_help=False)
|
||||
options_parser.add_argument(
|
||||
@@ -2384,6 +2474,11 @@ def parse_args(argv):
|
||||
help="Upload as partition table (OTA).",
|
||||
action="store_true",
|
||||
)
|
||||
parser_upload.add_argument(
|
||||
"--prompt-ota-key",
|
||||
action="store_true",
|
||||
help=ARGUMENT_HELP_PROMPT_OTA_KEY,
|
||||
)
|
||||
parser_upload.add_argument(
|
||||
"--bootloader",
|
||||
help="Upload as bootloader (OTA).",
|
||||
@@ -2464,6 +2559,11 @@ def parse_args(argv):
|
||||
"(HTTP Basic auth) when that is the only configured platform."
|
||||
),
|
||||
)
|
||||
parser_run.add_argument(
|
||||
"--prompt-ota-key",
|
||||
action="store_true",
|
||||
help=ARGUMENT_HELP_PROMPT_OTA_KEY,
|
||||
)
|
||||
|
||||
parser_clean = subparsers.add_parser(
|
||||
"clean-mqtt",
|
||||
@@ -2689,6 +2789,23 @@ def run_esphome(argv):
|
||||
args.log_level = "CRITICAL"
|
||||
|
||||
setup_log(log_level=args.log_level)
|
||||
# Taken out of the environment before any command runs, so no build
|
||||
# tool inherits a key a calling program handed over
|
||||
args.env_ota_key = os.environ.pop(ENV_OTA_KEY, None)
|
||||
if args.command in ("upload", "run"):
|
||||
# One key is one device's; several configs run in child processes
|
||||
# that would never see it
|
||||
if (args.env_ota_key is not None or args.prompt_ota_key) and len(
|
||||
args.configuration
|
||||
) > 1:
|
||||
raise EsphomeError(
|
||||
f"--prompt-ota-key and {ENV_OTA_KEY} take one configuration; "
|
||||
f"{len(args.configuration)} were given"
|
||||
)
|
||||
elif args.env_ota_key is not None:
|
||||
_LOGGER.warning(
|
||||
"%s is set but the %s command does not use it", ENV_OTA_KEY, args.command
|
||||
)
|
||||
_warn_if_source_tree_mismatch()
|
||||
_warn_if_intel_macos()
|
||||
|
||||
|
||||
+97
-17
@@ -1,4 +1,4 @@
|
||||
from collections.abc import Callable, Sequence
|
||||
from collections.abc import Awaitable, Callable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
import logging
|
||||
import string
|
||||
@@ -465,6 +465,22 @@ def register_apply_action(
|
||||
) -> None:
|
||||
"""Register an action that only forwards config values to its parent, with no C++ class.
|
||||
|
||||
See ``apply_action_builder``.
|
||||
"""
|
||||
register_action(name, ApplyAction, schema, synchronous=True)(
|
||||
apply_action_builder(name, schema, *fields, call=call, id_key=id_key)
|
||||
)
|
||||
|
||||
|
||||
def apply_action_builder(
|
||||
name: str,
|
||||
schema: cv.Schema,
|
||||
*fields: ApplyField | ApplyCall,
|
||||
call: str | None = None,
|
||||
id_key: str = CONF_ID,
|
||||
) -> Callable[..., Awaitable[MockObj]]:
|
||||
"""The builder ``register_apply_action`` registers, for a caller that wraps it.
|
||||
|
||||
Generates one static function with the parent (read from ``id_key``) and constants baked
|
||||
in, lambdas called inline with the trigger args, and an ``ApplyAction`` templated on it.
|
||||
A constant that is an id (``cv.use_id`` under ``cv.templatable``) is the object it names.
|
||||
@@ -515,7 +531,7 @@ def register_apply_action(
|
||||
action_id, cg.void, template_arg, lambda_args, statements
|
||||
)
|
||||
|
||||
register_action(name, ApplyAction, schema, synchronous=True)(builder)
|
||||
return builder
|
||||
|
||||
|
||||
def _apply_call_active(members: list[tuple[Any, Any, Any]], values: list[Any]) -> bool:
|
||||
@@ -724,7 +740,7 @@ async def condition_group_to_code(
|
||||
if len(conditions) == 1:
|
||||
return conditions[0]
|
||||
return cg.new_Pvariable(
|
||||
condition_id, cg.TemplateArguments(len(conditions), *template_arg), conditions
|
||||
condition_id, cg.TemplateArguments(len(conditions), *template_arg), *conditions
|
||||
)
|
||||
|
||||
|
||||
@@ -840,11 +856,13 @@ async def if_action_to_code(
|
||||
condition = await build_condition(config[cond_conf], template_arg, args)
|
||||
var = cg.new_Pvariable(action_id, if_template_arg, condition)
|
||||
if CONF_THEN in config:
|
||||
actions = await build_action_list(config[CONF_THEN], template_arg, args)
|
||||
cg.add(var.add_then(actions))
|
||||
for action in await build_action_list(config[CONF_THEN], template_arg, args):
|
||||
cg.add(var.add_then_action(action))
|
||||
cg.add(var.finish_then())
|
||||
if has_else:
|
||||
actions = await build_action_list(config[CONF_ELSE], template_arg, args)
|
||||
cg.add(var.add_else(actions))
|
||||
for action in await build_action_list(config[CONF_ELSE], template_arg, args):
|
||||
cg.add(var.add_else_action(action))
|
||||
cg.add(var.finish_else())
|
||||
return var
|
||||
|
||||
|
||||
@@ -867,8 +885,9 @@ async def while_action_to_code(
|
||||
) -> MockObj:
|
||||
condition = await build_condition(config[CONF_CONDITION], template_arg, args)
|
||||
var = cg.new_Pvariable(action_id, template_arg, condition)
|
||||
actions = await build_action_list(config[CONF_THEN], template_arg, args)
|
||||
cg.add(var.add_then(actions))
|
||||
for action in await build_action_list(config[CONF_THEN], template_arg, args):
|
||||
cg.add(var.add_then_action(action))
|
||||
cg.add(var.finish_then())
|
||||
return var
|
||||
|
||||
|
||||
@@ -897,7 +916,9 @@ async def repeat_action_to_code(
|
||||
cg.TemplateArguments(cg.uint32, *template_arg.args),
|
||||
[(cg.uint32, "iteration"), *args],
|
||||
)
|
||||
cg.add(var.add_then(actions))
|
||||
for action in actions:
|
||||
cg.add(var.add_then_action(action))
|
||||
cg.add(var.finish_then())
|
||||
return var
|
||||
|
||||
|
||||
@@ -1033,21 +1054,79 @@ def has_non_synchronous_actions(actions: ConfigType) -> bool:
|
||||
Non-synchronous actions (delay, wait_until, script.wait, etc.) store
|
||||
trigger args for later execution, making non-owning types like StringRef
|
||||
unsafe.
|
||||
|
||||
Accepts an action list, a single action, or an automation. Only the keys of
|
||||
action entries are looked up as action names; the options of an action are
|
||||
only searched for nested action lists (``then:``, ``else:``, ...), so an
|
||||
option that shares a name with an action, such as the ``delay:`` option of
|
||||
``speaker_source.set_playlist_delay``, is not mistaken for that action.
|
||||
"""
|
||||
if isinstance(actions, list):
|
||||
return any(has_non_synchronous_actions(item) for item in actions)
|
||||
if isinstance(actions, dict):
|
||||
for key in actions:
|
||||
for key, options in actions.items():
|
||||
if key in ACTION_REGISTRY and not ACTION_REGISTRY[key].synchronous:
|
||||
return True
|
||||
return any(
|
||||
has_non_synchronous_actions(v)
|
||||
for v in actions.values()
|
||||
if isinstance(v, (list, dict))
|
||||
)
|
||||
if _options_have_non_synchronous_actions(options):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _options_have_non_synchronous_actions(options: Any) -> bool:
|
||||
"""Search an action's options for nested action lists, without treating option keys as actions."""
|
||||
if isinstance(options, list):
|
||||
return has_non_synchronous_actions(options)
|
||||
if isinstance(options, dict):
|
||||
return any(_options_have_non_synchronous_actions(v) for v in options.values())
|
||||
return False
|
||||
|
||||
|
||||
def validate_no_deferring_actions(
|
||||
context: str, data: str = "the trigger data"
|
||||
) -> Callable[[ConfigType], ConfigType]:
|
||||
"""Return a validator that rejects deferring actions in a validated automation.
|
||||
|
||||
Use it for triggers whose arguments only live while the callback runs (views into a reused
|
||||
buffer, a JSON document freed on return, ...): deferring actions keep the arguments for later.
|
||||
|
||||
:param context: Where the automation is, for the error message, e.g. ``"on_json and on_data"``.
|
||||
:param data: What is only valid while the automation runs, for the error message.
|
||||
"""
|
||||
|
||||
def validator(value: ConfigType) -> ConfigType:
|
||||
if has_non_synchronous_actions(value):
|
||||
raise cv.Invalid(
|
||||
f"Deferring actions (delay, wait_until, script.wait, ...) are not allowed in "
|
||||
f"{context}: {data} is only valid while the automation runs. Copy what you need "
|
||||
"into globals first, then defer in a separate script or automation."
|
||||
)
|
||||
return value
|
||||
|
||||
return validator
|
||||
|
||||
|
||||
def validate_synchronous_automation(
|
||||
context: str,
|
||||
data: str = "the trigger data",
|
||||
extra_schema=None,
|
||||
extra_validators=None,
|
||||
single: bool = False,
|
||||
) -> cv.All:
|
||||
"""``validate_automation()`` that also rejects deferring actions.
|
||||
|
||||
See ``validate_no_deferring_actions()`` for ``context`` and ``data``; the other parameters are
|
||||
passed to ``validate_automation()``.
|
||||
"""
|
||||
return cv.All(
|
||||
validate_automation(
|
||||
extra_schema=extra_schema,
|
||||
extra_validators=extra_validators,
|
||||
single=single,
|
||||
),
|
||||
validate_no_deferring_actions(context, data),
|
||||
)
|
||||
|
||||
|
||||
async def _new_automation(
|
||||
args: TemplateArgsType, config: ConfigType, *ctor_args: MockObj
|
||||
) -> MockObj:
|
||||
@@ -1055,7 +1134,8 @@ async def _new_automation(
|
||||
templ = cg.TemplateArguments(*(arg[0] for arg in args))
|
||||
obj = cg.new_Pvariable(config[CONF_AUTOMATION_ID], templ, *ctor_args)
|
||||
actions = await build_action_list(config[CONF_THEN], templ, args)
|
||||
cg.add(obj.add_actions(actions))
|
||||
for action in actions:
|
||||
cg.add(obj.add_action(action))
|
||||
return obj
|
||||
|
||||
|
||||
|
||||
+8
-12
@@ -102,25 +102,21 @@ _KNOWN_FILE_EXTENSIONS = frozenset(
|
||||
)
|
||||
|
||||
|
||||
# Matches !secret references in YAML text. An optional surrounding
|
||||
# quote pair around the key is allowed and ignored: YAML treats
|
||||
# ``!secret 'foo'`` and ``!secret foo`` as the same key. This is
|
||||
# intentionally a simple regex scan rather than a YAML parse — it may
|
||||
# match inside comments or multi-line strings, which is the conservative
|
||||
# direction (include more secrets rather than fewer).
|
||||
_SECRET_RE = re.compile(r"""!secret\s+['"]?([^\s'"]+)""")
|
||||
|
||||
|
||||
def _find_used_secret_keys(yaml_files: list[Path]) -> set[str]:
|
||||
"""Scan YAML files for ``!secret <key>`` references."""
|
||||
keys: set[str] = set()
|
||||
for fpath in yaml_files:
|
||||
try:
|
||||
text = fpath.read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError):
|
||||
except (OSError, UnicodeDecodeError) as err:
|
||||
_LOGGER.warning(
|
||||
"Could not scan %s for !secret references (%s); the bundled "
|
||||
"secret set may be incomplete",
|
||||
fpath,
|
||||
err,
|
||||
)
|
||||
continue
|
||||
for match in _SECRET_RE.finditer(text):
|
||||
keys.add(match.group(1))
|
||||
keys |= yaml_util.find_secret_references(text)
|
||||
return keys
|
||||
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ from esphome.cpp_generator import ( # noqa: F401
|
||||
safe_exp,
|
||||
set_cpp_standard,
|
||||
shared_progmem_array,
|
||||
shared_progmem_string,
|
||||
statement,
|
||||
static_const_array,
|
||||
static_function,
|
||||
|
||||
@@ -128,10 +128,10 @@ class ADCSensor final : public sensor::Sensor, public PollingComponent, public v
|
||||
#endif // USE_RP2
|
||||
|
||||
protected:
|
||||
uint8_t sample_count_{1};
|
||||
bool output_raw_{false};
|
||||
uint8_t sample_count_{1}; // Must match DEFAULT_SAMPLES in sensor.py
|
||||
bool output_raw_{false}; // Must match CONF_RAW default in sensor.py
|
||||
InternalGPIOPin *pin_;
|
||||
SamplingMode sampling_mode_{SamplingMode::AVG};
|
||||
SamplingMode sampling_mode_{SamplingMode::AVG}; // Must match DEFAULT_SAMPLING_MODE in sensor.py
|
||||
|
||||
#ifdef USE_ESP32
|
||||
float sample_autorange_();
|
||||
@@ -139,7 +139,7 @@ class ADCSensor final : public sensor::Sensor, public PollingComponent, public v
|
||||
bool autorange_{false};
|
||||
adc_oneshot_unit_handle_t adc_handle_{nullptr};
|
||||
adc_cali_handle_t calibration_handle_{nullptr};
|
||||
adc_atten_t attenuation_{ADC_ATTEN_DB_0};
|
||||
adc_atten_t attenuation_{ADC_ATTEN_DB_0}; // Must match DEFAULT_ATTENUATION in sensor.py
|
||||
adc_channel_t channel_{};
|
||||
adc_unit_t adc_unit_{};
|
||||
struct SetupFlags {
|
||||
|
||||
@@ -48,6 +48,11 @@ AUTO_LOAD = ["voltage_sampler"]
|
||||
CONF_SAMPLES = "samples"
|
||||
CONF_SAMPLING_MODE = "sampling_mode"
|
||||
|
||||
# Keep in sync with the initializers in adc_sensor.h
|
||||
DEFAULT_ATTENUATION = "0db"
|
||||
DEFAULT_SAMPLING_MODE = "avg"
|
||||
DEFAULT_SAMPLES = 1
|
||||
|
||||
|
||||
_attenuation = cv.enum(ATTENUATION_MODES, lower=True)
|
||||
_sampling_mode = cv.enum(SAMPLING_MODES, lower=True)
|
||||
@@ -65,7 +70,10 @@ def validate_config(config: ConfigType) -> ConfigType:
|
||||
):
|
||||
raise cv.Invalid("ESP32-S31 only supports 'attenuation: 0db'")
|
||||
|
||||
if config.get(CONF_ATTENUATION, None) == "auto" and config.get(CONF_SAMPLES, 1) > 1:
|
||||
if (
|
||||
config.get(CONF_ATTENUATION, None) == "auto"
|
||||
and config.get(CONF_SAMPLES, DEFAULT_SAMPLES) > 1
|
||||
):
|
||||
raise cv.Invalid(
|
||||
"Automatic attenuation cannot be used when multisampling is set"
|
||||
)
|
||||
@@ -113,12 +121,16 @@ CONFIG_SCHEMA = cv.All(
|
||||
{
|
||||
cv.Required(CONF_PIN): validate_adc_pin,
|
||||
cv.Optional(CONF_RAW, default=False): cv.boolean,
|
||||
cv.SplitDefault(CONF_ATTENUATION, esp32="0db"): cv.All(
|
||||
cv.SplitDefault(CONF_ATTENUATION, esp32=DEFAULT_ATTENUATION): cv.All(
|
||||
cv.only_on_esp32, _attenuation
|
||||
),
|
||||
cv.OnlyWith(CONF_NRF_SAADC, PLATFORM_NRF52): cv.declare_id(adc_dt_spec),
|
||||
cv.Optional(CONF_SAMPLES, default=1): cv.int_range(min=1, max=255),
|
||||
cv.Optional(CONF_SAMPLING_MODE, default="avg"): _sampling_mode,
|
||||
cv.Optional(CONF_SAMPLES, default=DEFAULT_SAMPLES): cv.int_range(
|
||||
min=1, max=255
|
||||
),
|
||||
cv.Optional(
|
||||
CONF_SAMPLING_MODE, default=DEFAULT_SAMPLING_MODE
|
||||
): _sampling_mode,
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("60s")),
|
||||
@@ -155,9 +167,13 @@ async def to_code(config: ConfigType) -> None:
|
||||
pin = await cg.gpio_pin_expression(config[CONF_PIN])
|
||||
cg.add(var.set_pin(pin))
|
||||
|
||||
cg.add(var.set_output_raw(config[CONF_RAW]))
|
||||
cg.add(var.set_sample_count(config[CONF_SAMPLES]))
|
||||
cg.add(var.set_sampling_mode(config[CONF_SAMPLING_MODE]))
|
||||
# Skip the setters when the config matches the C++ initializers.
|
||||
if config[CONF_RAW]:
|
||||
cg.add(var.set_output_raw(True))
|
||||
if (samples := config[CONF_SAMPLES]) != DEFAULT_SAMPLES:
|
||||
cg.add(var.set_sample_count(samples))
|
||||
if (sampling_mode := config[CONF_SAMPLING_MODE]) != DEFAULT_SAMPLING_MODE:
|
||||
cg.add(var.set_sampling_mode(sampling_mode))
|
||||
|
||||
if CORE.is_esp32:
|
||||
# Re-enable ESP-IDF's ADC driver (excluded by default to save compile time)
|
||||
@@ -166,7 +182,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
if attenuation := config.get(CONF_ATTENUATION):
|
||||
if attenuation == "auto":
|
||||
cg.add(var.set_autorange(cg.global_ns.true))
|
||||
else:
|
||||
elif attenuation != DEFAULT_ATTENUATION:
|
||||
cg.add(var.set_attenuation(attenuation))
|
||||
|
||||
variant = get_esp32_variant()
|
||||
|
||||
@@ -54,7 +54,7 @@ from esphome.const import (
|
||||
from esphome.core import CORE, ID, CoroPriority, EsphomeError, coroutine_with_priority
|
||||
from esphome.cpp_generator import Expression, MockObj, TemplateArgsType
|
||||
import esphome.final_validate as fv
|
||||
from esphome.helpers import cpp_string_escape, fnv1_hash
|
||||
from esphome.helpers import fnv1_hash
|
||||
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor
|
||||
from esphome.types import ConfigFragmentType, ConfigType
|
||||
|
||||
@@ -537,28 +537,11 @@ FINAL_VALIDATE_SCHEMA = cv.All(
|
||||
)
|
||||
|
||||
|
||||
def _add_action_strings(
|
||||
index: int, strings: list[str | None], interned: dict[str, MockObj]
|
||||
) -> MockObj:
|
||||
"""Emit the PROGMEM string table for one action.
|
||||
|
||||
Each string is its own PROGMEM array because on ESP8266 .rodata is RAM, and identical
|
||||
strings are shared between actions through `interned`.
|
||||
"""
|
||||
entries: list[MockObj] = []
|
||||
for string in strings:
|
||||
if string is None:
|
||||
entries.append(cg.nullptr)
|
||||
continue
|
||||
if (var := interned.get(string)) is None:
|
||||
var = interned[string] = cg.progmem_array(
|
||||
ID(f"api_action_str{len(interned)}", is_declaration=True, type=cg.char),
|
||||
string,
|
||||
)
|
||||
entries.append(var)
|
||||
def _add_action_strings(index: int, strings: list[str | None]) -> MockObj:
|
||||
"""Emit the PROGMEM string table for one action."""
|
||||
return cg.progmem_array(
|
||||
ID(f"api_action{index}_strings", is_declaration=True, type=cg.const_char_ptr),
|
||||
entries,
|
||||
[cg.nullptr if s is None else cg.shared_progmem_string(s) for s in strings],
|
||||
)
|
||||
|
||||
|
||||
@@ -611,7 +594,6 @@ async def to_code(config: ConfigType) -> None:
|
||||
has_metadata = _has_action_metadata(actions)
|
||||
if has_metadata:
|
||||
cg.add_define("USE_API_USER_DEFINED_ACTION_METADATA")
|
||||
interned_strings: dict[str, MockObj] = {}
|
||||
# Collect all triggers first, then register all at once with initializer_list
|
||||
triggers: list[cg.MockObj] = []
|
||||
for index, conf in enumerate(actions):
|
||||
@@ -656,7 +638,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
service_template_args.append(native)
|
||||
func_args.append((native, name))
|
||||
strings = _action_strings(conf, has_metadata)
|
||||
table = _add_action_strings(index, strings, interned_strings)
|
||||
table = _add_action_strings(index, strings)
|
||||
if CORE.is_esp8266:
|
||||
scratch_size = max(scratch_size, _action_strings_size(strings))
|
||||
# Template args: supports_response mode, then user service arg types
|
||||
@@ -682,7 +664,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
unregister_id,
|
||||
var,
|
||||
)
|
||||
cg.add(auto.add_actions([unregister_action]))
|
||||
cg.add(auto.add_action(unregister_action))
|
||||
# Register all services at once - single allocation, no reallocations
|
||||
cg.add(var.initialize_user_services(triggers))
|
||||
if CORE.is_esp8266 and has_user_actions:
|
||||
@@ -828,14 +810,6 @@ HOMEASSISTANT_ACTION_ACTION_SCHEMA = cv.All(
|
||||
)
|
||||
|
||||
|
||||
def _field_string(value: str) -> Expression:
|
||||
# ESP8266 can only keep a string in flash as its own PROGMEM array
|
||||
literal = cg.RawExpression(cpp_string_escape(value))
|
||||
if CORE.is_esp8266:
|
||||
return cg.shared_progmem_array("ha_field_str", cg.char, literal)
|
||||
return literal
|
||||
|
||||
|
||||
async def _new_service_call_action(
|
||||
server_id: ID,
|
||||
action_id: ID,
|
||||
@@ -858,12 +832,12 @@ async def _new_service_call_action(
|
||||
)
|
||||
|
||||
async def field(key: str | None, value: Any, output_type: Any = None) -> Expression:
|
||||
key_exp = cg.nullptr if key is None else _field_string(key)
|
||||
key_exp = cg.nullptr if key is None else cg.shared_progmem_string(key)
|
||||
if cg.is_template(value):
|
||||
# output_type=None lets lambdas return numbers or char pointers; C++ converts them
|
||||
lam = await cg.process_lambda(value, args, return_type=output_type)
|
||||
return cg.RawExpression(f"{field_type}::from_lambda({key_exp}, {lam})")
|
||||
return cg.ArrayInitializer(key_exp, _field_string(value), cg.nullptr)
|
||||
return cg.ArrayInitializer(key_exp, cg.shared_progmem_string(value), cg.nullptr)
|
||||
|
||||
entries = [await field(None, service, cg.std_string)]
|
||||
for group in groups:
|
||||
|
||||
@@ -444,7 +444,7 @@ message DeviceWizardRequest {
|
||||
// {"version": 1,
|
||||
// "pages": [{"title": "...", "description": "...",
|
||||
// "entities": [{"key": 123, "device_id": 456, "description": "..."}],
|
||||
// "inputs": [{"key": 789, "description": "...",
|
||||
// "inputs": [{"key": 789, "description": "...", "multiple": true, "max_length": 1023,
|
||||
// "entity_filters": [{"integration": "...", "domain": ["..."],
|
||||
// "device_class": ["..."], "supported_features": ["..."]}]}]}]}
|
||||
//
|
||||
@@ -468,6 +468,14 @@ message DeviceWizardRequest {
|
||||
// an entity matches a filter when it satisfies every field that is set, and an entity
|
||||
// that matches any one of the filters is accepted.
|
||||
//
|
||||
// An input with "multiple": true lets the user pick several entities. The client sends
|
||||
// them in one WizardInputSetRequest as a comma separated list with no spaces
|
||||
// ("calendar.a,calendar.b"); the device also accepts spaces around each id and stores the
|
||||
// list without them. "max_length" (only on a multiple input, 255 when left out) is the
|
||||
// longest list in bytes the device accepts. The version stays 1: a client that does not
|
||||
// know "multiple" ignores it, shows a single picker and sends one entity id, which a
|
||||
// multiple input accepts.
|
||||
//
|
||||
// The device keeps the entity id of an input in RAM only and does not store it across
|
||||
// restarts. The client therefore stores the choice itself and, after every connection
|
||||
// and before it sends SubscribeHomeAssistantStatesRequest, sends a WizardInputSetRequest
|
||||
@@ -483,8 +491,13 @@ message DeviceWizardResponse {
|
||||
|
||||
// Sets the entity id of a wizard input (see WizardInputField.key). Clients send
|
||||
// this only when DeviceCapabilitiesResponse.wizard.configured is set. There is no
|
||||
// reply. The device ignores a request whose key matches no input or whose entity_id
|
||||
// is empty, longer than 255 bytes or has no '.'. Otherwise it keeps the id in RAM,
|
||||
// reply. The device ignores a request whose key matches no input. A single input is
|
||||
// ignored when the entity_id is empty, longer than 255 bytes or has no '.'. A multiple
|
||||
// input takes a comma separated list ("calendar.a,calendar.b"); the client sends no
|
||||
// spaces, the device trims spaces around each id and stores the list without them. The
|
||||
// whole request is ignored when any id is empty or has no '.', or when the list without
|
||||
// spaces does not fit the input's max_length (255 by default). Otherwise it keeps the id
|
||||
// or list in RAM,
|
||||
// not across restarts, and when the input belongs to a homeassistant platform entity
|
||||
// it subscribes to that entity's state. Clients send this for every input right
|
||||
// after connecting, before SubscribeHomeAssistantStatesRequest. A request that
|
||||
@@ -496,7 +509,7 @@ message WizardInputSetRequest {
|
||||
option (ifdef) = "USE_API_WIZARD_INPUTS";
|
||||
|
||||
fixed32 key = 1;
|
||||
string entity_id = 2 [(max_data_length) = 255];
|
||||
string entity_id = 2 [(max_data_length) = 4095];
|
||||
}
|
||||
|
||||
message ListEntitiesRequest {
|
||||
@@ -2557,7 +2570,7 @@ message ListEntitiesEventResponse {
|
||||
EntityCategory entity_category = 7;
|
||||
string device_class = 8 [(max_data_length) = 47];
|
||||
|
||||
repeated string event_types = 9 [(container_pointer_no_template) = "FixedVector<const char *>"];
|
||||
repeated string event_types = 9 [(container_pointer_no_template) = "ConstVector<const char *, true>"];
|
||||
uint32 device_id = 10 [(field_ifdef) = "USE_DEVICES"];
|
||||
}
|
||||
message EventResponse {
|
||||
|
||||
@@ -3460,7 +3460,7 @@ class ListEntitiesEventResponse final : public InfoResponseProtoMessage {
|
||||
const LogString *message_name() const override { return LOG_STR("list_entities_event_response"); }
|
||||
#endif
|
||||
StringRef device_class{nullptr, 0}; // null until set, encode only
|
||||
const FixedVector<const char *> *event_types{};
|
||||
const ConstVector<const char *, true> *event_types{};
|
||||
static uint8_t *encode_msg(const void *self, uint8_t *pos PROTO_ENCODE_DEBUG_PARAM);
|
||||
uint8_t *encode(ProtoWriteBuffer &buffer PROTO_ENCODE_DEBUG_PARAM) const {
|
||||
return encode_msg(this, buffer.get_pos() PROTO_ENCODE_DEBUG_ARG);
|
||||
|
||||
@@ -237,6 +237,8 @@ void APIServer::refill_spare_ephemeral_() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Generating the key pair cannot be split across loop passes
|
||||
UnavoidableBlockingScope scope;
|
||||
noise::prepare_spare_ephemeral();
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -14,26 +14,68 @@ namespace esphome::api {
|
||||
ESPHOME_LOG_TAG(TAG, "api.wizard");
|
||||
|
||||
#ifdef USE_API_WIZARD_INPUTS
|
||||
#ifdef USE_API_WIZARD_MULTIPLE_INPUTS
|
||||
// Walks the comma separated entity ids in value, without the spaces around each. Returns the length they take joined
|
||||
// by ',', or 0 when one is empty or has no '.'. Writes the joined list to out unless it is nullptr.
|
||||
static size_t wizard_join_entity_ids(const char *value, size_t length, char *out) {
|
||||
size_t joined = 0;
|
||||
const char *end = value + length;
|
||||
while (true) {
|
||||
const char *comma = static_cast<const char *>(memchr(value, ',', end - value));
|
||||
const char *id_end = comma != nullptr ? comma : end;
|
||||
while (value < id_end && *value == ' ')
|
||||
value++;
|
||||
while (id_end > value && id_end[-1] == ' ')
|
||||
id_end--;
|
||||
size_t id_length = id_end - value;
|
||||
if (id_length == 0 || memchr(value, '.', id_length) == nullptr)
|
||||
return 0;
|
||||
if (joined != 0) {
|
||||
if (out != nullptr)
|
||||
out[joined] = ',';
|
||||
joined++;
|
||||
}
|
||||
if (out != nullptr)
|
||||
memcpy(out + joined, value, id_length);
|
||||
joined += id_length;
|
||||
if (comma == nullptr)
|
||||
return joined;
|
||||
value = comma + 1;
|
||||
}
|
||||
}
|
||||
#endif // USE_API_WIZARD_MULTIPLE_INPUTS
|
||||
|
||||
static bool wizard_entity_id_valid(const char *entity_id, size_t length) {
|
||||
return length > 0 && length < WIZARD_ENTITY_ID_BUFFER_SIZE && memchr(entity_id, '.', length) != nullptr;
|
||||
}
|
||||
|
||||
const char *wizard_set_input(const WizardInputSetRequest &msg) {
|
||||
if (!wizard_entity_id_valid(msg.entity_id.c_str(), msg.entity_id.size())) {
|
||||
ESP_LOGW(TAG, "Ignoring an invalid entity id for wizard input");
|
||||
return nullptr;
|
||||
}
|
||||
const char *value = msg.entity_id.c_str();
|
||||
const size_t length = msg.entity_id.size();
|
||||
for (size_t i = 0; i < API_WIZARD_INPUT_COUNT; i++) {
|
||||
// The table is in flash, which ESP8266 can only read through progmem_memcpy
|
||||
WizardInputEntry entry;
|
||||
progmem_memcpy(&entry, &API_WIZARD_INPUTS[i], sizeof(entry));
|
||||
if (entry.key != msg.key)
|
||||
continue;
|
||||
memcpy(entry.entity_id, msg.entity_id.c_str(), msg.entity_id.size());
|
||||
entry.entity_id[msg.entity_id.size()] = '\0';
|
||||
#ifdef USE_API_WIZARD_MULTIPLE_INPUTS
|
||||
if (entry.size != 0) {
|
||||
// Two passes, validate and measure then write, so a rejected request leaves the buffer unchanged
|
||||
const size_t joined = wizard_join_entity_ids(value, length, nullptr);
|
||||
if (joined == 0 || joined >= entry.size)
|
||||
break;
|
||||
wizard_join_entity_ids(value, length, entry.entity_id);
|
||||
entry.entity_id[joined] = '\0';
|
||||
return entry.entity_id;
|
||||
}
|
||||
#endif
|
||||
if (!wizard_entity_id_valid(value, length))
|
||||
break;
|
||||
memcpy(entry.entity_id, value, length);
|
||||
entry.entity_id[length] = '\0';
|
||||
return entry.entity_id;
|
||||
}
|
||||
ESP_LOGW(TAG, "Ignoring an entity id for an unknown wizard input");
|
||||
ESP_LOGW(TAG, "Ignoring an entity id for an unknown wizard input, or one that is not valid");
|
||||
return nullptr;
|
||||
}
|
||||
#endif // USE_API_WIZARD_INPUTS
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#ifdef USE_API_WIZARD_MULTIPLE_INPUTS
|
||||
#include <cstring>
|
||||
#endif
|
||||
|
||||
#include "esphome/core/hal.h"
|
||||
#include "proto.h"
|
||||
@@ -26,7 +29,10 @@ extern const uint8_t API_WIZARD_DATA[] PROGMEM;
|
||||
/// Where the entity id of an input is kept, found by the key the client uses for it.
|
||||
struct WizardInputEntry {
|
||||
uint32_t key; // FNV-1 hash of the ESPHome id of the input
|
||||
char *entity_id; // RAM buffer of WIZARD_ENTITY_ID_BUFFER_SIZE bytes, shared with the homeassistant entity
|
||||
char *entity_id; // RAM buffer, WIZARD_ENTITY_ID_BUFFER_SIZE bytes or size, shared with the homeassistant entity
|
||||
#ifdef USE_API_WIZARD_MULTIPLE_INPUTS
|
||||
uint16_t size; // Buffer size of a multiple input, 0 for a single input
|
||||
#endif
|
||||
};
|
||||
|
||||
/// The inputs of the wizard, in flash. API_WIZARD_INPUT_COUNT entries long.
|
||||
@@ -44,9 +50,34 @@ const char *wizard_set_input(const WizardInputSetRequest &msg);
|
||||
class WizardInput {
|
||||
public:
|
||||
explicit WizardInput(const char *entity_id) : entity_id_(entity_id) {}
|
||||
/// The Home Assistant entity ID, empty until the wizard sets one.
|
||||
/// The Home Assistant entity ID, empty until the wizard sets one. For a multiple input this is the whole
|
||||
/// comma separated list, which homeassistant.action data can use as it is.
|
||||
StringRef entity_id() const { return StringRef(this->entity_id_); }
|
||||
bool has_entity_id() const { return this->entity_id_[0] != '\0'; }
|
||||
#ifdef USE_API_WIZARD_MULTIPLE_INPUTS
|
||||
/// The number of entity IDs in the list, 0 until the wizard sets one.
|
||||
size_t entity_id_count() const {
|
||||
if (!this->has_entity_id())
|
||||
return 0;
|
||||
size_t count = 1;
|
||||
for (const char *p = this->entity_id_; (p = strchr(p, ',')) != nullptr; p++)
|
||||
count++;
|
||||
return count;
|
||||
}
|
||||
/// Call callback(StringRef) for each entity ID in the list, in order. The StringRef points into the list and is
|
||||
/// not null terminated, so print it with "%.*s".
|
||||
template<typename F> void for_each_entity_id(F &&callback) const {
|
||||
// The device stores the list without spaces or empty entries
|
||||
const char *start = this->entity_id_;
|
||||
while (*start != '\0') {
|
||||
const char *end = strchr(start, ',');
|
||||
if (end == nullptr)
|
||||
end = start + strlen(start);
|
||||
callback(StringRef(start, end - start));
|
||||
start = *end == ',' ? end + 1 : end;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
protected:
|
||||
const char *entity_id_;
|
||||
|
||||
@@ -20,6 +20,8 @@ from esphome.const import (
|
||||
CONF_ENTITY_ID,
|
||||
CONF_ID,
|
||||
CONF_INTERNAL,
|
||||
CONF_MAX_LENGTH,
|
||||
CONF_MULTIPLE,
|
||||
CONF_NAME,
|
||||
CONF_PAGES,
|
||||
CONF_PLATFORM,
|
||||
@@ -51,6 +53,10 @@ WizardInput = _API.class_("WizardInput")
|
||||
WIZARD_ENTITY_ID_BUFFER_SIZE = (
|
||||
256 # api_wizard.h; Home Assistant entity IDs are at most 255 bytes
|
||||
)
|
||||
WIZARD_ENTITY_ID_MAX_LENGTH = WIZARD_ENTITY_ID_BUFFER_SIZE - 1
|
||||
# The value of a multiple input fits one WizardInputSetRequest, which the device accepts up to 8 KiB on ESP8266;
|
||||
# api.proto max_data_length documents the same value
|
||||
WIZARD_MULTIPLE_MAX_LENGTH = 4095
|
||||
# One API message must fit APIBuffer::MAX_SIZE (65535) together with the largest frame header (7 bytes,
|
||||
# Noise) and footer (16 bytes, Noise MAC)
|
||||
WIZARD_RESPONSE_MAX_SIZE = 65535 - 7 - 16
|
||||
@@ -106,6 +112,21 @@ WIZARD_ENTITY_SCHEMA = cv.Schema(
|
||||
)
|
||||
|
||||
|
||||
def _validate_multiple(conf: ConfigType) -> ConfigType:
|
||||
if conf[CONF_MULTIPLE] and CONF_ENTITY in conf:
|
||||
raise cv.Invalid(
|
||||
"A linked input follows the state of exactly one Home Assistant entity, so multiple "
|
||||
"is only for standalone inputs (id)",
|
||||
path=[CONF_MULTIPLE],
|
||||
)
|
||||
if CONF_MAX_LENGTH in conf and not conf[CONF_MULTIPLE]:
|
||||
raise cv.Invalid(
|
||||
"max_length only applies to an input with multiple: true",
|
||||
path=[CONF_MAX_LENGTH],
|
||||
)
|
||||
return conf
|
||||
|
||||
|
||||
# An input is either standalone (id declares a new WizardInput) or linked to a homeassistant entity that has no
|
||||
# entity_id of its own: Home Assistant sets it
|
||||
WIZARD_INPUT_SCHEMA = cv.All(
|
||||
@@ -114,6 +135,10 @@ WIZARD_INPUT_SCHEMA = cv.All(
|
||||
cv.Optional(CONF_ID): cv.declare_id(WizardInput),
|
||||
cv.Optional(CONF_ENTITY): cv.use_id(cg.EntityBase),
|
||||
cv.Optional(CONF_DESCRIPTION): _wizard_text(WIZARD_DESCRIPTION_MAX_LENGTH),
|
||||
cv.Optional(CONF_MULTIPLE, default=False): cv.boolean,
|
||||
cv.Optional(CONF_MAX_LENGTH): cv.int_range(
|
||||
min=WIZARD_ENTITY_ID_MAX_LENGTH, max=WIZARD_MULTIPLE_MAX_LENGTH
|
||||
),
|
||||
cv.Optional(CONF_TARGET): cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_ENTITY): cv.All(
|
||||
@@ -124,6 +149,7 @@ WIZARD_INPUT_SCHEMA = cv.All(
|
||||
}
|
||||
),
|
||||
cv.has_exactly_one_key(CONF_ID, CONF_ENTITY),
|
||||
_validate_multiple,
|
||||
)
|
||||
|
||||
WIZARD_PAGE_SCHEMA = cv.All(
|
||||
@@ -248,6 +274,8 @@ def _wizard_defines(wizard: ConfigType) -> set[str]:
|
||||
defines.add("USE_API_WIZARD_LINKED_INPUTS")
|
||||
if any(CONF_ID in conf for conf in inputs):
|
||||
defines.add("USE_API_WIZARD_STANDALONE_INPUTS")
|
||||
if any(conf.get(CONF_MULTIPLE) for conf in inputs):
|
||||
defines.add("USE_API_WIZARD_MULTIPLE_INPUTS")
|
||||
return defines
|
||||
|
||||
|
||||
@@ -371,6 +399,10 @@ def _input_document(conf: ConfigType, config: fv.FinalValidateConfig) -> ConfigT
|
||||
document: ConfigType = {"key": fnv1_hash(_wizard_input_id(conf).id)}
|
||||
if description := conf.get(CONF_DESCRIPTION):
|
||||
document[CONF_DESCRIPTION] = description
|
||||
if conf.get(CONF_MULTIPLE):
|
||||
document["multiple"] = True
|
||||
if (max_length := conf.get(CONF_MAX_LENGTH)) is not None:
|
||||
document["max_length"] = max_length
|
||||
if filters := _wizard_input_filters(conf, config):
|
||||
document["entity_filters"] = [dict(entity_filter) for entity_filter in filters]
|
||||
return document
|
||||
@@ -384,7 +416,7 @@ def wizard_document(wizard: ConfigType, config: fv.FinalValidateConfig) -> Confi
|
||||
{"version": 1,
|
||||
"pages": [{"title": "...", "description": "...",
|
||||
"entities": [{"key": 123, "device_id": 456, "description": "..."}],
|
||||
"inputs": [{"key": 789, "description": "...",
|
||||
"inputs": [{"key": 789, "description": "...", "multiple": true, "max_length": 1023,
|
||||
"entity_filters": [{"integration": "...", "domain": ["..."],
|
||||
"device_class": ["..."], "supported_features": ["..."]}]}]}]}
|
||||
|
||||
@@ -396,6 +428,14 @@ def wizard_document(wizard: ConfigType, config: fv.FinalValidateConfig) -> Confi
|
||||
the device it belongs to (esphome/core/config.py), and is left out for the main device.
|
||||
- An input key is the FNV-1 hash of the ESPHome id of the input, or of the linked entity. A linked
|
||||
entity must not set entity_id, as that is a static entry kept apart from the ones the wizard sets.
|
||||
- multiple means the user may pick several entities. The client sends them in one
|
||||
WizardInputSetRequest as a comma separated list ("calendar.a,calendar.b") with no spaces; the
|
||||
device trims spaces around each id and stores the list without them. The whole request is
|
||||
ignored when any id is empty or has no '.', or when the list without spaces does not fit
|
||||
max_length (only on a multiple input, 255 when left out). A single input is ignored when the id
|
||||
is empty, longer than 255 bytes or has no '.'. The version stays 1: a client that does not know
|
||||
multiple ignores it, shows a single picker and sends one entity id, which a multiple input
|
||||
accepts.
|
||||
- entity_filters are the filters of the input, or the default filters of a linked switch,
|
||||
number, text, select or button.
|
||||
"""
|
||||
@@ -441,14 +481,15 @@ async def to_code(wizard: ConfigType) -> None:
|
||||
input_id = _wizard_input_id(conf)
|
||||
# Every buffer starts empty, until the wizard sets it. A linked homeassistant entity uses it as its entity id.
|
||||
buffer = _wizard_buffer_name(input_id)
|
||||
cg.add_global(
|
||||
cg.RawStatement(
|
||||
f'static char {buffer}[{WIZARD_ENTITY_ID_BUFFER_SIZE}] = "";'
|
||||
)
|
||||
)
|
||||
size = conf.get(CONF_MAX_LENGTH, WIZARD_ENTITY_ID_MAX_LENGTH) + 1
|
||||
cg.add_global(cg.RawStatement(f'static char {buffer}[{size}] = "";'))
|
||||
if CONF_ID in conf:
|
||||
cg.new_Pvariable(input_id, cg.RawExpression(buffer))
|
||||
entries.append(cg.RawExpression(f"{{{fnv1_hash(input_id.id)}u, {buffer}}}"))
|
||||
key = fnv1_hash(input_id.id)
|
||||
if conf[CONF_MULTIPLE]:
|
||||
entries.append(cg.RawExpression(f"{{{key}u, {buffer}, {size}}}"))
|
||||
else:
|
||||
entries.append(cg.RawExpression(f"{{{key}u, {buffer}}}"))
|
||||
if entries:
|
||||
cg.extern_progmem_array(
|
||||
"esphome::api::API_WIZARD_INPUTS",
|
||||
|
||||
@@ -391,7 +391,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
# Adds a define and IDF component for legacy `audio_decoder.cpp`.
|
||||
if data.flac_support:
|
||||
cg.add_define("USE_AUDIO_FLAC_SUPPORT")
|
||||
add_idf_component(name="esphome/micro-flac", ref="0.2.0")
|
||||
add_idf_component(name="esphome/micro-flac", ref="0.3.0")
|
||||
_emit_memory_pair(
|
||||
data.flac.buffer_memory,
|
||||
"CONFIG_MICRO_FLAC_PREFER_PSRAM",
|
||||
|
||||
@@ -146,10 +146,7 @@ bool BalluClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t checksum = 0;
|
||||
// Calculate checksum and compare with signal value.
|
||||
for (uint8_t i = 0; i < BALLU_STATE_LENGTH - 1; i++)
|
||||
checksum += remote_state[i];
|
||||
const uint8_t checksum = sum_bytes(remote_state, BALLU_STATE_LENGTH - 1);
|
||||
|
||||
if (checksum != remote_state[BALLU_STATE_LENGTH - 1]) {
|
||||
ESP_LOGVV(TAG, "Checksum fail");
|
||||
|
||||
@@ -607,7 +607,8 @@ async def setup_binary_sensor_core_(var, config):
|
||||
if filters_config := config.get(CONF_FILTERS):
|
||||
cg.add_define("USE_BINARY_SENSOR_FILTER")
|
||||
filters = await cg.build_registry_list(FILTER_REGISTRY, filters_config)
|
||||
cg.add(var.add_filters(filters))
|
||||
for filter_ in filters:
|
||||
cg.add(var.add_filter(filter_))
|
||||
|
||||
CORE.add_job(_build_binary_sensor_automations, var, config)
|
||||
|
||||
|
||||
@@ -51,12 +51,8 @@ void BL0939::loop() {
|
||||
}
|
||||
|
||||
bool BL0939::validate_checksum(const DataPacket *data) {
|
||||
uint8_t checksum = BL0939_READ_COMMAND;
|
||||
// Whole package but checksum
|
||||
for (uint32_t i = 0; i < sizeof(data->raw) - 1; i++) {
|
||||
checksum += data->raw[i];
|
||||
}
|
||||
checksum ^= 0xFF;
|
||||
const uint8_t checksum = sum_bytes(data->raw, sizeof(data->raw) - 1, BL0939_READ_COMMAND) ^ 0xFF;
|
||||
if (checksum != data->checksum) {
|
||||
ESP_LOGW(TAG, "BL0939 invalid checksum! 0x%02X != 0x%02X", checksum, data->checksum);
|
||||
}
|
||||
@@ -120,13 +116,24 @@ void BL0939::received_package_(const DataPacket *data) const {
|
||||
energy_sensor_sum_->publish_state(total_energy_consumption);
|
||||
}
|
||||
|
||||
if (this->internal_temperature_sensor_ != nullptr) {
|
||||
const uint16_t raw_temperature = ((uint16_t(data->tps1.h) << 8) | data->tps1.l) & 0x3FF;
|
||||
// Datasheet temperature conversion: Tx = (170 / 448) * (TB / 2 - 32) - 45.
|
||||
const float temperature = (170.0f / 448.0f) * (raw_temperature / 2.0f - 32.0f) - 45.0f;
|
||||
this->internal_temperature_sensor_->publish_state(temperature);
|
||||
}
|
||||
|
||||
ESP_LOGV(TAG,
|
||||
"BL0939: U %fV, I1 %fA, I2 %fA, P1 %fW, P2 %fW, CntA %" PRId32 ", CntB %" PRId32 ", ∫P1 %fkWh, ∫P2 %fkWh",
|
||||
v_rms, ia_rms, ib_rms, a_watt, b_watt, cfa_cnt, cfb_cnt, a_energy_consumption, b_energy_consumption);
|
||||
}
|
||||
|
||||
void BL0939::dump_config() { // NOLINT(readability-function-cognitive-complexity)
|
||||
ESP_LOGCONFIG(TAG, "BL0939:");
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"BL0939:\n"
|
||||
" Mode: %s",
|
||||
this->mode_ == BL0939Mode::BL0939_MODE_CURRENT_TRANSFORMER ? LOG_STR_LITERAL("current_transformer")
|
||||
: LOG_STR_LITERAL("direct"));
|
||||
LOG_SENSOR("", "Voltage", this->voltage_sensor_);
|
||||
LOG_SENSOR("", "Current 1", this->current_sensor_1_);
|
||||
LOG_SENSOR("", "Current 2", this->current_sensor_2_);
|
||||
@@ -135,6 +142,7 @@ void BL0939::dump_config() { // NOLINT(readability-function-cognitive-complexit
|
||||
LOG_SENSOR("", "Energy 1", this->energy_sensor_1_);
|
||||
LOG_SENSOR("", "Energy 2", this->energy_sensor_2_);
|
||||
LOG_SENSOR("", "Energy sum", this->energy_sensor_sum_);
|
||||
LOG_SENSOR("", "Internal Temperature", this->internal_temperature_sensor_);
|
||||
}
|
||||
|
||||
uint32_t BL0939::to_uint32_t(ube24_t input) { return input.h << 16 | input.m << 8 | input.l; }
|
||||
|
||||
@@ -8,13 +8,32 @@ namespace esphome::bl0939 {
|
||||
|
||||
// https://datasheet.lcsc.com/lcsc/2108071830_BL-Shanghai-Belling-BL0939_C2841044.pdf
|
||||
// (unfortunately chinese, but the formulas can be easily understood)
|
||||
// The datasheet has one set of formulas for direct mode (current shunt) and one for current transformer mode.
|
||||
|
||||
// Direct mode.
|
||||
// Sonoff Dual R3 V2 has the exact same resistor values for the current shunts (RL=1miliOhm)
|
||||
// and for the voltage divider (R1=0.51kOhm, R2=5*390kOhm)
|
||||
// as in the manufacturer's reference circuit, so the same formulas were used here (Vref=1.218V)
|
||||
static const float BL0939_IREF = 324004 * 1 / 1.218;
|
||||
static const float BL0939_UREF = 79931 * 0.51 * 1000 / (1.218 * (5 * 390 + 0.51));
|
||||
static const float BL0939_PREF = 4046 * 1 * 0.51 * 1000 / (1.218 * 1.218 * (5 * 390 + 0.51));
|
||||
static const float BL0939_EREF = 3.6e6 * 4046 * 1 * 0.51 * 1000 / (1638.4 * 256 * 1.218 * 1.218 * (5 * 390 + 0.51));
|
||||
static constexpr float BL0939_IREF = 324004 * 1 / 1.218;
|
||||
static constexpr float BL0939_UREF = 79931 * 0.51 * 1000 / (1.218 * (5 * 390 + 0.51));
|
||||
static constexpr float BL0939_PREF = 4046 * 1 * 0.51 * 1000 / (1.218 * 1.218 * (5 * 390 + 0.51));
|
||||
static constexpr float BL0939_EREF = 3.6e6 * 4046 * 1 * 0.51 * 1000 / (1638.4 * 256 * 1.218 * 1.218 * (5 * 390 + 0.51));
|
||||
|
||||
// Current transformer mode.
|
||||
// Values from the Seeed Studio XIAO 2-Channel Wi-Fi AC Energy Meter V1.0 schematic (Vref=1.218V).
|
||||
// Current: 100A:50mA CT (2000:1) into a 0.6Ohm burden (2 * 0.3Ohm), so 0.3mV per primary amp.
|
||||
// That is the same as a 0.3mOhm shunt in the direct mode formula.
|
||||
// Voltage: ZMPT107-1 2mA:2mA voltage transformer with R2=5*22kOhm on the primary and R1=24.9Ohm on
|
||||
// the secondary. The transformer isolates R1 from R2, so the divider is R1/R2 instead of R1/(R1+R2).
|
||||
static constexpr float BL0939_IREF_CT = 324004 * 0.3 / 1.218;
|
||||
static constexpr float BL0939_UREF_CT = 79931 * 24.9 * 1000 / (1.218 * 5 * 22000);
|
||||
static constexpr float BL0939_PREF_CT = 4046 * 0.3 * 24.9 * 1000 / (1.218 * 1.218 * 5 * 22000);
|
||||
static constexpr float BL0939_EREF_CT = 3.6e6 * 4046 * 0.3 * 24.9 * 1000 / (1638.4 * 256 * 1.218 * 1.218 * 5 * 22000);
|
||||
|
||||
enum class BL0939Mode : uint8_t {
|
||||
BL0939_MODE_DIRECT = 0,
|
||||
BL0939_MODE_CURRENT_TRANSFORMER = 1,
|
||||
};
|
||||
|
||||
struct ube24_t { // NOLINT(readability-identifier-naming,altera-struct-pack-align)
|
||||
uint8_t l;
|
||||
@@ -66,6 +85,16 @@ class BL0939 final : public PollingComponent, public uart::UARTDevice {
|
||||
void set_energy_sensor_1(sensor::Sensor *energy_sensor_1) { energy_sensor_1_ = energy_sensor_1; }
|
||||
void set_energy_sensor_2(sensor::Sensor *energy_sensor_2) { energy_sensor_2_ = energy_sensor_2; }
|
||||
void set_energy_sensor_sum(sensor::Sensor *energy_sensor_sum) { energy_sensor_sum_ = energy_sensor_sum; }
|
||||
void set_internal_temperature_sensor(sensor::Sensor *sensor) { this->internal_temperature_sensor_ = sensor; }
|
||||
// Inline so a constant mode from codegen folds down to plain stores.
|
||||
void set_mode(BL0939Mode mode) {
|
||||
this->mode_ = mode;
|
||||
const bool current_transformer = mode == BL0939Mode::BL0939_MODE_CURRENT_TRANSFORMER;
|
||||
this->power_reference_ = current_transformer ? BL0939_PREF_CT : BL0939_PREF;
|
||||
this->voltage_reference_ = current_transformer ? BL0939_UREF_CT : BL0939_UREF;
|
||||
this->current_reference_ = current_transformer ? BL0939_IREF_CT : BL0939_IREF;
|
||||
this->energy_reference_ = current_transformer ? BL0939_EREF_CT : BL0939_EREF;
|
||||
}
|
||||
|
||||
void loop() override;
|
||||
|
||||
@@ -84,6 +113,7 @@ class BL0939 final : public PollingComponent, public uart::UARTDevice {
|
||||
sensor::Sensor *energy_sensor_1_{nullptr};
|
||||
sensor::Sensor *energy_sensor_2_{nullptr};
|
||||
sensor::Sensor *energy_sensor_sum_{nullptr};
|
||||
sensor::Sensor *internal_temperature_sensor_{nullptr};
|
||||
|
||||
// Divide by this to turn into Watt
|
||||
float power_reference_ = BL0939_PREF;
|
||||
@@ -93,6 +123,7 @@ class BL0939 final : public PollingComponent, public uart::UARTDevice {
|
||||
float current_reference_ = BL0939_IREF;
|
||||
// Divide by this to turn into kWh
|
||||
float energy_reference_ = BL0939_EREF;
|
||||
BL0939Mode mode_{BL0939Mode::BL0939_MODE_DIRECT};
|
||||
|
||||
static uint32_t to_uint32_t(ube24_t input);
|
||||
|
||||
|
||||
@@ -3,14 +3,19 @@ from esphome.components import sensor, uart
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_ID,
|
||||
CONF_INTERNAL_TEMPERATURE,
|
||||
CONF_MODE,
|
||||
CONF_VOLTAGE,
|
||||
DEVICE_CLASS_CURRENT,
|
||||
DEVICE_CLASS_ENERGY,
|
||||
DEVICE_CLASS_POWER,
|
||||
DEVICE_CLASS_TEMPERATURE,
|
||||
DEVICE_CLASS_VOLTAGE,
|
||||
ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
STATE_CLASS_MEASUREMENT,
|
||||
STATE_CLASS_TOTAL_INCREASING,
|
||||
UNIT_AMPERE,
|
||||
UNIT_CELSIUS,
|
||||
UNIT_KILOWATT_HOURS,
|
||||
UNIT_VOLT,
|
||||
UNIT_WATT,
|
||||
@@ -29,11 +34,22 @@ CONF_ENERGY_TOTAL = "energy_total"
|
||||
|
||||
bl0939_ns = cg.esphome_ns.namespace("bl0939")
|
||||
BL0939 = bl0939_ns.class_("BL0939", cg.PollingComponent, uart.UARTDevice)
|
||||
BL0939Mode = bl0939_ns.enum("BL0939Mode", is_class=True)
|
||||
MODE_OPTIONS = {
|
||||
"direct": BL0939Mode.BL0939_MODE_DIRECT,
|
||||
"current_transformer": BL0939Mode.BL0939_MODE_CURRENT_TRANSFORMER,
|
||||
}
|
||||
# Must match the mode_ member initializer in bl0939.h; set_mode() is skipped
|
||||
# when the config already equals it.
|
||||
DEFAULT_MODE = "direct"
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(BL0939),
|
||||
cv.Optional(CONF_MODE, default=DEFAULT_MODE): cv.enum(
|
||||
MODE_OPTIONS, lower=True
|
||||
),
|
||||
cv.Optional(CONF_VOLTAGE): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_VOLT,
|
||||
accuracy_decimals=1,
|
||||
@@ -82,6 +98,13 @@ CONFIG_SCHEMA = (
|
||||
device_class=DEVICE_CLASS_ENERGY,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional(CONF_INTERNAL_TEMPERATURE): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_CELSIUS,
|
||||
accuracy_decimals=1,
|
||||
device_class=DEVICE_CLASS_TEMPERATURE,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
|
||||
),
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
@@ -94,6 +117,9 @@ async def to_code(config: ConfigType) -> None:
|
||||
await cg.register_component(var, config)
|
||||
await uart.register_uart_device(var, config)
|
||||
|
||||
if (mode := config[CONF_MODE]) != DEFAULT_MODE:
|
||||
cg.add(var.set_mode(mode))
|
||||
|
||||
sensors = sensor.sub_sensors(config)
|
||||
await sensors(CONF_VOLTAGE, var.set_voltage_sensor)
|
||||
await sensors(CONF_CURRENT_1, var.set_current_sensor_1)
|
||||
@@ -103,3 +129,4 @@ async def to_code(config: ConfigType) -> None:
|
||||
await sensors(CONF_ENERGY_1, var.set_energy_sensor_1)
|
||||
await sensors(CONF_ENERGY_2, var.set_energy_sensor_2)
|
||||
await sensors(CONF_ENERGY_TOTAL, var.set_energy_sensor_sum)
|
||||
await sensors(CONF_INTERNAL_TEMPERATURE, var.set_internal_temperature_sensor)
|
||||
|
||||
@@ -44,13 +44,9 @@ void BL0940::loop() {
|
||||
}
|
||||
|
||||
bool BL0940::validate_checksum_(DataPacket *data) {
|
||||
uint8_t checksum = this->read_command_;
|
||||
// Whole package but checksum
|
||||
uint8_t *raw = (uint8_t *) data;
|
||||
for (uint32_t i = 0; i < sizeof(*data) - 1; i++) {
|
||||
checksum += raw[i];
|
||||
}
|
||||
checksum ^= 0xFF;
|
||||
const uint8_t checksum =
|
||||
sum_bytes(reinterpret_cast<const uint8_t *>(data), sizeof(*data) - 1, this->read_command_) ^ 0xFF;
|
||||
if (checksum != data->checksum) {
|
||||
ESP_LOGW(TAG, "Invalid checksum! 0x%02X != 0x%02X", checksum, data->checksum);
|
||||
}
|
||||
|
||||
@@ -70,13 +70,10 @@ void BL0942::loop() {
|
||||
}
|
||||
|
||||
bool BL0942::validate_checksum_(DataPacket *data) {
|
||||
uint8_t checksum = BL0942_READ_COMMAND | this->address_;
|
||||
// Whole package but checksum
|
||||
uint8_t *raw = (uint8_t *) data;
|
||||
for (uint32_t i = 0; i < sizeof(*data) - 1; i++) {
|
||||
checksum += raw[i];
|
||||
}
|
||||
checksum ^= 0xFF;
|
||||
const uint8_t checksum =
|
||||
sum_bytes(reinterpret_cast<const uint8_t *>(data), sizeof(*data) - 1, BL0942_READ_COMMAND | this->address_) ^
|
||||
0xFF;
|
||||
if (checksum != data->checksum) {
|
||||
ESP_LOGW(TAG, "BL0942 invalid checksum! 0x%02X != 0x%02X", checksum, data->checksum);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ from esphome.components.logger import request_log_listener
|
||||
from esphome.components.uart import (
|
||||
UARTComponent,
|
||||
debug_to_code,
|
||||
mark_unclocked,
|
||||
maybe_empty_debug,
|
||||
uart_ns,
|
||||
)
|
||||
@@ -42,7 +43,7 @@ def validate_rx_buffer(config: ConfigType) -> ConfigType:
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(BLENUS),
|
||||
cv.GenerateID(): cv.All(cv.declare_id(BLENUS), mark_unclocked),
|
||||
cv.Optional(CONF_TYPE, default=CONF_LOGS): cv.one_of(
|
||||
*[CONF_LOGS, CONF_UART], lower=True
|
||||
),
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DATA, CONF_ID, CONF_TRIGGER_ID
|
||||
from esphome.const import CONF_DATA, CONF_ID, CONF_PLATFORM, CONF_TRIGGER_ID
|
||||
from esphome.core import CORE, ID
|
||||
from esphome.cpp_generator import MockObj, TemplateArgsType
|
||||
from esphome.types import ConfigType
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CODEOWNERS = ["@mvturnho", "@danielschramm"]
|
||||
DOMAIN = "canbus"
|
||||
IS_PLATFORM_COMPONENT = True
|
||||
@@ -150,9 +153,19 @@ async def setup_canbus_core_(var: MockObj, config: ConfigType) -> None:
|
||||
)
|
||||
|
||||
|
||||
async def register_canbus(var: MockObj, config: ConfigType) -> None:
|
||||
async def register_canbus(
|
||||
var: MockObj, config: ConfigType, *, reports_status: bool | None = None
|
||||
) -> None:
|
||||
if not CORE.has_id(config[CONF_ID]):
|
||||
var = cg.new_Pvariable(config[CONF_ID], var)
|
||||
if reports_status is None:
|
||||
_LOGGER.warning(
|
||||
"CAN bus platform '%s' does not report bus state, so bus-off recovery and "
|
||||
"error-state logging are disabled. Platform authors should either override "
|
||||
"get_status() and get_events() and call register_canbus(..., reports_status=True) "
|
||||
"or pass reports_status=False if the hardware cannot report it",
|
||||
config[CONF_PLATFORM],
|
||||
)
|
||||
await setup_canbus_core_(var, config)
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "canbus.h"
|
||||
#include <algorithm>
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::canbus {
|
||||
@@ -65,6 +66,12 @@ void Canbus::add_trigger(CanbusTrigger *trigger) {
|
||||
};
|
||||
|
||||
void Canbus::loop() {
|
||||
uint32_t now = App.get_loop_component_start_time();
|
||||
if ((now - this->last_event_check_time_) >= EVENT_CHECK_INTERVAL_MS) {
|
||||
this->log_events_(this->get_events(), now);
|
||||
this->last_event_check_time_ = now;
|
||||
}
|
||||
|
||||
struct CanFrame can_message;
|
||||
uint32_t message_counter = 0;
|
||||
for (; message_counter < this->max_frames_per_loop_; message_counter++) {
|
||||
@@ -109,4 +116,55 @@ void Canbus::loop() {
|
||||
}
|
||||
}
|
||||
|
||||
void Canbus::log_events_(CanEventFlags events, uint32_t now) {
|
||||
// Bus-off gets its own handling because automatic recovery can make it flap
|
||||
if (events & CanEventFlags::CAN_EVENT_BUS_OFF) {
|
||||
this->last_bus_off_time_ = now;
|
||||
if (!this->bus_off_) {
|
||||
this->bus_off_ = true;
|
||||
this->status_set_warning(LOG_STR("Bus off"));
|
||||
}
|
||||
} else if (this->bus_off_) {
|
||||
if ((now - this->last_bus_off_time_) >= EVENT_LOG_BUS_OFF_HOLDOFF_MS) {
|
||||
// No bus-off event for the hold-off time, so ask whether it is really over
|
||||
if (this->get_status().bus_off) {
|
||||
this->last_bus_off_time_ = now;
|
||||
} else {
|
||||
this->bus_off_ = false;
|
||||
this->status_clear_warning();
|
||||
// Events gathered while bus-off say nothing about the recovered bus
|
||||
this->events_to_log_ = 0;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this->events_to_log_ |= events;
|
||||
if (this->events_to_log_ != 0 && (now - this->last_event_log_time_) >= EVENT_LOG_THROTTLE_MS) {
|
||||
if (this->events_to_log_ & (CanEventFlags::CAN_EVENT_PASSIVE | CanEventFlags::CAN_EVENT_ACTIVE)) {
|
||||
bool error_passive = this->events_to_log_ & CanEventFlags::CAN_EVENT_PASSIVE;
|
||||
if (error_passive && (this->events_to_log_ & CanEventFlags::CAN_EVENT_ACTIVE)) {
|
||||
// Both edges within one throttle window, so the counters decide the current state
|
||||
auto status = this->get_status();
|
||||
error_passive = status.rx_error_counter >= CAN_ERROR_PASSIVE_THRESHOLD ||
|
||||
status.tx_error_counter >= CAN_ERROR_PASSIVE_THRESHOLD;
|
||||
}
|
||||
ESP_LOGW(TAG, "entered %s", error_passive ? LOG_STR_LITERAL("error-passive") : LOG_STR_LITERAL("error-active"));
|
||||
}
|
||||
if (this->events_to_log_ & CanEventFlags::CAN_EVENT_RX_QUEUE_FULL) {
|
||||
ESP_LOGD(TAG, "receive buffer overrun");
|
||||
}
|
||||
this->events_to_log_ = 0;
|
||||
this->last_event_log_time_ = now;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef ESPHOME_LOG_HAS_VERBOSE
|
||||
if ((now - this->last_state_log_time_) >= STATE_LOG_INTERVAL_MS) {
|
||||
auto status = this->get_status();
|
||||
ESP_LOGV(TAG, "Status: bus_off %d, tx_err %d, rx_err %d", status.bus_off, status.tx_error_counter,
|
||||
status.rx_error_counter);
|
||||
this->last_state_log_time_ = now;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace esphome::canbus
|
||||
|
||||
@@ -48,6 +48,8 @@ template<typename... Ts> class CanbusSendAction;
|
||||
/* CAN payload length definitions according to ISO 11898-1 */
|
||||
static const uint8_t CAN_MAX_DATA_LENGTH = 8;
|
||||
|
||||
static const uint8_t CAN_ERROR_PASSIVE_THRESHOLD = 128;
|
||||
|
||||
/*
|
||||
Can Frame describes a normative CAN Frame
|
||||
The RTR = Remote Transmission Request is implemented in every CAN controller but rarely used
|
||||
@@ -61,6 +63,26 @@ struct CanFrame {
|
||||
uint8_t data[CAN_MAX_DATA_LENGTH] __attribute__((aligned(8)));
|
||||
};
|
||||
|
||||
enum CanEventFlags : uint8_t {
|
||||
CAN_EVENT_PASSIVE = 1 << 0,
|
||||
CAN_EVENT_ACTIVE = 1 << 1,
|
||||
CAN_EVENT_BUS_OFF = 1 << 2,
|
||||
CAN_EVENT_RX_QUEUE_FULL = 1 << 3,
|
||||
};
|
||||
|
||||
static constexpr uint32_t CAN_STATUS_UNSET = UINT32_MAX;
|
||||
|
||||
struct CanStatus {
|
||||
bool bus_off{false};
|
||||
uint8_t rx_error_counter{0};
|
||||
uint8_t tx_error_counter{0};
|
||||
uint32_t tx_failed_count{CAN_STATUS_UNSET};
|
||||
uint32_t rx_missed_count{CAN_STATUS_UNSET};
|
||||
uint32_t rx_overrun_count{CAN_STATUS_UNSET};
|
||||
uint32_t arb_lost_count{CAN_STATUS_UNSET};
|
||||
uint32_t bus_error_count{CAN_STATUS_UNSET};
|
||||
};
|
||||
|
||||
class Canbus : public Component {
|
||||
public:
|
||||
Canbus(){};
|
||||
@@ -83,6 +105,7 @@ class Canbus : public Component {
|
||||
void set_use_extended_id(bool use_extended_id) { this->use_extended_id_ = use_extended_id; }
|
||||
void set_bitrate(CanSpeed bit_rate) { this->bit_rate_ = bit_rate; }
|
||||
void set_max_frames_per_loop(uint32_t max_frames_per_loop) { this->max_frames_per_loop_ = max_frames_per_loop; }
|
||||
virtual CanStatus get_status() { return {}; }
|
||||
|
||||
void add_trigger(CanbusTrigger *trigger);
|
||||
/**
|
||||
@@ -104,12 +127,33 @@ class Canbus : public Component {
|
||||
uint32_t max_frames_per_loop_{50}; // Keep in sync with DEFAULT_MAX_FRAMES_PER_LOOP in __init__.py
|
||||
CanSpeed bit_rate_{CAN_125KBPS}; // Keep in sync with DEFAULT_BIT_RATE in __init__.py
|
||||
bool use_extended_id_{false};
|
||||
uint8_t events_to_log_{0};
|
||||
bool bus_off_{false};
|
||||
CallbackManager<void(uint32_t can_id, bool extended_id, bool rtr, const std::vector<uint8_t> &data)>
|
||||
callback_manager_{};
|
||||
|
||||
// interval in which to check for new can bus events (bus-off, passive, active)
|
||||
static constexpr uint32_t EVENT_CHECK_INTERVAL_MS = 100;
|
||||
uint32_t last_event_check_time_{0};
|
||||
|
||||
// time to wait after logging an event before logging the next event(s)
|
||||
static constexpr uint32_t EVENT_LOG_THROTTLE_MS = 1000;
|
||||
uint32_t last_event_log_time_{0};
|
||||
|
||||
// time span without bus-off events before the bus is declared recovered
|
||||
static constexpr uint32_t EVENT_LOG_BUS_OFF_HOLDOFF_MS = 1000;
|
||||
uint32_t last_bus_off_time_{0};
|
||||
|
||||
#ifdef ESPHOME_LOG_HAS_VERBOSE
|
||||
static constexpr uint32_t STATE_LOG_INTERVAL_MS = 1000;
|
||||
uint32_t last_state_log_time_{0};
|
||||
#endif
|
||||
|
||||
void log_events_(CanEventFlags events, uint32_t now);
|
||||
virtual bool setup_internal() = 0;
|
||||
virtual Error send_message(struct CanFrame *frame) = 0;
|
||||
virtual Error read_message(struct CanFrame *frame) = 0;
|
||||
virtual CanEventFlags get_events() { return CanEventFlags{}; }
|
||||
};
|
||||
|
||||
template<typename... Ts> class CanbusSendAction final : public Action<Ts...>, public Parented<Canbus> {
|
||||
|
||||
@@ -4,7 +4,6 @@ import esphome.codegen as cg
|
||||
from esphome.components import web_server_base, wifi
|
||||
from esphome.components.web_server_base import CONF_WEB_SERVER_BASE_ID
|
||||
from esphome.components.wifi import DOMAIN as WIFI_DOMAIN
|
||||
from esphome.config_helpers import filter_source_files_from_platform
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_AP,
|
||||
@@ -16,7 +15,6 @@ from esphome.const import (
|
||||
PLATFORM_LN882X,
|
||||
PLATFORM_RP2,
|
||||
PLATFORM_RTL87XX,
|
||||
PlatformFramework,
|
||||
)
|
||||
from esphome.core import CORE, coroutine_with_priority
|
||||
from esphome.coroutine import CoroPriority
|
||||
@@ -78,17 +76,7 @@ def _final_validate(config: ConfigType) -> None:
|
||||
"Add 'ap:' to your WiFi configuration to enable the captive portal."
|
||||
)
|
||||
|
||||
# Register socket needs for DNS server and additional HTTP connections
|
||||
# - 1 UDP socket for DNS server
|
||||
# - 3 TCP sockets for captive portal detection probes + configuration requests
|
||||
# OS captive portal detection makes multiple probe requests that stay in TIME_WAIT.
|
||||
# Need headroom for actual user configuration requests.
|
||||
# LRU purging will reclaim idle sockets to prevent exhaustion from repeated attempts.
|
||||
# The listening socket is registered by web_server_base (shared HTTP server).
|
||||
from esphome.components import socket
|
||||
|
||||
socket.consume_sockets(3, "captive_portal")(config)
|
||||
socket.consume_sockets(1, "captive_portal", socket.SocketType.UDP)(config)
|
||||
web_server_base.consume_captive_dns_sockets(config, DOMAIN)
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = _final_validate
|
||||
@@ -108,16 +96,4 @@ async def to_code(config: ConfigType) -> None:
|
||||
if config[CONF_COMPRESSION] == "gzip":
|
||||
cg.add_define("USE_CAPTIVE_PORTAL_GZIP")
|
||||
|
||||
if CORE.using_arduino and (CORE.is_esp8266 or CORE.is_libretiny or CORE.is_rp2):
|
||||
cg.add_library("DNSServer", None)
|
||||
|
||||
|
||||
# Only compile the ESP-IDF DNS server when using ESP-IDF framework
|
||||
FILTER_SOURCE_FILES = filter_source_files_from_platform(
|
||||
{
|
||||
"dns_server_esp32_idf.cpp": {
|
||||
PlatformFramework.ESP32_ARDUINO,
|
||||
PlatformFramework.ESP32_IDF,
|
||||
},
|
||||
}
|
||||
)
|
||||
web_server_base.add_captive_dns_library()
|
||||
|
||||
@@ -6,9 +6,6 @@
|
||||
#include "esphome/core/string_ref.h"
|
||||
#include "esphome/components/wifi/scan_list.h"
|
||||
#include "esphome/components/wifi/wifi_component.h"
|
||||
#ifdef USE_PROVISIONING
|
||||
#include "esphome/components/provisioning/provisioning.h"
|
||||
#endif
|
||||
#include "captive_index.h"
|
||||
|
||||
namespace esphome::captive_portal {
|
||||
@@ -81,20 +78,6 @@ void CaptivePortal::handle_wifisave(AsyncWebServerRequest *request) {
|
||||
void CaptivePortal::setup() {
|
||||
// Disable loop by default - will be enabled when captive portal starts
|
||||
this->disable_loop();
|
||||
#ifdef USE_PROVISIONING
|
||||
// The captive portal is a provisioning surface: once the provisioning window
|
||||
// has closed, stop serving it. WiFi's own closed-callback shuts down the
|
||||
// access point the portal runs on, and the gated fallback in WiFiComponent's
|
||||
// loop() ensures neither is started again afterwards.
|
||||
if (provisioning::global_provisioning_manager != nullptr) {
|
||||
provisioning::global_provisioning_manager->add_on_closed_callback([this]() {
|
||||
if (this->active_) {
|
||||
ESP_LOGD(TAG, "Provisioning window closed; stopping captive portal");
|
||||
this->end();
|
||||
}
|
||||
});
|
||||
}
|
||||
#endif
|
||||
}
|
||||
void CaptivePortal::start() {
|
||||
this->base_->init();
|
||||
@@ -102,17 +85,7 @@ void CaptivePortal::start() {
|
||||
this->base_->add_handler_without_auth(this);
|
||||
}
|
||||
|
||||
network::IPAddress ip = wifi::global_wifi_component->wifi_soft_ap_ip();
|
||||
|
||||
#if defined(USE_ESP32)
|
||||
// Create DNS server instance for ESP-IDF
|
||||
this->dns_server_ = make_unique<DNSServer>();
|
||||
this->dns_server_->start(ip);
|
||||
#elif defined(USE_ARDUINO)
|
||||
this->dns_server_ = make_unique<DNSServer>();
|
||||
this->dns_server_->setErrorReplyCode(DNSReplyCode::NoError);
|
||||
this->dns_server_->start(53, ESPHOME_F("*"), ip);
|
||||
#endif
|
||||
this->dns_.start(wifi::global_wifi_component->wifi_soft_ap_ip());
|
||||
|
||||
this->initialized_ = true;
|
||||
this->active_ = true;
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
#pragma once
|
||||
#include "esphome/core/defines.h"
|
||||
#ifdef USE_CAPTIVE_PORTAL
|
||||
#include <memory>
|
||||
#if defined(USE_ESP32)
|
||||
#include "dns_server_esp32_idf.h"
|
||||
#elif defined(USE_ARDUINO)
|
||||
#include <DNSServer.h>
|
||||
#endif
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/preferences.h"
|
||||
#include "esphome/components/web_server_base/web_server_base.h"
|
||||
#include "esphome/components/web_server_base/captive_dns.h"
|
||||
|
||||
namespace esphome::captive_portal {
|
||||
|
||||
@@ -19,17 +14,7 @@ class CaptivePortal final : public AsyncWebHandler, public Component {
|
||||
CaptivePortal(web_server_base::WebServerBase *base);
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
void loop() override {
|
||||
#if defined(USE_ESP32)
|
||||
if (this->dns_server_ != nullptr) {
|
||||
this->dns_server_->process_next_request();
|
||||
}
|
||||
#elif defined(USE_ARDUINO)
|
||||
if (this->dns_server_ != nullptr) {
|
||||
this->dns_server_->processNextRequest();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
void loop() override { this->dns_.loop(); }
|
||||
float get_setup_priority() const override;
|
||||
void start();
|
||||
bool is_active() const { return this->active_; }
|
||||
@@ -37,10 +22,7 @@ class CaptivePortal final : public AsyncWebHandler, public Component {
|
||||
this->active_ = false;
|
||||
this->disable_loop(); // Stop processing DNS requests
|
||||
this->base_->deinit();
|
||||
if (this->dns_server_ != nullptr) {
|
||||
this->dns_server_->stop();
|
||||
this->dns_server_ = nullptr;
|
||||
}
|
||||
this->dns_.stop();
|
||||
}
|
||||
|
||||
bool canHandle(AsyncWebServerRequest *request) const override {
|
||||
@@ -60,9 +42,7 @@ class CaptivePortal final : public AsyncWebHandler, public Component {
|
||||
web_server_base::WebServerBase *base_;
|
||||
bool initialized_{false};
|
||||
bool active_{false};
|
||||
#if defined(USE_ARDUINO) || defined(USE_ESP32)
|
||||
std::unique_ptr<DNSServer> dns_server_{nullptr};
|
||||
#endif
|
||||
web_server_base::CaptiveDNS dns_;
|
||||
};
|
||||
|
||||
extern CaptivePortal *global_captive_portal; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
|
||||
@@ -46,7 +46,6 @@ from esphome.const import (
|
||||
CONF_TARGET_TEMPERATURE_LOW_STATE_TOPIC,
|
||||
CONF_TARGET_TEMPERATURE_STATE_TOPIC,
|
||||
CONF_TEMPERATURE_STEP,
|
||||
CONF_TRIGGER_ID,
|
||||
CONF_VISUAL,
|
||||
CONF_WEB_SERVER,
|
||||
)
|
||||
@@ -164,14 +163,6 @@ def visual_temperature_step(value: Any) -> ConfigType:
|
||||
)
|
||||
|
||||
|
||||
# Actions
|
||||
StateTrigger = climate_ns.class_(
|
||||
"StateTrigger", automation.Trigger.template(Climate.operator("ref"))
|
||||
)
|
||||
ControlTrigger = climate_ns.class_(
|
||||
"ControlTrigger", automation.Trigger.template(ClimateCall.operator("ref"))
|
||||
)
|
||||
|
||||
_CLIMATE_SCHEMA = (
|
||||
cv.ENTITY_BASE_SCHEMA.extend(web_server.WEBSERVER_SORTING_SCHEMA)
|
||||
.extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA)
|
||||
@@ -250,16 +241,8 @@ _CLIMATE_SCHEMA = (
|
||||
cv.Optional(CONF_TARGET_HUMIDITY_STATE_TOPIC): cv.All(
|
||||
cv.requires_component("mqtt"), cv.publish_topic
|
||||
),
|
||||
cv.Optional(CONF_ON_CONTROL): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(ControlTrigger),
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_ON_STATE): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(StateTrigger),
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_ON_CONTROL): automation.validate_automation(),
|
||||
cv.Optional(CONF_ON_STATE): automation.validate_automation(),
|
||||
}
|
||||
)
|
||||
)
|
||||
@@ -288,6 +271,16 @@ def climate_schema(
|
||||
return _CLIMATE_SCHEMA.extend(schema)
|
||||
|
||||
|
||||
_CALLBACK_AUTOMATIONS = (
|
||||
automation.CallbackAutomation(
|
||||
CONF_ON_STATE, "add_on_state_callback", [(Climate.operator("ref"), "x")]
|
||||
),
|
||||
automation.CallbackAutomation(
|
||||
CONF_ON_CONTROL, "add_on_control_callback", [(ClimateCall.operator("ref"), "x")]
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@setup_entity("climate")
|
||||
async def setup_climate_core_(var: MockObj, config: ConfigType) -> None:
|
||||
visual = config.get(CONF_VISUAL, {})
|
||||
@@ -443,17 +436,7 @@ async def setup_climate_core_(var: MockObj, config: ConfigType) -> None:
|
||||
)
|
||||
)
|
||||
|
||||
for conf in config.get(CONF_ON_STATE, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(
|
||||
trigger, [(Climate.operator("ref"), "x")], conf
|
||||
)
|
||||
|
||||
for conf in config.get(CONF_ON_CONTROL, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(
|
||||
trigger, [(ClimateCall.operator("ref"), "x")], conf
|
||||
)
|
||||
await automation.build_callback_automations(var, config, _CALLBACK_AUTOMATIONS)
|
||||
|
||||
if web_server_config := config.get(CONF_WEB_SERVER):
|
||||
await web_server.add_entity_config(var, web_server_config)
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/automation.h"
|
||||
#include "climate.h"
|
||||
|
||||
namespace esphome::climate {
|
||||
|
||||
class ControlTrigger final : public Trigger<ClimateCall &> {
|
||||
public:
|
||||
ControlTrigger(Climate *climate) {
|
||||
climate->add_on_control_callback([this](ClimateCall &x) { this->trigger(x); });
|
||||
}
|
||||
};
|
||||
|
||||
class StateTrigger final : public Trigger<Climate &> {
|
||||
public:
|
||||
StateTrigger(Climate *climate) {
|
||||
climate->add_on_state_callback([this](Climate &x) { this->trigger(x); });
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace esphome::climate
|
||||
@@ -14,9 +14,11 @@ CONF_ALLOWED_IPS = "allowed_ips"
|
||||
CONF_AQI = "aqi"
|
||||
CONF_AUTOMATIC_BASELINE_CALIBRATION = "automatic_baseline_calibration"
|
||||
CONF_B_CONSTANT = "b_constant"
|
||||
CONF_BLUE_CHANNEL = "blue_channel"
|
||||
CONF_BREATH_VOC_EQUIVALENT = "breath_voc_equivalent"
|
||||
CONF_BYTE_ORDER = "byte_order"
|
||||
CONF_CHANNEL_COLORS = "channel_colors"
|
||||
CONF_CLEAR_CHANNEL = "clear_channel"
|
||||
CONF_CLIMATE_ID = "climate_id"
|
||||
CONF_CO2_EQUIVALENT = "co2_equivalent"
|
||||
CONF_COLOR_DEPTH = "color_depth"
|
||||
@@ -29,6 +31,7 @@ CONF_DESCRIPTION = "description"
|
||||
CONF_DRAW_ROUNDING = "draw_rounding"
|
||||
CONF_ENABLE_OTA_DOWNGRADE_PROTECTION = "enable_ota_downgrade_protection"
|
||||
CONF_ENABLED = "enabled"
|
||||
CONF_GREEN_CHANNEL = "green_channel"
|
||||
CONF_GYROSCOPE_ODR = "gyroscope_odr"
|
||||
CONF_GYROSCOPE_RANGE = "gyroscope_range"
|
||||
CONF_HOLD_STATE = "hold_state"
|
||||
@@ -47,9 +50,11 @@ CONF_ON_PACKET = "on_packet"
|
||||
CONF_ON_RECEIVE = "on_receive"
|
||||
CONF_ON_SCAN_END = "on_scan_end"
|
||||
CONF_ON_STATE_CHANGE = "on_state_change"
|
||||
CONF_ON_STOP = "on_stop"
|
||||
CONF_PARITY = "parity"
|
||||
CONF_RECEIVER_FREQUENCY = "receiver_frequency"
|
||||
CONF_RECONNECT_INTERVAL = "reconnect_interval"
|
||||
CONF_RED_CHANNEL = "red_channel"
|
||||
CONF_REQUEST_HEADERS = "request_headers"
|
||||
CONF_ROLE = "role"
|
||||
CONF_ROWS = "rows"
|
||||
|
||||
@@ -18,21 +18,40 @@ static constexpr int CSE7761_UREF = 42563; // RmsUc
|
||||
static constexpr int CSE7761_IREF = 52241; // RmsIAC
|
||||
static constexpr int CSE7761_PREF = 44513; // PowerPAC
|
||||
|
||||
// Empirical Sonoff POW CT factor taken from Tasmota
|
||||
static constexpr uint32_t CURRENT_TRANSFORMER_COEFFICIENT_SCALE = 5;
|
||||
|
||||
// PGA 16x on both current channels
|
||||
static constexpr uint16_t SYSCON_SHUNT = 0xFF04;
|
||||
// All PGAs 1x, ADC2ON
|
||||
static constexpr uint16_t SYSCON_CURRENT_TRANSFORMER = 0xFE00;
|
||||
|
||||
// System clock (3.579545MHz) / 8, divided by Ufreq gives the line frequency in Hz
|
||||
static constexpr float CSE7761_UFREQ_CLOCK = 3579545.0f / 8.0f;
|
||||
|
||||
static constexpr uint8_t CSE7761_REG_SYSCON = 0x00; // (2) System Control Register (0x0A04)
|
||||
static constexpr uint8_t CSE7761_REG_EMUCON = 0x01; // (2) Metering control register (0x0000)
|
||||
static constexpr uint8_t CSE7761_REG_HFCONST = 0x02; // (2) Pulse frequency register (0x1000)
|
||||
static constexpr uint8_t CSE7761_REG_EMUCON2 = 0x13; // (2) Metering control register 2 (0x0001)
|
||||
static constexpr uint8_t CSE7761_REG_PULSE1SEL = 0x1D; // (2) Pin function output select register (0x3210)
|
||||
|
||||
static constexpr uint8_t CSE7761_REG_RMSIA = 0x24; // (3) The effective value of channel A current (0x000000)
|
||||
static constexpr uint8_t CSE7761_REG_RMSIB = 0x25; // (3) The effective value of channel B current (0x000000)
|
||||
static constexpr uint8_t CSE7761_REG_RMSU = 0x26; // (3) Voltage RMS (0x000000)
|
||||
static constexpr uint8_t CSE7761_REG_POWERPA = 0x2C; // (4) Channel A active power, update rate 27.2Hz (0x00000000)
|
||||
static constexpr uint8_t CSE7761_REG_POWERPB = 0x2D; // (4) Channel B active power, update rate 27.2Hz (0x00000000)
|
||||
static constexpr uint8_t CSE7761_REG_SYSSTATUS = 0x43; // (1) System status register
|
||||
static constexpr uint8_t CSE7761_REG_UFREQ = 0x23; // (2) Voltage frequency (0x0000)
|
||||
static constexpr uint8_t CSE7761_REG_RMSIA = 0x24; // (3) The effective value of channel A current (0x000000)
|
||||
static constexpr uint8_t CSE7761_REG_RMSIB = 0x25; // (3) The effective value of channel B current (0x000000)
|
||||
static constexpr uint8_t CSE7761_REG_RMSU = 0x26; // (3) Voltage RMS (0x000000)
|
||||
static constexpr uint8_t CSE7761_REG_POWERFACTOR = 0x27; // (3) Power factor of the selected channel (0x7FFFFF)
|
||||
static constexpr uint8_t CSE7761_REG_ENERGY_PA = 0x28; // (3) Channel A active energy pulse count (0x000000)
|
||||
static constexpr uint8_t CSE7761_REG_ENERGY_PB = 0x29; // (3) Channel B active energy pulse count (0x000000)
|
||||
static constexpr uint8_t CSE7761_REG_POWERPA = 0x2C; // (4) Channel A active power, update rate 27.2Hz (0x00000000)
|
||||
static constexpr uint8_t CSE7761_REG_POWERPB = 0x2D; // (4) Channel B active power, update rate 27.2Hz (0x00000000)
|
||||
static constexpr uint8_t CSE7761_REG_SYSSTATUS = 0x43; // (1) System status register
|
||||
|
||||
static constexpr uint8_t CSE7761_REG_COEFFCHKSUM = 0x6F; // (2) Coefficient checksum
|
||||
static constexpr uint8_t CSE7761_REG_RMSIAC = 0x70; // (2) Channel A effective current conversion coefficient
|
||||
|
||||
// Datasheet: Wh = pulses * EnergyXC * HFConst * 1000 / 2^41 with K1 = K2 = 1
|
||||
static constexpr float CSE7761_ENERGY_WH_SCALE = 1000.0f / 2199023255552.0f;
|
||||
|
||||
static constexpr uint8_t CSE7761_SPECIAL_COMMAND = 0xEA; // Start special command
|
||||
static constexpr uint8_t CSE7761_CMD_RESET = 0x96; // Reset command, after receiving the command, the chip resets
|
||||
static constexpr uint8_t CSE7761_CMD_CLOSE_WRITE = 0xDC; // Close write operation
|
||||
@@ -57,7 +76,18 @@ void CSE7761Component::dump_config() {
|
||||
if (this->is_failed()) {
|
||||
ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " Current input: %s",
|
||||
LOG_STR_ARG(this->is_current_transformer_() ? LOG_STR("current transformer") : LOG_STR("shunt")));
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
LOG_SENSOR(" ", "Voltage", this->voltage_sensor_);
|
||||
LOG_SENSOR(" ", "Current 1", this->current_sensor_1_);
|
||||
LOG_SENSOR(" ", "Current 2", this->current_sensor_2_);
|
||||
LOG_SENSOR(" ", "Power 1", this->power_sensor_1_);
|
||||
LOG_SENSOR(" ", "Power 2", this->power_sensor_2_);
|
||||
LOG_SENSOR(" ", "Frequency", this->frequency_sensor_);
|
||||
LOG_SENSOR(" ", "Power Factor 1", this->power_factor_sensor_1_);
|
||||
LOG_SENSOR(" ", "Energy 1", this->energy_sensors_[0]);
|
||||
LOG_SENSOR(" ", "Energy 2", this->energy_sensors_[1]);
|
||||
}
|
||||
|
||||
void CSE7761Component::update() {
|
||||
@@ -73,7 +103,7 @@ void CSE7761Component::write_(uint8_t reg, uint16_t data) {
|
||||
buffer[1] = reg;
|
||||
uint32_t len = 2;
|
||||
if (data) {
|
||||
if (data < 0xFF) {
|
||||
if (data <= 0xFF) {
|
||||
buffer[2] = data & 0xFF;
|
||||
len = 3;
|
||||
} else {
|
||||
@@ -81,11 +111,7 @@ void CSE7761Component::write_(uint8_t reg, uint16_t data) {
|
||||
buffer[3] = data & 0xFF;
|
||||
len = 4;
|
||||
}
|
||||
uint8_t crc = 0;
|
||||
for (uint32_t i = 0; i < len; i++) {
|
||||
crc += buffer[i];
|
||||
}
|
||||
buffer[len] = ~crc;
|
||||
buffer[len] = ~sum_bytes(buffer, len);
|
||||
len++;
|
||||
}
|
||||
|
||||
@@ -115,46 +141,44 @@ bool CSE7761Component::read_once_(uint8_t reg, uint8_t size, uint32_t *value) {
|
||||
}
|
||||
|
||||
rcvd--;
|
||||
if (static_cast<uint8_t>(~sum_bytes(buffer, rcvd, 0xA5 + reg)) != buffer[rcvd]) {
|
||||
return false;
|
||||
}
|
||||
uint32_t result = 0;
|
||||
// CRC check
|
||||
uint8_t crc = 0xA5 + reg;
|
||||
for (uint32_t i = 0; i < rcvd; i++) {
|
||||
result = (result << 8) | buffer[i];
|
||||
crc += buffer[i];
|
||||
}
|
||||
crc = ~crc;
|
||||
if (crc != buffer[rcvd]) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*value = result;
|
||||
return true;
|
||||
}
|
||||
|
||||
uint32_t CSE7761Component::read_(uint8_t reg, uint8_t size) {
|
||||
bool result = false; // Start loop
|
||||
uint8_t retry = 3; // Retry up to three times
|
||||
uint32_t value = 0; // Default no value
|
||||
while (!result && retry > 0) {
|
||||
retry--;
|
||||
if (this->read_once_(reg, size, &value))
|
||||
return value;
|
||||
bool CSE7761Component::read_(uint8_t reg, uint8_t size, uint32_t *value) {
|
||||
for (uint8_t retry = 0; retry < 3; retry++) {
|
||||
if (this->read_once_(reg, size, value))
|
||||
return true;
|
||||
}
|
||||
ESP_LOGE(TAG, "Reading register %hhu failed!", reg);
|
||||
return value;
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t CSE7761Component::read_(uint8_t reg, uint8_t size) {
|
||||
uint32_t value = 0;
|
||||
return this->read_(reg, size, &value) ? value : 0;
|
||||
}
|
||||
|
||||
uint32_t CSE7761Component::coefficient_by_unit_(uint32_t unit) {
|
||||
const uint32_t scale = this->is_current_transformer_() ? CURRENT_TRANSFORMER_COEFFICIENT_SCALE : 1;
|
||||
uint32_t coeff = 0;
|
||||
switch (unit) {
|
||||
case RMS_UC:
|
||||
coeff = this->data_.coefficient[RMS_UC];
|
||||
return coeff ? 0x400000 * 100 / coeff : 0;
|
||||
case RMS_IAC:
|
||||
coeff = this->data_.coefficient[RMS_IAC];
|
||||
coeff = this->data_.coefficient[RMS_IAC] * scale;
|
||||
return coeff ? (0x800000 * 100 / coeff) * 10 : 0; // Stay within 32 bits
|
||||
case POWER_PAC:
|
||||
coeff = this->data_.coefficient[POWER_PAC];
|
||||
coeff = this->data_.coefficient[POWER_PAC] * scale;
|
||||
return coeff ? 0x80000000 / coeff : 0;
|
||||
}
|
||||
return 0;
|
||||
@@ -167,21 +191,38 @@ bool CSE7761Component::chip_init_() {
|
||||
calc_chksum += this->data_.coefficient[i];
|
||||
}
|
||||
calc_chksum = ~calc_chksum;
|
||||
const bool energy_configured = this->energy_sensors_[0] != nullptr || this->energy_sensors_[1] != nullptr;
|
||||
uint16_t coeff_chksum = this->read_(CSE7761_REG_COEFFCHKSUM, 2);
|
||||
if ((calc_chksum != coeff_chksum) || (!calc_chksum)) {
|
||||
ESP_LOGD(TAG, "Default calibration");
|
||||
this->data_.coefficient[RMS_IAC] = CSE7761_IREF;
|
||||
this->data_.coefficient[RMS_UC] = CSE7761_UREF;
|
||||
this->data_.coefficient[POWER_PAC] = CSE7761_PREF;
|
||||
if (energy_configured) {
|
||||
ESP_LOGW(TAG, "No energy calibration, energy unavailable");
|
||||
}
|
||||
} else if (energy_configured) {
|
||||
uint32_t hf_const = 0;
|
||||
if (!this->read_(CSE7761_REG_HFCONST, 2, &hf_const)) {
|
||||
ESP_LOGW(TAG, "HFConst read failed, energy unavailable");
|
||||
}
|
||||
// The pulse counters follow the raw power, so they need the same front end factor as power
|
||||
const float input_scale = this->is_current_transformer_() ? CURRENT_TRANSFORMER_COEFFICIENT_SCALE : 1.0f;
|
||||
for (uint8_t channel = 0; channel < 2; channel++) {
|
||||
uint32_t scale = this->data_.coefficient[ENERGY_AC + channel] * hf_const;
|
||||
this->energy_[channel].wh_per_pulse = static_cast<float>(scale) * CSE7761_ENERGY_WH_SCALE * input_scale;
|
||||
}
|
||||
}
|
||||
|
||||
this->write_(CSE7761_SPECIAL_COMMAND, CSE7761_CMD_ENABLE_WRITE);
|
||||
|
||||
uint8_t sys_status = this->read_(CSE7761_REG_SYSSTATUS, 1);
|
||||
if (sys_status & 0x10) { // Write enable to protected registers (WREN)
|
||||
this->write_(CSE7761_REG_SYSCON | 0x80, 0xFF04);
|
||||
this->write_(CSE7761_REG_SYSCON | 0x80,
|
||||
this->is_current_transformer_() ? SYSCON_CURRENT_TRANSFORMER : SYSCON_SHUNT);
|
||||
this->write_(CSE7761_REG_EMUCON | 0x80, 0x1183);
|
||||
this->write_(CSE7761_REG_EMUCON2 | 0x80, 0x0FC1);
|
||||
// WaveEN|ZxEN, needed for Ufreq
|
||||
this->write_(CSE7761_REG_EMUCON2 | 0x80, this->frequency_sensor_ != nullptr ? 0x0FE5 : 0x0FC1);
|
||||
this->write_(CSE7761_REG_PULSE1SEL | 0x80, 0x3290);
|
||||
} else {
|
||||
ESP_LOGD(TAG, "Write failed at chip_init");
|
||||
@@ -199,14 +240,15 @@ void CSE7761Component::get_data_() {
|
||||
uint32_t value = this->read_(CSE7761_REG_RMSU, 3);
|
||||
this->data_.voltage_rms = (value >= 0x800000) ? 0 : value;
|
||||
|
||||
// No load threshold of 10mA with a shunt; the raw value stands for 5 times more with a current transformer
|
||||
value = this->read_(CSE7761_REG_RMSIA, 3);
|
||||
this->data_.current_rms[0] = ((value >= 0x800000) || (value < 1600)) ? 0 : value; // No load threshold of 10mA
|
||||
this->data_.current_rms[0] = ((value >= 0x800000) || (value < 1600)) ? 0 : value;
|
||||
value = this->read_(CSE7761_REG_POWERPA, 4);
|
||||
// PowerPA is two's complement signed 32-bit per datasheet
|
||||
this->data_.active_power[0] = (0 == this->data_.current_rms[0]) ? 0 : static_cast<int32_t>(value);
|
||||
|
||||
value = this->read_(CSE7761_REG_RMSIB, 3);
|
||||
this->data_.current_rms[1] = ((value >= 0x800000) || (value < 1600)) ? 0 : value; // No load threshold of 10mA
|
||||
this->data_.current_rms[1] = ((value >= 0x800000) || (value < 1600)) ? 0 : value;
|
||||
value = this->read_(CSE7761_REG_POWERPB, 4);
|
||||
// PowerPB is two's complement signed 32-bit per datasheet
|
||||
this->data_.active_power[1] = (0 == this->data_.current_rms[1]) ? 0 : static_cast<int32_t>(value);
|
||||
@@ -218,12 +260,35 @@ void CSE7761Component::get_data_() {
|
||||
this->voltage_sensor_->publish_state(voltage);
|
||||
}
|
||||
|
||||
uint32_t raw_reg = 0;
|
||||
if (this->frequency_sensor_ != nullptr && this->read_(CSE7761_REG_UFREQ, 2, &raw_reg)) {
|
||||
// Ufreq highest bit set means no signal
|
||||
float frequency = (raw_reg == 0 || raw_reg >= 0x8000) ? 0.0f : CSE7761_UFREQ_CLOCK / raw_reg;
|
||||
this->frequency_sensor_->publish_state(frequency);
|
||||
}
|
||||
|
||||
if (this->power_factor_sensor_1_ != nullptr && this->read_(CSE7761_REG_POWERFACTOR, 3, &raw_reg)) {
|
||||
// ADC2ON makes the chip report channel A
|
||||
int24_t pf{static_cast<int32_t>(raw_reg)};
|
||||
this->power_factor_sensor_1_->publish_state(static_cast<float>(static_cast<int32_t>(pf)) / 0x800000);
|
||||
}
|
||||
|
||||
for (uint8_t channel = 0; channel < 2; channel++) {
|
||||
// Active power = PowerPA * PowerPAC * 1000 / 0x80000000
|
||||
float active_power =
|
||||
static_cast<float>(this->data_.active_power[channel]) / this->coefficient_by_unit_(POWER_PAC); // W
|
||||
float amps = static_cast<float>(this->data_.current_rms[channel]) / this->coefficient_by_unit_(RMS_IAC); // A
|
||||
ESP_LOGD(TAG, "Channel %d power %f W, current %f A", channel + 1, active_power, amps);
|
||||
sensor::Sensor *energy_sensor = this->energy_sensors_[channel];
|
||||
CSE7761EnergyChannel &energy = this->energy_[channel];
|
||||
uint8_t energy_reg = (channel == 0) ? CSE7761_REG_ENERGY_PA : CSE7761_REG_ENERGY_PB;
|
||||
uint32_t raw = 0;
|
||||
if (energy_sensor != nullptr && energy.wh_per_pulse > 0.0f && this->read_(energy_reg, 3, &raw)) {
|
||||
// 24-bit counter, not cleared on read
|
||||
energy.pulses += (raw - energy.last_pulses) & 0xFFFFFF;
|
||||
energy.last_pulses = raw;
|
||||
energy_sensor->publish_state(energy.pulses * energy.wh_per_pulse);
|
||||
}
|
||||
if (channel == 0) {
|
||||
if (this->power_sensor_1_ != nullptr) {
|
||||
this->power_sensor_1_->publish_state(active_power);
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
#include "esphome/components/uart/uart.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/datatypes.h"
|
||||
|
||||
namespace esphome::cse7761 {
|
||||
|
||||
struct CSE7761DataStruct {
|
||||
uint32_t frequency = 0;
|
||||
uint32_t voltage_rms = 0;
|
||||
uint32_t current_rms[2] = {0};
|
||||
int32_t active_power[2] = {0};
|
||||
@@ -15,14 +15,32 @@ struct CSE7761DataStruct {
|
||||
bool ready = false;
|
||||
};
|
||||
|
||||
struct CSE7761EnergyChannel {
|
||||
uint32_t last_pulses{0};
|
||||
uint32_t pulses{0};
|
||||
float wh_per_pulse{0.0f};
|
||||
};
|
||||
|
||||
enum class CSE7761CurrentInput : uint8_t {
|
||||
CSE7761_CURRENT_INPUT_SHUNT,
|
||||
CSE7761_CURRENT_INPUT_CURRENT_TRANSFORMER,
|
||||
};
|
||||
|
||||
/// This class implements support for the CSE7761 UART power sensor.
|
||||
class CSE7761Component final : public PollingComponent, public uart::UARTDevice {
|
||||
public:
|
||||
explicit CSE7761Component(CSE7761CurrentInput current_input) : current_input_(current_input) {}
|
||||
void set_voltage_sensor(sensor::Sensor *voltage_sensor) { voltage_sensor_ = voltage_sensor; }
|
||||
void set_frequency_sensor(sensor::Sensor *frequency_sensor) { frequency_sensor_ = frequency_sensor; }
|
||||
void set_power_factor_1_sensor(sensor::Sensor *power_factor_sensor_1) {
|
||||
power_factor_sensor_1_ = power_factor_sensor_1;
|
||||
}
|
||||
void set_active_power_1_sensor(sensor::Sensor *power_sensor_1) { power_sensor_1_ = power_sensor_1; }
|
||||
void set_current_1_sensor(sensor::Sensor *current_sensor_1) { current_sensor_1_ = current_sensor_1; }
|
||||
void set_energy_1_sensor(sensor::Sensor *energy_sensor_1) { this->energy_sensors_[0] = energy_sensor_1; }
|
||||
void set_active_power_2_sensor(sensor::Sensor *power_sensor_2) { power_sensor_2_ = power_sensor_2; }
|
||||
void set_current_2_sensor(sensor::Sensor *current_sensor_2) { current_sensor_2_ = current_sensor_2; }
|
||||
void set_energy_2_sensor(sensor::Sensor *energy_sensor_2) { this->energy_sensors_[1] = energy_sensor_2; }
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
void update() override;
|
||||
@@ -30,14 +48,23 @@ class CSE7761Component final : public PollingComponent, public uart::UARTDevice
|
||||
protected:
|
||||
// Sensors
|
||||
sensor::Sensor *voltage_sensor_{nullptr};
|
||||
sensor::Sensor *frequency_sensor_{nullptr};
|
||||
sensor::Sensor *power_factor_sensor_1_{nullptr};
|
||||
sensor::Sensor *power_sensor_1_{nullptr};
|
||||
sensor::Sensor *current_sensor_1_{nullptr};
|
||||
sensor::Sensor *power_sensor_2_{nullptr};
|
||||
sensor::Sensor *current_sensor_2_{nullptr};
|
||||
sensor::Sensor *energy_sensors_[2]{nullptr, nullptr};
|
||||
CSE7761DataStruct data_;
|
||||
CSE7761EnergyChannel energy_[2];
|
||||
const CSE7761CurrentInput current_input_;
|
||||
|
||||
bool is_current_transformer_() const {
|
||||
return this->current_input_ == CSE7761CurrentInput::CSE7761_CURRENT_INPUT_CURRENT_TRANSFORMER;
|
||||
}
|
||||
void write_(uint8_t reg, uint16_t data);
|
||||
bool read_once_(uint8_t reg, uint8_t size, uint32_t *value);
|
||||
bool read_(uint8_t reg, uint8_t size, uint32_t *value);
|
||||
uint32_t read_(uint8_t reg, uint8_t size);
|
||||
uint32_t coefficient_by_unit_(uint32_t unit);
|
||||
bool chip_init_();
|
||||
|
||||
@@ -2,15 +2,22 @@ import esphome.codegen as cg
|
||||
from esphome.components import sensor, uart
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_FREQUENCY,
|
||||
CONF_ID,
|
||||
CONF_VOLTAGE,
|
||||
DEVICE_CLASS_CURRENT,
|
||||
DEVICE_CLASS_ENERGY,
|
||||
DEVICE_CLASS_FREQUENCY,
|
||||
DEVICE_CLASS_POWER,
|
||||
DEVICE_CLASS_POWER_FACTOR,
|
||||
DEVICE_CLASS_VOLTAGE,
|
||||
STATE_CLASS_MEASUREMENT,
|
||||
STATE_CLASS_TOTAL_INCREASING,
|
||||
UNIT_AMPERE,
|
||||
UNIT_HERTZ,
|
||||
UNIT_VOLT,
|
||||
UNIT_WATT,
|
||||
UNIT_WATT_HOURS,
|
||||
)
|
||||
from esphome.types import ConfigType
|
||||
|
||||
@@ -26,17 +33,41 @@ CONF_CURRENT_1 = "current_1"
|
||||
CONF_CURRENT_2 = "current_2"
|
||||
CONF_ACTIVE_POWER_1 = "active_power_1"
|
||||
CONF_ACTIVE_POWER_2 = "active_power_2"
|
||||
CONF_ENERGY_1 = "energy_1"
|
||||
CONF_ENERGY_2 = "energy_2"
|
||||
CONF_POWER_FACTOR_1 = "power_factor_1"
|
||||
CONF_CURRENT_INPUT = "current_input"
|
||||
|
||||
CSE7761CurrentInput = cse7761_ns.enum("CSE7761CurrentInput", is_class=True)
|
||||
CURRENT_INPUTS = {
|
||||
"shunt": CSE7761CurrentInput.CSE7761_CURRENT_INPUT_SHUNT,
|
||||
"current_transformer": CSE7761CurrentInput.CSE7761_CURRENT_INPUT_CURRENT_TRANSFORMER,
|
||||
}
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(CSE7761Component),
|
||||
cv.Optional(CONF_CURRENT_INPUT, default="shunt"): cv.enum(
|
||||
CURRENT_INPUTS, lower=True
|
||||
),
|
||||
cv.Optional(CONF_VOLTAGE): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_VOLT,
|
||||
accuracy_decimals=1,
|
||||
device_class=DEVICE_CLASS_VOLTAGE,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_FREQUENCY): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_HERTZ,
|
||||
accuracy_decimals=2,
|
||||
device_class=DEVICE_CLASS_FREQUENCY,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_POWER_FACTOR_1): sensor.sensor_schema(
|
||||
accuracy_decimals=2,
|
||||
device_class=DEVICE_CLASS_POWER_FACTOR,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_CURRENT_1): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_AMPERE,
|
||||
accuracy_decimals=2,
|
||||
@@ -61,6 +92,18 @@ CONFIG_SCHEMA = (
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional(CONF_ENERGY_1): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_WATT_HOURS,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_ENERGY,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional(CONF_ENERGY_2): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_WATT_HOURS,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_ENERGY,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
@@ -79,19 +122,17 @@ FINAL_VALIDATE_SCHEMA = uart.final_validate_device_schema(
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
var = cg.new_Pvariable(config[CONF_ID], config[CONF_CURRENT_INPUT])
|
||||
await cg.register_component(var, config)
|
||||
await uart.register_uart_device(var, config)
|
||||
|
||||
for key in [
|
||||
CONF_VOLTAGE,
|
||||
CONF_CURRENT_1,
|
||||
CONF_CURRENT_2,
|
||||
CONF_ACTIVE_POWER_1,
|
||||
CONF_ACTIVE_POWER_2,
|
||||
]:
|
||||
if key not in config:
|
||||
continue
|
||||
conf = config[key]
|
||||
sens = await sensor.new_sensor(conf)
|
||||
cg.add(getattr(var, f"set_{key}_sensor")(sens))
|
||||
sensors = sensor.sub_sensors(config)
|
||||
await sensors(CONF_VOLTAGE, var.set_voltage_sensor)
|
||||
await sensors(CONF_FREQUENCY, var.set_frequency_sensor)
|
||||
await sensors(CONF_POWER_FACTOR_1, var.set_power_factor_1_sensor)
|
||||
await sensors(CONF_CURRENT_1, var.set_current_1_sensor)
|
||||
await sensors(CONF_CURRENT_2, var.set_current_2_sensor)
|
||||
await sensors(CONF_ACTIVE_POWER_1, var.set_active_power_1_sensor)
|
||||
await sensors(CONF_ACTIVE_POWER_2, var.set_active_power_2_sensor)
|
||||
await sensors(CONF_ENERGY_1, var.set_energy_1_sensor)
|
||||
await sensors(CONF_ENERGY_2, var.set_energy_2_sensor)
|
||||
|
||||
@@ -67,10 +67,7 @@ bool CSE7766Component::check_byte_() {
|
||||
}
|
||||
|
||||
if (index == CSE7766_RAW_DATA_SIZE - 1) {
|
||||
uint8_t checksum = 0;
|
||||
for (uint8_t i = 2; i < CSE7766_RAW_DATA_SIZE - 1; i++) {
|
||||
checksum += this->raw_data_[i];
|
||||
}
|
||||
const uint8_t checksum = sum_bytes(this->raw_data_ + 2, CSE7766_RAW_DATA_SIZE - 3);
|
||||
|
||||
if (checksum != this->raw_data_[CSE7766_RAW_DATA_SIZE - 1]) {
|
||||
ESP_LOGW(TAG, "Invalid checksum from CSE7766: 0x%02X != 0x%02X", checksum,
|
||||
@@ -205,9 +202,10 @@ void CSE7766Component::parse_data_() {
|
||||
float pf = NAN;
|
||||
if (apparent_power > 0) {
|
||||
pf = power / apparent_power;
|
||||
if (pf < 0 || pf > 1) {
|
||||
ESP_LOGD(TAG, "Impossible power factor: %.4f not in interval [0, 1]", pf);
|
||||
pf = NAN;
|
||||
if (pf > 1) {
|
||||
// Noise near the chip's resolution limit, seen during inrush, pushes the ratio past unity
|
||||
ESP_LOGD(TAG, "Power factor %.4f above 1, clamped", pf);
|
||||
pf = 1.0f;
|
||||
}
|
||||
} else if (apparent_power == 0 && power == 0) {
|
||||
// No load, report ideal power factor
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "daikin.h"
|
||||
#include "esphome/components/remote_base/remote_base.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
namespace esphome::daikin {
|
||||
|
||||
@@ -8,14 +9,6 @@ ESPHOME_LOG_TAG(TAG, "daikin.climate");
|
||||
|
||||
static constexpr uint32_t BOOST_TIMEOUT_ID = 0;
|
||||
|
||||
static uint8_t sum_bytes(const uint8_t *data, size_t len) {
|
||||
uint8_t sum = 0;
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
sum += data[i];
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
void DaikinClimate::setup() {
|
||||
climate_ir::ClimateIR::setup();
|
||||
// A boost preset restored from flash gets its timer too
|
||||
|
||||
@@ -246,10 +246,7 @@ climate::ClimateTraits DaikinArcClimate::traits() {
|
||||
}
|
||||
|
||||
bool DaikinArcClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
uint8_t checksum = 0;
|
||||
for (int i = 0; i < (DAIKIN_STATE_FRAME_SIZE - 1); i++) {
|
||||
checksum += frame[i];
|
||||
}
|
||||
const uint8_t checksum = sum_bytes(frame, DAIKIN_STATE_FRAME_SIZE - 1);
|
||||
if (frame[DAIKIN_STATE_FRAME_SIZE - 1] != checksum) {
|
||||
ESP_LOGI(TAG, "checksum error");
|
||||
return false;
|
||||
|
||||
@@ -6,6 +6,8 @@ from esphome.types import ConfigType
|
||||
|
||||
AUTO_LOAD = ["climate_ir"]
|
||||
|
||||
CONF_SUB_UNIT = "sub_unit"
|
||||
|
||||
daikin_brc_ns = cg.esphome_ns.namespace("daikin_brc")
|
||||
DaikinBrcClimate = daikin_brc_ns.class_("DaikinBrcClimate", climate_ir.ClimateIR)
|
||||
|
||||
@@ -13,6 +15,7 @@ DaikinBrcClimate = daikin_brc_ns.class_("DaikinBrcClimate", climate_ir.ClimateIR
|
||||
CONFIG_SCHEMA = climate_ir.climate_ir_with_receiver_schema(DaikinBrcClimate).extend(
|
||||
{
|
||||
cv.Optional(CONF_USE_FAHRENHEIT, default=False): cv.boolean,
|
||||
cv.Optional(CONF_SUB_UNIT, default=0): cv.int_range(min=0, max=5),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -20,3 +23,4 @@ CONFIG_SCHEMA = climate_ir.climate_ir_with_receiver_schema(DaikinBrcClimate).ext
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = await climate_ir.new_climate_ir(config)
|
||||
cg.add(var.set_fahrenheit(config[CONF_USE_FAHRENHEIT]))
|
||||
cg.add(var.set_sub_unit(config[CONF_SUB_UNIT]))
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "daikin_brc.h"
|
||||
#include "esphome/components/remote_base/remote_base.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
namespace esphome::daikin_brc {
|
||||
|
||||
@@ -19,13 +20,18 @@ void DaikinBrcClimate::transmit_state() {
|
||||
0xDA, 0x17, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x20, 0x00};
|
||||
|
||||
// The low 3 bits of the frame header byte address the indoor unit, in the preamble and the state frame
|
||||
remote_state[3] |= this->sub_unit_;
|
||||
remote_state[10] |= this->sub_unit_;
|
||||
remote_state[6] += this->sub_unit_; // preamble checksum covers byte 3
|
||||
|
||||
remote_state[12] = this->alt_mode_();
|
||||
remote_state[13] = this->mode_button_;
|
||||
remote_state[14] = this->operation_mode_();
|
||||
remote_state[17] = this->temperature_();
|
||||
remote_state[18] = this->fan_speed_swing_();
|
||||
|
||||
// Calculate checksum
|
||||
// Calculate state frame checksum
|
||||
for (int i = DAIKIN_BRC_PREAMBLE_SIZE; i < DAIKIN_BRC_TRANSMIT_FRAME_SIZE - 1; i++) {
|
||||
remote_state[DAIKIN_BRC_TRANSMIT_FRAME_SIZE - 1] += remote_state[i];
|
||||
}
|
||||
@@ -160,10 +166,7 @@ uint8_t DaikinBrcClimate::temperature_() {
|
||||
}
|
||||
|
||||
bool DaikinBrcClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
uint8_t checksum = 0;
|
||||
for (int i = 0; i < (DAIKIN_BRC_STATE_FRAME_SIZE - 1); i++) {
|
||||
checksum += frame[i];
|
||||
}
|
||||
const uint8_t checksum = sum_bytes(frame, DAIKIN_BRC_STATE_FRAME_SIZE - 1);
|
||||
if (frame[DAIKIN_BRC_STATE_FRAME_SIZE - 1] != checksum) {
|
||||
ESP_LOGCONFIG(TAG, "Bad CheckSum %x", checksum);
|
||||
return false;
|
||||
@@ -256,8 +259,8 @@ bool DaikinBrcClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
if (byte != 0x17)
|
||||
return false;
|
||||
} else if (pos == 3) {
|
||||
// frame header
|
||||
if (byte != 0x18)
|
||||
// frame header, with this unit's address in the low 3 bits
|
||||
if (byte != (0x18 | this->sub_unit_))
|
||||
return false;
|
||||
} else if (pos == 4) {
|
||||
// frame type
|
||||
|
||||
@@ -60,6 +60,8 @@ class DaikinBrcClimate final : public climate_ir::ClimateIR {
|
||||
this->fahrenheit_ = value;
|
||||
this->temperature_step_ = value ? 0.5f : 1.0f;
|
||||
}
|
||||
/// Which indoor unit (0 to 5) this climate addresses on a multi-unit system
|
||||
void set_sub_unit(uint8_t value) { this->sub_unit_ = value; }
|
||||
|
||||
protected:
|
||||
uint8_t mode_button_ = 0x00;
|
||||
@@ -75,6 +77,7 @@ class DaikinBrcClimate final : public climate_ir::ClimateIR {
|
||||
bool on_receive(remote_base::RemoteReceiveData data) override;
|
||||
bool parse_state_frame_(const uint8_t frame[]);
|
||||
bool fahrenheit_{false};
|
||||
uint8_t sub_unit_{0};
|
||||
};
|
||||
|
||||
} // namespace esphome::daikin_brc
|
||||
|
||||
@@ -129,12 +129,7 @@ void DalyBmsComponent::decode_data_(std::vector<uint8_t> data) {
|
||||
|
||||
while ((it = std::find(it, data.end(), 0xA5)) != data.end()) {
|
||||
if (data.end() - it >= DALY_FRAME_SIZE && it[1] == 0x01) {
|
||||
uint8_t checksum;
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 12; i++) {
|
||||
sum += it[i];
|
||||
}
|
||||
checksum = sum;
|
||||
const uint8_t checksum = sum_bytes(&*it, 12);
|
||||
|
||||
if (checksum == it[12]) {
|
||||
switch (it[2]) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "delonghi.h"
|
||||
#include "esphome/components/remote_base/remote_base.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
namespace esphome::delonghi {
|
||||
|
||||
@@ -102,10 +103,7 @@ uint8_t DelonghiClimate::temperature_() {
|
||||
}
|
||||
|
||||
bool DelonghiClimate::parse_state_frame_(const uint8_t frame[]) {
|
||||
uint8_t checksum = 0;
|
||||
for (int i = 0; i < (DELONGHI_STATE_FRAME_SIZE - 1); i++) {
|
||||
checksum += frame[i];
|
||||
}
|
||||
const uint8_t checksum = sum_bytes(frame, DELONGHI_STATE_FRAME_SIZE - 1);
|
||||
if (frame[DELONGHI_STATE_FRAME_SIZE - 1] != checksum) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ from esphome.const import (
|
||||
CONF_PAGES,
|
||||
CONF_ROTATION,
|
||||
CONF_TO,
|
||||
CONF_TRIGGER_ID,
|
||||
CONF_UPDATE_INTERVAL,
|
||||
CONF_WIDTH,
|
||||
SCHEDULER_DONT_RUN,
|
||||
@@ -39,14 +38,13 @@ DisplayPage = display_ns.class_("DisplayPage")
|
||||
DisplayPagePtr = DisplayPage.operator("ptr")
|
||||
DisplayRef = Display.operator("ref")
|
||||
DisplayPageShowAction = display_ns.class_("DisplayPageShowAction", automation.Action)
|
||||
DisplayOnPageChangeTrigger = display_ns.class_(
|
||||
"DisplayOnPageChangeTrigger", automation.Trigger
|
||||
)
|
||||
|
||||
CONF_ON_PAGE_CHANGE = "on_page_change"
|
||||
CONF_SHOW_TEST_CARD = "show_test_card"
|
||||
CONF_UNSPECIFIED = "unspecified"
|
||||
|
||||
_request_page_change_slot = cg.slot_counter("DISPLAY_PAGE_CHANGE_CALLBACK_COUNT")
|
||||
|
||||
DISPLAY_ROTATIONS = {
|
||||
0: display_ns.DISPLAY_ROTATION_0_DEGREES,
|
||||
90: display_ns.DISPLAY_ROTATION_90_DEGREES,
|
||||
@@ -99,9 +97,6 @@ FULL_DISPLAY_SCHEMA = BASIC_DISPLAY_SCHEMA.extend(
|
||||
),
|
||||
cv.Optional(CONF_ON_PAGE_CHANGE): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(
|
||||
DisplayOnPageChangeTrigger
|
||||
),
|
||||
cv.Optional(CONF_FROM): cv.use_id(DisplayPage),
|
||||
cv.Optional(CONF_TO): cv.use_id(DisplayPage),
|
||||
}
|
||||
@@ -137,15 +132,18 @@ async def setup_display_core_(var, config):
|
||||
pages.append(page)
|
||||
cg.add(var.set_pages(pages))
|
||||
for conf in config.get(CONF_ON_PAGE_CHANGE, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
if CONF_FROM in conf:
|
||||
page = await cg.get_variable(conf[CONF_FROM])
|
||||
cg.add(trigger.set_from(page))
|
||||
if CONF_TO in conf:
|
||||
page = await cg.get_variable(conf[CONF_TO])
|
||||
cg.add(trigger.set_to(page))
|
||||
await automation.build_automation(
|
||||
trigger, [(DisplayPagePtr, "from"), (DisplayPagePtr, "to")], conf
|
||||
_request_page_change_slot(str(var))
|
||||
checks = []
|
||||
for key, name in ((CONF_FROM, "from"), (CONF_TO, "to")):
|
||||
if (page_id := conf.get(key)) is not None:
|
||||
page = await cg.get_variable(page_id)
|
||||
checks.append(f"{name} == ::{page}")
|
||||
await automation.build_callback_automation(
|
||||
var,
|
||||
"add_on_page_change_callback",
|
||||
[(DisplayPagePtr, "from"), (DisplayPagePtr, "to")],
|
||||
conf,
|
||||
when=" && ".join(checks) or None,
|
||||
)
|
||||
if config.get(CONF_SHOW_TEST_CARD):
|
||||
cg.add(var.show_test_card())
|
||||
|
||||
@@ -678,12 +678,14 @@ void Display::set_pages(std::vector<DisplayPage *> pages) {
|
||||
}
|
||||
|
||||
void Display::show_page(DisplayPage *page) {
|
||||
this->previous_page_ = this->page_;
|
||||
#ifdef DISPLAY_PAGE_CHANGE_CALLBACK_COUNT
|
||||
DisplayPage *previous = this->page_;
|
||||
this->page_ = page;
|
||||
if (this->previous_page_ != this->page_) {
|
||||
for (auto *t : on_page_change_triggers_)
|
||||
t->process(this->previous_page_, this->page_);
|
||||
}
|
||||
if (previous != page)
|
||||
this->page_change_callback_.call(previous, page);
|
||||
#else
|
||||
this->page_ = page;
|
||||
#endif
|
||||
}
|
||||
|
||||
void Display::do_update_() {
|
||||
@@ -700,11 +702,6 @@ void Display::do_update_() {
|
||||
this->clear_clipping_();
|
||||
}
|
||||
|
||||
void DisplayOnPageChangeTrigger::process(DisplayPage *from, DisplayPage *to) {
|
||||
if ((this->from_ == nullptr || this->from_ == from) && (this->to_ == nullptr || this->to_ == to))
|
||||
this->trigger(from, to);
|
||||
}
|
||||
|
||||
void Display::strftime(int x, int y, BaseFont *font, Color color, Color background, TextAlign align, const char *format,
|
||||
ESPTime time) {
|
||||
char buffer[64];
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
|
||||
#include "esphome/core/color.h"
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/time.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "display_color_utils.h"
|
||||
@@ -173,7 +175,6 @@ enum RegularPolygonDrawing {
|
||||
|
||||
class Display;
|
||||
class DisplayPage;
|
||||
class DisplayOnPageChangeTrigger;
|
||||
|
||||
/** Optimized display writer that uses function pointers for stateless lambdas.
|
||||
*
|
||||
@@ -702,7 +703,11 @@ class Display : public PollingComponent {
|
||||
|
||||
const DisplayPage *get_active_page() const { return this->page_; }
|
||||
|
||||
void add_on_page_change_trigger(DisplayOnPageChangeTrigger *t) { this->on_page_change_triggers_.push_back(t); }
|
||||
#ifdef DISPLAY_PAGE_CHANGE_CALLBACK_COUNT
|
||||
template<typename F> void add_on_page_change_callback(F &&callback) {
|
||||
this->page_change_callback_.add(std::forward<F>(callback));
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Internal method to set the display rotation with.
|
||||
virtual void set_rotation(DisplayRotation rotation);
|
||||
@@ -809,8 +814,9 @@ class Display : public PollingComponent {
|
||||
DisplayRotation rotation_{DISPLAY_ROTATION_0_DEGREES};
|
||||
display_writer_t writer_{};
|
||||
DisplayPage *page_{nullptr};
|
||||
DisplayPage *previous_page_{nullptr};
|
||||
std::vector<DisplayOnPageChangeTrigger *> on_page_change_triggers_;
|
||||
#ifdef DISPLAY_PAGE_CHANGE_CALLBACK_COUNT
|
||||
StaticCallbackManager<DISPLAY_PAGE_CHANGE_CALLBACK_COUNT, void(DisplayPage *, DisplayPage *)> page_change_callback_;
|
||||
#endif
|
||||
bool auto_clear_enabled_{true};
|
||||
std::vector<Rect> clipping_rectangle_;
|
||||
uint8_t wdt_pixel_counter_{0};
|
||||
@@ -850,18 +856,6 @@ template<typename... Ts> class DisplayPageShowAction final : public Action<Ts...
|
||||
}
|
||||
};
|
||||
|
||||
class DisplayOnPageChangeTrigger final : public Trigger<DisplayPage *, DisplayPage *> {
|
||||
public:
|
||||
explicit DisplayOnPageChangeTrigger(Display *parent) { parent->add_on_page_change_trigger(this); }
|
||||
void process(DisplayPage *from, DisplayPage *to);
|
||||
void set_from(DisplayPage *p) { this->from_ = p; }
|
||||
void set_to(DisplayPage *p) { this->to_ = p; }
|
||||
|
||||
protected:
|
||||
DisplayPage *from_{nullptr};
|
||||
DisplayPage *to_{nullptr};
|
||||
};
|
||||
|
||||
const LogString *text_align_to_string(TextAlign textalign);
|
||||
|
||||
} // namespace esphome::display
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID
|
||||
from esphome.types import ConfigType
|
||||
|
||||
CODEOWNERS = ["@linkedupbits"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
MULTI_CONF = True
|
||||
DOMAIN = "ds3231"
|
||||
|
||||
CONF_DS3231_ID = "ds3231_id"
|
||||
|
||||
ds3231_ns = cg.esphome_ns.namespace("ds3231")
|
||||
DS3231Component = ds3231_ns.class_("DS3231Component", cg.Component, i2c.I2CDevice)
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
cv.Schema({cv.GenerateID(): cv.declare_id(DS3231Component)})
|
||||
.extend(cv.COMPONENT_SCHEMA)
|
||||
.extend(i2c.i2c_device_schema(0x68))
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
await i2c.register_i2c_device(var, config)
|
||||
|
||||
|
||||
automation.register_apply_action(
|
||||
"ds3231.force_temperature_conversion",
|
||||
automation.maybe_simple_id({cv.GenerateID(): cv.use_id(DS3231Component)}),
|
||||
automation.ApplyCall("force_temperature_conversion()"),
|
||||
)
|
||||
@@ -0,0 +1,82 @@
|
||||
#include "ds3231.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
// Datasheet:
|
||||
// - https://www.analog.com/media/en/technical-documentation/data-sheets/DS3231.pdf
|
||||
|
||||
namespace esphome::ds3231 {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "ds3231");
|
||||
|
||||
static constexpr uint8_t DS3231_REG_CONTROL = 0x0E;
|
||||
static constexpr uint8_t DS3231_REG_TEMPERATURE = 0x11;
|
||||
|
||||
void DS3231Component::setup() {
|
||||
if (!this->read_control_status_()) {
|
||||
this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
|
||||
return;
|
||||
}
|
||||
|
||||
this->control_reg_ &= ~CONTROL_EOSC; // keep the oscillator running on battery
|
||||
// INT/SQW is the (unused) interrupt line rather than a square-wave output.
|
||||
this->control_reg_ |= CONTROL_INTCN;
|
||||
if (!this->write_control_()) {
|
||||
this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void DS3231Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "DS3231:");
|
||||
LOG_I2C_DEVICE(this);
|
||||
if (this->is_failed()) {
|
||||
ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
bool DS3231Component::read_temperature(float &out) {
|
||||
uint8_t raw[2];
|
||||
if (this->is_failed() || !this->read_bytes(DS3231_REG_TEMPERATURE, raw, sizeof(raw))) {
|
||||
return false;
|
||||
}
|
||||
// 10-bit two's complement, 0.25 degC per LSB.
|
||||
int16_t value = static_cast<int16_t>((raw[0] << 8) | raw[1]) >> 6;
|
||||
out = value * 0.25f;
|
||||
return true;
|
||||
}
|
||||
|
||||
void DS3231Component::force_temperature_conversion() {
|
||||
// Just kick off the conversion - the chip clears CONV and updates the temperature
|
||||
// register on its own within ~200 ms, and the next temperature poll picks it up.
|
||||
// Blocking here to wait for it would stall the main loop.
|
||||
if (this->is_failed() || !this->read_control_status_())
|
||||
return;
|
||||
if ((this->status_reg_ & STATUS_BSY) != 0) {
|
||||
ESP_LOGW(TAG, "A temperature conversion is already in progress.");
|
||||
return;
|
||||
}
|
||||
this->control_reg_ |= CONTROL_CONV;
|
||||
this->write_control_();
|
||||
}
|
||||
|
||||
bool DS3231Component::read_control_status_() {
|
||||
uint8_t raw[2];
|
||||
if (!this->read_bytes(DS3231_REG_CONTROL, raw, sizeof(raw))) {
|
||||
ESP_LOGW(TAG, "Can't read control/status registers.");
|
||||
return false;
|
||||
}
|
||||
this->control_reg_ = raw[0];
|
||||
this->status_reg_ = raw[1];
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DS3231Component::write_control_() {
|
||||
if (!this->write_byte(DS3231_REG_CONTROL, this->control_reg_)) {
|
||||
ESP_LOGW(TAG, "Can't write control register.");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace esphome::ds3231
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
|
||||
namespace esphome::ds3231 {
|
||||
|
||||
/// Hub for a single DS3231 real-time clock. Owns all register access; the platforms talk to the
|
||||
/// chip through this class.
|
||||
class DS3231Component final : public Component, public i2c::I2CDevice {
|
||||
public:
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
|
||||
bool read_temperature(float &out);
|
||||
void force_temperature_conversion();
|
||||
|
||||
protected:
|
||||
static constexpr uint8_t CONTROL_INTCN = 0x04;
|
||||
static constexpr uint8_t CONTROL_CONV = 0x20;
|
||||
static constexpr uint8_t CONTROL_EOSC = 0x80;
|
||||
|
||||
static constexpr uint8_t STATUS_BSY = 0x04;
|
||||
|
||||
bool read_control_status_();
|
||||
bool write_control_();
|
||||
|
||||
uint8_t control_reg_{0};
|
||||
uint8_t status_reg_{0};
|
||||
};
|
||||
|
||||
} // namespace esphome::ds3231
|
||||
@@ -0,0 +1,41 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import sensor
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
DEVICE_CLASS_TEMPERATURE,
|
||||
ICON_THERMOMETER,
|
||||
STATE_CLASS_MEASUREMENT,
|
||||
UNIT_CELSIUS,
|
||||
)
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from .. import CONF_DS3231_ID, DS3231Component, ds3231_ns
|
||||
|
||||
DEPENDENCIES = ["ds3231"]
|
||||
|
||||
DS3231TemperatureSensor = ds3231_ns.class_(
|
||||
"DS3231TemperatureSensor",
|
||||
sensor.Sensor,
|
||||
cg.PollingComponent,
|
||||
cg.Parented.template(DS3231Component),
|
||||
)
|
||||
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
sensor.sensor_schema(
|
||||
DS3231TemperatureSensor,
|
||||
unit_of_measurement=UNIT_CELSIUS,
|
||||
accuracy_decimals=2,
|
||||
device_class=DEVICE_CLASS_TEMPERATURE,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
icon=ICON_THERMOMETER,
|
||||
)
|
||||
.extend({cv.GenerateID(CONF_DS3231_ID): cv.use_id(DS3231Component)})
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = await sensor.new_sensor(config)
|
||||
await cg.register_component(var, config)
|
||||
await cg.register_parented(var, config[CONF_DS3231_ID])
|
||||
@@ -0,0 +1,23 @@
|
||||
#include "ds3231_temperature.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::ds3231 {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "ds3231.sensor");
|
||||
|
||||
void DS3231TemperatureSensor::update() {
|
||||
float temperature;
|
||||
if (!this->parent_->read_temperature(temperature)) {
|
||||
this->status_set_warning();
|
||||
return;
|
||||
}
|
||||
this->status_clear_warning();
|
||||
this->publish_state(temperature);
|
||||
}
|
||||
|
||||
void DS3231TemperatureSensor::dump_config() {
|
||||
LOG_SENSOR("", "DS3231 Temperature", this);
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
}
|
||||
|
||||
} // namespace esphome::ds3231
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
|
||||
#include "../ds3231.h"
|
||||
|
||||
namespace esphome::ds3231 {
|
||||
|
||||
class DS3231TemperatureSensor final : public sensor::Sensor, public PollingComponent, public Parented<DS3231Component> {
|
||||
public:
|
||||
void update() override;
|
||||
void dump_config() override;
|
||||
};
|
||||
|
||||
} // namespace esphome::ds3231
|
||||
@@ -87,7 +87,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
cg.add_build_flag("-DDSMR_WATER_MBUS_ID=" + str(config[CONF_WATER_MBUS_ID]))
|
||||
cg.add_build_flag("-DDSMR_THERMAL_MBUS_ID=" + str(config[CONF_THERMAL_MBUS_ID]))
|
||||
|
||||
cg.add_library("esphome/dsmr_parser", "1.9.0")
|
||||
cg.add_library("esphome/dsmr_parser", "1.10.0")
|
||||
|
||||
|
||||
def final_validate(config: ConfigType) -> None:
|
||||
|
||||
@@ -97,6 +97,12 @@ CONFIG_SCHEMA = cv.Schema(
|
||||
device_class=DEVICE_CLASS_ENERGY,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("energy_delivered_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT_HOURS,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_ENERGY,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("energy_delivered_tariff1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT_HOURS,
|
||||
accuracy_decimals=3,
|
||||
@@ -109,6 +115,12 @@ CONFIG_SCHEMA = cv.Schema(
|
||||
device_class=DEVICE_CLASS_ENERGY,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("energy_returned_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT_HOURS,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_ENERGY,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("energy_returned_tariff1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT_HOURS,
|
||||
accuracy_decimals=3,
|
||||
@@ -121,6 +133,77 @@ CONFIG_SCHEMA = cv.Schema(
|
||||
device_class=DEVICE_CLASS_ENERGY,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
# Reactive energy totals and per-quadrant (Q1-Q4) values (Switzerland, e.g. EWL Luzern AM550)
|
||||
cv.Optional("total_imported_energy_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("total_exported_energy_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q1_tariff1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q1_tariff2_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q2_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q2_tariff1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q2_tariff2_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q3_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q3_tariff1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q3_tariff2_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q4_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q4_tariff1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("reactive_energy_q4_tariff2_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE_HOURS,
|
||||
accuracy_decimals=3,
|
||||
state_class=STATE_CLASS_TOTAL_INCREASING,
|
||||
),
|
||||
cv.Optional("energy_delivered_tariff1_il"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT_HOURS,
|
||||
accuracy_decimals=3,
|
||||
@@ -231,6 +314,91 @@ CONFIG_SCHEMA = cv.Schema(
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
# Per-phase active power and maximum demand (Switzerland, e.g. EWL Luzern AM550)
|
||||
cv.Optional("power_delivered_l1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("power_delivered_l2_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("power_delivered_l3_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("power_returned_l1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("power_returned_l2_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("power_returned_l3_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("reactive_power_delivered_l1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_REACTIVE_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("reactive_power_delivered_l2_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_REACTIVE_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("reactive_power_delivered_l3_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_REACTIVE_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("reactive_power_returned_l1_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_REACTIVE_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("reactive_power_returned_l2_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_REACTIVE_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("reactive_power_returned_l3_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_REACTIVE_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("maximum_power_delivered_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("maximum_power_returned_ch"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOWATT,
|
||||
accuracy_decimals=3,
|
||||
device_class=DEVICE_CLASS_POWER,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
),
|
||||
cv.Optional("reactive_power_delivered"): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_KILOVOLT_AMPS_REACTIVE,
|
||||
accuracy_decimals=3,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import socket
|
||||
from esphome.components.light.effects import register_addressable_effect
|
||||
from esphome.components.light.types import AddressableLightEffect
|
||||
import esphome.config_validation as cv
|
||||
@@ -28,12 +29,17 @@ CHANNELS = {
|
||||
CONF_UNIVERSE = "universe"
|
||||
CONF_E131_ID = "e131_id"
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(E131Component),
|
||||
cv.Optional(CONF_METHOD, default="MULTICAST"): cv.one_of(*METHODS, upper=True),
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA)
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(E131Component),
|
||||
cv.Optional(CONF_METHOD, default="MULTICAST"): cv.one_of(
|
||||
*METHODS, upper=True
|
||||
),
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA),
|
||||
socket.consume_sockets(1, "e131", socket.SocketType.UDP),
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "e131.h"
|
||||
#ifdef USE_NETWORK
|
||||
#include "e131_addressable_light_effect.h"
|
||||
#include "esphome/components/network/util.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -13,18 +14,18 @@ static const int PORT = 5568;
|
||||
E131Component::E131Component() {}
|
||||
|
||||
E131Component::~E131Component() {
|
||||
#if defined(USE_SOCKET_IMPL_BSD_SOCKETS) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS)
|
||||
if (this->socket_) {
|
||||
this->socket_->close();
|
||||
}
|
||||
#elif defined(USE_SOCKET_IMPL_LWIP_TCP)
|
||||
this->udp_.stop();
|
||||
#endif
|
||||
}
|
||||
|
||||
void E131Component::setup() {
|
||||
#if defined(USE_SOCKET_IMPL_BSD_SOCKETS) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS)
|
||||
this->socket_ = socket::socket_ip(SOCK_DGRAM, IPPROTO_IP);
|
||||
this->socket_ = socket::socket_ip_udp(IPPROTO_IP);
|
||||
if (!this->socket_) {
|
||||
ESP_LOGW(TAG, "Could not create socket: errno %d", errno);
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
|
||||
int enable = 1;
|
||||
int err = this->socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
|
||||
@@ -54,18 +55,13 @@ void E131Component::setup() {
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
#elif defined(USE_SOCKET_IMPL_LWIP_TCP)
|
||||
if (!this->udp_.begin(PORT)) {
|
||||
ESP_LOGW(TAG, "Cannot bind E1.31 to port %d.", PORT);
|
||||
this->mark_failed();
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
join_igmp_groups_();
|
||||
}
|
||||
|
||||
void E131Component::loop() {
|
||||
if (this->igmp_join_pending_ && network::is_connected())
|
||||
this->join_igmp_groups_();
|
||||
E131Packet packet;
|
||||
int universe = 0;
|
||||
uint8_t buf[1460];
|
||||
@@ -74,7 +70,7 @@ void E131Component::loop() {
|
||||
// Drain all queued packets so multi-universe frames are applied
|
||||
// atomically before the light writes. Without this, each universe
|
||||
// packet would trigger a separate full-strip write causing tearing.
|
||||
while ((len = this->read_(buf, sizeof(buf))) > 0) {
|
||||
while ((len = this->socket_->read(buf, sizeof(buf))) > 0) {
|
||||
if (!this->packet_(buf, (size_t) len, universe, packet)) {
|
||||
ESP_LOGV(TAG, "Invalid packet received of size %d.", (int) len);
|
||||
continue;
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
#pragma once
|
||||
#include "esphome/core/defines.h"
|
||||
#ifdef USE_NETWORK
|
||||
#if defined(USE_SOCKET_IMPL_BSD_SOCKETS) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS)
|
||||
#include "esphome/components/socket/socket.h"
|
||||
#elif defined(USE_SOCKET_IMPL_LWIP_TCP)
|
||||
#include <WiFiUdp.h>
|
||||
#endif
|
||||
#include "esphome/core/component.h"
|
||||
|
||||
#include <cinttypes>
|
||||
@@ -45,30 +41,17 @@ class E131Component final : public esphome::Component {
|
||||
void set_method(E131ListenMethod listen_method) { this->listen_method_ = listen_method; }
|
||||
|
||||
protected:
|
||||
inline ssize_t read_(uint8_t *buf, size_t len) {
|
||||
#if defined(USE_SOCKET_IMPL_BSD_SOCKETS) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS)
|
||||
return this->socket_->read(buf, len);
|
||||
#elif defined(USE_SOCKET_IMPL_LWIP_TCP)
|
||||
if (!this->udp_.parsePacket())
|
||||
return -1;
|
||||
return this->udp_.read(buf, len);
|
||||
#else
|
||||
return -1;
|
||||
#endif
|
||||
}
|
||||
bool packet_(const uint8_t *data, size_t len, int &universe, E131Packet &packet);
|
||||
bool process_(int universe, const E131Packet &packet);
|
||||
bool join_igmp_groups_();
|
||||
void join_igmp_groups_();
|
||||
void join_universe_(uint16_t universe);
|
||||
UniverseConsumer *find_universe_(int universe);
|
||||
void join_(int universe);
|
||||
void leave_(int universe);
|
||||
|
||||
E131ListenMethod listen_method_{E131_MULTICAST};
|
||||
#if defined(USE_SOCKET_IMPL_BSD_SOCKETS) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS)
|
||||
std::unique_ptr<socket::Socket> socket_;
|
||||
#elif defined(USE_SOCKET_IMPL_LWIP_TCP)
|
||||
WiFiUDP udp_;
|
||||
#endif
|
||||
bool igmp_join_pending_{false};
|
||||
std::unique_ptr<socket::UDPSocket> socket_;
|
||||
std::vector<E131AddressableLightEffect *> light_effects_;
|
||||
std::vector<UniverseConsumer> universe_consumers_;
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "e131.h"
|
||||
#ifdef USE_NETWORK
|
||||
#include "esphome/components/network/ip_address.h"
|
||||
#include "esphome/components/network/util.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/util.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
@@ -59,33 +60,35 @@ union E131RawPacket {
|
||||
// Get the offset of `property_values[1]`
|
||||
const size_t E131_MIN_PACKET_SIZE = offsetof(E131RawPacket, property_values) + sizeof(uint8_t);
|
||||
|
||||
bool E131Component::join_igmp_groups_() {
|
||||
if (this->listen_method_ != E131_MULTICAST)
|
||||
return false;
|
||||
#if defined(USE_SOCKET_IMPL_BSD_SOCKETS) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS)
|
||||
if (this->socket_ == nullptr)
|
||||
return false;
|
||||
#endif
|
||||
|
||||
void E131Component::join_igmp_groups_() {
|
||||
if (this->listen_method_ != E131_MULTICAST || this->socket_ == nullptr)
|
||||
return;
|
||||
// Joined from loop() once the network is up; RP2040 has no interface to join before then
|
||||
if (!network::is_connected()) {
|
||||
this->igmp_join_pending_ = true;
|
||||
return;
|
||||
}
|
||||
this->igmp_join_pending_ = false;
|
||||
for (auto &entry : this->universe_consumers_) {
|
||||
if (!entry.consumers)
|
||||
continue;
|
||||
if (entry.consumers)
|
||||
this->join_universe_(entry.universe);
|
||||
}
|
||||
}
|
||||
|
||||
ip4_addr_t multicast_addr =
|
||||
network::IPAddress(239, 255, ((entry.universe >> 8) & 0xff), ((entry.universe >> 0) & 0xff));
|
||||
void E131Component::join_universe_(uint16_t universe) {
|
||||
ip4_addr_t multicast_addr = network::IPAddress(239, 255, ((universe >> 8) & 0xff), ((universe >> 0) & 0xff));
|
||||
|
||||
err_t err;
|
||||
{
|
||||
LwIPLock lock;
|
||||
err = igmp_joingroup(IP4_ADDR_ANY4, &multicast_addr);
|
||||
}
|
||||
|
||||
if (err) {
|
||||
ESP_LOGW(TAG, "IGMP join for %d universe of E1.31 failed. Multicast might not work.", entry.universe);
|
||||
}
|
||||
err_t err;
|
||||
{
|
||||
LwIPLock lock;
|
||||
err = igmp_joingroup(IP4_ADDR_ANY4, &multicast_addr);
|
||||
}
|
||||
|
||||
return true;
|
||||
if (err) {
|
||||
ESP_LOGW(TAG, "IGMP join for %d universe of E1.31 failed. Multicast might not work.", universe);
|
||||
} else {
|
||||
ESP_LOGD(TAG, "Joined %d universe for E1.31.", universe);
|
||||
}
|
||||
}
|
||||
|
||||
UniverseConsumer *E131Component::find_universe_(int universe) {
|
||||
@@ -107,9 +110,15 @@ void E131Component::join_(int universe) {
|
||||
this->universe_consumers_.push_back({static_cast<uint16_t>(universe), 1});
|
||||
}
|
||||
|
||||
if (this->join_igmp_groups_()) {
|
||||
ESP_LOGD(TAG, "Joined %d universe for E1.31.", universe);
|
||||
if (this->listen_method_ != E131_MULTICAST || this->socket_ == nullptr)
|
||||
return;
|
||||
// A pending batch join covers this universe too; joining it here as well would break leave_()
|
||||
if (this->igmp_join_pending_ || !network::is_connected()) {
|
||||
ESP_LOGD(TAG, "IGMP join for %d universe of E1.31 deferred until the network is up.", universe);
|
||||
this->igmp_join_pending_ = true;
|
||||
return;
|
||||
}
|
||||
this->join_universe_(universe);
|
||||
}
|
||||
|
||||
void E131Component::leave_(int universe) {
|
||||
|
||||
@@ -27,6 +27,7 @@ EmonTx = emontx_ns.class_("EmonTx", cg.Component, uart.UARTDevice)
|
||||
CONF_EMONTX_ID = "emontx_id"
|
||||
CONF_TAG_NAME = "tag_name"
|
||||
CONF_ON_JSON = "on_json"
|
||||
CONF_LOCK_ON_REBOOT = "lock_on_reboot"
|
||||
|
||||
DOMAIN = "emontx"
|
||||
|
||||
@@ -44,20 +45,11 @@ def _get_data() -> EmonTxData:
|
||||
return CORE.data[DOMAIN]
|
||||
|
||||
|
||||
def _synchronous_automation(value: ConfigType) -> ConfigType:
|
||||
"""Reject deferring actions: the received line and parsed JSON are only valid while the
|
||||
automation runs, and DelayAction and friends keep the trigger arguments for later."""
|
||||
if automation.has_non_synchronous_actions(value):
|
||||
raise cv.Invalid(
|
||||
"Deferring actions (delay, wait_until, script.wait, ...) are not allowed in on_json and "
|
||||
"on_data: the received data is only valid while the automation runs. Copy what you need "
|
||||
"into globals first, then defer in a separate script or automation."
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def _synchronous_automation_schema() -> cv.All:
|
||||
return cv.All(automation.validate_automation({}), _synchronous_automation)
|
||||
# The received line and the parsed JSON document only live while the callbacks run.
|
||||
return automation.validate_synchronous_automation(
|
||||
"on_json and on_data", "the received data"
|
||||
)
|
||||
|
||||
|
||||
# Main configuration schema
|
||||
@@ -67,6 +59,7 @@ CONFIG_SCHEMA = (
|
||||
cv.GenerateID(): cv.declare_id(EmonTx),
|
||||
cv.Optional(CONF_ON_JSON): _synchronous_automation_schema(),
|
||||
cv.Optional(CONF_ON_DATA): _synchronous_automation_schema(),
|
||||
cv.Optional(CONF_LOCK_ON_REBOOT, default=False): cv.boolean,
|
||||
}
|
||||
)
|
||||
.extend(cv.COMPONENT_SCHEMA)
|
||||
@@ -142,6 +135,9 @@ async def to_code(config: ConfigType) -> None:
|
||||
await uart.register_uart_device(var, config)
|
||||
await automation.build_callback_automations(var, config, _CALLBACK_AUTOMATIONS)
|
||||
|
||||
if config[CONF_LOCK_ON_REBOOT]:
|
||||
cg.add(var.set_lock_on_reboot(True))
|
||||
|
||||
|
||||
# Action: emontx.send_command
|
||||
|
||||
@@ -166,3 +162,16 @@ automation.register_apply_action(
|
||||
CONF_COMMAND, "send_command", cg.std_string, const_fn=_plain_literal
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
# Let another component (e.g. serial_proxy) take exclusive ownership of the UART.
|
||||
|
||||
EMONTX_ID_SCHEMA = automation.maybe_simple_id({cv.GenerateID(): cv.use_id(EmonTx)})
|
||||
|
||||
automation.register_apply_action(
|
||||
"emontx.pause", EMONTX_ID_SCHEMA, automation.ApplyCall("set_paused(true)")
|
||||
)
|
||||
automation.register_apply_action(
|
||||
"emontx.resume", EMONTX_ID_SCHEMA, automation.ApplyCall("set_paused(false)")
|
||||
)
|
||||
automation.register_apply_condition("emontx.is_paused", EMONTX_ID_SCHEMA, "is_paused()")
|
||||
|
||||
@@ -6,7 +6,27 @@ namespace esphome::emontx {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "emontx");
|
||||
|
||||
void EmonTx::setup() { this->buffer_pos_ = 0; }
|
||||
void EmonTx::setup() {
|
||||
this->buffer_pos_ = 0;
|
||||
if (!this->lock_on_reboot_)
|
||||
return;
|
||||
// The line feed ends any boot noise first
|
||||
ESP_LOGI(TAG, "Unlocking emonTx after boot");
|
||||
this->write_byte('\n');
|
||||
this->send_command("emonunlock");
|
||||
}
|
||||
|
||||
void EmonTx::on_shutdown() {
|
||||
if (!this->lock_on_reboot_)
|
||||
return;
|
||||
if (this->is_paused()) {
|
||||
ESP_LOGW(TAG, "Not locking emonTx before shutdown, UART is paused");
|
||||
return;
|
||||
}
|
||||
ESP_LOGI(TAG, "Locking emonTx before shutdown");
|
||||
this->send_command("emonlock");
|
||||
this->flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Implements the main loop for parsing data from the serial port.
|
||||
@@ -16,6 +36,20 @@ void EmonTx::setup() { this->buffer_pos_ = 0; }
|
||||
* 2. If line starts with '{', parse as JSON and update sensors/callbacks
|
||||
*/
|
||||
void EmonTx::loop() {
|
||||
if (this->is_paused()) {
|
||||
this->was_paused_ = true;
|
||||
return;
|
||||
}
|
||||
if (this->was_paused_) {
|
||||
// Drop what arrived during the pause and resync at the next line start
|
||||
this->was_paused_ = false;
|
||||
this->buffer_pos_ = 0;
|
||||
this->discarding_line_ = true;
|
||||
uint8_t dropped;
|
||||
while (this->available() > 0 && this->read_byte(&dropped))
|
||||
this->discarding_line_ = dropped != '\n';
|
||||
}
|
||||
|
||||
// Read all available data to prevent UART buffer overflow
|
||||
while (this->available() > 0) {
|
||||
uint8_t received;
|
||||
@@ -45,7 +79,7 @@ void EmonTx::loop() {
|
||||
}
|
||||
}
|
||||
} else if (received == '\r' || this->discarding_line_) {
|
||||
// Ignore CR, and the rest of a line that overflowed the buffer
|
||||
// Ignore CR, and the rest of a line that overflowed or was interrupted by a pause
|
||||
} else if (this->buffer_pos_ >= MAX_LINE_LENGTH) {
|
||||
ESP_LOGW(TAG, "Buffer overflow (>%zu bytes), discarding line", MAX_LINE_LENGTH);
|
||||
this->buffer_pos_ = 0;
|
||||
@@ -83,6 +117,7 @@ void EmonTx::parse_json_(const char *data, size_t len) {
|
||||
*/
|
||||
void EmonTx::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "EmonTx:");
|
||||
ESP_LOGCONFIG(TAG, " Lock on reboot: %s", YESNO(this->lock_on_reboot_));
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
ESP_LOGCONFIG(TAG, " Registered sensors: %zu", this->sensors_.size());
|
||||
@@ -100,6 +135,10 @@ void EmonTx::dump_config() {
|
||||
* @param command The command string to send (LF will be appended automatically).
|
||||
*/
|
||||
void EmonTx::send_command(const char *command) {
|
||||
if (this->is_paused()) {
|
||||
ESP_LOGW(TAG, "Not sending command, UART is paused: %s", command);
|
||||
return;
|
||||
}
|
||||
ESP_LOGD(TAG, "Sending command to emonTx: %s", command);
|
||||
this->write_str(command);
|
||||
this->write_byte('\n');
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "esphome/components/json/json_util.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
@@ -32,6 +33,7 @@ class EmonTx final : public Component, public uart::UARTDevice {
|
||||
void loop() override;
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
void on_shutdown() override;
|
||||
|
||||
template<typename F> void add_on_json_callback(F &&callback) { this->json_callbacks_.add(std::forward<F>(callback)); }
|
||||
|
||||
@@ -41,6 +43,16 @@ class EmonTx final : public Component, public uart::UARTDevice {
|
||||
void send_command(const char *command);
|
||||
void send_command(const std::string &command) { this->send_command(command.c_str()); }
|
||||
|
||||
/// Stop reading the UART and sending commands, so another component can use it.
|
||||
/// Atomic, so it can be called from any task. Hold the pause for at least one loop() pass.
|
||||
void set_paused(bool paused) { this->paused_.store(paused, std::memory_order_relaxed); }
|
||||
|
||||
bool is_paused() const { return this->paused_.load(std::memory_order_relaxed); }
|
||||
|
||||
/// Lock the emonTx ('emonlock') before a reboot, so serial garbage during the reboot is not taken
|
||||
/// as a command, and unlock it in setup(). Needs emonTx firmware v1.2.0 or later.
|
||||
void set_lock_on_reboot(bool lock_on_reboot) { this->lock_on_reboot_ = lock_on_reboot; }
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
void init_sensors(size_t count) { this->sensors_.init(count); }
|
||||
void register_sensor(const char *tag_name, sensor::Sensor *sensor);
|
||||
@@ -55,7 +67,10 @@ class EmonTx final : public Component, public uart::UARTDevice {
|
||||
LazyCallbackManager<void(JsonObject, StringRef)> json_callbacks_;
|
||||
LazyCallbackManager<void(StringRef)> data_callbacks_;
|
||||
uint16_t buffer_pos_{0};
|
||||
bool discarding_line_{false}; // Set after an overflow until the end of that line
|
||||
std::atomic<bool> paused_{false};
|
||||
bool was_paused_{false};
|
||||
bool lock_on_reboot_{false};
|
||||
bool discarding_line_{false}; // Set after an overflow or a pause until the end of that line
|
||||
std::array<char, MAX_LINE_LENGTH + 1> buffer_{};
|
||||
};
|
||||
|
||||
|
||||
@@ -118,3 +118,39 @@ jd79660.extend(
|
||||
(0x04,),
|
||||
),
|
||||
)
|
||||
|
||||
# Good Display GDEY0213F51
|
||||
#
|
||||
# Panel: 2.13" BWYR (4-color) e-paper, 122x250, controller JD79661
|
||||
# Init derived from Good Display sample
|
||||
# <https://www.good-display.com/companyfile/1047.html>
|
||||
# Cross-checked against GxEPD2_213c_GDEY0213F51
|
||||
# <https://github.com/ZinggJM/GxEPD2/blob/master/src/epd4c/GxEPD2_213c_GDEY0213F51.cpp>
|
||||
#
|
||||
# Note: busy pin uses LOW=busy, HIGH=idle.
|
||||
#
|
||||
# fmt: off
|
||||
jd79660.extend(
|
||||
"goodisplay-gdey0213f51-2.13",
|
||||
width=128,
|
||||
height=250,
|
||||
|
||||
initsequence=(
|
||||
(0x4D, 0x78,),
|
||||
(0x00, 0x0F, 0x29,), # PSR
|
||||
(0x01, 0x07, 0x00,), # PWRR
|
||||
(0x03, 0x10, 0x54, 0x44,), # POFS
|
||||
(0x06, 0x05, 0x00, 0x3F, 0x0A, 0x25, 0x12, 0x1A,), # BTST_P
|
||||
(0x50, 0x37,), # CDI
|
||||
(0x60, 0x02, 0x02,), # TCON
|
||||
(0x61, 128 // 256, 128 % 256, 250 // 256, 250 % 256,), # TRES: 128x250 fixed
|
||||
(0xE7, 0x1C,),
|
||||
(0xE3, 0x22,),
|
||||
(0xB4, 0xD0,),
|
||||
(0xB5, 0x03,),
|
||||
(0xE9, 0x01,),
|
||||
(0x30, 0x08,),
|
||||
# Power On (0x04): Must be early part of init seq = Disabled later!
|
||||
(0x04,),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
"""ES7210 audio ADC component."""
|
||||
|
||||
DOMAIN = "es7210"
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c
|
||||
from esphome.components import esp32, i2c
|
||||
from esphome.components.audio_adc import AudioAdc
|
||||
from esphome.components.esp32.const import VARIANT_ESP32, VARIANT_ESP32S2
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_BITS_PER_SAMPLE, CONF_ID, CONF_MIC_GAIN, CONF_SAMPLE_RATE
|
||||
from esphome.core import CORE
|
||||
from esphome.types import ConfigType
|
||||
|
||||
CODEOWNERS = ["@kahrendt"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
|
||||
CONF_CHANNEL_GAINS = "channel_gains"
|
||||
CONF_TDM = "tdm"
|
||||
|
||||
es7210_ns = cg.esphome_ns.namespace("es7210")
|
||||
ES7210 = es7210_ns.class_("ES7210", AudioAdc, cg.Component, i2c.I2CDevice)
|
||||
|
||||
@@ -21,24 +26,42 @@ ES7210_BITS_PER_SAMPLE_ENUM = {
|
||||
|
||||
|
||||
ES7210_MIC_GAINS = [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 34.5, 36, 37.5]
|
||||
ES7210_MIC_GAIN_DEFAULT = 24
|
||||
|
||||
_validate_bits = cv.float_with_unit("bits", "bit")
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
|
||||
def _validate_tdm(value: bool) -> bool:
|
||||
"""Reject TDM on ESP32 variants without TDM hardware support."""
|
||||
if value and CORE.is_esp32:
|
||||
esp32.only_on_variant(
|
||||
unsupported=[VARIANT_ESP32, VARIANT_ESP32S2],
|
||||
msg_prefix="ES7210 TDM mode",
|
||||
)(value)
|
||||
return value
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(ES7210),
|
||||
cv.Optional(CONF_BITS_PER_SAMPLE, default="16bit"): cv.All(
|
||||
_validate_bits, cv.enum(ES7210_BITS_PER_SAMPLE_ENUM)
|
||||
),
|
||||
cv.Optional(CONF_MIC_GAIN, default="24db"): cv.All(
|
||||
cv.Optional(CONF_MIC_GAIN): cv.All(
|
||||
cv.decibel, cv.one_of(*ES7210_MIC_GAINS)
|
||||
),
|
||||
cv.Optional(CONF_CHANNEL_GAINS): cv.All(
|
||||
cv.ensure_list(cv.All(cv.decibel, cv.one_of(*ES7210_MIC_GAINS))),
|
||||
cv.Length(min=4, max=4),
|
||||
),
|
||||
cv.Optional(CONF_SAMPLE_RATE, default=16000): cv.int_range(min=1),
|
||||
cv.Optional(CONF_TDM, default=False): cv.All(cv.boolean, _validate_tdm),
|
||||
}
|
||||
)
|
||||
.extend(cv.COMPONENT_SCHEMA)
|
||||
.extend(i2c.i2c_device_schema(0x40))
|
||||
.extend(i2c.i2c_device_schema(0x40)),
|
||||
cv.has_at_most_one_key(CONF_MIC_GAIN, CONF_CHANNEL_GAINS),
|
||||
)
|
||||
|
||||
|
||||
@@ -48,5 +71,10 @@ async def to_code(config: ConfigType) -> None:
|
||||
await i2c.register_i2c_device(var, config)
|
||||
|
||||
cg.add(var.set_bits_per_sample(config[CONF_BITS_PER_SAMPLE]))
|
||||
cg.add(var.set_mic_gain(config[CONF_MIC_GAIN]))
|
||||
if channel_gains := config.get(CONF_CHANNEL_GAINS):
|
||||
for channel, gain in enumerate(channel_gains):
|
||||
cg.add(var.set_channel_gain(channel, gain))
|
||||
else:
|
||||
cg.add(var.set_mic_gain(config.get(CONF_MIC_GAIN, ES7210_MIC_GAIN_DEFAULT)))
|
||||
cg.add(var.set_sample_rate(config[CONF_SAMPLE_RATE]))
|
||||
cg.add(var.set_tdm(config[CONF_TDM]))
|
||||
|
||||
@@ -27,8 +27,10 @@ void ES7210::dump_config() {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"ES7210 audio ADC:\n"
|
||||
" Bits Per Sample: %" PRIu8 "\n"
|
||||
" Sample Rate: %" PRIu32,
|
||||
this->bits_per_sample_, this->sample_rate_);
|
||||
" Sample Rate: %" PRIu32 "\n"
|
||||
" Channel Gains: %.1f dB, %.1f dB, %.1f dB, %.1f dB",
|
||||
this->bits_per_sample_, this->sample_rate_, this->channel_gains_[0], this->channel_gains_[1],
|
||||
this->channel_gains_[2], this->channel_gains_[3]);
|
||||
|
||||
if (this->is_failed()) {
|
||||
ESP_LOGE(TAG, " Failed to initialize");
|
||||
@@ -88,7 +90,17 @@ void ES7210::setup() {
|
||||
}
|
||||
|
||||
bool ES7210::set_mic_gain(float mic_gain) {
|
||||
this->mic_gain_ = clamp<float>(mic_gain, ES7210_MIC_GAIN_MIN, ES7210_MIC_GAIN_MAX);
|
||||
this->channel_gains_.fill(clamp<float>(mic_gain, ES7210_MIC_GAIN_MIN, ES7210_MIC_GAIN_MAX));
|
||||
if (this->setup_complete_) {
|
||||
return this->configure_mic_gain_();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ES7210::set_channel_gain(uint8_t channel, float gain) {
|
||||
if (channel >= this->channel_gains_.size())
|
||||
return false;
|
||||
this->channel_gains_[channel] = clamp<float>(gain, ES7210_MIC_GAIN_MIN, ES7210_MIC_GAIN_MAX);
|
||||
if (this->setup_complete_) {
|
||||
return this->configure_mic_gain_();
|
||||
}
|
||||
@@ -133,7 +145,6 @@ bool ES7210::configure_sample_rate_() {
|
||||
}
|
||||
|
||||
bool ES7210::configure_mic_gain_() {
|
||||
auto regv = this->es7210_gain_reg_value_(this->mic_gain_);
|
||||
for (uint8_t i = 0; i < 4; ++i) {
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC1_GAIN_REG43 + i, 0x10, 0x00));
|
||||
}
|
||||
@@ -144,26 +155,30 @@ bool ES7210::configure_mic_gain_() {
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_CLOCK_OFF_REG01, 0x0b, 0x00));
|
||||
ES7210_ERROR_CHECK(this->write_byte(ES7210_MIC12_POWER_REG4B, 0x00));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC1_GAIN_REG43, 0x10, 0x10));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC1_GAIN_REG43, 0x0f, regv));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC1_GAIN_REG43, 0x0f,
|
||||
this->es7210_gain_reg_value_(this->channel_gains_[0])));
|
||||
|
||||
// Configure mic 2
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_CLOCK_OFF_REG01, 0x0b, 0x00));
|
||||
ES7210_ERROR_CHECK(this->write_byte(ES7210_MIC12_POWER_REG4B, 0x00));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC2_GAIN_REG44, 0x10, 0x10));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC2_GAIN_REG44, 0x0f, regv));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC2_GAIN_REG44, 0x0f,
|
||||
this->es7210_gain_reg_value_(this->channel_gains_[1])));
|
||||
|
||||
// Configure mic 3
|
||||
// MIC3 uses the ADC3/4 and MIC3/4 clock domains (bits 2 and 4), not the MIC1/2 domains.
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_CLOCK_OFF_REG01, 0x15, 0x00));
|
||||
ES7210_ERROR_CHECK(this->write_byte(ES7210_MIC34_POWER_REG4C, 0x00));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC3_GAIN_REG45, 0x10, 0x10));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC3_GAIN_REG45, 0x0f, regv));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC3_GAIN_REG45, 0x0f,
|
||||
this->es7210_gain_reg_value_(this->channel_gains_[2])));
|
||||
|
||||
// Configure mic 4
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_CLOCK_OFF_REG01, 0x15, 0x00));
|
||||
ES7210_ERROR_CHECK(this->write_byte(ES7210_MIC34_POWER_REG4C, 0x00));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC4_GAIN_REG46, 0x10, 0x10));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC4_GAIN_REG46, 0x0f, regv));
|
||||
ES7210_ERROR_CHECK(this->es7210_update_reg_bit_(ES7210_MIC4_GAIN_REG46, 0x0f,
|
||||
this->es7210_gain_reg_value_(this->channel_gains_[3])));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
|
||||
#include "esphome/components/audio_adc/audio_adc.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/core/component.h"
|
||||
@@ -27,10 +29,15 @@ class ES7210 final : public audio_adc::AudioAdc, public Component, public i2c::I
|
||||
void dump_config() override;
|
||||
|
||||
void set_bits_per_sample(ES7210BitsPerSample bits_per_sample) { this->bits_per_sample_ = bits_per_sample; }
|
||||
/// Sets all four channel gains, replacing any configured per-channel gains.
|
||||
bool set_mic_gain(float mic_gain) override;
|
||||
/// Sets a zero-based channel gain; returns false for an invalid channel or an I2C failure.
|
||||
bool set_channel_gain(uint8_t channel, float gain);
|
||||
void set_sample_rate(uint32_t sample_rate) { this->sample_rate_ = sample_rate; }
|
||||
void set_tdm(bool enable_tdm) { this->enable_tdm_ = enable_tdm; }
|
||||
|
||||
float mic_gain() override { return this->mic_gain_; };
|
||||
/// Returns the MIC1 gain; other channels may have different gains.
|
||||
float mic_gain() override { return this->channel_gains_[0]; };
|
||||
|
||||
protected:
|
||||
/// @brief Updates an I2C registry address by modifying the current state
|
||||
@@ -50,8 +57,8 @@ class ES7210 final : public audio_adc::AudioAdc, public Component, public i2c::I
|
||||
bool configure_sample_rate_();
|
||||
|
||||
bool setup_complete_{false};
|
||||
bool enable_tdm_{false}; // TDM is unsupported in ESPHome as of version 2024.12
|
||||
float mic_gain_{0};
|
||||
bool enable_tdm_{false};
|
||||
std::array<float, 4> channel_gains_{{0.0f, 0.0f, 0.0f, 0.0f}};
|
||||
ES7210BitsPerSample bits_per_sample_{ES7210_BITS_PER_SAMPLE_16};
|
||||
uint32_t sample_rate_{0};
|
||||
};
|
||||
|
||||
@@ -164,6 +164,10 @@ void ESP32InternalGPIOPin::setup() {
|
||||
conf.pull_down_en = this->flags_ & gpio::FLAG_PULLDOWN ? GPIO_PULLDOWN_ENABLE : GPIO_PULLDOWN_DISABLE;
|
||||
conf.intr_type = GPIO_INTR_DISABLE;
|
||||
gpio_config(&conf);
|
||||
#ifdef CONFIG_FREERTOS_USE_TICKLESS_IDLE
|
||||
// If auto light sleep is used gpio sleep mode needs to be disabled for the pin
|
||||
gpio_sleep_sel_dis(this->get_pin_num());
|
||||
#endif
|
||||
if (this->flags_ & gpio::FLAG_OUTPUT) {
|
||||
gpio_set_drive_capability(this->get_pin_num(), this->get_drive_strength());
|
||||
}
|
||||
|
||||
@@ -350,19 +350,8 @@ bool ESP32BLE::ble_setup_() {
|
||||
}
|
||||
} else {
|
||||
const auto &app_name = App.get_name();
|
||||
size_t name_len = app_name.length();
|
||||
if (name_len > 20) {
|
||||
if (App.is_name_add_mac_suffix_enabled()) {
|
||||
// Keep first 13 chars and last 7 chars (MAC suffix), remove middle
|
||||
memcpy(name_buffer, app_name.c_str(), 13);
|
||||
memcpy(name_buffer + 13, app_name.c_str() + name_len - 7, 7);
|
||||
} else {
|
||||
memcpy(name_buffer, app_name.c_str(), 20);
|
||||
}
|
||||
name_buffer[20] = '\0';
|
||||
} else {
|
||||
memcpy(name_buffer, app_name.c_str(), name_len + 1); // Include null terminator
|
||||
}
|
||||
truncate_name_to(name_buffer, sizeof(name_buffer), app_name.c_str(), app_name.length(),
|
||||
App.is_name_add_mac_suffix_enabled() ? MAC_ADDRESS_SUFFIX_WITH_SEPARATOR_LEN : 0);
|
||||
device_name = name_buffer;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import encodings
|
||||
import struct
|
||||
from typing import Any
|
||||
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
@@ -25,8 +27,10 @@ from esphome.const import (
|
||||
__version__ as ESPHOME_VERSION,
|
||||
)
|
||||
from esphome.core import CORE
|
||||
from esphome.cpp_generator import MockObj
|
||||
import esphome.final_validate as fv
|
||||
from esphome.schema_extractors import SCHEMA_EXTRACT
|
||||
from esphome.types import ConfigType, TemplateArgsType
|
||||
|
||||
AUTO_LOAD = ["esp32_ble", "bytebuffer"]
|
||||
CODEOWNERS = ["@jesserockz", "@clydebarrow", "@Rapsssito"]
|
||||
@@ -111,8 +115,6 @@ BLECharacteristicNotifyAction = esp32_ble_server_automations_ns.class_(
|
||||
)
|
||||
bytebuffer_ns = cg.esphome_ns.namespace("bytebuffer")
|
||||
Endianness_ns = bytebuffer_ns.namespace("Endian")
|
||||
ByteBuffer_ns = bytebuffer_ns.namespace("ByteBuffer")
|
||||
ByteBuffer = bytebuffer_ns.class_("ByteBuffer")
|
||||
|
||||
|
||||
PROPERTY_MAP = {
|
||||
@@ -141,6 +143,15 @@ class ValueType:
|
||||
return value
|
||||
|
||||
|
||||
def float32(value: Any) -> float:
|
||||
value = cv.float_(value)
|
||||
try:
|
||||
struct.pack("<f", value)
|
||||
except OverflowError as e:
|
||||
raise cv.Invalid(f"{value} is out of range for a float") from e
|
||||
return value
|
||||
|
||||
|
||||
VALUE_TYPES = {
|
||||
type_name: ValueType(type_name, validator, length)
|
||||
for type_name, validator, length in (
|
||||
@@ -152,7 +163,7 @@ VALUE_TYPES = {
|
||||
("int16_t", cv.int_range(-32768, 32767), 2),
|
||||
("int32_t", cv.int_range(-2147483648, 2147483647), 4),
|
||||
("int64_t", cv.int_range(-9223372036854775808, 9223372036854775807), 8),
|
||||
("float", cv.float_, 4),
|
||||
("float", float32, 4),
|
||||
("double", cv.float_, 8),
|
||||
("string", cv.string_strict, None), # Length is variable
|
||||
)
|
||||
@@ -495,19 +506,48 @@ def parse_uuid(uuid):
|
||||
return ESPBTUUID_ns.from_raw(uuid)
|
||||
|
||||
|
||||
_STRUCT_FORMATS = {
|
||||
"uint8_t": "B",
|
||||
"uint16_t": "H",
|
||||
"uint32_t": "I",
|
||||
"uint64_t": "Q",
|
||||
"int8_t": "b",
|
||||
"int16_t": "h",
|
||||
"int32_t": "i",
|
||||
"int64_t": "q",
|
||||
"float": "f",
|
||||
"double": "d",
|
||||
}
|
||||
|
||||
|
||||
def value_bytes(value_config: ConfigType) -> list[int]:
|
||||
"""The bytes of a constant value, as ByteBuffer::wrap packed them at runtime."""
|
||||
value = value_config[CONF_DATA]
|
||||
if isinstance(value, str):
|
||||
return list(value.encode(value_config[CONF_STRING_ENCODING]))
|
||||
if isinstance(value, list):
|
||||
return value
|
||||
order = ">" if value_config[CONF_ENDIANNESS] == "BIG" else "<"
|
||||
return list(struct.pack(order + _STRUCT_FORMATS[value_config[CONF_TYPE]], value))
|
||||
|
||||
|
||||
async def parse_value(value_config, args):
|
||||
value = value_config[CONF_DATA]
|
||||
if isinstance(value, cv.Lambda):
|
||||
return await cg.templatable(value, args, cg.std_vector.template(cg.uint8))
|
||||
# An initializer list calls the set_value(std::initializer_list<uint8_t>) overload
|
||||
return cg.ArrayInitializer(*value_bytes(value_config))
|
||||
|
||||
if isinstance(value, str):
|
||||
value = list(value.encode(value_config[CONF_STRING_ENCODING]))
|
||||
if isinstance(value, list):
|
||||
# Generate initializer list {1, 2, 3} instead of std::vector<uint8_t>({1, 2, 3})
|
||||
# This calls the set_value(std::initializer_list<uint8_t>) overload
|
||||
return cg.ArrayInitializer(*value)
|
||||
val = cg.RawExpression(f"{value_config[CONF_TYPE]}({cg.safe_exp(value)})")
|
||||
return ByteBuffer_ns.wrap(val, value_config[CONF_ENDIANNESS])
|
||||
|
||||
async def set_value_buffer(
|
||||
var: MockObj, value_config: ConfigType, args: TemplateArgsType
|
||||
) -> None:
|
||||
value = value_config[CONF_DATA]
|
||||
if not isinstance(value, cv.Lambda):
|
||||
value = value_bytes(value_config)
|
||||
await automation.templatable_bytes(
|
||||
value, args, var.set_buffer_template, var.set_buffer_static, "ble_server_value"
|
||||
)
|
||||
|
||||
|
||||
def calculate_num_handles(service_config):
|
||||
@@ -662,8 +702,7 @@ async def to_code(config):
|
||||
async def ble_server_characteristic_set_value(config, action_id, template_arg, args):
|
||||
paren = await cg.get_variable(config[CONF_ID])
|
||||
var = cg.new_Pvariable(action_id, template_arg, paren)
|
||||
value = await parse_value(config[CONF_VALUE], args)
|
||||
cg.add(var.set_buffer(value))
|
||||
await set_value_buffer(var, config[CONF_VALUE], args)
|
||||
cg.add_define("USE_ESP32_BLE_SERVER_SET_VALUE_ACTION")
|
||||
return var
|
||||
|
||||
@@ -682,8 +721,7 @@ async def ble_server_characteristic_set_value(config, action_id, template_arg, a
|
||||
async def ble_server_descriptor_set_value(config, action_id, template_arg, args):
|
||||
paren = await cg.get_variable(config[CONF_ID])
|
||||
var = cg.new_Pvariable(action_id, template_arg, paren)
|
||||
value = await parse_value(config[CONF_VALUE], args)
|
||||
cg.add(var.set_buffer(value))
|
||||
await set_value_buffer(var, config[CONF_VALUE], args)
|
||||
cg.add_define("USE_ESP32_BLE_SERVER_DESCRIPTOR_SET_VALUE_ACTION")
|
||||
return var
|
||||
|
||||
|
||||
@@ -30,6 +30,14 @@ BLECharacteristic::BLECharacteristic(const ESPBTUUID uuid, uint32_t properties)
|
||||
|
||||
void BLECharacteristic::set_value(ByteBuffer buffer) { this->set_value(buffer.get_data()); }
|
||||
|
||||
void BLECharacteristic::set_value(const uint8_t *data, size_t length) {
|
||||
if (length == 0) { // An empty constant is a nullptr table
|
||||
this->value_.clear();
|
||||
return;
|
||||
}
|
||||
this->value_.assign(data, data + length);
|
||||
}
|
||||
|
||||
void BLECharacteristic::set_value(std::vector<uint8_t> &&buffer) { this->value_ = std::move(buffer); }
|
||||
|
||||
void BLECharacteristic::set_value(std::initializer_list<uint8_t> data) {
|
||||
|
||||
@@ -30,6 +30,7 @@ class BLECharacteristic final {
|
||||
~BLECharacteristic();
|
||||
|
||||
void set_value(ByteBuffer buffer);
|
||||
void set_value(const uint8_t *data, size_t length);
|
||||
void set_value(std::vector<uint8_t> &&buffer);
|
||||
void set_value(std::initializer_list<uint8_t> data);
|
||||
void set_value(const std::string &buffer);
|
||||
|
||||
@@ -49,17 +49,18 @@ void BLEDescriptor::do_create(BLECharacteristic *characteristic) {
|
||||
this->state_ = CREATING;
|
||||
}
|
||||
|
||||
void BLEDescriptor::set_value(std::vector<uint8_t> &&buffer) { this->set_value_impl_(buffer.data(), buffer.size()); }
|
||||
void BLEDescriptor::set_value(std::vector<uint8_t> &&buffer) { this->set_value(buffer.data(), buffer.size()); }
|
||||
|
||||
void BLEDescriptor::set_value(std::initializer_list<uint8_t> data) { this->set_value_impl_(data.begin(), data.size()); }
|
||||
void BLEDescriptor::set_value(std::initializer_list<uint8_t> data) { this->set_value(data.begin(), data.size()); }
|
||||
|
||||
void BLEDescriptor::set_value_impl_(const uint8_t *data, size_t length) {
|
||||
void BLEDescriptor::set_value(const uint8_t *data, size_t length) {
|
||||
if (length > this->value_.attr_max_len) {
|
||||
ESP_LOGE(TAG, "Size %d too large, must be no bigger than %d", length, this->value_.attr_max_len);
|
||||
return;
|
||||
}
|
||||
this->value_.attr_len = length;
|
||||
memcpy(this->value_.attr_value, data, length);
|
||||
if (length != 0) // An empty constant is a nullptr table
|
||||
memcpy(this->value_.attr_value, data, length);
|
||||
}
|
||||
|
||||
void BLEDescriptor::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
|
||||
|
||||
@@ -26,6 +26,7 @@ class BLEDescriptor {
|
||||
void do_create(BLECharacteristic *characteristic);
|
||||
ESPBTUUID get_uuid() const { return this->uuid_; }
|
||||
|
||||
void set_value(const uint8_t *data, size_t length);
|
||||
void set_value(std::vector<uint8_t> &&buffer);
|
||||
void set_value(std::initializer_list<uint8_t> data);
|
||||
void set_value(ByteBuffer buffer) { this->set_value(buffer.get_data()); }
|
||||
@@ -42,8 +43,6 @@ class BLEDescriptor {
|
||||
}
|
||||
|
||||
protected:
|
||||
void set_value_impl_(const uint8_t *data, size_t length);
|
||||
|
||||
BLECharacteristic *characteristic_{nullptr};
|
||||
ESPBTUUID uuid_;
|
||||
uint16_t handle_{0xFFFF};
|
||||
|
||||
@@ -16,6 +16,16 @@ namespace esphome::esp32_ble_server::esp32_ble_server_automations {
|
||||
|
||||
using namespace esp32_ble;
|
||||
|
||||
/// Sets a characteristic or descriptor value from a constant flash table or a lambda's vector.
|
||||
// Not TemplatableBytes::visit, which would copy the lambda's vector instead of moving it into the value.
|
||||
template<typename T, typename V, typename... Xs> void apply_value(T *target, const V &value, Xs &&...x) {
|
||||
if (value.is_static()) {
|
||||
target->set_value(value.data(), value.size());
|
||||
} else {
|
||||
target->set_value(value.value(x...));
|
||||
}
|
||||
}
|
||||
|
||||
class BLETriggers {
|
||||
public:
|
||||
#ifdef USE_ESP32_BLE_SERVER_CHARACTERISTIC_ON_WRITE
|
||||
@@ -67,25 +77,23 @@ class BLECharacteristicSetValueActionManager {
|
||||
template<typename... Ts> class BLECharacteristicSetValueAction final : public Action<Ts...> {
|
||||
public:
|
||||
BLECharacteristicSetValueAction(BLECharacteristic *characteristic) : parent_(characteristic) {}
|
||||
TEMPLATABLE_VALUE(std::vector<uint8_t>, buffer)
|
||||
void set_buffer(std::initializer_list<uint8_t> buffer) { this->buffer_ = std::vector<uint8_t>(buffer); }
|
||||
void set_buffer(ByteBuffer buffer) { this->set_buffer(buffer.get_data()); }
|
||||
TEMPLATABLE_BYTES(buffer)
|
||||
void play(const Ts &...x) override {
|
||||
// If the listener is already set, do nothing
|
||||
if (BLECharacteristicSetValueActionManager::get_instance()->has_listener(this->parent_))
|
||||
return;
|
||||
// Set initial value
|
||||
this->parent_->set_value(this->buffer_.value(x...));
|
||||
apply_value(this->parent_, this->buffer_, x...);
|
||||
// Set the listener for read events
|
||||
// ``mutable`` keeps by-copy captures non-const for triggers passing args by reference
|
||||
// (e.g. climate on_control's ClimateCall&). See #17142.
|
||||
this->parent_->on_read([this, x...](uint16_t id) mutable {
|
||||
// Set the value of the characteristic every time it is read
|
||||
this->parent_->set_value(this->buffer_.value(x...));
|
||||
apply_value(this->parent_, this->buffer_, x...);
|
||||
});
|
||||
// Set the listener in the global manager so only one BLECharacteristicSetValueAction is set for each characteristic
|
||||
BLECharacteristicSetValueActionManager::get_instance()->set_listener(
|
||||
this->parent_, [this, x...]() mutable { this->parent_->set_value(this->buffer_.value(x...)); });
|
||||
this->parent_, [this, x...]() mutable { apply_value(this->parent_, this->buffer_, x...); });
|
||||
}
|
||||
|
||||
protected:
|
||||
@@ -115,10 +123,8 @@ template<typename... Ts> class BLECharacteristicNotifyAction final : public Acti
|
||||
template<typename... Ts> class BLEDescriptorSetValueAction final : public Action<Ts...> {
|
||||
public:
|
||||
BLEDescriptorSetValueAction(BLEDescriptor *descriptor) : parent_(descriptor) {}
|
||||
TEMPLATABLE_VALUE(std::vector<uint8_t>, buffer)
|
||||
void set_buffer(std::initializer_list<uint8_t> buffer) { this->buffer_ = std::vector<uint8_t>(buffer); }
|
||||
void set_buffer(ByteBuffer buffer) { this->set_buffer(buffer.get_data()); }
|
||||
void play(const Ts &...x) override { this->parent_->set_value(this->buffer_.value(x...)); }
|
||||
TEMPLATABLE_BYTES(buffer)
|
||||
void play(const Ts &...x) override { apply_value(this->parent_, this->buffer_, x...); }
|
||||
|
||||
protected:
|
||||
BLEDescriptor *parent_;
|
||||
|
||||
@@ -129,7 +129,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
# Also enable esp_driver_twai for future migration to new API
|
||||
include_builtin_idf_component("esp_driver_twai")
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await canbus.register_canbus(var, config)
|
||||
await canbus.register_canbus(var, config, reports_status=True)
|
||||
|
||||
cg.add(var.set_rx(config[CONF_RX_PIN]))
|
||||
cg.add(var.set_tx(config[CONF_TX_PIN]))
|
||||
|
||||
@@ -84,6 +84,8 @@ bool ESP32Can::setup_internal() {
|
||||
twai_general_config_t g_config =
|
||||
TWAI_GENERAL_CONFIG_DEFAULT((gpio_num_t) this->tx_, (gpio_num_t) this->rx_, twai_mode);
|
||||
g_config.controller_id = next_twai_ctrl_num++;
|
||||
g_config.alerts_enabled = TWAI_ALERT_ERR_PASS | TWAI_ALERT_ERR_ACTIVE | TWAI_ALERT_BUS_OFF |
|
||||
TWAI_ALERT_BUS_RECOVERED | TWAI_ALERT_RX_QUEUE_FULL;
|
||||
if (this->tx_queue_len_.has_value()) {
|
||||
g_config.tx_queue_len = this->tx_queue_len_.value();
|
||||
}
|
||||
@@ -116,6 +118,86 @@ bool ESP32Can::setup_internal() {
|
||||
return true;
|
||||
}
|
||||
|
||||
canbus::CanEventFlags ESP32Can::get_events() {
|
||||
if (this->twai_handle_ == nullptr) {
|
||||
return {}; // not set up yet, or setup failed
|
||||
}
|
||||
|
||||
uint32_t alerts;
|
||||
esp_err_t err = twai_read_alerts_v2(this->twai_handle_, &alerts, 0);
|
||||
if (err != ESP_OK) {
|
||||
if (err != ESP_ERR_TIMEOUT) {
|
||||
ESP_LOGD(TAG, "failed to get CAN events");
|
||||
}
|
||||
alerts = 0;
|
||||
}
|
||||
|
||||
uint8_t events = 0;
|
||||
if (alerts & TWAI_ALERT_ERR_PASS) {
|
||||
events |= canbus::CAN_EVENT_PASSIVE;
|
||||
}
|
||||
if (alerts & TWAI_ALERT_ERR_ACTIVE) {
|
||||
events |= canbus::CAN_EVENT_ACTIVE;
|
||||
}
|
||||
if (alerts & TWAI_ALERT_BUS_OFF) {
|
||||
events |= canbus::CAN_EVENT_BUS_OFF;
|
||||
// Start recovery at once, as the MCP2515 does in hardware
|
||||
this->recovery_pending_ = true;
|
||||
}
|
||||
if (alerts & TWAI_ALERT_BUS_RECOVERED) {
|
||||
// Recovery leaves the controller stopped
|
||||
this->restart_pending_ = true;
|
||||
}
|
||||
if (this->recovery_pending_ || this->restart_pending_) {
|
||||
this->handle_bus_off_recovery_();
|
||||
}
|
||||
if (alerts & TWAI_ALERT_RX_QUEUE_FULL) {
|
||||
events |= canbus::CAN_EVENT_RX_QUEUE_FULL;
|
||||
}
|
||||
return static_cast<canbus::CanEventFlags>(events);
|
||||
}
|
||||
|
||||
void ESP32Can::handle_bus_off_recovery_() {
|
||||
// These only fail with an invalid handle or outside the expected state; retry on the next pass
|
||||
if (this->recovery_pending_) {
|
||||
if (twai_initiate_recovery_v2(this->twai_handle_) != ESP_OK) {
|
||||
this->status_set_error(LOG_STR("Recovery after bus off failed"));
|
||||
return;
|
||||
}
|
||||
this->recovery_pending_ = false;
|
||||
}
|
||||
if (this->restart_pending_) {
|
||||
if (twai_start_v2(this->twai_handle_) != ESP_OK) {
|
||||
this->status_set_error(LOG_STR("Restart after bus off failed"));
|
||||
return;
|
||||
}
|
||||
this->restart_pending_ = false;
|
||||
}
|
||||
this->status_clear_error();
|
||||
}
|
||||
|
||||
canbus::CanStatus ESP32Can::get_status() {
|
||||
canbus::CanStatus status = {};
|
||||
|
||||
twai_status_info_t twai_status;
|
||||
|
||||
if (this->twai_handle_ != nullptr && twai_get_status_info_v2(this->twai_handle_, &twai_status) == ESP_OK) {
|
||||
status.bus_off = (twai_status.state == TWAI_STATE_BUS_OFF) || (twai_status.state == TWAI_STATE_RECOVERING);
|
||||
status.rx_error_counter = twai_status.rx_error_counter;
|
||||
status.tx_error_counter = twai_status.tx_error_counter;
|
||||
|
||||
status.tx_failed_count = twai_status.tx_failed_count;
|
||||
status.rx_missed_count = twai_status.rx_missed_count;
|
||||
status.rx_overrun_count = twai_status.rx_overrun_count;
|
||||
status.arb_lost_count = twai_status.arb_lost_count;
|
||||
status.bus_error_count = twai_status.bus_error_count;
|
||||
} else {
|
||||
ESP_LOGD(TAG, "failed to get CAN status");
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
canbus::Error ESP32Can::send_message(struct canbus::CanFrame *frame) {
|
||||
// In listen-only mode, we cannot transmit
|
||||
if (this->mode_ == CAN_MODE_LISTEN_ONLY) {
|
||||
|
||||
@@ -24,16 +24,21 @@ class ESP32Can final : public canbus::Canbus {
|
||||
void set_tx_enqueue_timeout_ms(uint32_t tx_enqueue_timeout_ms) {
|
||||
this->tx_enqueue_timeout_ticks_ = pdMS_TO_TICKS(tx_enqueue_timeout_ms);
|
||||
}
|
||||
canbus::CanStatus get_status() override;
|
||||
ESP32Can(){};
|
||||
|
||||
protected:
|
||||
bool setup_internal() override;
|
||||
canbus::CanEventFlags get_events() override;
|
||||
canbus::Error send_message(struct canbus::CanFrame *frame) override;
|
||||
canbus::Error read_message(struct canbus::CanFrame *frame) override;
|
||||
void handle_bus_off_recovery_();
|
||||
|
||||
int rx_{-1};
|
||||
int tx_{-1};
|
||||
CanMode mode_{CAN_MODE_NORMAL};
|
||||
bool recovery_pending_{false};
|
||||
bool restart_pending_{false};
|
||||
TickType_t tx_enqueue_timeout_ticks_{};
|
||||
optional<uint32_t> tx_queue_len_{};
|
||||
optional<uint32_t> rx_queue_len_{};
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DOMAIN = "esp32_power_management"
|
||||
@@ -0,0 +1,75 @@
|
||||
#include "esp32_power_management.h"
|
||||
#ifdef USE_ESP32
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
#include "esp_private/esp_clk.h"
|
||||
#include "soc/rtc.h"
|
||||
|
||||
namespace esphome::esp32_power_management {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "esp32_power_management");
|
||||
|
||||
void ESP32PowerManagement::setup() {
|
||||
if (this->max_freq_mhz_ == 0)
|
||||
this->max_freq_mhz_ = CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ;
|
||||
if (this->min_freq_mhz_ == 0)
|
||||
this->min_freq_mhz_ = esp_clk_xtal_freq() / MHZ;
|
||||
// A low boot frequency (ESP32-H2 at 16 MHz) can sit below the crystal frequency.
|
||||
if (this->min_freq_mhz_ > this->max_freq_mhz_)
|
||||
this->min_freq_mhz_ = this->max_freq_mhz_;
|
||||
|
||||
esp_pm_config_t pm_config = {
|
||||
.max_freq_mhz = this->max_freq_mhz_,
|
||||
.min_freq_mhz = this->min_freq_mhz_,
|
||||
#if CONFIG_FREERTOS_USE_TICKLESS_IDLE
|
||||
.light_sleep_enable = true,
|
||||
#endif
|
||||
};
|
||||
esp_err_t rc = esp_pm_configure(&pm_config);
|
||||
if (rc != ESP_OK) {
|
||||
// The usual cause is a minimum frequency that does not divide this board's crystal
|
||||
ESP_LOGE(TAG, "esp_pm_configure failed: %s (crystal %u MHz)", esp_err_to_name(rc),
|
||||
static_cast<unsigned>(esp_clk_xtal_freq() / MHZ));
|
||||
this->mark_failed();
|
||||
}
|
||||
}
|
||||
|
||||
void ESP32PowerManagement::dump_config() {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"Power Management:\n"
|
||||
" Max Frequency: %uMHZ\n"
|
||||
" Min Frequency: %uMHZ",
|
||||
this->max_freq_mhz_, this->min_freq_mhz_);
|
||||
#if SOC_CLK_XTAL32K_SUPPORTED
|
||||
ESP_LOGCONFIG(TAG, " 32k XTAL: %s",
|
||||
rtc_clk_slow_src_get() == SOC_RTC_SLOW_CLK_SRC_XTAL32K ? LOG_STR_LITERAL("in use")
|
||||
: LOG_STR_LITERAL("not in use"));
|
||||
#endif
|
||||
#if CONFIG_FREERTOS_USE_TICKLESS_IDLE
|
||||
ESP_LOGCONFIG(TAG, " Light Sleep Enabled");
|
||||
#if CONFIG_ESP_SLEEP_POWER_DOWN_FLASH
|
||||
ESP_LOGCONFIG(TAG, " PM Flash Power Down in Light Sleep Enabled");
|
||||
#endif
|
||||
#if CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP
|
||||
ESP_LOGCONFIG(TAG, " PM Peripheral Power Down in Light Sleep Enabled");
|
||||
#endif
|
||||
#if CONFIG_IEEE802154_SLEEP_ENABLE
|
||||
ESP_LOGCONFIG(TAG, " ieee802154 Sleep Enabled");
|
||||
#endif
|
||||
#if CONFIG_PM_PROFILING
|
||||
ESP_LOGCONFIG(TAG, " PM Profiling Enabled");
|
||||
#endif
|
||||
#if CONFIG_PM_TRACE
|
||||
ESP_LOGCONFIG(TAG, " PM Trace Enabled");
|
||||
#endif
|
||||
#if defined(CONFIG_LWIP_IPV6) && !defined(CONFIG_LWIP_ND6)
|
||||
ESP_LOGCONFIG(TAG, " IPv6 Neighbor Discovery Disabled (CONFIG_LWIP_ND6)");
|
||||
#endif
|
||||
#if CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION
|
||||
ESP_LOGCONFIG(TAG, " USB Serial/JTAG Light Sleep Prevention Enabled");
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace esphome::esp32_power_management
|
||||
#endif
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef USE_ESP32
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/components/power_management/power_management.h"
|
||||
// Lets a YAML lambda call esp_pm_dump_locks().
|
||||
#include "esp_pm.h"
|
||||
|
||||
namespace esphome::esp32_power_management {
|
||||
|
||||
class ESP32PowerManagement : public power_management::PowerManagementComponent {
|
||||
public:
|
||||
float get_setup_priority() const override { return setup_priority::POWER; }
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
void set_max_freq_mhz(uint16_t max_freq_mhz) { this->max_freq_mhz_ = max_freq_mhz; }
|
||||
void set_min_freq_mhz(uint16_t min_freq_mhz) { this->min_freq_mhz_ = min_freq_mhz; }
|
||||
|
||||
protected:
|
||||
// Zero means the build default; setup() replaces it with the value applied.
|
||||
uint16_t max_freq_mhz_{0};
|
||||
uint16_t min_freq_mhz_{0};
|
||||
};
|
||||
|
||||
} // namespace esphome::esp32_power_management
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,254 @@
|
||||
import logging
|
||||
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import esp32, power_management
|
||||
from esphome.components.esp32 import (
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C2,
|
||||
VARIANT_ESP32C3,
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32H4,
|
||||
VARIANT_ESP32H21,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S2,
|
||||
VARIANT_ESP32S3,
|
||||
VARIANT_ESP32S31,
|
||||
add_idf_sdkconfig_option,
|
||||
get_esp32_variant,
|
||||
)
|
||||
from esphome.components.openthread.const import CONF_POLL_PERIOD
|
||||
from esphome.components.psram import DOMAIN as PSRAM_DOMAIN
|
||||
from esphome.components.zigbee import DOMAIN as ZIGBEE_DOMAIN
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_OPENTHREAD, CONF_PLATFORM
|
||||
from esphome.core import CORE
|
||||
import esphome.final_validate as fv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CODEOWNERS = ["@rwrozelle"]
|
||||
DEPENDENCIES = ["esp32"]
|
||||
|
||||
CONF_ENABLE_LIGHT_SLEEP = "enable_light_sleep"
|
||||
CONF_IDLE_TIME_BEFORE_SLEEP = "idle_time_before_sleep"
|
||||
CONF_MAX_FREQUENCY = "max_frequency"
|
||||
CONF_MIN_FREQUENCY = "min_frequency"
|
||||
CONF_POWER_DOWN_FLASH = "power_down_flash"
|
||||
CONF_POWER_DOWN_PERIPHERALS = "power_down_peripherals"
|
||||
CONF_PROFILING = "profiling"
|
||||
CONF_TRACE = "trace"
|
||||
|
||||
# Variants with a TOP power domain, which can power down peripherals in light sleep.
|
||||
_TOP_PD_VARIANTS = [
|
||||
VARIANT_ESP32C5,
|
||||
VARIANT_ESP32C6,
|
||||
VARIANT_ESP32C61,
|
||||
VARIANT_ESP32H2,
|
||||
VARIANT_ESP32H21,
|
||||
VARIANT_ESP32H4,
|
||||
VARIANT_ESP32P4,
|
||||
VARIANT_ESP32S31,
|
||||
]
|
||||
|
||||
# Crystal frequencies each variant can be built for (ESP-IDF's SOC_XTAL_FREQ_* values).
|
||||
# Below the PLL frequencies the CPU runs from the crystal through an integer divider.
|
||||
_XTAL_MHZ = {
|
||||
VARIANT_ESP32: (24, 26, 40),
|
||||
VARIANT_ESP32C2: (26, 32, 40),
|
||||
VARIANT_ESP32C3: (32, 40),
|
||||
VARIANT_ESP32C5: (40, 48),
|
||||
VARIANT_ESP32C6: (40,),
|
||||
VARIANT_ESP32C61: (40,),
|
||||
VARIANT_ESP32H2: (32,),
|
||||
VARIANT_ESP32H21: (32,),
|
||||
VARIANT_ESP32H4: (32,),
|
||||
VARIANT_ESP32P4: (40,),
|
||||
VARIANT_ESP32S2: (40,),
|
||||
VARIANT_ESP32S3: (32, 40),
|
||||
VARIANT_ESP32S31: (40,),
|
||||
}
|
||||
# esp_pm_configure() keeps the 1 MHz reference clock reachable: its divider must be
|
||||
# at least 10 on the ESP32 and 2 on every other variant.
|
||||
_MIN_FREQUENCY_FLOOR_MHZ = {VARIANT_ESP32: 10}
|
||||
|
||||
esp32_power_management_ns = cg.esphome_ns.namespace("esp32_power_management")
|
||||
PowerManagement = esp32_power_management_ns.class_(
|
||||
"ESP32PowerManagement", power_management.PowerManagementComponent
|
||||
)
|
||||
|
||||
|
||||
def _mhz(value: object) -> int:
|
||||
"""Validate a frequency and keep it as whole megahertz."""
|
||||
return int(cv.frequency(value)) // 1_000_000
|
||||
|
||||
|
||||
def valid_min_frequencies(variant: str) -> list[int]:
|
||||
"""The minimum CPU frequencies esp_pm_configure() accepts on a variant, in MHz.
|
||||
|
||||
A value must divide one of the variant's crystal frequencies, stay above the
|
||||
reference clock floor, or be one of the PLL frequencies.
|
||||
"""
|
||||
floor = _MIN_FREQUENCY_FLOOR_MHZ.get(variant, 2)
|
||||
mhz = {
|
||||
xtal // divider
|
||||
for xtal in _XTAL_MHZ[variant]
|
||||
for divider in range(1, xtal // floor + 1)
|
||||
if xtal % divider == 0
|
||||
}
|
||||
mhz.update(int(freq[:-3]) for freq in esp32.CPU_FREQUENCIES[variant])
|
||||
return sorted(mhz)
|
||||
|
||||
|
||||
def _validate(config: ConfigType) -> ConfigType:
|
||||
variant = get_esp32_variant()
|
||||
if (max_mhz := config.get(CONF_MAX_FREQUENCY)) is not None:
|
||||
valid = esp32.CPU_FREQUENCIES[variant]
|
||||
if f"{max_mhz}MHZ" not in valid:
|
||||
raise cv.Invalid(
|
||||
f"{max_mhz}MHZ is not a valid CPU frequency for {variant}. "
|
||||
f"Valid options are: {', '.join(valid)}",
|
||||
path=[CONF_MAX_FREQUENCY],
|
||||
)
|
||||
if (min_mhz := config.get(CONF_MIN_FREQUENCY)) is not None and (
|
||||
min_mhz not in (valid_min := valid_min_frequencies(variant))
|
||||
):
|
||||
raise cv.Invalid(
|
||||
f"{min_mhz}MHZ is not a valid minimum frequency for {variant}; it must "
|
||||
f"divide the crystal frequency. Valid options are: "
|
||||
f"{', '.join(f'{mhz}MHZ' for mhz in valid_min)}",
|
||||
path=[CONF_MIN_FREQUENCY],
|
||||
)
|
||||
if not config[CONF_ENABLE_LIGHT_SLEEP]:
|
||||
for key in (CONF_POWER_DOWN_PERIPHERALS, CONF_POWER_DOWN_FLASH):
|
||||
if config.get(key):
|
||||
raise cv.Invalid(
|
||||
f"{key} requires {CONF_ENABLE_LIGHT_SLEEP}: true", path=[key]
|
||||
)
|
||||
config[CONF_POWER_DOWN_PERIPHERALS] = False
|
||||
elif CONF_POWER_DOWN_PERIPHERALS not in config:
|
||||
config[CONF_POWER_DOWN_PERIPHERALS] = variant in _TOP_PD_VARIANTS
|
||||
elif config[CONF_POWER_DOWN_PERIPHERALS] and variant not in _TOP_PD_VARIANTS:
|
||||
raise cv.Invalid(
|
||||
f"{CONF_POWER_DOWN_PERIPHERALS} is only available on "
|
||||
f"{', '.join(_TOP_PD_VARIANTS)}",
|
||||
path=[CONF_POWER_DOWN_PERIPHERALS],
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(PowerManagement),
|
||||
cv.Optional(CONF_MAX_FREQUENCY): _mhz,
|
||||
cv.Optional(CONF_MIN_FREQUENCY): _mhz,
|
||||
cv.Optional(CONF_ENABLE_LIGHT_SLEEP, default=False): cv.boolean,
|
||||
cv.Optional(CONF_IDLE_TIME_BEFORE_SLEEP, default=3): cv.int_range(
|
||||
min=2, max=4294967295
|
||||
),
|
||||
cv.Optional(CONF_POWER_DOWN_PERIPHERALS): cv.boolean,
|
||||
cv.Optional(CONF_POWER_DOWN_FLASH, default=False): cv.boolean,
|
||||
cv.Optional(CONF_PROFILING, default=False): cv.boolean,
|
||||
# Repurposes GPIOs as trace outputs, so keep it out of the visual editor.
|
||||
cv.Optional(
|
||||
CONF_TRACE, default=False, visibility=cv.Visibility.YAML_ONLY
|
||||
): cv.boolean,
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA),
|
||||
_validate,
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await power_management.register_power_management(var, config)
|
||||
add_idf_sdkconfig_option("CONFIG_PM_ENABLE", True)
|
||||
|
||||
if (max_mhz := config.get(CONF_MAX_FREQUENCY)) is not None:
|
||||
cg.add(var.set_max_freq_mhz(max_mhz))
|
||||
if (min_mhz := config.get(CONF_MIN_FREQUENCY)) is not None:
|
||||
cg.add(var.set_min_freq_mhz(min_mhz))
|
||||
if config[CONF_PROFILING]:
|
||||
add_idf_sdkconfig_option("CONFIG_PM_PROFILING", True)
|
||||
if config[CONF_TRACE]:
|
||||
add_idf_sdkconfig_option("CONFIG_PM_TRACE", True)
|
||||
if not config[CONF_ENABLE_LIGHT_SLEEP]:
|
||||
return
|
||||
|
||||
# Automatic light sleep whenever no task is runnable.
|
||||
add_idf_sdkconfig_option("CONFIG_FREERTOS_USE_TICKLESS_IDLE", True)
|
||||
add_idf_sdkconfig_option("CONFIG_ESP_PHY_MAC_BB_PD", True)
|
||||
# Kconfig's own "depends on" no-ops this where it doesn't apply.
|
||||
add_idf_sdkconfig_option("CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION", True)
|
||||
add_idf_sdkconfig_option(
|
||||
"CONFIG_FREERTOS_IDLE_TIME_BEFORE_SLEEP", config[CONF_IDLE_TIME_BEFORE_SLEEP]
|
||||
)
|
||||
if config[CONF_POWER_DOWN_PERIPHERALS]:
|
||||
add_idf_sdkconfig_option("CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP", True)
|
||||
if config[CONF_POWER_DOWN_FLASH]:
|
||||
add_idf_sdkconfig_option("CONFIG_ESP_SLEEP_POWER_DOWN_FLASH", True)
|
||||
|
||||
ot_conf = CORE.config.get(CONF_OPENTHREAD)
|
||||
# A polling (sleepy) Thread end device cannot answer neighbour solicitations.
|
||||
if (
|
||||
ot_conf is not None
|
||||
and (poll_period := ot_conf.get(CONF_POLL_PERIOD)) is not None
|
||||
and poll_period.total_milliseconds > 0
|
||||
):
|
||||
add_idf_sdkconfig_option("CONFIG_LWIP_ND6", False)
|
||||
if ot_conf is not None or ZIGBEE_DOMAIN in CORE.config:
|
||||
add_idf_sdkconfig_option("CONFIG_IEEE802154_SLEEP_ENABLE", True)
|
||||
|
||||
|
||||
def _final_validate(config: ConfigType) -> ConfigType:
|
||||
full_config = fv.full_config.get()
|
||||
entries = full_config.get(power_management.DOMAIN, [])
|
||||
if sum(entry.get(CONF_PLATFORM) == DOMAIN for entry in entries) > 1:
|
||||
raise cv.Invalid(f"Only one {DOMAIN} instance is allowed")
|
||||
boot_freq = full_config[esp32.DOMAIN][esp32.CONF_CPU_FREQUENCY]
|
||||
boot_mhz = int(boot_freq[:-3])
|
||||
max_mhz = config.get(CONF_MAX_FREQUENCY)
|
||||
# Without max_frequency the boot frequency is the ceiling esp_pm_configure() gets.
|
||||
if (min_mhz := config.get(CONF_MIN_FREQUENCY)) is not None and min_mhz > (
|
||||
max_mhz if max_mhz is not None else boot_mhz
|
||||
):
|
||||
raise cv.Invalid(
|
||||
f"{CONF_MIN_FREQUENCY} must not be greater than the maximum frequency",
|
||||
path=[CONF_MIN_FREQUENCY],
|
||||
)
|
||||
if max_mhz is not None:
|
||||
if boot_mhz > max_mhz:
|
||||
_LOGGER.info(
|
||||
"esp32.%s (%s) is higher than %s (%dMHZ); the CPU will be "
|
||||
"downclocked to %dMHZ as soon as power management is set up",
|
||||
esp32.CONF_CPU_FREQUENCY,
|
||||
boot_freq,
|
||||
CONF_MAX_FREQUENCY,
|
||||
max_mhz,
|
||||
max_mhz,
|
||||
)
|
||||
elif boot_mhz < max_mhz:
|
||||
_LOGGER.warning(
|
||||
"esp32.%s (%s) is lower than %s (%dMHZ); the CPU may run as "
|
||||
"high as %dMHZ under load once power management is set up",
|
||||
esp32.CONF_CPU_FREQUENCY,
|
||||
boot_freq,
|
||||
CONF_MAX_FREQUENCY,
|
||||
max_mhz,
|
||||
max_mhz,
|
||||
)
|
||||
if config[CONF_POWER_DOWN_FLASH] and PSRAM_DOMAIN in full_config:
|
||||
raise cv.Invalid(
|
||||
f"{CONF_POWER_DOWN_FLASH} is not allowed when the device has PSRAM",
|
||||
path=[CONF_POWER_DOWN_FLASH],
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = _final_validate
|
||||
@@ -214,6 +214,15 @@ CLK_MODES = {
|
||||
|
||||
spi_host_device_t = cg.global_ns.enum("spi_host_device_t")
|
||||
|
||||
# Must match the member initializers in ethernet_component.h; setters are skipped
|
||||
# when the config already equals them.
|
||||
DEFAULT_SPI_INTERFACE = "spi2"
|
||||
DEFAULT_PHY_ADDR = 0
|
||||
DEFAULT_MDC_PIN = 23
|
||||
DEFAULT_MDIO_PIN = 18
|
||||
DEFAULT_CLK_MODE = "CLK_EXT_IN"
|
||||
DEFAULT_CLK_PIN = 0
|
||||
|
||||
SPI_INTERFACE_MAP = {
|
||||
"spi2": spi_host_device_t.SPI2_HOST,
|
||||
"spi3": spi_host_device_t.SPI3_HOST,
|
||||
@@ -437,7 +446,9 @@ RMII_SCHEMA = cv.All(
|
||||
" GPIO17_OUT -> mode: CLK_OUT, pin: GPIO17"
|
||||
),
|
||||
cv.Required(CONF_CLK): CLK_SCHEMA,
|
||||
cv.Optional(CONF_PHY_ADDR, default=0): cv.int_range(min=0, max=31),
|
||||
cv.Optional(CONF_PHY_ADDR, default=DEFAULT_PHY_ADDR): cv.int_range(
|
||||
min=0, max=31
|
||||
),
|
||||
cv.Optional(CONF_POWER_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Optional(CONF_PHY_REGISTERS): cv.ensure_list(PHY_REGISTER_SCHEMA),
|
||||
}
|
||||
@@ -454,7 +465,9 @@ GENERIC_SCHEMA = cv.All(
|
||||
{
|
||||
cv.Required(CONF_MDC_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Required(CONF_MDIO_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Optional(CONF_PHY_ADDR, default=0): cv.int_range(min=0, max=31),
|
||||
cv.Optional(CONF_PHY_ADDR, default=DEFAULT_PHY_ADDR): cv.int_range(
|
||||
min=0, max=31
|
||||
),
|
||||
cv.Optional(CONF_POWER_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Optional(CONF_PHY_REGISTERS): cv.ensure_list(PHY_REGISTER_SCHEMA),
|
||||
}
|
||||
@@ -683,6 +696,15 @@ async def to_code(config: ConfigType) -> None:
|
||||
CORE.add_job(final_step)
|
||||
|
||||
|
||||
def _add_mdio_setters(var: cg.MockObj, config: ConfigType) -> None:
|
||||
if (phy_addr := config[CONF_PHY_ADDR]) != DEFAULT_PHY_ADDR:
|
||||
cg.add(var.set_phy_addr(phy_addr))
|
||||
if (mdc_pin := config[CONF_MDC_PIN]) != DEFAULT_MDC_PIN:
|
||||
cg.add(var.set_mdc_pin(mdc_pin))
|
||||
if (mdio_pin := config[CONF_MDIO_PIN]) != DEFAULT_MDIO_PIN:
|
||||
cg.add(var.set_mdio_pin(mdio_pin))
|
||||
|
||||
|
||||
async def _to_code_esp32(var: cg.MockObj, config: ConfigType) -> None:
|
||||
from esphome.components.esp32 import (
|
||||
add_idf_component,
|
||||
@@ -701,7 +723,8 @@ async def _to_code_esp32(var: cg.MockObj, config: ConfigType) -> None:
|
||||
cg.add(var.set_clk_pin(config[CONF_CLK_PIN]))
|
||||
cg.add(var.set_miso_pin(config[CONF_MISO_PIN]))
|
||||
cg.add(var.set_mosi_pin(config[CONF_MOSI_PIN]))
|
||||
cg.add(var.set_interface(SPI_INTERFACE_MAP[config[CONF_INTERFACE]]))
|
||||
if (interface := config[CONF_INTERFACE]) != DEFAULT_SPI_INTERFACE:
|
||||
cg.add(var.set_interface(SPI_INTERFACE_MAP[interface]))
|
||||
cg.add(var.set_cs_pin(config[CONF_CS_PIN]))
|
||||
if CONF_INTERRUPT_PIN in config:
|
||||
cg.add(var.set_interrupt_pin(config[CONF_INTERRUPT_PIN]))
|
||||
@@ -730,18 +753,16 @@ async def _to_code_esp32(var: cg.MockObj, config: ConfigType) -> None:
|
||||
add_idf_sdkconfig_option("CONFIG_ETH_USE_OPENETH", True)
|
||||
elif config[CONF_TYPE] in ("GENERIC", "YT8531"):
|
||||
# RGMII data pins come from the IDF default config; set MDC/MDIO + PHY addr.
|
||||
cg.add(var.set_phy_addr(config[CONF_PHY_ADDR]))
|
||||
cg.add(var.set_mdc_pin(config[CONF_MDC_PIN]))
|
||||
cg.add(var.set_mdio_pin(config[CONF_MDIO_PIN]))
|
||||
_add_mdio_setters(var, config)
|
||||
if CONF_POWER_PIN in config:
|
||||
cg.add(var.set_power_pin(config[CONF_POWER_PIN]))
|
||||
_add_phy_registers(var, config)
|
||||
else:
|
||||
cg.add(var.set_phy_addr(config[CONF_PHY_ADDR]))
|
||||
cg.add(var.set_mdc_pin(config[CONF_MDC_PIN]))
|
||||
cg.add(var.set_mdio_pin(config[CONF_MDIO_PIN]))
|
||||
cg.add(var.set_clk_mode(config[CONF_CLK][CONF_MODE]))
|
||||
cg.add(var.set_clk_pin(config[CONF_CLK][CONF_PIN]))
|
||||
_add_mdio_setters(var, config)
|
||||
if (clk_mode := config[CONF_CLK][CONF_MODE]) != DEFAULT_CLK_MODE:
|
||||
cg.add(var.set_clk_mode(clk_mode))
|
||||
if (clk_pin := config[CONF_CLK][CONF_PIN]) != DEFAULT_CLK_PIN:
|
||||
cg.add(var.set_clk_pin(clk_pin))
|
||||
if CONF_POWER_PIN in config:
|
||||
cg.add(var.set_power_pin(config[CONF_POWER_PIN]))
|
||||
_add_phy_registers(var, config)
|
||||
|
||||
@@ -271,7 +271,7 @@ class EthernetComponent final : public Component {
|
||||
int reset_pin_{-1};
|
||||
int phy_addr_spi_{-1};
|
||||
int clock_speed_;
|
||||
spi_host_device_t interface_{SPI2_HOST};
|
||||
spi_host_device_t interface_{SPI2_HOST}; // Must match DEFAULT_SPI_INTERFACE in __init__.py
|
||||
#ifdef USE_SPI
|
||||
// When set, the SPI bus is owned and initialized by this spi component
|
||||
// and the ethernet chip only adds a device to it.
|
||||
@@ -283,16 +283,16 @@ class EthernetComponent final : public Component {
|
||||
#else
|
||||
// Group all 32-bit members first
|
||||
int power_pin_{-1};
|
||||
emac_rmii_clock_mode_t clk_mode_{EMAC_CLK_EXT_IN};
|
||||
emac_rmii_clock_mode_t clk_mode_{EMAC_CLK_EXT_IN}; // Must match DEFAULT_CLK_MODE in __init__.py
|
||||
#ifdef ESPHOME_ETHERNET_PHY_REGISTER_COUNT
|
||||
StaticVector<PHYRegister, ESPHOME_ETHERNET_PHY_REGISTER_COUNT> phy_registers_{};
|
||||
#endif
|
||||
|
||||
// Group all 8-bit members together
|
||||
uint8_t clk_pin_{0};
|
||||
uint8_t phy_addr_{0};
|
||||
uint8_t mdc_pin_{23};
|
||||
uint8_t mdio_pin_{18};
|
||||
uint8_t clk_pin_{0}; // Must match DEFAULT_CLK_PIN in __init__.py
|
||||
uint8_t phy_addr_{0}; // Must match DEFAULT_PHY_ADDR in __init__.py
|
||||
uint8_t mdc_pin_{23}; // Must match DEFAULT_MDC_PIN in __init__.py
|
||||
uint8_t mdio_pin_{18}; // Must match DEFAULT_MDIO_PIN in __init__.py
|
||||
#endif // USE_ETHERNET_SPI
|
||||
|
||||
// ESP32 pointers
|
||||
|
||||
@@ -98,7 +98,9 @@ async def setup_event_core_(
|
||||
) -> None:
|
||||
await automation.build_callback_automations(var, config, _CALLBACK_AUTOMATIONS)
|
||||
|
||||
cg.add(var.set_event_types(event_types))
|
||||
if event_types:
|
||||
table = cg.shared_progmem_array("event_types", cg.const_char_ptr, event_types)
|
||||
cg.add(var.set_event_types_static(table, len(event_types)))
|
||||
|
||||
setup_device_class(config)
|
||||
|
||||
|
||||
@@ -28,11 +28,8 @@ void Event::trigger(const char *event_type) {
|
||||
#endif
|
||||
}
|
||||
|
||||
void Event::set_event_types(const FixedVector<const char *> &event_types) {
|
||||
this->types_.init(event_types.size());
|
||||
for (const char *type : event_types) {
|
||||
this->types_.push_back(type);
|
||||
}
|
||||
void Event::set_event_types_copy_(const char *const *event_types, size_t count) {
|
||||
this->types_.assign_copy(event_types, count);
|
||||
this->last_event_type_ = nullptr; // Reset when types change
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
|
||||
namespace esphome::event {
|
||||
|
||||
/// A codegen table in flash, or a heap copy of a runtime list (see ConstVector).
|
||||
using EventTypes = ConstVector<const char *, true>;
|
||||
|
||||
#define LOG_EVENT(prefix, type, obj) \
|
||||
if ((obj) != nullptr) { \
|
||||
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, LOG_STR_LITERAL(type), (obj)->get_name().c_str()); \
|
||||
@@ -24,20 +27,29 @@ class Event : public EntityBase {
|
||||
void trigger(const char *event_type);
|
||||
void trigger(const std::string &event_type) { this->trigger(event_type.c_str()); }
|
||||
|
||||
/// Set the event types supported by this event; called by generated code with string literals.
|
||||
/// Codegen only: points at a table that outlives the event (see ConstVector::assign_static).
|
||||
void set_event_types_static(const char *const *event_types, size_t count) {
|
||||
this->types_.assign_static(event_types, count);
|
||||
this->last_event_type_ = nullptr;
|
||||
}
|
||||
/// Runtime lists are copied; the strings must still outlive the event.
|
||||
void set_event_types(std::initializer_list<const char *> event_types) {
|
||||
this->types_ = event_types;
|
||||
this->last_event_type_ = nullptr; // Reset when types change
|
||||
this->set_event_types_copy_(event_types.begin(), event_types.size());
|
||||
}
|
||||
/// Copy the event types of another event, for components that wrap one.
|
||||
void set_event_types(const FixedVector<const char *> &event_types);
|
||||
void set_event_types(const EventTypes &event_types) {
|
||||
this->set_event_types_copy_(event_types.data(), event_types.size());
|
||||
}
|
||||
void set_event_types(const FixedVector<const char *> &event_types) {
|
||||
this->set_event_types_copy_(event_types.begin(), event_types.size());
|
||||
}
|
||||
|
||||
// Deleted overloads to catch incorrect std::string usage at compile time with clear error messages
|
||||
void set_event_types(std::initializer_list<std::string> event_types) = delete;
|
||||
void set_event_types(const FixedVector<std::string> &event_types) = delete;
|
||||
|
||||
/// Return the event types supported by this event.
|
||||
const FixedVector<const char *> &get_event_types() const { return this->types_; }
|
||||
const EventTypes &get_event_types() const { return this->types_; }
|
||||
|
||||
/// Return the last triggered event type, or empty StringRef if no event triggered yet.
|
||||
StringRef get_last_event_type() const { return StringRef::from_maybe_nullptr(this->last_event_type_); }
|
||||
@@ -68,8 +80,10 @@ class Event : public EntityBase {
|
||||
}
|
||||
|
||||
protected:
|
||||
void set_event_types_copy_(const char *const *event_types, size_t count);
|
||||
|
||||
LazyCallbackManager<void(StringRef event_type)> event_callback_;
|
||||
FixedVector<const char *> types_;
|
||||
EventTypes types_;
|
||||
|
||||
private:
|
||||
/// Last triggered event type - must point to entry in types_ to ensure valid lifetime.
|
||||
|
||||
@@ -64,9 +64,6 @@ RESTORE_MODES = {
|
||||
# Actions
|
||||
CycleSpeedAction = fan_ns.class_("CycleSpeedAction", automation.Action)
|
||||
|
||||
FanStateTrigger = fan_ns.class_(
|
||||
"FanStateTrigger", automation.Trigger.template(Fan.operator("ptr"))
|
||||
)
|
||||
FanTurnOnTrigger = fan_ns.class_("FanTurnOnTrigger", automation.Trigger.template())
|
||||
FanTurnOffTrigger = fan_ns.class_("FanTurnOffTrigger", automation.Trigger.template())
|
||||
FanDirectionSetTrigger = fan_ns.class_(
|
||||
@@ -115,11 +112,7 @@ _FAN_SCHEMA = (
|
||||
cv.Optional(CONF_SPEED_COMMAND_TOPIC): cv.All(
|
||||
cv.requires_component("mqtt"), cv.subscribe_topic
|
||||
),
|
||||
cv.Optional(CONF_ON_STATE): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(FanStateTrigger),
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_ON_STATE): automation.validate_automation(),
|
||||
cv.Optional(CONF_ON_TURN_ON): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(FanTurnOnTrigger),
|
||||
@@ -221,6 +214,17 @@ def validate_preset_modes(value):
|
||||
return value
|
||||
|
||||
|
||||
# The edge and set triggers keep their classes; each tracks the previous value.
|
||||
_TRIGGER_AUTOMATIONS = (
|
||||
(CONF_ON_TURN_ON, []),
|
||||
(CONF_ON_TURN_OFF, []),
|
||||
(CONF_ON_DIRECTION_SET, [(FanDirection, "x")]),
|
||||
(CONF_ON_OSCILLATING_SET, [(cg.bool_, "x")]),
|
||||
(CONF_ON_SPEED_SET, [(cg.int_, "x")]),
|
||||
(CONF_ON_PRESET_SET, [(cg.StringRef, "x")]),
|
||||
)
|
||||
|
||||
|
||||
@setup_entity("fan")
|
||||
async def setup_fan_core_(var, config):
|
||||
cg.add(var.set_restore_mode(config[CONF_RESTORE_MODE]))
|
||||
@@ -266,26 +270,10 @@ async def setup_fan_core_(var, config):
|
||||
await web_server.add_entity_config(var, web_server_config)
|
||||
|
||||
for conf in config.get(CONF_ON_STATE, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [(Fan.operator("ptr"), "x")], conf)
|
||||
for conf in config.get(CONF_ON_TURN_ON, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [], conf)
|
||||
for conf in config.get(CONF_ON_TURN_OFF, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [], conf)
|
||||
for conf in config.get(CONF_ON_DIRECTION_SET, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [(FanDirection, "x")], conf)
|
||||
for conf in config.get(CONF_ON_OSCILLATING_SET, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [(cg.bool_, "x")], conf)
|
||||
for conf in config.get(CONF_ON_SPEED_SET, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [(cg.int_, "x")], conf)
|
||||
for conf in config.get(CONF_ON_PRESET_SET, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [(cg.StringRef, "x")], conf)
|
||||
await automation.build_parent_callback_automation(
|
||||
var, "add_on_state_callback", (Fan.operator("ptr"), "x"), conf
|
||||
)
|
||||
await automation.build_trigger_automations(var, config, _TRIGGER_AUTOMATIONS)
|
||||
|
||||
|
||||
async def register_fan(var, config):
|
||||
|
||||
@@ -50,16 +50,6 @@ template<typename... Ts> class CycleSpeedAction final : public Action<Ts...> {
|
||||
Fan *state_;
|
||||
};
|
||||
|
||||
class FanStateTrigger final : public Trigger<Fan *> {
|
||||
public:
|
||||
FanStateTrigger(Fan *state) : fan_(state) {
|
||||
state->add_on_state_callback([this]() { this->trigger(this->fan_); });
|
||||
}
|
||||
|
||||
protected:
|
||||
Fan *fan_;
|
||||
};
|
||||
|
||||
class FanTurnOnTrigger final : public Trigger<> {
|
||||
public:
|
||||
FanTurnOnTrigger(Fan *state) : fan_(state) {
|
||||
|
||||
@@ -81,8 +81,8 @@ CONFIG_SCHEMA = cv.All(
|
||||
cv.Optional(
|
||||
CONF_IDLE_PERIOD_TO_SLEEP
|
||||
): cv.positive_time_period_milliseconds,
|
||||
cv.Optional(CONF_PASSWORD): cv.uint32_t,
|
||||
cv.Optional(CONF_NEW_PASSWORD): cv.uint32_t,
|
||||
cv.Optional(CONF_PASSWORD): cv.sensitive(cv.uint32_t),
|
||||
cv.Optional(CONF_NEW_PASSWORD): cv.sensitive(cv.uint32_t),
|
||||
cv.Optional(CONF_ON_FINGER_SCAN_START): automation.validate_automation({}),
|
||||
cv.Optional(CONF_ON_FINGER_SCAN_MATCHED): automation.validate_automation(
|
||||
{}
|
||||
|
||||
@@ -42,12 +42,7 @@ void FS3000Component::update() {
|
||||
}
|
||||
|
||||
// checksum passes if the modulo 256 sum of the five bytes is 0
|
||||
uint8_t checksum = 0;
|
||||
for (uint8_t i : data) {
|
||||
checksum += i;
|
||||
}
|
||||
|
||||
if (checksum != 0) {
|
||||
if (sum_bytes(data, sizeof(data)) != 0) {
|
||||
this->status_set_warning();
|
||||
ESP_LOGW(TAG, "Checksum failure when reading from FS3000");
|
||||
return;
|
||||
|
||||
@@ -224,11 +224,7 @@ void FujitsuGeneralClimate::transmit_(uint8_t const *message, uint8_t length) {
|
||||
}
|
||||
|
||||
uint8_t FujitsuGeneralClimate::checksum_state_(uint8_t const *message) {
|
||||
uint8_t checksum = 0;
|
||||
for (uint8_t i = 7; i < FUJITSU_GENERAL_STATE_MESSAGE_LENGTH - 1; ++i) {
|
||||
checksum += message[i];
|
||||
}
|
||||
return 256 - checksum;
|
||||
return -sum_bytes(message + 7, FUJITSU_GENERAL_STATE_MESSAGE_LENGTH - 8);
|
||||
}
|
||||
|
||||
uint8_t FujitsuGeneralClimate::checksum_util_(uint8_t const *message) { return 255 - message[5]; }
|
||||
|
||||
@@ -37,7 +37,6 @@ void GreeClimate::transmit_state() {
|
||||
remote_state[1] = this->temperature_();
|
||||
|
||||
if (model == GREE_YAN) {
|
||||
remote_state[2] = 0x20; // bits 0..3 always 0000, bits 4..7 TURBO, LIGHT, HEALTH, X-FAN
|
||||
remote_state[3] = 0x50; // bits 4..7 always 0101
|
||||
remote_state[4] = this->vertical_swing_();
|
||||
}
|
||||
@@ -61,7 +60,6 @@ void GreeClimate::transmit_state() {
|
||||
}
|
||||
|
||||
if (model == GREE_YAA || model == GREE_YAC || model == GREE_YAC1FB9) {
|
||||
remote_state[2] = 0x20; // bits 0..3 always 0000, bits 4..7 TURBO, LIGHT, HEALTH, X-FAN
|
||||
remote_state[3] = 0x50; // bits 4..7 always 0101
|
||||
remote_state[6] = 0x20; // YAA1FB, FAA1FB1, YB1F2 bits 4..7 always 0010
|
||||
|
||||
|
||||
@@ -76,6 +76,12 @@ static constexpr uint8_t GREE_PRESET_NONE = 0x00;
|
||||
static constexpr uint8_t GREE_PRESET_SLEEP = 0x01;
|
||||
static constexpr uint8_t GREE_PRESET_SLEEP_BIT = 0x80;
|
||||
|
||||
// Mode bits stored in remote_state[2] bits 4..7 for YAN/YAA/YAC/YAC1FB9.
|
||||
static constexpr uint8_t GREE_MODE_BIT_TURBO = 0x10;
|
||||
static constexpr uint8_t GREE_MODE_BIT_LIGHT = 0x20;
|
||||
static constexpr uint8_t GREE_MODE_BIT_HEALTH = 0x40;
|
||||
static constexpr uint8_t GREE_MODE_BIT_XFAN = 0x80;
|
||||
|
||||
// Model codes
|
||||
enum Model : uint8_t { GREE_GENERIC, GREE_YAN, GREE_YAA, GREE_YAC, GREE_YAC1FB9, GREE_YX1FF, GREE_YAG };
|
||||
|
||||
@@ -103,7 +109,7 @@ class GreeClimate final : public climate_ir::ClimateIR {
|
||||
uint8_t preset_();
|
||||
|
||||
Model model_{};
|
||||
uint8_t mode_bits_{0}; // Combined mode bits for remote_state[2]
|
||||
uint8_t mode_bits_{GREE_MODE_BIT_LIGHT}; // The display light is on until a switch says otherwise
|
||||
};
|
||||
|
||||
} // namespace esphome::gree
|
||||
|
||||
@@ -17,12 +17,22 @@ CONF_HEALTH = "health"
|
||||
CONF_XFAN = "xfan"
|
||||
CONF_GREE_ID = "gree_id"
|
||||
|
||||
# Switch configurations: (config_key, display_name, bit_mask, icon)
|
||||
# Switch configurations: (config_key, display_name, mode_bit, icon)
|
||||
SWITCH_CONFIGS = (
|
||||
(CONF_TURBO, "Gree Turbo Switch", 0x10, "mdi:car-turbocharger"),
|
||||
(CONF_LIGHT, "Gree Light Switch", 0x20, "mdi:led-outline"),
|
||||
(CONF_HEALTH, "Gree Health Switch", 0x40, "mdi:pine-tree"),
|
||||
(CONF_XFAN, "Gree X-FAN Switch", 0x80, "mdi:wall-sconce-flat"),
|
||||
(
|
||||
CONF_TURBO,
|
||||
"Gree Turbo Switch",
|
||||
gree_ns.GREE_MODE_BIT_TURBO,
|
||||
"mdi:car-turbocharger",
|
||||
),
|
||||
(CONF_LIGHT, "Gree Light Switch", gree_ns.GREE_MODE_BIT_LIGHT, "mdi:led-outline"),
|
||||
(CONF_HEALTH, "Gree Health Switch", gree_ns.GREE_MODE_BIT_HEALTH, "mdi:pine-tree"),
|
||||
(
|
||||
CONF_XFAN,
|
||||
"Gree X-FAN Switch",
|
||||
gree_ns.GREE_MODE_BIT_XFAN,
|
||||
"mdi:wall-sconce-flat",
|
||||
),
|
||||
)
|
||||
|
||||
SUPPORTED_MODELS = {
|
||||
@@ -39,7 +49,10 @@ CONFIG_SCHEMA = cv.Schema(
|
||||
cv.Optional(key): switch.switch_schema(
|
||||
GreeModeBitSwitch,
|
||||
icon=icon,
|
||||
default_restore_mode="RESTORE_DEFAULT_OFF",
|
||||
# The display light was on before the switches existed, so it stays on by default
|
||||
default_restore_mode="RESTORE_DEFAULT_ON"
|
||||
if key == CONF_LIGHT
|
||||
else "RESTORE_DEFAULT_OFF",
|
||||
device_class=DEVICE_CLASS_SWITCH,
|
||||
entity_category=ENTITY_CATEGORY_CONFIG,
|
||||
)
|
||||
|
||||
@@ -186,7 +186,12 @@ def _base_config_schema(class_: MockObjClass) -> cv.Schema:
|
||||
cv.Optional(
|
||||
CONF_ANSWER_TIMEOUT,
|
||||
): cv.positive_time_period_milliseconds,
|
||||
cv.Optional(CONF_ON_STATUS_MESSAGE): automation.validate_automation({}),
|
||||
# data points into the protocol's receive buffer, reused for the next frame
|
||||
cv.Optional(
|
||||
CONF_ON_STATUS_MESSAGE
|
||||
): automation.validate_synchronous_automation(
|
||||
"on_status_message", "the received frame"
|
||||
),
|
||||
}
|
||||
)
|
||||
.extend(uart.UART_DEVICE_SCHEMA)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "heatpumpir.h"
|
||||
|
||||
#include "receiver_mitsubishi_heavy.h"
|
||||
|
||||
#if defined(USE_ARDUINO) || defined(USE_ESP32)
|
||||
|
||||
#include <cmath>
|
||||
@@ -125,6 +127,13 @@ void HeatpumpIRClimate::setup() {
|
||||
}
|
||||
}
|
||||
|
||||
void HeatpumpIRClimate::control(const climate::ClimateCall &call) {
|
||||
// Picking a fan speed ends HiPower or Econo, as it does on the remote
|
||||
if (this->has_fan_byte_presets_() && call.get_fan_mode().has_value() && !call.get_preset().has_value())
|
||||
this->preset = climate::CLIMATE_PRESET_NONE;
|
||||
climate_ir::ClimateIR::control(call);
|
||||
}
|
||||
|
||||
void HeatpumpIRClimate::transmit_state() {
|
||||
uint8_t power_mode_cmd;
|
||||
uint8_t operating_mode_cmd;
|
||||
@@ -188,8 +197,9 @@ void HeatpumpIRClimate::transmit_state() {
|
||||
}
|
||||
|
||||
// MitsubishiMSCHeatpumpIR only knows FAN_1..FAN_3 and sends anything else as auto,
|
||||
// so low/medium/high have to start at FAN_1 there instead of FAN_2.
|
||||
const bool three_speed_fan = this->protocol_ == PROTOCOL_MITSUBISHI_MSC;
|
||||
// so low/medium/high have to start at FAN_1 there instead of FAN_2. Mitsubishi Heavy
|
||||
// ZJ and ZMP also stop at FAN_3 and use FAN_4 and FAN_5 for HiPower and Econo.
|
||||
const bool three_speed_fan = this->protocol_ == PROTOCOL_MITSUBISHI_MSC || this->has_fan_byte_presets_();
|
||||
switch (this->fan_mode.value_or(climate::CLIMATE_FAN_AUTO)) {
|
||||
case climate::CLIMATE_FAN_LOW:
|
||||
fan_speed_cmd = three_speed_fan ? FAN_1 : FAN_2;
|
||||
@@ -206,6 +216,19 @@ void HeatpumpIRClimate::transmit_state() {
|
||||
break;
|
||||
}
|
||||
|
||||
if (this->has_fan_byte_presets_()) {
|
||||
switch (this->preset.value_or(climate::CLIMATE_PRESET_NONE)) {
|
||||
case climate::CLIMATE_PRESET_BOOST:
|
||||
fan_speed_cmd = FAN_4; // HiPower
|
||||
break;
|
||||
case climate::CLIMATE_PRESET_ECO:
|
||||
fan_speed_cmd = FAN_5; // Econo
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
switch (this->mode) {
|
||||
case climate::CLIMATE_MODE_COOL:
|
||||
power_mode_cmd = POWER_ON;
|
||||
@@ -246,6 +269,23 @@ void HeatpumpIRClimate::transmit_state() {
|
||||
swing_h_cmd);
|
||||
}
|
||||
|
||||
bool HeatpumpIRClimate::on_receive(remote_base::RemoteReceiveData data) {
|
||||
switch (this->protocol_) {
|
||||
case PROTOCOL_MITSUBISHI_HEAVY_ZMP: {
|
||||
uint8_t frame[MITSUBISHI_HEAVY_FRAME_LENGTH];
|
||||
if (!decode_mitsubishi_heavy_frame(data, frame, *this))
|
||||
return false;
|
||||
decode_mitsubishi_heavy_zmp(frame, *this);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return false; // no decoder for this protocol
|
||||
}
|
||||
this->target_temperature = clamp(this->target_temperature, this->min_temperature_, this->max_temperature_);
|
||||
this->publish_state();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace esphome::heatpumpir
|
||||
|
||||
#endif
|
||||
|
||||
@@ -102,7 +102,12 @@ class HeatpumpIRClimate final : public climate_ir::ClimateIR {
|
||||
{climate::CLIMATE_SWING_OFF, climate::CLIMATE_SWING_HORIZONTAL,
|
||||
climate::CLIMATE_SWING_VERTICAL, climate::CLIMATE_SWING_BOTH}) {}
|
||||
void setup() override;
|
||||
void set_protocol(Protocol protocol) { this->protocol_ = protocol; }
|
||||
void set_protocol(Protocol protocol) {
|
||||
this->protocol_ = protocol;
|
||||
if (this->has_fan_byte_presets_()) {
|
||||
this->presets_ = {climate::CLIMATE_PRESET_NONE, climate::CLIMATE_PRESET_ECO, climate::CLIMATE_PRESET_BOOST};
|
||||
}
|
||||
}
|
||||
void set_horizontal_default(HorizontalDirection horizontal_direction) {
|
||||
this->default_horizontal_direction_ = horizontal_direction;
|
||||
}
|
||||
@@ -115,8 +120,15 @@ class HeatpumpIRClimate final : public climate_ir::ClimateIR {
|
||||
|
||||
protected:
|
||||
HeatpumpIR *heatpump_ir_;
|
||||
void control(const climate::ClimateCall &call) override;
|
||||
/// Transmit via IR the state of this climate controller.
|
||||
void transmit_state() override;
|
||||
/// Mitsubishi Heavy ZJ and ZMP carry HiPower and Econo in the fan byte as FAN_4 and FAN_5
|
||||
bool has_fan_byte_presets_() const {
|
||||
return this->protocol_ == PROTOCOL_MITSUBISHI_HEAVY_ZJ || this->protocol_ == PROTOCOL_MITSUBISHI_HEAVY_ZMP;
|
||||
}
|
||||
/// Handle received IR data from the remote control.
|
||||
bool on_receive(remote_base::RemoteReceiveData data) override;
|
||||
Protocol protocol_;
|
||||
HorizontalDirection default_horizontal_direction_;
|
||||
VerticalDirection default_vertical_direction_;
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
#include "receiver_mitsubishi_heavy.h"
|
||||
#include "heatpumpir.h"
|
||||
|
||||
#if defined(USE_ARDUINO) || defined(USE_ESP32)
|
||||
|
||||
#include <HeatpumpIRFactory.h>
|
||||
|
||||
namespace esphome::heatpumpir {
|
||||
|
||||
static constexpr uint8_t FRAME_PREFIX[5] = {0x52, 0xAE, 0xC3, 0x26, 0xD9};
|
||||
static constexpr uint8_t XOR_CHECKSUM_EXPECTED = 0xFF;
|
||||
static constexpr uint8_t PREFIX_LENGTH = 5;
|
||||
static constexpr uint8_t MODE_TEMP_BYTE = 9;
|
||||
static constexpr uint8_t MODE_MASK = 0x07;
|
||||
static constexpr uint8_t TEMP_MASK = 0x0F;
|
||||
static constexpr uint8_t TEMPERATURE_BASE = 17;
|
||||
static constexpr uint8_t TEMPERATURE_SHIFT = 4;
|
||||
|
||||
static bool read_raw_bytes(remote_base::RemoteReceiveData &data, uint8_t frame[MITSUBISHI_HEAVY_FRAME_LENGTH]) {
|
||||
if (!data.expect_item(MITSUBISHI_HEAVY_HDR_MARK, MITSUBISHI_HEAVY_HDR_SPACE))
|
||||
return false;
|
||||
|
||||
for (uint8_t i = 0; i < MITSUBISHI_HEAVY_FRAME_LENGTH; i++) {
|
||||
uint8_t byte = 0;
|
||||
for (uint8_t bit = 0; bit < 8; bit++) {
|
||||
if (data.expect_item(MITSUBISHI_HEAVY_BIT_MARK, MITSUBISHI_HEAVY_ONE_SPACE)) {
|
||||
byte |= 1 << bit;
|
||||
} else if (!data.expect_item(MITSUBISHI_HEAVY_BIT_MARK, MITSUBISHI_HEAVY_ZERO_SPACE)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
frame[i] = byte;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool validate_prefix(const uint8_t frame[MITSUBISHI_HEAVY_FRAME_LENGTH]) {
|
||||
for (uint8_t i = 0; i < PREFIX_LENGTH; i++) {
|
||||
if (frame[i] != FRAME_PREFIX[i])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool validate_checksums(const uint8_t frame[MITSUBISHI_HEAVY_FRAME_LENGTH]) {
|
||||
for (uint8_t i = PREFIX_LENGTH; i < MITSUBISHI_HEAVY_FRAME_LENGTH; i += 2) {
|
||||
if ((uint8_t) (frame[i] ^ frame[i + 1]) != XOR_CHECKSUM_EXPECTED)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool decode_mode_field(const uint8_t frame[MITSUBISHI_HEAVY_FRAME_LENGTH], climate::ClimateMode &mode) {
|
||||
if (frame[MODE_TEMP_BYTE] & MITSUBISHI_HEAVY_MODE_OFF) {
|
||||
mode = climate::CLIMATE_MODE_OFF;
|
||||
return true;
|
||||
}
|
||||
switch (frame[MODE_TEMP_BYTE] & MODE_MASK) {
|
||||
case MITSUBISHI_HEAVY_MODE_AUTO:
|
||||
mode = climate::CLIMATE_MODE_HEAT_COOL;
|
||||
return true;
|
||||
case MITSUBISHI_HEAVY_MODE_HEAT:
|
||||
mode = climate::CLIMATE_MODE_HEAT;
|
||||
return true;
|
||||
case MITSUBISHI_HEAVY_MODE_COOL:
|
||||
mode = climate::CLIMATE_MODE_COOL;
|
||||
return true;
|
||||
case MITSUBISHI_HEAVY_MODE_DRY:
|
||||
mode = climate::CLIMATE_MODE_DRY;
|
||||
return true;
|
||||
case MITSUBISHI_HEAVY_MODE_FAN:
|
||||
mode = climate::CLIMATE_MODE_FAN_ONLY;
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static float decode_temperature_field(const uint8_t frame[MITSUBISHI_HEAVY_FRAME_LENGTH]) {
|
||||
uint8_t temp_nibble = frame[MODE_TEMP_BYTE] >> TEMPERATURE_SHIFT;
|
||||
uint8_t inverted_nibble = ~temp_nibble;
|
||||
uint8_t temp_offset = inverted_nibble & TEMP_MASK;
|
||||
return TEMPERATURE_BASE + temp_offset;
|
||||
}
|
||||
|
||||
static bool apply_climate_state(const uint8_t frame[MITSUBISHI_HEAVY_FRAME_LENGTH], HeatpumpIRClimate &climate) {
|
||||
climate::ClimateMode mode;
|
||||
if (!decode_mode_field(frame, mode))
|
||||
return false;
|
||||
climate.mode = mode;
|
||||
climate.target_temperature = decode_temperature_field(frame);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool decode_mitsubishi_heavy_frame(remote_base::RemoteReceiveData &data, uint8_t frame[MITSUBISHI_HEAVY_FRAME_LENGTH],
|
||||
HeatpumpIRClimate &climate) {
|
||||
if (!read_raw_bytes(data, frame))
|
||||
return false;
|
||||
if (!validate_prefix(frame))
|
||||
return false;
|
||||
if (!validate_checksums(frame))
|
||||
return false;
|
||||
return apply_climate_state(frame, climate);
|
||||
}
|
||||
|
||||
} // namespace esphome::heatpumpir
|
||||
|
||||
#endif
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user