diff --git a/esphome/codegen.py b/esphome/codegen.py index 57316ab4fa..90f59f75bc 100644 --- a/esphome/codegen.py +++ b/esphome/codegen.py @@ -21,6 +21,7 @@ from esphome.cpp_generator import ( # noqa progmem_array, statement, variable, + new_variable, Pvariable, new_Pvariable, add, diff --git a/esphome/components/color/__init__.py b/esphome/components/color/__init__.py index 7c044040ee..6712d078a4 100644 --- a/esphome/components/color/__init__.py +++ b/esphome/components/color/__init__.py @@ -51,7 +51,7 @@ def to_code(config): elif CONF_WHITE_INT in config: w = config[CONF_WHITE_INT] - cg.variable( + cg.new_variable( config[CONF_ID], cg.StructInitializer(ColorStruct, ("r", r), ("g", g), ("b", b), ("w", w)), ) diff --git a/esphome/cpp_generator.py b/esphome/cpp_generator.py index 754ce229a9..999b252dde 100644 --- a/esphome/cpp_generator.py +++ b/esphome/cpp_generator.py @@ -448,6 +448,29 @@ def variable(id_: ID, rhs: SafeExpType, type_: "MockObj" = None) -> "MockObj": return obj +def new_variable(id_: ID, rhs: SafeExpType, type_: "MockObj" = None) -> "MockObj": + """Declare and define a new variable, not pointer type, in the code generation. + + :param id_: The ID used to declare the variable. + :param rhs: The expression to place on the right hand side of the assignment. + :param type_: Manually define a type for the variable, only use this when it's not possible + to do so during config validation phase (for example because of template arguments). + + :returns The new variable as a MockObj. + """ + assert isinstance(id_, ID) + rhs = safe_exp(rhs) + obj = MockObj(id_, ".") + if type_ is not None: + id_.type = type_ + decl = VariableDeclarationExpression(id_.type, "", id_) + CORE.add_global(decl) + assignment = AssignmentExpression(None, "", id_, rhs, obj) + CORE.add(assignment) + CORE.register_variable(id_, obj) + return obj + + def Pvariable(id_: ID, rhs: SafeExpType, type_: "MockObj" = None) -> "MockObj": """Declare a new pointer variable in the code generation.