平台(platform)
理解平台概念
平台:当集成接入的设备,属于某种通用类型时,可以通过创建平台简化其开发
常见的通用类型:
alarm_control_panel
:报警控制面板air_quality
:空气净化器binary_sensor
:开关型传感器climate
:空调cover
:窗帘device_tracker
:位置跟踪fan
:风扇lock
:智能锁sensor
:传感器light
:智能灯switch
:智能开关camera
:摄像头media_player
:媒体播放器image_processing
:图像处理remote
:无线遥控设备weather
:天气状况- ……
绝大多数的设备接入,都可以通过在集成中创建平台来简化开发
平台程序
-
代码位置
集成的平台逻辑代码,放置在该集成目录下的
X.py
文件中(X是平台对应的通用设备类型)例:基于xiaomi_miio协议的
device_tracker
、fan
、light
、remote
、sensor
、switch
、vacuum
-
基础类
代码中一般会实现一个从基础类继承的类
基础类: -
homeassistant.components.sensor.SensorEntity
-homeassistant.components.media_player.MediaPlayerEntity
-homeassistant.components.light.LightEntity
-homeassistant.components.climate.ClimateEntity
- ……官方文档:https://developers.home-assistant.io/docs/core/entity
参考:https://github.com/home-assistant/core/tree/master/homeassistant/components/demo
配置与加载
-
在类型域中配置(
configuration.yaml
)sensor: - platform: example_load_platform1 name: abc value: 23.33
-
流程入口:
(async_)setup_platform
- 配置被加载时,自动调用此函数
- 配置内容通过
config
参数传入 - 在此函数中通过传入的
(async_)add_entities
函数加载设备
-
-
在集成域中配置(
configuration.yaml
)example_load_platform2: sensor: name: abc value: 25.55
-
流程入口:
(async_)setup
- 在此函数中调用
hass.helpers.discovery.(async_)load_platform
函数
- 在此函数中调用
-
(async_)setup_platform
- 调用
hass.helpers.discovery.(async_)load_platform
函数后,自动启动此函数 - 配置内容可通过
discovery_info
参数传入 - 在此函数中,通过传入的
(async_)add_entities
函数加载设备
- 调用
-
-
前端配置
-
流程入口:
async_setup_entry
- 在此函数中调用
hass.config_entries.async_forward_entry_setup
函数
- 在此函数中调用
-
async_setup_entry
- 调用
hass.config_entries.async_forward_entry_setup
函数后,自动启动此函数 - 配置信息通过
config_entry
参数传入 - 在此函数中,通过传入的
async_add_entities
函数加载设备
- 调用
-
以上三种方式并不互斥,可以同时实现