1#!/usr/bin/env python3 2# 3# Copyright (C) 2018 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); you may not 6# use this file except in compliance with the License. You may obtain a copy of 7# the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14# License for the specific language governing permissions and limitations under 15# the License. 16 17import time 18 19 20def le_scan_for_device_by_name(fd, 21 log, 22 search_name, 23 timeout, 24 partial_match=False): 25 """Scan for and returns the first BLE advertisement with the device name. 26 27 Args: 28 fd: The Fuchsia device to start LE scanning on. 29 name: The name to find. 30 timeout: How long to scan for. 31 partial_match: Only do a partial match for the LE advertising name. 32 This will return the first result that had a partial match. 33 34 Returns: 35 The dictionary of device information. 36 """ 37 scan_filter = {"name_substring": search_name} 38 fd.gattc_lib.bleStartBleScan(scan_filter) 39 end_time = time.time() + timeout 40 found_device = None 41 while time.time() < end_time and not found_device: 42 time.sleep(1) 43 scan_res = fd.gattc_lib.bleGetDiscoveredDevices()['result'] 44 for device in scan_res: 45 name, did, connectable = device["name"], device["id"], device[ 46 "connectable"] 47 if name == search_name or (partial_match and search_name in name): 48 log.info("Successfully found advertisement! name, id: {}, {}". 49 format(name, did)) 50 found_device = device 51 fd.gattc_lib.bleStopBleScan() 52 if not found_device: 53 log.error("Failed to find device with name {}.".format(search_name)) 54 return found_device 55 return found_device 56