Пример #1
0
 def find_temp_sensors(sensors):
   TempSensor._scanning_lock.acquire()
   logger.debug('Scanning for devices')
   scanner = Scanner().withDelegate(ScanDelegate())
   try:
     devices = scanner.scan(10.0)
     if sensors is None:
       sensors = {}
     for device in devices:
       if device.addr in sensors:
         continue
       name = ''
       if device.getValueText(9):
         name = device.getValueText(9)
       elif device.getValueText(8):
         name = device.getValueText(8)
       logger.debug('Device name: ' + name)
       if 'SensorTag' in name:
         logger.info('Found SensorTag with address: ' + device.addr)
         sensors[device.addr] = SensorTag(device)
       elif 'MetaWear' in name:
         logger.info('Found MetaWear with address: ' + device.addr)
         sensors[device.addr] = MetaWear(device)
     logger.debug('Finished scanning for devices')
     TempSensor._scanning_lock.release()
     if len(sensors) == 0:
       raise NoTagsFoundException('No sensors found!')
   except BTLEException as e:
     scanner.stop()
     logger.warn('Got exception ' + e.message)
     TempSensor._scanning_lock.release()
   return sensors
Пример #2
0
    def find_port(self):
        """Detects Ganglion board MAC address
        If more than 1 around, will select first. Needs root privilege.
        """

        print("Try to detect Ganglion MAC address. "
              "NB: Turn on bluetooth and run as root for this to work!"
              "Might not work with every BLE dongles.")
        scan_time = 5
        print("Scanning for 5 seconds nearby devices...")

        #   From bluepy example
        class ScanDelegate(DefaultDelegate):
            def __init__(self):
                DefaultDelegate.__init__(self)

            def handleDiscovery(self, dev, isNewDev, isNewData):
                if isNewDev:
                    print("Discovered device: " + dev.addr)
                elif isNewData:
                    print("Received new data from: " + dev.addr)

        scanner = Scanner().withDelegate(ScanDelegate())
        devices = scanner.scan(scan_time)

        nb_devices = len(devices)
        if nb_devices < 1:
            print("No BLE devices found. Check connectivity.")
            return ""
        else:
            print("Found " + str(nb_devices) + ", detecting Ganglion")
            list_mac = []
            list_id = []

            for dev in devices:
                # "Ganglion" should appear inside the "value" associated
                # to "Complete Local Name", e.g. "Ganglion-b2a6"
                for (adtype, desc, value) in dev.getScanData():
                    if desc == "Complete Local Name" and value.startswith("Ganglion"):
                        list_mac.append(dev.addr)
                        list_id.append(value)
                        print("Got Ganglion: " + value +
                              ", with MAC: " + dev.addr)
                        break
        nb_ganglions = len(list_mac)

        if nb_ganglions < 1:
            print("No Ganglion found ;(")
            raise OSError('Cannot find OpenBCI Ganglion MAC address')

        if nb_ganglions > 1:
            print("Found " + str(nb_ganglions) + ", selecting first")

        print("Selecting MAC address " + list_mac[0] + " for " + list_id[0])
        return list_mac[0]
Пример #3
0
    def getTag(self):
        """Scans for BT LE devices and returns the choosen keywords"""
        self.count = 0
        scanner = Scanner().withDelegate(DefaultDelegate())
        devices = scanner.scan(self.scanTimeout)
        for dev in devices:
            if dev.addr == self.address.lower():
                self.count = 1
			
        if self.count > 0:
            self.count = 0
            return self.found
        else:
            return self.missing
Пример #4
0
 def cmd_list_devices(self, *args):
     try:
         self.last_scan = ScanDelegate()
         scanner = Scanner().withDelegate(self.last_scan)
         print('Listing Bluetooth LE devices in range for 5 minutes.'
               'Press CTRL+C to stop searching.')
         print('{: <5} {: <30} {: <12}'.format('ID', 'Name', 'Mac address'))
         print('{: <5} {: <30} {: <12}'.format('--', '----', '-----------'))
         scanner.scan(350)
     except KeyboardInterrupt:
         print('\n')
     except RuntimeError as e:
         logger.error('Problem with the Bluetooth adapter : {}'.format(e))
         return False
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))
Пример #6
0
def scan(timeout=10.0) -> []:
    if (_semaphore.acquire(True, 0.5)):
        try:
            scanner = Scanner().withDelegate(ScanDelegate())
            devices = scanner.scan(timeout)

            for dev in devices:
                logger.info("Device {} ({}), RSSI={} dB".format(
                    dev.addr, dev.addrType, dev.rssi))
                for (adtype, desc, value) in dev.getScanData():
                    logger.info("  {} = {}".format(desc, value))
            return devices
        except Exception as ex:
            logger.error('Error {}'.format(ex))
        finally:
            _semaphore.release()
    else:
        raise BlockingIOError(errno.EINPROGRESS)
Пример #7
0
def scanForNew(checkList):
    global NofDongles
    NofDongles= getDongleNumber()
    newList = []
    
    for i in range(NofDongles):
        print ("using dongle: "+str(i))
        scanner = Scanner().withDelegate(ScanDelegate())
        devices = scanner.scan(10.0)
        
        for dev in devices:
            for (adtype, _, value)in dev.getScanData():                 
                if adtype==2 and value=="0000fe95-0000-1000-8000-00805f9b34fb" and not dev.addr in checkList and not dev.addr in newList:
                    newList.append(dev.addr)

                    print("ok_ALREADY")
    
    return newList
