Skip to content

Commit

Permalink
feat: add unattended mode
Browse files Browse the repository at this point in the history
  • Loading branch information
zabackary committed Sep 29, 2024
1 parent 97e9a2e commit 36a20c4
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 8 deletions.
27 changes: 24 additions & 3 deletions src/backend/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::{
use daktronics_allsport_5000::{sports::Sport, RTDState};
use latency_graph::{LatencyGraphData, LatencySample, SerialEvent};
use tokio::{
select,
sync::{
mpsc::{self, Receiver},
Mutex,
Expand All @@ -19,6 +20,8 @@ use crate::APP_USER_AGENT;

use super::{network::put_to_server, profile::Profile};

const MAX_SERIAL_PACKET_DELAY: u64 = 3000;

mod latency_graph {
use std::time::{Duration, Instant};

Expand Down Expand Up @@ -77,6 +80,10 @@ pub struct ActiveStream {

impl ActiveStream {
pub fn new(profile: Profile, tty_path: String) -> Result<Self, Box<dyn Error>> {
eprintln!(
"INFO stream Creating stream bound to {} with profile {}",
tty_path, profile.name
);
let (worker_event_tx, worker_event_rx) = mpsc::channel(255);

// allow because cargo gets suspicious on Windows
Expand Down Expand Up @@ -105,7 +112,14 @@ impl ActiveStream {
tokio::task::spawn(async move {
loop {
// get the underlying rtd_state to update it
let has_new_data = sport.rtd_state().update_async().await;
let has_new_data = select! {
result = sport.rtd_state().update_async() => {
result.map_err(Some)
},
() = tokio::time::sleep(Duration::from_millis(MAX_SERIAL_PACKET_DELAY)) => {
Err(None)
}
};

match has_new_data {
Ok(true) => match sport.serialize_to_value() {
Expand Down Expand Up @@ -139,12 +153,16 @@ impl ActiveStream {
Ok(false) => {
// don't bother to update if nothing changed
}
Err(err) => worker_event_tx
Err(Some(err)) => worker_event_tx
.send(WorkerEvent::ErrorEvent(
format!("failed to update RTD state: {err}").into(),
))
.await
.expect("worker event tx closed!"),
Err(None) => worker_event_tx
.send(WorkerEvent::ErrorEvent("timeout when waiting for new score data from the serial connection".to_owned().into()))
.await
.expect("worker event tx closed!"),
}
tokio::task::yield_now().await;
}
Expand Down Expand Up @@ -285,7 +303,10 @@ impl ActiveStream {
event: WorkerEvent,
) {
match event {
WorkerEvent::ErrorEvent(err) => errors.push(err),
WorkerEvent::ErrorEvent(err) => {
eprintln!("WARN stream {}", err.msg);
errors.push(err)
}
WorkerEvent::LatencySampleEvent(
sample,
new_latest_payload,
Expand Down
47 changes: 44 additions & 3 deletions src/frontend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ pub struct DaktronicsSingularUiApp {
pub dark_mode: bool,
pub sport_type_keys: Vec<String>,
pub hide_header: bool,
pub unattended: Option<usize>,
pub initial_tty_path: Option<String>,
}

fn use_dark_mode() -> bool {
Expand All @@ -45,6 +47,8 @@ impl Default for DaktronicsSingularUiApp {
dark_mode: use_dark_mode(),
sport_type_keys: vec![],
hide_header: false,
unattended: None,
initial_tty_path: None,
}
}
}
Expand Down Expand Up @@ -309,6 +313,28 @@ impl DaktronicsSingularUiApp {
Message::UpdateStreamStatsResponse(events) => match self.screen {
Screen::Stream(ref mut active_stream) => {
active_stream.update_from_events(events);
if self.unattended.is_some()
&& self.initial_tty_path.is_some()
&& active_stream.errors().len() > self.unattended.unwrap()
{
eprintln!(
"ERR frontend Stream will be restarted due to volume of errors ({}) exceeding configured value ({}) (unattended mode)",
active_stream.errors().len(),
self.unattended.unwrap()
);
match ActiveStream::new(
self.profile.clone(),
self.initial_tty_path.as_ref().expect("no tty path").clone(),
) {
Ok(stream) => {
self.screen = Screen::Stream(stream);
eprintln!("INFO frontend Restarted stream successfully");
}
Err(err) => {
eprintln!("ERR frontend Failed to restart stream: {}", err);
}
}
}
Task::done(Message::UpdateStreamStats)
}
_ => Task::none(),
Expand Down Expand Up @@ -526,11 +552,26 @@ impl DaktronicsSingularUiApp {
)
.style(|theme: &iced::Theme| {
let palette = theme.extended_palette();
container::Style {
text_color: Some(palette.secondary.base.text),
background: Some(palette.secondary.base.color.into()),
let error_state = match &self.screen {
Screen::Stream(stream) => stream.errors().len() > 0,
_ => false
};
let base_style = container::Style {
border: iced::Border { color: iced::Color::TRANSPARENT, width: 0.0, radius: Radius::new(0.0).bottom(8.0) },
..Default::default()
};
if error_state {
container::Style {
text_color: Some(palette.danger.base.text),
background: Some(palette.danger.base.color.into()),
..base_style
}
} else {
container::Style {
text_color: Some(palette.secondary.base.text),
background: Some(palette.secondary.base.color.into()),
..base_style
}
}
})
.into()
Expand Down
16 changes: 14 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,19 @@ struct Args {
#[arg(short, long, default_value_t = false)]
fullscreen: bool,

/// Whether to hide the header
/// Whether to hide the header and show a minimized video
///
/// Useful for small display sizes
#[arg(long, default_value_t = false)]
hide_header: bool,

/// Enable unattended mode, restarting automatically if there are many
/// errors
///
/// Passing a number indicates the maximum tolerated error count. Default 3.
/// Max 15.
#[arg(short, long, default_missing_value = "3", require_equals = true, num_args = 0..1)]
unattended: Option<usize>,
}

enum DSUError {
Expand Down Expand Up @@ -195,7 +205,7 @@ fn main() -> Result<(), DSUError> {
) {
Ok(stream) => frontend::Screen::Stream(stream),
Err(err) => {
eprintln!("couldn't start stream: {}", err);
eprintln!("ERR main Couldn't start stream: {}", err);
immediately_exit = true;
frontend::Screen::Welcome
}
Expand All @@ -210,6 +220,8 @@ fn main() -> Result<(), DSUError> {
profile: profile.clone(),
screen,
hide_header: args.hide_header,
initial_tty_path: args.serial_path.clone(),
unattended: args.unattended,
..Default::default()
},
iced::Task::batch([
Expand Down

0 comments on commit 36a20c4

Please sign in to comment.