ブラウザから心拍計やセンサー、自社の IoT 機器に直接つなぎ、URL を開くだけで使ってもらいたい。Web Bluetooth API は、その要望に応えられる数少ない手段です。ただ、日本語の解説は 2016〜2019 年ごろの JavaScript が中心で、TypeScript での型付け、再接続、GATT 操作の衝突、対応ブラウザの現状までを通して扱ったものは見当たりませんでした。
この記事は、フロントエンドや Next.js / React の開発者、IoT アプリの開発者、そして「自社の BLE 機器を Web サービスにつなげたい」と考えている担当者に向けた実装ガイドです。
この記事で分かること
- Web Bluetooth で何ができて、何ができないか(Central 専用、アドバタイズ不可、MTU は読めない)
- 2026-11-17 時点の対応ブラウザと OS、仕様の位置づけ
- 最小のデモを動かす手順と、requestDevice から通知の購読までを TypeScript で型安全に書く方法
- 切断の検知、再接続、GATT 操作の直列化、エラー名ごとの対処、React での後始末
- Web Bluetooth ではなくネイティブアプリ、Web Serial、WebUSB、WebRTC を選ぶべき場面
短い結論: Web Bluetooth は、ブラウザを BLE の Central(GATT クライアント) にする API です。利用者が Chrome 系のブラウザを使える業務アプリや社内ツールでは有力な選択肢になります。しかし iPhone の Safari では動かず、仕様もまだ W3C の正式な標準ではありません。利用者の端末を選べるかどうかが、採用の分かれ目です。
この記事のコードについて:TypeScript のコードブロックはすべて、サンプルのリポジトリにあるファイルから一字一句コピーしたものです(コメントだけ日本語に訳しています)。vitest のユニットテストで検証していますが、Web Bluetooth の部分はテスト用のフェイクです。実ブラウザと実デバイスでの接続は未検証です。検証の範囲は第16章にまとめました。
1. Web Bluetooth とは何か
Web Bluetooth は、Web ページの JavaScript から近くの Bluetooth 機器を探し、接続し、データを読み書きするための API です。入口は navigator.bluetooth で、すべての操作は Promise と DOM イベントで返ってきます。これまで BLE 機器を扱うにはネイティブアプリが必要でしたが、Web Bluetooth なら URL を開くだけで機器の設定画面やデータの可視化を提供でき、ストアの審査も要りません。
1-1. Central と Peripheral、GATT クライアントとサーバー
仕様の導入部の説明では、BLE の Peripheral は接続を受ける側、Central は Peripheral に接続しにいく側です。これとは別に、データを公開する側を GATT サーバー、読み書きする側を GATT クライアントと呼びます。GATT(Generic Attribute Profile)は、機器が公開するデータの表の作り方を決める規格です。
Web Bluetooth の仕様は、最初の版の範囲を「Central のロールで動く UA(ブラウザ)が GATT サーバーに接続すること」と定めています。Chrome のドキュメントも同じ説明です。つまりブラウザは常に「つなぎにいく側」で、「つながれる側」にはなれません。そのためブラウザ同士は Bluetooth で直接つながれず、間に GATT サーバー役の機器が要ります。その実装はESP32 を中継役にした BLE チャットの記事で扱います。
1-2. ブラウザと OS の Bluetooth スタックの関係
ブラウザは無線を直接操作しません。Web ページの呼び出しは、ブラウザの Web Bluetooth 実装を経て OS の Bluetooth スタックに渡り、OS がコントローラー(無線チップ)を通して周辺機器とやり取りします。
この分担は、開発者に見える挙動を左右します。ブラウザ側では、選択画面の表示、権限、ブロックリストの照合、書き込みサイズ(512 バイト)の検査が行われます。OS 側では、ペアリング、ATT_MTU の交渉、接続の共有が行われます。仕様の connect() の手順には「Exchange MTU の手順で、対応する最大の MTU を交渉する」とあり、MTU はページではなく UA(実際には OS のスタック)が交渉します。また Chrome のドキュメントによると、device.gatt.disconnect() を呼んでも、別のアプリが同じ機器と通信していれば通信は止まりません。
次の図は、この縦の関係を上から順に並べたものです。上から、Web ページ、ブラウザの Web Bluetooth 実装(選択画面・権限・ブロックリスト・512 バイト検査)、OS の Bluetooth スタック(ペアリング・MTU 交渉・接続の共有)、Bluetooth コントローラー、そして GATT サーバーである周辺機器です。
Web ページ(JavaScript / TypeScript)
│ navigator.bluetooth(Promise と DOM イベント)
▼
ブラウザの Web Bluetooth 実装
・デバイス選択画面(chooser)と権限
・ブロックリスト、512 バイト上限の検査
▼
OS の Bluetooth スタック
・Windows / macOS / ChromeOS / Android / BlueZ
・ペアリング、ATT_MTU の交渉、接続の共有
▼
Bluetooth コントローラー(無線チップ)
│ 2.4 GHz
▼
周辺機器(GATT サーバー)
GATT、ATT、MTU が Bluetooth の階層のどこにあるかは、ピラー記事の BluetoothとWi-Fiの違いで詳しく説明しています。
2. できること・できないこと
次の表は、仕様と Chrome の実装で確認できた範囲です。
| 項目 | 可否 | 根拠と補足 |
|---|---|---|
| Central として GATT サーバーに接続 | できる | 仕様の範囲そのもの |
| サービス・キャラクタリスティックの読み書き | できる | readValue() / writeValueWithResponse() など |
| 通知(Notify / Indicate)の購読 | できる | startNotifications() |
| ブラウザがアドバタイズする・Peripheral になる | できない | IDL にアドバタイズを出す API が無い |
| 交渉後の ATT_MTU を読む | できない | 出荷中の API に無い(第14章) |
| GATT 以外のプロファイル(RFCOMM/SPP、オーディオなど) | できない | API は GATT だけを扱う。仕様に RFCOMM・L2CAP の語は出てこない |
serviceData での絞り込み | Chrome は未実装 | 仕様の IDL にはあるが、Chromium の IDL は TODO(crbug.com/707635) |
| HID サービスへのアクセス | できない | ブロックリストで除外(0x1812) |
| Web Worker からの利用 | できない | Exposed=Window のみ |
以前許可したデバイスの再取得(getDevices()) | Chrome はフラグの裏 | watchAdvertisements() も同じ |
仕様の導入部は「GATT は BR/EDR 上でも動く」と書き、BR/EDR 上の GATT サーバーへの接続も範囲に含めています。正確な言い方は「Classic には一切つながらない」ではなく「SPP/RFCOMM など GATT 以外は扱えない」です。HID の除外理由は、ブロックリストのコメントによると「キーボードのような HID 機器へ直接アクセスできると、Web ページがキーロガーになれる」からです。署名を検証しないファームウェア更新サービスや FIDO 関連の UUID も除外されています。
3. 2026年11月17日時点の対応状況と仕様の位置づけ
3-1. ブラウザと OS
対応状況は、MDN の browser-compat-data(BCD、コミット 3cb1804)と、仕様リポジトリの実装状況の文書で確認しました。
| 環境 | 状況 |
|---|---|
| Chrome(Windows・macOS・ChromeOS) | 既定で有効。BCD はデスクトップ版を Chrome 70 から「部分的な実装」と記録(56〜69 は macOS のみ) |
| Chrome(Linux) | 既定では無効。chrome://flags/#enable-experimental-web-platform-features を有効にする必要がある |
| Chrome(Android) | Chrome 56 から。Android 6.0 以上が必要 |
| Microsoft Edge | 実装状況の文書では version 79 から |
| Samsung Internet | 実装状況の文書では v6.4 から |
| Android の WebView | 未対応 |
| Firefox | 未対応。Mozilla の立場は negative |
| Safari(macOS・iOS) | 未対応。WebKit の立場は oppose |
| iOS の WebKit ベースのブラウザ | Safari と同じく未対応 |
OS の最低条件は、実装状況の文書によると OS X Yosemite、Windows 10 version 1703、Linux は Kernel 3.19 と BlueZ 5.41 以上です。Mozilla は「ユーザーの同意だけに頼る方針では保護として不十分で、ブロックリストに頼るモデルは持続しない」との立場です。WebKit の issue #570 はプライバシー、セキュリティ、デバイス非依存性の懸念を挙げて position: oppose で閉じられました(2025-12-02)。日本と EU で別エンジンが認められた iOS ブラウザが Web Bluetooth を提供しているかは、2026-11-17 時点で未確認です。BCD は API 全体を experimental としています。
3-2. 仕様の状態
Web Bluetooth の仕様は W3C Community Group のドラフト(Draft Community Group Report、最終更新 2026年6月3日)です。仕様の冒頭には「W3C の標準ではなく、W3C の標準化トラックにも乗っていない」と明記されています。
2026年8月には WHATWG が「Peripheral APIs」のワークストリーム(この Peripheral は周辺機器 API 全般の意味で、BLE の Peripheral ロールとは別)を設け、Serial、USB、HID、NFC と並んで Bluetooth を対象に含めました。リポジトリも whatwg/bluetooth に移り、仕様の URL は bluetooth.spec.whatwg.org になっています。ただし公開されている本文は 6月3日付の CG ドラフトのままで、「W3C 勧告」や「WHATWG の Living Standard」と呼ぶのは誤りです。
4. 使う前の3つの前提
4-1. HTTPS か localhost でしか使えない
仕様の IDL では、navigator.bluetooth に SecureContext の属性が付いています。このため http:// のページでは、プロパティそのものが undefined になり、例外は投げられません。
Secure Contexts 仕様の判定手順では、https のほか、ホストが 127.0.0.0/8 か ::1 のオリジンは無条件で「潜在的に信頼できる」とされます。localhost という名前も、それが必ずループバックに解決されるという規則を守るブラウザでは同じ扱いです。開発中に http://localhost:3000 で試せるのはこのためです。逆に、同じ LAN のスマートフォンから http://192.168.x.x で開くと使えません。実装上の結論は「navigator.bluetooth に直接触らない」です。
4-2. ユーザー操作とデバイス選択画面
requestDevice() は、クリックなどの直後(一時的なユーザーアクティベーションがある間)にしか呼べません。仕様は、アクティベーションが無ければ SecurityError を投げると定めています。Chrome のメッセージは "Must be handling a user gesture to show a permission request." です。
呼び出しに成功すると、ブラウザが選択画面(chooser)を出し、ページは利用者が選んだ1台だけを受け取ります。周囲の機器の一覧はページに渡りません。利用者が選択画面を閉じると、Chrome は NotFoundError("User cancelled the requestDevice() chooser.")で reject します。
重要なのは、ユーザー操作が要るのは requestDevice() だけだという点です。仕様の connect() の手順には、アクティベーションを確認する手順がありません。これが再接続の設計の土台になります。
4-3. Permissions-Policy と iframe
Web Bluetooth は Permissions Policy で制御され、トークンは bluetooth、既定の許可リストは ["self"] です。同じオリジンのページでは何もしなくても使え、別オリジンの iframe では使えません。別オリジンの iframe に許可するには、MDN によると、Permissions-Policy: bluetooth ヘッダーに許可するオリジンを書き、iframe にも allow="bluetooth" を付けます(BCD ではヘッダーの bluetooth は Chrome 104 から)。禁止されたページでは Chrome は SecurityError を返し、getAvailability() は false を返します。セキュリティヘッダーを一括設定しているサイトは、bluetooth=() で全面禁止していないか確認してください。
5. まず動かす:最小のデモ
仕組みに入る前に、心拍数を画面に出すだけの最小のデモを動かします。フレームワークは使いません。HTML はボタンと、状態の行と、測定値の行だけです。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Web Bluetooth heart rate demo</title>
</head>
<body>
<main>
<button id="connect" type="button">Connect a heart rate sensor</button>
<p id="status" role="status">Not connected</p>
<p id="reading" aria-live="polite">–</p>
</main>
<!-- Replace with the bundle built from demo-main.ts -->
<script type="module" src="./demo-main.js"></script>
</body>
</html>
ページのスクリプトは、要素を3つ受け取ってクリックを待ちます。
// フレームワークを使わないページ用スクリプト。ボタン1つ、状態1行、測定値1つ。
// 要素の型は構造的なので、DOM の無いテストでも動き、本物の
// HTMLButtonElement / HTMLElement もそのまま満たす。
import { BleConnection, type ConnectionState } from "./connection";
import { parseHeartRateMeasurement } from "./heart-rate";
import { pickHeartRateMonitor } from "./pick-device";
export interface DemoElements {
button: EventTarget & { disabled: boolean };
status: { textContent: string | null };
reading: { textContent: string | null };
}
const STATE_LABEL: Record<ConnectionState, string> = {
connecting: "Connecting…",
connected: "Connected",
reconnecting: "Reconnecting…",
disconnected: "Disconnected",
failed: "Connection failed",
};
export function mountHeartRateDemo({ button, status, reading }: DemoElements): () => Promise<void> {
let connection: BleConnection | undefined;
const onClick = async (): Promise<void> => {
// requestDevice() は最初の await より前、クリックのアクティベーション内で走る。
const picking = pickHeartRateMonitor();
button.disabled = true;
const picked = await picking;
if (!picked.ok) {
status.textContent = `No device selected (${picked.reason})`;
button.disabled = false;
return;
}
await connection?.disconnect();
connection = new BleConnection(picked.device, {
service: "heart_rate",
notifyCharacteristic: "heart_rate_measurement",
onNotification: (value) => {
try {
reading.textContent = `${parseHeartRateMeasurement(value).bpm} bpm`;
} catch {
reading.textContent = "Unreadable measurement";
}
},
onStateChange: (state) => {
status.textContent = STATE_LABEL[state];
},
});
try {
await connection.connect();
} catch {
// onStateChange("failed") で表示済み。
} finally {
button.disabled = false;
}
};
button.addEventListener("click", onClick);
return async () => {
button.removeEventListener("click", onClick);
await connection?.disconnect();
};
}
onClick は、最初の await より前に pickHeartRateMonitor() を呼びます。ボタンを無効にするのはその後です。requestDevice() をクリックのアクティベーションが有効な間に走らせるための順序です。接続は第8〜10章の BleConnection に任せ、通知が来るたびに第9章のパーサーで心拍数を取り出して「72 bpm」のように表示します。戻り値の関数は、リスナーを外して接続を切る後始末です。
入口のファイルは、HTML から要素を探して渡すだけです。
// index.html の入口。任意のバンドラーでこのファイルからバンドルし、
// https:// か http://localhost(セキュアコンテキスト)でページを配信する。
import { mountHeartRateDemo } from "./demo";
function element<T extends Element>(selector: string): T {
const found = document.querySelector<T>(selector);
if (!found) throw new Error(`Missing element ${selector}`);
return found;
}
mountHeartRateDemo({
button: element<HTMLButtonElement>("#connect"),
status: element<HTMLElement>("#status"),
reading: element<HTMLElement>("#reading"),
});
動かす手順は次のとおりです。
- サンプルのディレクトリの
web-bluetooth/から、index.htmlと、demo-main.tsが読み込む.tsファイル(demo.ts、connection.ts、heart-rate.ts、pick-device.ts、errors.ts、types.ts)をコピーする - 手元のバンドラーで
demo-main.tsを入口に1つの JavaScript にまとめ、index.htmlのscript要素が指すdemo-main.jsとして置く - そのフォルダーを
http://localhostの静的サーバーで配信し、Chrome で開く - ボタンを押し、選択画面で Heart Rate サービスを持つ機器を選ぶ
手元に心拍計が無い場合、Chrome のドキュメントは、Battery、Heart Rate、Health Thermometer のサービスを模擬する Android アプリ「BLE Peripheral Simulator」を勧めています。うまくつながらないときは、Chrome の about://bluetooth-internals を開くと、周囲の機器の状態、サービス、キャラクタリスティック、ディスクリプタを確認できます(同じドキュメントより)。なお、このデモも実機では動かしておらず、検証はフェイクを使ったテスト(3件)までです。
6. GATT の基礎と UUID
GATT サーバーは、データを Service(機能のまとまり)→ Characteristic(値を持つ項目)→ Descriptor(付帯情報)の3段で公開します。心拍計なら Heart Rate サービス(0x180D)の下に Heart Rate Measurement(0x2A37)があります。階層と ATT の関係はピラー記事で説明しています。
Web Bluetooth では、通知の購読状態を持つ CCCD(Client Characteristic Configuration、0x2902)を直接書き換えません。startNotifications() を呼ぶと、UA が CCCD のビットを立てます。ブロックリストでも 0x2902 は書き込み禁止で、理由は「書けると他のページの通知を妨害できる」からです。
UUID は、16 ビットの番号が 00000000-0000-1000-8000-00805f9b34fb の上位 32 ビットに入る形で 128 ビットに展開されます(仕様の canonicalUUID())。
16 ビット: 0x180D
128 ビット: 0000180d-0000-1000-8000-00805f9b34fb
^^^^^^^^ ここが置き換わる(残りは固定)
API には、数値(0x180d)、SIG が定めた名前の別名('heart_rate')、128 ビットの文字列のどれでも渡せます。文字列には落とし穴があり、仕様は有効な UUID 文字列を「小文字で、16 ビットや 32 ビットの省略形を使わないもの」と定め、それ以外を TypeError で reject します。データシートの大文字の UUID をそのまま貼ると動かないので、独自 UUID は小文字の定数として一か所で定義します。
7. 型から始める:TypeScript で Web Bluetooth を扱う
7-1. lib.dom に型は無い
TypeScript に同梱される lib.dom.d.ts には、Web Bluetooth の型がありません(このリポジトリの TypeScript 5.9.3 で BluetoothDevice は 0 件)。DefinitelyTyped の @types/web-bluetooth(最新は 2026-10-21 公開の 0.0.22)を入れるか、使う部分だけを自分で宣言します。このサンプルは後者です。
// このサンプルが使う Web Bluetooth API の部分集合。
// TypeScript の lib.dom.d.ts には Web Bluetooth の型が無いので、呼ぶものだけを
// モジュールの export として宣言する。完全な代替は @types/web-bluetooth だが、
// こちらはグローバルに型を宣言し、navigator.bluetooth を常に存在する型にする。
// そのため getBluetooth() のガードは残すこと。
export type BluetoothServiceUUID = number | string;
export type BluetoothCharacteristicUUID = number | string;
export interface BluetoothLEScanFilter {
services?: BluetoothServiceUUID[];
name?: string;
namePrefix?: string;
}
// 仕様は filters と acceptAllDevices の同時指定と、空の filters を拒否する。
// never のフィールドと空でないタプルで、どちらもコンパイルエラーにする。
export type RequestDeviceOptions =
| {
filters: [BluetoothLEScanFilter, ...BluetoothLEScanFilter[]];
acceptAllDevices?: never;
optionalServices?: BluetoothServiceUUID[];
}
| {
acceptAllDevices: true;
filters?: never;
optionalServices?: BluetoothServiceUUID[];
};
export interface BluetoothRemoteGATTCharacteristic extends EventTarget {
readonly uuid: string;
readonly value?: DataView;
readValue(): Promise<DataView>;
writeValueWithResponse(value: BufferSource): Promise<void>;
writeValueWithoutResponse(value: BufferSource): Promise<void>;
startNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
stopNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
}
export interface BluetoothRemoteGATTService {
readonly uuid: string;
getCharacteristic(
characteristic: BluetoothCharacteristicUUID,
): Promise<BluetoothRemoteGATTCharacteristic>;
}
export interface BluetoothRemoteGATTServer {
readonly connected: boolean;
connect(): Promise<BluetoothRemoteGATTServer>;
disconnect(): void;
getPrimaryService(service: BluetoothServiceUUID): Promise<BluetoothRemoteGATTService>;
}
export interface BluetoothDevice extends EventTarget {
readonly id: string;
readonly name?: string;
readonly gatt?: BluetoothRemoteGATTServer;
}
export interface Bluetooth {
getAvailability(): Promise<boolean>;
requestDevice(options: RequestDeviceOptions): Promise<BluetoothDevice>;
}
// SSR 中、Firefox と Safari、セキュアコンテキストでないページでは undefined を返す。
// navigator.bluetooth には直接触らない。
export function getBluetooth(): Bluetooth | undefined {
if (typeof navigator === "undefined") return undefined;
return (navigator as Navigator & { bluetooth?: Bluetooth }).bluetooth;
}
読みどころは三つです。
1. serviceData を入れていない。 仕様にはありますが、Chrome は実装していません。型にあると「書けば効く」と誤解させるので省いています。manufacturerData(BCD では Chrome 92 から)や exclusionFilters(同 Chrome 114 から)は必要なときに足します。
2. getBluetooth() が Bluetooth | undefined を返す。 @types/web-bluetooth 0.0.22 は interface Navigator { bluetooth: Bluetooth; } と宣言し、navigator.bluetooth を常に存在する型にします。実際には http:// や Firefox、Safari では undefined なので、型を信じて触ると実行時に TypeError で落ちます。undefined を型で表しておけば、未対応の分岐の書き忘れをコンパイラーが止めます。
3. 仕様が拒否する組み合わせを型で書けなくする。 仕様では filters と acceptAllDevices は排他で、どちらも無いオプションも空の filters も無効です。両方を書くと Chrome は実行時に TypeError("Either 'filters' should be present or 'acceptAllDevices' should be true, but not both.")を投げます。素朴な { filters } | { acceptAllDevices: true } では、過剰プロパティ検査がユニオンのどれかにあるキーを「余分」とみなさないため、両方を書いた形が通ってしまいます(筆者が TypeScript 5.9.3 で確認)。そこで相手のキーを never にし、filters を空でないタプルにしています。サンプルの types.test.ts は「両方」「どちらも無い」「空の filters」が型エラーになることを @ts-expect-error で固定しています。中身が空のフィルタ filters: [{}] だけは、この型でも検出できません。
7-2. TypeScript 5.7 以降と Uint8Array<ArrayBuffer>
後で見る write() の引数は Uint8Array<ArrayBuffer> です。TypeScript 5.7 で TypedArray がジェネリクスになり、5.9 の lib.d.ts の変更で ArrayBufferLike を持つ TypedArray が BufferSource に代入できない場面が出ました。リリースノートは Uint8Array<ArrayBuffer> と明示する対処を勧めています。この書き方には TypeScript 5.7 以降が必要です。
8. 接続までの流れ
8-1. 全体のデータフロー
利用者のクリックで requestDevice() を呼び、選ばれた BluetoothDevice を受け取ります。ユーザー操作が要るのはここだけです。次に device.gatt.connect() で接続し、getPrimaryService() でサービスを、getCharacteristic() でキャラクタリスティックを取得します。startNotifications() で購読し、characteristicvaluechanged イベントで DataView を受け取ります。切断されたら gattserverdisconnected イベントが届くので、待ってから gatt.connect() 以降をやり直します。
[クリック]
└ requestDevice({ filters }) ← ユーザー操作が必要
└ 選択画面 → BluetoothDevice
└ device.gatt.connect()
└ getPrimaryService("heart_rate")
└ getCharacteristic(
"heart_rate_measurement")
├ addEventListener(
│ "characteristicvaluechanged")
└ startNotifications()
└ イベントごとに DataView
[切断] gattserverdisconnected
└ 待機(バックオフ)→ gatt.connect() から再実行
8-2. requestDevice とフィルタ
// クリックハンドラー側。ユーザー操作が要るのは requestDevice() だけで、
// その後の connect や再接続には要らない。
import { classifyBleError, type BleFailure } from "./errors";
import { getBluetooth, type BluetoothDevice } from "./types";
export type PickResult =
| { ok: true; device: BluetoothDevice }
| { ok: false; reason: BleFailure };
// onClick から直接呼ぶ。先に時間のかかる処理を await しないこと。
// ユーザーアクティベーションは一時的で、requestDevice() の前に切れることがある。
export async function pickHeartRateMonitor(): Promise<PickResult> {
const bluetooth = getBluetooth();
if (!bluetooth) return { ok: false, reason: "unsupported" };
try {
const device = await bluetooth.requestDevice({
filters: [{ services: ["heart_rate"] }],
});
return { ok: true, device };
} catch (error) {
return { ok: false, reason: classifyBleError(error, "request") };
}
}
この関数は例外を投げず、判別共用体 PickResult を返します。ok で分岐するだけで、device が確実にある分岐と reason が分かる分岐に型で分かれます。requestDevice() の前に await を挟まないことも重要で、待ちを入れるとアクティベーションが失効して SecurityError になることがあります。
acceptAllDevices: true は周囲の機器をすべて出すので調査には便利ですが、利用者が無関係な機器を選ぶ余地を作ります。筆者の判断では、本番はサービス UUID か名前の接頭辞でフィルタするのが基本です。
8-3. optionalServices を忘れると SecurityError
接続後にアクセスできるのは、filters[].services か optionalServices に書いたサービスだけです(MDN)。リストに無いサービスを getPrimaryService() すると、Chrome は SecurityError("Origin is not allowed to access the service. Tip: Add the service UUID to 'optionalServices' in requestDevice() options.")で reject します。
心拍計の電池残量も読みたいなら、optionalServices: ['battery_service'] を書きます。接続中に追加する API は無く、足すには requestDevice() を(ユーザー操作つきで)呼び直す必要があります。必要になりうるサービスは、選択の時点で列挙しておきます。
8-4. gatt.connect、getPrimaryService、getCharacteristic
接続とサービスの取得は、BleConnection クラスにまとめています。まず外に見せる型です。
export type ConnectionState =
| "connecting"
| "connected"
| "reconnecting"
| "disconnected"
| "failed";
export interface RetryPolicy {
maxAttempts: number;
baseDelayMs: number;
maxDelayMs: number;
}
export interface BleConnectionOptions {
service: BluetoothServiceUUID;
notifyCharacteristic: BluetoothCharacteristicUUID;
writeCharacteristic?: BluetoothCharacteristicUUID;
onNotification: (value: DataView) => void;
onStateChange?: (state: ConnectionState, error?: unknown) => void;
retry?: RetryPolicy;
// 機器が二度とアドバタイズしないと、gatt.connect() は永遠に待ちうる。
connectTimeoutMs?: number;
}
const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;
const DEFAULT_RETRY: RetryPolicy = { maxAttempts: 5, baseDelayMs: 500, maxDelayMs: 8_000 };
状態を文字列リテラルのユニオンで表すのは、boolean の isConnected では「再接続中」と「諦めた」を区別できず、UI が「接続中…」のまま固まる原因になるからです。connectTimeoutMs は第10章で説明します。
次が、接続してから購読するまでの本体です(BleConnection クラスの抜粋)。
// 前回の接続のキャラクタリスティックは再接続後には古くなっているので、
// サービスの検索と購読を最初からやり直す。決着しない操作に詰まらされない
// よう、キューも新しく作る。
private async openSession(token: number): Promise<void> {
const gatt = this.device.gatt;
if (!gatt) throw new Error("Device has no GATT server");
const queue = new GattQueue();
const current = () => {
if (token !== this.session) throw new Error("superseded by a newer attempt");
};
await gatt.connect();
current();
const service = await queue.run(() => gatt.getPrimaryService(this.options.service));
current();
const notifyChar = await queue.run(() =>
service.getCharacteristic(this.options.notifyCharacteristic),
);
const writeUuid = this.options.writeCharacteristic;
const writeChar =
writeUuid === undefined ? undefined : await queue.run(() => service.getCharacteristic(writeUuid));
current();
this.detachCharacteristics();
this.queue = queue;
notifyChar.addEventListener("characteristicvaluechanged", this.handleValue);
this.notifyChar = notifyChar;
this.writeChar = writeChar;
await queue.run(() => notifyChar.startNotifications());
current();
}
private detachCharacteristics(): void {
this.notifyChar?.removeEventListener("characteristicvaluechanged", this.handleValue);
this.notifyChar = undefined;
this.writeChar = undefined;
}
private readonly handleValue = (event: Event): void => {
const value = (event.target as BluetoothRemoteGATTCharacteristic).value;
if (value) this.options.onNotification(value);
};
gatt.connect() は、接続済みならすぐに解決します(仕様の手順に「connected が true ならそのまま解決する」とあります)。そのため初回の接続にも再接続にも使えます。サービスの検索は、試行ごとに新しく作る GattQueue(第11章)を通して1つずつ実行します。current() は、各 await の後で「この試行がまだ最新か」を確かめる関数で、第10章のタイムアウトと組み合わせて働きます。リスナーを startNotifications() の 前 に登録するのは、購読直後の最初の通知を取りこぼさないためです。
event.target as BluetoothRemoteGATTCharacteristic は connection.ts で唯一の型アサーションです。このリスナーは notifyChar にしか登録しないので、target がキャラクタリスティックであることはコードの構造で保証されています。
9. 値の読み書きと通知
9-1. DataView で Heart Rate Measurement を解析する
キャラクタリスティックの値は、readValue() の戻り値でも characteristic.value でも DataView として届きます。オフセットとエンディアンを自分で指定して読むので、ここを型付きのパーサーにしておくのが、コードを安全にする一番の近道です。
題材は Heart Rate Measurement(0x2A37)です。GATT Specification Supplement の定義では、先頭 1 バイトがフラグです。bit0 が 0 なら心拍数は uint8、1 なら uint16。bit1 はセンサーの接触を検出したか、bit2 は接触の検出に対応しているか。bit3 が 1 なら Energy Expended(uint16)が、bit4 が 1 なら RR-Interval(uint16、単位は 1/1024 秒、複数可)が続きます。
次の図は、このバイト配置と、テストで使っている 8 バイトの例です。例はフラグ 0x18(bit3 と bit4 が 1)、心拍 80、Energy Expended 258、RR-Interval が 1024(1000 ms)と 512(500 ms)です。
byte 0 Flags
bit0 心拍の形式 0=uint8 / 1=uint16
bit1 センサーの接触を検出
bit2 接触の検出に対応
bit3 Energy Expended あり
bit4 RR-Interval あり
byte 1 心拍数 uint8(bit0=0 のとき)
byte 1-2 心拍数 uint16 LE(bit0=1 のとき)
次の 2 byte Energy Expended uint16 LE(bit3=1)
残り 2 byte ずつ RR-Interval uint16 LE(bit4=1)
例: 18 50 | 02 01 | 00 04 | 00 02
flags=0x18 bpm=80 | 258 | 1024 | 512
// Heart Rate Service(0x180D)の標準キャラクタリスティック
// Heart Rate Measurement(0x2A37)を解析する。形式が標準化されているので、
// このサービスを実装したセンサーなら1つのパーサーで扱える。
export type SensorContact = "unsupported" | "not-detected" | "detected";
export interface HeartRateMeasurement {
bpm: number;
sensorContact: SensorContact;
// 送られてきた uint16 のまま。利用者に見せる前に、
// Heart Rate Service の仕様書で単位を確認すること。
energyExpended?: number;
rrIntervalsMs: number[];
}
const FLAG_HR_UINT16 = 0x01;
const FLAG_CONTACT_DETECTED = 0x02;
const FLAG_CONTACT_SUPPORTED = 0x04;
const FLAG_ENERGY_PRESENT = 0x08;
const FLAG_RR_PRESENT = 0x10;
export function parseHeartRateMeasurement(view: DataView): HeartRateMeasurement {
if (view.byteLength < 2) {
throw new RangeError(`Heart Rate Measurement too short: ${view.byteLength} bytes`);
}
const flags = view.getUint8(0);
let offset = 1;
// GATT キャラクタリスティックの複数バイトのフィールドはリトルエンディアン。
const readUint16 = (): number => {
if (offset + 2 > view.byteLength) {
throw new RangeError(`Heart Rate Measurement truncated at byte ${offset}`);
}
const value = view.getUint16(offset, true);
offset += 2;
return value;
};
let bpm: number;
if (flags & FLAG_HR_UINT16) {
bpm = readUint16();
} else {
bpm = view.getUint8(offset);
offset += 1;
}
const sensorContact: SensorContact = !(flags & FLAG_CONTACT_SUPPORTED)
? "unsupported"
: flags & FLAG_CONTACT_DETECTED
? "detected"
: "not-detected";
const energyExpended = flags & FLAG_ENERGY_PRESENT ? readUint16() : undefined;
// RR-Interval の単位は 1/1024 秒。1回の通知に複数入ることがある。
// 末尾に奇数バイトが余ると、測定値全体を無効(RangeError)とする。
const rrIntervalsMs: number[] = [];
if (flags & FLAG_RR_PRESENT) {
while (offset < view.byteLength) {
rrIntervalsMs.push(Math.round((readUint16() * 1000) / 1024));
}
}
return { bpm, sensorContact, energyExpended, rrIntervalsMs };
設計のポイントは四つです。
- エンディアンを明示する。
getUint16(offset, true)のtrueがリトルエンディアンの指定です。省略するとビッグエンディアンで読み、300 bpm(バイト列2C 01)が 11265 に化けます。仕様の例もgetUint16(index, /*littleEndian=*/ true)です。 - 範囲外を読まない。 読む前に残りのバイト数を確かめ、足りなければどのバイトで切れたかを含む
RangeErrorを投げます。RR-Interval の後に奇数バイトが余った場合も、測定値全体を無効にします。 - センサー接触は3状態。 「非対応」と「接触していない」は意味が違うので、
booleanに潰しません。 - 単位を決めつけない。 仕様の例のコメントは "Meaning 750kJ." ですが、GATT Specification Supplement の単位の行は joule としか書いていません。分解能は Heart Rate Service の仕様書で確かめる必要があり、筆者は 2026-11-17 時点で未確認 です。そのため生の値を返しています。
9-2. writeValueWithResponse と writeValueWithoutResponse
| メソッド | ATT の手順 | 向いている用途 |
|---|---|---|
writeValueWithResponse() | Write Request。相手の応答を待つ | 設定値の変更など、確実に届いたか知りたい書き込み |
writeValueWithoutResponse() | Write Command。応答を待たない | 頻繁に送る小さなデータ。届かなくても次で取り戻せるもの |
以前からある writeValue() は仕様で非推奨("Deprecated. Use writeValueWithResponse() and writeValueWithoutResponse() instead.")で、BCD でも deprecated です。どちらの書き込みかがコードから読めないので、新しいコードでは使いません。新しい2つは BCD では Chrome 85 からです。サンプルの write() は確実性を優先して writeValueWithResponse() だけを使います(BleConnection クラスの抜粋)。
export class BleConnection {
private queue = new GattQueue();
private readonly retry: RetryPolicy;
private readonly connectTimeoutMs: number;
private notifyChar?: BluetoothRemoteGATTCharacteristic;
private writeChar?: BluetoothRemoteGATTCharacteristic;
private userClosed = false;
private busy = false;
private reconnecting = false;
// セッションを最後まで開けている間だけ true。その前に切れたリンク(自分の
// タイムアウトによる中断を含む)は接続の失敗であり、自動再接続の理由ではない。
private established = false;
// 試行ごとと disconnect() のたびに増える。タイムアウトに負けた試行は裏で
// 動き続けるが、このトークンで、新しい試行のものになった状態に触れさせない。
private session = 0;
constructor(
private readonly device: BluetoothDevice,
private readonly options: BleConnectionOptions,
) {
this.retry = options.retry ?? DEFAULT_RETRY;
this.connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
}
async connect(): Promise<void> {
if (this.busy) throw new Error("connect() is already in progress");
this.busy = true;
this.userClosed = false;
this.established = false;
// 同じリスナーを2回登録しても何も起きない。
this.device.addEventListener("gattserverdisconnected", this.handleDisconnected);
this.setState("connecting");
try {
await this.openSessionWithTimeout();
this.established = true;
this.setState("connected");
} catch (error) {
// その間に disconnect() が走っていれば、後始末は済んでいる。ここで機器に
// 触ると、同じ機器への新しい接続を中断させかねない(React の StrictMode は
// 同じ機器でマウント、アンマウント、マウントを行う)。
if (this.userClosed) throw error;
// そうでなければ、リスナーも半開きのリンクも残さない。
this.device.removeEventListener("gattserverdisconnected", this.handleDisconnected);
this.detachCharacteristics();
this.device.gatt?.disconnect();
this.setState("failed", error);
throw error;
} finally {
this.busy = false;
}
}
write(bytes: Uint8Array<ArrayBuffer>): Promise<void> {
const target = this.writeChar;
if (!target) return Promise.reject(new Error("Not connected"));
return this.queue.run(() => target.writeValueWithResponse(bytes));
}
// ユーザーによる切断: 監視をやめ、自動再接続もしない。
async disconnect(): Promise<void> {
this.userClosed = true;
this.established = false;
this.session += 1;
this.device.removeEventListener("gattserverdisconnected", this.handleDisconnected);
const notifyChar = this.notifyChar;
this.detachCharacteristics();
if (notifyChar && this.device.gatt?.connected) {
await this.queue.run(() => notifyChar.stopNotifications()).catch(() => undefined);
}
this.device.gatt?.disconnect();
this.setState("disconnected");
}
connect() の流れを順に見ます。
- 接続中や再接続中にもう一度呼ぶと、"connect() is already in progress" で reject します。同じ接続を二重に開かないためです。
- 失敗したとき、その間に
disconnect()が走っていれば、機器には触らずに例外だけを返します。後始末はdisconnect()が済ませており、ここでgatt.disconnect()を呼ぶと、同じ機器への新しい接続を巻き添えで切りかねないからです(React の StrictMode で起きる。第13章)。 - それ以外の失敗では、リスナーを外し、半開きのリンクを切ってから
failedを通知します。
write() は書き込み先を target に取り出してからキューに入れるので、順番待ちの間に切断されても失敗はそのまま呼び出し元に返ります。disconnect() は userClosed を立て、session を進めて進行中の試行を無効にし、購読を解除してから切断します。
ATT_MTU − 3 を超える writeValueWithoutResponse() を各プラットフォームがどう扱うかは、2026-11-17 時点で未確認 です。仕様と Chrome は 512 バイトの上限をどちらの書き込みにも課しますが、MTU を読めない現状では、応答なしの書き込みは「1回 20 バイト以内」から始めるのが安全側です。
9-3. startNotifications と characteristicvaluechanged
通知は startNotifications() で購読を始め、characteristicvaluechanged イベントで受け取り、値はイベントの target の value で読みます。仕様には「デバイスが切断されると、すべての通知は無効になる。再接続後も通知を受けたいサイトは startNotifications() を呼び直す必要があり、一部の通知を取りこぼす危険は避けられない」とあります。心拍のように最新値だけが意味を持つデータなら問題ありませんが、取りこぼせないデータには、連番を付けて欠けた範囲を再要求する仕組みがアプリ層に要ります。具体例はBLE チャットの記事の連番と確認応答の設計で扱います。
10. 切断と再接続
10-1. gattserverdisconnected
BLE の接続は、電波の範囲から出る、機器の電源が落ちるといった理由でいつでも切れ、そのとき BluetoothDevice に gattserverdisconnected イベントが届きます。仕様と Chrome のドキュメントによると、ページが自分で gatt.disconnect() を呼んだ場合も届きます。そのためイベントだけでは「利用者が切った」のか「勝手に切れた」のかを区別できず、サンプルでは userClosed フラグと、disconnect() で先にリスナーを外す順序で区別しています。
10-2. 再接続の戦略
再接続は三つの事実の上に組み立てます。
- 新しいユーザー操作は要らない(4-2 のとおり)。Chrome のドキュメントも、指数バックオフで再接続する「Automatic Reconnect」のサンプルを挙げています。
- 古いオブジェクトは使えない。 Chrome のドキュメントは、GATT の属性は切断で無効になるので再接続のたびに取得し直すよう書いています。古いキャラクタリスティックを使うと
InvalidStateError("GATT Characteristic no longer exists.")になります。 - 通知は購読し直す(9-3 のとおり)。
private readonly handleDisconnected = (): void => {
this.detachCharacteristics();
const wasEstablished = this.established;
this.established = false;
if (!wasEstablished || this.userClosed || this.reconnecting) return;
void this.reconnect();
};
// ユーザーが一度選んだデバイスは、新しいユーザー操作なしに gatt.connect() で
// 再接続できる。ユーザー操作が要るのは requestDevice() だけ。
private async reconnect(): Promise<void> {
this.reconnecting = true;
this.busy = true;
this.setState("reconnecting");
let lastError: unknown;
try {
for (let attempt = 0; attempt < this.retry.maxAttempts; attempt++) {
await sleep(backoffDelay(attempt, this.retry));
if (this.userClosed) return;
try {
await this.openSessionWithTimeout();
this.established = true;
this.setState("connected");
return;
} catch (error) {
if (this.userClosed) return;
lastError = error;
}
}
// 諦めるとき: 半開きのリンクを残さない。
this.detachCharacteristics();
this.device.gatt?.disconnect();
this.setState("failed", lastError);
} finally {
this.reconnecting = false;
this.busy = false;
}
}
private setState(state: ConnectionState, error?: unknown): void {
this.options.onStateChange?.(state, error);
}
}
切断イベントが来たら古いキャラクタリスティックからリスナーを外します。established は、セッションを最後まで開けている間だけ true で、確立前に切れたリンクは「接続の失敗」として扱い、自動再接続しません。reconnect() は「待ってから openSessionWithTimeout() を試す」を最大 maxAttempts 回くり返し、中の openSession() がサービスの検索から購読までを毎回やり直すので、三つの事実が一か所で満たされます。待っている間や試行の失敗後に利用者が切断していれば抜けます。諦めるときは、半開きのリンクを切ってから failed を通知します。
待ち時間は full jitter 方式の指数バックオフで決めます。
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
// Full jitter: [0, min(max, base * 2^attempt)] の範囲の乱数だけ待つ。
// 同じ周辺機器へ複数のタブが再接続しても、同時に再試行しないようにする。
export function backoffDelay(attempt: number, policy: RetryPolicy, random = Math.random): number {
const ceiling = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** attempt);
return Math.floor(random() * ceiling);
}
既定値(基準 500 ms、上限 8,000 ms)なら、1回目は 0〜499 ms、5回目は 0〜7,999 ms の範囲の乱数です。乱数で散らすのは、同じ機器に複数のタブが同時につなぎ直すと、再試行のタイミングがそろって衝突し続けるからです。
10-3. connect() が返ってこない場合に備えてタイムアウトを付ける
仕様の connect() の手順には「接続可能なアドバタイズを受信しなければ永遠に待ち続けることがある。接続を望まなくなったら、Web サイトは disconnect() を呼ぶべきだ」という注記があり、disconnect() は進行中の connect() を AbortError(Chrome のメッセージは "The GATT connect attempt was cancelled.")で中断させます。Chromium では、この中断は kWebBluetoothCancelConnect という機能フラグの裏にあり、main ブランチでは既定で有効です。どの安定版から有効かは未確認です。
タイムアウトが無いと、機器の電源が切れたままのとき gatt.connect() が返らず、状態が reconnecting のまま止まります。そこでサンプルは、初回も再接続の各試行も、openSession() をタイマーと競争させています(BleConnection クラスの抜粋)。
// gatt.disconnect() は保留中の connect() を AbortError で中断させる。
// 返ってこない試行はこの方法で打ち切る。
private async openSessionWithTimeout(): Promise<void> {
const token = ++this.session;
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
this.session += 1;
this.device.gatt?.disconnect();
reject(new DOMException(`connect timed out after ${this.connectTimeoutMs} ms`, "TimeoutError"));
}, this.connectTimeoutMs);
});
try {
await Promise.race([this.openSession(token), timeout]);
} finally {
clearTimeout(timer);
}
}
connectTimeoutMs(既定 10,000 ms)が過ぎると、session を進め、gatt.disconnect() で保留中の connect() を中断し、名前が TimeoutError の DOMException で reject します。Promise.race は負けた側を止めないので、タイムアウトした試行は裏で動き続けます。session が進んでいるため、その試行は次の current() で例外になり、新しい試行の notifyChar やキューを上書きできません。タイムアウトの gatt.disconnect() が確立前のリンクを切っても、established が false なので自動再接続は始まりません。10 秒は筆者の仮置きで、機器のアドバタイズ間隔に合わせて調整してください。
ページを再読み込みすると BluetoothDevice そのものが失われます。以前のデバイスを取り出す getDevices() は Chrome ではまだフラグの裏なので、再読み込み後は利用者にもう一度選んでもらう前提です。
11. GATT 操作を直列化する
読み書きと購読を並行して投げると、Chrome は重なった操作を NetworkError("GATT operation already in progress.")で拒否することがあります。Chromium のソースでは、macOS と Windows の実装はキャラクタリスティック単位で、読み取りか書き込みが保留中なら次の操作を拒否します。他の OS は未確認です。仕様も「今のところサイトは API の使用を直列化するか、失敗した操作を利用者が再試行できるようにする必要がある」と書き(Issue #188)、Chrome のドキュメントも「プラットフォームによってはエラーになる。手動でキューに入れることを強く勧める」と書いています。ただし、そのキューのコードはありません。
// Chrome は実行中の GATT 操作と重なった操作を拒否することがあるので、
// 読み書きと購読・購読解除はすべて1本の Promise チェーンを通す。
export class GattQueue {
private tail: Promise<unknown> = Promise.resolve();
run<T>(operation: () => Promise<T>): Promise<T> {
const result = this.tail.then(operation);
this.tail = result.catch(() => undefined);
return result;
}
}
run() は直前の操作が終わってから次を始め、その操作自身の結果を返します。要は this.tail = result.catch(() => undefined) で、result をそのまま tail にすると1つの失敗でチェーン全体が reject 状態になり、後続がすべて失敗します。失敗は result として返るので、握りつぶしてはいません。サンプルはこのキューを接続の試行ごとに作り直すので、決着しないまま止まった操作があっても、次の接続まで詰まらせません。
12. エラー処理:名前と呼び出しの段階で分ける
Web Bluetooth の reject はほとんどが DOMException ですが、同じ名前でも投げた呼び出しで意味が変わります。そこでサンプルでは、名前と「段階」(request か gatt か)の組で分類しています。
// Web Bluetooth の reject を、UI が対処できる場合分けに変換する。同じ
// DOMException の名前でも、投げた呼び出しによって意味が変わる。
// requestDevice() の NotFoundError はたいてい「ユーザーが選択画面を閉じた」で、
// getPrimaryService() の NotFoundError は「サービスが無い」を意味する。
export type BleFailure =
| "unsupported"
| "chooser-closed"
| "not-allowed"
| "not-found"
| "operation-unsupported"
| "gatt-failed"
| "stale-handle"
| "value-too-large"
| "timeout"
| "aborted"
| "invalid-argument"
| "unknown";
export type BlePhase = "request" | "gatt";
export function classifyBleError(error: unknown, phase: BlePhase): BleFailure {
// たとえば大文字の UUID 文字列や、filters と acceptAllDevices の同時指定。
if (error instanceof TypeError) return "invalid-argument";
if (!(error instanceof DOMException)) return "unknown";
switch (error.name) {
case "NotFoundError":
// Chrome の requestDevice() は "Bluetooth adapter not available." にも
// これを使う。両者を区別できるのはメッセージの文字列だけで、
// getAvailability() は電源の切れたアダプタを検出できないので、UI の文言は
// 「キャンセルしました」ではなく「デバイスが選択されませんでした」にする。
return phase === "request" ? "chooser-closed" : "not-found";
case "SecurityError":
// ユーザー操作が無い、ブロックリストの UUID、optionalServices に無い
// サービス、Permissions-Policy による拒否のいずれか。
return "not-allowed";
case "NotSupportedError":
// キャラクタリスティックがその操作に対応していない(たとえば読み取り専用の
// 値への notify)。Chrome はプラットフォーム非対応を NotFoundError で返すので、
// "unsupported" は getBluetooth() の側から来る。
return "operation-unsupported";
case "NetworkError":
// 切断、"GATT operation already in progress."(キューの不備)、
// "Not paired." のいずれか。再接続してから再試行する。
return "gatt-failed";
case "InvalidStateError":
return "stale-handle";
case "InvalidModificationError":
return "value-too-large";
// BleConnection 自身の接続タイムアウト。
case "TimeoutError":
return "timeout";
// gatt.disconnect() が保留中の connect() を中断した。
case "AbortError":
return "aborted";
default:
return "unknown";
}
}
TypeError(引数の誤り)を先に分け、それ以外の DOMException 以外は推測せずに unknown を返します。戻り値はユニオン型なので、UI 側の switch の網羅性をコンパイラーが確認できます。次の表は、主な失敗と、Chrome のソースにある名前とメッセージ、サンプルの分類の対応です。
| 状況 | 呼び出し | 名前と Chrome のメッセージ | 分類 | UI での対処 |
|---|---|---|---|---|
| 選択画面を閉じた | requestDevice | NotFoundError "User cancelled the requestDevice() chooser." | chooser-closed | 「デバイスが選択されませんでした」 |
| アダプタが無い | requestDevice | NotFoundError "Bluetooth adapter not available." | chooser-closed | 同上。Bluetooth の確認を促す |
| クリックの外で呼んだ | requestDevice | SecurityError "Must be handling a user gesture to show a permission request." | not-allowed | ボタンから呼ぶよう実装を直す |
| optionalServices に無い | getPrimaryService | SecurityError "Origin is not allowed to access the service. …" | not-allowed | 実装の修正 |
| ポリシーで禁止 | 各呼び出し | SecurityError "Access to the feature "bluetooth" is disallowed by permissions policy." | not-allowed | ヘッダーと iframe の設定 |
| 引数の誤り | requestDevice など | TypeError(大文字の UUID、filters と acceptAllDevices の同時指定) | invalid-argument | 実装の修正 |
| 許されない操作 | 読み書き・購読 | NotSupportedError "GATT operation not permitted." | operation-unsupported | プロパティを確認 |
| 切断中の操作 | GATT 全般 | NetworkError "GATT Server is disconnected. Cannot …" | gatt-failed | 再接続を待つ |
| 操作の衝突 | GATT 全般 | NetworkError "GATT operation already in progress." | gatt-failed | キューを通す |
| 古いオブジェクト | GATT 全般 | InvalidStateError "GATT Characteristic no longer exists." | stale-handle | 取り直す |
| 512 バイト超 | 書き込み | InvalidModificationError "Value can't exceed 512 bytes." | value-too-large | 分割する |
| 接続の中断 | gatt.connect | AbortError "The GATT connect attempt was cancelled." | aborted | 多くは自分の切断の結果 |
| 接続のタイムアウト | BleConnection | TimeoutError(サンプル自身が投げる) | timeout | 機器の電源と距離を確認 |
| 暗号化が必要 | 読み書き | SecurityError "GATT operation not authorized." または NetworkError "GATT Error: Not paired." | not-allowed / gatt-failed | OS でのペアリングを案内 |
SecurityError を段階によらず not-allowed にまとめるのは、どの原因も利用者ではなく実装か配信設定で直すものだからです。NotSupportedError は常に operation-unsupported です。Chrome のソースでは、プラットフォーム非対応は NotFoundError("Web Bluetooth is not supported on this platform…")で返り、unsupported は navigator.bluetooth が無い場合だけを意味します。request 段階の NotFoundError はキャンセルとアダプタ不在を区別できず、仕様の getAvailability() も「無線があれば電源の状態に関係なく true」なので、UI は「デバイスが選択されませんでした」という中立な文言にします。メッセージは実装依存なので、分岐には使わずログにだけ残します。
13. React で使う:ライフサイクルとクリーンアップ
原則は二つです。デバイスの選択はクリックハンドラーで行い、接続はエフェクトが所有して不要になったら必ず切ります。
// React との結合。デバイスはクリックハンドラー(ユーザー操作)で選んで渡す。
// エフェクトが接続を持ち、アンマウント時か別のデバイスが選ばれたときに片付ける。
import { useEffect, useState } from "react";
import { BleConnection, type ConnectionState } from "./connection";
import { parseHeartRateMeasurement, type HeartRateMeasurement } from "./heart-rate";
import type { BluetoothDevice } from "./types";
export interface HeartRateState {
connection: ConnectionState | "idle";
latest: HeartRateMeasurement | null;
error: unknown;
}
export function useHeartRate(device: BluetoothDevice | null): HeartRateState {
const [state, setState] = useState<HeartRateState>({
connection: "idle",
latest: null,
error: null,
});
useEffect(() => {
if (!device) return;
// 片付けた接続も状態を報告しうる(中断された connect() がクリーンアップ後に
// 失敗する。StrictMode はセットアップを2回走らせる)。それは無視する。
let active = true;
const connection = new BleConnection(device, {
service: "heart_rate",
notifyCharacteristic: "heart_rate_measurement",
onNotification: (value) => {
if (!active) return;
try {
const latest = parseHeartRateMeasurement(value);
setState((prev) => ({ ...prev, latest }));
} catch (error) {
// 不正な通知が1つ来てもページ全体を落とさない。
setState((prev) => ({ ...prev, error }));
}
},
onStateChange: (connectionState, error) => {
if (!active) return;
setState((prev) => ({ ...prev, connection: connectionState, error: error ?? null }));
},
});
connection.connect().catch(() => {
// onStateChange("failed", error) で通知済み。
});
return () => {
active = false;
void connection.disconnect();
// 前の機器の値を次の機器に持ち越さない。
setState({ connection: "idle", latest: null, error: null });
};
}, [device]);
return state;
}
コンポーネントでは、ボタンの onClick で pickHeartRateMonitor() を呼び、ok が true なら device を state に入れて useHeartRate(device) に渡します。requestDevice() をエフェクトで呼んではいけません。マウント時のエフェクトにはユーザー操作が無いので SecurityError になります。クリックで state を変えてエフェクトで呼ぶ形も、アクティベーションの有効期間に依存するので当てにできません。
依存配列は [device] なので、デバイスが変わるたびとアンマウント時に、古い接続の disconnect() が走ります。クリーンアップは状態も idle に戻すので、前の機器の測定値が次の機器に持ち越されません。
React の StrictMode は、開発時にすべてのエフェクトで「実行 → クリーンアップ」を1回余分に走らせます。このとき1つ目の接続の connect() は disconnect() で中断されて遅れて失敗しますが、二つの仕掛けで2つ目の接続を守っています。エフェクトごとの active フラグは、片付けた接続からのコールバックを捨てます。BleConnection.connect() は、disconnect() 済みなら失敗時に機器へ触れないので、同じ機器への2つ目の接続を切りません。BleConnection 側の挙動はフェイクを使ったテストで確かめましたが、フック自体にはテストが無く、実ブラウザでも確認していません。同じ機器での中断と再接続が重なる場合の Chrome の挙動は、実機で未確認です。
14. 本番で効く制約
14-1. 1回の値は 512 バイトまで、MTU は分からない前提で
属性値の最大長は、Core Specification の ATT(Vol 3 Part F)で 512 オクテットです。Web Bluetooth の仕様は書き込み時にこれを検査し、超えたら InvalidModificationError で reject すると定め、Chrome も "Value can't exceed 512 bytes." で同じエラーを返します。NetworkError ではない点に注意してください。
1回の書き込みや通知に乗る値の大きさは ATT_MTU で決まります。LE の既定の ATT_MTU は 23 で、Write Request や通知の値は最大 ATT_MTU − 3 です。
1回の値の上限 = ATT_MTU − 3(opcode 1 + handle 2)
既定(交渉なし): 23 − 3 = 20 バイト
交渉後の例: 247 − 3 = 244 バイト
(247 はよく使われる値で、仕様の定数ではない)
「BLE は最大 20 バイト」は誤りで、20 は既定の ATT_MTU のときの値です。ただし Web Bluetooth では交渉の結果をページから読む API が出荷されておらず、それを求める issue #383 は 2018 年から開いたままです。BluetoothRemoteGATTServer.maxWriteWithoutResponseSize を足す仕様の PR #672 は開いたままで、chromestatus は「Proposed」(予定マイルストーン 160)、BCD には項目がありません。Chromium の main ブランチでは既定で有効になっていますが、安定版での状態は未確認です。出荷後は機能検出で使い、無い環境向けの分割は残すのが安全です。
したがって 20 バイトを超えるデータは、MTU を知らない前提でアプリ層の分割と再組み立て(フレーム)を設計します。フレームの設計と実装はBLE チャットの記事で扱います。
14-2. ペアリングは OS 任せで、その場のペアリングは一部の OS だけ
暗号化が必要なキャラクタリスティックには、ペアリング(鍵を保存する場合はボンディング)が要ります。仕様は「UA はボンディングを試みてもよい(MAY)」とだけ書き、ページから制御する手段はありません。仕様の注記によると、macOS の Core Bluetooth がその制御を提供していないためです。実装状況の表で「On-demand device pairing」に印があるのは Android と Mac だけで、Windows、ChromeOS、Linux では OS の設定画面で先にペアリングしないと、暗号化されたキャラクタリスティックへのアクセスが失敗する可能性があります。実際の Windows での挙動は確認していません。暗号化を使う製品では、OS ごとのペアリング手順を利用者向けの案内に含めてください。
14-3. ページの寿命に縛られる
Web Bluetooth は Window でしか使えず、Worker からは呼べません。ページを閉じたり再読み込みしたりすると BluetoothDevice は失われ、getDevices() と watchAdvertisements() はフラグの裏、永続的な権限も chrome://flags/#enable-web-bluetooth-new-permissions-backend の裏です。「タブを閉じても計測を続けたい」「ページを開くと自動でつながってほしい」という要件は、2026-11-17 時点では満たせません。
15. Web Bluetooth を選ばない方がよい場面
次の表は、本記事の調査をもとに筆者が作った方式選定の目安です。対応状況は BCD と MDN で確認した範囲だけを書いています。
| 状況・要件 | 第一候補 | 理由 |
|---|---|---|
| 機器が BLE の GATT サーバーで、利用者は Chrome / Edge のデスクトップ(Linux はフラグが必要)か Android | Web Bluetooth | URL だけで配れる。ストアの審査が要らない |
| 利用者に iPhone / iPad が含まれる | ネイティブアプリ、またはネットワーク経由の構成 | Safari と iOS の WebKit 系ブラウザは非対応 |
| Android アプリに WebView で画面を埋め込む | ネイティブ側の BLE API | Android の WebView は Web Bluetooth に非対応 |
| ブラウザを Peripheral にしたい(アドバタイズしたい) | ネイティブアプリ | Web Bluetooth は Central 専用 |
| タブを閉じても接続を保つ、起動時に自動でつなぐ | ネイティブアプリ | Worker 不可、getDevices() はフラグの裏 |
| 機器が USB シリアル(CDC-ACM)や Bluetooth SPP の仮想シリアル | Web Serial | GATT ではなくシリアルポートとして見える機器 |
| 機器がクラスドライバの無い独自の USB デバイス | WebUSB | 独自 USB デバイスを Web に出すための API |
| ブラウザ同士、または遠くの端末とリアルタイムに通信 | WebRTC か WebSocket(サーバー経由) | Bluetooth は近距離で、ブラウザ同士は直接つながらない |
- Web Serial: MDN によると、シリアルポートのほか、USB や Bluetooth でシリアルポートを模倣する機器(USB CDC-ACM や Bluetooth SPP)を扱えます。BCD では Chrome 89 から、Android 版 Chrome は 148 から完全な対応です。Firefox は 151 からデスクトップで対応していますが、MDN のリリースノートによると、利用者がサイトごとの権限アドオンを入れる必要があります。Safari は未対応です。
- WebUSB: MDN は、標準クラスの機器は OS のクラスドライバが扱い、WebUSB はどのクラスにも当てはまらない機器のための API だと説明しています。BCD では Chrome 61 から。Firefox と Safari は未対応で、BCD は API 全体を実験的としています。
遠隔のリアルタイム通信は IP ネットワークの上で組み立てます。サーバー経由なら WebSocket や SSE が候補で、選び方はWebSocket と SSE の設計判断の記事で整理しています。BLE 機器のデータを遠隔に届けるなら、「機器 → Web Bluetooth のページ → WebSocket でサーバーへ」と、近距離と遠距離を別の手段でつなぐ構成が現実的です。
筆者の判断では、Web Bluetooth が最も活きるのは「利用者の端末を指定できる業務・社内向けの用途」です。現場のタブレットを Android に揃えられる、社内 PC が Chrome で統一されている、といった条件があれば、ネイティブアプリを作らずに済む利点は大きいでしょう。一般消費者向けで iPhone の利用者を外せないなら、最初からネイティブアプリを前提にした方が手戻りは少なくなります。
16. このコードをどう検証したか
記事の TypeScript は examples/bluetooth/web-bluetooth/ のファイルの転載で、記事のコードブロックがソースの連続した行と一致するかをテストで機械的に検査しています(訳したコメント行は比較から除外)。ユニットテストは vitest で、Web Bluetooth はフェイクで置き換えています。フェイクは Chrome より厳しく、機器単位で重なった操作を "GATT operation already in progress." で拒否し、サービスを検索するたびに新しいキャラクタリスティックを返して、再接続で古いオブジェクトが使えなくなる状況を再現します。
- 接続、購読、書き込みの直列化、切断後の再接続と購読のやり直し、試行を使い切ったときの後始末
- 返らない
connect()のタイムアウト、二重のconnect()の拒否、StrictMode のように同じ機器で接続が重なる場合 - Heart Rate Measurement の解析、エラーの分類、
RequestDeviceOptionsの型(@ts-expect-error)、デモのクリックから表示まで
実行結果は次のとおりです(2026-11-17、筆者の環境で実行)。
npx vitest run examples/bluetooth/web-bluetooth
RUN v4.1.4 /Users/tomodahinata/ProgrammingCode/products/portfolio
✓ examples/bluetooth/web-bluetooth/connection.test.ts (16 tests) 11ms
✓ examples/bluetooth/web-bluetooth/demo.test.ts (3 tests) 4ms
✓ examples/bluetooth/web-bluetooth/pick-device.test.ts (3 tests) 3ms
✓ examples/bluetooth/web-bluetooth/heart-rate.test.ts (5 tests) 2ms
✓ examples/bluetooth/web-bluetooth/errors.test.ts (6 tests) 2ms
✓ examples/bluetooth/web-bluetooth/types.test.ts (1 test) 1ms
Test Files 6 passed (6)
Tests 34 passed (34)
Start at 09:01:12
Duration 509ms (transform 45ms, setup 0ms, import 80ms, tests 22ms, environment 0ms)
テストが通ることは、実ブラウザと実デバイスで接続できることの証拠ではありません。選択画面、OS のペアリング、電波の状態、プラットフォームごとの差は再現していません。実ブラウザと実機での接続、10 秒のタイムアウトの妥当性、React フックの実際の挙動は、2026-11-17 時点で未検証です。
17. まとめ:本番投入前のチェックリスト
- 利用者のブラウザと OS を確認した(Chrome 系のみ。Linux はフラグ、Safari・iOS・Firefox・Android WebView は不可)
- HTTPS で配信し、
navigator.bluetoothに直接触らずundefinedの分岐を書いた -
requestDevice()はクリックハンドラーから直接呼び、その前にawaitを挟んでいない - 使うサービスはすべて
filters[].servicesかoptionalServicesに書いた - 独自 UUID は小文字の 128 ビット文字列で定義した
-
writeValue()ではなくwriteValueWithResponse()/writeValueWithoutResponse()を使い分けた - GATT 操作は1本のキューで直列化した
- 切断で古いオブジェクトを捨て、再接続でサービスの検索から購読までやり直す
- 再接続は full jitter のバックオフで、試行回数の上限と
connect()のタイムアウトを決めた - エラーは名前と段階の組で分類し、
chooser-closedを利用者を責める文言にしていない - 1回の書き込みは 512 バイト以下、MTU は不明の前提でフレームを設計した
- 暗号化が要る場合、OS ごとのペアリング手順を案内に含めた
- React ではエフェクトのクリーンアップで切断し、片付けた接続からの状態更新を無視する
Web Bluetooth は、条件が合えばインストール不要で BLE 機器とつながる Web アプリを実現できます。一方で、対応ブラウザ、仕様の成熟度、MTU やペアリングの不透明さという制約もはっきりしています。採用を判断する材料として、この記事のコードと表を使ってください。