コード例 #1
0
ファイル: scanner.py プロジェクト: miguelcma/bluebox
 def _doScan(self, devid=-1):
     status = 0
     seenaddresses = []
     try:
         if self.lastScanTimestamp: print "[SCN] last scan was performed %.2f seconds ago" % round(time.time() - self.lastScanTimestamp, 2)
         self.lastScanTimestamp = time.time()
         try: # try to use a specific Bluetooth interface:
             print "[SCN] address scanning using hci%s..." % devid
             seenaddresses = bluetooth.discover_devices(device_id=devid)
         except TypeError: # if there is no support for multiple interfaces, use the default one:
             print "[SCN] address scanning using default interface (no support for multiple interfaces)"
             seenaddresses = bluetooth.discover_devices()
         status = seenaddresses.__len__()
         print "[SCN] done. took %.2f sec. seen addresses:" % (round(time.time() - self.lastScanTimestamp, 2)), seenaddresses
         self.numErrors = 0
     except bluetooth.btcommon.BluetoothError: # if an error occurs, try to recover
         status = -1
         self.numErrors += 1
         print "[SCN] bluetooth error (%d of %d tolerated)" % (self.numErrors, self.numErrorsUntilReset)
         if self.numErrors == self.numErrorsUntilReset+1:
             print "[SCN] BT ERROR: Resetting interface hci%d" % devid
             basics.Exec().execlp('hciconfig', ['hci'+str(devid), 'down'], wait=True)
         elif self.numErrors == self.numErrorsUntilReset+3:
             print "[SCN] BT ERROR: Critical, restarting hotspot :("
             #basics.Exec().execlp('reboot')
     return (status, seenaddresses)
コード例 #2
0
 def _scan(self):
     """
     Encapsulate the call to the callback function.
     Catch exception and test thread stop.
     """
     while not self._stop.isSet():
         self.log.info(u"Scanning")
         self.log.debug(self._devices)
         try:
             found = bluetooth.discover_devices()
             for dev in self._devices:
                 if dev in found and self._devices[dev]['status'] == 0:
                     # toggle from not seen to seen
                     data = {}
                     data['current'] = 1
                     data['device'] = dev
                     self._send_xpl('sensor.basic', data)
                     self._devices[dev]['hyster'] = 0
                     self._devices[dev]['status'] = 1
                     self.log.info(u"dev {0} moved from away to seen".format(dev))
                 elif dev not in found and self._devices[dev]['status'] == 0 and self._devices[dev]['hyster'] == self._hysteresis:
                     data = {}
                     data['current'] = 0
                     data['device'] = dev
                     self._send_xpl('sensor.basic', data)
                     self.log.info(u"dev {0} moved from seen to away".format(dev))
                 elif dev not in found and self._devices[dev]['hyster'] < self._hysteresis:
                     # not seen and previous not seen, but hysteresis not reached
                     self._devices[dev]['hyster'] += 1
                     self._devices[dev]['status'] = 0
             self._stop.wait(self._scan_delay)
         except Exception as exp:
             self.log.info(u"Error happend waiting for {0} seconds".format(self._error_delay))
             self.log.debug(exp)
             self._stop.wait(self._error_delay)
コード例 #3
0
ファイル: server.py プロジェクト: Tfou57/robomow
def find_host():
	for host, name in bluetooth.discover_devices(lookup_names=True):
		print host, name
		#if (name == 'Nexus 10' or host == 'BC:20:A4:74:7E:43'):
		if (host == "04:E4:51:11:19:09"):
			print "name: ", name
			return host
コード例 #4
0
ファイル: BluetoothSupport.py プロジェクト: kineticgar/htdp
def __linuxSearch():
    from bluetooth import discover_devices, lookup_name
    import time, threading

    ## Threads are used to look up names to avoid the
    ## problem of waiting for each device to respond before
    ## moving on to the next which may have left 'discoverable'
    ## mode. It may be possible to get this info when we do the
    ## initial search...

    class LinuxNameGetter(threading.Thread):
        def __init__(self, address):
            print "Address: ", address
            self.name = None
            ## set up the stuff needed for threading
            threading.Thread.__init__(self)
            self.addr = address

        def run(self):
            print "Starting thread for addr %s" % self.addr
            self.name = lookup_name(self.addr)
            print "addr %s --> %s" % (self.addr, self.name)

    print "Searching for wiimotes..."
    addresses = discover_devices(0)
    print "Found %i devices" % len(addresses)
    ## create the thread things
    threads = [LinuxNameGetter(x) for x in addresses]
    for t in threads:
        t.start()
    while any([t.isAlive() for t in threads]):  ## checks if any threads are still running
        time.sleep(0.1)
    return [(t.addr, t.name) for t in threads]
コード例 #5
0
ファイル: pymw.py プロジェクト: arsh0r/PyMetaWatch
    def __init__(self, watchaddr = None, verbose = False):
        self.CRC=CRC_CCITT();
        self._last_tx_time = time.clock()
        self.verbose = verbose

        while watchaddr == None or watchaddr == "none":
            print("performing inquiry...")
            nearby_devices = bluetooth.discover_devices(lookup_names = True)

            print("found %d devices" % len(nearby_devices))
            for addr, name in nearby_devices:
                print("  %s - '%s'" % (addr, name))
                if name and ('MetaWatch Digital' in name or 'Fossil Digital' in name) :
                    watchaddr=addr;
                    print("Identified Watch at %s" % watchaddr);

        # MetaWatch doesn't run the Service Discovery Protocol.
        # Instead we manually use the portnumber.
        port=1;

        print("Connecting to %s on port %i." % (watchaddr, port));
        sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM);
        sock.setblocking(True)

        self.sock = sock;
        sock.connect((watchaddr, port));
        sock.settimeout(10);            # IMPORTANT Must be patient, must come after connect().
        self.setclock()
コード例 #6
0
ファイル: spp.py プロジェクト: fhorinek/MotionLog
def perform_scan(dev_id = SCAN_DEVICE):
    sock = bluez.hci_open_dev(dev_id)
    mode = read_inquiry_mode(sock)

    if mode != 1:
        write_inquiry_mode(sock, 1)

    names = {}
    for line in bluetooth.discover_devices(duration=5, lookup_names=True, device_id = dev_id):
        names[line[0].lower()] = line[1]
    
    devices = {}
    for line in device_inquiry_with_with_rssi(sock):
        addr = line[0].lower()
        rssi = line[1]
        if addr in devices:
            devices[addr].append(rssi)
        else:
            devices[addr] = [rssi]
    
    result = {}
    for addr in names:
        name = names[addr]
        if addr not in devices:
            continue
        rssis = devices[addr];
        result[addr] =  [name, sum(rssis) / len(rssis)]
        
    return result
コード例 #7
0
def sendComannd(command):
    """Método que faz a modificação do comando
    :Param command: O novo comando
    :Type command: String
    """
    try:
        nearby_devices = bluetooth.discover_devices()
        if (len(nearby_devices) > 0):
            for bdaddr in nearby_devices:
                if bdaddr in address_list:
                    print "ip encontrado"
                    target_address = bdaddr
                    break
            if target_address is not None:
                print "Dispositivo encontrado com o endereço ", target_address

                sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM )
  
                sock.connect((target_address, port))
                print("conexao aceita")
                sock.send(command)
                sock.close()
                return True
        else:
            print "Nenhum dispositivo encontrado."
    except Exception as e:
        print "except",e
        return False
    return False
