Coming Soon!

#07 値の読み込みと書き込み1

この動画について

実際にデータにアクセスして、書き込みを行いきます。

キャラクタリスティックのデータ読み書きコード

'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) => {
           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;
                setTimeout(() => {
                    characteristics[0].write(new Buffer.from([state]), true);
                },2000);
            });
        });
    })
}

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

コメント