feat: Basic frontend

This commit is contained in:
Baud 2024-05-03 18:23:21 +01:00
parent a61eb0734d
commit ee375e34a8
25 changed files with 3241 additions and 84 deletions

6
.cargo/config.toml Normal file
View File

@ -0,0 +1,6 @@
# clipboard api is still unstable, so web-sys requires the below flag to be passed for copy (ctrl + c) to work
# https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html
# check status at https://developer.mozilla.org/en-US/docs/Web/API/Clipboard#browser_compatibility
# we don't use `[build]` because of rust analyzer's build cache invalidation https://github.com/emilk/eframe_template/issues/93
[target.wasm32-unknown-unknown]
rustflags = ["--cfg=web_sys_unstable_apis"]

2
.gitignore vendored
View File

@ -1,4 +1,2 @@
.direnv .direnv
target/ target/
node_modules/
index.js

3
.typos.toml Normal file
View File

@ -0,0 +1,3 @@
[default.extend-words]
egui = "egui"
hyperdeck = "hyperdeck"

2800
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,12 @@
[package] [workspace]
name = "hyperdeck-monitor" members = [
version = "0.1.0" "monitor",
edition = "2021" "frontend"
]
resolver = "2"
[dependencies] [profile.release]
color-eyre = "0.6.3" opt-level = 2
futures-util = "0.3.30"
serde = { version = "1.0.199", features = ["derive"] } [profile.dev.package."*"]
serde_json = "1.0.116" opt-level = 2
tokio = { version = "1.37.0", features = ["full"] }
tokio-tungstenite = "0.21.0"
tokio-util = "0.7.10"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
url = "2.5.0"

View File