コード例 #8
0
ファイル: pymw.py プロジェクト: vad1110/PyMetaWatch
   def __init__(self, watchaddr=None):
      self.CRC=CRC_CCITT();
      
      while watchaddr==None or watchaddr=="none":
         print "performing inquiry..."
         nearby_devices = bluetooth.discover_devices(lookup_names = True)
         print "found %d devices" % len(nearby_devices)
         for addr, name in nearby_devices:
            print "  %s - '%s'" % (addr, name)
            if name=='Fossil Digital Watch V2':
               watchaddr=addr;
         print "Identified Watch at %s" % watchaddr;

      # MetaWatch doesn't run the Service Discovery Protocol.
      # Instead we manually use the portnumber.
      port=1;
      
      print "Connecting to %s on port %i." % (watchaddr, port);
      sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM);
      self.sock=sock;
      sock.connect((watchaddr,port));
      sock.settimeout(10);  #IMPORTANT Must be patient.
      
      #Grab settings from the watch.
      try:
         print "Connected to %s" % self.getinfo();
         self.setclock();
         self.getclock();
      except:
         print "Connection probably failed.  Continuing anyways."
コード例 #9
0
ファイル: util.py プロジェクト: uberchicgeekchick/alacast
def discover_bluetooth_devices():
    """
    This is a generator function that returns
    (address, name) tuples of all nearby bluetooth
    devices found.

    If the user has python-bluez installed, it will
    be used. If not, we're trying to use "hcitool".

    If neither python-bluez or hcitool are available,
    this function is the empty generator.
    """
    try:
        # If the user has python-bluez installed
        import bluetooth
        log('Using python-bluez to find nearby bluetooth devices')
        for name, addr in bluetooth.discover_devices(lookup_names=True):
            yield (name, addr)
    except:
        if find_command('hcitool') is not None:
            log('Using hcitool to find nearby bluetooth devices')
            # If the user has "hcitool" installed
            p=subprocess.Popen(['hcitool', 'scan'], stdout=subprocess.PIPE)
            for line in p.stdout:
                match=re.match('^\t([^\t]+)\t([^\t]+)\n$', line)
                if match is not None:
                    (addr, name)=match.groups()
                    yield (name, addr)
        else:
            log('Cannot find either python-bluez or hcitool - no bluetooth?')
            return # <= empty generator
コード例 #10
0
ファイル: bitalino.py プロジェクト: ddparker/bitalino-python
    def find(self, serial=False):
        """
        :param serial: Serial port (True) or MAC address (False)
        :type serial: bool.
        :returns: MAC address or serial of each device found

        Searches for bluetooth devices nearby.
        
        Possible return formats:
        
        =========  ===================================================== =====================
        *serial*   Returns                                                Examples              
        =========  ===================================================== =====================
        True       List of port names containing ``bitalino`` or ``COM`` ``['COM1','COM3']``
        False      List of (tuples) with MAC address and name            ``[('00:0a:95:9d:68:16','bitalino_name')]``
        =========  ===================================================== =====================
        """
        
        try:
            if serial:
                nearby_devices = list(port[0] for port in list_ports.comports() if 'bitalino' or 'COM' in port[0])
            else:
                nearby_devices = discover_devices(lookup_names=True)
            return nearby_devices
        except:
            return -1
コード例 #11
0
    def search(self, name):
        """Searches nearby devices for a given name.

        Args:
            name: The name of the device to search for.

        Returns:
            The MAC address of the device with the given
            name if it was found. Otherwise returns None
        """
        self.name = name
        logging.debug("Searching for nearby devices.")
        nearby_devices = bluetooth.discover_devices()

        max_attempts = 3
        
        while max_attempts > 0:
            
            for addr in nearby_devices:
                logging.info("Found device: %s", addr)
                if bluetooth.lookup_name(addr) == name:
                    logging.info("Device %s is %s", addr, name)
                    return addr
            logging.debug("Device not found. Attempts remaining: %s",
                    max_attempts)
            
            max_attempts = max_attempts - 1

        return None
コード例 #12
0
ファイル: agobluescan.py プロジェクト: bibi21000/agocontrol
def listen_discovery():
    """
    Listen to bluetooth adaptator. This method use the
    bluetooth.discover_devices(). It takes approcimatively 10 seconds
    to proceed. Phones must be "visible" in bluetooth.
    """
    try:
        nearby_devices = bluetooth.discover_devices()
        syslog.syslog(syslog.LOG_DEBUG, 'listen_discovery devices discovered %s' % nearby_devices)
        for phon in phones.keys():
            if phones[phon]["status"] == 1 :
                if phone not in nearby_devices:
                    phones[phon]["count"] =  phones[phon]["count"] + 1
                    if phones[phon]["count"] >= hysteresis:
                        client.emitEvent(ex_bluescan%phon,"event.device.statechanged", "0", "")
                        phones[phon]["status"] = 0
                        syslog.syslog(syslog.LOG_DEBUG, "%s has gone"%phon)
        for phon in nearby_devices:
            if phon in phones.keys():
                if 'name' not in phones[phon] :
                    phones[phon]['name'] = bluetooth.lookup_name(phon)
                phones[phon]["count"] = 0
                if phones[phon]["status"] == 0:
                    phones[phon]["status"] = 1
                    client.emitEvent(ex_bluescan%phon,"event.device.statechanged", "255", "")
                    syslog.syslog(syslog.LOG_DEBUG, "%s is here"%phon)
        return True
    except :
        error = traceback.format_exc()
        syslog.syslog(syslog.LOG_ERR, 'Error when discovering devices in listen_discovery')
        log_exception(error)
        return False
コード例 #13
0
ファイル: bluez.py プロジェクト: capof/domogik
 def _listen_adaptator_discovery(self):
     """
     Listen to bluetooth adaptator. This method use the
     bluetooth.discover_devices(). It takes approcimatively 10 seconds
     to proceed. Phones must be "visible" in bluetooth.
     """
     try:
 #        self.log.debug("_listen_adaptator_discovery : Start \
 #bluetooth.discover_devices at %s" % datetime.datetime.today())
         nearby_devices = bluetooth.discover_devices()
 #        self.log.debug("_listen_adaptator_discovery : Stop \
 #bluetooth.discover_devices at %s" % datetime.datetime.today())
         for aaddr in self._targets:
             if self._targets[aaddr]["status"] == HIGH :
                 if aaddr not in nearby_devices:
                     self._targets[aaddr]["count"] = \
                         self._targets[aaddr]["count"] +1
                     if self._targets[aaddr]["count"] >= self._hysteresis:
                         self._trig_detect("xpl-trig", aaddr, LOW)
         for bdaddr in nearby_devices:
             target_name = bluetooth.lookup_name( bdaddr )
             if bdaddr in self._targets:
                 self._targets[bdaddr]["count"] = 0
                 if self._targets[bdaddr]["status"] == LOW:
                     self._trig_detect("xpl-trig", bdaddr, HIGH)
                     self.log.info("Match bluetooth device %s with address %s" % (target_name, bdaddr))
         return True
     except:
         self.log.error("_listen_adaptator : Error with bluetooth adaptator")
         error = "traceback : %s" %  \
              (traceback.format_exc())
         self.log.error("listen_adaptator : " + error)
         return False
