hisiflash 0.3.0

Library for flashing HiSilicon chips
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
//! Device discovery and classification utilities.
//!
//! This module provides transport-agnostic device discovery primitives.
//! Currently, native discovery is serial-port based, but the data model is
//! designed to support future transports (TCP, BLE, USB-HID, etc.).

#[cfg(feature = "native")]
use log::{debug, info, trace};

use crate::error::{Error, Result};

/// Transport type for discovered endpoints.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransportKind {
    /// Serial transport (UART/USB CDC).
    Serial,
    /// Unknown or unclassified transport.
    Unknown,
}

/// Known USB bridge/device kinds commonly used with HiSilicon boards.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceKind {
    /// CH340/CH341 USB-to-Serial converter.
    Ch340,
    /// Silicon Labs CP210x USB-to-Serial converter.
    Cp210x,
    /// FTDI FT232/FT2232/FT4232 USB-to-Serial converter.
    Ftdi,
    /// Prolific PL2303 USB-to-Serial converter.
    Prolific,
    /// HiSilicon native USB device.
    HiSilicon,
    /// Unknown device.
    Unknown,
}

/// Legacy type alias kept for compatibility inside this release line.
pub type UsbDevice = DeviceKind;

/// Known USB VID/PID pairs for common USB-to-UART bridges.
const KNOWN_USB_DEVICES: &[(u16, &[u16], DeviceKind)] = &[
    (
        0x1A86,
        &[0x7523, 0x7522, 0x5523, 0x5512, 0x55D4],
        DeviceKind::Ch340,
    ),
    (
        0x10C4,
        &[0xEA60, 0xEA70, 0xEA71, 0xEA63],
        DeviceKind::Cp210x,
    ),
    (
        0x0403,
        &[0x6001, 0x6010, 0x6011, 0x6014, 0x6015],
        DeviceKind::Ftdi,
    ),
    (
        0x067B,
        &[0x2303, 0x23A3, 0x23C3, 0x23D3],
        DeviceKind::Prolific,
    ),
    (0x12D1, &[], DeviceKind::HiSilicon),
];

impl DeviceKind {
    /// Check if this VID/PID combination is a known HiSilicon-compatible
    /// device.
    #[must_use]
    pub fn from_vid_pid(vid: u16, pid: u16) -> Self {
        for (known_vid, pids, device) in KNOWN_USB_DEVICES {
            if vid == *known_vid && (pids.is_empty() || pids.contains(&pid)) {
                return *device;
            }
        }
        Self::Unknown
    }

    /// Get a human-readable name for the device kind.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Ch340 => "CH340/CH341",
            Self::Cp210x => "CP210x",
            Self::Ftdi => "FTDI",
            Self::Prolific => "PL2303",
            Self::HiSilicon => "HiSilicon",
            Self::Unknown => "Unknown",
        }
    }

    /// Check if this is a known/expected device kind.
    pub fn is_known(&self) -> bool {
        !matches!(self, Self::Unknown)
    }

    /// Check if this device kind should be preferred during auto-selection.
    pub fn is_high_priority(&self) -> bool {
        matches!(self, Self::HiSilicon | Self::Ch340 | Self::Cp210x)
    }
}

/// Discovered device endpoint information.
#[derive(Debug, Clone)]
pub struct DetectedPort {
    /// Endpoint name/path (e.g., "/dev/ttyUSB0" or "COM3").
    pub name: String,
    /// Transport type.
    pub transport: TransportKind,
    /// Classified device kind.
    pub device: DeviceKind,
    /// USB Vendor ID (if available).
    pub vid: Option<u16>,
    /// USB Product ID (if available).
    pub pid: Option<u16>,
    /// Device manufacturer string (if available).
    pub manufacturer: Option<String>,
    /// Device product string (if available).
    pub product: Option<String>,
    /// Serial number (if available).
    pub serial: Option<String>,
}

