aboutsummaryrefslogtreecommitdiffstats
path: root/src/radio.rs
blob: 1a917be7bd0c629c58c8e99354aff3ae2abc44df (plain)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use anyhow::{anyhow, bail, Context};
use rand::{thread_rng, Rng};
use rf4463::{config::RADIO_CONFIG_CATS, Rf4463};
use rppal::{
    gpio::{Gpio, OutputPin},
    hal::Delay,
    spi::{Bus, Mode, SlaveSelect, Spi},
};
use std::{
    sync::Arc,
    time::{Duration, Instant},
};
use tokio::sync::{
    mpsc::{error::TryRecvError, Receiver, Sender},
    Mutex,
};

pub const MAX_PACKET_LEN: usize = 8191;

pub struct RadioManager {
    radio: Rf4463<Spi, OutputPin, OutputPin, Delay>,

    receive_queue: Sender<(Vec<u8>, f64)>,
    transmit_queue: Receiver<Vec<u8>>,
    rx_buf: [u8; MAX_PACKET_LEN],
    temperature: Arc<Mutex<f32>>,
}

impl RadioManager {
    pub fn new(receive_queue: Sender<(Vec<u8>, f64)>, transmit_queue: Receiver<Vec<u8>>) -> anyhow::Result<Self> {
        let spi = Spi::new(Bus::Spi0, SlaveSelect::Ss0, 1_000_000, Mode::Mode0)?;
        let gpio = Gpio::new()?;
        let sdn = gpio.get(22)?.into_output();
        let cs = gpio.get(24)?.into_output();

        let delay = Delay::new();

        let mut radio = Rf4463::new(spi, sdn, cs, delay, &mut RADIO_CONFIG_CATS.clone())
            .map_err(|e| anyhow!("{e:?}"))?;
        radio.set_channel(20);

        let rx_buf = [0; MAX_PACKET_LEN];
        let temperature = Arc::new(Mutex::new(radio.get_temp()?));

        Ok(Self {
            radio,
            receive_queue,
            transmit_queue,
            rx_buf,
            temperature,
        })
    }

    pub fn set_channel(&mut self, channel: u8) {
        self.radio.set_channel(channel);
    }

    #[allow(dead_code)]
    pub fn temperature_mutex(&self) -> Arc<Mutex<f32>> {
        self.temperature.clone()
    }

    pub async fn process_forever(&mut self) -> anyhow::Result<()> {
        loop {
            self.tick().await?;

            *self.temperature.lock().await = self.radio.get_temp()?;

            match self.transmit_queue.try_recv() {
                Ok(pkt) => {
                    self.tx(&pkt).await?;
                }
                Err(TryRecvError::Empty) => {}
                Err(TryRecvError::Disconnected) => {
                    bail!("TX channel disconnected")
                }
            }

            tokio::time::sleep(Duration::from_millis(25)).await;
        }
    }

    async fn tick(&mut self) -> anyhow::Result<()> {
        if self.radio.is_idle() {
            self.radio
                .start_rx(None, false)
                .map_err(|e| anyhow!("{e}"))?;

            tokio::time::sleep(Duration::from_millis(25)).await;
        }

        self.radio
            .interrupt(Some(&mut self.rx_buf), None)
            .map_err(|e| anyhow!("{e:?}"))?;

        if let Some(data) = self
            .radio
            .finish_rx(&mut self.rx_buf)
            .map_err(|e| anyhow!("{e}"))?
        {
            self.radio
                .start_rx(None, false)
                .map_err(|e| anyhow!("{e}"))?;

            self.receive_queue
                .send((data.data().to_vec(), data.rssi()))
                .await
                .ok()
                .context("RX channel died")?;
        }

        Ok(())
    }

    async fn tx(&mut self, data: &[u8]) -> anyhow::Result<()> {
        // ensures we don't tx over a packet,
        // and adds some random delay so that every node
        // if offset slightly
        self.tx_delay().await?;

        self.radio.start_tx(data).map_err(|e| anyhow!("{e:?}"))?;

        const TIMEOUT: Duration = Duration::from_secs(10);
        let start_time = Instant::now();
        while !self.radio.is_idle() {
            self.radio
                .interrupt(None, Some(data))
                .map_err(|e| anyhow!("{e:?}"))?;

            if start_time + TIMEOUT < Instant::now() {
                bail!("Timeout while transmitting");
            }

            tokio::time::sleep(Duration::from_millis(25)).await;
        }

        Ok(())
    }

    async fn tx_delay(&mut self) -> anyhow::Result<()> {
        loop {
            let delay_ms = thread_rng().gen_range(0..50);

            // since delay_ms < 100 we can safely sleep without calling tick
            tokio::time::sleep(Duration::from_millis(delay_ms)).await;

            let mut rx = false;

            while self.radio.is_busy_rxing()? {
                rx = true;
                self.tick().await?;

                tokio::time::sleep(Duration::from_millis(25)).await;
            }

            if !rx {
                // didn't rx a packet, so we're safe to leave
                break Ok(());
            }
        }
    }
}