Compare commits
10
Commits
a77b7761cd
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab7b9401a5 | ||
|
|
4f251de3d5 | ||
|
|
ffc5899c33 | ||
|
|
47b539f364 | ||
|
|
fafb4fc34f
|
||
|
|
4d9cd05f72 | ||
|
|
240e2b081d | ||
|
|
0aa1370a2b | ||
|
|
b814c61f45 | ||
|
|
290758d203 |
+1
-1
@@ -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
+80
-1652
File diff suppressed because it is too large
Load Diff
+10
-6
@@ -28,14 +28,10 @@ log = "0.4.27"
|
|||||||
|
|
||||||
critical-section = "1.2.0"
|
critical-section = "1.2.0"
|
||||||
embedded-io = "0.7.1"
|
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-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/InvisibleUSA/esp-hal-wifimanager", 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"
|
||||||
@@ -46,7 +42,7 @@ embedded-graphics-core = "0.4.1"
|
|||||||
base64 = { version = "0.23.1", default-features = false, features = ["alloc"] }
|
base64 = { version = "0.23.1", default-features = false, features = ["alloc"] }
|
||||||
pn532 = "0.5.0"
|
pn532 = "0.5.0"
|
||||||
num_enum = { version = "0.7.6", default-features = false }
|
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"
|
embedded-hal-async = "1.0.0"
|
||||||
i2c-character-display = "0.5.1"
|
i2c-character-display = "0.5.1"
|
||||||
ch1115 = { version = "0.1.2", features = ["graphics"] }
|
ch1115 = { version = "0.1.2", features = ["graphics"] }
|
||||||
@@ -55,6 +51,13 @@ embedded-storage = "0.3.1"
|
|||||||
binary_serde = "1.0.25"
|
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-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"
|
||||||
@@ -83,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"
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
+2
-2
@@ -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();
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ 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);
|
||||||
|
|
||||||
|
if (pin_header)
|
||||||
position(BOTTOM + LEFT)
|
position(BOTTOM + LEFT)
|
||||||
xrot(180)
|
xrot(180)
|
||||||
pin_header(14, spin=90, anchor=BOTTOM + BACK);
|
pin_header(14, spin=90, anchor=BOTTOM + BACK);
|
||||||
|
|||||||
+220
-6
@@ -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();
|
||||||
|
|||||||
@@ -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
@@ -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,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;
|
||||||
@@ -42,12 +43,13 @@ pub async fn nfc_scanner(
|
|||||||
};
|
};
|
||||||
CARD_DATA.lock().await.replace(card);
|
CARD_DATA.lock().await.replace(card);
|
||||||
|
|
||||||
|
log::debug!("saving card to flash");
|
||||||
match peripherals
|
match peripherals
|
||||||
.store
|
.store
|
||||||
.lock()
|
.lock()
|
||||||
.await
|
.await
|
||||||
.card_store
|
.card_store
|
||||||
.save_raw_card(split_data, peripherals.rtc.current_time_us())
|
.save_raw_card(&split_data, peripherals.rtc.current_time_us())
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(()) => {}
|
Ok(()) => {}
|
||||||
@@ -75,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+37
-17
@@ -8,6 +8,8 @@
|
|||||||
#![deny(clippy::large_stack_frames)]
|
#![deny(clippy::large_stack_frames)]
|
||||||
|
|
||||||
use alloc::boxed::Box;
|
use alloc::boxed::Box;
|
||||||
|
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;
|
||||||
@@ -17,15 +19,16 @@ use creaturedex::drivers::spi_bus;
|
|||||||
use creaturedex::drivers::tertiary_lcd::{
|
use creaturedex::drivers::tertiary_lcd::{
|
||||||
BOX, EMPTY, EXAMPLE, HEART, TertiaryDisplay, TertiaryDisplayPinConfiguration,
|
BOX, EMPTY, EXAMPLE, HEART, TertiaryDisplay, TertiaryDisplayPinConfiguration,
|
||||||
};
|
};
|
||||||
use creaturedex::navigation::navigation::Mutex;
|
|
||||||
use creaturedex::navigation::inputs::Inputs;
|
use creaturedex::navigation::inputs::Inputs;
|
||||||
use creaturedex::navigation::navigation::{self};
|
use creaturedex::navigation::navigation::{self};
|
||||||
use creaturedex::navigation::state::NavigationState;
|
|
||||||
use creaturedex::navigation::outputs::Outputs;
|
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::Peripherals;
|
||||||
use creaturedex::peripherals::storage::cardstore::CardStore;
|
use creaturedex::peripherals::storage::cardstore::CardStore;
|
||||||
use creaturedex::peripherals::storage::flash_store::FlashStore;
|
|
||||||
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::{
|
||||||
@@ -37,20 +40,17 @@ 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 = 0x9000;
|
||||||
|
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>
|
||||||
esp_bootloader_esp_idf::esp_app_desc!();
|
esp_bootloader_esp_idf::esp_app_desc!();
|
||||||
@@ -122,24 +122,37 @@ async fn main(spawner: Spawner) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let flash_store = Box::leak(Box::new(
|
let storage = esp_storage::FlashStorage::new(esp_peripherals.FLASH);
|
||||||
FlashStore::new(esp_peripherals.FLASH).expect("Could not initialize Flash Store"),
|
|
||||||
|
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
|
.await
|
||||||
.expect("Could not initialize Card Store");
|
.expect("Could not initialize Card Store");
|
||||||
|
|
||||||
let store = Store {
|
let store = Store {
|
||||||
flash_store,
|
|
||||||
card_store,
|
card_store,
|
||||||
|
wifi_store,
|
||||||
};
|
};
|
||||||
let rtc = Rtc::new(esp_peripherals.LPWR);
|
let rtc = Rtc::new(esp_peripherals.LPWR);
|
||||||
//setup_wifi(peripherals.WIFI, peripherals.FLASH, &spawner).await;
|
|
||||||
|
|
||||||
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));
|
||||||
@@ -179,10 +192,17 @@ async fn main(spawner: Spawner) {
|
|||||||
let navigation_state = Box::leak(Box::new(Mutex::new(NavigationState::new())));
|
let navigation_state = Box::leak(Box::new(Mutex::new(NavigationState::new())));
|
||||||
|
|
||||||
log::info!("Setup complete, entering main loop");
|
log::info!("Setup complete, entering main loop");
|
||||||
spawner.spawn(navigation::run(inputs, outputs, peripherals, navigation_state).expect("run task failed"));
|
|
||||||
spawner.spawn(
|
spawner.spawn(
|
||||||
background_tasks::nfc_scanner(nfc_driver, outputs, peripherals, navigation_state).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
|
core::future::pending::<()>().await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
|
use base64::prelude::*;
|
||||||
use core::fmt::Display;
|
use core::fmt::Display;
|
||||||
|
use esp_nvs::Key;
|
||||||
|
|
||||||
use alloc::{string::String, vec::Vec};
|
use alloc::{string::String, vec::Vec};
|
||||||
use num_enum::FromPrimitive;
|
use num_enum::FromPrimitive;
|
||||||
@@ -22,6 +24,38 @@ pub struct RawCard {
|
|||||||
pub _padding: [u8; 2],
|
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));
|
static_assertions::const_assert!(RawCard::SERIALIZED_SIZE.is_multiple_of(4));
|
||||||
|
|
||||||
#[derive(Debug, Clone, Eq, PartialEq, FromPrimitive)]
|
#[derive(Debug, Clone, Eq, PartialEq, FromPrimitive)]
|
||||||
|
|||||||
+5
-116
@@ -23,118 +23,9 @@ where
|
|||||||
struct PageParseError<const N: usize> {
|
struct PageParseError<const N: usize> {
|
||||||
iteration: u8,
|
iteration: u8,
|
||||||
bytes: [u8; N],
|
bytes: [u8; N],
|
||||||
status_code: Option<CommandResult>,
|
status_code: Option<pn532::ErrorCode>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
struct CommandResult {
|
|
||||||
/// # WrErr
|
|
||||||
/// Set to logic 1, when data is written into the FIFO by the 80C51 during the AutoColl command or MFAuthent command or
|
|
||||||
/// if data is written into the FIFO by the 80C51 during the time between sending the last bit on the RF interface and
|
|
||||||
/// receiving the last bit on the RF interface.
|
|
||||||
write_error: bool,
|
|
||||||
/// # TempErr
|
|
||||||
/// Set to logic 1, if the internal temperature sensor detects overheating. In this case the antenna drivers are switched off automatically.
|
|
||||||
overheating: bool,
|
|
||||||
/// # RFErr
|
|
||||||
/// Set to logic 1, if in active communication mode the counterpart does not switch on the RF field in time as defined in NFCIP-1 standard.
|
|
||||||
/// Note: RFErr is only used in active communication mode. The bit RxFraming or the bit TxFraming has to be set to 01h to enable
|
|
||||||
/// this functionality.
|
|
||||||
rf_timeout: bool,
|
|
||||||
/// # BufferOvfl
|
|
||||||
/// Set to logic 1, if the 80C51 or if the internal state machine (e.g. receiver) tries to write data into the FIFO buffer
|
|
||||||
/// although the FIFO buffer is already full.
|
|
||||||
buffer_overflow: bool,
|
|
||||||
/// # CollErr
|
|
||||||
/// Set to logic 1, if a bit-collision is detected. It is set to logic 0 automatically at receiver start phase.
|
|
||||||
/// This flag is only valid during the bitwise anticollision at 106 kbit/s. During communication schemes at 212 and 424 kbit/s
|
|
||||||
/// this flag is always set to logic 0.
|
|
||||||
bit_collision: bool,
|
|
||||||
/// # CRCErr
|
|
||||||
/// Set to logic 1, if RxCRCEn in CIU_RxMode register is set to logic 1 and the CRC calculation fails. It is set to logic 0 automatically
|
|
||||||
/// at receiver start-up phase.
|
|
||||||
crc_error: bool,
|
|
||||||
/// # ParityErr
|
|
||||||
/// Set to logic 1, if the parity check has failed. It is set to logic 0 automatically at receiver start-up phase.
|
|
||||||
/// Only valid for ISO/IEC 14443A/MIFARE or NFCIP-1 communication at 106 kbit/s.
|
|
||||||
parity_error: bool,
|
|
||||||
/// # ProtocollErr
|
|
||||||
/// Set to logic 1, if one out of the following cases occurs:
|
|
||||||
/// - Set to logic 1 if the SOF is incorrect. It is set to logic 0 automatically at receiver start-up phase.
|
|
||||||
/// The bit is only valid for 106 kbit in Active and Passive Communication mode.
|
|
||||||
/// - If bit DetectSync in CIU_Mode register is set to logic 1 during FeliCa communication or Active Communication
|
|
||||||
/// with transfer speeds higher than 106 kbit, ProtocolErr is set to logic 1 in case of a byte length violation.
|
|
||||||
/// - During the AutoColl command, ProtocolErr is set to logic 1, if the Initiator bit in CIU_Control register is set to logic 1.
|
|
||||||
/// - During the MFAuthent Command, ProtocolErr is set to logic 1, if the number of bytes received in one data stream is incorrect.
|
|
||||||
/// - Set to logic 1, if the Miller Decoder detects 2 pauses below the minimum time according to the ISO/IEC 14443A definitions.
|
|
||||||
protocol_error: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CommandResult {
|
|
||||||
pub fn is_error(&self) -> bool {
|
|
||||||
self.write_error
|
|
||||||
|| self.overheating
|
|
||||||
|| self.rf_timeout
|
|
||||||
|| self.buffer_overflow
|
|
||||||
|| self.bit_collision
|
|
||||||
|| self.crc_error
|
|
||||||
|| self.parity_error
|
|
||||||
|| self.protocol_error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<u8> for CommandResult {
|
|
||||||
fn from(value: u8) -> Self {
|
|
||||||
let mask = |bit| 1u8 << bit;
|
|
||||||
let take_bit = |bit| (value & mask(bit)) != 0u8;
|
|
||||||
|
|
||||||
Self {
|
|
||||||
write_error: take_bit(7),
|
|
||||||
overheating: take_bit(6),
|
|
||||||
rf_timeout: take_bit(5),
|
|
||||||
buffer_overflow: take_bit(4),
|
|
||||||
bit_collision: take_bit(3),
|
|
||||||
crc_error: take_bit(2),
|
|
||||||
parity_error: take_bit(1),
|
|
||||||
protocol_error: take_bit(0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl core::fmt::Display for CommandResult {
|
|
||||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
|
||||||
if !self.is_error() {
|
|
||||||
return write!(f, "ok");
|
|
||||||
}
|
|
||||||
|
|
||||||
write!(f, "error: ")?;
|
|
||||||
|
|
||||||
let errors = [
|
|
||||||
(self.write_error, "write_error(7)"),
|
|
||||||
(self.overheating, "overheating(6)"),
|
|
||||||
(self.rf_timeout, "rf_timeout(5)"),
|
|
||||||
(self.buffer_overflow, "buffer_overflow(4)"),
|
|
||||||
(self.bit_collision, "bit_collision(3)"),
|
|
||||||
(self.crc_error, "crc_error(2)"),
|
|
||||||
(self.parity_error, "parity_error(1)"),
|
|
||||||
(self.protocol_error, "protocol_error(0)"),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|(active, name)| active.then_some(name));
|
|
||||||
|
|
||||||
let mut first = true;
|
|
||||||
for error in errors {
|
|
||||||
let separator = if !first { ", " } else { "" };
|
|
||||||
write!(f, "{separator}{error}")?;
|
|
||||||
first = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Error for CommandResult {}
|
|
||||||
|
|
||||||
impl<const N: usize> Error for PageParseError<N> {}
|
impl<const N: usize> Error for PageParseError<N> {}
|
||||||
|
|
||||||
impl<const N: usize> core::fmt::Display for PageParseError<N> {
|
impl<const N: usize> core::fmt::Display for PageParseError<N> {
|
||||||
@@ -147,7 +38,7 @@ impl<const N: usize> core::fmt::Display for PageParseError<N> {
|
|||||||
match status_code {
|
match status_code {
|
||||||
Some(code) => write!(
|
Some(code) => write!(
|
||||||
f,
|
f,
|
||||||
"NFC pages parse error in iteration {iteration} with {code}: {bytes:02x?}"
|
"NFC pages parse error in iteration {iteration} with code: {code:?}: {bytes:02x?}"
|
||||||
),
|
),
|
||||||
None => write!(
|
None => write!(
|
||||||
f,
|
f,
|
||||||
@@ -187,7 +78,7 @@ where
|
|||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(uid) => {
|
Ok(uid) => {
|
||||||
info!("PN532 detected NFC target UID: {uid:?}");
|
info!("PN532 detected NFC target UID: 0x{uid:x?}");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -210,7 +101,7 @@ where
|
|||||||
error => Err(PageParseError {
|
error => Err(PageParseError {
|
||||||
iteration,
|
iteration,
|
||||||
bytes: arr,
|
bytes: arr,
|
||||||
status_code: error.copied().map(Into::into),
|
status_code: Some(pn532::ErrorCode::try_from(error.copied().unwrap()).unwrap()),
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -238,16 +129,14 @@ where
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
log::info!("{bytes:x?}");
|
||||||
match Self::parse_nfc_page(i, bytes) {
|
match Self::parse_nfc_page(i, bytes) {
|
||||||
Ok(data) => break data,
|
Ok(data) => break data,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("Parsing page failed: {e}");
|
error!("Parsing page failed: {e}");
|
||||||
if e.status_code.is_some_and(|e| e.protocol_error) {
|
|
||||||
// After protocol error, all subsequent reads will fail, so we can stop trying to read more pages.
|
|
||||||
return Err("Failed to parse NFC page");
|
return Err("Failed to parse NFC page");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
};
|
};
|
||||||
let bytes = if i == 0x0B { &bytes[1..] } else { &bytes };
|
let bytes = if i == 0x0B { &bytes[1..] } else { &bytes };
|
||||||
data.extend(bytes);
|
data.extend(bytes);
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
+71
-1
@@ -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;
|
||||||
|
|
||||||
@@ -12,3 +13,72 @@ pub mod navigation;
|
|||||||
pub mod network;
|
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)]
|
||||||
|
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::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;
|
||||||
|
|
||||||
|
|||||||
+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"))]
|
#[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;
|
||||||
flash: esp_hal::peripherals::FLASH<'static>,
|
use alloc::string::String;
|
||||||
spawner: &Spawner,
|
use core::error::Error;
|
||||||
) {
|
use core::fmt::Display;
|
||||||
let nvs = esp_hal_wifimanager::Nvs::new(0x9000, 0x6000, flash).unwrap();
|
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(&nvs), 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(
|
|
||||||
|
#[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>,
|
wifi: esp_hal::peripherals::WIFI<'static>,
|
||||||
flash: esp_hal::peripherals::FLASH<'static>,
|
nvs: Arc<Mutex<Nvs>>,
|
||||||
spawner: &Spawner,
|
spawner: &Spawner,
|
||||||
) {
|
) {
|
||||||
log::info!("Wokwi mode active: pre-seeding WiFi Manager with Wokwi credentials");
|
log::info!("Wokwi mode active: pre-seeding WiFi Manager with Wokwi credentials");
|
||||||
|
|
||||||
// Preload connection data so init_wm can connect immediately without AP setup.
|
const WIFIMANAGER_NAMESPACE: Key = Key::from_str("wifimanager");
|
||||||
let nvs = match esp_hal_wifimanager::Nvs::new(0x9000, 0x6000, flash) {
|
const WIFIMANAGER_NVS_KEY: Key = Key::from_str("WIFI_SETUP");
|
||||||
Ok(nvs) => nvs,
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to initialize NVS for Wokwi: {e:?}");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Err(e) = nvs
|
if let Err(e) = nvs.lock().await.set(
|
||||||
.set(
|
&WIFIMANAGER_NAMESPACE,
|
||||||
esp_hal_wifimanager::WIFI_NVS_KEY,
|
&WIFIMANAGER_NVS_KEY,
|
||||||
"{\"ssid\":\"Wokwi-GUEST\",\"psk\":\"\",\"data\":{}}",
|
"{\"ssid\":\"Wokwi-GUEST\",\"psk\":\"\",\"data\":{}}",
|
||||||
)
|
) {
|
||||||
.await
|
|
||||||
{
|
|
||||||
log::error!("Failed to store Wokwi WiFi config in NVS: {e:?}");
|
log::error!("Failed to store Wokwi WiFi config in NVS: {e:?}");
|
||||||
return;
|
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();
|
let mut wm_settings = esp_hal_wifimanager::WmSettings::default();
|
||||||
|
|
||||||
// Wokwi simulation uses a default open network called "Wokwi-GUEST"
|
// 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;
|
wm_settings.wifi_conn_timeout = 30000;
|
||||||
|
|
||||||
// Initialize Wi-Fi connection through WiFi Manager using the pre-seeded NVS data.
|
// 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:?}");
|
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;
|
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,32 +1,8 @@
|
|||||||
pub struct MemoryRegion {
|
use esp_storage::FlashStorage;
|
||||||
pub offset: u32,
|
|
||||||
pub size: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MemoryRegion {
|
pub type Nvs = esp_nvs::Nvs<FlashStorage<'static>>;
|
||||||
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 mod cardstore;
|
pub mod cardstore;
|
||||||
pub mod flash_store;
|
|
||||||
pub mod settings;
|
pub mod settings;
|
||||||
pub mod store;
|
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 alloc::vec::Vec;
|
||||||
|
use binary_serde::{BinarySerde, DeserializeError, Endianness};
|
||||||
use core::error::Error;
|
use core::error::Error;
|
||||||
use core::fmt::Display;
|
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;
|
const NVS_CARDSTORE_DUMMY_KEY: Key = Key::from_str("DUMMY");
|
||||||
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(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum CardStoreError {
|
pub enum CardStoreError {
|
||||||
Store(FlashStoreError),
|
Store(esp_nvs::error::Error),
|
||||||
CorruptedEntry(DeserializeError),
|
CorruptedEntry(DeserializeError),
|
||||||
NoEntry(u32),
|
NoEntry(u32),
|
||||||
}
|
}
|
||||||
@@ -84,8 +36,8 @@ impl Display for CardStoreError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<FlashStoreError> for CardStoreError {
|
impl From<esp_nvs::error::Error> for CardStoreError {
|
||||||
fn from(error: FlashStoreError) -> CardStoreError {
|
fn from(error: esp_nvs::error::Error) -> CardStoreError {
|
||||||
CardStoreError::Store(error)
|
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 {
|
pub struct CardStore {
|
||||||
store: &'static FlashStore,
|
nvs: Arc<Mutex<Nvs>>,
|
||||||
count: u32,
|
|
||||||
pub allocation_table: BTreeMap<u32, AllocationTableEntry>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CardStore {
|
impl CardStore {
|
||||||
pub async fn new(store: &'static FlashStore) -> Result<Self, CardStoreError> {
|
pub async fn new(nvs: Arc<Mutex<Nvs>>) -> Result<Self, CardStoreError> {
|
||||||
let mut count_bytes: [u8; COUNT_REGION.size] = [0; COUNT_REGION.size];
|
if !Self::is_initialized(&nvs).await? {
|
||||||
|
log::info!("CardStore has not been initialized");
|
||||||
store.read(COUNT_REGION.offset, &mut count_bytes).await?;
|
Self::initialize(&nvs).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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Self {
|
log::info!("CardStore has been initialized");
|
||||||
store,
|
let card_count = nvs
|
||||||
count,
|
.lock()
|
||||||
allocation_table,
|
.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> {
|
async fn is_initialized(nvs: &Mutex<Nvs>) -> Result<bool, CardStoreError> {
|
||||||
let entry = self
|
log::info!("check initialization");
|
||||||
.allocation_table
|
let mut nvs_lock = nvs.lock().await;
|
||||||
.get(&uuid)
|
match nvs_lock.get::<bool>(&NVS_NAMESPACE_CARDSTORE, &NVS_CARDSTORE_INITIALIZED_KEY) {
|
||||||
.ok_or(CardStoreError::NoEntry(uuid))?;
|
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>()];
|
// initializing cardstore with 0 cards, so that all namespaces exist and there
|
||||||
self.store.read(entry.offset, &mut raw_card).await?;
|
// are only keynotfound errors in the future
|
||||||
|
async fn initialize(nvs: &Mutex<Nvs>) -> Result<(), CardStoreError> {
|
||||||
|
log::info!("initializing card store");
|
||||||
|
|
||||||
Ok(RawCard::binary_deserialize(
|
Self::delete_all_cards(nvs).await?;
|
||||||
raw_card.as_ref(),
|
|
||||||
Endianness::Little,
|
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(
|
pub async fn save_raw_card(
|
||||||
&mut self,
|
&self,
|
||||||
raw_card: RawCard,
|
card: &RawCard,
|
||||||
timestamp: u64,
|
timestamp: u64,
|
||||||
) -> Result<(), CardStoreError> {
|
) -> Result<(), CardStoreError> {
|
||||||
let uuid: u32 = (u16::from_ne_bytes(raw_card.event_encoding) as u32) << 16
|
log::debug!("saving raw card\ntimestamp: {timestamp}");
|
||||||
| (u16::from_ne_bytes(raw_card.card_uuid) as u32);
|
let nvs_key = card.get_nvs_key();
|
||||||
log::info!("Saving card with uuid {:x}", uuid);
|
|
||||||
|
|
||||||
// check if we already got the card
|
self.write_card(nvs_key, card).await?;
|
||||||
// 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,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
// only write card data if it is new. else it is already written in flash
|
let new_card = self.update_card_metadata(nvs_key, timestamp).await?;
|
||||||
if is_new {
|
|
||||||
log::debug!("writing RawCard to flash");
|
if new_card {
|
||||||
let mut serialized_card: [u8; RawCard::SERIALIZED_SIZE] = [0; RawCard::SERIALIZED_SIZE];
|
self.increment_card_count().await?;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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(())
|
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,110 +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 = 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 + offset + 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::cardstore::CardStore;
|
||||||
use crate::peripherals::storage::flash_store::FlashStore;
|
use crate::peripherals::storage::wifistore::WifiStore;
|
||||||
|
|
||||||
pub struct Store {
|
pub struct Store {
|
||||||
pub flash_store: &'static FlashStore,
|
|
||||||
pub card_store: CardStore,
|
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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,8 +4,6 @@ use crate::navigation::navigation::Navigable;
|
|||||||
use crate::navigation::navigation::NewState;
|
use crate::navigation::navigation::NewState;
|
||||||
use crate::navigation::outputs::Outputs;
|
use crate::navigation::outputs::Outputs;
|
||||||
use crate::peripherals::Peripherals;
|
use crate::peripherals::Peripherals;
|
||||||
use crate::peripherals::storage::MAGIC_REGION;
|
|
||||||
use crate::peripherals::storage::cardstore::COUNT_REGION;
|
|
||||||
use crate::views::view::View;
|
use crate::views::view::View;
|
||||||
use alloc::boxed::Box;
|
use alloc::boxed::Box;
|
||||||
use core::error;
|
use core::error;
|
||||||
@@ -39,22 +37,6 @@ impl Navigable for FlashInfoView {
|
|||||||
.clear(Rgb565::BLACK)
|
.clear(Rgb565::BLACK)
|
||||||
.map_err(PrimaryDisplayError::from)?;
|
.map_err(PrimaryDisplayError::from)?;
|
||||||
let _style = MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE);
|
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 style = MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE);
|
||||||
let textbox_style = TextBoxStyleBuilder::new()
|
let textbox_style = TextBoxStyleBuilder::new()
|
||||||
@@ -65,14 +47,18 @@ impl Navigable for FlashInfoView {
|
|||||||
let display_area = outputs.primary_display.bounding_box();
|
let display_area = outputs.primary_display.bounding_box();
|
||||||
let bounds = Rectangle::new(Point::new(0, 30), display_area.size);
|
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(
|
TextBox::with_textbox_style(
|
||||||
&format!(
|
&format!(
|
||||||
"
|
"
|
||||||
Flash Init Magic: 0x{:x}\n
|
|
||||||
Card Count: {}\n
|
Card Count: {}\n
|
||||||
",
|
",
|
||||||
u32::from_le_bytes(magic_bytes),
|
card_count
|
||||||
u32::from_le_bytes(card_count_bytes)
|
|
||||||
),
|
),
|
||||||
bounds,
|
bounds,
|
||||||
style,
|
style,
|
||||||
|
|||||||
+3
-2
@@ -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'
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user