1
+ use core:: time;
2
+ use std:: {
3
+ io:: { self , BufRead , BufReader , Write } ,
4
+ thread:: sleep,
5
+ time:: Duration ,
6
+ } ;
7
+
1
8
use serde_json;
2
- use serialport:: available_ports;
9
+ use serialport:: { self , available_ports} ;
3
10
4
11
const HELP : & str = "\
5
12
App
@@ -9,13 +16,19 @@ FLAGS:
9
16
-h, --help Prints help information
10
17
OPTIONS:
11
18
--list, -l Lists serial ports avaiable
19
+ --follow, Follow serial port if it disconnects
20
+ --port, Port to connect to
21
+ --baud, Baud to use (default 115200)
12
22
ARGS:
13
23
<INPUT>
14
24
" ;
15
25
16
26
#[ derive( Debug ) ]
17
27
struct AppArgs {
18
28
list : bool ,
29
+ port : Option < String > ,
30
+ baud : u32 ,
31
+ follow : bool ,
19
32
}
20
33
21
34
fn parse_args ( ) -> Result < AppArgs , pico_args:: Error > {
@@ -29,6 +42,9 @@ fn parse_args() -> Result<AppArgs, pico_args::Error> {
29
42
30
43
let args = AppArgs {
31
44
list : pargs. contains ( [ "-l" , "--list" ] ) ,
45
+ port : pargs. opt_value_from_str ( "--port" ) ?,
46
+ baud : pargs. value_from_str ( "--baud" ) . or ( Ok ( 115_200 ) ) ?,
47
+ follow : pargs. contains ( [ "-f" , "--follow" ] ) ,
32
48
} ;
33
49
34
50
// It's up to the caller what to do with the remaining arguments.
@@ -49,6 +65,7 @@ fn main() {
49
65
}
50
66
} ;
51
67
68
+ // Show list of possible ports
52
69
if args. list {
53
70
match available_ports ( ) {
54
71
Ok ( ports) => {
@@ -66,5 +83,63 @@ fn main() {
66
83
eprintln ! ( "Error listing serial ports" ) ;
67
84
}
68
85
}
86
+
87
+ return ;
69
88
}
89
+
90
+ if args. port . is_some ( ) {
91
+ print ! ( "Connecting.." ) ;
92
+ io:: stdout ( ) . flush ( ) . unwrap ( ) ;
93
+
94
+ let port_name = args. port . unwrap ( ) ;
95
+
96
+ loop {
97
+ // Open with settings
98
+ let port = serialport:: new ( & port_name, args. baud )
99
+ . timeout ( time:: Duration :: from_millis ( 10 ) )
100
+ . open ( ) ;
101
+
102
+ // Then watch the buffer until terminated..
103
+ match port {
104
+ Ok ( p) => {
105
+ // Start incoming data on a new line
106
+ println ! ( "\n Connected to {}!" , port_name) ;
107
+
108
+ let lines = BufReader :: new ( p) . lines ( ) ;
109
+
110
+ for line in lines {
111
+ match line {
112
+ Ok ( l) => println ! ( "{}" , l) ,
113
+ Err ( e) => {
114
+ if e. to_string ( ) . contains ( "Operation timed out" ) {
115
+ continue ;
116
+ } else {
117
+ if args. follow {
118
+ break ;
119
+ } else {
120
+ eprintln ! ( "Error: {}" , e) ;
121
+ std:: process:: exit ( 1 ) ;
122
+ }
123
+ }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ Err ( _e) => {
129
+ if !args. follow {
130
+ eprintln ! ( "Unable to connect to {} with baud {}" , port_name, args. baud) ;
131
+ std:: process:: exit ( 1 ) ;
132
+ }
133
+ }
134
+ }
135
+
136
+ // Print that we're waiting..
137
+ print ! ( "." ) ;
138
+ io:: stdout ( ) . flush ( ) . unwrap ( ) ;
139
+ sleep ( Duration :: from_secs ( 1 ) ) ;
140
+ }
141
+ }
142
+
143
+ // Otherwise print help
144
+ print ! ( "{}" , HELP ) ;
70
145
}
0 commit comments