Python bluepy.btle.BTLEException() Examples

The following are 30 code examples of bluepy.btle.BTLEException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bluepy.btle , or try the search function .
Example #1
Source File: manager.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def __init__(self, show_warnings=False, *args, **kwargs):
        """Constructor.

        Args:
            show_warnings (bool, optional): If True shows warnings, if any, when
            discovering devices not respecting the BlueSTSDK's advertising
            data format, nothing otherwise.
        """
        try:
            super(_StoppableScanner, self).__init__(*args, **kwargs)
            self._stop_called = threading.Event()
            self._process_done = threading.Event()
            with lock(self):
                self._scanner = Scanner().withDelegate(_ScannerDelegate(show_warnings))
        except BTLEException as e:
            # Save details of the exception raised but don't re-raise, just
            # complete the function.
            import sys
            self._exc = sys.exc_info() 
Example #2
Source File: sensor.py    From Xiaomi_Hygrothermo with MIT License 7 votes vote down vote up
def get_data(self, now = None):
        try:
            from bluepy import btle

            p = btle.Peripheral(self.address)

            #self.name = ''.join(map(chr, p.readCharacteristic(0x3)))
            #self.firmware = ''.join(map(chr, p.readCharacteristic(0x24)))
            if self.last_battery is None or (utcnow() - self.last_battery).seconds >= 3600:
                self.battery = p.readCharacteristic(0x18)[0]
                self.last_battery = utcnow()

            delegate = XiomiHygroThermoDelegate()
            p.withDelegate( delegate )
            p.writeCharacteristic(0x10, bytearray([1, 0]), True)
            while not delegate.received:
                p.waitForNotifications(30.0)

            self.temperature = delegate.temperature
            self.humidity = delegate.humidity

            ok = True
        except Exception as ex:
            if isinstance(ex, btle.BTLEException):
                _LOGGER.warning("BT connection error: {}".format(ex))
            else:
                _LOGGER.error("Unexpected error: {}".format(ex))
            ok = False

        for i in [0, 1]:
            changed = self.entities[i].set_state(ok, self.battery, self.temperature if i == 0 else self.humidity)
            if (not now is None) and changed:
                self.entities[i].async_schedule_update_ha_state() 
Example #3
Source File: connection.py    From python-eq3bt with MIT License 7 votes vote down vote up
def __enter__(self):
        """
        Context manager __enter__ for connecting the device
        :rtype: btle.Peripheral
        :return:
        """
        self._conn = btle.Peripheral()
        self._conn.withDelegate(self)
        _LOGGER.debug("Trying to connect to %s", self._mac)
        try:
            self._conn.connect(self._mac)
        except btle.BTLEException as ex:
            _LOGGER.debug("Unable to connect to the device %s, retrying: %s", self._mac, ex)
            try:
                self._conn.connect(self._mac)
            except Exception as ex2:
                _LOGGER.debug("Second connection try to %s failed: %s", self._mac, ex2)
                raise

        _LOGGER.debug("Connected to %s", self._mac)
        return self 
Example #4
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handleNotification(self, char_handle, data):
        """It is called whenever a notification arises.

        Args:
            char_handle (int): The characteristic's handle to look for.
            data (str): The data notified from the given characteristic.
        """
        try:
            # Calling on-read callback.
            if self._node._debug_console:
                # Calling on-update callback for a debug characteristic.
                characteristic = \
                    self._node._char_handle_to_characteristic_dict[char_handle]
                if Debug.is_debug_characteristic(str(characteristic.uuid)):
                    self._node._debug_console.on_update_characteristic(
                        characteristic, data)
                    return

            # Calling on-read callback for the other characteristics.
            self._node._update_features(char_handle, data, True)
        except BlueSTInvalidDataException as e:
            self._logger.warning(str(e))
        except BTLEException as e:
            self._unexpected_disconnect() 
Example #5
Source File: manager.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self):
        """Run the thread."""
        self._stop_called.clear()
        self._process_done.clear()
        try:
            with lock(self):
                self._scanner.clear()
                self._exc = None
                self._scanner.start(passive=False)
                while True:
                    #print('.')
                    self._scanner.process(_ScannerDelegate._SCANNING_TIME_PROCESS_s)
                    if self._stop_called.isSet():
                        self._process_done.set()
                        break
 
        except BTLEException as e:
            # Save details of the exception raised but don't re-raise, just
            # complete the function.
            import sys
            self._exc = sys.exc_info() 
