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
//! RSS “Received Signal Strength"

use crate::ParseError;

/// Represents a RSS “Received Signal Strength" message type.
#[derive(Clone, Debug, PartialEq)]
pub enum RssType {
    /// Frequency message `SS,1,NNN<CR>`.
    Frequency(),
    /// Alert message `SS,A,NNN<CR>`.
    Alert(),
}

/// Represents a RSS “Received Signal Strength" message.
#[derive(Clone, Debug, PartialEq)]
pub struct Rss {
    /// Message type (see [`RssType`]).
    pub rss_type: RssType,

    /// NNN - Value between 0 and 255. This value is not calibrated, but is approximately `-130 + (NNN / 2)` dBm
    pub nnn: u8,
}

impl Rss {
    /// Returns whether `message` is a valid RSS message.
    ///
    /// ## Examples
    /// ```
    /// use wte_mt_rx_parser::rss::Rss;
    /// println!("is it rss? {}", Rss::is_rss("SS,A,123"));
    /// ```
    pub fn is_rss(message: &str) -> bool {
        return message.starts_with("SS,");
    }

    /// Tries to parse a RSS `message`.
    ///
    /// ## Examples
    /// ```
    /// use wte_mt_rx_parser::rss::Rss;
    /// let parsed = Rss::parse("SS,A,123").unwrap();
    /// println!("parsed: {:?}", parsed);
    /// ```
    ///
    /// ## Data
    /// Data provided should be in the following format:
    /// - `SS,X,NNN<CR>` where `X` can be `A` (alerts) or `1` (frequency)
    pub fn parse(message: &str) -> Result<Rss, ParseError> {
        // 01 2 3 4 567
        // SS , X , NNN

        const RSS_LEN: usize = 8;
        if message.len() != RSS_LEN {
            return Err(ParseError::SizeNotMatch {
                expected: RSS_LEN,
                found: message.len(),
            });
        }

        let x = message.as_bytes()[3];
        let nnn = message[5..8].parse::<u8>()?;

        match x {
            b'A' => Ok(Rss {
                nnn,
                rss_type: RssType::Alert(),
            }),
            b'1' => Ok(Rss {
                nnn,
                rss_type: RssType::Frequency(),
            }),
            _ => Err(ParseError::Invalid()),
        }
    }
}