serialplugin-core 0.2.3

Serial port core of tauri-plugin-serialplugin without Tauri: RX hub, watch streams with native parsers, AT exchange, CMUX, TCP and BLE transports
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Typed per-port details ([`available_ports_detailed`]): numeric vid/pid, USB
//! interface number, physical location and Linux `/dev/serial` links. The 4.x string
//! map of [`SerialManager::available_ports`](crate::SerialManager::available_ports)
//! is unchanged.

use serde::{Deserialize, Serialize};
#[cfg(any(all(target_os = "linux", not(target_os = "android")), all(test, unix)))]
use std::collections::HashMap;
#[cfg(any(all(target_os = "linux", not(target_os = "android")), all(test, unix)))]
use std::path::{Path, PathBuf};

/// Kind of port, as in the 4.x `type` field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum PortType {
    #[serde(rename = "USB")]
    Usb,
    #[serde(rename = "Bluetooth")]
    Bluetooth,
    #[serde(rename = "PCI")]
    Pci,
    #[default]
    Unknown,
}

/// One enumerated port. Unknown values are `None` (not `"Unknown"`).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PortDetails {
    /// Port path (`/dev/ttyUSB0`, `/dev/cu.usbmodem1`, `COM3`, Android device path).
    pub path: String,
    pub port_type: PortType,
    pub vid: Option<u16>,
    pub pid: Option<u16>,
    /// Full serial number (on Windows untruncated, like the 4.x map).
    pub serial_number: Option<String>,
    pub manufacturer: Option<String>,
    pub product: Option<String>,
    /// USB interface number: tells the ports of one composite device (a modem's
    /// AT / NMEA / diag ports) apart. On macOS it can be the data interface. Desktop
    /// with the core feature `usb-port-details` only, else `None`.
    pub interface: Option<u8>,
    /// Physical USB location as `bus-port.port…` (Linux sysfs `busnum`/`devpath`,
    /// macOS IOKit `locationID`, Windows `LocationPaths`). Same socket, same value.
    /// Desktop with the core feature `usb-port-details` only, else `None`.
    pub location: Option<String>,
    /// Linux `/dev/serial/by-id/*` links to this port (empty elsewhere).
    pub by_id: Vec<String>,
    /// Linux `/dev/serial/by-path/*` links to this port (empty elsewhere).
    pub by_path: Vec<String>,
}

/// USB location string of a `serialport` port type, if it has one (feature
/// `usb-port-details`; `None` without it).
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub(crate) fn usb_location(port: &serialport::SerialPortType) -> Option<String> {
    #[cfg(feature = "usb-port-details")]
    if let serialport::SerialPortType::UsbPort(info) = port {
        return info.location.as_ref().map(|l| l.to_string());
    }
    let _ = port;
    None
}

/// Convert one `serialport` entry (desktop).
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub fn details_from_type(path: String, port: serialport::SerialPortType) -> PortDetails {
    use serialport::SerialPortType as T;
    #[cfg(feature = "usb-port-details")]
    let location = usb_location(&port);
    match port {
        T::UsbPort(info) => {
            #[allow(unused_mut)]
            let mut d = PortDetails {
                path,
                port_type: PortType::Usb,
                vid: Some(info.vid),
                pid: Some(info.pid),
                serial_number: info.serial_number,
                manufacturer: info.manufacturer,
                product: info.product,
                ..Default::default()
            };
            // Without the feature serialport has no interface / location: `None`.
            #[cfg(feature = "usb-port-details")]
            {
                d.interface = info.interface;
                d.location = location;
            }
            d
        }
        T::BluetoothPort => PortDetails {
            path,
            port_type: PortType::Bluetooth,
            ..Default::default()
        },
        T::PciPort => PortDetails {
            path,
            port_type: PortType::Pci,
            ..Default::default()
        },
        T::Unknown => PortDetails {
            path,
            ..Default::default()
        },
    }
}

