tauri_plugin_serialplugin/
commands.rs

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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use crate::error::Error;
use crate::state::{ReadData, SerialportInfo, SerialportState};
use serde::{Deserialize, Serialize};
use serialport::{DataBits as SerialDataBits, FlowControl as SerialFlowControl,
                 Parity as SerialParity, StopBits as SerialStopBits, ClearBuffer as SerialClearBuffer};
use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
use std::thread;
use std::time::Duration;
use tauri::{AppHandle, Emitter, Runtime, State, Window};

const UNKNOWN: &str = "Unknown";
const USB: &str = "USB";
const BLUETOOTH: &str = "Bluetooth";
const PCI: &str = "PCI";

/// Number of bits per character
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DataBits {
    /// 5 bits per character
    Five,
    /// 6 bits per character
    Six,
    /// 7 bits per character
    Seven,
    /// 8 bits per character
    Eight,
}

impl From<DataBits> for SerialDataBits {
    fn from(bits: DataBits) -> Self {
        match bits {
            DataBits::Five => SerialDataBits::Five,
            DataBits::Six => SerialDataBits::Six,
            DataBits::Seven => SerialDataBits::Seven,
            DataBits::Eight => SerialDataBits::Eight,
        }
    }
}

/// Flow control modes
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum FlowControl {
    /// No flow control
    None,
    /// Flow control using XON/XOFF bytes
    Software,
    /// Flow control using RTS/CTS signals
    Hardware,
}

impl From<FlowControl> for SerialFlowControl {
    fn from(flow: FlowControl) -> Self {
        match flow {
            FlowControl::None => SerialFlowControl::None,
            FlowControl::Software => SerialFlowControl::Software,
            FlowControl::Hardware => SerialFlowControl::Hardware,
        }
    }
}

/// Parity checking modes
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Parity {
    /// No parity bit
    None,
    /// Parity bit sets odd number of 1 bits
    Odd,
    /// Parity bit sets even number of 1 bits
    Even,
}

impl From<Parity> for SerialParity {
    fn from(parity: Parity) -> Self {
        match parity {
            Parity::None => SerialParity::None,
            Parity::Odd => SerialParity::Odd,
            Parity::Even => SerialParity::Even,
        }
    }
}

/// Number of stop bits
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum StopBits {
    /// One stop bit
    One,
    /// Two stop bits
    Two,
}

impl From<StopBits> for SerialStopBits {
    fn from(bits: StopBits) -> Self {
        match bits {
            StopBits::One => SerialStopBits::One,
            StopBits::Two => SerialStopBits::Two,
        }
    }
}

/// Buffer types for clearing
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ClearBuffer {
    /// Input buffer (received data)
    Input,
    /// Output buffer (transmitted data)
    Output,
    /// Both input and output buffers
    All,
}

impl From<ClearBuffer> for SerialClearBuffer {
    fn from(buffer: ClearBuffer) -> Self {
        match buffer {
            ClearBuffer::Input => SerialClearBuffer::Input,
            ClearBuffer::Output => SerialClearBuffer::Output,
            ClearBuffer::All => SerialClearBuffer::All,
        }
    }
}

/// Get serial port list
#[tauri::command]
pub fn available_ports() -> HashMap<String, HashMap<String, String>> {
    let mut list = serialport::available_ports().unwrap_or_else(|_| vec![]);
    list.retain(|port| matches!(port.port_type, serialport::SerialPortType::UsbPort(_)));
    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, get_port_info(p.port_type));
    }

    result_list
}

/// Get serial port list using platform-specific commands
#[tauri::command]
pub fn available_ports_direct() -> HashMap<String, HashMap<String, String>> {
    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);
            }
        }
    }

    result_list
}

/// Cancel reading data from the serial port
#[tauri::command]
pub async fn cancel_read<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<(), Error> {
    get_serialport(state, path.clone(), |serialport_info| {
        if let Some(sender) = &serialport_info.sender {
            sender.send(1).map_err(|e| {
                Error::String(format!("Failed to cancel serial port data reading: {}", e))
            })?;
        }
        serialport_info.sender = None;
        Ok(())
    })
}