@ -51,11 +51,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1714356894, "lastModified": 1714616033,
"narHash": "sha256-W6Mss7AG6bnFT1BqRApHXvLXBrFOu7V0+EUe9iML30s=", "narHash": "sha256-JcWAjIDl3h0bE/pII0emeHwokTeBl+SWrzwrjoRu7a0=",
"owner": "oxalica", "owner": "oxalica",
"repo": "rust-overlay", "repo": "rust-overlay",
"rev": "d9b44509b4064f0a3fc9c7c92a603861f52fbedc", "rev": "3e416d5067ba31ff8ac31eeb763e4388bdf45089",
"type": "github" "type": "github"
}, },
"original": { "original": {

View File

@ -27,6 +27,9 @@
nativeBuildInputs = with pkgs; [ nativeBuildInputs = with pkgs; [
rustToolchain rustToolchain
nodejs nodejs
trunk
typos
trunk
]; ];
buildInputs = with pkgs; [ buildInputs = with pkgs; [
rustToolchain rustToolchain

7
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
# trunk output folder
dist
# Rust compile target directories:
target
target_ra
target_wasm

26
frontend/Cargo.toml Normal file
View File

@ -0,0 +1,26 @@
[package]
name = "hyperdeck_monitor_gui"
version = "0.1.0"
edition = "2021"
[dependencies]
egui = "0.27.0"
eframe = { version = "0.27.0", default-features = false, features = [
"accesskit", # Make egui comptaible with screen readers.
"default_fonts", # Embed the default egui fonts.
"glow", # Use the glow rendering backend. Alternative: "wgpu".
"persistence", # Enable restoring app state when restarting the app.
] }
log = "0.4"
serde = { version = "1", features = ["derive"] }
hrtime = "0.2.0"
wasm-timer = "0.2.5"
# native:
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
env_logger = "0.10"
# web:
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen-futures = "0.4"

1
frontend/Trunk.toml Normal file
View File

@ -0,0 +1 @@
[build]

View File

@ -0,0 +1,11 @@
{
"name": "Hyperdeck Monitor",
"short_name": "Hyperdeck Monitor",
"icons": [],
"lang": "en-GB",
"id": "/index.html",
"start_url": "./index.html",
"display": "standalone",
"background_color": "white",
"theme_color": "white"
}

25
frontend/assets/sw.js Normal file
View File

@ -0,0 +1,25 @@
var cacheName = 'hyperdeck-monitor-pwa';
var filesToCache = [
'./',
'./index.html',
'./hyperdeck_monitor.js',
'./hyperdeck_monitor_bg.wasm',
];
/* Start the service worker and cache all of the app's content */
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open(cacheName).then(function (cache) {
return cache.addAll(filesToCache);
})
);
});
/* Serve cached content when offline */
self.addEventListener('fetch', function (e) {
e.respondWith(
caches.match(e.request).then(function (response) {
return response || fetch(e.request);
})
);
});

129
frontend/index.html Normal file
View File

@ -0,0 +1,129 @@
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<head>
<title>Hyperdeck Monitor</title>
<!-- config for our rust wasm binary. go to https://trunkrs.dev/assets/#rust for more customization -->
<link data-trunk rel="rust" data-wasm-opt="2" data-bin="hyperdeck_monitor_gui" />
<!-- this is the base url relative to which other urls will be constructed. trunk will insert this from the public-url option -->
<base data-trunk-public-url />
<link data-trunk rel="copy-file" href="assets/sw.js" />
<link data-trunk rel="copy-file" href="assets/manifest.json" />
<link rel="manifest" href="manifest.json">
<meta name="theme-color" media="(prefers-color-scheme: light)" content="white">
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#404040">
<style>
html {
/* Remove touch delay: */
touch-action: manipulation;
}
body {
/* Light mode background color for what is not covered by the egui canvas,
or where the egui canvas is translucent. */
background: #909090;
}
@media (prefers-color-scheme: dark) {
body {
/* Dark mode background color for what is not covered by the egui canvas,
or where the egui canvas is translucent. */
background: #404040;
}
}
/* Allow canvas to fill entire web page: */
html,
body {
overflow: hidden;
margin: 0 !important;
padding: 0 !important;
height: 100%;
width: 100%;
}
/* Position canvas in center-top: */
canvas {
margin-right: auto;
margin-left: auto;
display: block;
position: absolute;
top: 0%;
left: 50%;
transform: translate(-50%, 0%);
}
.centered {
margin-right: auto;
margin-left: auto;
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #f0f0f0;
font-size: 24px;
font-family: Ubuntu-Light, Helvetica, sans-serif;
text-align: center;
}
/* ---------------------------------------------- */
/* Loading animation from https://loading.io/css/ */
.lds-dual-ring {
display: inline-block;
width: 24px;
height: 24px;
}
.lds-dual-ring:after {
content: " ";
display: block;
width: 24px;
height: 24px;
margin: 0px;
border-radius: 50%;
border: 3px solid #fff;
border-color: #fff transparent #fff transparent;
animation: lds-dual-ring 1.2s linear infinite;
}
@keyframes lds-dual-ring {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<!-- The WASM code will resize the canvas dynamically -->
<!-- the id is hardcoded in main.rs . so, make sure both match. -->
<canvas id="the_canvas_id"></canvas>
<!--Register Service Worker. this will cache the wasm / js scripts for offline use (for PWA functionality). -->
<!-- Force refresh (Ctrl + F5) to load the latest files instead of cached files -->
<script>
// We disable caching during development so that we always view the latest version.
if ('serviceWorker' in navigator && window.location.hash !== "#dev") {
window.addEventListener('load', function () {
navigator.serviceWorker.register('sw.js');
});
}
</script>
</body>
</html>
<!-- Powered by egui: https://github.com/emilk/egui/ -->

218
frontend/src/app.rs Normal file
View File

@ -0,0 +1,218 @@
use std::{
fmt::Display,
net::{IpAddr, Ipv4Addr},
};
use egui::{Color32, RichText, Sense, Stroke, Vec2};
use wasm_timer::Instant;
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(default)]
pub struct HyperdeckMonitorApp {
#[serde(skip)]
blink: bool,
#[serde(skip)]
last_blink_change: Instant,
#[serde(skip)]
new_hyperdeck_ip: String,
#[serde(skip)]
new_hyperdeck_name: String,
#[serde(skip)]
hyperdecks: Vec<Hyperdeck>,
}
impl Default for HyperdeckMonitorApp {
fn default() -> Self {
Self {
blink: false,
last_blink_change: Instant::now(),
new_hyperdeck_ip: "".to_owned(),
new_hyperdeck_name: "".to_owned(),
hyperdecks: vec![
Hyperdeck {
name: "Test Hyperdeck 1".to_string(),
ip: IpAddr::V4(Ipv4Addr::new(192, 168, 10, 1)),
status: HyperdeckStatus::Connected,
recording_bays: vec![HyperdeckRecordBay {
status: RecordingStatus::NotRecording,
storage_capacity_mb: 500_000,
recording_time_remaining: TimeRemaining(60),
}],
},
Hyperdeck {
name: "Test Hyperdeck 2".to_string(),
ip: IpAddr::V4(Ipv4Addr::new(192, 168, 10, 2)),
status: HyperdeckStatus::Disconnected,
recording_bays: vec![HyperdeckRecordBay {
status: RecordingStatus::NotRecording,
storage_capacity_mb: 500_000,
recording_time_remaining: TimeRemaining(3600 * 5), // 5 Hours
}],
},
],
}
}
}
impl HyperdeckMonitorApp {
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
// Load previous app state (if any)
if let Some(storage) = cc.storage {
return eframe::get_value(storage, eframe::APP_KEY).unwrap_or_default();
}
Default::default()
}
}
impl eframe::App for HyperdeckMonitorApp {
fn save(&mut self, storage: &mut dyn eframe::Storage) {
eframe::set_value(storage, eframe::APP_KEY, self);
}
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::TopBottomPanel::top("top_panel").show(ctx, |ui| {
egui::menu::bar(ui, |ui| {
egui::widgets::global_dark_light_mode_buttons(ui);
});
});
egui::CentralPanel::default().show(ctx, |ui| {
add_hyperdeck_panel(ui, &mut self.new_hyperdeck_ip, &mut self.new_hyperdeck_name);
ui.separator();
ui.vertical(|ui| {
hyperdeck_list(ui, &self.hyperdecks, self.blink);
});
ui.with_layout(egui::Layout::bottom_up(egui::Align::LEFT), |ui| {
connection_status(ui);
egui::warn_if_debug_build(ui);
});
});
if self.last_blink_change.elapsed().as_secs() >= 1 {
self.blink = !self.blink;
println!("BLINK");
self.last_blink_change = Instant::now();
}
egui::Context::request_repaint(ctx);
}
}
fn add_hyperdeck_panel(
ui: &mut egui::Ui,
new_hyperdeck_ip: &mut String,
new_hyperdeck_name: &mut String,
) {
ui.heading("Add hyperdeck");
ui.horizontal(|ui| {
ui.label("Name");
ui.text_edit_singleline(new_hyperdeck_name);
ui.label("IP");
ui.text_edit_singleline(new_hyperdeck_ip);
if ui.button("Add").clicked() {
// Do Something
}
});
}
fn hyperdeck_list(ui: &mut egui::Ui, hyperdecks: &[Hyperdeck], blink: bool) {
for hyperdeck in hyperdecks {
ui.vertical(|ui| {
ui.horizontal(|ui| {
let status_colour = match hyperdeck.status {
HyperdeckStatus::Connected => Color32::GREEN,
HyperdeckStatus::Disconnected => Color32::RED,
};
let (response, painter) =
ui.allocate_painter(Vec2 { x: 16.0, y: 16.0 }, Sense::hover());
let rect = response.rect;
let c = rect.center();
let r = (rect.width() / 2.0) * 0.8;
painter.circle(c, r, status_colour, Stroke::NONE);
let hyperdeck_heading: RichText =
format!("{} [{}]", hyperdeck.name, hyperdeck.ip).into();
ui.heading(hyperdeck_heading.strong());
});
if !hyperdeck.recording_bays.is_empty()
&& matches!(hyperdeck.status, HyperdeckStatus::Connected)
{
let recording_bays_text: RichText = "Recording Bays".into();
ui.label(recording_bays_text.size(16.0).strong());
for (index, bay) in hyperdeck.recording_bays.iter().enumerate() {
ui.horizontal(|ui| {
let bay_label: RichText = format!("Bay {}", index + 1).into();
ui.label(bay_label.strong());
match bay.status {
RecordingStatus::Recording => ui.label("Recording"),
RecordingStatus::NotRecording => ui.label("Not Recording"),
};
ui.label(format!(
"Total Storage Capacity: {}GB",
bay.storage_capacity_mb / 1000,
));
let time_remaining_text: RichText =
format!("Time remaining: {}", bay.recording_time_remaining).into();
if bay.recording_time_remaining.0 > 15 * 60 || !blink {
ui.label(time_remaining_text);
} else {
ui.label(time_remaining_text.color(Color32::RED));
};
});
}
}
ui.separator();
});
}
}
fn connection_status(ui: &mut egui::Ui) {
ui.horizontal(|ui| {
// TODO: Make it real
ui.label("Connected");
});
}
#[derive(serde::Deserialize, serde::Serialize)]
struct Hyperdeck {
name: String,
ip: IpAddr,
status: HyperdeckStatus,
recording_bays: Vec<HyperdeckRecordBay>,
}
#[derive(serde::Deserialize, serde::Serialize)]
enum HyperdeckStatus {
Connected,
Disconnected,
}
#[derive(serde::Deserialize, serde::Serialize)]
struct HyperdeckRecordBay {
status: RecordingStatus,
/// Storage capacity in MB.
storage_capacity_mb: u64,
/// Recording time available in seconds.
recording_time_remaining: TimeRemaining,
}
#[derive(serde::Deserialize, serde::Serialize)]
struct TimeRemaining(u64);
impl Display for TimeRemaining {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let time = hrtime::from_sec_padded(self.0);
write!(f, "{time}")
}
}
#[derive(serde::Deserialize, serde::Serialize)]
enum RecordingStatus {
Recording,
NotRecording,
}

