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
//! State types and enums for serial port configuration
//! 
//! This module contains all the types and enums used for configuring serial ports,
//! including data bits, flow control, parity, stop bits, and buffer types.
//! 
//! # Example
//! 
//! ```rust
//! use tauri_plugin_serialplugin::state::{DataBits, FlowControl, Parity, StopBits, ClearBuffer};
//! 
//! // Configure serial port settings
//! let data_bits = DataBits::Eight;
//! let flow_control = FlowControl::None;
//! let parity = Parity::None;
//! let stop_bits = StopBits::One;
//! let buffer_type = ClearBuffer::All;
//! ```

use serde::{Deserialize, Serialize};
use serialport::{self, SerialPort};
use serialport::{
    ClearBuffer as SerialClearBuffer, DataBits as SerialDataBits, FlowControl as SerialFlowControl,
    Parity as SerialParity, StopBits as SerialStopBits,
};
use std::thread::JoinHandle;
use std::{
    collections::HashMap,
    sync::{mpsc::Sender, Arc, Mutex, OnceLock},
};

/// Open serial port with optional background read thread handles (desktop).
pub struct ConnectedPort {
    /// Underlying serial device
    pub port: Box<dyn SerialPort>,
    /// Signal channel for the read thread (when listening)
    pub sender: Option<Sender<usize>>,
    /// Background read thread
    pub thread_handle: Option<JoinHandle<()>>,
}

/// Lifecycle state for a managed port (desktop).
pub enum PortState {
    /// Slot unused or released (only kept for tests / explicit transitions)
    Closed,
    /// `open()` is in progress — I/O must wait
    Opening,
    /// Port is ready for read/write/settings
    Connected(ConnectedPort),
}

impl PortState {
    /// Human-readable reason when [`PortState::Connected`] is required but state differs.
    pub fn not_connected_reason(&self) -> String {
        match self {
            PortState::Closed => "Port is closed".to_string(),
            PortState::Opening => "Port is still opening".to_string(),
            PortState::Connected(_) => "Port is connected".to_string(),
        }
    }
}

/// Main state structure for managing serial ports
/// 
/// This structure holds the global state of all serial ports managed by the plugin.
/// It uses thread-safe containers to allow concurrent access from multiple threads.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::SerialportState;
/// 
/// let state = SerialportState::default();
/// ```
#[derive(Default)]
pub struct SerialportState {
    /// Thread-safe map of port names to port information
    /// 
    /// This field stores all currently managed serial ports. The outer `Arc<Mutex<>>`
    /// ensures thread safety, while the inner `HashMap` maps port names (like "COM1")
    /// to their corresponding `SerialportInfo` structures.
    pub serialports: Arc<Mutex<HashMap<String, SerialportInfo>>>,
}
/// Information structure for a single serial port (desktop)
/// 
/// Holds a [`PortState`] so I/O runs only in [`PortState::Connected`], avoiding use-after-close.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::SerialportInfo;
/// use serialport::SerialPort;
/// 
/// // This is typically created internally by the plugin
/// // let info = SerialportInfo::new(port);
/// ```
pub struct SerialportInfo {
    /// Current lifecycle state (desktop).
    pub state: PortState,
}

impl SerialportInfo {
    /// Creates a new `SerialportInfo` in [`PortState::Connected`] with no listener thread.
    pub fn new(port: Box<dyn SerialPort>) -> Self {
        Self {
            state: PortState::Connected(ConnectedPort {
                port,
                sender: None,
                thread_handle: None,
            }),
        }
    }

    /// Mutable access to [`ConnectedPort`] when state is [`PortState::Connected`].
    #[cfg(test)]
    pub(crate) fn connected_port_mut(&mut self) -> Option<&mut ConnectedPort> {
        match &mut self.state {
            PortState::Connected(cp) => Some(cp),
            _ => None,
        }
    }
}

/// Result structure for Tauri invoke operations
/// 
/// This structure is used to return results from Tauri command invocations
/// with a standardized format including a status code and message.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::InvokeResult;
/// 
/// let result = InvokeResult {
///     code: 0,
///     message: "Operation completed successfully".to_string(),
/// };
/// ```
#[derive(Serialize, Clone)]
pub struct InvokeResult {
    /// Status code indicating success (0) or error (non-zero)
    pub code: i32,
    /// Human-readable message describing the result
    pub message: String,
}

