-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial.js
More file actions
115 lines (100 loc) · 2.8 KB
/
serial.js
File metadata and controls
115 lines (100 loc) · 2.8 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
const { SerialPort } = require( 'serialport' );
const { ReadlineParser } = require( '@serialport/parser-readline' );
let port, parser
let connected = false;
let scanInterval;
module.exports = {
//TODO add a listener for key presses
scan,
connect,
stopScan,
send,
invoke,
on,
onClose: setOnClose,
disconnect
}
let onNextJson;
let onMsg = {};
let onClose;
function normalizeMessage( msg ) {
return String( msg || "" ).trim().replace( /^-\s*/, '' );
}
function onMessage( msg ) {
const normalized = normalizeMessage( msg );
if ( onNextJson && ( normalized[0] === "{" || normalized[0] === "[" ) ) {
onNextJson( JSON.parse( normalized ) );
onNextJson = "";
} else if ( normalized.startsWith( 'module ' ) && typeof onMsg.module === 'function' ) {
onMsg.module( normalized );
} else if ( normalized.startsWith( 'status ' ) && typeof onMsg.status === 'function' ) {
onMsg.status( normalized );
} else if ( Object.keys( onMsg ).includes( normalized.match( /^\w*/ )[0] ) ) {
onMsg[normalized.match( /^\w*/ )[0]]( normalized );
} else {
console.log( "Unknown command from serial:\t", normalized );
}
}
function on( command, callback ) {
onMsg[command] = callback;
}
function setOnClose( callback ) {
onClose = callback
}
function scan( callback ) {
scanInterval = setInterval( async () => {
callback( await SerialPort.list() );
}, 2000 );
}
function stopScan() {
clearInterval( scanInterval );
scanInterval = null;
}
function connect( path ) {
return new Promise( ( resolve ) => {
stopScan();
port = new SerialPort( { path: path, baudRate: 14400, autoOpen: false, } );
port.on( 'open', function () {
connected = true;
resolve();
} );
port.open( function ( err ) {
if ( err ) {
console.error( 'Error opening port: ', err.message );
return false;
}
} )
parser = port.pipe( new ReadlineParser( { delimiter: '\r\n' } ) );
parser.on( 'data', onMessage );
port.on( 'close', () => {
port = null;
parser = null;
if ( typeof onClose === "function" ) {
onClose();
}
} )
} )
}
function send( msg ) {
//TODO check to see if initialized
try {
//console.log( "sending: ", msg );
port.write( msg );
port.write( '\r\n' );
} catch ( e ) {
console.error( "error sending serial port data", e );
return false;
}
return true;
}
function invoke( msg ) {
return new Promise( ( resolve ) => {
send( msg );
onNextJson = list => {
resolve( list );
};
} );
}
function disconnect(){
port.close();
}