/// Convert a 4.x string map (Android, iOS): `"Unknown"` -> `None`, vid/pid hex
/// (`0x1A86`) or decimal. No interface / location there.
pub fn details_from_info_map(
    path: String,
    info: &std::collections::HashMap<String, String>,
) -> PortDetails {
    let text = |k: &str| {
        info.get(k)
            .filter(|v| v.as_str() != crate::state::UNKNOWN)
            .cloned()
    };
    let id = |k: &str| {
        let v = text(k)?;
        match v.strip_prefix("0x").or_else(|| v.strip_prefix("0X")) {
            Some(hex) => u16::from_str_radix(hex, 16).ok(),
            None => v.parse().ok(),
        }
    };
    let port_type = match info.get("type").map(String::as_str) {
        Some(crate::state::USB) => PortType::Usb,
        Some(crate::state::BLUETOOTH) => PortType::Bluetooth,
        Some(crate::state::PCI) => PortType::Pci,
        _ => PortType::Unknown,
    };
    PortDetails {
        path,
        port_type,
        vid: id("vid"),
        pid: id("pid"),
        serial_number: text("serial_number"),
        manufacturer: text("manufacturer"),
        product: text("product"),
        ..Default::default()
    }
}

/// Symlinks in `dir`, grouped by their canonical target (sorted link paths).
/// Dangling links and a missing `dir` are skipped.
#[cfg(any(all(target_os = "linux", not(target_os = "android")), all(test, unix)))]
fn serial_links(dir: &Path) -> HashMap<PathBuf, Vec<String>> {
    let mut out: HashMap<PathBuf, Vec<String>> = HashMap::new();
    let Ok(entries) = std::fs::read_dir(dir) else {
        return out;
    };
    for entry in entries.flatten() {
        let link = entry.path();
        if let Ok(target) = link.canonicalize() {
            out.entry(target)
                .or_default()
                .push(link.display().to_string());
        }
    }
    out.values_mut().for_each(|v| v.sort());
    out
}

