85 Commits

Author SHA1 Message Date
39ced811c3 yield display to audio 2025-11-17 15:15:39 -07:00
90d32f050c remove uneeded 2025-11-17 15:07:04 -07:00
0e7e330998 selection ui for wav_player 2025-11-17 15:02:32 -07:00
8c20864392 audio works 2025-11-17 14:52:47 -07:00
7efea9eb8d fix justfile 2025-11-17 10:25:46 -07:00
edbd598803 Merge branch 'main' into audio-driver 2025-11-17 10:19:14 -07:00
1c1000dfcb fixes from nes 2025-11-17 08:10:03 -07:00
691ef2b26b fix selection ui 2025-11-10 13:30:37 -07:00
d9886fdea1 updates 2025-11-10 11:35:21 -07:00
f0d9f41fea fix comp time and rename feature to psram 2025-11-09 10:58:33 -07:00
6d7912ce5b fix release
fix release
2025-11-09 10:19:01 -07:00
0e6e4e45c8 improve how fps is drawn to avoid being drawn over 2025-11-08 22:54:12 -07:00
d9af87eb92 fix false fps reading 2025-11-08 22:04:01 -07:00
60758f3cb5 display real time display fps 2025-11-08 19:57:34 -07:00
ee0d2880bb selection ui for user apps
works
2025-11-05 08:32:33 -07:00
dd26e3528b gif responsive 2025-11-03 16:07:14 -07:00
74ec86da8f fix lock 2025-11-03 15:26:22 -07:00
cc463a34be fix alloc panics 2025-11-03 14:09:53 -07:00
355be5cde3 do batching tiles again in fb 2025-11-03 13:45:03 -07:00
1bbb892fcc remove unsafe fb 2025-11-03 10:56:29 -07:00
7fcc5291e6 fix build 2025-10-31 17:46:52 -06:00
9afec60033 set rp2350 as kernel default target 2025-10-31 17:46:02 -06:00
382e2e73ef fix rp2350 2025-10-31 17:41:36 -06:00
1d7ab3fb42 move fb to psram to save 200KB for user apps 2025-10-31 17:28:16 -06:00
2226541813 fix release 2025-10-31 14:15:47 -06:00
05198c716d increase clock speed of display 2025-10-29 08:07:58 -06:00
ba426f5baa center gif 2025-10-28 19:06:32 -06:00
7bc6aeb998 forgot display lock 2025-10-28 17:44:31 -06:00
1182560582 remvove lock_display 2025-10-28 12:36:15 -06:00
a7daa4c5fc get fps better 2025-10-28 12:20:02 -06:00
bbc9613f62 cleanup 2025-10-28 09:50:15 -06:00
10c9457953 double framebuffer 2025-10-27 19:46:09 -06:00
4c58f66c94 gif plays at low fps 2025-10-27 18:53:22 -06:00
999b22a96f only mark framebuffer tile as dirty if pixel changes 2025-10-27 12:30:23 -06:00
f6d5fb98ab alloc user to access kernel backed heap (psram, if equiped) 2025-10-27 12:25:57 -06:00
b872e6be7c Merge branch 'psram-alloc' into gif 2025-10-27 09:15:40 -06:00
5414725241 add pimoroni2w support 2025-10-26 20:21:34 -06:00
7662e485c0 gif need psram 2025-10-19 15:25:01 -06:00
31a3772bcb spi psram works 2025-10-14 14:07:58 -06:00
212077578c Merge branch 'main' into psram-alloc 2025-10-14 12:43:26 -06:00
38cdfcd549 add syscall to get time in ms since application start 2025-10-06 18:23:31 -06:00
76c7870a79 remove shared crate 2025-10-06 00:25:56 -06:00
28417cce69 fix bug in abi_sys causing display driver crashes 2025-10-06 00:18:44 -06:00
ddcdd5942a make all syscalls ffi compat 2025-10-05 18:24:44 -06:00
af238b2847 cbindgen abi_sys 2025-10-05 17:14:38 -06:00
f2a5801284 fully c ffi compat 2025-10-05 15:43:57 -06:00
4c63f77c24 WIP 2025-10-01 13:36:25 -06:00
d8a5ab465e WIP 2025-09-30 20:27:07 -06:00
f73df7e0b8 fix abi in readme 2025-09-30 12:14:51 -06:00
2021ef9753 update readme and just for release builds 2025-09-30 12:11:57 -06:00
59e4a7faa2 file names in gallery 2025-09-29 18:33:37 -06:00
15a09b52d7 gallery works 2025-09-29 12:35:54 -06:00
f353cad108 WIP gallery app 2025-09-28 22:24:29 -06:00
d986f1409f lower kernel version 2025-09-28 17:46:49 -06:00
2221ffdbde basic fs syscall(s) 2025-09-28 14:07:03 -06:00
7bd6012748 use C abi for syscalls 2025-09-26 23:39:19 -06:00
bf3b37783f Readme 2025-09-26 22:51:35 -06:00
16e0374550 remove unused 2025-09-26 20:30:21 -06:00
dbb811c9f5 use section parser 2025-09-26 20:29:38 -06:00
fb2c3583de remove debugs 2025-09-26 20:26:42 -06:00
180d9e82d2 PIE binaries & fix currupted framebuffer 2025-09-26 20:24:23 -06:00
07b4905a06 use strum for abicalltable 2025-09-26 11:15:42 -06:00
d00e644100 semi-working snake game 2025-09-19 13:08:16 -06:00
2012e68995 remove unused 2025-09-18 19:21:17 -06:00
e628c47e4b remove screen tearing 2025-09-18 19:20:20 -06:00
9468ceab51 fix first selection 2025-09-18 17:48:21 -06:00
bf359f0513 selection menu works for multiple binaries, and shows selection box 2025-09-18 17:43:49 -06:00
4f93ee4e9d cargo upgrade 2025-09-18 16:45:03 -06:00
fab10dfa1f cargo fix 2025-09-18 16:44:18 -06:00
46c69ead67 remove debug comments 2025-09-18 16:28:32 -06:00
39abe19fd3 can load & reload programs 2025-09-18 16:25:24 -06:00
1cd0d292fe calculator works pretty well minus the tearing 2025-09-18 15:53:35 -06:00
e07700beea wip calculator 2025-09-18 11:50:28 -06:00
1f1aa5ada5 clear ui, when loading bin 2025-09-18 11:07:14 -06:00
177c15e9cc fixes 2025-09-18 10:57:08 -06:00
dadde9048d fix loader 2025-09-16 16:52:45 -06:00
ef66933a25 WIP scsi :( 2025-09-16 16:46:24 -06:00
4c6e16270e WIP scsi 2025-09-15 19:54:40 -06:00
903a4ab631 Merge pull request #1 from LegitCamper/fix-fb
Fix fb
2025-09-14 20:47:20 -06:00
505450c8b8 working dynamically loaded app 2025-09-14 20:46:43 -06:00
d934036965 screen tearing kinda poop 2025-09-14 19:12:17 -06:00
919744dbec atomic fb 2025-09-14 18:40:48 -06:00
59f6bf8ef7 update deps 2025-09-13 14:43:54 -06:00
1994d74a17 WIP 2025-09-13 13:57:41 -06:00
13d267f61e can alloc with psram 2025-06-26 20:34:18 -06:00
56 changed files with 5163 additions and 1145 deletions

5
.gitignore vendored
View File

@@ -1 +1,6 @@
/target
*.uf2
abi_sys.h
assets/gif/bad_apple.gif
picolibc
user-apps/gboy/Peanut-GB

6
.gitmodules vendored Normal file
View File

@@ -0,0 +1,6 @@
[submodule "picolibc"]
path = picolibc
url = https://github.com/picolibc/picolibc
[submodule "user-apps/gboy/Peanut-GB"]
path = user-apps/gboy/Peanut-GB
url = https://github.com/deltabeard/Peanut-GB

5
.helix/languages.toml Normal file
View File

@@ -0,0 +1,5 @@
[[language]]
name = "rust"
[language-server.rust-analyzer.config.check]
allTargets = false

1039
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,16 @@
[workspace]
resolver = "3"
members = ["kernel", "abi", "shared", "user-apps/calculator"]
members = [
"kernel",
"abi_sys",
"abi",
"selection_ui",
"user-apps/calculator",
"user-apps/snake",
"user-apps/gallery",
"user-apps/gif",
"user-apps/wav_player",
]
[profile.release]
debug = true
@@ -10,10 +20,12 @@ codegen-units = 1
[profile.release-binary]
inherits = "release"
codegen-units = 1
lto = true
debug = false
opt-level = "s"
opt-level = "z"
panic = "unwind"
[profile.dev]
lto = true
opt-level = "z"
opt-level = "s"

34
README.md Normal file
View File

@@ -0,0 +1,34 @@
# PicoCalc OS (Rust)
A simple operating system for the **Clockwork PicoCalc**, written in Rust.
This project provides a minimal kernel, ABI, and user-space applications to experiment with OS development on constrained hardware.
## Status
Basic synchronous applications are working great.
Current focus is on **expanding the ABI syscalls** and **fixing the MSC/USB-SCSI driver** to make application development easier and smoother.
## Project Structure
- **`kernel/`** The core OS kernel (task scheduling, drivers, memory, etc.)
- **`abi_sys/`** Shared application binary interface definitions for kernel ↔ userspace (Repr "C")
- **`abi/`** Rust focused ABI helpers and abstractions for easier development
- **`user-apps/`** Collection of userspace programs (calculator, snake, etc.)
## Features
- Minimal Rust-based kernel targeting the PicoCalc
- Custom ABI for safe communication between kernel and applications
- Support for multiple user-space applications
- Hardware drivers tailored for the PicoCalc
## Getting Started
```bash
git clone https://github.com/LegitCamper/picocalc-os-rs.git
cd picocalc-os-rs
just userapps
# copy the build applications from target/thumbv8m.main-none-eabihf/release-binary/application to the sdcard and rename them to app.bin
# has builds for the official rp2350 board and the pimoroni2w board
just kernel-release rp235x # keep in mind that https://github.com/StripedMonkey/elf2uf2-rs version is required until https://github.com/JoNil/elf2uf2-rs/pull/41 is merged

View File

@@ -4,9 +4,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
embedded-graphics = "0.8.1"
shared = { path = "../shared" }
abi_sys = { path = "../abi_sys" }
talc = "4.4.3"
spin = "0.10.0"
embassy-time = "0.5.0"
embedded-graphics = "0.8.1"
once_cell = { version = "1", default-features = false }
rand_core = "0.9.3"

View File

@@ -1,24 +1,57 @@
#![no_std]
#![allow(static_mut_refs)]
use abi_sys::draw_iter;
pub use abi_sys::{get_key, print};
pub use embassy_time;
pub use shared::keyboard::{KeyCode, KeyEvent, KeyState, Modifiers};
use talc::*;
extern crate alloc;
static mut ARENA: [u8; 10000] = [0; 10000];
use abi_sys::{RngRequest, keyboard::KeyEvent};
pub use abi_sys::{keyboard, print};
pub use alloc::format;
use core::alloc::{GlobalAlloc, Layout};
use rand_core::RngCore;
#[global_allocator]
static ALLOCATOR: Talck<spin::Mutex<()>, ClaimOnOom> =
Talc::new(unsafe { ClaimOnOom::new(Span::from_array(core::ptr::addr_of!(ARENA).cast_mut())) })
.lock();
static ALLOC: Alloc = Alloc;
struct Alloc;
unsafe impl GlobalAlloc for Alloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
abi_sys::alloc(layout.into())
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
abi_sys::dealloc(ptr, layout.into());
}
}
#[macro_export]
macro_rules! println {
($($arg:tt)*) => {{
let s = $crate::format!($($arg)*);
$crate::print(s.as_ptr(), s.len());
}};
}
pub fn sleep(ms: u64) {
abi_sys::sleep(ms);
}
pub fn get_ms() -> u64 {
abi_sys::get_ms()
}
pub fn get_key() -> KeyEvent {
abi_sys::keyboard::get_key().into()
}
pub mod display {
use crate::draw_iter;
use core::sync::atomic::{AtomicBool, Ordering};
use abi_sys::CPixel;
use embedded_graphics::{
Pixel,
geometry::{Dimensions, Point},
pixelcolor::{Rgb565, RgbColor},
pixelcolor::Rgb565,
prelude::{DrawTarget, Size},
primitives::Rectangle,
};
@@ -28,7 +61,28 @@ pub mod display {
pub type Pixel565 = Pixel<Rgb565>;
pub struct Display;
const BUF_SIZE: usize = 1024;
static mut BUF: [CPixel; BUF_SIZE] = [CPixel::new(); BUF_SIZE];
static DISPLAY_TAKEN: AtomicBool = AtomicBool::new(false);
pub struct Display {
_private: (),
}
impl Display {
/// Only one instance of Display can be taken
pub fn take() -> Option<Display> {
if DISPLAY_TAKEN
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_ok()
{
Some(Self { _private: () })
} else {
None
}
}
}
impl Dimensions for Display {
fn bounding_box(&self) -> Rectangle {
@@ -50,25 +104,174 @@ pub mod display {
where
I: IntoIterator<Item = Pixel<Self::Color>>,
{
const BUF_SIZE: usize = 1024; // tune this for performance
let mut buf: [Pixel565; BUF_SIZE] = [Pixel(Point::new(0, 0), Rgb565::BLACK); BUF_SIZE];
let mut count = 0;
for p in pixels {
buf[count] = p;
unsafe { BUF[count] = p.into() };
count += 1;
if count == BUF_SIZE {
draw_iter(&buf[..count]);
if count == BUF_SIZE - 1 {
abi_sys::draw_iter(unsafe { BUF.as_ptr() }, count);
count = 0;
}
}
if count > 0 {
draw_iter(&buf[..count]);
abi_sys::draw_iter(unsafe { BUF.as_ptr() }, count);
}
Ok(())
}
}
}
fn gen_rand(req: &mut RngRequest) {
abi_sys::gen_rand(req);
}
pub struct Rng;
impl RngCore for Rng {
fn next_u32(&mut self) -> u32 {
let mut req = RngRequest::U32(0);
gen_rand(&mut req);
if let RngRequest::U32(i) = req {
return i;
};
0
}
fn next_u64(&mut self) -> u64 {
let mut req = RngRequest::U64(0);
gen_rand(&mut req);
if let RngRequest::U64(i) = req {
return i;
};
0
}
fn fill_bytes(&mut self, dst: &mut [u8]) {
let mut req = RngRequest::Bytes {
ptr: dst.as_mut_ptr(),
len: dst.len(),
};
gen_rand(&mut req);
}
}
pub mod fs {
use alloc::vec::Vec;
use core::fmt::Display;
pub fn read_file(file: &str, start_from: usize, buf: &mut [u8]) -> usize {
abi_sys::read_file(
file.as_ptr(),
file.len(),
start_from,
buf.as_mut_ptr(),
buf.len(),
)
}
pub fn write_file(file: &str, start_from: usize, buf: &[u8]) {
abi_sys::write_file(
file.as_ptr(),
file.len(),
start_from,
buf.as_ptr(),
buf.len(),
)
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FileName<'a> {
full: &'a str,
base: &'a str,
ext: Option<&'a str>,
}
impl<'a> FileName<'a> {
pub fn full_name(&self) -> &str {
self.full
}
pub fn base(&self) -> &str {
self.base
}
pub fn extension(&self) -> Option<&str> {
self.ext
}
}
impl<'a> Display for FileName<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.full_name())
}
}
impl<'a> From<&'a str> for FileName<'a> {
fn from(s: &'a str) -> FileName<'a> {
let full = s;
// Split on last dot for extension
let (base, ext) = match s.rfind('.') {
Some(idx) => (&s[..idx], Some(&s[idx + 1..])),
None => (s, None),
};
FileName { full, base, ext }
}
}
const MAX_ENTRY_NAME_LEN: usize = 25;
const MAX_ENTRIES: usize = 25;
#[derive(Clone, Copy, Debug)]
pub struct Entries([[u8; MAX_ENTRY_NAME_LEN]; MAX_ENTRIES]);
impl Entries {
pub fn new() -> Self {
Self([[0; MAX_ENTRY_NAME_LEN]; MAX_ENTRIES])
}
/// Get list of file names after listing
pub fn entries<'a>(&'a self) -> Vec<FileName<'a>> {
self.0
.iter()
.filter_map(|buf| {
let nul_pos = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
Some(core::str::from_utf8(&buf[..nul_pos]).ok()?.into())
})
.collect()
}
fn as_ptrs(&mut self) -> [*mut u8; MAX_ENTRIES] {
let mut ptrs: [*mut u8; MAX_ENTRIES] = [core::ptr::null_mut(); MAX_ENTRIES];
for (i, buf) in self.0.iter_mut().enumerate() {
ptrs[i] = buf.as_mut_ptr();
}
ptrs
}
}
pub fn list_dir(path: &str, entries: &mut Entries) -> usize {
abi_sys::list_dir(
path.as_ptr(),
path.len(),
entries.as_ptrs().as_mut_ptr(),
MAX_ENTRIES,
MAX_ENTRY_NAME_LEN,
)
}
pub fn file_len(str: &str) -> usize {
abi_sys::file_len(str.as_ptr(), str.len())
}
}
pub mod audio {
pub use abi_sys::{AUDIO_BUFFER_LEN, AUDIO_BUFFER_SAMPLES, audio_buffer_ready};
pub fn send_audio_buffer(buf: &[u8]) {
abi_sys::send_audio_buffer(buf.as_ptr(), buf.len())
}
}

View File

@@ -3,6 +3,16 @@ name = "abi_sys"
version = "0.1.0"
edition = "2024"
[features]
default = ["alloc"]
alloc = []
defmt = ["dep:defmt"]
[dependencies]
strum = { version = "0.27.2", default-features = false, features = ["derive"] }
bitflags = "2.9.4"
embedded-graphics = "0.8.1"
shared = { path = "../shared" }
defmt = { version = "0.3", optional = true }
[build-dependencies]
cbindgen = "0.24.0"

View File

@@ -1,60 +1,496 @@
#![no_std]
#[cfg(feature = "alloc")]
use core::alloc::Layout;
extern crate alloc;
use alloc::boxed::Box;
use core::pin::Pin;
pub use embedded_graphics::{
use core::ffi::c_char;
use embedded_graphics::{
Pixel,
geometry::Point,
pixelcolor::{Rgb565, RgbColor},
pixelcolor::{Rgb565, raw::RawU16},
prelude::{IntoStorage, Point},
};
use shared::keyboard::{KeyCode, KeyEvent, KeyState, Modifiers};
use strum::{EnumCount, EnumIter};
pub type EntryFn = fn() -> Pin<Box<dyn Future<Output = ()>>>;
pub type EntryFn = fn();
pub const ABI_CALL_TABLE_COUNT: usize = 14;
const _: () = assert!(ABI_CALL_TABLE_COUNT == CallTable::COUNT);
#[derive(Clone, Copy, EnumIter, EnumCount)]
#[repr(u8)]
pub enum CallTable {
Alloc = 0,
Dealloc = 1,
PrintString = 2,
SleepMs = 3,
GetMs = 4,
DrawIter = 5,
GetKey = 6,
GenRand = 7,
ListDir = 8,
ReadFile = 9,
WriteFile = 10,
FileLen = 11,
AudioBufferReady = 12,
SendAudioBuffer = 13,
}
#[unsafe(no_mangle)]
#[unsafe(link_section = ".user_reloc")]
pub static mut CALL_ABI_TABLE: [usize; CallAbiTable::COUNT] = [0; CallAbiTable::COUNT];
#[unsafe(link_section = ".syscall_table")]
pub static mut CALL_ABI_TABLE: [usize; ABI_CALL_TABLE_COUNT] = [0; ABI_CALL_TABLE_COUNT];
#[repr(usize)]
#[derive(Clone, Copy)]
pub enum CallAbiTable {
Print = 0,
DrawIter = 1,
GetKey = 2,
#[cfg(feature = "alloc")]
#[repr(C)]
pub struct CLayout {
size: usize,
alignment: usize,
}
impl CallAbiTable {
pub const COUNT: usize = 3;
}
pub type PrintAbi = extern "Rust" fn(msg: &str);
pub fn print(msg: &str) {
unsafe {
let ptr = CALL_ABI_TABLE[CallAbiTable::Print as usize];
let f: PrintAbi = core::mem::transmute(ptr);
f(msg);
#[cfg(feature = "alloc")]
impl Into<Layout> for CLayout {
fn into(self) -> Layout {
unsafe { Layout::from_size_align_unchecked(self.size, self.alignment) }
}
}
pub type DrawIterAbi = extern "Rust" fn(pixels: &[Pixel<Rgb565>]);
pub fn draw_iter(pixels: &[Pixel<Rgb565>]) {
unsafe {
let ptr = CALL_ABI_TABLE[CallAbiTable::DrawIter as usize];
let f: DrawIterAbi = core::mem::transmute(ptr);
f(pixels);
#[cfg(feature = "alloc")]
impl From<Layout> for CLayout {
fn from(value: Layout) -> Self {
Self {
size: value.size(),
alignment: value.align(),
}
}
}
pub type GetKeyAbi = extern "Rust" fn() -> Option<KeyEvent>;
pub type AllocAbi = extern "C" fn(layout: CLayout) -> *mut u8;
pub fn get_key() -> Option<KeyEvent> {
unsafe {
let ptr = CALL_ABI_TABLE[CallAbiTable::GetKey as usize];
let f: GetKeyAbi = core::mem::transmute(ptr);
#[unsafe(no_mangle)]
pub extern "C" fn alloc(layout: CLayout) -> *mut u8 {
let f: AllocAbi = unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::Alloc as usize]) };
f(layout)
}
pub type DeallocAbi = extern "C" fn(ptr: *mut u8, layout: CLayout);
#[unsafe(no_mangle)]
pub extern "C" fn dealloc(ptr: *mut u8, layout: CLayout) {
let f: DeallocAbi =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::Dealloc as usize]) };
f(ptr, layout)
}
pub type PrintAbi = extern "C" fn(ptr: *const u8, len: usize);
#[unsafe(no_mangle)]
pub extern "C" fn print(ptr: *const u8, len: usize) {
let f: PrintAbi =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::PrintString as usize]) };
f(ptr, len);
}
pub type SleepMsAbi = extern "C" fn(ms: u64);
#[unsafe(no_mangle)]
pub extern "C" fn sleep(ms: u64) {
let f: SleepMsAbi =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::SleepMs as usize]) };
f(ms);
}
pub type GetMsAbi = extern "C" fn() -> u64;
#[unsafe(no_mangle)]
pub extern "C" fn get_ms() -> u64 {
let f: GetMsAbi = unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::GetMs as usize]) };
f()
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct CPixel {
pub x: i32,
pub y: i32,
pub color: u16,
}
impl CPixel {
pub const fn new() -> Self {
Self {
x: 0,
y: 0,
color: 0,
}
}
}
impl Into<CPixel> for Pixel<Rgb565> {
fn into(self) -> CPixel {
CPixel {
x: self.0.x,
y: self.0.y,
color: self.1.into_storage(),
}
}
}
impl Into<Pixel<Rgb565>> for CPixel {
fn into(self) -> Pixel<Rgb565> {
Pixel(Point::new(self.x, self.y), RawU16::new(self.color).into())
}
}
pub type DrawIterAbi = extern "C" fn(ptr: *const CPixel, len: usize);
#[unsafe(no_mangle)]
pub extern "C" fn draw_iter(ptr: *const CPixel, len: usize) {
let f: DrawIterAbi =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::DrawIter as usize]) };
f(ptr, len);
}
pub mod keyboard {
use crate::{CALL_ABI_TABLE, CallTable};
bitflags::bitflags! {
#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)]
#[repr(C)]
pub struct Modifiers: u8 {
const NONE = 0;
const CTRL = 1;
const ALT = 2;
const LSHIFT = 4;
const RSHIFT = 8;
const SYM = 16;
}
}
#[repr(C)]
pub struct KeyEventC {
pub key: u8,
pub state: KeyState,
pub mods: Modifiers,
}
impl Into<KeyEvent> for KeyEventC {
fn into(self) -> KeyEvent {
KeyEvent {
key: self.key.into(),
state: self.state,
mods: self.mods,
}
}
}
#[derive(Debug)]
pub struct KeyEvent {
pub key: KeyCode,
pub state: KeyState,
pub mods: Modifiers,
}
impl Into<KeyEventC> for KeyEvent {
fn into(self) -> KeyEventC {
KeyEventC {
key: self.key.into(),
state: self.state,
mods: self.mods,
}
}
}
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum KeyState {
Idle = 0,
Pressed = 1,
Hold = 2,
Released = 3,
}
impl From<u8> for KeyState {
fn from(value: u8) -> Self {
match value {
1 => KeyState::Pressed,
2 => KeyState::Hold,
3 => KeyState::Released,
0 | _ => KeyState::Idle,
}
}
}
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum KeyCode {
JoyUp = 0x01,
JoyDown = 0x02,
JoyLeft = 0x03,
JoyRight = 0x04,
JoyCenter = 0x05,
BtnLeft1 = 0x06,
BtnRight1 = 0x07,
BtnLeft2 = 0x11,
BtnRight2 = 0x12,
Backspace = 0x08,
Tab = 0x09,
Enter = 0x0A,
ModAlt = 0xA1,
ModShiftLeft = 0xA2,
ModShiftRight = 0xA3,
ModSym = 0xA4,
ModCtrl = 0xA5,
Esc = 0xB1,
Left = 0xB4,
Up = 0xB5,
Down = 0xB6,
Right = 0xB7,
Break = 0xD0,
Insert = 0xD1,
Home = 0xD2,
Del = 0xD4,
End = 0xD5,
PageUp = 0xD6,
PageDown = 0xD7,
CapsLock = 0xC1,
F1 = 0x81,
F2 = 0x82,
F3 = 0x83,
F4 = 0x84,
F5 = 0x85,
F6 = 0x86,
F7 = 0x87,
F8 = 0x88,
F9 = 0x89,
F10 = 0x90,
Char(char),
Unknown(u8),
}
impl Into<u8> for KeyCode {
fn into(self) -> u8 {
match self {
KeyCode::JoyUp => 0x01,
KeyCode::JoyDown => 0x02,
KeyCode::JoyLeft => 0x03,
KeyCode::JoyRight => 0x04,
KeyCode::JoyCenter => 0x05,
KeyCode::BtnLeft1 => 0x06,
KeyCode::BtnRight1 => 0x07,
KeyCode::BtnLeft2 => 0x11,
KeyCode::BtnRight2 => 0x12,
KeyCode::Backspace => 0x08,
KeyCode::Tab => 0x09,
KeyCode::Enter => 0x0A,
KeyCode::ModAlt => 0xA1,
KeyCode::ModShiftLeft => 0xA2,
KeyCode::ModShiftRight => 0xA3,
KeyCode::ModSym => 0xA4,
KeyCode::ModCtrl => 0xA5,
KeyCode::Esc => 0xB1,
KeyCode::Left => 0xB4,
KeyCode::Up => 0xB5,
KeyCode::Down => 0xB6,
KeyCode::Right => 0xB7,
KeyCode::Break => 0xD0,
KeyCode::Insert => 0xD1,
KeyCode::Home => 0xD2,
KeyCode::Del => 0xD4,
KeyCode::End => 0xD5,
KeyCode::PageUp => 0xD6,
KeyCode::PageDown => 0xD7,
KeyCode::CapsLock => 0xC1,
KeyCode::F1 => 0x81,
KeyCode::F2 => 0x82,
KeyCode::F3 => 0x83,
KeyCode::F4 => 0x84,
KeyCode::F5 => 0x85,
KeyCode::F6 => 0x86,
KeyCode::F7 => 0x87,
KeyCode::F8 => 0x88,
KeyCode::F9 => 0x89,
KeyCode::F10 => 0x90,
KeyCode::Char(char) => char as u8,
KeyCode::Unknown(i) => i,
}
}
}
impl From<u8> for KeyCode {
fn from(value: u8) -> Self {
match value {
0x01 => Self::JoyUp,
0x02 => Self::JoyDown,
0x03 => Self::JoyLeft,
0x04 => Self::JoyRight,
0x05 => Self::JoyCenter,
0x06 => Self::BtnLeft1,
0x07 => Self::BtnRight1,
0x08 => Self::Backspace,
0x09 => Self::Tab,
0x0A => Self::Enter,
0x11 => Self::BtnLeft2,
0x12 => Self::BtnRight2,
0xA1 => Self::ModAlt,
0xA2 => Self::ModShiftLeft,
0xA3 => Self::ModShiftRight,
0xA4 => Self::ModSym,
0xA5 => Self::ModCtrl,
0xB1 => Self::Esc,
0xB4 => Self::Left,
0xB5 => Self::Up,
0xB6 => Self::Down,
0xB7 => Self::Right,
0xC1 => Self::CapsLock,
0xD0 => Self::Break,
0xD1 => Self::Insert,
0xD2 => Self::Home,
0xD4 => Self::Del,
0xD5 => Self::End,
0xD6 => Self::PageUp,
0xD7 => Self::PageDown,
0x81 => Self::F1,
0x82 => Self::F2,
0x83 => Self::F3,
0x84 => Self::F4,
0x85 => Self::F5,
0x86 => Self::F6,
0x87 => Self::F7,
0x88 => Self::F8,
0x89 => Self::F9,
0x90 => Self::F10,
_ => match char::from_u32(value as u32) {
Some(c) => Self::Char(c),
None => Self::Unknown(value),
},
}
}
}
pub type GetKeyAbi = extern "C" fn() -> KeyEventC;
#[unsafe(no_mangle)]
pub extern "C" fn get_key() -> KeyEventC {
let f: GetKeyAbi =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::GetKey as usize]) };
f()
}
}
#[repr(C)]
pub enum RngRequest {
U32(u32),
U64(u64),
Bytes { ptr: *mut u8, len: usize },
}
pub type GenRand = extern "C" fn(req: &mut RngRequest);
#[unsafe(no_mangle)]
pub extern "C" fn gen_rand(req: &mut RngRequest) {
unsafe {
let ptr = CALL_ABI_TABLE[CallTable::GenRand as usize];
let f: GenRand = core::mem::transmute(ptr);
f(req)
}
}
pub type ListDir = extern "C" fn(
str: *const u8,
len: usize,
entries: *mut *mut c_char,
file_len: usize,
max_entry_str_len: usize,
) -> usize;
#[unsafe(no_mangle)]
pub extern "C" fn list_dir(
str: *const u8,
len: usize,
entries: *mut *mut c_char,
entry_count: usize,
max_entry_str_len: usize,
) -> usize {
unsafe {
let ptr = CALL_ABI_TABLE[CallTable::ListDir as usize];
let f: ListDir = core::mem::transmute(ptr);
f(str, len, entries, entry_count, max_entry_str_len)
}
}
pub type ReadFile = extern "C" fn(
str: *const u8,
len: usize,
read_from: usize,
buf: *mut u8,
buf_len: usize,
) -> usize;
#[unsafe(no_mangle)]
pub extern "C" fn read_file(
str: *const u8,
len: usize,
read_from: usize,
buf: *mut u8,
buf_len: usize,
) -> usize {
unsafe {
let ptr = CALL_ABI_TABLE[CallTable::ReadFile as usize];
let f: ReadFile = core::mem::transmute(ptr);
f(str, len, read_from, buf, buf_len)
}
}
pub type WriteFile =
extern "C" fn(str: *const u8, len: usize, write_from: usize, buf: *const u8, buf_len: usize);
#[unsafe(no_mangle)]
pub extern "C" fn write_file(
str: *const u8,
len: usize,
write_from: usize,
buf: *const u8,
buf_len: usize,
) {
unsafe {
let ptr = CALL_ABI_TABLE[CallTable::WriteFile as usize];
let f: WriteFile = core::mem::transmute(ptr);
f(str, len, write_from, buf, buf_len)
}
}
pub type FileLen = extern "C" fn(str: *const u8, len: usize) -> usize;
#[unsafe(no_mangle)]
pub extern "C" fn file_len(str: *const u8, len: usize) -> usize {
unsafe {
let ptr = CALL_ABI_TABLE[CallTable::FileLen as usize];
let f: FileLen = core::mem::transmute(ptr);
f(str, len)
}
}
pub type AudioBufferReady = extern "C" fn() -> bool;
#[allow(unused)]
pub fn audio_buffer_ready() -> bool {
unsafe {
let ptr = CALL_ABI_TABLE[CallTable::AudioBufferReady as usize];
let f: AudioBufferReady = core::mem::transmute(ptr);
f()
}
}
pub const AUDIO_BUFFER_SAMPLES: usize = 1024;
pub const AUDIO_BUFFER_LEN: usize = AUDIO_BUFFER_SAMPLES * 2;
pub type SendAudioBuffer = extern "C" fn(ptr: *const u8, len: usize);
#[allow(unused)]
pub fn send_audio_buffer(buf: *const u8, len: usize) {
unsafe {
let ptr = CALL_ABI_TABLE[CallTable::SendAudioBuffer as usize];
let f: SendAudioBuffer = core::mem::transmute(ptr);
f(buf, len)
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

4
cbindgen.toml Normal file
View File

@@ -0,0 +1,4 @@
language = "C"
[macro_expansion]
bitflags = true

View File

@@ -1,4 +1,58 @@
kernel: calculator
cargo run --bin kernel
calculator:
RUSTFLAGS="-C link-arg=--noinhibit-exec" cargo build --bin calculator --profile release-binary
kernel-dev board:
cargo run --bin kernel --features {{board}} --features fps
kernel-release-probe board:
cargo run --bin kernel --profile release --features {{board}} --features fps
kernel-release board:
cargo build --bin kernel --release --no-default-features --features {{board}}
elf2uf2-rs -d target/thumbv8m.main-none-eabihf/release/kernel
binary-args := "RUSTFLAGS=\"-C link-arg=-pie -C relocation-model=pic\""
cbindgen:
cbindgen abi_sys --output abi_sys.h -q
newlib:
#!/bin/bash
cd picolibc
mkdir build
cd build
CONFIG_PICOLIBC=true ../scripts/do-configure thumbv8m_main_fp-none-eabi \
--buildtype=minsize \
-Dtests=true \
-Dtinystdio=false \
-Dsingle-thread=true \
-Db_pie=true \
-Ddefault_library=static \
-Dtinystdio=false \
-Dnewlib-nano-malloc=true \
-Dmultilib=false \
-Dpicolib=true \
"$@"
DESTDIR=./install meson install
ninja
userapp app:
{{binary-args}} cargo build --bin {{app}} --profile release-binary
userapps: cbindgen
just userapp calculator
just userapp snake
just userapp gallery
just userapp gif
just userapp wav_player
copy-userapp app:
cp ./target/thumbv8m.main-none-eabihf/release-binary/{{app}} /run/media/$(whoami)/PICOCALC/{{app}}.bin
copy-userapps:
#!/bin/bash
just userapps
just copy-userapp calculator
just copy-userapp snake
just copy-userapp gallery
just copy-userapp gif
just copy-userapp wav_player
DEV=$(lsblk -o LABEL,NAME -nr | awk -v L="PICOCALC" '$1==L {print "/dev/" $2}')
udisksctl unmount -b "$DEV"
udisksctl power-off -b "$DEV"

View File

@@ -1,6 +1,6 @@
[package]
name = "kernel"
version = "0.1.0"
version = "0.0.1"
edition = "2024"
[[bin]]
@@ -12,9 +12,13 @@ bench = false
[features]
default = ["rp235x", "defmt"]
rp2040 = ["embassy-rp/rp2040"]
pimoroni2w = ["rp235x", "psram"]
# rp2040 = ["embassy-rp/rp2040"] # unsupported, ram too small for fb
rp235x = ["embassy-rp/rp235xb"]
trouble = ["dep:bt-hci", "dep:cyw43", "dep:cyw43-pio", "dep:trouble-host"]
psram = ["dep:embedded-alloc"]
overclock = []
fps = []
defmt = [
"dep:defmt",
"panic-probe/print-defmt",
@@ -31,21 +35,21 @@ defmt = [
]
[dependencies]
embassy-executor = { version = "0.7", features = [
embassy-executor = { version = "0.9", features = [
"arch-cortex-m",
"executor-interrupt",
"executor-thread",
"nightly",
] }
embassy-rp = { version = "0.4.0", features = [
embassy-rp = { version = "0.8.0", features = [
"critical-section-impl",
"unstable-pac",
"time-driver",
] }
embassy-usb = "0.4.0"
embassy-futures = "0.1.1"
embassy-time = { version = "0.4.0", features = ["generic-queue-8"] }
embassy-embedded-hal = "0.3.1"
embassy-usb = "0.5.1"
embassy-futures = "0.1.2"
embassy-time = { version = "0.5.0", features = ["generic-queue-8"] }
embassy-embedded-hal = "0.3.2"
embassy-sync = { version = "0.7" }
trouble-host = { version = "0.1", features = [
"derive",
@@ -58,31 +62,41 @@ cyw43 = { version = "0.3.0", features = [
], optional = true }
cyw43-pio = { version = "0.3.0", optional = true }
critical-section = "1.2.0"
embedded-hal-bus = { version = "0.3.0", features = ["async"] }
embedded-hal = "0.2.7"
embedded-hal_2 = { package = "embedded-hal", version = "1.0.0" }
embedded-hal-async = "1.0.0"
cortex-m = { version = "0.7.7" }
cortex-m-rt = "0.7.5"
panic-probe = "0.3"
portable-atomic = { version = "1.11", features = ["critical-section"] }
assign-resources = "0.5.0"
defmt = { version = "0.3", optional = true }
defmt-rtt = "0.4.2"
defmt = { version = "1.0.1", optional = true }
defmt-rtt = "1.1.0"
embedded-sdmmc = { version = "0.9", default-features = false }
# st7365p-lcd = { git = "https://github.com/legitcamper/st7365p-lcd-rs", rev = "87abf450404865dcb535292e9e1a6a2457fd4599" } # async branch
st7365p-lcd = { path = "../../ST7365P-lcd-rs" } # async branch
st7365p-lcd = { git = "https://github.com/legitcamper/st7365p-lcd-rs", rev = "a784b9e6df0769371dfc522528e770cf8fc6403a" } # async branch
embedded-graphics = { version = "0.8.1" }
embedded-text = "0.7.2"
embedded-layout = "0.4.2"
micromath = "2.1.0"
fixed = "1.29.0"
strum = { version = "0.27.2", default-features = false }
rand = { version = "0.9.0", default-features = false }
once_cell = { version = "1.21.3", default-features = false }
static_cell = "2.1.1"
bitflags = "2.9.1"
bitflags = "2.9.4"
heapless = "0.8.0"
num_enum = { version = "0.7.4", default-features = false }
goblin = { version = "0.10.0", default-features = false, features = ["elf32"] }
talc = "4.4.3"
spin = "0.10.0"
num_enum = { version = "0.7.4", default-features = false }
goblin = { version = "0.10.1", default-features = false, features = ["elf32"] }
talc = "4.4.3"
embedded-alloc = { version = "0.6.0", features = [
"allocator_api",
], optional = true }
bumpalo = "3.19.0"
shared = { path = "../shared" }
abi_sys = { path = "../abi_sys" }

View File

@@ -13,13 +13,18 @@ use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
#[cfg(all(feature = "rp235x", not(feature = "pimoroni2w")))]
const MEMORY: &'static [u8] = include_bytes!("rp2350.x");
#[cfg(feature = "pimoroni2w")]
const MEMORY: &'static [u8] = include_bytes!("rp2350.x");
fn main() {
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("memory.x"))
.write_all(MEMORY)
.unwrap();
println!("cargo:rustc-link-search={}", out.display());

60
kernel/pimoroni2w.x Normal file
View File

@@ -0,0 +1,60 @@
MEMORY {
FLASH : ORIGIN = 0x10000000, LENGTH = 16M - 4K
RAM : ORIGIN = 0x20000000, LENGTH = 512K
# SRAM4 : ORIGIN = 0x20080000, LENGTH = 4K
SRAM5 : ORIGIN = 0x20081000, LENGTH = 4K
}
SECTIONS {
/* ### Boot ROM info
*
* Goes after .vector_table, to keep it in the first 4K of flash
* where the Boot ROM (and picotool) can find it
*/
.start_block : ALIGN(4)
{
__start_block_addr = .;
KEEP(*(.start_block));
KEEP(*(.boot_info));
} > FLASH
} INSERT AFTER .vector_table;
/* move .text to start /after/ the boot info */
_stext = ADDR(.start_block) + SIZEOF(.start_block);
SECTIONS {
/* ### Picotool 'Binary Info' Entries
*
* Picotool looks through this block (as we have pointers to it in our
* header) to find interesting information.
*/
.bi_entries : ALIGN(4)
{
/* We put this in the header */
__bi_entries_start = .;
/* Here are the entries */
KEEP(*(.bi_entries));
/* Keep this block a nice round size */
. = ALIGN(4);
/* We put this in the header */
__bi_entries_end = .;
} > FLASH
} INSERT AFTER .text;
SECTIONS {
/* ### Boot ROM extra info
*
* Goes after everything in our program, so it can contain a signature.
*/
.end_block : ALIGN(4)
{
__end_block_addr = .;
KEEP(*(.end_block));
} > FLASH
} INSERT AFTER .uninit;
PROVIDE(start_to_end = __end_block_addr - __start_block_addr);
PROVIDE(end_to_start = __start_block_addr - __end_block_addr);

View File

@@ -1,10 +1,7 @@
MEMORY {
FLASH : ORIGIN = 0x10000000, LENGTH = 4096K
RAM : ORIGIN = 0x20000000, LENGTH = 512K
/* Reserve a block of RAM for the user app */
USERAPP : ORIGIN = 0x20010000, LENGTH = 192K
SRAM4 : ORIGIN = 0x20080000, LENGTH = 4K
SRAM5 : ORIGIN = 0x20081000, LENGTH = 4K
}
@@ -61,11 +58,3 @@ SECTIONS {
PROVIDE(start_to_end = __end_block_addr - __start_block_addr);
PROVIDE(end_to_start = __start_block_addr - __end_block_addr);
SECTIONS {
.userapp (NOLOAD) :
{
__userapp_start__ = ORIGIN(USERAPP);
__userapp_end__ = ORIGIN(USERAPP) + LENGTH(USERAPP);
} > USERAPP
}

View File

@@ -1,34 +1,359 @@
use core::pin::Pin;
use abi_sys::{DrawIterAbi, GetKeyAbi, Pixel, PrintAbi};
use alloc::boxed::Box;
use defmt::info;
use embedded_graphics::{
Drawable,
draw_target::DrawTarget,
pixelcolor::Rgb565,
prelude::{Point, RgbColor, Size},
primitives::{PrimitiveStyle, Rectangle, StyledDrawable},
use abi_sys::{
AUDIO_BUFFER_SAMPLES, AllocAbi, AudioBufferReady, CLayout, CPixel, DeallocAbi, DrawIterAbi,
FileLen, GenRand, GetMsAbi, ListDir, PrintAbi, ReadFile, RngRequest, SendAudioBuffer,
SleepMsAbi, WriteFile, keyboard::*,
};
use shared::keyboard::KeyEvent;
use alloc::{string::ToString, vec::Vec};
use core::{ffi::c_char, ptr, sync::atomic::Ordering};
use embassy_rp::clocks::{RoscRng, clk_sys_freq};
use embassy_time::Instant;
use embedded_graphics::draw_target::DrawTarget;
use embedded_sdmmc::LfnBuffer;
use heapless::spsc::Queue;
use crate::{KEY_CACHE, display::framebuffer_mut};
#[cfg(feature = "psram")]
use crate::heap::HEAP;
#[cfg(feature = "psram")]
use core::alloc::GlobalAlloc;
use crate::{
audio::{AUDIO_BUFFER, AUDIO_BUFFER_READY},
display::FRAMEBUFFER,
framebuffer::FB_PAUSED,
storage::{Dir, File, SDCARD},
};
const _: AllocAbi = alloc;
pub extern "C" fn alloc(layout: CLayout) -> *mut u8 {
// SAFETY: caller guarantees layout is valid
unsafe {
#[cfg(feature = "psram")]
{
return HEAP.alloc(layout.into());
}
#[cfg(not(feature = "psram"))]
{
return alloc::alloc::alloc(layout.into());
}
}
}
const _: DeallocAbi = dealloc;
pub extern "C" fn dealloc(ptr: *mut u8, layout: CLayout) {
// SAFETY: caller guarantees ptr and layout are valid
#[cfg(feature = "psram")]
{
unsafe { HEAP.dealloc(ptr, layout.into()) }
}
#[cfg(not(feature = "psram"))]
{
unsafe { alloc::alloc::dealloc(ptr, layout.into()) }
}
}
// ensure the abi and the kernel fn signatures are the same
const _: PrintAbi = print;
pub extern "C" fn print(ptr: *const u8, len: usize) {
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
let slice = unsafe { core::slice::from_raw_parts(ptr, len) };
if let Ok(_msg) = core::str::from_utf8(slice) {
#[cfg(feature = "defmt")]
defmt::info!("print: {}", _msg);
} else {
#[cfg(feature = "defmt")]
defmt::warn!("print: <invalid utf8>");
}
}
const _: SleepMsAbi = sleep;
pub extern "C" fn sleep(ms: u64) {
let cycles_per_ms = clk_sys_freq() / 1000;
let total_cycles = ms * cycles_per_ms as u64;
for _ in 0..total_cycles {
cortex_m::asm::nop();
}
}
pub static mut MS_SINCE_LAUNCH: Option<Instant> = None;
const _: GetMsAbi = get_ms;
pub extern "C" fn get_ms() -> u64 {
Instant::now()
.duration_since(unsafe { MS_SINCE_LAUNCH.unwrap() })
.as_millis()
}
const _: DrawIterAbi = draw_iter;
pub extern "C" fn draw_iter(cpixels: *const CPixel, len: usize) {
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
let cpixels = unsafe { core::slice::from_raw_parts(cpixels, len) };
let iter = cpixels.iter().copied().map(|c: CPixel| c.into());
FB_PAUSED.store(true, Ordering::Release);
unsafe { FRAMEBUFFER.as_mut().unwrap().draw_iter(iter).unwrap() }
FB_PAUSED.store(false, Ordering::Release);
}
pub static mut KEY_CACHE: Queue<KeyEvent, 32> = Queue::new();
const _: GetKeyAbi = get_key;
pub extern "Rust" fn print(msg: &str) {
defmt::info!("{:?}", msg);
pub extern "C" fn get_key() -> KeyEventC {
if let Some(event) = unsafe { KEY_CACHE.dequeue() } {
event.into()
} else {
KeyEvent {
key: KeyCode::Unknown(0),
state: KeyState::Idle,
mods: Modifiers::empty(),
}
.into()
}
}
// TODO: maybe return result
pub extern "Rust" fn draw_iter(pixels: &[Pixel<Rgb565>]) {
let fb = framebuffer_mut();
fb.draw_iter(pixels.iter().copied()).unwrap();
const _: GenRand = gen_rand;
pub extern "C" fn gen_rand(req: &mut RngRequest) {
let mut rng = RoscRng;
match req {
RngRequest::U32(i) => *i = rng.next_u32(),
RngRequest::U64(i) => *i = rng.next_u64(),
RngRequest::Bytes { ptr, len } => {
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
let slice: &mut [u8] = unsafe { core::slice::from_raw_parts_mut(*ptr, *len) };
rng.fill_bytes(slice);
}
}
}
pub extern "Rust" fn get_key() -> Option<KeyEvent> {
unsafe { KEY_CACHE.dequeue() }
unsafe fn copy_entry_to_user_buf(name: &[u8], dest: *mut c_char, max_str_len: usize) {
if !dest.is_null() {
let len = name.len().min(max_str_len - 1);
unsafe {
ptr::copy_nonoverlapping(name.as_ptr(), dest as *mut u8, len);
*dest.add(len) = 0; // nul terminator
}
}
}
unsafe fn get_dir_entries(dir: &Dir, entries: &mut [*mut c_char], max_str_len: usize) -> usize {
let mut b = [0; 25];
let mut buf = LfnBuffer::new(&mut b);
let mut i = 0;
dir.iterate_dir_lfn(&mut buf, |entry, lfn_name| {
if i < entries.len() {
if let Some(name) = lfn_name {
unsafe { copy_entry_to_user_buf(name.as_bytes(), entries[i], max_str_len) };
} else {
unsafe { copy_entry_to_user_buf(entry.name.base_name(), entries[i], max_str_len) };
}
i += 1;
}
})
.unwrap();
i
}
unsafe fn recurse_dir(
dir: &Dir,
dirs: &[&str],
entries: &mut [*mut c_char],
max_str_len: usize,
) -> usize {
if dirs.is_empty() {
return unsafe { get_dir_entries(dir, entries, max_str_len) };
}
let dir = dir.open_dir(dirs[0]).unwrap();
unsafe { recurse_dir(&dir, &dirs[1..], entries, max_str_len) }
}
const _: ListDir = list_dir;
pub extern "C" fn list_dir(
dir: *const u8,
len: usize,
entries: *mut *mut c_char,
files_len: usize,
max_entry_str_len: usize,
) -> usize {
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
let files = unsafe { core::slice::from_raw_parts_mut(entries, files_len) };
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
let dir = unsafe { core::str::from_raw_parts(dir, len) };
let dirs: Vec<&str> = dir.split('/').collect();
let mut guard = SDCARD.get().try_lock().expect("Failed to get sdcard");
let sd = guard.as_mut().unwrap();
let mut wrote = 0;
sd.access_root_dir(|root| {
if dirs[0] == "" && dirs.len() >= 2 {
unsafe {
if dir == "/" {
wrote = get_dir_entries(&root, files, max_entry_str_len);
} else {
wrote = recurse_dir(&root, &dirs[1..], files, max_entry_str_len);
}
}
}
});
wrote
}
fn recurse_file<T>(
dir: &Dir,
dirs: &[&str],
mut access: impl FnMut(&mut File) -> T,
) -> Result<T, ()> {
if dirs.len() == 1 {
let mut b = [0_u8; 50];
let mut buf = LfnBuffer::new(&mut b);
let mut short_name = None;
dir.iterate_dir_lfn(&mut buf, |entry, name| {
if let Some(name) = name {
if name == dirs[0] || entry.name.to_string().as_str() == dirs[0] {
short_name = Some(entry.name.clone());
}
}
})
.expect("Failed to iterate dir");
if let Some(name) = short_name {
let mut file = dir
.open_file_in_dir(name, embedded_sdmmc::Mode::ReadWriteAppend)
.map_err(|_| ())?;
return Ok(access(&mut file));
}
return Err(());
}
let dir = dir.open_dir(dirs[0]).unwrap();
recurse_file(&dir, &dirs[1..], access)
}
const _: ReadFile = read_file;
pub extern "C" fn read_file(
str: *const u8,
len: usize,
start_from: usize,
buf: *mut u8,
buf_len: usize,
) -> usize {
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
let file = unsafe { core::str::from_raw_parts(str, len) };
let mut components: [&str; 8] = [""; 8];
let mut count = 0;
for part in file.split('/') {
if count >= components.len() {
break;
}
components[count] = part;
count += 1;
}
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
let mut buf = unsafe { core::slice::from_raw_parts_mut(buf, buf_len) };
let mut read = 0;
let mut guard = SDCARD.get().try_lock().expect("Failed to get sdcard");
let sd = guard.as_mut().unwrap();
if !file.is_empty() {
sd.access_root_dir(|root| {
if let Ok(result) = recurse_file(&root, &components[1..count], |file| {
file.seek_from_start(start_from as u32).unwrap_or(());
file.read(&mut buf).unwrap()
}) {
read = result
};
});
}
read
}
const _: WriteFile = write_file;
pub extern "C" fn write_file(
str: *const u8,
len: usize,
start_from: usize,
buf: *const u8,
buf_len: usize,
) {
// SAFETY: caller guarantees str ptr is valid for `len` bytes
let file = unsafe { core::str::from_raw_parts(str, len) };
let mut components: [&str; 8] = [""; 8];
let mut count = 0;
for part in file.split('/') {
if count >= components.len() {
break;
}
components[count] = part;
count += 1;
}
// SAFETY: caller guarantees buf ptr is valid for `buf_len` bytes
let buf = unsafe { core::slice::from_raw_parts(buf, buf_len) };
let mut guard = SDCARD.get().try_lock().expect("Failed to get sdcard");
let sd = guard.as_mut().unwrap();
if !file.is_empty() {
sd.access_root_dir(|root| {
recurse_file(&root, &components[1..count], |file| {
file.seek_from_start(start_from as u32).unwrap();
file.write(&buf).unwrap()
})
.unwrap_or(())
});
};
}
const _: FileLen = file_len;
pub extern "C" fn file_len(str: *const u8, len: usize) -> usize {
// SAFETY: caller guarantees str ptr is valid for `len` bytes
let file = unsafe { core::str::from_raw_parts(str, len) };
let file: Vec<&str> = file.split('/').collect();
let mut len = 0;
let mut guard = SDCARD.get().try_lock().expect("Failed to get sdcard");
let sd = guard.as_mut().unwrap();
if !file.is_empty() {
sd.access_root_dir(|root| {
if let Ok(result) = recurse_file(&root, &file[1..], |file| file.length()) {
len = result
}
});
}
len as usize
}
const _: AudioBufferReady = audio_buffer_ready;
pub extern "C" fn audio_buffer_ready() -> bool {
AUDIO_BUFFER_READY.load(Ordering::Acquire)
}
const _: SendAudioBuffer = send_audio_buffer;
pub extern "C" fn send_audio_buffer(ptr: *const u8, len: usize) {
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
let buf = unsafe { core::slice::from_raw_parts(ptr, len) };
while !AUDIO_BUFFER_READY.load(Ordering::Acquire) {}
if buf.len() == AUDIO_BUFFER_SAMPLES * 2 {
AUDIO_BUFFER_READY.store(false, Ordering::Release);
unsafe { AUDIO_BUFFER.copy_from_slice(buf) };
} else {
#[cfg(feature = "defmt")]
defmt::warn!(
"user audio stream was wrong size: {} should be {}",
buf.len(),
AUDIO_BUFFER_SAMPLES * 2
)
}
}

149
kernel/src/audio.rs Normal file
View File

@@ -0,0 +1,149 @@
use crate::Audio;
use core::sync::atomic::{AtomicBool, Ordering};
use embassy_futures::join::join;
use embassy_rp::{
Peri,
clocks::clk_sys_freq,
dma::{AnyChannel, Channel},
gpio::Level,
pio::{
Common, Config, Direction, FifoJoin, Instance, LoadedProgram, PioPin, ShiftConfig,
StateMachine, program::pio_asm,
},
};
use fixed::traits::ToFixed;
pub const SAMPLE_RATE_HZ: u32 = 22_050;
const AUDIO_BUFFER_SAMPLES: usize = 1024;
const _: () = assert!(AUDIO_BUFFER_SAMPLES == abi_sys::AUDIO_BUFFER_SAMPLES);
// 8bit stereo interleaved PCM audio buffers
pub static mut AUDIO_BUFFER: [u8; AUDIO_BUFFER_SAMPLES * 2] = [0; AUDIO_BUFFER_SAMPLES * 2];
static mut AUDIO_BUFFER_1: [u8; AUDIO_BUFFER_SAMPLES * 2] = [0; AUDIO_BUFFER_SAMPLES * 2];
pub static AUDIO_BUFFER_READY: AtomicBool = AtomicBool::new(true);
#[embassy_executor::task]
pub async fn audio_handler(mut audio: Audio) {
const SILENCE_VALUE: u8 = u8::MAX / 2;
let prg = PioPwmAudioProgram8Bit::new(&mut audio.pio);
let mut pwm_pio_left =
PioPwmAudio::new(audio.dma0, &mut audio.pio, audio.sm0, audio.left, &prg);
let mut pwm_pio_right =
PioPwmAudio::new(audio.dma1, &mut audio.pio, audio.sm1, audio.right, &prg);
loop {
write_samples(&mut pwm_pio_left, &mut pwm_pio_right, unsafe {
&AUDIO_BUFFER_1
})
.await;
unsafe { &mut AUDIO_BUFFER_1 }.fill(SILENCE_VALUE);
unsafe { core::mem::swap(&mut AUDIO_BUFFER, &mut AUDIO_BUFFER_1) };
AUDIO_BUFFER_READY.store(true, Ordering::Release)
}
}
async fn write_samples<PIO: Instance>(
left: &mut PioPwmAudio<'static, PIO, 0>,
right: &mut PioPwmAudio<'static, PIO, 1>,
buf: &[u8],
) {
// pack two samples per word
let mut packed_buf_left: [u32; AUDIO_BUFFER_SAMPLES / 2] = [0; AUDIO_BUFFER_SAMPLES / 2];
let mut packed_buf_right: [u32; AUDIO_BUFFER_SAMPLES / 2] = [0; AUDIO_BUFFER_SAMPLES / 2];
for ((pl, pr), sample) in packed_buf_left
.iter_mut()
.zip(packed_buf_right.iter_mut())
.zip(buf.chunks(4))
{
*pl = pack_u8_samples(sample[0], sample[2]);
*pr = pack_u8_samples(sample[1], sample[3]);
}
let left_fut = left
.sm
.tx()
.dma_push(left.dma.reborrow(), &packed_buf_left, false);
let right_fut = right
.sm
.tx()
.dma_push(right.dma.reborrow(), &packed_buf_right, false);
join(left_fut, right_fut).await;
}
struct PioPwmAudioProgram8Bit<'d, PIO: Instance>(LoadedProgram<'d, PIO>);
/// Writes one sample to pwm as high and low time
impl<'d, PIO: Instance> PioPwmAudioProgram8Bit<'d, PIO> {
fn new(common: &mut Common<'d, PIO>) -> Self {
// only uses 16 bits top for high, bottom for low
// allows two samples per word
let prg = pio_asm!(
"out x, 8", // pwm high time
"out y, 8", // pwm low time
"loop_high:",
"set pins, 1", // keep pin high
"jmp x-- loop_high", // decrement X until 0
"loop_low:",
"set pins, 0", // keep pin low
"jmp y-- loop_low", // decrement Y until 0
);
let prg = common.load_program(&prg.program);
Self(prg)
}
}
struct PioPwmAudio<'d, PIO: Instance, const SM: usize> {
dma: Peri<'d, AnyChannel>,
sm: StateMachine<'d, PIO, SM>,
}
impl<'d, PIO: Instance, const SM: usize> PioPwmAudio<'d, PIO, SM> {
fn new(
dma: Peri<'d, impl Channel>,
pio: &mut Common<'d, PIO>,
mut sm: StateMachine<'d, PIO, SM>,
pin: Peri<'d, impl PioPin>,
prg: &PioPwmAudioProgram8Bit<'d, PIO>,
) -> Self {
let pin = pio.make_pio_pin(pin);
sm.set_pins(Level::High, &[&pin]);
sm.set_pin_dirs(Direction::Out, &[&pin]);
let mut cfg = Config::default();
cfg.set_set_pins(&[&pin]);
cfg.fifo_join = FifoJoin::TxOnly;
let mut shift_cfg = ShiftConfig::default();
shift_cfg.auto_fill = true;
cfg.shift_out = shift_cfg;
cfg.use_program(&prg.0, &[]);
sm.set_config(&cfg);
let target_clock = (u8::MAX as u32 + 1) * SAMPLE_RATE_HZ;
let divider = (clk_sys_freq() / (target_clock * 2)).to_fixed();
sm.set_clock_divider(divider);
sm.set_enable(true);
Self {
dma: dma.into(),
sm,
}
}
}
/// packs two u8 samples into 32bit word
fn pack_u8_samples(sample1: u8, sample2: u8) -> u32 {
(u8_pcm_to_pwm(sample1) as u32) << 16 | u8_pcm_to_pwm(sample2) as u32
}
fn u8_pcm_to_pwm(sample: u8) -> u16 {
((sample as u16) << 8) | ((u8::MAX - sample) as u16)
}

View File

@@ -1,13 +1,23 @@
use crate::framebuffer::{self, AtomicFrameBuffer, FB_PAUSED};
use core::alloc::{GlobalAlloc, Layout};
use core::sync::atomic::Ordering;
use embassy_futures::yield_now;
use embassy_rp::{
Peri,
gpio::{Level, Output},
peripherals::{PIN_13, PIN_14, PIN_15, SPI1},
spi::{Async, Spi},
};
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
use embassy_time::{Delay, Timer};
use embassy_time::Delay;
use embedded_graphics::{draw_target::DrawTarget, pixelcolor::Rgb565, prelude::RgbColor};
use embedded_hal_bus::spi::ExclusiveDevice;
use st7365p_lcd::{FrameBuffer, ST7365P};
use static_cell::StaticCell;
use st7365p_lcd::ST7365P;
#[cfg(feature = "psram")]
use crate::heap::HEAP;
#[cfg(feature = "fps")]
pub use framebuffer::fps::{FPS_CANVAS, FPS_COUNTER};
type DISPLAY = ST7365P<
ExclusiveDevice<Spi<'static, SPI1, Async>, Output<'static>, Delay>,
@@ -19,19 +29,36 @@ type DISPLAY = ST7365P<
pub const SCREEN_WIDTH: usize = 320;
pub const SCREEN_HEIGHT: usize = 320;
type FB = FrameBuffer<SCREEN_WIDTH, SCREEN_HEIGHT, { SCREEN_WIDTH * SCREEN_HEIGHT }>;
static mut FRAMEBUFFER: Option<FB> = None;
pub static mut FRAMEBUFFER: Option<AtomicFrameBuffer> = None;
pub fn framebuffer_mut() -> &'static mut FB {
unsafe { FRAMEBUFFER.as_mut().unwrap() }
fn init_fb() {
unsafe {
#[cfg(feature = "psram")]
{
let slab = HEAP.alloc(Layout::array::<u16>(framebuffer::SIZE).unwrap()) as *mut u16;
let buf = core::slice::from_raw_parts_mut(slab, framebuffer::SIZE);
let mut fb = AtomicFrameBuffer::new(buf);
fb.clear(Rgb565::BLACK).unwrap();
FRAMEBUFFER = Some(fb);
}
#[cfg(not(feature = "psram"))]
{
static mut BUF: [u16; framebuffer::SIZE] = [0; framebuffer::SIZE];
FRAMEBUFFER = Some(AtomicFrameBuffer::new(&mut BUF));
}
}
}
pub async fn init_display(
spi: Spi<'static, SPI1, Async>,
cs: PIN_13,
data: PIN_14,
reset: PIN_15,
cs: Peri<'static, PIN_13>,
data: Peri<'static, PIN_14>,
reset: Peri<'static, PIN_15>,
) -> DISPLAY {
init_fb();
let spi_device = ExclusiveDevice::new(spi, Output::new(cs, Level::Low), Delay).unwrap();
let mut display = ST7365P::new(
spi_device,
@@ -41,20 +68,54 @@ pub async fn init_display(
true,
Delay,
);
display.init().await.unwrap();
display.set_custom_orientation(0x40).await.unwrap();
unsafe { FRAMEBUFFER.replace(FrameBuffer::new()) };
display.draw(framebuffer_mut()).await.unwrap();
unsafe {
FRAMEBUFFER
.as_mut()
.unwrap()
.draw(&mut display)
.await
.unwrap()
}
display.set_on().await.unwrap();
display
}
#[embassy_executor::task]
pub async fn display_handler(mut display: DISPLAY) {
let fb = framebuffer_mut();
use embassy_time::{Instant, Timer};
// Target ~60 Hz refresh (≈16.67 ms per frame)
const FRAME_TIME_MS: u64 = 1000 / 60;
loop {
display.partial_draw_batched(fb).await.unwrap();
embassy_time::Timer::after_millis(32).await; // 30 fps
let start = Instant::now();
#[cfg(feature = "fps")]
unsafe {
if FPS_COUNTER.should_draw() {
FPS_CANVAS.draw_fps().await;
}
}
if !FB_PAUSED.load(Ordering::Acquire) {
unsafe {
FRAMEBUFFER
.as_mut()
.unwrap()
.partial_draw(&mut display)
.await
.unwrap();
}
}
let elapsed = start.elapsed().as_millis() as u64;
if elapsed < FRAME_TIME_MS {
Timer::after_millis(FRAME_TIME_MS - elapsed).await;
} else {
yield_now().await;
}
}
}

View File

@@ -1,82 +1,159 @@
#![allow(static_mut_refs)]
use crate::{
abi,
storage::{File, SDCARD},
};
use abi_sys::{CallAbiTable, EntryFn};
use abi_sys::{CallTable, EntryFn};
use alloc::{vec, vec::Vec};
use bumpalo::Bump;
use core::ptr;
use embedded_sdmmc::ShortFileName;
use goblin::{
elf::{
header::header32::Header,
program_header::program_header32::{PT_LOAD, ProgramHeader},
section_header::SHT_SYMTAB,
reloc::R_ARM_RELATIVE,
section_header::{SHT_REL, SHT_SYMTAB},
},
elf32::{section_header::SectionHeader, sym::Sym},
elf32::{header, reloc::Rel, section_header::SectionHeader, sym::Sym},
};
use strum::IntoEnumIterator;
const ELF32_HDR_SIZE: usize = 52;
// userland ram region defined in memory.x
unsafe extern "C" {
static __userapp_start__: u8;
static __userapp_end__: u8;
}
pub async unsafe fn load_binary(name: &ShortFileName) -> Result<EntryFn, &str> {
pub async unsafe fn load_binary(name: &ShortFileName) -> Option<(EntryFn, Bump)> {
let mut sd_lock = SDCARD.get().lock().await;
let sd = sd_lock.as_mut().unwrap();
let mut error = "";
let mut entry = 0;
let mut header_buf = [0; ELF32_HDR_SIZE];
sd.read_file(name, |mut file| {
let (entry, bump) = sd
.read_file(name, |mut file| {
file.read(&mut header_buf).unwrap();
let elf_header = Header::from_bytes(&header_buf);
let mut program_headers_buf = vec![0_u8; elf_header.e_phentsize as usize];
for i in 1..=elf_header.e_phnum {
// reject non-PIE
if elf_header.e_type != header::ET_DYN {
return None;
}
let mut ph_buf = vec![0_u8; elf_header.e_phentsize as usize];
let (total_size, min_vaddr, _max_vaddr) =
total_loadable_size(&mut file, &elf_header, &mut ph_buf);
let bump = Bump::with_capacity(total_size);
let base = bump.alloc_slice_fill_default::<u8>(total_size);
// load each segment into bump, relative to base_ptr
for i in 0..elf_header.e_phnum {
file.seek_from_start(elf_header.e_phoff + (elf_header.e_phentsize * i) as u32)
.unwrap();
file.read(&mut program_headers_buf).unwrap();
file.read(&mut ph_buf).unwrap();
let ph = cast_phdr(&ph_buf);
let ph = cast_phdr(&program_headers_buf);
let seg_offset = (ph.p_vaddr - min_vaddr) as usize;
let mut segment = &mut base[seg_offset..seg_offset + ph.p_memsz as usize];
if ph.p_type == PT_LOAD {
load_segment(&mut file, &ph).unwrap()
load_segment(&mut file, &ph, &mut segment).unwrap();
}
}
// MUST MATCH ABI EXACTLY
let entries: &[(CallAbiTable, usize)] = &[
(CallAbiTable::Print, abi::print as usize),
(CallAbiTable::DrawIter, abi::draw_iter as usize),
(CallAbiTable::GetKey, abi::get_key as usize),
];
assert!(entries.len() == CallAbiTable::COUNT);
for i in 0..elf_header.e_shnum {
let sh = read_section(&mut file, elf_header, i.into());
patch_abi(entries, &elf_header, &mut file).unwrap();
match sh.sh_type {
SHT_REL => {
apply_relocations(&sh, min_vaddr, base.as_mut_ptr(), &mut file).unwrap();
}
_ => {}
}
}
// TODO: dynamically search for abi table
patch_abi(&elf_header, base.as_mut_ptr(), min_vaddr, &mut file).unwrap();
entry = elf_header.e_entry as u32;
// entry pointer is base_ptr + (entry - min_vaddr)
let entry_ptr: EntryFn = unsafe {
core::mem::transmute(base.as_ptr().add((elf_header.e_entry - min_vaddr) as usize))
};
Some((entry_ptr, bump))
})
.await
.unwrap();
.expect("Failed to read file")?;
if entry != 0 {
Ok(unsafe { core::mem::transmute(entry) })
} else {
Err(error)
Some((entry, bump))
}
fn load_segment(file: &mut File, ph: &ProgramHeader, segment: &mut [u8]) -> Result<(), ()> {
let filesz = ph.p_filesz as usize;
let memsz = ph.p_memsz as usize;
// read file contents
let mut remaining = filesz;
let mut dst_offset = 0;
let mut file_offset = ph.p_offset;
let mut buf = [0u8; 512];
while remaining > 0 {
let to_read = core::cmp::min(remaining, buf.len());
file.seek_from_start(file_offset).unwrap();
file.read(&mut buf[..to_read]).unwrap();
segment[dst_offset..dst_offset + to_read].copy_from_slice(&buf[..to_read]);
remaining -= to_read;
dst_offset += to_read;
file_offset += to_read as u32;
}
// zero BSS if needed
if memsz > filesz {
segment[filesz..].fill(0);
}
Ok(())
}
fn apply_relocations(
sh: &SectionHeader,
min_vaddr: u32,
base: *mut u8,
file: &mut File,
) -> Result<(), ()> {
let mut reloc = [0_u8; 8];
let num_relocs = sh.sh_size as usize / sh.sh_entsize as usize;
for i in 0..num_relocs {
file.seek_from_start(sh.sh_offset + (i as u32 * 8)).unwrap();
file.read(&mut reloc).unwrap();
let rel = cast_rel(&reloc);
let reloc_type = rel.r_info & 0xff;
let reloc_addr = unsafe { base.add((rel.r_offset - min_vaddr) as usize) as *mut u32 };
match reloc_type {
R_ARM_RELATIVE => {
// REL: add base to the word already stored there
unsafe {
let val = ptr::read_unaligned(reloc_addr);
ptr::write_unaligned(reloc_addr, val.wrapping_add(base as u32));
}
}
_ => {
return Err(());
}
}
}
Ok(())
}
fn patch_abi(
entries: &[(CallAbiTable, usize)],
elf_header: &Header,
base: *mut u8,
min_vaddr: u32,
file: &mut File,
) -> Result<(), ()> {
for i in 1..=elf_header.e_shnum {
@@ -112,11 +189,29 @@ fn patch_abi(
let symbol_name = core::str::from_utf8(&name).unwrap();
if symbol_name == "CALL_ABI_TABLE" {
let table_base = sym.st_value as *mut usize;
let table_base =
unsafe { base.add((sym.st_value as usize) - min_vaddr as usize) }
as *mut usize;
for &(abi_idx, func_ptr) in entries {
for (idx, call) in CallTable::iter().enumerate() {
let ptr = match call {
CallTable::Alloc => abi::alloc as usize,
CallTable::Dealloc => abi::dealloc as usize,
CallTable::PrintString => abi::print as usize,
CallTable::SleepMs => abi::sleep as usize,
CallTable::GetMs => abi::get_ms as usize,
CallTable::DrawIter => abi::draw_iter as usize,
CallTable::GetKey => abi::get_key as usize,
CallTable::GenRand => abi::gen_rand as usize,
CallTable::ListDir => abi::list_dir as usize,
CallTable::ReadFile => abi::read_file as usize,
CallTable::WriteFile => abi::write_file as usize,
CallTable::FileLen => abi::file_len as usize,
CallTable::AudioBufferReady => abi::audio_buffer_ready as usize,
CallTable::SendAudioBuffer => abi::send_audio_buffer as usize,
};
unsafe {
table_base.add(abi_idx as usize).write(func_ptr);
table_base.add(idx as usize).write(ptr);
}
}
return Ok(());
@@ -127,65 +222,41 @@ fn patch_abi(
Err(())
}
fn total_loadable_size(
file: &mut File,
elf_header: &Header,
ph_buf: &mut [u8],
) -> (usize, u32, u32) {
let mut min_vaddr = u32::MAX;
let mut max_vaddr = 0u32;
for i in 0..elf_header.e_phnum {
file.seek_from_start(elf_header.e_phoff + (elf_header.e_phentsize * i) as u32)
.unwrap();
file.read(ph_buf).unwrap();
let ph = cast_phdr(&ph_buf);
if ph.p_type == PT_LOAD {
if ph.p_vaddr < min_vaddr {
min_vaddr = ph.p_vaddr;
}
if ph.p_vaddr + ph.p_memsz > max_vaddr {
max_vaddr = ph.p_vaddr + ph.p_memsz;
}
}
}
let total_size = (max_vaddr - min_vaddr) as usize;
(total_size, min_vaddr, max_vaddr)
}
fn read_section(file: &mut File, elf_header: &Header, section: u32) -> SectionHeader {
let mut section_header_buf = vec![0_u8; elf_header.e_shentsize as usize];
let mut sh_buf = vec![0_u8; elf_header.e_shentsize as usize];
file.seek_from_start(elf_header.e_shoff + (elf_header.e_shentsize as u32 * section))
.unwrap();
file.read(&mut section_header_buf).unwrap();
file.read(&mut sh_buf).unwrap();
cast_shdr(&section_header_buf)
}
fn load_segment(file: &mut File, ph: &ProgramHeader) -> Result<(), ()> {
let dst_start = ph.p_vaddr as *mut u8;
let filesz = ph.p_filesz as usize;
let memsz = ph.p_memsz as usize;
let vaddr = ph.p_vaddr as usize;
let mut remaining = filesz;
let mut dst_ptr = dst_start;
let mut file_offset = ph.p_offset;
let seg_start = vaddr;
let seg_end = vaddr + memsz;
// Bounds check: make sure segment fits inside payload region
let user_start = unsafe { &__userapp_start__ as *const u8 as usize };
let user_end = unsafe { &__userapp_end__ as *const u8 as usize };
if seg_start < user_start || seg_end > user_end {
panic!(
"Segment out of bounds: {:x}..{:x} not within {:x}..{:x}",
seg_start, seg_end, user_start, user_end
);
}
// Buffer for chunked reads (512 bytes is typical SD sector size)
let mut buf = [0u8; 512];
while remaining > 0 {
let to_read = core::cmp::min(remaining, buf.len());
// Read chunk from file
file.seek_from_start(file_offset).unwrap();
file.read(&mut buf[..to_read]).unwrap();
unsafe {
// Copy chunk directly into destination memory
core::ptr::copy_nonoverlapping(buf.as_ptr(), dst_ptr, to_read);
dst_ptr = dst_ptr.add(to_read);
}
remaining -= to_read;
file_offset += to_read as u32;
}
// Zero BSS (memsz - filesz)
if memsz > filesz {
unsafe {
core::ptr::write_bytes(dst_ptr, 0, memsz - filesz);
}
}
Ok(())
cast_shdr(&sh_buf)
}
fn cast_phdr(buf: &[u8]) -> ProgramHeader {
@@ -202,3 +273,8 @@ fn cast_sym(buf: &[u8]) -> Sym {
assert!(buf.len() >= core::mem::size_of::<Sym>());
unsafe { core::ptr::read(buf.as_ptr() as *const Sym) }
}
fn cast_rel(buf: &[u8]) -> Rel {
assert!(buf.len() >= core::mem::size_of::<Rel>());
unsafe { core::ptr::read(buf.as_ptr() as *const Rel) }
}

574
kernel/src/framebuffer.rs Normal file
View File

@@ -0,0 +1,574 @@
use crate::display::{SCREEN_HEIGHT, SCREEN_WIDTH};
use core::sync::atomic::{AtomicBool, Ordering};
use embedded_graphics::{
draw_target::DrawTarget,
pixelcolor::{
Rgb565,
raw::{RawData, RawU16},
},
prelude::*,
primitives::Rectangle,
};
use embedded_hal_2::digital::OutputPin;
use embedded_hal_async::{delay::DelayNs, spi::SpiDevice};
use st7365p_lcd::ST7365P;
#[cfg(feature = "fps")]
use fps::{FPS_CANVAS, FPS_CANVAS_HEIGHT, FPS_CANVAS_WIDTH, FPS_CANVAS_X, FPS_CANVAS_Y};
const TILE_SIZE: usize = 16; // 16x16 tile
const TILE_COUNT: usize = (SCREEN_WIDTH / TILE_SIZE) * (SCREEN_HEIGHT / TILE_SIZE); // 400 tiles
const NUM_TILE_ROWS: usize = SCREEN_WIDTH / TILE_SIZE;
const NUM_TILE_COLS: usize = SCREEN_WIDTH / TILE_SIZE;
const MAX_BATCH_TILES: usize = (SCREEN_WIDTH / TILE_SIZE) * 2;
type BatchTileBuf = [u16; MAX_BATCH_TILES * TILE_SIZE * TILE_SIZE];
pub const SIZE: usize = SCREEN_HEIGHT * SCREEN_WIDTH;
pub static FB_PAUSED: AtomicBool = AtomicBool::new(false);
#[allow(dead_code)]
pub struct AtomicFrameBuffer<'a> {
fb: &'a mut [u16],
dirty_tiles: [AtomicBool; TILE_COUNT],
batch_tile_buf: BatchTileBuf,
}
impl<'a> AtomicFrameBuffer<'a> {
pub fn new(buffer: &'a mut [u16]) -> Self {
assert!(buffer.len() == SIZE);
Self {
fb: buffer,
dirty_tiles: core::array::from_fn(|_| AtomicBool::new(true)),
batch_tile_buf: [0; MAX_BATCH_TILES * TILE_SIZE * TILE_SIZE],
}
}
fn mark_tiles_dirty(&mut self, rect: Rectangle) {
let tiles_x = (SCREEN_WIDTH + TILE_SIZE - 1) / TILE_SIZE;
let start_tx = (rect.top_left.x as usize) / TILE_SIZE;
let end_tx = ((rect.top_left.x + rect.size.width as i32 - 1) as usize) / TILE_SIZE;
let start_ty = (rect.top_left.y as usize) / TILE_SIZE;
let end_ty = ((rect.top_left.y + rect.size.height as i32 - 1) as usize) / TILE_SIZE;
for ty in start_ty..=end_ty {
for tx in start_tx..=end_tx {
let tile_idx = ty * tiles_x + tx;
self.dirty_tiles[tile_idx].store(true, Ordering::Release);
}
}
}
fn set_pixels<P: IntoIterator<Item = u16>>(
&mut self,
sx: u16,
sy: u16,
ex: u16,
ey: u16,
colors: P,
) -> Result<(), ()> {
if sx >= self.size().width as u16
|| ex >= self.size().width as u16
|| sy >= self.size().height as u16
|| ey >= self.size().height as u16
{
return Err(()); // Bounds check
}
let mut color_iter = colors.into_iter();
for y in sy..=ey {
for x in sx..=ex {
if let Some(color) = color_iter.next() {
self.fb[(y as usize * SCREEN_WIDTH) + x as usize] = color;
} else {
return Err(()); // Not enough data
}
}
}
// Optional: check that we consumed *exactly* the right amount
if color_iter.next().is_some() {
return Err(()); // Too much data
}
Ok(())
}
// Checks if a full draw would be faster than individual tile batches
fn should_full_draw(&self) -> bool {
let threshold_pixels = SIZE * 80 / 100;
let mut dirty_pixels = 0;
self.dirty_tiles.iter().any(|tile| {
if tile.load(Ordering::Acquire) {
dirty_pixels += TILE_SIZE * TILE_SIZE;
}
dirty_pixels >= threshold_pixels
})
}
/// Sends the entire framebuffer to the display
pub async fn draw<SPI, DC, RST, DELAY: DelayNs>(
&mut self,
display: &mut ST7365P<SPI, DC, RST, DELAY>,
) -> Result<(), ()>
where
SPI: SpiDevice,
DC: OutputPin,
RST: OutputPin,
{
display
.set_pixels_buffered(
0,
0,
self.size().width as u16 - 1,
self.size().height as u16 - 1,
&self.fb[..],
)
.await?;
for tile in self.dirty_tiles.iter() {
tile.store(false, Ordering::Release);
}
#[cfg(feature = "fps")]
unsafe {
crate::display::FPS_COUNTER.measure()
}
Ok(())
}
// used when doing a full screen refresh fps must be drawn into fb
// unfortunately it is not garenteed to not be drawn over before
// being pushed to the display
#[cfg(feature = "fps")]
pub fn draw_fps_into_fb(&mut self) {
unsafe {
let canvas = &FPS_CANVAS.canvas;
for y in 0..FPS_CANVAS_HEIGHT {
let fb_y = FPS_CANVAS_Y + y;
let fb_row_start = fb_y * SCREEN_WIDTH + FPS_CANVAS_X;
let canvas_row_start = y * FPS_CANVAS_WIDTH;
self.fb[fb_row_start..fb_row_start + FPS_CANVAS_WIDTH].copy_from_slice(
&canvas[canvas_row_start..canvas_row_start + FPS_CANVAS_WIDTH],
);
}
}
}
// copy N tiles horizontally to the right into batch tile buf
fn append_tiles_to_batch(
&mut self,
tile_x: u16,
tile_y: u16,
total_tiles: u16, // number of tiles being written to buf
) {
debug_assert!(total_tiles as usize <= NUM_TILE_COLS);
for batch_row_num in 0..TILE_SIZE {
let batch_row_offset = batch_row_num * total_tiles as usize * TILE_SIZE;
let batch_row = &mut self.batch_tile_buf
[batch_row_offset..batch_row_offset + (total_tiles as usize * TILE_SIZE)];
let fb_row_offset = (tile_y as usize * TILE_SIZE + batch_row_num) * SCREEN_WIDTH
+ tile_x as usize * TILE_SIZE;
let fb_row =
&self.fb[fb_row_offset..fb_row_offset + (total_tiles as usize * TILE_SIZE)];
batch_row.copy_from_slice(fb_row);
// override fps pixel region with fps
// avoids writing to fps, and having it overridden before draw
#[cfg(feature = "fps")]
{
let global_y = tile_y as usize * TILE_SIZE + batch_row_num;
if global_y >= FPS_CANVAS_Y && global_y < FPS_CANVAS_Y + FPS_CANVAS_HEIGHT {
let start_x = tile_x as usize * TILE_SIZE;
let end_x = start_x + (total_tiles as usize * TILE_SIZE);
// horizontal overlap check
let fps_x0 = FPS_CANVAS_X;
let fps_x1 = FPS_CANVAS_X + FPS_CANVAS_WIDTH;
let x0 = start_x.max(fps_x0);
let x1 = end_x.min(fps_x1);
if x1 > x0 {
let row_in_fps = global_y - FPS_CANVAS_Y;
let fps_off = row_in_fps
.checked_mul(FPS_CANVAS_WIDTH)
.and_then(|v| v.checked_add(x0 - fps_x0));
let batch_off = x0 - start_x;
let len = x1 - x0;
if let Some(fps_off) = fps_off {
let fps_len_ok = fps_off + len <= unsafe { FPS_CANVAS.canvas.len() };
let batch_len_ok = batch_off + len <= batch_row.len();
if fps_len_ok && batch_len_ok {
batch_row[batch_off..batch_off + len].copy_from_slice(unsafe {
&FPS_CANVAS.canvas[fps_off..fps_off + len]
});
}
}
}
}
}
}
}
// Pushes tiles to the display in batches to avoid full frame pushes (unless needed)
pub async fn partial_draw<SPI, DC, RST, DELAY>(
&mut self,
display: &mut ST7365P<SPI, DC, RST, DELAY>,
) -> Result<(), ()>
where
SPI: SpiDevice,
DC: OutputPin,
RST: OutputPin,
DELAY: DelayNs,
{
if self.should_full_draw() {
#[cfg(feature = "fps")]
self.draw_fps_into_fb();
return self.draw(display).await;
}
#[cfg(feature = "fps")]
{
let fps_tile_x = FPS_CANVAS_X / TILE_SIZE;
let fps_tile_y = FPS_CANVAS_Y / TILE_SIZE;
let fps_tile_w = (FPS_CANVAS_WIDTH + TILE_SIZE - 1) / TILE_SIZE;
let fps_tile_h = (FPS_CANVAS_HEIGHT + TILE_SIZE - 1) / TILE_SIZE;
for ty in fps_tile_y..fps_tile_y + fps_tile_h {
for tx in fps_tile_x..fps_tile_x + fps_tile_w {
self.dirty_tiles[ty * NUM_TILE_COLS + tx].store(true, Ordering::Release);
}
}
}
for tile_row in 0..NUM_TILE_ROWS {
let row_start_idx = tile_row * NUM_TILE_COLS;
let mut col = 0;
while col < NUM_TILE_COLS {
// Check for dirty tile
if self.dirty_tiles[row_start_idx + col].swap(false, Ordering::Acquire) {
let run_start = col;
let mut run_len = 1;
// Extend run while contiguous dirty tiles and within MAX_BATCH_TILES
while col + 1 < NUM_TILE_COLS
&& self.dirty_tiles[row_start_idx + col + 1].load(Ordering::Acquire)
&& run_len < MAX_BATCH_TILES
{
col += 1;
run_len += 1;
}
// Copy the whole horizontal run into the batch buffer in one call
let tile_x = run_start;
let tile_y = tile_row;
self.append_tiles_to_batch(tile_x as u16, tile_y as u16, run_len as u16);
// Compute coordinates for display write
let start_x = tile_x * TILE_SIZE;
let end_x = start_x + run_len * TILE_SIZE - 1;
let start_y = tile_y * TILE_SIZE;
let end_y = start_y + TILE_SIZE - 1;
// Send batch to display
display
.set_pixels_buffered(
start_x as u16,
start_y as u16,
end_x as u16,
end_y as u16,
&self.batch_tile_buf[..run_len * TILE_SIZE * TILE_SIZE],
)
.await?;
}
col += 1;
}
}
#[cfg(feature = "fps")]
unsafe {
crate::display::FPS_COUNTER.measure()
}
Ok(())
}
}
impl<'a> DrawTarget for AtomicFrameBuffer<'a> {
type Error = ();
type Color = Rgb565;
fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
where
I: IntoIterator<Item = Pixel<Self::Color>>,
{
let mut dirty_rect: Option<Rectangle> = None;
let mut changed = false;
for Pixel(coord, color) in pixels {
if coord.x >= 0 && coord.y >= 0 {
let x = coord.x;
let y = coord.y;
if (x as usize) < SCREEN_WIDTH && (y as usize) < SCREEN_HEIGHT {
let idx = (y as usize) * SCREEN_WIDTH + (x as usize);
let raw_color = RawU16::from(color).into_inner();
if self.fb[idx] != raw_color {
self.fb[idx] = raw_color;
changed = true;
}
if let Some(ref mut rect) = dirty_rect {
rect.top_left.x = rect.top_left.x.min(x);
rect.top_left.y = rect.top_left.y.min(y);
let max_x = (rect.top_left.x + rect.size.width as i32 - 1).max(x);
let max_y = (rect.top_left.y + rect.size.height as i32 - 1).max(y);
rect.size.width = (max_x - rect.top_left.x + 1) as u32;
rect.size.height = (max_y - rect.top_left.y + 1) as u32;
} else {
dirty_rect = Some(Rectangle::new(Point::new(x, y), Size::new(1, 1)));
}
}
}
}
if changed {
if let Some(rect) = dirty_rect {
self.mark_tiles_dirty(rect);
}
}
Ok(())
}
fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error>
where
I: IntoIterator<Item = Self::Color>,
{
let drawable_area = area.intersection(&Rectangle::new(Point::zero(), self.size()));
if drawable_area.size != Size::zero() {
// We assume that `colors` iterator is in row-major order for the original `area`
// So we must skip rows/pixels that are clipped
let area_width = area.size.width;
let area_height = area.size.height;
let mut colors = colors.into_iter();
let mut changed = false;
for y in 0..area_height {
for x in 0..area_width {
let p = area.top_left + Point::new(x as i32, y as i32);
if drawable_area.contains(p) {
if let Some(color) = colors.next() {
let idx = (p.y as usize * SCREEN_WIDTH) + (p.x as usize);
let raw_color = RawU16::from(color).into_inner();
if self.fb[idx] != raw_color {
self.fb[idx] = raw_color;
changed = true;
}
} else {
break;
}
} else {
// Still need to consume the color even if not used!
let _ = colors.next();
}
}
}
if changed {
self.mark_tiles_dirty(*area);
}
}
Ok(())
}
fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
self.fill_contiguous(
area,
core::iter::repeat(color).take((self.size().width * self.size().height) as usize),
)
}
fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
self.set_pixels(
0,
0,
self.size().width as u16 - 1,
self.size().height as u16 - 1,
core::iter::repeat(RawU16::from(color).into_inner())
.take((self.size().width * self.size().height) as usize),
)?;
for tile in self.dirty_tiles.iter() {
tile.store(true, Ordering::Release);
}
Ok(())
}
}
impl<'a> OriginDimensions for AtomicFrameBuffer<'a> {
fn size(&self) -> Size {
Size::new(SCREEN_WIDTH as u32, SCREEN_HEIGHT as u32)
}
}
#[cfg(feature = "fps")]
pub mod fps {
use crate::display::SCREEN_WIDTH;
use core::fmt::Write;
use embassy_time::{Duration, Instant};
use embedded_graphics::{
Drawable, Pixel,
draw_target::DrawTarget,
geometry::Point,
mono_font::{MonoTextStyle, ascii::FONT_8X13},
pixelcolor::Rgb565,
prelude::{IntoStorage, OriginDimensions, RgbColor, Size},
text::{Alignment, Text},
};
pub static mut FPS_COUNTER: FpsCounter = FpsCounter::new();
pub static mut FPS_CANVAS: FpsCanvas = FpsCanvas::new();
// "FPS: 120" = 8 len
const FPS_LEN: usize = 8;
pub const FPS_CANVAS_WIDTH: usize = (FONT_8X13.character_size.width + 4) as usize * FPS_LEN;
pub const FPS_CANVAS_HEIGHT: usize = FONT_8X13.character_size.height as usize;
// puts canvas in the top right of the display
// top left point of canvas
pub const FPS_CANVAS_X: usize = SCREEN_WIDTH - FPS_CANVAS_WIDTH;
pub const FPS_CANVAS_Y: usize = 0;
pub struct FpsCanvas {
pub canvas: [u16; FPS_CANVAS_HEIGHT * FPS_CANVAS_WIDTH],
}
impl FpsCanvas {
const fn new() -> Self {
Self {
canvas: [0; FPS_CANVAS_HEIGHT * FPS_CANVAS_WIDTH],
}
}
fn clear(&mut self) {
for p in &mut self.canvas {
*p = 0;
}
}
pub async fn draw_fps(&mut self) {
let mut buf: heapless::String<FPS_LEN> = heapless::String::new();
let fps = unsafe { FPS_COUNTER.smoothed };
let _ = write!(buf, "FPS: {}", fps as u8);
self.clear();
let text_style = MonoTextStyle::new(&FONT_8X13, Rgb565::WHITE);
Text::with_alignment(
buf.as_str(),
Point::new(
FPS_CANVAS_WIDTH as i32 / 2,
(FPS_CANVAS_HEIGHT as i32 + 8) / 2,
),
text_style,
Alignment::Center,
)
.draw(self)
.unwrap();
}
}
impl DrawTarget for FpsCanvas {
type Error = ();
type Color = Rgb565;
fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
where
I: IntoIterator<Item = Pixel<Self::Color>>,
{
for Pixel(point, color) in pixels {
if point.x < 0
|| point.x >= FPS_CANVAS_WIDTH as i32
|| point.y < 0
|| point.y >= FPS_CANVAS_HEIGHT as i32
{
continue;
}
let index = (point.y as usize) * FPS_CANVAS_WIDTH + point.x as usize;
self.canvas[index] = color.into_storage();
}
Ok(())
}
}
impl OriginDimensions for FpsCanvas {
fn size(&self) -> Size {
Size::new(FPS_CANVAS_WIDTH as u32, FPS_CANVAS_HEIGHT as u32)
}
}
pub struct FpsCounter {
last_frame: Option<Instant>,
smoothed: f32,
last_draw: Option<Instant>,
}
impl FpsCounter {
pub const fn new() -> Self {
Self {
last_frame: None,
smoothed: 0.0,
last_draw: None,
}
}
// Is called once per frame or partial frame to update FPS
pub fn measure(&mut self) {
let now = Instant::now();
if let Some(last) = self.last_frame {
let dt_us = (now - last).as_micros() as f32;
if dt_us > 0.0 {
let current = 1_000_000.0 / dt_us;
self.smoothed = if self.smoothed == 0.0 {
current
} else {
0.9 * self.smoothed + 0.1 * current
};
}
}
self.last_frame = Some(now);
}
pub fn should_draw(&mut self) -> bool {
let now = Instant::now();
match self.last_draw {
Some(last) if now - last < Duration::from_millis(200) => false,
_ => {
self.last_draw = Some(now);
true
}
}
}
}
}

95
kernel/src/heap.rs Normal file
View File

@@ -0,0 +1,95 @@
// This whole file was taken from:
// https://github.com/wezterm/picocalc-wezterm/blob/main/src/heap.rs
use core::alloc::{GlobalAlloc, Layout};
use core::sync::atomic::{AtomicUsize, Ordering};
use embedded_alloc::LlffHeap as Heap;
pub static mut HEAP: PsramHeap = PsramHeap::empty();
struct Region {
start: AtomicUsize,
size: AtomicUsize,
}
impl Region {
const fn default() -> Self {
Self {
start: AtomicUsize::new(0),
size: AtomicUsize::new(0),
}
}
fn contains(&self, address: usize) -> bool {
let start = self.start.load(Ordering::Relaxed);
let end = self.start.load(Ordering::Relaxed);
(start..start + end).contains(&address)
}
fn new(start: usize, size: usize) -> Self {
Self {
start: AtomicUsize::new(start),
size: AtomicUsize::new(size),
}
}
}
/// FIXME: PSRAM-allocated memory isn't compatible with
/// CAS atomics, so we might need a bit of a think about this!
pub struct PsramHeap {
heap: Heap,
region: Region,
}
impl PsramHeap {
pub const fn empty() -> Self {
Self {
heap: Heap::empty(),
region: Region::default(),
}
}
unsafe fn add_psram(&self, region: Region) {
let start = region.start.load(Ordering::SeqCst);
let size = region.size.load(Ordering::SeqCst);
unsafe {
self.heap.init(start, size);
}
self.region.start.store(start, Ordering::SeqCst);
self.region.size.store(size, Ordering::SeqCst);
}
pub fn used(&self) -> usize {
self.heap.used()
}
pub fn free(&self) -> usize {
self.heap.free()
}
}
unsafe impl GlobalAlloc for PsramHeap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
unsafe {
let ptr = self.heap.alloc(layout);
if !ptr.is_null() {
return ptr;
} else {
panic!("HEAP FULL");
}
}
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe {
let ptr_usize = ptr as usize;
if self.region.contains(ptr_usize) {
self.heap.dealloc(ptr, layout);
}
}
}
}
pub fn init_qmi_psram_heap(size: u32) {
unsafe { HEAP.add_psram(Region::new(0x11000000, size as usize)) }
}

View File

@@ -1,15 +1,18 @@
#![feature(impl_trait_in_assoc_type)]
#![feature(type_alias_impl_trait)]
#![feature(ascii_char)]
#![feature(str_from_raw_parts)]
#![cfg_attr(not(test), no_std)]
#![cfg_attr(not(test), no_main)]
#![allow(static_mut_refs)]
#![feature(allocator_api)]
#![feature(slice_ptr_get)]
extern crate alloc;
mod abi;
mod audio;
mod display;
mod elf;
mod framebuffer;
mod peripherals;
mod scsi;
mod storage;
@@ -17,40 +20,60 @@ mod ui;
mod usb;
mod utils;
#[cfg(feature = "psram")]
#[allow(unused)]
mod heap;
#[cfg(feature = "psram")]
#[allow(unused)]
mod psram;
#[cfg(feature = "psram")]
use crate::{heap::HEAP, heap::init_qmi_psram_heap, psram::init_psram, psram::init_psram_qmi};
use crate::{
display::{display_handler, framebuffer_mut, init_display},
abi::{KEY_CACHE, MS_SINCE_LAUNCH},
audio::audio_handler,
display::{FRAMEBUFFER, display_handler, init_display},
peripherals::{
conf_peripherals,
keyboard::{KeyCode, KeyState, read_keyboard_fifo},
keyboard::{KeyState, read_keyboard_fifo},
},
scsi::MSC_SHUTDOWN,
storage::{SDCARD, SdCard},
ui::{SELECTIONS, ui_handler},
usb::usb_handler,
ui::{SELECTIONS, clear_selection, ui_handler},
};
use abi_sys::{EntryFn, Rgb565, RgbColor};
use defmt::unwrap;
use abi_sys::EntryFn;
use bumpalo::Bump;
use core::sync::atomic::{AtomicBool, Ordering};
use embassy_executor::{Executor, Spawner};
use embassy_futures::join::{join, join3, join4, join5};
use embassy_futures::{join::join, select::select};
use embassy_rp::{
Peri,
clocks::ClockConfig,
config::Config,
gpio::{Input, Level, Output, Pull},
i2c::{self, I2c},
multicore::{Stack, spawn_core1},
peripherals::{
DMA_CH0, DMA_CH1, I2C1, PIN_6, PIN_7, PIN_10, PIN_11, PIN_12, PIN_13, PIN_14, PIN_15,
PIN_16, PIN_17, PIN_18, PIN_19, PIN_22, SPI0, SPI1, USB,
DMA_CH0, DMA_CH1, DMA_CH3, DMA_CH4, I2C1, PIN_2, PIN_3, PIN_6, PIN_7, PIN_10, PIN_11,
PIN_12, PIN_13, PIN_14, PIN_15, PIN_16, PIN_17, PIN_18, PIN_19, PIN_20, PIN_21, PIN_22,
PIN_26, PIN_27, PIO0, SPI0, SPI1, USB, WATCHDOG,
},
pio::{self, Common, Pio, StateMachine},
spi::{self, Spi},
usb as embassy_rp_usb,
watchdog::{ResetReason, Watchdog},
};
use embassy_sync::{
blocking_mutex::raw::CriticalSectionRawMutex, channel::Channel, mutex::Mutex, signal::Signal,
blocking_mutex::raw::CriticalSectionRawMutex, channel::Channel, signal::Signal,
};
use embassy_time::{Delay, Duration, Instant, Ticker, Timer};
use embedded_graphics::{
pixelcolor::Rgb565,
prelude::{DrawTarget, RgbColor},
};
use embassy_time::{Delay, Timer};
use embedded_graphics::draw_target::DrawTarget;
use embedded_hal_bus::spi::ExclusiveDevice;
use embedded_sdmmc::SdCard as SdmmcSdCard;
use heapless::spsc::Queue;
use shared::keyboard::KeyEvent;
use static_cell::StaticCell;
use talc::*;
use {defmt_rtt as _, panic_probe as _};
@@ -58,38 +81,64 @@ use {defmt_rtt as _, panic_probe as _};
embassy_rp::bind_interrupts!(struct Irqs {
I2C1_IRQ => i2c::InterruptHandler<I2C1>;
USBCTRL_IRQ => embassy_rp_usb::InterruptHandler<USB>;
PIO0_IRQ_0 => pio::InterruptHandler<PIO0>;
});
static mut CORE1_STACK: Stack<16384> = Stack::new();
static EXECUTOR0: StaticCell<Executor> = StaticCell::new();
static EXECUTOR1: StaticCell<Executor> = StaticCell::new();
static mut ARENA: [u8; 10 * 1024] = [0; 10 * 1024];
#[cfg(not(feature = "pimoroni2w"))]
static mut ARENA: [u8; 250 * 1024] = [0; 250 * 1024];
#[cfg(feature = "pimoroni2w")]
static mut ARENA: [u8; 400 * 1024] = [0; 400 * 1024];
#[global_allocator]
static ALLOCATOR: Talck<spin::Mutex<()>, ClaimOnOom> =
Talc::new(unsafe { ClaimOnOom::new(Span::from_array(core::ptr::addr_of!(ARENA).cast_mut())) })
.lock();
static TASK_STATE: Mutex<CriticalSectionRawMutex, TaskState> = Mutex::new(TaskState::Ui);
static TASK_STATE_CHANGED: Signal<CriticalSectionRawMutex, ()> = Signal::new();
#[derive(Copy, Clone)]
enum TaskState {
Ui,
Kernel,
#[embassy_executor::task]
async fn watchdog_task(mut watchdog: Watchdog) {
if let Some(reason) = watchdog.reset_reason() {
let _reason = match reason {
ResetReason::Forced => "forced",
ResetReason::TimedOut => "timed out",
};
#[cfg(feature = "debug")]
defmt::error!("Watchdog reset reason: {}", _reason);
}
watchdog.start(Duration::from_secs(3));
let mut ticker = Ticker::every(Duration::from_secs(2));
loop {
watchdog.feed();
ticker.next().await;
}
}
static ENABLE_UI: AtomicBool = AtomicBool::new(true);
static UI_CHANGE: Signal<CriticalSectionRawMutex, ()> = Signal::new();
const OVERCLOCK: u32 = 300_000_000;
#[embassy_executor::main]
async fn main(_spawner: Spawner) {
let p = embassy_rp::init(Default::default());
let p = if cfg!(feature = "overclock") {
let clocks = ClockConfig::system_freq(OVERCLOCK).unwrap();
let config = Config::new(clocks);
embassy_rp::init(config)
} else {
embassy_rp::init(Default::default())
};
spawn_core1(
p.CORE1,
unsafe { &mut *core::ptr::addr_of_mut!(CORE1_STACK) },
move || {
let executor1 = EXECUTOR1.init(Executor::new());
executor1.run(|spawner| unwrap!(spawner.spawn(userland_task())));
executor1.run(|spawner| spawner.spawn(userland_task()).unwrap());
},
);
@@ -104,6 +153,19 @@ async fn main(_spawner: Spawner) {
data: p.PIN_14,
reset: p.PIN_15,
};
let Pio {
common, sm0, sm1, ..
} = Pio::new(p.PIO0, Irqs);
let audio = Audio {
pio: common,
sm0,
dma0: p.DMA_CH3,
left: p.PIN_26,
sm1,
dma1: p.DMA_CH4,
right: p.PIN_27,
};
let sd = Sd {
spi: p.SPI0,
clk: p.PIN_18,
@@ -112,89 +174,122 @@ async fn main(_spawner: Spawner) {
cs: p.PIN_17,
det: p.PIN_22,
};
// let psram = Psram {
// pio: p.PIO0,
// sclk: p.PIN_21,
// mosi: p.PIN_2,
// miso: p.PIN_3,
// cs: p.PIN_20,
// dma1: p.DMA_CH3,
// dma2: p.DMA_CH4,
// };
let mcu = Mcu {
i2c: p.I2C1,
clk: p.PIN_7,
data: p.PIN_6,
};
let executor0 = EXECUTOR0.init(Executor::new());
executor0.run(|spawner| unwrap!(spawner.spawn(kernel_task(display, sd, mcu, p.USB))));
executor0.run(|spawner| {
spawner
.spawn(kernel_task(
spawner, p.WATCHDOG, display, audio, sd, mcu, p.USB,
))
.unwrap()
});
}
// One-slot channel to pass EntryFn from core1
static BINARY_CH: Channel<CriticalSectionRawMutex, EntryFn, 1> = Channel::new();
static BINARY_CH: Channel<CriticalSectionRawMutex, (EntryFn, Bump), 1> = Channel::new();
// runs dynamically loaded elf files
#[embassy_executor::task]
async fn userland_task() {
let recv = BINARY_CH.receiver();
loop {
let entry = recv.receive().await;
defmt::info!("got bin");
let (entry, _bump) = recv.receive().await;
// disable kernel ui
{
let mut state = TASK_STATE.lock().await;
*state = TaskState::Kernel;
TASK_STATE_CHANGED.signal(());
ENABLE_UI.store(false, Ordering::Release);
UI_CHANGE.signal(());
clear_selection().await;
MSC_SHUTDOWN.signal(());
}
{
let fb = framebuffer_mut();
fb.clear(Rgb565::BLACK).unwrap();
}
defmt::info!("running entry");
entry().await;
unsafe { MS_SINCE_LAUNCH = Some(Instant::now()) };
#[cfg(feature = "defmt")]
defmt::info!("Executing Binary");
entry();
// enable kernel ui
{
let mut state = TASK_STATE.lock().await;
*state = TaskState::Ui;
TASK_STATE_CHANGED.signal(());
ENABLE_UI.store(true, Ordering::Release);
UI_CHANGE.signal(());
unsafe { FRAMEBUFFER.as_mut().unwrap().clear(Rgb565::BLACK).unwrap() };
let mut selections = SELECTIONS.lock().await;
selections.set_changed(true);
}
}
}
struct Display {
spi: SPI1,
clk: PIN_10,
mosi: PIN_11,
miso: PIN_12,
dma1: DMA_CH0,
dma2: DMA_CH1,
cs: PIN_13,
data: PIN_14,
reset: PIN_15,
spi: Peri<'static, SPI1>,
clk: Peri<'static, PIN_10>,
mosi: Peri<'static, PIN_11>,
miso: Peri<'static, PIN_12>,
dma1: Peri<'static, DMA_CH0>,
dma2: Peri<'static, DMA_CH1>,
cs: Peri<'static, PIN_13>,
data: Peri<'static, PIN_14>,
reset: Peri<'static, PIN_15>,
}
struct Audio {
pio: Common<'static, PIO0>,
dma0: Peri<'static, DMA_CH3>,
sm0: StateMachine<'static, PIO0, 0>,
left: Peri<'static, PIN_26>,
dma1: Peri<'static, DMA_CH4>,
sm1: StateMachine<'static, PIO0, 1>,
right: Peri<'static, PIN_27>,
}
struct Sd {
spi: SPI0,
clk: PIN_18,
mosi: PIN_19,
miso: PIN_16,
cs: PIN_17,
det: PIN_22,
spi: Peri<'static, SPI0>,
clk: Peri<'static, PIN_18>,
mosi: Peri<'static, PIN_19>,
miso: Peri<'static, PIN_16>,
cs: Peri<'static, PIN_17>,
det: Peri<'static, PIN_22>,
}
#[allow(dead_code)]
struct Psram {
pio: Peri<'static, PIO0>,
sclk: Peri<'static, PIN_21>,
mosi: Peri<'static, PIN_2>,
miso: Peri<'static, PIN_3>,
cs: Peri<'static, PIN_20>,
dma1: Peri<'static, DMA_CH3>,
dma2: Peri<'static, DMA_CH4>,
}
struct Mcu {
i2c: I2C1,
clk: PIN_7,
data: PIN_6,
i2c: Peri<'static, I2C1>,
clk: Peri<'static, PIN_7>,
data: Peri<'static, PIN_6>,
}
#[embassy_executor::task]
async fn kernel_task(display: Display, sd: Sd, mcu: Mcu, usb: USB) {
// MCU i2c bus for peripherals
async fn setup_mcu(mcu: Mcu) {
// MCU i2c bus for peripherals( keyboard)
let mut config = i2c::Config::default();
config.frequency = 400_000;
let i2c1 = I2c::new_async(mcu.i2c, mcu.clk, mcu.data, Irqs, config);
conf_peripherals(i2c1).await;
}
Timer::after_millis(250).await;
async fn setup_display(display: Display, spawner: Spawner) {
let mut config = spi::Config::default();
config.frequency = 16_000_000;
config.frequency = 192_000_000;
let spi = Spi::new(
display.spi,
display.clk,
@@ -205,31 +300,43 @@ async fn kernel_task(display: Display, sd: Sd, mcu: Mcu, usb: USB) {
config,
);
let display = init_display(spi, display.cs, display.data, display.reset).await;
spawner.spawn(display_handler(display)).unwrap();
}
let display_fut = display_handler(display);
// psram is kind of useless on the pico calc
// ive opted to use the pimoroni with on onboard xip psram instead
// async fn setup_psram(psram: Psram) {
// let psram = init_psram(
// psram.pio, psram.sclk, psram.mosi, psram.miso, psram.cs, psram.dma1, psram.dma2,
// )
// .await;
let ui_fut = ui_handler();
// #[cfg(feature = "defmt")]
// defmt::info!("psram size: {}", psram.size);
let binary_search_fut = async {
loop {
{
let mut guard = SDCARD.get().lock().await;
// if psram.size == 0 {
// #[cfg(feature = "defmt")]
// defmt::info!("\u{1b}[1mExternal PSRAM was NOT found!\u{1b}[0m");
// }
// }
if let Some(sd) = guard.as_mut() {
let files = sd.list_files_by_extension(".bin").unwrap();
let mut select = SELECTIONS.lock().await;
#[cfg(feature = "psram")]
async fn setup_qmi_psram() {
Timer::after_millis(250).await;
let psram_qmi_size = init_psram_qmi(&embassy_rp::pac::QMI, &embassy_rp::pac::XIP_CTRL);
#[cfg(feature = "debug")]
defmt::info!("size: {}", psram_qmi_size);
Timer::after_millis(100).await;
if select.selections != files {
select.selections = files;
select.reset();
if psram_qmi_size > 0 {
init_qmi_psram_heap(psram_qmi_size);
return;
} else {
panic!("qmi psram not initialized");
}
}
}
Timer::after_secs(5).await;
}
};
{
async fn setup_sd(sd: Sd) {
let mut config = spi::Config::default();
config.frequency = 400_000;
let spi = Spi::new_blocking(sd.spi, sd.clk, sd.mosi, sd.miso, config.clone());
@@ -242,27 +349,81 @@ async fn kernel_task(display: Display, sd: Sd, mcu: Mcu, usb: USB) {
config.frequency = 32_000_000;
sdcard.spi(|dev| dev.bus_mut().set_config(&config));
SDCARD.get().lock().await.replace(SdCard::new(sdcard, det));
};
}
// let usb = embassy_rp_usb::Driver::new(usb, Irqs);
// let usb_fut = usb_handler(usb);
#[embassy_executor::task]
async fn kernel_task(
spawner: Spawner,
watchdog: Peri<'static, WATCHDOG>,
display: Display,
audio: Audio,
sd: Sd,
// _psram: Psram,
mcu: Mcu,
usb: Peri<'static, USB>,
) {
spawner
.spawn(watchdog_task(Watchdog::new(watchdog)))
.unwrap();
let key_abi_fut = async {
loop {
#[cfg(feature = "debug")]
defmt::info!("Clock: {}", embassy_rp::clocks::clk_sys_freq());
setup_mcu(mcu).await;
#[cfg(feature = "defmt")]
defmt::info!("setting up psram");
Timer::after_millis(100).await;
get_keys().await
}
};
join4(display_fut, ui_fut, binary_search_fut, key_abi_fut).await;
// setup_psram(psram).await;
#[cfg(feature = "psram")]
setup_qmi_psram().await;
Timer::after_millis(100).await;
setup_display(display, spawner).await;
setup_sd(sd).await;
spawner.spawn(audio_handler(audio)).unwrap();
let _usb = embassy_rp_usb::Driver::new(usb, Irqs);
// spawner.spawn(usb_handler(usb)).unwrap();
loop {
let ui_enabled = ENABLE_UI.load(Ordering::Relaxed);
if ui_enabled {
select(join(ui_handler(), prog_search_handler()), UI_CHANGE.wait()).await;
} else {
select(key_handler(), UI_CHANGE.wait()).await;
}
}
}
static mut KEY_CACHE: Queue<KeyEvent, 32> = Queue::new();
async fn prog_search_handler() {
loop {
{
let mut guard = SDCARD.get().lock().await;
let sd = guard.as_mut().unwrap();
async fn get_keys() {
let mut files = sd.list_files_by_extension(".bin").unwrap();
files.sort();
let mut select = SELECTIONS.lock().await;
if *select.selections() != files {
select.update_selections(files);
select.reset();
}
}
Timer::after_secs(5).await;
}
}
async fn key_handler() {
loop {
if let Some(event) = read_keyboard_fifo().await {
unsafe {
let _ = KEY_CACHE.enqueue(event);
}
}
Timer::after_millis(50).await;
}
}

View File

@@ -1,5 +1,5 @@
use crate::peripherals::PERIPHERAL_BUS;
pub use shared::keyboard::{KeyCode, KeyEvent, KeyState, Modifiers};
pub use abi_sys::keyboard::{KeyCode, KeyEvent, KeyState, Modifiers};
const REG_ID_KEY: u8 = 0x04;
const REG_ID_FIF: u8 = 0x09;

View File

@@ -5,7 +5,9 @@ use embassy_rp::{
i2c::{Async, I2c},
peripherals::I2C1,
};
use embassy_sync::{blocking_mutex::raw::NoopRawMutex, lazy_lock::LazyLock, mutex::Mutex};
use embassy_sync::{
blocking_mutex::raw::CriticalSectionRawMutex, lazy_lock::LazyLock, mutex::Mutex,
};
use embassy_time::Timer;
pub mod keyboard;
@@ -15,7 +17,7 @@ use crate::peripherals::keyboard::{configure_keyboard, read_keyboard_fifo};
const MCU_ADDR: u8 = 0x1F;
type I2CBUS = I2c<'static, I2C1, Async>;
pub static PERIPHERAL_BUS: LazyLock<Mutex<NoopRawMutex, Option<I2CBUS>>> =
pub static PERIPHERAL_BUS: LazyLock<Mutex<CriticalSectionRawMutex, Option<I2CBUS>>> =
LazyLock::new(|| Mutex::new(None));
const REG_ID_VER: u8 = 0x01;

618
kernel/src/psram.rs Normal file
View File

@@ -0,0 +1,618 @@
// This whole file was taken from
// <https://github.com/wezterm/picocalc-wezterm/blob/8dcf8aae0598afdeaf0ed2ba50c39dea6e30c011/src/psram.rs>
//
use crate::Irqs;
use embassy_futures::yield_now;
use embassy_rp::Peri;
use embassy_rp::clocks::clk_peri_freq;
use embassy_rp::gpio::{Drive, SlewRate};
use embassy_rp::peripherals::{DMA_CH3, DMA_CH4, PIN_2, PIN_3, PIN_20, PIN_21, PIO0};
use embassy_rp::pio::program::pio_asm;
use embassy_rp::pio::{Config, Direction, Pio, ShiftDirection};
use embassy_rp::pio_programs::clock_divider::calculate_pio_clock_divider;
use embassy_time::{Duration, Instant, Timer};
// The physical connections in the picocalc schematic are:
// LABEL PICO ESP-PSRAM64H
// RAM_CS - PIN_20 CE (pulled up to 3v3 via 10kOhm)
// RAM_SCK - PIN_21 SCLK
// RAM_TX - PIN_2 SI/SIO0
// RAM_RX - PIN_3 SO/SIO1
// RAM_IO2 - PIN_4 SIO2 (QPI Mode)
// RAM_IO3 - PIN_5 SIO3 (QPI Mode)
#[allow(unused)]
const PSRAM_CMD_QUAD_END: u8 = 0xf5;
#[allow(unused)]
const PSRAM_CMD_QUAD_ENABLE: u8 = 0x35;
#[allow(unused)]
const PSRAM_CMD_READ_ID: u8 = 0x9F;
const PSRAM_CMD_RSTEN: u8 = 0x66;
const PSRAM_CMD_RST: u8 = 0x99;
const PSRAM_CMD_WRITE: u8 = 0x02;
const PSRAM_CMD_FAST_READ: u8 = 0x0B;
#[allow(unused)]
const PSRAM_CMD_QUAD_READ: u8 = 0xEB;
#[allow(unused)]
const PSRAM_CMD_QUAD_WRITE: u8 = 0x38;
#[allow(unused)]
const PSRAM_CMD_NOOP: u8 = 0xFF;
#[allow(unused)]
const PSRAM_KNOWN_GOOD_DIE_PASS: u8 = 0x5d;
const MAX_PSRAM_FREQ: u32 = 133_000_000;
pub struct PsRam {
sm: embassy_rp::pio::StateMachine<'static, PIO0, 0>,
tx_ch: Peri<'static, DMA_CH3>,
rx_ch: Peri<'static, DMA_CH4>,
pub size: u32,
}
impl PsRam {
pub async fn send_command(&mut self, cmd: &[u8], out: &mut [u8]) {
if out.is_empty() {
self.sm
.tx()
.dma_push(self.tx_ch.reborrow(), cmd, false)
.await;
} else {
let (rx, tx) = self.sm.rx_tx();
tx.dma_push(self.tx_ch.reborrow(), cmd, false).await;
rx.dma_pull(self.rx_ch.reborrow(), out, false).await;
}
}
pub async fn write(&mut self, mut addr: u32, mut data: &[u8]) {
// I haven't seen this work reliably over 24 bytes
const MAX_CHUNK: usize = 24;
while data.len() > 0 {
let to_write = data.len().min(MAX_CHUNK);
//defmt::info!("writing {to_write} @ {addr}");
#[rustfmt::skip]
let mut to_send = [
32 + (to_write as u8 * 8), // write address + data
0, // read 0 bits
PSRAM_CMD_WRITE,
((addr >> 16) & 0xff) as u8,
((addr >> 8) & 0xff) as u8,
(addr & 0xff) as u8,
// This sequence must be MAX_CHUNK in length
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
];
for (src, dst) in data.iter().zip(to_send.iter_mut().skip(6)) {
*dst = *src;
}
self.send_command(&to_send[0..6 + to_write], &mut []).await;
addr += to_write as u32;
data = &data[to_write..];
}
}
pub async fn read_id(&mut self) -> [u8; 3] {
let mut id = [0u8; 3];
#[rustfmt::skip]
self.send_command(
&[
32, // write 32 bits
3 * 8, // read 8 bytes = 64 bits
PSRAM_CMD_READ_ID,
// don't care: 24-bit "address"
0, 0, 0,
],
&mut id,
)
.await;
id
}
pub async fn read(&mut self, mut addr: u32, mut out: &mut [u8]) {
// Cannot get reliable reads above 4 bytes at a time.
// out[4] will always have a bit error
const MAX_CHUNK: usize = 4;
while out.len() > 0 {
let to_read = out.len().min(MAX_CHUNK);
//defmt::info!("reading {to_read} @ {addr}");
self.send_command(
&[
40, // write 40 bits
to_read as u8 * 8, // read n bytes
PSRAM_CMD_FAST_READ,
((addr >> 16) & 0xff) as u8,
((addr >> 8) & 0xff) as u8,
(addr & 0xff) as u8,
0, // 8 cycle delay by sending 8 bits of don't care data
],
&mut out[0..to_read],
)
.await;
addr += to_read as u32;
out = &mut out[to_read..];
}
}
#[allow(unused)]
pub async fn write8(&mut self, addr: u32, data: u8) {
//defmt::info!("write8 addr {addr} <- {data:x}");
self.send_command(
&[
40, // write 40 bits
0, // read 0 bits
PSRAM_CMD_WRITE,
((addr >> 16) & 0xff) as u8,
((addr >> 8) & 0xff) as u8,
(addr & 0xff) as u8,
data,
],
&mut [],
)
.await;
}
#[allow(unused)]
pub async fn read8(&mut self, addr: u32) -> u8 {
let mut buf = [0u8];
self.send_command(
&[
40, // write 40 bits
8, // read 8 bits
PSRAM_CMD_FAST_READ,
((addr >> 16) & 0xff) as u8,
((addr >> 8) & 0xff) as u8,
(addr & 0xff) as u8,
0, // 8 cycle delay
],
&mut buf,
)
.await;
buf[0]
}
}
pub async fn init_psram(
pio: Peri<'static, PIO0>,
sclk: Peri<'static, PIN_21>,
mosi: Peri<'static, PIN_2>,
miso: Peri<'static, PIN_3>,
cs: Peri<'static, PIN_20>,
dma1: Peri<'static, DMA_CH3>,
dma2: Peri<'static, DMA_CH4>,
) -> PsRam {
let mut pio = Pio::new(pio, Irqs);
let divider = calculate_pio_clock_divider(MAX_PSRAM_FREQ);
// This pio program was taken from
// <https://github.com/polpo/rp2040-psram/blob/7786c93ec8d02dbb4f94a2e99645b25fb4abc2db/psram_spi.pio>
// which is Copyright © 2023 Ian Scott, reproduced here under the MIT license
let p = pio_asm!(
r#"
.side_set 2 ; sideset bit 1 is SCK, bit 0 is CS
begin:
out x, 8 side 0b01 ; x = number of bits to output. CS deasserted
out y, 8 side 0b01 ; y = number of bits to input
jmp x--, writeloop side 0b01 ; Pre-decement x by 1 so loop has correct number of iterations
writeloop:
out pins, 1 side 0b00 ; Write value on pin, lower clock. CS asserted
jmp x--, writeloop side 0b10 ; Raise clock: this is when PSRAM reads the value. Loop if we have more to write
jmp !y, done side 0b00 ; If this is a write-only operation, jump back to beginning
nop side 0b10 ; Fudge factor of extra clock cycle; the PSRAM needs 1 extra for output to start appearing
jmp readloop_mid side 0b00 ; Jump to middle of readloop to decrement y and get right clock phase
readloop:
in pins, 1 side 0b00 ; Read value on pin, lower clock. Datasheet says to read on falling edge > 83MHz
readloop_mid:
jmp y--, readloop side 0b10 ; Raise clock. Loop if we have more to read
done:
nop side 0b11 ; CS deasserted
"#
);
let prog = pio.common.load_program(&p.program);
let mut cfg = Config::default();
let mut cs = pio.common.make_pio_pin(cs);
let mut sclk = pio.common.make_pio_pin(sclk);
let mut mosi = pio.common.make_pio_pin(mosi);
let mut miso = pio.common.make_pio_pin(miso);
sclk.set_slew_rate(SlewRate::Fast);
mosi.set_slew_rate(SlewRate::Fast);
cs.set_drive_strength(Drive::_4mA);
sclk.set_drive_strength(Drive::_4mA);
mosi.set_drive_strength(Drive::_4mA);
miso.set_drive_strength(Drive::_4mA);
cfg.use_program(&prog, &[&cs, &sclk]);
cfg.set_out_pins(&[&mosi]);
cfg.set_in_pins(&[&miso]);
cfg.shift_out.direction = ShiftDirection::Left;
cfg.shift_out.auto_fill = true;
cfg.shift_out.threshold = 8;
cfg.shift_in = cfg.shift_out;
cfg.clock_divider = divider;
let mut sm = pio.sm0;
sm.restart();
sm.set_pin_dirs(Direction::Out, &[&cs, &sclk]);
sm.set_pin_dirs(Direction::Out, &[&mosi]);
sm.set_pin_dirs(Direction::In, &[&miso]);
miso.set_input_sync_bypass(true);
sm.set_config(&cfg);
sm.set_enable(true);
let mut psram = PsRam {
sm,
tx_ch: dma1,
rx_ch: dma2,
size: 0,
};
// Issue a reset command
psram.send_command(&[8, 0, PSRAM_CMD_RSTEN], &mut []).await;
Timer::after(Duration::from_micros(50)).await;
psram.send_command(&[8, 0, PSRAM_CMD_RST], &mut []).await;
Timer::after(Duration::from_micros(100)).await;
#[cfg(feature = "defmt")]
defmt::info!("Verifying 1 byte write and read...");
for i in 0..10u8 {
psram.write8(i as u32, i).await;
}
for i in 0..10u32 {
let n = psram.read8(i as u32).await;
if n as u32 != i {}
}
#[cfg(feature = "defmt")]
defmt::info!("testing read again @ 0");
let mut got = [0u8; 8];
psram.read(0, &mut got).await;
const EXPECT: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7];
if got != EXPECT {
#[cfg(feature = "defmt")]
defmt::warn!("Got Read error");
}
const DEADBEEF: &[u8] = &[0xd, 0xe, 0xa, 0xd, 0xb, 0xe, 0xe, 0xf];
#[cfg(feature = "defmt")]
defmt::info!("testing write of deadbeef at 0");
psram.write(0, DEADBEEF).await;
#[cfg(feature = "defmt")]
defmt::info!("testing read of deadbeef from 0");
psram.read(0, &mut got).await;
if got != DEADBEEF {
for addr in 0..DEADBEEF.len() {
let bad = got[addr];
if bad != DEADBEEF[addr] {
let x = psram.read8(addr as u32).await;
#[cfg(feature = "defmt")]
defmt::info!("read addr: {}, got: {:X}", addr, x);
}
}
}
const TEST_STRING: &[u8] = b"hello there, this is a test, how is it?";
psram.write(16, TEST_STRING).await;
let mut buffer = [0u8; 42];
psram.read(16, &mut buffer).await;
let got = &buffer[0..TEST_STRING.len()];
if got != TEST_STRING {}
#[cfg(feature = "defmt")]
defmt::info!("PSRAM test complete");
let id = psram.read_id().await;
#[cfg(feature = "defmt")]
defmt::info!("psram id: {}", id);
// id: [d, 5d, 53, 15, 49, e3, 7c, 7b]
// id[0] -- manufacturer id
// id[1] -- "known good die" status
if id[1] == PSRAM_KNOWN_GOOD_DIE_PASS {
// See <https://github.com/espressif/esp-idf/blob/1c468f68259065ef51afd114605d9122f13d9d72/components/esp_psram/esp32/esp_psram_impl_quad.c#L67-L86>
// for information on deciding the size of ESP PSRAM chips,
// such as the one used in the picocalc
let size = match (id[2] >> 5) & 0x7 {
0 => 16,
1 => 32,
2 => 64,
_ => 0,
};
psram.size = size * 1024 * 1024 / 8;
}
psram
}
#[allow(unused)]
pub async fn test_psram(psram: &mut PsRam) -> bool {
const REPORT_CHUNK: u32 = 256 * 1024;
const BLOCK_SIZE: usize = 8;
let limit = psram.size; //.min(4 * 1024 * 1024);
let start = Instant::now();
fn expect(addr: u32) -> [u8; BLOCK_SIZE] {
[
!((addr >> 24 & 0xff) as u8),
!((addr >> 16 & 0xff) as u8),
!((addr >> 8 & 0xff) as u8),
!((addr & 0xff) as u8),
((addr >> 24 & 0xff) as u8),
((addr >> 16 & 0xff) as u8),
((addr >> 8 & 0xff) as u8),
((addr & 0xff) as u8),
]
}
for i in 0..limit / BLOCK_SIZE as u32 {
let addr = i * BLOCK_SIZE as u32;
let data = expect(addr);
psram.write(addr, &data).await;
if addr > 0 && addr % REPORT_CHUNK == 0 {
if start.elapsed() > Duration::from_secs(5) {}
}
// Yield so that the watchdog doesn't kick in
yield_now().await;
}
let writes_took = start.elapsed();
#[cfg(feature = "defmt")]
defmt::info!("Starting reads...");
Timer::after(Duration::from_millis(200)).await;
let start = Instant::now();
let mut bad_count = 0;
let mut data = [0u8; BLOCK_SIZE];
for i in 0..limit / BLOCK_SIZE as u32 {
let addr = i * BLOCK_SIZE as u32;
let expect = expect(addr);
psram.read(addr, &mut data).await;
if addr == 0 {
Timer::after(Duration::from_millis(200)).await;
}
if data != expect {
bad_count += 1;
if bad_count < 50 {}
}
if addr > 0 && addr % REPORT_CHUNK == 0 {
if start.elapsed() > Duration::from_secs(5) {}
}
// Yield so that the watchdog doesn't kick in
yield_now().await;
}
let reads_took = start.elapsed();
bad_count == 0
}
// The origin of the code in this file is:
// <https://github.com/Altaflux/rp2350-psram-test/blob/ae50a819fef96486f6d962a609984cde4b4dd4cc/src/psram.rs#L1>
// which is MIT/Apache-2 licensed.
#[unsafe(link_section = ".data")]
#[inline(never)]
pub fn detect_psram_qmi(qmi: &embassy_rp::pac::qmi::Qmi) -> u32 {
const GPIO_FUNC_XIP_CS1: u8 = 9;
const XIP_CS_PIN: usize = 47;
embassy_rp::pac::PADS_BANK0.gpio(XIP_CS_PIN).modify(|w| {
w.set_iso(true);
});
embassy_rp::pac::PADS_BANK0.gpio(XIP_CS_PIN).modify(|w| {
w.set_ie(true);
w.set_od(false);
});
embassy_rp::pac::IO_BANK0
.gpio(XIP_CS_PIN)
.ctrl()
.write(|w| w.set_funcsel(GPIO_FUNC_XIP_CS1));
embassy_rp::pac::PADS_BANK0.gpio(XIP_CS_PIN).modify(|w| {
w.set_iso(false);
});
critical_section::with(|_cs| {
// Try and read the PSRAM ID via direct_csr.
qmi.direct_csr().write(|w| {
w.set_clkdiv(30);
w.set_en(true);
});
// Need to poll for the cooldown on the last XIP transfer to expire
// (via direct-mode BUSY flag) before it is safe to perform the first
// direct-mode operation
while qmi.direct_csr().read().busy() {
// rp235x_hal::arch::nop();
}
// Exit out of QMI in case we've inited already
qmi.direct_csr().modify(|w| w.set_assert_cs1n(true));
// Transmit the command to exit QPI quad mode - read ID as standard SPI
// Transmit as quad.
qmi.direct_tx().write(|w| {
w.set_oe(true);
w.set_iwidth(embassy_rp::pac::qmi::vals::Iwidth::Q);
w.set_data(PSRAM_CMD_QUAD_END.into());
});
while qmi.direct_csr().read().busy() {
// rp235x_hal::arch::nop();
}
let _ = qmi.direct_rx().read();
qmi.direct_csr().modify(|w| {
w.set_assert_cs1n(false);
});
// Read the id
qmi.direct_csr().modify(|w| {
w.set_assert_cs1n(true);
});
// kgd is "known good die"
let mut kgd: u16 = 0;
let mut eid: u16 = 0;
for i in 0usize..7 {
qmi.direct_tx().write(|w| {
w.set_data(if i == 0 {
PSRAM_CMD_READ_ID.into()
} else {
PSRAM_CMD_NOOP.into()
})
});
while !qmi.direct_csr().read().txempty() {
// rp235x_hal::arch::nop();
}
while qmi.direct_csr().read().busy() {
// rp235x_hal::arch::nop();
}
let value = qmi.direct_rx().read().direct_rx();
match i {
5 => {
kgd = value;
}
6 => {
eid = value;
}
_ => {}
}
}
qmi.direct_csr().modify(|w| {
w.set_assert_cs1n(false);
w.set_en(false);
});
let mut param_size: u32 = 0;
if kgd == PSRAM_KNOWN_GOOD_DIE_PASS as u16 {
param_size = 1024 * 1024;
let size_id = eid >> 5;
if eid == 0x26 || size_id == 2 {
param_size *= 8;
} else if size_id == 0 {
param_size *= 2;
} else if size_id == 1 {
param_size *= 4;
}
}
param_size
})
}
#[unsafe(link_section = ".data")]
#[inline(never)]
pub fn init_psram_qmi(
qmi: &embassy_rp::pac::qmi::Qmi,
xip: &embassy_rp::pac::xip_ctrl::XipCtrl,
) -> u32 {
let psram_size = detect_psram_qmi(qmi);
if psram_size == 0 {
#[cfg(feature = "debug")]
defmt::error!("qmi psram size 0");
return 0;
}
let clock_hz = clk_peri_freq();
let mut divisor: u32 = (clock_hz + MAX_PSRAM_FREQ - 1) / MAX_PSRAM_FREQ;
if divisor == 1 && clock_hz > 100_000_000 {
divisor = 2;
}
let mut rxdelay: u32 = divisor;
if clock_hz / divisor > 100_000_000 {
rxdelay += 1;
}
// - Max select must be <= 8us. The value is given in multiples of 64 system clocks.
// - Min deselect must be >= 18ns. The value is given in system clock cycles - ceil(divisor / 2).
let clock_period_fs: u64 = 1_000_000_000_000_000_u64 / u64::from(clock_hz);
let max_select: u8 = ((125 * 1_000_000) / clock_period_fs) as u8;
let min_deselect: u32 = ((18 * 1_000_000 + (clock_period_fs - 1)) / clock_period_fs
- u64::from(divisor + 1) / 2) as u32;
// #[cfg(feature = "defmt")]
// defmt::info!(
// "clock_period_fs={} max_select={} min_deselect={}",
// clock_period_fs,
// max_select,
// min_deselect
// );
qmi.direct_csr().write(|w| {
w.set_clkdiv(10);
w.set_en(true);
w.set_auto_cs1n(true);
});
while qmi.direct_csr().read().busy() {
// rp235x_hal::arch::nop();
}
qmi.direct_tx().write(|w| {
w.set_nopush(true);
w.0 = 0x35;
});
while qmi.direct_csr().read().busy() {
// rp235x_hal::arch::nop();
}
qmi.mem(1).timing().write(|w| {
w.set_cooldown(1);
w.set_pagebreak(embassy_rp::pac::qmi::vals::Pagebreak::_1024);
w.set_max_select(max_select as u8);
w.set_min_deselect(min_deselect as u8);
w.set_rxdelay(rxdelay as u8);
w.set_clkdiv(divisor as u8);
});
// // Set PSRAM commands and formats
qmi.mem(1).rfmt().write(|w| {
w.set_prefix_width(embassy_rp::pac::qmi::vals::PrefixWidth::Q);
w.set_addr_width(embassy_rp::pac::qmi::vals::AddrWidth::Q);
w.set_suffix_width(embassy_rp::pac::qmi::vals::SuffixWidth::Q);
w.set_dummy_width(embassy_rp::pac::qmi::vals::DummyWidth::Q);
w.set_data_width(embassy_rp::pac::qmi::vals::DataWidth::Q);
w.set_prefix_len(embassy_rp::pac::qmi::vals::PrefixLen::_8);
w.set_dummy_len(embassy_rp::pac::qmi::vals::DummyLen::_24);
});
qmi.mem(1).rcmd().write(|w| w.0 = 0xEB);
qmi.mem(1).wfmt().write(|w| {
w.set_prefix_width(embassy_rp::pac::qmi::vals::PrefixWidth::Q);
w.set_addr_width(embassy_rp::pac::qmi::vals::AddrWidth::Q);
w.set_suffix_width(embassy_rp::pac::qmi::vals::SuffixWidth::Q);
w.set_dummy_width(embassy_rp::pac::qmi::vals::DummyWidth::Q);
w.set_data_width(embassy_rp::pac::qmi::vals::DataWidth::Q);
w.set_prefix_len(embassy_rp::pac::qmi::vals::PrefixLen::_8);
});
qmi.mem(1).wcmd().write(|w| w.0 = 0x38);
// Disable direct mode
qmi.direct_csr().write(|w| w.0 = 0);
// Enable writes to PSRAM
xip.ctrl().modify(|w| w.set_writable_m1(true));
psram_size
}

View File

@@ -1,67 +1,114 @@
use crate::format;
use embassy_futures::select::select;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::lazy_lock::LazyLock;
use embassy_sync::signal::Signal;
use embassy_usb::Builder;
use embassy_usb::driver::{Driver, EndpointIn, EndpointOut};
use embassy_usb::types::StringIndex;
use embassy_usb::{Builder, Config};
use embedded_sdmmc::{Block, BlockIdx};
use heapless::Vec;
mod scsi_types;
use scsi_types::*;
use crate::storage::SdCard;
use crate::storage::{SDCARD, SdCard};
const BULK_ENDPOINT_PACKET_SIZE: usize = 64;
pub struct MassStorageClass<'d, 's, D: Driver<'d>> {
sdcard: &'s SdCard,
pub static MSC_SHUTDOWN: Signal<CriticalSectionRawMutex, ()> = Signal::new();
// number of blocks to read from sd at once
// higher is better, but is larger. Size is BLOCKS * 512 bytes
const BLOCKS: usize = 32;
static mut BLOCK_BUF: LazyLock<[Block; BLOCKS]> =
LazyLock::new(|| core::array::from_fn(|_| Block::new()));
pub struct MassStorageClass<'d, D: Driver<'d>> {
temp_sd: Option<SdCard>, // temporary owns sdcard when scsi is running
ejected: bool,
pending_eject: bool,
bulk_out: D::EndpointOut,
bulk_in: D::EndpointIn,
}
impl<'d, 's, D: Driver<'d>> MassStorageClass<'d, 's, D> {
pub fn new(builder: &mut Builder<'d, D>, sdcard: &'s SdCard) -> Self {
impl<'d, 's, D: Driver<'d>> MassStorageClass<'d, D> {
pub fn new(builder: &mut Builder<'d, D>, temp_sd: Option<SdCard>) -> Self {
let mut function = builder.function(0x08, SUBCLASS_SCSI, 0x50); // Mass Storage class
let mut interface = function.interface();
let mut alt = interface.alt_setting(0x08, SUBCLASS_SCSI, 0x50, None);
let bulk_out = alt.endpoint_bulk_out(BULK_ENDPOINT_PACKET_SIZE as u16);
let bulk_in = alt.endpoint_bulk_in(BULK_ENDPOINT_PACKET_SIZE as u16);
let bulk_out = alt.endpoint_bulk_out(None, BULK_ENDPOINT_PACKET_SIZE as u16);
let bulk_in = alt.endpoint_bulk_in(None, BULK_ENDPOINT_PACKET_SIZE as u16);
Self {
temp_sd,
pending_eject: false,
ejected: false,
bulk_out,
bulk_in,
sdcard,
}
}
pub async fn poll(&mut self) {
loop {
if !self.ejected {
select(self.handle_cbw(), MSC_SHUTDOWN.wait()).await;
if MSC_SHUTDOWN.signaled() {
#[cfg(feature = "defmt")]
defmt::info!("MSC shutting down");
if self.temp_sd.is_some() {
let mut guard = SDCARD.get().lock().await;
guard.replace(self.temp_sd.take().unwrap()).unwrap();
}
self.ejected = true;
return;
}
}
}
}
async fn handle_cbw(&mut self) {
let mut cbw_buf = [0u8; 31];
if let Ok(n) = self.bulk_out.read(&mut cbw_buf).await {
if n == 31 {
if let Some(cbw) = CommandBlockWrapper::parse(&cbw_buf[..n]) {
// TODO: validate cbw
if self.handle_command(&cbw.CBWCB).await.is_ok() {
// Take sdcard to increase speed
if self.temp_sd.is_none() {
let mut guard = SDCARD.get().lock().await;
if let Some(sd) = guard.take() {
self.temp_sd = Some(sd);
} else {
#[cfg(feature = "defmt")]
defmt::warn!("Tried to take SDCARD but it was already taken");
return;
}
}
let command = parse_cb(&cbw.CBWCB);
if self.handle_command(command).await.is_ok() {
self.send_csw_success(cbw.dCBWTag).await
} else {
self.send_csw_fail(cbw.dCBWTag).await
}
if self.pending_eject {
if let ScsiCommand::Write { lba: _, len: _ } = command {
MSC_SHUTDOWN.signal(());
}
}
}
}
}
}
async fn handle_command(&mut self, cbw: &[u8]) -> Result<(), ()> {
async fn handle_command(&mut self, command: ScsiCommand) -> Result<(), ()> {
let mut response: Vec<u8, BULK_ENDPOINT_PACKET_SIZE> = Vec::new();
let mut block = [Block::new(); 1];
match parse_cb(cbw) {
ScsiCommand::Unknown => {
#[cfg(feature = "defmt")]
defmt::warn!("Got unexpected scsi command: {}", cbw);
Err(())
}
match command {
ScsiCommand::Unknown => Err(()),
ScsiCommand::Inquiry {
evpd,
page_code,
@@ -139,18 +186,21 @@ impl<'d, 's, D: Driver<'d>> MassStorageClass<'d, 's, D> {
self.bulk_in.write(&response[..len]).await.map_err(|_| ())
}
ScsiCommand::TestUnitReady => {
if self.sdcard.is_attached() {
if self.temp_sd.as_ref().unwrap().is_attached() {
Ok(())
} else {
Err(())
}
}
ScsiCommand::RequestSense { desc, alloc_len } => Ok(()),
ScsiCommand::RequestSense {
desc: _,
alloc_len: _,
} => Ok(()),
ScsiCommand::ModeSense6 {
dbd,
page_control,
page_code,
subpage_code,
dbd: _,
page_control: _,
page_code: _,
subpage_code: _,
alloc_len,
} => {
// DBD=0, no block descriptors; total length = 4
@@ -166,10 +216,10 @@ impl<'d, 's, D: Driver<'d>> MassStorageClass<'d, 's, D> {
self.bulk_in.write(&response[..len]).await.map_err(|_| ())
}
ScsiCommand::ModeSense10 {
dbd,
page_control,
page_code,
subpage_code,
dbd: _,
page_control: _,
page_code: _,
subpage_code: _,
alloc_len,
} => {
let response = [
@@ -186,7 +236,7 @@ impl<'d, 's, D: Driver<'d>> MassStorageClass<'d, 's, D> {
}
ScsiCommand::ReadCapacity10 => {
let block_size = SdCard::BLOCK_SIZE as u64;
let total_blocks = self.sdcard.size() / block_size;
let total_blocks = self.temp_sd.as_ref().unwrap().size() / block_size;
let last_lba = total_blocks.checked_sub(1).unwrap_or(0);
@@ -197,7 +247,7 @@ impl<'d, 's, D: Driver<'d>> MassStorageClass<'d, 's, D> {
}
ScsiCommand::ReadCapacity16 { alloc_len } => {
let block_size = SdCard::BLOCK_SIZE as u64;
let total_blocks = self.sdcard.size() / block_size;
let total_blocks = self.temp_sd.as_ref().unwrap().size() / block_size;
let last_lba = total_blocks.checked_sub(1).unwrap_or(0);
@@ -209,31 +259,80 @@ impl<'d, 's, D: Driver<'d>> MassStorageClass<'d, 's, D> {
self.bulk_in.write(&response[..len]).await.map_err(|_| ())
}
ScsiCommand::Read { lba, len } => {
for i in 0..len {
let block_idx = BlockIdx(lba as u32 + i as u32);
self.sdcard.read_blocks(&mut block, block_idx)?;
for chunk in block[0].contents.chunks(BULK_ENDPOINT_PACKET_SIZE.into()) {
let sdcard = self.temp_sd.as_ref().unwrap();
let block_buf = unsafe { &mut *BLOCK_BUF.get_mut() };
let mut blocks = len;
let mut idx = lba;
while blocks > 0 {
if blocks >= block_buf.len() as u64 {
sdcard.read_blocks(block_buf, BlockIdx(idx as u32))?;
for block in &mut *block_buf {
for chunk in block.contents.chunks(BULK_ENDPOINT_PACKET_SIZE.into()) {
self.bulk_in.write(chunk).await.map_err(|_| ())?;
}
}
blocks -= block_buf.len() as u64;
idx += block_buf.len() as u64;
} else {
sdcard
.read_blocks(&mut block_buf[..blocks as usize], BlockIdx(idx as u32))?;
for block in &block_buf[..blocks as usize] {
for chunk in block.contents.chunks(BULK_ENDPOINT_PACKET_SIZE.into()) {
self.bulk_in.write(chunk).await.map_err(|_| ())?;
}
}
idx += blocks;
blocks = 0;
}
}
Ok(())
}
ScsiCommand::Write { lba, len } => {
for i in 0..len {
let block_idx = BlockIdx(lba as u32 + i as u32);
for chunk in block[0]
.contents
.chunks_mut(BULK_ENDPOINT_PACKET_SIZE.into())
let sdcard = self.temp_sd.as_ref().unwrap();
let block_buf = unsafe { &mut *BLOCK_BUF.get_mut() };
let mut blocks = len;
let mut idx = lba;
while blocks > 0 {
if blocks >= block_buf.len() as u64 {
for block in block_buf.as_mut() {
for chunk in block.contents.chunks_mut(BULK_ENDPOINT_PACKET_SIZE.into())
{
self.bulk_out.read(chunk).await.map_err(|_| ())?;
}
self.sdcard.write_blocks(&mut block, block_idx)?;
}
sdcard.read_blocks(block_buf, BlockIdx(idx as u32))?;
blocks -= block_buf.len() as u64;
idx += block_buf.len() as u64;
} else {
for block in block_buf[..blocks as usize].as_mut() {
for chunk in block.contents.chunks_mut(BULK_ENDPOINT_PACKET_SIZE.into())
{
self.bulk_out.read(chunk).await.map_err(|_| ())?;
}
}
sdcard.write_blocks(
&mut block_buf[..blocks as usize],
BlockIdx(idx as u32),
)?;
idx += blocks;
blocks = 0;
}
}
Ok(())
}
ScsiCommand::ReadFormatCapacities { alloc_len } => {
let block_size = SdCard::BLOCK_SIZE as u32;
let num_blocks = (self.sdcard.size() / block_size as u64) as u32;
let num_blocks = (self.temp_sd.as_ref().unwrap().size() / block_size as u64) as u32;
let mut response = [0u8; 12];
@@ -252,7 +351,12 @@ impl<'d, 's, D: Driver<'d>> MassStorageClass<'d, 's, D> {
.map_err(|_| ())
}
ScsiCommand::PreventAllowMediumRemoval { prevent: _prevent } => Ok(()),
ScsiCommand::StartStopUnit { start, load_eject } => Ok(()),
ScsiCommand::StartStopUnit { start, load_eject } => {
if !start && load_eject {
self.pending_eject = true;
}
Ok(())
}
}
}
@@ -261,7 +365,8 @@ impl<'d, 's, D: Driver<'d>> MassStorageClass<'d, 's, D> {
}
pub async fn send_csw_fail(&mut self, tag: u32) {
defmt::error!("Command Failed");
#[cfg(feature = "defmt")]
defmt::error!("Command Failed: {}", tag);
self.send_csw(tag, 0x01, 0).await; // 0x01 = Command Failed
}
@@ -276,6 +381,7 @@ impl<'d, 's, D: Driver<'d>> MassStorageClass<'d, 's, D> {
}
#[repr(C, packed)]
#[allow(non_snake_case)]
struct CommandBlockWrapper {
dCBWSignature: u32,
dCBWTag: u32,
@@ -286,6 +392,7 @@ struct CommandBlockWrapper {
CBWCB: [u8; 16],
}
#[allow(non_snake_case)]
impl CommandBlockWrapper {
fn parse(buf: &[u8]) -> Option<Self> {
if buf.len() < 31 {

View File

@@ -1,10 +1,5 @@
use num_enum::TryFromPrimitive;
#[derive(Debug, Clone, Copy)]
pub enum ScsiError {
NotReady,
}
/// THE CODE BELOW ORIGINATES FROM: https://github.com/apohrebniak/usbd-storage/blob/master/usbd-storage/src/subclass/scsi.rs
/// SCSI device subclass code

View File

@@ -3,7 +3,7 @@ use core::str::FromStr;
use embassy_rp::gpio::{Input, Output};
use embassy_rp::peripherals::SPI0;
use embassy_rp::spi::{Blocking, Spi};
use embassy_sync::blocking_mutex::raw::NoopRawMutex;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::lazy_lock::LazyLock;
use embassy_sync::mutex::Mutex;
use embassy_time::Delay;
@@ -22,10 +22,10 @@ type Device = ExclusiveDevice<Spi<'static, SPI0, Blocking>, Output<'static>, emb
type SD = SdmmcSdCard<Device, Delay>;
type VolMgr = VolumeManager<SD, DummyTimeSource, MAX_DIRS, MAX_FILES, MAX_VOLUMES>;
type Vol<'a> = Volume<'a, SD, DummyTimeSource, MAX_DIRS, MAX_FILES, MAX_VOLUMES>;
type Dir<'a> = Directory<'a, SD, DummyTimeSource, MAX_DIRS, MAX_FILES, MAX_VOLUMES>;
pub type Dir<'a> = Directory<'a, SD, DummyTimeSource, MAX_DIRS, MAX_FILES, MAX_VOLUMES>;
pub type File<'a> = SdFile<'a, SD, DummyTimeSource, MAX_DIRS, MAX_FILES, MAX_VOLUMES>;
pub static SDCARD: LazyLock<Mutex<NoopRawMutex, Option<SdCard>>> =
pub static SDCARD: LazyLock<Mutex<CriticalSectionRawMutex, Option<SdCard>>> =
LazyLock::new(|| Mutex::new(None));
pub struct DummyTimeSource {}
@@ -35,12 +35,24 @@ impl TimeSource for DummyTimeSource {
}
}
#[derive(Clone, PartialEq)]
#[derive(Clone, PartialEq, Eq)]
pub struct FileName {
pub long_name: String,
pub short_name: ShortFileName,
}
impl PartialOrd for FileName {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.long_name.cmp(&other.long_name))
}
}
impl Ord for FileName {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.long_name.cmp(&other.long_name)
}
}
pub struct SdCard {
det: Input<'static>,
volume_mgr: VolMgr,
@@ -101,7 +113,7 @@ impl SdCard {
pub fn write_blocks(&self, blocks: &mut [Block], start_block_idx: BlockIdx) -> Result<(), ()> {
let mut res: Result<(), Error> = Ok(());
self.volume_mgr.device(|sd| {
let res = sd.write(blocks, start_block_idx);
res = sd.write(blocks, start_block_idx);
DummyTimeSource {}
});
res.map_err(|_| ())
@@ -114,16 +126,15 @@ impl SdCard {
access(root_dir);
}
pub async fn read_file(
pub async fn read_file<T>(
&mut self,
name: &ShortFileName,
mut access: impl FnMut(File),
) -> Result<(), ()> {
mut access: impl FnMut(File) -> T,
) -> Result<T, ()> {
let mut res = Err(());
self.access_root_dir(|root_dir| {
if let Ok(file) = root_dir.open_file_in_dir(name, Mode::ReadOnly) {
res = Ok(());
access(file);
res = Ok(access(file));
}
});

View File

@@ -1,114 +1,90 @@
use crate::{
BINARY_CH, TASK_STATE, TaskState,
display::{SCREEN_HEIGHT, SCREEN_WIDTH, framebuffer_mut},
elf::load_binary,
format,
peripherals::keyboard,
storage::FileName,
usb::RESTART_USB,
BINARY_CH, display::FRAMEBUFFER, elf::load_binary, framebuffer::FB_PAUSED,
peripherals::keyboard, storage::FileName,
};
use alloc::{string::String, vec::Vec};
use core::{fmt::Debug, str::FromStr, sync::atomic::Ordering};
use defmt::info;
use embassy_rp::{
gpio::{Level, Output},
peripherals::{PIN_13, PIN_14, PIN_15, SPI1},
spi::{Async, Spi},
};
use embassy_sync::{
blocking_mutex::raw::{CriticalSectionRawMutex, ThreadModeRawMutex},
mutex::Mutex,
signal::Signal,
};
use embassy_time::{Delay, Timer};
use abi_sys::keyboard::{KeyCode, KeyState};
use alloc::{str::FromStr, string::String, vec::Vec};
use core::sync::atomic::Ordering;
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
use embedded_graphics::{
Drawable,
draw_target::DrawTarget,
mono_font::{
MonoTextStyle,
ascii::{FONT_6X9, FONT_6X10, FONT_9X15, FONT_10X20},
},
mono_font::{MonoTextStyle, ascii::FONT_10X20},
pixelcolor::Rgb565,
prelude::{Dimensions, Point, Primitive, RgbColor, Size},
primitives::{PrimitiveStyle, Rectangle, StyledDrawable},
primitives::{PrimitiveStyle, Rectangle},
text::Text,
};
use embedded_hal_async::spi::SpiDevice;
use embedded_hal_bus::spi::{ExclusiveDevice, NoDelay};
use embedded_layout::{
align::{horizontal, vertical},
layout::linear::LinearLayout,
object_chain::Chain,
layout::linear::{FixedMargin, LinearLayout},
prelude::*,
};
use embedded_text::TextBox;
use shared::keyboard::{KeyCode, KeyState};
pub static SELECTIONS: Mutex<CriticalSectionRawMutex, SelectionList> =
Mutex::new(SelectionList::new());
pub async fn run_selected() {
info!("Getting selections lock");
let selections = SELECTIONS.lock().await;
info!("Got selections lock");
let selection = selections.selections[selections.current_selection as usize - 1].clone();
let entry = unsafe { load_binary(&selection.short_name).await.unwrap() };
info!("loaded binary");
BINARY_CH.send(entry).await;
info!("sent bin");
}
pub async fn ui_handler() {
loop {
let state = *TASK_STATE.lock().await;
if let TaskState::Ui = state {
let mut redraw = false;
if let Some(event) = keyboard::read_keyboard_fifo().await {
if event.state == KeyState::Pressed {
if let KeyState::Pressed = event.state {
match event.key {
KeyCode::JoyUp => {
KeyCode::Up => {
let mut selections = SELECTIONS.lock().await;
selections.up();
redraw = true;
}
KeyCode::JoyDown => {
KeyCode::Down => {
let mut selections = SELECTIONS.lock().await;
selections.down();
redraw = true;
}
KeyCode::Enter | KeyCode::JoyRight => run_selected().await,
_ => {}
KeyCode::Enter | KeyCode::Right => {
let selections = SELECTIONS.lock().await;
let selection =
selections.selections[selections.current_selection as usize].clone();
let entry = unsafe {
load_binary(&selection.short_name)
.await
.expect("unable to load binary")
};
BINARY_CH.send(entry).await;
}
_ => (),
}
}
}
{
let mut selections = SELECTIONS.lock().await;
redraw |= selections.take_changed();
}
if redraw {
let changed = SELECTIONS.lock().await.changed;
if changed {
clear_selection().await;
draw_selection().await;
}
}
}
pub async fn clear_selection() {
let sel = SELECTIONS.lock().await;
if let Some(area) = sel.last_bounds {
Rectangle::new(area.top_left, area.size)
.into_styled(PrimitiveStyle::with_fill(Rgb565::BLACK))
.draw(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap();
}
}
async fn draw_selection() {
let file_names: Vec<FileName> = {
let guard = SELECTIONS.lock().await;
guard.selections.clone()
};
let mut guard = SELECTIONS.lock().await;
let file_names = guard.selections.clone();
let fb = framebuffer_mut();
let text_style = MonoTextStyle::new(&FONT_9X15, Rgb565::WHITE);
let display_area = fb.bounding_box();
let text_style = MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE);
let display_area = unsafe { FRAMEBUFFER.as_mut().unwrap().bounding_box() };
const NO_BINS: &str = "No Programs found on SD Card. Ensure programs end with '.bin', and are located in the root directory";
let no_bins = String::from_str(NO_BINS).unwrap();
FB_PAUSED.store(true, Ordering::Release); // ensure all elements show up at once
if file_names.is_empty() {
TextBox::new(
&no_bins,
@@ -118,71 +94,94 @@ async fn draw_selection() {
),
text_style,
)
.draw(fb)
.draw(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap();
} else {
let mut file_names = file_names.iter();
let Some(first) = file_names.next() else {
Text::new("No Programs found on SD Card\nEnsure programs end with '.bin',\nand are located in the root directory",
Point::zero(), text_style).draw(fb).unwrap();
let mut views: alloc::vec::Vec<Text<MonoTextStyle<Rgb565>>> = Vec::new();
return;
};
for i in &file_names {
views.push(Text::new(&i.long_name, Point::zero(), text_style));
}
let chain = Chain::new(Text::new(&first.long_name, Point::zero(), text_style));
let views_group = Views::new(views.as_mut_slice());
// for _ in 0..file_names.len() {
// let chain = chain.append(Text::new(
// file_names.next().unwrap(),
// Point::zero(),
// text_style,
// ));
// }
LinearLayout::vertical(chain)
let layout = LinearLayout::vertical(views_group)
.with_alignment(horizontal::Center)
.with_spacing(FixedMargin(5))
.arrange()
.align_to(&display_area, horizontal::Center, vertical::Center)
.draw(fb)
.align_to(&display_area, horizontal::Center, vertical::Center);
// draw selected box
let selected_bounds = layout
.inner()
.get(guard.current_selection as usize)
.expect("Selected binary missing")
.bounding_box();
Rectangle::new(selected_bounds.top_left, selected_bounds.size)
.into_styled(PrimitiveStyle::with_stroke(Rgb565::WHITE, 1))
.draw(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap();
};
guard.last_bounds = Some(layout.bounds());
layout
.draw(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap();
}
guard.changed = false;
FB_PAUSED.store(false, Ordering::Release); // ensure all elements show up at once
}
#[derive(Clone)]
pub struct SelectionList {
// allows easy clearing of selection ui,
// based on previous bounds
last_bounds: Option<Rectangle>,
current_selection: u16,
pub selections: Vec<FileName>,
has_changed: bool,
selections: Vec<FileName>,
changed: bool,
}
impl SelectionList {
pub const fn new() -> Self {
Self {
last_bounds: None,
selections: Vec::new(),
current_selection: 0,
has_changed: true,
changed: false,
}
}
pub fn set_changed(&mut self, changed: bool) {
self.changed = changed
}
pub fn update_selections(&mut self, selections: Vec<FileName>) {
self.selections = selections;
self.changed = true;
}
pub fn selections(&self) -> &Vec<FileName> {
&self.selections
}
pub fn reset(&mut self) {
self.current_selection = 1
self.current_selection = 0;
self.changed = true;
}
fn up(&mut self) {
if self.current_selection > 0 {
self.current_selection -= 1;
self.changed = true;
}
}
fn down(&mut self) {
if self.current_selection + 1 < self.selections.len() as u16 {
self.current_selection += 1
self.current_selection += 1;
self.changed = true;
}
}
fn up(&mut self) {
if self.current_selection > self.selections.len() as u16 {
self.current_selection -= 1
}
}
pub fn take_changed(&mut self) -> bool {
let changed = self.has_changed;
self.has_changed = false;
changed
}
}

View File

@@ -1,21 +1,12 @@
use core::sync::atomic::Ordering;
use crate::{
scsi::MassStorageClass,
storage::{SDCARD, SdCard},
};
use embassy_futures::{
join::join,
select::{select, select3},
};
use crate::{scsi::MassStorageClass, storage::SdCard};
use core::sync::atomic::{AtomicBool, Ordering};
use embassy_futures::select::select;
use embassy_rp::{peripherals::USB, usb::Driver};
use embassy_sync::{blocking_mutex::raw::ThreadModeRawMutex, signal::Signal};
use embassy_usb::{Builder, Config};
use portable_atomic::AtomicBool;
use embassy_usb::{Builder, Config, UsbDevice};
pub static RESTART_USB: Signal<ThreadModeRawMutex, ()> = Signal::new();
pub static ENABLE_SCSI: AtomicBool = AtomicBool::new(false);
pub static USB_ACTIVE: AtomicBool = AtomicBool::new(false);
#[embassy_executor::task]
pub async fn usb_handler(driver: Driver<'static, USB>) {
let mut config = Config::new(0xc0de, 0xbabe);
config.manufacturer = Some("LegitCamper");
@@ -37,27 +28,18 @@ pub async fn usb_handler(driver: Driver<'static, USB>) {
&mut control_buf,
);
let lock = SDCARD.get().lock().await;
let sdcard = lock.as_ref().unwrap();
let temp_sd: Option<SdCard> = None;
let mut scsi = MassStorageClass::new(&mut builder, temp_sd);
let usb = builder.build();
let mut scsi = MassStorageClass::new(&mut builder, &sdcard);
let mut usb = builder.build();
select(run(usb), scsi.poll()).await;
}
async fn run<'d>(mut usb: UsbDevice<'d, Driver<'d, USB>>) -> ! {
loop {
select3(
async {
loop {
RESTART_USB.wait().await;
return;
}
},
usb.run(),
async {
if ENABLE_SCSI.load(Ordering::Acquire) {
scsi.poll().await
}
},
)
.await;
usb.wait_resume().await;
USB_ACTIVE.store(true, Ordering::Release);
usb.run_until_suspend().await;
USB_ACTIVE.store(false, Ordering::Release);
}
}

1
picolibc Submodule

Submodule picolibc added at d664643068

10
selection_ui/Cargo.toml Normal file
View File

@@ -0,0 +1,10 @@
[package]
name = "selection_ui"
version = "0.1.0"
edition = "2024"
[dependencies]
abi = { path = "../abi" }
embedded-graphics = "0.8.1"
embedded-layout = "0.4.2"
embedded-text = "0.7.3"

148
selection_ui/src/lib.rs Normal file
View File

@@ -0,0 +1,148 @@
#![no_std]
extern crate alloc;
use abi::{
display::Display,
get_key,
keyboard::{KeyCode, KeyState},
};
use alloc::vec::Vec;
use embedded_graphics::{
Drawable,
mono_font::{MonoTextStyle, ascii::FONT_10X20},
pixelcolor::Rgb565,
prelude::{Dimensions, DrawTarget, Point, Primitive, RgbColor},
primitives::{PrimitiveStyle, Rectangle},
text::{Alignment, Text, renderer::TextRenderer},
};
use embedded_layout::{
align::{horizontal, vertical},
layout::linear::{FixedMargin, LinearLayout},
prelude::*,
};
#[derive(Debug)]
pub enum SelectionUiError<DisplayError> {
SelectionListEmpty,
DisplayError(DisplayError),
}
pub struct SelectionUi<'a> {
selection: usize,
items: &'a [&'a str],
last_bounds: Option<Rectangle>,
}
impl<'a> SelectionUi<'a> {
pub fn new(items: &'a [&'a str]) -> Self {
Self {
selection: 0,
items,
last_bounds: None,
}
}
pub fn run_selection_ui(
&mut self,
display: &mut Display,
) -> Result<Option<usize>, SelectionUiError<<Display as DrawTarget>::Error>> {
self.draw(display)?;
let selection;
loop {
let key = get_key();
if key.state == KeyState::Pressed {
if let Some(s) = self.update(display, key.key)? {
selection = Some(s);
display
.clear(Rgb565::BLACK)
.map_err(|e| SelectionUiError::DisplayError(e))?;
break;
}
}
}
Ok(selection)
}
/// updates the display with a new keypress.
/// returns selection idx if selected
pub fn update(
&mut self,
display: &mut Display,
key: KeyCode,
) -> Result<Option<usize>, SelectionUiError<<Display as DrawTarget>::Error>> {
match key {
KeyCode::Down => {
self.selection = (self.selection + 1).min(self.items.len() - 1);
}
KeyCode::Up => {
self.selection = self.selection.saturating_sub(1);
}
KeyCode::Enter | KeyCode::Right => return Ok(Some(self.selection)),
_ => return Ok(None),
};
self.draw(display)?;
Ok(None)
}
fn draw(
&mut self,
display: &mut Display,
) -> Result<(), SelectionUiError<<Display as DrawTarget>::Error>> {
let text_style = MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE);
let display_area = display.bounding_box();
if self.items.is_empty() {
return Err(SelectionUiError::SelectionListEmpty);
}
if let Some(bounds) = self.last_bounds {
Rectangle::new(bounds.top_left, bounds.size)
.into_styled(PrimitiveStyle::with_fill(Rgb565::BLACK))
.draw(display)
.map_err(|e| SelectionUiError::DisplayError(e))?;
}
let mut views: Vec<Text<MonoTextStyle<Rgb565>>> = Vec::new();
for i in self.items {
views.push(Text::new(i, Point::zero(), text_style));
}
let views_group = Views::new(views.as_mut_slice());
let layout = LinearLayout::vertical(views_group)
.with_alignment(horizontal::Center)
.with_spacing(FixedMargin(5))
.arrange()
.align_to(&display_area, horizontal::Center, vertical::Center);
layout
.draw(display)
.map_err(|e| SelectionUiError::DisplayError(e))?;
// draw selected box
if let Some(selected_bounds) = layout.inner().get(self.selection) {
let selected_bounds = selected_bounds.bounding_box();
Rectangle::new(selected_bounds.top_left, selected_bounds.size)
.into_styled(PrimitiveStyle::with_stroke(Rgb565::WHITE, 1))
.draw(display)
.map_err(|e| SelectionUiError::DisplayError(e))?;
self.last_bounds = Some(selected_bounds);
}
Ok(())
}
}
pub fn draw_text_center<'a, S>(
display: &mut Display,
text: &'a str,
style: S,
) -> Result<Point, <Display as DrawTarget>::Error>
where
S: TextRenderer<Color = <Display as DrawTarget>::Color>,
{
Text::with_alignment(text, Point::zero(), style, Alignment::Center).draw(display)
}

View File

@@ -1,11 +0,0 @@
[package]
name = "shared"
version = "0.1.0"
edition = "2024"
[features]
defmt = ["dep:defmt"]
[dependencies]
bitflags = "2.9.1"
defmt = { version = "1.0.1", optional = true }

View File

@@ -1,142 +0,0 @@
#![no_std]
pub mod keyboard {
bitflags::bitflags! {
#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)]
pub struct Modifiers: u8 {
const NONE = 0;
const CTRL = 1;
const ALT = 2;
const LSHIFT = 4;
const RSHIFT = 8;
const SYM = 16;
}
}
#[derive(Debug)]
pub struct KeyEvent {
pub key: KeyCode,
pub state: KeyState,
pub mods: Modifiers,
}
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyState {
Idle = 0,
Pressed = 1,
Hold = 2,
Released = 3,
}
impl From<u8> for KeyState {
fn from(value: u8) -> Self {
match value {
1 => KeyState::Pressed,
2 => KeyState::Hold,
3 => KeyState::Released,
0 | _ => KeyState::Idle,
}
}
}
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
#[repr(u8)]
pub enum KeyCode {
JoyUp = 0x01,
JoyDown = 0x02,
JoyLeft = 0x03,
JoyRight = 0x04,
JoyCenter = 0x05,
BtnLeft1 = 0x06,
BtnRight1 = 0x07,
BtnLeft2 = 0x11,
BtnRight2 = 0x12,
Backspace = 0x08,
Tab = 0x09,
Enter = 0x0A,
ModAlt = 0xA1,
ModShiftLeft = 0xA2,
ModShiftRight = 0xA3,
ModSym = 0xA4,
ModCtrl = 0xA5,
Esc = 0xB1,
Left = 0xB4,
Up = 0xB5,
Down = 0xB6,
Right = 0xB7,
Break = 0xD0,
Insert = 0xD1,
Home = 0xD2,
Del = 0xD4,
End = 0xD5,
PageUp = 0xD6,
PageDown = 0xD7,
CapsLock = 0xC1,
F1 = 0x81,
F2 = 0x82,
F3 = 0x83,
F4 = 0x84,
F5 = 0x85,
F6 = 0x86,
F7 = 0x87,
F8 = 0x88,
F9 = 0x89,
F10 = 0x90,
Char(char),
Unknown(u8),
}
impl From<u8> for KeyCode {
fn from(value: u8) -> Self {
match value {
0x01 => Self::JoyUp,
0x02 => Self::JoyDown,
0x03 => Self::JoyLeft,
0x04 => Self::JoyRight,
0x05 => Self::JoyCenter,
0x06 => Self::BtnLeft1,
0x07 => Self::BtnRight1,
0x08 => Self::Backspace,
0x09 => Self::Tab,
0x0A => Self::Enter,
0x11 => Self::BtnLeft2,
0x12 => Self::BtnRight2,
0xA1 => Self::ModAlt,
0xA2 => Self::ModShiftLeft,
0xA3 => Self::ModShiftRight,
0xA4 => Self::ModSym,
0xA5 => Self::ModCtrl,
0xB1 => Self::Esc,
0xB4 => Self::Left,
0xB5 => Self::Up,
0xB6 => Self::Down,
0xB7 => Self::Right,
0xC1 => Self::CapsLock,
0xD0 => Self::Break,
0xD1 => Self::Insert,
0xD2 => Self::Home,
0xD4 => Self::Del,
0xD5 => Self::End,
0xD6 => Self::PageUp,
0xD7 => Self::PageDown,
0x81 => Self::F1,
0x82 => Self::F2,
0x83 => Self::F3,
0x84 => Self::F4,
0x85 => Self::F5,
0x86 => Self::F6,
0x87 => Self::F7,
0x88 => Self::F8,
0x89 => Self::F9,
0x90 => Self::F10,
_ => match char::from_u32(value as u32) {
Some(c) => Self::Char(c),
None => Self::Unknown(value),
},
}
}
}
}

View File

@@ -6,3 +6,4 @@ edition = "2024"
[dependencies]
abi = { path = "../../abi" }
embedded-graphics = "0.8.1"
embedded-layout = "0.4.2"

View File

@@ -2,57 +2,199 @@
#![no_main]
extern crate alloc;
use abi::{KeyCode, display::Display, embassy_time, get_key, print};
use alloc::{boxed::Box, string::String, vec};
use core::{panic::PanicInfo, pin::Pin};
use abi::{
display::Display,
get_key,
keyboard::{KeyCode, KeyState},
println,
};
use alloc::{format, string::String, vec, vec::Vec};
use core::panic::PanicInfo;
use embedded_graphics::{
Drawable,
geometry::{Dimensions, Point},
mono_font::{MonoTextStyle, ascii::FONT_6X10},
mono_font::{MonoTextStyle, ascii::FONT_7X14, iso_8859_1::FONT_10X20},
pixelcolor::Rgb565,
prelude::RgbColor,
text::{Alignment, Text},
prelude::{Primitive, RgbColor},
primitives::{PrimitiveStyle, Rectangle},
text::Text,
};
use embedded_layout::{
View,
align::{Align, horizontal, vertical},
layout::linear::LinearLayout,
prelude::Chain,
};
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
fn panic(info: &PanicInfo) -> ! {
println!("user panic: {} @ {:?}", info.message(), info.location(),);
loop {}
}
pub async fn main() {
print("Starting Async Calculator app");
let mut display = Display;
#[unsafe(no_mangle)]
pub extern "Rust" fn _start() {
main()
}
let character_style = MonoTextStyle::new(&FONT_6X10, Rgb565::RED);
pub fn main() {
println!("Starting Calculator app");
let mut display = Display::take().unwrap();
let mut text = vec!['H', 'E', 'L', 'L', 'O'];
let mut input = vec!['e', 'x', 'p', 'r', ':', ' '];
let input_min = input.len();
let mut dirty = true;
let mut last_area: Option<(Rectangle, Rectangle)> = None;
// loop {
Text::with_alignment(
&text.iter().cloned().collect::<String>(),
display.bounding_box().center() + Point::new(0, 15),
character_style,
Alignment::Center,
)
LinearLayout::vertical(Chain::new(Text::new(
"Calculator!",
Point::zero(),
MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE),
)))
.arrange()
.align_to(&display.bounding_box(), horizontal::Center, vertical::Top)
.draw(&mut display)
.expect("Failed to draw title");
loop {
if dirty {
let style = PrimitiveStyle::with_fill(Rgb565::BLACK);
if let Some(area) = last_area {
Rectangle::new(area.0.top_left, area.0.size)
.into_styled(style)
.draw(&mut display)
.unwrap();
if let Some(event) = get_key() {
print("User got event");
match event.key {
KeyCode::Char(ch) => {
text.push(ch);
}
KeyCode::Backspace => {
text.pop();
}
_ => (),
}
}
// }
Rectangle::new(area.1.top_left, area.1.size)
.into_styled(style)
.draw(&mut display)
.unwrap();
}
#[unsafe(no_mangle)]
pub extern "Rust" fn _start() -> Pin<Box<dyn Future<Output = ()>>> {
Box::pin(async { main().await })
let text = input.iter().cloned().collect::<String>();
let style = MonoTextStyle::new(&FONT_7X14, Rgb565::WHITE);
let expr_layout = LinearLayout::vertical(Chain::new(Text::new(
&text,
display.bounding_box().center(),
style,
)))
.arrange()
.align_to(&display.bounding_box(), horizontal::Left, vertical::Center);
let result = if let Ok(result) = evaluate(&input[input_min..]) {
&format!(" = {}", result)
} else {
" = Error"
};
let eq_layout = LinearLayout::vertical(Chain::new(Text::new(
result,
display.bounding_box().center(),
style,
)))
.arrange()
.align_to(&display.bounding_box(), horizontal::Right, vertical::Center);
last_area = Some((expr_layout.bounds(), eq_layout.bounds()));
expr_layout.draw(&mut display).unwrap();
eq_layout.draw(&mut display).unwrap();
dirty = false;
}
let event = get_key();
if event.state == KeyState::Released {
match event.key {
KeyCode::Char(ch) => {
input.push(ch);
}
KeyCode::Del => {
input.truncate(input_min);
}
KeyCode::Backspace => {
if input.len() > input_min {
input.pop();
}
}
KeyCode::Esc => return,
_ => (),
}
dirty = true;
}
}
}
fn get_int(int: &[char]) -> Result<i32, ()> {
let mut output: i32 = 0;
for &c in int {
let digit = c.to_digit(10).ok_or(())? as i32;
output = output
.checked_mul(10)
.and_then(|v| v.checked_add(digit))
.ok_or(())?;
}
Ok(output)
}
fn primary(input: &[char], pos: &mut usize) -> Result<i32, ()> {
let mut digits = Vec::new();
while *pos < input.len() && input[*pos].is_ascii_digit() {
digits.push(input[*pos]);
*pos += 1;
}
if digits.is_empty() {
return Err(());
}
get_int(&digits)
}
fn mul_div(input: &[char], pos: &mut usize) -> Result<i32, ()> {
let mut value = primary(input, pos)?;
while *pos < input.len() {
let op = input[*pos];
if op != '*' && op != '/' {
break;
}
*pos += 1;
let rhs = primary(input, pos)?;
value = match op {
'*' => value.checked_mul(rhs).ok_or(())?,
'/' => {
if rhs == 0 {
return Err(());
}
value.checked_div(rhs).ok_or(())?
}
_ => unreachable!(),
};
}
Ok(value)
}
fn add_sub(input: &[char], pos: &mut usize) -> Result<i32, ()> {
let mut value = mul_div(input, pos)?;
while *pos < input.len() {
let op = input[*pos];
if op != '+' && op != '-' {
break;
}
*pos += 1;
let rhs = mul_div(input, pos)?;
value = match op {
'+' => value.checked_add(rhs).ok_or(())?,
'-' => value.checked_sub(rhs).ok_or(())?,
_ => unreachable!(),
};
}
Ok(value)
}
fn evaluate(input: &[char]) -> Result<i32, ()> {
let mut pos = 0;
let result = add_sub(input, &mut pos)?;
if pos != input.len() {
return Err(());
}
Ok(result)
}

View File

@@ -0,0 +1,9 @@
[package]
name = "gallery"
version = "0.1.0"
edition = "2024"
[dependencies]
abi = { path = "../../abi" }
embedded-graphics = "0.8.1"
tinybmp = "0.6.0"

View File

@@ -0,0 +1,28 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() {
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("../memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=-Tmemory.x");
}

View File

@@ -0,0 +1,95 @@
#![no_std]
#![no_main]
#![allow(static_mut_refs)]
extern crate alloc;
use abi::{
display::{Display, SCREEN_HEIGHT, SCREEN_WIDTH},
fs::{Entries, list_dir, read_file},
get_key,
keyboard::{KeyCode, KeyState},
println,
};
use alloc::{format, vec};
use core::panic::PanicInfo;
use embedded_graphics::{
Drawable, image::Image, mono_font::MonoTextStyle, mono_font::ascii::FONT_6X10,
pixelcolor::Rgb565, prelude::*, text::Text,
};
use tinybmp::Bmp;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
println!("user panic: {} @ {:?}", info.message(), info.location());
loop {}
}
#[unsafe(no_mangle)]
pub extern "Rust" fn _start() {
main()
}
pub fn main() {
println!("Starting Gallery app");
let mut bmp_buf = vec![0_u8; 100_000];
let mut display = Display::take().unwrap();
let grid_cols = 3;
let grid_rows = 3;
let cell_width = SCREEN_WIDTH as i32 / grid_cols;
let cell_height = SCREEN_HEIGHT as i32 / grid_rows;
let mut images_drawn = 0;
let mut entries = Entries::new();
let files_num = list_dir("/images", &mut entries);
for file in &entries.entries()[2..files_num] {
if images_drawn >= grid_cols * grid_rows {
break; // only draw 3x3
}
println!("file: {}", file);
if file.extension().unwrap_or("") == "bmp" || file.extension().unwrap_or("") == "BMP" {
let file_path = format!("/images/{}", file);
let read = read_file(&file_path, 0, &mut &mut bmp_buf[..]);
if read > 0 {
let bmp = Bmp::from_slice(&bmp_buf).expect("failed to parse bmp");
let row = images_drawn / grid_cols;
let col = images_drawn % grid_cols;
let cell_x = col * cell_width;
let cell_y = row * cell_height;
// Center image inside cell
let bmp_w = bmp.size().width as i32;
let bmp_h = bmp.size().height as i32;
let x = cell_x + (cell_width - bmp_w) / 2;
let y = cell_y + 5; // 5px top margin
Image::new(&bmp, Point::new(x, y))
.draw(&mut display)
.unwrap();
let text_style = MonoTextStyle::new(&FONT_6X10, Rgb565::WHITE);
let text_y = y + bmp_h + 2; // 2px gap under image
Text::new(&file.base(), Point::new(cell_x + 2, text_y), text_style)
.draw(&mut display)
.unwrap();
images_drawn += 1;
}
}
}
loop {
let event = get_key();
if event.state != KeyState::Idle {
match event.key {
KeyCode::Esc => return,
_ => (),
}
};
}
}

10
user-apps/gif/Cargo.toml Normal file
View File

@@ -0,0 +1,10 @@
[package]
name = "gif"
version = "0.1.0"
edition = "2024"
[dependencies]
abi = { path = "../../abi" }
selection_ui = { path = "../../selection_ui" }
embedded-graphics = "0.8.1"
tinygif = { git = "https://github.com/LegitCamper/tinygif" }

28
user-apps/gif/build.rs Normal file
View File

@@ -0,0 +1,28 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() {
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("../memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=-Tmemory.x");
}

103
user-apps/gif/src/main.rs Normal file
View File

@@ -0,0 +1,103 @@
#![no_std]
#![no_main]
extern crate alloc;
use abi::{
display::{Display, SCREEN_HEIGHT, SCREEN_WIDTH},
fs::{Entries, file_len, list_dir, read_file},
get_key, get_ms,
keyboard::{KeyCode, KeyState},
println, sleep,
};
use alloc::{format, vec, vec::Vec};
use core::panic::PanicInfo;
use embedded_graphics::{
image::ImageDrawable,
mono_font::{MonoTextStyle, ascii::FONT_6X10},
pixelcolor::Rgb565,
prelude::{Point, RgbColor},
transform::Transform,
};
use selection_ui::{SelectionUi, SelectionUiError, draw_text_center};
use tinygif::Gif;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
println!("user panic: {} @ {:?}", info.message(), info.location(),);
loop {}
}
#[unsafe(no_mangle)]
pub extern "Rust" fn _start() {
main()
}
pub fn main() {
println!("Starting Gif app");
let mut display = Display::take().unwrap();
let mut entries = Entries::new();
list_dir("/gifs", &mut entries);
let mut files = entries.entries();
files.retain(|e| e.extension().unwrap_or("") == "gif");
let mut gifs = files.iter().map(|e| e.full_name()).collect::<Vec<&str>>();
gifs.sort();
let mut selection_ui = SelectionUi::new(&mut gifs);
let selection = match selection_ui.run_selection_ui(&mut display) {
Ok(maybe_sel) => maybe_sel,
Err(e) => match e {
SelectionUiError::SelectionListEmpty => {
draw_text_center(
&mut display,
"No Gifs were found in /gifs",
MonoTextStyle::new(&FONT_6X10, Rgb565::RED),
)
.expect("Display Error");
None
}
SelectionUiError::DisplayError(_) => panic!("Display Error"),
},
};
assert!(selection.is_some());
let file_name = format!("/gifs/{}", gifs[selection.unwrap()]);
let size = file_len(&file_name);
let mut buf = vec![0_u8; size];
let read = read_file(&file_name, 0, &mut buf);
println!("read: {}, file size: {}", read, size);
assert!(read == size);
let gif = Gif::<Rgb565>::from_slice(&buf).expect("Failed to parse gif");
let translation = Point::new(
(SCREEN_WIDTH as i32 - gif.width() as i32) / 2,
(SCREEN_HEIGHT as i32 - gif.height() as i32) / 2,
);
let mut frame_num = 0;
loop {
for mut frame in gif.frames() {
let start = get_ms();
frame.translate_mut(translation).draw(&mut display).unwrap();
frame_num += 1;
if frame_num % 5 == 0 {
let event = get_key();
if event.state != KeyState::Idle {
match event.key {
KeyCode::Esc => {
drop(buf);
return;
}
_ => (),
};
};
}
sleep(((frame.delay_centis as u64) * 10).saturating_sub(start));
}
}
}

View File

@@ -1,19 +1,10 @@
MEMORY
{
/* Must match the USERAPP region in the kernel linker script */
RAM : ORIGIN = 0x20010000, LENGTH = 192K
RAM : ORIGIN = 0x0, LENGTH = 250K
}
SECTIONS
{
/* Reserve first 1KB for patchable symbols */
.user_reloc (NOLOAD) : ALIGN(4)
{
__user_reloc_start = .;
KEEP(*(.user_reloc*));
__user_reloc_end = .;
} > RAM
.text : ALIGN(4)
{
*(.text .text.*);
@@ -30,4 +21,11 @@ SECTIONS
*(.bss .bss.*);
*(COMMON);
} > RAM
.syscall_table (NOLOAD) : ALIGN(4)
{
__user_reloc_start = .;
KEEP(*(.user_reloc*));
__user_reloc_end = .;
} > RAM
}

View File

@@ -0,0 +1,10 @@
[package]
name = "snake"
version = "0.1.0"
edition = "2024"
[dependencies]
abi = { path = "../../abi" }
embedded-graphics = "0.8.1"
embedded-snake = { git = "https://github.com/LegitCamper/embedded-snake-rs" }
rand = { version = "0.9.0", default-features = false }

28
user-apps/snake/build.rs Normal file
View File

@@ -0,0 +1,28 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() {
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("../memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=-Tmemory.x");
}

View File

@@ -0,0 +1,65 @@
#![no_std]
#![no_main]
extern crate alloc;
use abi::{
Rng,
display::{Display, SCREEN_HEIGHT, SCREEN_WIDTH},
get_key,
keyboard::{KeyCode, KeyState},
println, sleep,
};
use core::panic::PanicInfo;
use embedded_graphics::{pixelcolor::Rgb565, prelude::RgbColor};
use embedded_snake::{Direction, SnakeGame};
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
println!("user panic: {} @ {:?}", info.message(), info.location(),);
loop {}
}
#[unsafe(no_mangle)]
pub extern "Rust" fn _start() {
main()
}
const CELL_SIZE: usize = 8;
pub fn main() {
println!("Starting Snake app");
let mut display = Display::take().unwrap();
let mut game = SnakeGame::<100, Rgb565, Rng>::new(
SCREEN_WIDTH as u16,
SCREEN_HEIGHT as u16,
CELL_SIZE as u16,
CELL_SIZE as u16,
Rng,
Rgb565::BLACK,
Rgb565::GREEN,
Rgb565::RED,
50,
);
loop {
let event = get_key();
if event.state != KeyState::Idle {
let direction = match event.key {
KeyCode::Up => Direction::Up,
KeyCode::Down => Direction::Down,
KeyCode::Right => Direction::Right,
KeyCode::Left => Direction::Left,
KeyCode::Esc => return,
_ => Direction::None,
};
game.set_direction(direction);
};
// ensure all draws show up at once
game.pre_draw(&mut display);
game.draw(&mut display);
sleep(15);
}
}

View File

@@ -0,0 +1,11 @@
[package]
name = "wav_player"
version = "0.1.0"
edition = "2024"
[dependencies]
abi = { path = "../../abi" }
selection_ui = { path = "../../selection_ui" }
embedded-graphics = "0.8.1"
rand = { version = "0.9.0", default-features = false }
embedded-audio = { git = "https://github.com/LegitCamper/embedded-audio" }

View File

@@ -0,0 +1,28 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() {
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("../memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=-Tmemory.x");
}

View File

@@ -0,0 +1,139 @@
#![no_std]
#![no_main]
extern crate alloc;
use abi::{
audio::{AUDIO_BUFFER_LEN, audio_buffer_ready, send_audio_buffer},
display::Display,
format,
fs::{Entries, file_len, list_dir, read_file},
get_key,
keyboard::{KeyCode, KeyState},
println,
};
use alloc::{string::String, vec::Vec};
use core::panic::PanicInfo;
use embedded_audio::{AudioFile, PlatformFile, PlatformFileError, wav::Wav};
use embedded_graphics::{
mono_font::{MonoTextStyle, ascii::FONT_6X10},
pixelcolor::Rgb565,
prelude::RgbColor,
};
use selection_ui::{SelectionUi, SelectionUiError, draw_text_center};
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
println!("user panic: {} @ {:?}", info.message(), info.location(),);
loop {}
}
#[unsafe(no_mangle)]
pub extern "Rust" fn _start() {
main()
}
pub fn main() {
println!("Starting Wav player app");
let mut display = Display::take().unwrap();
loop {
let mut entries = Entries::new();
list_dir("/music", &mut entries);
let mut files = entries.entries();
files.retain(|e| e.extension().unwrap_or("") == "wav");
let mut wavs = files.iter().map(|e| e.full_name()).collect::<Vec<&str>>();
wavs.sort();
let mut selection_ui = SelectionUi::new(&mut wavs);
let selection = match selection_ui.run_selection_ui(&mut display) {
Ok(maybe_sel) => maybe_sel,
Err(e) => match e {
SelectionUiError::SelectionListEmpty => {
draw_text_center(
&mut display,
"No Wavs were found in /gifs",
MonoTextStyle::new(&FONT_6X10, Rgb565::RED),
)
.expect("Display Error");
None
}
SelectionUiError::DisplayError(_) => panic!("Display Error"),
},
};
assert!(selection.is_some());
let file_name = format!("/music/{}", wavs[selection.unwrap()]);
let file = File::new(String::from(file_name));
let mut wav = Wav::new(file).unwrap();
println!("sample rate: {}", wav.sample_rate());
println!("channels: {:?}", wav.channels() as u8);
let mut buf = [0_u8; AUDIO_BUFFER_LEN];
loop {
if audio_buffer_ready() {
if wav.is_eof() {
break;
}
let _read = wav.read(&mut buf).unwrap();
send_audio_buffer(&buf);
}
let event = get_key();
if event.state == KeyState::Released {
match event.key {
KeyCode::Esc => return,
_ => (),
}
}
}
}
}
struct File {
current_pos: usize,
file: String,
}
impl File {
fn new(file: String) -> Self {
Self {
current_pos: 0,
file,
}
}
}
impl PlatformFile for File {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, PlatformFileError> {
let read = read_file(&self.file, self.current_pos, buf);
self.current_pos += read;
Ok(read)
}
fn seek_from_current(&mut self, offset: i64) -> Result<(), PlatformFileError> {
if offset.is_positive() {
self.current_pos += offset as usize;
} else {
self.current_pos -= offset as usize;
}
Ok(())
}
fn seek_from_start(&mut self, offset: usize) -> Result<(), PlatformFileError> {
self.current_pos = offset;
Ok(())
}
fn seek_from_end(&mut self, offset: usize) -> Result<(), PlatformFileError> {
self.current_pos = self.length() - offset;
Ok(())
}
fn length(&mut self) -> usize {
file_len(&self.file)
}
}