如何让pybluez每隔X秒返回一个已发现设备的列表,然后重复?

时间:2010-07-27 10:42:49

标签: python bluetooth

我一直试图找出如何使用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 个答案:

答案 0 :(得分:4)

此代码对我有用:

'''
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驱动程序。

希望它有所帮助。

答案 1 :(得分:0)

我不知道pybluez,但bluetooth.discover_devices(lookup_names = True)本身已经返回一个可迭代的,所以你应该循环它以便屈服。

def search():
   while True:
      devices = bluetooth.discover_devices(lookup_names = True)
      for x in devices: # <--
         yield x        # <--