2011年1月27日木曜日

PythonでBluetoothデバイスを検出する

今までWindowsXPでプログラムからBluetoothデバイスを検出する方法がさっぱりわからなかったが、PythonのライブラリPyBluezで簡単に検出できた。
Python2.6用ならPyBluez-0.18.win32-py2.6.exeをダウンロードして実行するとライブラリがインストールされる。
下記のテスト用に作ってみたプログラムはExamplesのinquiry.py
改造しただけ。
行頭の+は新たに検出したデバイス、-は消失したデバイスを表しています。セットの差集合を利用。

# -*- coding: utf-8 -*-
import bluetooth # PyBluez
import time
import datetime

old_devices = set()
while True:
    try:
        nearby_devices = bluetooth.discover_devices(lookup_names = True)
    except IOError, err:
        print err
        time.sleep(10)
    else:
        dt = datetime.datetime.now()
        dt_str = dt.strftime("%Y/%m/%d %H:%M:%S")
        new_devices = set(nearby_devices)
        for addr,name in new_devices-old_devices:
            print u"+ %s %s %s" % (dt_str, addr, name.decode('utf-8'))
        for addr,name in old_devices-new_devices:
            print u"- %s %s %s" % (dt_str, addr, name.decode('utf-8'))
        old_devices = new_devices.copy()
        time.sleep(3)

0 件のコメント: