Esempio n. 1
0
        }, {
            'topic': constants.BEACON_CONF['event_topic'],
            'payload': payload
        }]
        publish.multiple(msgs,
                         hostname=constants.MQTT_CON['host'],
                         port=constants.MQTT_CON['port'])

    def enter_event(self):
        logging.info('ENTER_EVENT mac %s', self.beacon_addr)
        self.send_event('ENTER')

    def leave_event(self):
        logging.info('LEAVE_EVENT mac %s', self.beacon_addr)
        self.send_event('LEAVE')


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)s %(message)s',
                        datefmt='%m-%d-%Y %H:%M:%S')

    user = User()
    t = threading.Thread(target=user.check)
    t.start()
    scanner = Scanner().withDelegate(ScanDelegate(user))

    logging.info('Entering main scan loop')
    while True:
        scanner.scan()
Esempio n. 2
0
    def scan_devs(self, timeout=8, scan_type='active', sort='rssi'):
        """LE devices scanning

        scan_type  - Indicate the type of LE scan:active, passive, adv or 
                     features.
        """
        if scan_type == 'adv':
            return

        scanner = Scanner(self.devid).withDelegate(LEDelegate())
        #print("[Debug] timeout =", timeout)

        # scan() 返回的 devs 是 dictionary view。
        if scan_type == 'active':  # Active scan 会在 LL 发送 SCAN_REQ PDU
            logger.warning(
                'Before doing an active scan, make sure you spoof your BD_ADDR.'
            )
            logger.info('LE active scanning on %s with timeout %d sec\n' % \
                (blue('hci%d'%self.devid), timeout))
            devs = scanner.scan(timeout)
        elif scan_type == 'passive':
            logger.info('LE passive scanning on %s with timeout %d sec\n' % \
                (blue('hci%d'%self.devid), timeout))
            devs = scanner.scan(timeout, passive=True)
        else:
            logger.error('Unknown LE scan type')
            return

        if sort == 'rssi':
            devs = list(devs)  # 将 dictionary view 转换为 list
            devs.sort(key=lambda d: d.rssi)

        for dev in devs:
            print('Addr:       ', blue(dev.addr.upper()))
            print('Addr type:  ', blue(dev.addrType))
            print('Connectable:',
                  green('True') if dev.connectable else red('False'))
            print("RSSI:        %d dB" % dev.rssi)
            print("General Access Profile:")
            for (adtype, desc, val) in dev.getScanData():
                # 打印当前 remote LE dev 透露的所有 GAP 数据(AD structure)。
                #
                # 如果 bluepy.scan() 执行的是 active scan,那么这些 GAP 数据
                # 可能同时包含 AdvData 与 ScanRspData。其中 AdvData 由 remote LE
                # dev 主动返回,ScanRspData 由 remote BLE dev 响应 SCAN_REQ 返回。
                #
                # 虽然 LL 分开定义了 Advertising PDUs (ADV_IND, ADV_DIRECT_IND...)
                # 和 Scanning PDUs (SCAN_REQ, SCAN_RSP)。但它们分别包含的 AdvData
                # 与 ScanRspData 到了 HCI 层都被放在了 HCI_LE_Advertising_Report
                # event 中。HCI_LE_Advertising_Report 的 Event_Type 标识了这些数
                # 据具体来源于哪个 LL 层的 PDU。另外 ScanRspData 与 AdvData 的格式
                # 完全相同,都是 GAP 协议标准定义的 AD structure。
                #
                # 在 LL 定义的 Advertising PDUs 中 ADV_DIRECT_IND 一定不会包含
                # AdvData。其余的 ADV_IND,ADV_NONCONN_IND 以及 ADV_SCAN_IND 都
                # 可能包含 AdvData。
                #
                # 另外 getScanData() 返回的 desc 还可以通过 ScanEntry.getDescription()
                # 单独获取;val 还可以通过 ScanEntry.getValueText() 单独获取;
                # adtype 表示当前一条 GAP 数据(AD structure)的类型。
                print('\t' + desc + ': ', end='')
                if adtype == COMPLETE_16_BIT_SERVICE_CLS_UUID_LIST:
                    print()
                    for uuid in val.split(','):
                        if len(uuid) == 36:
                            # 这里拿到的是完整的 128-bit uuid,但我们需要 16-bit uuid。
                            print('\t\t' + blue(uuid[4:8]))
                        else:
                            print('\t\t' + blue(uuid))
                    continue
                elif adtype == COMPLETE_32_BIT_SERVICE_CLS_UUID_LIST:
                    print()
                    for uuid in val.split(','):
                        if len(uuid) == 36:
                            # 这里拿到的是完整的 128-bit uuid,但我们需要 32-bit uuid。
                            print('\t\t' + blue(uuid[0:8]))
                        else:
                            print('\t\t' + blue(uuid))
                    continue
                elif adtype == MANUFACTURER_SPECIFIC_DATA:
                    val = bytes.fromhex(val)
                    if len(val) > 2:
                        print()
                        print(
                            '\t\tCompany ID:', '0x%04x' %
                            int.from_bytes(val[0:2], 'little', signed=False))
                        print('\t\tData:', val[2:])
                    else:
                        print(val)
                    continue
                print(val)
            print("\n")
Esempio n. 3
0
    def connect(self):
        if self.target_address is None:
            sys.stdout.write("Searching for devices....")
            sys.stdout.flush()

            scanner = Scanner(self.port)
            scanner.withDelegate(ScanDelegate())
            nearby_devices = scanner.scan(10)

            if len(nearby_devices) > 0:
                for dev in nearby_devices:
                    #look for a device name that starts with the specified target name
                    for (adtype, desc, value) in dev.getScanData():
                        #one of the data points returned by getScanData is the device's
                        #human-readable name. This is what we want to match against to see
                        #if we have discovered a Sphero device.
                        if value.startswith(self.target_name):
                            self.found_device = True
                            self.target_address = dev.addr
                            break
                        if self.found_device:
                            break

            if self.target_address is not None:
                sys.stdout.write("\nFound Sphero device with address: %s\n" %
                                 (self.target_address))
                sys.stdout.flush()
            else:
                sys.stdout.write("\nNo Sphero devices found.\n")
                sys.stdout.flush()
                sys.exit(1)
        else:
            sys.stdout.write("Connecting to device: " + self.target_address +
                             "...")

        try:
            #Connect to sphero and populate services and characteristics
            self.peripheral = btle.Peripheral(self.target_address,
                                              addrType=btle.ADDR_TYPE_RANDOM)
            sys.stdout.write("Connected!\nFinding services...")
            sys.stdout.flush()
            self.peripheral.getServices()
            self.ble_service = self.peripheral.getServiceByUUID(
                btle.UUID(self.UUIDs['BLE_SVC']))
            self.anti_dos_characteristic = self.ble_service.getCharacteristics(
                self.UUIDs['ANTI_DOS_CHAR'])[0]
            self.robot_control_service = self.peripheral.getServiceByUUID(
                self.UUIDs['BOT_CTRL_SVC'])
            self.wake_characteristic = self.ble_service.getCharacteristics(
                self.UUIDs['WAKE_CHAR'])[0]
            self.tx_power_characteristic = self.ble_service.getCharacteristics(
                self.UUIDs['TX_PWR_CHAR'])[0]
            self.anti_dos_characteristic = self.ble_service.getCharacteristics(
                self.UUIDs['ANTI_DOS_CHAR'])[0]
            self.commands_characteristic = self.robot_control_service.getCharacteristics(
                self.UUIDs['CMD_CHAR'])[0]
            self.response_characteristic = self.robot_control_service.getCharacteristics(
                self.UUIDs['RESP_CHAR'])[0]
            sys.stdout.write("Services found!\nEnabling dev mode...")
            sys.stdout.flush()
            self._enable_dev_mode()
        except btle.BTLEException as error:
            sys.stdout.write(error.strerror)
            sys.stdout.flush()
            time.sleep(5.0)
            sys.exit(1)
        sys.stdout.write("Done.\n")
        sys.stdout.flush()
        return True
            tempOZ = ((ord(data[5]) << 8) + ord(data[4])) / 100

            if tempOZ > 327.67:
                tempOZ = -(655.35 - tempOZ)

            if len(yO) < 600:
                yO.appendleft(tempOZ)
            else:
                yO.pop()
                yO.appendleft(tempOZ)


