當前位置: 首頁>>代碼示例>>Python>>正文


Python btle.BTLEDisconnectError方法代碼示例

本文整理匯總了Python中bluepy.btle.BTLEDisconnectError方法的典型用法代碼示例。如果您正苦於以下問題:Python btle.BTLEDisconnectError方法的具體用法?Python btle.BTLEDisconnectError怎麽用?Python btle.BTLEDisconnectError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在bluepy.btle的用法示例。


在下文中一共展示了btle.BTLEDisconnectError方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: on_attributes_update

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import BTLEDisconnectError [as 別名]
def on_attributes_update(self, content):
        log.debug(content)
        for device in self.__devices_around:
            if self.__devices_around[device]['device_config'].get('name') == content['device']:
                for requests in self.__devices_around[device]['device_config']["attributeUpdates"]:
                    for service in self.__devices_around[device]['services']:
                        if requests['characteristicUUID'] in self.__devices_around[device]['services'][service]:
                            characteristic = self.__devices_around[device]['services'][service][requests['characteristicUUID']]['characteristic']
                            if 'WRITE' in characteristic.propertiesToString():
                                if content['data'].get(requests['attributeOnThingsBoard']) is not None:
                                    try:
                                        self.__check_and_reconnect(device)
                                        content_to_write = content['data'][requests['attributeOnThingsBoard']].encode('UTF-8')
                                        characteristic.write(content_to_write, True)
                                    except BTLEDisconnectError:
                                        self.__check_and_reconnect(device)
                                        content_to_write = content['data'][requests['attributeOnThingsBoard']].encode('UTF-8')
                                        characteristic.write(content_to_write, True)
                                    except Exception as e:
                                        log.exception(e)
                            else:
                                log.error(
                                    'Cannot process attribute update request for device: %s with data: %s and config: %s',
                                    device,
                                    content,
                                    self.__devices_around[device]['device_config']["attributeUpdates"]) 
開發者ID:thingsboard,項目名稱:thingsboard-gateway,代碼行數:28,代碼來源:ble_connector.py

示例2: main

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import BTLEDisconnectError [as 別名]
def main():
    if MQTT_DISCOVERY:
        discovery()
    BluetoothFailCounter = 0
    while True:
        try:
            scanner = btle.Scanner(HCI_DEV).withDelegate(ScanProcessor())
            scanner.scan(5) # Adding passive=True to try and fix issues on RPi devices
        except BTLEDisconnectError as error:
            sys.stderr.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - btle disconnected: {error}\n")
            pass
        except BTLEManagementError as error:
            sys.stderr.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Bluetooth connection error: {error}\n")
            if BluetoothFailCounter >= 4:
                sys.stderr.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - 5+ Bluetooth connection errors. Resetting Bluetooth...\n")
                cmd = 'hciconfig hci0 reset'
                ps = subprocess.Popen(cmd, shell=True)
                time.sleep(30)
                BluetoothFailCounter = 0
            else:
                BluetoothFailCounter+=1
            pass
        except Exception as error:
            sys.stderr.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Error while running the script: {error}\n")
            pass
        else:
            BluetoothFailCounter = 0
        time.sleep(TIME_INTERVAL) 
開發者ID:lolouk44,項目名稱:xiaomi_mi_scale,代碼行數:30,代碼來源:Xiaomi_Scale.py

示例3: status_update

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import BTLEDisconnectError [as 別名]
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))] 
開發者ID:zewelor,項目名稱:bt-mqtt-gateway,代碼行數:14,代碼來源:lywsd02.py

示例4: connect

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import BTLEDisconnectError [as 別名]
def connect(self, timeout=5):
        from bluepy import btle

        try:
            device = btle.Peripheral(self.mac)
            _LOGGER.debug("%s connected ", self.mac)
            return device
        except btle.BTLEDisconnectError as er:
            _LOGGER.debug("failed connect %s", er) 
開發者ID:zewelor,項目名稱:bt-mqtt-gateway,代碼行數:11,代碼來源:ibbq.py

