Guide for developing ESPHome components and firmware for ESP32/ESP8266/RP2040 microcontrollers using YAML configuration and Python code generation
ESPHome is a system to configure microcontrollers (ESP32, ESP8266, RP2040, LibreTiny-based chips) using YAML configuration files. It generates C++ firmware compiled via PlatformIO for remote control through home automation systems.
ESPHome follows a **code-generation architecture**: Python parses YAML configs and generates C++ source code, which is then compiled and flashed to target microcontrollers.
1. **Configuration System** (`esphome/config*.py`): YAML parsing, Voluptuous validation, schema definitions
2. **Code Generation** (`esphome/codegen.py`, `esphome/cpp_generator.py`): Python-to-C++ generation, templates, build flags
3. **Component System** (`esphome/components/`): Modular hardware/software components with platform-specific implementations
4. **Core Framework** (`esphome/core/`): Application lifecycle, hardware abstraction, component registration
5. **Dashboard** (`esphome/dashboard/`): Web interface for configuration, management, OTA updates
- Functions/methods/variables: `lower_snake_case`
- Classes/structs/enums: `UpperCamelCase`
- Top-level constants: `UPPER_SNAKE_CASE`
- Function-local constants: `lower_snake_case`
- Protected/private fields: `lower_snake_case_with_trailing_underscore_`
1. Pointer lifetime issues (setters validate/store pointers from known lists)
2. Invariant coupling (fields must stay synchronized)
3. Resource management (setters perform cleanup/registration)
```
components/[component_name]/
├── __init__.py # Configuration schema and code generation
├── [component].h # C++ header (if needed)
├── [component].cpp # C++ implementation (if needed)
└── [platform]/ # Platform-specific implementations
├── __init__.py # Platform configuration
├── [platform].h # Platform C++ header
└── [platform].cpp # Platform C++ implementation
```
```python
DEPENDENCIES = ["required_component"] # Required components
AUTO_LOAD = ["auto_loaded_component"] # Auto-load components
CONFLICTS_WITH = ["incompatible_comp"] # Incompatible components
CODEOWNERS = ["@username"] # GitHub maintainers
MULTI_CONF = True # Allow multiple instances
```
```python
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import CONF_KEY, CONF_ID
CONF_PARAM = "param" # New constant (not in esphome/const.py)
my_component_ns = cg.esphome_ns.namespace("my_component")
MyComponent = my_component_ns.class_("MyComponent", cg.Component)
CONFIG_SCHEMA = cv.Schema({
cv.GenerateID(): cv.declare_id(MyComponent),
cv.Required(CONF_KEY): cv.string,
cv.Optional(CONF_PARAM, default=42): cv.int_,
}).extend(cv.COMPONENT_SCHEMA)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
cg.add(var.set_key(config[CONF_KEY]))
cg.add(var.set_param(config[CONF_PARAM]))
```
```cpp
namespace esphome::my_component {
class MyComponent : public Component {
public:
void setup() override;
void loop() override;
void dump_config() override;
void set_key(const std::string &key) { this->key_ = key; }
void set_param(int param) { this->param_ = param; }
protected:
std::string key_;
int param_{0};
};
} // namespace esphome::my_component
```
**Sensor:**
```python
from esphome.components import sensor
CONFIG_SCHEMA = sensor.sensor_schema(MySensor).extend(cv.polling_component_schema("60s"))
async def to_code(config):
var = await sensor.new_sensor(config)
await cg.register_component(var, config)
```
**Binary Sensor:**
```python
from esphome.components import binary_sensor
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend({ ... })
async def to_code(config):
var = await binary_binary_sensor.new_binary_sensor(config)
```
**Switch:**
```python
from esphome.components import switch
CONFIG_SCHEMA = switch.switch_schema().extend({ ... })
async def to_code(config):
var = await switch.new_switch(config)
```
```python
CONFIG_SCHEMA = cv.Schema({ ... })
.extend(cv.COMPONENT_SCHEMA)
.extend(uart.UART_DEVICE_SCHEMA)
.extend(i2c.i2c_device_schema(0x48))
.extend(spi.spi_device_schema(cs_pin_required=True))
```
**Python Unit Tests:**
```bash
pytest
```
**C++ Static Analysis:**
```bash
clang-tidy
```
**Component YAML Tests:**
```bash
./script/test_build_components -c <component> -t <target>
```
**All Components Together:**
```bash
./script/test_component_grouping.py -e config --all
```
**Linting:**
```bash
python3 script/run-in-env.py pre-commit run
```
1. Use descriptive names over abbreviations
2. Prefix all member access with `this->`
3. Avoid `#define` for constants (use `const` or enums)
4. Extend existing component schemas where possible
5. Test components individually and in groups
6. Follow platform-specific constraints in validation schemas
7. Use `protected` fields by default for extensibility
8. Document complex validation logic
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/esphome-component-development/raw