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


Python btle.Scanner方法代碼示例

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


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

示例1: btle

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def btle():
    findkey = False
    scanner = Scanner()
    devices = scanner.scan(10.0)
    for dev in devices:
        for (adtype, desc, value) in dev.getScanData():
            if findkey:
                if 'Complete 128b Services' in desc:
                    subprocess.call('umount /home/pi-enc 2>/dev/null', shell=True)
                    subprocess.call('cryptsetup close /dev/mapper/pi.enc 2>/dev/null', shell=True)
                    subprocess.call('losetup -D', shell=True)
                    subprocess.call('losetup /dev/loop0 /home/pi.enc 2>/dev/null', shell=True)
                    subprocess.call('echo ' + value +  ' | cryptsetup --batch-mode luksOpen /dev/loop0 pi.enc', shell=True)
                    subprocess.call('mount /dev/mapper/pi.enc /home/pi-enc', shell=True)
                    break
            if 'Complete Local Name' in desc:
                if btlename in value:
                    findkey = True 
開發者ID:ekiojp,項目名稱:circo,代碼行數:20,代碼來源:luksmnt.py

示例2: __init__

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def __init__(self, gateway, config, connector_type):
        super().__init__()
        self.__connector_type = connector_type
        self.__default_services = list(range(0x1800, 0x183A))
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}
        self.__gateway = gateway
        self.__config = config
        self.setName(self.__config.get("name",
                                       'BLE Connector ' + ''.join(choice(ascii_lowercase) for _ in range(5))))

        self._connected = False
        self.__stopped = False
        self.__previous_scan_time = time.time() - 10000
        self.__previous_read_time = time.time() - 10000
        self.__check_interval_seconds = self.__config['checkIntervalSeconds'] if self.__config.get(
            'checkIntervalSeconds') is not None else 10
        self.__rescan_time = self.__config['rescanIntervalSeconds'] if self.__config.get(
            'rescanIntervalSeconds') is not None else 10
        self.__scanner = Scanner().withDelegate(ScanDelegate(self))
        self.__devices_around = {}
        self.__available_converters = []
        self.__notify_delegators = {}
        self.__fill_interest_devices()
        self.daemon = True 
開發者ID:thingsboard,項目名稱:thingsboard-gateway,代碼行數:27,代碼來源:ble_connector.py

示例3: scan_for_devices

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def scan_for_devices(timeout: float, adapter='hci0') -> List[Tuple[str, str]]:
        """Scan for bluetooth low energy devices.

        Note this must be run as root!"""
        from bluepy.btle import Scanner

        match_result = re.search(r'hci([\d]+)', adapter)
        if match_result is None:
            raise BluetoothBackendException(
                'Invalid pattern "{}" for BLuetooth adpater. '
                'Expetected something like "hci0".'.format(adapter))
        iface = int(match_result.group(1))

        scanner = Scanner(iface=iface)
        result = []
        for device in scanner.scan(timeout):
            result.append((device.addr, device.getValueText(9)))
        return result 
開發者ID:ChristianKuehnel,項目名稱:btlewrap,代碼行數:20,代碼來源:bluepy.py

示例4: connect

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def connect(self, hub_mac=None, hub_name=None):
        log.debug("Trying to connect client to MoveHub with MAC: %s", hub_mac)
        scanner = btle.Scanner()

        while not self._peripheral:
            log.info("Discovering devices...")
            scanner.scan(1)
            devices = scanner.getDevices()

            for dev in devices:
                address = dev.addr
                address_type = dev.addrType
                name = dev.getValueText(COMPLETE_LOCAL_NAME_ADTYPE)

                if self._is_device_matched(address, name, hub_mac, hub_name):
                    self._peripheral = BluepyThreadedPeripheral(address, address_type, self._controller)
                    break

        return self 
開發者ID:undera,項目名稱:pylgbst,代碼行數:21,代碼來源:cbluepy.py

示例5: _get_data

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

        scan_processor = ScanProcessor(self.mac)
        scanner = btle.Scanner().withDelegate(scan_processor)
        scanner.scan(self.SCAN_TIMEOUT, passive=True)

        with timeout(
            self.SCAN_TIMEOUT,
            exception=DeviceTimeoutError(
                "Retrieving data from {} device {} timed out after {} seconds".format(
                    repr(self), self.mac, self.SCAN_TIMEOUT
                )
            ),
        ):
            while not scan_processor.ready:
                time.sleep(1)
            return scan_processor.results

        return scan_processor.results 
開發者ID:zewelor,項目名稱:bt-mqtt-gateway,代碼行數:22,代碼來源:miscale.py

示例6: __init__

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def __init__(self, command_timeout, global_topic_prefix, **kwargs):
        from bluepy.btle import Scanner, DefaultDelegate

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

            def handleDiscovery(self, dev, isNewDev, isNewData):
                if isNewDev:
                    _LOGGER.debug("Discovered new device: %s" % dev.addr)

        super(BlescanmultiWorker, self).__init__(
            command_timeout, global_topic_prefix, **kwargs
        )
        self.scanner = Scanner().withDelegate(ScanDelegate())
        self.last_status = [
            BleDeviceStatus(self, mac, name) for name, mac in self.devices.items()
        ]
        _LOGGER.info("Adding %d %s devices", len(self.devices), repr(self)) 
