1use 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#[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#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
27#[serde(rename_all = "camelCase")]
28#[non_exhaustive]
29pub struct PortDetails {
30 pub path: String,
32 pub port_type: PortType,
33 pub vid: Option<u16>,
34 pub pid: Option<u16>,
35 pub serial_number: Option<String>,
37 pub manufacturer: Option<String>,
38 pub product: Option<String>,
39 pub interface: Option<u8>,
43 pub location: Option<String>,
47 pub by_id: Vec<String>,
49 pub by_path: Vec<String>,
51}
52
53#[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#[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 #[cfg(feature = "usb-port-details")]
70 let location = usb_location(&port);
71 match port {
72 T::UsbPort(info) => {
73 #[allow(unused_mut)]
74 let mut d = PortDetails {
75 path,
76 port_type: PortType::Usb,
77 vid: Some(info.vid),
78 pid: Some(info.pid),
79 serial_number: info.serial_number,
80 manufacturer: info.manufacturer,
81 product: info.product,
82 ..Default::default()
83 };
84 #[cfg(feature = "usb-port-details")]
86 {
87 d.interface = info.interface;
88 d.location = location;
89 }
90 d
91 }
92 T::BluetoothPort => PortDetails {
93 path,
94 port_type: PortType::Bluetooth,
95 ..Default::default()
96 },
97 T::PciPort => PortDetails {
98 path,
99 port_type: PortType::Pci,
100 ..Default::default()
101 },
102 T::Unknown => PortDetails {
103 path,
104 ..Default::default()
105 },
106 }
107}
108
109pub fn details_from_info_map(
112 path: String,
113 info: &std::collections::HashMap<String, String>,
114) -> PortDetails {
115 let text = |k: &str| {
116 info.get(k)
117 .filter(|v| v.as_str() != crate::state::UNKNOWN)
118 .cloned()
119 };
120 let id = |k: &str| {
121 let v = text(k)?;
122 match v.strip_prefix("0x").or_else(|| v.strip_prefix("0X")) {
123 Some(hex) => u16::from_str_radix(hex, 16).ok(),
124 None => v.parse().ok(),
125 }
126 };
127 let port_type = match info.get("type").map(String::as_str) {
128 Some(crate::state::USB) => PortType::Usb,
129 Some(crate::state::BLUETOOTH) => PortType::Bluetooth,
130 Some(crate::state::PCI) => PortType::Pci,
131 _ => PortType::Unknown,
132 };
133 PortDetails {
134 path,
135 port_type,
136 vid: id("vid"),
137 pid: id("pid"),
138 serial_number: text("serial_number"),
139 manufacturer: text("manufacturer"),
140 product: text("product"),
141 ..Default::default()
142 }
143}
144
145#[cfg(any(all(target_os = "linux", not(target_os = "android")), all(test, unix)))]
148fn serial_links(dir: &Path) -> HashMap<PathBuf, Vec<String>> {
149 let mut out: HashMap<PathBuf, Vec<String>> = HashMap::new();
150 let Ok(entries) = std::fs::read_dir(dir) else {
151 return out;
152 };
153 for entry in entries.flatten() {
154 let link = entry.path();
155 if let Ok(target) = link.canonicalize() {
156 out.entry(target)
157 .or_default()
158 .push(link.display().to_string());
159 }
160 }
161 out.values_mut().for_each(|v| v.sort());
162 out
163}
164
165#[cfg(not(target_os = "android"))]
168pub fn available_ports_detailed() -> Result<Vec<PortDetails>, crate::error::Error> {
169 #[cfg(target_os = "ios")]
170 {
171 Ok(Vec::new())
172 }
173 #[cfg(not(target_os = "ios"))]
174 {
175 #[allow(unused_mut)]
176 let mut out: Vec<PortDetails> = crate::port::list::raw_ports()?
177 .into_iter()
178 .map(|p| details_from_type(p.port_name, p.port_type))
179 .collect();
180
181 #[cfg(target_os = "windows")]
182 {
183 let full = crate::port::list::windows_full_serials();
184 for d in &mut out {
185 let picked = match (d.serial_number.as_deref(), full.get(&d.path)) {
186 (Some(current), Some(instances)) => {
187 crate::port::list::pick_full_serial(current, instances)
188 }
189 _ => None,
190 };
191 if let Some(f) = picked.map(str::to_string) {
192 d.serial_number = Some(f);
193 }
194 }
195 }
196
197 #[cfg(target_os = "linux")]
198 {
199 let by_id = serial_links(Path::new("/dev/serial/by-id"));
200 let by_path = serial_links(Path::new("/dev/serial/by-path"));
201 for d in &mut out {
202 if let Ok(target) = Path::new(&d.path).canonicalize() {
203 d.by_id = by_id.get(&target).cloned().unwrap_or_default();
204 d.by_path = by_path.get(&target).cloned().unwrap_or_default();
205 }
206 }
207 }
208
209 Ok(out)
210 }
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216 use std::collections::HashMap;
217
218 #[cfg(all(
219 feature = "usb-port-details",
220 not(any(target_os = "android", target_os = "ios"))
221 ))]
222 fn quectel(interface: u8) -> serialport::SerialPortType {
223 serialport::SerialPortType::UsbPort(serialport::UsbPortInfo {
224 vid: 0x2c7c,
225 pid: 0x0125,
226 serial_number: Some("a1b2c3".into()),
227 manufacturer: Some("Quectel".into()),
228 product: Some("EG25-G".into()),
229 location: Some(serialport::Location::new("1".into(), vec![2, 3])),
230 interface: Some(interface),
231 })
232 }
233
234 #[cfg(all(
237 feature = "usb-port-details",
238 not(any(target_os = "android", target_os = "ios"))
239 ))]
240 #[test]
241 fn quectel_ports_differ_by_interface_number() {
242 let ports: Vec<PortDetails> = (0..4u8)
243 .map(|i| details_from_type(format!("/dev/ttyUSB{i}"), quectel(i)))
244 .collect();
245 for (i, d) in ports.iter().enumerate() {
246 assert_eq!(d.port_type, PortType::Usb);
247 assert_eq!(d.vid, Some(0x2c7c));
248 assert_eq!(d.pid, Some(0x0125));
249 assert_eq!(d.serial_number.as_deref(), Some("a1b2c3"));
250 assert_eq!(d.manufacturer.as_deref(), Some("Quectel"));
251 assert_eq!(d.product.as_deref(), Some("EG25-G"));
252 assert_eq!(d.location.as_deref(), Some("1-2.3"));
253 assert_eq!(d.interface, Some(i as u8));
254 }
255 let mut ifaces: Vec<_> = ports.iter().map(|d| d.interface).collect();
256 ifaces.dedup();
257 assert_eq!(ifaces.len(), 4);
258
259 let maps: Vec<_> = (0..4u8)
260 .map(|i| crate::port::list::port_info_from_type(quectel(i)))
261 .collect();
262 assert!(
263 maps.iter().all(|m| m == &maps[0]),
264 "4.x map cannot tell them apart"
265 );
266 }
267
268 #[cfg(not(any(target_os = "android", target_os = "ios")))]
269 #[test]
270 fn non_usb_ports_have_no_usb_fields() {
271 let d = details_from_type("/dev/ttyS0".into(), serialport::SerialPortType::PciPort);
272 assert_eq!(d.port_type, PortType::Pci);
273 assert_eq!(d.vid, None);
274 assert_eq!(d.interface, None);
275 assert_eq!(d.location, None);
276 let bt = details_from_type("x".into(), serialport::SerialPortType::BluetoothPort);
277 assert_eq!(bt.port_type, PortType::Bluetooth);
278 }
279
280 #[cfg(not(any(target_os = "android", target_os = "ios")))]
281 #[test]
282 fn every_type_keeps_its_path_and_usb_fields() {
283 let usb = details_from_type(
284 "/dev/ttyUSB7".into(),
285 serialport::SerialPortType::UsbPort(serialport::UsbPortInfo {
286 vid: 1,
287 pid: 2,
288 serial_number: Some("S".into()),
289 manufacturer: Some("M".into()),
290 product: Some("P".into()),
291 #[cfg(feature = "usb-port-details")]
292 location: None,
293 #[cfg(feature = "usb-port-details")]
294 interface: None,
295 }),
296 );
297 assert_eq!(
298 usb,
299 PortDetails {
300 path: "/dev/ttyUSB7".into(),
301 port_type: PortType::Usb,
302 vid: Some(1),
303 pid: Some(2),
304 serial_number: Some("S".into()),
305 manufacturer: Some("M".into()),
306 product: Some("P".into()),
307 ..Default::default()
308 }
309 );
310 use serialport::SerialPortType as T;
311 for (t, kind) in [
312 (T::BluetoothPort, PortType::Bluetooth),
313 (T::PciPort, PortType::Pci),
314 (T::Unknown, PortType::Unknown),
315 ] {
316 let d = details_from_type("/dev/x".into(), t);
317 assert_eq!(d.path, "/dev/x");
318 assert_eq!(d.port_type, kind);
319 }
320 }
321
322 #[cfg(not(any(target_os = "android", target_os = "ios")))]
324 #[test]
325 fn detailed_list_matches_the_system_ports() {
326 let raw: Vec<String> = crate::port::list::raw_ports()
327 .unwrap()
328 .into_iter()
329 .map(|p| p.port_name)
330 .collect();
331 let paths: Vec<String> = available_ports_detailed()
332 .unwrap()
333 .into_iter()
334 .map(|d| d.path)
335 .collect();
336 assert_eq!(paths, raw);
337 }
338
339 #[test]
340 fn from_info_map_keeps_path_text_fields_and_types() {
341 let map = HashMap::from([
342 ("type".to_string(), "Bluetooth".to_string()),
343 ("serial_number".to_string(), "SN".to_string()),
344 ("product".to_string(), "Prod".to_string()),
345 ]);
346 let d = details_from_info_map("/dev/rfcomm0".into(), &map);
347 assert_eq!(d.path, "/dev/rfcomm0");
348 assert_eq!(d.port_type, PortType::Bluetooth);
349 assert_eq!(d.serial_number.as_deref(), Some("SN"));
350 assert_eq!(d.product.as_deref(), Some("Prod"));
351 let pci = HashMap::from([("type".to_string(), "PCI".to_string())]);
352 assert_eq!(
353 details_from_info_map("p".into(), &pci).port_type,
354 PortType::Pci
355 );
356 }
357
358 #[test]
361 fn from_info_map_parses_vid_pid_and_unknown() {
362 let map = HashMap::from([
363 ("type".to_string(), "USB".to_string()),
364 ("vid".to_string(), "0x1A86".to_string()),
365 ("pid".to_string(), "29987".to_string()),
366 ("serial_number".to_string(), "Unknown".to_string()),
367 ("manufacturer".to_string(), "QinHeng".to_string()),
368 ("product".to_string(), "Unknown".to_string()),
369 ]);
370 let d = details_from_info_map("/dev/bus/usb/001/002#1".into(), &map);
371 assert_eq!(d.port_type, PortType::Usb);
372 assert_eq!(d.vid, Some(0x1a86));
373 assert_eq!(d.pid, Some(29987));
374 assert_eq!(d.serial_number, None);
375 assert_eq!(d.manufacturer.as_deref(), Some("QinHeng"));
376 assert_eq!(d.product, None);
377 let empty = details_from_info_map("x".into(), &HashMap::new());
378 assert_eq!(empty.port_type, PortType::Unknown);
379 }
380
381 #[cfg(unix)]
382 #[test]
383 fn serial_links_maps_targets_to_link_names() {
384 struct Cleanup(std::path::PathBuf);
386 impl Drop for Cleanup {
387 fn drop(&mut self) {
388 let _ = std::fs::remove_dir_all(&self.0);
389 }
390 }
391 let exe = std::env::current_exe().unwrap();
393 let root = exe
394 .parent()
395 .unwrap()
396 .join(format!("sp-links-{}", std::process::id()));
397 let _ = std::fs::remove_dir_all(&root);
398 let _cleanup = Cleanup(root.clone());
399 let by_id = root.join("by-id");
400 std::fs::create_dir_all(&by_id).unwrap();
401 let dev = root.join("ttyUSB0");
402 std::fs::write(&dev, b"").unwrap();
403 std::os::unix::fs::symlink(&dev, by_id.join("usb-Quectel_EG25-if00-port0")).unwrap();
404 std::os::unix::fs::symlink("../ttyUSB0", by_id.join("usb-alias")).unwrap();
405 std::os::unix::fs::symlink(root.join("gone"), by_id.join("dangling")).unwrap();
406
407 let links = serial_links(&by_id);
408 let target = dev.canonicalize().unwrap();
409 assert_eq!(
410 links.get(&target).cloned().unwrap_or_default(),
411 vec![
412 by_id
413 .join("usb-Quectel_EG25-if00-port0")
414 .display()
415 .to_string(),
416 by_id.join("usb-alias").display().to_string(),
417 ]
418 );
419 assert_eq!(links.len(), 1);
420 assert!(serial_links(&root.join("missing")).is_empty());
421 std::fs::remove_dir_all(&root).unwrap();
422 }
423
424 #[cfg(not(any(target_os = "android", target_os = "ios")))]
426 #[test]
427 #[ignore = "needs real serial hardware"]
428 fn live_print_details() {
429 for d in available_ports_detailed().unwrap() {
430 println!("{d:#?}");
431 }
432 }
433}