Paolo
Paolo

Reputation: 55

Multiple bluetooth device scanning

Newbie here. I've been trying to expand some code to scan several devices instead of just one phone. This was the original code:

import automationhat
import bluetooth
import time

while True:
    print "Checking " + time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())
    result = bluetooth.lookup_name('B0:70:2D:D0:C9:XX', timeout=5)
    if (result != None):
        print "User present"
        automationhat.relay.one.on()
        time.sleep(2)
        automationhat.relay.one.off()
        time.sleep(200)
    else:
        print "User out of range"
        automationhat.relay.one.off()
    time.sleep(5)

and this after I tried to extend it.

import automationhat
import bluetooth
import time

DEVICES=['D8:BB:2C:XX:22:17', '34:AB:37:EA:XX:XX', '74:8D:08:XX:XX:7B']

while True:

        print "Checking " + time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())

        for device in DEVICES:
                result = bluetooth.lookup_name(device, timeout=5)
        if (result != None):
                print "User present"
                automationhat.relay.one.on()
                time.sleep(2)
                automationhat.relay.one.off()
                time.sleep(20)
        else:
                print "User out of range"
                automationhat.relay.one.off()

        time.sleep(10)

but it seems to consider only the last device in the DEVICES list. What am I missing? Sorry for the "stupid" question, but I'm just starting out and I couldn't find anything online. Cheers

Upvotes: 3

Views: 354

Answers (1)

Pierre
Pierre

Reputation: 1099

It looks like the operations handling the result are outside the scope of the for device in DEVICES: loop, so result always has the value of the last device.

Indent the code below result = bluetooth.lookup_name(device, timeout=5) so it is at the same level.

Upvotes: 1

Related Questions