如何让pybluez每隔X秒返回一个发现的设备列表并重复执行?

5
我一直在试图找出如何使用pybluez来监视附近的设备...
我想能够运行我的程序,并让它每20秒搜索设备。问题是,如何让pybluez很好地工作呢? :/
使用他们的示例代码http://code.google.com/p/pybluez/source/browse/trunk/examples/simple/inquiry.py,很容易发现设备。您运行该代码,它将显示MAC地址,如果选择,还会显示设备名称。
我该如何将此放入循环中?我一直在尝试以下代码,但它失败了 >.<
import bluetooth

def search():
   while True:
      devices = bluetooth.discover_devices(lookup_names = True)

      yield devices

for addr, name in search():
   print "{0} - {1}".format(addr, name)
2个回答

7
这段代码对我有效:
'''
Created on Nov 16, 2011    
@author: Radu
'''
import time
import bluetooth

def search():         
    devices = bluetooth.discover_devices(duration=20, lookup_names = True)
    return devices

if __name__=="__main__":
    while True:        
        results = search()
        if (results!=None):
            for addr, name in results:
                print "{0} - {1}".format(addr, name)
            #endfor
        #endif
        time.sleep(60)
    #endwhile

它会在查找设备20秒后进入1分钟的休眠状态,然后无限循环。我正在Windows上工作,在Serioux BT Dongle上使用默认的Windows驱动程序。
希望这能帮到你。

0
我不熟悉pybluez,但是bluetooth.discover_devices(lookup_names = True)本身已经返回了一个可迭代对象,所以你应该循环它来进行yield操作。
def search():
   while True:
      devices = bluetooth.discover_devices(lookup_names = True)
      for x in devices: # <--
         yield x        # <-- 

这个很好用,但是似乎设备被缓存了? 我想要在蓝牙设备不在附近时收到通知,但即使我关闭它,它仍然出现在扫描中... - Pitto
3
这几乎难以置信。我来到这里时想:“太神奇了,这正是我所遇到的问题!”可那是两年前的我 :'( - Pitto
@Pitto https://github.com/pybluez/pybluez/blob/23d34718046b2ad40bd519bea26cac38d33933a7/bluetooth/msbt.py - Levi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接