Reputation: 181
I am currently trying to connect to a GPS Bluetooth device. My Python 2.7 code worked correctly initially but I have now tried to implement my code into a while loop so that, whilst my device is not available, it will continue to keep on looping for it. Unfortunately, my code seems to be stuck in a loop and repeatedly prints out the error message "Unable to Locate Bluetooth GPS Device. Retrying..." I'm using the Bluetooth module from PyBluez.
Here's my code:-
import bluetooth
target_address = "00:11:22:33:44:55:66"
discovered_devices = discover_devices() # Object to discover devices from Bluetooth module
while True:
print "Attempting to locate the correct Bluetooth GPS Device..."
for address in discovered_devices:
if address != target_address:
print "Unable to Locate Bluetooth GPS Device. Retrying..."
else:
print "Bluetooth GPS Device Located: ", target_address
break
# move on to next statement outside of loop (connection etc...)
As said, basically what I am looking to achieve is for the device discovery object to start and a message appear on console to indicate it is looking for a device transmitting the specified device address (ie "00:11:22:33:44:55:66"). Should no device have this address, I'd like the code to present an error message relating to being unable to locate device and then I'd like it to continue to keep on looking.
On a side, I would also ultimately like to edit this code so that, after attempting to locate the device for X amount of time / on a number of X occasions but to no avail, I'd like the code to end and the program to present an error message. Any guidance on that?
Thanks
Upvotes: 1
Views: 2423
Reputation: 32873
The line
discovered_devices = discover_devices()
should go inside your while
loop, before entering the for
loop.
Then replace your while
loop by a for
loop to limit the number of attempts.
And to properly exit the inner for
loop, do as @Jeremy said: add
else:
continue
break
at the end of it.
You may also want to wait between each attempt using sleep()
at each iteration of your outer loop.
Upvotes: 5
Reputation: 129715
You're breaking the for
loop, not the outer while
loop. If you're not doing anything after the for
loop, you can propagate the break
by adding this:
while True:
print "Attempting to locate the correct Bluetooth GPS Device..."
for address in discovered_devices:
if address != target_address:
print "Unable to Locate Bluetooth GPS Device. Retrying..."
else:
print "Bluetooth GPS Device Located: ", target_address
break
else:
# if we don't break, then continue the while loop normally
continue
# otherwise, break the while loop as well
break
Upvotes: 4