tauri-plugin-serialplugin 2.22.0

Access the current process of your Tauri application.
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
use crate::error::Error;
use crate::state::{
    ClearBuffer, ConnectedPort, DataBits, FlowControl, Parity, PortState, ReadData, SerialportInfo,
    StopBits, BLUETOOTH, PCI, UNKNOWN, USB,
};
use crate::{log_debug, log_error, log_info, log_warn};
use serialport::{
    DataBits as SerialDataBits, FlowControl as SerialFlowControl, Parity as SerialParity,
    StopBits as SerialStopBits,
};
use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter, Runtime};
use tauri::plugin::PluginHandle;

/// Tear down resources held by a [`SerialportInfo`] (listener thread + port).
fn finish_serialport_info(info: SerialportInfo) -> Result<(), Error> {
    match info.state {
        PortState::Connected(mut cp) => {
            if let Some(sender) = cp.sender.take() {
                sender.send(1).ok();
            }
            if let Some(handle) = cp.thread_handle.take() {
                handle
                    .join()
                    .map_err(|e| Error::String(format!("Failed to join thread: {:?}", e)))?;
            }
            drop(cp.port);
            Ok(())
        }
        PortState::Opening | PortState::Closed => Ok(()),
    }
}

/// Access to the serial port APIs for mobile platforms.
pub struct SerialPort<R: Runtime> {
    #[allow(dead_code)]
    pub(crate) app: AppHandle<R>,
    pub(crate) serialports: Arc<Mutex<HashMap<String, SerialportInfo>>>,
}

