Skip to content

Commit 635d7b9

Browse files
committed
fix: Proper disconnect/reconnect of BLE.
1 parent db30505 commit 635d7b9

File tree

2 files changed

+27
-11
lines changed

2 files changed

+27
-11
lines changed

src-tauri/src/transport/gatt.rs

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use futures::StreamExt;
55
use std::time::Duration;
66
use uuid::Uuid;
77

8-
use bluest::{Adapter, DeviceId};
8+
use bluest::{Adapter, ConnectionEvent, DeviceId};
99

1010
use tauri::{command, AppHandle, State};
1111

@@ -46,22 +46,38 @@ pub async fn gatt_connect(
4646

4747
if let Some(c) = char {
4848
let c2 = c.clone();
49-
tauri::async_runtime::spawn(async move {
49+
let ah1 = app_handle.clone();
50+
let notify_handle = tauri::async_runtime::spawn(async move {
5051
if let Ok(mut n) = c2.notify().await {
51-
// Need to keep adapter from being dropped while active/connected
52-
let a = adapter;
53-
5452
use tauri::Manager;
5553

5654
while let Some(Ok(vn)) = n.next().await {
57-
app_handle.emit("connection_data", vn.clone());
55+
ah1.emit("connection_data", vn.clone());
5856
}
57+
}
58+
});
59+
60+
let ah2 = app_handle.clone();
61+
tauri::async_runtime::spawn(async move {
62+
// Need to keep adapter from being dropped while active/connected
63+
let a = adapter;
5964

60-
let state = app_handle.state::<super::commands::ActiveConnection>();
61-
*state.conn.lock().await = None;
65+
use tauri::Manager;
6266

63-
app_handle.emit("connection_disconnected", ());
64-
}
67+
if let Ok(mut events) = a.device_connection_events(&d).await {
68+
while let Some(ev) = events.next().await {
69+
if ev == ConnectionEvent::Disconnected {
70+
let state = ah2.state::<super::commands::ActiveConnection>();
71+
*state.conn.lock().await = None;
72+
73+
if let Err(e) = ah2.emit("connection_disconnected", ()) {
74+
println!("ERROR RAISING! {:?}", e);
75+
}
76+
77+
notify_handle.abort();
78+
}
79+
}
80+
};
6581
});
6682

6783
let (send, mut recv) = channel(5);

src/tauri/ble.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ export async function connect(dev: AvailableDevice): Promise<RpcTransport> {
3030
const unlisten_disconnected = await listen('connection_disconnected', async (_ev: any) => {
3131
unlisten_data();
3232
unlisten_disconnected();
33-
readable.cancel();
33+
response_writable.close();
3434
});
3535

3636
return { label: dev.label, readable, writable };

0 commit comments

Comments
 (0)