告别智能家居监控烦恼:Xiaomi Home Integration设备状态变更通知模板全解析
告别智能家居监控烦恼:Xiaomi Home Integration设备状态变更通知模板全解析
你是否还在为无法及时掌握小米智能家居设备状态变化而困扰?当空调意外关闭、门锁被异常开启或温湿度传感器超出阈值时,能否立即获得通知?本文将系统讲解如何基于Home Assistant的Xiaomi Home Integration实现设备状态变更通知,通过12个实战模板、5种触发机制和3套完整场景方案,让你彻底掌握智能家居监控主动权。
读完本文你将获得:
- 设备状态通知的核心实现原理与数据流向
- 12个即插即用的通知模板(覆盖开关、传感器、安防等设备类型)
- 5种高级触发条件配置技巧(含阈值、延迟、组合逻辑)
- 3套完整场景方案(家庭安防、能源管理、老人关怀)
- 通知内容自定义与多渠道推送(短信、APP、语音)指南
一、技术原理与架构设计
1.1 状态变更通知工作流
Xiaomi Home Integration通过设备状态监听→属性变化解析→通知触发三个核心环节实现状态变更通知功能,具体工作流程如下:
关键技术点在于miot_device.py中实现的设备状态订阅机制,通过sub_device_state()方法注册状态变化处理器:
def sub_device_state(
self, key: str, handler: Callable[[str, MIoTDeviceState], None]
) -> int:
sub_id = self.__gen_sub_id()
if key in self._device_state_sub_list:
self._device_state_sub_list[key][str(sub_id)] = handler
else:
self._device_state_sub_list[key] = {str(sub_id): handler}
return sub_id
当设备状态发生变化时,__on_device_state_changed()方法会被触发,进而调用注册的处理器函数更新实体状态。
1.2 通知实体实现结构
通知功能主要通过notify.py中的Notify类实现,该类继承自MIoTActionEntity和Home Assistant的NotifyEntity,核心代码结构如下:
class Notify(MIoTActionEntity, NotifyEntity):
"""Notify entities for Xiaomi Home."""
async def async_send_message(
self, message: str, title: Optional[str] = None
) -> None:
"""Send a message."""
if not message:
_LOGGER.error('empty action params')
return
# YAML格式解析
in_list: Any = yaml.parse_yaml(content=message)
# 参数类型验证
if len(self.spec.in_) == 1 and not isinstance(in_list, list):
in_list = [in_list]
# 类型转换与执行
await self.action_async(in_list=in_value)
该类实现了Home Assistant通知实体的核心接口async_send_message(),支持将设备状态变化信息格式化为YAML格式参数,并通过MIoT协议发送到设备或触发通知。
二、核心功能模块解析
2.1 设备状态监听机制
Xiaomi Home Integration通过多层订阅机制实现设备状态的实时监听,主要包括:
- 设备级订阅:通过
miot_client.py中的sub_device_state()方法订阅整个设备的状态变化 - 属性级订阅:通过
sub_property()方法订阅特定属性(siid/piid)的变化 - 事件级订阅:通过
sub_event()方法订阅设备事件
其中属性级订阅的实现代码如下:
def sub_property(
self, handler: Callable[[dict, Any], None], siid: int, piid: int
) -> int:
key: str = f'p.{siid}.{piid}'
def _on_prop_changed(params: dict, ctx: Any) -> None:
for handler in self._value_sub_list[key].values():
handler(params, ctx)
sub_id = self.__gen_sub_id()
if key in self._value_sub_list:
self._value_sub_list[key][str(sub_id)] = handler
else:
self._value_sub_list[key] = {str(sub_id): handler}
self.miot_client.sub_prop(
did=self._did, handler=_on_prop_changed, siid=siid, piid=piid)
return sub_id
这种分层订阅机制确保系统能精确监听特定设备、特定属性的变化,为精准触发通知提供了基础。
2.2 消息格式与参数验证
通知消息采用YAML格式进行参数传递,async_send_message()方法会对输入消息进行严格的格式验证和类型转换:
async def async_send_message(
self, message: str, title: Optional[str] = None
) -> None:
if not message:
_LOGGER.error('empty action params')
return
try:
in_list = yaml.parse_yaml(content=message)
except HomeAssistantError:
_LOGGER.error('invalid action params format: %s', message)
return
# 参数类型验证与转换
if len(self.spec.in_) == 1 and not isinstance(in_list, list):
in_list = [in_list]
# 类型检查与转换
for index, prop in enumerate(self.spec.in_):
if prop.format_ == str:
in_value.append({'piid': prop.iid, 'value': str(in_list[index])})
elif prop.format_ == bool:
in_value.append({'piid': prop.iid, 'value': bool(in_list[index])})
# 其他类型处理...
支持的参数类型包括字符串、布尔值、整数和浮点数,系统会根据设备规格定义自动进行类型转换和验证。
三、基础通知模板与使用指南
3.1 开关类设备状态通知
适用设备:智能插座、智能开关、窗帘电机等具有开关状态的设备
模板代码:
# configuration.yaml
automation:
- alias: "智能插座状态变化通知"
trigger:
platform: state
entity_id: switch.xiaomi_smart_plug
action:
service: notify.xiaomi_home_notify
data:
title: "智能插座状态变化"
message: |
- device: "客厅智能插座"
entity_id: "{{ trigger.entity_id }}"
old_state: "{{ trigger.from_state.state }}"
new_state: "{{ trigger.to_state.state }}"
time: "{{ now().strftime('%Y-%m-%d %H:%M:%S') }}"
关键参数说明:
| 参数 | 类型 | 说明 |
|---|---|---|
| device | 字符串 | 设备友好名称 |
| entity_id | 字符串 | Home Assistant实体ID |
| old_state | 字符串 | 变化前状态 |
| new_state | 字符串 | 变化后状态 |
| time | 字符串 | 变化时间戳 |
效果展示:当插座从"开"变为"关"时,用户将收到包含设备名称、状态变化前后值和时间戳的通知。
3.2 传感器数值变化通知
适用设备:温湿度传感器、人体传感器、烟雾报警器等
模板代码:
# configuration.yaml
automation:
- alias: "温湿度异常通知"
trigger:
- platform: numeric_state
entity_id: sensor.temperature_sensor_temperature
above: 30
- platform: numeric_state
entity_id: sensor.temperature_sensor_humidity
above: 70
action:
service: notify.xiaomi_home_notify
data:
title: "温湿度异常警报"
message: |
- device: "卧室温湿度传感器"
type: "{{ '温度' if 'temperature' in trigger.entity_id else '湿度' }}"
value: "{{ trigger.to_state.state }}{{ trigger.to_state.attributes.unit_of_measurement }}"
threshold: "{{ trigger.below if trigger.below else trigger.above }}{{ trigger.to_state.attributes.unit_of_measurement }}"
time: "{{ now().strftime('%Y-%m-%d %H:%M:%S') }}"
触发条件说明:
| 条件类型 | 参数 | 说明 |
|---|---|---|
| numeric_state | above | 数值高于阈值时触发 |
| numeric_state | below | 数值低于阈值时触发 |
| state | from_state/to_state | 状态变化时触发 |
高级配置:可添加延迟触发条件避免抖动:
trigger:
platform: numeric_state
entity_id: sensor.temperature_sensor_temperature
above: 30
for:
minutes: 5
四、高级功能与自定义技巧
4.1 多条件组合触发
通过condition配置实现多条件组合逻辑,满足复杂场景需求:
automation:
- alias: "离家模式安全检查"
trigger:
platform: state
entity_id: person.family_member
to: "not_home"
condition:
condition: and
conditions:
- condition: state
entity_id: switch.main_door_lock
state: "unlocked"
- condition: state
entity_id: switch.window_sensor
state: "on"
- condition: numeric_state
entity_id: sensor.gas_sensor
above: 0
action:
service: notify.xiaomi_home_notify
data:
title: "离家安全检查提醒"
message: |
- 检查结果: 发现{{ states('sensor.door_lock_unlocked_count') }}个隐患
- 未锁设备: {% for entity in states.switch if entity.state == 'unlocked' %}
{{ entity.name }}{% if not loop.last %}, {% endif %}{% endfor %}
- 时间: {{ now().strftime('%Y-%m-%d %H:%M:%S') }}
条件类型支持:
| 条件类型 | 说明 |
|---|---|
| state | 实体状态等于指定值 |
| numeric_state | 数值实体满足指定范围 |
| template | 自定义模板条件 |
| sun | 基于日出日落时间 |
| time | 基于特定时间 |
4.2 通知内容格式化与美化
利用Home Assistant的模板功能美化通知内容,添加图标和格式化输出:
automation:
- alias: "格式化状态通知"
trigger:
platform: state
entity_id: switch.xiaomi_smart_plug
action:
service: notify.xiaomi_home_notify
data:
title: "设备状态更新 🔌"
message: |
📌 <b>设备状态变化通知</b>
🕒 {{ now().strftime('%Y-%m-%d %H:%M:%S') }}
🏷️ <b>设备名称:</b> {{ state_attr(trigger.entity_id, 'friendly_name') }}
🔄 <b>状态变化:</b> <span style="color:{% if trigger.to_state.state == 'on' %}green{% else %}red{% endif %}">
{{ trigger.from_state.state | upper }} → {{ trigger.to_state.state | upper }}</span>
📊 <b>运行时长:</b> {% if trigger.to_state.state == 'off' %}
{{ (as_timestamp(now()) - as_timestamp(trigger.from_state.last_changed)) | timestamp_custom('%H:%M:%S', false) }}
{% else %}
刚刚开启
{% endif %}
格式化技巧:
- 使用HTML标签:
<b>(加粗)、<i>(斜体)、<span>(颜色设置) - 添加 emoji 图标增强可读性
- 使用条件样式:根据状态值动态改变文字颜色
- 计算运行时长:通过时间戳计算设备运行时间
4.3 多渠道通知推送配置
Xiaomi Home Integration支持与Home Assistant的多渠道通知集成,实现短信、APP推送、语音播报等多种通知方式:
# configuration.yaml
notify:
- name: xiaomi_home_notify
platform: group
services:
- service: mobile_app_my_phone
- service: sms_notification
- service: tts_service
- name: sms_notification
platform: twilio
account_sid: !secret twilio_account_sid
auth_token: !secret twilio_auth_token
from_number: !secret twilio_phone_number
to_number: !secret my_phone_number
- name: tts_service
platform: media_player
entity_id: media_player.smart_speaker
多渠道策略建议:
| 通知类型 | 推荐渠道 | 优先级 | 特点 |
|---|---|---|---|
| 紧急警报 | 短信 + APP推送 + 语音 | 高 | 多渠道确保送达 |
| 一般提醒 | APP推送 | 中 | 低打扰 |
| 状态通知 | 日志记录 | 低 | 仅记录不打扰 |
五、实战场景方案
5.1 家庭安防监控系统
场景描述:当检测到门窗异常开启、陌生人移动或烟雾报警时,立即推送警报通知并触发本地声光提醒。
系统架构:
核心自动化配置:
automation:
- alias: "家庭安防警报系统"
trigger:
- platform: state
entity_id: binary_sensor.door_contact_sensor
to: "on"
- platform: state
entity_id: binary_sensor.motion_sensor
to: "on"
- platform: state
entity_id: binary_sensor.smoke_sensor
to: "on"
condition:
condition: state
entity_id: input_boolean.security_mode
state:. "on"
action:
- service: notify.xiaomi_home_notify
data:
title: "【紧急警报】家庭安防事件"
message: |
- 事件类型: {% if trigger.entity_id == 'binary_sensor.smoke_sensor' %}
烟雾报警
{% elif trigger.entity_id == 'binary_sensor.door_contact_sensor' %}
门窗异常开启
{% else %}
异常移动检测
{% endif %}
- 位置: {{ state_attr(trigger.entity_id, 'friendly_name').split(' ')[0] }}
- 时间: {{ now().strftime('%Y-%m-%d %H:%M:%S') }}
- 处理建议: {% if trigger.entity_id == 'binary_sensor.smoke_sensor' %}
立即检查是否发生火灾
{% else %}
确认是否为家庭成员活动
{% endif %}
- service: switch.turn_on
entity_id: switch.siren
- delay:
minutes: 5
- service: switch.turn_off
entity_id: switch.siren
扩展功能:可添加人脸识别条件,当检测到家庭成员时自动取消警报,避免误报。
5.2 能源管理与节能提醒
场景描述:实时监控大功率电器用电情况,当检测到异常用电或长时间待机时发送提醒,帮助用户节约能源。
实现方案:
automation:
- alias: "空调异常用电提醒"
trigger:
- platform: numeric_state
entity_id: sensor.air_conditioner_power
above: 1500
for:
minutes: 10
- platform: state
entity_id: sensor.air_conditioner_power
above: 0
for:
hours: 8
action:
service: notify.xiaomi_home_notify
data:
title: "空调用电异常提醒"
message: |
- 设备: "客厅空调"
- 异常类型: {% if trigger.platform == 'numeric_state' %}
高功率运行
{% else %}
长时间待机
{% endif %}
- 当前功率: {{ states('sensor.air_conditioner_power') }}W
- 持续时间: {% if trigger.platform == 'numeric_state' %}
{{ trigger.for.seconds // 60 }}分钟
{% else %}
{{ trigger.for.seconds // 3600 }}小时
{% endif %}
- 建议操作: {% if trigger.platform == 'numeric_state' %}
检查温度设置是否过高
{% else %}
关闭空调电源节约用电
{% endif %}
- 预计每日浪费: {% if trigger.platform == 'state' %}
{{ (states('sensor.air_conditioner_power') | float * 24 / 1000) | round(2) }}度电
{% endif %}
数据统计:通过历史数据统计可生成用电报告:
sensor:
- platform: template
sensors:
ac_daily_energy:
friendly_name: "空调每日用电量"
unit_of_measurement: "kWh"
value_template: >-
{{ (states('sensor.air_conditioner_energy') | float -
state_attr('sensor.ac_daily_energy', 'last_reset_value') | float) | round(2) }}
attributes:
last_reset_value: "{{ states('sensor.air_conditioner_energy') | float }}"
六、故障排除与优化建议
6.1 常见问题解决方案
| 问题现象 | 可能原因 | 解决方法 |
|---|---|---|
| 收不到通知 | 1. 设备未联网 2. 通知实体未正确配置 3. 权限不足 |
1. 检查设备网络连接 2. 检查notify实体是否存在 3. 验证API密钥和权限设置 |
| 通知延迟 | 1. 网络延迟 2. 设备轮询间隔过长 3. 系统负载过高 |
1. 检查网络状况 2. 减小轮询间隔(最小30秒) 3. 优化自动化条件 |
| 重复通知 | 1. 状态抖动 2. 触发器配置不当 3. 设备离线重连 |
1. 添加for条件设置延迟触发 2. 优化触发条件 3. 增加离线判断逻辑 |
6.2 性能优化建议
-
减少不必要的通知:通过合理设置触发条件和阈值,避免频繁通知
# 优化前 trigger: platform: state entity_id: sensor.temperature_sensor_temperature # 优化后 trigger: platform: state entity_id: sensor.temperature_sensor_temperature to: - "on" - "off" for: seconds: 5 -
合并相似通知:将多个同类设备的通知合并为一个综合报告
action: service: notify.xiaomi_home_notify data: title: "设备状态汇总报告" message: | {% set on_switches = states.switch | selectattr('state', 'eq', 'on') | list %} {% set low_batteries = states.sensor | selectattr('attributes.battery_level', 'lt', 20) | list %} 📊 设备状态摘要 ({{ now().strftime('%H:%M') }}) 🔌 开启的开关: {{ on_switches | length }}个 🔋 低电量设备: {{ low_batteries | length }}个 {% if low_batteries %} ⚠️ 需要更换电池: {% for device in low_batteries %} - {{ device.name }}: {{ device.attributes.battery_level }}% {% endfor %} {% endif %} -
优化状态监听:通过
miot_device.py中的unsub_device_state()方法及时取消不再需要的状态监听,减少系统资源占用。
七、总结与未来展望
Xiaomi Home Integration提供了强大而灵活的设备状态变更通知功能,通过本文介绍的模板和技巧,用户可以构建从基础状态通知到复杂场景联动的全方位智能家居监控系统。关键要点包括:
- 技术原理:基于MIoTDevice的状态订阅机制和Notify实体实现
- 核心模板:开关状态、传感器数值、安防事件三类基础模板
- 高级应用:多条件触发、内容格式化、多渠道推送
- 场景方案:家庭安防、能源管理、老人关怀三大实用场景
- 优化建议:性能优化、故障排除、用户体验提升
未来功能展望:
- AI异常检测:结合机器学习算法识别异常用电模式、行为习惯
- 语音交互通知:支持自然语言查询历史通知和设备状态
- 跨平台协同:与智能音箱、智能手表等设备深度集成
- 通知优先级管理:基于用户行为自动调整通知优先级
通过不断优化和扩展通知功能,Xiaomi Home Integration将为用户打造更加智能、安全、高效的智能家居体验。建议用户定期更新组件版本以获取最新功能和安全更新。
如果您在使用过程中遇到任何问题或有功能建议,欢迎通过项目GitHub仓库提交issue或参与社区讨论。
附录:常用实体ID与属性参考
开关类设备
switch.xiaomi_smart_plug:智能插座switch.xiaomi_light_switch:智能灯开关cover.xiaomi_curtain:窗帘电机
传感器类设备
sensor.temperature_sensor_temperature:温度传感器sensor.temperature_sensor_humidity:湿度传感器binary_sensor.motion_sensor:人体传感器binary_sensor.door_contact_sensor:门窗传感器
常用属性
state:实体状态friendly_name:友好名称unit_of_measurement:计量单位last_changed:最后状态变化时间battery_level:电池电量(百分比)signal_strength:信号强度(dB)
希望本文提供的模板和指南能帮助您充分利用Xiaomi Home Integration的状态通知功能,构建更加智能的家居环境。如有任何问题或建议,请随时与我们联系。
openvela 操作系统专为 AIoT 领域量身定制,以轻量化、标准兼容、安全性和高度可扩展性为核心特点。openvela 以其卓越的技术优势,已成为众多物联网设备和 AI 硬件的技术首选,涵盖了智能手表、运动手环、智能音箱、耳机、智能家居设备以及机器人等多个领域。
更多推荐

所有评论(0)