Skip to main content

aprs_decode/
query.rs

1/// An APRS General Query packet.
2///
3/// DTI: `?`
4///
5/// Format: `?TYPE?` or `?TYPE?lat,lon,radius` (with optional geographic footprint).
6///
7/// Common query types: `APRS`, `IGATE`, `WX`, `VERSION`, `STATUS`.
8#[derive(Debug, Clone, PartialEq)]
9#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10pub struct AprsQuery {
11    /// The query type (between the two `?` characters).
12    pub query_type: Vec<u8>,
13    /// Optional geographic footprint: (latitude°, longitude°, radius km).
14    pub footprint: Option<QueryFootprint>,
15    /// Any trailing bytes after the footprint (preserved verbatim).
16    pub trailing: Vec<u8>,
17}
18
19/// A geographic footprint associated with a query.
20#[derive(Debug, Clone, PartialEq)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub struct QueryFootprint {
23    pub latitude: f64,
24    pub longitude: f64,
25    pub radius_km: f32,
26}
27
28impl AprsQuery {
29    /// Decode from the information field (including the leading `?` DTI byte).
30    pub(crate) fn parse(info: &[u8]) -> Self {
31        // Format: ?TYPE?[lat,lon,radius]
32        // The first `?` is the DTI; the second `?` ends the type token.
33        let body = info.get(1..).unwrap_or_default();
34
35        let second_q = body.iter().position(|&b| b == b'?');
36        let (query_type, after_type) = match second_q {
37            Some(pos) => (body[..pos].to_vec(), body.get(pos + 1..).unwrap_or_default()),
38            None => (body.to_vec(), &b""[..]),
39        };
40
41        let (footprint, trailing) = parse_footprint(after_type);
42
43        Self { query_type, footprint, trailing }
44    }
45
46    pub fn encode(&self) -> Vec<u8> {
47        let mut out = vec![b'?'];
48        out.extend_from_slice(&self.query_type);
49        out.push(b'?');
50        if let Some(ref fp) = self.footprint {
51            out.extend_from_slice(format!("{},{},{}", fp.latitude, fp.longitude, fp.radius_km).as_bytes());
52        }
53        out.extend_from_slice(&self.trailing);
54        out
55    }
56}
57
58fn parse_footprint(b: &[u8]) -> (Option<QueryFootprint>, Vec<u8>) {
59    if b.is_empty() {
60        return (None, vec![]);
61    }
62    let parts: Vec<&[u8]> = b.splitn(4, |&c| c == b',').collect();
63    if parts.len() >= 3 {
64        let lat = parse_f64(parts[0]);
65        let lon = parse_f64(parts[1]);
66        let radius = parse_f32(parts[2]);
67        if let (Some(lat), Some(lon), Some(radius)) = (lat, lon, radius) {
68            let trailing = parts.get(3).map(|p| p.to_vec()).unwrap_or_default();
69            return (Some(QueryFootprint { latitude: lat, longitude: lon, radius_km: radius }), trailing);
70        }
71    }
72    (None, b.to_vec())
73}
74
75fn parse_f64(b: &[u8]) -> Option<f64> {
76    std::str::from_utf8(b).ok()?.trim().parse().ok()
77}
78
79fn parse_f32(b: &[u8]) -> Option<f32> {
80    std::str::from_utf8(b).ok()?.trim().parse().ok()
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    #[test]
88    fn simple_aprs_query() {
89        let q = AprsQuery::parse(b"?APRS?");
90        assert_eq!(q.query_type, b"APRS");
91        assert!(q.footprint.is_none());
92    }
93
94    #[test]
95    fn query_with_footprint() {
96        let q = AprsQuery::parse(b"?APRS?49.0,-72.0,10");
97        assert_eq!(q.query_type, b"APRS");
98        let fp = q.footprint.unwrap();
99        assert!((fp.latitude - 49.0).abs() < 0.01);
100        assert!((fp.longitude - -72.0).abs() < 0.01);
101        assert!((fp.radius_km - 10.0).abs() < 0.01);
102    }
103
104    #[test]
105    fn no_second_question_mark() {
106        // Some implementations omit the second `?`
107        let q = AprsQuery::parse(b"?APRS");
108        assert_eq!(q.query_type, b"APRS");
109    }
110
111    #[test]
112    fn encode_round_trip() {
113        let raw = b"?IGATE?";
114        let q = AprsQuery::parse(raw);
115        assert_eq!(q.encode().as_slice(), raw.as_slice());
116    }
117}