Skip to main content

vuquest_3320/command/
qr.rs

1use crate::result::{Error, Result};
2
3const DEFAULT_SETTINGS: &str = "QRCDFT";
4const QR_OFF: &str = "QRCENA0";
5const QR_ON: &str = "QRCENA1";
6
7/// Represents the `Mobile Phone Read Mode` serial command.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum QRCode {
10    DefaultSettings,
11    Off,
12    On,
13}
14
15impl QRCode {
16    /// Creates a new [QRCode].
17    pub const fn new() -> Self {
18        Self::On
19    }
20
21    /// Gets the ASCII serial command code for [QRCode].
22    pub const fn command(&self) -> &str {
23        match self {
24            Self::DefaultSettings => DEFAULT_SETTINGS,
25            Self::Off => QR_OFF,
26            Self::On => QR_ON,
27        }
28    }
29}
30
31impl Default for QRCode {
32    fn default() -> Self {
33        Self::new()
34    }
35}
36
37impl TryFrom<&str> for QRCode {
38    type Error = Error;
39
40    fn try_from(val: &str) -> Result<Self> {
41        match val {
42            v if v.contains(DEFAULT_SETTINGS) => Ok(Self::DefaultSettings),
43            v if v.contains(QR_ON) => Ok(Self::On),
44            v if v.contains(QR_OFF) => Ok(Self::Off),
45            _ => Err(Error::InvalidVariant),
46        }
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn test_valid() {
56        [QRCode::DefaultSettings, QRCode::Off, QRCode::On]
57            .into_iter()
58            .zip([DEFAULT_SETTINGS, QR_OFF, QR_ON])
59            .for_each(|(cmd, exp_ascii_cmd)| {
60                assert_eq!(cmd.command(), exp_ascii_cmd);
61                assert_eq!(QRCode::try_from(exp_ascii_cmd), Ok(cmd));
62            });
63    }
64}