bt_addresses = ['00:0b:57:51:bd:7e', '00:0b:57:51:c0:a9']
connections = []
connection_threads = []
scanner = Scanner(0)


class ListenerThread(threading.Thread):
    def __init__(self, connection_index):
        threading.Thread.__init__(self)
        self.connection_index = connection_index

    def run(self):
        connection = connections[self.connection_index]
        connection.setDelegate(MyDelegate(self.connection_index))
        connection.writeCharacteristic(79, "\x01\x00")
        connection.writeCharacteristic(82, "\x01\x00")

        while True:
            if connection.waitForNotifications(1):
Esempio n. 5
0
                if(prox == 2):
                    break
        return prox


## Initiate the Local class
Display = Display()
Local = Local()
Local.localClient.subscribe(Local.topicWeight)
## Initialize the Azure class
Azure = Azure()

## Initiate Receiver class
Receiver = Receiver()

scanner = Scanner()

publishData = '{"id":"00815414", "DeviceID":"Receiver_WeighBridge", "EventType":"ENTRY_AUTH", "iIndustry":"true", "Devices":{ "TruckID":"111", "BLEID":"1111", "dynamic1":"11", "dynamic2":"11111" }, "Data":{}}'
while True:
    result = None
    try:
        if(ScanInit):
            rssi, address = Receiver.rangeScanner()
            if(rssi > -45):
                result = Receiver.proximityScanner(address)
                if(result >= 2):
                    Azure.azureClient.publish("devices/" + Azure.device_id + "/messages/events/",
                                               publishData, qos=1)
                    ScanInit = False
    except (KeyboardInterrupt, SystemExit):
        print()
Esempio n. 6
0
def connect(pi):
    from bluepy.btle import Scanner, DefaultDelegate, Peripheral, ADDR_TYPE_RANDOM, UUID, BTLEException
    device = None
    addr = None

    _LOGGER.debug("Starting plejd connection")

    disconnect(pi)

    scanner = Scanner()

    for i in range(1, 10):
        devs = sorted(list(scanner.scan(1)), key=lambda d: d.rssi)[::-1]

        for d in devs:
            for (adtype, desc, value) in d.getScanData():
                if (adtype == 8 and value == "P mesh"):
                    try:
                        dev = Peripheral(d, addrType=ADDR_TYPE_RANDOM)
                        if dev.getServiceByUUID(UUID(PLEJD_SERVICE)):
                            device = dev
                        else:
                            dev.disconnect()

                        break
                    except BTLEException as e:
                        _LOGGER.warning(
                            "failed connecting to device '%s' : '%s'" %
                            (d.addr, e))
            if device:
                break

        if device is None:
            _LOGGER.warning("no device found on iteration %d" % (i))
        else:
            break

    if device == None:
        _LOGGER.warning("Failed to find a Plejd device to connect to")
        return

    _LOGGER.debug("Connected to Plejd device '%s'" % (device.addr))

    pi["device"] = device
    pi["address"] = binascii.a2b_hex(device.addr.replace(':', ''))[::-1]
    pi["handles"] = {}
    pi["handles"]["last_data"] = pi["device"].getCharacteristics(
        uuid=UUID(LAST_DATA_UUID))[0].getHandle()
    pi["handles"]["auth"] = pi["device"].getCharacteristics(
        uuid=UUID(AUTH_UUID))[0].getHandle()
    pi["handles"]["ping"] = pi["device"].getCharacteristics(
        uuid=UUID(PING_UUID))[0].getHandle()
    pi["handles"]["data"] = pi["device"].getCharacteristics(
        uuid=UUID(DATA_UUID))[0].getHandle()

    class PlejdDelegate(DefaultDelegate):
        def handleNotification(self, handle, value):
            if handle == pi["handles"]["last_data"]:
                dec = plejd_enc_dec(pi["key"], pi["address"], value)
                # check if this is a device we care about
                if dec[0] in PLEJD_DEVICES:
                    device = PLEJD_DEVICES[dec[0]]
                else:
                    _LOGGER.debug("no match for device '%02x' (%s)" %
                                  (dec[0], binascii.b2a_hex(dec)))
                    return
                dim = 0xffff
                state = None
                if dec[3:5] == b'\x00\xc8' or dec[3:5] == b'\x00\x98':
                    # 00c8 and 0098 both mean state+dim
                    state = dec[5]
                    dim = int.from_bytes(dec[6:8], 'little')
                elif dec[3:5] == b'\x00\x97':
                    # 0097 is state only
                    state = dec[5]
                else:
                    _LOGGER.debug(
                        "no match for command '%s' (%s)" %
                        (binascii.b2a_hex(dec[3:5]), binascii.b2a_hex(dec)))
                    return
                if (state == 0):
                    state = False
                else:
                    state = True

                device.update_state(state, dim)

    class PlejdNotificationThread(Thread):
        def __init__(self):
            Thread.__init__(self)
            self.stopped = True
            _LOGGER.debug("setting up notification thread")

        def stop(self):
            _LOGGER.debug("stopping notification thread")
            self.stopped = True

        import time

        def run(self):
            from bluepy.btle import BTLEInternalError
            _LOGGER.debug("starting notification thread")
            self.stopped = False
            while True:
                try:
                    pi["device"].waitForNotifications(1)
                except BTLEInternalError as e:
                    _LOGGER.warning("Encountered bluepy internal error: '%s'" %
                                    (e))
                if self.stopped:
                    break

            _LOGGER.debug("exiting notification thread")

    authenticate(pi)
    # the notification handle is last_data + 2
    pi["device"].writeCharacteristic(pi["handles"]["last_data"] + 2,
                                     b'\x02\x00')
    pi["device"].withDelegate(PlejdDelegate())
    pi["thread"] = PlejdNotificationThread()
    pi["thread"].start()

    _LOGGER.debug("all plejd setup completed")
