-
Notifications
You must be signed in to change notification settings - Fork 7
/
app.js
executable file
·172 lines (126 loc) · 5.1 KB
/
app.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
// added .env support
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const log = require('./helpers/logger');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var https = require('https');
// require the ws server
const sonoffServerEngine = require("./sonoff_server.js");
// load config from config.json.
const config = JSON.parse(fs.readFileSync(path.resolve(__dirname, './config.json')));
// load https cert to config.
config.ssl_key = fs.readFileSync(path.resolve(__dirname, './certs/server.key'));
config.ssl_cert = fs.readFileSync(path.resolve(__dirname, './certs/server.crt'));
// Override config.json with env or .env if exists.
if (process.env.HTTP_PORT !== undefined)
config.HTTP_PORT = parseInt(process.env.HTTP_PORT);
if (process.env.HTTPS_PORT !== undefined)
config.HTTPS_PORT = parseInt(process.env.HTTPS_PORT);
if (process.env.WEBSOCKET_PORT !== undefined)
config.WEBSOCKET_PORT = parseInt(process.env.WEBSOCKET_PORT);
if (process.env.SERVER_IP !== undefined)
config.SERVER_IP = process.env.SERVER_IP;
if (process.env.IS_ALIVE_CHECK_ENABLED !== undefined)
config.IS_ALIVE_CHECK_ENABLED = process.env.IS_ALIVE_CHECK_ENABLED;
if (process.env.IS_ALIVE_CHECK_INTERVAL !== undefined)
config.IS_ALIVE_CHECK_INTERVAL = parseInt(process.env.IS_ALIVE_CHECK_INTERVAL);
// Register body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Create http(s) server
var credentials = {
key: config.ssl_key,
cert: config.ssl_cert,
rejectUnauthorized: false
};
// start Websocket server.
var sonoffServer = sonoffServerEngine.createServer(config);
// Start the http server.
var httpServer = http.createServer(app);
// Start the https server.
var httpsServer = https.createServer(credentials, app);
// Set servers listeners.
httpServer.listen(config.HTTP_PORT, function () {
log.log(`HTTP server started on port: ${ config.HTTP_PORT } `);
});
httpsServer.listen(config.HTTPS_PORT, function () {
log.log(`HTTPS server started on port: ${ config.HTTPS_PORT }`);
});
// -------------------------------------------------
// Register http & https routes.
// -------------------------------------------------
app.post('/dispatch/device', function (req, res) {
log.log('REQ | %s | %s ', req.method, req.url);
log.trace('REQ | %s', JSON.stringify(req.body));
res.json({
"error": 0,
"reason": "ok",
"IP": config.SERVER_IP,
"port": config.WEBSOCKET_PORT
});
});
// Register routes
app.get('/', function (req, res) {
log.log('REQ | %s | %s ', req.method, req.url);
res.json({'message':"This is the Sonoff Server, to see active devices go to /devices"});
});
//returns an simple 0 or 1 for a known device
app.get('/devices/:deviceId/status', function (req, res) {
log.log('GET | %s | %s ', req.method, req.url);
var d = sonoffServer.getDeviceState(req.params.deviceId);
if (!d || d == "disconnected") {
res.status(404).send('Sonoff device ' + req.params.deviceId + ' not found');
} else {
res.status(200).send(((d == 'on') ? '1' : '0'));
}
});
//switch the device
app.get('/devices/:deviceId/:state', function (req, res) {
log.log('GET | %s | %s ', req.method, req.url);
var d = sonoffServer.getDeviceState(req.params.deviceId);
if (!d || d == "disconnected") {
res.status(400);
res.json({error:true, message : `Sonoff device + ${ req.params.deviceId } was not found`});
res.set("Connection", "close");
} else {
switch (req.params.state.toUpperCase()) {
case "1":
case "ON":
sonoffServer.turnOnDevice(req.params.deviceId);
res.status(200);
res.json({error:false, message : "success"});
res.set("Connection", "close");
break;
case "0":
case "OFF":
sonoffServer.turnOffDevice(req.params.deviceId);
res.status(200);
res.json({error:false, message : "success"});
res.set("Connection", "close");
break;
default:
res.status(400);
res.json({error:true, message : `Sonoff device ${ req.params.deviceId } can not be switched to ${ req.params.state }, only "ON" and "OFF" are supported currently`});
res.set("Connection", "close");
}
}
});
//get the known state of one known device
app.get('/devices/:deviceId', function (req, res) {
log.log('GET | %s | %s ', req.method, req.url);
var d = sonoffServer.getDeviceState(req.params.deviceId);
if (!d || d == "disconnected") {
res.status(404).send('Sonoff device ' + req.params.deviceId + ' not found');
} else {
res.json(sonoffServer.getConnectedDevices().find(d => d.id == req.params.deviceId));
}
});
//get a list of known devices
app.get('/devices', function (req, res) {
log.log('GET | %s | %s ', req.method, req.url);
res.json(sonoffServer.getConnectedDevices());
});