Skip to content

Commit

Permalink
Create watcher
Browse files Browse the repository at this point in the history
  • Loading branch information
timmo001 committed Jun 7, 2024
1 parent dc675a5 commit f331f9d
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 69 deletions.
95 changes: 93 additions & 2 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ humantime = "2.1.0"
log = "0.4.21"
mac_address = "1.1.7"
machine-uid = "0.5.1"
notify = "6.1.1"
platform-dirs = "0.3.0"
pyo3 = { version = "0.21.2", features = ["auto-initialize"] }
reqwest = "0.12.4"
Expand Down
4 changes: 0 additions & 4 deletions src-tauri/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ pub const TYPE_KEYBOARD_KEYPRESS: &str = "KEYBOARD_KEYPRESS";
pub const TYPE_KEYBOARD_TEXT_SENT: &str = "KEYBOARD_TEXT_SENT";
pub const TYPE_KEYBOARD_TEXT: &str = "KEYBOARD_TEXT";
pub const TYPE_MEDIA_CONTROL: &str = "MEDIA_CONTROL";
pub const TYPE_MODULE_UPDATED: &str = "MODULE_UPDATED";
pub const TYPE_NOTIFICATION_SENT: &str = "NOTIFICATION_SENT";
pub const TYPE_NOTIFICATION: &str = "NOTIFICATION";
pub const TYPE_OPEN: &str = "OPEN";
Expand Down Expand Up @@ -73,7 +72,6 @@ pub enum EventType {
KeyboardText,
KeyboardTextSent,
MediaControl,
ModuleUpdated,
Notification,
NotificationSent,
Open,
Expand Down Expand Up @@ -125,7 +123,6 @@ impl FromStr for EventType {
TYPE_KEYBOARD_TEXT => Ok(EventType::KeyboardText),
TYPE_KEYBOARD_TEXT_SENT => Ok(EventType::KeyboardTextSent),
TYPE_MEDIA_CONTROL => Ok(EventType::MediaControl),
TYPE_MODULE_UPDATED => Ok(EventType::ModuleUpdated),
TYPE_NOTIFICATION => Ok(EventType::Notification),
TYPE_NOTIFICATION_SENT => Ok(EventType::NotificationSent),
TYPE_OPEN => Ok(EventType::Open),
Expand Down Expand Up @@ -181,7 +178,6 @@ impl fmt::Display for EventType {
EventType::KeyboardText => TYPE_KEYBOARD_TEXT,
EventType::KeyboardTextSent => TYPE_KEYBOARD_TEXT_SENT,
EventType::MediaControl => TYPE_MEDIA_CONTROL,
EventType::ModuleUpdated => TYPE_MODULE_UPDATED,
EventType::Notification => TYPE_NOTIFICATION,
EventType::NotificationSent => TYPE_NOTIFICATION_SENT,
EventType::Open => TYPE_OPEN,
Expand Down
60 changes: 31 additions & 29 deletions src-tauri/src/modules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@ mod processes;
mod sensors;
mod system;

use crate::{
event::EventType,
shared::get_data_path,
websocket::{client::WebSocketClient, WebsocketRequest},
};
use crate::shared::get_data_path;
use log::{error, info};
use notify::{recommended_watcher, RecursiveMode, Watcher};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt;
use std::str::FromStr;
use std::{fmt, path::Path};

#[derive(Debug, Serialize, Deserialize)]
pub enum Module {
Expand Down Expand Up @@ -159,8 +156,6 @@ pub async fn get_module_data(module: &Module) -> Result<Value, String> {
}

pub async fn update_modules(modules: &Vec<Module>) -> Result<(), String> {
let websocket_client = WebSocketClient::new().await;

for module in modules {
let data = match module {
Module::Battery => battery::update().await,
Expand Down Expand Up @@ -198,27 +193,6 @@ pub async fn update_modules(modules: &Vec<Module>) -> Result<(), String> {
continue;
}
};

// Send updated module data to the websocket
match websocket_client
.send_message(WebsocketRequest {
id: uuid::Uuid::new_v4().to_string(),
token: websocket_client.settings.api.token.clone(),
event: EventType::ModuleUpdated.to_string(),
data: serde_json::to_value(ModuleUpdate {
module: module.to_string(),
data: data.clone().unwrap(),
})
.unwrap(),
})
.await
{
Ok(_) => info!("'{:?}' module data sent to websocket", module),
Err(e) => error!(
"'{:?}' module data failed to send to websocket: {:?}",
module, e
),
};
}
Err(e) => {
error!("'{:?}' module update failed: {:?}", module, e)
Expand All @@ -228,3 +202,31 @@ pub async fn update_modules(modules: &Vec<Module>) -> Result<(), String> {

Ok(())
}

pub fn watch_modules(
modules: &Vec<String>,
callback_fn: fn(&Module, &Value),
) -> Result<(), String> {
info!("Watching modules: {:?}", modules);

// Watch for changes in module data files
let watcher_result = recommended_watcher(|res| match res {
Ok(event) => {
info!("event: {:?}", event);
}
Err(e) => {
error!("watch error: {:?}", e);
}
});

if watcher_result.is_err() {
return Err("Failed to create watcher".to_string());
}

let mut watcher = watcher_result.unwrap();

match watcher.watch(Path::new(&get_modules_path()), RecursiveMode::NonRecursive) {
Ok(_) => Ok(()),
Err(e) => Err(format!("Failed to watch modules: {:?}", e)),
}
}
6 changes: 0 additions & 6 deletions src-tauri/src/websocket/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,3 @@ pub struct WebsocketResponse {
pub message: Option<String>,
pub module: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DataListener {
pub id: String,
pub modules: Vec<String>,
}
45 changes: 17 additions & 28 deletions src-tauri/src/websocket/server.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::{DataListener, WebsocketRequest, WebsocketResponse};
use super::{WebsocketRequest, WebsocketResponse};
use crate::{
event::{EventSubtype, EventType},
modules::{get_module_data, Module, ModuleUpdate, RequestModules},
modules::{get_module_data, watch_modules, Module, RequestModules},
settings::{get_settings, update_settings, Settings},
};
use log::{debug, error, info, warn};
Expand All @@ -11,8 +11,6 @@ use serde_json::Value;
use std::str::FromStr;
use std::sync::Mutex;

static REGISTERED_LISTENERS: Mutex<Vec<DataListener>> = Mutex::new(vec![]);

#[get("/api/websocket")]
pub async fn websocket(ws: WebSocket) -> Stream!['static] {
Stream! { ws =>
Expand Down Expand Up @@ -153,26 +151,6 @@ pub async fn websocket(ws: WebSocket) -> Stream!['static] {
module: None,
}).unwrap());
}
Ok(EventType::ModuleUpdated) => {
let module_update_result: Result<ModuleUpdate, _> =
serde_json::from_value(request.data.clone());
if let Err(e) = module_update_result {
warn!("Invalid module update: {:?}", e);
continue;
}

let module_update = module_update_result.unwrap();
info!("Module update: {:?}", module_update.module.to_string());

yield Message::text(serde_json::to_string(&WebsocketResponse {
id: request_id.clone(),
type_: EventType::DataUpdate.to_string(),
data: module_update.data,
subtype: None,
message: None,
module: module_update.module.to_string().into(),
}).unwrap());
}
Ok(EventType::Open) => {
info!("Open event");

Expand All @@ -189,10 +167,21 @@ pub async fn websocket(ws: WebSocket) -> Stream!['static] {
let request_data = request_data_result.unwrap();
info!("Register data listener for modules: {:?}", request_data.modules);

// Register data listener
REGISTERED_LISTENERS.lock().unwrap().push(DataListener {
id: uuid::Uuid::new_v4().to_string(),
modules: request_data.modules,
// Listen for data updates for the requested modules on another thread
tokio::spawn(async move {
watch_modules(&request_data.modules, |module, data| {
// Send data update to the client
info!("Data update for module: {:?} - {:?}", module, data);

// yield Message::text(serde_json::to_string(&WebsocketResponse {
// id: request_id.clone(),
// type_: EventType::DataUpdate.to_string(),
// data: data.clone(),
// subtype: None,
// message: None,
// module: Some(module.to_string()),
// }).unwrap());
}).unwrap();
});

yield Message::text(serde_json::to_string(&WebsocketResponse {
Expand Down

0 comments on commit f331f9d

Please sign in to comment.