Example #6
Source File: manager.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def reset_discovery(self):
        """Reset the discovery process.

        Stop the discovery process and remove all the already discovered nodes.
        Node already bounded with the device will be kept in the list.

        Raises:
            :exc:`blue_st_sdk.utils.blue_st_exceptions.BlueSTInvalidOperationException`
            is raised if this method is not run as root.
        """
        try:
            if self.is_discovering():
                self.stop_discovery()
            self.remove_nodes()
        except BTLEException as e:
            msg = '\nBluetooth scanning requires root privileges, ' \
                  'so please run the application with \"sudo\".'
            raise BlueSTInvalidOperationException(msg) 
Example #7
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def disconnect(self):
        """Close the connection to the node.

        Returns:
            bool: True if the disconnection to the node has been successful,
            False otherwise.
        """
        try:
            if not self.is_connected():
                return False

            # Disconnecting.
            self._update_node_status(NodeStatus.DISCONNECTING)
            with lock(self):
                super(Node, self).disconnect()
            self._update_node_status(NodeStatus.IDLE)

            return self._status == NodeStatus.IDLE
        except BTLEException as e:
            self._unexpected_disconnect() 
Example #8
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def characteristic_can_be_read(self, characteristic):
        """Check if a characteristics can be read.

        Args:
            characteristic (Characteristic): The BLE characteristic to check.
            Refer to
            `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_
            for more information.

        Returns:
            bool: True if the characteristic can be read, False otherwise.
        """
        try:
            if characteristic is not None:
                with lock(self):
                    return "READ" in characteristic.propertiesToString()
            return False
        except BTLEException as e:
            self._unexpected_disconnect() 
Example #9
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def characteristic_can_be_written(self, characteristic):
        """Check if a characteristics can be written.

        Args:
            characteristic (Characteristic): The BLE characteristic to check.
            Refer to
            `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_
            for more information.

        Returns:
            bool: True if the characteristic can be written, False otherwise.
        """
        try:
            if characteristic is not None:
                with lock(self):
                    return "WRITE" in characteristic.propertiesToString()
            return False
        except BTLEException as e:
            self._unexpected_disconnect() 
Example #10
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def characteristic_can_be_notified(self, characteristic):
        """Check if a characteristics can be notified.

        Args:
            characteristic (Characteristic): The BLE characteristic to check.
            Refer to
            `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_
            for more information.

        Returns:
            bool: True if the characteristic can be notified, False otherwise.
        """
        try:
            if characteristic is not None:
                with lock(self):
                    return "NOTIFY" in characteristic.propertiesToString()
            return False
        except BTLEException as e:
            self._unexpected_disconnect() 
Example #11
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def wait_for_notifications(self, timeout_s):
        """Block until a notification is received from the peripheral, or until
        the given timeout has elapsed.

        If a notification is received, the
        :meth:`blue_st_sdk.feature.FeatureListener.on_update` method of any
        added listener is called.

        Args:
            timeout_s (float): Time in seconds to wait before returning.

        Returns:
            bool: True if a notification is received before the timeout elapses,
            False otherwise.
        """
        try:
            if self.is_connected():
                with lock(self):
                    return self.waitForNotifications(timeout_s)
            return False
        except BTLEException as e:
            self._unexpected_disconnect() 
Example #12
Source File: bluepy.py    From btlewrap with MIT License 6 votes vote down vote up
def wrap_exception(func: Callable) -> Callable:
    """Decorator to wrap BTLEExceptions into BluetoothBackendException."""
    try:
        # only do the wrapping if bluepy is installed.
        # otherwise it's pointless anyway
        from bluepy.btle import BTLEException
    except ImportError:
        return func

    def _func_wrapper(*args, **kwargs):
        error_count = 0
        last_error = None
        while error_count < RETRY_LIMIT:
            try:
                return func(*args, **kwargs)
            except BTLEException as exception:
                error_count += 1
                last_error = exception
                time.sleep(RETRY_DELAY)
                _LOGGER.debug('Call to %s failed, try %d of %d', func, error_count, RETRY_LIMIT)
        raise BluetoothBackendException() from last_error

    return _func_wrapper 
Example #13
Source File: bleConnection.py    From pyparrot with MIT License 6 votes vote down vote up
def connect(self, num_retries):
        """
        Connects to the drone and re-tries in case of failure the specified number of times

        :param: num_retries is the number of times to retry

        :return: True if it succeeds and False otherwise
        """

        # first try to connect to the wifi
        try_num = 1
        connected = False
        while (try_num < num_retries and not connected):
            try:
                self._connect()
                connected = True
            except BTLEException:
                color_print("retrying connections", "INFO")
                try_num += 1

        # fall through, return False as something failed
        return connected 
