在查找 liff.bluetooth.requestDevice() 的用途,發現一份Web Bluetooth文件,感覺又可以再寫個30天。而 Web Bluetooth 是什麼?我們可以直接利用它,在瀏覽器中與 Bluetooth Low Energy (低功耗藍芽裝置) 進行通訊。
掃描已連接的藍芽裝置,取得設備資訊。
// Don't filter devices receiving advertisement packets
liff.bluetooth.requestDevice().then(device => {
const listener = (e) => {
device.removeEventListener('advertisementreceived', listener);
};
device.addEventListener('advertisementreceived', listener);
device.watchAdvertisements();
}).catch(e => {
console.log(e.code + ':' + e.message);
});
// Filter devices receiving advertisement packets
liff.bluetooth.requestDevice({
filters: [
{
// ID of desired bluetooth device (BluetoothDevice.id)
deviceId: 't99137fe055dd4980b40f6ac526da7b0b'
}
]
}).then(device => {
const listener = (e) => {
device.removeEventListener('advertisementreceived', listener);
};
device.addEventListener('advertisementreceived', listener);
device.watchAdvertisements();
}).catch(e => {
console.log(e.code + ':' + e.message);
});
以上程式碼中,有兩段liff.bluetooth.requestDevice。其中的差別,在於執行方法的時候,有沒有傳入帶有filters屬性
的物件作參數。帶有filters屬性
的物件,可以在其中設定deviceId
,主要用在篩選BLE設備。假如用戶透過畫面按鈕觸發事件,執行此方法,且傳入物件參數,用戶可以從畫面得到依filters篩選條件的BLE設備。
執行liff.bluetooth.requestDevice,成功連接裝置後,可以從回傳物件中,找到gatt
物件。執行裝置的device.gatt.connect()
方法,可以連線到 GATT 服務端。接續執行device.gatt.getPrimaryService
、service.getCharacteristic
,就可以用得到的值,存取資料,控制裝置,如以下程式碼。
// Read and write characteristic values from LIFF app
device.gatt
.connect()
.then(async () => {
const service = await device.gatt.getPrimaryService(
'01234567-0123-0123-0123-012345678901'
);
const characteristic = await service.getCharacteristic(
'01234567-0123-0123-0123-012345678902'
);
const value = await characteristic.readValue();
// suppose we know it is a string, we can decode it
// here we use TextDecoder for simplicity, you should add a polyfill for compatibility
const stringValue = new TextDecoder().decode(value);
// to write string 'liff' into the characteristic
// here we use TextEncoder for simplicity, you should add a polyfill for compatibility
await characteristic.writeValue(new TextEncoder().encode('liff'));
})
.catch(e => {
console.log(e.code + ':' + e.message);
});
// Notify change in characteristic value from LINE Things device
device.gatt.connect().then(async () => {
const service = await device.gatt.getPrimaryService('01234567-0123-0123-0123-012345678901');
const characteristic = await service.getCharacteristic('01234567-0123-0123-0123-012345678903');
characteristic.addEventListener('characteristicvaluechanged', (e) => {
// suppose we know it is a 16-bit integer value
console.log('value changed to:' + e.target.value.getInt16();
});
await characteristic.startNotifications();
}).catch(e => {
console.log(e.code + ':' + e.message);
});
今天就淺淺的認識一下 liff.bluetooth.requestDevice(),
期待日後的認識Web Bluetooth容易嗎30天系列,欸不是!