Пример #8
0
    def __init__(self,
                 yaml_config: dict,
                 min_rssi: float = -65,
                 ble_device: str = 'hci0'):

        self.devs_in_range = {}  # Stores devices found to be in range
        self.active_connections = {}
        self._chrcs_cache = {}

        self.yaml_config = yaml_config
        self.valid_names = yaml_config['regex']['names']
        self.valid_addrs = yaml_config['regex']['addrs']
        self.chrc_handles = list(yaml_config['characteristics'].keys())

        self.min_rssi = min_rssi
        self.ble_device = ble_device[-1]  # Hacky

        self.scanner = Scanner()
Пример #9
0
def getCharacteristic():

    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(0.3)
    for dev in devices:
        for (adtype, desc, value) in dev.getScanData():

            if str(value).find("8856") != -1:
                # timestamp

                t = time.time()
                distance = CalculateDistance(dev.rssi, -60)
                uuid = "8856"
                # print("distance is %s" % distance)
                usefulInformation = ("%s ,%s ,%s " % (t, distance, uuid))

                return usefulInformation
    return ("cannot detect the target object")
Пример #10
0
def scan():
    devices_set = set()
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(2.0)
    for dev in devices:
        for (adtype, desc, value) in dev.getScanData():
            #if value == SVC_UUID:
            print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
            print("  %s = %s" % (desc, value))
            devices_set.add(dev.addr)
            d = btle.Peripheral(dev.addr)
            print(value)
            service = d.getServiceByUUID(btle.UUID(MY_SRVC))
            for svc in d.services:
                print(str(svc))
            for ch in service.getCharacteristics():
                print(str(ch))
    return devices_set
Пример #11
0
class BLE_handler:
    '''
    This class handles the communication with the sensor modules through BLE protocol.

    '''
    # Constructor initializing all properties:
    def __init__(self):
        # modules_MACs = ['18:93:d7:14:5e:2b', 'c8:fd:19:3e:be:7f']
        self.modules_MACs = []
        self.connected_modules = []
        self.connection_threads = []
        self.scanner = Scanner(0)
        self.api = API_handler()
        self.apiWrite = False
        self.bleDevices = []

    def addModuleMAC(self, new_MAC):
        self.modules_MACs.append(new_MAC)

    def scan(self):
        self.bleDevices = self.scanner.scan(2)
        for d in self.bleDevices:
            print(d.addr)

    def connect(self):
        while len(self.connection_threads) < len(self.modules_MACs):
            print 'Scanning ...'
            devices = self.scanner.scan(2)
            for d in devices:
                if d.addr in self.modules_MACs:
                    p = Peripheral(d)
                    self.connected_modules.append(p)
                    print 'Module ' + d.addr + ' connected. Assigned ID = ' + str(len(self.connected_modules)-1)
                    t = ConnectionHandlerThread(len(self.connected_modules)-1, self.connected_modules, self.api)
                    t.start()
                    self.connection_threads.append(t)
                    # time.sleep(3)

        print 'All devices are connected.'

    def disconnect(self):
        print 'Disconnecting ...'
        for connection in self.connection_threads:
            connection.stop()
Пример #12
0
    def thermoBeacon(self):
        scanner = Scanner().withDelegate(ScanDelegate())
        try:
            while (True):
                devices = scanner.scan(1.0)

                ManuData = ""

                for dev in devices:
                    if dev.addr == "dc:12:00:00:06:a5":
                        CurrentDevAddr = dev.addr
                        for (adtype, desc, value) in dev.getScanData():
                            if (desc == "Manufacturer"):
                                ManuData = value

                        if (ManuData == ""):
                            print("No data received, end decoding")
                            continue

                        ManuDataHex = []
                        for i, j in zip(ManuData[::2], ManuData[1::2]):
                            ManuDataHex.append(int(i + j, 16))

                        if not len(ManuDataHex) == 20:
                            continue

                        tempidx = 12
                        humidityidx = 14

                        TempData = ManuDataHex[tempidx]
                        TempData += ManuDataHex[tempidx + 1] * 0x100
                        TempData = TempData * 0.0625
                        if TempData > 4000:
                            TempData = -1 * (4096 - TempData)

                        HumidityData = ManuDataHex[humidityidx]
                        HumidityData += ManuDataHex[humidityidx + 1] * 0x100
                        HumidityData = HumidityData * 0.0625

                        self.recv.recv_signal.emit(TempData, HumidityData)

        except DecodeErrorException:
            print("Decode Exception")
            pass
