forked from hobbyquaker/homematic-rega
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
391 lines (357 loc) · 11.9 KB
/
index.js
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
const fs = require('fs');
const path = require('path');
const tempDir = require('temp-dir');
const request = require('request');
const iconv = require('iconv-lite');
const parseXml = require('xml2js').parseString;
class Rega {
/**
* @param {object} options
* @param {string} options.host - hostname or IP address of the Homematic CCU
* @param {string} [options.language=de] - language used for translation of placeholders in variables/rooms/functions
* @param {boolean} [options.disableTranslation=false] - disable translation of placeholders
* @param {boolean} [options.tls=false] - Connect using TLS
* @param {boolean} [options.inSecure=false] - Ignore invalid TLS Certificates
* @param {boolean} [options.auth=false] - Use Basic Authentication
* @param {string} [options.user] - Auth Username
* @param {string} [options.pass] - Auth Password
* @param {number} [options.port=8181] - rega remote script port. Defaults to 48181 if options.tls is true
*/
constructor(options) {
this.language = options.language || 'de';
this.disableTranslation = options.disableTranslation;
this.host = options.host;
this.tls = options.tls;
this.port = options.port || (this.tls ? 48181 : 8181);
this.inSecure = options.inSecure;
this.auth = options.auth;
this.user = options.user;
this.pass = options.pass;
this.url = (this.tls ? 'https' : 'http') + '://' + this.host + ':' + this.port + '/rega.exe';
this.encoding = 'iso-8859-1';
this.requestOptions = {
method: 'POST',
url: this.url,
encoding: null
};
if (this.auth) {
this.requestOptions.auth = {
user: this.user,
pass: this.pass,
sendImmediately: true
};
}
if (this.tls) {
this.requestOptions.strictSSL = !this.inSecure;
}
}
/**
* @callback Rega~scriptCallback
* @param {?Error} err
* @param {string} output - the scripts output
* @param {Object.<string, string>} variables - contains all variables that are set in the script (as strings)
*/
_parseResponse(res, callback) {
const ERROR_XML_MISSING = new Error('xml in rega response missing');
if (res) {
const outputEnd = res.lastIndexOf('<xml>');
if (outputEnd === -1) {
callback(ERROR_XML_MISSING);
} else {
const output = res.slice(0, outputEnd);
const xml = res.slice(outputEnd);
if (xml) {
parseXml(xml, {explicitArray: false}, (err, res) => {
if (err) {
callback(err, output);
} else if (res) {
callback(null, output, res.xml);
} else {
callback(ERROR_XML_MISSING);
}
});
} else {
callback(ERROR_XML_MISSING);
}
}
} else {
callback(new Error('empty rega response'));
}
}
/**
* Execute a rega script
* @method Rega#exec
* @param {string} script - string containing a rega script
* @param {Rega~scriptCallback} [callback]
*/
exec(script, callback) {
if (typeof callback !== 'function') {
callback = () => {};
}
script = iconv.encode(script, this.encoding);
request(Object.assign(this.requestOptions, {
body: script,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': script.length
}
}), (err, res, body) => {
if (!err && body) {
if (res.statusCode === 401) {
callback(new Error('401 Unauthorized'));
} else {
body = iconv.decode(body, this.encoding);
this._parseResponse(body, callback);
}
} else {
callback(err);
}
});
}
/**
* Execute a rega script from a file
* @method Rega#script
* @param {string} file - path to script file
* @param {Rega~scriptCallback} [callback]
*/
script(file, callback) {
// TODO cache files
fs.readFile(file, (err, res) => {
if (err) {
if (typeof callback === 'function') {
callback(err);
}
} else {
this.exec(res.toString(), callback);
}
});
}
_jsonScript(file, callback) {
this.script(file, (err, res) => {
if (err) {
callback(err);
} else {
try {
callback(null, JSON.parse(res));
} catch (_) {
const debugFile = path.join(tempDir, path.basename(file) + '.failed.json');
fs.writeFile(debugFile, res, () => {});
callback(new Error('JSON.parse failed. Saved debug data to ' + debugFile));
}
}
});
}
/**
* Get all devices and channels
* @method Rega#getChannels
* @param {Rega~channelCallback} callback
*/
getChannels(callback) {
this._jsonScript(path.join(__dirname, 'scripts', 'channels.rega'), (err, res) => {
if (err) {
callback(err, res);
} else {
res.forEach((channel, index) => {
channel.name = unescape(channel.name);
res[index] = channel;
});
callback(null, res);
}
});
}
/**
* Get all devices and channels values
* @method Rega#getValues
* @param {Rega~valuesCallback} callback
*/
getValues(callback) {
this._jsonScript(path.join(__dirname, 'scripts', 'values.rega'), (err, res) => {
if (err) {
callback(err, res);
} else {
res.forEach((ch, index) => {
ch.name = unescape(ch.name);
if (typeof ch.value === 'string') {
ch.value = unescape(ch.value);
}
res[index] = ch;
});
callback(null, res);
}
});
}
/**
* Get all programs
* @method Rega#getPrograms
* @param {Rega~programsCallback} callback
*/
getPrograms(callback) {
this._jsonScript(path.join(__dirname, 'scripts', 'programs.rega'), (err, res) => {
if (err) {
callback(err, res);
} else {
res.forEach((prg, index) => {
prg.name = unescape(prg.name);
prg.info = unescape(prg.info);
res[index] = prg;
});
callback(null, res);
}
});
}
_getTranslations(callback) {
const url = 'http://' + this.host + '/webui/js/lang/' + this.language + '/translate.lang.extension.js';
this.translations = {};
request({
method: 'GET',
url,
encoding: null
}, (err, res, body) => {
if (!err && body) {
this._parseTranslations(iconv.decode(body, this.encoding));
}
callback();
});
}
_parseTranslations(body) {
const lines = body.split('\n');
lines.forEach(line => {
const match = line.match(/\s*"((func|room|sysVar)[^"]+)"\s*:\s*"([^"]+)"/);
if (match) {
this.translations[match[1]] = unescape(match[3]); // TODO replace deprecated unescape
}
});
}
_translate(item) {
if (!this.disableTranslation) {
let key = item;
if (key.startsWith('${') && key.endsWith('}')) {
key = key.slice(2, item.length - 3);
}
if (this.translations[key]) {
item = this.translations[key];
}
}
return item;
}
_translateNames(res) {
if (!this.disableTranslation) {
Object.keys(res).forEach(id => {
const obj = res[id];
obj.name = this._translate(unescape(obj.name));
if (obj.info) {
obj.info = this._translate(unescape(obj.info));
}
});
}
return res;
}
_translateEnum(values) {
if (!this.disableTranslation) {
values.forEach((val, i) => {
values[i] = this._translate(val);
});
}
return values;
}
_translateJsonScript(file, callback) {
if (this.translations || this.disableTranslation) {
this._jsonScript(file, (err, res) => {
if (err) {
callback(err);
} else {
callback(null, this.disableTranslation ? res : this._translateNames(res));
}
});
} else {
this._getTranslations(() => {
this._translateJsonScript(file, callback);
});
}
}
/**
* Get all variables
* @method Rega#getVariables
* @param {Rega~variablesCallback} callback
*/
getVariables(callback) {
this._translateJsonScript(path.join(__dirname, 'scripts', 'variables.rega'), (err, res) => {
if (err) {
callback(err);
} else {
res.forEach((sysvar, index) => {
if (sysvar.type === 'string') {
sysvar.val = unescape(sysvar.val);
}
if (sysvar.enum === '') {
sysvar.enum = [];
} else {
sysvar.enum = this._translateEnum(unescape(sysvar.enum).split(';'));
}
res[index] = sysvar;
});
callback(null, res);
}
});
}
/**
* Get all rooms
* @method Rega#getRooms
* @param {Rega~roomsCallback} callback
*/
getRooms(callback) {
this._translateJsonScript(path.join(__dirname, 'scripts', 'rooms.rega'), callback);
}
/**
* Get all functions
* @method Rega#getFunctions
* @param {Rega~functionsCallback} callback
*/
getFunctions(callback) {
this._translateJsonScript(path.join(__dirname, 'scripts', 'functions.rega'), callback);
}
/**
* Set a variables value
* @method Rega#setVariable
* @param {number} id
* @param {number|boolean|string} val
* @param {function} [callback]
*/
setVariable(id, val, callback) {
const script = 'dom.GetObject(' + id + ').State(' + JSON.stringify(val) + ');';
this.exec(script, callback);
}
/**
* Execute a program
* @method Rega#startProgram
* @param {number} id
* @param {function} [callback]
*/
startProgram(id, callback) {
const script = 'dom.GetObject(' + id + ').ProgramExecute();';
this.exec(script, callback);
}
/**
* Activate/Deactivate a program
* @method Rega#setProgram
* @param {number} id
* @param {boolean} active
* @param {function} [callback]
*/
setProgram(id, active, callback) {
const script = 'dom.GetObject(' + id + ').Active(' + Boolean(active) + ');';
this.exec(script, callback);
}
/**
* Rename an object
* @method Rega#setName
* @param {number} id
* @param {string} name
* @param {function} [callback]
*/
setName(id, name, callback) {
const script = 'dom.GetObject(' + id + ').Name("' + name + '");';
this.exec(script, callback);
}
}
module.exports = Rega;