-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial.js
More file actions
75 lines (65 loc) · 2.27 KB
/
serial.js
File metadata and controls
75 lines (65 loc) · 2.27 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
let command = process.argv[2];
let portName = process.argv[3];
let baudRate = process.argv[4];
import readline from 'readline';
import serialport from 'serialport';
import chalk from 'chalk';
import boxen from 'boxen';
switch(command){
case "help": Instructions();
break;
case "list": listPorts();
break;
case "open": openPort();
break;
default : const style = {
// backgroundColor:"#ff0000",
padding: 0,
margin:0,
borderStyle: "round",
borderColor: 'red'
}
console.log(boxen(chalk.white.bold("Invalid option!"),style));
Instructions();
break;
}
function openPort(){
const serial = new serialport(portName, baudRate);
serial.on('data', readSerialData);
serial.on('open', showPortOpen);
serial.on('error', showError);
serial.write('main screen turn on', function(err){
if(err){
return console.log('error on write: ', err.message)
}
console.log('message written')
})
}
function readSerialData(data) {
console.log(data.toString());
}
function showPortOpen() {
console.log(portName+ ' open, Data rate: ' + baudRate + 'bps');
}
function showError(error) {
console.log('Serial port error: ' + error);
}
function Instructions() {
console.log('\nUsage:' + chalk.green('\tnode serial.js') + chalk.blueBright(' [option] [portname] [baudrate]'));
console.log('Example:' + chalk.green('node serial.js') + chalk.blueBright(' open com1 9600\n'));
console.log('Options:');
console.log('\t' + chalk.yellowBright('list') + '\t\tList available comports');
console.log('\t' + chalk.yellowBright('open') + '\t\tConnect to the specified comport');
console.log('Arguments:');
console.log('\t' + chalk.yellowBright('help') + '\t\tShow help');
console.log('\t' + chalk.yellowBright('portname') + '\tserial comport');
console.log('\t' + chalk.yellowBright('baudrate') + '\tserial baudrate');
process.exit(0);
}
function listPorts() {
console.log(chalk.yellowBright("\nListing available ports"));
serialport.list().then(
ports => ports.forEach(port => console.log(chalk.blueBright('\t' + port.path))),
err => console.log(err)
)
}