4 Commits
Author SHA1 Message Date
rhetenor 4f251de3d5 wifi: fix issue with initialization
tertiary display: implement feature flag to disable
common: remove debug from cargo config, use ESP_LOG="creaturedex:debug"
2026-09-15 20:54:48 +02:00
rhetenor ffc5899c33 wifi: implement station change and connect 2026-09-15 20:54:48 +02:00
rhetenor 47b539f364 use own wifi implementation to connect to wifi. store credentials in flash. no wifi connection yet 2026-09-15 20:54:48 +02:00
ede1998 fafb4fc34f re-model left half of housing with bosl2 2026-09-13 20:06:04 +02:00
23 changed files with 694 additions and 1811 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
runner = "espflash flash --monitor --chip esp32s3" runner = "espflash flash --monitor --chip esp32s3"
[env] [env]
ESP_LOG = "debug" ESP_LOG = "info"
WM_CONN = '{"ssid": "Wokwi-GUEST", "psk": "", "data": {}}' WM_CONN = '{"ssid": "Wokwi-GUEST", "psk": "", "data": {}}'
[build] [build]
Generated
+29 -1583
View File
File diff suppressed because it is too large Load Diff
+7 -4
View File
@@ -32,10 +32,6 @@ embassy-executor = { version = "0.10.0", features = ["trace", "metadata-name"] }
embassy-time = { version = "0.5.1", default-features = false } embassy-time = { version = "0.5.1", default-features = false }
embassy-futures = "0.1.2" embassy-futures = "0.1.2"
esp-alloc = "0.10.0" 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"] } esp-println = { version = "0.17.0", features = ["esp32s3", "log-04"] }
display-interface-spi = "0.5.0" display-interface-spi = "0.5.0"
ili9341 = "0.6.0" ili9341 = "0.6.0"
@@ -56,6 +52,12 @@ binary_serde = "1.0.25"
static_assertions = { version = "1.1.0", default-features = false } static_assertions = { version = "1.1.0", default-features = false }
embedded-text = "0.7.3" embedded-text = "0.7.3"
esp-nvs = { version = "0.5.0", features = ["esp32s3"] } 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] [build-dependencies]
log = "0.4.27" log = "0.4.27"
@@ -84,6 +86,7 @@ opt-level = 's'
[features] [features]
default = [] default = []
wokwi = [] wokwi = []
nop_tertiary = []
[lints.clippy] [lints.clippy]
manual_async_fn = "allow" manual_async_fn = "allow"
+2 -2
View File
@@ -2,8 +2,8 @@ include <common.scad>
use <left-half.scad> use <left-half.scad>
use <right-half.scad> use <right-half.scad>
left_half(); left_half_creaturedex();
right_half(); right_half_creaturedex();
#union() { #union() {
right_half_components(); right_half_components();
+4 -3
View File
@@ -61,9 +61,10 @@ module main_display(pin_header = false) {
left(sd_inset) left(sd_inset)
cuboid([sd_width, sd_length, sd_height], anchor=TOP + RIGHT + FRONT); cuboid([sd_width, sd_length, sd_height], anchor=TOP + RIGHT + FRONT);
position(BOTTOM + LEFT) if (pin_header)
xrot(180) position(BOTTOM + LEFT)
pin_header(14, spin=90, anchor=BOTTOM + BACK); xrot(180)
pin_header(14, spin=90, anchor=BOTTOM + BACK);
} }
xcopies(length - (2 * hole_inset) - hole_diameter) { xcopies(length - (2 * hole_inset) - hole_diameter) {
+220 -6
View File
@@ -1,12 +1,226 @@
include <BOSL2/std.scad>
include <common.scad> include <common.scad>
module left_half_components() { module left_half_orig() {
cube([1,1,1]); translate(BASE_MODEL_TRANSLATE) scale(BASE_MODEL_SCALE) import(file="left-half.3mf");
} }
module left_half() { BASE_MODEL_SCALE = 1.1;
translate(BASE_MODEL_TRANSLATE) scale(BASE_MODEL_SCALE) import(file = "left-half.3mf"); // Bounds: ~ [128.62, 185.46, 35.2]
LEFT_HALF_BOUNDING_BOX = BASE_MODEL_SCALE * [116.93, 168.6, 32];
w = LEFT_HALF_BOUNDING_BOX.x;
l = LEFT_HALF_BOUNDING_BOX.y;
max_h = LEFT_HALF_BOUNDING_BOX.z;
// Proportional heights based on a 4.5 unit total scale
base_h = max_h * (2.0 / 4.5);
border_h = max_h * (2.5 / 4.5);
top_h = max_h * (3.5 / 4.5);
sphere_r = max_h - top_h;
recess_h = 3;
bump_height = 10;
faceplate_thickness = 2;
wall = 5;
top_bump_width_big = 55;
top_bump_width_small = 35;
hinge_thickness = 22;
/// Builds the top bump.
module top_bump(height, extra_width = 0, inverted = false, wall = 2, anchor = CENTER, spin = 0, orient = UP) {
width_big = top_bump_width_big;
width_small = top_bump_width_small;
// Assuming 'w' is your base width defined in the outer scope.
// Lock the left side to the base width, add extra_width only to the right.
left_x = -w / 2;
right_x = (w / 2) + extra_width;
top_path = back(
// center the path around the origin
width_big / 2, [
[right_x, 0], // Index 0, top-right
[left_x, 0], // Index 1, top-left
[left_x, -width_big], // Index 2, bottom-left
[left_x / 2 + 20, -width_big], // Index 3, bottom-center-left
[0, -width_small], // Index 4, middle-center
[right_x, -width_small], // Index 5, bottom-right
]
);
radii_list = [5, 5, 5, 15, 5, 5];
top_poly = round_corners(top_path, radius=radii_list);
inner_poly = offset(top_poly, delta=-wall);
// The new total width
total_width = w + extra_width;
part_size = [total_width, width_big, height];
// The geometric center of the asymmetric shape is shifted to the right
part_offset = [extra_width / 2, 0, 0];
// Removed the `right(extra_width)` translation here.
// Added `offset` so BOSL2 knows the bounding box isn't centered at [0,0,0],
// keeping the CENTER anchor exactly on your original origin point.
attachable(anchor, spin, orient, size=part_size, offset=part_offset) {
if (inverted) {
down(wall / 2)
linear_sweep(inner_poly, height=height - wall + EPS, center=true);
} else {
diff("empty") {
linear_sweep(top_poly, height=height, center=true) {
attach(TOP)
tag("empty")
down(wall)
left(wall / 4) // (Leaving your original shift here)
linear_sweep(inner_poly, height=height - wall + EPS, anchor=TOP);
}
}
}
children();
}
} }
left_half(); module top_bump_skirt(height = 5) {
#left_half_components(); intersection() {
diff("heel_holes") {
tag("heel_holes")
down(EPS / 2)
top_bump(height=height * 2 + EPS, wall=wall, inverted=true, anchor=FRONT + BOTTOM);
top_bump(height=height, wall=wall, anchor=FRONT + BOTTOM);
}
down(EPS / 2)
cuboid([w, wall + (top_bump_width_big - top_bump_width_small) + EPS, height * 2 + EPS], anchor=FRONT + BOTTOM);
}
}
module top_bump_side_extension(width, height = 5) {
intersection() {
diff("heel_holes") {
tag("heel_holes")
down(EPS / 2)
top_bump(height=height * 2 + EPS, wall=wall, inverted=true, anchor=RIGHT + TOP + BACK);
top_bump(height=height, wall=wall, anchor=RIGHT + TOP + BACK);
}
back(EPS / 2)
up(EPS / 2)
cuboid([width, top_bump_width_small + EPS, height * 2 + EPS], anchor=RIGHT + TOP + BACK);
}
}
module top_bump_big_sphere(diameter, ring_extra_diameter, ring_height) {
zcyl(d=diameter + ring_extra_diameter, h=ring_height, anchor=BOTTOM)
position(TOP)
top_half() sphere(diameter / 2);
}
module top_bump_small_spheres(diameter, spacing) {
top_half() {
left(spacing) sphere(r=diameter / 2, anchor=CENTER);
sphere(r=diameter / 2, anchor=CENTER);
right(spacing) sphere(r=diameter / 2, anchor=CENTER);
}
}
/// Hinges to attach the right to the left (=this) half.
/// Origin is at the bottom left front corner.
module hinges(joint_axis_length = 80, hinge_thickness = 22) {
hinge_inset = 10;
hinge_inset_diameter = 6;
back(joint_axis_length)
yflip_copy(offset=joint_axis_length) {
right(border_h / 2 + 2)
// cannot get it to align with edge otherwise
ycyl(r=border_h / 2 + 2, l=hinge_thickness, anchor=BOTTOM + BACK)
position(FRONT) tag("holes") fwd(EPS) ycyl(d=hinge_inset_diameter, l=hinge_inset, anchor=FRONT);
cuboid([border_h / 2 + 2 + EPS, hinge_thickness, base_h], anchor=LEFT + BOTTOM + BACK);
}
}
module left_half_creaturedex() {
left((w + hinge_thickness) / 2)
diff("holes", "forcekeep")
// Outer walls
color_this("green")
rect_tube(h=base_h, size=[w, l], wall=wall, rounding=[0, 5, 5, 0]) {
// Gap for extension of top bump
position(RIGHT + BACK + BOTTOM)
fwd(wall)
move([EPS / 2, 0, -EPS / 2])
tag("holes")
cuboid([wall + EPS, top_bump_width_small - wall + EPS, EPS + bump_height + base_h], anchor=RIGHT + BOTTOM + BACK);
// Recessed Faceplate
attach(TOP)
recolor("blue")
down(recess_h) {
cuboid([w - EPS, l - EPS, faceplate_thickness], rounding=5, edges="Z", anchor=TOP) {
position(BACK)
tag("holes") top_bump(height=bump_height + faceplate_thickness + recess_h, wall=wall, inverted=true, anchor=BACK);
}
}
// Top Bump
tag("forcekeep")
recolor("Gold")
position(TOP + BACK) {
down(recess_h + faceplate_thickness)
top_bump(height=bump_height + faceplate_thickness + recess_h, extra_width=hinge_thickness, wall=wall, anchor=BOTTOM + BACK) {
position(TOP + BACK)
fwd(20) {
position(LEFT)
right(w / 5)
top_bump_big_sphere(diameter=23, ring_extra_diameter=4, ring_height=2);
position(RIGHT)
left(w / 5)
top_bump_small_spheres(diameter=7, spacing=15);
}
position(FRONT + BOTTOM)
fwd(wall)
top_bump_skirt(recess_h + faceplate_thickness);
position(RIGHT + BACK + TOP)
down(EPS)
back(EPS)
recolor("red")
top_bump_side_extension(width=hinge_thickness + wall, height=bump_height + base_h);
}
}
// TODO: do this properly!
// 4. Cutouts/Details in the Recessed Area
*up(base_h / 2 - max_h / 2) {
// Main Portrait Display Cutout
translate([0, 10, 0])
tag("holes") cuboid([w - 40, l - 90, base_h + 2], rounding=2, edges="Z");
// Small Landscape Display Cutout (Bottom Left)
translate([-w / 2 + 35, -l / 2 + 35, 0])
tag("holes") cuboid([28, 12, base_h + 2], rounding=1, edges="Z");
// D-Pad Cutout (Bottom Right)
translate([w / 2 - 35, -l / 2 + 35, 0])
tag("holes") union() {
cuboid([22, 8, base_h + 2], rounding=1, edges="Z");
cuboid([8, 22, base_h + 2], rounding=1, edges="Z");
}
}
// 5. Right Side Hinges
recolor("Red")
position(BOTTOM + RIGHT + FRONT) {
hinges();
}
}
}
left_half_creaturedex();
left(300) left_half_orig();
+2 -2
View File
@@ -106,10 +106,10 @@ module right_half_hinge_only() {
} }
// !right_half_hinge_only(); // !right_half_hinge_only();
module right_half() { module right_half_creaturedex() {
right_half_door_only(); right_half_door_only();
right_half_hinge_only(); right_half_hinge_only();
} }
// right_half(); // right_half_creaturedex();
// #right_half_components(); // #right_half_components();
+2 -7
View File
@@ -1,9 +1,4 @@
# ESP-IDF Partition Table # ESP-IDF Partition Table
# Name,Type,SubType,Offset,Size,Flags # Name,Type,SubType,Offset,Size,Flags
nvs,data,nvs,0x9000,0x6000, nvs,data,nvs,0x9000,0xa00000,
phy_init,data,phy,0xf000,0x1000, factory,app,factory,0xa10000,0x200000,
# 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,
1 # ESP-IDF Partition Table
2 # Name,Type,SubType,Offset,Size,Flags
3 nvs,data,nvs,0x9000,0x6000, nvs,data,nvs,0x9000,0xa00000,
4 phy_init,data,phy,0xf000,0x1000, factory,app,factory,0xa10000,0x200000,
# 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,
+2 -1
View File
@@ -1,6 +1,7 @@
use crate::navigation::navigation::display_error; use crate::navigation::navigation::display_error;
use crate::{ use crate::{
navigation::{navigation::Mutex, outputs::Outputs, state::NavigationState}, Mutex,
navigation::{outputs::Outputs, state::NavigationState},
peripherals::Peripherals, peripherals::Peripherals,
}; };
use alloc::string::ToString; use alloc::string::ToString;
+25 -14
View File
@@ -9,6 +9,7 @@
use alloc::boxed::Box; use alloc::boxed::Box;
use alloc::sync::Arc; use alloc::sync::Arc;
use creaturedex::Mutex;
use creaturedex::background_tasks; use creaturedex::background_tasks;
use creaturedex::drivers::i2c_bus::I2cBusPinConfiguration; use creaturedex::drivers::i2c_bus::I2cBusPinConfiguration;
use creaturedex::drivers::nfc_pn532::NfcPn532Driver; use creaturedex::drivers::nfc_pn532::NfcPn532Driver;
@@ -19,14 +20,15 @@ use creaturedex::drivers::tertiary_lcd::{
BOX, EMPTY, EXAMPLE, HEART, TertiaryDisplay, TertiaryDisplayPinConfiguration, BOX, EMPTY, EXAMPLE, HEART, TertiaryDisplay, TertiaryDisplayPinConfiguration,
}; };
use creaturedex::navigation::inputs::Inputs; use creaturedex::navigation::inputs::Inputs;
use creaturedex::navigation::navigation::Mutex;
use creaturedex::navigation::navigation::{self}; use creaturedex::navigation::navigation::{self};
use creaturedex::navigation::outputs::Outputs; use creaturedex::navigation::outputs::Outputs;
use creaturedex::navigation::state::NavigationState; 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::Peripherals;
use creaturedex::peripherals::storage::cardstore::CardStore; use creaturedex::peripherals::storage::cardstore::CardStore;
use creaturedex::peripherals::storage::store::Store; use creaturedex::peripherals::storage::store::Store;
use creaturedex::peripherals::storage::wifistore::WifiStore;
use embassy_executor::Spawner; use embassy_executor::Spawner;
use embedded_graphics::pixelcolor::BinaryColor; use embedded_graphics::pixelcolor::BinaryColor;
use embedded_graphics::{ use embedded_graphics::{
@@ -38,22 +40,16 @@ use embedded_hal_bus::i2c::AtomicDevice;
use esp_hal::clock::CpuClock; use esp_hal::clock::CpuClock;
use esp_hal::gpio::{Input, InputConfig, Pull}; use esp_hal::gpio::{Input, InputConfig, Pull};
use esp_hal::timer::timg::TimerGroup; use esp_hal::timer::timg::TimerGroup;
use log::error;
use esp_backtrace as _;
use esp_hal::rtc_cntl::Rtc; use esp_hal::rtc_cntl::Rtc;
#[panic_handler]
fn panic(panic_info: &core::panic::PanicInfo) -> ! {
error!("{}", panic_info);
loop {}
}
extern crate alloc; extern crate alloc;
const HEAP_SIZE: usize = 73744; const HEAP_SIZE: usize = 73744;
const NVS_PARTITION_OFFSET: usize = 0x10000; const NVS_PARTITION_OFFSET: usize = 0x9000;
const NVS_PARTITION_SIZE: usize = 0xfa000; const NVS_PARTITION_SIZE: usize = 0xa0000;
// This creates a default app-descriptor required by the esp-idf bootloader. // 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> // 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"), .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 .await
.expect("Could not initialize Card Store"); .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 rtc = Rtc::new(esp_peripherals.LPWR);
let peripherals = Box::leak(Box::new(Peripherals { let peripherals = Box::leak(Box::new(Peripherals {
store: Mutex::new(store), store: Mutex::new(store),
rtc, rtc,
wifi: Mutex::new(wifi),
})); }));
let mut nfc_driver = NfcPn532Driver::new(AtomicDevice::new(shared_i2c)); 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) background_tasks::nfc_scanner(nfc_driver, outputs, peripherals, navigation_state)
.expect("nfc scanner task failed"), .expect("nfc scanner task failed"),
); );
spawner.spawn(
wait_for_wifi_credentials(outputs, peripherals).expect("wifi credential task failed"),
);
core::future::pending::<()>().await core::future::pending::<()>().await
} }
+41 -2
View File
@@ -14,6 +14,14 @@ pub struct TertiaryDisplayPinConfiguration<'a> {
pub i2c: I2cBus<'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> { impl<'a> TertiaryDisplayPinConfiguration<'a> {
pub fn build(self) -> Result<TertiaryDisplay<'a>, Self> { pub fn build(self) -> Result<TertiaryDisplay<'a>, Self> {
let device = AtomicDevice::new(self.i2c); 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> { pub struct TertiaryDisplay<'a> {
display: TertiaryDisplayRaw<'a>, display: TertiaryDisplayRaw<'a>,
charset: CustomCharset, charset: CustomCharset,
} }
#[cfg(feature = "nop_tertiary")]
pub struct TertiaryDisplay<'a> {
phantom: &'a (),
}
#[cfg(feature = "nop_tertiary")]
impl<'a> TertiaryDisplay<'a> { impl<'a> TertiaryDisplay<'a> {
pub const WIDTH: usize = 16; pub const WIDTH: usize = 16;
pub const ROWS: usize = 2; pub const ROWS: usize = 2;
pub fn inner_mut(&mut self) -> &mut TertiaryDisplayRaw<'a> { pub fn load_charset(&mut self, charset: CustomCharset) -> Result<(), TertiaryDisplayError<'a>> {
&mut self.display 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>> { pub fn load_charset(&mut self, charset: CustomCharset) -> Result<(), TertiaryDisplayError<'a>> {
self.charset = charset; self.charset = charset;
for (index, charmap) in self for (index, charmap) in self
+10 -6
View File
@@ -1,5 +1,6 @@
#![no_std] #![no_std]
#![feature(vec_into_chunks)]
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
extern crate alloc; extern crate alloc;
@@ -13,8 +14,11 @@ pub mod network;
pub mod peripherals; pub mod peripherals;
pub mod views; 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)] #[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 /// 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 /// 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 TASK state transition from WAITING -> RUNNING
/// This marks the EXECUTOR state transition from SCHEDULING -> POLLING /// This marks the EXECUTOR state transition from SCHEDULING -> POLLING
#[unsafe(no_mangle)] #[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 /// This callback is called AFTER a task has completed polling. There will
/// always be a matching call to `_embassy_trace_task_exec_begin`. /// 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 /// This marks the EXECUTOR state transition from POLLING -> SCHEDULING
#[unsafe(no_mangle)] #[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 /// This callback is called AFTER the waker for a task is awoken, and BEFORE it
/// is added to the run queue. /// 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 /// NOTE: This may be called from an interrupt, outside the contpub ext of the current
/// task or executor. /// task or executor.
#[unsafe(no_mangle)] #[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 /// 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 /// 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 /// This marks the EXECUTOR state transition from SCHEDULING -> IDLE
/// ///
#[unsafe(no_mangle)] #[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
View File
@@ -1,3 +1,4 @@
use crate::Mutex;
use crate::card::model::Card; use crate::card::model::Card;
use crate::navigation::inputs::ButtonAction; use crate::navigation::inputs::ButtonAction;
use crate::navigation::inputs::Inputs; use crate::navigation::inputs::Inputs;
@@ -12,11 +13,8 @@ use alloc::string::ToString;
use core::error; use core::error;
use embassy_futures::select::{Either, select}; use embassy_futures::select::{Either, select};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_time::{Duration, Timer}; 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); pub static CARD_DATA: Mutex<Option<Card>> = Mutex::new(None);
const DEBOUNCE_DURATION_MILLIS: u64 = 100; const DEBOUNCE_DURATION_MILLIS: u64 = 100;
+189 -53
View File
@@ -1,67 +1,203 @@
use crate::navigation::navigation::Mutex; use crate::Mutex;
use crate::peripherals::storage::Nvs; use crate::Signal;
use alloc::sync::Arc; use crate::alloc::string::ToString;
use embassy_executor::Spawner; use crate::navigation::outputs::Outputs;
use crate::peripherals::Peripherals;
#[cfg(not(feature = "wokwi"))] #[cfg(not(feature = "wokwi"))]
pub async fn setup_wifi( use crate::peripherals::storage::wifistore::WifiStore;
wifi: esp_hal::peripherals::WIFI<'static>, use crate::peripherals::storage::wifistore::WifiStoreError;
nvs: Arc<Mutex<Nvs>>, use alloc::string::String;
spawner: &Spawner, use core::error::Error;
) { use core::fmt::Display;
let espnvs = esp_hal_wifimanager::Nvs::new_from_nvs(nvs, 0, 0); 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 {
wm_settings.ssid.clear(); pub ssid: String,
_ = core::fmt::write( pub pass: String,
&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:?}");
} }
#[cfg(feature = "wokwi")] pub static WIFI_CREDENTIALS: Signal<WifiCredentials> = Signal::new();
pub async fn setup_wifi(
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; #[derive(Debug)]
const WIFIMANAGER_NAMESPACE: Key = Key::from_str("wifimanager"); pub struct Wifi {
const WIFIMANAGER_NVS_KEY: Key = Key::from_str("WIFI_SETUP"); controller: WifiController<'static>,
interfaces: wifi::Interfaces<'static>,
}
if let Err(e) = nvs.lock().await.set( #[derive(Debug)]
&WIFIMANAGER_NAMESPACE, pub enum WifiError {
&WIFIMANAGER_NVS_KEY, Store(WifiStoreError),
"{\"ssid\":\"Wokwi-GUEST\",\"psk\":\"\",\"data\":{}}", Radio(esp_radio::wifi::WifiError),
) { NoCredentialsStored,
log::error!("Failed to store Wokwi WiFi config in NVS: {e:?}"); }
return;
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(())
} }
// Preload connection data so init_wm can connect immediately without AP setup. pub async fn connect(&mut self) -> Result<(), WifiError> {
let nvs = esp_hal_wifimanager::Nvs::new_from_nvs(nvs, 0, 0); log::info!("connecting wifi...");
let mut wm_settings = esp_hal_wifimanager::WmSettings::default(); let stationinfo = self.controller.connect_async().await?;
// Wokwi simulation uses a default open network called "Wokwi-GUEST" log::info!("connected to {}", stationinfo.ssid.as_str());
wm_settings.ssid.clear();
_ = core::fmt::write(&mut wm_settings.ssid, format_args!("Wokwi-GUEST"));
wm_settings.wifi_conn_timeout = 30000; Ok(())
}
// Initialize Wi-Fi connection through WiFi Manager using the pre-seeded NVS data. pub async fn set_station(&mut self, credentials: WifiCredentials) -> Result<(), WifiError> {
let wifi_res = esp_hal_wifimanager::init_wm(wm_settings, spawner, Some(&nvs), wifi, None).await; let station_config = StationConfig::default()
.with_ssid(credentials.ssid)
.with_password(credentials.pass);
self.controller
.set_config(&Config::Station(station_config))?;
Ok(())
}
log::info!("Wokwi wifi_res: {wifi_res:?}"); #[cfg(feature = "wokwi")]
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");
const WIFIMANAGER_NAMESPACE: Key = Key::from_str("wifimanager");
const WIFIMANAGER_NVS_KEY: Key = Key::from_str("WIFI_SETUP");
if let Err(e) = nvs.lock().await.set(
&WIFIMANAGER_NAMESPACE,
&WIFIMANAGER_NVS_KEY,
"{\"ssid\":\"Wokwi-GUEST\",\"psk\":\"\",\"data\":{}}",
) {
log::error!("Failed to store Wokwi WiFi config in NVS: {e:?}");
return;
}
// Preload connection data so init_wm can connect immediately without AP setup.
let nvs = esp_hal_wifimanager::Nvs::new_from_nvs(nvs, 0, 0);
let mut wm_settings = esp_hal_wifimanager::WmSettings::default();
// Wokwi simulation uses a default open network called "Wokwi-GUEST"
wm_settings.ssid.clear();
_ = core::fmt::write(&mut wm_settings.ssid, format_args!("Wokwi-GUEST"));
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;
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
View File
@@ -1,6 +1,7 @@
pub mod storage; pub mod storage;
use crate::navigation::navigation::Mutex; use crate::Mutex;
use crate::network::wifi::Wifi;
use crate::peripherals::storage::store::Store; use crate::peripherals::storage::store::Store;
use esp_hal::rtc_cntl::Rtc; use esp_hal::rtc_cntl::Rtc;
@@ -8,4 +9,5 @@ use esp_hal::rtc_cntl::Rtc;
pub struct Peripherals { pub struct Peripherals {
pub store: Mutex<Store>, pub store: Mutex<Store>,
pub rtc: Rtc<'static>, pub rtc: Rtc<'static>,
pub wifi: Mutex<Wifi>,
} }
+1
View File
@@ -5,3 +5,4 @@ pub type Nvs = esp_nvs::Nvs<FlashStorage<'static>>;
pub mod cardstore; pub mod cardstore;
pub mod settings; pub mod settings;
pub mod store; pub mod store;
pub mod wifistore;
+6 -6
View File
@@ -60,7 +60,7 @@ pub struct CardStoreMetaData {
impl CardStoreMetaData { impl CardStoreMetaData {
fn new(creation_date: u64) -> Self { fn new(creation_date: u64) -> Self {
Self { Self {
creation_date: creation_date, creation_date,
last_read_date: creation_date, last_read_date: creation_date,
read_count: 0, read_count: 0,
} }
@@ -94,18 +94,18 @@ impl CardStore {
match nvs_lock.get::<bool>(&NVS_NAMESPACE_CARDSTORE, &NVS_CARDSTORE_INITIALIZED_KEY) { match nvs_lock.get::<bool>(&NVS_NAMESPACE_CARDSTORE, &NVS_CARDSTORE_INITIALIZED_KEY) {
Ok(initialized) => { Ok(initialized) => {
log::debug!("initialization_check: initialized {initialized:?}"); log::debug!("initialization_check: initialized {initialized:?}");
return Ok(true); Ok(true)
} }
Err(esp_nvs::error::Error::NamespaceNotFound) => { Err(esp_nvs::error::Error::NamespaceNotFound) => {
log::debug!("initialization_check: error: namespace not found"); log::debug!("initialization_check: error: namespace not found");
return Ok(false); Ok(false)
} }
Err(esp_nvs::error::Error::KeyNotFound) => { Err(esp_nvs::error::Error::KeyNotFound) => {
log::debug!("initialization_check: error: key not found"); log::debug!("initialization_check: error: key not found");
return Ok(false); Ok(false)
} }
Err(error) => return Err(error.into()), Err(error) => Err(error.into()),
}; }
} }
// initializing cardstore with 0 cards, so that all namespaces exist and there // initializing cardstore with 0 cards, so that all namespaces exist and there
-112
View File
@@ -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,
)))
}
}
}
+1
View File
@@ -0,0 +1 @@
+2
View File
@@ -1,5 +1,7 @@
use crate::peripherals::storage::cardstore::CardStore; use crate::peripherals::storage::cardstore::CardStore;
use crate::peripherals::storage::wifistore::WifiStore;
pub struct Store { pub struct Store {
pub card_store: CardStore, pub card_store: CardStore,
pub wifi_store: WifiStore,
} }
+140
View File
@@ -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
View File
@@ -1,9 +1,10 @@
[wokwi] [wokwi]
version = 1 version = 1
gdbServerPort = 3333 gdbServerPort = 3333
elf = "target/xtensa-esp32s3-none-elf/debug/creaturedex" elf = "target/xtensa-esp32s3-none-elf/release/creaturedex"
firmware = "target/xtensa-esp32s3-none-elf/debug/creaturedex" firmware = "target/xtensa-esp32s3-none-elf/release/creaturedex"
[[chip]] [[chip]]
name = 'ch1115' name = 'ch1115'
binary = 'wokwi/ch1115.chip.wasm' binary = 'wokwi/ch1115.chip.wasm'