forked from iobroker-community-adapters/ioBroker.shelly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshelly.js
executable file
·260 lines (240 loc) · 8.46 KB
/
shelly.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
/* jshint -W097 */
/* jshint -W030 */
/* jshint strict:true */
/* jslint node: true */
/* jslint esversion: 6 */
'use strict';
const utils = require('@iobroker/adapter-core');
const objectHelper = require('@apollon/iobroker-tools').objectHelper; // Get common adapter utils
const mqttServer = require(__dirname + '/lib/mqtt');
const coapServer = require(__dirname + '/lib/coap');
const adapterName = require('./package.json').name.split('.').pop();
const ping = require('ping');
const tcpp = require('tcp-ping');
const events = require('events');
const eventEmitter = new events.EventEmitter();
let pollTimeout = null;
let adapter;
function decrypt(key, value) {
let result = '';
for (let i = 0; i < value.length; ++i) {
result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i));
}
return result;
}
/**
* Change the external Sentry Logging. After changing the Logging
* the adapter restarts once
* @param {*} id : adapter.config.sentry_enable for example
*/
async function setSentryLogging(value) {
try {
value = value === true;
let idSentry = 'system.adapter.' + adapter.namespace + '.plugins.sentry.enabled';
let stateSentry = await adapter.getForeignStateAsync(idSentry);
if (stateSentry && stateSentry.val !== value) {
await adapter.setForeignStateAsync(idSentry, value);
adapter.log.info('Restarting Adapter because of changeing Sentry settings');
adapter.restart();
return true;
}
} catch (error) {
return false;
}
return false;
}
function startAdapter(options) {
options = options || {};
options.name = adapterName;
adapter = new utils.Adapter(options);
adapter.on('unload', (callback) => {
if (pollTimeout) {
clearTimeout(pollTimeout);
pollTimeout = null;
}
try {
adapter.log.info('Closing Adapter');
callback();
} catch (e) {
// adapter.log.error('Error');
callback();
}
});
adapter.on('message', (msg) => {
adapter.sendTo(msg.from, msg.command, 'Execute command ' + msg.command, msg.callback);
});
adapter.on('stateChange', (id, state) => {
// Warning, state can be null if it was deleted
if (state && !state.ack) {
let stateId = id.replace(adapter.namespace + '.', '');
adapter.log.debug('stateChange ' + id + ' ' + JSON.stringify(state));
adapter.log.debug('stateChange ' + id + ' = ' + state.val);
objectHelper.handleStateChange(id, state);
if (stateId === 'info.update') {
eventEmitter.emit('onFirmwareUpdate');
}
}
});
adapter.on('ready', async () => {
try {
adapter.config.polltime = Number(adapter.config.polltime) || 5;
adapter.log.info('Starting Adapter ' + adapter.namespace + ' in version ' + adapter.version);
adapter.log.info('Polltime of the shelly devices: ' + adapter.config.polltime + ' sec.');
if (await setSentryLogging(adapter.config.sentry_enable)) return;
await migrateconfig();
await encryptPasswords();
await main();
} catch (error) {
// ...
}
});
return adapter;
}
process.on('SIGINT', () => {
adapter.terminate ? adapter.terminate() : process.exit();
});
process.on('uncaughtException', (err) => {
console.log('Exception: ' + err + '/' + err.toString());
console.log(err.message);
console.log(err.stack);
if (adapter && adapter.log) {
adapter.log.error('Exception: ' + err);
adapter.log.error('Exception: ' + err.message);
adapter.log.error('Exception: ' + err.stack);
}
process.exit();
// adapter.terminate ? adapter.terminate() : process.exit();
});
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function getAllDevices() {
let ids = [];
try {
let objs = await adapter.getAdapterObjectsAsync();
for (let id in objs) {
let obj = objs[id];
if (id && id.endsWith('.online') && obj && obj.type === 'state') {
ids.push(id);
}
}
} catch (error) { /* */ }
return ids;
}
async function onlineCheck() {
if (pollTimeout) {
clearTimeout(pollTimeout);
}
try {
let idsOnline = await getAllDevices();
for (let i in idsOnline) {
let idOnline = idsOnline[i];
let idParent = idOnline.split('.').slice(0, -1).join('.');
let idHostname = idParent + '.hostname';
let stateHostaname = await adapter.getStateAsync(idHostname);
let valHostname = stateHostaname ? stateHostaname.val : undefined;
let valPort = 80;
if (valHostname) {
/*
ping.sys.probe(valHostname, async (isAlive) => {
let hostname = valHostname;
let oldState = await adapter.getStateAsync(idOnline);
let oldValue = oldState && oldState.val ? oldState.val === 'true' || oldState.val === true : false;
if (oldValue != isAlive)
await adapter.setStateAsync(idOnline, { val: isAlive, ack: true });
});
*/
tcpp.probe(valHostname, valPort, async (error, isAlive) => {
let hostname = valHostname;
let oldState = await adapter.getStateAsync(idOnline);
let oldValue = oldState && oldState.val ? oldState.val === 'true' || oldState.val === true : false;
if (oldValue != isAlive)
await adapter.setStateAsync(idOnline, { val: isAlive, ack: true });
});
}
}
} catch (error) { /* */ }
pollTimeout = setTimeout(() => {
pollTimeout = null;
onlineCheck();
}, adapter.config.polltime * 1000);
}
async function encryptPasswords() {
return new Promise((resolve, reject) => {
adapter.getForeignObject('system.config', (err, obj) => {
if (err) reject(err);
if (adapter.config.mqttpassword) {
if (obj && obj.native && obj.native.secret) {
//noinspection JSUnresolvedVariable
adapter.config.mqttpassword = decrypt(obj.native.secret, adapter.config.mqttpassword);
} else {
//noinspection JSUnresolvedVariable
adapter.config.mqttpassword = decrypt('Zgfr56gFe87jJOM', adapter.config.mqttpassword);
}
}
if (adapter.config.httppassword) {
if (obj && obj.native && obj.native.secret) {
//noinspection JSUnresolvedVariable
adapter.config.httppassword = decrypt(obj.native.secret, adapter.config.httppassword);
} else {
//noinspection JSUnresolvedVariable
adapter.config.httppassword = decrypt('Zgfr56gFe87jJOM', adapter.config.httppassword);
}
}
resolve();
});
});
}
async function migrateconfig() {
let native = {};
if (adapter.config.http_username) {
native.httpusername = adapter.config.http_username;
native.http_username = '';
}
if (adapter.config.http_password) {
native.httppassword = adapter.config.http_password;
native.http_password = '';
}
if (adapter.config.user) {
native.mqttusername = adapter.config.user;
native.user = '';
}
if (adapter.config.password) {
native.mqttpassword = adapter.config.password;
native.password = '';
}
if (Object.keys(native).length) {
adapter.log.info('Migrate some data from old Shelly Adapter version. Restarting Shelly Adapter now!');
await adapter.extendForeignObjectAsync('system.adapter.' + adapter.namespace, { native: native });
}
}
async function main() {
onlineCheck();
adapter.setState('info.connection', { val: true, ack: true });
adapter.subscribeStates('*');
objectHelper.init(adapter);
let protocol = adapter.config.protocol || 'coap';
setImmediate(() => {
if (protocol === 'both' || protocol === 'mqtt') {
adapter.log.info('Starting Shelly adapter in MQTT modus. Listening on ' + adapter.config.bind + ':' + adapter.config.port);
if (!adapter.config.mqttusername || adapter.config.mqttusername.length === 0) { adapter.log.error('MQTT Username is missing!'); }
if (!adapter.config.mqttpassword || adapter.config.mqttpassword.length === 0) { adapter.log.error('MQTT Password is missing!'); }
let serverMqtt = new mqttServer.MQTTServer(adapter, objectHelper, eventEmitter);
serverMqtt.listen();
}
});
setImmediate(() => {
if (protocol === 'both' || protocol === 'coap') {
adapter.log.info('Starting Shelly adapter in CoAP modus.');
let serverCoap = new coapServer.CoAPServer(adapter, objectHelper, eventEmitter);
serverCoap.listen();
}
});
}
// If started as allInOne mode => return function to create instance
if (typeof module !== 'undefined' && module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}