From c061240dfcf87bc5d3a1b588977bc4c270746b82 Mon Sep 17 00:00:00 2001 From: AzureMarker Date: Wed, 2 Feb 2022 21:41:33 -0800 Subject: [PATCH] Add futures-tokio-basic example (not working yet) There's some issues with the example right now. See https://github.com/Meziu/ctru-rs/pull/36#issuecomment-1028617954 --- ctru-rs/Cargo.toml | 1 + ctru-rs/examples/futures-tokio-basic.rs | 65 +++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 ctru-rs/examples/futures-tokio-basic.rs diff --git a/ctru-rs/Cargo.toml b/ctru-rs/Cargo.toml index 1b303f3..ff327f5 100644 --- a/ctru-rs/Cargo.toml +++ b/ctru-rs/Cargo.toml @@ -26,6 +26,7 @@ toml = "0.5" [dev-dependencies] ferris-says = "0.2.1" time = "0.3.7" +tokio = { version = "1.16", features = ["rt", "time", "sync", "macros"] } [features] default = ["romfs"] diff --git a/ctru-rs/examples/futures-tokio-basic.rs b/ctru-rs/examples/futures-tokio-basic.rs new file mode 100644 index 0000000..e8e8775 --- /dev/null +++ b/ctru-rs/examples/futures-tokio-basic.rs @@ -0,0 +1,65 @@ +use ctru::console::Console; +use ctru::services::hid::KeyPad; +use ctru::services::{Apt, Hid}; +use ctru::Gfx; +use std::time::Duration; + +fn main() { + ctru::init(); + let gfx = Gfx::default(); + let hid = Hid::init().expect("Couldn't obtain HID controller"); + let apt = Apt::init().expect("Couldn't obtain APT controller"); + let _console = Console::init(gfx.top_screen.borrow_mut()); + + // FIXME: replace this with `Ps` when #39 merges + assert!(unsafe { ctru_sys::psInit() } >= 0); + + // Give ourselves up to 30% of the system core's time + apt.set_app_cpu_time_limit(30) + .expect("Failed to enable system core"); + + println!("Starting runtime..."); + + let (exit_sender, mut exit_receiver) = tokio::sync::oneshot::channel(); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .expect("Couldn't build runtime"); + + let runtime_thread = ctru::thread::Builder::new() + .affinity(1) + .spawn(move || { + runtime.block_on(async move { + let mut wake_time = tokio::time::Instant::now() + Duration::from_secs(1); + loop { + let sleep_future = tokio::time::sleep_until(wake_time); + + tokio::select! { + _ = &mut exit_receiver => break, + _ = sleep_future => { + println!("Tick"); + wake_time += Duration::from_secs(1); + } + } + } + }); + }) + .expect("Failed to create runtime thread"); + + println!("Runtime started!"); + + while apt.main_loop() { + hid.scan_input(); + + if hid.keys_down().contains(KeyPad::KEY_START) { + println!("Shutting down..."); + let _ = exit_sender.send(()); + let _ = runtime_thread.join(); + break; + } + + gfx.flush_buffers(); + gfx.swap_buffers(); + gfx.wait_for_vblank(); + } +}