本文整理汇总了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
示例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
示例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
示例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
示例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
示例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))
示例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
示例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]
示例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()
示例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))
示例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
示例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)
示例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)
示例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]
示例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