示例5: update

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import BTLEDisconnectError [as 別名]
def update(self):
        from bluepy import btle

        if not self.connected:
            return list()
        self.values = list()
        self.cnt += 1
        try:
            if self.cnt > 5:
                self.cnt = 0
                self.getBattery()
            while self.device.waitForNotifications(1):
                pass
            if self.values:
                self.offline = 0
            else:
                _LOGGER.debug("%s is silent", self.mac)
                if self.offline > 3:
                    try:
                        self.device.disconnect()
                    except btle.BTLEInternalError as e:
                        _LOGGER.debug("%s", e)
                    self.device = None
                    _LOGGER.debug("%s reconnect", self.mac)
                else:
                    self.offline += 1
        except btle.BTLEDisconnectError as e:
            _LOGGER.debug("%s", e)
            self.device = None
        finally:
            return (self.batteryPct, self.values) 
開發者ID:zewelor,項目名稱:bt-mqtt-gateway,代碼行數:33,代碼來源:ibbq.py

示例6: status_update

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import BTLEDisconnectError [as 別名]
def status_update(self):
        from bluepy import btle

        for name, lywsd03mmc in self.devices.items():
            try:
                ret = lywsd03mmc.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))] 
開發者ID:zewelor,項目名稱:bt-mqtt-gateway,代碼行數:14,代碼來源:lywsd03mmc.py

示例7: subscribe

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import BTLEDisconnectError [as 別名]
def subscribe(self):
        while True:
            try:
                self.device.waitForNotifications(1.0)
            except KeyboardInterrupt:
                print("Module Interrupted")
                return True
            except BTLEDisconnectError:
                print_error("Device disconnected...")
            except:
                self.disconnect() 
開發者ID:ElevenPaths,項目名稱:HomePWN,代碼行數:13,代碼來源:ble.py

示例8: server_side_rpc_handler

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import BTLEDisconnectError [as 別名]
def server_side_rpc_handler(self, content):
        log.debug(content)
        try:
            for device in self.__devices_around:
                if self.__devices_around[device]['device_config'].get('name') == content['device']:
                    for requests in self.__devices_around[device]['device_config']["serverSideRpc"]:
                        for service in self.__devices_around[device]['services']:
                            if requests['characteristicUUID'] in self.__devices_around[device]['services'][service]:
                                characteristic = self.__devices_around[device]['services'][service][requests['characteristicUUID']]['characteristic']
                                if requests.get('methodProcessing') and requests['methodProcessing'].upper() in characteristic.propertiesToString():
                                    if content['data']['method'] == requests['methodRPC']:
                                        response = None
                                        if requests['methodProcessing'].upper() == 'WRITE':
                                            try:
                                                self.__check_and_reconnect(device)
                                                response = characteristic.write(content['data'].get('params', '').encode('UTF-8'),
                                                                                requests.get('withResponse', False))
                                            except BTLEDisconnectError:
                                                self.__check_and_reconnect(device)
                                                response = characteristic.write(content['data'].get('params', '').encode('UTF-8'),
                                                                                requests.get('withResponse', False))
                                        elif requests['methodProcessing'].upper() == 'READ':
                                            try:
                                                self.__check_and_reconnect(device)
                                                response = characteristic.read()
                                            except BTLEDisconnectError:
                                                self.__check_and_reconnect(device)
                                                response = characteristic.read()
                                        elif requests['methodProcessing'].upper() == 'NOTIFY':
                                            try:
                                                self.__check_and_reconnect(device)
                                                delegate = self.__notify_handler(self.__devices_around[device],
                                                                                 characteristic.handle)
                                                response = delegate.data
                                            except BTLEDisconnectError:
                                                self.__check_and_reconnect(device)
                                                delegate = self.__notify_handler(self.__devices_around[device],
                                                                                 characteristic.handle)
                                                response = delegate.data
                                        if response is not None:
                                            log.debug('Response from device: %s', response)
                                            if requests['withResponse']:
                                                response = 'success'
                                            self.__gateway.send_rpc_reply(content['device'], content['data']['id'],
                                                                          str(response))
                                else:
                                    log.error(
                                        'Method for rpc request - not supported by characteristic or not found in the config.\nDevice: %s with data: %s and config: %s',
                                        device,
                                        content,
                                        self.__devices_around[device]['device_config']["serverSideRpc"])
        except Exception as e:
            log.exception(e) 
開發者ID:thingsboard,項目名稱:thingsboard-gateway,代碼行數:55,代碼來源:ble_connector.py


注:本文中的bluepy.btle.BTLEDisconnectError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。