Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

orb-ui: diamond: self-serve with cone support #172

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
502 changes: 491 additions & 11 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ members = [
"orb-slot-ctrl",
"orb-thermal-cam-ctrl",
"orb-ui",
"orb-ui/cone",
"orb-ui/pid",
"orb-ui/sound",
"orb-ui/uart",
Expand Down Expand Up @@ -58,6 +59,7 @@ tokio-test = "0.4.4"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
zbus = { version = "4", default-features = false, features = ["tokio"] }
ftdi-embedded-hal = { version = "0.22.0", features = ["libftd2xx", "libftd2xx-static"] }

orb-security-utils.path = "security-utils"

Expand Down
2 changes: 1 addition & 1 deletion hil/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ camino = "1.1.6"
clap = { workspace = true, features = ["derive"] }
cmd_lib = "1.9.3"
color-eyre.workspace = true
ftdi-embedded-hal = { version = "0.22.0", features = ["libftd2xx-static"] }
ftdi-embedded-hal.workspace = true
libftd2xx = { version = "0.32.4", features = ["static"] }
nusb = { git = "https://github.com/thebutlah/nusb", rev = "ca8b2edc9a8dad773a609b2d65b26d6b738670ad" }
orb-build-info.path = "../build-info"
Expand Down
2 changes: 2 additions & 0 deletions orb-ui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ orb-build-info.path = "../build-info"
orb-messages.workspace = true
orb-sound.path = "sound"
orb-uart.path = "uart"
orb-cone.path = "cone"
orb-rgb.path = "rgb"
pid.path = "pid"
prost = "0.12.3"
serde.workspace = true
Expand Down
1 change: 1 addition & 0 deletions orb-ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Test new event with the orb-ui daemon running:

```shell
busctl --user call org.worldcoin.OrbUiState1 /org/worldcoin/OrbUiState1 org.worldcoin.OrbUiState1 OrbSignupStateEvent s "\"Bootup\""
busctl --user call org.worldcoin.OrbUserEvent1 /org/worldcoin/OrbUserEvent1 org.worldcoin.OrbUserEvent1 UserEvent s "\"ConeButtonPressed\""
```

## Platform Support
Expand Down
26 changes: 26 additions & 0 deletions orb-ui/cone/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "orb-cone"
version = "0.0.0"
authors = ["Cyril Fougeray"]
publish = false

edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
color-eyre.workspace = true
tracing.workspace = true
tokio.workspace = true
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
image = { version = "0.25.1", features = [] }
rand = "0.8.5"
gc9a01-rs = "0.2.1"
tinybmp = "0.5.0"
embedded-graphics = "0.8.1"
orb-rgb = { path = "../rgb" }
qrcode = "0.14.1"
ftdi-embedded-hal.workspace = true
15 changes: 15 additions & 0 deletions orb-ui/cone/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Cone library

Cross-platform library to control the cone components over USB:

- LCD screen
- LED strip
- Button

## Running the example

With an FTDI module (`FT4232H`) connected to the host over USB:

```bash
cargo-zigbuild run --example cone-simulation --release
```
127 changes: 127 additions & 0 deletions orb-ui/cone/examples/cone-simulation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/// This is an example that shows how to initialize and
/// control devices connected to the cone (FTDI chip)
use color_eyre::eyre;
use tokio::sync::mpsc;
use tokio::task;
use tracing::info;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter};

use orb_cone::led::CONE_LED_COUNT;
use orb_cone::ConeEvents;
use orb_rgb::Argb;

const CONE_LED_STRIP_DIMMING_DEFAULT: u8 = 10_u8;
const CONE_LED_STRIP_RAINBOW_PERIOD_S: u64 = 2;
const CONE_LED_STRIP_MAXIMUM_BRIGHTNESS: u8 = 20;

