-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_server.js
102 lines (84 loc) · 2.69 KB
/
node_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
/*
* Configurations and helpers
*/
var coAPPath = ["light", "serial", "acc", "mag"];
var serverPort = 8080;
/*
* Project dependencies
*/
var io = require('socket.io')(serverPort);
var coap = require('coap');
var url = require('url');
var http = require('http');
if (process.argv.length <= 2) {
console.log("Usage: " + __filename + " br_ipv6");
process.exit(-1);
}
var brHostName = process.argv[2];
var networkSubnet = brHostName.split('::')[0]
/*
* Collect data
*/
function getCoAPClients() {
req = http.request({host : brHostName}, function(res) {
var clients = [];
res.on('data', function (chunk) {
var line = chunk.toString();
if (line.lastIndexOf(networkSubnet, 0) == 0) {
line = line.replace(/(\n)/gm,"");
clients.push(line.split('/')[0]);
};
});
res.on('end', function() {
for (var i = 0; i < clients.length; i++) {
for (var j = 0; j < coAPPath.length; j++) {
var coAPClient = new CoAPClient(clients[i], coAPPath[j]);
coAPClient.get();
}
}
});
});
req.end();
}
var CoAPClient = function (hostname, path) {
this._hostname = hostname;
this._path = path;
};
CoAPClient.prototype.get = function () {
var self = this;
//coap get -o coap://[2001:660:5307:31C0::c269]:5683/light
var urlString = 'coap://['.concat(this._hostname).concat(']:5683/').concat(this._path);
var coapUrl = url.parse(urlString);
coapUrl.observe = true;
coapUrl.method = 'GET';
req = coap.request(coapUrl);
req.on('response', function(res) {
res.on('data', function (chunk) {
var date = new Date();
var data = JSON.parse(chunk.toString());
data.time_stamp = date.getTime();
// socket io : namespace = node name (eg m3-<id>) / eventName = path
var nameSpace = data.node;
var eventName = self._path;
io.of('/'+nameSpace).emit(eventName, JSON.stringify(data));
console.log("New event : Hostname=%s Namespace=%s EventName=%s Value=%s Time=%s", self._hostname, nameSpace, eventName, data.value, date.toLocaleTimeString());
});
});
req.end();
}
/*
* Handle Sockets.io connections
*/
// Event handlers
io.sockets.on('connection', function(socket) {
console.log("New client connected.");
// On disconnect events
socket.on('disconnect', function(socket) {
console.log("Client disconnect");
});
});
/*
* Run
*/
console.log("Starting Node.js server on port " + serverPort);
getCoAPClients();