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 let location = usb_location(&port);
70 match port {
71 T::UsbPort(info) => PortDetails {
72 path,
73 port_type: PortType::Usb,
74 vid: Some(info.vid),
75 pid: Some(info.pid),
76 serial_number: info.serial_number,
77 manufacturer: info.manufacturer,
78 product: info.product,
79 #[cfg(feature = "usb-port-details")]
80 interface: info.interface,
81 location,
82 ..Default::default()
83 },
84 T::BluetoothPort => PortDetails {
85 path,
86 port_type: PortType::Bluetooth,
87 ..Default::default()
88 },
89 T::PciPort => PortDetails {
90 path,
91 port_type: PortType::Pci,
92 ..Default::default()
93 },
94 T::Unknown => PortDetails {
95 path,
96 ..Default::default()
97 },
98 }
99}
100
101pub fn details_from_info_map(
104 path: String,
105 info: &std::collections::HashMap<String, String>,
106) -> PortDetails {
107 let text = |k: &str| {
108 info.get(k)
109 .filter(|v| v.as_str() != crate::state::UNKNOWN)
110 .cloned()
111 };
112 let id = |k: &str| {
113 let v = text(k)?;
114 match v.strip_prefix("0x").or_else(|| v.strip_prefix("0X")) {
115 Some(hex) => u16::from_str_radix(hex, 16).ok(),
116 None => v.parse().ok(),
117 }
118 };
119 let port_type = match info.get("type").map(String::as_str) {
120 Some(crate::state::USB) => PortType::Usb,
121 Some(crate::state::BLUETOOTH) => PortType::Bluetooth,
122 Some(crate::state::PCI) => PortType::Pci,
123 _ => PortType::Unknown,
124 };
125 PortDetails {
126 path,
127 port_type,
128 vid: id("vid"),
129 pid: id("pid"),
130 serial_number: text("serial_number"),
131 manufacturer: text("manufacturer"),
132 product: text("product"),
133 ..Default::default()
134 }
135}
136
137#[cfg(any(all(target_os = "linux", not(target_os = "android")), all(test, unix)))]
140fn serial_links(dir: &Path) -> HashMap<PathBuf, Vec<String>> {
141 let mut out: HashMap<PathBuf, Vec<String>> = HashMap::new();
142 let Ok(entries) = std::fs::read_dir(dir) else {
143 return out;
144 };
145 for entry in entries.flatten() {
146 let link = entry.path();
147 if let Ok(target) = link.canonicalize() {
148 out.entry(target)
149 .or_default()
150 .push(link.display().to_string());
151 }
152 }
153 out.values_mut().for_each(|v| v.sort());
154 out
155}
156
157#[cfg(not(target_os = "android"))]
160pub fn available_ports_detailed() -> Result<Vec<PortDetails>, crate::error::Error> {
161 #[cfg(target_os = "ios")]
162 {
163 Ok(Vec::new())
164 }
165 #[cfg(not(target_os = "ios"))]
166 {
167 #[allow(unused_mut)]
168 let mut out: Vec<PortDetails> = crate::port::list::raw_ports()?
169 .into_iter()
170 .map(|p| details_from_type(p.port_name, p.port_type))
171 .collect();
172
173 #[cfg(target_os = "windows")]
174 {
175 let full = crate::port::list::windows_full_serials();
176 for d in &mut out {
177 let picked = match (d.serial_number.as_deref(), full.get(&d.path)) {
178 (Some(current), Some(instances)) => {
179 crate::port::list::pick_full_serial(current, instances)
180 }
181 _ => None,
182 };
183 if let Some(f) = picked.map(str::to_string) {
184 d.serial_number = Some(f);
185 }
186 }
187 }
188
189 #[cfg(target_os = "linux")]
190 {
191 let by_id = serial_links(Path::new("/dev/serial/by-id"));
192 let by_path = serial_links(Path::new("/dev/serial/by-path"));
193 for d in &mut out {
194 if let Ok(target) = Path::new(&d.path).canonicalize() {
195 d.by_id = by_id.get(&target).cloned().unwrap_or_default();
196 d.by_path = by_path.get(&target).cloned().unwrap_or_default();
197 }
198 }
199 }
200
201 Ok(out)
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208 use std::collections::HashMap;
209
210 #[cfg(all(
211 feature = "usb-port-details",
212 not(any(target_os = "android", target_os = "ios"))
213 ))]
214 fn quectel(interface: u8) -> serialport::SerialPortType {
215 serialport::SerialPortType::UsbPort(serialport::UsbPortInfo {
216 vid: 0x2c7c,
217 pid: 0x0125,
218 serial_number: Some("a1b2c3".into()),
219 manufacturer: Some("Quectel".into()),
220 product: Some("EG25-G".into()),
221 location: Some(serialport::Location::new("1".into(), vec![2, 3])),
222 interface: Some(interface),
223 })
224 }
225
226 #[cfg(all(
229 feature = "usb-port-details",
230 not(any(target_os = "android", target_os = "ios"))
231 ))]
232 #[test]
233 fn quectel_ports_differ_by_interface_number() {
234 let ports: Vec<PortDetails> = (0..4u8)
235 .map(|i| details_from_type(format!("/dev/ttyUSB{i}"), quectel(i)))
236 .collect();
237 for (i, d) in ports.iter().enumerate() {
238 assert_eq!(d.port_type, PortType::Usb);
239 assert_eq!(d.vid, Some(0x2c7c));
240 assert_eq!(d.pid, Some(0x0125));
241 assert_eq!(d.serial_number.as_deref(), Some("a1b2c3"));
242 assert_eq!(d.manufacturer.as_deref(), Some("Quectel"));
243 assert_eq!(d.product.as_deref(), Some("EG25-G"));
244 assert_eq!(d.location.as_deref(), Some("1-2.3"));
245 assert_eq!(d.interface, Some(i as u8));
246 }
247 let mut ifaces: Vec<_> = ports.iter().map(|d| d.interface).collect();
248 ifaces.dedup();
249 assert_eq!(ifaces.len(), 4);
250
251 let maps: Vec<_> = (0..4u8)
252 .map(|i| crate::port::list::port_info_from_type(quectel(i)))
253 .collect();
254 assert!(
255 maps.iter().all(|m| m == &maps[0]),
256 "4.x map cannot tell them apart"
257 );
258 }
259
260 #[cfg(not(any(target_os = "android", target_os = "ios")))]
261 #[test]
262 fn non_usb_ports_have_no_usb_fields() {
263 let d = details_from_type("/dev/ttyS0".into(), serialport::SerialPortType::PciPort);
264 assert_eq!(d.port_type, PortType::Pci);
265 assert_eq!(d.vid, None);
266 assert_eq!(d.interface, None);
267 assert_eq!(d.location, None);
268 let bt = details_from_type("x".into(), serialport::SerialPortType::BluetoothPort);
269 assert_eq!(bt.port_type, PortType::Bluetooth);
270 }
271
272 #[test]
275 fn from_info_map_parses_vid_pid_and_unknown() {
276 let map = HashMap::from([
277 ("type".to_string(), "USB".to_string()),
278 ("vid".to_string(), "0x1A86".to_string()),
279 ("pid".to_string(), "29987".to_string()),
280 ("serial_number".to_string(), "Unknown".to_string()),
281 ("manufacturer".to_string(), "QinHeng".to_string()),
282 ("product".to_string(), "Unknown".to_string()),
283 ]);
284 let d = details_from_info_map("/dev/bus/usb/001/002#1".into(), &map);
285 assert_eq!(d.port_type, PortType::Usb);
286 assert_eq!(d.vid, Some(0x1a86));
287 assert_eq!(d.pid, Some(29987));
288 assert_eq!(d.serial_number, None);
289 assert_eq!(d.manufacturer.as_deref(), Some("QinHeng"));
290 assert_eq!(d.product, None);
291 let empty = details_from_info_map("x".into(), &HashMap::new());
292 assert_eq!(empty.port_type, PortType::Unknown);
293 }
294
295 #[cfg(unix)]
296 #[test]
297 fn serial_links_maps_targets_to_link_names() {
298 let root = std::env::temp_dir().join(format!("sp-links-{}", std::process::id()));
299 let _ = std::fs::remove_dir_all(&root);
300 let by_id = root.join("by-id");
301 std::fs::create_dir_all(&by_id).unwrap();
302 let dev = root.join("ttyUSB0");
303 std::fs::write(&dev, b"").unwrap();
304 std::os::unix::fs::symlink(&dev, by_id.join("usb-Quectel_EG25-if00-port0")).unwrap();
305 std::os::unix::fs::symlink("../ttyUSB0", by_id.join("usb-alias")).unwrap();
306 std::os::unix::fs::symlink(root.join("gone"), by_id.join("dangling")).unwrap();
307
308 let links = serial_links(&by_id);
309 let target = dev.canonicalize().unwrap();
310 assert_eq!(
311 links.get(&target).cloned().unwrap_or_default(),
312 vec![
313 by_id
314 .join("usb-Quectel_EG25-if00-port0")
315 .display()
316 .to_string(),
317 by_id.join("usb-alias").display().to_string(),
318 ]
319 );
320 assert_eq!(links.len(), 1);
321 assert!(serial_links(&root.join("missing")).is_empty());
322 std::fs::remove_dir_all(&root).unwrap();
323 }
324
325 #[cfg(not(any(target_os = "android", target_os = "ios")))]
327 #[test]
328 #[ignore = "needs real serial hardware"]
329 fn live_print_details() {
330 for d in available_ports_detailed().unwrap() {
331 println!("{d:#?}");
332 }
333 }
334}