Skip to content

Commit

Permalink
fix: fix config
Browse files Browse the repository at this point in the history
  • Loading branch information
SARDONYX-sard committed Jul 27, 2024
1 parent 52de472 commit ded5008
Show file tree
Hide file tree
Showing 21 changed files with 381 additions and 627 deletions.
594 changes: 183 additions & 411 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion cspell.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"PCWSTR",
"repr",
"tauri",
"Uncategorized"
"Uncategorized",
"unlisten"
]
}
2 changes: 1 addition & 1 deletion gui/backend/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "bluetooth_battery_monitor_gui"
name = "bluetooth_battery_monitor"
version.workspace = true
description = "Bluetooth battery monitor GUI"
authors = ["SARDONYX-sard"]
Expand Down
18 changes: 11 additions & 7 deletions gui/backend/src/cmd/battery_reporter.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use super::bluetooth_info_cache::write_bt_cache;
use super::config::write_config;
use super::supports::{notify, update_tray};
use super::{config::read_config, find_bluetooth_devices};
Expand All @@ -7,20 +6,22 @@ use std::{
sync::atomic::{AtomicU64, Ordering},
time::Duration,
};
use tauri::AppHandle;
use tauri::{Manager, Window};
use timer::{clear_interval, set_interval};

static INTERVAL_ID: AtomicU64 = AtomicU64::new(0);