impl DetectedPort {
    /// Check if this endpoint is likely a HiSilicon development board.
    pub fn is_likely_hisilicon(&self) -> bool {
        self.device
            .is_known()
    }
}

/// Detect all available endpoints with metadata.
#[cfg(feature = "native")]
pub fn detect_ports() -> Vec<DetectedPort> {
    let mut result = Vec::new();

    match serialport::available_ports() {
        Ok(ports) => {
            for port_info in ports {
                let mut detected = DetectedPort {
                    name: port_info
                        .port_name
                        .clone(),
                    transport: TransportKind::Serial,
                    device: DeviceKind::Unknown,
                    vid: None,
                    pid: None,
                    manufacturer: None,
                    product: None,
                    serial: None,
                };

                if let serialport::SerialPortType::UsbPort(usb_info) = port_info.port_type {
                    detected.vid = Some(usb_info.vid);
                    detected.pid = Some(usb_info.pid);
                    detected.manufacturer = usb_info.manufacturer;
                    detected.product = usb_info.product;
                    detected.serial = usb_info.serial_number;
                    detected.device = DeviceKind::from_vid_pid(usb_info.vid, usb_info.pid);

                    trace!(
                        "Found USB port: {} (VID: {:04X}, PID: {:04X}, Device: {:?})",
                        port_info.port_name, usb_info.vid, usb_info.pid, detected.device
                    );
                }

                result.push(detected);
            }
        },
        Err(e) => {
            debug!("Failed to enumerate serial ports: {e}");
        },
    }

    result
}

/// Detect all available endpoints (WASM stub - always returns empty).
#[cfg(not(feature = "native"))]
pub fn detect_ports() -> Vec<DetectedPort> {
    Vec::new()
}

/// Detect endpoints that are likely HiSilicon development boards.
pub fn detect_hisilicon_ports() -> Vec<DetectedPort> {
    detect_ports()
        .into_iter()
        .filter(DetectedPort::is_likely_hisilicon)
        .collect()
}

/// Auto-detect a single HiSilicon endpoint.
#[cfg(feature = "native")]
pub fn auto_detect_port() -> Result<DetectedPort> {
    let ports = detect_ports();

    if let Some(port) = ports
        .iter()
        .find(|p| p.device == DeviceKind::HiSilicon)
    {
        info!("Auto-detected HiSilicon USB device: {}", port.name);
        return Ok(port.clone());
    }

    if let Some(port) = ports
        .iter()
        .find(|p| {
            p.device
                .is_high_priority()
        })
    {
        info!(
            "Auto-detected {} USB-UART bridge: {}",
            port.device
                .name(),
            port.name
        );
        return Ok(port.clone());
    }

    if let Some(port) = ports
        .iter()
        .find(|p| {
            p.device
                .is_known()
        })
    {
        info!(
            "Auto-detected {} USB-UART bridge: {}",
            port.device
                .name(),
            port.name
        );
        return Ok(port.clone());
    }

    if let Some(port) = ports
        .into_iter()
        .next()
    {
        info!("Using first available port: {}", port.name);
        return Ok(port);
    }

    Err(Error::DeviceNotFound)
}

/// Auto-detect a single HiSilicon endpoint (WASM stub - not supported).
#[cfg(not(feature = "native"))]
pub fn auto_detect_port() -> Result<DetectedPort> {
    Err(Error::Unsupported(
        "Auto-detection is not available in WASM. Use the Web Serial API to request a port."
            .to_string(),
    ))
}

/// Find an endpoint by name pattern.
#[cfg(feature = "native")]
pub fn find_port_by_pattern(pattern: &str) -> Result<DetectedPort> {
    let ports = detect_ports();

    ports
        .into_iter()
        .find(|p| {
            p.name
                .contains(pattern)
        })
        .ok_or(Error::DeviceNotFound)
}

