mcuat/
lib.rs

1// use std::error;
2use log::{info,error,warn};
3use serialport::SerialPort;
4
5use std::io::{BufRead, Read, Write};
6pub use serialport;
7
8pub struct Com{
9    pub com:Box<dyn SerialPort>,
10}
11impl Com {
12    pub fn new(com:Box<dyn SerialPort>)->Self{
13        Self { com }
14    }
15    pub fn m_write(&mut self,cmd:&str)->std::io::Result<usize>{
16        self.com.write(cmd.as_bytes())
17    }
18    pub fn m_read(&mut self)->Option<String>{
19        let mut buff = [0;4096];
20        let d = self.com.read(&mut buff).ok()?;
21        let data = std::str::from_utf8(&buff[..d]).ok()?;
22        info!("<-{data}");
23        Some(data.to_string())
24    }
25    
26    pub fn m_query(&mut self,cmd:&str)->Option<String>{
27        self.m_write(cmd).ok()?;
28        self.m_read()
29    }
30    // pub fn m_sendhex(&mut self,hex:&str)->std::io::Result<usize>{
31    //     faster_hex::h
32    //     self.com.write(buf)?
33    // }
34    pub fn m_confirmkey1s(&mut self,cmd:&str,key:&str)->std::io::Result<String>{
35        self.m_write(cmd)?;
36        info!("->{cmd}");
37        let now = std::time::Instant::now();
38        while now.elapsed()<std::time::Duration::from_secs(1){
39            if let Some(d) = self.m_read(){
40                if d.contains(key){
41                    return Ok(d);
42                }
43            }
44        }
45        Err(std::io::ErrorKind::TimedOut.into())
46    }
47    pub fn m_write_bytes_line_key_timeout(&mut self,cmd:&[u8],key:&str,timeout:u64)->std::io::Result<String>{
48        let mut allcount = cmd.len();
49        let mut nn = self.com.write(cmd)?;
50        while nn<allcount{
51            allcount -=nn;
52            nn = self.com.write(&cmd[..allcount])?;
53        }
54        let mut buff = [0;4096];
55        let mut linecache = String::new();
56        let now = std::time::Instant::now();
57        while now.elapsed()<std::time::Duration::from_secs(timeout){
58            if let Ok(n) = self.com.read(&mut buff){
59                if let Ok(nn) = std::str::from_utf8(&buff[0..n]){
60                    linecache.push_str(nn);
61                    for iidx in linecache.lines(){
62                        if iidx.contains(key){
63                            info!("<-{iidx}");
64                            return Ok(iidx.to_string());
65                        }
66                    }
67                }
68            }
69            if now.elapsed()>std::time::Duration::from_secs(1){
70                nn = self.com.write("\r\n\r\n\r\n".as_bytes())?;
71            }
72        }
73        Err(std::io::ErrorKind::TimedOut.into())
74    }
75    pub fn m_confirm_line_key_timeout(&mut self,cmd:&str,key:&str,timeout:u64)->std::io::Result<String>{
76        self.m_write(cmd)?;
77        info!("->{cmd}");
78        let mut buff = [0;4096];
79        let now = std::time::Instant::now();
80        while now.elapsed()<std::time::Duration::from_secs(timeout){
81            if let Ok(n) = self.com.read(&mut buff){
82                for idx in buff[0..n].lines(){
83                    if let Ok(ss) = idx{
84                        info!("<-{ss}");
85                        if ss.contains(key){
86                            return Ok(ss);
87                        }
88                    }
89                }
90            }
91        }
92        Err(std::io::ErrorKind::TimedOut.into())
93    }
94    pub fn m_sendwhilekeytimecount(&mut self,cmd:&str,key:&str,timeout:u64,count:usize)->std::io::Result<()>{
95        for idx in 0..count{
96            if self.m_confirm_line_key_timeout(cmd, key, timeout).is_ok(){
97                return Ok(());
98            }
99        }
100        Err(std::io::ErrorKind::TimedOut.into())
101    }
102}
103#[test]
104fn test1(){
105    let mut dd = serialport::new("COM3", 115200).open().unwrap();
106    let mut at = Com::new(dd);
107    // dd.write(b"233");
108}
109// impl Chat for Atpack {
110//     fn m_send(&mut self,cmd:&str,rn:bool)->std::io::Result<usize>{
111//         match rn {
112//             true => {
113//                 let tosend = format!("{}\r\n",cmd);
114//                 info!("->{}",tosend);
115//                 self.write(tosend.as_bytes())
116//             },
117//             false => {info!("->{}",cmd);self.write(cmd.as_bytes())},
118//         }
119//     }
120//     fn m_send_raw(&mut self,buf:&[u8])->std::io::Result<usize> {
121//         info!("->hex:{}",faster_hex::hex_string_upper(&buf));
122//         self.write(buf)
123//     }
124//     fn m_read(&mut self)->Option<String>{
125//         // self.set_buffer_size(rx_size, tx_size)
126//         let mut buff = [0;4096];
127//         if let Ok(d)= self.read(&mut buff){
128//             if let Ok(dd) = std::str::from_utf8(&buff[..d]){
129//                 if dd.len()>0{
130//                     info!("<-{dd}");
131//                     return Some(dd.to_string());
132//                 }
133//             }else{
134//                 error!("有数据解析错误");
135//             }
136//         }
137//         None
138//     }
139//     fn m_read_logbin(&mut self,fl:&mut std::fs::File)->Option<String>{
140//         // self.set_buffer_size(rx_size, tx_size)
141//         let mut buff = [0;4096];
142//         if let Ok(d)= self.read(&mut buff){
143//             fl.write(&buff[..d]);
144//             if let Ok(dd) = std::str::from_utf8(&buff[..d]){
145//                 if dd.len()>0{
146//                     return Some(dd.to_string());
147//                 }
148//             }else{
149//                 println!("有数据解析错误");
150//             }
151//         }
152//         None
153//     }
154//     fn m_read_n1(&mut self)->Option<String>{
155//         let mut buff = String::new();
156//         self.read_to_string(&mut buff).ok()?;
157//         Some(buff)
158//     }
159//     fn m_query(&mut self,cmd:&str)->Option<String>{
160//         self.m_send(cmd, true).ok()?;
161//         self.m_read()
162//     }
163
164//     fn m_confirmkey(&mut self,cmd:&str,key:&str)->Option<String> {
165//         if let Some(data) = self.m_query(cmd){
166//             return data.contains(key).then_some(data)
167//         }
168//         None
169//     }
170
171//     fn m_rts(&mut self,level:bool)->Result<(),()> {
172//         self.set_request_to_send(level).ok().ok_or(())?;
173//         Ok(())
174//     }
175
176//     fn m_dtr(&mut self,level:bool)->Result<(),()> {
177//         self.set_data_terminal_ready(level).ok().ok_or(())?;
178//         Ok(())
179//     }
180
181//     fn m_cts(&mut self)->Result<bool,()> {
182//         match  self.read_clear_to_send(){
183//             Ok(level) => Ok(level),
184//             Err(_) => Err(()),
185//         }
186//     }
187//     fn m_ri(&mut self)->Result<bool,()>{
188//         match self.read_ring_indicator(){
189//             Ok(level) => Ok(level),
190//             Err(_) => Err(()),
191//         }
192//     }
193
194//     fn m_dcd(&mut self)->Result<bool,()> {
195//         match self.read_carrier_detect(){
196//             Ok(level) => Ok(level),
197//             Err(_) => Err(()),
198//         }
199//     }
200
201//     fn m_sendwhilekeytime(&mut self,cmd:&str,key:&str,timeout_s:u64)->std::io::Result<()> {
202//         let nowtime = std::time::Instant::now();
203//         loop{
204//             if let Some(dd) = self.m_query(cmd){
205//                 if dd.contains(key){
206//                     return Ok(());
207//                 }
208//             };
209//             std::thread::sleep(std::time::Duration::from_millis(1000));
210//             if nowtime.elapsed()>std::time::Duration::from_secs(timeout_s){
211//                 return Err(std::io::ErrorKind::TimedOut.into());
212//             }
213            
214//         }
215//     }
216    
217//     fn m_sendwhilekeytimecount(&mut self,cmd:&str,key:&str,timeout_s:u64,count:usize)->std::io::Result<()> {
218//         let mut allcount = 0;
219//         let nowtime = std::time::Instant::now();
220//         loop{
221//             if let Some(dd) = self.m_query(cmd){
222//                 if dd.contains(key){
223//                     allcount+=1;
224//                     if allcount>count{
225//                         return Ok(());
226//                     }
227//                 }
228//             };
229//             std::thread::sleep(std::time::Duration::from_millis(1000));
230//             if nowtime.elapsed()>std::time::Duration::from_secs(timeout_s){
231//                 return Err(std::io::ErrorKind::TimedOut.into());
232//             }
233            
234//         }
235//         todo!()
236//     }
237
238    
239
240
241//     // fn m_confirmkey(&mut self,cmd:&str,key:&str)->Option<String,String>{
242
243//     // }
244
245// }
246
247#[derive(Default)]
248pub struct Atpack{
249    porthandle:Option<Box<dyn serialport::SerialPort>>
250}
251// impl Chat for Atpack {
252//     fn m_send(&mut self,data:&str,rn:bool)->std::io::Result<usize>{
253//         if let Some(port) = &mut self.porthandle{
254//             if rn{
255//                 port.write(format!("{}\r\n",data).as_bytes())
256//             }else{
257//                 port.write(data.as_bytes())
258//             }
259//         }else{
260//             Err(std::io::Error::from_raw_os_error(233))
261//         }
262
263//     }
264//     fn m_read(&mut self)->Option<String>{
265//         if let Some(port) = &mut self.porthandle{
266//             let mut buff = [0;2048];
267//             if let Ok(numc) = port.read(&mut buff){
268//                 if let Ok(data) = std::str::from_utf8(&buff[..numc]){
269//                     return Some(data.into());
270//                 }
271//             };
272//         }
273//         None
274//     }
275//     fn m_read_logbin(&mut self,fl:&mut std::fs::File)->Option<String>{
276//         if let Some(port) = &mut self.porthandle{
277//             let mut buff = [0;2048];
278//             if let Ok(numc) = port.read(&mut buff){
279//                 fl.write(&buff[..numc]);
280//                 if let Ok(data) = std::str::from_utf8(&buff[..numc]){
281//                     return Some(data.into());
282//                 }
283//             };
284//         }
285//         None
286//     }
287//     fn m_rts(&mut self,level:bool)->Result<(),()>{
288//         if let Some(port) = &mut self.porthandle{
289//             port.write_request_to_send(level).ok().ok_or(())?;
290//             Ok(())
291//         }else{
292//             Err(())
293//         }
294//     }
295//     fn m_dtr(&mut self,level:bool)->Result<(),()>{
296//         if let Some(port) = &mut self.porthandle{
297//             port.write_data_terminal_ready(level).ok().ok_or(())?;
298//             Ok(())
299//         }else{
300//             Err(())
301//         }
302//     }
303//     fn m_cts(&mut self)->Result<bool,()> {
304//         if let Some(port) = &mut self.porthandle{
305//             return match port.read_clear_to_send() {
306//                 Ok(level) => Ok(level),
307//                 Err(_) => Err(()),
308//             }
309//         }
310//         Err(())
311        
312//     }
313//     fn m_ri(&mut self)->Result<bool,()>{
314//         if let Some(port) = &mut self.porthandle{
315//             return match port.read_ring_indicator() {
316//                 Ok(level) => Ok(level),
317//                 Err(_) => Err(()),
318//             };
319//         }
320//         Err(())
321//     }
322
323//     fn m_dcd(&mut self)->Result<bool,()> {
324//         if let Some(port) = &mut self.porthandle {
325//             return match port.read_carrier_detect() {
326//                 Ok(level) => Ok(level),
327//                 Err(_) => Err(()),
328//             };
329//         }
330//         Err(())
331//     }
332
333//     fn m_read_n1(&mut self)->Option<String> {
334//         None
335//     }
336
337//     fn m_query(&mut self,cmd:&str)->Option<String>{
338//         self.m_send(cmd, true).ok()?;
339//         self.m_read()
340//     }
341
342//     fn m_confirmkey(&mut self,cmd:&str,key:&str)->Option<String> {
343//         if let Some(data) = self.m_query(cmd){
344//             return data.contains(key).then_some(data)
345//         }
346//         None
347//     }
348
349//     fn m_sendwhilekeytime(&mut self,cmd:&str,key:&str,timeout_s:u64)->std::io::Result<()> {
350//         let nowtime = std::time::Instant::now();
351//         loop{
352//             if let Some(dd) = self.m_query(cmd){
353//                 info!("{}",dd);
354//                 if dd.contains(key){
355//                     return Ok(());
356//                 }
357//             };
358//             if nowtime.elapsed()>std::time::Duration::from_secs(timeout_s){
359//                 return Err(std::io::ErrorKind::TimedOut.into());
360//             }
361//         }
362//     }
363
364//     fn m_send_raw(&mut self,buf:&[u8])->std::io::Result<usize> {
365//         // todo!()
366//         Ok(2)
367//     }
368
369//     fn m_sendwhilekeytimecount(&mut self,cmd:&str,key:&str,timeout_s:u64,count:usize)->std::io::Result<()> {
370//         Ok(())
371//     }
372    
373//     // pub fn query(&mut self,msg:&str)->Option<String>{
374//     //     if let Some(hand) =&mut self.porthandle{
375//     //         if let Err(_) = hand.write(msg.as_bytes()){
376//     //             return None;
377//     //         };
378//     //         let mut buff = [0;1024];
379//     //         if let Ok(_) = hand.read(&mut buff){
380//     //             if let Ok(data) = std::str::from_utf8(&buff[..]){
381//     //                 return Some(data.into());
382//     //             }
383//     //         };
384//     //     };
385//     //     None
386//     // }
387//     // pub fn send_and_recv_confirm_single_key(&mut self,at_send:&str,at_recv:&str)->Result<String,String>{
388//     //     let mut tmpdata = String::new();
389//     //     if let Some(getdata) = self.query(at_send){
390//     //         if let Some(_) = getdata.find(at_recv){
391//     //             return Ok(getdata);
392//     //         }
393//     //         tmpdata = getdata;
394//     //     }
395//     //     Err(tmpdata)
396//     // }
397//     // pub fn send_and_recv_confirm_single_key_split_while(&mut self,at_send:&str,at_recv:&str,time_s:u64)->Result<String,String>{
398//     //     let marktime = SystemTime::now();
399//     //     let mut errmsg = String::new();
400//     //     loop{
401//     //         if let Some(data) = self.query(at_send){
402//     //             let cc:Vec<&str> = data.split(",").collect();
403//     //             for idx in cc{
404//     //                 if let Some(_) = idx.find(at_recv){
405//     //                     return Ok(data);
406//     //                 }
407//     //             }
408//     //             errmsg = data;
409//     //         }
410//     //         if let Ok(tt) = marktime.elapsed(){
411//     //             if tt>Duration::from_secs(time_s){
412//     //                 return Err(errmsg);
413//     //             }
414//     //         };
415//     //         sleep(Duration::from_secs(1));
416//     //     }
417//     // }
418// }
419// impl Atpack {
420//     pub fn new()->Self{
421//         Self{..Default::default()}
422//     }
423//     pub fn m_open(&mut self,compath:&str,boud:u32,tout:u64)->bool{
424//         if let Ok(port) = serialport::new(compath, boud)
425//         .timeout(std::time::Duration::from_millis(tout)).open(){
426//             // let dd1 = Arc::new(Mutex::new(port));
427//             // std::thread::spawn(move||{
428//             //     unsafe{
429//             //         dd1.as_ptr
430//             //     }
431//             // });
432//             self.porthandle = Some(port);
433//             return true;
434//         };
435//         false
436//     }
437    
438// }
439
440