LoginSignup
0
0

Mac で noble を使って BLE対応のデバイスをスキャンする+α(2024年5月版)

Posted at

以下の記事の、2024年5月バージョンの内容です。

●Mac で noble を使って BLE対応のデバイスをスキャンする(2021年4月版) - Qiita
https://qiita.com/youtoy/items/d9c8ff3a33985359f39b

上記の BLE 絡みの話の一部は、久しぶりにやってみると OS のバージョンアップの影響など、何らかの要因で突然動かなくなるということがあるので、久しぶりに試してみたという話です。

試す環境

試す環境は以下の通りで、当時と異なる部分に「★」をつけてみました。

  • 機器
    • MacBook Pro(13-inch, 2020, Four Thunderbolt 3 ports)
  • OS
    • ★ macOS Sonoma 14.5
  • Node.js のバージョン
    • ★ v22.1.0
  • パッケージ

軽く試してみる

パッケージのインストール

それでは、パッケージをインストールします。

npm i @abandonware/noble

ワーニングがいろいろでつつ、インストールは完了しました。

image.png

スキャンを試す

簡単なプログラムでスキャンを試します。

const noble = require("@abandonware/noble");

noble.on("stateChange", (state) => {
  if (state === "poweredOn") {
    noble.startScanningAsync();
  } else {
    noble.stopScanningAsync();
  }
});

noble.on("discover", async (peripheral) => {
  console.log("Details:", peripheral);
});

実行してみると、スキャンできた内容がどんどん表示されるのが確認できました。

一部、ピックアップしてみます。

image.png

image.png

構造が異なる内容のものが取得できていました。

スキャン対象を絞りこむ

もう少し、何かやってみようと思います。

やってみる内容

以前、以下の記事で Web Bluetooth API を使って試した、SwitchBot温湿度計のスキャンを試してみることにします。

●SwitchBot温湿度計のデータを Web Bluetooth API で取得する【完結編】 - Qiita
 https://qiita.com/youtoy/items/8e3cca2172e2c4806846

具体的には、以下に該当する処理を noble で行います。

image.png

実際に試してみる

上記の内容を試してみます。
少し調べてみると、スキャン時に設定してやると良いようです。

具体的には、以下のようにしました。

const noble = require("@abandonware/noble");

const targetServiceUUID = "cba20d00-224d-11e6-9fb8-0002a5d5c51b";

noble.on("stateChange", (state) => {
  if (state === "poweredOn") {
    noble.startScanningAsync([targetServiceUUID], false);
  } else {
    noble.stopScanningAsync();
  }
});

noble.on("discover", async (peripheral) => {
  console.log("Details:", peripheral);
});

出力を見てみると、以下のように特定の「serviceUuids」のもののみが取り出されていました

image.png

【余談】 気になった別のパッケージ

別パッケージで気になるものを見かけたので、メモしておきます。

●thegecko/webbluetooth: Node.js implementation of the Web Bluetooth Specification
 https://github.com/thegecko/webbluetooth

●webbluetooth - npm
 https://www.npmjs.com/package/webbluetooth

●Node Web Bluetooth
 https://thegecko.github.io/webbluetooth/

こちらも試して、使い勝手を比較してみたいところです。

0
0
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
0
0