Skip to main content

tauri_plugin_bluetooth_manager/
lib.rs

1use tauri::{
2    async_runtime,
3    plugin::{Builder, TauriPlugin},
4    Manager, Runtime,
5};
6
7pub use models::*;
8
9mod commands;
10mod desktop;
11mod error;
12mod models;
13mod logging;
14
15pub use error::{Error, Result};
16
17use desktop::BluetoothManager;
18
19pub trait BluetoothManagerExt<R: Runtime> {
20    fn bluetooth_manager(&self) -> &BluetoothManager;
21}
22
23impl<R: Runtime, T: Manager<R>> BluetoothManagerExt<R> for T {
24    fn bluetooth_manager(&self) -> &BluetoothManager {
25        self.state::<BluetoothManager>().inner()
26    }
27}
28
29/// Initializes the plugin.
30pub fn init<R: Runtime>() -> TauriPlugin<R> {
31    logging::init_logging();
32
33    Builder::<R>::new("bluetooth-manager")
34        .invoke_handler(tauri::generate_handler![
35            commands::list_adapters,
36            commands::set_adapter_powered,
37            commands::get_adapter_state,
38            commands::start_scan,
39            commands::stop_scan,
40            commands::list_devices,
41            commands::list_paired_devices,
42            commands::connect_device,
43            commands::disconnect_device,
44            commands::get_device_info,
45            commands::bluetooth_plugin_status,
46        ])
47        .setup(|app_handle, api| {
48            let result = async_runtime::block_on(desktop::init(app_handle.clone(), api));
49            let initialized = result.is_ok();
50            if let Some(manager) = app_handle.try_state::<desktop::BluetoothManager>() {
51                let mut guard = manager.inner().initialized.lock().unwrap();
52                *guard = initialized;
53            }
54            if let Err(e) = result {
55                tracing::error!("Bluetooth service not available: {e}");
56            }
57            Ok(())
58        })
59        .build()
60}