#[tokio::main]
async fn main() -> eyre::Result<()> {
let registry = tracing_subscriber::registry();
#[cfg(tokio_unstable)]
let registry = registry.with(console_subscriber::spawn());
registry
.with(fmt::layer())
.with(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();

let devices = ftdi_embedded_hal::libftd2xx::list_devices()?;
for device in devices.iter() {
tracing::debug!("Device: {:?}", device);
}

let (tx, mut rx) = mpsc::unbounded_channel();
let mut cone = orb_cone::Cone::new(tx)?;

// spawn a thread to receive events
task::spawn(async move {
let mut button_pressed = false;
loop {
match rx.recv().await {
Some(event) => match event {
ConeEvents::ButtonPressed(state) => {
if state != button_pressed {
info!(
"🔘 Button {}",
if state { "pressed" } else { "released" }
);
button_pressed = state;
}
}
},
None => {
tracing::error!("Cone events channel closed");
break;
}
}
}
});

info!("🍦 Cone initialized");

let mut counter = 0;
loop {
let mut pixels = [Argb::default(); CONE_LED_COUNT];

match counter {
0 => {
cone.queue_lcd_fill(Argb::DIAMOND_USER_IDLE)?;
for pixel in pixels.iter_mut() {
*pixel = Argb::DIAMOND_USER_IDLE;
}
}
1 => {
cone.queue_lcd_fill(Argb::FULL_RED)?;
for pixel in pixels.iter_mut() {
*pixel = Argb::FULL_RED;
pixel.0 = Some(CONE_LED_STRIP_DIMMING_DEFAULT);
}
}
2 => {
cone.queue_lcd_fill(Argb::FULL_GREEN)?;
for pixel in pixels.iter_mut() {
*pixel = Argb::FULL_GREEN;
pixel.0 = Some(CONE_LED_STRIP_DIMMING_DEFAULT);
}
}
3 => {
cone.queue_lcd_fill(Argb::FULL_BLUE)?;
for pixel in pixels.iter_mut() {
*pixel = Argb::FULL_BLUE;
pixel.0 = Some(CONE_LED_STRIP_DIMMING_DEFAULT);
}
}
4 => {
cone.queue_lcd_bmp(String::from("examples/logo.bmp"))?;
for pixel in pixels.iter_mut() {
*pixel = Argb(
Some(CONE_LED_STRIP_DIMMING_DEFAULT),
// random
rand::random::<u8>() % CONE_LED_STRIP_MAXIMUM_BRIGHTNESS,
rand::random::<u8>() % CONE_LED_STRIP_MAXIMUM_BRIGHTNESS,
rand::random::<u8>() % CONE_LED_STRIP_MAXIMUM_BRIGHTNESS,
);
}
}
5 => {
cone.queue_lcd_qr_code(String::from("https://www.worldcoin.org/"))?;
for pixel in pixels.iter_mut() {
*pixel = Argb::DIAMOND_USER_AMBER;
}
}
_ => {}
}
cone.queue_rgb_leds(&pixels)?;

std::thread::sleep(std::time::Duration::from_secs(
CONE_LED_STRIP_RAINBOW_PERIOD_S,
));
counter = (counter + 1) % 6;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what about naming this magic 6? It will be easier to understand it's purpose ;)

}
}
86 changes: 86 additions & 0 deletions orb-ui/cone/src/button.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
use crate::{ConeEvents, Status};
use color_eyre::eyre;
use ftdi_embedded_hal::libftd2xx::{BitMode, Ft4232h, Ftdi, FtdiCommon};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;
use tracing::debug;

const BUTTON_GPIO_PIN: u8 = 0;
const BUTTON_GPIO_MASK: u8 = 1 << BUTTON_GPIO_PIN;

pub struct Button {
thread_handle: Option<std::thread::JoinHandle<()>>,
terminate: Arc<AtomicBool>,
}

/// Poll the button state.
/// Events are sent to the event queue when the button is pressed or released
/// The thread that polls the button is also used to check the connection status
impl Button {
pub(crate) fn spawn(
event_queue: mpsc::UnboundedSender<ConeEvents>,
connection: Arc<Mutex<Status>>,
) -> eyre::Result<Self> {
let mut device: Ft4232h = Ftdi::with_index(7)?.try_into()?;
let mask: u8 = !BUTTON_GPIO_MASK; // button pin as input, all others as output
device.set_bit_mode(mask, BitMode::AsyncBitbang)?;
debug!("Button GPIO initialized");

let terminate = Arc::new(AtomicBool::new(false));
let terminate_clone = Arc::clone(&terminate);

// spawn a thread to poll the button
let thread_handle = std::thread::spawn(move || {
// keep state so that we send an event only on state change
let mut last_state = false;
loop {
if terminate_clone.load(Ordering::Relaxed) {
return;
}
match device.bit_mode() {
Ok(mode) => {
// connected
if let Ok(mut status) = connection.lock() {
*status = Status::Connected;
}
// button is active low
let pressed = mode & BUTTON_GPIO_MASK == 0;
if pressed != last_state {
if let Err(e) =
event_queue.send(ConeEvents::ButtonPressed(pressed))
{
tracing::error!("Error sending event: {:?} - no receiver? stopping producer", e);
return;
}
last_state = pressed;
}
}
Err(e) => {
// disconnected
if let Ok(mut status) = connection.lock() {
*status = Status::Disconnected;
}
tracing::trace!("Error reading button state: {:?}", e);
}
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
});

Ok(Button {
thread_handle: Some(thread_handle),
terminate,
})
}
}

impl Drop for Button {
fn drop(&mut self) {
self.terminate.store(true, Ordering::Relaxed);
if let Some(handle) = self.thread_handle.take() {
handle.join().unwrap();
debug!("Button thread joined");
}
}
}
Loading
Loading