@@ -3,7 +3,7 @@ use clap::{App, Arg, SubCommand};
33use error:: Error ;
44use espflash:: { Config , Flasher , PartitionTable } ;
55use miette:: { IntoDiagnostic , Result , WrapErr } ;
6- use serial:: { BaudRate , SerialPort } ;
6+ use serial:: { BaudRate , SerialPort , SystemPort } ;
77
88use std:: {
99 fs,
@@ -14,8 +14,14 @@ use std::{
1414
1515mod cargo_config;
1616mod error;
17+ mod line_endings;
1718
19+ use crate :: line_endings:: normalized;
1820use cargo_config:: has_build_std;
21+ use std:: io:: { stdout, ErrorKind , Read , Write } ;
22+ use std:: thread:: sleep;
23+ use std:: time:: Duration ;
24+ use termion:: { async_stdin, raw:: IntoRawMode } ;
1925
2026fn main ( ) -> Result < ( ) > {
2127 let mut app = App :: new ( env ! ( "CARGO_PKG_NAME" ) )
@@ -80,6 +86,11 @@ fn main() -> Result<()> {
8086 . takes_value ( true )
8187 . value_name ( "SERIAL" )
8288 . help ( "Serial port connected to target device" ) ,
89+ )
90+ . arg (
91+ Arg :: with_name ( "monitor" )
92+ . long ( "monitor" )
93+ . help ( "Open a serial monitor after flashing" ) ,
8394 ) ,
8495 ) ;
8596
@@ -178,6 +189,10 @@ fn main() -> Result<()> {
178189 flasher. load_elf_to_flash ( & elf_data, bootloader, partition_table) ?;
179190 }
180191
192+ if matches. is_present ( "monitor" ) {
193+ monitor ( flasher. into_serial ( ) ) ?;
194+ }
195+
181196 // We're all done!
182197 Ok ( ( ) )
183198}
@@ -280,3 +295,50 @@ fn exit_with_process_status(status: ExitStatus) -> ! {
280295
281296 exit ( code)
282297}
298+
299+ const KEYCODE_CTRL_C : u8 = 3 ;
300+ const KEYCODE_CTRL_R : u8 = 18 ;
301+
302+ fn monitor ( mut serial : SystemPort ) -> anyhow:: Result < ( ) > {
303+ println ! ( "Commands:" ) ;
304+ println ! ( " CTRL+R Reset chip" ) ;
305+ println ! ( " CTRL+C Exit" ) ;
306+ println ! ( ) ;
307+
308+ let mut buff = [ 0 ; 128 ] ;
309+ serial. set_timeout ( Duration :: from_millis ( 5 ) ) ?;
310+
311+ let mut stdin = async_stdin ( ) . bytes ( ) ;
312+ let stdout = stdout ( ) . into_raw_mode ( ) ?;
313+ let mut stdout = stdout. lock ( ) ;
314+ loop {
315+ let read = match serial. read ( & mut buff) {
316+ Ok ( count) => Ok ( count) ,
317+ Err ( e) if e. kind ( ) == ErrorKind :: TimedOut => Ok ( 0 ) ,
318+ err => err,
319+ } ?;
320+ if read > 0 {
321+ let data: Vec < u8 > = normalized ( buff[ 0 ..read] . iter ( ) . copied ( ) ) . collect ( ) ;
322+ stdout. write_all ( & data) . ok ( ) ;
323+ stdout. flush ( ) ?;
324+ }
325+ if let Some ( Ok ( byte) ) = stdin. next ( ) {
326+ match byte {
327+ KEYCODE_CTRL_C => break ,
328+ KEYCODE_CTRL_R => {
329+ serial. set_dtr ( false ) ?;
330+ serial. set_rts ( true ) ?;
331+
332+ sleep ( Duration :: from_millis ( 100 ) ) ;
333+
334+ serial. set_rts ( false ) ?;
335+ }
336+ _ => {
337+ serial. write_all ( & [ byte] ) ?;
338+ serial. flush ( ) ?;
339+ }
340+ }
341+ }
342+ }
343+ Ok ( ( ) )
344+ }
0 commit comments