-
Notifications
You must be signed in to change notification settings - Fork 0
/
srv.socket.js
98 lines (85 loc) · 3.07 KB
/
srv.socket.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
/**
* srv.web.js – Handling Socket.IO Requests
* This file is part of noduino (c) 2012 Sebastian Müller <[email protected]>
*
* @package noduino
* @author Sebastian Müller <[email protected]>
* @license MIT License – http://www.opensource.org/licenses/mit-license.php
* @url https://github.com/semu/noduino
*/
define(['socket.io', 'public/scripts/libs/Noduino', 'public/scripts/libs/Noduino.Serial', 'public/scripts/libs/Logger'], function(io, Noduino, Connector, Logger) {
/**
* Define SocketHandler
* @param object socket Socket.IO
*/
var SocketHandler = function(socket) {
this.sockets = {};
this.arduinos = {};
this.handler = socket.listen(8090);
this.handler.set('origin', '*');
this.pinCache = {};
this.bindings();
};
/**
* Get selected Arduino
*/
SocketHandler.prototype.current = function() {
return this.arduinos[0];
};
/**
* Connect Bindings
*/
SocketHandler.prototype.bindings = function() {
var io = this.handler, that = this;
io.sockets.on('connection', function(socket) {
that.sockets[socket.id] = socket;
/**
* Incoming Serial Request
*/
that.sockets[socket.id].on('serial', function(data) {
switch (data.type) {
case 'write':
that.current().write(data.write);
break;
case 'analogRead':
var curPin = data.pin;
that.current().watchAnalogIn({'pin': data.pin}, function(m) {
if (!m.pin || m.pin == null || m.pin == NaN) {
return; }
if (m.state != that.pinCache[m.pin] && curPin == m.pin) {
socket.emit('response', {'type': 'analogRead', 'pin': m.pin, 'value': m.state});
that.pinCache[m.pin] = m.state;
}
});
break;
case 'digitalRead':
var curPin = data.pin;
that.current().watchDigitalIn({'pin': data.pin}, function(m) {
if (!m.pin || m.pin == null || m.pin == NaN) {
return; }
if (m.state != that.pinCache[m.pin] && curPin == m.pin) {
socket.emit('response', {'type': 'digitalRead', 'pin': m.pin, 'value': m.state});
that.pinCache[m.pin] = m.state;
}
});
break;
}
});
/**
* Connect to Arduino
*/
that.sockets[socket.id].on('board.connect', function(data) {
if (that.current() && that.current().connected == true) {
return socket.emit('response', {'msg': 'board.connect', 'response': 'ready'}); }
that.arduinos[0] = new Noduino({'debug': true}, Connector, Logger);
that.current().connect(function(err, board) {
that.current().connected = false;
if (err) { return socket.emit('response', {'msg': 'board.connect', 'response': 'failed'}); }
that.current().connected = true;
return socket.emit('response', {'msg': 'board.connect', 'response': 'ready'});
});
});
});
};
return new SocketHandler(io, Noduino, Connector, Logger);
});