介绍
node-red-contrib-home-assistant-ws 是一个基于 Home Assistant 的 WebSocket 通信的 Node-RED 插件。通过使用该插件,可以方便地实现 Node-RED 和 Home Assistant 之间的实时通信,以及与 Home Assistant 中的实体进行交互。
安装
在安装该插件之前,需要确保已经成功安装了 Node-RED 和 Home Assistant,并且两者均已启动运行。
使用 npm 包管理器进行安装,可以通过以下命令来安装 node-red-contrib-home-assistant-ws:
npm install node-red-contrib-home-assistant-ws
使用
连接 Home Assistant WebSocket
在 Node-RED 的流程中拖入 "ha-ws-connection" 节点,并配置好 Home Assistant 的 WebSocket 地址、Websocket API 密钥,以及自定义的节点 ID。
# 节点配置 - WebSocket 地址:ws://localhost:8123/api/websocket - Websocket API 密钥:Your Home Assistant API key - 自定义节点 ID:my-ha-ws-connection
订阅实体事件
在 Node-RED 的流程中拖入 "ha-ws-entity" 节点,并配置好要订阅的实体 ID、节点 ID,以及需要监听的事件类型。
# 节点配置 - 实体 ID:sensor.my_temperature - 节点 ID:my-ha-ws-connection - 事件类型:state_changed
发送服务调用
在 Node-RED 的流程中拖入 "ha-ws-service" 节点,并配置好要调用的服务、节点 ID,以及服务所需的参数。
# 节点配置 - 服务:light.turn_on - 节点 ID:my-ha-ws-connection - 服务参数:{"entity_id": "light.bedroom", "brightness": 100}
示例代码
可以通过以下代码示例来了解如何在 Node-RED 中使用 node-red-contrib-home-assistant-ws 插件:
[{"id":"632d54bc.0bea9c","type":"ha-ws-connection","z":"c7bee604.524e3","name":"","server":"ws://localhost:8123/api/websocket","authToken":"Your Home Assistant API key","protocolVersion":"1.1","eventInterval":"0","clockInterval":"0","timeout":"10","retryDelay":"5","debugoutput":false,"outputs":2,"x":90,"y":100,"wires":[["5fadd14a.3cc9ac"],["20d574ce.09395a"]]},{"id":"20d574ce.09395a","type":"debug","z":"c7bee604.524e3","name":"","active":true,"console":"false","complete":"false","x":450,"y":100,"wires":[]},{"id":"5fadd14a.3cc9ac","type":"ha-ws-entity","z":"c7bee604.524e3","server":"632d54bc.0bea9c","name":"","entityId":"sensor.my_temperature","eventType":"state_changed","outputInitialValue":false,"sendAllEvents":false,"x":290,"y":160,"wires":[["20d574ce.09395a"]]},{"id":"9d415912.0d14d","type":"inject","z":"c7bee604.524e3","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":90,"y":160,"wires":[["5fadd14a.3cc9ac"]]},{"id":"8bbf24ae.7e696","type":"ha-ws-service","z":"c7bee604.524e3","server":"632d54bc.0bea9c","name":"","serviceDomain":"light","service":"turn_on","entityId":"light.bedroom","payload":"{\"brightness\":100}","outputOnPayload":true,"x":300,"y":220,"wires":[["20d574ce.09395a"]]},{"id":"361dfca6.0ed016","type":"inject","z":"c7bee604.524e3","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":90,"y":220,"wires":[["8bbf24ae.7e696"]]},{"id":"e70a9a9a.291d4","type":"comment","z":"c7bee604.524e3","name":"Home Assistant WebSocket Plugin Demo","info":"","x":170,"y":60,"wires":[]}]
总结
通过使用 node-red-contrib-home-assistant-ws 插件,可以方便地实现 Node-RED 和 Home Assistant 之间的实时通信,以及与 Home Assistant 中的实体进行交互。无论是简单的实体状态订阅,还是服务调用,都可以通过该插件轻松完成。希望本文对您有所帮助。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/60055d1e81e8991b448dabec