forked from wonderslug/MMM-HomeAssistantDisplay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_helper.js
More file actions
218 lines (200 loc) · 5.69 KB
/
node_helper.js
File metadata and controls
218 lines (200 loc) · 5.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/* Magic Mirror
* Node Helper: MMM-HomeAssistantDisplay
*
* By Brian Towles
* MIT Licensed.
*/
var backoff = require('backoff')
const NodeHelper = require("node_helper");
const HomeAssistant = require("homeassistant");
const HomeAssistantWS = require("homeassistant-ws");
const Logger = require("./helpers/Logger");
util = require('util'),
module.exports = NodeHelper.create({
start,
stop,
socketNotificationReceived,
connect,
reconnectWebsocket,
connectWebsocket,
buildHttpUrl,
onStateChangedEvent,
evaluateTemplate,
onWebsocketCloseEvent,
backoffWSConnection,
});
function start() {
this.logger = new Logger(this.name);
if (config.debuglogging) {
this.logger.debug("MMM-HomeAssistantDisplay helper started...");
}
this.connections = {};
}
function stop() {
for (const connection in this.connections) {
this.connections[connection].websocket.unsubscribeFromEvent("state_changed");
}
}
function socketNotificationReceived(notification, payload) {
if (config.debuglogging) {
this.logger.debug(`Recieved notification ${notification}`, payload);
}
if (notification !== "CONNECT" && (!payload.identifier || !this.connections[payload.identifier])) {
this.logger.error(`No connection for ${payload.identifier} found`);
return;
}
switch (notification) {
case "CONNECT":
this.connect(payload);
break;
case "RECONNECT_WS":
this.reconnectWebsocket(payload);
break;
case "SET_WATCHED_ENTITY":
if (!this.connections[payload.identifier].entities.includes(payload.entity)) {
if (config.debuglogging) {
this.logger.debug(`Registering entity ${payload.entity}`);
}
this.connections[payload.identifier].entities.push(payload.entity);
}
break;
case "RENDER_MODULE_DISPLAY_TEMPLATE":
this.evaluateTemplate(payload).then((ret) => {
this.sendSocketNotification("MODULE_DISPLAY_RENDERED", ret);
}).catch((err) => {
this.logger.error(
"Unable to evaluate template",
err
);
});
break;
case "RENDER_SECTION_DISPLAY_TEMPLATE":
this.evaluateTemplate(payload).then((ret) => {
this.sendSocketNotification("SECTION_DISPLAY_RENDERED", {
...ret,
section: payload.section
});
}).catch((err) => {
this.logger.error(
"unable to evaluate section template",
err
);
});
break;
}
}
async function evaluateTemplate(payload) {
if (config.debuglogging) {
this.logger.debug(`Evaluating template for ${payload.template}`);
}
const hass = this.connections[payload.identifier].hass;
const response = await hass.templates.render(payload.template);
return {
identifier: payload.identifier,
render: response
}
}
function buildHttpUrl(config) {
if (config.useTLS){
schema = "https"
}
else {
schema = "http"
}
var url = `${schema}://${config.host}`;
return url;
}
async function connect(payload) {
const connectionConfig = {
host: payload.host,
port: payload.port,
token: payload.token,
ignoreCert: payload.ignoreCert,
useTLS: payload.useTLS,
};
const hass = new HomeAssistant({...connectionConfig, host: this.buildHttpUrl(connectionConfig)});
this.logger.info(`HomeAssistant connected for ${payload.identifier}`);
this.connections[payload.identifier] = {
hass,
entities: []
};
await this.backoffWSConnection(payload.identifier, connectionConfig)
}
async function backoffWSConnection(identifier, connectionConfig) {
self = this;
var call = backoff.call(this.connectWebsocket, this, identifier, connectionConfig, function(err, res) {
if (err) {
self.logger.info(`Unable to connect to Home Assistant for ${identifier}: ` + err.message);
} else {
self.logger.info(`Conected to Home Assistant for ${identifier} after ${call.getNumRetries()} retries`);
}
});
call.retryIf(function(err) {
return true;
});
call.setStrategy(new backoff.ExponentialStrategy({
initialDelay: 10,
maxDelay: 10000
}));
call.start();
}
function connectWebsocket(obj, identifier, connectionConfig, callback) {
var self = obj;
HomeAssistantWS.default({
...connectionConfig,
protocol: ((connectionConfig.useTLS) ? "wss" : "ws")
})
.then((hassWs) => {
self.connections[identifier].websocket = hassWs;
hassWs.on("state_changed", onStateChangedEvent.bind(self));
hassWs.on("ws_close", onWebsocketCloseEvent.bind(self));
callback(null, hassWs);
})
.catch((err) => {
self.logger.error(
`Unable to connect to Home Assistant for module ${identifier} failed with message: `,
err.message
);
callback(err, null);
});
return;
}
async function reconnectWebsocket(payload) {
const connectionConfig = {
host: payload.host,
port: payload.port,
token: payload.token,
useTLS: payload.useTLS,
ignoreCert: payload.ignoreCert
};
for (const connection in this.connections) {
if (connection == payload.identifier){
this.logger.info(`Reconnecting to Home Assistant websocket for ${payload.identifier}`);
await this.backoffWSConnection(payload.identifier, connectionConfig)
}
}
}
function onStateChangedEvent(event) {
if (config.debuglogging) {
this.logger.debug(`Got state change for ${event.data.entity_id}`);
}
for (const connection in this.connections) {
if (this.connections[connection].entities.includes(event.data.entity_id)) {
this.logger.debug(`Found listening connection (${connection}) for entity ${event.data.entity_id}`);
this.sendSocketNotification("CHANGED_STATE", {
identifier: connection,
cause: event.data.entity_id,
});
}
}
}
function onWebsocketCloseEvent(event) {
for (const connection in this.connections) {
if (event.target == this.connections[connection].websocket.rawClient.ws) {
this.logger.debug(`Hass WS Disconnected (${connection})`);
this.sendSocketNotification("HASSWS_DISCONNECTED", {
identifier: connection,
});
}
}
}