Пример #13
0
class ClientScanner(threading.Thread, Observer):

    def __init__(self):
        threading.Thread.__init__(self)
        # print("Creation")
        self.ScannerDelegate = ScannerInterface(['ac:23:3f:a3:33:d8'])
        self.scanner = Scanner().withDelegate(self.ScannerDelegate)
        self.__stop_event = False

    def add_observateur(self, obs: Observer):
        # print(self.__dict__)
        self.ScannerDelegate.add_observer(obs)

    def unstop(self):
        self.__stop_event = True
        print("Lancement")

    def stop(self):
        self.__stop_event = False

    def update(self, subject: ClientObservable) -> None:
        print("update client scanner")
        param = subject.event.split('/')[-1]
        print(param)
        if param == 'add_device':
            new_device = eval(subject.valeurs.decode())
            print(new_device)
            if new_device not in self.ScannerDelegate.deviceToScan:
                self.ScannerDelegate.deviceToScan.append(new_device)
            print(self.ScannerDelegate.deviceToScan)
        if param == 'set_min_rssi':
            rssi = eval(subject.valeurs.decode())
            print('new rssi min :',rssi)
            self.ScannerDelegate.minRSSI = rssi
            print(self.ScannerDelegate.minRSSI)


    def run(self) -> None:
        if self.ScannerDelegate.list_observers:
            while 1:
                if self.__stop_event:
                    self.scanner.scan()
        else:
            print("Erreur il n'y a personne pour récupérer les infos du scanner")
Пример #14
0
def find_acaia_devices(timeout=3, backend='bluepy'):
    addresses = []
    print('Looking for ACAIA devices...')

    if backend == 'pygatt':
        try:
            from pygatt import GATTToolBackend
            adapter = GATTToolBackend('hci0')
            adapter.reset()
            adapter.start(False)
            devices = adapter.scan(timeout=timeout, run_as_root=True)
            addresses = []
            for d in devices:
                if d['name'] and d['name'].startswith('ACAIA'):
                    print(d['name'], d['address'])
                    addresses.append(d['address'])
            adapter.stop()
        except ImportError:
            raise Exception('pygatt is not installed')

    elif backend == 'bluepy':

        try:
            from bluepy.btle import Scanner, DefaultDelegate

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

            scanner = Scanner().withDelegate(ScanDelegate())
            devices = scanner.scan(timeout)

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

        except ImportError:
            raise Exception('bluepy is not installed')

    return addresses
def connect(strip, scanTimeout=2, reconnectAttempts=1, maxAttempts=10):
    # Max attempts reached
    if reconnectAttempts > maxAttempts:
        print("Failed to connect after %d attempts" % maxAttempts)
        return

    try:
        # Scanning for devices
        print("Scanning for devices (%d / %d)" %
              (reconnectAttempts, maxAttempts))
        scanner = Scanner()
        devices = scanner.scan(scanTimeout)

        for device in devices:
            # Only connect to Nuimos
            if device.connectable and device.getValueText(9) == "Nuimo":
                # Init Nuimo class
                nuimo = Nuimo(device.addr)
                nuimo.set_delegate(NuimoDelegate(nuimo, strip))

                # Connect to Nuimo
                print("Trying to connect to %s." % device.addr)

                nuimo.connect()
                nuimo.displayLedMatrix(LedMatrixString().getRaspberry(), 5)

                print("Connected successfully to %s." % device.addr)
                # Reset reconnect attempts on successfull connect
                reconnectAttempts = 0

                while True:
                    nuimo.waitForNotifications()
                return

        # Found no Nuimo
        print("Couldn't find a Nuimo.")
        connect(strip, scanTimeout + 1, reconnectAttempts + 1)
    except BTLEException:
        print("Failed to connect to %s. Make sure to:\n  1. Run program as root (For Scanning and the Strip)\n  2. Disable the Bluetooth device: hciconfig hci0 down\n  3. Enable the Bluetooth device: hciconfig hci0 up\n  4. Enable BLE: btmgmt le on\n" % nuimo.macAddress)
        connect(strip, scanTimeout + 1, reconnectAttempts + 1)
    except KeyboardInterrupt:
        print("Program aborted.")
        return
Пример #16
0
def scan(timeScan=3):
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(timeScan)
    global deviceScan
    deviceScan = []

    for dev in devices:
        print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
        for (adtype, desc, value) in dev.getScanData():
            if desc == "Complete Local Name":
                deviceScan.append({'name': value, 'id': dev.addr})
            print "  %s = %s" % (desc, value)

    print "\nDevice list: "
    index = 0
    for dev in deviceScan:
        print "%d) Device name: %s;\tID: %s" % (index, dev['name'], dev['id'])
        index += 1
    print "\n"
Пример #17
0
def main():
    while True:
        scanner = Scanner()  # スキャン開始。
        print('scan start.')
        while True:
            devices = scanner.scan(5.0)
            for device in devices:
                if device.addr == ADDR_BSTICK:
                    con = Connection(device)
                    con.setDelegate(NotifyDelegate())
                    con.start()
                    print("connect to:", device.addr, " RSSI=", device.rssi)
                    con.writeCharacteristic(HANDLE_RSSI,
                                            str(device.rssi).encode('utf-8'),
                                            0)
                    while True:
                        if con.waitForNotifications(10):
                            continue
                        print("wait..")