/// Close the specified serial port
#[tauri::command]
pub fn close<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<(), Error> {
    match state.serialports.lock() {
        Ok(mut serialports) => {
            if let Some(port_info) = serialports.remove(&path) {
                // Signal the thread to stop
                if let Some(sender) = &port_info.sender {
                    sender.send(1).map_err(|e| {
                        Error::String(format!("Failed to cancel serial port data reading: {}", e))
                    })?;
                }

                // Wait for the thread to finish
                if let Some(handle) = port_info.thread_handle {
                    handle.join().map_err(|e| {
                        Error::String(format!("Failed to join thread: {:?}", e))
                    })?;
                }

                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
#[tauri::command]
pub fn close_all<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, SerialportState>,
) -> Result<(), Error> {
    match state.serialports.lock() {
        Ok(mut map) => {
            let mut errors = Vec::new();

            for (path, port_info) in map.drain() {
                if let Some(sender) = &port_info.sender {
                    if let Err(e) = sender.send(1) {
                        errors.push(format!("Failed to cancel port {}: {}", path, e));
                        continue;
                    }
                }

                if let Some(handle) = port_info.thread_handle {
                    if let Err(e) = handle.join() {
                        errors.push(format!("Failed to join thread for port {}: {:?}", path, e));
                    }
                }
            }

            if errors.is_empty() {
                Ok(())
            } else {
                Err(Error::String(format!("Errors during close: {}", errors.join(", "))))
            }
        }
        Err(error) => Err(Error::String(format!("Failed to acquire lock: {}", error))),
    }
}

/// Force close a serial port
#[tauri::command]
pub fn force_close<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<(), Error> {
    match state.serialports.lock() {
        Ok(mut map) => {
            if let Some(serial) = map.remove(&path) {
                if let Some(sender) = &serial.sender {
                    sender.send(1).map_err(|e| {
                        Error::String(format!("Failed to cancel serial port data reading: {}", e))
                    })?;
                }

                if let Some(handle) = serial.thread_handle {
                    handle.join().map_err(|e| {
                        Error::String(format!("Failed to join thread: {:?}", e))
                    })?;
                }
            }
            Ok(())
        }
        Err(error) => Err(Error::String(format!("Failed to acquire lock: {}", error))),
    }
}

#[tauri::command]
pub fn open<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, SerialportState>,
    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> {
    match state.serialports.lock() {
        Ok(mut serialports) => {
            if serialports.contains_key(&path) {
                return Err(Error::String(format!("Serial port {} is open!", path)));
            }

            let port = 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()
                .map_err(|e| Error::String(format!("Failed to open serial port: {}", e)))?;

            let port_info = SerialportInfo {
                serialport: port,
                sender: None,
                thread_handle: None,
            };

            serialports.insert(path, port_info);
            Ok(())
        }
        Err(error) => Err(Error::String(format!("Failed to acquire lock: {}", error))),
    }
}


/// Read data from the serial port
#[tauri::command]
pub fn start_listening<R: Runtime>(
    app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, SerialportState>,
    path: String,
    timeout: Option<u64>,
    size: Option<usize>,
) -> Result<(), Error> {
    println!("Starting listening on port: {}", path);

    get_serialport(state.clone(), path.clone(), |port_info| {
        if port_info.sender.is_some() {
            println!("Existing listener found, stopping it first");
            if let Some(sender) = &port_info.sender {
                sender.send(1).map_err(|e| {
                    eprintln!("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() {
                println!("Waiting for existing thread to finish");
                if let Err(e) = handle.join() {
                    eprintln!("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);

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

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

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

        let app_clone = app.clone();
        let path_clone = path.clone();
        let thread_handle = thread::spawn(move || {
            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),
                        ) {
                            eprintln!("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) => {
                        if let Err(e) = app_clone.emit(
                            &read_event,
                            ReadData {
                                data: &buffer[..n],
                                size: n,
                            },
                        ) {
                            eprintln!("Failed to send data: {}", e);
                        }
                    }
                    Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {}
                    Err(e) => {
                        eprintln!("Failed to read data: {}", e);
                        break; // Exit on error
                    }
                }

                thread::sleep(Duration::from_millis(timeout.unwrap_or(200)));
            }
        });

        port_info.thread_handle = Some(thread_handle);

        Ok({})
    })
}

#[tauri::command]
pub fn stop_listening<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<(), Error> {
    println!("Stopping listening on port: {}", path);

    get_serialport(state.clone(), 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
#[tauri::command]
pub fn read<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, SerialportState>,
    path: String,
    timeout: Option<u64>,
    size: Option<usize>,
) -> Result<String, Error> {
    get_serialport(state.clone(), path.clone(), |serialport_info| {
        let mut buffer = vec![0; size.unwrap_or(1024)];
        serialport_info.serialport.set_timeout(Duration::from_millis(timeout.unwrap_or(200)))
            .map_err(|e| Error::String(format!("Failed to set timeout: {}", e)))?;

        match serialport_info.serialport.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 => Ok(String::new()),
            Err(e) => Err(Error::String(format!("Failed to read data: {}", e))),
        }
    })
}

/// Write data to the serial port
#[tauri::command]
pub fn write<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, SerialportState>,
    path: String,
    value: String,
) -> Result<usize, Error> {
    get_serialport(state, path.clone(), |serialport_info| {
        serialport_info
            .serialport
            .write(value.as_bytes())
            .map_err(|e| Error::String(format!("Failed to write data: {}", e)))
    })
}

/// Write binary data to the serial port
#[tauri::command]
pub fn write_binary<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, SerialportState>,
    path: String,
    value: Vec<u8>,
) -> Result<usize, Error> {
    get_serialport(state, path.clone(), |serialport_info| {
        serialport_info
            .serialport
            .write(&value)
            .map_err(|e| Error::String(format!("Failed to write binary data: {}", e)))
    })
}

/// Set the baud rate
#[tauri::command]
pub async fn set_baud_rate<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
    baud_rate: u32,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .set_baud_rate(baud_rate)
            .map_err(Error::from)
    })
}

/// Set the data bits
#[tauri::command]
pub async fn set_data_bits<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
    data_bits: DataBits,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .set_data_bits(data_bits.into())
            .map_err(Error::from)
    })
}

