minor progress

This commit is contained in:
Nickiel12 2024-09-11 01:17:41 +00:00
parent 66aa62de98
commit c5880964e7
7 changed files with 90 additions and 45 deletions

View file

@ -11,9 +11,8 @@ use vcs_common::ApplicationMessage;
use crate::config::AppConfig;
use crate::APP_HANDLE;
mod satellite_connection;
mod joystick_source;
mod satellite_connection;
use joystick_source::joystick_loop;
use satellite_connection::SatelliteConnection;
@ -21,6 +20,7 @@ use satellite_connection::SatelliteConnection;
pub enum ApplicationEvent {
WebRTCMessage((String, vcs_common::ApplicationMessage)),
JoystickMove(Point),
RetryDisconnectedSatellites,
Close,
}
@ -82,7 +82,7 @@ impl AppState {
}
}
pub fn check_alive_things(&mut self) {
pub async fn check_alive_things(&mut self) {
if !self
.joystick_task_is_alive
.load(std::sync::atomic::Ordering::SeqCst)
@ -92,6 +92,14 @@ impl AppState {
Arc::clone(&self.joystick_task_is_alive),
));
}
for i in self
.camera_satellites
.iter_mut()
.filter(|x| !x.is_connected() && x.try_connecting)
{
i.connect(self.runtime.clone()).await
}
}
}
@ -104,39 +112,51 @@ pub async fn run_main_event_loop(
) {
let mut state = AppState::new(mec, to_mec, config, rt).await;
loop {
state.check_alive_things();
state.check_alive_things().await;
match state.mec.try_recv() {
Err(TryRecvError::Empty) => tokio::time::sleep(Duration::from_millis(50)).await,
Err(TryRecvError::Closed) => break,
Ok(msg) => match msg {
ApplicationEvent::Close => {
state.mec.close(); // cleanup is handled on reading from a closed mec
}
ApplicationEvent::WebRTCMessage((name, msg)) => {
for conn in state
.camera_satellites
.iter_mut()
.filter(|x| x.name == name && x.is_connected())
{
if let Err(_) = conn.send(msg.clone()).await {
error!("The websocket gave an error when I tried to send a message! I hope your logging is good enough");
Ok(msg) => {
match msg {
ApplicationEvent::Close => {
state.mec.close(); // cleanup is handled on reading from a closed mec
}
ApplicationEvent::RetryDisconnectedSatellites => {
state
.camera_satellites
.iter_mut()
.filter(|x| !x.is_connected() && !x.try_connecting)
.for_each(|x| {
x.try_connecting = true;
x.retry_attempts = 0;
});
}
ApplicationEvent::WebRTCMessage((name, msg)) => {
for conn in state
.camera_satellites
.iter_mut()
.filter(|x| x.name == name && x.is_connected())
{
if let Err(_) = conn.send(msg.clone()).await {
error!("The websocket gave an error when I tried to send a message! I hope your logging is good enough");
}
}
}
}
ApplicationEvent::JoystickMove(coord) => {
if let Some(target) = state.target_satellite {
if state.camera_satellites.len() < target {
if let Err(e) = state.camera_satellites[target]
.send(ApplicationMessage::ManualMovementOverride((
coord.x, coord.y,
)))
.await
{
error!("There was an error sending the joystick movement message to the target! {:?}", e);
ApplicationEvent::JoystickMove(coord) => {
if let Some(target) = state.target_satellite {
if state.camera_satellites.len() < target {
if let Err(e) = state.camera_satellites[target]
.send(ApplicationMessage::ManualMovementOverride((
coord.x, coord.y,
)))
.await
{
error!("There was an error sending the joystick movement message to the target! {:?}", e);
}
} else {
error!("That was not a valid target! Need to notifiy the UI about this");
}
} else {
error!("That was not a valid target! Need to notifiy the UI about this");
}
}
}
@ -147,16 +167,19 @@ pub async fn run_main_event_loop(
match connection.try_next().await {
Some(msg) => match msg {
ApplicationMessage::NameRequest(None) => {
if let Err(e) = connection.send(ApplicationMessage::NameRequest(Some("Controller".to_owned()))).await {
if let Err(e) = connection
.send(ApplicationMessage::NameRequest(Some(
"Controller".to_owned(),
)))
.await
{
info!("Was not able to send name to remote? {:?}", e);
}
}
ApplicationMessage::NameRequest(Some(name)) => connection.name = name,
ApplicationMessage::ChangeTrackingID(_) => {}
ApplicationMessage::ManualMovementOverride(_) => {}
ApplicationMessage::TrackingBoxes(_update) => {
}
ApplicationMessage::TrackingBoxes(_update) => {}
ApplicationMessage::WebRTCIceCandidateInit(pkt) => {
send_frontend_message(serde_json::to_string(&pkt).unwrap())
@ -164,10 +187,10 @@ pub async fn run_main_event_loop(
ApplicationMessage::WebRTCIceCandidate(pkt) => {
send_frontend_message(serde_json::to_string(&pkt).unwrap())
}
ApplicationMessage::WebRTCPacket(pkt) => {
ApplicationMessage::WebRTCPacket(pkt) => {
send_frontend_message(serde_json::to_string(&pkt).unwrap())
}
}
},
None => {}
}
}
@ -187,13 +210,13 @@ pub async fn run_main_event_loop(
pub fn send_frontend_message(message: String) {
if let Ok(mut e) = APP_HANDLE.lock() {
if e.is_none() {
if e.is_none() {
return;
} else {
let handle = e.take().unwrap();
handle.emit_all("frontend_message", message)
handle
.emit_all("frontend_message", message)
.expect("Could not send message to the tauri frontend!");
}
}
}

View file

@ -15,6 +15,8 @@ pub enum SatelliteConnectionError {
pub struct SatelliteConnection {
pub name: String,
pub retry_attempts: usize,
pub try_connecting: bool,
connection: ConnectionString,
to_socket: Option<AppSender>,
@ -29,6 +31,9 @@ impl SatelliteConnection {
name: String::new(),
connection: conn_string.clone(),
retry_attempts: 0,
try_connecting: true,
to_socket: None,
from_socket: None,
socket_is_alive: Arc::new(AtomicBool::new(false)),
@ -66,9 +71,14 @@ impl SatelliteConnection {
self.socket_is_alive = is_alive;
}
Err(e) => {
self.retry_attempts += 1;
if self.retry_attempts > 5 {
self.try_connecting = false;
}
error!(
"Could not connect to socket remote: '{}' \n {}",
"Could not connect to socket remote: '{}' \nRetry Attempt: {} \n {}",
self.connection.build_conn_string(),
self.retry_attempts,
e
);
}

View file

@ -57,6 +57,7 @@ fn main() {
let rt = runtime::Runtime::new().expect("Could not start tokio runtime");
let handle = rt.handle().clone();
let handle2 = handle.clone();
let _coordinator = rt.handle().spawn(run_main_event_loop(
mec,
@ -71,6 +72,7 @@ fn main() {
tauri::Builder::default()
.manage(tauri_functions::TauriState {
to_mec: to_mec.clone(),
rt: handle2.clone(),
})
.invoke_handler(tauri::generate_handler![tauri_functions::connect_to_camera])
.setup(|app| {
@ -102,7 +104,12 @@ fn main() {
};
if message.is_some() {
if let Err(e) = to_mec.send_blocking(ApplicationEvent::WebRTCMessage(("first".to_owned(), message.unwrap()))) {
if let Err(e) =
to_mec.send_blocking(ApplicationEvent::WebRTCMessage((
"first".to_owned(),
message.unwrap(),
)))
{
error!("Could not send to mec! {e}");
}
}

View file

View file

@ -1,16 +1,20 @@
use async_channel::Sender;
use tauri::State;
use tokio::runtime::Handle;
use tracing::info;
use crate::coordinator::ApplicationEvent;
pub struct TauriState {
pub to_mec: Sender<ApplicationEvent>,
pub rt: Handle,
}
#[tauri::command]
pub fn connect_to_camera(state: State<'_, TauriState>) {
let _ = state
.to_mec
.send_blocking(ApplicationEvent::CameraConnectionPress);
let mec = state.to_mec.clone();
state.rt.spawn(async move{
let _ = mec
.send_blocking(ApplicationEvent::RetryDisconnectedSatellites);
});
}

View file

@ -30,7 +30,7 @@
<div class="flex flex-row h-dvh w-100 text-neutral-400">
<div class="flex flex-col bg-neutral-300 h-dvh w-1/8">
<button id="camera_connect_button" onclick="call_camera_connect()" class="rounded-full font-semibold mx-3 mt-2 px-4 py-2 text-white bg-cyan-600">Connect to Camera</button>
<button id="camera_connect_button" class="rounded-full font-semibold mx-3 mt-2 px-4 py-2 text-white bg-cyan-600">Connect to Camera</button>
<button class="rounded-full font-semibold mx-3 mt-2 px-4 py-2 text-white bg-cyan-600">Connect to Computer</button>

View file

@ -1,4 +1,4 @@
const { invoke } = window.__TAURI__.tauri;
import { invoke } from "./@tauri-apps/api/index.js";
import { rtc_init } from "./rtc.js";
function call_camera_connect() {
@ -15,6 +15,7 @@ function call_camera_connect() {
async function init() {
console.log("Setting up");
document.getElementById("camera_connect_button").addEventListener("click", call_camera_connect);
await rtc_init();
}