Пример #18
0
def search_loop():
    while True:
        scanner = Scanner().withDelegate(ScanDelegate())
        devices = scanner.scan(5.0)

        for dev in devices:
            data = dev.getScanData()
            for (adtype, desc, value) in data:
                if "Short Local Name" in desc:
                    print("Cube found:")
                    print("  Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
                    for (adtype, desc, value) in data:
                        print("  %s = %s" % (desc, value))
                    p = Peripheral(deviceAddr=dev.addr, addrType=dev.addrType)
                    for serv in p.getServices():
                        print(serv.uuid.getCommonName())
                        for char in serv.getCharacteristics():
                            pprint(char.propertiesToString())
                    return
Пример #19
0
    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()
Пример #20
0
def main():
    # mjpeg-Streamer起動
    r = subprocess.check_output("sh /home/pi/lib/mjpg-streamer/start.sh", shell=True)
    lcd.print( 'mjpeg-streamer started')
    # Scannerインスタンスを生成するとスキャン開始
    # withDelegateでデバイス見つけたときのハンドラーを渡しておくと呼んでくれる。
    while True:
        scanner = Scanner().withDelegate(ScanDelegate())
        lcd.print( 'scan start.')
        try:
            while True:
                scanner.scan(5.0)
        except BTLEException:
            #scannedDevs = {}
            # 駆動系緊急停止
            moveCameraHead(0, 0)
            moveTwinGear(0, 0)
            lcd.print( 'BTLE Exception.')
            pass
Пример #21
0
    def status_update(self):
        scanner = Scanner().withDelegate(ScanDelegate())
        devices = scanner.scan(5.0)
        ret = []

        for name, mac in self.devices.items():
            _LOGGER.info("Updating %s device '%s' (%s)", repr(self), name, mac)
            device = self.searchmac(devices, mac)
            for attr in monitoredAttrs:
                if attr == 'rssi' and device is not None:
                    ret.append(
                        MqttMessage(topic=self.format_topic(name, attr),
                                    payload=device.rssi))
                if attr == 'rssi_level':
                    level = get_rssi_level(device.rssi) if device else -1
                    ret.append(
                        MqttMessage(topic=self.format_topic(name, attr),
                                    payload=level))
        return ret
Пример #22
0
def getMamboAddr():
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(10.0)
    mamboAddr = None
    mamboName = None

    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))
                    mamboAddr = dev.addr
                    mamboName = value
    return mamboAddr, mamboName
Пример #23
0
    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
Пример #24
0
    def discover():
        """
        Scans for BLE devices and tries to automatically select the glasses

        Returns:
            str: The glasses' MAC address
        """
        scanner = Scanner()
        selected_glasses = None
        devices = scanner.scan(10.0)

        print("[" + Fore.CYAN + "*" + Fore.RESET + "] Looking for glasses ...")
        glasses_list = [
            device.addr for device in devices
            ]

        if len(glasses_list) > 1:
            print(
                "[" +
                Fore.GREEN +
                "+" +
                Fore.RESET +
                "] Multiple glasses have been found, please select one :"
                )

            for index, glasses_address in enumerate(glasses_list):
                print("    {0} - {1}".format(index + 1, glasses_address))

            while not selected_glasses:
                try:
                    selected_glasses = glasses_list[int(input("Selection : ")) - 1]
                except ValueError as parsing_error:
                    print("Error while parsing : please enter a number")
                    print(parsing_error)

        elif len(glasses_list) == 1:
            selected_glasses = glasses_list[0]
            print("[" + Fore.GREEN + "+" + Fore.RESET + "] {0}".format(selected_glasses))

        else:
            print("[" + Fore.RED + "-" + Fore.RESET + "] No glasses have been found")

        return selected_glasses
    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))
Пример #26
0
def scan_for_btle_devices(timeout=30):
    class ScanDelegate(DefaultDelegate):
        def __init__(self):
            DefaultDelegate.__init__(self)

    try:
        if set_lock(timeout + 5):
            scanner = Scanner().withDelegate(ScanDelegate())
            scan_result = scanner.scan(float(timeout), passive=True)
            delete_lock()
            return (scan_result)
        else:
            print('Failed to acquire lock.')
            return
    except BTLEManagementError:
        log_btle_error()
        print('Got BTLEManagementError. Failure counter at {}.'.format(
            r.get('btle-error')))
        return
Пример #27
0
def ble_scan():
	try:
		scanner = Scanner().withDelegate(ScanDelegate())
		devices = scanner.scan(5.0)
		print("-----show devices data: {:d}:".format(len(devices)))
		if devices:   
			devInfoA = [] 
			for dev in devices:
				print("----device:{}".format(dev))
                #print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
                #devInfoA.append((dev.addr, dev.rssi))
				for (adtype, desc, value) in dev.getScanData():
					if desc == "Complete Local Name":
						devInfoA.append((value,dev.addr ,dev.rssi))
						print("%s = %s" % (desc, value))
			print(devInfoA)
		insertScanList(devInfoA)
	except:
		print("Scanner Scan exception")
