-
Notifications
You must be signed in to change notification settings - Fork 1
/
platform.js
81 lines (60 loc) · 1.5 KB
/
platform.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
const { EventEmitter } = require('events');
const Nut = require('node-nut');
const { Device } = require('./device');
module.exports.Platform = class Platform extends EventEmitter {
constructor(config) {
super();
this.online = false;
this.devices = [];
this.config = config;
this.nut = new Nut(config.port, config.host);
this.nut.on('error', (error) => {
this.status(false);
this.emit('error', error);
setTimeout(() => this.connect(), config.reconnect);
});
this.nut.on('close', () => {
this.status(false);
this.emit('close');
});
this.nut.on('ready', () => {
this.status(true);
this.fetch();
});
this.connect();
}
async connect() {
await this.call('start');
await this.call('SetUsername', this.config.username);
await this.call('SetPassword', this.config.password);
}
async fetch() {
const list = await this.call('GetUPSList');
Object.keys(list).forEach((name) => {
this.init(name, list[name]);
});
}
status(status) {
if (status === this.online) return;
this.online = status;
this.emit('status', status);
}
call(method, ...args) {
return new Promise(
(resolve, reject) => this.nut[method](
...args,
(data, err) => (err ? reject(err) : resolve(data)),
),
);
}
init(name, description) {
const device = new Device(this, name, description);
this.devices.push(device);
device.on('update', (...args) => {
this.emit('update', device, ...args);
});
device.on('ready', () => {
this.emit('device', device);
});
}
};