use std::env;
use crate::model::device;
use crate::ui::device::{Parity, EOL};
use crate::wrapper::platformio;
pub fn device_list(json_output: &bool) -> Result<String, String> {
let devices = device::get_port_list()?;
if *json_output {
Ok(format_devices_json(&devices)?)
} else {
Ok(format_devices_table(&devices))
}
}
pub fn device_monitor(
port: &Option<String>,
baud: &Option<u32>,
parity: &Option<Parity>,
rtscts: &bool,
xonxoff: &bool,
rts: &Option<u8>,
dtr: &Option<u8>,
echo: &bool,
encoding: &Option<String>,
filter: &Option<String>,
eol: &Option<EOL>,
raw: &bool,
exit_char: &Option<u8>,
menu_char: &Option<u8>,
quiet: &bool,
no_reconnect: &bool
) ->Result<(), String> {
let proj_path = match env::current_dir() {
Ok(path) => path,
Err(_) => {
return Err("Failed to get current working directory.".to_string());
},
};
platformio::device_monitor(
&proj_path, port, baud, parity, rtscts, xonxoff, rts, dtr,
echo, encoding, filter, eol, raw, exit_char, menu_char, quiet, no_reconnect
)?;
Ok(())
}
fn format_devices_json(devices: &Vec<device::PioDevice>) -> Result<String, String> {
let json_string = match serde_json::to_string_pretty(devices) {
Ok(json) => json,
Err(_) => {
return Err("Failed to parse devices to the json format.".to_string())
}
};
Ok(json_string)
}
fn format_devices_table(devices: &Vec<device::PioDevice>) -> String {
let mut table_string = String::new();
for device in devices {
let hwid = match &device.hwid {
Some(id) => id.clone(),
None => "n/a".to_string()
};
let description = match &device.description {
Some(desc) => desc.clone(),
None => "n/a".to_string()
};
table_string += format!("{}\n", device.port).as_str();
table_string += "----------------\n";
table_string += format!("Hardware ID: {}\n", hwid).as_str();
table_string += format!("Description: {}\n\n", description).as_str();
}
table_string
}