Пример #28
0
def ble_scan():
    data_tmp = [0] * 7
    scanner = Scanner().withDelegate(ScanDelegate())

    while True:
        devices = scanner.scan(5.0)

        for dev in devices:
            if dev.addr in Target_device_addr:
                print("Device %s (%s), RSSI=%d DB" %
                      (dev.addr, dev.addrType, dev.rssi))
                for (adtype, desc, value) in dev.getScanData():
                    if desc == "Manufacturer":
                        print("   %s = %s" % (desc, value))
                        data_tmp[0] = float(
                            str(int(value[0] + value[1], 16)) + '.' +
                            str(int(value[2] + value[3], 16)))
                        data_tmp[1] = float(
                            str(int(value[4] + value[5], 16)) + '.' +
                            str(int(value[6] + value[7], 16)))
                        data_tmp[2] = int(value[8] + value[9], 16)
                        data_tmp[3] = int(value[10] + value[11], 16)
                        data_tmp[4] = float(
                            str(
                                int(
                                    value[-6] + value[-5] + value[-4] +
                                    value[-3], 16)) + '.' +
                            str(int(value[-2] + value[-1], 16)))
                        data_tmp[5] = time.strftime('%Y-%m-%d %H:%M:%S')
                        if dev.addr == "c3:98:3a:11:5a:38":
                            data_tmp[6] = 102
                        elif dev.addr == "ac:1a:30:f0:49:38":
                            data_tmp[6] = 101
                        elif dev.addr == "20:20:1d:27:d1:38":
                            data_tmp[6] = 103
                        print(data_tmp)
                        data_que.put(data_tmp)
                        data_store = [
                            data_tmp[0], data_tmp[1], data_tmp[2], data_tmp[3],
                            data_tmp[4], data_tmp[5]
                        ]
                        print("data_store in ble_scan: ", data_store)
Пример #29
0
def scan():
    print('Scanning...')
    sys.stdout.flush()

    scanner = Scanner()
    devices = scanner.scan(5)

    switchmates = []
    for dev in devices:
        for (adtype, desc, value) in dev.getScanData():
            is_switchmate = adtype == SERVICES_AD_TYPE and value in SWITCHMATE_SERVICES
            if is_switchmate and dev not in switchmates:
                switchmates.append(dev)

    if len(switchmates):
        print('Found Switchmates:')
        for switchmate in switchmates:
            print(switchmate.addr)
    else:
        print('No Switchmate devices found')
Пример #30
0
class ClientScanner(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

        #print("Creation")
        self.ScannerDelegate = ScannerInterface()

        self.scanner = Scanner().withDelegate(self.ScannerDelegate)

    def add_observateur(self, obs: Observateur):
        #print(self.__dict__)
        self.ScannerDelegate.add_observer(obs)

    def run(self) -> None:
        if self.ScannerDelegate.list_observers:
            while 1:
                self.scanner.scan()
        else:
            print(
                "Erreur il n'y a personne pour récupérer les infos du scanner")
Пример #31
0
    def __init__(self):
        cmd.Cmd.__init__(self)
        threshold = -70
        strikes = 10
        self.sc = Scanner()
        self.scd = MiBand2ScanDelegate(threshold)
        self.sc.withDelegate(self.scd)

        self.mibands = []

        self.scan_thread = threading.Thread(target=scan_miband2,
                                            args=(self.sc, strikes, threshold))
        self.scan_thread.start()

        for i in range(max_connections):
            t = threading.Thread(target=worker, args=(self, ))
            t.daemon = True
            t.start()

        self.prompt = 'MB2S # '
Пример #32
0
 def ble_scan(self):
     try:
         hci_index = self.get_int("hci_index", 0)
         scanner = Scanner(hci_index).withDelegate(
             BLE.ScanDelegate(self.agent))
         self_delay = self.delay()
         scan_delay = round(self_delay / 4.0, 2)
         self.info("Starting BLE Scan on hci[{}] for [{}]s ".format(
             hci_index, scan_delay))
         devices = scanner.scan(scan_delay)
     except BTLEManagementError:
         self.warning(
             "Failed to connect to bluetooth peripheral. (BLE scan requires root)"
         )
     except BTLEDisconnectError:
         self.warning("BLE device disconnected")
     except:
         self.error("Unexpected error:")
         self.error(sys.exc_info()[0])
         raise
Пример #33
0
    def status_update(self):
        scanner = Scanner().withDelegate(ScanDelegate())
        devices = scanner.scan(5.0)
        ret = []

        for name, mac in self.devices.items():
            device = self.searchmac(devices, mac)
            if device is None:
                ret.append(
                    MqttMessage(topic=self.format_topic(name + "/presence"),
                                payload="0"))
            else:
                ret.append(
                    MqttMessage(
                        topic=self.format_topic(name + "/presence/rssi"),
                        payload=device.rssi,
                    ))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + "/presence"),
                                payload="1"))
                _LOGGER.debug("text: %s" % device.getValueText(255))
                bytes_ = bytearray(bytes.fromhex(device.getValueText(255)))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + "/running"),
                                payload=bytes_[5]))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + "/pressure"),
                                payload=bytes_[6]))
                ret.append(
                    MqttMessage(
                        topic=self.format_topic(name + "/time"),
                        payload=bytes_[7] * 60 + bytes_[8],
                    ))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + "/mode"),
                                payload=bytes_[9]))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + "/quadrant"),
                                payload=bytes_[10]))

            yield ret
