Skip to content
Snippets Groups Projects
Commit 9b4b41f8 authored by Samuel Tardieu's avatar Samuel Tardieu
Browse files

Pass state as an opaque value to I²C callback

parent 65fddca3
No related branches found
No related tags found
No related merge requests found
......@@ -22,8 +22,6 @@ impl State {
}
}
static mut STATE: Option<State> = None;
#[allow(clippy::needless_pass_by_value, clippy::used_underscore_binding)] // Clippy bug
pub fn start_i2c_target(
spawner: Spawner,
......@@ -32,22 +30,19 @@ pub fn start_i2c_target(
encoders: Encoders<'static>,
_wwdg: WWDG,
) {
unsafe {
STATE = Some(State::new(i2c2, encoders));
}
spawner.spawn(i2c_engine()).unwrap();
spawner.spawn(i2c_engine(i2c2, encoders)).unwrap();
spawner.spawn(watchdog::watchdog()).unwrap();
spawner.spawn(motor_control::motor_control(motors)).unwrap();
}
#[embassy_executor::task]
async fn i2c_engine() {
I2C2::start(&i2c_callback).await;
async fn i2c_engine(i2c2: I2C2, encoders: Encoders<'static>) {
let state = State::new(i2c2, encoders);
I2C2::start(&i2c_callback, state).await;
}
fn i2c_callback(command: &[u8], response: &mut Vec<u8, MESSAGE_SIZE>) {
fn i2c_callback(command: &[u8], response: &mut Vec<u8, MESSAGE_SIZE>, state: &mut State) {
#[allow(static_mut_refs)]
let state = unsafe { STATE.as_mut().unwrap() };
if process_command(state, command, response) {
watchdog::ping();
} else {
......
......@@ -12,7 +12,7 @@ use heapless::Vec;
pub const MESSAGE_SIZE: usize = 8;
pub type Callback = &'static dyn Fn(&[u8], &mut Vec<u8, MESSAGE_SIZE>);
pub type Callback<State> = &'static dyn Fn(&[u8], &mut Vec<u8, MESSAGE_SIZE>, &mut State);
struct Format(Sr1);
......@@ -89,7 +89,7 @@ impl I2C2 {
}
/// Start answering I²C requests using the provided callback.
pub async fn start(callback: Callback) {
pub async fn start<State>(callback: Callback<State>, mut state: State) {
let mut incoming = [0u8; MESSAGE_SIZE];
let mut outgoing: Vec<u8, MESSAGE_SIZE> = Vec::new();
unsafe {
......@@ -110,7 +110,7 @@ impl I2C2 {
let r = i2c_receive(&mut incoming).await;
outgoing.clear();
match r {
Ok(incoming) => callback(incoming, &mut outgoing),
Ok(incoming) => callback(incoming, &mut outgoing, &mut state),
Err(e) => {
defmt::warn!("error while receiving: {}", e);
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment