From 409052a93bdfe5d6b36f7c183d72c46bbe0e9312 Mon Sep 17 00:00:00 2001
From: zdmx <hi@zdmx.me>
Date: Sat, 19 Aug 2023 15:27:01 +0200
Subject: [PATCH] make template supply main fn

---
 flow3-rs-rt/Cargo.lock                |  1 +
 flow3-rs-rt/Cargo.toml                |  1 +
 flow3-rs-rt/src/flow3r.rs             | 47 +++++++++++++--------------
 flow3-rs-rt/src/lib.rs                |  6 +---
 flow3-rs-rt/src/runtime.rs            | 36 +++++++++++++++++---
 flow3-rs-template/Cargo.lock          |  5 ++-
 flow3-rs-template/Cargo.toml          |  7 ++--
 flow3-rs-template/src/demo_tasks.rs   |  5 ---
 flow3-rs-template/src/main.rs         | 27 ++++-----------
 flow3-rs-template/src/ui/main_menu.rs |  7 ++++
 flow3-rs/src/captouch.rs              |  3 ++
 flow3-rs/src/input.rs                 |  1 +
 flow3-rs/src/lib.rs                   |  4 +--
 13 files changed, 85 insertions(+), 65 deletions(-)

diff --git a/flow3-rs-rt/Cargo.lock b/flow3-rs-rt/Cargo.lock
index e9099e7..13a9775 100644
--- a/flow3-rs-rt/Cargo.lock
+++ b/flow3-rs-rt/Cargo.lock
@@ -722,6 +722,7 @@ dependencies = [
  "esp32s3-hal",
  "flow3-rs",
  "lazy_static",
+ "port-expander",
  "shared-bus",
  "static_cell",
 ]
diff --git a/flow3-rs-rt/Cargo.toml b/flow3-rs-rt/Cargo.toml
index 9ed15f0..1fd04c9 100644
--- a/flow3-rs-rt/Cargo.toml
+++ b/flow3-rs-rt/Cargo.toml
@@ -15,3 +15,4 @@ flow3-rs = { path = "../flow3-rs" }
 lazy_static = { version = "1.4.0", features = ["spin_no_std"] }
 esp-println = { version = "0.5.0", features = ["esp32s3"] }
 embassy-sync = "0.2.0"
+port-expander = "0.4.0"
diff --git a/flow3-rs-rt/src/flow3r.rs b/flow3-rs-rt/src/flow3r.rs
index 4d7efe2..e0179e5 100644
--- a/flow3-rs-rt/src/flow3r.rs
+++ b/flow3-rs-rt/src/flow3r.rs
@@ -1,17 +1,16 @@
 use hal::{
     clock::{ClockControl, Clocks},
-    cpu_control::CpuControl,
     embassy,
     gdma::Gdma,
     i2c::I2C,
     ledc::LEDC,
     peripherals::{Peripherals, I2C0},
     prelude::*,
-    pulse_control::ClockSource,
     systimer::SystemTimer,
     timer::TimerGroup,
-    PulseControl, Rtc, Spi, Uart, IO, uart::{self, TxRxPins}, Rng,
+    Rmt, Rtc, Spi, Uart, IO, uart::{self, TxRxPins}, Rng,
 };
+use shared_bus::{BusManager, XtensaMutex};
 use static_cell::StaticCell;
 
 use flow3_rs::{
@@ -26,7 +25,7 @@ use flow3_rs::{
 
 static CLOCKS: StaticCell<Clocks> = StaticCell::new();
 
-pub async fn init_flow3r() -> (Flow3r, InputRunner, CaptouchRunner)  {
+pub async fn init_flow3r() -> (Flow3r, I2C<'static, I2C0> )  {
     let peripherals = Peripherals::take();
     let mut system = peripherals.SYSTEM.split();
     let clocks = CLOCKS.init(ClockControl::boot_defaults(system.clock_control).freeze());
@@ -61,16 +60,16 @@ pub async fn init_flow3r() -> (Flow3r, InputRunner, CaptouchRunner)  {
     .unwrap();
 
     let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
-    let pulse = PulseControl::new(
+
+    let rmt = Rmt::new(
         peripherals.RMT,
+        80u32.MHz(),
         &mut system.peripheral_clock_control,
-        ClockSource::APB,
-        0,
-        0,
-        0,
+        &clocks,
     )
     .unwrap();
 
+
     // Init I2C
 
     let sda = io.pins.gpio2;
@@ -87,7 +86,7 @@ pub async fn init_flow3r() -> (Flow3r, InputRunner, CaptouchRunner)  {
 
     // Create shared I2C Bus
 
-    let i2c_busmanager = shared_bus::new_xtensa!(I2C<'static, I2C0> = i2c).unwrap();
+    //let i2c_busmanager = shared_bus::new_xtensa!(I2C<'static, I2C0> = i2c).unwrap();
 
     // Init SPI + DMA
 
@@ -137,7 +136,7 @@ pub async fn init_flow3r() -> (Flow3r, InputRunner, CaptouchRunner)  {
     };
     let uart0_pins = TxRxPins::new_tx_rx(io.pins.gpio7.into_push_pull_output(), io.pins.gpio6.into_floating_input());
     let mut uart0 = Uart::new_with_config(peripherals.UART1, Some(uart0_config), Some(uart0_pins), &clocks, &mut system.peripheral_clock_control);
-    uart0.set_rx_fifo_full_threshold(64 as u16);
+    uart0.set_rx_fifo_full_threshold(64 as u16).unwrap();
 
     hal::interrupt::enable(
         hal::peripherals::Interrupt::UART1,
@@ -153,7 +152,7 @@ pub async fn init_flow3r() -> (Flow3r, InputRunner, CaptouchRunner)  {
     };
     let uart1_pins = TxRxPins::new_tx_rx(io.pins.gpio5.into_push_pull_output(), io.pins.gpio4.into_floating_input());
     let mut uart1 = Uart::new_with_config(peripherals.UART2, Some(uart1_config),Some(uart1_pins), &clocks, &mut system.peripheral_clock_control);
-    uart1.set_rx_fifo_full_threshold(64 as u16);
+    uart1.set_rx_fifo_full_threshold(64 as u16).unwrap();
 
     hal::interrupt::enable(
         hal::peripherals::Interrupt::UART2,
@@ -163,15 +162,7 @@ pub async fn init_flow3r() -> (Flow3r, InputRunner, CaptouchRunner)  {
 
     let rng = Rng::new(peripherals.RNG);
 
-    // Init Flow3r components
-
-    let badgelink = BadgeLink::new(i2c_busmanager.acquire_i2c());
-    let imu = ImuHandler::new(i2c_busmanager.acquire_i2c());
-    let inputs = Inputs;
-    let captouch = Captouch;
-    let leds = init_leds(pulse.channel0, io.pins.gpio14);
-
-    let input_runner = InputRunner::new(
+    /*let input_runner = InputRunner::new(
         i2c_busmanager.acquire_i2c(),
         io.pins.gpio8,
         io.pins.gpio0,
@@ -183,9 +174,17 @@ pub async fn init_flow3r() -> (Flow3r, InputRunner, CaptouchRunner)  {
         i2c_busmanager.acquire_i2c(),
         io.pins.gpio16,
         io.pins.gpio15,
-    );
+    );*/
+
+    // Init Flow3r components
+
+    //let badgelink = BadgeLink::new(i2c_busmanager.acquire_i2c());
+    //let imu = ImuHandler::new(i2c_busmanager.acquire_i2c());
+    let inputs = Inputs;
+    let captouch = Captouch;
+    let leds = init_leds(rmt, io.pins.gpio14);
 
-    let flow3r = Flow3r::new(Some(badgelink), Some(captouch), Some(display), Some(imu), Some(inputs), Some(leds), Some(uart0), Some(uart1), Some(rng));
+    let flow3r = Flow3r::new(None, Some(captouch), Some(display), None, Some(inputs), Some(leds), Some(uart0), Some(uart1), Some(rng));
 
-    (flow3r, input_runner, captouch_runner)
+    (flow3r, i2c)
 }
\ No newline at end of file
diff --git a/flow3-rs-rt/src/lib.rs b/flow3-rs-rt/src/lib.rs
index dba5d27..af2e7bd 100644
--- a/flow3-rs-rt/src/lib.rs
+++ b/flow3-rs-rt/src/lib.rs
@@ -3,8 +3,4 @@
 
 mod runtime;
 mod flow3r;
-pub use runtime::start_runtime;
-pub use runtime::EXECUTOR;
-pub use flow3r::init_flow3r;
-pub use runtime::captouch_task;
-pub use runtime::input_task;
\ No newline at end of file
+pub use runtime::start_runtime;
\ No newline at end of file
diff --git a/flow3-rs-rt/src/runtime.rs b/flow3-rs-rt/src/runtime.rs
index 8849ab7..687a289 100644
--- a/flow3-rs-rt/src/runtime.rs
+++ b/flow3-rs-rt/src/runtime.rs
@@ -1,5 +1,7 @@
 use embassy_executor::{Executor, Spawner, SpawnToken};
 use esp_println::println;
+use hal::{i2c::I2C, peripherals::I2C0, gpio::{Gpio8, Gpio0, Gpio3, Unknown}, prelude::_embedded_hal_blocking_i2c_Read};
+use shared_bus::{I2cProxy, XtensaMutex};
 use static_cell::StaticCell;
 
 use flow3_rs::{Flow3r, input::InputRunner, captouch::CaptouchRunner};
@@ -21,17 +23,22 @@ pub fn start_runtime<S>(main: fn(Flow3r) -> SpawnToken<S>) -> !
 
 #[embassy_executor::task]
 async fn init_runtime(main: fn(Flow3r) -> SpawnToken<*mut ()>) {
+    let (flow3r, mut i2c) = init_flow3r().await;
 
-    let (flow3r, input_runner, captouch_runner) = init_flow3r().await;
+    let addr = 0x60 | ((true as u8) << 3) | ((true as u8) << 2) | ((true as u8) << 1) | (false as u8);
+
+    let mut buf = [0u8;1];
+    i2c.read(addr, &mut buf).unwrap();
+    println!("buf {}", buf[0]);
 
     // Spawn background tasks
     let spawner = Spawner::for_current_executor().await;
-    spawner
+    /*spawner
         .spawn(input_task(input_runner))
-        .unwrap();
-    spawner
+        .unwrap();*/
+    /*spawner
         .spawn(captouch_task(captouch_runner))
-        .unwrap();
+        .unwrap();*/
 
     // Hand over to main task
     spawner.spawn(main(flow3r)).unwrap();
@@ -45,4 +52,23 @@ pub async fn input_task(runner: InputRunner) -> ! {
 #[embassy_executor::task]
 pub async fn captouch_task(runner: CaptouchRunner) -> ! {
     runner.run().await
+}
+
+#[embassy_executor::task]
+async fn input(
+    i2c: I2cProxy<'static, XtensaMutex<I2C<'static, I2C0>>>,
+ ) {
+    let mut pe2 = port_expander::Max7321::new(i2c, true, true, false, true);
+
+    let pe2_io = pe2.split();
+    let mut sw1_r = pe2_io.p0;
+    sw1_r.set_high().unwrap();
+    let mut sw1_l = pe2_io.p7;
+    sw1_l.set_high().unwrap();
+    let mut sw2_r = pe2_io.p5;
+    sw2_r.set_high().unwrap();
+    let mut sw2_l = pe2_io.p4;
+    sw2_l.set_high().unwrap();
+
+    let _lcd_rst = pe2_io.p3;
 }
\ No newline at end of file
diff --git a/flow3-rs-template/Cargo.lock b/flow3-rs-template/Cargo.lock
index 44cb455..db7667e 100644
--- a/flow3-rs-template/Cargo.lock
+++ b/flow3-rs-template/Cargo.lock
@@ -562,6 +562,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "b9bb3220d63ba0ec4e9b1846edd47e8da3a884c6557b3ba7398494c56a93de35"
 dependencies = [
  "basic-toml",
+ "bitfield",
  "bitflags 2.4.0",
  "cfg-if",
  "critical-section",
@@ -721,6 +722,7 @@ dependencies = [
  "esp32s3-hal",
  "flow3-rs",
  "lazy_static",
+ "port-expander",
  "shared-bus",
  "static_cell",
 ]
@@ -1345,7 +1347,7 @@ dependencies = [
  "embedded-graphics",
  "embedded-graphics-framebuf",
  "embedded-hal 0.2.7",
- "embedded-hal 1.0.0-alpha.10",
+ "embedded-hal 1.0.0-alpha.11",
  "embedded-hal-async",
  "embedded-hal-bus",
  "esp-backtrace",
@@ -1354,6 +1356,7 @@ dependencies = [
  "flow3-rs",
  "flow3-rs-rt",
  "heapless",
+ "shared-bus",
  "smart-leds",
  "smoltcp",
  "static_cell",
diff --git a/flow3-rs-template/Cargo.toml b/flow3-rs-template/Cargo.toml
index 882ef57..6338c41 100644
--- a/flow3-rs-template/Cargo.toml
+++ b/flow3-rs-template/Cargo.toml
@@ -15,7 +15,7 @@ embassy-futures = "0.1.0"
 embassy-net = { version = "0.1.0", features = ["medium-ethernet", "udp", "proto-ipv6", "nightly", "unstable-traits"] }
 embassy-net-badgelink = { path = "../embassy-net-badgelink" }
 embassy-sync = "0.2.0"
-embassy-time = { version = "=0.1.1", features = ["nightly", "unstable-traits"] }
+embassy-time = { version = "=0.1.2", features = ["nightly", "unstable-traits"] }
 embedded-dma = "0.2.0"
 embedded-graphics = "0.8.0"
 embedded-graphics-framebuf = "0.5.0"
@@ -25,11 +25,12 @@ embedded-hal-async = "0.2.0-alpha.1"
 embedded-hal-bus = "0.1.0-alpha.2"
 esp-backtrace = { version = "0.7.0", features = ["esp32s3", "panic-handler", "exception-handler", "print-uart"] }
 esp-println = { version = "0.5.0", features = ["esp32s3"] }
-hal = { package = "esp32s3-hal", version = "0.155.0", features = ["embassy", "async", "embassy-time", "embassy-time-systick"] }
+hal = { package = "esp32s3-hal", version = "0.11.0", features = ["embassy", "async", "embassy-time", "embassy-time-systick"] }
 heapless = "0.7.16"
 smart-leds = "0.3.0"
 smoltcp = { version = "0.10.0", default-features = false }
 static_cell = "1.2.0"
 tinybmp = "0.5.0"
 flow3-rs = { path = "../flow3-rs" }
-flow3-rs-rt = { path = "../flow3-rs-rt" }
\ No newline at end of file
+flow3-rs-rt = { path = "../flow3-rs-rt" }
+shared-bus = { version = "0.3.0", features = ["xtensa-lx", "xtensa"] }
diff --git a/flow3-rs-template/src/demo_tasks.rs b/flow3-rs-template/src/demo_tasks.rs
index e0479b9..7fa6acc 100644
--- a/flow3-rs-template/src/demo_tasks.rs
+++ b/flow3-rs-template/src/demo_tasks.rs
@@ -26,18 +26,13 @@ use flow3_rs::{display::Display, imu::ImuHandler, badgelink::{BadgeLink, badgene
 pub async fn leds_fade(mut leds: flow3_rs::leds::Leds) -> ! {
     let mut b = (30, false);
 
-    println!("led task running");
-
     loop {
-        println!("led loop entry");
         leds.write(smart_leds::brightness(
             smart_leds::gamma([smart_leds::colors::VIOLET; 40].into_iter()),
             b.0,
         ))
         .expect("failed to set leds");
 
-        println!("led loop");
-
         Timer::after(Duration::from_millis(30)).await;
         b = flow3_rs::leds::brightness_fade_in_out(b, 30, 0);
     }
diff --git a/flow3-rs-template/src/main.rs b/flow3-rs-template/src/main.rs
index a91cdf1..2cc8046 100644
--- a/flow3-rs-template/src/main.rs
+++ b/flow3-rs-template/src/main.rs
@@ -7,37 +7,24 @@ mod demo_tasks;
 mod ui;
 
 use demo_tasks::draw_start_screen;
-use embassy_executor::{Spawner, Executor};
-use embassy_time::{Duration, Timer};
+use embassy_executor::Spawner;
+use embassy_time::{Duration, Timer, Delay};
 
 use esp_backtrace as _;
 use esp_println::println;
-use flow3_rs_rt::{init_flow3r, input_task, captouch_task};
+use flow3_rs::Flow3r;
+use flow3_rs_rt::start_runtime;
 use hal::prelude::*;
 
 use crate::ui::main_menu::main_menu;
 
 #[entry]
 fn runtime() -> ! {
-    let executor = flow3_rs_rt::EXECUTOR.init(Executor::new());
-    executor.run(|spawner| {
-        spawner.spawn(main()).unwrap();
-    });
+    start_runtime(main)
 }
 
 #[embassy_executor::task]
-async fn main() -> ! {
-    let (mut flow3r, input_runner, captouch_runner) = init_flow3r().await;
-
-    // Spawn background tasks
-    let spawner = Spawner::for_current_executor().await;
-    spawner
-        .spawn(input_task(input_runner))
-        .unwrap();
-    spawner
-        .spawn(captouch_task(captouch_runner))
-        .unwrap();
-
+async fn main(mut flow3r: Flow3r) -> ! {
     println!("started main");
     // draw_start_screen(&mut flow3r.take_display()).await;
 
@@ -46,7 +33,7 @@ async fn main() -> ! {
 
     println!("started led task");
 
-    Timer::after(Duration::from_secs(2)).await;
+    Timer::after(Duration::from_micros(100)).await;
 
     main_menu(flow3r).await
 }
diff --git a/flow3-rs-template/src/ui/main_menu.rs b/flow3-rs-template/src/ui/main_menu.rs
index 3957be5..8f7207d 100644
--- a/flow3-rs-template/src/ui/main_menu.rs
+++ b/flow3-rs-template/src/ui/main_menu.rs
@@ -7,6 +7,7 @@ use embedded_graphics::{
     text::Text,
 };
 
+use esp_println::println;
 use flow3_rs::{display::Display, imu::ImuHandler, Flow3r};
 
 use crate::demo_tasks::{display_demo, imu_demo, captouch_demo};
@@ -16,9 +17,13 @@ pub async fn main_menu(mut flow3r: Flow3r) -> ! {
     let mut display = flow3r.take_display();
     let mut imu = flow3r.take_imu();
 
+    println!("main menu running");
+
     let apps = ["input_test", "imu_test", "captouch_test"];
     let mut selected = 0usize;
 
+    display.set_backlight(100).unwrap();
+
     display
         .fill_solid(&display.bounding_box(), Rgb565::BLACK)
         .unwrap();
@@ -31,6 +36,8 @@ pub async fn main_menu(mut flow3r: Flow3r) -> ! {
     text.draw(&mut display).unwrap();
     display.flush().await.unwrap();
 
+    println!("drawn");
+
     loop {
         match select3(
             inputs.sw1_center.wait_for_press(),
diff --git a/flow3-rs/src/captouch.rs b/flow3-rs/src/captouch.rs
index c590eef..894e00b 100644
--- a/flow3-rs/src/captouch.rs
+++ b/flow3-rs/src/captouch.rs
@@ -111,9 +111,11 @@ impl CaptouchRunner {
     pub async fn run(
         self
     ) -> ! {
+        println!("started captouch runner");
         let mut cap_bot_int = self.cap_bot_int.into_pull_up_input();
         let mut cap_top_int = self.cap_top_int.into_pull_up_input();
         let (mut ad7147_bot, mut ad7147_top) = init_captouch(self.i2c_bot, self.i2c_top).unwrap();
+        println!("captouch initialized");
 
         let device_id = ad7147_bot.read_device_id().unwrap();
         println!("captouch bot device id: {:016b}", device_id);
@@ -380,6 +382,7 @@ fn init_captouch(
                 .build(),
         ])
         .build();
+    println!("initializing ad7147");
     Ok((
         ad7147_bot.init(config_bot, &mut Delay)?,
         ad7147_top.init(config_top, &mut Delay)?,
diff --git a/flow3-rs/src/input.rs b/flow3-rs/src/input.rs
index a9277f6..4e7c59f 100644
--- a/flow3-rs/src/input.rs
+++ b/flow3-rs/src/input.rs
@@ -78,6 +78,7 @@ impl InputRunner {
         let inputs_publisher = INPUTS_CHANNEL.immediate_publisher();
     
         loop {
+            println!("input loop");
             match select3(
                 i2c_int.wait_for_low(),
                 sw1_button.wait_for_any_edge(),
diff --git a/flow3-rs/src/lib.rs b/flow3-rs/src/lib.rs
index cc307ce..545b15a 100644
--- a/flow3-rs/src/lib.rs
+++ b/flow3-rs/src/lib.rs
@@ -30,7 +30,7 @@ pub struct Flow3r {
     leds: Option<Leds>,
     uart0: Option<BadgenetUartLeft>,
     uart1: Option<BadgenetUartRight>,
-    rng: Option<Rng<'static>>,
+    rng: Option<Rng>,
 }
 
 impl Flow3r {
@@ -43,7 +43,7 @@ impl Flow3r {
         leds: Option<Leds>,
         uart0: Option<BadgenetUartLeft>,
         uart1: Option<BadgenetUartRight>,
-        rng: Option<Rng<'static>>,
+        rng: Option<Rng>,
     ) -> Self {
         Self {
             badgelink,
-- 
GitLab