コード例 #14
0
ファイル: bluez.py プロジェクト: capof/domogik
 def scan(self, args = None):
     """
     Scan for bluetooth devices
     """
     self._log.debug("scan : Start ...")
     data = []
     fmtret = "%-15s | %-15s"
     nb = 0
     try:
         nearby_devices = bluetooth.discover_devices()
         data.append(fmtret % ("Address", "Name"))
         data.append(fmtret % ("---------------", "---------------"))
         for bdaddr in nearby_devices:
             nb = nb+1
             target_name = bluetooth.lookup_name(bdaddr)
             data.append(fmtret % (bdaddr, target_name))                
         data.append(fmtret % ("---------------", "---------------"))
         data.append("Found %s bluetooth devices." % nb)
     except:
         data.append("Error with bluetooth adaptator. Look at logs.")
         self._log.error("Error with bluetooth adaptator")
         error = "traceback : %s" %  \
              (traceback.format_exc())
         self._log.error("Exception : " + error)
     self._log.debug("telldusHelper.list : Done")
     return data
コード例 #15
0
ファイル: bt_main.py プロジェクト: hugomatic/btiswatchingu
def timerEvent():
    # Prepare the timer for the next run ...
    global t, lock, database
    t = threading.Timer(period, timerEvent)
    t.start()
    if lock == True:
        return
    try:
        lock = True
        print "timer", time.localtime()        
        
        print "performing inquiry ..."
        nearby_devices = ()
        try:
            # Search for bluetooth devices ...        
            nearby_devices = bluetooth.discover_devices(lookup_names = True)
        except:
            print "bluetooth network not found"
    
        # For each device found, add the address and the name to the database 
        for addr, name in nearby_devices:
            print "  processing %s - %s" % (addr, name)
            
            newPing = ping(device(name, addr), username, location)        
            database.saveDevice(newPing)
            database.savePing(newPing)
        
    except:
        None
    finally:
        lock = False
コード例 #16
0
ファイル: main.py プロジェクト: IoTEnv/Library
def scanThings():
    """scan the things"""
    f = open("./Schema/vibrate.cleaned.json")
    # scanResult = json.loads(f.read())
    deviceList = bluetooth.discover_devices(lookup_names=True)
    deviceProfiles = [];
    for MACaddress, deviceName in deviceList:
        splittedName = deviceName.split('::')
        # print(splittedName)
        if len(splittedName) == 4:
            deviceName = splittedName[1]
            deviceProfURL = splittedName[2]
            deviceKey = splittedName[3]
            requestPayload = {
                "deviceID": deviceName,
                "appID" : IMPROMPTO_APP_ID,
                "key" : deviceKey,
                "context[]" : IOT_CONTEXT
            }
            encodedRequestPayload = urllib.parse.urlencode(requestPayload)
            full_url = deviceProfURL + "?" + encodedRequestPayload
            data = urllib.request.urlopen(full_url)
            deviceProfile = json.loads(data.read().decode('UTF-8'))
            if "IOT" in deviceProfile.keys():
                deviceProfile = deviceProfile["IOT"]
                deviceProfile["rssi"] = "-22" # temp workaround
                deviceProfile["uuid"] = deviceName
                deviceProfile["name"] = deviceName
                deviceProfiles.append(deviceProfile)
    scanResult = deviceProfiles
    print(scanResult)
    return scanResult
コード例 #17
0
ファイル: guidemo.py プロジェクト: loosepascal/Dienes-Blocks
def main():
##    FrameCreator()
    print "Performing inquiry.."
    target_address = "00:12:02:28:73:47"
    target_name = "jyl2"
    port = 1
    nearby_devices = bluetooth.discover_devices(lookup_names=True)

    print "found %d devices" % len(nearby_devices)
    for name, addr in nearby_devices:
        print " %s - %s" % (addr,name)

    #bluetooth address of the bluetooth module is 00:12:02:28:73:47
    global client_socket, window
    client_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    client_socket.connect((target_address, port)) #client connects to the server on port 1
    print "connected to server"

    window =Tk()
    window.geometry("291x300")
    window.title("Dienes Blocks Application")
    window.configure(background='black')
    window.tk_setPalette(background='black', foreground='white', activeBackground='black', activeForeground='white')
    window.iconbitmap(default='favicon.ico')
##    w=Tkinter.Label(window,image=photo)
##    w.grid(row=0, column=1)
    app = HomeScreen(window)
    window.protocol("WM_DELETE_WINDOW", handler)
    window.mainloop()
コード例 #18
0
ファイル: main.py プロジェクト: edgaralejod/rpi3-bluescan
def find_devices():
    print("Searching for nearby devices")
    nearby_devices = bluetooth.discover_devices(lookup_names=True)
    print("found %d devices" % len(nearby_devices))

    for addr, name in nearby_devices:
        print("  %s - %s" % (addr, name))
コード例 #19
0
	def __init__(self):
		print "Connecting to bluetooth..."
		target_name = "Onetouch Idol 3"
		#target_name = "Galaxy Mega"
		target_address = None

		nearby_devices = bluetooth.discover_devices()
		print nearby_devices

		for addr in nearby_devices:
			print bluetooth.lookup_name(addr)
			if target_name == bluetooth.lookup_name(addr):
				target_address = addr
				break

		print target_address

		uuid = "fa87c0d0-afac-11de-8a39-0800200c9a66"
		service_matches = bluetooth.find_service(uuid = uuid, address = target_address)

		if len(service_matches) == 0:
			print "Could not  find service"
			sys.exit(0)

		port = service_matches[0]["port"]
		name = service_matches[0]["name"]
		host = service_matches[0]["host"]

		self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
		self.socket.connect((host, port))
コード例 #20
0
 def discover(self):
     address = None
     bluetoothdevices = bluetooth.discover_devices(duration=6, lookup_names=True)
     for bluetoothdevice in bluetoothdevices:
         if bluetoothdevice[1] == BLUETOOTH_NAME:
             address = bluetoothdevice[0]
     return address
コード例 #21
0
def search(reader, devices, pusher, history):
    while True:
        nearby_devices = bluetooth.discover_devices() # get all nearby devices
        eligibleMacs = list(map(lambda d: d["MAC"], devices)) # convert devices to list of macs
        registered_devices = list(set(nearby_devices) & set(eligibleMacs)) # get the intersection of eligible devices and available devices
        if len(registered_devices) > 0:
            try:
                # if pushbullet and db exist, continue
                if pusher is not None and history is not None:
                    pushed_devices = []
                    for device in registered_devices:
                        try:
                            devObj = list(filter(lambda d: d["MAC"] == device, devices))[0] # get the device with a given MAC address
                            iden = devObj["pushbullet_iden"] # get the device_iden of pushbullet
                            name = devObj["name"] # get the person name
                            pusher.pushNotification(reader["temperature"], "bt", name=name, device=iden) # send the notification to the person
                            pushed_devices.append(device) # successfully pushed
                        except IndexError as err:
                            print(err)
                            continue
                        except KeyError:
                            print("please check your configuration file")
                            continue
                        except:
                            print("Fail to call pushbullet API")
                            continue
                    history.writeHistory(pushed_devices, reader["temperature"], reader["deviceid"]) # write history for all successfull pushes
            except (exceptions.InfluxDBClientError, exceptions.InfluxDBServerError) as err:
                print(err)
            break
        time.sleep(3) #Sleep three seconds 
