use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serialport::{available_ports, SerialPortInfo, SerialPortType};
use crate::error::Result;
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PortTransport {
Usb,
Pci,
Bluetooth,
Unknown,
}
impl std::fmt::Display for PortTransport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PortTransport::Usb => f.write_str("usb"),
PortTransport::Pci => f.write_str("pci"),
PortTransport::Bluetooth => f.write_str("bluetooth"),
PortTransport::Unknown => f.write_str("unknown"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct PortInfo {
pub name: String,
pub display_name: String,
pub description: String,
pub hardware_id: Option<String>,
pub transport: PortTransport,
#[serde(skip_serializing_if = "Option::is_none", default)]
#[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
pub vid: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none", default)]
#[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
pub pid: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub serial_number: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub manufacturer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
#[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
pub interface: Option<u8>,
}
impl PortInfo {
pub fn list_available() -> Result<Vec<PortInfo>> {
let ports = available_ports()?;
Ok(ports.into_iter().map(PortInfo::from_os).collect())
}
fn from_os(port: SerialPortInfo) -> Self {
let transport = transport_from_os(&port.port_type);
let (vid, pid, serial_number, manufacturer, product, interface) =
usb_fields(&port.port_type);
let description = describe_port(&port);
let hardware_id = format_hardware_id(&port);
let display_name = short_display_name(&port.port_name);
PortInfo {
display_name,
name: port.port_name,
description,
hardware_id,
transport,
vid,
pid,
serial_number,
manufacturer,
product,
interface,
}
}
}
pub trait PortProvider: Send + Sync {
fn list_available(&self) -> crate::error::Result<Vec<PortInfo>>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemPortProvider;
impl PortProvider for SystemPortProvider {
fn list_available(&self) -> crate::error::Result<Vec<PortInfo>> {
PortInfo::list_available()
}
}
fn short_display_name(port_name: &str) -> String {
port_name
.rsplit(&['/', '\\'][..])
.next()
.unwrap_or(port_name)
.to_string()
}
fn transport_from_os(port_type: &SerialPortType) -> PortTransport {
match port_type {
SerialPortType::UsbPort(_) => PortTransport::Usb,
SerialPortType::PciPort => PortTransport::Pci,
SerialPortType::BluetoothPort => PortTransport::Bluetooth,
SerialPortType::Unknown => PortTransport::Unknown,
}
}
#[allow(clippy::type_complexity)]
fn usb_fields(
port_type: &SerialPortType,
) -> (
Option<u16>,
Option<u16>,
Option<String>,
Option<String>,
Option<String>,
Option<u8>,
) {
if let SerialPortType::UsbPort(info) = port_type {
(
Some(info.vid),
Some(info.pid),
info.serial_number.clone(),
info.manufacturer.clone(),
info.product.clone(),
info.interface,
)
} else {
(None, None, None, None, None, None)
}
}
fn format_hardware_id(port: &SerialPortInfo) -> Option<String> {
match &port.port_type {
SerialPortType::UsbPort(info) => {
Some(format!("USB VID:{:04X} PID:{:04X}", info.vid, info.pid))
}
SerialPortType::PciPort => Some("PCI".to_string()),
SerialPortType::BluetoothPort => Some("Bluetooth".to_string()),
SerialPortType::Unknown => None,
}
}
fn describe_port(port: &SerialPortInfo) -> String {
match &port.port_type {
SerialPortType::UsbPort(info) => format!(
"{} {}",
info.manufacturer.as_deref().unwrap_or("Unknown"),
info.product.as_deref().unwrap_or("USB Serial Device")
),
SerialPortType::PciPort => "PCI Serial Port".to_string(),
SerialPortType::BluetoothPort => "Bluetooth Serial Port".to_string(),
SerialPortType::Unknown => "Serial Port".to_string(),
}
}