1#[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#[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#[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#[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 let mut list = serialport::available_ports()
69 .map_err(|e| Error::String(format!("Failed to enumerate serial ports: {}", e)))?;
70 list.sort_by(|a, b| a.port_name.cmp(&b.port_name));
71
72 let mut result_list: HashMap<String, HashMap<String, String>> = HashMap::new();
73 for p in list {
74 result_list.insert(p.port_name, port_info_from_type(p.port_type));
75 }
76
77 #[cfg(target_os = "windows")]
78 enrich_windows_serial_numbers(&mut result_list);
79
80 Ok(apply_single_port_per_device(
81 result_list,
82 single_port_per_device,
83 ))
84}
85
86#[cfg(target_os = "windows")]
87fn enrich_windows_serial_numbers(ports: &mut HashMap<String, HashMap<String, String>>) {
88 use winreg::enums::HKEY_LOCAL_MACHINE;
93 use winreg::RegKey;
94
95 let Ok(usb) =
96 RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(r"SYSTEM\CurrentControlSet\Enum\USB")
97 else {
98 return;
99 };
100 for vid_pid in usb.enum_keys().flatten() {
101 let Ok(device) = usb.open_subkey(&vid_pid) else {
102 continue;
103 };
104 for instance in device.enum_keys().flatten() {
105 let Ok(params) = device.open_subkey(format!(r"{instance}\Device Parameters")) else {
106 continue;
107 };
108 let Ok(port_name) = params.get_value::<String, _>("PortName") else {
109 continue;
110 };
111 if let Some(info) = ports.get_mut(&port_name) {
112 let current = info.get("serial_number").map(String::as_str).unwrap_or("");
113 if instance.len() > current.len()
116 && instance.starts_with(current)
117 && !current.is_empty()
118 {
119 info.insert("serial_number".to_string(), instance.clone());
120 }
121 }
122 }
123 }
124}
125
126pub fn apply_single_port_per_device(
131 ports: HashMap<String, HashMap<String, String>>,
132 single_port_per_device: bool,
133) -> HashMap<String, HashMap<String, String>> {
134 if !single_port_per_device {
135 return ports;
136 }
137 filter_macos_single_port_per_device(ports)
138}
139
140pub fn apply_android_single_port_per_device(
143 ports: HashMap<String, HashMap<String, String>>,
144 single_port_per_device: bool,
145) -> HashMap<String, HashMap<String, String>> {
146 if !single_port_per_device {
147 return ports;
148 }
149 let mut best: HashMap<String, (u32, String, HashMap<String, String>)> = HashMap::new();
150 for (path, info) in ports {
151 let (device, port_idx) = android_path_parts(&path);
152 let replace = match best.get(device) {
153 None => true,
154 Some((idx, _, _)) => port_idx < *idx,
155 };
156 if replace {
157 best.insert(device.to_string(), (port_idx, path, info));
158 }
159 }
160 best.into_values()
161 .map(|(_, path, info)| (path, info))
162 .collect()
163}
164
165fn android_path_parts(path: &str) -> (&str, u32) {
166 if let Some(idx) = path.rfind('#') {
167 let port = path[idx + 1..].parse().unwrap_or(0);
168 (&path[..idx], port)
169 } else {
170 (path, 0)
171 }
172}
173
174fn filter_macos_single_port_per_device(
175 ports: HashMap<String, HashMap<String, String>>,
176) -> HashMap<String, HashMap<String, String>> {
177 let mut callout: HashMap<String, (String, HashMap<String, String>)> = HashMap::new();
178 let mut dialin: HashMap<String, (String, HashMap<String, String>)> = HashMap::new();
179 let mut other: HashMap<String, HashMap<String, String>> = HashMap::new();
180
181 for (path, info) in ports {
182 if let Some(suffix) = path.strip_prefix("/dev/cu.") {
183 callout.insert(suffix.to_string(), (path, info));
184 } else if let Some(suffix) = path.strip_prefix("/dev/tty.") {
185 dialin.insert(suffix.to_string(), (path, info));
186 } else {
187 other.insert(path, info);
188 }
189 }
190
191 let mut result = other;
192 for (suffix, entry) in dialin {
193 callout.entry(suffix).or_insert(entry);
194 }
195 for (_, (path, info)) in callout {
196 result.insert(path, info);
197 }
198 result
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 fn info(type_: &str) -> HashMap<String, String> {
206 HashMap::from([("type".to_string(), type_.to_string())])
207 }
208
209 #[test]
210 fn no_op_when_disabled() {
211 let ports = HashMap::from([
212 ("/dev/cu.usbmodem1".to_string(), info("USB")),
213 ("/dev/tty.usbmodem1".to_string(), info("USB")),
214 ]);
215 let out = apply_single_port_per_device(ports.clone(), false);
216 assert_eq!(out.len(), 2);
217 assert_eq!(out, ports);
218 }
219
220 #[test]
221 fn prefers_callout_over_dialin_for_same_suffix() {
222 let ports = HashMap::from([
223 ("/dev/tty.usbmodem1421".to_string(), info("USB")),
224 ("/dev/cu.usbmodem1421".to_string(), info("USB")),
225 (
226 "/dev/cu.Bluetooth-Incoming-Port".to_string(),
227 info("Bluetooth"),
228 ),
229 (
230 "/dev/tty.Bluetooth-Incoming-Port".to_string(),
231 info("Bluetooth"),
232 ),
233 ]);
234 let out = apply_single_port_per_device(ports, true);
235 assert_eq!(out.len(), 2);
236 assert!(out.contains_key("/dev/cu.usbmodem1421"));
237 assert!(out.contains_key("/dev/cu.Bluetooth-Incoming-Port"));
238 assert!(!out.contains_key("/dev/tty.usbmodem1421"));
239 }
240
241 #[test]
242 fn keeps_dialin_when_callout_missing() {
243 let ports = HashMap::from([("/dev/tty.usbserial-ABC".to_string(), info("USB"))]);
244 let out = apply_single_port_per_device(ports, true);
245 assert_eq!(out.len(), 1);
246 assert!(out.contains_key("/dev/tty.usbserial-ABC"));
247 }
248
249 #[test]
250 fn preserves_non_macos_style_paths() {
251 let ports = HashMap::from([
252 ("COM3".to_string(), info("USB")),
253 ("/dev/ttyUSB0".to_string(), info("USB")),
254 ]);
255 let out = apply_single_port_per_device(ports.clone(), true);
256 assert_eq!(out, ports);
257 }
258
259 #[test]
260 fn android_keeps_lowest_port_index_per_device() {
261 let ports = HashMap::from([
262 ("/dev/bus/usb/001/002#1".to_string(), info("USB")),
263 ("/dev/bus/usb/001/002#0".to_string(), info("USB")),
264 ("/dev/bus/usb/001/003".to_string(), info("USB")),
265 ]);
266 let out = apply_android_single_port_per_device(ports, true);
267 assert_eq!(out.len(), 2);
268 assert!(out.contains_key("/dev/bus/usb/001/002#0"));
269 assert!(out.contains_key("/dev/bus/usb/001/003"));
270 }
271}