def get_myo(mac=None): if mac is not None: while True: for i in btle.Scanner(0).scan(1): if i.addr == mac: return str(mac).upper() while True: for i in btle.Scanner(0).scan(1): for j in i.getScanData(): if j[0] == 6 and j[2] == 'd5060001-a904-deb9-4748-2c7f4a124842': return str(i.addr).upper()
def get_myo(mac=None): if mac is not None: while True: for i in btle.Scanner(0).scan(1): if i.addr == mac: return str(mac).upper() while True: for i in btle.Scanner(0).scan(1): for j in i.getScanData(): if j[0] == 6 and j[2] == '4248124a7f2c4847b9de04a9010006d5': return str(i.addr).upper()
def get_myo(mac=None): if mac is not None: while True: for i in btle.Scanner(0).scan(1): if i.addr == mac: return str(mac).upper() id = "ARM Myo " while True: for i in btle.Scanner(0).scan(1): for j in i.getScanData(): print(str(i.addr).upper(), j[0], "lol" + j[2] + "lol") if j[0] == 8 and j[ 2] == id: #'4248124a7f2c4847b9de04a9010006d5': print("success-->") return str(i.addr).upper()
def connect(self): try: if self._conn: self._conn.disconnect() try: self._conn = btle.Peripheral(self._mac, addrType=btle.ADDR_TYPE_PUBLIC) except btle.BTLEException as ex: print("Faild first connexion on " + self._mac) btle.Scanner().scan(10) self._conn = btle.Peripheral(self._mac, addrType=btle.ADDR_TYPE_PUBLIC) handles = self._conn.getCharacteristics() for handle in handles: if handle.uuid == yeelight_candela.NOTIFY_UUID: notify_char = handle if handle.uuid == yeelight_candela.CONTROL_UUID: control_chars = handle self.notify_handle = notify_char.getHandle() self.control_char = control_chars self.control_handle = self.control_char.getHandle() # We need to register to receive notifications self._conn.writeCharacteristic(self.REGISTER_NOTIFY_HANDLE, struct.pack("<BB", 0x01, 0x00)) except btle.BTLEException as generic: print("Faild to connect to " + self.mac)
def main(): scanner = btle.Scanner(0) print (ANSI_RED + "Scanning for devices..." + ANSI_OFF) with open('scan.log', 'a+') as log: while True: devices = scanner.scan(1.25) devices = filter(lambda dev: dev.addr in BEACONS, devices) beacons_missing = set(BEACONS.keys()) for device in devices: beacon = BEACONS[device.addr] beacon.add_recent(device.rssi) log.write(json.dumps({'event_type': 'beacon_detection', 'time': time.time(), 'beacon_name': beacon.name, 'rssi': device.rssi}) + "\n") log.flush() beacons_missing.remove(device.addr) for mac in beacons_missing: beacon = BEACONS[mac] beacon.mark_missing() for beacon in BEACONS.values(): if beacon.is_too_close: print(ANSI_RED + f"{beacon.name} is too close ({beacon.recent_moving_average} ({beacon.stdev}))!" + ANSI_OFF) alert(log) else: print(ANSI_GREEN + f"{beacon.name} is far enough away ({beacon.recent_moving_average} ({beacon.stdev}))" + ANSI_OFF)
def main(): sys.stdout.write(' \n') sys.stdout.write('-------------------------------------\n') sys.stdout.write('Starting Xiaomi mi Scale...\n') BluetoothFailCounter = 0 while True: try: scanner = btle.Scanner().withDelegate(ScanProcessor()) scanner.scan( 5) # Adding passive=True to try and fix issues on RPi devices except BTLEDisconnectError as error: sys.stderr.write(f"btle disconnected: {error}\n") pass except BTLEManagementError as error: sys.stderr.write(f"Bluetooth connection error: {error}\n") if BluetoothFailCounter >= 4: sys.stderr.write( f"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: sys.stderr.write("Error while running the script, continuing...\n") pass else: BluetoothFailCounter = 0 time.sleep(TIME_INTERVAL)
def ScanForTomatoOrDie(): if os.geteuid() != 0: print('you need root permission for ble scanning.') print('please run the program with sudo ...') print('program exiting.') sys.exit(0) logging.info('scaning for tomato...') scanner = btle.Scanner() print('scanning for miaomiao devices') devices = scanner.scan(7) found_devices = 0 tomato_device = None print('devices found:') for device in devices: name = device.getValueText(9) print(device.addr, device.addrType, name) if 'miaomiao' in name: found_devices += 1 tomato_device = device if found_devices == 0: print('No miaomiao devices found, please try again. Program exiting.') sys.exit(0) if found_devices > 1: print('More then one device found, Program exiting.') sys.exit(0) print('Will use device ', device.getValueText(9), device.addr) ConfigReader.g_config.UpdateSection('BTDevice', 'bt_mac_address', device.addr)
def scan(iface, interval, continuous): delegate = MiaoMiaoScanner() scanner = btle.Scanner(iface).withDelegate(delegate) while True: device = scanner.scan(interval) if not continuous: break
def pairWand(): print("Looking for a magic wand...") # TODO Change to discover the closest device of type Wand-75 try: global blueWand scanner = btle.Scanner() le_devices = scanner.scan(timeout=5) for dev in le_devices: # print("D: dvc {} ({}), RSSI={} dB".format(dev.addr, \ # dev.addrType, dev.rssi)) for (adtype, desc, value) in dev.getScanData(): # print("D: {}, {} = {}".format(adtype, desc, value)) if ("Kano-Wand" in value): print("I found a wand! A: {}".format(dev.addr)) MAC_ADDRESS = dev.addr if (MAC_ADDRESS is None): print("E: MAC_ADDRESS is not set (no Wand was found :/)...") exit(0) blueWand = btle.Peripheral(MAC_ADDRESS, btle.ADDR_TYPE_RANDOM) blueWand.setDelegate(MyDelegate()) print('Hey. We paired.') except Exception as e: print('E: I am afraid I cannot connect: {}', e) sys.exit(0)
def status_update(self): from bluepy import btle if self.passive: scanner = btle.Scanner() results = scanner.scan( self.scan_timeout if hasattr(self, 'scan_timeout') else 20.0, passive=True) for res in results: device = self.find_device(res.addr) if device: for (adtype, desc, value) in res.getScanData(): if ("1a18" in value): _LOGGER.debug("%s - received scan data %s", res.addr, value) device.processScanValue(value) 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)) ]
def retrieve_notifications(): address = None scanner = btle.Scanner() while address is None: scan_time = 1 print('scanning for {} seconds...'.format(scan_time)) for device in scanner.scan(scan_time): # scan for 10 seconds device_name = device.getValueText( COMPLETE_LOCAL_NAME) # get adtype for "Complete Local Name" if device_name is not None and 'tempSensor' in device_name: address = device.addr print('found one!') queue = Queue() #address = 'D0:B5:C2:9F:95:02' peripheral = btle.Peripheral(address).withDelegate( Delegate(lambda val: queue.put(val))) while True: # empty queue (filled during waitForNotifications) while not queue.empty(): yield queue.get() queue.task_done() if peripheral.waitForNotifications(1): # one second timeout # handleNotification() was called continue print('Waiting...')
def discover(self, scan_duration=1): #seconds btle.Debugging = False scanner = btle.Scanner().withDelegate(ScanDummy()) raw_devices = scanner.scan(scan_duration) scan_items = {} for scan_item in raw_devices: device_name = None for (sdid, desc, val) in scan_item.getScanData(): if sdid == self.DEVICE_NAME_FIELD_ID: device_name = val if device_name == self.DEVICE_NAME: try: rssi = scan_item.rssi mac = scan_item.addr.upper() scan_date = datetime.datetime.now() adv_payload = self.unpack_broadcast_data(scan_item.rawData) if not (mac in scan_items): scan_items[mac] = { 'scan_date': scan_date, 'rssi': rssi, 'adv_payload': adv_payload } else: scan_items[mac]['rssi'] = rssi scan_items[mac]['scan_date'] = scan_date except Exception as e: s = traceback.format_exc() self.logger.error( "unexpected failure during scan, {} ,{}".format(e, s)) return scan_items
def standard_scan(iface=0, timeout=2, verbose=False): from bluepy import btle # importing here for now so that we can test device manager code on systems without bluepy installed btle.Debugging = verbose scanner = btle.Scanner(iface) try: devices = scanner.scan(timeout) except btle.BTLEDisconnectError: # seems to occur sometimes if the timeout is too long print('BTLE disconnect error') devices = [] dev_infos = [] for d in devices: manufacturer = d.getValueText(255) if manufacturer and manufacturer.startswith('3301'): label = d.getValueText(9) if label and len(d.rawData) > 17: # TODO: does the rawData include a checksum? if so, we should check it rssi = d.rssi vals = d.rawData temperature = (vals[13] * 256 + vals[14]) * 0.1 humidity = (vals[15] * 256 + vals[16]) * 0.1 if temperature < 100 and humidity < 100: # TODO: any other checks we should use? dev_info = { 'label': label, 'rssi': d.rssi, 'temperature': temperature, 'humidity': humidity, } dev_infos.append(dev_info) return dev_infos
def discover(self, scanDuration=1): #seconds btle.Debugging = False scanner = btle.Scanner().withDelegate(ScanDummy()) raw_devices = scanner.scan(scanDuration) devices = {} for device in raw_devices: device_name = None for (sdid, desc, val) in device.getScanData(): if sdid == self.DEVICE_NAME_FIELD_ID: device_name = val if device_name == self.DEVICE_NAME: rssi = device.rssi mac = device.addr.upper() is_sync = not (self.CLOCK_STATE_UNSYNC in device.rawData) scan_date = datetime.datetime.now() if not (mac in devices): devices[mac] = { 'scan_date': scan_date, 'is_sync': is_sync, 'rssi': rssi } else: devices[mac]['rssi'] = rssi devices[mac]['scan_date'] = scan_date return devices
def discover(interface_index=0, timeout=2): ''' Discover devices. Only does basic checking by comparing name of the device to the default name. Parameters ---------- device : string The bluetooth device to use for discovery, defaults to 'hci0'. timeout : int Timeout for searching the devices, defaults to 2. Returns ------- devices : list of MiPlant -objects A list of MiPlant -objects corresponding to the devices found. ''' return [ MiPlant(device.addr, interface_index=interface_index) for device in btle.Scanner(interface_index).scan(timeout) if device.addr.startswith('c4:7c') and len([[1 for x in device.getScanData() if x[1] == 'Complete Local Name' and x[2] == 'Flower mate']]) != 0 ]
def scan(): '''Scans for BLE devices and returns information about them used essentially for the user to find belonging new 'devices' (sensor|ringer) Returns: dict: data in json format ''' data = {} devices = btle.Scanner().scan(10.0) for dev in devices: dev_data = {} dev_data['addr'] = dev.addr dev_data['addrType'] = dev.addrType dev_data['rssi'] = dev.rssi print("Device ", dev.addr, " (", dev.addrType, "), RSSI=", dev.rssi, " dB") scan_data = {} for (adtype, desc, value) in dev.getScanData(): scan_data[desc] = value print(adtype, " | ", desc, " = ", value) dev_data['scan_data'] = scan_data print("--------------------------------------------------") data[dev.addr] = dev_data return data
def connect(self, hub_mac=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 addressType = dev.addrType name = dev.getValueText(COMPLETE_LOCAL_NAME_ADTYPE) log.debug("Found dev, name: {}, address: {}".format( name, address)) if address != "00:00:00:00:00:00": if (not hub_mac and name == LEGO_MOVE_HUB) or hub_mac == address: logging.info("Found %s at %s", name, address) self._peripheral = BluepyThreadedPeripheral( address, addressType, self._controller) break return self
def ScanForBTLEDevices(): scanner = btle.Scanner() print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") + " Scanning for bluetooth devices....", flush=True) devices = scanner.scan() bAllDevicesFound = True for blind in config['AM43_BLE_Devices']: blindMAC = config.get('AM43_BLE_Devices', blind) # Read BLE MAC from ini file bFound = False for dev in devices: if (blindMAC == dev.addr): print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") + " Found " + blindMAC, flush=True) bFound = True break #else: #bFound = False if bFound == False: print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") + " " + blindMAC + " not found on BTLE network!", flush=True) bAllDevicesFound = False if (bAllDevicesFound == True): print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") + " Every AM43 Blinds Controller is found on BTLE network", flush=True) return else: print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") + " Not all AM43 Blinds Controllers are found on BTLE network, restarting bluetooth stack and checking again....", flush=True) os.system("service bluetooth restart") raise ValueError(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") + " Not all AM43 Blinds Controllers are found on BTLE network, restarting bluetooth stack and check again....")
def scan_for_devices(): """ Scan for bluetooth low energy devices. """ scanner = btle.Scanner() result = [] scan_data = [] addr_list = [] temp_dict = {} #BLE device scan for device in scanner.scan(): scan_data.append(device.scanData) addr_list.append(device.addr) #scanEntry 가공 for i in range(len(scan_data)): if 9 in scan_data[i]: temp_dict = {'addr':addr_list[i], 'name':scan_data[i][9].decode('utf-8')} else: temp_dict = {'addr':addr_list[i], 'name':'no name'} result.append(temp_dict) print(result) return result
def connect(self): try: try: self.device = btle.Peripheral(self.mac, addrType=btle.ADDR_TYPE_PUBLIC) except btle.BTLEException as inst: print(inst) btle.Scanner().scan(10) self.device = btle.Peripheral(self.mac, addrType=btle.ADDR_TYPE_PUBLIC) handles = self.device.getCharacteristics() for handle in handles: if handle.uuid == "217887f8-0af2-40029c05-24c9ecf71600": self.statehandle = handle if handle.uuid == "74532143-fff1-460d-8e8a-370f934d40be": self.rgbhandle = handle if handle.uuid == "5b430c99-cb06-4c66-be2c-b538acfd1961": self.whitehandle = handle # From 0x00 to 0x7F if handle.uuid == "1c537b0a-4eaa-4e19-b98c-eaaa5bcd9bc9": self.rgbBrightnessHandle = handle # From 0x00 to 0x64 if handle.uuid == "d8da934c-3d8f-4bdf-9230-f61295b69570": self.whiteBrightnessHandle = handle # From 0x00 to 0x73 if handle.uuid == "9e926da7-cffa-47f5-8d4b-7e82aff1a02a": self.lightMode = handle # 0x00 for White mode and 0x01 for color mode self.get_state() return True except btle.BTLEException as inst: print(inst) return False
def ble_scanning(self, scanTime): #print("\033[0;35;40m ble_scanning()\033[0m") """ Scan for StretchSense devices in the area and store them in listPeripheralAvailable. :param scanTime: int : Time to scan for. July 29, 2020: argparse commented by Alvee to allow use with Jupyter Notebook added EasyDict instead to work with Jupyter Notebook """ # parser = argparse.ArgumentParser() # parser.add_argument('-i', '--hci', action='store', type=int, default=0, # help='Interface number for scan') # parser.add_argument('-t', '--timeout', action='store', type=int, default=4, # help='Scan delay, 0 for continuous') # parser.add_argument('-s', '--sensitivity', action='store', type=int, default=-128, # help='dBm value for filtering far devices') # parser.add_argument('-d', '--discover', action='store_true', # help='Connect and discover service to scanned devices') # parser.add_argument('-a', '--all', action='store_true', # help='Display duplicate adv responses, by default show new + updated') # parser.add_argument('-n', '--new', action='store_true', # help='Display only new adv responses, by default show new + updated') # parser.add_argument('-v', '--verbose', action='store_true', # help='Increase output verbosity') # arg = parser.parse_args(sys.argv[1:]) arg = EasyDict({ 'hci': 0, 'timeout': 4, 'sensitivity': -128, 'discover': True, 'all': True, 'new': True, 'verbose': True }) # self.Debugging = arg.verbose scanner = btle.Scanner(arg.hci).withDelegate(self.ScanPrint(arg)) devicesAvailable = scanner.scan(scanTime) self.listPeripheralInUse = [] for devices in devicesAvailable: deviceAlreadyInTheList = False for (sdid, desc, val) in devices.getScanData(): if (val == StretchSenseAPI.deviceName): for myDeviceInTheList in self.listPeripheralAvailable: if (myDeviceInTheList.addr == devices.addr): deviceAlreadyInTheList = True if deviceAlreadyInTheList is False: self.listPeripheralAvailable.append(devices)
def scan(self, name="BubbleCannon", timeout=6, limitone=False): if not ble_support: logging.info("no ble support") return False scanner = btle.Scanner() #.withDelegate(ScanDelegate()) t0 = time() scanned = set() try: while time() < t0 + timeout: # Scanner.scan() has no way to return early # so we will just do a succession of really short scans for d in scanner.scan(timeout=0.1): if not d.addr in scanned: print("new device: {}".format(d.addr)) scanned.add(d.addr) for _, key, val in d.getScanData(): # print("{}: {}".format(key, val)) if key == "Complete Local Name": # print("device name: {}".format(val)) if val == name: # print("Found it!") self.addr = d.addr return True except btle.BTLEException as e: print(" ->", e) return False
def run(self): scanner = btle.Scanner() scanner.withDelegate(self) while True: scanner.start() scanner.process(1) scanner.stop()
def ble_scan(self): self.dev_list = [] self.conn_list = [] scan = btle.Scanner() print("Scanning for 5 seconds") devs = scan.scan(5) for dev in devs: self.dev_list.append(dev.addr) for dev in self.dev_list: print(dev) for ble_mac in self.ble_list: try: print("Try To connect : " + ble_mac) if ble_mac in self.dev_list: conn = btle.Peripheral(ble_mac) #conn_list.append(conn); ch = conn.getCharacteristics(uuid=self.cont_uuid)[0] self.conn_list.append(ch) else: self.conn_list.append(None) except btle.BTLEException as ex: self.conn_list.append(None)
def main(): if MQTT_DISCOVERY: discovery() BluetoothFailCounter = 0 while True: try: scanner = btle.Scanner(HCI_DEV).withDelegate(ScanProcessor()) if BLUEPY_PASSIVE_SCAN: scanner.scan(5, passive=True) #passive=True to try and fix issues for bluepy on RPi devices else: scanner.scan(5) 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 hci' + HCI_DEV + ' down' ps = subprocess.Popen(cmd, shell=True) time.sleep(1) cmd = 'hciconfig hci' + HCI_DEV + ' up' 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)
def getMyo(mac=None): cnt = 0 if mac != None: while True: for i in btle.Scanner(0).scan(1): if i.addr == mac: return str(mac).upper() cnt += 1 logging.info('Try #' + str(cnt)) while True: for i in btle.Scanner(0).scan(1): for j in i.getScanData(): if j[0] == 6 and j[2] == '4248124a7f2c4847b9de04a9010006d5': return str(i.addr).upper() logging.info('Try #' + str(cnt))
def findRobots(self): scanner = btle.Scanner().withDelegate(btle.DefaultDelegate()) devices = scanner.scan(10.0) for dev in devices: for (adtype, desc, value) in dev.getScanData(): if (adtype == 9 and value.startswith('OzoEvo')): print(adtype, dev.addr, value) self.robots.append(Robot(dev.addr, value))
def run(self): '''Main-loop of the daemon, started via daemon.start().''' scanner = btle.Scanner().withDelegate(RuuviDaemon.ScanDelegate(self)) scanner.start(passive=True) while not self.__stop.is_set(): scanner.process(timeout=0.1) scanner.stop()
def scan(): """ Scans for available devices. """ scan = btle.Scanner() devs = scan.scan(5) for dev in devs: # print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi) for (adtype, desc, value) in dev.getScanData(): if adtype == 255 and value.startswith("1234"): parseSensorData(dev.addr, dev.rssi, value)
def scan(): scanner = btle.Scanner(0) devices = scanner.scan(1.0) for device in devices: print(f"[ADDR {device.addr}]") print(f" AddrType {device.addrType}") for (adTypeCode, description, valueText) in device.getScanData(): print(f" ad: code:{adTypeCode} {description}:{valueText}")