ogn_parser/
lib.rs

1use ogn_parser::{AprsData, AprsPacket, ServerResponse};
2use pyo3::{
3    prelude::*,
4    types::{PyDict, PyList},
5};
6use pythonize::pythonize;
7use rayon::prelude::*;
8
9/// Parse an APRS packet from a string to a list of JSON strings: List[str]
10#[pyfunction]
11fn parse_serde_json(s: &str) -> PyResult<Vec<String>> {
12    let lines = s.lines().collect::<Vec<_>>();
13    let json_strings = lines
14        .par_iter()
15        .map(|&aprs_string| {
16            serde_json::to_string(&aprs_string.parse::<ServerResponse>().unwrap()).unwrap()
17        })
18        .collect();
19    Ok(json_strings)
20}
21
22/// Parse an APRS packet from a string to a Python object: List[Dict[str, Any]]
23#[pyfunction]
24fn parse_pythonize(py: Python, s: &str) -> PyResult<Py<PyAny>> {
25    let lines = s.lines().collect::<Vec<_>>();
26    let packets = lines
27        .par_iter()
28        .map(|&aprs_string| aprs_string.parse::<ServerResponse>().unwrap())
29        .collect::<Vec<_>>();
30    Ok(pythonize(py, &packets)?.into())
31}
32
33// Parse an APRS packet from a string to a Python dict: Dict[str, Any]
34#[pyfunction]
35fn parse_pyo3(py: Python, s: &str) -> PyResult<Py<PyList>> {
36    let lines = s.lines().collect::<Vec<_>>();
37    let packets = lines
38        .par_iter()
39        .map(|aprs_string| aprs_string.parse::<AprsPacket>().unwrap())
40        .collect::<Vec<AprsPacket>>();
41    let dicts = PyList::empty(py);
42    for packet in packets {
43        let dict = PyDict::new(py);
44        dict.set_item("raw_string", s).unwrap();
45        match packet.data {
46            AprsData::Position(ref pos) => {
47                dict.set_item("latitude", *pos.latitude).unwrap();
48                dict.set_item("longitude", *pos.longitude).unwrap();
49            }
50            AprsData::Status(ref _status) => {}
51            _ => {}
52        };
53        dicts.append(dict).unwrap();
54    }
55
56    Ok(dicts.into())
57}
58
59/// A Python module implemented in Rust.
60#[pymodule(name = "ogn_parser")]
61fn python_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
62    m.add_function(wrap_pyfunction!(parse_serde_json, m)?)?;
63    m.add_function(wrap_pyfunction!(parse_pythonize, m)?)?;
64    m.add_function(wrap_pyfunction!(parse_pyo3, m)?)?;
65    Ok(())
66}