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    let location = usb_location(&port);
70    match port {
71        T::UsbPort(info) => PortDetails {
72            path,
73            port_type: PortType::Usb,
74            vid: Some(info.vid),
75            pid: Some(info.pid),
76            serial_number: info.serial_number,
77            manufacturer: info.manufacturer,
78            product: info.product,
79            #[cfg(feature = "usb-port-details")]
80            interface: info.interface,
81            location,
82            ..Default::default()
83        },
84        T::BluetoothPort => PortDetails {
85            path,
86            port_type: PortType::Bluetooth,
87            ..Default::default()
88        },
89        T::PciPort => PortDetails {
90            path,
91            port_type: PortType::Pci,
92            ..Default::default()
93        },
94        T::Unknown => PortDetails {
95            path,
96            ..Default::default()
97        },
98    }
99}
100
101/// Convert a 4.x string map (Android, iOS): `"Unknown"` -> `None`, vid/pid hex
102/// (`0x1A86`) or decimal. No interface / location there.
103pub fn details_from_info_map(
104    path: String,
105    info: &std::collections::HashMap<String, String>,
106) -> PortDetails {
107    let text = |k: &str| {
108        info.get(k)
109            .filter(|v| v.as_str() != crate::state::UNKNOWN)
110            .cloned()
111    };
112    let id = |k: &str| {
113        let v = text(k)?;
114        match v.strip_prefix("0x").or_else(|| v.strip_prefix("0X")) {
115            Some(hex) => u16::from_str_radix(hex, 16).ok(),
116            None => v.parse().ok(),
117        }
118    };
119    let port_type = match info.get("type").map(String::as_str) {
120        Some(crate::state::USB) => PortType::Usb,
121        Some(crate::state::BLUETOOTH) => PortType::Bluetooth,
122        Some(crate::state::PCI) => PortType::Pci,
123        _ => PortType::Unknown,
124    };
125    PortDetails {
126        path,
127        port_type,
128        vid: id("vid"),
129        pid: id("pid"),
130        serial_number: text("serial_number"),
131        manufacturer: text("manufacturer"),
132        product: text("product"),
133        ..Default::default()
134    }
135}
136
137/// Symlinks in `dir`, grouped by their canonical target (sorted link paths).
138/// Dangling links and a missing `dir` are skipped.
139#[cfg(any(all(target_os = "linux", not(target_os = "android")), all(test, unix)))]
140fn serial_links(dir: &Path) -> HashMap<PathBuf, Vec<String>> {
141    let mut out: HashMap<PathBuf, Vec<String>> = HashMap::new();
142    let Ok(entries) = std::fs::read_dir(dir) else {
143        return out;
144    };
145    for entry in entries.flatten() {
146        let link = entry.path();
147        if let Ok(target) = link.canonicalize() {
148            out.entry(target)
149                .or_default()
150                .push(link.display().to_string());
151        }
152    }
153    out.values_mut().for_each(|v| v.sort());
154    out
155}
156
157/// Every serial port with typed details, sorted by path (both macOS `cu.` and
158/// `tty.` nodes, no de-duplication). iOS: empty.
159#[cfg(not(target_os = "android"))]
160pub fn available_ports_detailed() -> Result<Vec<PortDetails>, crate::error::Error> {
161    #[cfg(target_os = "ios")]
162    {
163        Ok(Vec::new())
164    }
165    #[cfg(not(target_os = "ios"))]
166    {
167        #[allow(unused_mut)]
168        let mut out: Vec<PortDetails> = crate::port::list::raw_ports()?
169            .into_iter()
170            .map(|p| details_from_type(p.port_name, p.port_type))
171            .collect();
172
173        #[cfg(target_os = "windows")]
174        {
175            let full = crate::port::list::windows_full_serials();
176            for d in &mut out {
177                let picked = match (d.serial_number.as_deref(), full.get(&d.path)) {
178                    (Some(current), Some(instances)) => {
179                        crate::port::list::pick_full_serial(current, instances)
180                    }
181                    _ => None,
182                };
183                if let Some(f) = picked.map(str::to_string) {
184                    d.serial_number = Some(f);
185                }
186            }
187        }
188
189        #[cfg(target_os = "linux")]
190        {
191            let by_id = serial_links(Path::new("/dev/serial/by-id"));
192            let by_path = serial_links(Path::new("/dev/serial/by-path"));
193            for d in &mut out {
194                if let Ok(target) = Path::new(&d.path).canonicalize() {
195                    d.by_id = by_id.get(&target).cloned().unwrap_or_default();
196                    d.by_path = by_path.get(&target).cloned().unwrap_or_default();
197                }
198            }
199        }
200
201        Ok(out)
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use std::collections::HashMap;
209
210    #[cfg(all(
211        feature = "usb-port-details",
212        not(any(target_os = "android", target_os = "ios"))
213    ))]
214    fn quectel(interface: u8) -> serialport::SerialPortType {
215        serialport::SerialPortType::UsbPort(serialport::UsbPortInfo {
216            vid: 0x2c7c,
217            pid: 0x0125,
218            serial_number: Some("a1b2c3".into()),
219            manufacturer: Some("Quectel".into()),
220            product: Some("EG25-G".into()),
221            location: Some(serialport::Location::new("1".into(), vec![2, 3])),
222            interface: Some(interface),
223        })
224    }
225
226    /// The 4 ports of one Quectel modem look the same in the 4.x map; the interface
227    /// number tells them apart.
228    #[cfg(all(
229        feature = "usb-port-details",
230        not(any(target_os = "android", target_os = "ios"))
231    ))]
232    #[test]
233    fn quectel_ports_differ_by_interface_number() {
234        let ports: Vec<PortDetails> = (0..4u8)
235            .map(|i| details_from_type(format!("/dev/ttyUSB{i}"), quectel(i)))
236            .collect();
237        for (i, d) in ports.iter().enumerate() {
238            assert_eq!(d.port_type, PortType::Usb);
239            assert_eq!(d.vid, Some(0x2c7c));
240            assert_eq!(d.pid, Some(0x0125));
241            assert_eq!(d.serial_number.as_deref(), Some("a1b2c3"));
242            assert_eq!(d.manufacturer.as_deref(), Some("Quectel"));
243            assert_eq!(d.product.as_deref(), Some("EG25-G"));
244            assert_eq!(d.location.as_deref(), Some("1-2.3"));
245            assert_eq!(d.interface, Some(i as u8));
246        }
247        let mut ifaces: Vec<_> = ports.iter().map(|d| d.interface).collect();
248        ifaces.dedup();
249        assert_eq!(ifaces.len(), 4);
250
251        let maps: Vec<_> = (0..4u8)
252            .map(|i| crate::port::list::port_info_from_type(quectel(i)))
253            .collect();
254        assert!(
255            maps.iter().all(|m| m == &maps[0]),
256            "4.x map cannot tell them apart"
257        );
258    }
259
260    #[cfg(not(any(target_os = "android", target_os = "ios")))]
261    #[test]
262    fn non_usb_ports_have_no_usb_fields() {
263        let d = details_from_type("/dev/ttyS0".into(), serialport::SerialPortType::PciPort);
264        assert_eq!(d.port_type, PortType::Pci);
265        assert_eq!(d.vid, None);
266        assert_eq!(d.interface, None);
267        assert_eq!(d.location, None);
268        let bt = details_from_type("x".into(), serialport::SerialPortType::BluetoothPort);
269        assert_eq!(bt.port_type, PortType::Bluetooth);
270    }
271
272    /// Android and iOS go through the 4.x map: hex ("0x1A86") or decimal vid/pid,
273    /// "Unknown" becomes `None`.
274    #[test]
275    fn from_info_map_parses_vid_pid_and_unknown() {
276        let map = HashMap::from([
277            ("type".to_string(), "USB".to_string()),
278            ("vid".to_string(), "0x1A86".to_string()),
279            ("pid".to_string(), "29987".to_string()),
280            ("serial_number".to_string(), "Unknown".to_string()),
281            ("manufacturer".to_string(), "QinHeng".to_string()),
282            ("product".to_string(), "Unknown".to_string()),
283        ]);
284        let d = details_from_info_map("/dev/bus/usb/001/002#1".into(), &map);
285        assert_eq!(d.port_type, PortType::Usb);
286        assert_eq!(d.vid, Some(0x1a86));
287        assert_eq!(d.pid, Some(29987));
288        assert_eq!(d.serial_number, None);
289        assert_eq!(d.manufacturer.as_deref(), Some("QinHeng"));
290        assert_eq!(d.product, None);
291        let empty = details_from_info_map("x".into(), &HashMap::new());
292        assert_eq!(empty.port_type, PortType::Unknown);
293    }
294
295    #[cfg(unix)]
296    #[test]
297    fn serial_links_maps_targets_to_link_names() {
298        let root = std::env::temp_dir().join(format!("sp-links-{}", std::process::id()));
299        let _ = std::fs::remove_dir_all(&root);
300        let by_id = root.join("by-id");
301        std::fs::create_dir_all(&by_id).unwrap();
302        let dev = root.join("ttyUSB0");
303        std::fs::write(&dev, b"").unwrap();
304        std::os::unix::fs::symlink(&dev, by_id.join("usb-Quectel_EG25-if00-port0")).unwrap();
305        std::os::unix::fs::symlink("../ttyUSB0", by_id.join("usb-alias")).unwrap();
306        std::os::unix::fs::symlink(root.join("gone"), by_id.join("dangling")).unwrap();
307
308        let links = serial_links(&by_id);
309        let target = dev.canonicalize().unwrap();
310        assert_eq!(
311            links.get(&target).cloned().unwrap_or_default(),
312            vec![
313                by_id
314                    .join("usb-Quectel_EG25-if00-port0")
315                    .display()
316                    .to_string(),
317                by_id.join("usb-alias").display().to_string(),
318            ]
319        );
320        assert_eq!(links.len(), 1);
321        assert!(serial_links(&root.join("missing")).is_empty());
322        std::fs::remove_dir_all(&root).unwrap();
323    }
324
325    /// Live check: `cargo test -p serialplugin-core live_print_details -- --ignored --nocapture`.
326    #[cfg(not(any(target_os = "android", target_os = "ios")))]
327    #[test]
328    #[ignore = "needs real serial hardware"]
329    fn live_print_details() {
330        for d in available_ports_detailed().unwrap() {
331            println!("{d:#?}");
332        }
333    }
334}