Featured image of post Web Bluetooth API:ブラウザからハードウェアに接続する Featured image of post Web Bluetooth API:ブラウザからハードウェアに接続する

Web Bluetooth API:ブラウザからハードウェアに接続する

Web Bluetooth APIの実践ガイド。BLE GATT通信、デバイス探索、サービス/キャラクタリスティック操作、ペアリング、再接続、セキュリティ、IoT応用例までを解説。

Web Bluetooth APIは、ブラウザからBluetooth Low Energy(BLE)デバイスと通信するためのインターフェースを提供します。心拍数モニターや温度センサー、スマートライトなどのIoTデバイスをWebページから直接操作できるようになります。

Web Bluetoothの仕組み

Web BluetoothはBLE通信の標準プロトコルであるGATT(Generic Attribute Profile)上で動作します。BLEデバイスがサービスとキャラクタリスティックを公開するペリフェラルとなり、ブラウザがそれらを消費するセントラルとして機能します。

用語説明
Serviceキャラクタリスティックの集合Battery Service (0x180F)
Characteristicプロパティを持つデータポイントBattery Level (0x2A19)
Descriptorキャラクタリスティックのメタデータ単位、説明
UUIDサービス/キャラクタリスティックの識別子16ビット標準または128ビットカスタム

Web Bluetoothはセキュアコンテキスト(HTTPSまたはlocalhost)とユーザージェスチャーを必須とし、不正なスキャンを防止します。


デバイス探索と接続

ブラウザのBluetooth選択画面を表示してデバイスを要求します:

async function connectDevice() {
  try {
    const device = await navigator.bluetooth.requestDevice({
      filters: [{ services: ['battery_service'] }],
      optionalServices: ['environmental_sensing'],
    });

    const server = await device.gatt.connect();
    console.log('接続完了:', device.name);
    return server;
  } catch (error) {
    console.error('接続失敗:', error);
  }
}

filtersで表示するデバイスを絞り込み、optionalServicesでアドバタイズされていないサービスにアクセスします。


データの読み書き

接続後、サービスとキャラクタリスティックを介してデータを交換します:

async function readBatteryLevel(server) {
  const service = await server.getPrimaryService('battery_service');
  const characteristic = await service.getCharacteristic('battery_level');
  const value = await characteristic.readValue();
  return value.getUint8(0);
}

async function subscribeToHeartRate(server) {
  const service = await server.getPrimaryService('heart_rate');
  const characteristic = await service.getCharacteristic('heart_rate_measurement');
  await characteristic.startNotifications();
  characteristic.addEventListener('characteristicvaluechanged', (event) => {
    const data = event.target.value;
    // ArrayBufferから心拍数データを解析
  });
}

再接続と管理

切断を検出して自動再接続を実装できます:

device.addEventListener('gattserverdisconnected', () => {
  console.log('切断されました。再接続を試みます...');
  setTimeout(async () => {
    if (!device.gatt.connected) {
      await device.gatt.connect();
    }
  }, 1000);
});

セキュリティ

HTTPSによる暗号化、ユーザージェスチャーによる承認、ペアリング時の認証(パスキー入力や数値比較)により、複数層のセキュリティが確保されています。過去に許可したデバイスのみnavigator.bluetooth.getDevices()で取得可能です。


制限と代替手段

Web BluetoothはBLEのみ対応、モバイルでのバックグラウンドスキャン不可、iOS Safariは実験的対応です。通信範囲は約10〜30メートル、ペイロードは約20バイトに制限されます。クラシックBluetoothが必要な場合はWeb SerialやWeb USBを検討してください。


Web Bluetooth APIは、物理デバイスと連携する新しいクラスのWebアプリケーションを可能にします。センサー値の読み取りや通知の受信から始め、双方向通信やボンディングへと段階的にスケールアップしていきましょう。