How can I make pybluez return a list of discovered devices every X seconds and then repeat?

12,935

This code worked for me:

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

It searches for 20 seconds for a device, and then sleeps for 1 minute, all in an infinite loop. I am working on Windows, with default windows drivers on a Serioux BT Dongle.

Hope it helps.

Share:
12,935
dave
Author by

dave

Updated on August 02, 2022

Comments

  • dave
    dave almost 2 years

    I've been trying to figure out how I can use pybluez to monitor nearby devices...

    I want to be able to run my program and have it search for devices every 20 seconds. The problem is, how do I get pybluez to place nicely? :/

    Using their example code http://code.google.com/p/pybluez/source/browse/trunk/examples/simple/inquiry.py, it's easy enough to get it to discover devices. You run that code and it'll spit out MAC address and, if you choose, the device names.

    How can I put this in a loop? I've been playing around with the following code but it's failing >.<

    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)