iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 29
1
Modern Web

認識LIFF容易嗎?系列 第 29

[Day 29] LIFF Bluetooth RequestDevice

  • 分享至 

  • xImage
  •  

前言

在查找 liff.bluetooth.requestDevice() 的用途,發現一份Web Bluetooth文件,感覺又可以再寫個30天。而 Web Bluetooth 是什麼?我們可以直接利用它,在瀏覽器中與 Bluetooth Low Energy (低功耗藍芽裝置) 進行通訊。

liff.bluetooth.requestDevice()

掃描已連接的藍芽裝置,取得設備資訊。

實作

// 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.getPrimaryServiceservice.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天系列,欸不是!

參考


上一篇
[Day 28] LIFF Bluetooth 與 LINE Things
下一篇
[Day 30] 認識LIFF
系列文
認識LIFF容易嗎?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言