Compare commits

..
Author SHA1 Message Date
3c20c4e13c
show ping on panel 2025-03-30 03:13:19 -04:00
7811eaf91c
disconnect button 2025-03-30 01:06:29 -04:00
a3864c4ef0
use past convergence logic when one sensor is pat the convergence point
the hardware is in really bad shape, the tofs randomly are stuck at max
and randomly stuck at min. The drive esc can't feed more than ~20%
power, and then not consistently either. Without any signal in the noise
it is impossible to move forward.

A possible full system redesign is to use a global shutter camera from
outside the box for all position data, perhaps supplemented with an
onboard IMU. tofs (at this price point) are not useful. It may be worth
trying new tofs that haven't had the chance for particulate to
accumulate in the emmiter/collector, but I'm not bullish on it.
2025-03-29 19:02:58 -04:00
7fe4e4477e
fire in auto 2025-03-28 18:35:40 -04:00
17f484acd5
re-embedded auto in interface
crashes seem to occur when mutating state from across the dylib boundary

not worth troubleshooting when I don't need hot-reloading anymore
2025-03-28 00:08:13 -04:00
9a68f43e5d
run auto (it crashes) 2025-03-27 19:45:47 -04:00
1e1a82830b
show auto status on gui 2025-03-27 19:39:42 -04:00
311427b0a5
plumb auto interface into controller 2025-03-27 19:25:39 -04:00
b956c543fc
remove storage_dir 2025-03-27 18:59:47 -04:00
a2b629beab
loadstore 2025-03-27 18:54:39 -04:00
c0daf3f64c
use storage manager in gui 2025-03-27 18:35:31 -04:00
9f4b2e57a2
slight auto interface api changes
I'm not liking the ControlPacket architecture anymore, I'd like to
switch to a state-based controller from message-based to accommodate
reliably getting side changes to work
2025-03-26 22:29:09 -04:00
b63986711d
run (untested) 2025-03-22 15:27:49 -04:00
321ece84bc
auto load struct 2025-03-22 15:07:39 -04:00
474841212d
anyhow 2025-03-22 14:34:51 -04:00
d90011d921
storage manager 2025-03-22 14:28:57 -04:00
9c61d88fe4
started to replace the egui persistence layer 2025-03-11 14:08:47 -04:00
9e43e6a943
load config from real file 2025-03-09 20:08:54 -04:00
ce223621d1
auto conf sync to gui 2025-03-08 20:47:52 -05:00
27e69bf301
impl data receive 2025-03-08 19:28:05 -05:00
5b3347bb00
use configurable as a key 2025-03-08 19:18:25 -05:00
21e269bc43
builder pattern for configs 2025-03-08 19:09:30 -05:00
05c7904513
factored auto into separate crate 2025-03-08 17:21:55 -05:00
9d107d6c26
made interface a library 2025-03-08 15:22:14 -05:00
a000276c22
added auto stub 2025-03-08 15:13:39 -05:00
354f600f92
added icon (not testable on sway) 2025-03-08 12:05:50 -05:00
95c5b50dd3
added combat logger
A refactor might be beneficial here, now data is being
sent to multiple streams which feels a tad off
2025-03-08 11:40:07 -05:00
e352c5b048
propagate volume threshold 2025-03-08 11:03:13 -05:00
2fb5a5709f
gui conf persistence 2025-03-08 10:58:27 -05:00
b567bf7528
added config sliders and vendored eframe's persistence path finder 2025-03-08 10:33:53 -05:00
d448f05dd7
interface retries and error logging 2025-03-08 08:32:03 -05:00
81f55cc0e8
handle close requests (slightly bodgey) 2025-03-08 02:04:06 -05:00
0bef5cc6e7
tuned windows sampling settings for stability 2025-03-06 20:33:23 -05:00
cf0a6b94d7
buffer received samples until they hit the analysis threshold 2025-03-06 20:24:14 -05:00
706ed9db03
adapt to windows audio quirks (virtualbox ones at least) 2025-03-06 17:09:37 -05:00
bb974c2015
send tof status to gui 2025-03-06 12:17:13 -05:00
79b22b3cb7
added basic control gui
tried fltk, didn't like it, using egui
2025-03-06 11:49:33 -05:00
971c57fa13
graceful decay on gyro failure
also switched gyro iic pins because the other ones were
shorted under the pico :|
2025-03-05 21:10:17 -05:00
b063a41783
motors are swapped on new chassis 2025-03-05 15:01:58 -05:00
99f0ed69e4
fixes
restored esc pwm calculator

send length before data
2025-03-05 14:20:17 -05:00
02f6efaaa5
change ip to an allowable linksys DHCP subnet 2025-03-05 13:55:42 -05:00
b82c6dbed8
set auto light over the network 2025-03-05 13:02:04 -05:00
31c847f39a
gracefully handle senosr death 2025-03-05 12:55:57 -05:00
6192627e25
now using a mosfet, no "center" 2025-03-05 12:44:55 -05:00
782fd891a1
triple tof init 2025-03-05 12:36:24 -05:00
57522c26cc
added weapon enable flag 2025-01-19 17:17:29 -05:00
70d4e551b4
sax control 2025-01-19 12:20:06 -05:00
bc3b710403
recorder control update 2025-01-19 11:19:39 -05:00
9b1b289b92
don't wait to stop charging, debouncing handled by user 2025-01-19 04:50:44 -05:00
5953f2c584
shifted override fire 2025-01-19 01:20:46 -05:00
5a30e91800
cam state in telemetry 2025-01-19 01:20:13 -05:00
f532dd6d70
fix controller not returning to idle on network death 2025-01-19 01:06:49 -05:00
02720f32dd
switch to laptop ap
handles robot restarts better
2025-01-18 23:48:47 -05:00
3ea2af5c60
stop when no note is played 2025-01-18 23:48:32 -05:00
978a3fe213
stop robot on music end 2025-01-18 22:45:23 -05:00
2af0807abd
cam manager, hopefully somewhat realtime 2025-01-18 22:36:57 -05:00
f7ab1c119a
front panel write data 2025-01-18 15:04:34 -05:00
bd7b3fb287
interface telem 2025-01-18 14:56:19 -05:00
63bb5b8fea
tuning for recorder 2025-01-18 14:28:39 -05:00
4945b4d777
rx netcode 2025-01-18 14:28:29 -05:00
736584f5d6
copy pwm config from door winch 2025-01-18 13:45:49 -05:00
3b829b1b59
remove partial tof driver 2025-01-18 13:31:25 -05:00
9f740d8435
sensor data timestamp 2025-01-18 13:31:10 -05:00
088e0225ca
feasible second core sensor impl 2025-01-18 13:27:48 -05:00
7a918e2b65
transitioning sensor reads to second core 2025-01-18 13:10:07 -05:00
4c616de4a0
note -> action correspondence 2025-01-16 11:45:33 -05:00
945b4710e7
volume calculation 2025-01-16 11:16:45 -05:00
fed2a43481
frequency detection from mic 2025-01-16 11:08:08 -05:00
d0b66575d9
reduce tof enable time budget 2025-01-14 16:08:43 -05:00
24 changed files with 12938 additions and 707 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
**/target

5259
auto/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

11
auto/Cargo.toml Normal file
View file

@ -0,0 +1,11 @@
[lib]
crate-type = ["dylib"]
[package]
name = "auto"
version = "0.1.0"
edition = "2024"
[dependencies]
common = {path = "../common"}
interface = {path = "../interface"}

94
auto/src/lib.rs Normal file
View file

@ -0,0 +1,94 @@
use std::{collections::VecDeque, ops::Sub, pin::Pin};
use common::CamState;
use interface::auto::{AutoInterface, Configurable};
#[unsafe(no_mangle)]
pub fn entry(interface: AutoInterface) -> Pin<Box<dyn Future<Output = ()>>> {
Box::pin(auto(interface))
}
#[unsafe(no_mangle)]
pub static NAME: &'static str = "scanseek v1";
const AUTO_GAP: Configurable = Configurable::new("auto minimum gap").range(0. .. 300.).default(140.)
.description("distance (mm) distance measurements must instantaneously drop to indicate a detection. This should line up with the size of the smallest robot you compete against");
const AUTO_SELF_OCCLUSION: Configurable = Configurable::new("auto self occlusion").range(0. .. 200.).default(143.)
.description("distance (mm) below which measurements are considered noise in the scan phase");
#[unsafe(no_mangle)]
pub static CONFIGS: &[Configurable] = &[
AUTO_GAP,
AUTO_SELF_OCCLUSION,
];
async fn auto (mut interface: AutoInterface) {
let mut tof_l = Stats::new();
let mut tof_r = Stats::new();
loop {
let data = interface.sensor_update().await;
let cam = interface.cam_state();
let CamState::Charged = cam else {
continue;
};
let Some(latest_tof_l) = data.tof_l else {
continue;
};
tof_l.update(latest_tof_l as i16);
let Some(latest_tof_r) = data.tof_r else {
continue;
};
tof_r.update(latest_tof_r as i16);
let auto_gap = interface.conf(&AUTO_GAP);
let auto_self_occlusion = interface.conf(&AUTO_SELF_OCCLUSION);
let detection = |latest: u16, delta: i16| {
delta < auto_gap as i16 && latest > auto_self_occlusion as u16
};
if detection(latest_tof_l, tof_l.delta()) || detection(latest_tof_l, tof_l.delta()) {
if let Ok(()) = interface.enable() {
println!("found, now seek")
}
}
}
}
struct Stats<T> {
table: VecDeque<T>
}
impl<T> Stats<T> {
pub fn new() -> Self {
Self { table: VecDeque::new() }
}
const MAX_ELEMENTS: usize = 3;
pub fn update(&mut self, elem: T) {
self.table.push_front(elem);
if self.table.len() > Self::MAX_ELEMENTS {
self.table.pop_back();
}
}
}
impl<T: Ord + Sub<Output = T> + Copy + From<u8>> Stats<T> {
pub fn delta(&self) -> T {
*self.table.get(0).unwrap_or(&T::from(0)) - *self.table.get(1).unwrap_or(&T::from(0))
}
pub fn max(&self) -> T {
*self.table.iter().max().unwrap_or(&T::from(0))
}
pub fn min(&self) -> T {
*self.table.iter().max().unwrap_or(&T::from(0))
}
}

