-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
71 lines (54 loc) · 2.06 KB
/
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
// Create a websocket server and listen
// to port 8080
var socket = require('socket.io');
var io = socket.listen(8080);
// Set the server to be an mqtt client that publishs
// to the MQTT client messages that need to be routed
// to the arduino
var mqtt = require('mqtt');
// var client = mqtt.createClient(1883, '162.243.38.166');
var client = mqtt.createClient(1883, '127.0.0.1');
client.subscribe('arduino');
client.subscribe('digitalRead');
client.subscribe('analogRead');
io.sockets.on('connection', function (socket) {
client.on('message', function (topic, message) {
console.log(message);
console.log(message);
if (topic=='digitalRead'){
var data=JSON.parse(message);
socket.emit('digitalRead', data);
}
if (topic=='analogRead'){
console.log('reading analog input');
var data=JSON.parse(message);
socket.emit('analogRead', data);
}
});
// ******************** ARDUINO to VIRTUAL ********************
// On DIGITAL READ
// // readFromPin reads a sensor's value and re-routes it to virtual element
// // type : digitalWrite -> digitalWrite(pin, value);
// socket.on('readFromPinSV', function(data){
// console.log('test write to arduino');
// console.log(data);
// socket.emit('vDigitalRead', {'value':1, 'arduinoId':0,'pin':4});
// });
// ******************** VIRTUAL to ARDUINO ********************
// InitPin rerouts message to arduino to call
// pinMode(pin, value)
// on corresponding arduino with given ID
socket.on('initPin', function(data){
console.log('initalizing pin');
console.log(JSON.stringify(data));
// socket.emit('initPin', {msg:data});
client.publish('b', JSON.stringify(data) );
});
// writeToPin reads an actuator's value and rerouts it to physical element
// type : digitalWrite -> digitalWrite(pin, value);
socket.on('writeToPin', function(data){
console.log('test write to arduino');
console.log(data);
client.publish('b', JSON.stringify(data) );
});
});