/// Every serial port with typed details, sorted by path (both macOS `cu.` and
/// `tty.` nodes, no de-duplication). iOS: empty.
#[cfg(not(target_os = "android"))]
pub fn available_ports_detailed() -> Result<Vec<PortDetails>, crate::error::Error> {
    #[cfg(target_os = "ios")]
    {
        Ok(Vec::new())
    }
    #[cfg(not(target_os = "ios"))]
    {
        #[allow(unused_mut)]
        let mut out: Vec<PortDetails> = crate::port::list::raw_ports()?
            .into_iter()
            .map(|p| details_from_type(p.port_name, p.port_type))
            .collect();

        #[cfg(target_os = "windows")]
        {
            let full = crate::port::list::windows_full_serials();
            for d in &mut out {
                let picked = match (d.serial_number.as_deref(), full.get(&d.path)) {
                    (Some(current), Some(instances)) => {
                        crate::port::list::pick_full_serial(current, instances)
                    }
                    _ => None,
                };
                if let Some(f) = picked.map(str::to_string) {
                    d.serial_number = Some(f);
                }
            }
        }

        #[cfg(target_os = "linux")]
        {
            let by_id = serial_links(Path::new("/dev/serial/by-id"));
            let by_path = serial_links(Path::new("/dev/serial/by-path"));
            for d in &mut out {
                if let Ok(target) = Path::new(&d.path).canonicalize() {
                    d.by_id = by_id.get(&target).cloned().unwrap_or_default();
                    d.by_path = by_path.get(&target).cloned().unwrap_or_default();
                }
            }
        }

        Ok(out)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[cfg(all(
        feature = "usb-port-details",
        not(any(target_os = "android", target_os = "ios"))
    ))]
    fn quectel(interface: u8) -> serialport::SerialPortType {
        serialport::SerialPortType::UsbPort(serialport::UsbPortInfo {
            vid: 0x2c7c,
            pid: 0x0125,
            serial_number: Some("a1b2c3".into()),
            manufacturer: Some("Quectel".into()),
            product: Some("EG25-G".into()),
            location: Some(serialport::Location::new("1".into(), vec![2, 3])),
            interface: Some(interface),
        })
    }

    /// The 4 ports of one Quectel modem look the same in the 4.x map; the interface
    /// number tells them apart.
    #[cfg(all(
        feature = "usb-port-details",
        not(any(target_os = "android", target_os = "ios"))
    ))]
    #[test]
    fn quectel_ports_differ_by_interface_number() {
        let ports: Vec<PortDetails> = (0..4u8)
            .map(|i| details_from_type(format!("/dev/ttyUSB{i}"), quectel(i)))
            .collect();
        for (i, d) in ports.iter().enumerate() {
            assert_eq!(d.port_type, PortType::Usb);
            assert_eq!(d.vid, Some(0x2c7c));
            assert_eq!(d.pid, Some(0x0125));
            assert_eq!(d.serial_number.as_deref(), Some("a1b2c3"));
            assert_eq!(d.manufacturer.as_deref(), Some("Quectel"));
            assert_eq!(d.product.as_deref(), Some("EG25-G"));
            assert_eq!(d.location.as_deref(), Some("1-2.3"));
            assert_eq!(d.interface, Some(i as u8));
        }
        let mut ifaces: Vec<_> = ports.iter().map(|d| d.interface).collect();
        ifaces.dedup();
        assert_eq!(ifaces.len(), 4);

        let maps: Vec<_> = (0..4u8)
            .map(|i| crate::port::list::port_info_from_type(quectel(i)))
            .collect();
        assert!(
            maps.iter().all(|m| m == &maps[0]),
            "4.x map cannot tell them apart"
        );
    }

    #[cfg(not(any(target_os = "android", target_os = "ios")))]
    #[test]
    fn non_usb_ports_have_no_usb_fields() {
        let d = details_from_type("/dev/ttyS0".into(), serialport::SerialPortType::PciPort);
        assert_eq!(d.port_type, PortType::Pci);
        assert_eq!(d.vid, None);
        assert_eq!(d.interface, None);
        assert_eq!(d.location, None);
        let bt = details_from_type("x".into(), serialport::SerialPortType::BluetoothPort);
        assert_eq!(bt.port_type, PortType::Bluetooth);
    }

    #[cfg(not(any(target_os = "android", target_os = "ios")))]
    #[test]
    fn every_type_keeps_its_path_and_usb_fields() {
        let usb = details_from_type(
            "/dev/ttyUSB7".into(),
            serialport::SerialPortType::UsbPort(serialport::UsbPortInfo {
                vid: 1,
                pid: 2,
                serial_number: Some("S".into()),
                manufacturer: Some("M".into()),
                product: Some("P".into()),
                #[cfg(feature = "usb-port-details")]
                location: None,
                #[cfg(feature = "usb-port-details")]
                interface: None,
            }),
        );
        assert_eq!(
            usb,
            PortDetails {
                path: "/dev/ttyUSB7".into(),
                port_type: PortType::Usb,
                vid: Some(1),
                pid: Some(2),
                serial_number: Some("S".into()),
                manufacturer: Some("M".into()),
                product: Some("P".into()),
                ..Default::default()
            }
        );
        use serialport::SerialPortType as T;
        for (t, kind) in [
            (T::BluetoothPort, PortType::Bluetooth),
            (T::PciPort, PortType::Pci),
            (T::Unknown, PortType::Unknown),
        ] {
            let d = details_from_type("/dev/x".into(), t);
            assert_eq!(d.path, "/dev/x");
            assert_eq!(d.port_type, kind);
        }
    }

    /// The typed list holds exactly the ports serialport enumerates, in path order.
    #[cfg(not(any(target_os = "android", target_os = "ios")))]
    #[test]
    fn detailed_list_matches_the_system_ports() {
        let raw: Vec<String> = crate::port::list::raw_ports()
            .unwrap()
            .into_iter()
            .map(|p| p.port_name)
            .collect();
        let paths: Vec<String> = available_ports_detailed()
            .unwrap()
            .into_iter()
            .map(|d| d.path)
            .collect();
        assert_eq!(paths, raw);
    }

    #[test]
    fn from_info_map_keeps_path_text_fields_and_types() {
        let map = HashMap::from([
            ("type".to_string(), "Bluetooth".to_string()),
            ("serial_number".to_string(), "SN".to_string()),
            ("product".to_string(), "Prod".to_string()),
        ]);
        let d = details_from_info_map("/dev/rfcomm0".into(), &map);
        assert_eq!(d.path, "/dev/rfcomm0");
        assert_eq!(d.port_type, PortType::Bluetooth);
        assert_eq!(d.serial_number.as_deref(), Some("SN"));
        assert_eq!(d.product.as_deref(), Some("Prod"));
        let pci = HashMap::from([("type".to_string(), "PCI".to_string())]);
        assert_eq!(
            details_from_info_map("p".into(), &pci).port_type,
            PortType::Pci
        );
    }

    /// Android and iOS go through the 4.x map: hex ("0x1A86") or decimal vid/pid,
    /// "Unknown" becomes `None`.
    #[test]
    fn from_info_map_parses_vid_pid_and_unknown() {
        let map = HashMap::from([
            ("type".to_string(), "USB".to_string()),
            ("vid".to_string(), "0x1A86".to_string()),
            ("pid".to_string(), "29987".to_string()),
            ("serial_number".to_string(), "Unknown".to_string()),
            ("manufacturer".to_string(), "QinHeng".to_string()),
            ("product".to_string(), "Unknown".to_string()),
        ]);
        let d = details_from_info_map("/dev/bus/usb/001/002#1".into(), &map);
        assert_eq!(d.port_type, PortType::Usb);
        assert_eq!(d.vid, Some(0x1a86));
        assert_eq!(d.pid, Some(29987));
        assert_eq!(d.serial_number, None);
        assert_eq!(d.manufacturer.as_deref(), Some("QinHeng"));
        assert_eq!(d.product, None);
        let empty = details_from_info_map("x".into(), &HashMap::new());
        assert_eq!(empty.port_type, PortType::Unknown);
    }

    #[cfg(unix)]
    #[test]
    fn serial_links_maps_targets_to_link_names() {
        // Removed on drop too, so a failed assert (or a mutant) leaves no temp dir behind.
        struct Cleanup(std::path::PathBuf);
        impl Drop for Cleanup {
            fn drop(&mut self) {
                let _ = std::fs::remove_dir_all(&self.0);
            }
        }
        // Next to the test binary (inside cargo's target dir), not the system temp dir.
        let exe = std::env::current_exe().unwrap();
        let root = exe
            .parent()
            .unwrap()
            .join(format!("sp-links-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let _cleanup = Cleanup(root.clone());
        let by_id = root.join("by-id");
        std::fs::create_dir_all(&by_id).unwrap();
        let dev = root.join("ttyUSB0");
        std::fs::write(&dev, b"").unwrap();
        std::os::unix::fs::symlink(&dev, by_id.join("usb-Quectel_EG25-if00-port0")).unwrap();
        std::os::unix::fs::symlink("../ttyUSB0", by_id.join("usb-alias")).unwrap();
        std::os::unix::fs::symlink(root.join("gone"), by_id.join("dangling")).unwrap();

        let links = serial_links(&by_id);
        let target = dev.canonicalize().unwrap();
        assert_eq!(
            links.get(&target).cloned().unwrap_or_default(),
            vec![
                by_id
                    .join("usb-Quectel_EG25-if00-port0")
                    .display()
                    .to_string(),
                by_id.join("usb-alias").display().to_string(),
            ]
        );
        assert_eq!(links.len(), 1);
        assert!(serial_links(&root.join("missing")).is_empty());
        std::fs::remove_dir_all(&root).unwrap();
    }

    /// Live check: `cargo test -p serialplugin-core live_print_details -- --ignored --nocapture`.
    #[cfg(not(any(target_os = "android", target_os = "ios")))]
    #[test]
    #[ignore = "needs real serial hardware"]
    fn live_print_details() {
        for d in available_ports_detailed().unwrap() {
            println!("{d:#?}");
        }
    }
}