Пример #34
0
def findWave():
    serial_no = ""
    attempts = 3

    if not bluePyFound:
        return 0

    scanner = Scanner().withDelegate(ScanDelegate())

    try:
        while not serial_no and attempts:
            attempts = attempts - 1
            devices = scanner.scan(2.0)

            for dev in devices:
                ManuData = ""
                ManuDataHex = []
                for (adtype, desc, value) in dev.getScanData():
                    if (desc == "Manufacturer"):
                        ManuData = value

                    if (ManuData == ""):
                        continue

                    for i, j in zip(ManuData[::2], ManuData[1::2]):
                        ManuDataHex.append(int(i + j, 16))

                    #Start decoding the raw Manufacturer data
                    if ((ManuDataHex[0] == 0x34) and (ManuDataHex[1] == 0x03)):
                        serial_no = str(256 * 256 * 256 * ManuDataHex[5] +
                                        256 * 256 * ManuDataHex[4] +
                                        256 * ManuDataHex[3] + ManuDataHex[2])
                        print("Airthings addr %s (%s), RSSI=%d dB, SN=%s\n" %
                              (dev.addr, dev.addrType, dev.rssi, serial_no))
                    else:
                        continue

    except DecodeErrorException:
        pass

    return int(serial_no)
Пример #35
0
    def run(self):
        # debug print
        print("***BLE sniffer***")

        # get BLE Scanner object instance
        scanner = Scanner()
        # get start time for timestamp
        startTime = time.time()

        # clear previous measurements on start
        if os.path.exists(self.recordFile):
            os.remove(self.recordFile)
        os.mknod(self.recordFile)

        while True:
            # scan for 500 ms
            devices = scanner.scan(0.5)

            for dev in devices:
                for (adtype, desc, value) in dev.getScanData():
                    # check adv type and length
                    if adtype != self.manufacturerSpecificData or len(
                            value) != self.packetLength:
                        break

                    # string + little endian
                    tempStr = value[8] + value[9] + value[6] + value[
                        7] + value[4] + value[5] + value[2] + value[3]

                    # string to hex
                    temp = (struct.unpack('!f', bytes.fromhex(tempStr))[0])

                    # get timestamp
                    timestamp = time.time() - startTime

                    # first byte is device ID
                    if (value[0] + value[1]) == 'ab':
                        self.appendMeasurement(timestamp, temp, 'nRF52832')

                    if (value[0] + value[1]) == 'cd':
                        self.appendMeasurement(timestamp, temp, 'nRF52840')
Пример #36
0
    def _findRileyLink(self):
        scanner = Scanner()
        found = None
        self.logger.debug("Scanning for RileyLink")
        retries = 10
        while found 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")
                    found = result.addr
                    try:
                        with open(RILEYLINK_MAC_FILE, "w") as stream:
                            stream.write(result.addr)
                    except IOError:
                        self.logger.warning("Cannot store rileylink mac radio_address for later")
                    break

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

        return found
Пример #37
0
    def scan_devs(self):
        func_name = inspect.stack()[0][3]
	logging.debug('%s start BLE scan', func_name)
        adapter = Scanner(0)
        devices = adapter.scan(10.0)
        logging.debug('%s found %d devices', func_name, len(devices))
        for d in devices:
            logging.debug('%s inspecting device %s', func_name, d.addr)
            for (tag, desc, value) in d.getScanData():
                logging.debug('%s tag=%s desc=%s value=%s',
                    func_name, tag, desc, value)
                if tag == 9 and value in self.supported_devs:
                    logging.debug('%s compatible device @%s', func_name, d.addr)
                    if d.addr not in self.devices:
                        self.devices[d.addr] = d
                        logging.info('%s added device @%s to ble_devices', 
                            func_name, d.addr)
                        self.cons[d.addr] = Peripheral(d.addr, 'random')
                        self.sendDevice(d.addr)
                        logging.info('%s connected to device @%s', func_name, d.addr)
        logging.debug('%s devices=%s', func_name, self.devices)
        logging.debug('%s cons=%s', func_name, self.cons)
        logging.debug('%s done BLE scan', func_name)
Пример #38
0
class BLEHelper(object):
    
    def __init__(self):
        self.scanThread = None
        self.scanner = Scanner().withDelegate(ScanDelegate())
    
    def __scanInThread(self, timeout):
        self.scanThread = threading.Thread(target=self.scanner.scan, args=(timeout,))
        self.scanThread.start()
        return True
        
    def startScan(self, timeout=10):
        if self.scanThread is None:
            return self.__scanInThread(timeout)
        else:
            if self.scanThread.is_alive():
                return False
            else:
                self.scanThread = None
                return self.startScan(timeout)
        
    def stopScan(self):
        self.scanner.stop()
Пример #39
0
 def __init__(self,mac=None,iface=0):
     Scanner.__init__(self,iface)
     self.mac = mac
Пример #40
0
		print(scanentry.getScanData())
		print(scanentry.getValueText(9))
		print(scanentry.getValueText(22))
		

#scanner = Scanner().withDelegate(BTThermometerDelegate("C4:B3:61:94:78:38"))
#while True:
#devices = scanner.scan()


from bluepy.btle import Scanner, DefaultDelegate

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

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr

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)

Пример #41
0
 def __init__(self):
     self.scanThread = None
     self.scanner = Scanner().withDelegate(ScanDelegate())
