Created by Masayuki Shiizu / @_shimizu
近距離無線通信技術Bluetoothの拡張仕様の一つで、極低電力で通信が可能なもの。2010年7月に発表されたBluetooth 4.0規格の一部として策定された。
対応チップは従来の1/3程度の電力で動作することができ、ボタン電池一つで数年稼働することができるとされている。
WebサイトからBLE(Bluetooth Low Energy)デバイスへ接続できるAPI。ブラウザだけでBLEデバイスに接続することができる。
navigator.bluetooth.requestDevice(options) //デバイスのスキャンを開始
.then(device => {
console.log("デバイスを取得しました", device);
return device.gatt.connect();
})
.then(server =>{
console.log("GATTサーバーに接続しました", server);
return server.getPrimaryService(SERVICE_UUID);
})
.then(service => {
console.log("サービスを取得しました", service);
return service.getCharacteristic(CHARACTERISTIC_UUID);
})
.then(chara => {
console.log("キャラクタリスティックを取得しました", chara);
chara.writeValue(value); //値を書き込む
})
.catch(error => {
console.log(error);
});
options.filters = [
{services: [LED_SERVICE_UUID]}, // <- 重要
{name: "BBC micro:bit [vaget]"}
];
navigator.bluetooth.requestDevice(options)
.then(device => {
bluetoothDevice = device;
console.log("device", device);
return device.gatt.connect();
})
.then(server =>{
console.log("server", server)
return server.getPrimaryService(LED_SERVICE_UUID);
})
.then(service => {
console.log("service", service)
return service.getCharacteristic(LED_TEXT_CHARACTERISTIC_UUID)
})
.then(chara => {
console.log("characteristic", chara)
alert("BLE接続が完了しました。");
characteristic = chara;
})
.catch(error => {
console.log(error);
});
//LEDに表示するメッセージを送信
function sendMessage() {
if (!bluetoothDevice || !bluetoothDevice.gatt.connected || !characteristic) return ;
var text = document.querySelector("#message").value;
var arrayBuffe = new TextEncoder().encode(text);
characteristic.writeValue(arrayBuffe);
}
options.filters = [
{services: [BUTTON_SERVICE_UUID]},
{name: "BBC micro:bit [vaget]"}
];
navigator.bluetooth.requestDevice(options)
.then(device => {
bluetoothDevice = device;
console.log("device", device);
return device.gatt.connect();
})
.then(server =>{
console.log("server", server)
return server.getPrimaryService(BUTTON_SERVICE_UUID);
})
.then(service => {
console.log("service", service);
return Promise.all([
service.getCharacteristic(BUTTON_A_CHARACTERISTIC_UUID),
service.getCharacteristic(BUTTON_B_CHARACTERISTIC_UUID)
]);
})
.then(chara => {
alert("BLE接続が完了しました。");
characteristic = chara;
chara[0].startNotifications();
chara[1].startNotifications();
chara[0].oncharacteristicvaluechanged = changeABtnEvent;
chara[1].oncharacteristicvaluechanged = changeBBtnEvent;
return chara;
})
.catch(error => {
console.log(error);
});
function changeABtnEvent(event) {
var value = event.currentTarget.value.getInt8(0);
if (value) console.log(value);
}
function changeBBtnEvent(evnet) {
var value = event.currentTarget.value.getInt8(0);
if (value) console.log(value);
}