コード例 #22
0
ファイル: GoodFET.py プロジェクト: BastilleResearch/goodfet
    def __init__(self,btaddr):
        import bluetooth;
        if btaddr==None or btaddr=="none" or btaddr=="bluetooth":
            print "performing inquiry..."
            nearby_devices = bluetooth.discover_devices(lookup_names = True)
            print "found %d devices" % len(nearby_devices)
            for addr, name in nearby_devices:
                print "  %s - '%s'" % (addr, name)
                #TODO switch to wildcards.
                if name=='FireFly-A6BD':
                    btaddr=addr;
                if name=='RN42-A94A':
                    btaddr=addr;
                
            print "Please set $GOODFET to the address of your device.";
            sys.exit();
        print "Identified GoodFET at %s" % btaddr;

        # Manually use the portnumber.
        port=1;
        
        print "Connecting to %s on port %i." % (btaddr, port);
        sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM);
        self.sock=sock;
        sock.connect((btaddr,port));
        sock.settimeout(10);  #IMPORTANT Must be patient.
        
        ##This is what we'd do for a normal reset.
        #str="";
        #while not str.endswith("goodfet.sf.net/"):
        #    str=self.read(64);
        #    print str;
        
        # Instead, just return and hope for the best.
        return;
コード例 #23
0
ファイル: Bluetooth.py プロジェクト: casibbald/kamaelia
 def discover(self,id=False,name=False):
     devices = bluetooth.discover_devices(lookup_names=True)
     if len(devices) > 0:
         services = bluetooth.find_service()
     if id:
         for device in devices:
             if device[0] == id:
                 localservices = list()
                 for service in services:
                     if service['host'] == device[0]:
                         localservices.append(service)
                 self.send(["OK",device,localservices],"outbox")
                 break
         else:
             self.send(["ERROR",id])
     elif name:
         for device in devices:
             if device[1] == name:
                 localservices = list()
                 for service in services:
                     if service['host'] == device[0]:
                         localservices.append(service)
                 self.send(["OK",device,localservices],"outbox")
                 break
         else:
             self.send(["ERROR",name])
     else:
         if len(devices) == 0:
             self.send(["ERROR","No Devices Found"],"outbox")
         else:
             self.send([devices,services],"outbox")
コード例 #24
0
 def discover_devices():
     """Discover Bluetooth devices."""
     result = bluetooth.discover_devices(
         duration=8, lookup_names=True, flush_cache=True,
         lookup_class=False)
     _LOGGER.debug("Bluetooth devices discovered = %d", len(result))
     return result
コード例 #25
0
ファイル: manager.py プロジェクト: SIGMusic/tonal-lightfield
def find_lights():
    """ Finds nearby lights and adds them to the dictionary """
    print("Discovering devices...")
    nearby_devices = bt.discover_devices()

    for address in nearby_devices:
        name = bt.lookup_name(address)
        # Ignore non-lights
        if name.startswith("Light"):
            # Get the light number from the name
            num = int(name[-2:])
            # Check to see if we already found the light
            if not num in lights:
                # Create a light object
                print("Found light", num)
                lights[num] = Light(address, num)
            elif not lights[num].is_connected:
                # We found the light, but it wasn't able to connect. Try again
                print("Attempting to reconnect light", num)
                lights[num].connect_light()

    # Figure out how many lights are connected
    count = 0
    for light in lights:
        if lights[light].is_connected:
            count += 1
    
    if count == 0:
        print("No lights are connected!")
    else:
        # Save the lights
        pickle.dump(lights, open("saved_lights.p", "wb"))
    return count
コード例 #26
0
 def searchControll(self): 
     try:
         nearby_devices = bluetooth.discover_devices()
                 
         for bdaddr in nearby_devices:
             if self.target_name == bluetooth.lookup_name( bdaddr ):
                 self.target_address = bdaddr
                 break
                 
         if self.target_address is not None:
                     
             print "Dispositivo encontrado com o endereço ", self.target_address
                     #recebe do dispostivo
                     
                     #envia pra o controle
     
             sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM )
                 
             sock.connect((self.target_address, self.port))
             print("conexao aceita")
             sock.send(self.comannd)
             sock.close()
             
         else:
             print "Nao há dispositivos na proximidade"   
     except Exception as e:
         print e
コード例 #27
0
 def __init__(self):
     target = "BT-GPS"
     nearby_devices = bluetooth.discover_devices()
     for dev in nearby_devices:
         if bluetooth.lookup_name(dev) == target:
             # Get GPS stuff
             pass
コード例 #28
0
    def find_device(self):
        while self.run and not self.connected:
            if bluetooth_available:
                if self.last_mac:
                    for i in range(100):
                        print "lost connection? trying to reconnect to last mac, try:" , i
                        try:
                            self.btconnect(self.last_mac)
                            break
                        except Exception, e:
                            print e
                            print traceback.format_exc()

                        time.sleep(0.3)
                devices_macs = bluetooth.discover_devices()
                print "found: " , devices_macs
                for device_mac in devices_macs:
                    if device_mac in config.macs:
                        self.btconnect(device_mac)
                        return
                for device_mac in devices_macs:
                    if bluetooth.lookup_name(device_mac) in config.names:
                        self.btconnect(device_mac)
                        #time.sleep(2)
                        return
            try:
                self.sock = None
                self.ser = serial.Serial(self.list_serial_ports()[0], 115200, timeout=1)
                print "connected to " , self.ser
                self.flush_input()
                self.connected = True
                return
            except Exception as e:
                print("could not connect, retrying in 3s\n", e )
                time.sleep(3)
コード例 #29
0
	def get_nearest_phone(self):
		#finds the phone with the best rssi value. returns a tuple with phone_name,mac_address,rssi_value
		nearest_phone = None
		snatcher = RSSI_snatcher(self.logger) #class that gets the signal strength of a phone
		devices = bluetooth.discover_devices()	
		
		for address in devices:
			new_phone = snatcher.get_device_strength(address)
			print("NewPhone: "+str(new_phone))
			print >> self.logger, "NewPhone: "+str(new_phone)

			if self.is_valid(new_phone): #executes if phone is registered
				print("Phone: "+new_phone[0]+" is registered")
				print >> self.logger, "Phone: "+new_phone[0]+" is registered"

				if nearest_phone == None: 
					nearest_phone = new_phone
				elif new_phone[1] >= nearest_phone[1]: #checks RSSI value is stronger and sets the strongest as nearest phone
					nearest_phone = new_phone

			else:
				print("Phone: "+new_phone[0]+" is not registered")
				print >> self.logger, "Phone: "+new_phone[0]+" is not registered"

		if nearest_phone != None: #creates final return value 
			nearest_phone = (bluetooth.lookup_name(nearest_phone[0])
					,nearest_phone[0],nearest_phone[1])

		else: 
			nearest_phone = "No Devices Detected"

		print("NearestPhone: "+str(nearest_phone))
		print >> self.logger, "NearestPhone: "+str(nearest_phone)

		return nearest_phone
コード例 #30
0
ファイル: APRStracker.py プロジェクト: zitanjian/APRStracker
# Simple APRS Receiver and GPX Exporter for Python 3.5
# Works only with Mobilinkd TNC with Bluetooth
#
# Copyright (C) 2019, Juha-Pekka Varjonen, Juvar, OH1FWW
# Version 1.0
#

