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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use embassy_executor::Executor;
use embassy_time::{Duration, Timer};
use esp_println::println;
use hal::{
    clock::ClockControl,
    embassy,
    gpio::{Gpio7, Output, PushPull},
    interrupt,
    peripherals::{Interrupt, Peripherals, UART1},
    prelude::*,
    system::SystemParts,
    timer::TimerGroup,
    uart::{
        TxRxPins,
    },
    Priority, Rng, Rtc, Uart, IO,
};

use nmea::ParseResult;

/// The Rust ESP32-C3 board has onboard LED on GPIO 7
pub type OnboardLed = Gpio7<Output<PushPull>>;

static MOCK_SENTENCES: &'static str = include_str!("../../tests/nmea.log");

pub struct Application {
    // TODO: Uncomment when you create a `Uart` instance of the `UART1` peripheral
    uart: Uart<'static, UART1>,
    // TODO: Uncomment when you create a `Rng` instance
    rng: Rng<'static>,
    // TODO: Uncomment when you create the `OnboardLed` instance
    onboard_led: OnboardLed,
}

impl Application {
    /// Initialises all the peripherals which the [`Application`] will use.
    pub fn init(peripherals: Peripherals) -> Self {
        let system: SystemParts = peripherals.SYSTEM.split();
        let clocks = ClockControl::boot_defaults(system.clock_control).freeze();

        let mut rtc = Rtc::new(peripherals.RTC_CNTL);
        let mut peripheral_clock_control = system.peripheral_clock_control;
        let timer_group0 =
            TimerGroup::new(peripherals.TIMG0, &clocks, &mut peripheral_clock_control);
        let mut wdt0 = timer_group0.wdt;
        let timer_group1 =
            TimerGroup::new(peripherals.TIMG1, &clocks, &mut peripheral_clock_control);
        let mut wdt1 = timer_group1.wdt;

        // Disable watchdog timers
        rtc.swd.disable();
        rtc.rwdt.disable();
        wdt0.disable();
        wdt1.disable();

        #[cfg(feature = "embassy-time-systick")]
        embassy::init(&clocks, system_timer);

        #[cfg(feature = "embassy-time-timg0")]
        embassy::init(&clocks, timer_group0.timer0);

        // Setup peripherals for application
        let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);

        // Onboard LED
        // Rust ESP32-C3 schematics: https://raw.githubusercontent.com/esp-rs/esp-rust-board/master/assets/rust_board_v1_pin-layout.png
        // Set GPIO7 as an output, and set its state high initially.
        let mut onboard_led = io.pins.gpio7.into_push_pull_output();
        onboard_led.set_high().unwrap();

        // Setup Random Generator for GNSS Reading
        // Hal example: https://github.com/esp-rs/esp-hal/blob/main/esp32c3-hal/examples/rng.rs
        let rng = Rng::new(peripherals.RNG);
        // let rng = todo!("Initialize the Random generator");

        // The Rust ESP32-C3 board has debug UART on pins 21 (TX) and 20 (RX)
        // but you should use GPIO pins 0 (TX) and 1 (RX) for sending and receiving data respectively
        // to/from the `power-system` board.
        // TODO: Configure the UART 1 peripheral
        // let uart1 = todo!("Configure UART 1 at pins 0 (TX) and 1 (RX) with `None` or default for the `Config`");
        let uart1 = Uart::new_with_config(
            peripherals.UART1,
            None,
            Some(TxRxPins::new_tx_rx(
                io.pins.gpio0.into_floating_input(),
                io.pins.gpio1.into_push_pull_output(),
            )),
            &clocks,
            &mut peripheral_clock_control,
        );
        interrupt::enable(Interrupt::UART1, Priority::Priority1).unwrap();

        Self {
            uart: uart1,
            rng,
            onboard_led,
        }
    }

    /// Runs the application by spawning each of the [`Application`]'s tasks
    pub fn run(self, executor: &'static mut Executor) -> ! {
        executor.run(|spawner| {
            spawner.must_spawn(run_uart(self.uart));
            spawner.must_spawn(run_gnss(self.rng));
        })
    }
}

/// # Exercise: Parse GNSS data from NMEA 0183 sentences
///
/// This task parses NMEA sentences simulated from a GNSS data log file
/// The task picks random sentences from a log file and looks out for `GNS` and `GSV` messages
///
///
/// Print the ID's of satellites used for fix in GSA sentence and the satellites in view from the GSV sentence
///
/// `nmea` crate docs: <https://docs.rs/nmea>
///
/// 0. Add the `nmea` crate to the `Cargo.toml` of the `onboard-computer`
/// - You should exclude the `default-features` of the crate, as we operate in `no_std` environment
/// - Alternate solution: You can add the crate to the `workspace` dependencies of the project in the `Cargo.toml` of the project
///   For more details see: <https://doc.rust-lang.org/cargo/reference/workspaces.html#the-dependencies-table>
///
/// 1. Use the `nmea` crate to parse the sentences
/// 2. Print the parsing result (for debugging purposes) using `esp_println::println!()`
/// 3. Use a match on the result and handle the cases:
/// - GSA - print "The IDs of satellites used for fix: {x:?}" field
/// - GSV - print "Satellites in View: {x}" field
/// 4. Repeat this processes every 2 seconds.
#[embassy_executor::task]
async fn run_gnss(mut rng: Rng<'static>) {
    loop {
        let num = rng.random() as u8;
        let sentence = MOCK_SENTENCES.lines().nth(num as usize).unwrap();

        // println!("(debug) NMEA sentence at line: {num}: {sentence}");
        // 1. Use the `nmea` crate to parse the sentences
        // TODO: Uncomment line and finish the `todo!()`
        // let parse_result = todo!("call nmea::parse_str");
        let parse_result = nmea::parse_str(sentence);
        // 2. Print the parsing result (for debugging purposes) using `esp_println::println!()`
        // println!("{:?}", parse_result);
        // 3. Use a match on the result and handle the sentences:
        // - GSA
        // - GSV
        match parse_result {
            Ok(ParseResult::GSA(gsa_data)) => {
                println!("GSA: Fix satellites: {:?}", gsa_data.fix_sats_prn);
            }
            Ok(ParseResult::GSV(gsv_data)) => {
                println!("GSV: Satellites in view: {}", gsv_data._sats_in_view);
            }
            _ => {}
        }
        Timer::after(Duration::from_secs(2)).await;
    }
}

/// # Exercise: Receive battery percentage over UART from the power-system
///
/// 1. create an infinite loop that
/// 2. tries to read the Battery Percentage value sent from the Power System,
/// 3. prints the value on success or the error on failure (using Debug formatting),
/// 4. Repeat the read every 20 milliseconds
#[embassy_executor::task]
async fn run_uart(mut uart: Uart<'static, UART1>) {
    loop {
        match nb::block!(uart.read()) {
            Ok(battery_percentage) => {
                println!("Battery: {battery_percentage}%");
            }
            Err(err) => {
                println!("Error: {err:?}")
            }
        }
        Timer::after(Duration::from_millis(20)).await;
    }
}