I'm trying to develop a web backend + embedded controller, but I'm having difficulty controlling global variables. When starting an application, declare a global variable or a list (containing objects) and call the web API to access the global variable and change the contents of the variable or look up the variable.
I started with the two approaches below.
Use : lazy_static + Mutex
lazy_static! { pub static ref ROBOT_LIST: Mutex<Vec<Robot>> = Mutex::new(vec![ Robot {id: 1, name: String::from("robot1"), pos_x: 1, pos_y: 1, speed: 0, direction: 0} ] ); }Use : OnceLock
static mut ROBOT_LIST: OnceLock<Vec<Robot>> = OnceLock::new();
But neither works well. When api call data not changes or async api doesn't work anything (cant debug also...)
Below is pseudo code what I want to implemented
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Robot {
pub id: usize,
pub name: String,
pub pos_x: i32,
pub pos_y: i32,
pub speed: i32,
pub direction: i32,
}
lazy_static! {
pub static ref ROBOT_LIST: Mutex<Vec<Robot>> = Mutex::new(vec![
Robot {id: 1, name: String::from("robot1"), pos_x: 1, pos_y: 1, speed: 0, direction: 0}
]
);
}
API 1: start sim-controller for attacking Object
pub fn sim(){
actix_rt::spawn(async move {
unsafe{
let mut robot_now = ROBOT_LIST.lock().unwrap();
let mut robot1: &mut Robot = &mut robot_now.get_mut(0).unwrap();
loop {
sleep(Duration::new(1, 0)).await;
if robot1.direction == 0 {
println!("x pos : {}, y pos {}", robot1.pos_x, robot1.pos_y);
continue;
} else if robot1.direction == 1 {
//x-axis
robot1.pos_x += robot1.speed;
} else if robot1.direction == 2 {
//y-axis
robot1.pos_y += robot1.speed;
}
println!("x pos : {}, y pos {}", robot1.pos_x, robot1.pos_y);
}
}
});
}
API 2: Order to move Object
pub fn move_robot(){
unsafe{
let mut robot_now = ROBOT_LIST.lock().unwrap();
let mut robot1: &mut Robot = robot_now.get_mut(0).unwrap();
robot1.speed = -1;
//0 : stop
//1 : x-axis
//2 : y-axis
robot1.direction = 1;
}
}
Please recommend a method that does not cause problems when accessing global variables in the above manner or please recommend a way to control global variables in Rust reliably and without problems.
Embedded controllers were implemented without problems in higher-level languages such as Python.