import bluetooth, re, ax25
from datetime import datetime
import zipfile, zlib

# search all available bt devices and put them to array
results = []
try:
    btDevices = bluetooth.discover_devices(lookup_names=True,
                                           flush_cache=True,
                                           duration=8)
except bluetooth.btcommon.BluetoothError as err:
    print("Info: %s" % err.args)
    exit()
except OSError:  #No such device (if no bt adapters)
    print("Info: No adapters")
    exit()
for addr, name in btDevices:
    results.append([name, addr, 1])

# inform user about available bt devices
# Automatically select Mobilinkd TNC
# exit if not any bt devices
mobilinkd = ""
if (len(results) > 0):
コード例 #31
0
def runMenu():
    while(True):
        print()
        print("1. engineer")
        print("2. user")
        selection = input("Select an option: ")
        print()
        if(selection == "1"):
            print()
            print("3. scan QR")
            print("4. open the car")
            selection1 = input("Select an option: ")
            print()
            if (selection1 == "3"):
                while True:
                    _, img = cap.read()
                    data, bbox, _ = detector.detectAndDecode(img)
                            
                    if(bbox is not None):
                        for i in range(len(bbox)):
                            cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255,
                                            0, 255), thickness=2)
                            cv2.putText(img, data, (int(bbox[0][0][0]), int(bbox[0][0][1]) - 10), cv2.FONT_HERSHEY_SIMPLEX,
                                            0.5, (0, 255, 0), 2)
                            conn = sqlite3.connect(DB_NAME)
                            conn.row_factory = sqlite3.Row
                            c = conn.cursor()
                            print(data)
                            with conn:
                                c.execute("SELECT * FROM engineer WHERE AccountID = ?", (data))
                                row = c.fetchone()
                                print(row)
                    cv2.imshow("code detector", img)
                    if(cv2.waitKey(1) == ord("q")):
                        break
            else:
                print("Performing inquiry...")

                nearby_devices = bluetooth.discover_devices(duration=8, lookup_names=True,
                                                                flush_cache=True, lookup_class=False)

                print("Found {} devices".format(len(nearby_devices)))

                for addr, name in nearby_devices:
                    try:
                        print("   {} - {}".format(addr, name))
                        if addr == "8C:83:E1:D0:84:03":
                            print ("the car is open")
                        else:
                            print ("Alert")
                    except UnicodeEncodeError:
                        print("   {} - {}".format(addr, name.encode("utf-8", "replace")))
        else:
            print()
            print("1. use the username and password")
            print("2. facial checking")
            selection2 = input("Select an option: ")
            print()
            if (selection2 == "1"):
                name = input("username: "******"password:"******"nhan.jpg")
                my_face_encoding = face_recognition.face_encodings(picture_of_me)[0]

                # Load a second sample picture and learn how to recognize it.
                duy = face_recognition.load_image_file("duy.jpg")
                duy_face_encoding = face_recognition.face_encodings(duy)[0]

                # Create arrays of known face encodings and their names
                known_face_encodings = [
                    my_face_encoding,
                    duy_face_encoding
                ]
                known_face_names = [
                    "Thanh Nhan","Khang Duy"
                    
                ]

                # Initialize some variables
                face_locations = []
                face_encodings = []
                face_names = []
                process_this_frame = True
                count=0
                # dbx = dropbox.Dropbox('6lYXOy3Wb2AAAAAAAAAADjd3j3ycNSoJ7e3FoakEJ-hqk3DMeMsPZe-9TVZAFilf')
                # Get a reference to webcam #0 (the default one)
                while True:
                    var = input("Launch The Security Service? ")
                    if str(var) == "Yes":
                        break

                while True:
                    # Grab a single frame of video
                    ret, frame = cap.read()
                    # Resize frame of video to 1/4 size for faster face recognition processing
                    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

                    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
                    rgb_small_frame = small_frame[:, :, ::-1]

                    # Only process every other frame of video to save time
                    if process_this_frame:
                        # Find all the faces and face encodings in the current frame of video
                        face_locations = face_recognition.face_locations(rgb_small_frame)
                        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

                        face_names = []
                        for face_encoding in face_encodings:
                            # See if the face is a match for the known face(s)
                            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                            name = "Unknown"
                            # If a match was found in known_face_encodings, just use the first one.
                            if True in matches:
                                first_match_index = matches.index(True)
                                name = known_face_names[first_match_index]

                            face_names.append(name)
                            if name == "Unknown":
                                print("Unknown people Warning")
                            else:
                                print("Car Door Opening...!!!!")
                                break
                    process_this_frame = not process_this_frame

                    # Display the results
                    for (top, right, bottom, left), name in zip(face_locations, face_names):
                        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
                        top *= 4
                        right *= 4
                        bottom *= 4
                        left *= 4
                    
                        # Draw a box around the face
                        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                    
                        # Draw a label with a name below the face
                        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
                        font = cv2.FONT_HERSHEY_DUPLEX
                        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
                    
                    # Display the resulting image
                    cv2.imshow('Video', frame)

                    # Hit 'q' on the keyboard to quit!
                    if cv2.waitKey(1) & 0xFF == ord('q'):
                        print("System Shutdown!!")
                        break
コード例 #32
0
ファイル: bt_RFCOMM.py プロジェクト: Pyro4Bot-RoboLab/PYRobot
 def Discover(self):
     self.btDevices = bluetooth.discover_devices(lookup_names=True)
     if len(self.btDevices) > 0:
         return self.btDevices
     else:
         return None
コード例 #33
0
def push_request():
    nearby_devices = bluetooth.discover_devices(duration=10, lookup_names=True)
    return nearby_devices
コード例 #34
0
#!/usr/bin/python3

import bluetooth as bt

for (addr, name) in bt.discover_devices(lookup_names=True):
    print("%s %s" % (addr, name))

コード例 #35
0
		f.write(imgdata)
		f.close()

	client_sock.close()
	server_sock.close()

	print "Screenshot received from client. Image save as \'", filename, "\'"
elif (choice0 == 2):
	print "------------------------------------------------------------------"
	print "1) Discover New Device \t\t 2) Enter MAC Address Manually"
	print "------------------------------------------------------------------"
	print 
	choice1 = int(input("Choice? "))
	if (choice1 == 1):
		print "Searching for nearby bluetooth-enabled devices for 10 seconds"
		devices = bluetooth.discover_devices(duration = 10, lookup_names = True)
		i = 1
		for address, name in devices:
			print "\t", i, ") ", name, " : ", address
			i += 1
		choice2 = int(input("Choice? "))
		if (1 <= choice2 <= len(devices)):
			MAC_Address = devices[choice2-1][0]
	elif(choice1 == 2):
		MAC_Address = input("Enter MAC Address: ")

	sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)

	bt_addr = MAC_Address
	port = 0x1001