/// Find an endpoint by name pattern (WASM stub - not supported).
#[cfg(not(feature = "native"))]
pub fn find_port_by_pattern(_pattern: &str) -> Result<DetectedPort> {
    Err(Error::Unsupported(
        "Port enumeration is not available in WASM. Use the Web Serial API to request a port."
            .to_string(),
    ))
}

/// Format a list of detected endpoints for display.
pub fn format_port_list(ports: &[DetectedPort]) -> Vec<String> {
    let mut result = Vec::new();

    for port in ports {
        let device_info = if port
            .device
            .is_known()
        {
            format!(
                " [{}]",
                port.device
                    .name()
            )
        } else if let (Some(vid), Some(pid)) = (port.vid, port.pid) {
            format!(" [VID:{vid:04X} PID:{pid:04X}]")
        } else {
            String::new()
        };

        let product_info = port
            .product
            .as_ref()
            .map(|p| format!(" - {p}"))
            .unwrap_or_default();

        result.push(format!("{}{}{}", port.name, device_info, product_info));
    }

    result
}

/// List all endpoints in a user-friendly format.
pub fn list_ports_pretty() -> Vec<String> {
    let ports = detect_ports();
    format_port_list(&ports)
}

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

    #[test]
    fn test_device_kind_from_vid_pid() {
        assert_eq!(DeviceKind::from_vid_pid(0x1A86, 0x7523), DeviceKind::Ch340);
        assert_eq!(DeviceKind::from_vid_pid(0x10C4, 0xEA60), DeviceKind::Cp210x);
        assert_eq!(DeviceKind::from_vid_pid(0x0403, 0x6001), DeviceKind::Ftdi);
        assert_eq!(
            DeviceKind::from_vid_pid(0x067B, 0x2303),
            DeviceKind::Prolific
        );
        assert_eq!(
            DeviceKind::from_vid_pid(0x12D1, 0x1234),
            DeviceKind::HiSilicon
        );
        assert_eq!(
            DeviceKind::from_vid_pid(0x1234, 0x5678),
            DeviceKind::Unknown
        );
    }

    #[test]
    fn test_device_kind_is_known() {
        assert!(DeviceKind::Ch340.is_known());
        assert!(!DeviceKind::Unknown.is_known());
    }

    #[test]
    fn test_detected_port_is_likely_hisilicon() {
        let known = DetectedPort {
            name: "/dev/ttyUSB0".to_string(),
            transport: TransportKind::Serial,
            device: DeviceKind::Ch340,
            vid: Some(0x1A86),
            pid: Some(0x7523),
            manufacturer: None,
            product: None,
            serial: None,
        };
        assert!(known.is_likely_hisilicon());

        let unknown = DetectedPort {
            name: "/dev/ttyS0".to_string(),
            transport: TransportKind::Serial,
            device: DeviceKind::Unknown,
            vid: None,
            pid: None,
            manufacturer: None,
            product: None,
            serial: None,
        };
        assert!(!unknown.is_likely_hisilicon());
    }

    #[test]
    fn test_format_port_list() {
        let ports = vec![
            DetectedPort {
                name: "/dev/ttyUSB0".to_string(),
                transport: TransportKind::Serial,
                device: DeviceKind::Ch340,
                vid: Some(0x1A86),
                pid: Some(0x7523),
                manufacturer: Some("WCH".to_string()),
                product: Some("USB-Serial".to_string()),
                serial: None,
            },
            DetectedPort {
                name: "/dev/ttyUSB1".to_string(),
                transport: TransportKind::Serial,
                device: DeviceKind::Unknown,
                vid: None,
                pid: None,
                manufacturer: None,
                product: None,
                serial: None,
            },
        ];

        let formatted = format_port_list(&ports);
        assert_eq!(formatted.len(), 2);
        assert!(formatted[0].contains("/dev/ttyUSB0"));
        assert!(formatted[0].contains("CH340/CH341"));
        assert!(formatted[1].contains("/dev/ttyUSB1"));
    }
}