2
frontend/src/lib.rs Normal file
View File

@ -0,0 +1,2 @@
mod app;
pub use app::HyperdeckMonitorApp;

34
frontend/src/main.rs Normal file
View File

@ -0,0 +1,34 @@
#[cfg(not(target_arch = "wasm32"))]
fn main() -> eframe::Result<()> {
env_logger::init();
let native_options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_inner_size([400.0, 300.0])
.with_min_inner_size([300.0, 220.0]),
..Default::default()
};
eframe::run_native(
"eframe template",
native_options,
Box::new(|cc| Box::new(hyperdeck_monitor_gui::HyperdeckMonitorApp::new(cc))),
)
}
#[cfg(target_arch = "wasm32")]
fn main() {
eframe::WebLogger::init(log::LevelFilter::Debug).ok();
let web_options = eframe::WebOptions::default();
wasm_bindgen_futures::spawn_local(async {
eframe::WebRunner::new()
.start(
"the_canvas_id", // Where to draw to.
web_options,
Box::new(|cc| Box::new(hyperdeck_monitor_gui::HyperdeckMonitorApp::new(cc))),
)
.await
.expect("failed to start eframe");
});
}

2
monitor/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
node_modules/
index.js

18
monitor/Cargo.toml Normal file
View File

@ -0,0 +1,18 @@
[package]
name = "hyperdeck-monitor"
version = "0.1.0"
edition = "2021"
default-run = "hyperdeck-monitor"
[dependencies]
color-eyre = "0.6.3"
futures-util = "0.3.30"
serde = { version = "1.0.199", features = ["derive"] }
serde_json = "1.0.116"
tokio = { version = "1.37.0", features = ["full"] }
tokio-tungstenite = "0.21.0"
tokio-util = "0.7.10"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
url = "2.5.0"

View File

@ -7,7 +7,6 @@
"": { "": {
"name": "hyperdeck-monitor", "name": "hyperdeck-monitor",
"version": "1.0.0", "version": "1.0.0",
"license": "ISC",
"dependencies": { "dependencies": {
"hyperdeck-connection": "^2.0.1", "hyperdeck-connection": "^2.0.1",
"ws": "^8.17.0" "ws": "^8.17.0"

View File

@ -40,7 +40,7 @@ async fn main() {
async fn run_node_process(cancel: CancellationToken) { async fn run_node_process(cancel: CancellationToken) {
while !cancel.is_cancelled() { while !cancel.is_cancelled() {
let result = tokio::process::Command::new("node") let result = tokio::process::Command::new("node")
.arg("index.js") .arg("monitor/index.js")
.output() .output()
.await; .await;
if let Ok(output) = result { if let Ok(output) = result {

View File

@ -1,3 +1,4 @@
[toolchain] [toolchain]
channel = "stable" channel = "stable"
components = [ "rust-src", "cargo", "rustc" ] components = [ "rust-src", "cargo", "rustc", "clippy", "rustfmt" ]
targets = [ "wasm32-unknown-unknown" ]