Esempio n. 7
0
def get_current_position():
    MIN = 30
    MAX = 100
    SCALE = 1.3
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(1.9)
    devlist = ['30:ae:a4:9c:e7:c2', '30:ae:a4:97:6c:26', '30:ae:a4:9c:8f:a2']
    global ds_test
    for dev in devices:
        if dev.addr in devlist:
            #   print("ADDR: %s" % (dev.addr))
            data = [[
                time.time(), dev.addr, -1 * dev.rssi, dev.iface, dev.addrType,
                dev.getValueText(1),
                dev.getValueText(10),
                dev.getValueText(255)
            ]]
            #data = [[time.time()]]
            ds_test = ds_test.append(data)

            #print("bucle: %d" % len(ds_test))

    if len(ds_test) == 0:
        return None

#   else:
#       print("bucle: %d" % (len(ds_test[ds_test[2]>=MIN])))
#       print("bucle2: %d" % len(ds_test))
#       return None

    ds_test = ds_test[ds_test[2] >= MIN]

    if debug:
        print("bucle2: %d" % len(ds_test))
        print(len(ds_test[ds_test[0] - (time.time()) < 2000]))
    #ds_test["rssi_norm"]=MAX-ds_test[2]
    ds_test["rssi_norm"] = (ds_test[2] - MIN) / (MAX - MIN)
    #ds_test["rssi_norm"]=1-ds_test["rssi_norm"]

    ds_test["rssi_norm"] = ds_test["rssi_norm"] * SCALE

    ds_test_b3 = ds_test[ds_test[1] == "30:ae:a4:97:6c:26"]  # 3
    ds_test_b1 = ds_test[ds_test[1] == "30:ae:a4:9c:e7:c2"]  # 1
    ds_test_b2 = ds_test[ds_test[1] == "30:ae:a4:9c:8f:a2"]  # 2

    ds_b1 = 0
    ds_b2 = 0
    ds_b3 = 0

    if len(ds_test_b1) > 0 and time.time() - ds_test_b1.iloc[-1][0] < 10:
        ds_b1 = ds_test_b1.iloc[-1]["rssi_norm"]

    if len(ds_test_b2) > 0 and time.time() - ds_test_b2.iloc[-1][0] < 10:
        ds_b2 = ds_test_b2.iloc[-1]["rssi_norm"]

    if len(ds_test_b3) > 0 and time.time() - ds_test_b3.iloc[-1][0] < 10:
        ds_b3 = ds_test_b3.iloc[-1]["rssi_norm"]

    print("Beacon 1:  %s" % (ds_b1))
    print("Beacon 2:  %s" % (ds_b2))
    print("Beacon 3:  %s" % (ds_b3))
    if debug:
        print("Summary:")
        print("#########")
        print("len ds_test %d" % (len(ds_test)))
        print(ds_b1)
        print(ds_b2)
        print(ds_b3)
        print("#########")
        print("Position 1:  %s" % (ds_b1))
        print("Position 2:  %s" % (ds_b2))
        print("Position 3:  %s" % (ds_b3))

    point = returnpoint(0, 0, ds_b1, 0, 1, ds_b2, 1, 0.5, ds_b3)

    if point == None:
        point = Point(0, 0)

    data = [[
        time.time() * 1000,
        str(point.x),
        str(point.y), 0, 0, ds_b1, 0, 1, ds_b2, 1, 0.5, ds_b3
    ]]
    temp = pd.DataFrame(data)
    temp.to_csv('/home/pepo/Documents/nissan_code/Loc_csv.csv',
                mode='a',
                header=False)

    return point
Esempio n. 8
0
 def scan(self, timeout=10.0):
     delegate = _ScanDelegate(self._callback)
     scanner = Scanner(self._interface).withDelegate(delegate)
     devices = list(filter(_DEVICE_FILTER, scanner.scan(float(timeout))))
     return devices
Esempio n. 9
0

def hex2int(_HEX):
    _BIN = bytes.fromhex(_HEX)
    _Rev = _BIN[::-1]
    _HEX = _Rev.hex()
    return int(_HEX, 16)


# Fill list with used sensors
registereddevices = ['4008DF']

knownddevices = []

while True:
    scan = Scanner(0)
    devs = scan.scan(10.0)

    for device in devs:
        if device.addr in knownddevices:

            for (Code, desc, value) in device.getScanData():
                # Check if string is indeed 36 characters long
                count = len(value)
                if count == 36:

                    # Check if mac adress is in string
                    mac = (device.addr.replace(':', ''))
                    m = re.search('/*{0}'.format(mac), value)

                    if m:
Esempio n. 10
0
def scan(timeout=None, mac_address=None):
    scanner = Scanner()
    return get_switchmates(scanner.scan(timeout), mac_address)
Esempio n. 11
0
def scanDevices():
	class ScanDelegate(DefaultDelegate):
		def __init__(self):
			DefaultDelegate.__init__(self)

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

	for dev in devices:
		# getScanData récupère les données adtype, desc et value (qui sont des tuples)
		#creation de la variable dictionnaire pour les adtype et pour les temperatures
		adtype8 = ""
		adtype22 = ""
		dicoTemperature = {}

		for (adtype, value) in dev.getScanData():


			if adtype == 8:
				adtype8 = value
			if adtype == 22:
				adtype22 = value

		if len(adtype22) == 38 and adtype22[4:10] == "113901" and adtype22[32:39] == "000000" :
			if 11000000 < int(adtype22[12:20]) < 12000000:
				# save l'index correspondant au numéro d'identification dans var valeurId
				valeurId = adtype22[12:20]
				# save l'index correspondant à la valeur batterie dans var valeurBatterieHexa
				valeurBatterieHexa = adtype22[20:22]
				# save l'index correspondant à la valeur température dans var valeurtempHexa
				valeurTempHexa = adtype22[24:28]

				# convert hexa to decimal (nomVar_D, base16)
				# On convertit l'hexa de la batterie en decimale
				valeurBatterie = int(valeurBatterieHexa, 16)

				# On convertit l'hexa de la temperature en decimale
				valeurTemp = int(valeurTempHexa, 16)

				#On deplace la décimale vers la gauche de 2
				temperature = valeurTemp * (1/100)

				# print pour voir ce qui est renvoyé
				print(time.strftime('%d/%m/%Y - %H:%M:%S'))
				print(adtype8)
				print(valeurId)
				print("{0:.2f}".format(temperature))
				print(valeurBatterie)


				# vérifie la température avec le seuil :
				# si c'est en dehors du seuil
				if valeurTemp < 2400 or valeurTemp > 3000 :
					# vérifie le capteur est deja dans le dictionnaire dicoTemperature
					if adtype8 not in dicoTemperature :
						# si le capteur n'est pas dedans, il ajoute le capteur et sa temp dedans puis envoi le mail messageKO de danger
						dicoTemperature.update({adtype8: valeurTemp})
						envoiMail(adtype8, valeurId, temperature, valeurBatterie, bool(True))

						# Message qui s'affiche si le mail a été envoyé avec succés
						print ("Enregistrement des températures pour les capteurs. Mail envoyé avec succés a %s" % (msg['To']))

				# si c'est compris dans le seuil
				else :
					# vérifie si capteur existant dans dicoTemperature
					if adtype8 in dicoTemperature :
						# si capteur est déjà existant, supprime ses données du dico et envoie un mail messageOK de rétablissement
						del dicoTemperature[adtype8]
						envoiMail(adtype8, valeurId, temperature, valeurBatterie, bool(False))


			else :
				print("probleme if 11000000 >< 12000000")

		else :
			print("probleme if len(adtype22)")
