1use log::{debug, error, info};
2use serialport::SerialPort;
3use std::io::{Read, Write};
4
5pub struct SerialClient {
6 port: Box<dyn serialport::SerialPort>,
7 pub write_locked: bool,
8 pub serial_datas: Vec<u8>,
9}
10
11impl SerialClient {
12 pub fn new(baudrate: u32, port_path: &str) -> Self {
13 let port = Self::connect(baudrate, port_path.to_string());
14 Self {
15 port,
16 write_locked: false,
17 serial_datas: vec![],
18 }
19 }
20
21 fn connect(baudrate: u32, port_path: String) -> Box<dyn SerialPort> {
22 let port = serialport::new(port_path.to_string(), baudrate).open();
23
24 match port {
25 Ok(port) => {
26 info!("SHIELD: Connected to {}", port_path);
27 port
28 }
29 Err(e) => {
30 panic!("SHIELD: Failed to connect to {}: {}", port_path, e);
31 }
32 }
33 }
34
35 pub fn disconnect(self) {
36 info!("SHIELD: Disconnected from {}", self.port.name().unwrap());
37 drop(self.port);
38 }
39
40 pub fn send(&mut self, bytes: &[u8]) -> bool {
41 let string = match std::str::from_utf8(&bytes[..bytes.len() - 2]) {
42 Ok(v) => v,
43 Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
44 };
45 if !self.write_locked {
46 self.write_locked = true;
47 match self.port.write(bytes) {
48 Ok(_) => {
49 debug!("SHIELD: Sent {}", string);
50 self.write_locked = false;
51 true
52 }
53 Err(e) => {
54 error!("SHIELD: Failed to send {}: {}", string, e);
55 self.write_locked = false;
56 false
57 }
58 }
59 } else {
60 debug!(
61 "SHIELD: Command not sent, waiting for serial unlock: {}",
62 string
63 );
64 false
65 }
66 }
67
68 fn push_serial_data(&mut self, byte: &u8) {
69 self.serial_datas.push(*byte);
70 }
71
72 pub fn read_incoming_raw_data(&mut self) {
73 let mut serial_data_raw: Vec<u8> = vec![];
74 let mut serial_buf: Vec<u8> = vec![0; 32];
75 match self.port.read(serial_buf.as_mut_slice()) {
76 Err(e) => {
77 error!("SHIELD: Error reading incoming data: {}", e);
78 }
79 Ok(_) => {
80 serial_buf.iter().for_each(|byte| {
81 if b'\n' == *byte {
82 let string = &String::from_utf8(serial_data_raw.clone()).unwrap();
83 debug!("SHIELD: Received data: {:?}", string);
84
85 self.push_serial_data(byte);
86 serial_data_raw = vec![];
87 } else {
88 serial_data_raw.push(*byte);
89 }
90 });
91 }
92 }
93 }
94}