Skip to main content

vuquest_3320/command/
trigger.rs

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