Example #14
Source File: bleConnection.py    From pyparrot with MIT License 6 votes vote down vote up
def _reconnect(self, num_retries):
        """
        Reconnect to the drone (assumed the BLE crashed)

        :param: num_retries is the number of times to retry

        :return: True if it succeeds and False otherwise
        """
        try_num = 1
        success = False
        while (try_num < num_retries and not success):
            try:
                color_print("trying to re-connect to the minidrone at address %s" % self.address, "WARN")
                self.drone_connection.connect(self.address, "random")
                color_print("connected!  Asking for services and characteristics", "SUCCESS")
                success = True
            except BTLEException:
                color_print("retrying connections", "WARN")
                try_num += 1

        if (success):
            # do the magic handshake
            self._perform_handshake()

        return success 
Example #15
Source File: bleConnection.py    From pyparrot with MIT License 6 votes vote down vote up
def _safe_ble_write(self, characteristic, packet):
        """
        Write to the specified BLE characteristic but first ensure the connection is valid

        :param characteristic:
        :param packet:
        :return:
        """

        success = False

        while (not success):
            try:
                characteristic.write(packet)
                success = True
            except BTLEException:
                color_print("reconnecting to send packet", "WARN")
                self._reconnect(3) 
Example #16
Source File: pr_rileylink.py    From omnipy with MIT License 6 votes vote down vote up
def disconnect(self, ignore_errors=True):
        try:
            if self.peripheral is None:
                self.logger.info("Already disconnected")
                return
            self.logger.info("Disconnecting..")
            if self.response_handle is not None:
                response_notify_handle = self.response_handle + 1
                notify_setup = b"\x00\x00"
                self.peripheral.writeCharacteristic(response_notify_handle, notify_setup)
        except Exception as e:
            if not ignore_errors:
                raise PacketRadioError("Error while disconnecting") from e
        finally:
            try:
                if self.peripheral is not None:
                    self.peripheral.disconnect()
                    self.peripheral = None
            except BTLEException as be:
                if ignore_errors:
                    self.logger.exception("Ignoring btle exception during disconnect")
                else:
                    raise PacketRadioError("Error while disconnecting") from be
            except Exception as e:
                raise PacketRadioError("Error while disconnecting") from e 
Example #17
Source File: pr_rileylink.py    From omnipy with MIT License 6 votes vote down vote up
def _connect_retry(self, retries):
        while retries > 0:
            retries -= 1
            self.logger.info("Connecting to RileyLink, retries left: %d" % retries)

            try:
                self.peripheral.connect(self.address)
                self.logger.info("Connected")
                break
            except BTLEException as btlee:
                self.logger.warning("BTLE exception trying to connect: %s" % btlee)
                try:
                    p = subprocess.Popen(["ps", "-A"], stdout=subprocess.PIPE)
                    out, err = p.communicate()
                    for line in out.splitlines():
                        if "bluepy-helper" in line:
                            pid = int(line.split(None, 1)[0])
                            os.kill(pid, 9)
                            break
                except:
                    self.logger.warning("Failed to kill bluepy-helper")
                time.sleep(1) 
Example #18
Source File: linakdesk.py    From bt-mqtt-gateway with MIT License 6 votes vote down vote up
def _get_height(self):
        from bluepy import btle

        with timeout(
            self.SCAN_TIMEOUT,
            exception=DeviceTimeoutError(
                "Retrieving the height from {} device {} timed out after {} seconds".format(
                    repr(self), self.mac, self.SCAN_TIMEOUT
                )
            ),
        ):
            try:
                self.desk.read_dpg_data()
                return self.desk.current_height_with_offset.cm
            except btle.BTLEException as e:
                logger.log_exception(
                    _LOGGER,
                    "Error during update of linak desk '%s' (%s): %s",
                    repr(self),
                    self.mac,
                    type(e).__name__,
                    suppress=True,
                )
                raise DeviceTimeoutError 
Example #19
Source File: Mambo.py    From pymambo with MIT License 6 votes vote down vote up
def connect(self, num_retries):
        """
        Connects to the drone and re-tries in case of failure the specified number of times

        :param: num_retries is the number of times to retry

        :return: True if it succeeds and False otherwise
        """

        try_num = 1
        while (try_num < num_retries):
            try:
                self._connect()
                return True
            except BTLEException:
                self._debug_print("retrying connections", 10)
                try_num += 1

        # if we fell through the while loop, it failed to connect
        return False 
