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/// iOS has no local serial ports (only `tcp://` works there): an empty list.
56#[cfg(target_os = "ios")]
57pub fn enumerate_available_ports(
58    _single_port_per_device: bool,
59) -> Result<HashMap<String, HashMap<String, String>>, Error> {
60    Ok(HashMap::new())
61}
62
63/// Enumerate available serial ports (desktop), with optional macOS de-duplication.
64#[cfg(not(any(target_os = "android", target_os = "ios")))]
65pub fn enumerate_available_ports(
66    single_port_per_device: bool,
67) -> Result<HashMap<String, HashMap<String, String>>, Error> {
68    Ok(enumerate_with_locations(single_port_per_device)?.0)
69}
70
71/// path -> 4.x info map.
72#[cfg(not(any(target_os = "android", target_os = "ios")))]
73type PortListMap = HashMap<String, HashMap<String, String>>;
74
75/// Raw `serialport` enumeration, sorted by path.
76#[cfg(not(any(target_os = "android", target_os = "ios")))]
77pub(crate) fn raw_ports() -> Result<Vec<serialport::SerialPortInfo>, Error> {
78    let mut list = serialport::available_ports()
79        .map_err(|e| Error::String(format!("Failed to enumerate serial ports: {}", e)))?;
80    list.sort_by(|a, b| a.port_name.cmp(&b.port_name));
81    Ok(list)
82}
83
84/// [`enumerate_available_ports`] plus each USB port's location (one scan), so the
85/// port-list monitor can see a different device re-plugged on the same path.
86#[cfg(not(any(target_os = "android", target_os = "ios")))]
87pub(crate) fn enumerate_with_locations(
88    single_port_per_device: bool,
89) -> Result<(PortListMap, HashMap<String, String>), Error> {
90    let list = raw_ports()?;
91    let mut locations = HashMap::new();
92    let mut result_list: HashMap<String, HashMap<String, String>> = HashMap::new();
93    for p in list {
94        if let Some(loc) = crate::port::details::usb_location(&p.port_type) {
95            locations.insert(p.port_name.clone(), loc);
96        }
97        result_list.insert(p.port_name, port_info_from_type(p.port_type));
98    }
99
100    #[cfg(target_os = "windows")]
101    for (port, instances) in windows_full_serials() {
102        if let Some(info) = result_list.get_mut(&port) {
103            let current = info.get("serial_number").map(String::as_str).unwrap_or("");
104            if let Some(full) = pick_full_serial(current, &instances) {
105                let full = full.to_string();
106                info.insert("serial_number".to_string(), full);
107            }
108        }
109    }
110
111    Ok((
112        apply_single_port_per_device(result_list, single_port_per_device),
113        locations,
114    ))
115}
116
117/// True when `full` (a USB device-instance key name) is the untruncated `current`
118/// serial. Composite-device instance ids ("6&2f3c...&0&0000") are not serial numbers.
119#[cfg(any(target_os = "windows", test))]
120pub(crate) fn extends_serial(current: &str, full: &str) -> bool {
121    full.len() > current.len() && full.starts_with(current) && !current.is_empty()
122}
123
124/// The first device instance that is the untruncated `current` serial (several
125/// instances, a phantom one included, can carry one COM name).
126#[cfg(any(target_os = "windows", test))]
127pub(crate) fn pick_full_serial<'a>(current: &str, instances: &'a [String]) -> Option<&'a str> {
128    instances
129        .iter()
130        .map(String::as_str)
131        .find(|full| extends_serial(current, full))
132}
133
134/// COM port -> every USB device-instance key name with that PortName (one of them
135/// is the full serial number).
136#[cfg(target_os = "windows")]
137pub(crate) fn windows_full_serials() -> HashMap<String, Vec<String>> {
138    // serialport truncates USB serial numbers at '-' (serialport-rs#351). The full
139    // one is the device-instance key name; its "Device Parameters\PortName" maps it
140    // to COMx. Read the registry directly: `wmic` is gone from Windows 11 24H2+ and
141    // spawning it flashed a console window on every port-list poll.
142    use winreg::enums::HKEY_LOCAL_MACHINE;
143    use winreg::RegKey;
144
145    let mut out = HashMap::new();
146    let Ok(usb) =
147        RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(r"SYSTEM\CurrentControlSet\Enum\USB")
148    else {
149        return out;
150    };
151    for vid_pid in usb.enum_keys().flatten() {
152        let Ok(device) = usb.open_subkey(&vid_pid) else {
153            continue;
154        };
155        for instance in device.enum_keys().flatten() {
156            let Ok(params) = device.open_subkey(format!(r"{instance}\Device Parameters")) else {
157                continue;
158            };
159            if let Ok(port_name) = params.get_value::<String, _>("PortName") {
160                out.entry(port_name).or_insert_with(Vec::new).push(instance);
161            }
162        }
163    }
164    out
165}
166
167/// macOS exposes each serial device twice: `/dev/cu.*` (callout) and `/dev/tty.*` (dial-in).
168/// `serialport-rs` returns both; Node.js `SerialPort.list()` keeps callout only.
169///
170/// When `single_port_per_device` is true, keeps one path per device suffix, preferring callout.
171pub fn apply_single_port_per_device(
172    ports: HashMap<String, HashMap<String, String>>,
173    single_port_per_device: bool,
174) -> HashMap<String, HashMap<String, String>> {
175    if !single_port_per_device {
176        return ports;
177    }
178    filter_macos_single_port_per_device(ports)
179}
180
181/// When `single_port_per_device` is true, keeps one USB serial port per Android device
182/// (lowest port index; paths without `#` are port 0).
183pub fn apply_android_single_port_per_device(
184    ports: HashMap<String, HashMap<String, String>>,
185    single_port_per_device: bool,
186) -> HashMap<String, HashMap<String, String>> {
187    if !single_port_per_device {
188        return ports;
189    }
190    let mut best: HashMap<String, (u32, String, HashMap<String, String>)> = HashMap::new();
191    for (path, info) in ports {
192        let (device, port_idx) = android_path_parts(&path);
193        let replace = match best.get(device) {
194            None => true,
195            Some((idx, _, _)) => port_idx < *idx,
196        };
197        if replace {
198            best.insert(device.to_string(), (port_idx, path, info));
199        }
200    }
201    best.into_values()
202        .map(|(_, path, info)| (path, info))
203        .collect()
204}
205
206fn android_path_parts(path: &str) -> (&str, u32) {
207    if let Some(idx) = path.rfind('#') {
208        let port = path[idx + 1..].parse().unwrap_or(0);
209        (&path[..idx], port)
210    } else {
211        (path, 0)
212    }
213}
214
215fn filter_macos_single_port_per_device(
216    ports: HashMap<String, HashMap<String, String>>,
217) -> HashMap<String, HashMap<String, String>> {
218    let mut callout: HashMap<String, (String, HashMap<String, String>)> = HashMap::new();
219    let mut dialin: HashMap<String, (String, HashMap<String, String>)> = HashMap::new();
220    let mut other: HashMap<String, HashMap<String, String>> = HashMap::new();
221
222    for (path, info) in ports {
223        if let Some(suffix) = path.strip_prefix("/dev/cu.") {
224            callout.insert(suffix.to_string(), (path, info));
225        } else if let Some(suffix) = path.strip_prefix("/dev/tty.") {
226            dialin.insert(suffix.to_string(), (path, info));
227        } else {
228            other.insert(path, info);
229        }
230    }
231
232    let mut result = other;
233    for (suffix, entry) in dialin {
234        callout.entry(suffix).or_insert(entry);
235    }
236    for (_, (path, info)) in callout {
237        result.insert(path, info);
238    }
239    result
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    fn info(type_: &str) -> HashMap<String, String> {
247        HashMap::from([("type".to_string(), type_.to_string())])
248    }
249
250    #[test]
251    fn no_op_when_disabled() {
252        let ports = HashMap::from([
253            ("/dev/cu.usbmodem1".to_string(), info("USB")),
254            ("/dev/tty.usbmodem1".to_string(), info("USB")),
255        ]);
256        let out = apply_single_port_per_device(ports.clone(), false);
257        assert_eq!(out.len(), 2);
258        assert_eq!(out, ports);
259    }
260
261    #[test]
262    fn prefers_callout_over_dialin_for_same_suffix() {
263        let ports = HashMap::from([
264            ("/dev/tty.usbmodem1421".to_string(), info("USB")),
265            ("/dev/cu.usbmodem1421".to_string(), info("USB")),
266            (
267                "/dev/cu.Bluetooth-Incoming-Port".to_string(),
268                info("Bluetooth"),
269            ),
270            (
271                "/dev/tty.Bluetooth-Incoming-Port".to_string(),
272                info("Bluetooth"),
273            ),
274        ]);
275        let out = apply_single_port_per_device(ports, true);
276        assert_eq!(out.len(), 2);
277        assert!(out.contains_key("/dev/cu.usbmodem1421"));
278        assert!(out.contains_key("/dev/cu.Bluetooth-Incoming-Port"));
279        assert!(!out.contains_key("/dev/tty.usbmodem1421"));
280    }
281
282    #[test]
283    fn keeps_dialin_when_callout_missing() {
284        let ports = HashMap::from([("/dev/tty.usbserial-ABC".to_string(), info("USB"))]);
285        let out = apply_single_port_per_device(ports, true);
286        assert_eq!(out.len(), 1);
287        assert!(out.contains_key("/dev/tty.usbserial-ABC"));
288    }
289
290    #[test]
291    fn preserves_non_macos_style_paths() {
292        let ports = HashMap::from([
293            ("COM3".to_string(), info("USB")),
294            ("/dev/ttyUSB0".to_string(), info("USB")),
295        ]);
296        let out = apply_single_port_per_device(ports.clone(), true);
297        assert_eq!(out, ports);
298    }
299
300    #[test]
301    fn extends_only_truncated_serials() {
302        assert!(extends_serial("A1B2", "A1B2-C3"));
303        assert!(!extends_serial("", "6&2f3c&0&0000"));
304        assert!(!extends_serial("A1B2", "6&2f3c&0&0000"));
305        assert!(!extends_serial("A1B2", "A1B2"));
306    }
307
308    /// Several device instances can map to one COM name (a phantom one included):
309    /// the one that extends the truncated serial wins, as in 4.x.
310    #[test]
311    fn full_serial_is_picked_from_every_instance() {
312        let instances = vec![
313            "6&2f3c&0&0000".to_string(),
314            "A1B2-C3".to_string(),
315            "ZZZ".to_string(),
316        ];
317        assert_eq!(pick_full_serial("A1B2", &instances), Some("A1B2-C3"));
318        assert_eq!(pick_full_serial("Q9", &instances), None);
319    }
320
321    #[test]
322    fn android_keeps_lowest_port_index_per_device() {
323        let ports = HashMap::from([
324            ("/dev/bus/usb/001/002#1".to_string(), info("USB")),
325            ("/dev/bus/usb/001/002#0".to_string(), info("USB")),
326            ("/dev/bus/usb/001/003".to_string(), info("USB")),
327        ]);
328        let out = apply_android_single_port_per_device(ports, true);
329        assert_eq!(out.len(), 2);
330        assert!(out.contains_key("/dev/bus/usb/001/002#0"));
331        assert!(out.contains_key("/dev/bus/usb/001/003"));
332    }
333}