Esempio n. 12
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()
Esempio n. 13
0
 def __init__(self):
     self.logger = logging.getLogger()
     self.scanner = Scanner(iface=0)
Esempio n. 14
0
 def __init__(self):
     self._scanner = Scanner()
     self._peripheral = Peripheral()
     self._desk = None
     self.config = Config()
Esempio n. 15
0
from bluepy.btle import Scanner, DefaultDelegate
from miband2 import MiBand2, ActivityDelegate

print "Scanning for nearby MiBands2..."
sc = Scanner()
devs = sc.scan(5)

print "Found {0} devices! Initializing...".format(len(devs)) 
mibands = []
for d in devs:
    mb = MiBand2(d)
    mibands += [mb]
    mb.initialize()
    mb.disconnect()
Esempio n. 16
0
def scanForDevices():
    scanner = Scanner().withDelegate(DefaultDelegate())  #ScanDelegate())
    devices = scanner.scan(4.0)
    return devices
Esempio n. 17
0
        # Scan Response
        if isNewData:
            print "Received more data", dev.addr, dev.getScanData()

    def handleNotification(self, cHandle, data):
        # Only print the value when the handle is 40 (the battery characteristic)
        if cHandle == 40:
            buttonPressed = struct.unpack('B', data)[0]
            print buttonPressed
            button_publish(buttonPressed, hexi_addr)


handler = BTEventHandler()

# Create a scanner with the handler as delegate
scanner = Scanner().withDelegate(handler)

# Start scanning. While scanning, handleDiscovery will be called whenever a new device or new data is found
devs = scanner.scan(10.0)

# Get HEXIWEAR's address
hexi_addr = [dev for dev in devs
             if dev.getValueText(0x8) == 'HEXIWEAR'][0].addr
# hexi_addr = '00:2A:40:08:00:10'

# Create a Peripheral object with the delegate
hexi = Peripheral().withDelegate(handler)

# Connect to Hexiwear
hexi.connect(hexi_addr)
Esempio n. 18
0
def sc():
    scne = Scanner()
    devices = scne.scan(0.5)
    return devices
Esempio n. 19
0
 def __init__(self):
     self.scanner = Scanner().withDelegate(ScanDelegate())
