From 638545de6d0daf913ce7441f4a9c9ac3048f179b Mon Sep 17 00:00:00 2001 From: rhetenor Date: Thu, 3 Sep 2026 13:36:12 +0200 Subject: [PATCH] wip --- Cargo.lock | 26 +++++- Cargo.toml | 1 + partitions.csv | 9 +- src/background_tasks/nfc.rs | 3 +- src/bin/main.rs | 15 ++-- src/lib.rs | 5 ++ src/navigation/navigation.rs | 4 +- src/network/wifi.rs | 82 ++++++++++++++---- src/peripherals.rs | 2 +- src/peripherals/storage/flash_store.rs | 112 ------------------------- wokwi.toml | 9 +- 11 files changed, 111 insertions(+), 157 deletions(-) delete mode 100644 src/peripherals/storage/flash_store.rs diff --git a/Cargo.lock b/Cargo.lock index 0c347ec..e51b395 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -359,6 +359,7 @@ dependencies = [ "embedded-storage", "embedded-text", "esp-alloc", + "esp-backtrace", "esp-bootloader-esp-idf", "esp-hal", "esp-hal-wifimanager", @@ -1099,6 +1100,23 @@ dependencies = [ "rlsf", ] +[[package]] +name = "esp-backtrace" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37950e24b2dfd98f1581102d1798281d4d9547af881e6bffc2c2b534c026ec8f" +dependencies = [ + "cfg-if", + "document-features", + "esp-config", + "esp-metadata-generated", + "esp-println", + "heapless 0.9.3", + "riscv", + "semihosting", + "xtensa-lx", +] + [[package]] name = "esp-bootloader-esp-idf" version = "0.5.0" @@ -1231,7 +1249,7 @@ dependencies = [ [[package]] name = "esp-hal-wifimanager" version = "0.3.1" -source = "git+https://github.com/rhetenor/esp-hal-wifimanager.git#c35c2b35c9c4b724138f2c62a8aed9adf6365a7f" +source = "git+https://github.com/rhetenor/esp-hal-wifimanager.git#c1a7c80e870070c74c1f116b4cae5df29c597537" dependencies = [ "embassy-executor", "embassy-futures", @@ -3026,6 +3044,12 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" +[[package]] +name = "semihosting" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8e4abf97879f4e80db69a9fba7bd64998e9bdad25f58ef045a778e191172fd4" + [[package]] name = "seq-macro" version = "0.3.6" diff --git a/Cargo.toml b/Cargo.toml index c9686e4..81dab7b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,6 +56,7 @@ binary_serde = "1.0.25" static_assertions = { version = "1.1.0", default-features = false } embedded-text = "0.7.3" esp-nvs = { version = "0.5.0", features = ["esp32s3"] } +esp-backtrace = { version = "0.19.0", features = ["esp32s3", "panic-handler", "println"] } [build-dependencies] log = "0.4.27" diff --git a/partitions.csv b/partitions.csv index c3b956e..8fff563 100644 --- a/partitions.csv +++ b/partitions.csv @@ -1,9 +1,4 @@ # ESP-IDF Partition Table # Name,Type,SubType,Offset,Size,Flags -nvs,data,nvs,0x9000,0x6000, -phy_init,data,phy,0xf000,0x1000, -# We keep the default layout more or less. But here we add a partition for more data before our application -more_nvs,data,nvs,0x10000,0xfa000, -# no offset given -> tool infers it for us -factory,app,factory, ,0xea6000, - +nvs,data,nvs,0x9000,0xa00000, +factory,app,factory,0xa10000,0x200000, diff --git a/src/background_tasks/nfc.rs b/src/background_tasks/nfc.rs index 155a382..5d32c48 100644 --- a/src/background_tasks/nfc.rs +++ b/src/background_tasks/nfc.rs @@ -1,6 +1,7 @@ use crate::navigation::navigation::display_error; use crate::{ - navigation::{navigation::Mutex, outputs::Outputs, state::NavigationState}, + Mutex, + navigation::{outputs::Outputs, state::NavigationState}, peripherals::Peripherals, }; use alloc::string::ToString; diff --git a/src/bin/main.rs b/src/bin/main.rs index bd57423..530ef94 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -9,6 +9,7 @@ use alloc::boxed::Box; use alloc::sync::Arc; +use creaturedex::Mutex; use creaturedex::background_tasks; use creaturedex::drivers::i2c_bus::I2cBusPinConfiguration; use creaturedex::drivers::nfc_pn532::NfcPn532Driver; @@ -19,7 +20,6 @@ use creaturedex::drivers::tertiary_lcd::{ BOX, EMPTY, EXAMPLE, HEART, TertiaryDisplay, TertiaryDisplayPinConfiguration, }; use creaturedex::navigation::inputs::Inputs; -use creaturedex::navigation::navigation::Mutex; use creaturedex::navigation::navigation::{self}; use creaturedex::navigation::outputs::Outputs; use creaturedex::navigation::state::NavigationState; @@ -40,20 +40,15 @@ use esp_hal::gpio::{Input, InputConfig, Pull}; use esp_hal::timer::timg::TimerGroup; use log::error; +use esp_backtrace as _; use esp_hal::rtc_cntl::Rtc; -#[panic_handler] -fn panic(panic_info: &core::panic::PanicInfo) -> ! { - error!("{}", panic_info); - loop {} -} - extern crate alloc; const HEAP_SIZE: usize = 73744; -const NVS_PARTITION_OFFSET: usize = 0x10000; -const NVS_PARTITION_SIZE: usize = 0xfa000; +const NVS_PARTITION_OFFSET: usize = 0x9000; +const NVS_PARTITION_SIZE: usize = 0xa0000; // This creates a default app-descriptor required by the esp-idf bootloader. // For more information see: @@ -133,7 +128,7 @@ async fn main(spawner: Spawner) { .expect("failed to create nvs"), )); - setup_wifi(esp_peripherals.WIFI, Arc::clone(&nvs), &spawner).await; + //setup_wifi(esp_peripherals.WIFI, Arc::clone(&nvs), &spawner).await; let card_store = CardStore::new(nvs) .await diff --git a/src/lib.rs b/src/lib.rs index 93384ea..ee1ac5e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,8 @@ #![no_std] #![feature(vec_into_chunks)] +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; + extern crate alloc; pub mod background_tasks; @@ -13,6 +15,9 @@ pub mod network; pub mod peripherals; pub mod views; +pub type Mutex = embassy_sync::mutex::Mutex; +pub type Signal = embassy_sync::signal::Signal; + #[unsafe(no_mangle)] pub extern "Rust" fn _embassy_trace_poll_start(executor_id: u32) {} diff --git a/src/navigation/navigation.rs b/src/navigation/navigation.rs index 583719f..d3c2e79 100644 --- a/src/navigation/navigation.rs +++ b/src/navigation/navigation.rs @@ -1,3 +1,4 @@ +use crate::Mutex; use crate::card::model::Card; use crate::navigation::inputs::ButtonAction; use crate::navigation::inputs::Inputs; @@ -12,11 +13,8 @@ use alloc::string::ToString; use core::error; use embassy_futures::select::{Either, select}; -use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_time::{Duration, Timer}; -pub type Mutex = embassy_sync::mutex::Mutex; -pub type Signal = embassy_sync::signal::Signal; pub static CARD_DATA: Mutex> = Mutex::new(None); const DEBOUNCE_DURATION_MILLIS: u64 = 100; diff --git a/src/network/wifi.rs b/src/network/wifi.rs index 205f457..db9a866 100644 --- a/src/network/wifi.rs +++ b/src/network/wifi.rs @@ -1,33 +1,80 @@ -use crate::navigation::navigation::Mutex; +use crate::Signal; +use crate::alloc::string::ToString; use crate::peripherals::storage::Nvs; +use alloc::string::String; use alloc::sync::Arc; +use core::error::Error; +use core::fmt::Display; use embassy_executor::Spawner; +use esp_nvs::Key; + +struct WifiCredentials { + ssid: String, + pass: String, +} + +pub static WIFI_CREDENTIALS: Signal = Signal::new(); + +const WIFI_NAMESPACE: Key = Key::from_str("WIFI"); +const WIFI_INIT_KEY: Key = Key::from_str("INIT"); +const WIFI_SSID_KEY: Key = Key::from_str("SSID"); +const WIFI_PASSWORD_KEY: Key = Key::from_str("PASSWORD"); + +#[derive(Debug)] +pub enum WifiError { + Store(esp_nvs::error::Error), + NoEntry(u32), +} + +impl Error for WifiError {} + +impl Display for WifiError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + WifiError::Store(e) => e.fmt(f), + WifiError::NoEntry(uuid) => write!(f, "No Card Entry\nuuid: 0x{uuid:x}"), + } + } +} + +impl From for WifiError { + fn from(error: esp_nvs::error::Error) -> WifiError { + WifiError::Store(error) + } +} #[cfg(not(feature = "wokwi"))] pub async fn setup_wifi( wifi: esp_hal::peripherals::WIFI<'static>, nvs: Arc>, spawner: &Spawner, -) { - let espnvs = esp_hal_wifimanager::Nvs::new_from_nvs(nvs, 0, 0); +) -> Result<(), WifiError> { + nvs.lock() + .await + .set::(&WIFI_NAMESPACE, &WIFI_INIT_KEY, true)?; - let mut wm_settings = esp_hal_wifimanager::WmSettings::default(); + let wifi_ssid = match option_env!("WIFI_SSID") { + Some(ssid) => ssid.to_string(), - wm_settings.ssid.clear(); - _ = core::fmt::write( - &mut wm_settings.ssid, - format_args!("CreatureDex-{:X}", esp_hal_wifimanager::get_efuse_mac()), - ); - - wm_settings.wifi_conn_timeout = 30000; - wm_settings.esp_reset_timeout = Some(300000); // 5min - - let wifi_res = - esp_hal_wifimanager::init_wm(wm_settings, spawner, Some(&espnvs), wifi, None).await; - - log::info!("wifi_res: {wifi_res:?}"); + None => match nvs + .lock() + .await + .get::(&WIFI_NAMESPACE, &WIFI_SSID_KEY) + { + Ok(ssid) => ssid, + Err(esp_nvs::error::Error::KeyNotFound) => "asdf".to_string(), + Err(err) => return Err(err.into()), + }, + }; + Ok(()) } +pub async fn wait_for_wifi_credentials() { + log::info!("Waiting for new WiFi credentials"); + WIFI_CREDENTIALS.wait().await; + log::info!("Received new WiFi credentials. Saving..."); + log::info!("Saved new WiFi credentials. Restarting WiFi"); +} #[cfg(feature = "wokwi")] pub async fn setup_wifi( wifi: esp_hal::peripherals::WIFI<'static>, @@ -36,7 +83,6 @@ pub async fn setup_wifi( ) { log::info!("Wokwi mode active: pre-seeding WiFi Manager with Wokwi credentials"); - use esp_nvs::Key; const WIFIMANAGER_NAMESPACE: Key = Key::from_str("wifimanager"); const WIFIMANAGER_NVS_KEY: Key = Key::from_str("WIFI_SETUP"); diff --git a/src/peripherals.rs b/src/peripherals.rs index 281d318..0ead101 100644 --- a/src/peripherals.rs +++ b/src/peripherals.rs @@ -1,6 +1,6 @@ pub mod storage; -use crate::navigation::navigation::Mutex; +use crate::Mutex; use crate::peripherals::storage::store::Store; use esp_hal::rtc_cntl::Rtc; diff --git a/src/peripherals/storage/flash_store.rs b/src/peripherals/storage/flash_store.rs deleted file mode 100644 index 60ed958..0000000 --- a/src/peripherals/storage/flash_store.rs +++ /dev/null @@ -1,112 +0,0 @@ -use core::error::Error; -use core::fmt::Display; - -use crate::navigation::navigation::Mutex; -use embedded_storage::nor_flash::NorFlash; -use embedded_storage::nor_flash::ReadNorFlash; -use esp_storage::{FlashStorage, FlashStorageError}; - -use crate::peripherals::storage::MAGIC_REGION; - -#[derive(Debug)] -pub struct FlashStoreError(FlashStorageError); - -impl From for FlashStoreError { - fn from(value: FlashStorageError) -> Self { - Self(value) - } -} - -impl Error for FlashStoreError {} - -impl Display for FlashStoreError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "FlashStoreError:\n{:?}", self.0) - } -} - -const FLASH_ADDR: u32 = 0x200000; - -const INITIALIZATION_SIZE: usize = 0x1000; -const FLASH_INITIALIZE_MAGIC: u32 = 0xde6de6de; - -pub struct FlashStore { - pub storage: Mutex>, -} - -impl FlashStore { - pub fn new(flash: esp_hal::peripherals::FLASH<'static>) -> Result { - let mut storage = FlashStorage::new(flash); - - let mut magic: [u8; 4] = [0, 0, 0, 0]; - storage.read(FLASH_ADDR + MAGIC_REGION.offset, &mut magic)?; - log::debug!("Magic bytes are {magic:?}"); - - if Self::has_magic_bytes(&mut storage)? { - log::info!("Skipped flash initialization, magic bytes already present."); - } else { - log::info!("Initializing flash because no magic bytes found."); - Self::initialize_flash(&mut storage)?; - } - - Ok(Self { - storage: Mutex::new(storage), - }) - } - - pub async fn read(&self, offset: u32, bytes: &mut [u8]) -> Result<(), FlashStoreError> { - self.storage.lock().await.read(FLASH_ADDR + offset, bytes)?; - Ok(()) - } - - pub async fn write(&self, offset: u32, bytes: &mut [u8]) -> Result<(), FlashStoreError> { - log::debug!("Writing {} bytes at offset 0x{offset:08x}", bytes.len()); - self.storage - .lock() - .await - .write(FLASH_ADDR + offset, bytes)?; - Ok(()) - } - - pub async fn write_erase(&self, offset: u32, bytes: &mut [u8]) -> Result<(), FlashStoreError> { - log::debug!( - "Erasing and Writing {} bytes at offset 0x{offset:08x}", - bytes.len() - ); - let mut lock = self.storage.lock().await; - let addr = FLASH_ADDR + offset; - let to = FLASH_ADDR + offset + bytes.len() as u32; - log::debug!("Erasing from 0x{addr:x} to 0x{to:x}"); - //lock.erase(addr, to)?; - - log::debug!("Writing bytes..."); - lock.write(addr, bytes)?; - Ok(()) - } - - pub fn has_magic_bytes(storage: &mut FlashStorage) -> Result { - let mut magic: [u8; 4] = [0, 0, 0, 0]; - storage.read(FLASH_ADDR + MAGIC_REGION.offset, &mut magic)?; - log::debug!("Magic bytes are {magic:?}"); - - Ok(u32::from_ne_bytes(magic) == FLASH_INITIALIZE_MAGIC) - } - - pub fn initialize_flash(storage: &mut FlashStorage) -> Result<(), FlashStoreError> { - storage.erase(FLASH_ADDR, FLASH_ADDR + INITIALIZATION_SIZE as u32)?; - let zeros: [u8; INITIALIZATION_SIZE] = [0; INITIALIZATION_SIZE]; - storage.write(FLASH_ADDR + MAGIC_REGION.end() as u32, &zeros)?; - storage.write( - FLASH_ADDR + MAGIC_REGION.offset, - &FLASH_INITIALIZE_MAGIC.to_ne_bytes(), - )?; - - if Self::has_magic_bytes(storage)? { - Ok(()) - } else { - Err(FlashStoreError(FlashStorageError::Other( - FLASH_INITIALIZE_MAGIC as i32, - ))) - } - } -} diff --git a/wokwi.toml b/wokwi.toml index c6e133d..297f99c 100644 --- a/wokwi.toml +++ b/wokwi.toml @@ -1,9 +1,10 @@ [wokwi] version = 1 gdbServerPort = 3333 -elf = "target/xtensa-esp32s3-none-elf/debug/creaturedex" -firmware = "target/xtensa-esp32s3-none-elf/debug/creaturedex" +elf = "target/xtensa-esp32s3-none-elf/release/creaturedex" +firmware = "target/xtensa-esp32s3-none-elf/release/creaturedex" [[chip]] -name = 'ch1115' -binary = 'wokwi/ch1115.chip.wasm' \ No newline at end of file +name = 'ch1115' +binary = 'wokwi/ch1115.chip.wasm' +