-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.js
More file actions
206 lines (186 loc) · 6.87 KB
/
main.js
File metadata and controls
206 lines (186 loc) · 6.87 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
'use strict';
const utils = require('@iobroker/adapter-core');
const objectHelper = require('@apollon/iobroker-tools').objectHelper;
const BaseClient = require('./lib/protocol/udp4').BaseClient;
const BaseServer = require('./lib/protocol/udp4').BaseServer;
const adapterName = require('./package.json').name.split('.').pop();
const tcpPing = require('tcp-ping');
class Refoss extends utils.Adapter {
/**
* @param [options] Adapter options
*/
constructor(options) {
super({
...options,
name: adapterName,
});
this.isUnloaded = false;
this.baseClient = null;
this.baseServer = null;
this.onlineCheckTimeout = null;
this.onlineDevices = {};
this.cachedDevices = [];
this.on('ready', this.onReady.bind(this));
// this.on('objectChange', this.onObjectChange.bind(this));
// this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
}
async onReady() {
try {
objectHelper.init(this);
await this.initOnlineStatus();
await this.onlineStatusCheck();
this.setTimeout(async () => {
// Create UDP broadcast
this.clientServer = new BaseClient(this);
const devices = await this.getDevicesAsync();
this.server = new BaseServer(this, objectHelper, devices);
}, 100);
} catch (error) {
this.log.error(error.toString());
}
}
/**
* @param callback onUnload callback
*/
async onUnload(callback) {
this.isUnloaded = true;
if (this.onlineCheckTimeout) {
this.clearTimeout(this.onlineCheckTimeout);
this.onlineCheckTimeout = null;
}
this.initOnlineStatus();
try {
if (this.clientServer) {
this.clientServer.destroy();
}
if (this.server) {
await this.server.destroy();
}
callback();
} catch (e) {
this.log.error(e.toString());
callback();
}
}
async initOnlineStatus() {
await this.getAllDeviceIds();
for (const deviceId of this.cachedDevices) {
const idOnline = `${deviceId}.online`;
const stateHostname = await this.getStateAsync(`${deviceId}.hostname`);
const valHostname = stateHostname ? stateHostname.val : undefined;
let isAlive = false;
if (valHostname) {
// Wrap tcpPing.probe with Promise
isAlive = await new Promise(resolve => {
tcpPing.probe(valHostname, 80, (error, alive) => {
resolve(alive);
});
});
}
await this.setStateAsync(idOnline, { val: isAlive, ack: true });
if (isAlive) {
this.onlineDevices[deviceId] = true;
}
}
// Update connection status
const onlineDeviceCount = Object.keys(this.onlineDevices).length;
await this.setStateAsync('info.connection', { val: onlineDeviceCount > 0, ack: true });
}
/**
* Online-Check TCP ping
*/
async onlineStatusCheck() {
const valPort = 80;
if (this.onlineCheckTimeout) {
this.clearTimeout(this.onlineCheckTimeout);
this.onlineCheckTimeout = null;
}
try {
for (const deviceId of this.cachedDevices) {
const stateHostaname = await this.getStateAsync(`${deviceId}.hostname`);
const valHostname = stateHostaname ? stateHostaname.val : undefined;
if (valHostname) {
this.log.debug(`[onlineStatusCheck] Checking ${deviceId} on ${valHostname}:${valPort}`);
tcpPing.probe(valHostname, valPort, (error, isAlive) => {
this.deviceStatusUpdate(deviceId, isAlive);
});
}
}
} catch (error) {
this.log.error(error.toString());
}
this.onlineCheckTimeout = this.setTimeout(() => {
this.onlineCheckTimeout = null;
this.onlineStatusCheck();
}, 15 * 1000); // Restart online check in 15 seconds
}
async deviceStatusUpdate(deviceId, status) {
if (this.isUnloaded) {
return;
}
if (!deviceId) {
return;
}
// Update online status
const idOnline = `${deviceId}.online`;
const stateOnline = await this.getStateAsync(idOnline);
const prevValue = stateOnline ? stateOnline.val === true || stateOnline.val === 'true' : false;
if (prevValue !== status) {
await this.setStateAsync(idOnline, { val: status, ack: true });
// If the device goes online again, trigger data update
if (status && this.server) {
const deviceBase = this.server.deviceBase.find(device => device.deviceId === deviceId);
if (deviceBase) {
await deviceBase.httpState();
}
}
}
// Update connection state
const oldOnlineDeviceCount = Object.keys(this.onlineDevices).length;
if (status) {
this.onlineDevices[deviceId] = true;
} else if (Object.prototype.hasOwnProperty.call(this.onlineDevices, deviceId)) {
delete this.onlineDevices[deviceId];
}
const newOnlineDeviceCount = Object.keys(this.onlineDevices).length;
// Check online devices
if (oldOnlineDeviceCount !== newOnlineDeviceCount) {
this.log.debug(`[deviceStatusUpdate] Online devices: ${JSON.stringify(Object.keys(this.onlineDevices))}`);
if (newOnlineDeviceCount > 0) {
await this.setStateAsync('info.connection', { val: true, ack: true });
} else {
await this.setStateAsync('info.connection', { val: false, ack: true });
}
}
}
async getAllDeviceIds() {
const devices = await this.getDevicesAsync();
this.cachedDevices = devices.map(device => this.removeNamespace(device._id));
}
registerDeviceId(deviceId) {
if (!deviceId) {
return;
}
if (!this.cachedDevices.includes(deviceId)) {
this.cachedDevices.push(deviceId);
}
}
isOnline(deviceId) {
return Object.prototype.hasOwnProperty.call(this.onlineDevices, deviceId);
}
removeNamespace(id) {
const re = new RegExp(`${this.namespace}*\\.`, 'g');
return id.replace(re, '');
}
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param [options] options
*/
module.exports = options => new Refoss(options);
} else {
// otherwise start the instance directly
new Refoss();
}