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.is_empty() && 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(t) if t.eq_ignore_ascii_case(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(all(test, unix))]
214mod tests {
215 use super::*;
217
218 #[test]
219 fn serial_links_maps_targets_to_link_names() {
220 struct Cleanup(std::path::PathBuf);
222 impl Drop for Cleanup {
223 fn drop(&mut self) {
224 let _ = std::fs::remove_dir_all(&self.0);
225 }
226 }
227 let exe = std::env::current_exe().unwrap();
229 let root = exe
230 .parent()
231 .unwrap()
232 .join(format!("sp-links-{}", std::process::id()));
233 let _ = std::fs::remove_dir_all(&root);
234 let _cleanup = Cleanup(root.clone());
235 let by_id = root.join("by-id");
236 std::fs::create_dir_all(&by_id).unwrap();
237 let dev = root.join("ttyUSB0");
238 std::fs::write(&dev, b"").unwrap();
239 std::os::unix::fs::symlink(&dev, by_id.join("usb-Quectel_EG25-if00-port0")).unwrap();
240 std::os::unix::fs::symlink("../ttyUSB0", by_id.join("usb-alias")).unwrap();
241 std::os::unix::fs::symlink(root.join("gone"), by_id.join("dangling")).unwrap();
242
243 let links = serial_links(&by_id);
244 let target = dev.canonicalize().unwrap();
245 assert_eq!(
246 links.get(&target).cloned().unwrap_or_default(),
247 vec![
248 by_id
249 .join("usb-Quectel_EG25-if00-port0")
250 .display()
251 .to_string(),
252 by_id.join("usb-alias").display().to_string(),
253 ]
254 );
255 assert_eq!(links.len(), 1);
256 assert!(serial_links(&root.join("missing")).is_empty());
257 std::fs::remove_dir_all(&root).unwrap();
258 }
259}