Coming Soon!

#08 値の読み込みと書き込み2

この動画について

一旦の完成形です。

読み書きをループさせるコード

'use strict';

const noble = require('noble');
const knownDevices = [];
const peripheralUUID = `7c67048222df46849621b62620924821`;
const serviceUUIDs = ['180d'];
const characteristicUUIDs = ['2a39'];

//discovered BLE device
const discovered = (peripheral) => {
    const device = {
        name: peripheral.advertisement.localName,
        uuid: peripheral.uuid,
        rssi: peripheral.rssi
    };
    knownDevices.push(device);
    console.log(`${knownDevices.length}:${device.name}(${device.uuid}) RSSI${device.rssi}`);

    if(peripheralUUID !== peripheral.uuid) return;
    noble.stopScanning();
    console.log(`device found.`);
    peripheral.connect((err) => {
        if(err) console.log(err);
        console.log(`connect device. coneccting service & characteristics`);        

        peripheral.discoverSomeServicesAndCharacteristics(serviceUUIDs, characteristicUUIDs, (error, services, characteristics) => {
            console.log(`connect characteristics. wait for READ VALUE......`);

            const toggle = () => {
                characteristics[0].read((err,data) => {
                    if(err) console.log(err);
                    console.log(`connect characteristic data.`);
                    let state = data.readUInt8(0);
                    console.log(state);
                    state = (state === 0) ? 1 : 0;
                    characteristics[0].write(new Buffer.from([state]), true);
                    setTimeout(() => toggle(),2000);
                });
            }
            toggle();

        });
    })
}

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

コメント