forked from felixls/node-red-contrib-tplink-smarthome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmart-plug.bak.js
227 lines (223 loc) · 9.88 KB
/
smart-plug.bak.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
module.exports = function(RED) {
'use strict';
const Client = require('tplink-smarthome-api').Client;
function SmartPlugNode(config) {
RED.nodes.createNode(this, config);
this.config = {
name: config.name,
device: config.device,
interval: config.interval,
eventInterval: config.eventInterval
};
const deviceIP = this.config.device;
const moment = require('moment');
const numeral = require('numeral');
const context = this.context();
const node = this;
node.deviceInstance = null;
node.deviceConnected = false;
if (deviceIP === null||deviceIP === '') {
node.status({fill:'red',shape:'ring',text:'Not configured'});
return false;
}
node.status({fill:'grey',shape:'dot',text:'Initializing…'});
//STARTING and PARAMETERS
node.connectClient = function() {
const client = new Client();
client.getDevice({host:deviceIP})
.then((device) => {
node.deviceConnected = true;
node.deviceInstance = device;
node.status({fill:'yellow',shape:'dot',text:'Connected'});
device.on('power-on', () => {node.sendPowerUpdateEvent(true)});
device.on('power-off', () => {node.sendPowerUpdateEvent(false)});
device.on('in-use', () => {node.sendInUseEvent(true)});
device.on('not-in-use', () => {node.sendInUseEvent(false)});
device.on('device-online', () => {node.sendDeviceOnlineEvent(true)});
device.on('device-offline', () => {node.sendDeviceOnlineEvent(false)});
node.startPolling();
})
.catch(() => {return node.handleConnectionError()});
};
node.disconnectClient = function() {node.deviceConnected = false};
node.isClientConnected = function() {return node.deviceConnected === true};
node.startIsAlivePolling = function() {
node.pingPolling = setInterval(function() {
if (node.isClientConnected()) node.deviceInstance.getInfo().catch(() => {return node.handleConnectionError()});
else return node.connectClient()
}, parseInt(node.config.interval));
};
node.stopIsAlivePolling = function() {
clearInterval(node.pingPolling);
node.pingPolling = null;
};
node.startPolling = function() {
node.eventPolling = setInterval(function() {
if (node.deviceInstance === null) {
node.stopPolling();
return;
}
if (node.isClientConnected()) {
if (node.checkAction('getInfoEvents')) node.sendDeviceSysInfo()
if (node.checkAction('getMeterEvents')) node.sendDeviceMeterInfo()
} else {
node.status({fill:'red',shape:'ring',text:'Not reachable'});
node.stopPolling();
return false;
}
}, parseInt(node.config.eventInterval));
};
node.stopPolling = function () {
clearInterval(node.eventPolling);
node.eventPolling = null;
};
//INPUTS
node.on('input', function(msg) {
if (!node.isClientConnected()) return node.handleConnectionError('not reachable');
const EVENT_ACTIONS = ['getMeterEvents','getInfoEvents','getPowerUpdateEvents','getInUseEvents','getOnlineEvents'];
if(msg.payload == true||msg.payload == false) {
node.deviceInstance.setPowerState(msg.payload).then(() => {node.sendDeviceSysInfo()})
.catch(error => {return node.handleConnectionError(error)});
} else if (msg.payload === 'getInfo') node.sendDeviceSysInfo();
else if (msg.payload === 'getCloudInfo') node.sendDeviceCloudInfo();
else if (msg.payload === 'getQuickInfo') node.sendDeviceQuickInfo();
else if (msg.payload === 'switch') node.deviceInstance.togglePowerState();
else if (msg.payload === 'getMeterInfo') node.sendDeviceMeterInfo();
else if (msg.payload === 'clearEvents') context.set('action', msg.payload);
else if (msg.payload === 'eraseStats') node.sendEraseStatsResult();
else {
const actions = msg.payload.split('|');
let enabledActions = [];
actions.forEach(action => {
if (EVENT_ACTIONS.indexOf(action) !== -1) enabledActions.push(action);
});
if (enabledActions.length > 0) context.set('action', enabledActions.join('|'));
else context.set('action', '');
}
});
//EVENTS
node.checkAction = function(action) {
return context.get('action') !== undefined &&
context.get('action') !== null &&
context.get('action').includes(action);
};
node.sendDeviceSysInfo = function() {
node.deviceInstance.getSysInfo()
.then(info => {
if (info.relay_state === 1) {
context.set('state','on');
node.status({fill:'green',shape:'dot',text:'Turned ON'});
} else {
context.set('state','off');
node.status({fill:'red',shape:'dot',text:'Turned OFF'});
}
let msg = {};
msg.payload = info;
msg.payload.timestamp = moment().format();
node.send(msg);
}).catch(error => {return node.handleConnectionError(error)});
};
node.sendDeviceCloudInfo = function() {
node.deviceInstance.cloud.getInfo()
.then(info => {
let msg = {};
msg.payload = info;
msg.payload.timestamp = moment().format();
node.send(msg);
}).catch(error => {return node.handleConnectionError(error)});
};
node.sendDeviceQuickInfo = function() {
node.deviceInstance.getInfo()
.then(info => {
let msg = {};
msg.payload = info;
msg.payload.timestamp = moment().format();
node.send(msg);
}).catch(error => {return node.handleConnectionError(error)});
};
node.sendDeviceMeterInfo = function() {
node.deviceInstance.emeter.getRealtime()
.then(info => {
const state = context.get('state') === 'on' ? 'turned on': 'turned off';
const current = numeral(info.current).format('0.[000]');
const voltage = numeral(info.voltage).format('0.[0]');
const power = numeral(info.power).format('0.[00]');
node.status({fill:'gray',shape:'dot',text:`${state} [${power}W: ${voltage}V@${current}A]`});
const msg = {};
msg.payload = info;
msg.payload.timestamp = moment().format();
node.send(msg);
}).catch(error => {return node.handleConnectionError(error)});
};
node.sendPowerUpdateEvent = function(powerOn) {
if (node.checkAction('getPowerUpdateEvents')) {
let msg = {};
msg.payload = {};
msg.payload.powerOn = powerOn;
msg.payload.timestamp = moment().format();
node.send(msg);
}
};
node.sendInUseEvent = function(inUse) {
if (node.checkAction('getInUseEvents')) {
let msg = {};
msg.payload = {};
msg.payload.inUse = inUse;
msg.payload.timestamp = moment().format();
node.send(msg);
}
};
node.sendDeviceOnlineEvent = function(online) {
if (node.checkAction('getOnlineEvents')) {
let msg = {};
msg.payload = {};
msg.payload.online = online;
msg.payload.timestamp = moment().format();
node.send(msg);
}
};
node.sendEraseStatsResult = function() {
node.deviceInstance.emeter.eraseStats({})
.then((result) => {
const msg = {};
msg.payload = result;
node.send(msg);
}).catch(error => {return node.handleConnectionError(error)});
};
node.handleConnectionError = function(error) {
if (error) node.error(error);
node.status({fill:'red',shape:'ring',text:'Not reachable'});
node.disconnectClient();
return false;
};
node.on('close', function() {
node.deviceConnected = false;
node.stopPolling();
node.stopIsAlivePolling();
});
node.connectClient();
node.startIsAlivePolling();
}
//Make available as node
RED.nodes.registerType('smart-plug', SmartPlugNode);
RED.httpAdmin.get('/smarthome/plugs', (req, res) => {
try {
const client = new Client();
let discoveryTimeout = 10000;
let devices = [];
client.on('device-new', device => {devices.push(device.host)});
client.startDiscovery({deviceTypes: ['plug']});
setTimeout(() => {
client.stopDiscovery();
res.end(JSON.stringify(devices));
}, discoveryTimeout);
} catch(error) {res.sendStatus(500).send(error.message)}
});
RED.httpAdmin.get('/smarthome/plug', (req, res) => {
if (!req.query.ip) return res.status(500).send('Missing Device IP…');
const client = new Client();
client.getDevice({host: req.query.ip})
.then(device => {res.end(device.model)})
.catch(error => {res.sendStatus(500).send(error.message)});
});
};