Skip to content

Commit b63386e

Browse files
committed
declaration: add include
1 parent 350216a commit b63386e

File tree

2 files changed

+21
-13
lines changed

2 files changed

+21
-13
lines changed

components/declaration/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ Parameters:
77
- namespace: Optional string or list of strings. Namespace to wrap lambda code.
88
- internal: boolean. Wrap or not to private anonymous namespace. Defaults: true.
99
- lambda: c++ code to be included in declaration.
10+
- include: one or list of includes.
1011

1112
## Configuration
1213

components/declaration/__init__.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,40 @@
22
import esphome.config_validation as cv
33
from esphome import cpp_generator as cpp
44
from esphome.const import CONF_INTERNAL, CONF_LAMBDA
5-
from esphome.core import Lambda
65

76
CONF_NAMESPACE = "namespace"
8-
7+
CONF_INCLUDE = "include"
98

109
DECLARATION_SCHEMA = cv.Schema(
1110
{
1211
cv.Optional(CONF_NAMESPACE): cv.ensure_list(cv.valid_name),
1312
cv.Optional(CONF_INTERNAL): cv.boolean,
14-
cv.Required(CONF_LAMBDA): cv.lambda_,
13+
cv.Optional(CONF_LAMBDA): cv.lambda_,
14+
cv.Optional(CONF_INCLUDE): cv.ensure_list(cv.string),
1515
}
16+
).add_extra(
17+
cv.has_at_least_one_key(
18+
CONF_LAMBDA,
19+
CONF_INCLUDE,
20+
)
1621
)
1722

18-
19-
def _validate_declaration(conf):
20-
if not isinstance(conf, dict):
21-
conf = {CONF_LAMBDA: conf}
22-
if not isinstance(conf[CONF_LAMBDA], Lambda):
23-
conf[CONF_LAMBDA] = cv.lambda_(conf[CONF_LAMBDA])
24-
return conf
25-
26-
27-
CONFIG_SCHEMA = cv.ensure_list(_validate_declaration)
23+
CONFIG_SCHEMA = cv.ensure_list(DECLARATION_SCHEMA)
2824

2925

3026
async def to_code(config):
27+
includes = set()
28+
# process includes first
3129
for conf in config:
30+
for inc in conf.get(CONF_INCLUDE, []):
31+
includes.add(inc)
32+
for inc in includes:
33+
cg.add_global(cg.RawStatement(f'#include "{inc}"'))
34+
35+
for conf in config:
36+
if CONF_LAMBDA not in conf:
37+
continue
38+
3239
lambda_: cpp.LambdaExpression = await cg.process_lambda(conf[CONF_LAMBDA], [])
3340
content = lambda_.content
3441

0 commit comments

Comments
 (0)