Example #20
Source File: Mambo.py    From pymambo with MIT License 6 votes vote down vote up
def _reconnect(self, num_retries):
        """
        Reconnect to the drone (assumed the BLE crashed)

        :param: num_retries is the number of times to retry

        :return: True if it succeeds and False otherwise
        """
        try_num = 1
        success = False
        while (try_num < num_retries and not success):
            try:
                self._debug_print("trying to re-connect to the mambo at address %s" % self.address, 10)
                self.drone.connect(self.address, "random")
                self._debug_print("connected!  Asking for services and characteristics", 5)
                success = True
            except BTLEException:
                self._debug_print("retrying connections", 10)
                try_num += 1

        if (success):
            # do the magic handshake
            self._perform_handshake()

        return success 
Example #21
Source File: Mambo.py    From pymambo with MIT License 6 votes vote down vote up
def _safe_ble_write(self, characteristic, packet):
        """
        Write to the specified BLE characteristic but first ensure the connection is valid

        :param characteristic:
        :param packet:
        :return:
        """

        success = False

        while (not success):
            try:
                characteristic.write(packet)
                success = True
            except BTLEException:
                self._debug_print("reconnecting to send packet", 10)
                self._reconnect(3) 
Example #22
Source File: smartgadget.py    From bt-mqtt-gateway with MIT License 6 votes vote down vote up
def status_update(self):
        from bluepy import btle

        _LOGGER.info("Updating %d %s devices", len(self.devices), repr(self))
        for name, device in self.devices.items():
            _LOGGER.debug("Updating %s device '%s' (%s)", repr(self), name, device.mac)
            try:
                yield self.update_device_state(name, device)
            except btle.BTLEException as e:
                logger.log_exception(
                    _LOGGER,
                    "Error during update of %s device '%s' (%s): %s",
                    repr(self),
                    name,
                    device.mac,
                    type(e).__name__,
                    suppress=True,
                ) 
Example #23
Source File: thermostat.py    From bt-mqtt-gateway with MIT License 6 votes vote down vote up
def status_update(self):
        from bluepy import btle

        _LOGGER.info("Updating %d %s devices", len(self.devices), repr(self))
        for name, data in self.devices.items():
            _LOGGER.debug("Updating %s device '%s' (%s)", repr(self), name, data["mac"])
            thermostat = data["thermostat"]
            try:
                thermostat.update()
            except btle.BTLEException as e:
                logger.log_exception(
                    _LOGGER,
                    "Error during update of %s device '%s' (%s): %s",
                    repr(self),
                    name,
                    data["mac"],
                    type(e).__name__,
                    suppress=True,
                )
            else:
                yield self.present_device_state(name, thermostat) 
Example #24
Source File: switchbot.py    From bt-mqtt-gateway with MIT License 6 votes vote down vote up
def status_update(self):
        from bluepy import btle

        ret = []
        _LOGGER.debug("Updating %d %s devices", len(self.devices), repr(self))
        for name, bot in self.devices.items():
            _LOGGER.debug("Updating %s device '%s' (%s)", repr(self), name, bot["mac"])
            try:
                ret += self.update_device_state(name, bot["state"])
            except btle.BTLEException as e:
                logger.log_exception(
                    _LOGGER,
                    "Error during update of %s device '%s' (%s): %s",
                    repr(self),
                    name,
                    bot["mac"],
                    type(e).__name__,
                    suppress=True,
                )
        return ret 
Example #25
Source File: lywsd02.py    From bt-mqtt-gateway with MIT License 5 votes vote down vote up
def status_update(self):
        from bluepy import btle

        for name, lywsd02 in self.devices.items():
            try:
                ret = lywsd02.readAll()
            except btle.BTLEDisconnectError as e:
                self.log_connect_exception(_LOGGER, name, e)
            except btle.BTLEException as e:
                self.log_unspecified_exception(_LOGGER, name, e)
            else:
                yield [MqttMessage(topic=self.format_topic(name), payload=json.dumps(ret))] 