コード例 #36
0
def run(file_flag):
    # Shimer MAC addresses
    # shimm_addr= ["00:06:66:46:9A:67", "00:06:66:46:B6:4A"]#, "00:06:66:46:BD:8D", "00:06:66:46:9A:1A", "00:06:66:46:BD:BF"]
    shimm_addr = ["00:06:66:46:B7:D4"]
    emg_addr = []  # ["00:06:66:46:9A:1A", "00:06:66:46:BD:BF"]

    # Configuration parameters
    scan_flag = 1
    plot_flag = 0

    sock_port = 1
    nodes = []
    plt_axx = 500
    plt_ylim = 4000
    plt_rate = 20

    rng_size = 50

    # rng_acc_x=RingBuffer(50)
    # Add sample to ringbuffer
    # rng_acc_x.append(pack_0)
    # buff1= np.zeros((n_nodes,10,rng_size),dtype=np.int)
    # buff2= np.zeros((n_nodes,10,rng_size),dtype=np.int)
    # buff_flag= 1
    # buff= [[[0 for x in range(10)] for y in range(2)] for z in range(rng_size)]
    # buff_idx= 0

    if plot_flag == 1:
        # plot parameters
        sample_idx = 0
        analogData = AnalogData(plt_axx)

    # Get the list of available nodes
    if scan_flag == 0:
        target_addr = shimm_addr
    else:
        try:
            target_addr = []
            print("Scanning bluetooth devices...")
            nearby_devices = bluetooth.discover_devices()
            for bdaddr in nearby_devices:
                print("			" + str(bdaddr) + " - " +
                      bluetooth.lookup_name(bdaddr))
                if bdaddr in shimm_addr:
                    target_addr.append(bdaddr)
        except:
            print("[Error] Problem while scanning bluetooth")
            sys.exit(1)

    n_nodes = len(target_addr)
    if n_nodes > 0:
        print(("Found %d target Shimmer nodes") % (len(target_addr)))
    else:
        print("Could not find target bluetooth device nearby. Exiting")
        sys.exit(1)

    print("Configuring the nodes...")
    for node_idx, bdaddr in enumerate(target_addr):
        try:
            # Connecting to the sensors
            sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            if bdaddr in emg_addr:
                n = shimmer_node(bdaddr, sock, 0x2)
            else:
                n = shimmer_node(bdaddr, sock, 0x1)
            nodes.append(n)

            print((bdaddr, sock_port), end=' ')
            nodes[-1].sock.connect((bdaddr, sock_port))
            print(" Shimmer %d (" % (node_idx) +
                  bluetooth.lookup_name(bdaddr) + ") [Connected]")
            # send the set sensors command
            nodes[-1].sock.send(
                struct.pack('BBB', 0x08, nodes[-1].senscfg_hi,
                            nodes[-1].senscfg_lo))
            nodes[-1].wait_for_ack()

            # send the set sampling rate command
            nodes[-1].sock.send(struct.pack('BB', 0x05, 0x14))  # 51.2Hz
            nodes[-1].wait_for_ack()

            # Inquiry command
            print("	Shimmer %d (" % (node_idx) +
                  bluetooth.lookup_name(bdaddr) + ") [Configured]")
            nodes[-1].sock.send(struct.pack('B', 0x01))
            nodes[-1].wait_for_ack()
            inq = nodes[-1].read_inquiry()
        except bluetooth.btcommon.BluetoothError as e:
            print(("BluetoothError during read_data: {0}".format(e.strerror)))
            print("Unable to connect to the nodes. Exiting")
            sys.exit(1)

    # Create file and plot
    try:
        if file_flag == 1:
            # Create buffer
            now = datetime.datetime.now()
            qc.make_dirs('../DATA')
            logname = "../DATA/IMU_" + now.strftime("%Y%m%d%H%M") + ".log"
            print("[cnbi_shimmer] Creating file: %s" % (logname))
            outfile = open(logname, "w")
            for node_idx, shim in enumerate(nodes):
                outfile.write(str(node_idx) + ": " + str(shim.addr) + "\n")
            outfile.close()

            fname = "../DATA/IMU_" + now.strftime("%Y%m%d%H%M") + ".dat"
            print("[cnbi_shimmer] Creating file: %s" % (fname))
            outfile = open(fname, "w")

        # Create plot
        if plot_flag == 1:
            analogPlot = AnalogPlot(analogData)
            plt.axis([0, plt_axx, 0, plt_ylim])
            plt.ion()
            plt.show()
    except:
        print("[Error]: Error creating file/plot!! Exiting")
        # close the socket
        print("Closing nodes")
        for node_idx, shim in enumerate(nodes):
            shim.sock.close()
            print("	Shimmer %d [Ok]" % (node_idx))
        sys.exit(1)

    print(
        "[cnbi_shimmer] Recording started. Press Ctrl+C to finish recording.")
    # send start streaming command
    for shim in nodes:
        shim.sock.send(struct.pack('B', 0x07))

    for node_idx, shim in enumerate(nodes):
        shim.wait_for_ack()
        shim.up = 1
        print("	Shimmer %d [Ok]" % (node_idx))

    # Main acquisition loop
    while True:
        try:
            sample = []
            sample_lslclock = []
            for shim in nodes:
                if shim.up == 1:
                    sample.append(shim.read_data())
                else:
                    sample.append([0] * (shim.n_fields))

            for samp in sample:
                sample_lslclock.append([pylsl.local_clock()] + list(samp[1:]))

            if file_flag == 1:
                simplejson.dump(sample_lslclock,
                                outfile,
                                separators=(',', ';'))
                outfile.write('\n')

            # print sample
            # plt.title(str(sample[0][0]))

            # leeq
            if plot_flag == 1:
                analogData.add([sample[0][1], sample[0][2]])
                sample_idx = sample_idx + 1
                if sample_idx % plt_rate == 0:
                    analogPlot.update(analogData)

            if file_flag == 0:
                print(qc.list2string(sample_lslclock[1], '%9.1f', ' '))

        # Exit if key is pressed
        except KeyboardInterrupt:
            print("\n[cnbi_shimmer] Stopping acquisition....")
            break
        except bluetooth.btcommon.BluetoothError as e:
            print(("[Error] BluetoothError during read_data: {0}".format(
                e.strerror)))

    # send stop streaming command
    print("[cnbi_shimmer] Stopping streaming")
    try:
        for shim in nodes:
            shim.sock.send(struct.pack('B', 0x20))
        for node_idx, shim in enumerate(nodes):
            shim.wait_for_ack()
            print("	Shimmer %d [Ok]" % (node_idx))
    except bluetooth.btcommon.BluetoothError as e:
        print(("[Error] BluetoothError during read_data: {0}".format(
            e.strerror)))
    '''
        n_nodes =	len(target_addr)
        while n_nodes>0:
        sample= []
        for node_idx,shim in enumerate(nodes):
        pckt= shim.wait_stop_streaming()
        print "	Shimmer %d [waiting]" % (node_idx)
        if len(pckt) != 1:
            sample.append(pckt)
        else:
        sample.append(str("0"*(shim.samplesize)))
        nodes.remove(shim)
        n_nodes= n_nodes-1
        print "	Shimmer %d [Ok]" % (node_idx)
        simplejson.dump(sample, outfile, separators=(',',';'))
        analogData.add([sample[0][1],sample[1][1]])
        analogPlot.update(analogData)
    '''

    # Closing	file
    if file_flag == 1:
        print("[cnbi_shimmer] Closing file: %s" % (fname))
        try:
            outfile.close()
        except:
            print("			[Error] Problem closing file!")

    # close the socket
    print("[cnbi_shimmer] Closing nodes")
    for node_idx, shim in enumerate(nodes):
        shim.sock.close()
        print("	Shimmer %d [Ok]" % (node_idx))

    print("[cnbi_shimmer] Recording Finished. Please close this window.")
    getch()