/// Structure for holding read data from serial ports
/// 
/// This structure holds data that has been read from a serial port,
/// including a reference to the data and its size.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::ReadData;
/// 
/// let data = b"Hello World";
/// let read_data = ReadData {
///     data: data,
///     size: data.len(),
/// };
/// ```
#[derive(Serialize, Clone)]
pub struct ReadData<'a> {
    /// Reference to the read data bytes
    pub data: &'a [u8],
    /// Size of the read data in bytes
    pub size: usize,
}

/// Port type constants for identifying serial port types
/// 
/// These constants are used to identify the type of serial port
/// when listing available ports.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::{USB, BLUETOOTH, PCI, UNKNOWN};
/// 
/// let port_type = USB;
/// match port_type {
///     USB => println!("USB serial port"),
///     BLUETOOTH => println!("Bluetooth serial port"),
///     PCI => println!("PCI serial port"),
///     _ => println!("Unknown port type"),
/// }
/// ```

/// Unknown port type
pub const UNKNOWN: &str = "Unknown";
/// USB serial port
pub const USB: &str = "USB";
/// Bluetooth serial port
pub const BLUETOOTH: &str = "Bluetooth";
/// PCI serial port
pub const PCI: &str = "PCI";

/// Number of bits per character for serial communication
/// 
/// This enum defines the number of data bits used in each character transmitted
/// over the serial port. Most modern applications use 8 data bits.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::DataBits;
/// 
/// let data_bits = DataBits::Eight; // Most common setting
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DataBits {
    /// 5 bits per character (rarely used)
    Five,
    /// 6 bits per character (rarely used)
    Six,
    /// 7 bits per character (used with parity)
    Seven,
    /// 8 bits per character (most common)
    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,
        }
    }
}

impl DataBits {
    /// Converts the data bits enum to its numeric value
    /// 
    /// Returns the number of bits as a `u8` value.
    /// 
    /// # Returns
    /// 
    /// The number of data bits: 5, 6, 7, or 8.
    /// 
    /// # Example
    /// 
    /// ```rust
    /// use tauri_plugin_serialplugin::state::DataBits;
    /// 
    /// let data_bits = DataBits::Eight;
    /// assert_eq!(data_bits.as_u8(), 8);
    /// ```
    pub fn as_u8(&self) -> u8 {
        match self {
            DataBits::Five => 5,
            DataBits::Six => 6,
            DataBits::Seven => 7,
            DataBits::Eight => 8,
        }
    }
}

/// Flow control modes for serial communication
/// 
/// Flow control prevents data loss by allowing the receiver to signal when it's
/// ready to receive more data.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::FlowControl;
/// 
/// let flow_control = FlowControl::None; // No flow control
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum FlowControl {
    /// No flow control (most common for simple applications)
    None,
    /// Software flow control using XON/XOFF bytes
    Software,
    /// Hardware 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,
        }
    }
}

impl FlowControl {
    /// Converts the flow control enum to its numeric value
    /// 
    /// Returns the flow control mode as a `u8` value.
    /// 
    /// # Returns
    /// 
    /// The flow control mode: 0 (None), 1 (Software), or 2 (Hardware).
    /// 
    /// # Example
    /// 
    /// ```rust
    /// use tauri_plugin_serialplugin::state::FlowControl;
    /// 
    /// let flow_control = FlowControl::None;
    /// assert_eq!(flow_control.as_u8(), 0);
    /// ```
    pub fn as_u8(&self) -> u8 {
        match self {
            FlowControl::None => 0,
            FlowControl::Software => 1,
            FlowControl::Hardware => 2,
        }
    }
}

/// Parity checking modes for serial communication
/// 
/// Parity is an error detection method that adds an extra bit to each character
/// to ensure the total number of 1 bits is either odd or even.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::Parity;
/// 
/// let parity = Parity::None; // No parity checking (most common)
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Parity {
    /// No parity bit (most common for modern applications)
    None,
    /// Parity bit ensures odd number of 1 bits
    Odd,
    /// Parity bit ensures 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,
        }
    }
}

