Compare commits
4
Commits
90d8173397
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f251de3d5 | ||
|
|
ffc5899c33 | ||
|
|
47b539f364 | ||
|
|
fafb4fc34f
|
+1
-1
@@ -2,7 +2,7 @@
|
||||
runner = "espflash flash --monitor --chip esp32s3"
|
||||
|
||||
[env]
|
||||
ESP_LOG = "debug"
|
||||
ESP_LOG = "info"
|
||||
WM_CONN = '{"ssid": "Wokwi-GUEST", "psk": "", "data": {}}'
|
||||
|
||||
[build]
|
||||
|
||||
Generated
+29
-1583
File diff suppressed because it is too large
Load Diff
+7
-4
@@ -32,10 +32,6 @@ embassy-executor = { version = "0.10.0", features = ["trace", "metadata-name"] }
|
||||
embassy-time = { version = "0.5.1", default-features = false }
|
||||
embassy-futures = "0.1.2"
|
||||
esp-alloc = "0.10.0"
|
||||
esp-hal-wifimanager = { git = "https://github.com/rhetenor/esp-hal-wifimanager.git", default-features = false, features = [
|
||||
"ap",
|
||||
"esp32s3",
|
||||
] }
|
||||
esp-println = { version = "0.17.0", features = ["esp32s3", "log-04"] }
|
||||
display-interface-spi = "0.5.0"
|
||||
ili9341 = "0.6.0"
|
||||
@@ -56,6 +52,12 @@ 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",
|
||||
] }
|
||||
esp-radio = { version = "0.18.0", features = ["esp32s3", "wifi"] }
|
||||
|
||||
[build-dependencies]
|
||||
log = "0.4.27"
|
||||
@@ -84,6 +86,7 @@ opt-level = 's'
|
||||
[features]
|
||||
default = []
|
||||
wokwi = []
|
||||
nop_tertiary = []
|
||||
|
||||
[lints.clippy]
|
||||
manual_async_fn = "allow"
|
||||
|
||||
+2
-2
@@ -2,8 +2,8 @@ include <common.scad>
|
||||
use <left-half.scad>
|
||||
use <right-half.scad>
|
||||
|
||||
left_half();
|
||||
right_half();
|
||||
left_half_creaturedex();
|
||||
right_half_creaturedex();
|
||||
|
||||
#union() {
|
||||
right_half_components();
|
||||
|
||||
@@ -144,7 +144,8 @@ module hinges(joint_axis_length = 80, hinge_thickness = 22) {
|
||||
}
|
||||
}
|
||||
|
||||
module left_half() {
|
||||
module left_half_creaturedex() {
|
||||
left((w + hinge_thickness) / 2)
|
||||
diff("holes", "forcekeep")
|
||||
// Outer walls
|
||||
color_this("green")
|
||||
@@ -220,6 +221,6 @@ module left_half() {
|
||||
}
|
||||
}
|
||||
|
||||
left_half();
|
||||
left_half_creaturedex();
|
||||
|
||||
left(300) left_half_orig();
|
||||
|
||||
@@ -106,10 +106,10 @@ module right_half_hinge_only() {
|
||||
}
|
||||
// !right_half_hinge_only();
|
||||
|
||||
module right_half() {
|
||||
module right_half_creaturedex() {
|
||||
right_half_door_only();
|
||||
right_half_hinge_only();
|
||||
}
|
||||
|
||||
// right_half();
|
||||
// right_half_creaturedex();
|
||||
// #right_half_components();
|
||||
|
||||
+2
-7
@@ -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,
|
||||
|
||||
|
@@ -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;
|
||||
|
||||
+25
-14
@@ -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,14 +20,15 @@ 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;
|
||||
use creaturedex::network::wifi::setup_wifi;
|
||||
use creaturedex::network::wifi::Wifi;
|
||||
use creaturedex::network::wifi::wait_for_wifi_credentials;
|
||||
use creaturedex::peripherals::Peripherals;
|
||||
use creaturedex::peripherals::storage::cardstore::CardStore;
|
||||
use creaturedex::peripherals::storage::store::Store;
|
||||
use creaturedex::peripherals::storage::wifistore::WifiStore;
|
||||
use embassy_executor::Spawner;
|
||||
use embedded_graphics::pixelcolor::BinaryColor;
|
||||
use embedded_graphics::{
|
||||
@@ -38,22 +40,16 @@ use embedded_hal_bus::i2c::AtomicDevice;
|
||||
use esp_hal::clock::CpuClock;
|
||||
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: <https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/app_image_format.html#application-description>
|
||||
@@ -133,18 +129,30 @@ async fn main(spawner: Spawner) {
|
||||
.expect("failed to create nvs"),
|
||||
));
|
||||
|
||||
setup_wifi(esp_peripherals.WIFI, Arc::clone(&nvs), &spawner).await;
|
||||
let wifi_store = WifiStore::new(nvs.clone())
|
||||
.await
|
||||
.expect("Could not initialize WiFi store");
|
||||
|
||||
let card_store = CardStore::new(nvs)
|
||||
let mut wifi = Wifi::new(esp_peripherals.WIFI).expect("Could not initialize WiFi");
|
||||
|
||||
wifi.connect_with_stored_credentials(&wifi_store)
|
||||
.await
|
||||
.expect("could not connect initially");
|
||||
|
||||
let card_store = CardStore::new(nvs.clone())
|
||||
.await
|
||||
.expect("Could not initialize Card Store");
|
||||
|
||||
let store = Store { card_store };
|
||||
let store = Store {
|
||||
card_store,
|
||||
wifi_store,
|
||||
};
|
||||
let rtc = Rtc::new(esp_peripherals.LPWR);
|
||||
|
||||
let peripherals = Box::leak(Box::new(Peripherals {
|
||||
store: Mutex::new(store),
|
||||
rtc,
|
||||
wifi: Mutex::new(wifi),
|
||||
}));
|
||||
|
||||
let mut nfc_driver = NfcPn532Driver::new(AtomicDevice::new(shared_i2c));
|
||||
@@ -191,6 +199,9 @@ async fn main(spawner: Spawner) {
|
||||
background_tasks::nfc_scanner(nfc_driver, outputs, peripherals, navigation_state)
|
||||
.expect("nfc scanner task failed"),
|
||||
);
|
||||
spawner.spawn(
|
||||
wait_for_wifi_credentials(outputs, peripherals).expect("wifi credential task failed"),
|
||||
);
|
||||
|
||||
core::future::pending::<()>().await
|
||||
}
|
||||
|
||||
@@ -14,6 +14,14 @@ pub struct TertiaryDisplayPinConfiguration<'a> {
|
||||
pub i2c: I2cBus<'a>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "nop_tertiary")]
|
||||
impl<'a> TertiaryDisplayPinConfiguration<'a> {
|
||||
pub fn build(self) -> Result<TertiaryDisplay<'a>, Self> {
|
||||
Ok(TertiaryDisplay { phantom: &() })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "nop_tertiary"))]
|
||||
impl<'a> TertiaryDisplayPinConfiguration<'a> {
|
||||
pub fn build(self) -> Result<TertiaryDisplay<'a>, Self> {
|
||||
let device = AtomicDevice::new(self.i2c);
|
||||
@@ -61,19 +69,50 @@ impl<'a> core::fmt::Display for TertiaryDisplayWriteError<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "nop_tertiary"))]
|
||||
pub struct TertiaryDisplay<'a> {
|
||||
display: TertiaryDisplayRaw<'a>,
|
||||
charset: CustomCharset,
|
||||
}
|
||||
|
||||
#[cfg(feature = "nop_tertiary")]
|
||||
pub struct TertiaryDisplay<'a> {
|
||||
phantom: &'a (),
|
||||
}
|
||||
|
||||
#[cfg(feature = "nop_tertiary")]
|
||||
impl<'a> TertiaryDisplay<'a> {
|
||||
pub const WIDTH: usize = 16;
|
||||
pub const ROWS: usize = 2;
|
||||
|
||||
pub fn inner_mut(&mut self) -> &mut TertiaryDisplayRaw<'a> {
|
||||
&mut self.display
|
||||
pub fn load_charset(&mut self, charset: CustomCharset) -> Result<(), TertiaryDisplayError<'a>> {
|
||||
log::info!("nop tertiary");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) -> Result<(), TertiaryDisplayError<'a>> {
|
||||
log::info!("nop tertiary");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes text to the LCD. Normal strings wrap by default but this can be controlled
|
||||
/// via explicit [`Lines::checked`].
|
||||
pub fn write<'b, L: Into<Lines<'b>>>(
|
||||
&mut self,
|
||||
text: L,
|
||||
) -> Result<(), TertiaryDisplayWriteError<'a>> {
|
||||
log::info!("nop tertiary");
|
||||
log::info!("{:?}", text.into());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "nop_tertiary"))]
|
||||
impl<'a> TertiaryDisplay<'a> {
|
||||
pub const WIDTH: usize = 16;
|
||||
pub const ROWS: usize = 2;
|
||||
|
||||
pub fn load_charset(&mut self, charset: CustomCharset) -> Result<(), TertiaryDisplayError<'a>> {
|
||||
self.charset = charset;
|
||||
for (index, charmap) in self
|
||||
|
||||
+10
-6
@@ -1,5 +1,6 @@
|
||||
#![no_std]
|
||||
#![feature(vec_into_chunks)]
|
||||
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
@@ -13,8 +14,11 @@ pub mod network;
|
||||
pub mod peripherals;
|
||||
pub mod views;
|
||||
|
||||
pub type Mutex<T> = embassy_sync::mutex::Mutex<CriticalSectionRawMutex, T>;
|
||||
pub type Signal<T> = embassy_sync::signal::Signal<CriticalSectionRawMutex, T>;
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn _embassy_trace_poll_start(executor_id: u32) {}
|
||||
pub extern "Rust" fn _embassy_trace_poll_start(_executor_id: u32) {}
|
||||
|
||||
/// This callback is called AFTER a task is initialized/allocated, and BEFORE
|
||||
/// it is enqueued to run for the first time. If the task ends (and does not
|
||||
@@ -40,7 +44,7 @@ pub extern "Rust" fn _embassy_trace_task_end(executor_id: u32, task_id: u32) {
|
||||
/// This marks the TASK state transition from WAITING -> RUNNING
|
||||
/// This marks the EXECUTOR state transition from SCHEDULING -> POLLING
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn _embassy_trace_task_exec_begin(executor_id: u32, task_id: u32) {}
|
||||
pub extern "Rust" fn _embassy_trace_task_exec_begin(_executor_id: u32, _task_id: u32) {}
|
||||
|
||||
/// This callback is called AFTER a task has completed polling. There will
|
||||
/// always be a matching call to `_embassy_trace_task_exec_begin`.
|
||||
@@ -53,7 +57,7 @@ pub extern "Rust" fn _embassy_trace_task_exec_begin(executor_id: u32, task_id: u
|
||||
///
|
||||
/// This marks the EXECUTOR state transition from POLLING -> SCHEDULING
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn _embassy_trace_task_exec_end(excutor_id: u32, task_id: u32) {}
|
||||
pub extern "Rust" fn _embassy_trace_task_exec_end(_executor_id: u32, _task_id: u32) {}
|
||||
|
||||
/// This callback is called AFTER the waker for a task is awoken, and BEFORE it
|
||||
/// is added to the run queue.
|
||||
@@ -67,7 +71,7 @@ pub extern "Rust" fn _embassy_trace_task_exec_end(excutor_id: u32, task_id: u32)
|
||||
/// NOTE: This may be called from an interrupt, outside the contpub ext of the current
|
||||
/// task or executor.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn _embassy_trace_task_ready_begin(executor_id: u32, task_id: u32) {}
|
||||
pub extern "Rust" fn _embassy_trace_task_ready_begin(_executor_id: u32, _task_id: u32) {}
|
||||
|
||||
/// This callback is called AFTER all dequeued tasks in a single call to poll
|
||||
/// have been processed. This will always be paired with a call to
|
||||
@@ -77,4 +81,4 @@ pub extern "Rust" fn _embassy_trace_task_ready_begin(executor_id: u32, task_id:
|
||||
/// This marks the EXECUTOR state transition from SCHEDULING -> IDLE
|
||||
///
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn _embassy_trace_executor_idle(executor_id: u32) {}
|
||||
pub extern "Rust" fn _embassy_trace_executor_idle(_executor_id: u32) {}
|
||||
|
||||
@@ -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<T> = embassy_sync::mutex::Mutex<CriticalSectionRawMutex, T>;
|
||||
pub type Signal<T> = embassy_sync::signal::Signal<CriticalSectionRawMutex, T>;
|
||||
pub static CARD_DATA: Mutex<Option<Card>> = Mutex::new(None);
|
||||
const DEBOUNCE_DURATION_MILLIS: u64 = 100;
|
||||
|
||||
|
||||
+161
-25
@@ -1,42 +1,134 @@
|
||||
use crate::navigation::navigation::Mutex;
|
||||
use crate::peripherals::storage::Nvs;
|
||||
use alloc::sync::Arc;
|
||||
use embassy_executor::Spawner;
|
||||
|
||||
use crate::Mutex;
|
||||
use crate::Signal;
|
||||
use crate::alloc::string::ToString;
|
||||
use crate::navigation::outputs::Outputs;
|
||||
use crate::peripherals::Peripherals;
|
||||
#[cfg(not(feature = "wokwi"))]
|
||||
pub async fn setup_wifi(
|
||||
wifi: esp_hal::peripherals::WIFI<'static>,
|
||||
nvs: Arc<Mutex<Nvs>>,
|
||||
spawner: &Spawner,
|
||||
) {
|
||||
let espnvs = esp_hal_wifimanager::Nvs::new_from_nvs(nvs, 0, 0);
|
||||
use crate::peripherals::storage::wifistore::WifiStore;
|
||||
use crate::peripherals::storage::wifistore::WifiStoreError;
|
||||
use alloc::string::String;
|
||||
use core::error::Error;
|
||||
use core::fmt::Display;
|
||||
use esp_radio::wifi::Config;
|
||||
use esp_radio::wifi::WifiController;
|
||||
use esp_radio::wifi::sta::StationConfig;
|
||||
use esp_radio::*;
|
||||
|
||||
let mut wm_settings = esp_hal_wifimanager::WmSettings::default();
|
||||
#[derive(Debug)]
|
||||
pub struct WifiCredentials {
|
||||
pub ssid: String,
|
||||
pub pass: String,
|
||||
}
|
||||
|
||||
wm_settings.ssid.clear();
|
||||
_ = core::fmt::write(
|
||||
&mut wm_settings.ssid,
|
||||
format_args!("CreatureDex-{:X}", esp_hal_wifimanager::get_efuse_mac()),
|
||||
);
|
||||
pub static WIFI_CREDENTIALS: Signal<WifiCredentials> = Signal::new();
|
||||
|
||||
wm_settings.wifi_conn_timeout = 30000;
|
||||
wm_settings.esp_reset_timeout = Some(300000); // 5min
|
||||
#[derive(Debug)]
|
||||
pub struct Wifi {
|
||||
controller: WifiController<'static>,
|
||||
interfaces: wifi::Interfaces<'static>,
|
||||
}
|
||||
|
||||
let wifi_res =
|
||||
esp_hal_wifimanager::init_wm(wm_settings, spawner, Some(&espnvs), wifi, None).await;
|
||||
#[derive(Debug)]
|
||||
pub enum WifiError {
|
||||
Store(WifiStoreError),
|
||||
Radio(esp_radio::wifi::WifiError),
|
||||
NoCredentialsStored,
|
||||
}
|
||||
|
||||
log::info!("wifi_res: {wifi_res:?}");
|
||||
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::Radio(e) => e.fmt(f),
|
||||
WifiError::NoCredentialsStored => write!(f, "No WiFi credentials stored in flash"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WifiStoreError> for WifiError {
|
||||
fn from(error: WifiStoreError) -> WifiError {
|
||||
WifiError::Store(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<esp_radio::wifi::WifiError> for WifiError {
|
||||
fn from(error: esp_radio::wifi::WifiError) -> WifiError {
|
||||
WifiError::Radio(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl Wifi {
|
||||
pub fn new(wifi: esp_hal::peripherals::WIFI<'static>) -> Result<Self, WifiError> {
|
||||
log::info!("creating new wifi");
|
||||
let wifi = wifi::new(wifi, Default::default())?;
|
||||
|
||||
Ok(Self {
|
||||
controller: wifi.0,
|
||||
interfaces: wifi.1,
|
||||
})
|
||||
}
|
||||
// get wifi credentials from env WIFI_SSID; WIFI_PASS (priority) or storage
|
||||
pub async fn connect_with_stored_credentials(
|
||||
&mut self,
|
||||
wifi_store: &WifiStore,
|
||||
) -> Result<(), WifiError> {
|
||||
let option_stored_credentials = wifi_store.load_credentials().await?;
|
||||
|
||||
let env_ssid = option_env!("WIFI_SSID");
|
||||
let env_pass = option_env!("WIFI_PASS");
|
||||
|
||||
if env_ssid.is_none() && option_stored_credentials.is_none() {
|
||||
log::info!("no initial wifi credentials. do not connect");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let stored_credentials = option_stored_credentials.unwrap_or(WifiCredentials {
|
||||
pass: "".to_string(),
|
||||
ssid: "".to_string(),
|
||||
});
|
||||
|
||||
let ssid = env_ssid.map_or(stored_credentials.ssid, |v| v.to_string());
|
||||
let pass = env_pass.map_or(stored_credentials.pass, |v| v.to_string());
|
||||
|
||||
log::info!("initial wifi credentials:\nssid:{ssid}, pass:{pass}");
|
||||
|
||||
let credentials = WifiCredentials { ssid, pass };
|
||||
|
||||
self.set_station(credentials).await?;
|
||||
self.connect().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn connect(&mut self) -> Result<(), WifiError> {
|
||||
log::info!("connecting wifi...");
|
||||
|
||||
let stationinfo = self.controller.connect_async().await?;
|
||||
|
||||
log::info!("connected to {}", stationinfo.ssid.as_str());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_station(&mut self, credentials: WifiCredentials) -> Result<(), WifiError> {
|
||||
let station_config = StationConfig::default()
|
||||
.with_ssid(credentials.ssid)
|
||||
.with_password(credentials.pass);
|
||||
self.controller
|
||||
.set_config(&Config::Station(station_config))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "wokwi")]
|
||||
pub async fn setup_wifi(
|
||||
pub async fn setup(
|
||||
wifi: esp_hal::peripherals::WIFI<'static>,
|
||||
nvs: Arc<Mutex<Nvs>>,
|
||||
spawner: &Spawner,
|
||||
) {
|
||||
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");
|
||||
|
||||
@@ -61,7 +153,51 @@ pub async fn setup_wifi(
|
||||
wm_settings.wifi_conn_timeout = 30000;
|
||||
|
||||
// Initialize Wi-Fi connection through WiFi Manager using the pre-seeded NVS data.
|
||||
let wifi_res = esp_hal_wifimanager::init_wm(wm_settings, spawner, Some(&nvs), wifi, None).await;
|
||||
let wifi_res =
|
||||
esp_hal_wifimanager::init_wm(wm_settings, spawner, Some(&nvs), wifi, None).await;
|
||||
|
||||
log::info!("Wokwi wifi_res: {wifi_res:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
pub async fn wait_for_wifi_credentials(
|
||||
_outputs: &'static Mutex<Outputs>,
|
||||
peripherals: &'static Peripherals,
|
||||
) {
|
||||
loop {
|
||||
log::info!("Waiting for new WiFi credentials");
|
||||
let credentials = WIFI_CREDENTIALS.wait().await;
|
||||
|
||||
log::info!(
|
||||
"Received new WiFi credentials:\nssid: {}, pass: {}",
|
||||
credentials.ssid,
|
||||
credentials.pass
|
||||
);
|
||||
if let Err(err) = peripherals
|
||||
.store
|
||||
.lock()
|
||||
.await
|
||||
.wifi_store
|
||||
.save_credentials(&credentials)
|
||||
.await
|
||||
{
|
||||
log::error!("Error storing credentials: {err}");
|
||||
continue;
|
||||
}
|
||||
|
||||
log::info!("Saved new WiFi credentials. Restarting WiFi");
|
||||
|
||||
let mut wifi = peripherals.wifi.lock().await;
|
||||
|
||||
if let Err(err) = wifi.set_station(credentials).await {
|
||||
log::error!("Error setting new wifi station: {err}");
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Err(err) = wifi.connect().await {
|
||||
log::error!("Error connecting to wifi: {err}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -1,6 +1,7 @@
|
||||
pub mod storage;
|
||||
|
||||
use crate::navigation::navigation::Mutex;
|
||||
use crate::Mutex;
|
||||
use crate::network::wifi::Wifi;
|
||||
use crate::peripherals::storage::store::Store;
|
||||
|
||||
use esp_hal::rtc_cntl::Rtc;
|
||||
@@ -8,4 +9,5 @@ use esp_hal::rtc_cntl::Rtc;
|
||||
pub struct Peripherals {
|
||||
pub store: Mutex<Store>,
|
||||
pub rtc: Rtc<'static>,
|
||||
pub wifi: Mutex<Wifi>,
|
||||
}
|
||||
|
||||
@@ -5,3 +5,4 @@ pub type Nvs = esp_nvs::Nvs<FlashStorage<'static>>;
|
||||
pub mod cardstore;
|
||||
pub mod settings;
|
||||
pub mod store;
|
||||
pub mod wifistore;
|
||||
|
||||
@@ -60,7 +60,7 @@ pub struct CardStoreMetaData {
|
||||
impl CardStoreMetaData {
|
||||
fn new(creation_date: u64) -> Self {
|
||||
Self {
|
||||
creation_date: creation_date,
|
||||
creation_date,
|
||||
last_read_date: creation_date,
|
||||
read_count: 0,
|
||||
}
|
||||
@@ -94,18 +94,18 @@ impl CardStore {
|
||||
match nvs_lock.get::<bool>(&NVS_NAMESPACE_CARDSTORE, &NVS_CARDSTORE_INITIALIZED_KEY) {
|
||||
Ok(initialized) => {
|
||||
log::debug!("initialization_check: initialized {initialized:?}");
|
||||
return Ok(true);
|
||||
Ok(true)
|
||||
}
|
||||
Err(esp_nvs::error::Error::NamespaceNotFound) => {
|
||||
log::debug!("initialization_check: error: namespace not found");
|
||||
return Ok(false);
|
||||
Ok(false)
|
||||
}
|
||||
Err(esp_nvs::error::Error::KeyNotFound) => {
|
||||
log::debug!("initialization_check: error: key not found");
|
||||
return Ok(false);
|
||||
Ok(false)
|
||||
}
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
}
|
||||
|
||||
// initializing cardstore with 0 cards, so that all namespaces exist and there
|
||||
|
||||
@@ -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<FlashStorageError> 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<FlashStorage<'static>>,
|
||||
}
|
||||
|
||||
impl FlashStore {
|
||||
pub fn new(flash: esp_hal::peripherals::FLASH<'static>) -> Result<Self, FlashStoreError> {
|
||||
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<bool, FlashStoreError> {
|
||||
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,
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::peripherals::storage::cardstore::CardStore;
|
||||
use crate::peripherals::storage::wifistore::WifiStore;
|
||||
|
||||
pub struct Store {
|
||||
pub card_store: CardStore,
|
||||
pub wifi_store: WifiStore,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
use alloc::string::String;
|
||||
use crate::network::wifi::WifiCredentials;
|
||||
use crate::Mutex;
|
||||
use crate::peripherals::storage::Nvs;
|
||||
use alloc::sync::Arc;
|
||||
use core::error::Error;
|
||||
use core::fmt::Display;
|
||||
use esp_nvs::Key;
|
||||
|
||||
const NVS_NAMESPACE_WIFI: Key = Key::from_str("WIFI");
|
||||
const NVS_WIFI_SSID_KEY: Key = Key::from_str("WIFI_SSID");
|
||||
const NVS_WIFI_PASS_KEY: Key = Key::from_str("WIFI_PASS");
|
||||
const NVS_WIFI_INITIALIZED_KEY: Key = Key::from_str("INITIALIZED");
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum WifiStoreError {
|
||||
Store(esp_nvs::error::Error),
|
||||
}
|
||||
|
||||
impl Error for WifiStoreError {}
|
||||
|
||||
impl Display for WifiStoreError {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
WifiStoreError::Store(e) => e.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<esp_nvs::error::Error> for WifiStoreError {
|
||||
fn from(error: esp_nvs::error::Error) -> WifiStoreError {
|
||||
WifiStoreError::Store(error)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WifiStore {
|
||||
nvs: Arc<Mutex<Nvs>>,
|
||||
}
|
||||
|
||||
impl WifiStore {
|
||||
pub async fn new(nvs: Arc<Mutex<Nvs>>) -> Result<Self, WifiStoreError> {
|
||||
if !Self::is_initialized(&nvs).await? {
|
||||
log::info!("WifiStore has not been initialized");
|
||||
Self::initialize(&nvs).await?;
|
||||
}
|
||||
|
||||
log::info!("WifiStore has been initialized");
|
||||
|
||||
Ok(Self { nvs })
|
||||
}
|
||||
|
||||
async fn is_initialized(nvs: &Mutex<Nvs>) -> Result<bool, WifiStoreError> {
|
||||
log::info!("check initialization");
|
||||
let mut nvs_lock = nvs.lock().await;
|
||||
match nvs_lock.get::<bool>(&NVS_NAMESPACE_WIFI, &NVS_WIFI_INITIALIZED_KEY) {
|
||||
Ok(initialized) => {
|
||||
log::debug!("initialization_check: initialized {initialized:?}");
|
||||
Ok(true)
|
||||
}
|
||||
Err(esp_nvs::error::Error::NamespaceNotFound) => {
|
||||
log::debug!("initialization_check: error: namespace not found");
|
||||
Ok(false)
|
||||
}
|
||||
Err(esp_nvs::error::Error::KeyNotFound) => {
|
||||
log::debug!("initialization_check: error: key not found");
|
||||
Ok(false)
|
||||
}
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn initialize(nvs: &Mutex<Nvs>) -> Result<(), WifiStoreError> {
|
||||
log::info!("initializing wifi store");
|
||||
|
||||
let mut nvs_lock = nvs.lock().await;
|
||||
|
||||
log::debug!("initialization: write empty ssid");
|
||||
nvs_lock.set::<&str>(
|
||||
&NVS_NAMESPACE_WIFI,
|
||||
&NVS_WIFI_SSID_KEY,
|
||||
""
|
||||
)?;
|
||||
|
||||
log::debug!("initialization: write empty pass");
|
||||
nvs_lock.set::<&str>(
|
||||
&NVS_NAMESPACE_WIFI,
|
||||
&NVS_WIFI_PASS_KEY,
|
||||
""
|
||||
)?;
|
||||
|
||||
// set initialized
|
||||
log::debug!("initialization: write initialized");
|
||||
nvs_lock.set::<bool>(
|
||||
&NVS_NAMESPACE_WIFI,
|
||||
&NVS_WIFI_INITIALIZED_KEY,
|
||||
true,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn load_credentials(&self) -> Result<Option<WifiCredentials>, WifiStoreError> {
|
||||
log::debug!("loading wifi credentials");
|
||||
log::debug!("loading ssid");
|
||||
let mut nvs_lock = self.nvs.lock().await;
|
||||
let ssid = nvs_lock.get::<String>(&NVS_NAMESPACE_WIFI, &NVS_WIFI_SSID_KEY)?;
|
||||
if ssid.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
log::debug!("ssid: {ssid}");
|
||||
|
||||
log::debug!("loading pass");
|
||||
let pass = nvs_lock.get::<String>(&NVS_NAMESPACE_WIFI, &NVS_WIFI_PASS_KEY)?;
|
||||
|
||||
log::debug!("pass: {pass}");
|
||||
|
||||
Ok(Some(WifiCredentials{ssid, pass}))
|
||||
}
|
||||
|
||||
pub async fn save_credentials(&self, credentials: &WifiCredentials) -> Result<(), WifiStoreError> {
|
||||
log::debug!("writing wifi credentials");
|
||||
log::debug!("writing ssid...\nssid: {}", credentials.ssid);
|
||||
|
||||
self.nvs.lock().await.set::<&str>(
|
||||
&NVS_NAMESPACE_WIFI,
|
||||
&NVS_WIFI_SSID_KEY,
|
||||
&credentials.ssid,
|
||||
)?;
|
||||
|
||||
log::debug!("writing pass...\npass: {}", credentials.pass);
|
||||
|
||||
self.nvs.lock().await.set::<&str>(
|
||||
&NVS_NAMESPACE_WIFI,
|
||||
&NVS_WIFI_PASS_KEY,
|
||||
&credentials.pass,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -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'
|
||||
|
||||
|
||||
Reference in New Issue
Block a user