Example #26
Source File: __main__.py    From bluescan with GNU General Public License v3.0 5 votes vote down vote up
def main():
    try:
        args = parse_cmdline()
        init(args['-i'])

        if args['-m'] == 'br':
            br_scanner = BRScanner(args['-i'])
            br_scanner.scan(args['--inquiry-len'])
        elif args['-m'] == 'lmp':
            LMPScanner(args['-i']).scan(args['BD_ADDR'])
        elif args['-m'] == 'le':
            LEScanner(args['-i']).scan(args['--timeout'], 
                args['--le-scan-type'], args['--sort']
            )
        elif args['-m'] == 'sdp':
            SDPScanner(args['-i']).scan(args['BD_ADDR'])
        elif args['-m'] == 'gatt':
            GATTScanner(args['-i']).scan(args['BD_ADDR'], args['--addr-type'],
                args['--include-descriptor'])
        elif args['-m'] == 'stack':
            StackScanner(args['-i']).scan(args['BD_ADDR'])
        elif args['-m'] == 'vuln':
            VulnScanner(args['-i']).scan(args['BD_ADDR'], args['--addr-type'])
        else:
            print(ERROR, "invalid scan mode")
    except BluetoothError as e:
        print(ERROR, e)
    except (BTLEException, ValueError) as e:
        print(ERROR, e)
        if 'le on' in str(e):
            print('        No BLE adapter? or missing sudo ?')
    except KeyboardInterrupt:
        print(INFO, args['-m'].upper() + " scan canceled\n")
    except Exception as e:
        #traceback.print_exc()
        print(ERROR, e) 
Example #27
Source File: test_bluepy.py    From btlewrap with MIT License 5 votes vote down vote up
def test_connect_exception(self, mock_peripheral):
        """Test exception wrapping."""
        mock_peripheral.side_effect = BTLEException('Test')
        backend = BluepyBackend()
        with self.assertRaises(BluetoothBackendException):
            backend.connect(TEST_MAC) 
Example #28
Source File: pr_rileylink.py    From omnipy with MIT License 5 votes vote down vote up
def connect(self, force_initialize=False):
        try:
            if self.address is None:
                self.address = self._findRileyLink()

            if self.peripheral is None:
                self.peripheral = Peripheral()

            try:
                state = self.peripheral.getState()
                if state == "conn":
                    return
            except BTLEException:
                pass

            self._connect_retry(3)

            self.service = self.peripheral.getServiceByUUID(RILEYLINK_SERVICE_UUID)
            data_char = self.service.getCharacteristics(RILEYLINK_DATA_CHAR_UUID)[0]
            self.data_handle = data_char.getHandle()

            char_response = self.service.getCharacteristics(RILEYLINK_RESPONSE_CHAR_UUID)[0]
            self.response_handle = char_response.getHandle()

            response_notify_handle = self.response_handle + 1
            notify_setup = b"\x01\x00"
            self.peripheral.writeCharacteristic(response_notify_handle, notify_setup)

            while self.peripheral.waitForNotifications(0.05):
                self.peripheral.readCharacteristic(self.data_handle)

            if self.initialized:
                self.init_radio(force_initialize)
            else:
                self.init_radio(True)
        except BTLEException as be:
            if self.peripheral is not None:
                self.disconnect()
            raise PacketRadioError("Error while connecting") from be
        except Exception as e:
            raise PacketRadioError("Error while connecting") from e 
Example #29
Source File: connection.py    From python-eq3bt with MIT License 5 votes vote down vote up
def make_request(self, handle, value, timeout=DEFAULT_TIMEOUT, with_response=True):
        """Write a GATT Command without callback - not utf-8."""
        try:
            with self:
                _LOGGER.debug("Writing %s to %s with with_response=%s", codecs.encode(value, 'hex'), handle, with_response)
                self._conn.writeCharacteristic(handle, value, withResponse=with_response)
                if timeout:
                    _LOGGER.debug("Waiting for notifications for %s", timeout)
                    self._conn.waitForNotifications(timeout)
        except btle.BTLEException as ex:
            _LOGGER.debug("Got exception from bluepy while making a request: %s", ex)
            raise 
Example #30
Source File: gatt.py    From csrmesh with GNU Lesser General Public License v3.0 5 votes vote down vote up
def connect(mac_list, debug=False):
    #Try to connect to each device in mac_list in order, returning after the first successful connection, or returning None after all attempts fail.
    device=None
    for mac in mac_list:
        try:
            if debug:
                print("[+] Connecting to device %s" % mac)
            device = btle.Peripheral(mac, addrType=btle.ADDR_TYPE_PUBLIC)
            return device
        except btle.BTLEException as err:
            if debug:
                print("[-] A connection error has occured: %s" % str(err))
    return None