IanHarvey / bluepy

Python interface to Bluetooth LE on Linux
Other
1.61k stars 491 forks source link

Trapping exceptions #165

Open Carduelis1 opened 7 years ago

Carduelis1 commented 7 years ago

How do I trap BLE exceptions in Python? The normal try/except construct doesn't seem to pick up an error when e.g a device moves out of range. i.e.

try: tag = SensorTag(arg.host) except btle.BTLEException: print ("connection error") do recovery stuff

bortek commented 6 years ago

I have the same question. How do I catch this exception in a proper way. I am calling like this.

import bluepy.btle as ble ... def init(self, addr, pin): try: self._debug = True self.conn = ble.Peripheral(deviceAddr=addr) self.setAuth(pin) except ble as bte: print(bte) print("Exception from bluepy")

and getting this exception "Failed to connect to peripheral %s, addr type: %s" % (addr, addrType)) bluepy.btle.BTLEException: Failed to connect to peripheral 58:2b:db:00:7b:a2, addr type: public

awneil commented 3 years ago

I also couldn't see how to do this from the documentation, but found some examples here:

https://www.programcreek.com/python/example/97794/bluepy.btle.BTLEException

Whence, from the Scan example:

import sys

from bluepy.btle import Scanner, DefaultDelegate
from bluepy.btle import BTLEException

class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr

try:
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(0)
except BTLEException as e:
    print "BLE Exception in scan:", e
    sys.exit( "needs sudo ?" )