-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
60 lines (51 loc) · 1.57 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
var http = require('http')
, connect = require('connect')
, fs = require('fs')
, jf = require('jsonfile')
, util = require('util')
if (process.argv.length < 3) {
console.log('Need to specify a config file');
return;
}
var config = jf.readFileSync(process.argv[2]);
console.log('Using config: ' + util.inspect(config));
// Load the devices
var devices = {};
for (var deviceName in config.devices) {
var descriptor = config.devices[deviceName];
if (fs.existsSync(descriptor.device)) {
var deviceModule = require(descriptor.module);
devices[deviceName] = deviceModule.create(descriptor);
console.log('Connected device: ' + deviceName);
} else {
console.log('Device "' + deviceName + '" not found');
}
}
// Start the web server
var app = connect()
.use(connect.logger('dev'))
.use(connect.static('www'))
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8080);
// Listen to web sockets
io.sockets.on('connection', function (socket) {
//socket.emit('devices', Object.keys(devices));
socket.emit('devices', Object.keys(config.devices));
socket.on('led toggle', function (data) {
var device = devices[data.device];
if (device && device.board) {
var board = device.board;
var isLedOn = device.isLedOn = !device.isLedOn;
board.digitalWrite(13, isLedOn ? board.HIGH : board.LOW);
}
});
if (devices['light']) {
devices['light'].bindSocket(socket);
}
if (devices['robot']) {
devices['robot'].bindSocket(socket);
}
socket.on('disconnect', function () {
});
});