impl Parity {
    /// Converts the parity enum to its numeric value
    /// 
    /// Returns the parity mode as a `u8` value.
    /// 
    /// # Returns
    /// 
    /// The parity mode: 0 (None), 1 (Odd), or 2 (Even).
    /// 
    /// # Example
    /// 
    /// ```rust
    /// use tauri_plugin_serialplugin::state::Parity;
    /// 
    /// let parity = Parity::None;
    /// assert_eq!(parity.as_u8(), 0);
    /// ```
    pub fn as_u8(&self) -> u8 {
        match self {
            Parity::None => 0,
            Parity::Odd => 1,
            Parity::Even => 2,
        }
    }
}

/// Number of stop bits for serial communication
/// 
/// Stop bits are used to signal the end of a character transmission.
/// Most modern applications use one stop bit.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::StopBits;
/// 
/// let stop_bits = StopBits::One; // Most common setting
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum StopBits {
    /// One stop bit (most common)
    One,
    /// Two stop bits (used in some legacy systems)
    Two,
}

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

impl StopBits {
    /// Converts the stop bits enum to its numeric value
    /// 
    /// Returns the number of stop bits as a `u8` value.
    /// 
    /// # Returns
    /// 
    /// The number of stop bits: 1 or 2.
    /// 
    /// # Example
    /// 
    /// ```rust
    /// use tauri_plugin_serialplugin::state::StopBits;
    /// 
    /// let stop_bits = StopBits::One;
    /// assert_eq!(stop_bits.as_u8(), 1);
    /// ```
    pub fn as_u8(&self) -> u8 {
        match self {
            StopBits::One => 1,
            StopBits::Two => 2,
        }
    }
}

/// Buffer types for clearing serial port buffers
/// 
/// Serial ports maintain input and output buffers to store data.
/// This enum allows you to specify which buffers to clear.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::ClearBuffer;
/// 
/// let buffer_type = ClearBuffer::All; // Clear both input and output buffers
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ClearBuffer {
    /// Input buffer (received data waiting to be read)
    Input,
    /// Output buffer (transmitted data waiting to be sent)
    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,
        }
    }
}

/// Logging level for controlling plugin verbosity
/// 
/// This enum allows you to control how much logging output the plugin produces.
/// Use it to reduce noise in production environments or enable detailed logs for debugging.
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::LogLevel;
/// 
/// let log_level = LogLevel::Error; // Only show errors
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum LogLevel {
    /// No logging output
    None,
    /// Only critical errors
    Error,
    /// Errors and warnings
    Warn,
    /// Errors, warnings, and general information
    Info,
    /// All logging including debug information
    Debug,
}

impl Default for LogLevel {
    fn default() -> Self {
        LogLevel::Info
    }
}

impl LogLevel {
    /// Checks if error messages should be logged at the current level
    pub fn should_log_error(&self) -> bool {
        matches!(self, LogLevel::Error | LogLevel::Warn | LogLevel::Info | LogLevel::Debug)
    }

    /// Checks if warning messages should be logged at the current level
    pub fn should_log_warn(&self) -> bool {
        matches!(self, LogLevel::Warn | LogLevel::Info | LogLevel::Debug)
    }

    /// Checks if info messages should be logged at the current level
    pub fn should_log_info(&self) -> bool {
        matches!(self, LogLevel::Info | LogLevel::Debug)
    }

    /// Checks if debug messages should be logged at the current level
    pub fn should_log_debug(&self) -> bool {
        matches!(self, LogLevel::Debug)
    }
}

/// Global log level state
static LOG_LEVEL: OnceLock<Mutex<LogLevel>> = OnceLock::new();

/// Gets or initializes the log level mutex
fn get_log_level_mutex() -> &'static Mutex<LogLevel> {
    LOG_LEVEL.get_or_init(|| Mutex::new(LogLevel::Info))
}

/// Sets the global log level for the plugin
/// 
/// # Arguments
/// 
/// * `level` - The new log level to set
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::{LogLevel, set_log_level};
/// 
/// set_log_level(LogLevel::Error);
/// ```
pub fn set_log_level(level: LogLevel) {
    if let Ok(mut log_level) = get_log_level_mutex().lock() {
        *log_level = level;
    }
}

/// Gets the current global log level
/// 
/// # Returns
/// 
/// The current log level
/// 
/// # Example
/// 
/// ```rust
/// use tauri_plugin_serialplugin::state::get_log_level;
/// 
/// let level = get_log_level();
/// ```
pub fn get_log_level() -> LogLevel {
    get_log_level_mutex().lock().unwrap_or_else(|e| {
        eprintln!("Failed to lock log level: {}", e);
        e.into_inner()
    }).clone()
}