serialplugin_core/state/config.rs
1//! Serial port configuration enums, constants, and global log level.
2#[cfg(target_os = "ios")]
3use crate::serialport;
4
5use serde::{Deserialize, Serialize};
6use serialport::{
7 ClearBuffer as SerialClearBuffer, DataBits as SerialDataBits, FlowControl as SerialFlowControl,
8 Parity as SerialParity, StopBits as SerialStopBits,
9};
10use std::sync::{Mutex, OnceLock};
11
12/// Port type constants for identifying serial port types
13///
14/// These constants are used to identify the type of serial port
15/// when listing available ports.
16///
17/// # Example
18///
19/// ```rust
20/// use serialplugin_core::state::{USB, BLUETOOTH, PCI, UNKNOWN};
21///
22/// let port_type = USB;
23/// match port_type {
24/// USB => println!("USB serial port"),
25/// BLUETOOTH => println!("Bluetooth serial port"),
26/// PCI => println!("PCI serial port"),
27/// _ => println!("Unknown port type"),
28/// }
29/// ```
30/// Unknown port type
31pub const UNKNOWN: &str = "Unknown";
32/// USB serial port
33pub const USB: &str = "USB";
34/// Bluetooth serial port
35pub const BLUETOOTH: &str = "Bluetooth";
36/// PCI serial port
37pub const PCI: &str = "PCI";
38
39/// Number of bits per character for serial communication
40///
41/// This enum defines the number of data bits used in each character transmitted
42/// over the serial port. Most modern applications use 8 data bits.
43///
44/// # Example
45///
46/// ```rust
47/// use serialplugin_core::state::DataBits;
48///
49/// let data_bits = DataBits::Eight; // Most common setting
50/// ```
51#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub enum DataBits {
53 /// 5 bits per character (rarely used)
54 Five,
55 /// 6 bits per character (rarely used)
56 Six,
57 /// 7 bits per character (used with parity)
58 Seven,
59 /// 8 bits per character (most common)
60 Eight,
61}
62
63impl From<DataBits> for SerialDataBits {
64 fn from(bits: DataBits) -> Self {
65 match bits {
66 DataBits::Five => SerialDataBits::Five,
67 DataBits::Six => SerialDataBits::Six,
68 DataBits::Seven => SerialDataBits::Seven,
69 DataBits::Eight => SerialDataBits::Eight,
70 }
71 }
72}
73
74impl DataBits {
75 /// Converts the data bits enum to its numeric value
76 ///
77 /// Returns the number of bits as a `u8` value.
78 ///
79 /// # Returns
80 ///
81 /// The number of data bits: 5, 6, 7, or 8.
82 ///
83 /// # Example
84 ///
85 /// ```rust
86 /// use serialplugin_core::state::DataBits;
87 ///
88 /// let data_bits = DataBits::Eight;
89 /// assert_eq!(data_bits.as_u8(), 8);
90 /// ```
91 pub fn as_u8(&self) -> u8 {
92 match self {
93 DataBits::Five => 5,
94 DataBits::Six => 6,
95 DataBits::Seven => 7,
96 DataBits::Eight => 8,
97 }
98 }
99}
100
101/// Flow control modes for serial communication
102///
103/// Flow control prevents data loss by allowing the receiver to signal when it's
104/// ready to receive more data.
105///
106/// # Example
107///
108/// ```rust
109/// use serialplugin_core::state::FlowControl;
110///
111/// let flow_control = FlowControl::None; // No flow control
112/// ```
113#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
114pub enum FlowControl {
115 /// No flow control (most common for simple applications)
116 None,
117 /// Software flow control using XON/XOFF bytes
118 Software,
119 /// Hardware flow control using RTS/CTS signals
120 Hardware,
121}
122
123impl From<FlowControl> for SerialFlowControl {
124 fn from(flow: FlowControl) -> Self {
125 match flow {
126 FlowControl::None => SerialFlowControl::None,
127 FlowControl::Software => SerialFlowControl::Software,
128 FlowControl::Hardware => SerialFlowControl::Hardware,
129 }
130 }
131}
132
133impl FlowControl {
134 /// Converts the flow control enum to its numeric value
135 ///
136 /// Returns the flow control mode as a `u8` value.
137 ///
138 /// # Returns
139 ///
140 /// The flow control mode: 0 (None), 1 (Software), or 2 (Hardware).
141 ///
142 /// # Example
143 ///
144 /// ```rust
145 /// use serialplugin_core::state::FlowControl;
146 ///
147 /// let flow_control = FlowControl::None;
148 /// assert_eq!(flow_control.as_u8(), 0);
149 /// ```
150 pub fn as_u8(&self) -> u8 {
151 match self {
152 FlowControl::None => 0,
153 FlowControl::Software => 1,
154 FlowControl::Hardware => 2,
155 }
156 }
157}
158
159/// Parity checking modes for serial communication
160///
161/// Parity is an error detection method that adds an extra bit to each character
162/// to ensure the total number of 1 bits is either odd or even.
163///
164/// # Example
165///
166/// ```rust
167/// use serialplugin_core::state::Parity;
168///
169/// let parity = Parity::None; // No parity checking (most common)
170/// ```
171#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
172pub enum Parity {
173 /// No parity bit (most common for modern applications)
174 None,
175 /// Parity bit ensures odd number of 1 bits
176 Odd,
177 /// Parity bit ensures even number of 1 bits
178 Even,
179}
180
181impl From<Parity> for SerialParity {
182 fn from(parity: Parity) -> Self {
183 match parity {
184 Parity::None => SerialParity::None,
185 Parity::Odd => SerialParity::Odd,
186 Parity::Even => SerialParity::Even,
187 }
188 }
189}
190
191impl Parity {
192 /// Converts the parity enum to its numeric value
193 ///
194 /// Returns the parity mode as a `u8` value.
195 ///
196 /// # Returns
197 ///
198 /// The parity mode: 0 (None), 1 (Odd), or 2 (Even).
199 ///
200 /// # Example
201 ///
202 /// ```rust
203 /// use serialplugin_core::state::Parity;
204 ///
205 /// let parity = Parity::None;
206 /// assert_eq!(parity.as_u8(), 0);
207 /// ```
208 pub fn as_u8(&self) -> u8 {
209 match self {
210 Parity::None => 0,
211 Parity::Odd => 1,
212 Parity::Even => 2,
213 }
214 }
215}
216
217/// Number of stop bits for serial communication
218///
219/// Stop bits are used to signal the end of a character transmission.
220/// Most modern applications use one stop bit.
221///
222/// # Example
223///
224/// ```rust
225/// use serialplugin_core::state::StopBits;
226///
227/// let stop_bits = StopBits::One; // Most common setting
228/// ```
229#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub enum StopBits {
231 /// One stop bit (most common)
232 One,
233 /// Two stop bits (used in some legacy systems)
234 Two,
235}
236
237impl From<StopBits> for SerialStopBits {
238 fn from(bits: StopBits) -> Self {
239 match bits {
240 StopBits::One => SerialStopBits::One,
241 StopBits::Two => SerialStopBits::Two,
242 }
243 }
244}
245
246impl StopBits {
247 /// Converts the stop bits enum to its numeric value
248 ///
249 /// Returns the number of stop bits as a `u8` value.
250 ///
251 /// # Returns
252 ///
253 /// The number of stop bits: 1 or 2.
254 ///
255 /// # Example
256 ///
257 /// ```rust
258 /// use serialplugin_core::state::StopBits;
259 ///
260 /// let stop_bits = StopBits::One;
261 /// assert_eq!(stop_bits.as_u8(), 1);
262 /// ```
263 pub fn as_u8(&self) -> u8 {
264 match self {
265 StopBits::One => 1,
266 StopBits::Two => 2,
267 }
268 }
269}
270
271/// Buffer types for clearing serial port buffers
272///
273/// Serial ports maintain input and output buffers to store data.
274/// This enum allows you to specify which buffers to clear.
275///
276/// # Example
277///
278/// ```rust
279/// use serialplugin_core::state::ClearBuffer;
280///
281/// let buffer_type = ClearBuffer::All; // Clear both input and output buffers
282/// ```
283#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
284pub enum ClearBuffer {
285 /// Input buffer (received data waiting to be read)
286 Input,
287 /// Output buffer (transmitted data waiting to be sent)
288 Output,
289 /// Both input and output buffers
290 All,
291}
292
293impl From<ClearBuffer> for SerialClearBuffer {
294 fn from(buffer: ClearBuffer) -> Self {
295 match buffer {
296 ClearBuffer::Input => SerialClearBuffer::Input,
297 ClearBuffer::Output => SerialClearBuffer::Output,
298 ClearBuffer::All => SerialClearBuffer::All,
299 }
300 }
301}
302
303/// Logging level for controlling plugin verbosity
304///
305/// This enum allows you to control how much logging output the plugin produces.
306/// Use it to reduce noise in production environments or enable detailed logs for debugging.
307///
308/// # Example
309///
310/// ```rust
311/// use serialplugin_core::state::LogLevel;
312///
313/// let log_level = LogLevel::Error; // Only show errors
314/// ```
315#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
316pub enum LogLevel {
317 /// No logging output
318 None,
319 /// Only critical errors
320 Error,
321 /// Errors and warnings
322 Warn,
323 /// Errors, warnings, and general information
324 #[default]
325 Info,
326 /// All logging including debug information
327 Debug,
328}
329
330impl LogLevel {
331 /// Checks if error messages should be logged at the current level
332 pub fn should_log_error(&self) -> bool {
333 matches!(
334 self,
335 LogLevel::Error | LogLevel::Warn | LogLevel::Info | LogLevel::Debug
336 )
337 }
338
339 /// Checks if warning messages should be logged at the current level
340 pub fn should_log_warn(&self) -> bool {
341 matches!(self, LogLevel::Warn | LogLevel::Info | LogLevel::Debug)
342 }
343
344 /// Checks if info messages should be logged at the current level
345 pub fn should_log_info(&self) -> bool {
346 matches!(self, LogLevel::Info | LogLevel::Debug)
347 }
348
349 /// Checks if debug messages should be logged at the current level
350 pub fn should_log_debug(&self) -> bool {
351 matches!(self, LogLevel::Debug)
352 }
353}
354
355/// Global log level state
356static LOG_LEVEL: OnceLock<Mutex<LogLevel>> = OnceLock::new();
357
358/// Gets or initializes the log level mutex
359fn get_log_level_mutex() -> &'static Mutex<LogLevel> {
360 LOG_LEVEL.get_or_init(|| Mutex::new(LogLevel::Info))
361}
362
363/// Sets the global log level for the plugin
364///
365/// # Arguments
366///
367/// * `level` - The new log level to set
368///
369/// # Example
370///
371/// ```rust
372/// use serialplugin_core::state::{LogLevel, set_log_level};
373///
374/// set_log_level(LogLevel::Error);
375/// ```
376pub fn set_log_level(level: LogLevel) {
377 if let Ok(mut log_level) = get_log_level_mutex().lock() {
378 *log_level = level;
379 }
380}
381
382/// Gets the current global log level
383///
384/// # Returns
385///
386/// The current log level
387///
388/// # Example
389///
390/// ```rust
391/// use serialplugin_core::state::get_log_level;
392///
393/// let level = get_log_level();
394/// ```
395pub fn get_log_level() -> LogLevel {
396 *get_log_level_mutex().lock().unwrap_or_else(|e| {
397 eprintln!("Failed to lock log level: {}", e);
398 e.into_inner()
399 })
400}
401
402/// DTR / RTS levels to apply when a port is opened (`None` = platform default:
403/// unchanged on desktop, asserted on Android). Deasserting DTR keeps Arduino-style
404/// boards from resetting on open; on Linux the kernel still pulses DTR briefly.
405#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
406pub struct ModemLinesOnOpen {
407 pub dtr: Option<bool>,
408 pub rts: Option<bool>,
409}