Bluetooth (BLE) への接続と切断

Recipe ID: hw-005

hw-004 でスキャンして発見した BLE デバイスに接続・切断する方法です。tauri-plugin-blec を使用することで、フロントエンドから簡単に接続管理ができます。

前提条件

hw-004 の「前提条件」セクションに記載されているプラグインのインストールと設定が完了していることを確認してください。

1. デバイスへの接続

スキャンで取得した address を使用してデバイスに接続します。

import { connect } from '@mnlphlp/plugin-blec';

async function connectToDevice(address: string) {
  try {
    await connect(
      address,
      () => {
        // 切断時に呼ばれるコールバック
        console.log('デバイスから切断されました');
      }
    );
    console.log('接続成功:', address);
  } catch (error) {
    console.error('接続失敗:', error);
  }
}

2. 接続の切断

現在接続中のデバイスから切断します。

import { disconnect } from '@mnlphlp/plugin-blec';

async function disconnectFromDevice() {
  try {
    await disconnect();
    console.log('切断しました');
  } catch (error) {
    console.error('切断に失敗:', error);
  }
}

3. 接続状態の監視

接続状態の変化をリアルタイムで監視できます。

import { getConnectionUpdates } from '@mnlphlp/plugin-blec';

// 接続状態が変わるたびに呼ばれる
getConnectionUpdates((isConnected) => {
  if (isConnected) {
    console.log('デバイスに接続しました');
  } else {
    console.log('デバイスから切断しました');
  }
});

4. サービス一覧の取得

接続後、デバイスが提供するサービスとキャラクタリスティックの一覧を取得できます。

import { listServices, type BleService } from '@mnlphlp/plugin-blec';

async function getServices(address: string) {
  const services = await listServices(address);
  
  if (typeof services === 'string') {
    console.error('エラー:', services);
    return;
  }
  
  for (const service of services) {
    console.log('サービス UUID:', service.uuid);
    
    for (const char of service.characteristics) {
      console.log('  キャラクタリスティック UUID:', char.uuid);
      console.log('  プロパティ:', char.properties);
    }
  }
}

5. 完全な接続フローの例

スキャンから接続までの完全なフローを示します。

import { 
  startScan, 
  stopScan, 
  connect, 
  disconnect,
  listServices,
  type BleDevice 
} from '@mnlphlp/plugin-blec';

let devices: BleDevice[] = [];
let connectedAddress: string | null = null;

// デバイスをスキャン
async function scan() {
  await startScan((found) => {
    devices = found;
  }, 5000);
}

// 特定のデバイスに接続
async function connectDevice(device: BleDevice) {
  await connect(device.address, () => {
    connectedAddress = null;
    console.log('切断されました');
  });
  
  connectedAddress = device.address;
  
  // 接続後にサービスを取得
  const services = await listServices(device.address);
  console.log('利用可能なサービス:', services);
}

// 切断
async function disconnectDevice() {
  await disconnect();
  connectedAddress = null;
}

接続後は、キャラクタリスティックへの読み書きが可能になります(hw-006 参照)。