Пример #42
0
    list_aux = data.split('X')
    list_aux = list_aux[1].split('Y')
    datax = list_aux[0]
    list_aux = list_aux[1].split('Z')
    datay = list_aux[0]
    dataz = list_aux[1]
    return;

###############################################
# Scanning Devices
###############################################
os.system("sudo hciconfig hci0 down")
os.system("sudo hciconfig hci0 up")
print " "
print "Scanning devices..."
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(8.0)

###############################################
# Connecting Devices
###############################################
print " "
print "Connecting to nodes..."
for dev in devices:
    # Creating Bendsaw Peripheral
    if dev.addr == MAC_DIC['BENDSAW']:
        print " "
        print "Device %s (%s) Bendsaw found, connecting..." %(dev.addr,
                                                              dev.addrType)
        bndsw = Peripheral(dev.addr, dev.addrType)
        nodes['bendsaw'] = bndsw
Пример #43
0
    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            pass
            #print ("Discovered device", dev.addr )
            #print(dev)
        elif isNewData:
            pass
            print ("Received new data from", dev.addr)
    def handleNotification(self, cHandle, data):
        # ... perhaps check cHandle
        # ... process 'data'
        pass


print("Scanning for Wallet")
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(5.0)
wallet_address = 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 dev.rssi >  -65 :
                print("Get Wallet address:%s!" % dev.addr)
                wallet_address = dev.addr

if wallet_address == 0:
        print ("No wallet found")
        exit()

p = Peripheral(wallet_address,btle.ADDR_TYPE_PUBLIC)
Пример #44
0
#!/usr/bin/python
from __future__ import print_function

from time import gmtime, strftime, sleep
from bluepy.btle import Scanner, DefaultDelegate, BTLEException
import sys


class ScanDelegate(DefaultDelegate):

    def handleDiscovery(self, dev, isNewDev, isNewData):
        print(strftime("%Y-%m-%d %H:%M:%S", gmtime()), dev.addr, dev.getScanData())
        sys.stdout.flush()

scanner = Scanner().withDelegate(ScanDelegate())

# listen for ADV_IND packages for 10s, then exit
scanner.scan(10.0, passive=True)
Пример #45
0
def main():
    # uuid definition
    targetDevice = ""
    targetUUID   = UUID("08590f7e-db05-467e-8757-72f6f66666d4")
    # targetUUID   = UUID(0x2a2b)
    serviceUUID  = UUID("e20a39f4-73f5-4bc4-a12f-17d1ad666661")

    # scanning for Bluetooth LE device
    # P.S. root permission is needed
    print "scanning started..."
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(5)

    print "\n\nscanning completed...\n found %d device(s)\n" % len(devices)

    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)

        try:
            p = Peripheral(dev.addr, "random")
            ch = p.getCharacteristics(uuid=targetUUID)
            if len(ch) > 0:
                print "the desired target found. the address is", dev.addr
                targetDevice = dev.addr
        except:
            # print "Unexpected error:", sys.exc_info()[0]
            print "Unable to connect"
            print " "
        finally:
            p.disconnect()

    # scanning completed, now continue to connect to device
    if targetDevice == "":
        # the target is not found. end.
        print "no target was found."
    else:
        # the target found, continue to subscribe.
        print "\n\nthe target device is ", targetDevice
        print "now try to subscribe..."

        try:
            # try to get the handle first
            p = Peripheral(targetDevice, "random")
            p.setDelegate(NotificationDelegate())
            # svc = p.getServiceByUUID(serviceUUID)
            ch = p.getCharacteristics(uuid=targetUUID)[0] # svc.getCharacteristics(targetUUID)[0]
            handle = ch.getHandle()
            print handle
            ch.write(struct.pack('<bb', 0x01, 0x00))
            # ch.write(bytes('aa', 'utf-8'))
            # p.writeCharacteristic(handle, struct.pack('<bb', 0x01, 0x00), True)

            print

            # Main loop
            while True:
                if p.waitForNotifications(5):
                    # handleNotification() was called
                    continue

                print "Waiting..."
                # Perhaps do something else here
        # except:
        #     print "Unexpected error:", sys.exc_info()[0]
        finally:
            p.disconnect()
Пример #46
0
#-*- coding: utf-8 -*-
from bluepy.btle import Scanner, DefaultDelegate
from SigObject import sigObject
from log import logger
import signals

class ScanDelegate(DefaultDelegate):
    
    def __init__(self):
        DefaultDelegate.__init__(self)
        
    def handleDiscovery(self, dev, isNewDev, isNewData):
        #logger.debug("%s[%d]" % (dev.addr, dev.rssi))
        sigObject.emit(signals.BLE_INFO_UPDATE, dev.addr, dev.rssi)

if __name__ == "__main__":
    from bluepy.btle import Scanner
    scanner = Scanner().withDelegate(ScanDelegate())
    scanner.scan(4)
Пример #47
0
 def start(self, notify):
     scanner = Scanner()
     scanner.withDelegate(ScanDelegate(scanner, notify))
     scanner.scan(10.0)
