-
Notifications
You must be signed in to change notification settings - Fork 0
/
milight_server.js
258 lines (222 loc) · 6.17 KB
/
milight_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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
A simple service offering an HTTP front to milight controllers.
*/
'use strict';
var bunyan = require('bunyan');
var log = bunyan.createLogger({
name: 'milight.service',
// level: DEBUG,
// serializers: {req: bunyan.stdSerializers.req}
serializers: {req: reqSerializer}
});
var express = require('express');
var app = express();
var jsonfile = require('jsonfile');
var extend = require('extend');
var Milight = require("milight");
var milight;
const zones = ['1', '2', '3', '4', 'all'];
const commands = ['on', 'off', 'bright', 'white', 'rgb'];
const configFileName = '/config.json';
const STATE_ON = 'ON';
const STATE_OFF = 'OFF';
var zoneStates = [];
var config = {
milight_host: 'milight',
http_port: 8030,
http_host: 'localhost',
base_url: 'http://localhost:8030'
};
// --- log serializer
function reqSerializer(req) {
return {
method: req.method,
url: req.url,
headers: req.headers
};
}
// --- setup the events system
const EventEmitter = require('events');
const util = require('util');
function EventController() {
EventEmitter.call(this);
}
util.inherits(EventController, EventEmitter);
const events = new EventController();
// --- load config file
events.on('configLoaded', setupServer);
var file = __dirname + configFileName;
jsonfile.readFile(file, function(err, obj) {
if (err) {
log.warn({error: err}, 'Could not read config file. Using default values.');
} else {
config = extend(true, {}, config, obj);
if (obj.base_url == undefined) {
config.base_url = 'http://'
+ config.http_host
+ (config.http_port == '80' ? '' : (':' + config.http_port));
}
log.info('Configuration file loaded.');
}
log.info({config: config});
events.emit('configLoaded');
});
// -- initiates zone status
function initiateZoneStates() {
for (var i in zones) {
var zone = zones[i];
zoneStates[zone] = {
state: STATE_OFF,
rgb: undefined,
white: 100,
brightness: 100
}
}
}
function setupServer() {
milight = new Milight({
host: config.milight_host,
broadcast: true
});
initiateZoneStates();
app.post('/zones/:zone/:cmd/:param?', milightService);
app.get('/zones/:zone', identifyZone);
app.get('/zones', listZones);
app.listen(config.http_port, config.http_host, function () {
console.log('Milight service is listening on port %s.', config.http_port);
});
}
// --- Create an invalid zone error message
function msgInvalidZone(zone) {
return 'Zone \'' + zone + '\' does not exist.';
}
function getZoneRef(req, zone) {
return config.base_url + '/zones/' + zone;
}
// --- Zones List
function listZones(req, res) {
var data = [];
for (var i in zones) {
var zone = zones[i];
data.push({id: zone, links: {self: getZoneRef(req, zone)}})
}
res.json({data: data});
log.info({req: req}, 'Responded to a zones list query.');
}
// --- Zone Identifier
function identifyZone(req, res) {
var zone = req.params.zone;
if (zones.indexOf(zone) >= 0) {
var data = {id: zone, name: ('zone ' + zone), lastStatus: zoneStates[zone]};
if (config.zone_names && config.zone_names[zone]) {
data.name = config.zone_names[zone];
}
var links = {self: getZoneRef(req, zone)};
for (var i in commands) {
links[commands[i]] = getZoneRef(req, zone) + '/' + commands[i];
}
res.json({data: data, links: links});
log.info({req: req, data: data}, 'Responded to a zone id query.');
} else {
var errorMsg = msgInvalidZone(zone);
res.status(400).json({error: [errorMsg]});
log.error({req: req, error: errorMsg}, 'Invalid zone id query.');
}
}
function milightService(req, res) {
var zone = req.params.zone;
var cmd = req.params.cmd
var param = req.params.param;
function milightServiceCallBack(error) {
if (error) {
error = error.toString();
res.status(400).json({errors: [error]});
log.error({req: req, error: error}, 'Invalid command request.');
} else {
res.sendStatus(202);
log.info({req: req}, 'Applied a light command.');
}
}
var msg = updateZone(zone, cmd, param, milightServiceCallBack);
}
function updateZone(zone, cmd, param, callback) {
var mzone;
if (zones.indexOf(zone) < 0) {
callback(msgInvalidZone(zone));
}
// set zone
if (zone == 'all') {
mzone = milight.allZones();
} else {
mzone = milight.zone(parseInt(zone));
}
switch (cmd) {
case 'on':
mzone.on(callback);
zoneStates[zone].state = STATE_ON;
break;
case 'off':
mzone.off(callback);
zoneStates[zone].state = STATE_OFF;
break;
case 'white':
if (param === undefined) {
param = '100';
}
var mparam = intValue(param);
if (mparam !== undefined) {
mzone.white(mparam, callback);
zoneStates[zone].state = STATE_ON;
zoneStates[zone].white = mparam;
zoneStates[zone].brightness = mparam;
zoneStates[zone].rgb = undefined;
} else {
callback("'" + param + "' is not a numeric value.");
}
break;
case 'bright':
if (param === undefined) {
param = '100';
}
var mparam = intValue(param);
if (mparam !== undefined) {
mzone.brightness(mparam, callback);
zoneStates[zone].state = STATE_ON;
zoneStates[zone].brightness = mparam;
if (zoneStates[zone].white !== undefined) {
zoneStates[zone].white = mparam;
}
} else {
callback("'" + param + "' is not a numeric value.");
}
break;
case 'rgb':
if (notEmptyValue(param)) {
mparam = '#' + param;
mzone.rgb(mparam, callback);
zoneStates[zone].state = STATE_ON;
zoneStates[zone].rgb = mparam;
zoneStates[zone].white = undefined;
} else {
callback("'" + param + "' is not an RGB value.");
}
break;
default:
callback('Command \'' + cmd + '\' not found.');
}
}
function notEmptyValue(str) {
return (str !== undefined) && (str.length > 0);
}
function intValue(str) {
if (notEmptyValue(str)) {
var result = parseInt(str);
if (isNaN(result)) {
return undefined;
} else {
return result;
}
} else {
return undefined;
}
}