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    //! In `src/`: the Windows registry helpers are private (and pure), and the locations are
246    //! only read by the port-list monitor.
247    use super::*;
248
249    /// Several device instances can map to one COM name (a phantom one included): the one
250    /// that extends the truncated serial wins, as in 4.x; an unrelated or equal one is none.
251    #[test]
252    fn a_truncated_serial_is_completed_from_its_instances() {
253        for (current, full, extends) in [
254            ("A1B2", "A1B2-C3", true),
255            ("", "6&2f3c&0&0000", false),
256            ("A1B2", "6&2f3c&0&0000", false),
257            ("A1B2", "A1B2", false),
258        ] {
259            assert_eq!(extends_serial(current, full), extends, "{current} {full}");
260        }
261        let instances = ["6&2f3c&0&0000", "A1B2-C3", "ZZZ"].map(String::from);
262        assert_eq!(pick_full_serial("A1B2", &instances), Some("A1B2-C3"));
263        assert_eq!(pick_full_serial("Q9", &instances), None);
264    }
265
266    #[cfg(not(any(target_os = "android", target_os = "ios")))]
267    #[test]
268    fn locations_belong_to_listed_ports() {
269        let (map, locations) = enumerate_with_locations(false).unwrap();
270        assert!(locations.keys().all(|k| map.contains_key(k)));
271        #[cfg(not(feature = "usb-port-details"))]
272        assert!(locations.is_empty());
273    }
274}