2022-03-30 20:37:54 +00:00
#![ cfg_attr(target_os = " none " , no_std) ]
#![ cfg_attr(target_os = " none " , no_main) ]
mod api ;
2022-04-26 16:53:58 +00:00
use api ::* ;
2022-05-02 14:59:33 +00:00
#[ cfg(any(target_os = " none " , target_os = " xous " )) ]
2022-04-26 16:53:58 +00:00
mod kbd ;
2022-05-02 14:59:33 +00:00
#[ cfg(any(target_os = " none " , target_os = " xous " )) ]
2022-04-26 18:41:07 +00:00
mod hw ;
#[ cfg(any(target_os = " none " , target_os = " xous " )) ]
use hw ::* ;
2022-03-30 20:37:54 +00:00
#[ cfg(not(any(target_os = " none " , target_os = " xous " ))) ]
2022-04-26 18:41:07 +00:00
mod hosted ;
#[ cfg(not(any(target_os = " none " , target_os = " xous " ))) ]
use hosted ::* ;
2022-03-30 20:37:54 +00:00
2022-05-02 14:59:33 +00:00
use num_traits ::* ;
use xous ::{ CID , msg_scalar_unpack , Message , send_message } ;
use std ::collections ::BTreeMap ;
2022-05-07 05:21:23 +00:00
use usb_device ::prelude ::* ;
use usb_device ::class_prelude ::* ;
use usbd_human_interface_device ::page ::Keyboard ;
use usbd_human_interface_device ::device ::keyboard ::{ KeyboardLedsReport , NKROBootKeyboardInterface } ;
use usbd_human_interface_device ::prelude ::* ;
use embedded_time ::Clock ;
use std ::convert ::TryInto ;
pub struct EmbeddedClock {
start : std ::time ::Instant ,
}
impl EmbeddedClock {
pub fn new ( ) -> EmbeddedClock {
EmbeddedClock { start : std ::time ::Instant ::now ( ) }
}
}
impl Clock for EmbeddedClock {
type T = u64 ;
const SCALING_FACTOR : embedded_time ::fraction ::Fraction = < embedded_time ::fraction ::Fraction > ::new ( 1 , 1_000 ) ;
fn try_now ( & self ) -> Result < embedded_time ::Instant < Self > , embedded_time ::clock ::Error > {
Ok ( embedded_time ::Instant ::new ( self . start . elapsed ( ) . as_millis ( ) . try_into ( ) . unwrap ( ) ) )
}
}
2022-03-30 20:37:54 +00:00
#[ xous::xous_main ]
fn xmain ( ) -> ! {
2022-05-02 14:59:33 +00:00
use crate ::SpinalUsbDevice ;
2022-03-30 20:37:54 +00:00
2022-05-05 12:51:48 +00:00
let _gpio_base = crate ::log_init ( ) ;
2022-03-30 20:37:54 +00:00
log_server ::init_wait ( ) . unwrap ( ) ;
log ::set_max_level ( log ::LevelFilter ::Info ) ;
log ::info! ( " my PID is {} " , xous ::process ::id ( ) ) ;
let xns = xous_names ::XousNames ::new ( ) . unwrap ( ) ;
2022-05-05 12:51:48 +00:00
let usbdev_sid = xns . register_name ( api ::SERVER_NAME_USBTEST , None ) . expect ( " can't register server " ) ;
log ::trace! ( " registered with NS -- {:?} " , usbdev_sid ) ;
2022-03-30 20:37:54 +00:00
2022-05-07 05:21:23 +00:00
let usbdev = SpinalUsbDevice ::new ( usbdev_sid ) ;
let mut usbmgmt = usbdev . get_iface ( ) ;
2022-05-09 02:04:59 +00:00
let mut kbd = kbd ::Keyboard ::new ( usbdev_sid ) ;
2022-05-07 05:21:23 +00:00
let tt = ticktimer_server ::Ticktimer ::new ( ) . unwrap ( ) ;
log ::info! ( " connecting device core " ) ;
usbmgmt . connect_device_core ( true ) ;
tt . sleep_ms ( 500 ) . unwrap ( ) ;
log ::info! ( " devcore connected " ) ;
2022-03-30 20:37:54 +00:00
log ::trace! ( " ready to accept requests " ) ;
std ::thread ::spawn ( {
move | | {
let tt = ticktimer_server ::Ticktimer ::new ( ) . unwrap ( ) ;
loop {
2022-05-10 05:24:08 +00:00
// keeps the WDT from firing
2022-03-30 20:37:54 +00:00
tt . sleep_ms ( 2500 ) . unwrap ( ) ;
}
}
} ) ;
// register a suspend/resume listener
2022-05-05 12:51:48 +00:00
let cid = xous ::connect ( usbdev_sid ) . expect ( " couldn't create suspend callback connection " ) ;
2022-04-26 16:53:58 +00:00
let mut susres = susres ::Susres ::new (
None ,
& xns ,
api ::Opcode ::SuspendResume as u32 ,
cid
) . expect ( " couldn't create suspend/resume object " ) ;
2022-05-09 02:04:59 +00:00
log ::info! ( " alloc " ) ;
2022-05-07 05:21:23 +00:00
let usb_alloc = UsbBusAllocator ::new ( usbdev ) ;
2022-05-09 02:04:59 +00:00
log ::info! ( " clock " ) ;
2022-05-07 05:21:23 +00:00
let clock = EmbeddedClock ::new ( ) ;
2022-05-09 02:04:59 +00:00
log ::info! ( " hid " ) ;
2022-05-07 05:21:23 +00:00
let mut keyboard = UsbHidClassBuilder ::new ( )
. add_interface (
NKROBootKeyboardInterface ::default_config ( & clock ) ,
)
. build ( & usb_alloc ) ;
2022-05-09 02:04:59 +00:00
log ::info! ( " dev " ) ;
2022-05-07 05:21:23 +00:00
let mut usb_dev = UsbDeviceBuilder ::new ( & usb_alloc , UsbVidPid ( 0x1209 , 0x0001 ) )
. manufacturer ( " usbd-human-interface-device " )
. product ( " NKRO Keyboard " )
. serial_number ( " PRECURSOR " )
. build ( ) ;
2022-05-09 02:04:59 +00:00
log ::info! ( " main " ) ;
2022-04-26 16:53:58 +00:00
let mut cmdline = String ::new ( ) ;
2022-03-30 20:37:54 +00:00
loop {
2022-05-05 12:51:48 +00:00
let msg = xous ::receive_message ( usbdev_sid ) . unwrap ( ) ;
2022-03-30 20:37:54 +00:00
match FromPrimitive ::from_usize ( msg . body . id ( ) ) {
Some ( Opcode ::SuspendResume ) = > xous ::msg_scalar_unpack! ( msg , token , _ , _ , _ , {
2022-04-26 16:53:58 +00:00
kbd . suspend ( ) ;
2022-05-07 05:21:23 +00:00
usbmgmt . xous_suspend ( ) ;
2022-03-30 20:37:54 +00:00
susres . suspend_until_resume ( token ) . expect ( " couldn't execute suspend/resume " ) ;
2022-04-26 16:53:58 +00:00
kbd . resume ( ) ;
2022-05-07 05:21:23 +00:00
usbmgmt . xous_resume ( ) ;
2022-03-30 20:37:54 +00:00
} ) ,
2022-05-02 17:13:24 +00:00
Some ( Opcode ::UsbIrqHandler ) = > {
log ::info! ( " got USB interrupt " ) ;
2022-05-13 15:44:15 +00:00
// usbmgmt.print_regs();
2022-05-07 05:21:23 +00:00
if usb_dev . poll ( & mut [ & mut keyboard ] ) {
match keyboard . interface ( ) . read_report ( ) {
Ok ( l ) = > {
log ::info! ( " got led state {:?} " , l ) ;
}
_ = > { }
}
}
2022-05-02 17:13:24 +00:00
}
2022-04-26 16:53:58 +00:00
Some ( Opcode ::DoCmd ) = > {
log ::info! ( " got command line: {} " , cmdline ) ;
if let Some ( ( cmd , args ) ) = cmdline . split_once ( ' ' ) {
// command and args
match cmd {
" test " = > {
log ::info! ( " got test command with arg {} " , args ) ;
}
2022-04-26 17:22:53 +00:00
" conn " = > {
match args {
2022-05-05 12:51:48 +00:00
" 1 " = > {
2022-05-07 05:21:23 +00:00
usbmgmt . connect_device_core ( true ) ;
2022-05-05 12:51:48 +00:00
log ::info! ( " device core connected " ) ;
} ,
" 0 " = > {
2022-05-07 05:21:23 +00:00
usbmgmt . connect_device_core ( false ) ;
2022-05-05 12:51:48 +00:00
log ::info! ( " debug core connected " ) ;
} ,
2022-04-26 18:41:07 +00:00
_ = > log ::info! ( " usage: conn [1,0]; got: 'conn {}' " , args ) ,
2022-04-26 17:22:53 +00:00
}
2022-05-07 05:21:23 +00:00
usbmgmt . print_regs ( ) ;
2022-04-26 17:22:53 +00:00
}
2022-04-26 16:53:58 +00:00
_ = > {
2022-05-05 12:51:48 +00:00
log ::info! ( " unrecognized command {} " , cmd ) ;
2022-04-26 16:53:58 +00:00
}
}
} else {
// just the command
match cmdline . as_str ( ) {
" help " = > {
log ::info! ( " wouldn't that be nice... " ) ;
}
2022-04-26 17:22:53 +00:00
" conn " = > {
2022-05-07 05:21:23 +00:00
usbmgmt . connect_device_core ( true ) ;
2022-04-26 18:41:07 +00:00
log ::info! ( " device core connected " ) ;
2022-05-07 05:21:23 +00:00
usbmgmt . print_regs ( ) ;
2022-04-26 18:41:07 +00:00
}
" regs " = > {
2022-05-07 05:21:23 +00:00
usbmgmt . print_regs ( ) ;
2022-04-26 17:22:53 +00:00
}
2022-04-26 16:53:58 +00:00
_ = > {
log ::info! ( " unrecognized command " ) ;
}
}
}
cmdline . clear ( ) ;
}
// this is via UART
Some ( Opcode ::KeyboardChar ) = > msg_scalar_unpack! ( msg , k , _ , _ , _ , {
let key = {
let bs_del_fix = if k = = 0x7f {
0x08
} else {
k
} ;
core ::char ::from_u32 ( bs_del_fix as u32 ) . unwrap_or ( '\u{0000}' )
} ;
if key ! = '\u{0000}' {
if key ! = '\u{000d}' {
cmdline . push ( key ) ;
} else {
send_message ( cid , Message ::new_scalar (
Opcode ::DoCmd . to_usize ( ) . unwrap ( ) , 0 , 0 , 0 , 0
) ) . unwrap ( ) ;
}
}
} ) ,
// this is via physical keyboard
Some ( Opcode ::HandlerTrigger ) = > {
2022-05-07 05:21:23 +00:00
keyboard . interface ( ) . write_report ( & [ Keyboard ::A ] ) . ok ( ) ; // just for testing
keyboard . interface ( ) . tick ( ) . unwrap ( ) ;
2022-04-26 16:53:58 +00:00
let rawstates = kbd . update ( ) ;
// interpret scancodes
let kc : Vec < char > = kbd . track_keys ( & rawstates ) ;
// handle keys, if any
for & key in kc . iter ( ) {
if key ! = '\u{000d}' {
cmdline . push ( key ) ;
} else {
send_message ( cid , Message ::new_scalar (
Opcode ::DoCmd . to_usize ( ) . unwrap ( ) , 0 , 0 , 0 , 0
) ) . unwrap ( ) ;
}
}
} ,
2022-03-30 20:37:54 +00:00
Some ( Opcode ::Quit ) = > {
log ::warn! ( " Quit received, goodbye world! " ) ;
break ;
} ,
None = > {
log ::error! ( " couldn't convert opcode: {:?} " , msg ) ;
}
}
}
// clean up our program
log ::trace! ( " main loop exit, destroying servers " ) ;
2022-05-05 12:51:48 +00:00
xns . unregister_server ( usbdev_sid ) . unwrap ( ) ;
xous ::destroy_server ( usbdev_sid ) . unwrap ( ) ;
2022-03-30 20:37:54 +00:00
log ::trace! ( " quitting " ) ;
xous ::terminate_process ( 0 )
}
2022-05-02 14:59:33 +00:00
2022-05-02 15:15:52 +00:00
pub ( crate ) const START_OFFSET : u32 = 0x0048 + 8 ; // align spinal free space to 16-byte boundary
2022-05-10 05:24:08 +00:00
pub ( crate ) const END_OFFSET : u32 = 0x1000 ; // derived from RAMSIZE parameter: this could be a dynamically read out constant, but, in practice, it's part of the hardware
2022-05-02 15:15:52 +00:00
/// USB endpoint allocator. The SpinalHDL USB controller appears as a block of
/// unstructured memory to the host. You can specify pointers into the memory with
/// an offset and length to define where various USB descriptors should be placed.
/// This allocator manages that space.
///
/// Note that all allocations must be aligned to 16-byte boundaries. This is a restriction
/// of the USB core.
2022-05-02 17:13:24 +00:00
///
/// Returns a full memory address as the pointer. Must be shifted left by 4 to get the
/// aligned representation used by the SpinalHDL block.
2022-05-02 14:59:33 +00:00
pub ( crate ) fn alloc_inner ( allocs : & mut BTreeMap < u32 , u32 > , requested : u32 ) -> Option < u32 > {
if requested = = 0 {
return None ;
}
let mut alloc_offset = START_OFFSET ;
for ( & offset , & length ) in allocs . iter ( ) {
2022-05-02 15:15:52 +00:00
// round length up to the nearest 16-byte increment
let length = if length & 0xF = = 0 { length } else { ( length + 16 ) & ! 0xF } ;
2022-05-02 14:59:33 +00:00
// println!("aoff: {}, cur: {}+{}", alloc_offset, offset, length);
assert! ( offset > = alloc_offset , " allocated regions overlap " ) ;
if offset > alloc_offset {
if offset - alloc_offset > = requested {
// there's a hole in the list, insert the element here
break ;
}
}
alloc_offset = offset + length ;
}
if alloc_offset + requested < = END_OFFSET {
allocs . insert ( alloc_offset , requested ) ;
Some ( alloc_offset )
} else {
None
}
}
2022-05-09 02:04:59 +00:00
#[ allow(dead_code) ]
2022-05-02 14:59:33 +00:00
pub ( crate ) fn dealloc_inner ( allocs : & mut BTreeMap < u32 , u32 > , offset : u32 ) -> bool {
allocs . remove ( & offset ) . is_some ( )
}
// run with `cargo test -- --nocapture --test-threads=1`:
#[ cfg(test) ]
mod tests {
use super ::* ;
#[ test ]
fn test_alloc ( ) {
use rand_chacha ::ChaCha8Rng ;
use rand_chacha ::rand_core ::SeedableRng ;
use rand_chacha ::rand_core ::RngCore ;
let mut rng = ChaCha8Rng ::seed_from_u64 ( 0 ) ;
let mut allocs = BTreeMap ::< u32 , u32 > ::new ( ) ;
assert_eq! ( alloc_inner ( & mut allocs , 128 ) , Some ( START_OFFSET ) ) ;
assert_eq! ( alloc_inner ( & mut allocs , 64 ) , Some ( START_OFFSET + 128 ) ) ;
assert_eq! ( alloc_inner ( & mut allocs , 256 ) , Some ( START_OFFSET + 128 + 64 ) ) ;
assert_eq! ( alloc_inner ( & mut allocs , 128 ) , Some ( START_OFFSET + 128 + 64 + 256 ) ) ;
assert_eq! ( alloc_inner ( & mut allocs , 128 ) , Some ( START_OFFSET + 128 + 64 + 256 + 128 ) ) ;
assert_eq! ( alloc_inner ( & mut allocs , 128 ) , Some ( START_OFFSET + 128 + 64 + 256 + 128 + 128 ) ) ;
assert_eq! ( alloc_inner ( & mut allocs , 0xFF00 ) , None ) ;
// create two holes and fill first hole, interleaved
assert_eq! ( dealloc_inner ( & mut allocs , START_OFFSET + 128 + 64 ) , true ) ;
let mut last_alloc = 0 ;
// consistency check and print out
for ( & offset , & len ) in allocs . iter ( ) {
assert! ( offset > = last_alloc , " new offset is inside last allocation! " ) ;
println! ( " {} - {} " , offset , offset + len ) ;
last_alloc = offset + len ;
}
assert_eq! ( alloc_inner ( & mut allocs , 128 ) , Some ( START_OFFSET + 128 + 64 ) ) ;
assert_eq! ( dealloc_inner ( & mut allocs , START_OFFSET + 128 + 64 + 256 + 128 ) , true ) ;
assert_eq! ( alloc_inner ( & mut allocs , 128 ) , Some ( START_OFFSET + 128 + 64 + 128 ) ) ;
// alloc something that doesn't fit at all
assert_eq! ( alloc_inner ( & mut allocs , 256 ) , Some ( START_OFFSET + 128 + 64 + 256 + 128 + 128 + 128 ) ) ;
// fill second hole
assert_eq! ( alloc_inner ( & mut allocs , 128 ) , Some ( START_OFFSET + 128 + 64 + 256 + 128 ) ) ;
// final tail alloc
assert_eq! ( alloc_inner ( & mut allocs , 64 ) , Some ( START_OFFSET + 128 + 64 + 256 + 128 + 128 + 128 + 256 ) ) ;
println! ( " after structured test: " ) ;
let mut last_alloc = 0 ;
// consistency check and print out
for ( & offset , & len ) in allocs . iter ( ) {
assert! ( offset > = last_alloc , " new offset is inside last allocation! " ) ;
println! ( " {} - {} ( {} ) " , offset , offset + len , len ) ;
last_alloc = offset + len ;
}
// random alloc/dealloc and check for overlapping regions
let mut tracker = Vec ::< u32 > ::new ( ) ;
for _ in 0 .. 10240 {
if rng . next_u32 ( ) % 2 = = 0 {
if tracker . len ( ) > 0 {
2022-05-02 15:15:52 +00:00
//println!("tracker: {:?}", tracker);
2022-05-02 14:59:33 +00:00
let index = tracker . remove ( ( rng . next_u32 ( ) % tracker . len ( ) as u32 ) as usize ) ;
2022-05-02 15:15:52 +00:00
//println!("removing: {} of {}", index, tracker.len());
2022-05-02 14:59:33 +00:00
assert_eq! ( dealloc_inner ( & mut allocs , index ) , true ) ;
}
} else {
let req = rng . next_u32 ( ) % 256 ;
if let Some ( offset ) = alloc_inner ( & mut allocs , req ) {
2022-05-02 15:15:52 +00:00
//println!("tracker: {:?}", tracker);
//println!("alloc: {}+{}", offset, req);
2022-05-02 14:59:33 +00:00
tracker . push ( offset ) ;
}
}
}
let mut last_alloc = 0 ;
// consistency check and print out
println! ( " after random test: " ) ;
for ( & offset , & len ) in allocs . iter ( ) {
assert! ( offset > = last_alloc , " new offset is inside last allocation! " ) ;
2022-05-02 15:15:52 +00:00
assert! ( offset & 0xF = = 0 , " misaligned allocation detected " ) ;
2022-05-02 14:59:33 +00:00
println! ( " {} - {} ( {} ) " , offset , offset + len , len ) ;
last_alloc = offset + len ;
}
}
}