-
Notifications
You must be signed in to change notification settings - Fork 2
/
ledblinker
executable file
·253 lines (240 loc) · 8.39 KB
/
ledblinker
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
#!/usr/bin/env node
'use strict';
/*****************************************************************************/
/* Led Blinker for the raspberry pi */
/* by: ok 2013 */
/* */
/* Set your pin configs at config.json before running. */
/* If you break something, it's your own fault. */
/* */
/* This software is free. */
/* */
/*****************************************************************************/
// some module deps and main vars
var Gpio = require('onoff').Gpio;
var config = require('./config');
var http = require('http');
var fs = require('fs');
var zlib = require('zlib')
var isValidJson = require('validjson');
var filePath = './public/index.html';
var htmlFile = fs.readFileSync(filePath).toString('utf8');
var fileStats = fs.statSync(filePath);
var route = {
file: htmlFile
};
var headers = {
'Content-Type': 'text/html',
'Cache-Control': 'public, max-age=31536000',
'X-Powered-By':'raspberry Pi',
'Last-Modified': fileStats.mtime,
'Expires': 'Wed, 01 Jan 2020 16:20:00 GMT',
'ETag': fileStats.size + '-' + Date.parse(fileStats.mtime)
};
var server = http.createServer(app);
var ledsO = {};
var ledsA = [];
var buttonO = {};
var buttonA = [];
var gi = 0;
// set up the objects for leds and buttons based on the config
(function setLeds() {
if (config.leds) {
var i = 0;
Object.keys(config.leds).forEach(function (ledc) {
ledsA[i] = new Gpio(config.leds[ledc].pin, 'out');
ledsA[i].writeSync(0);
ledsO[ledc] = { index: i, status: 'off', value: 0 };
i += 1;
});
}
if (config.buttons) {
var j = 0;
Object.keys(config.buttons).forEach(function (button) {
var but = config.buttons[button];
var pin = but.pin;
var edge = but.edge || 'both';
var debounce = but.debounce || 200;
buttonA[j] = new Gpio(pin, 'in', edge, { persistentWatch: true, debounceTimeout: debounce });;
buttonO[button] = { index : j, clicks: 0 };
buttonA[j].watch(function (err, value) {
if (err) {
throw err;
} else {
buttonO[button].clicks += 1;
wss.emit('sendAll', JSON.stringify({ type: 'buttons', data: buttonO }));
}
});
j += 1;
});
}
}());
// setup the in-memory http-server with both gzipped and deflated files
// after this is done, we can start listening on the server
['gzip', 'deflate'].forEach(function (gz) {
zlib[gz](htmlFile, function (err, gzipped) {
if (!err) {
route[gz] = gzipped;
}
if (gi === 1) {
server.listen(config.port);
} else {
gi += 1;
}
});
});
// this is the connectionhandler for the http-server
function app(req, res) {
var reqHeaders = req.headers;
if (reqHeaders['if-none-match'] === headers['ETag']) {
res.statusCode = 304;
return res.end();
}
var resHeaders = headers;
var acceptEncoding = reqHeaders['accept-encoding'];
if (acceptEncoding) {
var gzipd = acceptEncoding.match(/\bgzip|deflate\b/);
if (gzipd) {
resHeaders['content-encoding'] = gzipd[0];
res.writeHead(200, resHeaders);
return res.end(route[gzipd[0]]);
}
}
res.writeHead(200, resHeaders);
return res.end(route.file);
}
// set up the websocket server
var WebSocketServer = require('websocket').server;
var connIds = [];
var wss = new WebSocketServer({ httpServer: server });
wss.clientConnections = {};
// websocket server eventlisteners and callbacks
wss.on('request', function (request) {
var connection = request.accept(null, request.remoteAddress);
var cid = request.key;
var self = this;
connection.id = cid;
this.clientConnections[cid] = setConnectionListeners(connection);
connIds.push(cid);
connection.send(JSON.stringify({ type: 'leds', data: ledsO }));
connection.send(JSON.stringify({ type: 'buttons', data: buttonO }));
})
.on('sendAll', function (message) {
var self = this;
connIds.forEach(function (id) {
var conn = self.clientConnections[id];
if (conn.connected) {
conn.send(message);
}
});
});
// just a helper for sending status to all clients
function sendLedStatus() {
wss.emit('sendAll', JSON.stringify({type:'leds', data: ledsO }));
}
// a function to set websocket connection eventlisteners and callbacks
function setConnectionListeners(connection) {
connection.on('message', function (msg) {
if (msg.type === 'utf8') {
var message = msg.utf8Data;
var obj = isValidJson(message);
if (obj && obj.led && ledsO.hasOwnProperty(obj.led)) {
var ledname = obj.led;
var ledObj = ledsO[ledname];
if (obj.on && obj.off && obj.count && obj.count > 0 && obj.count < 1000000 && obj.on > 0 && obj.on < 1000000 && obj.off > 0 && obj.off < 1000000) {
obj.count = obj.count * 2;
leds.blink(obj);
} else if (obj.stop) {
leds.stopBlinking(ledname);
} else if (obj.hasOwnProperty('value') && obj.value === 1 || obj.value === 0) {
leds.switchLed(ledsA[ledObj.index], function (value) {
var stat = (obj.value === 1) ? 'on' : 'off';
ledObj.value = obj.value;
ledObj.status = stat;
sendLedStatus();
});
}
} else {
connection.close();
}
} else {
connection.close();
}
})
.on('error', function (error) {
connection.close();
})
.on('close', function () {
delete wss.clientConnections[connection.id];
connIds = Object.keys(wss.clientConnections);
});
return connection;
}
// the object that holds the methods for blinking and switching the leds
var leds = {
timeO: [],
switchLed: function (led, cb) {
led.read(function (err, value) {
if (err) {
throw err;
} else {
var val = value === 0 ? 1 : 0;
led.write(val, function (err) {
if (err) {
throw err;
} else {
cb(val);
}
});
}
});
},
blink: function(options) {
var indx = ledsO[options.led].index;
var led = ledsA[indx];
var self = this;
led.blinking = true;
ledsO[options.led].status = 'blinking';
sendLedStatus();
(function timeouts(indx, options, led) {
if (led.blinking) {
var onT = options.on;
var offT = options.off;
if (options.count <= 0) {
return self.stopBlinking(options.led);
}
options.count -= 1;
self.switchLed(led, function (value) {
var to = (value === 1) ? onT : offT;
self.timeO[indx] = setTimeout(function() {
timeouts(indx, options, led);
}, to);
});
}
}(indx, options, led));
},
stopBlinking: function (name) {
var ind = ledsO[name].index;
var val = ledsO[name].value;
ledsO[name].status = 'stop';
clearTimeout(this.timeO[ind]);
var led = ledsA[ind];
if (led.blinking) {
led.writeSync(val);
led.blinking = false;
}
sendLedStatus();
}
};
// this releases the pins after exit
process.on('exit', function() {
console.log(' Exiting...');
ledsA.forEach(function (led) {
led.unexport();
});
buttonA.forEach(function (button) {
button.unexport();
});
});
// print something to the console
console.log(' -= LED-Blinker || ok 2013 =-');