-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNodeJS_Server.js
62 lines (56 loc) · 2.58 KB
/
NodeJS_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
var SerialPort = require('serialport2').SerialPort;
var portName = 'COM15'; // USB COM port number
var io = require('socket.io').listen(8000); // server listens for socket.io communication at port 8000
io.set('log level', 1); // disables debugging. this is optional. you may remove it if desired.
var sp = new SerialPort(); // instantiate the serial port.
sp.open(portName, { // portName is instatiated to be COM3, replace as necessary
baudRate: 9600, // this is synced to what was set for the Arduino Code
dataBits: 8, // this is the default for Arduino serial communication
parity: 'none', // this is the default for Arduino serial communication
stopBits: 1, // this is the default for Arduino serial communication
flowControl: false // this is the default for Arduino serial communication
});
io.sockets.on('connection', function (socket) {
// If socket.io receives message from the client browser then
// this call back will be executed.
socket.on('message', function (msg) {
console.log(msg);
});
// If a web browser disconnects from Socket.IO then this callback is called.
socket.on('disconnect', function () {
console.log('disconnected');
});
});
var cleanData = ''; // this stores the clean data
var readData = ''; // this stores the buffer
sp.on('data', function (data) { // call back when data is received
readData = data.toString(); // append data to buffer
// if the letters '[' and ']' are found on the buffer then isolate what's in the middle
// as clean data. Then clear the buffer.
//console.log(readData);
if (readData.indexOf(']') >= 0 && readData.indexOf('[') >= 0) {
cleanData = readData.substring(readData.indexOf('[') + 1, readData.indexOf(']'));
readData = '';
console.log("-- "+cleanData);
io.sockets.emit('message', cleanData);
}else if(readData.indexOf('[') >= 0){
cleanData = readData.substring(readData.indexOf('[') + 1, readData.length);
readData = '';
}else if(readData.indexOf(']') >= 0){
cleanData += readData.substring(0, readData.indexOf(']'));
readData = '';
console.log("-- "+cleanData);
io.sockets.emit('message', cleanData);
}else{
cleanData += readData;
readData = '';
}
//console.log(readData);
//io.sockets.emit('message', readData);
});
//to connect on local network
// var util = require('util'),
// connect = require('connect'),
// connect.createServer(connect.static(__dirname)).listen(3000);
// util.puts('Listening on ' + port + '...');
// util.puts('Press Ctrl + C to stop.');