创建你的第一个集成
好了,现在是时候为你的集成编写第一段代码了。太棒了!别担心,我们已经尽力让它尽可能简单。在Home Assistant开发环境中,输入以下内容并按照说明操作:
python3 -m script.scaffold integration
这将为你设置好构建一个能够通过用户界面进行设置的集成所需的一切。更全面的集成示例可以从我们的示例仓库中获取。
最低要求
脚手架集成包含的内容比最低要求多一些。最低要求是你定义一个包含集成域的DOMAIN
常量。第二部分是它需要定义一个setup
方法,如果设置成功则返回一个布尔值。
DOMAIN = "hello_state"
def setup(hass, config):
hass.states.set("hello_state.world", "Paulus")
# 返回布尔值以指示初始化成功
return True
如果你更喜欢异步组件:
DOMAIN = "hello_state"
async def async_setup(hass, config):
await hass.states.async_set("hello_state.world", "Paulus")
# 返回布尔值以指示初始化成功
return True
使用上述两个代码块之一创建一个文件<config_dir>/custom_components/hello_state/__init__.py
。此外,还需要一个清单文件,至少包含以下键。创建<config_dir>/custom_components/hello_state/manifest.json
。
{"domain": "hello_state", "name": "Hello, state!", "version": "0.1.0"}
要加载它,在configuration.yaml
文件中添加hello_state:
。