feat: disconnect devices on app background mobile

This commit is contained in:
Lucas
2026-11-04 11:08:22 +01:00
parent be713620ef
commit ddb7a907a1
15 changed files with 264 additions and 37 deletions
+10
View File
@@ -10,6 +10,7 @@
"dependencies": { "dependencies": {
"@tauri-apps/api": "^2", "@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2.7.2", "@tauri-apps/plugin-opener": "^2.7.2",
"@tauri-apps/plugin-os": "^2.4.0",
"@tauri-apps/plugin-store": "^2.5.0", "@tauri-apps/plugin-store": "^2.5.0",
"react": "^19.2.8", "react": "^19.2.8",
"react-dom": "^19.2.8" "react-dom": "^19.2.8"
@@ -1592,6 +1593,15 @@
"@tauri-apps/api": "^2.12.0" "@tauri-apps/api": "^2.12.0"
} }
}, },
"node_modules/@tauri-apps/plugin-os": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-os/-/plugin-os-2.4.0.tgz",
"integrity": "sha512-XFQjntNNI3Vlqdy4WUGwiXX8DByzKVvoemAcUVkBm9NJPGmoDtII5i+vfuAzWaJfOE5cUJJLUDqXBnd4reSAIA==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.12.0"
}
},
"node_modules/@tauri-apps/plugin-store": { "node_modules/@tauri-apps/plugin-store": {
"version": "2.5.0", "version": "2.5.0",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-store/-/plugin-store-2.5.0.tgz", "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-store/-/plugin-store-2.5.0.tgz",
+1
View File
@@ -14,6 +14,7 @@
"dependencies": { "dependencies": {
"@tauri-apps/api": "^2", "@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2.7.2", "@tauri-apps/plugin-opener": "^2.7.2",
"@tauri-apps/plugin-os": "^2.4.0",
"@tauri-apps/plugin-store": "^2.5.0", "@tauri-apps/plugin-store": "^2.5.0",
"react": "^19.2.8", "react": "^19.2.8",
"react-dom": "^19.2.8" "react-dom": "^19.2.8"
+89 -30
View File
@@ -460,6 +460,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]] [[package]]
name = "chacha20" name = "chacha20"
version = "0.10.2" version = "0.10.2"
@@ -1257,6 +1263,16 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "gethostname"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
dependencies = [
"rustix",
"windows-link",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.2.17" version = "0.2.17"
@@ -1594,12 +1610,12 @@ dependencies = [
[[package]] [[package]]
name = "ico" name = "ico"
version = "0.5.0" version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371" checksum = "d75e94d66081e4d8dcd098bd8dc5254800fea14a26389b298410158d834de167"
dependencies = [ dependencies = [
"byteorder", "byteorder",
"png 0.17.16", "png",
] ]
[[package]] [[package]]
@@ -2091,7 +2107,7 @@ dependencies = [
"objc2-core-foundation", "objc2-core-foundation",
"objc2-foundation", "objc2-foundation",
"once_cell", "once_cell",
"png 0.18.1", "png",
"serde", "serde",
"thiserror 2.0.21", "thiserror 2.0.21",
"windows-sys 0.61.2", "windows-sys 0.61.2",
@@ -2133,6 +2149,18 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nix"
version = "0.31.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
dependencies = [
"bitflags 2.13.1",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]] [[package]]
name = "num-conv" name = "num-conv"
version = "0.2.2" version = "0.2.2"
@@ -2294,6 +2322,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [ dependencies = [
"bitflags 2.13.1", "bitflags 2.13.1",
"block2", "block2",
"libc",
"objc2", "objc2",
"objc2-core-foundation", "objc2-core-foundation",
] ]
@@ -2399,6 +2428,22 @@ dependencies = [
"pin-project-lite", "pin-project-lite",
] ]
[[package]]
name = "os_info"
version = "3.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"
dependencies = [
"android_system_properties",
"log",
"nix",
"objc2",
"objc2-foundation",
"objc2-ui-kit",
"serde",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "pango" name = "pango"
version = "0.18.3" version = "0.18.3"
@@ -2548,19 +2593,6 @@ dependencies = [
"time", "time",
] ]
[[package]]
name = "png"
version = "0.17.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
dependencies = [
"bitflags 1.3.2",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide",
]
[[package]] [[package]]
name = "png" name = "png"
version = "0.18.1" version = "0.18.1"
@@ -3362,6 +3394,15 @@ dependencies = [
"syn 2.0.119", "syn 2.0.119",
] ]
[[package]]
name = "sys-locale"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "system-deps" name = "system-deps"
version = "6.2.2" version = "6.2.2"
@@ -3434,9 +3475,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
[[package]] [[package]]
name = "tauri" name = "tauri"
version = "2.12.4" version = "2.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f316751027fc2644221d1a448564d519efb07067fda584879d9cda966391d212" checksum = "5fb0244332cfb9cee7e2a568bf5da29a36ed8fdbd717f6f47a66b6b7b358c072"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bytes", "bytes",
@@ -3485,9 +3526,9 @@ dependencies = [
[[package]] [[package]]
name = "tauri-build" name = "tauri-build"
version = "2.7.3" version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "641dd5fd297c99ab92717b0428cca5b9c6f960b2ac96ca131b3eebc9d70b8ddc" checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"cargo_toml", "cargo_toml",
@@ -3508,16 +3549,16 @@ dependencies = [
[[package]] [[package]]
name = "tauri-codegen" name = "tauri-codegen"
version = "2.7.3" version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6585c5b536c00f039d12ce70a9755172d5423bbcfd3969863baa70314c3e02f" checksum = "fb37631cf71dab5e8ab55e1bdd701e18a52653d90b78e71d0e5598b1e0a61316"
dependencies = [ dependencies = [
"base64 0.23.1", "base64 0.23.1",
"brotli", "brotli",
"ico", "ico",
"json-patch", "json-patch",
"plist", "plist",
"png 0.18.1", "png",
"proc-macro2", "proc-macro2",
"quote", "quote",
"semver", "semver",
@@ -3535,9 +3576,9 @@ dependencies = [
[[package]] [[package]]
name = "tauri-macros" name = "tauri-macros"
version = "2.7.3" version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2e83a0cfa1bae376e8fbbdc0b1692707aed50cd6072ce85cae4789af5d6c19f" checksum = "0cc38db58854c10fb5f91a887ed8bf82d3239bb92b5d8db86eda09e96d9963d1"
dependencies = [ dependencies = [
"heck 0.5.0", "heck 0.5.0",
"proc-macro2", "proc-macro2",
@@ -3585,6 +3626,24 @@ dependencies = [
"zbus", "zbus",
] ]
[[package]]
name = "tauri-plugin-os"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bd69d272ab772b30462779de12a40f837616831c794c71531bea91474e1061f"
dependencies = [
"gethostname",
"log",
"os_info",
"serde",
"serde_json",
"serialize-to-javascript",
"sys-locale",
"tauri",
"tauri-plugin",
"thiserror 2.0.21",
]
[[package]] [[package]]
name = "tauri-plugin-store" name = "tauri-plugin-store"
version = "2.5.0" version = "2.5.0"
@@ -3628,9 +3687,9 @@ dependencies = [
[[package]] [[package]]
name = "tauri-runtime-wry" name = "tauri-runtime-wry"
version = "2.12.2" version = "2.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d61892587aea2a85245bcaec98c6fe46268874c0a0deae5535fb71ca7b93eae" checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f"
dependencies = [ dependencies = [
"gtk", "gtk",
"http", "http",
@@ -3638,7 +3697,6 @@ dependencies = [
"log", "log",
"objc2", "objc2",
"objc2-app-kit", "objc2-app-kit",
"once_cell",
"percent-encoding", "percent-encoding",
"raw-window-handle", "raw-window-handle",
"softbuffer", "softbuffer",
@@ -3773,6 +3831,7 @@ dependencies = [
"tauri", "tauri",
"tauri-build", "tauri-build",
"tauri-plugin-opener", "tauri-plugin-opener",
"tauri-plugin-os",
"tauri-plugin-store", "tauri-plugin-store",
] ]
@@ -4058,7 +4117,7 @@ dependencies = [
"objc2-core-graphics", "objc2-core-graphics",
"objc2-foundation", "objc2-foundation",
"once_cell", "once_cell",
"png 0.18.1", "png",
"serde", "serde",
"thiserror 2.0.21", "thiserror 2.0.21",
"windows-sys 0.61.2", "windows-sys 0.61.2",
+2 -1
View File
@@ -18,8 +18,9 @@ crate-type = ["staticlib", "cdylib", "rlib"]
tauri-build = { version = "2", features = [] } tauri-build = { version = "2", features = [] }
[dependencies] [dependencies]
tauri = { version = "2.12.4", features = [] } tauri = { version = "2.12.5", features = [] }
tauri-plugin-opener = "2.7.2" tauri-plugin-opener = "2.7.2"
tauri-plugin-os = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1.0.154" serde_json = "1.0.154"
dsp_thomann = { path = "../../dsp-thomann", features = ["serialization"] } dsp_thomann = { path = "../../dsp-thomann", features = ["serialization"] }
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,5 +1,5 @@
// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. // THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
include ':tauri-android' include ':tauri-android'
project(':tauri-android').projectDir = new File("C:\\Users\\lsdg\\.cargo\\registry\\src\\index.crates.io-1949cf8c6b5b557f\\tauri-2.12.4\\mobile\\android") project(':tauri-android').projectDir = new File("C:\\Users\\lsdg\\.cargo\\registry\\src\\index.crates.io-1949cf8c6b5b557f\\tauri-2.12.5\\mobile\\android")
include ':tauri-plugin-opener' include ':tauri-plugin-opener'
project(':tauri-plugin-opener').projectDir = new File("C:\\Users\\lsdg\\.cargo\\registry\\src\\index.crates.io-1949cf8c6b5b557f\\tauri-plugin-opener-2.7.2\\android") project(':tauri-plugin-opener').projectDir = new File("C:\\Users\\lsdg\\.cargo\\registry\\src\\index.crates.io-1949cf8c6b5b557f\\tauri-plugin-opener-2.7.2\\android")
+7
View File
@@ -69,8 +69,15 @@ pub fn create_dsp408(
let id = *next_id; let id = *next_id;
*next_id += 1; *next_id += 1;
#[cfg(mobile)]
let mut device = DSPDevice { dsp };
#[cfg(not(mobile))]
let device = DSPDevice { dsp }; let device = DSPDevice { dsp };
#[cfg(mobile)]
device.dsp.set_auto_reconnect(false);
let mut devices = state.devices.lock().map_err(|e| e.to_string())?; let mut devices = state.devices.lock().map_err(|e| e.to_string())?;
devices.insert(id, Arc::new(Mutex::new(device))); devices.insert(id, Arc::new(Mutex::new(device)));
+21 -4
View File
@@ -4,11 +4,26 @@ mod state;
use state::AppState; use state::AppState;
use tauri::Manager; use tauri::Manager;
#[cfg(mobile)]
fn handle_run_event(app: &tauri::AppHandle, event: &tauri::RunEvent) {
if let tauri::RunEvent::WindowEvent {
event: tauri::WindowEvent::Focused(false),
..
} = event
{
app.state::<AppState>().disconnect_all();
}
}
#[cfg(not(mobile))]
fn handle_run_event(_app: &tauri::AppHandle, _event: &tauri::RunEvent) {}
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
tauri::Builder::default() let app = tauri::Builder::default()
.plugin(tauri_plugin_store::Builder::new().build()) .plugin(tauri_plugin_store::Builder::new().build())
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_os::init()) // added by `tauri add os`
.manage(AppState::new()) .manage(AppState::new())
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
commands::create_dsp408, commands::create_dsp408,
@@ -51,6 +66,8 @@ pub fn run() {
state.shutdown(); state.shutdown();
} }
}) })
.run(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while building tauri application");
}
app.run(|app, event| handle_run_event(app, &event));
}
+18
View File
@@ -30,4 +30,22 @@ impl AppState {
} }
} }
} }
pub fn disconnect_all(&self) {
// clone the Arcs so the map lock isn't held while waiting on devices
let devices: Vec<Arc<Mutex<DSPDevice>>> = {
let map = self.devices.lock().unwrap_or_else(|e| e.into_inner());
map.values().cloned().collect()
};
// one thread per device so a stuck device doesn't delay the others
for device in devices {
std::thread::spawn(move || {
let mut d = device.lock().unwrap_or_else(|e| e.into_inner());
if d.dsp.connected() {
let _ = d.dsp.disconnect();
}
});
}
}
} }
+4
View File
@@ -14,6 +14,7 @@ import { stopAllPolling } from './dsp/pollRegistry';
import { loadSavedDSPs, saveDSPs, toSaved } from './dsp/dspStorage'; import { loadSavedDSPs, saveDSPs, toSaved } from './dsp/dspStorage';
import { DSPMode } from './features/dsp408/types'; import { DSPMode } from './features/dsp408/types';
import { useIsMobile } from './hooks/useIsMobile'; import { useIsMobile } from './hooks/useIsMobile';
import { useMobileBackgroundDisconnect } from './dsp/useMobileBackgroundDisconnect';
function App() { function App() {
const [dsps, setDsps] = useState<DSP[]>([]); const [dsps, setDsps] = useState<DSP[]>([]);
@@ -30,6 +31,9 @@ function App() {
const dspsRef = useRef(dsps); const dspsRef = useRef(dsps);
dspsRef.current = dsps; dspsRef.current = dsps;
useMobileBackgroundDisconnect(dsps, setDsps, notify); // NEW
useEffect(() => { useEffect(() => {
return () => stopAllPolling(dspsRef.current); return () => stopAllPolling(dspsRef.current);
}, []); }, []);
+10
View File
@@ -0,0 +1,10 @@
import { platform } from '@tauri-apps/plugin-os';
export const isMobileOS: boolean = (() => {
try {
const p = platform();
return p === 'android' || p === 'ios';
} catch {
return false; // not running inside Tauri (tests, browser dev)
}
})();
+54
View File
@@ -0,0 +1,54 @@
import { useEffect, useRef } from 'react';
import { isMobileOS } from './platform';
import { forDSP408, setAppBackgrounded, isPolling } from '../features/dsp408/dsp408';
import { DSP, isConnected } from '../types';
import { SetDsps, NotifyFn } from './dspShared';
export function useMobileBackgroundDisconnect(
dsps: DSP[],
setDsps: SetDsps,
notify: NotifyFn
) {
const dspsRef = useRef(dsps);
dspsRef.current = dsps;
useEffect(() => {
if (!isMobileOS) return; // desktop: nothing is registered
const goBackground = () => {
setAppBackgrounded(true);
for (const d of dspsRef.current) {
if (d.type !== 'DSP408') continue;
// Rust disconnect is idempotent, so no connection-state filter is needed.
// ADJUST: skip demo-mode DSPs here if you don't want them disconnected.
void forDSP408(d, setDsps, notify).disconnectForBackground();
}
};
const onResume = () => {
setAppBackgrounded(false); // allows a MANUAL connect again; never reconnects
for (const d of dspsRef.current) {
if (d.type !== 'DSP408' || !isPolling(d.id)) continue;
const api = forDSP408(d, setDsps, notify);
api
.updateDSPState()
.then((s) => {
if (!isConnected({ ...d, state: s } as DSP)) return api.disconnectForBackground();
})
.catch(() => {});
}
};
const onVisibility = () => {
if (document.visibilityState === 'hidden') goBackground();
else onResume();
};
document.addEventListener('visibilitychange', onVisibility);
window.addEventListener('pagehide', goBackground);
return () => {
document.removeEventListener('visibilitychange', onVisibility);
window.removeEventListener('pagehide', goBackground);
};
}, [setDsps, notify]);
}
+46
View File
@@ -78,6 +78,16 @@ export function stopPolling(id: number) {
registerPollStopper('DSP408', stopPolling); registerPollStopper('DSP408', stopPolling);
// --- background state, private to this module --------------------------
let appBackgrounded = false;
export function setAppBackgrounded(v: boolean) {
appBackgrounded = v;
}
export function isPolling(id: number): boolean {
return pollIntervals.has(id);
}
// --- pause helper ---------------------------------------------------------- // --- pause helper ----------------------------------------------------------
async function withPollingPaused<T>( async function withPollingPaused<T>(
@@ -141,6 +151,30 @@ export function forDSP408(dsp: DSP408, setDsps: SetDsps, notify: NotifyFn) {
} }
} }
async function disconnectForBackground() {
// synchronous part first: the webview may be frozen right after this
stopPolling(dsp.id);
updateDSP(setDsps, dsp.id, (d) => ({
...d,
isConnecting: false,
pollingPaused: true,
}));
try {
await invoke('disconnect_dsp408', { id: dsp.id });
} catch {
// socket may already be gone; Rust-side fallback covers the rest
}
// quiet state refresh (no error toast while backgrounded)
try {
const state = await invoke<DSP408['state']>('get_dsp_state', { id: dsp.id });
updateDSP(setDsps, dsp.id, (d) => ({ ...d, state }) as DSP408);
} catch {
/* ignore */
}
}
const isLocked = (s: DSP408['state']) => s.flags.is_locked; const isLocked = (s: DSP408['state']) => s.flags.is_locked;
async function abortLocked() { async function abortLocked() {
@@ -155,6 +189,11 @@ export function forDSP408(dsp: DSP408, setDsps: SetDsps, notify: NotifyFn) {
try { try {
await invoke('connect_dsp408', { id: dsp.id }); await invoke('connect_dsp408', { id: dsp.id });
if (appBackgrounded) { // NEW: backgrounded mid-connect
await disconnectForBackground();
return;
}
let state = await updateDSPState(); let state = await updateDSPState();
if (isLocked(state)) { if (isLocked(state)) {
@@ -174,6 +213,11 @@ export function forDSP408(dsp: DSP408, setDsps: SetDsps, notify: NotifyFn) {
} }
} }
if (appBackgrounded) {
await disconnectForBackground();
return;
}
updateDSP(setDsps, dsp.id, (d) => ({ ...d, isConnecting: false, pollingPaused: false })); updateDSP(setDsps, dsp.id, (d) => ({ ...d, isConnecting: false, pollingPaused: false }));
notify('Connected', 'success', dsp.name); notify('Connected', 'success', dsp.name);
startPolling(dsp, setDsps); startPolling(dsp, setDsps);
@@ -939,5 +983,7 @@ export function forDSP408(dsp: DSP408, setDsps: SetDsps, notify: NotifyFn) {
} }
}); });
}, },
disconnectForBackground,
}; };
} }