Esempio n. 20
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Setup SPIN remote(s)."""

    from bluepy.btle import BTLEException, DefaultDelegate, Peripheral, Scanner

    bl_dev = config.get(ATTR_DEVICE, DEFAULT_DEVICE)
    scan_interval = config.get(ATTR_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
    scan_timeout = config.get(ATTR_SCAN_TIMEOUT, DEFAULT_SCAN_TIMEOUT)
    checking_devices = False
    connected_to_device = False
    homeassistant_stopped = False
    known_device_adresses = []
    spins = {}
    entities = {}

    # Would be a nice moment to check if bl_dev is even valid.

    class NotificationDelegate(DefaultDelegate):
        """
        If a notification is received, it will be handled by the handleNotification def in here
        """
        def __init__(self, hass, spin):
            DefaultDelegate.__init__(self)
            self.hass = hass
            self.spin = spin

        def handleNotification(self, cHandle, data):
            global ACTION_TO_STRING

            if cHandle == 0x30:  # Action
                self.spin['entity'].action_notification(
                    ACTION_TO_STRING[ord(data)])
            elif cHandle == 0x3c:  # Profile change
                self.spin['entity'].profile_update(data[0])

    @asyncio.coroutine
    def start_receiving_notifications(hass, device, peripheral):
        """Loop to receive notifications"""
        nonlocal checking_devices
        nonlocal connected_to_device
        nonlocal homeassistant_stopped
        nonlocal spins

        while not homeassistant_stopped:
            try:
                hasNotification = yield from hass.loop.run_in_executor(
                    None, peripheral.waitForNotifications, 1.0)
            except (BTLEException, AttributeError) as error:
                _LOGGER.warning(error)
                checking_devices = False
                connected_to_device = False

            if not connected_to_device:
                spins[device.addr]['entity'].is_connected(False)
                break

    @asyncio.coroutine
    def async_handle_spin(device, peripheral=None):
        """Prepare SPIN remote to be used by HASS"""
        nonlocal connected_to_device
        nonlocal spins
        global COMMAND_CHARACTERISTIC_UUID
        global ACTION_CHARACTERISTIC_UUID
        global PROFILE_ID_CHARACTERISTIC_UUID
        global UUID_CLIENT_CHARACTERISTIC_CONFIG

        if not peripheral:
            try:
                peripheral = yield from hass.loop.run_in_executor(
                    None, Peripheral, device)
                spins[device.addr]['device'] = device
                spins[device.addr]['peripheral'] = peripheral
                spins[device.addr]['entity'].is_connected(True)
            except BTLEException as error:
                _LOGGER.warning(error)

        if peripheral:
            connected_to_device = True
            services = yield from hass.loop.run_in_executor(
                None, peripheral.getServices)

            for service in services:
                if service.uuid == SPIN_SERVICE_UUID:
                    actionCharacteristic = service.getCharacteristics(
                        ACTION_CHARACTERISTIC_UUID)
                    profile_idCharacteristic = service.getCharacteristics(
                        PROFILE_ID_CHARACTERISTIC_UUID)
                    commandCharacteristic = service.getCharacteristics(
                        COMMAND_CHARACTERISTIC_UUID)

                    _LOGGER.info("Turning notifications on")
                    if actionCharacteristic:
                        descriptors = actionCharacteristic[0].getDescriptors(
                            UUID_CLIENT_CHARACTERISTIC_CONFIG)
                        descriptors[0].write(struct.pack('<bb', 0x01, 0x00),
                                             True)

                    if profile_idCharacteristic:
                        profile_id = profile_idCharacteristic[0].read()
                        descriptors = profile_idCharacteristic[
                            0].getDescriptors(
                                UUID_CLIENT_CHARACTERISTIC_CONFIG)
                        descriptors[0].write(struct.pack('<bb', 0x01, 0x00),
                                             True)
                        spins[device.addr]['entity'].profile_update(
                            profile_id[0])

                    if commandCharacteristic:
                        commandCharacteristic[0].write(
                            struct.pack('<bb', 0x08, 0x01), True)

                    peripheral.withDelegate(
                        NotificationDelegate(hass, spins[device.addr]))
                    hass.async_add_job(start_receiving_notifications, hass,
                                       device, peripheral)

    @asyncio.coroutine
    def async_new_device_found(device):
        """Check if the newly found BLE device is a SPIN"""
        nonlocal checking_devices
        nonlocal connected_to_device
        nonlocal known_device_adresses
        nonlocal spins
        nonlocal entities
        global DISCOVERY_UUID
        global SPIN_SERVICE_UUID
        global COMMAND_CHARACTERISTIC_UUID

        _LOGGER.info("Checking " + device.addr)

        checking_devices = True

        try:
            peripheral = yield from hass.loop.run_in_executor(
                None, Peripheral, device)
            services = yield from hass.loop.run_in_executor(
                None, peripheral.getServices)

            if not device.addr in spins:
                # Walk through the list of services to see if one of them matches the DISCOVERY_UUID
                for service in services:
                    if service.uuid == DISCOVERY_UUID:
                        sdc1 = SDC1('spin_' + str(len(spins) + 1), 'connected',
                                    device.addr)
                        spins[device.addr] = {
                            'device': device,
                            'peripheral': peripheral,
                            'entity': sdc1
                        }
                        entities[DOMAIN + '.' + sdc1.name] = sdc1
                        connected_to_device = True
                        yield from async_add_devices([sdc1])
                        _LOGGER.info("Connected to BLE device " + device.addr)

            known_device_adresses.append(device.addr)

            if connected_to_device == False:
                peripheral.disconnect()
            else:
                yield from async_handle_spin(device, peripheral)

        except BTLEException as error:
            _LOGGER.warning(error)
            checking_devices = False
            connected_to_device = False

    @asyncio.coroutine
    def async_on_time_interval(now: dt_util.dt.datetime):
        """Start scanning for BLE devices"""
        nonlocal scan_timeout
        nonlocal known_device_adresses
        nonlocal checking_devices
        nonlocal connected_to_device
        devices = []

        if not checking_devices and not connected_to_device:
            checking_devices = True
            _LOGGER.info("Scanning for BLE devices for " + str(scan_timeout) +
                         " seconds")

            try:
                devices = yield from hass.loop.run_in_executor(
                    None, scanner.scan, scan_timeout)
            except BTLEException as error:
                _LOGGER.warning(error)

            _LOGGER.info("Found " + str(len(devices)) + " BLE devices")
            for device in devices:
                if not device.addr in known_device_adresses:
                    yield from async_new_device_found(device)
                elif device.addr in spins:
                    _LOGGER.info("SPIN found, reconnecting...")
                    yield from async_handle_spin(device)
            checking_devices = False

    scanner = Scanner(bl_dev)

    # Because we sometimes get into trouble if we start searching to early; we'll start once Home Assistant is ready
    @asyncio.coroutine
    def async_on_homeassistant_start(event):
        """Once Home Assistant is started, we'll scan every 30 seconds or so"""
        nonlocal scan_interval
        interval = timedelta(seconds=scan_interval)
        remove_on_time_interval = async_track_time_interval(
            hass, async_on_time_interval, interval)
        hass.async_add_job(async_on_time_interval, None)

    @asyncio.coroutine
    def async_on_homeassistant_stop(event):
        """Once Home Assistant stops, prevent further futures from being created"""
        nonlocal homeassistant_stopped
        homeassistant_stopped = True

    # Add listeners:
    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START,
                               async_on_homeassistant_start)
    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                               async_on_homeassistant_stop)

    @asyncio.coroutine
    def async_handle_profile_service(call):
        """Handle profile service calls"""
        nonlocal spins
        profileRegex = r"profile_(\d+)"
        profile = call.data.get(ATTR_PROFILE,
                                DEFAULT_PROFILE)  # Default to current profile?
        match = re.search(profileRegex, profile)
        entity_ids = call.data.get('entity_id')

        if match:
            peripheral = spins[entities[entity_ids[0]].address]['peripheral']
            services = yield from hass.loop.run_in_executor(
                None, peripheral.getServices)
            for service in services:
                if service.uuid == SPIN_SERVICE_UUID:
                    profile_idCharacteristic = service.getCharacteristics(
                        PROFILE_ID_CHARACTERISTIC_UUID)
                    if profile_idCharacteristic:
                        profile_idCharacteristic[0].write(
                            struct.pack('<b', int(match.group(1))), True)
                        spins[entities[
                            entity_ids[0]].address]['entity'].profile_update(
                                int(match.group(1)))

    @asyncio.coroutine
    def async_handle_color_service(call):
        """Handle LED color service calls"""
        nonlocal spins
        nonlocal entities
        red, green, blue = call.data.get('rgb_color', [0, 0, 0])
        entity_ids = call.data.get('entity_id')

        peripheral = spins[entities[entity_ids[0]].address]['peripheral']
        services = yield from hass.loop.run_in_executor(
            None, peripheral.getServices)
        for service in services:
            if service.uuid == SPIN_SERVICE_UUID:
                commandCharacteristic = service.getCharacteristics(
                    COMMAND_CHARACTERISTIC_UUID)
                if commandCharacteristic:
                    if red + green + blue < 1:
                        commandCharacteristic[0].write(struct.pack(
                            '<b', 0x07), True)  # Remove forced LED color
                    else:
                        commandCharacteristic[0].write(
                            struct.pack('<bBBB', 0x09, red, green, blue), True)

    hass.services.async_register(DOMAIN, 'profile',
                                 async_handle_profile_service)
    hass.services.async_register(DOMAIN, 'rgb_color',
                                 async_handle_color_service)

    return True
Esempio n. 21
0
def init_scanner():
    scanner = Scanner()
    scanner.clear()
    scanner.start()
    return scanner
Esempio n. 22
0
def scan_and_connect(is_first=True):
    global SCAN_TIME
    global TARGET_MANUFA_UUID
    global TARGET_DEVICE_NAME
    global gTargetDevice
    global gSocketClient
    #
    # scanning for a while
    #
    scanner = Scanner().withDelegate(ScanDelegate())
    print("+--- BLE device scan %sstarted..." % ('re' if not is_first else ''))
    devices = scanner.scan(SCAN_TIME)
    print("\n+--- BLE device scan completed... [%d] devices are scanned" %
          gScannedCount)
    #
    # check to match BOSCH SCD device identifiers
    #
    for dev in devices:
        matching_count = 0
        for (adtype, desc, value) in dev.getScanData():
            if adtype == 255 and TARGET_MANUFA_UUID in value:
                matching_count += 1
                print("\tfound target (AD Type=%d) '%s' is '%s'" %
                      (adtype, desc, value))
            if adtype == 9 and TARGET_DEVICE_NAME in value:
                matching_count += 1
                print("\tfound target (AD Type=%d) '%s' is '%s'" %
                      (adtype, desc, value))
            if matching_count >= 2:
                print("\tfound BOSCH SCD device!")
                print("+--- device address [%s], type=[%s], RSSI=[%d]dB" %
                      (dev.addr, dev.addrType, dev.rssi))
                gTargetDevice = dev
                break
        if gTargetDevice != None:
            break
    #
    # if none found then exiting
    #
    if gTargetDevice == None:
        print("\tno matching device found... Exiting...")
        gSocketClient.close()
        sys.exit(1)
    #
    # connect
    #
    print("+--- connecting [%s], type=[%s]" %
          (gTargetDevice.addr, gTargetDevice.addrType))
    p = None
    retry = 0
    while p == None:
        try:
            p = Peripheral(gTargetDevice.addr, gTargetDevice.addrType)
        except:
            print(
                "\tBLE device connection error occured... retry after 3 sec..."
            )
            retry += 1
            if retry > 3:
                print("\tBLE device connection error occured... exiting...")
                gSocketClient.close()
                sys.exit(-1)
            time.sleep(3)
    #
    # should increase MTU
    #
    p.setMTU(SCD_MAX_MTU)
    return p