/// # NOTE
/// The callback fn cannot return a Result, so write only error log.
#[tauri::command]
pub async fn restart_interval(app: AppHandle) {
pub async fn restart_interval(window: Window) {
tracing::trace!("`restart_interval` was called.");
let id = INTERVAL_ID.load(Ordering::Acquire);
if id != 0 {
clear_interval(id).await;
};

let app = window.app_handle();
let config = read_config(app.clone()).unwrap_or_else(|_| {
let _ = err_log!(write_config(app.clone(), Default::default()));
Default::default()
Expand All @@ -33,15 +34,15 @@ pub async fn restart_interval(app: AppHandle) {
// Therefore, they become 'static' and must be cloned.
let app = app.clone();
let instance_id = config.instance_id.clone();
let window = window.clone();

async move {
// NOTE: The callback fn cannot return a Result, so write only error log.
match find_bluetooth_devices().await {
Ok(devices) => {
if let Ok(json) = err_log!(serde_json::to_string_pretty(&devices)) {
let _ = err_log!(write_bt_cache(app.clone(), &json));
};
tracing::debug!("Got devices: {:#?}", devices);

for dev in devices {
for dev in &devices {
if instance_id.is_empty() {
if !dev.is_connected {
continue;
Expand All @@ -59,6 +60,9 @@ pub async fn restart_interval(app: AppHandle) {
let dev_name = &dev.friendly_name;
let _ = err_log!(update_tray(&app, dev_name, battery_level).await);
}
if let Err(err) = window.emit("bt_monitor://restart_interval", devices) {
tracing::error!("{err}");
};
}
Err(e) => tracing::error!(e),
};
Expand Down
22 changes: 0 additions & 22 deletions gui/backend/src/cmd/bluetooth_info_cache.rs

This file was deleted.

21 changes: 14 additions & 7 deletions gui/backend/src/cmd/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
pub(crate) mod battery_reporter;
mod bluetooth_info_cache;
mod config;
mod supports;

use crate::err_log;
use bluetooth::{device::device_info::FindBluetooth as _, BluetoothDeviceInfo};
use supports::{default_tray, update_tray};
use tauri::{AppHandle, Builder, Wry};

#[tauri::command]
pub(crate) async fn update_tray_icon(
Expand All @@ -15,9 +16,19 @@ pub(crate) async fn update_tray_icon(
err_log!(update_tray(&app, device_name, battery_level).await)
}

#[tauri::command]
pub(crate) async fn set_default_tray_icon(
app: AppHandle,
) -> Result<(), String> {
err_log!(default_tray(&app).await)
}

#[tauri::command]
pub(crate) async fn find_bluetooth_devices() -> Result<Vec<BluetoothDeviceInfo>, String> {
err_log!(BluetoothDeviceInfo::find_devices())
tracing::trace!("`find_bluetooth_devices` was called.");
let devices = err_log!(BluetoothDeviceInfo::find_devices())?;
tracing::debug!("Got devices: {:#?}", devices);
Ok(devices)
}

#[tauri::command]
Expand All @@ -35,9 +46,6 @@ pub(crate) async fn write_file(path: &str, content: &str) -> Result<(), String>
err_log!(std::fs::write(path, content))
}

use supports::update_tray;
use tauri::{AppHandle, Builder, Wry};

pub(crate) trait CommandsRegister {
/// Implements custom commands.
fn impl_commands(self) -> Self;
Expand All @@ -48,11 +56,10 @@ impl CommandsRegister for Builder<Wry> {
self.invoke_handler(tauri::generate_handler![
change_log_level,
find_bluetooth_devices,
set_default_tray_icon,
update_tray_icon,
write_file,
battery_reporter::restart_interval,
bluetooth_info_cache::read_bt_cache,
bluetooth_info_cache::write_bt_cache,
config::read_config,
config::write_config,
])
Expand Down
2 changes: 1 addition & 1 deletion gui/backend/src/cmd/supports/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ mod system_tray;

pub(super) use logger::change_log_level;
pub(super) use notify::notify;
pub(super) use system_tray::update_tray;
pub(super) use system_tray::{default_tray, update_tray};
11 changes: 11 additions & 0 deletions gui/backend/src/cmd/supports/system_tray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,14 @@ pub async fn update_tray(
tray_handle.set_icon(tauri::Icon::Raw(battery_icon.to_vec()))?;
tray_handle.set_tooltip(&format!("{device_name} {battery_level}%"))
}

/// Update application tray icon & name
pub async fn default_tray(
app: &tauri::AppHandle,
) -> tauri::Result<()> {
let battery_icon = include_bytes!("../../../icons/icon.png").as_slice();

let tray_handle = app.tray_handle();
tray_handle.set_icon(tauri::Icon::Raw(battery_icon.to_vec()))?;
tray_handle.set_tooltip("Getting bluetooth battery...")
}
6 changes: 4 additions & 2 deletions gui/backend/src/setup/battery_reporter.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use crate::cmd::battery_reporter::restart_interval;
use tauri::{AppHandle, Manager as _};

/// # Note
/// Interval callback fn cannot return Result. So relies on internal error log.
pub fn start_interval(app: &tauri::AppHandle) {
pub fn start_interval(app: &AppHandle) {
let app = app.clone();
let window = app.get_window("main").unwrap();
tauri::async_runtime::spawn(async move {
let _ = restart_interval(app).await;
let _ = restart_interval(window).await;
});
}
23 changes: 2 additions & 21 deletions gui/frontend/src/backend_api/bluetooth_finder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,25 +40,6 @@ export async function FindBluetoothDevices() {
* Restart interval to get bluetooth device information.
* @throws `Error`
*/
export async function restartBtGetter() {
return await invoke<BluetoothDeviceInfo[]>('restart_interval');
export async function restartInterval() {
await invoke('restart_interval');
}

export const btCache = {
/**
* Get bluetooth device information from cache.
* @throws `Error`
*/
async read() {
return await invoke<BluetoothDeviceInfo[]>('read_bt_cache');
},

/**
* Write bluetooth device information to cache.
* @throws `Error`
*/
async write(devices: BluetoothDeviceInfo[]) {
// biome-ignore lint/style/useNamingConvention: <explanation>
await invoke('write_bt_cache', { devices_json: JSON.stringify(devices) });
},
};
31 changes: 31 additions & 0 deletions gui/frontend/src/backend_api/device_listener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { listen } from '@tauri-apps/api/event';

import type { BluetoothDeviceInfo } from '@/backend_api';
import { notify } from '@/components/notifications';

import type { EventCallback } from '@tauri-apps/api/event';
import type { JSX } from 'react/jsx-runtime';

type ListenerProps = {
setDev: (devices: BluetoothDeviceInfo[]) => void;
/** @default Error */
error?: string | JSX.Element;
};

export async function deviceListener({ setDev, error }: ListenerProps) {
let unlisten: (() => void) | null = null;
const eventHandler: EventCallback<BluetoothDeviceInfo[]> = (event) => {
setDev(event.payload);
};

try {
// Setup before run Promise(For event hook)
unlisten = await listen<BluetoothDeviceInfo[]>('bt_monitor://restart_interval', eventHandler);
return unlisten;
} catch (err) {
notify.error(error ?? `${err}`);
if (unlisten) {
unlisten();
}
}
}
4 changes: 2 additions & 2 deletions gui/frontend/src/backend_api/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// @index('./*', f => `export * from '${f.path}'`)
export * from './backup';
export * from './backend_config';
export * from './backup';
export * from './bluetooth_finder';
export * from './default_api_wrapper';
export * from './device_listener';
export * from './lang';
export * from './log';
export * from './progress_listener';
export * from './sys_tray';
90 changes: 0 additions & 90 deletions gui/frontend/src/backend_api/progress_listener.ts

This file was deleted.

4 changes: 4 additions & 0 deletions gui/frontend/src/backend_api/sys_tray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@ import { invoke } from '@tauri-apps/api';
export async function updateTrayIcon(deviceName: string, batteryLevel: number) {
await invoke('update_tray_icon', { deviceName, batteryLevel });
}

export async function defaultTrayIcon() {
await invoke('set_default_tray_icon');
}
Loading

0 comments on commit ded5008

Please sign in to comment.