BLE キャラクタリスティックを読み書きする

Recipe ID: hw-006

hw-005 で接続した BLE デバイスに対して、実際にデータの送受信(Read/Write)や通知(Notify)の受け取りを行います。

前提条件

hw-004 の「前提条件」セクションに記載されているプラグインのインストールと設定が完了していること、および hw-005 の手順でデバイスに接続済みであることを確認してください。

1. データの書き込み(Write)

バイト配列または文字列をキャラクタリスティックに書き込みます。

バイト配列の書き込み

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

const CHARACTERISTIC_UUID = '51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B';

async function writeData() {
  const data = [0x01, 0x02, 0x03];  // バイト配列
  
  // 書き込み確認あり(確実だが遅い)
  await send(CHARACTERISTIC_UUID, data, 'withResponse');
  
  // 書き込み確認なし(高速)
  // await send(CHARACTERISTIC_UUID, data, 'withoutResponse');
}

文字列の書き込み

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

const CHARACTERISTIC_UUID = '51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B';

async function writeString() {
  await sendString(CHARACTERISTIC_UUID, 'Hello, BLE!', 'withResponse');
}

2. データの読み取り(Read)

キャラクタリスティックからデータを読み取ります。

バイト配列の読み取り

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

const CHARACTERISTIC_UUID = '51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B';

async function readData() {
  const data = await read(CHARACTERISTIC_UUID);
  console.log('受信データ:', data);  // number[] 形式
}

文字列の読み取り

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

const CHARACTERISTIC_UUID = '51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B';

async function readStringData() {
  const text = await readString(CHARACTERISTIC_UUID);
  console.log('受信テキスト:', text);
}

3. 通知の受信(Subscribe)

センサー値のようにデバイス側からプッシュされるデータを受け取るには、subscribe を使用します。

バイト配列での通知受信

import { subscribe, unsubscribe } from '@mnlphlp/plugin-blec';

const CHARACTERISTIC_UUID = '51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B';

// 通知の購読を開始
async function startNotifications() {
  await subscribe(
    CHARACTERISTIC_UUID,
    (data) => {
      // 通知が届くたびに呼ばれる
      console.log('通知データ:', data);  // number[] 形式
    }
  );
}

// 通知の購読を解除
async function stopNotifications() {
  await unsubscribe(CHARACTERISTIC_UUID);
}

文字列での通知受信

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

const CHARACTERISTIC_UUID = '51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B';

async function startStringNotifications() {
  await subscribeString(
    CHARACTERISTIC_UUID,
    (text) => {
      console.log('通知テキスト:', text);
    }
  );
}

4. サービス UUID を指定した操作

同じキャラクタリスティック UUID が複数のサービスに存在する場合、サービス UUID を指定して操作できます。

import { send, read, subscribe } from '@mnlphlp/plugin-blec';

const SERVICE_UUID = '0000180D-0000-1000-8000-00805F9B34FB';      // Heart Rate Service
const CHARACTERISTIC_UUID = '00002A37-0000-1000-8000-00805F9B34FB';  // Heart Rate Measurement

// サービスを指定して書き込み
await send(CHARACTERISTIC_UUID, [0x01], 'withResponse', SERVICE_UUID);

// サービスを指定して読み取り
const data = await read(CHARACTERISTIC_UUID, SERVICE_UUID);

5. Rust バックエンドからの操作

フロントエンドで接続した後、Rust 側からもデータを送信できます。

use uuid::{uuid, Uuid};
use tauri_plugin_blec::models::WriteType;

const CHARACTERISTIC_UUID: Uuid = uuid!("51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B");

async fn send_from_backend() -> Result<(), String> {
    let data: [u8; 3] = [0x01, 0x02, 0x03];
    
    let handler = tauri_plugin_blec::get_handler()
        .ok_or("BLE ハンドラーが初期化されていません")?;
    
    handler
        .send_data(CHARACTERISTIC_UUID, &data, WriteType::WithResponse)
        .await
        .map_err(|e| e.to_string())?;
    
    Ok(())
}

hw-004 のスキャン、hw-005 の接続と組み合わせることで、完全な BLE アプリケーションが構築できます。