Esempio n. 23
0
def ScanNetwork():
    global rank, iterval_for_scan, interval_for_sending, macAddr


    
    subprocess.call("sudo hciconfig hci0 piscan",shell=True);

    interval = random.uniform(iterval_for_scan,iterval_for_scan_random)

    with open("clog.txt","a") as input_file:
        input_file.write(str(datetime.datetime.now())+ "|"+"start scan" + '\n')
        input_file.close()
        
    scanner = Scanner()#.withDelegate(ScanDelegate()) 
    devices = scanner.scan(interval) # 0 = loop
    
    with open("clog.txt","a") as input_file:
        input_file.write(str(datetime.datetime.now())+ "|"+"end scan" + '\n')
        input_file.close()
        
###############################################################
##  rerank first
    if (rank != 0 ): # if not the server, rerank
        print "reranking..."
        rank = -1
        for dev in devices: 
            dict = {}
            for (adtype, desc, value) in dev.getScanData(): 
                dict[adtype] = value

            # handle the flag == 88
            if (dict.has_key(1) and dict[1] == '88'):
               
        
###############################################################
                # handle type = 0xc1
                if (dict.has_key(0xc1)):
                    data = dict[0xc1]
                    print "recv data [0xC1]: ", data
                    # parse cmd
                    cmd = data[0:2]
                    data = data[2:]
                    print "cmd: ", cmd, ":",data
###############################################################
                    if (cmd == '03'):
                        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)

                        for key in dict:        
                            print "  msg %d = %s" % (key, dict[key])
                            
                        handle_cmd_03(data)
                    
###############################################################
## other task:       
    for dev in devices: 
        dict = {}
        for (adtype, desc, value) in dev.getScanData(): 
            dict[adtype] = value

        # handle the flag == 88
        if (dict.has_key(1) and dict[1] == '88'):
            
###############################################################
            # handle type = 0xc1
            if (dict.has_key(0xc1)):
                data = dict[0xc1]
                print "recv data [0xC1]: ", data
                # parse cmd
                cmd = data[0:2]
                data = data[2:]
                print "cmd: ", cmd, ":",data
###############################################################
                # cmd 01: upload to server
                if (cmd == '01'):
                    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)

                    for key in dict:        
                        print "  msg %d = %s" % (key, dict[key])
                        
                    handle_cmd_01(data)
                # cmd 02: download to client
                if (cmd == '02'):
                    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)

                    for key in dict:        
                        print "  msg %d = %s" % (key, dict[key])
                        
                    handle_cmd_02(data)
Esempio n. 24
0
def scanLE(n, devices1):
    scanner = Scanner(n)
    devices = scanner.scan(1)
    for dev in devices:
        devices1.append(str(dev.addr + "," + str(dev.rssi) + "," + str(n)))
Esempio n. 25
0
    def handle_request(self, method, params):
        """Handle requests from Scratch"""
        if self.delegate:
            # Do not allow notification during request handling to avoid
            # websocket server errors
            self.delegate.restart_notification_event.clear()

        logger.debug("handle request to BLE device")
        logger.debug(method)
        if len(params) > 0:
            logger.debug(params)

        res = {"jsonrpc": "2.0"}
        err_msg = None

        if self.status == self.INITIAL and method == 'discover':
            if not bluepy_helper_cap.is_set():
                logger.error("Capability is not set to bluepy helper.")
                logger.error("Run bluepy_helper_cap(.py).")
                logger.error("e.g. $ bluepy_helper_cap")
                logger.error("e.g. $ sudo bluepy_helper_cap.py")
                sys.exit(1)
            found_ifaces = 0
            for i in range(self.MAX_SCANNER_IF):
                scanner = Scanner(iface=i)
                try:
                    devices = scanner.scan(10.0)
                    for dev in devices:
                        if self.matches(dev, params['filters']):
                            self.found_devices.append(dev)
                    found_ifaces += 1
                    logger.debug(f"BLE device found with iface #{i}")
                except BTLEManagementError as e:
                    logger.debug(f"BLE iface #{i}: {e}")

            if found_ifaces == 0:
                err_msg = "Can not scan BLE devices. Check BLE controller."
                logger.error(err_msg)
                res["error"] = {"message": err_msg}
                self.status = self.DONE

            if len(self.found_devices) == 0 and not err_msg:
                err_msg = (f"No BLE device found: {params['filters']}. "
                           "Check BLE device.")
                res["error"] = {"message": err_msg}
                logger.error(err_msg)
                self.status = self.DONE
            else:
                res["result"] = None
                self.status = self.DISCOVERY
                self.ble_thread = self.BLEThread(self)
                self.ble_thread.start()

        elif self.status == self.DISCOVERY and method == 'connect':
            logger.debug("connecting to the BLE device")
            self.device = self.found_devices[params['peripheralId']]
            self.deviceName = self.device.getValueText(
                0x9) or self.device.getValueText(0x8)
            try:
                self.perip = Peripheral(self.device)
                logger.info(
                    f"connected to the BLE peripheral: {self.deviceName}")
            except BTLEDisconnectError as e:
                logger.error(
                    f"failed to connect to the BLE device \"{self.deviceName}\": {e}"
                )
                self.status = self.DONE

            if self.perip:
                res["result"] = None
                self.status = self.CONNECTED
                self.delegate = self.BLEDelegate(self)
                self.perip.withDelegate(self.delegate)
                self._cache_characteristics()
            else:
                err_msg = f"BLE connect failed: {self.deviceName}"
                res["error"] = {"message": err_msg}
                self.status = self.DONE

        elif self.status == self.CONNECTED and method == 'read':
            logger.debug("handle read request")
            service_id = params['serviceId']
            chara_id = params['characteristicId']
            c = self._get_characteristic(chara_id)
            if not c or c.uuid != UUID(chara_id):
                logger.error(f"Failed to get characteristic {chara_id}")
                self.status = self.DONE
            else:
                with self.lock:
                    b = c.read()
                message = base64.standard_b64encode(b).decode('ascii')
                res['result'] = {'message': message, 'encode': 'base64'}
            if params.get('startNotifications') == True:
                self.startNotifications(service_id, chara_id)

        elif self.status == self.CONNECTED and method == 'startNotifications':
            logger.debug("handle startNotifications request")
            service_id = params['serviceId']
            chara_id = params['characteristicId']
            self.startNotifications(service_id, chara_id)

        elif self.status == self.CONNECTED and method == 'stopNotifications':
            logger.debug("handle stopNotifications request")
            service_id = params['serviceId']
            chara_id = params['characteristicId']
            self.stopNotifications(service_id, chara_id)

        elif self.status == self.CONNECTED and method == 'write':
            logger.debug("handle write request")
            service_id = params['serviceId']
            chara_id = params['characteristicId']
            c = self._get_characteristic_cached(chara_id)
            if not c or c.uuid != UUID(chara_id):
                logger.error(f"Failed to get characteristic {chara_id}")
                self.status = self.DONE
            else:
                if params['encoding'] != 'base64':
                    logger.error(
                        "encoding other than base 64 is not "
                        "yet supported: ", params['encoding'])
                msg_bstr = params['message'].encode('ascii')
                data = base64.standard_b64decode(msg_bstr)
                logger.debug("getting lock for c.write()")
                with self.lock:
                    c.write(data)
                logger.debug("released lock for c.write()")
                res['result'] = len(data)

        logger.debug(res)
        return res