/// Set the flow control
#[tauri::command]
pub async fn set_flow_control<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
    flow_control: FlowControl,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .set_flow_control(flow_control.into())
            .map_err(Error::from)
    })
}

/// Set the parity
#[tauri::command]
pub async fn set_parity<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
    parity: Parity,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .set_parity(parity.into())
            .map_err(Error::from)
    })
}

/// Set the stop bits
#[tauri::command]
pub async fn set_stop_bits<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
    stop_bits: StopBits,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .set_stop_bits(stop_bits.into())
            .map_err(Error::from)
    })
}

/// Set the timeout
#[tauri::command]
pub async fn set_timeout<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
    timeout: Duration,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .set_timeout(timeout)
            .map_err(Error::from)
    })
}

/// Set the RTS (Request To Send) control signal
#[tauri::command]
pub async fn write_request_to_send<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
    level: bool,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .write_request_to_send(level)
            .map_err(Error::from)
    })
}

/// Set the DTR (Data Terminal Ready) control signal
#[tauri::command]
pub async fn write_data_terminal_ready<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
    level: bool,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .write_data_terminal_ready(level)
            .map_err(Error::from)
    })
}

/// Read the CTS (Clear To Send) control signal state
#[tauri::command]
pub async fn read_clear_to_send<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<bool, Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .read_clear_to_send()
            .map_err(Error::from)
    })
}

/// Read the DSR (Data Set Ready) control signal state
#[tauri::command]
pub async fn read_data_set_ready<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<bool, Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .read_data_set_ready()
            .map_err(Error::from)
    })
}

/// Read the RI (Ring Indicator) control signal state
#[tauri::command]
pub async fn read_ring_indicator<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<bool, Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .read_ring_indicator()
            .map_err(Error::from)
    })
}

/// Read the CD (Carrier Detect) control signal state
#[tauri::command]
pub async fn read_carrier_detect<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<bool, Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .read_carrier_detect()
            .map_err(Error::from)
    })
}

/// Get the number of bytes available to read
#[tauri::command]
pub async fn bytes_to_read<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<u32, Error> {
    get_serialport(state, path, |port_info| {
        port_info.serialport.bytes_to_read().map_err(Error::from)
    })
}

/// Get the number of bytes waiting to be written
#[tauri::command]
pub async fn bytes_to_write<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<u32, Error> {
    get_serialport(state, path, |port_info| {
        port_info.serialport.bytes_to_write().map_err(Error::from)
    })
}

/// Clear input/output buffers
#[tauri::command]
pub async fn clear_buffer<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
    buffer_to_clear: ClearBuffer,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info
            .serialport
            .clear(buffer_to_clear.into())
            .map_err(Error::from)
    })
}

/// Start break signal transmission
#[tauri::command]
pub async fn set_break<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info.serialport.set_break().map_err(Error::from)
    })
}

/// Stop break signal transmission
#[tauri::command]
pub async fn clear_break<R: Runtime>(
    _app: AppHandle<R>,
    state: State<'_, SerialportState>,
    path: String,
) -> Result<(), Error> {
    get_serialport(state, path, |port_info| {
        port_info.serialport.clear_break().map_err(Error::from)
    })
}

fn get_serialport<T, F: FnOnce(&mut SerialportInfo) -> Result<T, Error>>(
    state: State<'_, SerialportState>,
    path: String,
    f: F,
) -> Result<T, Error> {
    match state.serialports.lock() {
        Ok(mut map) => match map.get_mut(&path) {
            Some(serialport_info) => f(serialport_info),
            None => Err(Error::String("Serial port not found".to_string())),
        },
        Err(error) => Err(Error::String(format!(
            "Failed to acquire file lock! {}",
            error
        ))),
    }
}

fn get_port_info(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
}