近くの本体を探す
周囲の機器を一覧にし、本体の識別子を確認します。
- 必要な本体
- 探索する本体1台以上。接続しません。
- 線路・準備
- 線路は不要。電源とBluetoothをオンにします。
- 終了方法
- 約2秒の探索後に終了。走行の操作はありません。
- 保存する場所
matrain-python-async/examples/scan.py- 実行する場所
matrain-python-asyncフォルダー内。.venvのPythonを使います。
Mac:.venv/bin/python examples/scan.pyWindows:.venv\Scripts\python.exe examples\scan.py
通常終了の処理を原例のまま掲載しています。例外やCtrl+Cでの停止が保証されないため、異常時は本体のボタンを短く押して止めます。切断だけを停止とみなさないでください。
掲載版の調整
Bleak 3.0.2向けにreturn_adv=TrueとAdvertisementData.rssiを使います。原例のBLEDevice.rssiは現在のAPIにありません。
コード全文
scan.py
#!/usr/bin/env python3
# Matrain publication modification: licensing/source notice added.
# Executable behavior is unchanged except for the adaptations documented below.
# Source: https://github.com/intelino-code/intelino-trainlib-async-py
# Source commit: 298e1fd4091e069180c30f338b4c285b13accbd0
# This software is made available by Innokind, Inc. DBA Intelino, under the
# terms of the Intelino Public License Agreement, Version 1.0 located at
# https://intelino.com/intelino-public-license. BY INSTALLING, DOWNLOADING,
# ACCESSING, USING OR DISTRIBUTING ANY OF THE SOFTWARE, YOU AGREE TO THE TERMS OF
# SUCH LICENSE AGREEMENT.
# Publication adaptation: Bleak 3.0.2向けにreturn_adv=TrueとAdvertisementData.rssiを使います。原例のBLEDevice.rssiは現在のAPIにありません。
"""BLE scanning utility to find nearby intelino trains."""
import asyncio
from typing import List
from bleak import BleakScanner
from bleak.backends.device import BLEDevice
from bleak.backends.scanner import AdvertisementData
def list_devices(title: str, devices: List[tuple[BLEDevice, AdvertisementData]]) -> None:
print(f"{title} ({len(devices)}):")
for d, advertisement in devices:
print(f"{d.address} : {d.name} (RSSI {advertisement.rssi})")
async def scan(timeout: float) -> None:
advertisements = await BleakScanner.discover(timeout, return_adv=True)
devices = list(advertisements.values())
trains = list(filter(lambda item: str(item[0].name).startswith("intelino"), devices))
others = list(filter(lambda item: not str(item[0].name).startswith("intelino"), devices))
list_devices("Trains", trains)
print()
list_devices("Others", others)
def main():
asyncio.run(scan(2))
if __name__ == "__main__":
main()
冒頭に配布条件と出典のコメントを追加しています。表示している全文と、個別保存・ZIP内のこのファイルは同じです。ライセンス・出典を読む
