views:

49

answers:

4

I've been playing around with the pybluez module recently to scan for nearby Bluetooth devices. What I want to do now is extend the program to also find nearby WiFi client devices.

The WiFi client scanner will have need to have a While True loop to continually monitor the airwaves. If I were to write this as a straight up, one file program, it would be easy.

import ...

while True:
    client = scan()
    print client['mac']

What I want, however, is to make this a module. I want to be able to reuse it later and, possible, have others use it too. What I can't figure out is how to handle the loop.

import mymodule

scan()

Assuming the first example code was 'mymodule', this program would simply print out the data to stdout. I would want to be able to use this data in my program instead of having the module print it out...

How should I code the module?

+1  A: 

I think the best approach is going to be to have the scanner run on a separate thread from the main program. The module should have methods that start and stop the scanner, and another that returns the current access point list (using a lock to synchronize). See the threading module.

kindall
+1  A: 

How about something pretty straightforward like:

mymodule.py

import ...
def scanner():
    while True:
        client = scan()
        yield client['mac']

othermodule.py

import mymodule
for mac in mymodule.scanner():
    print mac

If you want something more useful than that, I'd also suggest a background thread as @kindall did.

ma3
A: 

If I get your question, you want scan() in a separate file, so that it can be reused later.

Create utils.py

def scan():
    # write code for scan here.

Create WiFi.py

import utils

def scan_wifi():
    while True:
        cli = utils.scan()
    ...
    return
MovieYoda
+1  A: 

Two interfaces would be useful.

  1. scan() itself, which returned a list of found devices, such that I could call it to get an instantaneous snapshot of available bluetooth. It might take a max_seconds_to_search or a max_num_to_return parameter.
  2. A "notify on found" function that accepted a callback. For instance (maybe typos, i just wrote this off the cuff).

    def find_bluetooth(callback_func, time_to_search = 5.0):
      already_found = []
      start_time = time.clock()
      while 1: 
        if time.clock()-start_time > 5.0: break
        found = scan()
        for entry in found:
          if entry not in already_found:
            callback_func(entry)
            already_found.append(entry)
    

    which would be used by doing this:

    def my_callback(new_entry):
      print new_entry    # or something more interesting...
    
    
    find_bluetooth(my_callback)
    
Scott Stafford
Upvoted for the callback idea, that would be very useful.
kindall