コード例 #37
0
def search():
	devices = bluetooth.discover_devices(duration=5, lookup_names = True)
	return devices
コード例 #38
0
ファイル: loadCells.py プロジェクト: jm-hsn/windkanal
    def scan(self):
        nearby_devices = bluetooth.discover_devices(lookup_names=True)
        print("Found {} devices.".format(len(nearby_devices)))

        for addr, name in nearby_devices:
            print("  {} - {}".format(addr, name))
コード例 #39
0
 def scan(self, duration=10):
     devices = bluetooth.discover_devices(duration, lookup_names=True)
     for addr, name in devices:
         if str(name).startswith('Spark'):
             logging.debug('Found {0} MAC {1}'.format(name, addr))
             self.spark_mac = addr
コード例 #40
0
def lookUpNearbyBluetoothDevices():
  nearby_devices = bluetooth.discover_devices()
  for bdaddr in nearby_devices:
    print str(bluetooth.lookup_name( bdaddr )) + " [" + str(bdaddr) + "]"
コード例 #41
0
ファイル: Project.py プロジェクト: Marcdaou/RaspberryPi
def prog(
    data, timing
):  #Function containing the actual identifying of Bluetooth devices in the server
    print('IN?')

    t = 1

    print(timing)
    data.writerow(timing)

    for t in range(
            t, 120
    ):  #looped 120 times, since each loop takes about 1 minute, results in a two hour loop

        file_time = time.strftime('%D %H:%M:%S', time.gmtime())

        device_lookup = bluetooth.discover_devices(
            lookup_names=True)  #Looking up Bluetooth Devices

        blue(device_lookup)

        for addr, name in device_lookup:
            ident = '%s' % (name)
            address = '%s' % (addr)

            print(time.strftime('%a, %D %H:%M:%S', time.gmtime()))
            result = bluetooth.lookup_name(address, timeout=5)

            if (
                    result != None
            ):  #If devices are present, the program will search firebase for their codes

                server = firebase.get(
                    '/ais', None
                )  #Searches a directory we named ais for the Bluetooth devices

                values = server.values(
                )  #Shows all Bluetooth Addresses present on the server
                print(values)

                position = str(values).find(
                    str(address)
                )  #Searches for any common devices amongst the perceived devices and those on the server
                print(position)
                position = position - 3
                n = position % 22  #Position returns an integer which represents the position of the first starting character of the address
                #Each address takes up about 22 character spaces
                #When looking up the item in the list, its list number must be found, which is its position relative to its character number
                #hence it is position divided 22

                final_integer = int(
                    math.floor(n)
                )  #This would return a decimal, thus we need the closest integer rounded down
                #We take the math.floor value of the decimal n
                print(final_integer)

                if (
                        int(position) < 0
                ):  #This is present to prevent the non-server addresses from interfering with the rest of the
                    empty = []
                    empty.append(final_integer)

                elif (
                        position >= 0
                ):  #Finds the perceived devices also present on the server, then writes them to the csv file

                    value_final = values[final_integer]
                    result_final = bluetooth.lookup_name(value_final,
                                                         timeout=5)
                    data.writerow(result_final + ' ' + value_final + ' ' +
                                  file_time)

            if (result == None):  #writes none if no devices are detected
                print('none found at the moment')
                data.writerow('None Found at the Moment')

        t = t + 1

        time.sleep(10)
コード例 #42
0
ファイル: blue.py プロジェクト: BrewBlox/bluetooth-demo
def discover():
    nearby_devices = bluetooth.discover_devices(lookup_names=True)
    LOGGER.info(f'discovered {nearby_devices}')
    return nearby_devices
コード例 #43
0
def find_bricks(host=None, name=None):
    for h, n in bluetooth.discover_devices(lookup_names=True):
        if _check_brick(host, h) and _check_brick(name, n):
            yield BlueSock(h)
コード例 #44
0
ファイル: scan.py プロジェクト: pawanembedded/pi_bt
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

# simple inquiry example
import bluetooth

nearby = bluetooth.discover_devices()

for b in nearby:
    print(bluetooth.lookup_name(b))



import bluetooth as bt
print "Searching for devices..."
print ""
nearby_devices = bt.discover_devices()
#Run through all the devices found and list their name
num = 0
print "Select your device by entering its coresponding number..."
for i in nearby_devices:
	num+=1
	print num , ": " , bt.lookup_name( i )

selection = input("> ") - 1
print "You have selected", bluetooth.lookup_name(nearby_devices[selection])
bd_addr = nearby_devices[selection]

port = 1

print "Generating Socket..."
sock = bt.BluetoothSocket(RFCOMM)
sock.connect((bd_addr,port))
while True:
	command = input("> Enter command to be sent to the robot...")
	sock.send(command)
コード例 #46
0
ファイル: Bluetooth.py プロジェクト: yitasha/IoT_Carshare
#!/usr/bin/env python3
#ifdef _WIN32
#include <Winsock2.h>
#endif

import bluetooth

print("local Bluetooth device address - {}".format(
    bluetooth.read_local_bdaddr()))

print("Performing inquiry...")

nearby_devices = bluetooth.discover_devices(duration=8,
                                            lookup_names=True,
                                            flush_cache=True,
                                            lookup_class=False)

print("Found {} devices".format(len(nearby_devices)))

for addr, name in nearby_devices:
    try:
        print("   {} - {}".format(addr, name))
    except UnicodeEncodeError:
        print("   {} - {}".format(addr, name.encode("utf-8", "replace")))

print(nearby_devices)

Engineer_devices = ['9C:B6:D0:FA:B0:54', 'others']
print(Engineer_devices)

for addr, name in nearby_devices:
コード例 #47
0
    def __init__(self):
        pygame.init()

        # Used to manage how fast the screen updates
        self._clock = pygame.time.Clock()

        # Loop until the user clicks the close button.
        self._done = False

        # Used to manage how fast the screen updates
        self._clock = pygame.time.Clock()

        # Kinect runtime object, we want only color and body frames
        self._kinect = PyKinectRuntime.PyKinectRuntime(
            PyKinectV2.FrameSourceTypes_Infrared)

        # back buffer surface for getting Kinect infrared frames, 8bit grey, width and height equal to the Kinect color frame size
        self._frame_surface = pygame.Surface(
            (self._kinect.infrared_frame_desc.Width,
             self._kinect.infrared_frame_desc.Height), 0, 24)
        # here we will store skeleton data
        self._bodies = None

        # Set the width and height of the screen [width, height]
        self._infoObject = pygame.display.Info()
        self._screen = pygame.display.set_mode(
            (self._kinect.infrared_frame_desc.Width,
             self._kinect.infrared_frame_desc.Height),
            pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE, 32)

        self.target = [100, 100]
        self.turnCheck = False

        pygame.display.set_caption("Kinect for Windows v2 Infrared")

        ## Bluetooth
        target_name = "HC-05"
        target_address = None

        while (target_address is None):
            nearby_devices = bluetooth.discover_devices()
            print(nearby_devices)

            for bdaddr in nearby_devices:
                print(bluetooth.lookup_name(bdaddr))
                if target_name == bluetooth.lookup_name(bdaddr):
                    target_address = bdaddr
                    break

        if target_address is not None:
            print("found target bluetooth device with address ",
                  target_address)
            self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

            print("Trying connection")

            i = 0  # ---- your port range starts here
            maxPort = 3  # ---- your port range ends here
            err = True
            while err == True and i <= maxPort:
                print("Checking Port ", i)
                port = i
                try:

                    self.sock.connect((target_address, port))
                    err = False
                except Exception:
                    ## print the exception if you like
                    i += 1
            if i > maxPort:
                print("Port detection Failed.")
                return

            # print("Trying sending")
            # self.sock.send("1 2 3")
            # print("Finished sending")
        else:
            print("could not find target bluetooth device nearby")
