このドキュメントでは、Bluetooth、Bluetooth ソケット、Bluetooth Low の使用方法について説明します。 Bluetooth デバイスおよび Bluetooth Low Energy デバイスと通信するための Energy API。
Bluetooth の背景情報については、公式の Bluetooth 仕様をご覧ください。
マニフェストの要件
Bluetooth を使用する Chrome アプリの場合、マニフェストに bluetooth エントリを追加し、 実装するプロファイル、プロトコル、サービスの UUID、および これらを実装するには、ソケット API や Low Energy API のいずれかまたは両方を使用します。
ソケットの実装の例を次に示します。
"bluetooth": {
"uuids": [ "1105", "1106" ],
"socket": true
}
Low Energy の実装の場合:
"bluetooth": {
"uuids": [ "180D", "1809", "180F" ],
"low_energy": true
}
アダプターの状態へのアクセス、付近のデバイスの検出、デバイスに関する基本情報の取得のみを行うため、 エントリ自体のみが必須です。
"bluetooth": {}
アダプター情報
アダプターの状態を取得する
Bluetooth アダプターの状態を取得するには、bluetooth.getAdapterState メソッドを使用します。
chrome.bluetooth.getAdapterState(function(adapter) {
console.log("Adapter " + adapter.address + ": " + adapter.name);
});
アダプターの通知
アダプターの状態が変化するたびに、bluetooth.onAdapterStateChanged イベントが送信されます。これにより、 アダプターの無線機の電源オン、オフの判断などに使用。
var powered = false;
chrome.bluetooth.getAdapterState(function(adapter) {
powered = adapter.powered;
});
chrome.bluetooth.onAdapterStateChanged.addListener(
function(adapter) {
if (adapter.powered != powered) {
powered = adapter.powered;
if (powered) {
console.log("Adapter radio is on");
} else {
console.log("Adapter radio is off");
}
}
});
デバイス情報
既知のデバイスを一覧表示する
Bluetooth アダプターが認識しているデバイスのリストを取得するには、bluetooth.getDevices を使用します。 メソッド:
chrome.bluetooth.getDevices(function(devices) {
for (var i = 0; i < devices.length; i++) {
console.log(devices[i].address);
}
});
ペア設定したデバイスや最近検出したデバイスを含め、すべてのデバイスが返品されます。機能しない 新しいデバイスの検出を開始する(付近のデバイスの検出をご覧ください)。
デバイスの通知を受信しています
bluetooth.getDevices を繰り返し呼び出す代わりに、 bluetooth.onDeviceAdded、bluetooth.onDeviceChanged、bluetooth.onDeviceRemoved 通知を受け取ることができます。
アダプターまたはデバイスが検出するたびに、bluetooth.onDeviceAdded イベントが送信されます。 次のようにしてアダプターに接続します。
chrome.bluetooth.onDeviceAdded.addListener(function(device) {
console.log(device.address);
});
このイベントのリスナーを追加しても、デバイスの検出は開始されません( デバイスをご覧ください)。
デバイスに加えられた変更は、以前に検出されたペア設定済みのデバイスを含め、 bluetooth.onDeviceChanged イベント:
chrome.bluetooth.onDeviceChanged.addListener(function(device) {
console.log(device.address);
});
最後に、ペア設定されたデバイスがデバイスから削除されるたびに bluetooth.onDeviceRemoved イベントが送信されます。 検出したデバイスが最近検出されていない、などです。
chrome.bluetooth.onDeviceRemoved.addListener(function(device) {
console.log(device.address);
});
付近のデバイスを検出しています
付近のデバイスの検出を開始するには、bluetooth.startDiscovery メソッドを使用します。Discovery は リソースを大量に消費するため、完了したら bluetooth.stopDiscovery を呼び出す必要がある。
アプリで付近のデバイスを検出する必要がある場合は、常に bluetooth.startDiscovery を呼び出します。
呼び出しに bluetooth.AdapterState の discovering
プロパティを条件としないでください。「
別のアプリが付近のデバイスを検出している場合でも呼び出しは成功し、アダプターは
他のアプリが停止した後も、引き続き検出を実行します。
新しく検出された各デバイスに関する情報は、bluetooth.onDeviceAdded を使用して受信されます。 イベントです。最近検出されたデバイス、または以前にペア設定されたデバイスの場合 イベントは送信されません。代わりに bluetooth.getDevices を呼び出して、 現在の情報を取得し、bluetooth.onDeviceChanged イベントを使用して、 情報が変更されることがあります。
例:
var device_names = {};
var updateDeviceName = function(device) {
device_names[device.address] = device.name;
};
var removeDeviceName = function(device) {
delete device_names[device.address];
}
// Add listeners to receive newly found devices and updates
// to the previously known devices.
chrome.bluetooth.onDeviceAdded.addListener(updateDeviceName);
chrome.bluetooth.onDeviceChanged.addListener(updateDeviceName);
chrome.bluetooth.onDeviceRemoved.addListener(removeDeviceName);
// With the listeners in place, get the list of devices found in
// previous discovery sessions, or any currently active ones,
// along with paired devices.
chrome.bluetooth.getDevices(function(devices) {
for (var i = 0; i < devices.length; i++) {
updateDeviceName(devices[i]);
}
});
// Now begin the discovery process.
chrome.bluetooth.startDiscovery(function() {
// Stop discovery after 30 seconds.
setTimeout(function() {
chrome.bluetooth.stopDiscovery(function() {});
}, 30000);
});
ユーザーが Bluetooth 無線をオフにすると、すべての検出セッションが終了し、再開されません。
自動的にオンになります。これがアプリにとって重要な場合は、
bluetooth.onAdapterStateChanged イベントにアタッチされています。discovering
プロパティが false
に変更された場合、次のようになります。
アプリで再開するには、bluetooth.startDiscovery を再度呼び出す必要があります。ただし、
リソースを大量に消費します
デバイスの識別
から返されたデバイスを識別するために、さまざまなオプションが用意されています。 bluetooth.getDevices と関連するイベント。
デバイスが Bluetooth のデバイス ID 仕様をサポートしている場合、いくつかのプロパティが Bluetooth デバイスに追加されます。 その仕様で定義されているフィールドを含む Device オブジェクト。例:
chrome.bluetooth.getDevices(function(devices) {
for (var i = 0; i < devices.length; i++) {
if (devices[0].vendorIdSource != undefined) {
console.log(devices[0].address + ' = ' +
devices[0].vendorIdSource + ':' +
devices[0].vendorId.toString(16) + ':' +
devices[0].productId.toString(16) + ':' +
devices[0].deviceId.toString(16));
}
}
});
通常、デバイス ID の仕様で、特定のモデル、さらにはリビジョンを識別し、
ダウンロードします。このフィールドが存在しない場合は、代わりに
デバイスのクラスまたはタイプ。必要に応じて address
でメーカーの接頭辞と組み合わせることができます。
ほとんどの Bluetooth デバイスは、デバイスのクラス情報を、
Baseband Assigned Numbers のドキュメントを参照してください。このビットフィールドは deviceClass
にあります。
プロパティです。
chrome.bluetooth.getDevices(function(devices) {
for (var i = 0; i < devices.length; i++) {
if (devices[0].vendorIdSource != undefined) {
console.log(devices[0].address + ' = ' +
devices[0].deviceClass.toString(16));
}
}
});
フィールドの解析は複雑な場合があるため、最も一般的なデバイスタイプでは Chrome が自動的に処理します。
type
フィールドを設定します。これを利用できない場合、またはニーズに対して不十分な場合は、以下を行う必要があります。
deviceClass
を自分で解析します。
chrome.bluetooth.getDevices(function(devices) {
for (var i = 0; i < devices.length; i++) {
if (devices[0].vendorIdSource != undefined) {
console.log(devices[0].address + ' = ' + devices[0].type);
}
}
});
RFCOMM と L2CAP の使用
Chrome アプリは、RFCOMM または L2CAP サービスをサポートする任意のデバイスに接続できます。例 従来の Bluetooth デバイスの大半で使用されています。
ソケットへの接続
デバイスに接続するには 3 つのデバイスが必要です。接続するためのソケット bluetoothSocket.create を使用して作成された接続するデバイスのアドレス サービス自体の UUID が必要です
接続する前に、 bluetooth.getDevice またはデバイス検出 API。
基盤となる接続を確立するために必要な情報(RFCOMM または L2CAP プロトコルを使用する必要があり、どのチャネルまたは PSM は、VPC ネットワークでの SDP ディスカバリを使用して取得されます。 ダウンロードします
例:
var uuid = '1105';
var onConnectedCallback = function() {
if (chrome.runtime.lastError) {
console.log("Connection failed: " + chrome.runtime.lastError.message);
} else {
// Profile implementation here.
}
};
chrome.bluetoothSocket.create(function(createInfo) {
chrome.bluetoothSocket.connect(createInfo.socketId,
device.address, uuid, onConnectedCallback);
});
後でこのアドレスにデータ(bluetoothSocket.send)を送信できるように、socketId へのハンドルを保持します。 あります。
ソケットとの送受信
ソケットとの間でのデータの受信と送信には ArrayBuffer
オブジェクトを使用します。ArrayBuffers について学ぶには、
概要、JavaScript 型配列、チュートリアル ArrayBuffer を変換する方法
String との相互変換をご覧ください。
arrayBuffer
にあるデータを送信するには、bluetoothSocket.send を使用します。
chrome.bluetoothSocket.send(socketId, arrayBuffer, function(bytes_sent) {
if (chrome.runtime.lastError) {
console.log("Send failed: " + chrome.runtime.lastError.message);
} else {
console.log("Sent " + bytes_sent + " bytes")
}
})
データを送信するメソッドとは対照的に、このメソッドはイベント イベントで (bluetoothSocket.onReceive.ソケットが一時停止せずに作成される(bluetoothSocket.setPaused を参照) そのため、このイベントのリスナーは通常、bluetoothSocket.create と bluetoothSocket.connect。
chrome.bluetoothSocket.onRecieve.addListener(function(receiveInfo) {
if (receiveInfo.socketId != socketId)
return;
// receiveInfo.data is an ArrayBuffer.
});
ソケットエラーと切断が発生する
切断などのソケットエラーの通知を受け取るには、 bluetoothSocket.onReceiveError イベントが返されます。
chrome.bluetoothSocket.onReceiveError.addListener(function(errorInfo) {
// Cause is in errorInfo.error.
console.log(errorInfo.errorMessage);
});
ソケットからの切断
接続を切断してソケットを切断するには、bluetoothSocket.disconnect を使用します。
chrome.bluetoothSocket.disconnect(socketId);
公開サービス
Chrome アプリは、デバイスに対してアウトバウンド接続を行うほかに、次のようなサービスを公開することがあります。 RFCOMM または L2CAP をサポートする デバイスで使用する必要があります
ソケットでのリッスン
2 種類の公開サービスがサポートされています。RFCOMM は最も一般的に使用され、 主なデバイスとプロファイル:
var uuid = '1105';
chrome.bluetoothSocket.create(function(createInfo) {
chrome.bluetoothSocket.listenUsingRfcomm(createInfo.socketId,
uuid, onListenCallback);
});
もう 1 つは L2CAP で、他のデバイスタイプやベンダー固有の用途(ファームウェアなど)に対応しています。 アップロード中。
var uuid = '0b87367c-f188-47cd-bc20-a5f4f70973c6';
chrome.bluetoothSocket.create(function(createInfo) {
chrome.bluetoothSocket.listenUsingL2cap(createInfo.socketId,
uuid, onListenCallback);
});
いずれの場合も、オプションの bluetoothSocket.ListenOptions を渡して、
チャネル(PSM)ですコールバックが chrome.runtime.lastError
を介してエラーと成功を示す
できません。後で接続を受け入れられるように、socketId へのハンドルを保持します。
(bluetoothSocket.onAccept など)。
クライアント接続の受け入れ
クライアント接続は受け入れられ、 bluetoothSocket.onAccept イベントと接続される。
chrome.bluetoothSocket.onAccept.addListener(function(acceptInfo) {
if (info.socketId != serverSocketId)
return;
// Say hello...
chrome.bluetoothSocket.send(acceptInfo.clientSocketId,
data, onSendCallback);
// Accepted sockets are initially paused,
// set the onReceive listener first.
chrome.bluetoothSocket.onReceive.addListener(onReceive);
chrome.bluetoothSocket.setPaused(false);
});
クライアント接続の受け入れを停止する
クライアント接続の受け入れを停止し、サービスの公開を停止するには、bluetoothSocket.disconnect を使用します。
chrome.bluetoothSocket.disconnect(serverSocketId);
Low Energy デバイスの操作
Bluetooth Low Energy(Bluetooth Smart)は、電力の消費を抑えることを目的としたワイヤレス技術です。 できます。Bluetooth Low Energy API を使用すると、アプリで中心的な役割を実装できます。 接続されています。以降のセクションでは、 Bluetooth Low Energy の周辺機器との通信を可能にします。
周辺機器の検出と接続
従来の Bluetooth デバイスと同様に、LE 周辺機器は次の方法で検出できます。
付近のデバイスを検出するをご覧ください。LE デバイスはデータパケットを送信することで自身を検出可能にする
「広告データ」と呼ばれるものですデバイスはアドバタイジング モードになっています。広告データ
デバイスで使用可能なサービスの UUID が含まれている可能性があります。存在する場合、これらの UUID は
対応する bluetooth.Device オブジェクトの uuids
プロパティを使用してアクセスできる。
検出後、bluetoothLowEnergy.connect を呼び出して LE デバイスを接続し、 アプリケーションがそのサービスとやり取りできます。
chrome.bluetooth.onDeviceAdded.addListener(function(device) {
var uuid = '0000180d-0000-1000-8000-00805f9b34fb';
if (!device.uuids || device.uuids.indexOf(uuid) < 0)
return;
// The device has a service with the desired UUID.
chrome.bluetoothLowEnergy.connect(device.address, function () {
if (chrome.runtime.lastError) {
console.log('Failed to connect: ' + chrome.runtime.lastError.message);
return;
}
// Connected! Do stuff...
...
});
});
接続されると、対応する bluetooth.Device オブジェクトの connected
プロパティが
値は true
です。bluetoothLowEnergy.connect を呼び出すと、
デバイスに物理的に接続する必要があります。デバイスとの物理的な接続が存在する可能性がある
bluetoothLowEnergy.connect を(別のアプリケーションなどで)呼び出すことなく、接続できます。イン
この場合、アプリはデバイスのサービスと引き続きやり取りできますが、
他のアプリが接続を解除できないようにするには、常に bluetoothLowEnergy.connect を呼び出します。
構成されます
アプリケーションを接続する必要がなくなったら、 bluetoothLowEnergy.disconnect を呼び出します。
chrome.bluetoothLowEnergy.disconnect(deviceAddress);
ただし、デバイスへの物理リンクが破棄されるとは限りません。別のリンクが存在する可能性があるため、 接続している複数のアプリケーションを検出できます。場合によっては、デバイスが アプリが制御できない理由によって接続が切断された場合(例: デバイスが ユーザーがオペレーティング システムのユーティリティを使用して消去または明示的に接続を解除した場合)。 アプリで bluetooth.onDeviceChanged イベントを監視して、変更の通知を取得する必要があります。 必要に応じて再接続します。
接続が終わると、Chrome を実行しているデバイスは、いわゆる中心的なロールに属し、Chrome を実行するデバイスは リモート デバイスは周辺機器ロールにあると見なされます。この時点で、アプリケーションは 以下のセクションで説明する方法で、デバイス上のサービスとの接続を確立する必要があります。注: 現在のところ、API は LE ペリフェラルとしての動作をサポートしていません。アプリは中心的なロールのみを実装できます。
サービス、特性、記述子
Bluetooth Low Energy は、属性プロトコルと呼ばれるシンプルなリクエスト / レスポンス プロトコルをベースにしています。 (ATT)。中央デバイスは ATT を使用して、周辺機器のいわゆる属性とやり取りします Generic Attribute Profile(GATT)と呼ばれる特別な Bluetooth プロファイルに準拠します。ガット では、次の大まかな概念を定義しています。
- サービス: GATT サービスは、次のことを達成するためのデータのコレクションとそれに関連する動作を表します。 特定の機能に対するアクセスをブロックします。たとえば、心拍数モニターは通常、 1 つ目は「心拍数サービス」ですGATT サービスに関する情報は、 bluetoothLowEnergy.Service オブジェクトもあるからです。
- 特性: GATT 特性は、GATT サービスの構築に使用される基本的なデータ要素です。 値と、その値へのアクセス方法を定義するプロパティが含まれます。たとえば 「心拍数サービス」の「心拍数測定」機能があるモデルのパフォーマンスを ユーザーの心拍数の値。GATT 特性に関する情報は、 bluetoothLowEnergy.Characteristic オブジェクトを使用すると、
- 記述子: GATT 特性記述子には、特性に関する追加情報が含まれます。 GATT 特性記述子に関する情報は、 bluetoothLowEnergy.Descriptor オブジェクトを使用できます。
Bluetooth Low Energy API を使用すると、アプリがデバイスの Bluetooth に関する情報を検出し、
bluetoothLowEnergy.getServices を呼び出して、サービス、特性、記述子を
bluetoothLowEnergy.getCharacteristics、bluetoothLowEnergy.getDescriptors などの属性を実装します。アプリは
uuid
フィールドを
必要な GATT UUID:
chrome.bluetoothLowEnergy.getServices(deviceAddress, function(services) {
...
for (var i = 0; i < services.length; i++) {
if (services[i].uuid == HEART_RATE_SERVICE_UUID) {
heartRateService = services[i];
break;
}
}
...
});
API でアクセスできる各サービス、特性、記述子には、一意の ID と
インスタンス ID。instanceId
フィールドで取得できます。このインスタンス ID は、
を使用して GATT オブジェクトを識別し、GATT オブジェクトに対して特定のオペレーションを実行します。
chrome.bluetoothLowEnergy.getCharacteristics(heartRateService.instanceId,
function(chracteristics) {
...
for (var i = 0; i < characteristics.length; i++) {
if (characteristics[i].uuid == HEART_RATE_MEASUREMENT_UUID) {
measurementChar = characteristics[i];
break;
}
}
...
chrome.bluetoothLowEnergy.getDescriptors(measurementChar.instanceId,
function(descriptors) {
...
});
});
サービス イベント
デバイスが接続されると、Chrome はそのサービスを検出します。各サービスが検出されると 削除された場合、アプリは bluetoothLowEnergy.onServiceAdded を受け取り、 bluetoothLowEnergy.onServiceRemoved イベントを実装する場合:
var initializeService = function(service) {
if (!service) {
console.log('No service selected!');
// Reset UI, etc.
...
return;
}
myService = service;
// Get all the characteristics and descriptors and bootstrap the app.
...
};
chrome.bluetoothLowEnergy.onServiceAdded.addListener(function(service) {
if (service.uuid == MY_SERVICE_UUID)
initializeService(service);
});
chrome.bluetoothLowEnergy.onServiceRemoved.addListener(function(service) {
if (service.instanceId == myService.instanceId)
initializeService(null);
});
Chrome はサービスのすべての特性と記述子を非同期で検出し、 bluetoothLowEnergy.onServiceAdded イベントが送信されると、このイベントが発生します。外部 IP アドレスへの接続が 終了すると、Chrome はすべての関連サービスを削除し、 bluetoothLowEnergy.onServiceRemoved イベントを検出しました。
周辺機器によっては、アプリケーションの特性によって、 サービスが追加または削除される可能性があります。Chrome は、 bluetoothLowEnergy.onServiceChanged、bluetoothLowEnergy.onServiceAdded bluetoothLowEnergy.onServiceRemoved イベント。
chrome.bluetoothLowEnergy.onServiceChanged.addListener(function(service) {
if (service.instanceId != myService.instanceId)
return;
updateMyService(service);
});
特性値の読み取りと書き込み
GATT 特性は、そのサービスの 1 つの側面をエンコードします。中央のアプリがデータの読み取り、操作、 特性の値に基づいて動作することで、周辺機器のサービスの状態を変化させます。特徴 value はバイトのシーケンスであり、その意味は、 ある程度の特性があります。(心拍数測定の特性の値など)。 ユーザーの心拍数と消費カロリーの総量をエンコードし、ボディセンサーは 位置情報は、心拍センサーを身体のどこに装着するかをエンコードします。
Chrome には bluetoothLowEnergy.readCharacteristicValue メソッドがあり、 特徴:
chrome.bluetoothLowEnergy.readCharacteristicValue(chrc.instanceId,
function(result) {
if (chrome.runtime.lastError) {
console.log('Failed to read value: ' + chrome.runtime.lastError.message);
return;
}
var bytes = new Uint8Array(result.value);
// Do stuff with the bytes.
...
});
一部の特性は書き込み可能です。特に、「コントロール ポイント」として動作する特性には、 副作用がありますたとえば、心拍数のコントロール ポイント特性は、 合計消費カロリーのカウントをリセットするように心拍数センサーに指示し、書き込みのみをサポートします。宛先 そのために、Chrome には bluetoothLowEnergy.writeCharacteristicValue メソッドが用意されています。
var myBytes = new Uint8Array([ ... ]);
chrome.bluetoothLowEnergy.writeCharacteristicValue(chrc.instanceId,
myBytes.buffer,
function() {
if (chrome.runtime.lastError) {
console.log('Failed to write value: ' +
chrome.runtime.lastError.message);
return;
}
// Value is written now.
});
特性記述子も同じように動作し、読み取り/書き込みが可能です。Chrome は、 bluetoothLowEnergy.readDescriptorValue と bluetoothLowEnergy.writeDescriptorValue を メソッドを使用すると、記述子の値を読み書きできます。
特性が読み取りまたは書き込みをサポートしているかどうかを確認するには、アプリで properties
bluetoothLowEnergy.Characteristic オブジェクトのフィールド フィールドを使用することもあるこのフィールドには
セキュリティ要件に関する情報が格納されていますが、
一般的な動作を表します。
値の通知の処理
一部の特性は、通知または表示を使用してその価値を知らせます。たとえば、 心拍数測定の特性は読み取りも書き込みもできませんが、 現在の値を定期的に確認できます。アプリケーションは、 bluetoothLowEnergy.onCharacteristicValueChanged イベントを使用しており、
chrome.bluetoothLowEnergy.onCharacteristicValueChanged.addListener(
function(chrc) {
if (chrc.instanceId != myCharId)
return;
var bytes = new Uint8Array(chrc.value);
// Do stuff with the bytes.
...
});
特性が通知/表示をサポートしていても、デフォルトでは有効になっていません。「 アプリは bluetoothLowEnergy.startCharacteristicNotifications を呼び出して、 bluetoothLowEnergy.stopCharacteristicNotifications メソッドを使用すると、 bluetoothLowEnergy.onCharacteristicValueChanged イベント、
// Start receiving characteristic value notifications.
var notifying = false;
chrome.bluetoothLowEnergy.startCharacteristicNotifications(chrc.instanceId,
function() {
if (chrome.runtime.lastError) {
console.log('Failed to enable notifications: ' +
chrome.runtime.lastError.message);
return;
}
notifying = true;
});
...
// No longer interested in notifications from this characteristic.
if (notifying) {
chrome.bluetoothLowEnergy.stopCharacteristicNotifications(
chrc.instanceId);
}
通知が開始されると、アプリケーションは bluetoothLowEnergy.onCharacteristicValueChanged 通知または表示が変更されるたびに 受信するメッセージの数です。特性が読み取りをサポートしている場合、このイベントも bluetoothLowEnergy.readCharacteristicValue の呼び出しが成功した後に送信されます。これにより、アプリが 次のようにして、読み取りリクエストと通知によってトリガーされる値更新の制御フローを統合します。
chrome.bluetoothLowEnergy.onCharacteristicValueChanged.addListener(
function(chrc) {
// Process the value.
...
});
chrome.bluetoothLowEnergy.startCharacteristicNotifications(chrc.instanceId,
function() {
// Notifications started. Read the initial value.
chrome.bluetoothLowEnergy.readCharacteristicValue(chrc.instanceId,
function(result) {
...
// No need to do anything here since onCharacteristicValueChanged
// will handle it.
});
});
特性が通知をサポートしている場合、その properties
フィールドには
"notify"
または "indicate"
プロパティ。
注: 特性が通知/表示をサポートしている場合、 特性の構成」をご覧ください。通知を有効または無効にすることができます。Chrome で許可しない この記述子に書き込みます。代わりに、 bluetoothLowEnergy.startCharacteristicNotifications と 通知の動作を制御する bluetoothLowEnergy.stopCharacteristicNotifications メソッド。