17 Commits
Author SHA1 Message Date
rhetenor 4f251de3d5 wifi: fix issue with initialization
tertiary display: implement feature flag to disable
common: remove debug from cargo config, use ESP_LOG="creaturedex:debug"
2026-09-15 20:54:48 +02:00
rhetenor ffc5899c33 wifi: implement station change and connect 2026-09-15 20:54:48 +02:00
rhetenor 47b539f364 use own wifi implementation to connect to wifi. store credentials in flash. no wifi connection yet 2026-09-15 20:54:48 +02:00
ede1998 fafb4fc34f re-model left half of housing with bosl2 2026-09-13 20:06:04 +02:00
rhetenor 4d9cd05f72 fix wokwi wifi 2026-09-02 20:31:37 +02:00
rhetenor 240e2b081d rewrite wifi crate 2026-09-02 20:11:40 +02:00
rhetenor 0aa1370a2b rework card storage to use nvs 2026-08-31 20:16:42 +02:00
rhetenor b814c61f45 more manuals 2026-08-31 20:14:26 +02:00
rhetenor 290758d203 add executer tracing for debug 2026-08-30 20:57:35 +02:00
ede1998 a77b7761cd add custom flash partitions 2026-08-30 17:15:09 +02:00
rhetenor 91948bdcf5 fix clippy warnings 2026-08-30 09:25:49 +00:00
rhetenor 3c657045ca pass outputs and state to nfc task so that they can show errors on their own 2026-08-30 09:18:53 +00:00
rhetenor 3d36885e11 flash_info_view: align content justified 2026-08-30 08:17:22 +00:00
rhetenor af964bcc37 default to debug log for now 2026-08-30 08:15:52 +00:00
rhetenor ccf16522bb flash_store: forgot to add offset when erasing before write 2026-08-30 08:15:52 +00:00
rhetenor 5ac8fe9610 error view: clear display 2026-08-30 08:15:52 +00:00
ede1998 9ee4b68306 vibe-code wokwi display ch1115 integration 2026-08-30 01:57:18 +02:00
36 changed files with 1415 additions and 2150 deletions
+1 -3
View File
@@ -6,9 +6,7 @@ ESP_LOG="info"
WM_CONN = '{"ssid": "Wokwi-GUEST", "psk": "", "data": {}}' WM_CONN = '{"ssid": "Wokwi-GUEST", "psk": "", "data": {}}'
[build] [build]
rustflags = [ rustflags = ["-C", "link-arg=-nostartfiles"]
"-C", "link-arg=-nostartfiles",
]
target = "xtensa-esp32s3-none-elf" target = "xtensa-esp32s3-none-elf"
+3
View File
@@ -32,3 +32,6 @@ creaturedex.wiki/
*.zip *.zip
*.lck *.lck
schematics/.history/ schematics/.history/
wokwi/wokwi-api.h
wokwi/ch1115.chip.wasm
Generated
+80 -1652
View File
File diff suppressed because it is too large Load Diff
+13 -6
View File
@@ -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,3 +86,7 @@ opt-level = 's'
[features] [features]
default = [] default = []
wokwi = [] wokwi = []
nop_tertiary = []
[lints.clippy]
manual_async_fn = "allow"
+23
View File
@@ -1,5 +1,6 @@
fn main() { fn main() {
generate_filter_snippet(); generate_filter_snippet();
compile_custom_wokwi_components();
linker_be_nice(); linker_be_nice();
// make sure linkall.x is the last linker script (otherwise might cause problems with flip-link) // make sure linkall.x is the last linker script (otherwise might cause problems with flip-link)
println!("cargo:rustc-link-arg=-Tlinkall.x"); println!("cargo:rustc-link-arg=-Tlinkall.x");
@@ -70,6 +71,28 @@ fn linker_be_nice() {
); );
} }
fn compile_custom_wokwi_components() {
use std::process::Command;
if std::env::var("CARGO_FEATURE_WOKWI").is_ok() {
println!("cargo:rerun-if-changed=wokwi/ch1115.chip.c");
println!("cargo:rerun-if-changed=wokwi/ch1115.chip.json");
println!("cargo:rerun-if-changed=wokwi/Makefile");
let status = Command::new("make")
.current_dir("wokwi")
.status()
.expect("Failed to execute make command. Is 'make' installed?");
if !status.success() {
panic!(
"Wokwi custom chip compilation failed with status: {}",
status
);
}
}
}
// Taken over from esp_println because impossible to just extend their existing env logger. // Taken over from esp_println because impossible to just extend their existing env logger.
// https://github.com/esp-rs/esp-hal/blob/8fa6d7e985e724d6ad998e34307429b0920da370/esp-println/build.rs // https://github.com/esp-rs/esp-hal/blob/8fa6d7e985e724d6ad998e34307429b0920da370/esp-println/build.rs
fn generate_filter_snippet() { fn generate_filter_snippet() {
+34 -6
View File
@@ -59,19 +59,23 @@
"top": -291.2, "top": -291.2,
"left": -167.2, "left": -167.2,
"attrs": { "pins": "i2c" } "attrs": { "pins": "i2c" }
} },
{ "type": "chip-ch1115", "id": "chip1", "top": 509.82, "left": -4.8, "attrs": {} },
{ "type": "chip-ch1115", "id": "chip2", "top": 625.02, "left": -4.8, "attrs": {} },
{ "type": "chip-ch1115", "id": "chip3", "top": 394.62, "left": -4.8, "attrs": {} },
{ "type": "wokwi-vcc", "id": "vcc1", "top": 39.16, "left": 316.8, "attrs": {} }
], ],
"connections": [ "connections": [
[ "esp1:TX", "$serialMonitor:RX", "", [] ], [ "esp1:TX", "$serialMonitor:RX", "", [] ],
[ "esp1:RX", "$serialMonitor:TX", "", [] ], [ "esp1:RX", "$serialMonitor:TX", "", [] ],
[ "lcd1:VCC", "esp1:3V3", "red", [ "v19.2", "h-57.6", "v-105.6", "h-124.95" ] ], [ "lcd1:VCC", "esp1:3V3", "red", [ "v19.2", "h-57.6", "v-105.6", "h-124.95" ] ],
[ "lcd1:GND", "esp1:GND.2", "black", [ "v28.8", "h-76.8", "v-76.8" ] ], [ "lcd1:GND", "esp1:GND.2", "black", [ "v28.8", "h-76.8", "v-76.8" ] ],
[ "lcd1:CS", "esp1:11", "orange", [ "v0" ] ], [ "lcd1:CS", "esp1:11", "orange", [ "v259.2", "h-729.6", "v-95.82" ] ],
[ "lcd1:D/C", "esp1:12", "gold", [ "v0" ] ], [ "lcd1:D/C", "esp1:12", "gold", [ "v278.4", "h-729.6", "v-105.42" ] ],
[ "lcd1:RESET", "esp1:10", "brown", [ "v0" ] ], [ "lcd1:RESET", "esp1:10", "brown", [ "v0" ] ],
[ "lcd1:MOSI", "esp1:35", "violet", [ "v105.6", "h-124.8", "v-144" ] ], [ "lcd1:MOSI", "esp1:35", "violet", [ "v124.8", "h-124.8", "v0.18" ] ],
[ "lcd1:SCK", "esp1:36", "white", [ "v115.2", "h-144", "v-86.4" ] ], [ "lcd1:SCK", "esp1:36", "white", [ "v115.2", "h-144", "v-86.4" ] ],
[ "esp1:37", "lcd1:MISO", "magenta", [ "h57.6", "v105.6", "h172.8" ] ], [ "esp1:37", "lcd1:MISO", "magenta", [ "h57.6", "v-0.18", "h594.94" ] ],
[ "btn-up:2.l", "esp1:38", "purple", [ "h-9.6", "v19.4" ] ], [ "btn-up:2.l", "esp1:38", "purple", [ "h-9.6", "v19.4" ] ],
[ "btn-up:1.l", "esp1:GND.2", "black", [ "h0" ] ], [ "btn-up:1.l", "esp1:GND.2", "black", [ "h0" ] ],
[ "btn-down:1.l", "esp1:GND.2", "black", [ "h0" ] ], [ "btn-down:1.l", "esp1:GND.2", "black", [ "h0" ] ],
@@ -87,7 +91,31 @@
[ "lcd2:GND", "esp1:GND.2", "black", [ "h0" ] ], [ "lcd2:GND", "esp1:GND.2", "black", [ "h0" ] ],
[ "lcd2:VCC", "esp1:3V3.1", "red", [ "h0" ] ], [ "lcd2:VCC", "esp1:3V3.1", "red", [ "h0" ] ],
[ "lcd2:SDA", "esp1:17", "green", [ "h-134.4", "v413" ] ], [ "lcd2:SDA", "esp1:17", "green", [ "h-134.4", "v413" ] ],
[ "lcd2:SCL", "esp1:18", "green", [ "h-124.8", "v38.7" ] ] [ "lcd2:SCL", "esp1:18", "green", [ "h-124.8", "v38.7" ] ],
[ "chip2:RES", "chip1:RES", "gray", [ "h-28.8", "v-115.2" ] ],
[ "chip1:RES", "chip3:RES", "gray", [ "h-28.8", "v-67.2" ] ],
[ "chip2:GND", "chip1:GND", "black", [ "h-48", "v-115.2" ] ],
[ "chip1:GND", "chip3:GND", "black", [ "h-48", "v-115.2" ] ],
[ "chip2:VCC", "chip1:VCC", "red", [ "h-38.4", "v-115.2" ] ],
[ "chip3:VCC", "chip1:VCC", "red", [ "h-38.4", "v115.2" ] ],
[ "chip2:DC", "chip1:DC", "gold", [ "h46.84", "v-115.2" ] ],
[ "chip1:DC", "chip3:DC", "gold", [ "h46.84", "v-115.2" ] ],
[ "chip2:SCL", "chip1:SCL", "white", [ "h56.44", "v-115.2" ] ],
[ "chip1:SCL", "chip3:SCL", "white", [ "h56.44", "v-115.2" ] ],
[ "chip3:SDA", "chip1:SDA", "violet", [ "h-1.16", "h67.2", "v57.6" ] ],
[ "chip1:SDA", "chip2:SDA", "violet", [ "h66.04", "v115.2" ] ],
[ "esp1:35", "chip3:SDA", "violet", [ "h364.53", "v153.42" ] ],
[ "chip3:SCL", "esp1:36", "white", [ "h56.44", "v-172.62" ] ],
[ "esp1:12", "chip3:DC", "gold", [ "h-29.12", "v105.42", "h460.8", "v67.2" ] ],
[ "esp1:GND.4", "chip3:GND", "black", [ "h18.93", "v19.02", "h105.6", "v48" ] ],
[ "esp1:3V3.1", "chip3:VCC", "red", [ "h-57.92", "v259.02" ] ],
[ "lcd1:VCC", "vcc1:VCC", "red", [ "v67.2", "h-48" ] ],
[ "lcd1:LED", "vcc1:VCC", "red", [ "v67.2", "h-144.01" ] ],
[ "lcd1:RST", "esp1:10", "gray", [ "v268.8", "h-729.6", "v-115.02" ] ],
[ "esp1:47", "chip3:RES", "gray", [ "h28.53", "v182.22" ] ],
[ "chip3:CS", "esp1:13", "blue", [ "h-278.4", "v-153.42" ] ],
[ "esp1:14", "chip1:CS", "magenta", [ "h-9.92", "v259.02" ] ],
[ "esp1:21", "chip2:CS", "#8f4814", [ "h95.73", "v316.62" ] ]
], ],
"dependencies": {} "dependencies": {}
} }
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
[idf_format_args]
partition_table = "partitions.csv"
+2 -2
View File
@@ -2,8 +2,8 @@ include <common.scad>
use <left-half.scad> use <left-half.scad>
use <right-half.scad> use <right-half.scad>
left_half(); left_half_creaturedex();
right_half(); right_half_creaturedex();
#union() { #union() {
right_half_components(); right_half_components();
+1
View File
@@ -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);
+221 -7
View File
@@ -1,12 +1,226 @@
include <BOSL2/std.scad>
include <common.scad> include <common.scad>
module left_half_components() { module left_half_orig() {
cube([1,1,1]);
}
module left_half() {
translate(BASE_MODEL_TRANSLATE) scale(BASE_MODEL_SCALE) import(file="left-half.3mf"); translate(BASE_MODEL_TRANSLATE) scale(BASE_MODEL_SCALE) import(file="left-half.3mf");
} }
left_half(); BASE_MODEL_SCALE = 1.1;
#left_half_components(); // 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();
}
}
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();
+2 -2
View File
@@ -106,10 +106,10 @@ module right_half_hinge_only() {
} }
// !right_half_hinge_only(); // !right_half_hinge_only();
module right_half() { module right_half_creaturedex() {
right_half_door_only(); right_half_door_only();
right_half_hinge_only(); right_half_hinge_only();
} }
// right_half(); // right_half_creaturedex();
// #right_half_components(); // #right_half_components();
+4
View File
@@ -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 # ESP-IDF Partition Table
2 # Name,Type,SubType,Offset,Size,Flags
3 nvs,data,nvs,0x9000,0xa00000,
4 factory,app,factory,0xa10000,0x200000,
+20 -4
View File
@@ -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 embedded_hal_bus::i2c::AtomicDevice;
use esp_hal::{Blocking, i2c::master::I2c, time::Instant}; use esp_hal::{Blocking, i2c::master::I2c, time::Instant};
@@ -15,7 +21,9 @@ use crate::{
)] )]
pub async fn nfc_scanner( pub async fn nfc_scanner(
mut nfc_driver: NfcPn532Driver<AtomicDevice<'static, I2c<'static, Blocking>>>, mut nfc_driver: NfcPn532Driver<AtomicDevice<'static, I2c<'static, Blocking>>>,
outputs: &'static Mutex<Outputs>,
peripherals: &'static Peripherals, peripherals: &'static Peripherals,
navigation_state: &'static Mutex<NavigationState>,
) { ) {
loop { loop {
while CARD_DATA.lock().await.is_none() { while CARD_DATA.lock().await.is_none() {
@@ -35,17 +43,25 @@ 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(()) => {}
Err(error) => { 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;
} }
} }
+54 -19
View File
@@ -8,22 +8,27 @@
#![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;
use creaturedex::drivers::primary_lcd::PrimaryDisplay;
use creaturedex::drivers::secondary_oled::SecondaryDisplay; use creaturedex::drivers::secondary_oled::SecondaryDisplay;
use creaturedex::drivers::spi_bus; 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::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::{
@@ -35,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!();
@@ -71,7 +73,7 @@ async fn main(spawner: Spawner) {
let timg0 = TimerGroup::new(esp_peripherals.TIMG0); let timg0 = TimerGroup::new(esp_peripherals.TIMG0);
esp_rtos::start(timg0.timer0, sw_interrupt.software_interrupt0); esp_rtos::start(timg0.timer0, sw_interrupt.software_interrupt0);
let (primary, mut secondaries) = retry( let (mut primary, mut secondaries) = retry(
5, 5,
spi_bus::DisplayPinConfiguration { spi_bus::DisplayPinConfiguration {
spi_peripheral: esp_peripherals.SPI2, spi_peripheral: esp_peripherals.SPI2,
@@ -120,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));
@@ -160,8 +175,9 @@ async fn main(spawner: Spawner) {
display_shit(&mut secondaries[0], "foo 1"); display_shit(&mut secondaries[0], "foo 1");
display_shit(&mut secondaries[1], "bar 1"); display_shit(&mut secondaries[1], "bar 1");
display_shit(&mut secondaries[2], "baz 1"); 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; let [sec_1, sec_2, sec_3] = secondaries;
Outputs { Outputs {
primary_display: primary, primary_display: primary,
@@ -171,13 +187,22 @@ async fn main(spawner: Spawner) {
tertiary_display: lcd, tertiary_display: lcd,
_led_a: (), _led_a: (),
} }
}; })));
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).expect("run task failed"));
spawner.spawn( 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 core::future::pending::<()>().await
} }
@@ -191,6 +216,16 @@ fn display_shit(oled: &mut SecondaryDisplay<'static>, text: &str) {
oled.flush().unwrap(); oled.flush().unwrap();
} }
fn display_shit_prim(main: &mut PrimaryDisplay<'static>, text: &str) {
use embedded_graphics::pixelcolor::Rgb565;
main.clear(Rgb565::BLACK).unwrap();
let text_style = MonoTextStyle::new(&FONT_6X10, Rgb565::WHITE);
Text::new(text, Point::new(10, 20), text_style)
.draw(main)
.unwrap();
}
fn retry<T, U, F: FnMut(T) -> Result<U, T>>(repetitions: u32, input: T, mut action: F) -> U { fn retry<T, U, F: FnMut(T) -> Result<U, T>>(repetitions: u32, input: T, mut action: F) -> U {
let mut initial_state = input; let mut initial_state = input;
for iteration in 0..repetitions { for iteration in 0..repetitions {
+34
View File
@@ -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)]
+9 -8
View File
@@ -158,14 +158,7 @@ where
OutputConfig::default(), OutputConfig::default(),
)); ));
let primary = PrimaryDisplayPinConfiguration { // Secondary displays must come first or they don't work in wokwi for some reason.
spi_bus: bus_static,
cs: low_active(self.cs_primary),
reset: low_active(self.reset_primary),
dc: dc.clone(),
}
.build();
let secondaries = SecondaryDisplayPinConfiguration { let secondaries = SecondaryDisplayPinConfiguration {
spi_bus: bus_static, spi_bus: bus_static,
cs_pins: [ cs_pins: [
@@ -174,6 +167,14 @@ where
low_active(self.cs_secondary_3), low_active(self.cs_secondary_3),
], ],
res: reset_secondary, res: reset_secondary,
dc: dc.clone(),
}
.build();
let primary = PrimaryDisplayPinConfiguration {
spi_bus: bus_static,
cs: low_active(self.cs_primary),
reset: low_active(self.reset_primary),
dc, dc,
} }
.build(); .build();
+41 -2
View File
@@ -14,6 +14,14 @@ pub struct TertiaryDisplayPinConfiguration<'a> {
pub i2c: I2cBus<'a>, pub i2c: I2cBus<'a>,
} }
#[cfg(feature = "nop_tertiary")]
impl<'a> TertiaryDisplayPinConfiguration<'a> {
pub fn build(self) -> Result<TertiaryDisplay<'a>, Self> {
Ok(TertiaryDisplay { phantom: &() })
}
}
#[cfg(not(feature = "nop_tertiary"))]
impl<'a> TertiaryDisplayPinConfiguration<'a> { impl<'a> TertiaryDisplayPinConfiguration<'a> {
pub fn build(self) -> Result<TertiaryDisplay<'a>, Self> { pub fn build(self) -> Result<TertiaryDisplay<'a>, Self> {
let device = AtomicDevice::new(self.i2c); let device = AtomicDevice::new(self.i2c);
@@ -61,19 +69,50 @@ impl<'a> core::fmt::Display for TertiaryDisplayWriteError<'a> {
} }
} }
#[cfg(not(feature = "nop_tertiary"))]
pub struct TertiaryDisplay<'a> { pub struct TertiaryDisplay<'a> {
display: TertiaryDisplayRaw<'a>, display: TertiaryDisplayRaw<'a>,
charset: CustomCharset, charset: CustomCharset,
} }
#[cfg(feature = "nop_tertiary")]
pub struct TertiaryDisplay<'a> {
phantom: &'a (),
}
#[cfg(feature = "nop_tertiary")]
impl<'a> TertiaryDisplay<'a> { impl<'a> TertiaryDisplay<'a> {
pub const WIDTH: usize = 16; pub const WIDTH: usize = 16;
pub const ROWS: usize = 2; pub const ROWS: usize = 2;
pub fn inner_mut(&mut self) -> &mut TertiaryDisplayRaw<'a> { pub fn load_charset(&mut self, charset: CustomCharset) -> Result<(), TertiaryDisplayError<'a>> {
&mut self.display log::info!("nop tertiary");
Ok(())
} }
pub fn clear(&mut self) -> Result<(), TertiaryDisplayError<'a>> {
log::info!("nop tertiary");
Ok(())
}
/// Writes text to the LCD. Normal strings wrap by default but this can be controlled
/// via explicit [`Lines::checked`].
pub fn write<'b, L: Into<Lines<'b>>>(
&mut self,
text: L,
) -> Result<(), TertiaryDisplayWriteError<'a>> {
log::info!("nop tertiary");
log::info!("{:?}", text.into());
Ok(())
}
}
#[cfg(not(feature = "nop_tertiary"))]
impl<'a> TertiaryDisplay<'a> {
pub const WIDTH: usize = 16;
pub const ROWS: usize = 2;
pub fn load_charset(&mut self, charset: CustomCharset) -> Result<(), TertiaryDisplayError<'a>> { pub fn load_charset(&mut self, charset: CustomCharset) -> Result<(), TertiaryDisplayError<'a>> {
self.charset = charset; self.charset = charset;
for (index, charmap) in self for (index, charmap) in self
+71 -1
View File
@@ -1,5 +1,6 @@
#![no_std] #![no_std]
#![feature(vec_into_chunks)]
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
extern crate alloc; extern crate alloc;
@@ -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) {}
+28 -18
View File
@@ -1,3 +1,4 @@
use crate::Mutex;
use crate::card::model::Card; use crate::card::model::Card;
use crate::navigation::inputs::ButtonAction; use crate::navigation::inputs::ButtonAction;
use crate::navigation::inputs::Inputs; use crate::navigation::inputs::Inputs;
@@ -12,11 +13,8 @@ use alloc::string::ToString;
use core::error; use core::error;
use embassy_futures::select::{Either, select}; use embassy_futures::select::{Either, select};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_time::{Duration, Timer}; use embassy_time::{Duration, Timer};
pub type Mutex<T> = embassy_sync::mutex::Mutex<CriticalSectionRawMutex, T>;
pub type Signal<T> = embassy_sync::signal::Signal<CriticalSectionRawMutex, T>;
pub static CARD_DATA: Mutex<Option<Card>> = Mutex::new(None); pub static CARD_DATA: Mutex<Option<Card>> = Mutex::new(None);
const DEBOUNCE_DURATION_MILLIS: u64 = 100; const DEBOUNCE_DURATION_MILLIS: u64 = 100;
@@ -41,43 +39,56 @@ pub trait Navigable {
fn handle_input(&self, input: Action) -> impl core::future::Future<Output = NewState> + Send; fn handle_input(&self, input: Action) -> impl core::future::Future<Output = NewState> + Send;
} }
#[embassy_executor::task] pub async fn display_error(
pub async fn run(mut inputs: Inputs, mut outputs: Outputs, peripherals: &'static Peripherals) {
async fn display_error(
error: String, error: String,
state: &mut NavigationState, navigation_state: &Mutex<NavigationState>,
outputs: &mut Outputs, outputs: &Mutex<Outputs>,
peripherals: &Peripherals, peripherals: &Peripherals,
) -> () { ) -> () {
let error_view = ErrorView { let error_view = ErrorView {
error: error.to_string(), error: error.to_string(),
}; };
let mut state = navigation_state.lock().await;
state.screens.push(View::Error(error_view)); state.screens.push(View::Error(error_view));
let mut outs = outputs.lock().await;
state state
.screens .screens
.last() .last()
// Unwrap: we just pushed the state // Unwrap: we just pushed the state
.unwrap() .unwrap()
.display(outputs, peripherals) .display(&mut outs, peripherals)
.await .await
// Unwrap: display will panic on error in error view // Unwrap: display will panic on error in error view
.unwrap(); .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"); 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 .screens
.last() .last()
.unwrap() .unwrap()
.display(&mut outputs, peripherals) .display(&mut outs, peripherals)
.await .await
{ {
display_error(error.to_string(), &mut state, &mut outputs, peripherals).await; display_error(error.to_string(), navigation_state, outputs, peripherals).await;
}; };
}
loop { loop {
Timer::after(Duration::from_millis(DEBOUNCE_DURATION_MILLIS)).await;
let mut state = navigation_state.lock().await;
let selection = select( let selection = select(
inputs.wait_for_press(), inputs.wait_for_press(),
Timer::after(Duration::from_millis(DEBOUNCE_DURATION_MILLIS)), 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); state.screens.push(new_state.view);
let mut outs = outputs.lock().await;
if (action != Action::Timer || new_state.redraw) if (action != Action::Timer || new_state.redraw)
&& let Err(error) = state && let Err(error) = state
.screens .screens
.last() .last()
.unwrap() .unwrap()
.display(&mut outputs, peripherals) .display(&mut outs, peripherals)
.await .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;
} }
} }
+171 -35
View File
@@ -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 {
pub ssid: String,
pub pass: String,
}
wm_settings.ssid.clear(); pub static WIFI_CREDENTIALS: Signal<WifiCredentials> = Signal::new();
_ = core::fmt::write(
&mut wm_settings.ssid,
format_args!("CreatureDex-{:X}", esp_hal_wifimanager::get_efuse_mac()),
);
wm_settings.wifi_conn_timeout = 30000; #[derive(Debug)]
wm_settings.esp_reset_timeout = Some(300000); // 5min pub struct Wifi {
controller: WifiController<'static>,
interfaces: wifi::Interfaces<'static>,
}
let wifi_res = esp_hal_wifimanager::init_wm(wm_settings, spawner, Some(&nvs), wifi, None).await; #[derive(Debug)]
pub enum WifiError {
Store(WifiStoreError),
Radio(esp_radio::wifi::WifiError),
NoCredentialsStored,
}
log::info!("wifi_res: {wifi_res:?}"); impl Error for WifiError {}
impl Display for WifiError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
WifiError::Store(e) => e.fmt(f),
WifiError::Radio(e) => e.fmt(f),
WifiError::NoCredentialsStored => write!(f, "No WiFi credentials stored in flash"),
}
}
}
impl From<WifiStoreError> for WifiError {
fn from(error: WifiStoreError) -> WifiError {
WifiError::Store(error)
}
}
impl From<esp_radio::wifi::WifiError> for WifiError {
fn from(error: esp_radio::wifi::WifiError) -> WifiError {
WifiError::Radio(error)
}
}
impl Wifi {
pub fn new(wifi: esp_hal::peripherals::WIFI<'static>) -> Result<Self, WifiError> {
log::info!("creating new wifi");
let wifi = wifi::new(wifi, Default::default())?;
Ok(Self {
controller: wifi.0,
interfaces: wifi.1,
})
}
// get wifi credentials from env WIFI_SSID; WIFI_PASS (priority) or storage
pub async fn connect_with_stored_credentials(
&mut self,
wifi_store: &WifiStore,
) -> Result<(), WifiError> {
let option_stored_credentials = wifi_store.load_credentials().await?;
let env_ssid = option_env!("WIFI_SSID");
let env_pass = option_env!("WIFI_PASS");
if env_ssid.is_none() && option_stored_credentials.is_none() {
log::info!("no initial wifi credentials. do not connect");
return Ok(());
}
let stored_credentials = option_stored_credentials.unwrap_or(WifiCredentials {
pass: "".to_string(),
ssid: "".to_string(),
});
let ssid = env_ssid.map_or(stored_credentials.ssid, |v| v.to_string());
let pass = env_pass.map_or(stored_credentials.pass, |v| v.to_string());
log::info!("initial wifi credentials:\nssid:{ssid}, pass:{pass}");
let credentials = WifiCredentials { ssid, pass };
self.set_station(credentials).await?;
self.connect().await?;
Ok(())
}
pub async fn connect(&mut self) -> Result<(), WifiError> {
log::info!("connecting wifi...");
let stationinfo = self.controller.connect_async().await?;
log::info!("connected to {}", stationinfo.ssid.as_str());
Ok(())
}
pub async fn set_station(&mut self, credentials: WifiCredentials) -> Result<(), WifiError> {
let station_config = StationConfig::default()
.with_ssid(credentials.ssid)
.with_password(credentials.pass);
self.controller
.set_config(&Config::Station(station_config))?;
Ok(())
} }
#[cfg(feature = "wokwi")] #[cfg(feature = "wokwi")]
pub async fn setup_wifi( 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
View File
@@ -1,6 +1,7 @@
pub mod storage; pub mod storage;
use crate::navigation::navigation::Mutex; use crate::Mutex;
use crate::network::wifi::Wifi;
use crate::peripherals::storage::store::Store; use crate::peripherals::storage::store::Store;
use esp_hal::rtc_cntl::Rtc; use esp_hal::rtc_cntl::Rtc;
@@ -8,4 +9,5 @@ use esp_hal::rtc_cntl::Rtc;
pub struct Peripherals { pub struct Peripherals {
pub store: Mutex<Store>, pub store: Mutex<Store>,
pub rtc: Rtc<'static>, pub rtc: Rtc<'static>,
pub wifi: Mutex<Wifi>,
} }
+3 -27
View File
@@ -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;
+246 -178
View File
@@ -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))
}
} }
-108
View File
@@ -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,
)))
}
}
}
+1
View File
@@ -0,0 +1 @@
+2 -2
View File
@@ -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,
} }
+140
View File
@@ -0,0 +1,140 @@
use alloc::string::String;
use crate::network::wifi::WifiCredentials;
use crate::Mutex;
use crate::peripherals::storage::Nvs;
use alloc::sync::Arc;
use core::error::Error;
use core::fmt::Display;
use esp_nvs::Key;
const NVS_NAMESPACE_WIFI: Key = Key::from_str("WIFI");
const NVS_WIFI_SSID_KEY: Key = Key::from_str("WIFI_SSID");
const NVS_WIFI_PASS_KEY: Key = Key::from_str("WIFI_PASS");
const NVS_WIFI_INITIALIZED_KEY: Key = Key::from_str("INITIALIZED");
#[derive(Debug)]
pub enum WifiStoreError {
Store(esp_nvs::error::Error),
}
impl Error for WifiStoreError {}
impl Display for WifiStoreError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
WifiStoreError::Store(e) => e.fmt(f),
}
}
}
impl From<esp_nvs::error::Error> for WifiStoreError {
fn from(error: esp_nvs::error::Error) -> WifiStoreError {
WifiStoreError::Store(error)
}
}
pub struct WifiStore {
nvs: Arc<Mutex<Nvs>>,
}
impl WifiStore {
pub async fn new(nvs: Arc<Mutex<Nvs>>) -> Result<Self, WifiStoreError> {
if !Self::is_initialized(&nvs).await? {
log::info!("WifiStore has not been initialized");
Self::initialize(&nvs).await?;
}
log::info!("WifiStore has been initialized");
Ok(Self { nvs })
}
async fn is_initialized(nvs: &Mutex<Nvs>) -> Result<bool, WifiStoreError> {
log::info!("check initialization");
let mut nvs_lock = nvs.lock().await;
match nvs_lock.get::<bool>(&NVS_NAMESPACE_WIFI, &NVS_WIFI_INITIALIZED_KEY) {
Ok(initialized) => {
log::debug!("initialization_check: initialized {initialized:?}");
Ok(true)
}
Err(esp_nvs::error::Error::NamespaceNotFound) => {
log::debug!("initialization_check: error: namespace not found");
Ok(false)
}
Err(esp_nvs::error::Error::KeyNotFound) => {
log::debug!("initialization_check: error: key not found");
Ok(false)
}
Err(error) => Err(error.into()),
}
}
async fn initialize(nvs: &Mutex<Nvs>) -> Result<(), WifiStoreError> {
log::info!("initializing wifi store");
let mut nvs_lock = nvs.lock().await;
log::debug!("initialization: write empty ssid");
nvs_lock.set::<&str>(
&NVS_NAMESPACE_WIFI,
&NVS_WIFI_SSID_KEY,
""
)?;
log::debug!("initialization: write empty pass");
nvs_lock.set::<&str>(
&NVS_NAMESPACE_WIFI,
&NVS_WIFI_PASS_KEY,
""
)?;
// set initialized
log::debug!("initialization: write initialized");
nvs_lock.set::<bool>(
&NVS_NAMESPACE_WIFI,
&NVS_WIFI_INITIALIZED_KEY,
true,
)?;
Ok(())
}
pub async fn load_credentials(&self) -> Result<Option<WifiCredentials>, WifiStoreError> {
log::debug!("loading wifi credentials");
log::debug!("loading ssid");
let mut nvs_lock = self.nvs.lock().await;
let ssid = nvs_lock.get::<String>(&NVS_NAMESPACE_WIFI, &NVS_WIFI_SSID_KEY)?;
if ssid.is_empty() {
return Ok(None);
}
log::debug!("ssid: {ssid}");
log::debug!("loading pass");
let pass = nvs_lock.get::<String>(&NVS_NAMESPACE_WIFI, &NVS_WIFI_PASS_KEY)?;
log::debug!("pass: {pass}");
Ok(Some(WifiCredentials{ssid, pass}))
}
pub async fn save_credentials(&self, credentials: &WifiCredentials) -> Result<(), WifiStoreError> {
log::debug!("writing wifi credentials");
log::debug!("writing ssid...\nssid: {}", credentials.ssid);
self.nvs.lock().await.set::<&str>(
&NVS_NAMESPACE_WIFI,
&NVS_WIFI_SSID_KEY,
&credentials.ssid,
)?;
log::debug!("writing pass...\npass: {}", credentials.pass);
self.nvs.lock().await.set::<&str>(
&NVS_NAMESPACE_WIFI,
&NVS_WIFI_PASS_KEY,
&credentials.pass,
)?;
Ok(())
}
}
+12 -3
View File
@@ -34,6 +34,15 @@ impl Navigable for ErrorView {
_: &Peripherals, _: &Peripherals,
) -> impl core::future::Future<Output = Result<(), Box<dyn error::Error>>> + Send { ) -> impl core::future::Future<Output = Result<(), Box<dyn error::Error>>> + Send {
async move { 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 style = MonoTextStyle::new(&FONT_10X20, Rgb565::RED);
let display_area = outputs.primary_display.bounding_box(); let display_area = outputs.primary_display.bounding_box();
Text::new( Text::new(
@@ -44,7 +53,7 @@ impl Navigable for ErrorView {
.draw(&mut outputs.primary_display) .draw(&mut outputs.primary_display)
.unwrap_or_else(|error| { .unwrap_or_else(|error| {
panic!( panic!(
"Error: {error:?}\nDraw error while rendering error: {}", "Error: {error:?}\nDraw error while rendering ErrorView: {}",
self.error self.error
) )
}); });
@@ -55,13 +64,13 @@ impl Navigable for ErrorView {
.alignment(HorizontalAlignment::Center) .alignment(HorizontalAlignment::Center)
.build(); .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) TextBox::with_textbox_style(&self.error.to_string(), bounds, style, textbox_style)
.draw(&mut outputs.primary_display) .draw(&mut outputs.primary_display)
.unwrap_or_else(|error| { .unwrap_or_else(|error| {
panic!( panic!(
"Error: {error:?}\nDraw error while rendering error: {}", "Error: {error:?}\nDraw error while rendering ErrorView: {}",
self.error self.error
) )
}); });
+12 -22
View File
@@ -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;
@@ -34,41 +32,33 @@ impl Navigable for FlashInfoView {
peripherals: &Peripherals, peripherals: &Peripherals,
) -> impl core::future::Future<Output = Result<(), Box<dyn error::Error>>> + Send { ) -> impl core::future::Future<Output = Result<(), Box<dyn error::Error>>> + Send {
async move { async move {
outputs
.primary_display
.clear(Rgb565::BLACK)
.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()
.height_mode(HeightMode::FitToText) .height_mode(HeightMode::FitToText)
.alignment(HorizontalAlignment::Center) .alignment(HorizontalAlignment::Justified)
.build(); .build();
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,
+4 -2
View File
@@ -12,7 +12,7 @@ use embedded_graphics::pixelcolor::Rgb565;
use embedded_graphics::prelude::RgbColor; use embedded_graphics::prelude::RgbColor;
use embedded_graphics_core::draw_target::DrawTarget; use embedded_graphics_core::draw_target::DrawTarget;
pub const MAX_SELECTED: i32 = 2; pub const MAX_SELECTED: i32 = 3;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct SettingsMenu { pub struct SettingsMenu {
@@ -27,7 +27,9 @@ impl Navigable for SettingsMenu {
) -> impl core::future::Future<Output = Result<(), Box<dyn error::Error>>> + Send { ) -> impl core::future::Future<Output = Result<(), Box<dyn error::Error>>> + Send {
async move { async move {
let display = &mut outputs.primary_display; 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) menu_item::show(display, "System Inforation", 0, self.selected)
.map_err(PrimaryDisplayError::from)?; .map_err(PrimaryDisplayError::from)?;
menu_item::show(display, "Wifi Information", 1, self.selected) menu_item::show(display, "Wifi Information", 1, self.selected)
+7 -2
View File
@@ -1,5 +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]]
name = 'ch1115'
binary = 'wokwi/ch1115.chip.wasm'
+36
View File
@@ -0,0 +1,36 @@
.PHONY: all auto native docker clean
# Configuration
SRC = ch1115.chip.c
OUT = ch1115.chip.wasm
# Check if wokwi-cli exists in PATH
WOKWI_CLI := $(shell command -v wokwi-cli 2> /dev/null)
HOST_UID := $(shell id -u)
HOST_GID := $(shell id -g)
# Default target runs the auto-detection
all: auto
auto:
ifeq ($(WOKWI_CLI),)
@echo "wokwi-cli not found in PATH. Falling back to Docker build..."
$(MAKE) docker
else
@echo "Found wokwi-cli at $(WOKWI_CLI). Using native build..."
$(MAKE) native
endif
native:
wokwi-cli chip compile $(SRC) -o $(OUT)
docker:
docker run --rm -v $(CURDIR):/workspace -w /workspace ubuntu:latest \
bash -c "apt-get update && apt-get install -y --no-install-recommends curl ca-certificates && \
curl -L https://wokwi.com/ci/install.sh | sh && \
~/.wokwi/bin/wokwi-cli chip compile $(SRC) -o $(OUT) && \
chown $(HOST_UID):$(HOST_GID) $(OUT)"
clean:
rm -f $(OUT)
+86
View File
@@ -0,0 +1,86 @@
#include "wokwi-api.h"
#include <stdlib.h>
#include <stdio.h>
typedef struct {
pin_t cs, dc, res;
spi_dev_t spi;
buffer_t fb;
uint32_t width, height;
uint8_t spi_buffer[1];
uint8_t page;
uint8_t col;
} chip_state_t;
// Forward declarations
static void on_cs_change(void *user_data, pin_t pin, uint32_t value);
static void chip_spi_done(void *user_data, uint8_t *buffer, uint32_t count);
void chip_init(void) {
printf("Initing CH1115 chip\n");
fflush(stdout);
chip_state_t *chip = malloc(sizeof(chip_state_t));
chip->fb = framebuffer_init(&chip->width, &chip->height);
chip->cs = pin_init("CS", INPUT_PULLUP);
chip->dc = pin_init("DC", INPUT);
chip->res = pin_init("RES", INPUT_PULLUP);
const spi_config_t spi_cfg = {
.sck = pin_init("SCL", INPUT),
.mosi = pin_init("SDA", INPUT),
.miso = NO_PIN,
.mode = 0,
.done = chip_spi_done,
.user_data = chip,
};
chip->spi = spi_init(&spi_cfg);
const pin_watch_config_t cs_watch = {
.edge = BOTH,
.pin_change = on_cs_change,
.user_data = chip,
};
pin_watch(chip->cs, &cs_watch);
}
static void on_cs_change(void *user_data, pin_t pin, uint32_t value) {
chip_state_t *chip = (chip_state_t*)user_data;
if (value == LOW) {
// Start receiving 1 byte at a time
spi_start(chip->spi, chip->spi_buffer, 1);
} else {
spi_stop(chip->spi);
}
}
static void chip_spi_done(void *user_data, uint8_t *buffer, uint32_t count) {
chip_state_t *chip = (chip_state_t*)user_data;
if (!count) return;
uint8_t val = buffer[0];
bool is_data = pin_read(chip->dc) == HIGH;
if (is_data) {
// Write 8 vertical pixels to the Wokwi RGBA Framebuffer
for (int i = 0; i < 8; i++) {
// 0xFFFFFFFF = White, 0x000000FF = Black
uint32_t color = (val & (1 << i)) ? 0xFFFFFFFF : 0x000000FF;
uint32_t y = (chip->page * 8) + i;
uint32_t offset = (y * chip->width + chip->col) * 4;
buffer_write(chip->fb, offset, &color, 4);
}
chip->col++; // Auto-increment column
} else {
// CH1115 Core Commands
if ((val & 0xB0) == 0xB0) chip->page = val & 0x0F; // Set Page Start
else if ((val & 0xF0) == 0x00) chip->col = (chip->col & 0xF0) | (val & 0x0F); // Lower Col
else if ((val & 0xF0) == 0x10) chip->col = (chip->col & 0x0F) | ((val & 0x0F) << 4); // Upper Col
}
// Continue receiving if CS is still active
if (pin_read(chip->cs) == LOW) {
spi_start(chip->spi, chip->spi_buffer, 1);
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"name": "CH1115 OLED",
"author": "ede1998",
"pins": ["VCC", "GND", "CS", "RES", "DC", "SCL", "SDA"],
"display": {
"width": 128,
"height": 64
}
}