コード例 #48
0
def search():         
  devices = bluetooth.discover_devices(duration = 5,flush_cache=True, lookup_names = False)
  return devices
コード例 #49
0
# file: inquiry.py
# auth: Albert Huang <*****@*****.**>
# desc: performs a simple device inquiry followed by a remote name request of
#       each discovered device
# $Id: inquiry.py 401 2006-05-05 19:07:48Z albert $
#

#If you are getting errors running this, sudo apt-get install bluetooth.

import bluetooth

print("performing inquiry...")

nearby_devices = bluetooth.discover_devices(lookup_names=True)

print("found %d devices" % len(nearby_devices))

for addr, name in nearby_devices:
    print("  %s - %s" % (addr, name))
コード例 #50
0
    def get_socket_stream_list(self):

        paired_devices = bluetooth.discover_devices(lookup_names=True)

        return paired_devices
コード例 #51
0
ファイル: Pi_operate.py プロジェクト: danlkv/payhere
def lookUpNearbyBluetoothDevices():
    print("Scanning...")
    nearby_devices = bluetooth.discover_devices()
    for bdaddr in nearby_devices:
        print(str(bluetooth.lookup_name(bdaddr)) + " [" + str(bdaddr) + "]")
コード例 #52
0
    def listAvailable(self):
        nearbyDevices = bluetooth.discover_devices(lookup_names=True)
        print("found %d devices" % len(nearbyDevices))

        for addr, name in nearbyDevices:
          print("  %s - %s" % (addr, name))
コード例 #53
0
def lookUpNearbyBluetoothDevices():
    nearby_devices = bt.discover_devices()
    for bdaddr in nearby_devices:
        print((bt.lookup_name(bdaddr)) + " [" + (bdaddr) + "]")
コード例 #54
0
	def run(self):
		nearby_devices = bluetooth.discover_devices(lookup_names = True)
		return nearby_devices
	while 1:
		line = ser.readline()
		if line: f.write(line)
except KeyboardInterrupt:
	f.close()
	ser.close()
"""
data_json = {"y": [], "x": [], "button_R": [], "button_L": []}

############ serial ###########

###############################

print "Searching for devices..."
print ""
devices = bluetooth.discover_devices()

num = 0
print "Select your device by entering its coresponding number..."
for i in devices:
    num += 1
    print num, ": ", bluetooth.lookup_name(i)

selection = input("> ") - 1
print "You have selected", bluetooth.lookup_name(devices[selection])
bd_addr = devices[selection]
print "--", bd_addr

port = 1

sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
search_time = 10
led_pin = "P8_7"
# You can hardcode the desired device ID here as a string to skip the discovery stage
addr = None

print("Welcome to the Bluetooth Detection Demo! \nMake sure your desired Bluetooth-capable device is turned on and discoverable.")

if addr == None:
    try:
        input("When you are ready to begin, press the Enter key to continue...")
    except SyntaxError:
        pass

    print("Searching for devices...")

    nearby_devices = bluetooth.discover_devices(duration=search_time, flush_cache=True, lookup_names=True)

    if len(nearby_devices) > 0:
        print("Found %d devices!" % len(nearby_devices))
    else:
        print("No devices found! Please check your Bluetooth device and restart the demo!")
        exit(0)

    i = 0 # Just an incrementer for labeling the list entries
    # Print out a list of all the discovered Bluetooth Devices
    for addr, name in nearby_devices:
        print("%s. %s - %s" % (i, addr, name))
        i =+ 1

    device_num = input("Please specify the number of the device you want to track: ")
コード例 #57
0
def BTDiscover(timeout):
    if hasBT:
        return bt.discover_devices(timeout,
                                   flush_cache=True,
                                   lookup_names=True)
    return []
コード例 #58
0
    def scan_button_clicked(self, widget):
        print "Scanning process initiated."
        self.quit_button.set_sensitive(False)
        self.scan_button.set_sensitive(False)

        # Inititiate WIFI Scan ##############################################
        # we first do the wifi scan because sometimes bluetooth discovery disables wifi connection

        if self.wifi:  # if wifi is enabled
            print "Wifi scan started."
            ip_ = 1
            while ip_ < 255:
                ip_ = ip_ + 1
                IP = self.server_IP_template + str(
                    ip_)  # create 1xx.xx.xx.i IP's
                if IP == self.server_IP:  # if IP is our own, continue
                    continue
                if IP in self.addresses.values(
                ):  # if already connected, continue
                    print "Already connected to %s" % IP
                    continue
                try:  # discover using threads
                    t = threading.Thread(target=self.discover, args=(IP, ))
                    self.thread_list.append(t)
                except Exception as e:
                    template = "An exception of type {0} occured. Arguments:{1!r}"
                    mesg = template.format(type(e).__name__, e.args)
                    print mesg

            for thread in self.thread_list:  # start all threads
                thread.start()

            for thread in self.thread_list:  # then wait for them to finish
                thread.join()

            del self.thread_list[:]  # remove all threads
            print "Wifi scan ended."
        else:
            "Wifi scan skipped, not connected to wifi."

        # Initiate bluetooth scan ###########################################

        if self.bluetooth:
            print "Bluetooth scan started."
            for addr, name in bluetooth.discover_devices(
                    lookup_names=True
            ):  # discover nearby devices using library function
                if addr in self.addresses.values():
                    print "Already connected to %s" % addr
                    continue
                try:  # use threads to connect to bluetooth devices
                    t = threading.Thread(target=self.discover_bluetooth,
                                         args=(
                                             addr,
                                             name,
                                         ))
                    self.thread_list.append(t)
                except Exception as e:
                    template = "An exception of type {0} occured. Arguments:{1!r}"
                    mesg = template.format(type(e).__name__, e.args)
                    print mesg

            for thread in self.thread_list:
                thread.start()

            for thread in self.thread_list:
                thread.join()

            del self.thread_list[:]
            print "Bluetooth scan ended."

        self.quit_button.set_sensitive(True)
        self.scan_button.set_sensitive(True)

        print "Done"
コード例 #59
0
 def _findMindwaveMobileAddress(self):
     nearby_devices = bluetooth.discover_devices(lookup_names=True)
     for address, name in nearby_devices:
         if (name == "MindWave Mobile"):
             return address
     return None
コード例 #60
-1
ファイル: bt_debug.py プロジェクト: erobinson/cloop
def debug_bt_bt():
    print "looking for nearby devices..."
    nearby_devices = bluetooth.discover_devices(lookup_names=True, flush_cache=True, duration=20)
    print "found %d devices" % len(nearby_devices)
    for addr, name in nearby_devices:
        print " %s - %s" % (addr, name)
        print_services(bluetooth.find_service(address=addr))