use embedded_shadow::prelude::*;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
type MyStorage = ShadowStorage<256, 32, 8, AllowAllPolicy, NoPersistPolicy, NoPersist, ()>;
static mut STORAGE: Option<MyStorage> = None;
static STORAGE_READY: AtomicBool = AtomicBool::new(false);
static INTERRUPT_PENDING: AtomicBool = AtomicBool::new(false);
fn main() {
println!("=== Critical Section Example ===\n");
unsafe {
STORAGE = Some(
ShadowStorageBuilder::new()
.total_size::<256>()
.block_size::<32>()
.block_count::<8>()
.default_access()
.no_persist()
.build(),
);
STORAGE_READY.store(true, Ordering::Release);
}
let isr_thread = thread::spawn(|| {
while !STORAGE_READY.load(Ordering::Acquire) {
thread::yield_now();
}
println!("ISR simulator: Started");
for _ in 0..20 {
if INTERRUPT_PENDING.load(Ordering::Acquire) {
handle_interrupt();
INTERRUPT_PENDING.store(false, Ordering::Release);
}
thread::sleep(Duration::from_millis(50));
}
println!("ISR simulator: Stopped");
});
println!("Main loop: Starting\n");
let host = unsafe {
let storage = &raw const STORAGE;
(*storage).as_ref().unwrap().host_shadow()
};
for cycle in 0..5 {
println!("Main loop: Cycle {cycle}");
host.with_view(|view| {
let addr = (cycle * 32) as u16;
let data = vec![cycle as u8 + 0x10; 16];
println!(" Writing {} bytes to 0x{:04X}", data.len(), addr);
view.write_range(addr, &data).unwrap();
});
INTERRUPT_PENDING.store(true, Ordering::Release);
thread::sleep(Duration::from_millis(200));
}
isr_thread.join().unwrap();
println!("\nMain loop: Complete - all operations succeeded");
}
fn handle_interrupt() {
println!("\n>>> ISR: Handling interrupt");
let kernel = unsafe {
let storage = &raw const STORAGE;
(*storage).as_ref().unwrap().kernel_shadow()
};
unsafe {
kernel.with_view_unchecked(|view| {
let mut dirty_found = false;
for block in 0..8 {
let addr = (block * 32) as u16;
if view.is_dirty(addr, 32).unwrap() {
dirty_found = true;
let mut buffer = [0u8; 32];
view.read_range(addr, &mut buffer).unwrap();
println!(
" Block {}: Dirty - first 8 bytes: {:02X?}",
block,
&buffer[0..8]
);
}
}
if dirty_found {
view.clear_dirty();
println!(" Cleared dirty flags");
} else {
println!(" No dirty blocks");
}
});
}
println!("<<< ISR: Complete\n");
}
#[cfg(test)]
mod tests {
#[test]
fn test_critical_section_example() {
super::main();
}
}