node-red-contrib-home-assistant-websocket
Version:
Node-RED integration with Home Assistant through websocket and REST API
2 lines (1 loc) • 2.09 kB
JavaScript
"use strict";const{merge:d}=require("lodash"),l=require("../common/errors/BaseError").default,E=require("./BaseNode"),{INTEGRATION_EVENT:c,INTEGRATION_LOADED:f,INTEGRATION_UNLOADED:u,INTEGRATION_NOT_LOADED:g}=require("../const"),m={debug:!1,config:{exposeToHomeAssistant:i=>i.exposeToHomeAssistant===void 0?!1:i.exposeToHomeAssistant}};class A extends E{constructor({node:e,config:t,RED:s,status:n,nodeOptions:r={}}){r=d({},m,r),super({node:e,config:t,RED:s,status:n,nodeOptions:r}),this.listeners={},this.registered=!1,this.integrationErrorMessage="Node-RED custom integration needs to be installed in Home Assistant for this node to function correctly.",this.status=n,this.status.init({nodeState:this.isEnabled,homeAssistant:this.homeAssistant});const o={"ha_client:close":this.onHaEventsClose,"ha_client:error":this.onHaEventsError,[c]:this.onHaIntegration};Object.entries(o).forEach(([a,h])=>this.addEventClientListener(a,h.bind(this)))}errorHanlderForEvents(e){return(...t)=>{try{e(...t)}catch(s){s instanceof l?(this.status.setFailed(s.statusMessage),this.node.error(s)):(this.status.setFailed(this.RED._("home-assistant.status.error")),this.node.error(s.message))}}}addEventClientListener(e,t){if(this.homeAssistant){const s=this.errorHanlderForEvents(t);this.listeners[e]=s,this.homeAssistant.addListener(e,s)}}removeEventClientListeners(){this.homeAssistant&&Object.entries(this.listeners).forEach(([e,t])=>{this.homeAssistant.removeListener(e,t)})}async onClose(e){super.onClose(e),this.removeEventClientListeners(),typeof this.status.destroy=="function"&&this.status.destroy()}onHaEventsClose(){this.registered=!1}onHaEventsError(e){e&&e.message&&this.node.error(e.message)}onHaIntegration(e){switch(e){case f:this.registerEntity();break;case u:case g:this.registered=!1;break}}registerEntity(){if(this.nodeConfig.exposeToHomeAssistant===!1)return!1;if(!this.isIntegrationLoaded)return(this.node.type==="ha-webhook"||this.node.type==="ha-entity")&&(this.node.error(this.integrationErrorMessage),this.status.setFailed("Error")),!1;if(this.registered)return!1}}module.exports=A;