homeassistant主动推送信息

homeassistant推送信息


问题背景:

前端刚启动时,会向云端发送获取硬件信息的请求,然后云端再调用homeassistant的rest api请求这些信息,再把信息发回前端。
但是这样有个问题,前端收到信息后,这些信息不会再发生变化,比如温度计的信息,可能前端获取到的温度是25度,但是过了1个小时,温度变成了27度,那么前端如果不重新启动就不能获取这个信息。
所以希望homeassistant内部或者其控制的硬件发生变化后,能够主动向云端发送这个变化信息。

解决方法:

幸运的是,homeassistant本身就提供了这个接口,它有一个notify组件能实现这个功能。
notify组件位置在(这是在我电脑上的位置)
E:\Anaconda3\Lib\site-packages\homeassistant\components\notify

在notify文件夹下增加一个文件sampleNotify.py

import requests
import logging

import voluptuous as vol

from homeassistant.components.notify import (ATTR_TARGET, ATTR_TITLE, PLATFORM_SCHEMA, BaseNotificationService)
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)
CONF_FROM_SOURCE = "from_source"


PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_FROM_SOURCE): cv.string,
})



def get_service(hass, config, discovery_info=None):
    return SmartHomeNotificationService(config[CONF_FROM_SOURCE])


class SmartHomeNotificationService(BaseNotificationService):
    def __init__(self, from_source):
        self.from_source = from_source

    def send_message(self, message="", **kwargs):
        receivers = kwargs.get(ATTR_TARGET)
        title = kwargs.get(ATTR_TITLE)
        try:
            for receiver in receivers:
                _LOGGER.info("已发送")

                data = {
                    "source": self.from_source,
                    "receiver": receiver,
                    "content": message,
                    "title": title
                }
                _LOGGER.info(data)
                requests.post(
                    // 注意这里需要修改成你服务器的api
                    "http://1.2.3.4:8989/a/b/notify",
                    data=data
                )

        except ConnectionError:
            _LOGGER.error("连接失败")

使用方式:
1.在configuration.yaml文件中加入sampleNotify

notify:
  - name: sample
    platform: sampleNotify
    from_source: '发送方身份标识'

注:sampleNotify是我们刚才在notify文件加下加入的sampleNotify.py的名字

2.在automations.yaml中加入

- alias: notify publish
  trigger:
    platform: homeassistant
    event: start
  action:
    service: notify.my_notify
    data:
      title: '题目'
      message: 'homeassistant start'
      target: '接收方身份标识'

这样在homeassistant启动后,云端就会收到homeassistant start这个信息

参考:
https://www.jianshu.com/p/1157057b97a6

猜你喜欢

转载自blog.csdn.net/sgafpzys/article/details/80849533