forked from mdopp/simple-sonoff-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sonoff.server.js
222 lines (203 loc) · 8.33 KB
/
sonoff.server.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
var ws = require("nodejs-websocket");
const fs = require('fs');
//config for wlan
config = JSON.parse(fs.readFileSync('./sonoff.config.json'));
//set initialized parameters
var state = {
knownDevices: []
};
// device in der liste finden
state.getDeviceById = (deviceId) => {
return state.knownDevices.find(d => d.id == deviceId);
};
state.updateKnownDevice = (device) => {
var updated = false;
for (var i = 0; i < state.knownDevices.length; i++) {
if (state.knownDevices[i].id == device.id) {
state.knownDevices[i] = device;
updated = true;
}
}
if (!updated) {
state.knownDevices.push(device);
}
};
state.pushMessage = a => {
var rq = {
"apikey": "111111111-1111-1111-1111-111111111111",
"action": a.action,
"deviceid": a.target,
"params": a.value,
"userAgent": "app",
"sequence": Date.now().toString(),
"ts": 0,
"from": "app"
};
var r = JSON.stringify(rq);
console.log('REQ | WS | APP | ' + r);
var device = state.getDeviceById(a.target);
if (!device.messages) device.messages = [];
device.messages.push(rq);
device.conn.sendText(r);
};
// ----------- https server ------------------------
// Import libraries
var express = require('express');
var server = express();
var bodyParser = require('body-parser')
var https = require('https');
var http = require('http');
// Register body-parser
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
// Create https server & run
https.createServer({
key: fs.readFileSync('./certs/66805011.key'),
cert: fs.readFileSync('./certs/66805011.cert')
}, server).listen(config.server.httpsPort, function () {
console.log('SONOFF API Server Started On Port %d', config.server.httpsPort);
});
// Create https server & run
http.createServer(server).listen(config.server.httpPort, function () {
console.log('API Server Started On Port %d', config.server.httpPort);
});
// Register routes
server.post('/dispatch/device', function (req, res) {
console.log('REQ | %s | %s ', req.method, req.url);
console.log('REQ | %s', JSON.stringify(req.body));
res.json({
"error": 0,
"reason": "ok",
"IP": config.server.IP,
"port": config.server.websocketPort
});
});
//switch the device via postman (https) <= does not work from browser!!
server.get('/devices/:deviceId/:state', function (req, res) {
console.log('GET | %s | %s ', req.method, req.url);
var d = state.getDeviceById(req.params.deviceId);
if (!d) {
res.status(404).send('Sonoff device ' + req.params.deviceId + ' not found');
} else {
res.sendStatus(200);
state.pushMessage({ action: 'update', value: { switch: req.params.state }, target: d.id });
}
});
//get a list of known devices via postman (https) <= does not work from browser!!
server.get('/devices/:deviceId', function (req, res) {
console.log('GET | %s | %s ', req.method, req.url);
var d = state.getDeviceById(req.params.deviceId);
if (!d) {
res.status(404).send('Sonoff device ' + req.params.deviceId + ' not found');
} else {
res.json({ id: d.id, state: d.state, model: d.model, kind: d.kind, version: d.version } );
}
});
//get a list of known devices via postman (https) <= does not work from browser!!
server.get('/devices', function (req, res) {
console.log('GET | %s | %s ', req.method, req.url);
res.json(state.knownDevices.map(x => { return { id: x.id, state: x.state, model: x.model, kind: x.kind, version: x.version } }));
});
// ----------- https server ------------------------
// setup a server, that will respond to the SONOFF requests
// this is the replacement for the SONOFF cloud!
var wsOptions = {
secure: true,
key: fs.readFileSync('./certs/66805011.key'),
cert: fs.readFileSync('./certs/66805011.cert'),
};
ws.createServer(wsOptions, function (conn) {
console.log("WS | Server is up %s:%s to %s:%s", config.server.IP, config.server.websocketPort, conn.socket.remoteAddress, conn.socket.remotePort);
conn.on("text", function (str) {
var data = JSON.parse(str);
console.log('REQ | WS | DEV | %s', JSON.stringify(data));
res = {
"error": 0,
"deviceid": data.deviceid,
"apikey": "111111111-1111-1111-1111-111111111111"
};
if (data.action) {
switch (data.action) {
case 'date':
res.date = new Date().toISOString();
break;
case 'query':
//device wants information
var device = state.getDeviceById(data.deviceid);
if (!device) {
console.log('ERR | WS | Unknown device ', data.deviceid);
} else {
/*if(data.params.includes('timers')){
console.log('INFO | WS | Device %s asks for timers',device.id);
if(device.timers){
res.params = [{timers : device.timers}];
}
}*/
res.params = {};
data.params.forEach(p => {
res.params[p] = device[p];
});
}
break;
case 'update':
//device wants to update its state
var device = state.getDeviceById(data.deviceid);
if (!device) {
console.log('ERR | WS | Unknown device ', data.deviceid);
} else {
device.state = data.params.switch;
device.conn = conn;
state.updateKnownDevice(device);
}
break;
case 'register':
var device = {
id: data.deviceid
};
//this is not valid anymore?! type is not based on the first two chars
var type = data.deviceid.substr(0, 2);
if (type == '01') device.kind = 'switch';
else if (type == '02') device.kind = 'light';
else if (type == '03') device.kind = 'sensor'; //temperature and humidity. No timers here;
device.version = data.romVersion;
device.model = data.model;
device.conn = conn;
state.updateKnownDevice(device);
console.log('INFO | WS | Device %s registered', device.id);
break;
default: console.log('TODO | Unknown action "%s"', data.action); break;
}
} else {
if (data.sequence && data.deviceid) {
var device = state.getDeviceById(data.deviceid);
if (!device) {
console.log('ERR | WS | Unknown device ', data.deviceid);
} else {
if (device.messages) {
var message = device.messages.find(item => item.sequence == data.sequence);
if (message) {
device.messages = device.messages.filter(function(item) {
return item !== message;
})
device.state = message.params.switch;
state.updateKnownDevice(device);
console.log('INFO | WS | APP | action has been accnowlaged by the device ' + JSON.stringify(data));
} else {
console.log('ERR | WS | No message send, but received an anser', JSON.stringify(data));
}
} else {
console.log('ERR | WS | No message send, but received an anser', JSON.stringify(data));
}
}
} else {
console.log('TODO | WS | Not data action frame\n' + JSON.stringify(data));
}
}
var r = JSON.stringify(res);
console.log('RES | WS | DEV | ' + r);
conn.sendText(r);
});
conn.on("close", function (code, reason) {
console.log("Connection closed");
});
}).listen(config.server.websocketPort, config.server.IP);