
ESPHome是一个折腾智能家居的嵌入式开源项目,仓库为github.com/esphome/esphome,语言为Python配置层加C++运行时,许可GPL-3.0/MIT(部分),支持ESP32、ESP8266、RP2040、BK72xx、RTL87xx、Host,包含700多个组件,每个组件三个文件。
作者用一个真实事故引出主题:2022年做菌菇房控制器,八个继电器控制加湿、加热、风机、补光,客户要求参数自己调、不要每次改固件。于是用ESPHome,配置写成YAML,改一行点一下OTA十几秒生效。第三个月客户自己加了路备用加热,把pin: GPIO16写成了pin: GPIO6,编译通过、OTA成功,重启后两个继电器一直吸合,主加热和备用加热同时通电,两小时后加热丝烧断、温控探头烤坏。问题不在ESPHome,它严格区分配置错误和编译错误,但没能力管配置合法、接线不符。
骨架方面,components目录下有700多个组件,每个目录包含注册用的__init__.py、YAML schema与to_code的sensor.py、C++类声明的dht.h和实现dht.cpp;core目录下有application.cpp总调度、component.h组件基类、scheduler.cpp定时回调;codegen.py、cpp_generator.py、config_validation.py、writer.py负责生成main.cpp。Python那半负责读懂YAML、生成C++语句,C++那半负责运行时干活,两边通过生成出来的main.cpp连接。
核心设计一:YAML不是脚本,是生成代码的输入。流程是YAML→Python校验→生成C++语句→拼成main.cpp→交给PlatformIO编译→烧进去,设备上跑的是和手写没区别的C++,YAML在运行时一个字节都不存在。cg.new_Pvariable不是new,是声明一个变量并给我一个句柄;语句是攒起来的而非立即写文件;schema和生成是分开的两件事,校验不通过走不到生成那一步,把配置错误挡在编译之前。
核心设计二:组件有状态且压在一个字节里。COMPONENT_STATE_MASK用位0-2表示8个状态,STATUS_LED_MASK位3-4表示状态灯,COMPONENT_HAS_LOOP位5表示要不要每轮loop都调它。一个字节装了跑在哪个阶段、状态灯什么颜色、要不要每轮loop都调它。因为ESP8266只有80KB RAM,每个组件省3字节就是几百字节。setup_priority中BUS为1000、IO为900、HARDWARE为800、DATA为600、PROCESSOR为400、LATE为250;PollingComponent周期性的活继承它只写update(),update里绝对不能delay,因为调度是协作式单线程。
核心设计三:启动失败几次就进安全模式,用一个掉电保持的计数器记录连续快速重启次数。计数器存在清除它的动作成功之后,正常启动完成后mark_successful清零;安全模式不是跑最小系统而是只跑OTA,业务组件全部不初始化,只有WiFi和API活着;enable_time到了自动重启兜底。参数num_attempts默认10次,boot_is_good_after默认60秒,跑满一分钟才算启动成功。
五条坑:YAML单位省略会变含义,温度传感器写60ms会打满I2C总线;pin写错不会编译报错,ESP32的GPIO6是Flash引脚;组件顺序靠setup_priority不靠YAML顺序;on_boot里的priority是另一套;生成的main.cpp在.esphome/build/<设备名>/src/main.cpp值得看一眼。
本文来源:https://www.eet-china.com/mp/a542305.html
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。
ESPHome is an embedded open-source project for smart-home tinkering. Its repository is github.com/esphome/esphome; the language is a Python configuration layer plus a C++ runtime; the license is GPL-3.0/MIT (in part); it supports ESP32, ESP8266, RP2040, BK72xx, RTL87xx and Host; and it contains more than 700 components, each with three files.
The author introduces the topic with a real incident: in 2022 they built a mushroom-room controller with eight relays controlling humidification, heating, fans and supplemental lighting; the customer wanted to adjust parameters themselves rather than change firmware every time. So they used ESPHome, wrote the configuration in YAML, and a one-line change followed by an OTA took effect in just over ten seconds. In the third month the customer added a backup heating circuit on their own and wrote pin: GPIO6 instead of pin: GPIO16; compilation passed and the OTA succeeded, but after reboot two relays stayed latched on, with the main heater and the backup heater energised at the same time. Two hours later the heating wire burned out and the temperature probe was ruined. The problem was not with ESPHome — it strictly distinguishes configuration errors from compilation errors, but it cannot enforce that a valid configuration matches the actual wiring.
As for the skeleton, the components directory contains more than 700 components, each with an __init__.py for registration, a sensor.py with the YAML schema and to_code, a dht.h with the C++ class declaration and a dht.cpp with the implementation; the core directory contains application.cpp for overall scheduling, component.h as the component base class and scheduler.cpp for timed callbacks; while codegen.py, cpp_generator.py, config_validation.py and writer.py are responsible for generating main.cpp. The Python half reads the YAML and generates C++ statements, the C++ half does the work at runtime, and the two halves are connected through the generated main.cpp.
Core design one: YAML is not a script, it is input for code generation. The flow is YAML → Python validation → generate C++ statements → assemble main.cpp → hand it to PlatformIO for compilation → flash it; what runs on the device is C++ indistinguishable from hand-written code, and not a single byte of YAML exists at runtime. cg.new_Pvariable is not new — it declares a variable and gives me a handle; statements are accumulated rather than written to a file immediately; schema validation and generation are two separate things, and if validation fails, generation is never reached, which blocks configuration errors before compilation.
Core design two: components have state packed into a single byte. COMPONENT_STATE_MASK uses bits 0-2 to represent eight states, STATUS_LED_MASK uses bits 3-4 for the status LED, and COMPONENT_HAS_LOOP uses bit 5 to indicate whether it should be called every loop. One byte holds which phase it is running in, what colour the status LED is, and whether it should be called on every loop. Because the ESP8266 has only 80KB of RAM, saving three bytes per component adds up to hundreds of bytes. In setup_priority, BUS is 1000, IO is 900, HARDWARE is 800, DATA is 600, PROCESSOR is 400 and LATE is 250; periodic work inherits from PollingComponent and only needs to implement update(), and you must never call delay() inside update(), because scheduling is cooperative and single-threaded.
Core design three: after a few failed boots it enters safe mode, using a power-loss-persistent counter to record consecutive rapid reboots. The counter is incremented only after the action that clears it has succeeded; once a normal boot completes, mark_successful resets it to zero; safe mode does not run a minimal system but only OTA — no application components are initialised, and only WiFi and the API stay alive; when enable_time expires, an automatic reboot serves as a fallback. The parameter num_attempts defaults to 10, and boot_is_good_after defaults to 60 seconds, so the device must run a full minute before the boot is considered successful.
Five pitfalls: omitting units in YAML changes the meaning — writing 60ms for a temperature sensor will saturate the I2C bus; a wrong pin will not cause a compilation error, and ESP32's GPIO6 is a Flash pin; component order depends on setup_priority, not YAML order; the priority in on_boot is a different system; and the generated main.cpp at .esphome/build/
本文来源:https://www.eet-china.com/mp/a542305.html
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。