Skip to main content

serialplugin_core/port/
list.rs

1//! Helpers for normalizing port lists returned by `serialport-rs`.
2
3#[cfg(not(target_os = "android"))]
4use crate::error::Error;
5#[cfg(not(any(target_os = "android", target_os = "ios")))]
6use crate::state::{BLUETOOTH, PCI, UNKNOWN, USB};
7use std::collections::HashMap;
8
9#[cfg(not(any(target_os = "android", target_os = "ios")))]
10use serialport::SerialPortType;
11
12/// Build metadata map for one enumerated port (desktop).
13#[cfg(not(any(target_os = "android", target_os = "ios")))]
14pub fn port_info_from_type(port: SerialPortType) -> HashMap<String, String> {
15    let mut port_info: HashMap<String, String> = HashMap::new();
16    port_info.insert("type".to_string(), UNKNOWN.to_string());
17    port_info.insert("vid".to_string(), UNKNOWN.to_string());
18    port_info.insert("pid".to_string(), UNKNOWN.to_string());
19    port_info.insert("serial_number".to_string(), UNKNOWN.to_string());
20    port_info.insert("manufacturer".to_string(), UNKNOWN.to_string());
21    port_info.insert("product".to_string(), UNKNOWN.to_string());
22
23    match port {
24        SerialPortType::UsbPort(info) => {
25            port_info.insert("type".to_string(), USB.to_string());
26            port_info.insert("vid".to_string(), info.vid.to_string());
27            port_info.insert("pid".to_string(), info.pid.to_string());
28            port_info.insert(
29                "serial_number".to_string(),
30                info.serial_number.unwrap_or_else(|| UNKNOWN.to_string()),
31            );
32            port_info.insert(
33                "manufacturer".to_string(),
34                info.manufacturer.unwrap_or_else(|| UNKNOWN.to_string()),
35            );
36            port_info.insert(
37                "product".to_string(),
38                info.product.unwrap_or_else(|| UNKNOWN.to_string()),
39            );
40        }
41        SerialPortType::BluetoothPort => {
42            port_info.insert("type".to_string(), BLUETOOTH.to_string());
43        }
44        SerialPortType::PciPort => {
45            port_info.insert("type".to_string(), PCI.to_string());
46        }
47        SerialPortType::Unknown => {
48            port_info.insert("type".to_string(), UNKNOWN.to_string());
49        }
50    }
51
52    port_info
53}
54
55/// Enumerate available serial ports (desktop), with optional macOS de-duplication.
56/// iOS has no local serial ports (only `tcp://` works there): an empty list.
57#[cfg(not(target_os = "android"))]
58pub fn enumerate_available_ports(
59    single_port_per_device: bool,
60) -> Result<HashMap<String, HashMap<String, String>>, Error> {
61    #[cfg(target_os = "ios")]
62    {
63        let _ = single_port_per_device;
64        Ok(HashMap::new())
65    }
66    #[cfg(not(target_os = "ios"))]
67    {
68        Ok(enumerate_with_locations(single_port_per_device)?.0)
69    }
70}
71
72/// path -> 4.x info map.
73#[cfg(not(any(target_os = "android", target_os = "ios")))]
74type PortListMap = HashMap<String, HashMap<String, String>>;
75
76/// Raw `serialport` enumeration, sorted by path.
77#[cfg(not(any(target_os = "android", target_os = "ios")))]
78pub(crate) fn raw_ports() -> Result<Vec<serialport::SerialPortInfo>, Error> {
79    let mut list = serialport::available_ports()
80        .map_err(|e| Error::String(format!("Failed to enumerate serial ports: {}", e)))?;
81    list.sort_by(|a, b| a.port_name.cmp(&b.port_name));
82    Ok(list)
83}
84
85/// [`enumerate_available_ports`] plus each USB port's location (one scan), so the
86/// port-list monitor can see a different device re-plugged on the same path.
87#[cfg(not(any(target_os = "android", target_os = "ios")))]
88pub(crate) fn enumerate_with_locations(
89    single_port_per_device: bool,
90) -> Result<(PortListMap, HashMap<String, String>), Error> {
91    let list = raw_ports()?;
92    let mut locations = HashMap::new();
93    let mut result_list: HashMap<String, HashMap<String, String>> = HashMap::new();
94    for p in list {
95        if let Some(loc) = crate::port::details::usb_location(&p.port_type) {
96            locations.insert(p.port_name.clone(), loc);
97        }
98        result_list.insert(p.port_name, port_info_from_type(p.port_type));
99    }
100
101    #[cfg(target_os = "windows")]
102    for (port, instances) in windows_full_serials() {
103        if let Some(info) = result_list.get_mut(&port) {
104            let current = info.get("serial_number").map(String::as_str).unwrap_or("");
105            if let Some(full) = pick_full_serial(current, &instances) {
106                let full = full.to_string();
107                info.insert("serial_number".to_string(), full);
108            }
109        }
110    }
111
112    Ok((
113        apply_single_port_per_device(result_list, single_port_per_device),
114        locations,
115    ))
116}
117
118/// True when `full` (a USB device-instance key name) is the untruncated `current`
119/// serial. Composite-device instance ids ("6&2f3c...&0&0000") are not serial numbers.
120#[cfg(any(target_os = "windows", test))]
121pub(crate) fn extends_serial(current: &str, full: &str) -> bool {
122    full.len() > current.len() && full.starts_with(current) && !current.is_empty()
123}
124
125/// The first device instance that is the untruncated `current` serial (several
126/// instances, a phantom one included, can carry one COM name).
127#[cfg(any(target_os = "windows", test))]
128pub(crate) fn pick_full_serial<'a>(current: &str, instances: &'a [String]) -> Option<&'a str> {
129    instances
130        .iter()
131        .map(String::as_str)
132        .find(|full| extends_serial(current, full))
133}
134
135/// COM port -> every USB device-instance key name with that PortName (one of them
136/// is the full serial number).
137#[cfg(target_os = "windows")]
138pub(crate) fn windows_full_serials() -> HashMap<String, Vec<String>> {
139    // serialport truncates USB serial numbers at '-' (serialport-rs#351). The full
140    // one is the device-instance key name; its "Device Parameters\PortName" maps it
141    // to COMx. Read the registry directly: `wmic` is gone from Windows 11 24H2+ and
142    // spawning it flashed a console window on every port-list poll.
143    use winreg::enums::HKEY_LOCAL_MACHINE;
144    use winreg::RegKey;
145
146    let mut out = HashMap::new();
147    let Ok(usb) =
148        RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(r"SYSTEM\CurrentControlSet\Enum\USB")
149    else {
150        return out;
151    };
152    for vid_pid in usb.enum_keys().flatten() {
153        let Ok(device) = usb.open_subkey(&vid_pid) else {
154            continue;
155        };
156        for instance in device.enum_keys().flatten() {
157            let Ok(params) = device.open_subkey(format!(r"{instance}\Device Parameters")) else {
158                continue;
159            };
160            if let Ok(port_name) = params.get_value::<String, _>("PortName") {
161                out.entry(port_name).or_insert_with(Vec::new).push(instance);
162            }
163        }
164    }
165    out
166}
167
168/// macOS exposes each serial device twice: `/dev/cu.*` (callout) and `/dev/tty.*` (dial-in).
169/// `serialport-rs` returns both; Node.js `SerialPort.list()` keeps callout only.
170///
171/// When `single_port_per_device` is true, keeps one path per device suffix, preferring callout.
172pub fn apply_single_port_per_device(
173    ports: HashMap<String, HashMap<String, String>>,
174    single_port_per_device: bool,
175) -> HashMap<String, HashMap<String, String>> {
176    if !single_port_per_device {
177        return ports;
178    }
179    filter_macos_single_port_per_device(ports)
180}
181
182/// When `single_port_per_device` is true, keeps one USB serial port per Android device
183/// (lowest port index; paths without `#` are port 0).
184pub fn apply_android_single_port_per_device(
185    ports: HashMap<String, HashMap<String, String>>,
186    single_port_per_device: bool,
187) -> HashMap<String, HashMap<String, String>> {
188    if !single_port_per_device {
189        return ports;
190    }
191    let mut best: HashMap<String, (u32, String, HashMap<String, String>)> = HashMap::new();
192    for (path, info) in ports {
193        let (device, port_idx) = android_path_parts(&path);
194        let replace = match best.get(device) {
195            None => true,
196            Some((idx, _, _)) => port_idx < *idx,
197        };
198        if replace {
199            best.insert(device.to_string(), (port_idx, path, info));
200        }
201    }
202    best.into_values()
203        .map(|(_, path, info)| (path, info))
204        .collect()
205}
206
207fn android_path_parts(path: &str) -> (&str, u32) {
208    if let Some(idx) = path.rfind('#') {
209        let port = path[idx + 1..].parse().unwrap_or(0);
210        (&path[..idx], port)
211    } else {
212        (path, 0)
213    }
214}
215
216fn filter_macos_single_port_per_device(
217    ports: HashMap<String, HashMap<String, String>>,
218) -> HashMap<String, HashMap<String, String>> {
219    let mut callout: HashMap<String, (String, HashMap<String, String>)> = HashMap::new();
220    let mut dialin: HashMap<String, (String, HashMap<String, String>)> = HashMap::new();
221    let mut other: HashMap<String, HashMap<String, String>> = HashMap::new();
222
223    for (path, info) in ports {
224        if let Some(suffix) = path.strip_prefix("/dev/cu.") {
225            callout.insert(suffix.to_string(), (path, info));
226        } else if let Some(suffix) = path.strip_prefix("/dev/tty.") {
227            dialin.insert(suffix.to_string(), (path, info));
228        } else {
229            other.insert(path, info);
230        }
231    }
232
233    let mut result = other;
234    for (suffix, entry) in dialin {
235        callout.entry(suffix).or_insert(entry);
236    }
237    for (_, (path, info)) in callout {
238        result.insert(path, info);
239    }
240    result
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    fn info(type_: &str) -> HashMap<String, String> {
248        HashMap::from([("type".to_string(), type_.to_string())])
249    }
250
251    #[test]
252    fn no_op_when_disabled() {
253        let ports = HashMap::from([
254            ("/dev/cu.usbmodem1".to_string(), info("USB")),
255            ("/dev/tty.usbmodem1".to_string(), info("USB")),
256        ]);
257        let out = apply_single_port_per_device(ports.clone(), false);
258        assert_eq!(out.len(), 2);
259        assert_eq!(out, ports);
260    }
261
262    #[test]
263    fn prefers_callout_over_dialin_for_same_suffix() {
264        let ports = HashMap::from([
265            ("/dev/tty.usbmodem1421".to_string(), info("USB")),
266            ("/dev/cu.usbmodem1421".to_string(), info("USB")),
267            (
268                "/dev/cu.Bluetooth-Incoming-Port".to_string(),
269                info("Bluetooth"),
270            ),
271            (
272                "/dev/tty.Bluetooth-Incoming-Port".to_string(),
273                info("Bluetooth"),
274            ),
275        ]);
276        let out = apply_single_port_per_device(ports, true);
277        assert_eq!(out.len(), 2);
278        assert!(out.contains_key("/dev/cu.usbmodem1421"));
279        assert!(out.contains_key("/dev/cu.Bluetooth-Incoming-Port"));
280        assert!(!out.contains_key("/dev/tty.usbmodem1421"));
281    }
282
283    #[test]
284    fn keeps_dialin_when_callout_missing() {
285        let ports = HashMap::from([("/dev/tty.usbserial-ABC".to_string(), info("USB"))]);
286        let out = apply_single_port_per_device(ports, true);
287        assert_eq!(out.len(), 1);
288        assert!(out.contains_key("/dev/tty.usbserial-ABC"));
289    }
290
291    #[test]
292    fn preserves_non_macos_style_paths() {
293        let ports = HashMap::from([
294            ("COM3".to_string(), info("USB")),
295            ("/dev/ttyUSB0".to_string(), info("USB")),
296        ]);
297        let out = apply_single_port_per_device(ports.clone(), true);
298        assert_eq!(out, ports);
299    }
300
301    #[test]
302    fn extends_only_truncated_serials() {
303        assert!(extends_serial("A1B2", "A1B2-C3"));
304        assert!(!extends_serial("", "6&2f3c&0&0000"));
305        assert!(!extends_serial("A1B2", "6&2f3c&0&0000"));
306        assert!(!extends_serial("A1B2", "A1B2"));
307    }
308
309    /// Several device instances can map to one COM name (a phantom one included):
310    /// the one that extends the truncated serial wins, as in 4.x.
311    #[test]
312    fn full_serial_is_picked_from_every_instance() {
313        let instances = vec![
314            "6&2f3c&0&0000".to_string(),
315            "A1B2-C3".to_string(),
316            "ZZZ".to_string(),
317        ];
318        assert_eq!(pick_full_serial("A1B2", &instances), Some("A1B2-C3"));
319        assert_eq!(pick_full_serial("Q9", &instances), None);
320    }
321
322    #[test]
323    fn android_keeps_lowest_port_index_per_device() {
324        let ports = HashMap::from([
325            ("/dev/bus/usb/001/002#1".to_string(), info("USB")),
326            ("/dev/bus/usb/001/002#0".to_string(), info("USB")),
327            ("/dev/bus/usb/001/003".to_string(), info("USB")),
328        ]);
329        let out = apply_android_single_port_per_device(ports, true);
330        assert_eq!(out.len(), 2);
331        assert!(out.contains_key("/dev/bus/usb/001/002#0"));
332        assert!(out.contains_key("/dev/bus/usb/001/003"));
333    }
334
335    /// Whatever order the map yields the ports in (each new map has its own hash
336    /// seed), the lowest index wins.
337    #[test]
338    fn android_lowest_index_wins_in_any_order() {
339        for _ in 0..64 {
340            let ports: HashMap<String, HashMap<String, String>> = ["#2", "#0", "#1", "#3"]
341                .iter()
342                .map(|i| (format!("/dev/bus/usb/001/002{i}"), info("USB")))
343                .collect();
344            let out = apply_android_single_port_per_device(ports, true);
345            assert_eq!(
346                out.keys().collect::<Vec<_>>(),
347                vec!["/dev/bus/usb/001/002#0"]
348            );
349        }
350    }
351
352    #[cfg(not(any(target_os = "android", target_os = "ios")))]
353    fn usb_type(serial: Option<&str>) -> SerialPortType {
354        SerialPortType::UsbPort(serialport::UsbPortInfo {
355            vid: 0x1a86,
356            pid: 0x7523,
357            serial_number: serial.map(Into::into),
358            manufacturer: serial.map(|_| "QinHeng".into()),
359            product: serial.map(|_| "CH340".into()),
360            #[cfg(feature = "usb-port-details")]
361            location: None,
362            #[cfg(feature = "usb-port-details")]
363            interface: None,
364        })
365    }
366
367    #[cfg(not(any(target_os = "android", target_os = "ios")))]
368    #[test]
369    fn port_info_map_per_type() {
370        let get = |m: &HashMap<String, String>, k: &str| m.get(k).cloned().unwrap();
371        let usb = port_info_from_type(usb_type(Some("A1")));
372        assert_eq!(get(&usb, "type"), USB);
373        assert_eq!(get(&usb, "vid"), "6790");
374        assert_eq!(get(&usb, "pid"), "29987");
375        assert_eq!(get(&usb, "serial_number"), "A1");
376        assert_eq!(get(&usb, "manufacturer"), "QinHeng");
377        assert_eq!(get(&usb, "product"), "CH340");
378        let bare = port_info_from_type(usb_type(None));
379        for k in ["serial_number", "manufacturer", "product"] {
380            assert_eq!(get(&bare, k), UNKNOWN, "{k}");
381        }
382        for (t, name) in [
383            (SerialPortType::BluetoothPort, BLUETOOTH),
384            (SerialPortType::PciPort, PCI),
385            (SerialPortType::Unknown, UNKNOWN),
386        ] {
387            let m = port_info_from_type(t);
388            assert_eq!(get(&m, "type"), name);
389            assert_eq!(get(&m, "vid"), UNKNOWN);
390            assert_eq!(m.len(), 6);
391        }
392    }
393
394    /// The 4.x map lists exactly what serialport enumerates.
395    #[cfg(not(any(target_os = "android", target_os = "ios")))]
396    #[test]
397    fn enumeration_lists_the_system_ports() {
398        let mut raw: Vec<String> = raw_ports()
399            .unwrap()
400            .into_iter()
401            .map(|p| p.port_name)
402            .collect();
403        raw.sort();
404        let keys = |m: &HashMap<String, HashMap<String, String>>| {
405            let mut k: Vec<String> = m.keys().cloned().collect();
406            k.sort();
407            k
408        };
409        assert_eq!(keys(&enumerate_available_ports(false).unwrap()), raw);
410        let (map, locations) = enumerate_with_locations(false).unwrap();
411        assert_eq!(keys(&map), raw);
412        assert!(map.values().all(|info| info.len() == 6));
413        #[cfg(not(feature = "usb-port-details"))]
414        assert!(locations.is_empty());
415        #[cfg(feature = "usb-port-details")]
416        assert!(locations.keys().all(|k| raw.contains(k)));
417    }
418}