Esempio n. 26
0
from bluepy.btle import Scanner
""" Scans for available devices. """
scan = Scanner()
sec = 5
print("Scanning for %s seconds" % sec)
devs = scan.scan(sec)
print("Scooters found:")
for dev in devs:
    localname = dev.getValueText(9)
    if localname and localname.startswith("MIScooter"):
        print("  %s, addr=%s, rssi=%d" % (localname, dev.addr, dev.rssi))
Esempio n. 27
0
def scanForNistSensors():

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

    if foundNistSensor == 0:
        print "Didn't find any nist sensors..."
        return False

    p = Peripheral(esp32Address)
    p.setMTU(500)

    #svcList = p.getServices()
    #print "Handle   UUID                                Properties"
    #print "-------------------------------------------------------"
    #for svc in svcList:
    #      print (str(svc.uuid))
    
    #chList = p.getCharacteristics()
    #print "Handle   UUID                                Properties"
    #print "-------------------------------------------------------"
    #for ch in chList:
    #         print ("  0x"+ format(ch.getHandle(),'02X')  +"   "+str(ch.uuid) +" " + ch.propertiesToString())

    nist_service_uuid = UUID("0000ffe0-0000-1000-8000-00805f9b34fb")
    nist_characteristic_uuid = UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8")

    nistService = p.getServiceByUUID(nist_service_uuid)
    #nistCharacteristic = p.getCharacteristics(nist_characteristic_uuid)[0]
    nistCharacteristic = nistService.getCharacteristics("beb5483e-36e1-4688-b7f5-ea07361b26a8")[0]

    #readBytes = bytes(p.readCharacteristic(0x2A))
    #readBytes = bytes(nistCharacteristic.read())

    #print binascii.hexlify(readBytes)

    #with open('/home/pi/Desktop/esp32-ndn-ble/src/readBytes.txt', 'a') as the_file:
    #      the_file.seek(0)
    #      the_file.truncate()
    #      the_file.write(binascii.hexlify(readBytes))

    #TlvData = Blob(readBytes)

    #data = Data()
    #data.wireDecode(TlvData)

    # Use a hard-wired secret for testing. In a real application the signer
    # ensures that the verifier knows the shared key and its keyName.
    key = Blob(bytearray([
       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
    ]))

    #if KeyChain.verifyDataWithHmacWithSha256(data, key):
    #  dump("Hard-coded data signature verification: VERIFIED")
    #else:
    #  dump("Hard-coded data signature verification: FAILED")

    freshData = Data(Name("/netInfo"))
    signature = HmacWithSha256Signature()
    signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
    signature.getKeyLocator().setKeyName(Name("key1"))
    freshData.setSignature(signature)
    freshData.setContent("EdwardPi\n11111111\n192.168.4.1\n")
    dump("Signing fresh data packet", freshData.getName().toUri())
    KeyChain.signWithHmacWithSha256(freshData, key)

    if KeyChain.verifyDataWithHmacWithSha256(freshData, key):
      dump("Freshly-signed data signature verification: VERIFIED")
    else:
      dump("Freshly-signed data signature verification: FAILED")

    bytesSend = freshData.wireEncode()

    print binascii.hexlify(bytes(bytesSend))

    try:
        nistCharacteristic.write(bytes(bytesSend), True)
    except:
        print "Exception when trying to write to BLE characteristic."
Esempio n. 28
0
def SCD_scan_and_connect(is_first=True):
    global gTargetDevice
    #
    # scanning for a while
    #
    print("SCD--> BLE device scan %sstarted..." %
          ('re' if not is_first else ''),
          flush=True)

    tm = tm_s = time.time()
    while tm_s - tm < RESCAN_PERIOD:
        scanner = Scanner().withDelegate(ScanDelegate())
        devices = scanner.scan(SCAN_TIME)
        print(
            "\nSCD--> BLE device scan completed... [%d] devices are scanned" %
            gScannedCount,
            flush=True)
        #
        # check to match BOSCH SCD device identifiers
        #
        for dev in devices:
            matching_count = 0
            for (adtype, desc, value) in dev.getScanData():
                if adtype == 255 and TARGET_MANUFA_UUID in value:
                    matching_count += 1
                    print("SCD--> => found target (AD Type=%d) '%s' is '%s'" %
                          (adtype, desc, value),
                          flush=True)
                if adtype == 9 and TARGET_DEVICE_NAME in value:
                    matching_count += 1
                    print("SCD--> => found target (AD Type=%d) '%s' is '%s'" %
                          (adtype, desc, value),
                          flush=True)
                if matching_count >= 2:
                    print("SCD--> => found BOSCH SCD device!")
                    print(
                        "SCD--> device address [%s], type=[%s], RSSI=[%d]dB" %
                        (dev.addr, dev.addrType, dev.rssi),
                        flush=True)
                    gTargetDevice = dev
                    break
            if gTargetDevice != None:
                break
        #
        # if none found then exiting
        #
        if gTargetDevice == None:
            tm = time.time()
            print("SCD--> no matching device found at [%s]... retry after %d sec..." \
                  % (datetime.datetime.fromtimestamp(tm).strftime('%Y-%m-%d %H:%M:%S'), RESCAN_INTERVAL), flush=True )
            if tm_s - tm >= RESCAN_PERIOD:
                print("SCD--> no matching device found... exiting...",
                      flush=True)
                sys.exit(-1)
            time.sleep(RESCAN_INTERVAL)
        else:
            break
    #
    # connect
    #
    print("SCD--> connecting [%s], type=[%s]" %
          (gTargetDevice.addr, gTargetDevice.addrType),
          flush=True)
    p = None
    retry = 0
    while p == None:
        try:
            p = Peripheral(gTargetDevice.addr, gTargetDevice.addrType)
        except:
            retry += 1
            print(
                "SCD--> => BLE device connection error occured [%d] time(s)... retry after 10 sec..."
                % retry,
                flush=True)
            if retry > 30:
                print(
                    "SCD--> => BLE device connection error occured... exiting...",
                    flush=True)
                sys.exit(-1)
            time.sleep(10)
    #
    # should increase MTU##
    #
    p.setMTU(SCD_MAX_MTU)
    #
    return p