開發者ID:zewelor,項目名稱:bt-mqtt-gateway,代碼行數:21,代碼來源:blescanmulti.py

示例7: scan

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def scan(self):
    result = False
    devices = []
    try:
     self.scanner = Scanner(self.bledev)
     devices = self.scanner.scan(self.timeout)
     result = True
     self.lastscan = time.time()
    except Exception as e:
     print("BLE error: ",e)
     self.devices = []
     self.devrssi = []
    tempdev = []
    temprssi = []
    for dev in devices:
      try:
       if self.bledev == int(dev.iface):
        temprssi.append(dev.rssi)
        tempdev.append(str(dev.addr).lower().strip())
      except:
        pass
    self.devices = tempdev
    self.devrrsi = temprssi
    return result 
開發者ID:enesbcs,項目名稱:rpieasy,代碼行數:26,代碼來源:lib_blescan.py

示例8: _find_mac

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def _find_mac():
    """Finds and returns the mac address of the first Ganglion board
    found"""
    scanner = Scanner()
    devices = scanner.scan(5)

    if len(devices) < 1:
        raise OSError(
            'No nearby Devices found. Make sure your Bluetooth Connection '
            'is on.')

    else:
        gang_macs = []
        for dev in devices:
            for adtype, desc, value in dev.getScanData():
                if desc == 'Complete Local Name' and value.startswith(
                        'Ganglion'):
                    gang_macs.append(dev.addr)
                    print(value)

    if len(gang_macs) < 1:
        raise OSError('Cannot find OpenBCI Ganglion Mac address.')
    else:
        return gang_macs[0] 
開發者ID:openbci-archive,項目名稱:pyOpenBCI,代碼行數:26,代碼來源:ganglion.py

示例9: __init__

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
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() 
開發者ID:STMicroelectronics,項目名稱:BlueSTSDK_Python,代碼行數:21,代碼來源:manager.py

示例10: main

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def main():
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(10.0)

    for dev in devices:
        #print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
        for (adtype, desc, value) in dev.getScanData():
            #print "  %s = %s" % (desc, value)
            if (desc == "Complete Local Name"):
                if ("Mambo" in value):
                    print("FOUND A MAMBO!")
                    print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
                    print("  %s = %s" % (desc, value))

                elif ("Swing" in value):
                    print("FOUND A SWING!")
                    print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
                    print("  %s = %s" % (desc, value)) 
開發者ID:amymcgovern,項目名稱:pyparrot,代碼行數:20,代碼來源:findMinidrone.py

示例11: _findRileyLink

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def _findRileyLink(self):
        global g_rl_address
        scanner = Scanner()
        g_rl_address = None
        self.logger.debug("Scanning for RileyLink")
        retries = 10
        while g_rl_address is None and retries > 0:
            retries -= 1
            for result in scanner.scan(1.0):
                if result.getValueText(7) == RILEYLINK_SERVICE_UUID:
                    self.logger.debug("Found RileyLink")
                    g_rl_address = result.addr

        if g_rl_address is None:
            raise PacketRadioError("Could not find RileyLink")

        return g_rl_address 
開發者ID:winemug,項目名稱:omnipy,代碼行數:19,代碼來源:pr_rileylink.py

示例12: scan_devices

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def scan_devices(self, delegate=DefaultDelegate, timeout=5):
        devices = Scanner(self.iface).withDelegate(delegate()).scan(timeout=timeout) 
        return self._package_data_devices(devices) 
開發者ID:ElevenPaths,項目名稱:HomePWN,代碼行數:5,代碼來源:ble.py

示例13: main

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [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

示例14: connect

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def connect(self):
        # Auto-discover device on first connection
        if (self.MacAddr is None):
            scanner     = Scanner().withDelegate(DefaultDelegate())
            searchCount = 0
            while self.MacAddr is None and searchCount < 50:
                devices      = scanner.scan(0.1) # 0.1 seconds scan period
                searchCount += 1
                for dev in devices:
                    ManuData = dev.getValueText(255)
                    SN = parseSerialNumber(ManuData)
                    if (SN == self.SN):
                        self.MacAddr = dev.addr # exits the while loop on next conditional check
                        break # exit for loop
            
            if (self.MacAddr is None):
                print "ERROR: Could not find device."
                print "GUIDE: (1) Please verify the serial number."
                print "       (2) Ensure that the device is advertising."
                print "       (3) Retry connection."
                sys.exit(1)
        
        # Connect to device
        if (self.periph is None):
            self.periph = Peripheral(self.MacAddr)
        if (self.curr_val_char is None):
            self.curr_val_char = self.periph.getCharacteristics(uuid=self.uuid)[0] 
開發者ID:Airthings,項目名稱:waveplus-reader,代碼行數:29,代碼來源:read_waveplus.py

示例15: discover

# 需要導入模塊: from bluepy import btle [as 別名]
# 或者: from bluepy.btle import Scanner [as 別名]
def discover(self):
        scan_interval = 0.1
        timeout = 3
        scanner = btle.Scanner()
        for _count in range(int(timeout / scan_interval)):
            advertisements = scanner.scan(scan_interval)
            for adv in advertisements:
                if self.serial_number == _parse_serial_number(adv.getValue(btle.ScanEntry.MANUFACTURER)):
                    return adv.addr
        return None 
開發者ID:Airthings,項目名稱:wave-reader,代碼行數:12,代碼來源:read_wave.py


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