266
common/Cargo.lock generated Normal file
View file

@ -0,0 +1,266 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "approx"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
dependencies = [
"num-traits",
]
[[package]]
name = "atomic-polyfill"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4"
dependencies = [
"critical-section",
]
[[package]]
name = "autocfg"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cobs"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67ba02a97a2bd10f4b59b25c7973101c79642302776489e030cd13cdab09ed15"
[[package]]
name = "common"
version = "0.1.0"
dependencies = [
"nalgebra",
"postcard",
"serde",
]
[[package]]
name = "critical-section"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"
[[package]]
name = "hash32"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67"
dependencies = [
"byteorder",
]
[[package]]
name = "heapless"
version = "0.7.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f"
dependencies = [
"atomic-polyfill",
"hash32",
"rustc_version",
"serde",
"spin",
"stable_deref_trait",
]
[[package]]
name = "lock_api"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "nalgebra"
version = "0.31.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20bd243ab3dbb395b39ee730402d2e5405e448c75133ec49cc977762c4cba3d1"
dependencies = [
"approx",
"num-complex",
"num-rational",
"num-traits",
"serde",
"simba",
"typenum",
]
[[package]]
name = "num-complex"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
"serde",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "postcard"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "170a2601f67cc9dba8edd8c4870b15f71a6a2dc196daec8c83f72b59dff628a8"
dependencies = [
"cobs",
"heapless",
"serde",
]
[[package]]
name = "proc-macro2"
version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "semver"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3cb6eb87a131f756572d7fb904f6e7b68633f09cca868c5df1c4b8d1a694bbba"
[[package]]
name = "serde"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "simba"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f3fd720c48c53cace224ae62bef1bbff363a70c68c4802a78b5cc6159618176"
dependencies = [
"approx",
"num-complex",
"num-traits",
"paste",
]
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
dependencies = [
"lock_api",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]
name = "syn"
version = "2.0.96"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
[[package]]
name = "unicode-ident"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"

9
common/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "common"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1.0.*", default-features = false }
postcard = "1.0.0"
nalgebra = { version = "0.31.2", default-features=false, features = ["serde-serialize-no-std"]}

60
common/src/lib.rs Normal file
View file

