Compare commits
16
Commits
9ee4b68306
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f251de3d5 | ||
|
|
ffc5899c33 | ||
|
|
47b539f364 | ||
|
|
fafb4fc34f
|
||
|
|
4d9cd05f72 | ||
|
|
240e2b081d | ||
|
|
0aa1370a2b | ||
|
|
b814c61f45 | ||
|
|
290758d203 | ||
|
|
a77b7761cd
|
||
|
|
91948bdcf5 | ||
|
|
3c657045ca | ||
|
|
3d36885e11 | ||
|
|
af964bcc37 | ||
|
|
ccf16522bb | ||
|
|
5ac8fe9610 |
+2
-4
@@ -2,13 +2,11 @@
|
||||
runner = "espflash flash --monitor --chip esp32s3"
|
||||
|
||||
[env]
|
||||
ESP_LOG="info"
|
||||
ESP_LOG = "info"
|
||||
WM_CONN = '{"ssid": "Wokwi-GUEST", "psk": "", "data": {}}'
|
||||
|
||||
[build]
|
||||
rustflags = [
|
||||
"-C", "link-arg=-nostartfiles",
|
||||
]
|
||||
rustflags = ["-C", "link-arg=-nostartfiles"]
|
||||
|
||||
target = "xtensa-esp32s3-none-elf"
|
||||
|
||||
|
||||
Generated
+80
-1652
File diff suppressed because it is too large
Load Diff
+13
-6
@@ -28,14 +28,10 @@ log = "0.4.27"
|
||||
|
||||
critical-section = "1.2.0"
|
||||
embedded-io = "0.7.1"
|
||||
embassy-executor = { version = "0.10.0", features = [] }
|
||||
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/InvisibleUSA/esp-hal-wifimanager", 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"
|
||||
@@ -46,7 +42,7 @@ embedded-graphics-core = "0.4.1"
|
||||
base64 = { version = "0.23.1", default-features = false, features = ["alloc"] }
|
||||
pn532 = "0.5.0"
|
||||
num_enum = { version = "0.7.6", default-features = false }
|
||||
embassy-sync = "0.8.0"
|
||||
embassy-sync = "0.7.2"
|
||||
embedded-hal-async = "1.0.0"
|
||||
i2c-character-display = "0.5.1"
|
||||
ch1115 = { version = "0.1.2", features = ["graphics"] }
|
||||
@@ -55,6 +51,13 @@ embedded-storage = "0.3.1"
|
||||
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"
|
||||
@@ -83,3 +86,7 @@ opt-level = 's'
|
||||
[features]
|
||||
default = []
|
||||
wokwi = []
|
||||
nop_tertiary = []
|
||||
|
||||
[lints.clippy]
|
||||
manual_async_fn = "allow"
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
[idf_format_args]
|
||||
partition_table = "partitions.csv"
|
||||
+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();
|
||||
|
||||
@@ -61,6 +61,7 @@ module main_display(pin_header = false) {
|
||||
left(sd_inset)
|
||||
cuboid([sd_width, sd_length, sd_height], anchor=TOP + RIGHT + FRONT);
|
||||
|
||||
if (pin_header)
|
||||
position(BOTTOM + LEFT)
|
||||
xrot(180)
|
||||
pin_header(14, spin=90, anchor=BOTTOM + BACK);
|
||||
|
||||
+220
-6
@@ -1,12 +1,226 @@
|
||||
include <BOSL2/std.scad>
|
||||
include <common.scad>
|
||||
|
||||
module left_half_components() {
|
||||
cube([1,1,1]);
|
||||
module left_half_orig() {
|
||||
translate(BASE_MODEL_TRANSLATE) scale(BASE_MODEL_SCALE) import(file="left-half.3mf");
|
||||
}
|
||||
|
||||
module left_half() {
|
||||
translate(BASE_MODEL_TRANSLATE) scale(BASE_MODEL_SCALE) import(file = "left-half.3mf");
|
||||
BASE_MODEL_SCALE = 1.1;
|
||||
// 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();
|
||||
#left_half_components();
|
||||
module top_bump_skirt(height = 5) {
|
||||
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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# ESP-IDF Partition Table
|
||||
# Name,Type,SubType,Offset,Size,Flags
|
||||
nvs,data,nvs,0x9000,0xa00000,
|
||||
factory,app,factory,0xa10000,0x200000,
|
||||
|
@@ -1,4 +1,10 @@
|
||||
use crate::peripherals::Peripherals;
|
||||
use crate::navigation::navigation::display_error;
|
||||
use crate::{
|
||||
Mutex,
|
||||
navigation::{outputs::Outputs, state::NavigationState},
|
||||
peripherals::Peripherals,
|
||||
};
|
||||
use alloc::string::ToString;
|
||||
use embedded_hal_bus::i2c::AtomicDevice;
|
||||
use esp_hal::{Blocking, i2c::master::I2c, time::Instant};
|
||||
|
||||
@@ -15,7 +21,9 @@ use crate::{
|
||||
)]
|
||||
pub async fn nfc_scanner(
|
||||
mut nfc_driver: NfcPn532Driver<AtomicDevice<'static, I2c<'static, Blocking>>>,
|
||||
outputs: &'static Mutex<Outputs>,
|
||||
peripherals: &'static Peripherals,
|
||||
navigation_state: &'static Mutex<NavigationState>,
|
||||
) {
|
||||
loop {
|
||||
while CARD_DATA.lock().await.is_none() {
|
||||
@@ -35,17 +43,25 @@ pub async fn nfc_scanner(
|
||||
};
|
||||
CARD_DATA.lock().await.replace(card);
|
||||
|
||||
log::debug!("saving card to flash");
|
||||
match peripherals
|
||||
.store
|
||||
.lock()
|
||||
.await
|
||||
.card_store
|
||||
.save_raw_card(split_data, peripherals.rtc.current_time_us())
|
||||
.save_raw_card(&split_data, peripherals.rtc.current_time_us())
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(error) => {
|
||||
log::error!("Error storing card in flash: {:?}", error)
|
||||
log::error!("Error storing card in flash: {:?}", error);
|
||||
display_error(
|
||||
error.to_string(),
|
||||
navigation_state,
|
||||
outputs,
|
||||
peripherals,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +77,6 @@ pub async fn nfc_scanner(
|
||||
}
|
||||
}
|
||||
}
|
||||
embassy_time::Timer::after(embassy_time::Duration::from_millis(1000)).await;
|
||||
embassy_time::Timer::after(embassy_time::Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
+41
-18
@@ -8,6 +8,8 @@
|
||||
#![deny(clippy::large_stack_frames)]
|
||||
|
||||
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;
|
||||
@@ -17,14 +19,16 @@ use creaturedex::drivers::spi_bus;
|
||||
use creaturedex::drivers::tertiary_lcd::{
|
||||
BOX, EMPTY, EXAMPLE, HEART, TertiaryDisplay, TertiaryDisplayPinConfiguration,
|
||||
};
|
||||
use creaturedex::navigation::navigation::Mutex;
|
||||
use creaturedex::navigation::inputs::Inputs;
|
||||
use creaturedex::navigation::navigation::{self};
|
||||
use creaturedex::navigation::outputs::Outputs;
|
||||
use creaturedex::navigation::state::NavigationState;
|
||||
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::flash_store::FlashStore;
|
||||
use creaturedex::peripherals::storage::store::Store;
|
||||
use creaturedex::peripherals::storage::wifistore::WifiStore;
|
||||
use embassy_executor::Spawner;
|
||||
use embedded_graphics::pixelcolor::BinaryColor;
|
||||
use embedded_graphics::{
|
||||
@@ -36,20 +40,17 @@ 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 = 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>
|
||||
esp_bootloader_esp_idf::esp_app_desc!();
|
||||
@@ -121,24 +122,37 @@ async fn main(spawner: Spawner) {
|
||||
);
|
||||
}
|
||||
|
||||
let flash_store = Box::leak(Box::new(
|
||||
FlashStore::new(esp_peripherals.FLASH).expect("Could not initialize Flash Store"),
|
||||
let storage = esp_storage::FlashStorage::new(esp_peripherals.FLASH);
|
||||
|
||||
let nvs = Arc::new(Mutex::new(
|
||||
esp_nvs::Nvs::new(NVS_PARTITION_OFFSET, NVS_PARTITION_SIZE, storage)
|
||||
.expect("failed to create nvs"),
|
||||
));
|
||||
|
||||
let card_store = CardStore::new(flash_store)
|
||||
let wifi_store = WifiStore::new(nvs.clone())
|
||||
.await
|
||||
.expect("Could not initialize WiFi store");
|
||||
|
||||
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 {
|
||||
flash_store,
|
||||
card_store,
|
||||
wifi_store,
|
||||
};
|
||||
let rtc = Rtc::new(esp_peripherals.LPWR);
|
||||
//setup_wifi(peripherals.WIFI, peripherals.FLASH, &spawner).await;
|
||||
|
||||
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));
|
||||
@@ -163,7 +177,7 @@ async fn main(spawner: Spawner) {
|
||||
display_shit(&mut secondaries[2], "baz 1");
|
||||
display_shit_prim(&mut primary, "Hello World");
|
||||
|
||||
let outputs = {
|
||||
let outputs = Box::leak(Box::new(Mutex::new({
|
||||
let [sec_1, sec_2, sec_3] = secondaries;
|
||||
Outputs {
|
||||
primary_display: primary,
|
||||
@@ -173,13 +187,22 @@ async fn main(spawner: Spawner) {
|
||||
tertiary_display: lcd,
|
||||
_led_a: (),
|
||||
}
|
||||
};
|
||||
})));
|
||||
|
||||
let navigation_state = Box::leak(Box::new(Mutex::new(NavigationState::new())));
|
||||
|
||||
log::info!("Setup complete, entering main loop");
|
||||
spawner.spawn(navigation::run(inputs, outputs, peripherals).expect("run task failed"));
|
||||
spawner.spawn(
|
||||
background_tasks::nfc_scanner(nfc_driver, peripherals).expect("nfc scanner task failed"),
|
||||
navigation::run(inputs, outputs, peripherals, navigation_state).expect("run task failed"),
|
||||
);
|
||||
spawner.spawn(
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use base64::prelude::*;
|
||||
use core::fmt::Display;
|
||||
use esp_nvs::Key;
|
||||
|
||||
use alloc::{string::String, vec::Vec};
|
||||
use num_enum::FromPrimitive;
|
||||
@@ -22,6 +24,38 @@ pub struct RawCard {
|
||||
pub _padding: [u8; 2],
|
||||
}
|
||||
|
||||
impl Default for RawCard {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
event_encoding: Default::default(),
|
||||
card_type: Default::default(),
|
||||
card_uuid: Default::default(),
|
||||
_reserved: Default::default(),
|
||||
sprite: [0; 722],
|
||||
packed_card_text: [0; 54],
|
||||
secret: Default::default(),
|
||||
_opaque_trailer: [0; 49],
|
||||
_padding: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RawCard {
|
||||
pub fn get_uuid(&self) -> u32 {
|
||||
((u16::from_ne_bytes(self.event_encoding) as u32) << 16)
|
||||
| (u16::from_ne_bytes(self.card_uuid) as u32)
|
||||
}
|
||||
|
||||
pub fn get_nvs_key(&self) -> Key {
|
||||
let uuid = self.get_uuid();
|
||||
Self::nvs_key_from_uuid(uuid)
|
||||
}
|
||||
|
||||
pub fn nvs_key_from_uuid(uuid: u32) -> Key {
|
||||
let base64 = BASE64_STANDARD.encode(uuid.to_ne_bytes());
|
||||
Key::from_str(&base64)
|
||||
}
|
||||
}
|
||||
static_assertions::const_assert!(RawCard::SERIALIZED_SIZE.is_multiple_of(4));
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, FromPrimitive)]
|
||||
|
||||
@@ -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
|
||||
|
||||
+71
-1
@@ -1,5 +1,6 @@
|
||||
#![no_std]
|
||||
#![feature(vec_into_chunks)]
|
||||
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
@@ -12,3 +13,72 @@ pub mod navigation;
|
||||
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) {}
|
||||
|
||||
/// 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
|
||||
/// loop "forever"), there will be a matching call to `_embassy_trace_task_end`.
|
||||
///
|
||||
/// Tasks start life in the SPAWNED state.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn _embassy_trace_task_new(executor_id: u32, task_id: u32) {
|
||||
log::debug!("Started new task on executer 0x{executor_id:x} with id 0x{task_id:x}")
|
||||
}
|
||||
|
||||
/// This callback is called AFTER a task is destructed/freed. This will always
|
||||
/// have a prior matching call to `_embassy_trace_task_new`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn _embassy_trace_task_end(executor_id: u32, task_id: u32) {
|
||||
log::debug!("Ended task on executer 0x{executor_id:x} with id 0x{task_id:x}")
|
||||
}
|
||||
|
||||
/// This callback is called AFTER a task has been dequeued from the runqueue,
|
||||
/// and BEFORE the task is polled. There will always be a matching call to
|
||||
/// `_embassy_trace_task_exec_end`.
|
||||
///
|
||||
/// 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) {}
|
||||
|
||||
/// This callback is called AFTER a task has completed polling. There will
|
||||
/// always be a matching call to `_embassy_trace_task_exec_begin`.
|
||||
///
|
||||
/// This marks the TASK state transition from either:
|
||||
/// * RUNNING -> IDLE - if there were no `_embassy_trace_task_ready_begin` events
|
||||
/// for this task since the last `_embassy_trace_task_exec_begin` for THIS task
|
||||
/// * RUNNING -> WAITING - if there WAS a `_embassy_trace_task_ready_begin` event
|
||||
/// for this task since the last `_embassy_trace_task_exec_begin` for THIS task
|
||||
///
|
||||
/// This marks the EXECUTOR state transition from POLLING -> SCHEDULING
|
||||
#[unsafe(no_mangle)]
|
||||
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.
|
||||
///
|
||||
/// If the given task is currently RUNNING, this marks no state change, BUT the
|
||||
/// RUNNING task will then move to the WAITING stage when polling is complete.
|
||||
///
|
||||
/// If the given task is currently IDLE, this marks the TASK state transition
|
||||
/// from IDLE -> WAITING.
|
||||
///
|
||||
/// 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) {}
|
||||
|
||||
/// 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
|
||||
/// `_embassy_trace_executor_idle`.
|
||||
///
|
||||
///
|
||||
/// This marks the EXECUTOR state transition from SCHEDULING -> IDLE
|
||||
///
|
||||
#[unsafe(no_mangle)]
|
||||
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;
|
||||
|
||||
@@ -41,43 +39,56 @@ pub trait Navigable {
|
||||
fn handle_input(&self, input: Action) -> impl core::future::Future<Output = NewState> + Send;
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
pub async fn run(mut inputs: Inputs, mut outputs: Outputs, peripherals: &'static Peripherals) {
|
||||
async fn display_error(
|
||||
pub async fn display_error(
|
||||
error: String,
|
||||
state: &mut NavigationState,
|
||||
outputs: &mut Outputs,
|
||||
navigation_state: &Mutex<NavigationState>,
|
||||
outputs: &Mutex<Outputs>,
|
||||
peripherals: &Peripherals,
|
||||
) -> () {
|
||||
) -> () {
|
||||
let error_view = ErrorView {
|
||||
error: error.to_string(),
|
||||
};
|
||||
let mut state = navigation_state.lock().await;
|
||||
state.screens.push(View::Error(error_view));
|
||||
let mut outs = outputs.lock().await;
|
||||
state
|
||||
.screens
|
||||
.last()
|
||||
// Unwrap: we just pushed the state
|
||||
.unwrap()
|
||||
.display(outputs, peripherals)
|
||||
.display(&mut outs, peripherals)
|
||||
.await
|
||||
// Unwrap: display will panic on error in error view
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
pub async fn run(
|
||||
mut inputs: Inputs,
|
||||
outputs: &'static Mutex<Outputs>,
|
||||
peripherals: &'static Peripherals,
|
||||
navigation_state: &'static Mutex<NavigationState>,
|
||||
) {
|
||||
log::info!("starting navigation");
|
||||
|
||||
let mut state = NavigationState::new();
|
||||
if let Err(error) = state
|
||||
{
|
||||
let mut outs = outputs.lock().await;
|
||||
if let Err(error) = navigation_state
|
||||
.lock()
|
||||
.await
|
||||
.screens
|
||||
.last()
|
||||
.unwrap()
|
||||
.display(&mut outputs, peripherals)
|
||||
.display(&mut outs, peripherals)
|
||||
.await
|
||||
{
|
||||
display_error(error.to_string(), &mut state, &mut outputs, peripherals).await;
|
||||
display_error(error.to_string(), navigation_state, outputs, peripherals).await;
|
||||
};
|
||||
}
|
||||
|
||||
loop {
|
||||
Timer::after(Duration::from_millis(DEBOUNCE_DURATION_MILLIS)).await;
|
||||
let mut state = navigation_state.lock().await;
|
||||
let selection = select(
|
||||
inputs.wait_for_press(),
|
||||
Timer::after(Duration::from_millis(DEBOUNCE_DURATION_MILLIS)),
|
||||
@@ -120,17 +131,16 @@ pub async fn run(mut inputs: Inputs, mut outputs: Outputs, peripherals: &'static
|
||||
}
|
||||
state.screens.push(new_state.view);
|
||||
|
||||
let mut outs = outputs.lock().await;
|
||||
if (action != Action::Timer || new_state.redraw)
|
||||
&& let Err(error) = state
|
||||
.screens
|
||||
.last()
|
||||
.unwrap()
|
||||
.display(&mut outputs, peripherals)
|
||||
.display(&mut outs, peripherals)
|
||||
.await
|
||||
{
|
||||
display_error(error.to_string(), &mut state, &mut outputs, peripherals).await;
|
||||
display_error(error.to_string(), navigation_state, outputs, peripherals).await;
|
||||
}
|
||||
|
||||
Timer::after(Duration::from_millis(DEBOUNCE_DURATION_MILLIS)).await;
|
||||
}
|
||||
}
|
||||
|
||||
+177
-41
@@ -1,57 +1,149 @@
|
||||
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>,
|
||||
flash: esp_hal::peripherals::FLASH<'static>,
|
||||
spawner: &Spawner,
|
||||
) {
|
||||
let nvs = esp_hal_wifimanager::Nvs::new(0x9000, 0x6000, flash).unwrap();
|
||||
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();
|
||||
|
||||
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(&nvs), wifi, None).await;
|
||||
|
||||
log::info!("wifi_res: {wifi_res:?}");
|
||||
#[derive(Debug)]
|
||||
pub struct WifiCredentials {
|
||||
pub ssid: String,
|
||||
pub pass: String,
|
||||
}
|
||||
|
||||
#[cfg(feature = "wokwi")]
|
||||
pub async fn setup_wifi(
|
||||
pub static WIFI_CREDENTIALS: Signal<WifiCredentials> = Signal::new();
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Wifi {
|
||||
controller: WifiController<'static>,
|
||||
interfaces: wifi::Interfaces<'static>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum WifiError {
|
||||
Store(WifiStoreError),
|
||||
Radio(esp_radio::wifi::WifiError),
|
||||
NoCredentialsStored,
|
||||
}
|
||||
|
||||
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: esp_hal::peripherals::WIFI<'static>,
|
||||
flash: esp_hal::peripherals::FLASH<'static>,
|
||||
nvs: Arc<Mutex<Nvs>>,
|
||||
spawner: &Spawner,
|
||||
) {
|
||||
) {
|
||||
log::info!("Wokwi mode active: pre-seeding WiFi Manager with Wokwi credentials");
|
||||
|
||||
// Preload connection data so init_wm can connect immediately without AP setup.
|
||||
let nvs = match esp_hal_wifimanager::Nvs::new(0x9000, 0x6000, flash) {
|
||||
Ok(nvs) => nvs,
|
||||
Err(e) => {
|
||||
log::error!("Failed to initialize NVS for Wokwi: {e:?}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
const WIFIMANAGER_NAMESPACE: Key = Key::from_str("wifimanager");
|
||||
const WIFIMANAGER_NVS_KEY: Key = Key::from_str("WIFI_SETUP");
|
||||
|
||||
if let Err(e) = nvs
|
||||
.set(
|
||||
esp_hal_wifimanager::WIFI_NVS_KEY,
|
||||
if let Err(e) = nvs.lock().await.set(
|
||||
&WIFIMANAGER_NAMESPACE,
|
||||
&WIFIMANAGER_NVS_KEY,
|
||||
"{\"ssid\":\"Wokwi-GUEST\",\"psk\":\"\",\"data\":{}}",
|
||||
)
|
||||
.await
|
||||
{
|
||||
) {
|
||||
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"
|
||||
@@ -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>,
|
||||
}
|
||||
|
||||
@@ -1,32 +1,8 @@
|
||||
pub struct MemoryRegion {
|
||||
pub offset: u32,
|
||||
pub size: usize,
|
||||
}
|
||||
use esp_storage::FlashStorage;
|
||||
|
||||
impl MemoryRegion {
|
||||
pub const fn new(offset: u32, size: usize) -> Self {
|
||||
assert!(offset.is_multiple_of(4), "Flash requires 4 bytes alignment");
|
||||
assert!(size.is_multiple_of(4), "Flash requires 4 bytes alignment");
|
||||
Self { offset, size }
|
||||
}
|
||||
|
||||
pub const fn end(&self) -> usize {
|
||||
self.offset as usize + self.size
|
||||
}
|
||||
}
|
||||
|
||||
pub const MAX_FLASH: usize = 16 * 1024 * 1024;
|
||||
|
||||
pub const MAGIC_REGION: MemoryRegion = MemoryRegion::new(0, 4);
|
||||
|
||||
pub const SETTINGS_REGION: MemoryRegion = MemoryRegion::new(MAGIC_REGION.end() as u32, 1024);
|
||||
|
||||
pub const CARDSTORE_REGION: MemoryRegion = MemoryRegion::new(
|
||||
SETTINGS_REGION.end() as u32,
|
||||
MAX_FLASH - SETTINGS_REGION.end(),
|
||||
);
|
||||
pub type Nvs = esp_nvs::Nvs<FlashStorage<'static>>;
|
||||
|
||||
pub mod cardstore;
|
||||
pub mod flash_store;
|
||||
pub mod settings;
|
||||
pub mod store;
|
||||
pub mod wifistore;
|
||||
|
||||
@@ -1,73 +1,25 @@
|
||||
use alloc::collections::BTreeMap;
|
||||
use crate::card::model::RawCard;
|
||||
use crate::peripherals::Mutex;
|
||||
use crate::peripherals::storage::Nvs;
|
||||
use alloc::sync::Arc;
|
||||
use alloc::vec::Vec;
|
||||
use binary_serde::{BinarySerde, DeserializeError, Endianness};
|
||||
use core::error::Error;
|
||||
use core::fmt::Display;
|
||||
use esp_nvs::Key;
|
||||
|
||||
use binary_serde::{BinarySerde, DeserializeError, Endianness};
|
||||
const NVS_NAMESPACE_CARDSTORE: Key = Key::from_str("CARDSTORE");
|
||||
const NVS_NAMESPACE_CARDSTORE_METADATA: Key = Key::from_str("CSMETA");
|
||||
const NVS_NAMESPACE_CARDSTORE_CARDS: Key = Key::from_str("CSCARDS");
|
||||
|
||||
//use crate::card::model::Nfcraw_card;
|
||||
const NVS_CARDSTORE_INITIALIZED_KEY: Key = Key::from_str("INITIALIZED");
|
||||
const NVS_CARDSTORE_CARDCOUNT_KEY: Key = Key::from_str("CARDCOUNT");
|
||||
|
||||
use crate::card::model::RawCard;
|
||||
use crate::peripherals::storage::flash_store::{FlashStore, FlashStoreError};
|
||||
|
||||
use crate::peripherals::storage::{CARDSTORE_REGION, MemoryRegion};
|
||||
|
||||
const MAX_CARDS: usize = 20000;
|
||||
|
||||
pub const COUNT_REGION: MemoryRegion = MemoryRegion::new(CARDSTORE_REGION.offset, size_of::<u32>());
|
||||
|
||||
const ALLOCATION_TABLE_REGION: MemoryRegion = MemoryRegion::new(
|
||||
COUNT_REGION.end() as u32,
|
||||
MAX_CARDS * AllocationTableEntry::SERIALIZED_SIZE,
|
||||
);
|
||||
|
||||
const CARDS_REGION: MemoryRegion = MemoryRegion::new(
|
||||
ALLOCATION_TABLE_REGION.end() as u32,
|
||||
CARDSTORE_REGION.size - ALLOCATION_TABLE_REGION.end(),
|
||||
);
|
||||
|
||||
#[derive(Debug, BinarySerde, PartialEq, Eq, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct AllocationTableEntry {
|
||||
uuid: u32,
|
||||
// this is the numeric offset of the AllocationTableEntry
|
||||
// as well as the card entry in flash memory
|
||||
// size_of::<AllocationTableEntry>() * offset
|
||||
// size_of::<RawCard>() * offset
|
||||
offset: u32,
|
||||
|
||||
creation_date: u64,
|
||||
last_read_date: u64,
|
||||
|
||||
// how often a card has been read by nfc
|
||||
read_count: u32,
|
||||
|
||||
deleted: bool,
|
||||
|
||||
reserved: [u64; 4],
|
||||
_padding: [u8; 3],
|
||||
}
|
||||
|
||||
static_assertions::const_assert!(AllocationTableEntry::SERIALIZED_SIZE.is_multiple_of(4));
|
||||
|
||||
impl AllocationTableEntry {
|
||||
fn new(uuid: u32, offset: u32, timestamp: u64) -> Self {
|
||||
Self {
|
||||
uuid,
|
||||
offset,
|
||||
creation_date: timestamp,
|
||||
last_read_date: timestamp,
|
||||
read_count: 0,
|
||||
deleted: true,
|
||||
reserved: Default::default(),
|
||||
_padding: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
const NVS_CARDSTORE_DUMMY_KEY: Key = Key::from_str("DUMMY");
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CardStoreError {
|
||||
Store(FlashStoreError),
|
||||
Store(esp_nvs::error::Error),
|
||||
CorruptedEntry(DeserializeError),
|
||||
NoEntry(u32),
|
||||
}
|
||||
@@ -84,8 +36,8 @@ impl Display for CardStoreError {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FlashStoreError> for CardStoreError {
|
||||
fn from(error: FlashStoreError) -> CardStoreError {
|
||||
impl From<esp_nvs::error::Error> for CardStoreError {
|
||||
fn from(error: esp_nvs::error::Error) -> CardStoreError {
|
||||
CardStoreError::Store(error)
|
||||
}
|
||||
}
|
||||
@@ -96,140 +48,256 @@ impl From<DeserializeError> for CardStoreError {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, BinarySerde, PartialEq, Eq, Clone)]
|
||||
pub struct CardStoreMetaData {
|
||||
pub creation_date: u64,
|
||||
pub last_read_date: u64,
|
||||
|
||||
// how often a card has been read by nfc
|
||||
pub read_count: u32,
|
||||
}
|
||||
|
||||
impl CardStoreMetaData {
|
||||
fn new(creation_date: u64) -> Self {
|
||||
Self {
|
||||
creation_date,
|
||||
last_read_date: creation_date,
|
||||
read_count: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CardStore {
|
||||
store: &'static FlashStore,
|
||||
count: u32,
|
||||
pub allocation_table: BTreeMap<u32, AllocationTableEntry>,
|
||||
nvs: Arc<Mutex<Nvs>>,
|
||||
}
|
||||
|
||||
impl CardStore {
|
||||
pub async fn new(store: &'static FlashStore) -> Result<Self, CardStoreError> {
|
||||
let mut count_bytes: [u8; COUNT_REGION.size] = [0; COUNT_REGION.size];
|
||||
|
||||
store.read(COUNT_REGION.offset, &mut count_bytes).await?;
|
||||
|
||||
let count: u32 = u32::from_ne_bytes(count_bytes);
|
||||
|
||||
log::info!("Found {count} cards in flash.");
|
||||
|
||||
let mut allocation_table_entries: Vec<u8> =
|
||||
Vec::with_capacity(AllocationTableEntry::SERIALIZED_SIZE * count as usize);
|
||||
|
||||
store
|
||||
.read(
|
||||
ALLOCATION_TABLE_REGION.offset,
|
||||
&mut allocation_table_entries,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let chunks =
|
||||
allocation_table_entries.into_chunks::<{ AllocationTableEntry::SERIALIZED_SIZE }>();
|
||||
|
||||
let mut allocation_table = BTreeMap::<u32, AllocationTableEntry>::new();
|
||||
for chunk in chunks {
|
||||
let allocation_table_entry =
|
||||
AllocationTableEntry::binary_deserialize(chunk.as_ref(), Endianness::Little)?;
|
||||
allocation_table.insert(allocation_table_entry.uuid, allocation_table_entry);
|
||||
pub async fn new(nvs: Arc<Mutex<Nvs>>) -> Result<Self, CardStoreError> {
|
||||
if !Self::is_initialized(&nvs).await? {
|
||||
log::info!("CardStore has not been initialized");
|
||||
Self::initialize(&nvs).await?;
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
store,
|
||||
count,
|
||||
allocation_table,
|
||||
})
|
||||
log::info!("CardStore has been initialized");
|
||||
let card_count = nvs
|
||||
.lock()
|
||||
.await
|
||||
.get::<u32>(&NVS_NAMESPACE_CARDSTORE, &NVS_CARDSTORE_CARDCOUNT_KEY)?;
|
||||
log::info!("Cards stored in flash: {card_count}");
|
||||
|
||||
Ok(Self { nvs })
|
||||
}
|
||||
|
||||
pub async fn get_card_by_uuid(&self, uuid: u32) -> Result<RawCard, CardStoreError> {
|
||||
let entry = self
|
||||
.allocation_table
|
||||
.get(&uuid)
|
||||
.ok_or(CardStoreError::NoEntry(uuid))?;
|
||||
async fn is_initialized(nvs: &Mutex<Nvs>) -> Result<bool, CardStoreError> {
|
||||
log::info!("check initialization");
|
||||
let mut nvs_lock = nvs.lock().await;
|
||||
match nvs_lock.get::<bool>(&NVS_NAMESPACE_CARDSTORE, &NVS_CARDSTORE_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()),
|
||||
}
|
||||
}
|
||||
|
||||
let mut raw_card: [u8; size_of::<RawCard>()] = [0; size_of::<RawCard>()];
|
||||
self.store.read(entry.offset, &mut raw_card).await?;
|
||||
// initializing cardstore with 0 cards, so that all namespaces exist and there
|
||||
// are only keynotfound errors in the future
|
||||
async fn initialize(nvs: &Mutex<Nvs>) -> Result<(), CardStoreError> {
|
||||
log::info!("initializing card store");
|
||||
|
||||
Ok(RawCard::binary_deserialize(
|
||||
raw_card.as_ref(),
|
||||
Endianness::Little,
|
||||
)?)
|
||||
Self::delete_all_cards(nvs).await?;
|
||||
|
||||
let mut nvs_lock = nvs.lock().await;
|
||||
|
||||
log::debug!("initialization: write card count");
|
||||
// initialize card count
|
||||
nvs_lock.set::<u32>(&NVS_NAMESPACE_CARDSTORE, &NVS_CARDSTORE_CARDCOUNT_KEY, 0)?;
|
||||
|
||||
// initialize card namespace
|
||||
let dummy_card = RawCard::default();
|
||||
let mut carddata_serialized: [u8; RawCard::SERIALIZED_SIZE] = [0; RawCard::SERIALIZED_SIZE];
|
||||
dummy_card.binary_serialize(&mut carddata_serialized, Endianness::Little);
|
||||
|
||||
log::debug!("initialization: write dummy card");
|
||||
nvs_lock.set::<&[u8]>(
|
||||
&NVS_NAMESPACE_CARDSTORE_CARDS,
|
||||
&NVS_CARDSTORE_DUMMY_KEY,
|
||||
&carddata_serialized,
|
||||
)?;
|
||||
|
||||
// initialize metadata namespace
|
||||
log::debug!("initialization: write dummy metadata");
|
||||
let dummy_metadata = CardStoreMetaData::new(0);
|
||||
|
||||
let mut metadata_serialized: [u8; CardStoreMetaData::SERIALIZED_SIZE] =
|
||||
[0; CardStoreMetaData::SERIALIZED_SIZE];
|
||||
|
||||
dummy_metadata.binary_serialize(&mut metadata_serialized, Endianness::Little);
|
||||
|
||||
nvs_lock.set::<&[u8]>(
|
||||
&NVS_NAMESPACE_CARDSTORE_METADATA,
|
||||
&NVS_CARDSTORE_DUMMY_KEY,
|
||||
&metadata_serialized,
|
||||
)?;
|
||||
|
||||
// set initialized
|
||||
log::debug!("initialization: write initialized");
|
||||
nvs_lock.set::<bool>(
|
||||
&NVS_NAMESPACE_CARDSTORE,
|
||||
&NVS_CARDSTORE_INITIALIZED_KEY,
|
||||
true,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete_all_cards(nvs: &Mutex<Nvs>) -> Result<(), CardStoreError> {
|
||||
log::info!("delete all cards");
|
||||
let mut nvs_lock = nvs.lock().await;
|
||||
let keys = nvs_lock.keys().collect::<Result<Vec<_>, _>>()?;
|
||||
for (namespace, key) in keys {
|
||||
if namespace == NVS_NAMESPACE_CARDSTORE || namespace == NVS_NAMESPACE_CARDSTORE_METADATA
|
||||
{
|
||||
nvs_lock.delete(&namespace, &key)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn load_card_count(&self) -> Result<u32, CardStoreError> {
|
||||
log::debug!("load card count");
|
||||
let mut nvs_lock = self.nvs.lock().await;
|
||||
let result = nvs_lock.get::<u32>(&NVS_NAMESPACE_CARDSTORE, &NVS_CARDSTORE_CARDCOUNT_KEY)?;
|
||||
log::debug!("card count: {result}");
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn load_raw_card(&self, uuid: u32) -> Result<Option<RawCard>, CardStoreError> {
|
||||
log::debug!("load raw card\nuuid: 0x{uuid:x}");
|
||||
let nvs_key = RawCard::nvs_key_from_uuid(uuid);
|
||||
let mut nvs_lock = self.nvs.lock().await;
|
||||
|
||||
let carddata_binary: Vec<u8> = match nvs_lock.get(&NVS_NAMESPACE_CARDSTORE_CARDS, &nvs_key)
|
||||
{
|
||||
Ok(carddata) => carddata,
|
||||
Err(esp_nvs::error::Error::KeyNotFound) => return Ok(None),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
let carddata = RawCard::binary_deserialize(carddata_binary.as_ref(), Endianness::Little)?;
|
||||
Ok(Some(carddata))
|
||||
}
|
||||
|
||||
async fn write_card(&self, nvs_key: Key, card: &RawCard) -> Result<(), CardStoreError> {
|
||||
log::debug!("writing card...\nkey: {nvs_key:?}");
|
||||
let mut carddata_serialized: [u8; RawCard::SERIALIZED_SIZE] = [0; RawCard::SERIALIZED_SIZE];
|
||||
card.binary_serialize(&mut carddata_serialized, Endianness::Little);
|
||||
|
||||
self.nvs.lock().await.set::<&[u8]>(
|
||||
&NVS_NAMESPACE_CARDSTORE_CARDS,
|
||||
&nvs_key,
|
||||
&carddata_serialized,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update_card_metadata(
|
||||
&self,
|
||||
nvs_key: Key,
|
||||
timestamp: u64,
|
||||
) -> Result<bool, CardStoreError> {
|
||||
log::debug!("updating card metadata...\nkey: {nvs_key:?}\ntimestamp: {timestamp}");
|
||||
let mut is_new = false;
|
||||
// update metadata
|
||||
let metadata: CardStoreMetaData =
|
||||
if let Some(mut metadata) = self.load_card_metadata(nvs_key).await? {
|
||||
log::debug!("found existing card");
|
||||
metadata.last_read_date = timestamp;
|
||||
metadata.read_count += 1;
|
||||
metadata
|
||||
} else {
|
||||
log::debug!("new card");
|
||||
is_new = true;
|
||||
CardStoreMetaData::new(timestamp)
|
||||
};
|
||||
|
||||
let mut metadata_serialized: [u8; CardStoreMetaData::SERIALIZED_SIZE] =
|
||||
[0; CardStoreMetaData::SERIALIZED_SIZE];
|
||||
|
||||
metadata.binary_serialize(&mut metadata_serialized, Endianness::Little);
|
||||
|
||||
self.nvs.lock().await.set::<&[u8]>(
|
||||
&NVS_NAMESPACE_CARDSTORE_METADATA,
|
||||
&nvs_key,
|
||||
&metadata_serialized,
|
||||
)?;
|
||||
|
||||
Ok(is_new)
|
||||
}
|
||||
|
||||
async fn increment_card_count(&self) -> Result<(), CardStoreError> {
|
||||
log::debug!("incrementing card count");
|
||||
let card_count: u32 = self.load_card_count().await?;
|
||||
log::debug!("previous card count: {card_count}");
|
||||
self.nvs.lock().await.set::<u32>(
|
||||
&NVS_NAMESPACE_CARDSTORE,
|
||||
&NVS_CARDSTORE_CARDCOUNT_KEY,
|
||||
card_count + 1,
|
||||
)?;
|
||||
|
||||
let card_count = self
|
||||
.nvs
|
||||
.lock()
|
||||
.await
|
||||
.get::<u32>(&NVS_NAMESPACE_CARDSTORE, &NVS_CARDSTORE_CARDCOUNT_KEY)?;
|
||||
log::info!("Cards stored in flash: {card_count}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn save_raw_card(
|
||||
&mut self,
|
||||
raw_card: RawCard,
|
||||
&self,
|
||||
card: &RawCard,
|
||||
timestamp: u64,
|
||||
) -> Result<(), CardStoreError> {
|
||||
let uuid: u32 = (u16::from_ne_bytes(raw_card.event_encoding) as u32) << 16
|
||||
| (u16::from_ne_bytes(raw_card.card_uuid) as u32);
|
||||
log::info!("Saving card with uuid {:x}", uuid);
|
||||
log::debug!("saving raw card\ntimestamp: {timestamp}");
|
||||
let nvs_key = card.get_nvs_key();
|
||||
|
||||
// check if we already got the card
|
||||
// if not find the next deleted entry,
|
||||
// if none create a new one at the end
|
||||
let (entry, is_new) = match self.allocation_table.get_mut(&uuid) {
|
||||
Some(entry) => {
|
||||
log::debug!("old entry");
|
||||
(entry, false)
|
||||
}
|
||||
None => match self
|
||||
.allocation_table
|
||||
.values_mut()
|
||||
.find(|entry| entry.deleted)
|
||||
{
|
||||
Some(entry) => {
|
||||
log::debug!("deleted entry");
|
||||
(entry, true)
|
||||
}
|
||||
None => {
|
||||
log::debug!("new entry");
|
||||
let entry = AllocationTableEntry::new(uuid, self.count + 1, timestamp);
|
||||
self.allocation_table.insert(uuid, entry);
|
||||
(
|
||||
self.allocation_table
|
||||
.get_mut(&uuid)
|
||||
.expect("entry was just inserted"),
|
||||
true,
|
||||
)
|
||||
}
|
||||
},
|
||||
};
|
||||
self.write_card(nvs_key, card).await?;
|
||||
|
||||
// only write card data if it is new. else it is already written in flash
|
||||
if is_new {
|
||||
log::debug!("writing RawCard to flash");
|
||||
let mut serialized_card: [u8; RawCard::SERIALIZED_SIZE] = [0; RawCard::SERIALIZED_SIZE];
|
||||
raw_card.binary_serialize(&mut serialized_card, Endianness::Little);
|
||||
self.store
|
||||
.write_erase(
|
||||
CARDS_REGION.offset + entry.offset * RawCard::SERIALIZED_SIZE as u32,
|
||||
&mut serialized_card,
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
entry.last_read_date = timestamp;
|
||||
entry.read_count += 1;
|
||||
let new_card = self.update_card_metadata(nvs_key, timestamp).await?;
|
||||
|
||||
if new_card {
|
||||
self.increment_card_count().await?;
|
||||
}
|
||||
|
||||
entry.deleted = false;
|
||||
|
||||
log::debug!("writing AllocationTableEntry to flash");
|
||||
let mut serialized_entry: [u8; AllocationTableEntry::SERIALIZED_SIZE] =
|
||||
[0; AllocationTableEntry::SERIALIZED_SIZE];
|
||||
entry.binary_serialize(&mut serialized_entry, Endianness::Little);
|
||||
self.store
|
||||
.write_erase(
|
||||
ALLOCATION_TABLE_REGION.offset
|
||||
+ entry.offset * AllocationTableEntry::SERIALIZED_SIZE as u32,
|
||||
&mut serialized_entry,
|
||||
)
|
||||
.await?;
|
||||
|
||||
self.count += 1;
|
||||
log::debug!("writing card count to flash");
|
||||
let mut serialized_count: [u8; 4] = self.count.to_le_bytes();
|
||||
self.store
|
||||
.write(COUNT_REGION.offset, serialized_count.as_mut_slice())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn load_card_metadata(
|
||||
&self,
|
||||
nvs_key: Key,
|
||||
) -> Result<Option<CardStoreMetaData>, CardStoreError> {
|
||||
log::debug!("load card meta data\nkey: {nvs_key:?}");
|
||||
let mut nvs_lock = self.nvs.lock().await;
|
||||
let metadata_binary: Vec<u8> =
|
||||
match nvs_lock.get(&NVS_NAMESPACE_CARDSTORE_METADATA, &nvs_key) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(esp_nvs::error::Error::KeyNotFound) => return Ok(None),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
let metadata =
|
||||
CardStoreMetaData::binary_deserialize(metadata_binary.as_ref(), Endianness::Little)?;
|
||||
|
||||
Ok(Some(metadata))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,108 +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 {
|
||||
use core::fmt::Debug;
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
const FLASH_ADDR: u32 = 0x9000;
|
||||
|
||||
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;
|
||||
lock.erase(FLASH_ADDR + offset, FLASH_ADDR + bytes.len() as u32)?;
|
||||
lock.write(FLASH_ADDR + offset, 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,7 +1,7 @@
|
||||
use crate::peripherals::storage::cardstore::CardStore;
|
||||
use crate::peripherals::storage::flash_store::FlashStore;
|
||||
use crate::peripherals::storage::wifistore::WifiStore;
|
||||
|
||||
pub struct Store {
|
||||
pub flash_store: &'static FlashStore,
|
||||
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(())
|
||||
}
|
||||
}
|
||||
+12
-3
@@ -34,6 +34,15 @@ impl Navigable for ErrorView {
|
||||
_: &Peripherals,
|
||||
) -> impl core::future::Future<Output = Result<(), Box<dyn error::Error>>> + Send {
|
||||
async move {
|
||||
outputs
|
||||
.primary_display
|
||||
.clear(Rgb565::BLACK)
|
||||
.unwrap_or_else(|error| {
|
||||
panic!(
|
||||
"Error: {error:?}\nDraw error while rendering ErrorView: {}",
|
||||
self.error
|
||||
)
|
||||
});
|
||||
let style = MonoTextStyle::new(&FONT_10X20, Rgb565::RED);
|
||||
let display_area = outputs.primary_display.bounding_box();
|
||||
Text::new(
|
||||
@@ -44,7 +53,7 @@ impl Navigable for ErrorView {
|
||||
.draw(&mut outputs.primary_display)
|
||||
.unwrap_or_else(|error| {
|
||||
panic!(
|
||||
"Error: {error:?}\nDraw error while rendering error: {}",
|
||||
"Error: {error:?}\nDraw error while rendering ErrorView: {}",
|
||||
self.error
|
||||
)
|
||||
});
|
||||
@@ -55,13 +64,13 @@ impl Navigable for ErrorView {
|
||||
.alignment(HorizontalAlignment::Center)
|
||||
.build();
|
||||
|
||||
let bounds = Rectangle::new(Point::new(0, 30), display_area.size);
|
||||
let bounds = Rectangle::new(Point::new(0, 50), display_area.size);
|
||||
|
||||
TextBox::with_textbox_style(&self.error.to_string(), bounds, style, textbox_style)
|
||||
.draw(&mut outputs.primary_display)
|
||||
.unwrap_or_else(|error| {
|
||||
panic!(
|
||||
"Error: {error:?}\nDraw error while rendering error: {}",
|
||||
"Error: {error:?}\nDraw error while rendering ErrorView: {}",
|
||||
self.error
|
||||
)
|
||||
});
|
||||
|
||||
@@ -4,8 +4,6 @@ use crate::navigation::navigation::Navigable;
|
||||
use crate::navigation::navigation::NewState;
|
||||
use crate::navigation::outputs::Outputs;
|
||||
use crate::peripherals::Peripherals;
|
||||
use crate::peripherals::storage::MAGIC_REGION;
|
||||
use crate::peripherals::storage::cardstore::COUNT_REGION;
|
||||
use crate::views::view::View;
|
||||
use alloc::boxed::Box;
|
||||
use core::error;
|
||||
@@ -34,41 +32,33 @@ impl Navigable for FlashInfoView {
|
||||
peripherals: &Peripherals,
|
||||
) -> impl core::future::Future<Output = Result<(), Box<dyn error::Error>>> + Send {
|
||||
async move {
|
||||
outputs
|
||||
.primary_display
|
||||
.clear(Rgb565::BLACK)
|
||||
.map_err(PrimaryDisplayError::from)?;
|
||||
let _style = MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE);
|
||||
let mut magic_bytes: [u8; MAGIC_REGION.size] = [0; MAGIC_REGION.size];
|
||||
peripherals
|
||||
.store
|
||||
.lock()
|
||||
.await
|
||||
.flash_store
|
||||
.read(MAGIC_REGION.offset, &mut magic_bytes)
|
||||
.await?;
|
||||
let mut card_count_bytes: [u8; COUNT_REGION.size] = [0; COUNT_REGION.size];
|
||||
peripherals
|
||||
.store
|
||||
.lock()
|
||||
.await
|
||||
.flash_store
|
||||
.read(COUNT_REGION.offset, &mut card_count_bytes)
|
||||
.await?;
|
||||
|
||||
let style = MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE);
|
||||
let textbox_style = TextBoxStyleBuilder::new()
|
||||
.height_mode(HeightMode::FitToText)
|
||||
.alignment(HorizontalAlignment::Center)
|
||||
.alignment(HorizontalAlignment::Justified)
|
||||
.build();
|
||||
|
||||
let display_area = outputs.primary_display.bounding_box();
|
||||
let bounds = Rectangle::new(Point::new(0, 30), display_area.size);
|
||||
|
||||
log::debug!("locking store");
|
||||
let store = peripherals.store.lock().await;
|
||||
|
||||
log::debug!("getting card count");
|
||||
let card_count = store.card_store.load_card_count().await?;
|
||||
|
||||
TextBox::with_textbox_style(
|
||||
&format!(
|
||||
"
|
||||
Flash Init Magic: 0x{:x}\n
|
||||
Card Count: {}\n
|
||||
",
|
||||
u32::from_le_bytes(magic_bytes),
|
||||
u32::from_le_bytes(card_count_bytes)
|
||||
card_count
|
||||
),
|
||||
bounds,
|
||||
style,
|
||||
|
||||
@@ -12,7 +12,7 @@ use embedded_graphics::pixelcolor::Rgb565;
|
||||
use embedded_graphics::prelude::RgbColor;
|
||||
use embedded_graphics_core::draw_target::DrawTarget;
|
||||
|
||||
pub const MAX_SELECTED: i32 = 2;
|
||||
pub const MAX_SELECTED: i32 = 3;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SettingsMenu {
|
||||
@@ -27,7 +27,9 @@ impl Navigable for SettingsMenu {
|
||||
) -> impl core::future::Future<Output = Result<(), Box<dyn error::Error>>> + Send {
|
||||
async move {
|
||||
let display = &mut outputs.primary_display;
|
||||
display.clear(Rgb565::BLACK).unwrap();
|
||||
display
|
||||
.clear(Rgb565::BLACK)
|
||||
.map_err(PrimaryDisplayError::from)?;
|
||||
menu_item::show(display, "System Inforation", 0, self.selected)
|
||||
.map_err(PrimaryDisplayError::from)?;
|
||||
menu_item::show(display, "Wifi Information", 1, self.selected)
|
||||
|
||||
+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