Esempio n. 29
0
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr """


"""   
def imprime(rssi):
    print '\x1b[2J\x1b[1;1H'
    print '\n RSSI:',rssi,'dbm' """

RSSI = []
sizeRSSI = 0
start_time = datetime.now()
while sizeRSSI < 600:

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

    for dev in devices:
        if (dev.addr == "7c:01:0a:77:3c:b9"):
            #imprime(dev.rssi)
            RSSI.append(dev.rssi)
            sizeRSSI += 1
        #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)

end_time = datetime.now()
print '\n Experiment time: {} \n'.format(end_time - start_time)
print ' RSSI:', RSSI
print "\n Dados Coletados: ", sizeRSSI
Esempio n. 30
0
def main():
    sc = Scanner()
    scd = MiBand2ScanDelegate()
    sc.withDelegate(scd)

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

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

    while True:
        try:
            s = raw_input('> ')
        except:
            break

        try:
            command = s.strip().lower()
            if command == "exit":
                scan_thread.do_scan = False
                scan_thread.join()
                print ("Disconnecting from %s devices" % len(connected_devices.values()))
                for con in connected_devices.values():
                    con.disconnect()
                print("Saving changes to Registered Devices storage")
                save_registered(registered_devices, devices_last_sync)
                break

            elif command == "save":
                print("Saving changes to Registered Devices storage")
                save_registered(registered_devices, devices_last_sync)
            elif command == "devices":
                mibands = scd.tmp_devices
                for idx,mb in enumerate(mibands.keys()):
                    str = "[%s] Mi Band 2 (%s) %sdB " % (idx,mb,mibands[mibands.keys()[idx]].rssi)
                    if mb in registered_devices:
                        str += "[R]"
                    if mb in connected_devices:
                        str += "[C]"
                    print str
            elif "alert" in command:
                arg = re.search("\w+\s+(\d+)\s+(\d+)", command)
                if arg != None and len(arg.groups()) == 2:
                    dev_id = int(arg.groups()[0])
                    alert_int = int(arg.groups()[1])
                    if mibands.keys()[dev_id] in registered_devices:
                        if mibands.keys()[dev_id] in connected_devices.keys():
                            try:
                                mb2 = connected_devices[mibands.keys()[dev_id]]
                                data = struct.pack('B', alert_int)
                                mb2.send_alert(data)
                                print "Sending Notification: " + binascii.hexlify(data)
                            except BTLEException:
                                print("There was a problem alerting this MiBand2, try again later")
                        else:
                            print("That MiBand2 is not connected!")
                    else:
                        print("That MiBand2 is not registered")
                else:
                    print("'alert' takes two parameters")
            elif "unregister" in command:
                arg = re.search("\w+\s+(\d+)", command)
                if arg != None and len(arg.groups()) == 1:
                    dev_id = int(arg.groups()[0])
                    if mibands.keys()[dev_id] in registered_devices:
                        if not mibands.keys()[dev_id] in connected_devices.values():
                            try:
                                registered_devices.remove(mibands.keys()[dev_id])
                                print("MiBand2 unregistered!")
                            except BTLEException:
                                print("There was a problem unregistering this MiBand2, try again later")
                        else:
                            print("Disconnect the miBand2 first!")
                    else:
                        print("That MiBand2 is not registered")
                else:
                    print("'unregister' takes only one parameter")

            elif "register" in command:
                arg = re.search("\w+\s+(\d+)", command)
                if arg != None and len(arg.groups()) == 1:
                    dev_id = int(arg.groups()[0])
                    if mibands.keys()[dev_id] in registered_devices:
                        print("That MiBand2 is already registered")
                    else:
                        try:
                            mb2 = MiBand2(mibands.keys()[dev_id], initialize=True)
                            registered_devices.append(mibands.keys()[dev_id])
                        except BTLEException as e:
                            print("There was a problem disconnecting this MiBand2, try again later")
                            print e
                else:
                    print("'register' takes only one parameter")

            elif "disconnect" in command:
                arg = re.search("\w+\s+(\d+)", command)
                if arg != None and len(arg.groups()) == 1:
                    dev_id = int(arg.groups()[0])
                    if len(connected_devices.keys()) >= max_connections:
                        print("Can't connect to more than 5 devices at the same time, disconnect some")
                    else:
                        if mibands.keys()[dev_id] in connected_devices.keys():
                            try:
                                mb2 = connected_devices[mibands.keys()[dev_id]]
                                mb2.disconnect()
                                del connected_devices[mibands.keys()[dev_id]]
                                del mb2
                                print ("MiBand2 disconnected!")
                            except BTLEException as e:
                                print("There was a problem disconnecting this MiBand2, try again later")
                                print e
                        else:
                            print("That MiBand2 isn't connected!")
                else:
                    print("'connect' takes only one parameter")

            elif "connect" in command:
                arg = re.search("\w+\s+(\d+)", command)
                if arg != None and len(arg.groups()) == 1:
                    dev_id = int(arg.groups()[0])
                    if len(connected_devices.keys()) >= 5:
                        print("Can't connect to more than 5 devices at the same time, disconnect some")
                    else:
                        if mibands.keys()[dev_id] in registered_devices:
                            if mibands.keys()[dev_id] in connected_devices.keys():
                                print("That MiBand2 is already connected")
                            else:
                                try:
                                    mb2 = MiBand2(mibands.keys()[dev_id], initialize=False)
                                    connected_devices[mibands.keys()[dev_id]] = mb2
                                except BTLEException as e:
                                    print("There was a problem connecting to this MiBand2, try again later")
                                    print e
                        else:
                            print("You have to register the MiBand2 before connecting to it")
                else:
                    print("'connect' takes only one parameter")

            elif "alarms" in command:
                pass
                # TODO:  load JSON alarms into device representation
                #        let the user view, queue, toggle and toggle days of each alarm
                #        save and persist alarms in JSON form, key should be mac
                #        and elements arrays of alarm parameters (hour, min, enabledness and daymasks)        

            elif "activity" in command:
                arg = re.search("\w+\s+(\w+)", command)
                if arg != None and len(arg.groups()) == 1:
                    if arg.groups()[0] == 'all':
                        print("Fetching all registered and in range Miband2's activity data")
                        # Check that the registered device is present on the scanned mibands list
                        for item in filter(lambda x: x in registered_devices, mibands.keys()):
                            q.put(item)
                    else:
                        dev_id = int(arg.groups()[0])
                        if mibands.keys()[dev_id] in registered_devices:
                            q.put(mibands.keys()[dev_id])
                        else:
                            print("MiBand2 should be registered before fetching activity data")
                else:
                    print("'activity' takes only one parameter")
            elif command == '':
                pass
            else:
                print ("Unknown command %s, try using 'help'" % command)

        except OSError:
            print 'Invalid command'