@ -0,0 +1,60 @@
#![no_std]
use nalgebra::Vector3;
use serde::{Deserialize, Serialize};
/// -1..1
pub type Speed = f32;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum ControlPacket {
/// Forward, Clockwise
Twist(Speed, Speed),
/// Launch the flipper once
Fire,
/// Run the flipper motor manually
FireOverride(Speed),
/// Enable/Disable flipper staging
Arm(bool),
/// Enable/Disable auto light
SetAuto(bool),
RunAuto,
/// Stop all motors
Stop,
/// Permanently stop all motors
EStop,
}
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct SensorData {
/// left distance, mm
pub tof_l: Option<u16>,
/// right distance, mm
pub tof_r: Option<u16>,
/// left side distance, mm
pub tof_s: Option<u16>,
/// acceleration, rad/s
pub gyro: Option<Vector3<f32>>,
/// acceleration, g
pub accel: Option<Vector3<f32>>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TelemetryPacket {
pub sensors: SensorData,
pub cam_state: CamState,
}
impl Default for TelemetryPacket {
fn default() -> Self {
Self { sensors: Default::default(), cam_state: CamState::Idle }
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum CamState {
Firing,
Charged,
Charging,
Idle,
}

633
controller/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -6,16 +6,17 @@ license = "MIT OR Apache-2.0"
[dependencies]
embassy-executor = { version = "0.6.0", git="https://github.com/embassy-rs/embassy", features = ["task-arena-size-98304", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] }
embassy-time = { version = "0.3.2", git="https://github.com/embassy-rs/embassy", features = ["defmt", "defmt-timestamp-uptime"] }
embassy-rp = { version = "0.2.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl", "rp2040"] }
embassy-usb = { version = "0.3.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] }
embassy-net = { version = "0.4.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns"] }
embassy-net-wiznet = { version = "0.1.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] }
embassy-executor = { version = "0.7.0", git="https://github.com/embassy-rs/embassy", features = ["task-arena-size-98304", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt"] }
embassy-time = { version = "0.4.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "defmt-timestamp-uptime"] }
embassy-rp = { version = "0.3.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl", "rp2040"] }
embassy-sync = { version = "0.6.2", git="https://github.com/embassy-rs/embassy" }
embassy-usb = { version = "0.4.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] }
embassy-net = { version = "0.6.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns"] }
embassy-net-wiznet = { version = "0.2.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] }
embassy-futures = { version = "0.1.0", git="https://github.com/embassy-rs/embassy"}
embassy-usb-logger = { version = "0.2.0", git="https://github.com/embassy-rs/embassy" }
cyw43 = { version = "0.2.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "firmware-logs", "bluetooth"] }
cyw43-pio = { version = "0.2.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] }
embassy-usb-logger = { version = "0.4.0", git="https://github.com/embassy-rs/embassy" }
cyw43 = { version = "0.3.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "firmware-logs", "bluetooth"] }
cyw43-pio = { version = "0.3.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] }
defmt = "0.3"
defmt-rtt = "0.4"
@ -25,6 +26,7 @@ fixed-macro = "1.2"
# for web request example
reqwless = { version = "0.12.0", features = ["defmt",]}
serde = { version = "1.0.203", default-features = false, features = ["derive"] }
postcard = "1.0.0"
serde-json-core = "0.5.1"
# for assign resources example
@ -57,10 +59,11 @@ pio = "0.2.1"
rand = { version = "0.8.5", default-features = false }
embedded-sdmmc = "0.7.0"
bt-hci = { version = "0.1.0", default-features = false, features = ["defmt"] }
hex = { version = "0.4.3", default-features=false }
mpu6050 = { git = "https://git.ank.dev/ank/mpu6050" }
vl53l0x = "1.0.1"
nalgebra = { version = "0.31.2", default-features=false, features = ["serde-serialize-no-std"] }
common = { path = "../common" }
[profile.release]

View file

@ -5,19 +5,24 @@
#![no_main]
#![allow(async_fn_in_trait)]
mod vl53l0;
mod sensor_manager;
use core::array;
use core::borrow::BorrowMut;
use core::cell::RefCell;
use core::fmt::Formatter;
use core::mem::transmute;
use core::panic::PanicInfo;
use core::str::from_utf8;
use bt_hci::cmd::info;
use cyw43_pio::PioSpi;
use cyw43::JoinOptions;
use cyw43_pio::{PioSpi, DEFAULT_CLOCK_DIVIDER};
use embassy_rp::i2c::{Async, I2c};
use embassy_rp::multicore::{spawn_core1, Stack};
use embassy_rp::pwm::{self, Pwm};
use embassy_sync::blocking_mutex::raw::{CriticalSectionRawMutex, ThreadModeRawMutex};
use embassy_sync::blocking_mutex::{Mutex, ThreadModeMutex};
use embassy_sync::channel::Channel;
use embedded_hal_bus::i2c::RefCellDevice;
use fixed::FixedU16;
use log::*;
@ -25,20 +30,22 @@ use log::*;
use embassy_executor::Spawner;
use embassy_net::tcp::TcpSocket;
use embassy_net::{Config, StackResources};
use embassy_rp::bind_interrupts;
use embassy_rp::{bind_interrupts, watchdog};
use embassy_rp::clocks::RoscRng;
use embassy_rp::gpio::{Level, Output};
use embassy_rp::gpio::{Input, Level, Output, Pull};
use embassy_rp::peripherals::{DMA_CH0, PIO0, USB};
use embassy_rp::pio::{InterruptHandler, Pio};
use embassy_rp::usb::Driver;
use embassy_time::{Delay, Duration, Timer};
use embedded_io_async::Write;
use embassy_time::{Delay, Duration, Instant, Timer};
use embedded_io_async::{Read, Write};
use mpu6050::Mpu6050;
use nalgebra::clamp;
use rand::RngCore;
use reqwless::response;
use sensor_manager::{sensor_manager, SensorHardware};
use common::{ControlPacket, SensorData, TelemetryPacket};
use static_cell::StaticCell;
use defmt_rtt as _;
use vl53l0::RegAddr::*;
bind_interrupts!(struct Irqs {
PIO0_IRQ_0 => InterruptHandler<PIO0>;
@ -47,6 +54,9 @@ bind_interrupts!(struct Irqs {
USBCTRL_IRQ => embassy_rp::usb::InterruptHandler<USB>;
});
static mut CORE1_STACK: Stack<4096> = Stack::new();
pub static CHANNEL: Channel<CriticalSectionRawMutex, (SensorData, Instant), 1> = Channel::new();
#[embassy_executor::task]
async fn logger_task(driver: Driver<'static, USB>) {
embassy_usb_logger::run!(1024, log::LevelFilter::Debug, driver);
@ -78,18 +88,24 @@ async fn main(spawner: Spawner) {
let driver = Driver::new(p.USB, Irqs);
spawner.spawn(logger_task(driver)).unwrap();
let mut flipper = Output::new(p.PIN_22, Level::Low);
let limit_switch = Input::new(p.PIN_16, Pull::Up);
let mut auto_status = Output::new(p.PIN_2, Level::High);
let mut c: pwm::Config = Default::default();
c.divider = 255.into();
c.top = 8715;
c.compare_b = 7210;
c.compare_a = 2240;
let mut pwm = Pwm::new_output_ab(p.PWM_SLICE1, p.PIN_18, p.PIN_19, c.clone());
flipper.set_high();
let mut d: pwm::Config = Default::default();
d.divider = 40.into();
d.top = 62500; // 20ms
d.compare_b = 4687; // 1.5ms
d.compare_a = 4687; // 1.5ms
let mut drive_pwm = Pwm::new_output_ab(p.PWM_SLICE1, p.PIN_18, p.PIN_19, d.clone());
let sda = p.PIN_20;
let scl = p.PIN_21;
let mut f: pwm::Config = Default::default();
f.divider = 1.into(); // no reason to slow down, this is going right into a mosfet
f.top = u16::MAX;
f.compare_b = 0;
let flip_pwm = Pwm::new_output_b(p.PWM_SLICE0, p.PIN_17, f.clone());
let sda = p.PIN_8;
let scl = p.PIN_9;
let config = embassy_rp::i2c::Config::default();
let bus = embassy_rp::i2c::I2c::new_async(p.I2C0, scl, sda, Irqs, config);
@ -97,47 +113,23 @@ async fn main(spawner: Spawner) {
let scl = p.PIN_27;
let config = embassy_rp::i2c::Config::default();
let bus1 = embassy_rp::i2c::I2c::new_async(p.I2C1, scl, sda, Irqs, config);
let bus1 = RefCell::new(bus1);
let tof_r_enable = Output::new(p.PIN_28, Level::Low);
let tof_l_enable = Output::new(p.PIN_22, Level::Low);
info!("made RefCell");
let hardware = SensorHardware {
bus_tof: unsafe {transmute(bus1)},
bus_gyro: unsafe {transmute(bus)},
tof_l_enable,
tof_r_enable,
};
let mut tof2on = Output::new(p.PIN_16, Level::Low);
info!("2");
Timer::after_millis(1).await;
let mut tof = vl53l0x::VL53L0x::new(RefCellDevice::new(&bus1)).unwrap();
info!("3");
tof.set_address(0x32).unwrap();
info!("4");
tof2on.set_high();
Timer::after_millis(13).await;
info!("5");
let mut tof2 = vl53l0x::VL53L0x::new(RefCellDevice::new(&bus1)).unwrap();
info!("6");
let mut gyro = Mpu6050::new_with_addr(bus,0x68);
Timer::after_millis(1300).await;
gyro.init(&mut Delay).unwrap();
gyro.set_gyro_range(mpu6050::device::GyroRange::D2000).unwrap();
gyro.set_accel_range(mpu6050::device::AccelRange::G16).unwrap();
info!("pinidtd");
Timer::after_millis(1300).await;
loop {
//info!("pos: {}", gyro.get_gyro().unwrap().x);
//info!("jerk: {}", gyro.get_acc().unwrap().x);
//info!("temp: {}", gyro.get_temp().unwrap() * (9./5.) + 32.);
if let Ok(dist) = tof.read_range_single_millimeters_blocking() {
info!("dist1: {dist}mm");
spawn_core1(
p.CORE1,
unsafe { &mut *core::ptr::addr_of_mut!(CORE1_STACK) },
move || {
sensor_manager(hardware)
}
Timer::after_millis(3).await;
if let Ok(dist) = tof2.read_range_single_millimeters_blocking() {
info!("dist2: {dist}mm");
}
Timer::after_millis(23).await;
}
);
let fw = include_bytes!("../../cyw43-firmware/43439A0.bin");
let clm = include_bytes!("../../cyw43-firmware/43439A0_clm.bin");
@ -152,7 +144,16 @@ async fn main(spawner: Spawner) {
let pwr = Output::new(p.PIN_23, Level::Low);
let cs = Output::new(p.PIN_25, Level::High);
let mut pio = Pio::new(p.PIO0, Irqs);
let spi = PioSpi::new(&mut pio.common, pio.sm0, pio.irq0, cs, p.PIN_24, p.PIN_29, p.DMA_CH0);
let spi = PioSpi::new(
&mut pio.common,
pio.sm0,
DEFAULT_CLOCK_DIVIDER,
pio.irq0,
cs,
p.PIN_24,
p.PIN_29,
p.DMA_CH0,
);
static STATE: StaticCell<cyw43::State> = StaticCell::new();
let state = STATE.init(cyw43::State::new());
@ -166,7 +167,7 @@ async fn main(spawner: Spawner) {
// Use a link-local address for communication without DHCP server
let config = Config::ipv4_static(embassy_net::StaticConfigV4 {
address: embassy_net::Ipv4Cidr::new(embassy_net::Ipv4Address::new(169, 254, 1, 1), 16),
address: embassy_net::Ipv4Cidr::new(embassy_net::Ipv4Address::new(192, 168, 1, 2), 16),
dns_servers: heapless::Vec::new(),
gateway: None,
});
@ -180,313 +181,44 @@ async fn main(spawner: Spawner) {
defmt::unwrap!(spawner.spawn(net_task(runner)));
//control.start_ap_open("cyw43", 5).await;
control.start_ap_wpa2("cyw43", "password", 5).await;
// password is not terribly private information
//control.start_ap_wpa2("cruisecontrol", "dxSk2avMFvsY", 5).await;
// And now we can use it!
loop {
match control
.join("cruisecontrol", JoinOptions::new("dxSk2avMFvsY".as_bytes()))
.await
{
Ok(_) => break,
Err(err) => {
info!("join failed with status={}", err.status);
}
}
}
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
let mut buf = [0; 4096];
let mut telem_buf = [0; 4096];
//embassy_time::Timer::after_millis(7000).await;
let cam_state: RefCell<CamState> = RefCell::new(CamState::Idle);
//async fn write_to_device<'a, T,const N: usize>(bus: &mut embassy_rp::i2c::I2c<'a, T,Async>, addr: u16, data: [[u8;2];N])
//where T: embassy_rp::i2c::Instance {
// for transaction in data {
// let _ = bus.write_async(addr, transaction).await;
// }
//}
//async fn write_flag<'a, T>(bus: &mut embassy_rp::i2c::I2c<'a, T,Async>, addr: u16, reg: u8, bit: u8, value: bool)
//where T: embassy_rp::i2c::Instance {
// let mut initial: [u8;1] = [0];
// let _ = bus.write_read_async(addr, [reg], &mut initial).await;
// let mask = 1 << bit;
// if value {
// initial[0] |= mask;
// } else {
// initial[0] &= !mask;
// }
// let _ = bus.write_async(addr, [reg, initial[0]]).await;
//}
//let id = 0x29;
//Timer::after_millis(50).await; // sensor boot
//write_to_device(&mut bus, id, [
// [0x88, 0x00],
// [0x80, 0x01],
// [0xFF, 0x01],
// [0x00, 0x00],
//]).await;
//let mut stop: [u8;1] = [0];
//let _ = bus.write_read_async(id, [0x91], &mut stop);
//write_to_device(&mut bus, id, [
// [0x00, 0x01],
// [0xFF, 0x00],
// [0x80, 0x00],
//]).await;
//
//// disable SIGNAL_RATE_MSRC (bit 1) and SIGNAL_RATE_PRE_RANGE (bit 4) limit checks
//write_flag(&mut bus, id, 0x60, 1, true).await;
//write_flag(&mut bus, id, 0x60, 4, true).await;
//let mega_counts_per_second = 0.25;
//let mega_counts_per_second: u16 = (mega_counts_per_second * (1<<7) as f64) as u16;
//let _ = bus.write_async(id, [FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT as u8,
// (mega_counts_per_second >> 8) as u8,
// (mega_counts_per_second & 255) as u8
//]).await;
//// get spad info
//let _ = bus.write_async(id, [SYSTEM_SEQUENCE_CONFIG as u8, 0xFF]).await;
//write_to_device(&mut bus, id , [
// [0x80, 0x01],
// [0xff, 0x01],
// [0x00, 0x00],
// [0xff, 0x06],
//]).await;
//write_flag(&mut bus, id, 0x83, 3, true).await;
//write_to_device(&mut bus, id , [
// [0xff, 0x07],
// [0x81, 0x01],
// [0x80, 0x01],
// [0x94, 0x6b],
// [0x83, 0x00],
//]).await;
//debug!("starting spad wait");
//loop {
// let mut wait: [u8;1] = [0];
// let _ = bus.write_read_async(id, [0x83], &mut wait).await;
// if wait[0] != 0 {
// break;
// }
// Timer::after_micros(5).await;
//}
//debug!("ended spad wait");
//let _ = bus.write_async(id, [0x83, 0x01]).await;
//let mut value: [u8;1] = [0];
//let _ = bus.write_read_async(id, [0x92], &mut value).await;
//write_to_device(&mut bus, id, [
// [0x81, 0x00],
// [0xff, 0x06],
//]).await;
//write_flag(&mut bus, id, 0x83, 3, false).await;
//write_to_device(&mut bus, id, [
// [0xff, 0x01],
// [0x00, 0x01],
// [0xff, 0x00],
// [0x80, 0x00],
//]).await;
//let count = value[0] & 0x7f;
//let is_aperture = value[0] & 0b10000000;
//let is_aperture = is_aperture != 0;
//// TODO: vl53l0x.py post line 200
//let mut spad_map: [u8;6]=[0;6];
//let _ = bus.write_read_async(id, [GLOBAL_CONFIG_SPAD_ENABLES_REF_0 as u8], &mut spad_map);
//write_to_device(&mut bus, id, [
// [0xff, 0x01],
// [DYNAMIC_SPAD_REF_EN_START_OFFSET as u8, 0x00],
// [DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD as u8, 0x2c],
// [0xff, 0x00],
// [DYNAMIC_SPAD_REF_EN_START_OFFSET as u8, 0xb4],
//]).await;
//let mut spads_enabled = 0;
//for i in 0..48 {
// if i < 12 && is_aperture || spads_enabled >= count {
// spad_map[i/8] &= !(1<< (i>>2));
// } else if (spad_map[i/8] & (1<< (i>>2))) != 0 {
// spads_enabled += 1;
// }
//}
//let mut spad_write: [u8;7] = [0;7];
//spad_write[0] = GLOBAL_CONFIG_SPAD_ENABLES_REF_0 as u8;
//spad_write[1..].clone_from_slice(&spad_map);
//let _ = bus.write_async(id, spad_write).await;
//
//write_to_device(&mut bus, id, [
// [0xFF, 0x01],
// [0x00, 0x00],
// [0xFF, 0x00],
// [0x09, 0x00],
// [0x10, 0x00],
// [0x11, 0x00],
// [0x24, 0x01],
// [0x25, 0xFF],
// [0x75, 0x00],
// [0xFF, 0x01],
// [0x4E, 0x2C],
// [0x48, 0x00],
// [0x30, 0x20],
// [0xFF, 0x00],
// [0x30, 0x09],
// [0x54, 0x00],
// [0x31, 0x04],
// [0x32, 0x03],
// [0x40, 0x83],
// [0x46, 0x25],
// [0x60, 0x00],
// [0x27, 0x00],
// [0x50, 0x06],
// [0x51, 0x00],
// [0x52, 0x96],
// [0x56, 0x08],
// [0x57, 0x30],
// [0x61, 0x00],
// [0x62, 0x00],
// [0x64, 0x00],
// [0x65, 0x00],
// [0x66, 0xA0],
// [0xFF, 0x01],
// [0x22, 0x32],
// [0x47, 0x14],
// [0x49, 0xFF],
// [0x4A, 0x00],
// [0xFF, 0x00],
// [0x7A, 0x0A],
// [0x7B, 0x00],
// [0x78, 0x21],
// [0xFF, 0x01],
// [0x23, 0x34],
// [0x42, 0x00],
// [0x44, 0xFF],
// [0x45, 0x26],
// [0x46, 0x05],
// [0x40, 0x40],
// [0x0E, 0x06],
// [0x20, 0x1A],
// [0x43, 0x40],
// [0xFF, 0x00],
// [0x34, 0x03],
// [0x35, 0x44],
// [0xFF, 0x01],
// [0x31, 0x04],
// [0x4B, 0x09],
// [0x4C, 0x05],
// [0x4D, 0x04],
// [0xFF, 0x00],
// [0x44, 0x00],
// [0x45, 0x20],
// [0x47, 0x08],
// [0x48, 0x28],
// [0x67, 0x00],
// [0x70, 0x04],
// [0x71, 0x01],
// [0x72, 0xFE],
// [0x76, 0x00],
// [0x77, 0x00],
// [0xFF, 0x01],
// [0x0D, 0x01],
// [0xFF, 0x00],
// [0x80, 0x01],
// [0x01, 0xF8],
// [0xFF, 0x01],
// [0x8E, 0x01],
// [0x00, 0x01],
// [0xFF, 0x00],
// [0x80, 0x00],
// [SYSTEM_INTERRUPT_CONFIG_GPIO as u8, 0x04],
//]).await;
////write_flag(&mut bus, id, GPIO_HV_MUX_ACTIVE_HIGH as u8, 4, false).await;
////let _ = bus.write_async(id, [SYSTEM_SEQUENCE_CONFIG as u8, 0x01]).await;
////calibrate(&mut bus, id, 0x40).await;
////let _ = bus.write_async(id, [SYSTEM_SEQUENCE_CONFIG as u8, 0x02]).await;
////calibrate(&mut bus, id, 0x00).await;
////let _ = bus.write_async(id, [SYSTEM_SEQUENCE_CONFIG as u8, 0xe8]).await;
//async fn calibrate<'a, T>(bus: &mut embassy_rp::i2c::I2c<'a, T,Async>, addr: u16, data: u8)
//where T: embassy_rp::i2c::Instance {
// let _ = bus.write_async(addr, [SYSRANGE_START as u8 ,data | 0x01]).await;
// debug!("started calib wait");
// loop {
// let mut wait: [u8;1] = [0];
// let _ = bus.write_read_async(addr, [0x13], &mut wait).await;
// if wait[0] & 0x07 != 0 {
// break;
// }
// Timer::after_micros(5).await;
// }
// debug!("ended calib wait");
// write_to_device(bus, addr, [
// [SYSTEM_INTERRUPT_CLEAR as u8, 0x01],
// [SYSRANGE_START as u8, 0x00],
// ]).await;
//}
////TODO VL53L0X.cpp L 236-280
//// start continuous mode
//write_to_device(&mut bus, id, [
// [0x80, 0x01],
// [0xFF, 0x01],
// [0x00, 0x00],
// [0x91, stop[0]],
// [0x00, 0x01],
// [0xFF, 0x00],
// [0x80, 0x00],
// //[0x04, 0x00], // measurement delay
// [0x00, 0x02], // back to back shots
//]).await;
////let _ = bus.write_async(0x88u16, [0x00]).await;
////let _ = bus.write_async(0x80u16, [0x01]).await;
////let _ = bus.write_async(0xFFu16, [0x01]).await;
////let _ = bus.write_async(0x00u16, [0x00]).await;
////let _ = bus.write_async(0x00u16, [0x01]).await;
////let _ = bus.write_async(0xFFu16, [0x00]).await;
////let _ = bus.write_async(0x80u16, [0x00]).await;
//
////loop {
//// debug!("starting wait part 1");
//// loop {
//// let mut wait: [u8;1] = [0];
//// let _ = bus.write_read_async(id, [SYSRANGE_START as u8], &mut wait).await;
//// debug!("{wait:?}");
//// if wait[0] & 0x01 != 0 {
//// break;
//// }
//// Timer::after_micros(5).await;
//// }
//// debug!("starting wait part 2");
//// loop {
//// let mut wait: [u8;1] = [0];
//// let _ = bus.write_read_async(id, [RESULT_INTERRUPT_STATUS as u8], &mut wait).await;
//// if wait[0] & 0x07 != 0 {
//// break;
//// }
//// Timer::after_micros(5).await;
//// }
//// debug!("ending wait part 2");
//// let mut output: [u8; 2] = [0;2];
//// let _ = bus.write_read_async(id, [0x14], &mut output).await;
//// let _ = bus.write_async(id, [0x0B, 0x01]).await;
//// info!("out: {:?}",output);
//// Timer::after_millis(20).await;
////}
let cam_state_forever = unsafe { transmute(&cam_state) }; // SAFETY: if main exits we shall
// shortly die.
spawner.spawn(cam_manager(flip_pwm, limit_switch, cam_state_forever)).unwrap();
loop {
let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(Duration::from_secs(3)));
let mut c: pwm::Config = Default::default();
c.divider = 255.into();
c.top = 8715;
c.compare_b = 0;
c.compare_a = 0;
pwm.set_config(&c);
c.divider = 40.into();
c.top = 62500; // 20ms
c.compare_b = 4687; // 1.5ms
c.compare_a = 4687; // 1.5ms
drive_pwm.set_config(&c);
flipper.set_low();
cam_state.replace(CamState::Idle);
control.gpio_set(0, false).await;
info!("Listening on TCP:1234...");
@ -499,85 +231,158 @@ async fn main(spawner: Spawner) {
control.gpio_set(0, true).await;
loop {
let mut n = match socket.read(&mut buf).await {
Ok(0) => {
warn!("read EOF");
break;
}
Ok(n) => n,
Err(e) => {
warn!("read error: {:?}", e);
break;
}
};
info!("rxd {}", from_utf8(&buf[..n]).unwrap());
Timer::after_millis(30).await;
let mut segs = buf[..n].trim_ascii().split(|c| *c == ' ' as u8);
match char::from_u32(segs.next().unwrap()[0] as u32).unwrap() {
'W' => {
let addr: [u8;1] = hex::FromHex::from_hex(segs.next().unwrap()).unwrap();
let reg: [u8;1] = hex::FromHex::from_hex(segs.next().unwrap()).unwrap();
let data: [u8;1] = hex::FromHex::from_hex(segs.next().unwrap()).unwrap();
info!("writing {:?}", reg);
Timer::after_millis(30).await;
bus.write_async(addr[0] as u16, [reg[0], data[0]]).await.unwrap();
buf[0] = b"O"[0];
buf[1] = b"K"[0];
n=2;
},
'R' => {
let addr: [u8;1] = hex::FromHex::from_hex(segs.next().unwrap()).unwrap();
let reg: [u8;1] = hex::FromHex::from_hex(segs.next().unwrap()).unwrap();
info!("writing {:?}, addr {addr:?}", reg);
let mut response: [u8;2] = [0;2];
let _ = bus.write_read_async(addr[0] as u16, reg, &mut response).await;
info!("recd {:?}", response);
info!("recd {:#02x}", response[0]);
let _ = hex::encode_to_slice(response, &mut buf);
n = 4;
},
'D' => {
let left: [u8;2] = hex::FromHex::from_hex(segs.next().unwrap()).unwrap();
let right: [u8;2] = hex::FromHex::from_hex(segs.next().unwrap()).unwrap();
info!("left {:?}, right {left:?}", right);
let left = u16::from_be_bytes(left);
c.compare_a = left;
let right = u16::from_be_bytes(right);
c.compare_b = right;
info!("left {:?}, right {left:?}", right);
pwm.set_config(&c);
},
'F' => {
flipper.set_high();
},
'L' => {
flipper.set_low();
},
_ => {}
let mut len: [u8; 4] = [0;4];
if let Err(e) = socket.read_exact(&mut len).await {
warn!("read err: {e:?}");
break;
}
let len = u32::from_be_bytes(len) as usize;
let data = &mut buf[0..len];
if let Err(e) = socket.read_exact(data).await {
warn!("read err: {e:?}");
break;
}
//let mut response: [u8;2] = [0;2];
if let Ok(data) = postcard::from_bytes::<ControlPacket>(&data) {
info!("got {data:?}");
match data {
ControlPacket::Twist(forward, right) => {
info!("left to {}", clamp(forward+right, -1., 1.));
info!("right to {}", clamp(forward-right, -1., 1.));
//let _ = bus.read_async(0xC0u16, &mut response).await;
//let _ = hex::encode_to_slice(response, &mut buf);
c.compare_a = calc_speed(-forward - right);
c.compare_b = calc_speed(-forward + right);
drive_pwm.set_config(&c);
},
ControlPacket::Fire => {
cam_state.replace(CamState::Fire);
},
ControlPacket::Stop => {
c.compare_a = calc_speed(0.);
c.compare_b = calc_speed(0.);
drive_pwm.set_config(&c);
match socket.write_all(&buf[..n]).await {
Ok(()) => {}
Err(e) => {
warn!("write error: {:?}", e);
break;
cam_state.replace(CamState::Idle);
},
ControlPacket::FireOverride(speed) => {
cam_state.replace(CamState::Override(speed));
},
ControlPacket::SetAuto(state) => {
auto_status.set_level(Level::from(state));
},
ControlPacket::Arm(enable) => {
if enable {
cam_state.replace(CamState::Charging);
} else {
cam_state.replace(CamState::Idle);
}
}
d => {error!("unimplemented: {d:?}")} // TODO
}
};
}
if let Ok((data, _ts)) = CHANNEL.try_receive() {
let telem = TelemetryPacket {
sensors: data,
cam_state: cam_state.borrow().to_telem(),
};
if let Ok(telem) = postcard::to_slice(&telem, &mut telem_buf) {
if let Err(e) = socket.write_all(&u32::to_be_bytes(telem.len() as u32)).await {
warn!("write error: {:?}", e);
break;
}
if let Err(e) = socket.write_all(&telem).await {
warn!("write error: {:?}", e);
break;
}
//if let Err(e) = socket.flush().await {
// warn!("write error: {:?}", e);
// break;
//}
}
}
}
}
}
/// 0 to 1
fn calc_speed_mosfet(speed: f32) -> u16 {
let speed = speed.clamp(0., 1.);
let speed = speed * u16::MAX as f32;
speed as u16
}
/// -1 to 1
fn calc_speed(speed: f32) -> u16 {
const COUNTS_PER_MS: f32 = 3125.;
let speed = speed.clamp(-1., 1.);
let ms = (speed/2.0)+1.5;
(COUNTS_PER_MS * ms) as u16
}
#[derive(Debug)]
enum CamState {
Override(f32),
Charging,
Charged,
Fire,
Idle,
}
impl CamState {
fn to_telem(&self) -> common::CamState {
match self {
Self::Override(_) | Self::Fire => common::CamState::Firing,
Self::Charging => common::CamState::Charging,
Self::Charged => common::CamState::Charged,
Self::Idle => common::CamState::Idle,
}
}
}
#[embassy_executor::task]
async fn cam_manager(mut cam: Pwm<'static>, limit: Input<'static>, cam_state: &'static RefCell<CamState>) {
loop {
let mut cam_state = cam_state.borrow_mut();
handle_cam(&mut cam, &mut (*cam_state), &limit);
drop(cam_state);
Timer::after_micros(500).await;
}
}
fn handle_cam(cam: &mut Pwm, state: &mut CamState, limit: &Input) {
let speed = match state {
CamState::Override(speed) => {
*speed
},
CamState::Charging => {
if limit.is_low() {
*state = CamState::Charged;
0.0
} else {
1.0
}
},
CamState::Fire => {
if limit.is_high() {
*state = CamState::Charging;
}
1.0
},
CamState::Charged | CamState::Idle => 0.0,
};
let mut f: pwm::Config = Default::default();
f.divider = 1.into();
f.top = u16::MAX;
f.compare_b = calc_speed_mosfet(speed);
cam.set_config(&f);
}

View file

@ -0,0 +1,117 @@
use core::sync::atomic::{AtomicU8, Ordering};
use core::task::Poll;
use core::{cell::RefCell, mem::transmute};
use common::SensorData;
use embassy_executor::Executor;
use embassy_rp::peripherals::{I2C0, I2C1};
use embassy_time::{Delay, Duration, Instant, Timer};
use embassy_rp::gpio::Output;
use embassy_rp::i2c::{Async, I2c};
use embedded_hal_bus::i2c::RefCellDevice;
use log::{error, info};
use mpu6050::Mpu6050;
use nalgebra::Vector3;
use crate::CHANNEL;
pub struct SensorHardware {
pub bus_tof: I2c<'static, I2C1, Async>,
pub bus_gyro: I2c<'static, I2C0, Async>,
pub tof_l_enable: Output<'static>,
pub tof_r_enable: Output<'static>,
}
pub fn sensor_manager(hardware: SensorHardware) -> ! {
let mut executor = Executor::new();
let executor: &'static mut Executor = unsafe{transmute(&mut executor)};
executor.run(move |spawner| {
spawner.spawn(init_sensors(hardware)).unwrap();
});
}
static POLL_STATE: AtomicU8 = AtomicU8::new(PollState::None as u8);
#[repr(u8)]
enum PollState {
None,
Tof,
Gyro,
}
#[embassy_executor::task]
async fn init_sensors(mut hardware: SensorHardware) {
let bus = RefCell::new(hardware.bus_tof);
Timer::after_millis(1).await;
let mut tof_s = vl53l0x::VL53L0x::new(RefCellDevice::new(&bus)).ok();
if let Some(ref mut tof_s) = tof_s {
tof_s.set_address(0x32).unwrap();
}
hardware.tof_l_enable.set_high();
Timer::after_micros(1200).await; // DS11555 3.2
let mut tof_l = vl53l0x::VL53L0x::new(RefCellDevice::new(&bus)).ok();
if let Some(ref mut tof_l) = tof_l {
tof_l.set_address(0x33).unwrap();
}
hardware.tof_r_enable.set_high();
Timer::after_micros(1200).await; // DS11555 3.2
let mut tof_r = vl53l0x::VL53L0x::new(RefCellDevice::new(&bus)).ok();
if let Some(ref mut tof_r) = tof_r {
tof_r.set_address(0x34).unwrap();
}
info!("initting gyro");
let mut gyro = Mpu6050::new_with_addr(hardware.bus_gyro,0x68);
let mut gyro_alive = true;
match gyro.init(&mut Delay) {
Ok(()) => {
gyro.set_gyro_range(mpu6050::device::GyroRange::D2000).unwrap_or_else(|_| gyro_alive = false);
gyro.set_accel_range(mpu6050::device::AccelRange::G16).unwrap_or_else(|_| gyro_alive = false);
info!("init gyro");
}
e => {
error!("gyro init err: {e:?}");
}
}
let mut data = SensorData {
tof_l: None,
tof_r: None,
tof_s: None,
gyro: None,
accel: None,
};
loop {
POLL_STATE.store(PollState::Tof as u8, Ordering::SeqCst);
for (tof, store) in
[(&mut tof_s, &mut data.tof_s), (&mut tof_l, &mut data.tof_l), (&mut tof_r, &mut data.tof_r)] {
if let Some(ref mut tof) = tof {
if let Ok(dist) = tof.read_range_single_millimeters_blocking() {
*store = Some(dist);
} else {
*store = None;
}
Timer::after_millis(3).await;
}
}
if gyro_alive {
POLL_STATE.store(PollState::Gyro as u8, Ordering::SeqCst);
if let Ok(gyro) = gyro.get_gyro() {
info!("rotation: {gyro}");
data.gyro = Some(gyro);
}
if let Ok(accel) = gyro.get_acc() {
data.accel = Some(accel);
}
}
POLL_STATE.store(PollState::None as u8, Ordering::SeqCst);
info!("sensors: {data:?}");
CHANNEL.send((data.clone(), Instant::now())).await;
}
}

View file

@ -1,91 +0,0 @@
use core::ops::Deref;
#[repr(u8)]
pub enum RegAddr
{
SYSRANGE_START = 0x00,
SYSTEM_THRESH_HIGH = 0x0C,
SYSTEM_THRESH_LOW = 0x0E,
SYSTEM_SEQUENCE_CONFIG = 0x01,
SYSTEM_RANGE_CONFIG = 0x09,
SYSTEM_INTERMEASUREMENT_PERIOD = 0x04,
SYSTEM_INTERRUPT_CONFIG_GPIO = 0x0A,
GPIO_HV_MUX_ACTIVE_HIGH = 0x84,
SYSTEM_INTERRUPT_CLEAR = 0x0B,
RESULT_INTERRUPT_STATUS = 0x13,
RESULT_RANGE_STATUS = 0x14,
RESULT_CORE_AMBIENT_WINDOW_EVENTS_RTN = 0xBC,
//RESULT_CORE_RANGING_TOTAL_EVENTS_RTN = 0xC0,
RESULT_CORE_AMBIENT_WINDOW_EVENTS_REF = 0xD0,
RESULT_CORE_RANGING_TOTAL_EVENTS_REF = 0xD4,
RESULT_PEAK_SIGNAL_RATE_REF = 0xB6,
ALGO_PART_TO_PART_RANGE_OFFSET_MM = 0x28,
I2C_SLAVE_DEVICE_ADDRESS = 0x8A,
MSRC_CONFIG_CONTROL = 0x60,
PRE_RANGE_CONFIG_MIN_SNR = 0x27,
PRE_RANGE_CONFIG_VALID_PHASE_LOW = 0x56,
PRE_RANGE_CONFIG_VALID_PHASE_HIGH = 0x57,
PRE_RANGE_MIN_COUNT_RATE_RTN_LIMIT = 0x64,
FINAL_RANGE_CONFIG_MIN_SNR = 0x67,
FINAL_RANGE_CONFIG_VALID_PHASE_LOW = 0x47,
FINAL_RANGE_CONFIG_VALID_PHASE_HIGH = 0x48,
FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT = 0x44,
PRE_RANGE_CONFIG_SIGMA_THRESH_HI = 0x61,
PRE_RANGE_CONFIG_SIGMA_THRESH_LO = 0x62,
PRE_RANGE_CONFIG_VCSEL_PERIOD = 0x50,
PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI = 0x51,
PRE_RANGE_CONFIG_TIMEOUT_MACROP_LO = 0x52,
SYSTEM_HISTOGRAM_BIN = 0x81,
HISTOGRAM_CONFIG_INITIAL_PHASE_SELECT = 0x33,
HISTOGRAM_CONFIG_READOUT_CTRL = 0x55,
FINAL_RANGE_CONFIG_VCSEL_PERIOD = 0x70,
FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI = 0x71,
FINAL_RANGE_CONFIG_TIMEOUT_MACROP_LO = 0x72,
CROSSTALK_COMPENSATION_PEAK_RATE_MCPS = 0x20,
MSRC_CONFIG_TIMEOUT_MACROP = 0x46,
SOFT_RESET_GO2_SOFT_RESET_N = 0xBF,
IDENTIFICATION_MODEL_ID = 0xC0,
IDENTIFICATION_REVISION_ID = 0xC2,
OSC_CALIBRATE_VAL = 0xF8,
GLOBAL_CONFIG_VCSEL_WIDTH = 0x32,
GLOBAL_CONFIG_SPAD_ENABLES_REF_0 = 0xB0,
GLOBAL_CONFIG_SPAD_ENABLES_REF_1 = 0xB1,
GLOBAL_CONFIG_SPAD_ENABLES_REF_2 = 0xB2,
GLOBAL_CONFIG_SPAD_ENABLES_REF_3 = 0xB3,
GLOBAL_CONFIG_SPAD_ENABLES_REF_4 = 0xB4,
GLOBAL_CONFIG_SPAD_ENABLES_REF_5 = 0xB5,
//GLOBAL_CONFIG_REF_EN_START_SELECT = 0xB6,
DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD = 0x4E,
DYNAMIC_SPAD_REF_EN_START_OFFSET = 0x4F,
POWER_MANAGEMENT_GO1_POWER_FORCE = 0x80,
VHV_CONFIG_PAD_SCL_SDA__EXTSUP_HV = 0x89,
ALGO_PHASECAL_LIM = 0x30,
//ALGO_PHASECAL_CONFIG_TIMEOUT = 0x30,
}
struct Vl53l0x {
}

1
interface/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
target

5329
interface/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

28
interface/Cargo.toml Normal file
View file

@ -0,0 +1,28 @@
[package]
name = "interface"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1.0.95"
cpal = "0.15.3"
pitch-detection = "0.3"
postcard = { version = "1.1.1", features = ["alloc", "use-std"] }
rust-music-theory = {git = "https://github.com/the-drunk-coder/rust-music-theory", rev = "a062d65"}
serde = { version = "1.0.217", features = ["derive"] }
tokio = { version = "1.43.0", features = ["full"] }
common = {path = "../common"}
heapless = "0.7.0"
eframe = { version = "0.30", features = ["persistence"] }
egui_extras = { version = "0.30", features = ["default", "image"] }
egui-toast = "0.16.0"
home = "0.5.11"
atomic_float = "1.1.0"
chrono = "0.4.40"
image = "0.25.5"
libloading = "0.8.6"
emath = "0.31.1"
dashmap = { version = "6.1.0", features = ["serde"] }
directories = "6.0.0"
ping-rs = "0.1.2"

BIN
interface/assets/lizard.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

182
interface/src/auto.rs Normal file
View file

@ -0,0 +1,182 @@
use std::{future::Future, ops::{Deref, Range}, pin::Pin, sync::{atomic::{AtomicBool, Ordering}, Arc}, thread::sleep, time::Duration};
use common::{CamState, ControlPacket, SensorData, TelemetryPacket};
use anyhow::{anyhow, Ok, Result};
use libloading::{Library, Symbol};
use tokio::{sync::watch, task::JoinHandle};
use crate::storage::StorageManager;
#[derive(Clone)]
pub struct AutoInterface {
command_sender: watch::Sender<ControlPacket>,
data_receiver: watch::Receiver<TelemetryPacket>,
config: StorageManager,
enabled: Arc<AtomicBool>,
enable_permission: Arc<AtomicBool>,
}
impl AutoInterface {
/// new
///
/// returns command channel from auto, enable status
pub fn new(data: watch::Receiver<TelemetryPacket>, config: StorageManager, enable_permission: Arc<AtomicBool>) -> (Self, watch::Receiver<ControlPacket>, Arc<AtomicBool>) {
let (commands, receiver) = watch::channel(ControlPacket::Fire);
let enabled = Arc::new(AtomicBool::new(false));
let interface = Self {
command_sender: commands,
data_receiver: data,
config,
enabled: enabled.clone(),
enable_permission,
};
(interface, receiver, enabled)
}
pub fn subscribe(&self) -> watch::Receiver<ControlPacket> {
self.command_sender.subscribe()
}
/// change active command, fails if not in control
pub fn run_command(&self, command: ControlPacket) -> Result<()> {
self.command_sender.send(command)?;
Ok(())
}
pub fn sensor_data(&mut self) -> SensorData {
self.data_receiver.borrow_and_update().sensors.clone()
}
pub fn cam_state(&mut self) -> CamState {
self.data_receiver.borrow_and_update().cam_state.clone()
}
pub async fn sensor_update(&mut self) -> SensorData {
self.data_receiver.changed().await.unwrap();
self.data_receiver.borrow().sensors.clone()
}
pub fn sensor_update_blocking(&mut self) -> SensorData {
loop {
if self.data_receiver.has_changed().unwrap() {
break;
}
sleep(Duration::from_millis(10)); // TODO: exponential or condvars
}
self.data_receiver.borrow_and_update().sensors.clone()
}
/// disable auto
pub fn disable(&mut self) {
self.enabled.store(false, Ordering::Release);
}
/// request auto enable, fails if the driver does not grant it
pub fn enable(&mut self) -> Result<()> {
if self.enable_permission.load(Ordering::Acquire) {
self.enabled.store(true, Ordering::Release);
Ok(())
} else {
Err(anyhow!("no enable"))?
}
}
pub fn enabled(&self) -> bool { self.enabled.load(Ordering::Acquire) }
pub fn conf(&self, key: &'static Configurable) -> f32 {
self.config.load(key)
}
}
pub struct Configurable {
pub name: &'static str,
pub description: Option<&'static str>,
pub default: f32,
pub min: f32,
pub max: f32,
}
impl Configurable {
pub const fn new(name: &'static str) -> Self {
Self { name, description: None, default: 0.0, min: 0.0, max: 1.0 }
}
pub const fn range(self, range: Range<f32>) -> Self {
Self { min: range.start, max: range.end, ..self }
}
pub const fn description(self, description: &'static str) -> Self {
Self { description: Some(description), ..self }
}
pub const fn default(self, default: f32) -> Self {
Self { default, ..self }
}
pub const fn name(&'static self) -> &'static str {
self.name
}
}
impl Deref for Configurable {
type Target = str;
fn deref(&self) -> &Self::Target {
self.name
}
}
impl Default for Configurable {
fn default() -> Self {
Self { name: Default::default(), description: Default::default(), default: Default::default(), min: 0.0, max: 1.0 }
}
}
pub struct Auto {
library: Arc<Library>,
// these aren't actually static, they have the same lifetime as the library xP
configs: &'static [Configurable],
name: &'static str,
}
impl Auto {
pub fn new(path: &str) -> Result<Self> {
let lib = unsafe {Library::new(path)?};
let lib = Arc::new(lib);
let configurations: Symbol<&&[Configurable]> = unsafe {lib.get(b"CONFIGS").unwrap()};
let name: Symbol<&&'static str> = unsafe {lib.get(b"NAME").unwrap()};
Ok(Self {
configs: *configurations,
name: *name,
library: lib,
})
}
/// entrypoint
pub fn run(&self, interface: AutoInterface) -> Result<()> {
let func: Symbol<unsafe extern "C" fn(AutoInterface) -> ()> = unsafe {self.library.get(b"entry")?};
unsafe { func(interface.clone()) };
Ok(())
}
pub fn configs(&self) -> &'static [Configurable] {
self.configs
}
pub fn name(&self) -> &'static str {
self.name
}
}
pub fn get_confs() -> Result<()> {
let lib = unsafe {Library::new("../auto/target/release/libauto.so")?};
let configurations: Symbol<&&[Configurable]> = unsafe {lib.get(b"CONFIGS").unwrap()};
for config in configurations.iter() {
println!("co {}", config.name);
println!("co {:?}", config.description);
}
let name: Symbol<&&'static str> = unsafe {lib.get(b"NAME").unwrap()};
println!("na {:?}", *name);
Ok(())
}

186
interface/src/auto_impl.rs Normal file
View file

@ -0,0 +1,186 @@
use std::{collections::VecDeque, future::Future, ops::Sub, pin::Pin};
use common::CamState;
use tokio::time::Instant;
use crate::auto::{AutoInterface, Configurable};
#[unsafe(no_mangle)]
pub fn entry(interface: AutoInterface) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin(auto(interface))
}
#[unsafe(no_mangle)]
pub static NAME: &'static str = "scanseek v1";
const AUTO_GAP: Configurable = Configurable::new("auto minimum gap").range(0. .. 300.).default(140.)
.description("distance (mm) distance measurements must instantaneously drop to indicate a detection. This should line up with the size of the smallest robot you compete against");
const AUTO_SELF_OCCLUSION: Configurable = Configurable::new("auto self occlusion").range(0. .. 200.).default(143.)
.description("distance (mm) below which measurements are considered noise in the scan phase");
const AUTO_CONVERGENCE_POINT: Configurable = Configurable::new("auto convergence").range(100. .. 300.).default(190.)
.description("distance (mm) where the tof beams intersect");
const AUTO_SEEK_RANGE: Configurable = Configurable::new("auto seek range").range(200. .. 8000.).default(500.);
#[unsafe(no_mangle)]
pub static CONFIGS: &[Configurable] = &[
AUTO_GAP,
AUTO_SELF_OCCLUSION,
AUTO_CONVERGENCE_POINT,
AUTO_SEEK_RANGE,
];
pub async fn auto(mut interface: AutoInterface) {
let mut tof_l = Stats::new();
let mut tof_r = Stats::new();
loop {
let data = interface.sensor_update().await;
let cam = interface.cam_state();
let CamState::Charged = cam else {
continue;
};
let Some(latest_tof_l) = data.tof_l else {
continue;
};
tof_l.update(latest_tof_l as i16);
let Some(latest_tof_r) = data.tof_r else {
continue;
};
tof_r.update(latest_tof_r as i16);
let auto_gap = interface.conf(&AUTO_GAP);
let auto_self_occlusion = interface.conf(&AUTO_SELF_OCCLUSION);
let auto_range = interface.conf(&AUTO_SEEK_RANGE);
let detection = |latest: u16, delta: i16| {
-delta > auto_gap as i16 &&
latest > auto_self_occlusion as u16 &&
latest < auto_range as u16
};
if dbg!(detection(latest_tof_l, tof_l.delta())) || dbg!(detection(latest_tof_r, dbg!(tof_r.delta()))) {
if let Ok(()) = interface.enable() {
println!("found, now seek");
seek(interface.clone(), &mut tof_l, &mut tof_r).await;
} else {
println!("requested enable")
}
}
}
}
async fn seek(mut interface: AutoInterface, tof_l: &mut Stats<i16>, tof_r: &mut Stats<i16>) {
let crossover = interface.conf(&AUTO_CONVERGENCE_POINT) as i16;
let range = interface.conf(&AUTO_SEEK_RANGE) as i16;
let mut timeout = Instant::now();
loop {
let data = interface.sensor_data();
data.tof_l.map(|d| tof_l.update(d as i16));
data.tof_r.map(|d| tof_r.update(d as i16));
if data.tof_l.is_none() || data.tof_r.is_none() {
return;
}
let left_near = tof_l.latest() < crossover && tof_l.delta() < 70;
let right_near = tof_r.latest() < crossover && tof_r.delta() < 70;
let left_far = tof_l.latest() > crossover && tof_l.latest() < range && tof_l.delta() < 70;
let right_far = tof_r.latest() > crossover && tof_r.latest() < range && tof_r.delta() < 70;
let near = left_near || right_near;
let far = !near && (left_far || right_far);
if !(near || far) {
if timeout.elapsed().as_millis() > 1200 {
return;
}
} else {
timeout = Instant::now();
}
let mut twist = 0.0;
if near {
// if one is beyond the convergence point use far logic
if tof_l.max().max(tof_r.max()) >
interface.conf(&AUTO_CONVERGENCE_POINT) as i16 {
if right_near {
twist = -0.7;
} else if left_near {
twist = 0.7;
}
} else {
// go towards the further side
let mut diff = tof_l.max() - tof_r.max();
diff = diff.max(-100).min(100);
twist = (diff as f32) / 150.;
}
} else if far {
if tof_r.max() - tof_l.max() > 100 {
twist = 0.7; // right high, go right
}
if tof_l.max() - tof_r.max() > 100 {
twist = -0.7; // left high, go left
}
}
if should_fire(&tof_l, &tof_r) {
let _ = interface.run_command(common::ControlPacket::Fire);
println!("fired");
return;
}
let _ = interface.run_command(common::ControlPacket::Twist(1.0, twist));
interface.sensor_update_blocking();
}
}
fn should_fire(left: &Stats<i16>, right: &Stats<i16>) -> bool {
left.latest() < 70 && left.latest() > 20 && left.delta() < 60 &&
right.latest() < 70 && right.latest() > 20 && right.delta() < 60
}
struct Stats<T> {
table: VecDeque<T>
}
impl<T: Copy> Stats<T> {
pub fn new() -> Self {
Self { table: VecDeque::new() }
}
const MAX_ELEMENTS: usize = 3;
pub fn update(&mut self, elem: T) {
self.table.push_front(elem);
if self.table.len() > Self::MAX_ELEMENTS {
self.table.pop_back();
}
}
/// panics if no values have been written
pub fn latest(&self) -> T {
self.table.front().unwrap().to_owned()
}
}
impl<T: Ord + Sub<Output = T> + Copy + From<u8>> Stats<T> {
pub fn delta(&self) -> T {
*self.table.get(0).unwrap_or(&T::from(0)) - *self.table.get(1).unwrap_or(&T::from(0))
}
pub fn max(&self) -> T {
*self.table.iter().max().unwrap_or(&T::from(0))
}
pub fn min(&self) -> T {
*self.table.iter().max().unwrap_or(&T::from(0))
}
}

View file

@ -0,0 +1,40 @@
use std::{path::Path, time::{Duration, SystemTime, UNIX_EPOCH}};
use anyhow::Ok;
use common::{ControlPacket, TelemetryPacket};
use serde::{Deserialize, Serialize};
use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc::Receiver, time::Instant};
#[derive(Serialize, Deserialize)]
pub enum CombatData {
Telemetry(TelemetryPacket),
Control(ControlPacket),
}
type CombatLogRow = (CombatData, u128);
pub async fn combat_logger(mut data: Receiver<CombatData>, path: &Path) -> anyhow::Result<()> {
let mut path = path.to_path_buf();
let time = chrono::offset::Utc::now();
let formatted = time.to_rfc3339_opts(chrono::SecondsFormat::Secs, false);
path.push(format!("{formatted}.combatlog"));
let mut file = File::options().create(true).append(true).open(path).await?;
let mut save = Instant::now();
while let Some(packet) = data.recv().await {
let time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_micros();
let vec = postcard::to_stdvec(&(packet, time))?;
file.write_u64(vec.len() as u64).await?;
file.write_all(&vec).await?;
if save.elapsed() > Duration::from_secs(30) {
save = Instant::now();
file.sync_all().await?;
}
}
Ok(())
}

164
interface/src/gui.rs Normal file
View file

@ -0,0 +1,164 @@
use std::{cell::OnceCell, collections::HashMap, path::PathBuf, sync::{atomic::{AtomicBool, Ordering}, Arc}, time::Duration};
use common::{ControlPacket, TelemetryPacket};
use eframe::{egui::{self, containers, Align2, Checkbox, Context, IconData, Id, ImageSource, Label, Ui}, Storage};
use image::ImageFormat;
use tokio::{runtime::Runtime, sync::{mpsc, watch::{self, Receiver}}};
use egui_toast::{Toast, Toasts};
use crate::{auto::Configurable, auto_impl::CONFIGS, storage::StorageManager, PingData, POWER_THRESHOLD, RECONNECT};
pub const GUI: OnceCell<Context> = OnceCell::new();
pub fn gui(data: Receiver<GUIData>, toasts: mpsc::Receiver<Toast>, executor: Runtime, autoconf: watch::Receiver<&'static [Configurable]>, storage: StorageManager, auto_allowed: Arc<AtomicBool>, auto_enabled: Arc<AtomicBool>, ping: PingData) -> eframe::Result {
let icon = egui::include_image!("../assets/lizard.png");
let icon = image::load_from_memory_with_format(include_bytes!("../assets/lizard.png"), ImageFormat::Png).unwrap();
let icon = IconData {
width: icon.width(),
height: icon.height(),
rgba: icon.into_rgba8().into_raw(),
};
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_inner_size([700.0, 480.0])
.with_app_id("cruisecontrol")
.with_icon(icon),
..Default::default()
};
eframe::run_native(
"Cruise Control Dashboard",
options,
Box::new(|cc| {
// This gives us image support:
egui_extras::install_image_loaders(&cc.egui_ctx);
Ok(Box::new(GUI::with_receivers(data, toasts, executor, storage, autoconf, auto_allowed, auto_enabled, ping)))
}),
)
}
#[derive(Default)]
pub struct GUIData {
pub telemetry: Option<TelemetryPacket>,
pub last_command: Option<ControlPacket>,
}
#[cfg(target_os = "linux")]
pub const DEFAULT_VOLUME_THRESHOLD: f32 = 5.0;
#[cfg(target_os = "windows")]
pub const DEFAULT_VOLUME_THRESHOLD: f32 = 1.0;
const VOLUME_THRESHOLD: Configurable = Configurable::new("Volume").range(0.0..10.).default(DEFAULT_VOLUME_THRESHOLD)
.description("higher accepts less noise (better)");
const DEFAULT_TURN_GAIN: f32 = 0.3;
const DEFAULT_FIRE_DISTANCE: f32 = 55.0;
struct GUI {
data: Receiver<GUIData>,
toasts: mpsc::Receiver<Toast>,
executor: Option<Runtime>,
selected_auto: usize,
autoconf: watch::Receiver<&'static [Configurable]>,
storage: StorageManager,
auto_allowed: Arc<AtomicBool>,
auto_enabled: Arc<AtomicBool>,
ping: PingData,
}
impl GUI {
fn with_receivers(data: Receiver<GUIData>, toasts: mpsc::Receiver<Toast>, executor: Runtime, storage: StorageManager, autoconf: watch::Receiver<&'static [Configurable]>, auto_allowed: Arc<AtomicBool>, auto_enabled: Arc<AtomicBool>, ping: PingData) -> Self {
Self {
data,
toasts,
executor: Some(executor),
selected_auto: 0,
autoconf,
storage,
auto_allowed,
auto_enabled,
ping,
}
}
}
impl eframe::App for GUI {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let _ = GUI.set(ctx.clone());
egui::SidePanel::right(Id::new("config")).resizable(false).show(ctx, |ui| {
ui.heading("configuration");
configurator(ui, &VOLUME_THRESHOLD, &self.storage);
ui.horizontal(|ui| {
egui::ComboBox::new("auto selector", "select auto")
.show_index(ui, &mut self.selected_auto, 3, |n| ["a","b","c"][n]);
ui.button("refresh").clicked();
});
POWER_THRESHOLD.store(self.storage.load(&VOLUME_THRESHOLD), Ordering::Relaxed);
for conf in CONFIGS {
configurator(ui, conf, &self.storage);
}
});
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("Cruise Control");
if !RECONNECT.load(Ordering::Acquire) {
if ui.button("disconnect").clicked() {
RECONNECT.store(true, Ordering::Release);
}
}
if let Ok(ping) = self.ping.try_read() {
ui.horizontal(|ui| {
ui.label(format!("router: {}", if let Some(rtt) = ping.0 {format!("✅ {rtt}ms")} else {"❌".into()}));
ui.label(format!("robot: {}", if let Some(rtt) = ping.1 {format!("✅ {rtt}ms")} else {"❌".into()}));
});
}
if let Some(ref command) = self.data.borrow().last_command {
ui.label(format!("sending {command:?}"));
}
ui.horizontal(|ui| {
ui.label(format!("auto authorized: {}", if self.auto_allowed.load(Ordering::Acquire) {"✅"} else {"❌"}));
ui.label(format!("auto running: {}", if self.auto_enabled.load(Ordering::Acquire) {"✅ zoom vroom"} else {"❌"}));
});
if let Some(ref telem) = self.data.borrow().telemetry {
ui.label(format!("Left tof: {}", if let Some(tof) = telem.sensors.tof_l {format!("✅ {tof}mm")} else {"❌".into()}));
ui.label(format!("Right tof: {}", if let Some(tof) = telem.sensors.tof_r {format!("✅ {tof}mm")} else {"❌".into()}));
ui.label(format!("Side tof: {}", if let Some(tof) = telem.sensors.tof_s {format!("✅ {tof}mm")} else {"❌".into()}));
ui.label(format!("Gyro: {}", if telem.sensors.gyro.is_some() {"✅"} else {"❌"}));
ui.label(format!("Cam: {:?}", telem.cam_state));
} else {
ui.label("disconnected");
}
});
let mut toasts = Toasts::new()
.anchor(Align2::RIGHT_BOTTOM, (-10.0, -10.0)) // 10 units from the bottom right corner
.direction(egui::Direction::BottomUp);
while let Ok(toast) = self.toasts.try_recv() {
toasts.add(toast);
}
toasts.show(ctx);
if ctx.input(|i| i.viewport().close_requested()) {
self.executor.take().unwrap().shutdown_timeout(Duration::from_millis(100));
}
}
}
fn configurator(ui: &mut Ui, config: &'static Configurable, map: &StorageManager) {
ui.add(egui::Slider::from_get_set(config.min as f64 ..= config.max as f64, map.get_set(config)).text(config.name));
if let Some(description) = config.description {
ui.label(description);
}
}

Some files were not shown because too many files have changed in this diff Show more