Coming Soon!

#09 おまけ: NobleをPromise(async/await)対応

この動画について

機能的には変わらないけど、見やすい形に書き換えしたコードを紹介します。

おまけ: async/awaitに書き換え

'use strict';

const noble = require('noble');

const peripheralUUID = '7c67048222df46849621b62620924821'; //各自書き換え
const serviceUUIDs = ['180d'];
const characteristicUUIDs = ['2a39'];

//discovered BLE device
const discovered = async (peripheral) => {
    // if(peripheral.advertisement.localName !== 'Heart Rate') return;
    if(peripheral.uuid !== peripheralUUID) return;
    noble.stopScanning(); //スキャン停止
    console.log(`[Found Device] ${peripheral.advertisement.localName}(${peripheral.uuid}) RSSI${peripheral.rssi}`);

    /**
     * ペリフェラルへのアクセス
     */
    //Promisify
    const pConnectAsync = () => new Promise((resolve, reject) => peripheral.connect(err => err ? reject() : resolve()));
    await pConnectAsync();
    
    console.log(`[Connect Device] coneccting service & characteristic ......`);

    /**
     * サービスとキャラクタリスティックへのアクセス
     */
    //Promisify
    const discoverSaCAsync = (sUUIDs, cUUIDs) => new Promise((resolve, reject) => peripheral.discoverSomeServicesAndCharacteristics(sUUIDs, cUUIDs,(err, ss, cs) => err ? reject() : resolve({services: ss, characteristics: cs})));
    const {characteristics} = await discoverSaCAsync(serviceUUIDs, characteristicUUIDs);
    console.log(`[Connect Characteristic] coneccting data ......`);
    
    /**
     * キャラクタリスティックのデータにアクセス
     */
    //Promisify
    const cReadAsync = () => new Promise((resolve, reject) => characteristics[0].read((err, data) => err ? reject(err) : resolve(data)));

    const toggle = async () => {
        try {
            const data = await cReadAsync();
            let state = data.readUInt8(0);
            console.log(state);
            state = (state === 0) ? 1 : 0;
            characteristics[0].write(new Buffer.from([state]), true);
            setTimeout(() => toggle(), 1000); //1秒ごとに実行
        } catch (error) {
            console.log(error);        
        }
    }
    toggle();
}

//BLE scan start
const scanStart = () => {
    if(noble.state !== 'poweredOn'){
        noble.on('stateChange', scanStart)
    }else{
        noble.startScanning();
        noble.on('discover', discovered); //Discover
    }
}
scanStart();
最終更新日

コメント