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(test)]
214mod tests {
215    use super::*;
216    use std::collections::HashMap;
217
218    #[cfg(all(
219        feature = "usb-port-details",
220        not(any(target_os = "android", target_os = "ios"))
221    ))]
222    fn quectel(interface: u8) -> serialport::SerialPortType {
223        serialport::SerialPortType::UsbPort(serialport::UsbPortInfo {
224            vid: 0x2c7c,
225            pid: 0x0125,
226            serial_number: Some("a1b2c3".into()),
227            manufacturer: Some("Quectel".into()),
228            product: Some("EG25-G".into()),
229            location: Some(serialport::Location::new("1".into(), vec![2, 3])),
230            interface: Some(interface),
231        })
232    }
233
234    /// The 4 ports of one Quectel modem look the same in the 4.x map; the interface
235    /// number tells them apart.
236    #[cfg(all(
237        feature = "usb-port-details",
238        not(any(target_os = "android", target_os = "ios"))
239    ))]
240    #[test]
241    fn quectel_ports_differ_by_interface_number() {
242        let ports: Vec<PortDetails> = (0..4u8)
243            .map(|i| details_from_type(format!("/dev/ttyUSB{i}"), quectel(i)))
244            .collect();
245        for (i, d) in ports.iter().enumerate() {
246            assert_eq!(d.port_type, PortType::Usb);
247            assert_eq!(d.vid, Some(0x2c7c));
248            assert_eq!(d.pid, Some(0x0125));
249            assert_eq!(d.serial_number.as_deref(), Some("a1b2c3"));
250            assert_eq!(d.manufacturer.as_deref(), Some("Quectel"));
251            assert_eq!(d.product.as_deref(), Some("EG25-G"));
252            assert_eq!(d.location.as_deref(), Some("1-2.3"));
253            assert_eq!(d.interface, Some(i as u8));
254        }
255        let mut ifaces: Vec<_> = ports.iter().map(|d| d.interface).collect();
256        ifaces.dedup();
257        assert_eq!(ifaces.len(), 4);
258
259        let maps: Vec<_> = (0..4u8)
260            .map(|i| crate::port::list::port_info_from_type(quectel(i)))
261            .collect();
262        assert!(
263            maps.iter().all(|m| m == &maps[0]),
264            "4.x map cannot tell them apart"
265        );
266    }
267
268    #[cfg(not(any(target_os = "android", target_os = "ios")))]
269    #[test]
270    fn non_usb_ports_have_no_usb_fields() {
271        let d = details_from_type("/dev/ttyS0".into(), serialport::SerialPortType::PciPort);
272        assert_eq!(d.port_type, PortType::Pci);
273        assert_eq!(d.vid, None);
274        assert_eq!(d.interface, None);
275        assert_eq!(d.location, None);
276        let bt = details_from_type("x".into(), serialport::SerialPortType::BluetoothPort);
277        assert_eq!(bt.port_type, PortType::Bluetooth);
278    }
279
280    #[cfg(not(any(target_os = "android", target_os = "ios")))]
281    #[test]
282    fn every_type_keeps_its_path_and_usb_fields() {
283        let usb = details_from_type(
284            "/dev/ttyUSB7".into(),
285            serialport::SerialPortType::UsbPort(serialport::UsbPortInfo {
286                vid: 1,
287                pid: 2,
288                serial_number: Some("S".into()),
289                manufacturer: Some("M".into()),
290                product: Some("P".into()),
291                #[cfg(feature = "usb-port-details")]
292                location: None,
293                #[cfg(feature = "usb-port-details")]
294                interface: None,
295            }),
296        );
297        assert_eq!(
298            usb,
299            PortDetails {
300                path: "/dev/ttyUSB7".into(),
301                port_type: PortType::Usb,
302                vid: Some(1),
303                pid: Some(2),
304                serial_number: Some("S".into()),
305                manufacturer: Some("M".into()),
306                product: Some("P".into()),
307                ..Default::default()
308            }
309        );
310        use serialport::SerialPortType as T;
311        for (t, kind) in [
312            (T::BluetoothPort, PortType::Bluetooth),
313            (T::PciPort, PortType::Pci),
314            (T::Unknown, PortType::Unknown),
315        ] {
316            let d = details_from_type("/dev/x".into(), t);
317            assert_eq!(d.path, "/dev/x");
318            assert_eq!(d.port_type, kind);
319        }
320    }
321
322    /// The typed list holds exactly the ports serialport enumerates, in path order.
323    #[cfg(not(any(target_os = "android", target_os = "ios")))]
324    #[test]
325    fn detailed_list_matches_the_system_ports() {
326        let raw: Vec<String> = crate::port::list::raw_ports()
327            .unwrap()
328            .into_iter()
329            .map(|p| p.port_name)
330            .collect();
331        let paths: Vec<String> = available_ports_detailed()
332            .unwrap()
333            .into_iter()
334            .map(|d| d.path)
335            .collect();
336        assert_eq!(paths, raw);
337    }
338
339    #[test]
340    fn from_info_map_keeps_path_text_fields_and_types() {
341        let map = HashMap::from([
342            ("type".to_string(), "Bluetooth".to_string()),
343            ("serial_number".to_string(), "SN".to_string()),
344            ("product".to_string(), "Prod".to_string()),
345        ]);
346        let d = details_from_info_map("/dev/rfcomm0".into(), &map);
347        assert_eq!(d.path, "/dev/rfcomm0");
348        assert_eq!(d.port_type, PortType::Bluetooth);
349        assert_eq!(d.serial_number.as_deref(), Some("SN"));
350        assert_eq!(d.product.as_deref(), Some("Prod"));
351        let pci = HashMap::from([("type".to_string(), "PCI".to_string())]);
352        assert_eq!(
353            details_from_info_map("p".into(), &pci).port_type,
354            PortType::Pci
355        );
356    }
357
358    /// Android and iOS go through the 4.x map: hex ("0x1A86") or decimal vid/pid,
359    /// "Unknown" becomes `None`.
360    #[test]
361    fn from_info_map_parses_vid_pid_and_unknown() {
362        let map = HashMap::from([
363            ("type".to_string(), "USB".to_string()),
364            ("vid".to_string(), "0x1A86".to_string()),
365            ("pid".to_string(), "29987".to_string()),
366            ("serial_number".to_string(), "Unknown".to_string()),
367            ("manufacturer".to_string(), "QinHeng".to_string()),
368            ("product".to_string(), "Unknown".to_string()),
369        ]);
370        let d = details_from_info_map("/dev/bus/usb/001/002#1".into(), &map);
371        assert_eq!(d.port_type, PortType::Usb);
372        assert_eq!(d.vid, Some(0x1a86));
373        assert_eq!(d.pid, Some(29987));
374        assert_eq!(d.serial_number, None);
375        assert_eq!(d.manufacturer.as_deref(), Some("QinHeng"));
376        assert_eq!(d.product, None);
377        let empty = details_from_info_map("x".into(), &HashMap::new());
378        assert_eq!(empty.port_type, PortType::Unknown);
379    }
380
381    #[cfg(unix)]
382    #[test]
383    fn serial_links_maps_targets_to_link_names() {
384        // Removed on drop too, so a failed assert (or a mutant) leaves no temp dir behind.
385        struct Cleanup(std::path::PathBuf);
386        impl Drop for Cleanup {
387            fn drop(&mut self) {
388                let _ = std::fs::remove_dir_all(&self.0);
389            }
390        }
391        // Next to the test binary (inside cargo's target dir), not the system temp dir.
392        let exe = std::env::current_exe().unwrap();
393        let root = exe
394            .parent()
395            .unwrap()
396            .join(format!("sp-links-{}", std::process::id()));
397        let _ = std::fs::remove_dir_all(&root);
398        let _cleanup = Cleanup(root.clone());
399        let by_id = root.join("by-id");
400        std::fs::create_dir_all(&by_id).unwrap();
401        let dev = root.join("ttyUSB0");
402        std::fs::write(&dev, b"").unwrap();
403        std::os::unix::fs::symlink(&dev, by_id.join("usb-Quectel_EG25-if00-port0")).unwrap();
404        std::os::unix::fs::symlink("../ttyUSB0", by_id.join("usb-alias")).unwrap();
405        std::os::unix::fs::symlink(root.join("gone"), by_id.join("dangling")).unwrap();
406
407        let links = serial_links(&by_id);
408        let target = dev.canonicalize().unwrap();
409        assert_eq!(
410            links.get(&target).cloned().unwrap_or_default(),
411            vec![
412                by_id
413                    .join("usb-Quectel_EG25-if00-port0")
414                    .display()
415                    .to_string(),
416                by_id.join("usb-alias").display().to_string(),
417            ]
418        );
419        assert_eq!(links.len(), 1);
420        assert!(serial_links(&root.join("missing")).is_empty());
421        std::fs::remove_dir_all(&root).unwrap();
422    }
423
424    /// Live check: `cargo test -p serialplugin-core live_print_details -- --ignored --nocapture`.
425    #[cfg(not(any(target_os = "android", target_os = "ios")))]
426    #[test]
427    #[ignore = "needs real serial hardware"]
428    fn live_print_details() {
429        for d in available_ports_detailed().unwrap() {
430            println!("{d:#?}");
431        }
432    }
433}