Пример #48
0
# General Functions
###############################################
def split_accel_data(data):
    global datax, datay, dataz
    list_aux = data.split('X')
    list_aux = list_aux[1].split('Y')
    datax = list_aux[0]
    list_aux = list_aux[1].split('Z')
    datay = list_aux[0]
    dataz = list_aux[1]
    return;

###############################################
# Scanning Devices
###############################################
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(6.0)

###############################################
# Connecting Devices
###############################################
print " "
print "Connecting to nodes..."
print " "
for dev in devices:
    if dev.addr == BNDSW_MAC_ADDR:
	print "Device %s (%s) Bendsaw found, connecting..." %(dev.addr, dev.addrType)
	bndsw = Peripheral(dev.addr, dev.addrType)
	for (adtype, desc, value) in dev.getScanData():
	    print "    %s = %s" % (desc, value)
	print " "
Пример #49
0
        "device": "TokenCube 1",
        "addr": "dc:00:62:95:62:67",
        "type": "ambient"
    }
}

INFLUX_SERVER = os.environ.get("INFLUX_SERVER", None) or "raspberrypi.local"
INFLUX_DATABASE = os.environ.get("INFLUX_DB", None) or "sensors"
INFLUX_USER = os.environ.get("INFLUX_USER", None) or "root"
INFLUX_PASSWORD = os.environ.get("INFLUX_PASSWORD", None) or "root"

if __name__ == "__main__":
    print "Creating Scanner"
    delegate = DeviceForwardingDelegate()
    delegate.handlers.append(IGrillHandler(device_settings))
    delegate.handlers.append(TokenCubeHandler(device_settings))

    scanner = Scanner()
    scanner.withDelegate(delegate)

    print "Connecting to InfluxDB server"
    persistence = DataPersistence(INFLUX_SERVER, INFLUX_DATABASE, INFLUX_USER, INFLUX_PASSWORD)

    while True:
        print "Scanning..."
        scanner.scan(30)

        print "Persisting..."
        for handler in delegate.handlers:
            handler.persist_stats(persistence)
import struct
import time
from bluepy.btle import UUID, Peripheral
from bluepy.btle import Scanner, DefaultDelegate

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

    def handleNotification(self, cHandle, data):
        print "inside notification"
        print "Heart rate:", ord(data[1]), "Energy=" ,int(binascii.b2a_hex((data[::-1])[0:2]),16) # This script was tested on ubuntu 14.04
                                                                                                  # To solve the endianess problem reverse the
                                                                                                  # string to find exact value

devices = Scanner()                 # Scanner Object
temp=devices.scan(10)               # Start Scan
try:
    for dev in temp:
        if dev.getScanData()[3][2] == "mr. singh":      # Check for the target BLE device name
            if dev.connectable:
                p = Peripheral(dev.addr, "random")
                p.setDelegate(ScanDelegate())           # Create internal Object of scandelegate class to handle the notifications
except (RuntimeError, TypeError, NameError):
    print "Device not found"
    exit(1)
################### Check for the Services and its characteristics #################
print p.getServices()[0]
print p.getServices()[1]
print p.getServices()[2]
Heart_Rate_Measurement = p.getServiceByUUID(0x180D).getCharacteristics()[0]
Пример #51
0
    keepScanning = False
        


if __name__ == '__main__':
    import signal
    log.basicConfig(level=logging.DEBUG)
    log.info('OHHAI')

    for sig in [signal.SIGHUP, 
                signal.SIGUSR1, 
                signal.SIGUSR2,
                signal.SIGTERM, 
                signal.SIGQUIT, 
                signal.SIGINT]:
        signal.signal(sig, sighandler)

    bm = BeepManager()
    bm.thread.start()
    while keepScanning:
        try:
            log.info('Starting scan...')
            scanner = Scanner().withDelegate(ScanDelegate())
            scanner.scan(30.0)
        except Exception as e:
            log.error('while scanning: %s: %s' % (type(e), e))
    bm.shutdown()
    bm.thread.join()
    log.info('KTHXBYE')

Пример #52
0
			count = struct.unpack('H', count_bytes)[0]

			pulse_duration_hex = value[4:12]
			pulse_duration_bytes = binascii.unhexlify(pulse_duration_hex)
			pulse_duration = struct.unpack('L', pulse_duration_bytes)[0]

			battery_voltage_hex = value[12:16]
			battery_voltage_bytes = binascii.unhexlify(battery_voltage_hex)
			battery_voltage = unpack('H', battery_voltage_bytes)[0]			

			if (pulse_duration > 0):
				ticks_per_second = float(1000) / pulse_duration
				watts = int(round(ticks_per_second * joules_per_tick))
	         		watts_message = short_addr + "watts:" + str(watts)
                        	mqtt_client.publish(mqtt_topic, watts_message)

			count_message = short_addr + "count:" + str(count)
			mqtt_client.publish(mqtt_topic, count_message)

			pulse_duration_message = short_addr + "pulseduration:" + str(pulse_duration)
			mqtt_client.publish(mqtt_topic, pulse_duration_message)

			battery_message = short_addr + "battery:" + str(battery_voltage)
			mqtt_client.publish(mqtt_topic, battery_message)

scanner = Scanner().withDelegate(ScanDelegate())
scanner.start(passive=True)
while True:
    print "Still running..."
    scanner.process()