12
12
const app = require ( 'express' ) ( ) ;
13
13
const http = require ( 'http' ) . Server ( app ) ;
14
14
const io = require ( 'socket.io' ) ( http ) ;
15
- const port = process . env . PORT || 3000 ;
15
+ const tcpPort = process . env . PORT || 3000 ;
16
16
17
- const serialport = require ( 'serialport' ) ;
18
- const SerialPort = serialport . SerialPort ;
17
+ const SerialPort = require ( 'serialport' ) ;
19
18
20
- const serial = new SerialPort ( '/dev/cu.usbmodem1411' , {
21
- baudRate : 9600 ,
22
- parser : SerialPort . parsers . byteLength ( 1 )
19
+ const port = new SerialPort ( '/dev/cu.usbmodem1411' , {
20
+ baudRate : 9600
23
21
} ) ;
24
22
23
+ const byteParser = new SerialPort . parsers . ByteLength ( { length : 1 } ) ;
24
+ port . pipe ( byteParser ) ;
25
+
25
26
// Values to send over to Arduino.
26
27
const HIGH = Buffer . from ( [ 1 ] ) ;
27
28
const LOW = Buffer . from ( [ 0 ] ) ;
@@ -36,8 +37,8 @@ app.get('/', (req, res) => {
36
37
res . sendfile ( 'index.html' ) ;
37
38
} ) ;
38
39
39
- http . listen ( port , ( ) => {
40
- console . log ( `listening on *: ${ port } ` ) ;
40
+ http . listen ( tcpPort , ( ) => {
41
+ console . log ( `listening on http://localhost: ${ tcpPort } ` ) ;
41
42
} ) ;
42
43
43
44
/* ===========================================
@@ -57,10 +58,10 @@ io.on('connection', (socket) => {
57
58
console . log ( 'Message received: ' , msg ) ;
58
59
switch ( msg ) {
59
60
case 'on' :
60
- serial . write ( HIGH ) ;
61
+ port . write ( HIGH ) ;
61
62
break ;
62
63
case 'off' :
63
- serial . write ( LOW ) ;
64
+ port . write ( LOW ) ;
64
65
break ;
65
66
default :
66
67
break ;
@@ -74,15 +75,14 @@ io.on('connection', (socket) => {
74
75
*
75
76
=========================================== */
76
77
77
- serial . on ( 'open' , ( ) => {
78
+ port . on ( 'open' , ( ) => {
78
79
console . log ( 'Port is open!' ) ;
79
80
} ) ;
80
81
81
82
/**
82
- * EventListener to receive data from .ino script uploaded to Arduino.
83
- *
83
+ * listen to the bytes as they are parsed from the parser.
84
84
*/
85
- serial . on ( 'data' , ( data ) => {
85
+ byteParser . on ( 'data' , ( data ) => {
86
86
let message ;
87
87
88
88
if ( HIGH . compare ( data ) === 0 ) {
@@ -96,7 +96,7 @@ serial.on('data', (data) => {
96
96
io . sockets . emit ( 'new message' , message ) ;
97
97
} ) ;
98
98
99
- serial . on ( 'close' , ( ) => {
99
+ port . on ( 'close' , ( ) => {
100
100
console . log ( 'Serial port disconnected.' ) ;
101
101
io . sockets . emit ( 'close' ) ;
102
102
} ) ;
0 commit comments