impl<R: Runtime> SerialPort<R> {
    #[allow(dead_code)]
    pub fn new(app: AppHandle<R>) -> Self {
        Self {
            app,
            serialports: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    #[allow(dead_code)]
    pub fn from_plugin_handle(plugin_handle: PluginHandle<R>) -> Self {
        Self {
            app: plugin_handle.app().clone(),
            serialports: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Get serial port list
    pub fn available_ports(&self) -> Result<HashMap<String, HashMap<String, String>>, Error> {
        let mut list = serialport::available_ports().unwrap_or_else(|_| vec![]);
        list.sort_by(|a, b| a.port_name.cmp(&b.port_name));

        let mut result_list: HashMap<String, HashMap<String, String>> = HashMap::new();

        for p in list {
            result_list.insert(p.port_name, self.get_port_info(p.port_type));
        }

        Ok(result_list)
    }

    /// Get serial port list using platform-specific commands
    pub fn available_ports_direct(
        &self,
    ) -> Result<HashMap<String, HashMap<String, String>>, Error> {
        let mut result_list: HashMap<String, HashMap<String, String>> = HashMap::new();

        #[cfg(target_os = "windows")]
        {
            use std::process::Command;

            // Get USB ports
            let usb_output = Command::new("wmic")
                .arg("path")
                .arg("Win32_PnPEntity")
                .arg("where")
                .arg("PNPDeviceID like '%USB%' and Name like '%(COM%'")
                .arg("get")
                .arg("Name,DeviceID")
                .output()
                .expect("Failed to execute command");

            let usb_devices = String::from_utf8_lossy(&usb_output.stdout);
            for line in usb_devices.lines().skip(1) {
                let device_info = line.trim();
                if !device_info.is_empty() {
                    let parts: Vec<&str> = device_info.split_whitespace().collect();
                    if parts.len() >= 2 {
                        let port_name = parts[1].trim();
                        let mut port_info = HashMap::new();
                        port_info.insert("type".to_string(), "USB".to_string());
                        result_list.insert(port_name.to_string(), port_info);
                    }
                }
            }

            // Get COM ports
            let com_output = Command::new("wmic")
                .arg("path")
                .arg("Win32_SerialPort")
                .arg("get")
                .arg("DeviceID,Name")
                .output()
                .expect("Failed to execute command");

            let com_devices = String::from_utf8_lossy(&com_output.stdout);
            for line in com_devices.lines().skip(1) {
                let device_info = line.trim();
                if !device_info.is_empty() {
                    let parts: Vec<&str> = device_info.split_whitespace().collect();
                    if parts.len() >= 2 {
                        let port_name = parts[0].trim();
                        let mut port_info = HashMap::new();
                        port_info.insert("type".to_string(), "COM".to_string());
                        result_list.insert(port_name.to_string(), port_info);
                    }
                }
            }
        }

        #[cfg(target_os = "linux")]
        {
            use std::process::Command;

            // Get USB devices
            let output = Command::new("lsusb")
                .output()
                .expect("Failed to execute lsusb command");

            let usb_devices = String::from_utf8_lossy(&output.stdout);
            for line in usb_devices.lines() {
                if line.contains("Serial") || line.contains("USB") {
                    let mut port_info = HashMap::new();
                    port_info.insert("type".to_string(), "USB".to_string());
                    result_list.insert(line.to_string(), port_info);
                }
            }

            // Get serial ports from /dev
            let dev_output = Command::new("ls")
                .arg("/dev")
                .output()
                .expect("Failed to execute ls command");

            let dev_ports = String::from_utf8_lossy(&dev_output.stdout);
            for line in dev_ports.lines() {
                if line.starts_with("ttyUSB") || line.starts_with("ttyS") {
                    let mut port_info = HashMap::new();
                    port_info.insert(
                        "type".to_string(),
                        if line.starts_with("ttyUSB") {
                            "USB"
                        } else {
                            "COM"
                        }
                        .to_string(),
                    );
                    result_list.insert(format!("/dev/{}", line), port_info);
                }
                if line.starts_with("rfcomm") {
                    let mut port_info = HashMap::new();
                    port_info.insert("type".to_string(), "Bluetooth".to_string());
                    result_list.insert(format!("/dev/{}", line), port_info);
                }
                if line.starts_with("ttyACM") {
                    let mut port_info = HashMap::new();
                    port_info.insert("type".to_string(), "Virtual".to_string());
                    result_list.insert(format!("/dev/{}", line), port_info);
                }
            }
        }

        #[cfg(target_os = "macos")]
        {
            use std::process::Command;

            // Get USB devices
            let output = Command::new("system_profiler")
                .arg("SPUSBDataType")
                .output()
                .expect("Failed to execute system_profiler");

            let usb_devices = String::from_utf8_lossy(&output.stdout);
            for line in usb_devices.lines() {
                if line.contains("Serial") || line.contains("USB") {
                    let mut port_info = HashMap::new();
                    port_info.insert("type".to_string(), "USB".to_string());
                    result_list.insert(line.to_string(), port_info);
                }
            }

            // Check devices in /dev
            let dev_output = Command::new("ls")
                .arg("/dev")
                .output()
                .expect("Failed to execute ls command");

            let dev_ports = String::from_utf8_lossy(&dev_output.stdout);
            for line in dev_ports.lines() {
                if line.starts_with("cu.") || line.starts_with("tty.") {
                    let mut port_info = HashMap::new();
                    if line.contains("Bluetooth") {
                        port_info.insert("type".to_string(), "Bluetooth".to_string());
                    } else if line.starts_with("cu.") {
                        port_info.insert("type".to_string(), "USB".to_string());
                    } else {
                        port_info.insert("type".to_string(), "COM".to_string());
                    }
                    result_list.insert(format!("/dev/{}", line), port_info);
                }
            }
        }

        Ok(result_list)
    }

    /// Get a list of managed serial ports.
    pub fn managed_ports(&self) -> Result<Vec<String>, Error> {
        // Lock the Mutex to safely access the data inside `self.serialports`.
        let ports = self.serialports.lock().map_err(|_| {
            Error::String("Failed to lock serialports mutex".to_string())
        })?;

        // Collect the keys (port names) from the HashMap into a vector.
        let port_list: Vec<String> = ports.keys().cloned().collect();

        // Return the list of managed port names.
        Ok(port_list)
    }

    /// Cancel reading data from the serial port
    pub fn cancel_read(&self, path: String) -> Result<(), Error> {
        self.with_connected_port(path.clone(), |cp| {
            if let Some(sender) = &cp.sender {
                sender.send(1).map_err(|e| {
                    Error::String(format!("Failed to cancel serial port data reading: {}", e))
                })?;
            }
            cp.sender = None;
            Ok(())
        })
    }

    /// Close the specified serial port
    pub fn close(&self, path: String) -> Result<(), Error> {
        log_debug!("close {}", path);
        
        // Emit disconnected event before closing
        let event_path = path.replace(".", "-").replace("/", "-");
        let disconnected_event = format!("plugin-serialplugin-disconnected-{}", &event_path);
        
        if let Err(e) = self.app.emit(
            &disconnected_event,
            format!("Serial port {} closed", &path),
        ) {
            log_warn!("Failed to send disconnection event on close: {}", e);
        }
        
        match self.serialports.lock() {
            Ok(mut serialports) => {
                if let Some(port_info) = serialports.remove(&path) {
                    log_debug!("stop {}", path);
                    finish_serialport_info(port_info)?;

                    log_debug!("end {}", path);

                    Ok(())
                } else {
                    Err(Error::String(format!("Serial port {} is not open!", &path)))
                }
            }
            Err(error) => Err(Error::String(format!("Failed to acquire lock: {}", error))),
        }
    }

    /// Close all open serial ports
    pub fn close_all(&self) -> Result<(), Error> {
        let mut ports = self
            .serialports
            .lock()
            .map_err(|e| Error::String(e.to_string()))?;
        let mut errors = vec![];

        for (path, port_info) in ports.drain() {
            // Emit disconnected event for each port
            let event_path = path.replace(".", "-").replace("/", "-");
            let disconnected_event = format!("plugin-serialplugin-disconnected-{}", &event_path);
            
            if let Err(e) = self.app.emit(
                &disconnected_event,
                format!("Serial port {} closed (close_all)", &path),
            ) {
                log_warn!("Failed to send disconnection event for {}: {}", path, e);
            }

            if let Err(e) = finish_serialport_info(port_info) {
                errors.push(e.to_string());
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(Error::String(errors.join(", ")))
        }
    }

    /// Force close a serial port
    pub fn force_close(&self, path: String) -> Result<(), Error> {
        match self.serialports.lock() {
            Ok(mut map) => {
                if let Some(serial) = map.remove(&path) {
                    finish_serialport_info(serial)?;
                }
                Ok(())
            }
            Err(error) => Err(Error::String(format!("Failed to acquire lock: {}", error))),
        }
    }

    pub fn open(
        &self,
        path: String,
        baud_rate: u32,
        data_bits: Option<DataBits>,
        flow_control: Option<FlowControl>,
        parity: Option<Parity>,
        stop_bits: Option<StopBits>,
        timeout: Option<u64>,
    ) -> Result<(), Error> {
        let mut serialports = self
            .serialports
            .lock()
            .map_err(|e| Error::String(format!("Failed to acquire lock: {}", e)))?;

        // Close existing port before opening a new one
        if let Some(existing) = serialports.remove(&path) {
            log_info!("Force closing existing port {}", path);
            finish_serialport_info(existing)?;
        }

        serialports.insert(
            path.clone(),
            SerialportInfo {
                state: PortState::Opening,
            },
        );

        // Open new port (mutex held — concurrent access to this path sees Opening)
        let port_result = serialport::new(path.clone(), baud_rate)
            .data_bits(data_bits.map(Into::into).unwrap_or(SerialDataBits::Eight))
            .flow_control(
                flow_control
                    .map(Into::into)
                    .unwrap_or(SerialFlowControl::None),
            )
            .parity(parity.map(Into::into).unwrap_or(SerialParity::None))
            .stop_bits(stop_bits.map(Into::into).unwrap_or(SerialStopBits::One))
            .timeout(Duration::from_millis(timeout.unwrap_or(200)))
            .open();

        match port_result {
            Ok(port) => {
                let entry = serialports
                    .get_mut(&path)
                    .ok_or_else(|| Error::String(format!("Port '{}' disappeared during open", path)))?;
                entry.state = PortState::Connected(ConnectedPort {
                    port,
                    sender: None,
                    thread_handle: None,
                });
                Ok(())
            }
            Err(e) => {
                serialports.remove(&path);
                Err(Error::String(format!("Failed to open serial port: {}", e)))
            }
        }
    }

    /// Read data from the serial port
    pub fn start_listening(
        &self,
        path: String,
        timeout: Option<u64>,
        size: Option<usize>,
    ) -> Result<(), Error> {
        log_debug!("Starting listening on port: {}", path);

        self.with_connected_port(path.clone(), |port_info| {
            if port_info.sender.is_some() {
                log_debug!("Existing listener found, stopping it first");
                if let Some(sender) = &port_info.sender {
                    sender.send(1).map_err(|e| {
                        log_error!("Failed to stop existing listener: {}", e);
                        Error::String(format!("Failed to stop existing listener: {}", e))
                    })?;
                }
                port_info.sender = None;

                // Wait for thread to finish
                if let Some(handle) = port_info.thread_handle.take() {
                    log_debug!("Waiting for existing thread to finish");
                    if let Err(e) = handle.join() {
                        log_error!("Error joining thread: {:?}", e);
                    }
                }
            }

            // Start listening immediately after opening
            let event_path = path.replace(".", "-").replace("/", "-");
            let read_event = format!("plugin-serialplugin-read-{}", &event_path);
            let disconnected_event = format!("plugin-serialplugin-disconnected-{}", &event_path);

            log_debug!("Setting up port monitoring for: {}", read_event);

            let mut serial = port_info
                .port
                .try_clone()
                .map_err(|e| Error::String(format!("Failed to clone serial port: {}", e)))?;

            let timeout_ms = timeout.unwrap_or(200).min(1);

            serial
                .set_timeout(Duration::from_millis(timeout_ms))
                .map_err(|e| Error::String(format!("Failed to set short timeout: {}", e)))?;

            let (tx, rx): (Sender<usize>, Receiver<usize>) = mpsc::channel();
            port_info.sender = Some(tx);

            let app_clone = self.app.clone();
            let path_clone = path.clone();
            let thread_handle = thread::spawn(move || {
                let mut combined_buffer: Vec<u8> = Vec::with_capacity(size.unwrap_or(1024));
                let mut start_time = Instant::now();
                loop {
                    match rx.try_recv() {
                        Ok(_) => break,
                        Err(TryRecvError::Disconnected) => {
                            if let Err(e) = app_clone.emit(
                                &disconnected_event,
                                format!("Serial port {} disconnected!", &path_clone),
                            ) {
                                log_error!("Failed to send disconnection event: {}", e);
                            }
                            break;
                        }
                        Err(TryRecvError::Empty) => {}
                    }

                    let mut buffer = vec![0; size.unwrap_or(1024)];
                    match serial.read(&mut buffer) {
                        Ok(n) => {
                            combined_buffer.extend_from_slice(&buffer[..n]);
                        }
                        Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {}
                        Err(e) => {
                            log_error!("Failed to read data: {}", e);

                            // Emit disconnected event if the port is gone
                            if let Err(err) = app_clone.emit(
                                &disconnected_event,
                                format!(
                                    "Serial port {} disconnected due to error: {}",
                                    &path_clone, e
                                ),
                            ) {
                                log_error!("Failed to send disconnection event: {}", err);
                            }

                            break;
                        }
                    }

                    let elapsed_time = start_time.elapsed();

                    if elapsed_time > Duration::from_millis(timeout.unwrap_or(200)) {
                        start_time = Instant::now();

                        let size = combined_buffer.len();

                        if size == 0 {
                            continue;
                        }

                        if let Err(e) = app_clone.emit(
                            &read_event,
                            ReadData {
                                size,
                                data: combined_buffer.as_mut_slice(),
                            },
                        ) {
                            log_error!("Failed to send data: {}", e);
                        }

                        combined_buffer.clear();
                    }
                }
            });

            port_info.thread_handle = Some(thread_handle);

            Ok({})
        })
    }

    pub fn stop_listening(&self, path: String) -> Result<(), Error> {
        log_debug!("Stopping listening on port: {}", path);

        self.with_connected_port(path.clone(), |port_info| {
            if let Some(sender) = &port_info.sender {
                sender.send(1).map_err(|e| {
                    Error::String(format!("Failed to cancel serial port data reading: {}", e))
                })?;
            }
            port_info.sender = None;
            port_info.thread_handle = None;

            Ok({})
        })
    }

    /// Read data from the serial port
    pub fn read(
        &self,
        path: String,
        timeout: Option<u64>,
        size: Option<usize>,
    ) -> Result<String, Error> {
        self.get_serialport(path.clone(), |port| {
            let timeout = timeout.unwrap_or(1000);

            let mut buffer = vec![0; size.unwrap_or(1024)];
            port.set_timeout(Duration::from_millis(timeout))
                .map_err(|e| Error::String(format!("Failed to set timeout: {}", e)))?;

            match port.read(&mut buffer) {
                Ok(n) => {
                    let data = String::from_utf8_lossy(&buffer[..n]).to_string();
                    Ok(data)
                }
                Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Err(Error::String(format!(
                    "no data received within {} ms",
                    timeout
                ))),
                Err(e) => Err(Error::String(format!("Failed to read data: {}", e))),
            }
        })
    }

    pub fn read_binary(
        &self,
        path: String,
        timeout: Option<u64>,
        size: Option<usize>,
    ) -> Result<Vec<u8>, Error> {
        self.get_serialport(path.clone(), |port| {
            let target_size = size.unwrap_or(1024);
            let timeout = timeout.unwrap_or(1000);
            let mut buffer = Vec::with_capacity(target_size);
            let start = std::time::Instant::now();

            while buffer.len() < target_size && start.elapsed() < Duration::from_millis(timeout) {
                let mut temp_buf = vec![0; target_size - buffer.len()];
                match port.read(&mut temp_buf) {
                    Ok(n) if n > 0 => {
                        buffer.extend_from_slice(&temp_buf[..n]);
                    }
                    Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {
                        if buffer.is_empty() {
                            return Err(Error::String(format!(
                                "no data received within {} ms",
                                timeout
                            )));
                        } else {
                            break;
                        }
                    }
                    Err(e) => return Err(Error::String(format!("Failed to read data: {}", e))),
                    _ => break,
                }
            }

            Ok(buffer)
        })
    }

    /// Write data to the serial port
    pub fn write(&self, path: String, value: String) -> Result<usize, Error> {
        self.get_serialport(path.clone(), |port| {
            port.write(value.as_bytes())
                .map_err(|e| Error::String(format!("Failed to write data: {}", e)))
        })
    }

    /// Write binary data to the serial port
    pub fn write_binary(&self, path: String, value: Vec<u8>) -> Result<usize, Error> {
        self.get_serialport(path.clone(), |port| {
            port.write(&value)
                .map_err(|e| Error::String(format!("Failed to write binary data: {}", e)))
        })
    }

    /// Set the baud rate
    pub fn set_baud_rate(&self, path: String, baud_rate: u32) -> Result<(), Error> {
        self.get_serialport(path, |port| {
            port.set_baud_rate(baud_rate)
                .map_err(|e| Error::String(format!("Failed to set baud rate: {}", e)))
        })
    }

    /// Set the data bits
    pub fn set_data_bits(&self, path: String, data_bits: DataBits) -> Result<(), Error> {
        self.get_serialport(path, |port| {
            port.set_data_bits(data_bits.into()).map_err(Error::from)
        })
    }

    /// Set the flow control
    pub fn set_flow_control(&self, path: String, flow_control: FlowControl) -> Result<(), Error> {
        self.get_serialport(path, |port| {
            port.set_flow_control(flow_control.into()).map_err(Error::from)
        })
    }

    /// Set the parity
    pub fn set_parity(&self, path: String, parity: Parity) -> Result<(), Error> {
        self.get_serialport(path, |port| {
            port.set_parity(parity.into()).map_err(Error::from)
        })
    }

    /// Set the stop bits
    pub fn set_stop_bits(&self, path: String, stop_bits: StopBits) -> Result<(), Error> {
        self.get_serialport(path, |port| {
            port.set_stop_bits(stop_bits.into()).map_err(Error::from)
        })
    }

    /// Set the timeout
    pub fn set_timeout(&self, path: String, timeout: Duration) -> Result<(), Error> {
        self.get_serialport(path, |port| {
            port.set_timeout(timeout).map_err(Error::from)
        })
    }

    /// Set the RTS (Request To Send) control signal
    pub fn write_request_to_send(&self, path: String, level: bool) -> Result<(), Error> {
        self.get_serialport(path, |port| {
            port.write_request_to_send(level).map_err(Error::from)
        })
    }

    /// Set the DTR (Data Terminal Ready) control signal
    pub fn write_data_terminal_ready(&self, path: String, level: bool) -> Result<(), Error> {
        self.get_serialport(path, |port| {
            port.write_data_terminal_ready(level).map_err(Error::from)
        })
    }

    /// Read the CTS (Clear To Send) control signal state
    pub fn read_clear_to_send(&self, path: String) -> Result<bool, Error> {
        self.get_serialport(path, |port| {
            port.read_clear_to_send().map_err(Error::from)
        })
    }

    /// Read the DSR (Data Set Ready) control signal state
    pub fn read_data_set_ready(&self, path: String) -> Result<bool, Error> {
        self.get_serialport(path, |port| {
            port.read_data_set_ready().map_err(Error::from)
        })
    }

    /// Read the RI (Ring Indicator) control signal state
    pub fn read_ring_indicator(&self, path: String) -> Result<bool, Error> {
        self.get_serialport(path, |port| {
            port.read_ring_indicator().map_err(Error::from)
        })
    }

    /// Read the CD (Carrier Detect) control signal state
    pub fn read_carrier_detect(&self, path: String) -> Result<bool, Error> {
        self.get_serialport(path, |port| {
            port.read_carrier_detect().map_err(Error::from)
        })
    }

    /// Get the number of bytes available to read
    pub fn bytes_to_read(&self, path: String) -> Result<u32, Error> {
        self.get_serialport(path, |port| port.bytes_to_read().map_err(Error::from))
    }

    /// Get the number of bytes waiting to be written
    pub fn bytes_to_write(&self, path: String) -> Result<u32, Error> {
        self.get_serialport(path, |port| port.bytes_to_write().map_err(Error::from))
    }

    /// Clear input/output buffers
    pub fn clear_buffer(&self, path: String, buffer_to_clear: ClearBuffer) -> Result<(), Error> {
        self.get_serialport(path, |port| {
            port.clear(buffer_to_clear.into()).map_err(Error::from)
        })
    }

    /// Start break signal transmission
    pub fn set_break(&self, path: String) -> Result<(), Error> {
        self.get_serialport(path, |port| port.set_break().map_err(Error::from))
    }

    /// Stop break signal transmission
    pub fn clear_break(&self, path: String) -> Result<(), Error> {
        self.get_serialport(path, |port| port.clear_break().map_err(Error::from))
    }

    /// Run `f` only when the port is [`PortState::Connected`].
    fn with_connected_port<T, F>(&self, path: String, f: F) -> Result<T, Error>
    where
        F: FnOnce(&mut ConnectedPort) -> Result<T, Error>,
    {
        let mut ports = self
            .serialports
            .lock()
            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;

        let info = ports
            .get_mut(&path)
            .ok_or_else(|| Error::String(format!("Port '{}' not found", path)))?;

        match &mut info.state {
            PortState::Connected(cp) => f(cp),
            other => Err(Error::String(other.not_connected_reason())),
        }
    }

    fn get_serialport<T, F>(&self, path: String, f: F) -> Result<T, Error>
    where
        F: FnOnce(&mut Box<dyn serialport::SerialPort>) -> Result<T, Error>,
    {
        self.with_connected_port(path, |cp| f(&mut cp.port))
    }

    fn get_port_info(&self, port: serialport::SerialPortType) -> HashMap<String, String> {
        let mut port_info: HashMap<String, String> = HashMap::new();
        port_info.insert("type".to_string(), UNKNOWN.to_string());
        port_info.insert("vid".to_string(), UNKNOWN.to_string());
        port_info.insert("pid".to_string(), UNKNOWN.to_string());
        port_info.insert("serial_number".to_string(), UNKNOWN.to_string());
        port_info.insert("manufacturer".to_string(), UNKNOWN.to_string());
        port_info.insert("product".to_string(), UNKNOWN.to_string());

        match port {
            serialport::SerialPortType::UsbPort(info) => {
                port_info.insert("type".to_string(), USB.to_string());
                port_info.insert("vid".to_string(), info.vid.to_string());
                port_info.insert("pid".to_string(), info.pid.to_string());
                port_info.insert(
                    "serial_number".to_string(),
                    info.serial_number.unwrap_or_else(|| UNKNOWN.to_string()),
                );
                port_info.insert(
                    "manufacturer".to_string(),
                    info.manufacturer.unwrap_or_else(|| UNKNOWN.to_string()),
                );
                port_info.insert(
                    "product".to_string(),
                    info.product.unwrap_or_else(|| UNKNOWN.to_string()),
                );
            }
            serialport::SerialPortType::BluetoothPort => {
                port_info.insert("type".to_string(), BLUETOOTH.to_string());
            }
            serialport::SerialPortType::PciPort => {
                port_info.insert("type".to_string(), PCI.to_string());
            }
            serialport::SerialPortType::Unknown => {
                port_info.insert("type".to_string(), UNKNOWN.to_string());
            }
        }

        port_info
    }
}