Skip to main content

serialplugin_core/port/
details.rs

1//! Typed per-port details (`available_ports_detailed`): numeric vid/pid, USB
2//! interface number, physical location and Linux `/dev/serial` links. The 4.x string
3//! map of [`SerialManager::available_ports`](crate::SerialManager::available_ports)
4//! is unchanged.
5
6use serde::{Deserialize, Serialize};
7#[cfg(any(all(target_os = "linux", not(target_os = "android")), all(test, unix)))]
8use std::collections::HashMap;
9#[cfg(any(all(target_os = "linux", not(target_os = "android")), all(test, unix)))]
10use std::path::{Path, PathBuf};
11
12/// Kind of port, as in the 4.x `type` field.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
14pub enum PortType {
15    #[serde(rename = "USB")]
16    Usb,
17    #[serde(rename = "Bluetooth")]
18    Bluetooth,
19    #[serde(rename = "PCI")]
20    Pci,
21    #[default]
22    Unknown,
23}
24
25/// One enumerated port. Unknown values are `None` (not `"Unknown"`).
26#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
27#[serde(rename_all = "camelCase")]
28#[non_exhaustive]
29pub struct PortDetails {
30    /// Port path (`/dev/ttyUSB0`, `/dev/cu.usbmodem1`, `COM3`, Android device path).
31    pub path: String,
32    pub port_type: PortType,
33    pub vid: Option<u16>,
34    pub pid: Option<u16>,
35    /// Full serial number (on Windows untruncated, like the 4.x map).
36    pub serial_number: Option<String>,
37    pub manufacturer: Option<String>,
38    pub product: Option<String>,
39    /// USB interface number: tells the ports of one composite device (a modem's
40    /// AT / NMEA / diag ports) apart. On macOS it can be the data interface. Desktop
41    /// with the core feature `usb-port-details` only, else `None`.
42    pub interface: Option<u8>,
43    /// Physical USB location as `bus-port.port…` (Linux sysfs `busnum`/`devpath`,
44    /// macOS IOKit `locationID`, Windows `LocationPaths`). Same socket, same value.
45    /// Desktop with the core feature `usb-port-details` only, else `None`.
46    pub location: Option<String>,
47    /// Linux `/dev/serial/by-id/*` links to this port (empty elsewhere).
48    pub by_id: Vec<String>,
49    /// Linux `/dev/serial/by-path/*` links to this port (empty elsewhere).
50    pub by_path: Vec<String>,
51}
52
53/// USB location string of a `serialport` port type, if it has one (feature
54/// `usb-port-details`; `None` without it).
55#[cfg(not(any(target_os = "android", target_os = "ios")))]
56pub(crate) fn usb_location(port: &serialport::SerialPortType) -> Option<String> {
57    #[cfg(feature = "usb-port-details")]
58    if let serialport::SerialPortType::UsbPort(info) = port {
59        return info.location.as_ref().map(|l| l.to_string());
60    }
61    let _ = port;
62    None
63}
64
65/// Convert one `serialport` entry (desktop).
66#[cfg(not(any(target_os = "android", target_os = "ios")))]
67pub fn details_from_type(path: String, port: serialport::SerialPortType) -> PortDetails {
68    use serialport::SerialPortType as T;
69    #[cfg(feature = "usb-port-details")]
70    let location = usb_location(&port);
71    match port {
72        T::UsbPort(info) => {
73            #[allow(unused_mut)]
74            let mut d = PortDetails {
75                path,
76                port_type: PortType::Usb,
77                vid: Some(info.vid),
78                pid: Some(info.pid),
79                serial_number: info.serial_number,
80                manufacturer: info.manufacturer,
81                product: info.product,
82                ..Default::default()
83            };
84            // Without the feature serialport has no interface / location: `None`.
85            #[cfg(feature = "usb-port-details")]
86            {
87                d.interface = info.interface;
88                d.location = location;
89            }
90            d
91        }
92        T::BluetoothPort => PortDetails {
93            path,
94            port_type: PortType::Bluetooth,
95            ..Default::default()
96        },
97        T::PciPort => PortDetails {
98            path,
99            port_type: PortType::Pci,
100            ..Default::default()
101        },
102        T::Unknown => PortDetails {
103            path,
104            ..Default::default()
105        },
106    }
107}
108
109/// Convert a 4.x string map (Android, iOS): `"Unknown"` -> `None`, vid/pid hex
110/// (`0x1A86`) or decimal. No interface / location there.
111pub fn details_from_info_map(
112    path: String,
113    info: &std::collections::HashMap<String, String>,
114) -> PortDetails {
115    let text = |k: &str| {
116        info.get(k)
117            .filter(|v| v.as_str() != crate::state::UNKNOWN)
118            .cloned()
119    };
120    let id = |k: &str| {
121        let v = text(k)?;
122        match v.strip_prefix("0x").or_else(|| v.strip_prefix("0X")) {
123            Some(hex) => u16::from_str_radix(hex, 16).ok(),
124            None => v.parse().ok(),
125        }
126    };
127    let port_type = match info.get("type").map(String::as_str) {
128        Some(crate::state::USB) => PortType::Usb,
129        Some(crate::state::BLUETOOTH) => PortType::Bluetooth,
130        Some(crate::state::PCI) => PortType::Pci,
131        _ => PortType::Unknown,
132    };
133    PortDetails {
134        path,
135        port_type,
136        vid: id("vid"),
137        pid: id("pid"),
138        serial_number: text("serial_number"),
139        manufacturer: text("manufacturer"),
140        product: text("product"),
141        ..Default::default()
142    }
143}
144
145/// Symlinks in `dir`, grouped by their canonical target (sorted link paths).
146/// Dangling links and a missing `dir` are skipped.
147#[cfg(any(all(target_os = "linux", not(target_os = "android")), all(test, unix)))]
148fn serial_links(dir: &Path) -> HashMap<PathBuf, Vec<String>> {
149    let mut out: HashMap<PathBuf, Vec<String>> = HashMap::new();
150    let Ok(entries) = std::fs::read_dir(dir) else {
151        return out;
152    };
153    for entry in entries.flatten() {
154        let link = entry.path();
155        if let Ok(target) = link.canonicalize() {
156            out.entry(target)
157                .or_default()
158                .push(link.display().to_string());
159        }
160    }
161    out.values_mut().for_each(|v| v.sort());
162    out
163}
164
165/// Every serial port with typed details, sorted by path (both macOS `cu.` and
166/// `tty.` nodes, no de-duplication). iOS: empty.
167#[cfg(not(target_os = "android"))]
168pub fn available_ports_detailed() -> Result<Vec<PortDetails>, crate::error::Error> {
169    #[cfg(target_os = "ios")]
170    {
171        Ok(Vec::new())
172    }
173    #[cfg(not(target_os = "ios"))]
174    {
175        #[allow(unused_mut)]
176        let mut out: Vec<PortDetails> = crate::port::list::raw_ports()?
177            .into_iter()
178            .map(|p| details_from_type(p.port_name, p.port_type))
179            .collect();
180
181        #[cfg(target_os = "windows")]
182        {
183            let full = crate::port::list::windows_full_serials();
184            for d in &mut out {
185                let picked = match (d.serial_number.as_deref(), full.get(&d.path)) {
186                    (Some(current), Some(instances)) => {
187                        crate::port::list::pick_full_serial(current, instances)
188                    }
189                    _ => None,
190                };
191                if let Some(f) = picked.map(str::to_string) {
192                    d.serial_number = Some(f);
193                }
194            }
195        }
196
197        #[cfg(target_os = "linux")]
198        {
199            let by_id = serial_links(Path::new("/dev/serial/by-id"));
200            let by_path = serial_links(Path::new("/dev/serial/by-path"));
201            for d in &mut out {
202                if let Ok(target) = Path::new(&d.path).canonicalize() {
203                    d.by_id = by_id.get(&target).cloned().unwrap_or_default();
204                    d.by_path = by_path.get(&target).cloned().unwrap_or_default();
205                }
206            }
207        }
208
209        Ok(out)
210    }
211}
212
213#[cfg(all(test, unix))]
214mod tests {
215    //! In `src/`: `/dev/serial/by-*` belongs to the system; the reader is given a directory.
216    use super::*;
217
218    #[test]
219    fn serial_links_maps_targets_to_link_names() {
220        // Removed on drop too, so a failed assert (or a mutant) leaves no temp dir behind.
221        struct Cleanup(std::path::PathBuf);
222        impl Drop for Cleanup {
223            fn drop(&mut self) {
224                let _ = std::fs::remove_dir_all(&self.0);
225            }
226        }
227        // Next to the test binary (inside cargo's target dir), not the system temp dir.
228        let exe = std::env::current_exe().unwrap();
229        let root = exe
230            .parent()
231            .unwrap()
232            .join(format!("sp-links-{}", std::process::id()));
233        let _ = std::fs::remove_dir_all(&root);
234        let _cleanup = Cleanup(root.clone());
235        let by_id = root.join("by-id");
236        std::fs::create_dir_all(&by_id).unwrap();
237        let dev = root.join("ttyUSB0");
238        std::fs::write(&dev, b"").unwrap();
239        std::os::unix::fs::symlink(&dev, by_id.join("usb-Quectel_EG25-if00-port0")).unwrap();
240        std::os::unix::fs::symlink("../ttyUSB0", by_id.join("usb-alias")).unwrap();
241        std::os::unix::fs::symlink(root.join("gone"), by_id.join("dangling")).unwrap();
242
243        let links = serial_links(&by_id);
244        let target = dev.canonicalize().unwrap();
245        assert_eq!(
246            links.get(&target).cloned().unwrap_or_default(),
247            vec![
248                by_id
249                    .join("usb-Quectel_EG25-if00-port0")
250                    .display()
251                    .to_string(),
252                by_id.join("usb-alias").display().to_string(),
253            ]
254        );
255        assert_eq!(links.len(), 1);
256        assert!(serial_links(&root.join("missing")).is_empty());
257        std::fs::remove_dir_all(&root).unwrap();
258    }
259}