LoginSignup
16
17

More than 5 years have passed since last update.

Node.jsから周辺のBLEデバイスを探すサンプル

Posted at

nobleの新しい感じのサンプルがなかったので書いてみる。

  • macOS Sierra
  • Node.js v8.1.2

準備

$ npm init -y
$ npm i --save noble

このバージョンだとnpm install時にwarningが出るけど問題なく動作します。

コード

app.js
'use strict';

const noble = require('noble');
const knownDevices = [];

//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}`);
}

//BLE scan start
const scanStart = () => {
    noble.startScanning();
    noble.on('discover', discovered);
}

if(noble.state === 'poweredOn'){
    scanStart();
}else{
    noble.on('stateChange', scanStart);
}

実行

$ node app.js
1:<デバイス名称>(<UUID>) RSSI-75
2:<デバイス名称>(<UUID>) RSSI85
3:<デバイス名称>(<UUID>) RSSI-49
・
・
・

デバイスが見つかる度にコンソールに表示されます。

参考: ノンプログラマでもコピペでOK!JavaScriptを使ってDroneを飛ばそう

16
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
17