node-red-contrib-home-assistant-websocket
Version:
Node-RED integration with Home Assistant through websocket and REST API
2 lines (1 loc) • 4.58 kB
JavaScript
"use strict";var x=Object.create;var l=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty;var E=(s,t)=>{for(var i in t)l(s,i,{get:t[i],enumerable:!0})},v=(s,t,i,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of O(t))!R.call(s,o)&&o!==i&&l(s,o,{get:()=>t[o],enumerable:!(a=T(t,o))||a.enumerable});return s};var p=(s,t,i)=>(i=s!=null?x(D(s)):{},v(t||!s||!s.__esModule?l(i,"default",{value:s,enumerable:!0}):i,s)),P=s=>v(l({},"__esModule",{value:!0}),s);var j={};E(j,{default:()=>C});module.exports=P(j);var I=require("lodash"),A=p(require("selectn")),N=p(require("../../common/controllers/InputOutputController")),y=p(require("../../common/errors/InputError")),S=p(require("../../common/errors/NoConnectionError")),w=require("../../common/services/InputService"),b=require("../../const"),m=require("../../globals"),_=require("../../helpers/mustache"),k=require("../../helpers/utils"),g=require("./const");class C extends N.default{#t=[];#e=!1;#i=!1;async onInput({message:t,parsedMessage:i,send:a,done:o}){if(!this.homeAssistant.websocket.isConnected&&this.node.config.queue===g.Queue.None)throw new S.default;const e=this.homeAssistant.websocket.getStates(),c=(0,_.generateRenderTemplate)(t,this.node.context(),e);let r=i.action.value;i.action.source===w.DataSource.Transformed?this.#e||(this.#e=!0,this.node.warn(m.RED._("ha-action.error.domain_service_deprecated"))):i.action.source===w.DataSource.Config&&(r=c(r));const[n,f]=r.toLowerCase().split(".");if(!n||!f)throw new y.default(["ha-action.error.invalid_action_format",{action:r}]);const d=this.#a(i.target.value,t),h=await this.#r((0,A.default)("payload.data",t),t,c);i.action?.value&&typeof d.entity_id=="string"&&this.homeAssistant.websocket.getServices()[n]?.[f]?.fields?.entity_id!==void 0&&!h.entity_id&&(this.#i||(this.#i=!0,this.node.warn(m.RED._("ha-action.error.entity_id_target_data"))),h.entity_id=d.entity_id,d.entity_id=void 0);const u={domain:n,service:f,data:Object.keys(h).length?h:void 0,target:d,message:t,done:o,send:a};if(!this.homeAssistant.isConnected){switch(this.node.config.queue){case g.Queue.First:this.#t.length===0&&(this.#t=[u]);break;case g.Queue.All:this.#t.push(u);break;case g.Queue.Last:this.#t=[u];break}this.node.debug(`Queueing: ${JSON.stringify({domain:n,service:f,target:d,data:h})}`),this.status.setText(`${this.#t.length} queued`);return}await this.#o(u)}async onClientReady(){for(;this.#t.length;){const t=this.#t.pop();t&&await this.#o(t)}}#s(t){try{return JSON.parse(t)}catch{throw new y.default(["ha-action.error.invalid_json",{json:t}])}}#n(t){return typeof t=="object"&&!Array.isArray(t)&&t!==void 0&&t!==null}async#r(t={},i,a){let o={};if(this.node.config.data.length)switch(this.node.config.dataType){case b.TypedInputTypes.JSONata:o=await this.jsonataService.evaluate(this.node.config.data,{message:i});break;case b.TypedInputTypes.JSON:o=this.#s(a(this.node.config.data,this.node.config.mustacheAltTags));break}let e={};if(this.node.config.mergeContext){const c=this.node.context(),r=c.flow.get(this.node.config.mergeContext),n=c.global.get(this.node.config.mergeContext);this.#n(n)&&(e=n),this.#n(r)&&(e={...e,...r})}return this.node.config.blockInputOverrides?{...o,...e}:{...o,...e,...t}}#a(t,i){const a=(0,_.generateRenderTemplate)(i,this.node.context(),this.homeAssistant.websocket.getStates()),o={floorId:"floor_id",areaId:"area_id",deviceId:"device_id",entityId:"entity_id",labelId:"label_id"},e={};for(const r in o){const n=o[r],f=this.node.config[r];e[n]=f?[...f]:void 0,Array.isArray(e[n])?e[n].length===0?e[n]=void 0:(e[n].forEach((d,h)=>{e[n][h]=(0,k.isNodeRedEnvVar)(d)?m.RED.util.evaluateNodeProperty(d,"env",this.node,i):a(d)}),e[n].length===1&&(e[n]=e[n][0])):e[n]!==void 0&&(e[n]=a(e[n]),n==="entity_id"&&(e.entity_id=e.entity_id.reduce((d,h)=>d.concat(h.indexOf(",")?h.split(",").map(u=>u.trim()):h),[])))}const c=(0,I.merge)(e,t);return Object.keys(c).forEach(r=>c[r]===void 0&&delete c[r]),c}async#o(t){const{domain:i,service:a,data:o,message:e,target:c,done:r,send:n}=t;this.status.setSending();const f={domain:i,service:a,target:c,data:o};this.debugToClient(f),this.node.debug(`Calling Service: ${JSON.stringify(f)}`);const d=await this.homeAssistant.websocket.callService(i,a,o,c);this.status.setSuccess(["ha-action.status.action_called",{domain:i,service:a}]),await this.setCustomOutputs(this.node.config.outputProperties,e,{config:this.node.config,data:{domain:i,service:a,data:o,target:c},results:d?.response}),n(e),r()}}