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))
Exemple #2
0
	def scan(self):
		#all is for just scanning
		#not only traget_name, target_address as well
		#self.target_address = None	#Will figure it out later
		found = False
		nb_test = self.nb_tries
		print 'Performing inquiry...'
		print '	-> requesting %s@%s' % (self.target_name, self.target_address)
		while found == False and nb_test > 0:
			if nb_test < self.nb_tries:
				print 'No suitable device detected, giving an other shot'
			nb_test -= 1
			try:
				btdevices = bluetooth.discover_devices(flush_cache=True)
			except:
				print '[!] Couldn\'t get any bluetooth socket'
				sys.exit(1)
			print '%d nearby device(s) detected' %len(btdevices)
			for bdaddr in btdevices:
				if self.target_name == bluetooth.lookup_name(bdaddr):
					self.target_address = bdaddr
					found = True
					break
				elif self.target_address == bdaddr:
					self.target_name = bluetooth.lookup_name(bdaddr)
					found = True
					break
			if found == False and nb_test == 0:
				print '[!] Couldn\'t find bluetooth target called ', self.target_name 
				print '[!] Make sure it is powered or nearby enough (about less than 8 meters distant)'
				sys.exit(1)
    def __init__(self):
        self.paths = path()
        bus_name = dbus.service.BusName("custom.LBRC", bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, "/custom/LBRC")
        self.btserver = BTServer()

        self.config = config()

        self.event_listener = []

        for i in (UinputDispatcher, CommandExecutor, DBUSCaller, ProfileSwitcher, MPlayer):
            self._register_listener(i)

        # load of config data
        self.cur_profile = None
        self.reload_config()

        self.btserver.connect("keycode", self.handler)
        self.btserver.connect(
            "connect", lambda btserver, btadress, port: self.connect_cb(bluetooth.lookup_name(btadress), btadress, port)
        )
        self.btserver.connect(
            "disconnect",
            lambda btserver, btadress, port: self.disconnect_cb(bluetooth.lookup_name(btadress), btadress, port),
        )
        # load the default profile
        self._load_default_profile()
def bluetoothInOut():
    
    bluetoothSerial = serial.Serial("/dev/rfcomm0", baudrate=9600) 
    
    restart = 0 
  
    print(timestr)
    print("Devices in the room: ") 
    result1 = bluetooth.lookup_name('C4:3A:BE:8E:9E:70', timeout=5)
    if(result1 != None):
        print("Bruna in")
        say(name1)
        restart=0
             
    else:
        print("Bruna out")
        restart = restart + 1
                
    result2 = bluetooth.lookup_name('00:14:01:21:11:18', timeout=10)
    
    if(result2 != None):
        print("Button in")
        say(name2)
        #serial.open()
        restart=0
        
                
    else:
        print("Button out")
        restart = restart + 1
                
    print (time.time())
    print (time.clock())
    
    return restart
def getDevices():
    nearby_devices = bluetooth.discover_devices(duration=getTimeoutDuration())

    for bdaddr in nearby_devices:
    #        if target_name == bluetooth.lookup_name( bdaddr ):
    #            target_address = bdaddr
    #            break
    #    print bluetooth.lookup_name(bdaddr),bluetooth.socket.create_connection(bdaddr)
        print bluetooth.lookup_name(bdaddr)
Exemple #6
0
def isDeviceNear( devName ):
	# Lists the names of all the discovered devices
	# MAKE SURE YOUR DEVICE IS DISCOVERABLE; otherwise, you will not be
	# able to discover it
	devices = bluetooth.discover_devices()
	for devAddr in devices:
		if devName == bluetooth.lookup_name( devAddr ):
			print bluetooth.lookup_name( devAddr )
			return True
	return False
Exemple #7
0
		def Connect():
	
			os.system('cls')
			print "\n\n    Izombol keresem...\n    Ellenorizd, hogy a Bluetooth eszkozok \n    be vannak-e kapcsolva, es lathatoak-e!"
			
			target_name = search_variable.get()	# Az Entry widget tartalmanak string formaban való atadasa ( param )
			target_address = None	# a Target eszkoz MAC cime elobb NONE, majd a bdaddr ( lookup visszateresi ertek )

			print "    A keresett eszkoz neve: %s" % target_name
			
			# BLUETOOTH ESZKÖZÖK KERESÉSE...
			nearby_devices = bluetooth.discover_devices()

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

			if target_address is not None:
				print "\n    Bluetooth eszkozt talaltam a kovetkezo MAC cimmel:", target_address	# sikeres kereses "target_address" MAC cimmel
			else:
				print "Nem talaltam Bluetooth eszkozt a kozelben."	# sikertelen kereses, ennek tobb oka lehet, pl. kikapcsolt / nem lathato modul
				
			# CSATLAKOZÁSI KÍSÉRLET...
			bd_addr = target_address
			port = 1
			
			sock.connect((bd_addr, port))

			pin = search_variable2.get()
			sock.send(pin) # A tartget eszozunk PIN kodja 1234
Exemple #8
0
 def run(self):
     self.cv.acquire()
     self.cv.wait()
     self.cv.release()
     while not self.kill_received:
         if self.addresses:
             devid = self.intrf.request(bandwidth=1)
             print "[SCN] getting names of %d devices using hci%s..." % (len(self.addresses), devid)
             try:
                 doneAddresses = {}
                 for addr in self.addresses:
                     #name = bluetooth.lookup_name(addr, device_id=devid)
                     name = bluetooth.lookup_name(addr)
                     self.knownDevices.setInfo(address=addr, name=name)
                     doneAddresses[addr] = name
                 self.cv.acquire()
                 for addr in doneAddresses:
                     if self.addresses.has_key(addr): self.addresses.pop(addr)
                 self.cv.release()
                 print "[SCN] inquiry ended. got the names of %d devices" % len(doneAddresses), doneAddresses
             except bluetooth.btcommon.BluetoothError:
                 #raise bluetooth.btcommon.BluetoothError
                 print "[SCN] bluetooth error"
                 time.sleep(1)
             self.intrf.release(interface=devid, bandwidth=1)
         else:
             #print "[SCN] there are no devices to get its names"
             self.cv.acquire()
             self.cv.wait()
             self.cv.release()
	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
Exemple #10
0
 def discover_devices(self):
   '''Method to discover devices nearby'''
   devices = bluetooth.discover_devices()
   device_info = []
   for dev in devices:
     device_info.append({ 'mac' : dev, 'name' : bluetooth.lookup_name(dev) })
   return device_info
    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
Exemple #12
0
 def _listen_adaptator_lookup(self):
     """
     Listen to bluetooth adaptator. This method use the
     bluetooth.lookup_name(). It takes approcimatively 3 seconds
     to proceed.
     """
     try:
         for aaddr in self._targets:
 #            self.log.debug("_listen_adaptator_lookup : Start \
 #bluetooth.lookup_name at %s" % datetime.datetime.today())
             target_name = bluetooth.lookup_name( aaddr )
 #            self.log.debug("_listen_adaptator_lookup : Stop \
 #bluetooth.lookup_name at %s" % datetime.datetime.today())
             if target_name == None:
                 if self._targets[aaddr]["status"] == HIGH :
                     self._targets[aaddr]["count"] = \
                         self._targets[aaddr]["count"] +1
                     if self._targets[aaddr]["count"] >= \
                         self._hysteresis:
                         self._trig_detect("xpl-trig", aaddr, LOW)
                         self.log.info("bluetooth device %s with address %s is gone" % (target_name, aaddr))
             else:
                 self._targets[aaddr]["count"] = 0
                 if self._targets[aaddr]["status"] == LOW:
                     self._trig_detect("xpl-trig", aaddr, HIGH)
                     self.log.info("Match bluetooth device %s with address %s" % (target_name, aaddr))
         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
	def searchDevices(self):
		"""
			Search for devices
		"""
		self.searchButton.set_sensitive(False)
		print "Scanning for devices..."
		while self.devicesList.get_active() != -1:
			self.devicesList.remove_text(0)
			
		self.textBuffer.insert(self.textBuffer.get_end_iter(), ">> Searching Bluetooth serial ports... ")
		self.searchSpinner.start()
		self.searchSpinner.show()
		try:
			self.services = bluez.find_service(uuid=bluez.SERIAL_PORT_CLASS)
		except Exception as e:
			print "Error, unable to search devices :", e.message[1]
			return

		self.textBuffer.insert(self.textBuffer.get_end_iter(), "found " + str(len(self.services)) + "\n")
		for i in range (len(self.services)):
			print " -> Found", self.services[i]["name"], "at", self.services[i]["host"]
			self.textBuffer.insert(self.textBuffer.get_end_iter(),
				" -> " + self.services[i]["name"] +
				" (" + bluez.lookup_name(self.services[i]["host"], 3)+ ") at " +
				self.services[i]["host"])
			self.devicesList.append_text(self.services[i]["name"])
			self.devicesList.set_active(0)
				

		self.searchSpinner.stop()
		self.searchSpinner.hide()
		self.searchButton.set_sensitive(True)
		if len(self.services) > 0:
			self.connectButton.set_sensitive(True)
Exemple #14
0
def tracker():
	cache={}
	devices={}
	try:
	    while 1:
		nearby_devices = bluetooth.discover_devices()
		cache={}
		for founded_addr in nearby_devices:
			target_name = bluetooth.lookup_name(founded_addr)
			cache[founded_addr]=target_name
			if founded_addr not in devices:
				devices[founded_addr]=target_name
				handler.entry(target_name,founded_addr)
				loginfo("ENTRY","%s: %s"%(target_name,founded_addr))
		
		for k in devices.keys():
			if k not in cache:
				loginfo("QUIT","%s: %s"%(devices.get(k),k))
				handler.quit(devices.get(k),k)
				del devices[k]
		handler.update(devices)
		loginfo("UPDATE","devices: %s"%devices)
		if options.repeat==False:
			loginfo("INFO","quit")
			break
		time.sleep(options.sleeptime);
	except BluetoothError,e:
		print >>sys.stderr, "error: %s"%e
def main():

    if (len(sys.argv) > 1):
        duration = sys.argv[1]
    else:
        duration = 10

    print("Scanning Area")
    MACs = bluetooth.discover_devices(duration, True, False)
    print("Scan Complete")
    print("MAC Address found: ")
    print(MACs)

    deviceNamesArray = []
    x = 0

    for MACAddress in MACs:

        devicename = bluetooth.lookup_name(MACAddress, 20)

        if (devicename == None): #device name cant be found
            print ("Cant find device name for:" + MACAddress)
            devicename = "NameNotFound"

        deviceNamesArray.append(devicename)

    print("Devices found: ")
    print(deviceNamesArray)
    addMACAddress(deviceNamesArray, MACs)
Exemple #16
0
def lg_da():
    result = bluetooth.lookup_name('00:18:6B:B3:5E:04', timeout=3)
    time.sleep(3)
    if (result != None):
        return 1
    else:
        return 0
Exemple #17
0
def plan_da():
    result = bluetooth.lookup_name('48:C1:AC:98:9E:62', timeout=3)
    time.sleep(3)
    if (result != None):
        return 1
    else:
        return 0
Exemple #18
0
def service_connect( deviceName, serviceName ):

	target = find_device_address_by_name(deviceName)
	services = bluetooth.find_service(address=target)

	for svc in services:
		print 'Device Name: %s' % bluetooth.lookup_name(svc['host'])
		print 'Service Name: %s'    % svc['name']
		print '    Host:        %s' % svc['host']
		print '    Description: %s' % svc['description']
		print '    Provided By: %s' % svc['provider']
		print '    Protocol:    %s' % svc['protocol']
		print '    channel/PSM: %s' % svc['port']
		print '    svc classes: %s' % svc['service-classes']
		print '    profiles:    %s' % svc['profiles']
		print '    service id:  %s' % svc['service-id']
		print ''

		if svc['host'] == target and svc['name'] == serviceName:
			print 'Connecting to OBEX File Transfer thingy...'

			protocols = {
				'RFCOMM': bluetooth.RFCOMM,
				'L2CAP': bluetooth.L2CAP
			}

			sock=bluetooth.BluetoothSocket( protocols[svc['protocol']] )
			sock.connect((svc['host'], svc['port']))
			return sock
	
	raise ValueError('Could not find "%s" service on %s' % (
		serviceName,
		deviceName
	))
Exemple #19
0
 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
Exemple #20
0
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
def getNewDevice():
    nearby_devices = bluetooth.discover_devices(duration=getTimeoutDuration())
    print nearby_devices
    for btaddr in nearby_devices:
        if bluetooth.lookup_name(btaddr)==cfg.newDeviceName():
            return btaddr    
    return None
    

 
#    for bdaddr in nearby_devices:
#        print bluetooth.lookup_name(bdaddr)
#    print nearby_devices
#    
#    while(1):
#        server_sock = bluetooth.BluetoothSocket()
#        server_sock.bind(("",3))
#        server_sock.listen(1)
#        client_socket, address = server_sock.accept()
#        
#        time.sleep(1)
    
#    client_sock = bluetooth.BluetoothSocket()
#    client_sock.connect((nearby_devices[0],3))
    
#    client_sock.bind()
    def getBTTransport(self):
        if sys.platform == 'symbian_s60': 
            import btsocket
            sock=btsocket.socket(btsocket.AF_BT,btsocket.SOCK_STREAM)
            addr,services=btsocket.bt_discover()
            if len(services)>0:
                port = services[u'opencoin']
            else:
                port=services[services.keys()[0]]
            address=(addr,port)
            sock.connect(address)
        else:
            import bluetooth as bt
            #evil hack
            appuifw.note(u'Searching for devices','info')
            results = [r for r in bt.find_service() if r['name']==None]
            targets = []
            for result in results:
                targets.append(u'%s' % (bt.lookup_name(result['host'])))
            selected = appuifw.popup_menu(targets,u'Connect to...?')
            
            host = results[selected]['host']
            #port = results[selected]['port']
            port = 3
            print 'host: %s, port: %s' % (host,port)
            sock=bt.BluetoothSocket( bt.RFCOMM )
            sock.connect((host, port))

            



        return transports.BTTransport(sock)
Exemple #23
0
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
    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)
Exemple #25
0
 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
 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
 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
 def getPresence(self):
     """Detects whether the device is near by or not"""
     result = bluetooth.lookup_name(self.address, timeout=25)
     if(result != None):
         return "ON"
     else:
         return "OFF"
Exemple #29
0
def listen_lookup():
    """
    Listen to bluetooth adaptator. This method use the
    bluetooth.lookup_name(). It takes approcimatively 3 seconds
    to proceed.
    """
    try:
        for phon in phones:
            target_name = bluetooth.lookup_name( phon )
            if target_name == None:
                if phones[phon]["status"] == 1 :
                    phones[phon]["count"] = phones[phon]["count"] + 1
                    if phones[phon]["count"] >= hysteresis:
                        phones[phon]["status"] = 0
                        client.emitEvent(ex_bluescan%phon,"event.device.statechanged", "0", "")
                        syslog.syslog(syslog.LOG_DEBUG, "%s has gone"%phon)
            else:
                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_lookup')
        log_exception(error)
 def get_presence(self):
     """Detects whether the device is near by or not using lookup_name"""
     result = bluetooth.lookup_name(self.address, timeout=25)
     if result is not None:
         return "ON"
     else:
         return "OFF"
def lookup_name(mac: str) -> str | None:
    """Lookup a Bluetooth device name."""
    _LOGGER.debug("Scanning %s", mac)
    return bluetooth.lookup_name(mac, timeout=5)  # type: ignore[no-any-return]
Exemple #32
0
            try:
                NearbyDevices = bluetooth.discover_devices()
            except KeyboardInterrupt:
                exit()
            except:
                print(
                    "unable to discover device, check your bluetooth settings")
            print(NearbyDevices)

            # scan through all the available BT devices and if the server MAC is found
            # then connect to the server
            for Address in NearbyDevices:
                # this step is just to get the name of the BT device, it is not used
                # anywhere just for information purpose
                try:
                    name = bluetooth.lookup_name(Address)
                except:
                    print("unable to fetch name")
                print(name, Address, TargetMACAddress)
                # connect to the server if MAC address is found
                if Address == TargetMACAddress:
                    # search for the service broadcasted by server
                    print("Services available with chip server",
                          TargetMACAddress)
                    services = bluetooth.find_service(address=TargetMACAddress)
                    for ser in services:
                        if ser['name'] == "Chip device":
                            print ser  # this display only the service with serial_port
                            # the service addtion we did
                            # check the description portion for the device
                            # address
import bluetooth
import os
import time

devices = bluetooth.discover_devices()

#Searching for HC-05 in the detected devices
hc05_found = False

for device in devices:
    device_name = bluetooth.lookup_name(device)
    if device_name == "HC-05\n":
        hc05_found = True
        break

if not hc05_found:
    print "Required device not found.\nPlease check your connections and try again."
    exit()
else:
    print "Device found.\nRefreshing..."

port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((device, port))
sock.send('r')
print "Refreshing complete."
sock.close()
Exemple #34
0
def lookUpNearbyBluetoothDevices():
	nearby_devices = bluetooth.discover_devices()
	for bdaddr in nearby_devices:
		print str(bluetooth.lookup_name( bdaddr )) + " [" + str(bdaddr) + "]"
Exemple #35
0
import sys
import bluetooth

device_name = None
device_address = None

# Device name may be supplied by user
if len(sys.argv) > 1:
    device_name = sys.argv[1]

# Discover
discovered_devices = bluetooth.discover_devices()

# List of devices found
print "Devices Found:"
for a_device_address in discovered_devices:
    print ">",bluetooth.lookup_name( a_device_address ), a_device_address
    if device_name == bluetooth.lookup_name( a_device_address ):
        device_address = a_device_address
        break

# Report status if device requested
if device_name is not None:
    if device_address is not None:
        print "Found bluetooth device: ", device_name, " with address: ", device_address
    else:
        print "Could not find bluetooth device: ", device_name

# TODO: Add exit code
Exemple #36
0
        self.current_value = None
        self.running = True  #setting the thread running to true

    def run(self):
        global gpsd
        while gpsp.running:
            gpsd.next(
            )  #this will continue to loop and grab EACH set of gpsd info to clear the buffer


if __name__ == '__main__':
    gpsp = GpsPoller()  # create the thread
    try:
        gpsp.start()  # start it up
        while True:
            tom = bluetooth.lookup_name(BEACON.rstrip(), timeout=110)
            if ((tom != None) or (GPIO.input(38))):
                while (GPIO.input(38)):
                    GPIO.output(RELAY1, 0)
                    GPIO.output(RELAY2, 0)
                    GPIO.output(RELAY3, 0)
                    GPIO.output(RELAY4, 0)
                    GPIO.output(RELAY5, 0)
                    GPIO.output(RELAY6, 0)
                    GPIO.output(RELAY7, 0)
                    GPIO.output(RELAY8, 0)
                    bl.set_power(True)
                    time.sleep(10)
                    check = "Key Engaged, " + time.strftime(
                        "%d %b %Y %H:%M:%S", time.localtime()) + ",  " + str(
                            gpsd.fix.latitude) + ",  " + str(
Exemple #37
0
import bluetooth as bt
import time
#######################################################
# Scan
#######################################################
#print(bt.discover_devices())

target_name = "ROBOTIS BT-210"  # target device name
target_address = "B8:63:BC:00:48:C8"
port = 1  # RFCOMM port

nearby_devices = bt.discover_devices()

# scanning for target device
for bdaddr in nearby_devices:
    print(bt.lookup_name(bdaddr))
    if target_name == bt.lookup_name(bdaddr):
        target_address = bdaddr
        break

if target_address is not None:
    print('device found. target address %s' % target_address)
else:
    print('could not find target bluetooth device nearby')

try:
    sock = bt.BluetoothSocket(bt.RFCOMM)
    sock.connect((target_address, port))

    while True:
        try:
Exemple #38
0
import sys
import bluetooth

nearby_devices = bluetooth.discover_devices()
num = 0
print "select devices by entering a number"
for i in nearby_devices:
    num += 1
    print num, ": ", bluetooth.lookup_name(i)

select = input("> ") - 1

##Bluetooth search is over

print "Bluetooth selected: ", bluetooth.lookup_name(nearby_devices[select])

bd_addr = nearby_devices[select]

print(bd_addr)
##connecting to the blue tooth
try:
    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

    sock.connect((bd_addr, 1))
    print("Initial Connection")
except BluetoothError as bt:
    print("Cannot connect to host" + str(bt))
    exit(0)
##Testing out the sending
try:
    sock.send("test")
Exemple #39
0
print("")

# nearby_devices = bluetooth.discover_devices()

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

#selection = int(input("> ")) - 1
#print ("You have selected "+bluetooth.lookup_name(nearby_devices[selection]))
#addr = nearby_devices[selection]
addr = "FC:A8:9B:00:0F:18"
print(addr)
name = bluetooth.lookup_name(addr)

passkey = "1234"  # passkey of the device you want to connect

try:
    port = 1
    socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    socket.connect((addr, port))
except bluetooth.btcommon.BluetoothError as err:
    # Error handler
    pass


def disconnect():
    #Close socket connection to device
    socket.close()
Exemple #40
0
    file.write("""<META HTTP-EQUIV="refresh" CONTENT="15">""")
    file.write("\n")
    file.write("</head>" + "\n")
    file.write("<body>" + "\n")
    file.write("<p>" + line1 + "</p>" + "\n")
    file.write("<p>" + line2 + "</p>" + "\n")
    file.write("<p>" + line3 + "</p>" + "\n")
    file.write("</body>" + "\n" + "</html>")
    file.close()
    return


print "Helloooooooo."
n1 = "name1"
n2 = "name2"
n3 = "name3"
member1 = "00:61:71:BE:24:E5"
tejas = "B4:8B:19:B7:10:21"
nirmala = "C0:EE:FB:42:5A:82"

while True:
    print "Checking " + time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())
    result = bluetooth.lookup_name(member1, timeout=5)
    inoutprint(n1, result, 1)
    result = bluetooth.lookup_name(member2, timeout=5)
    inoutprint(n2, result, 2)
    result = bluetooth.lookup_name(member3, timeout=5)
    inoutprint(n3, result, 3)
    filewrite()
    time.sleep(5)
Exemple #41
0
#!/usr/bin/python

import bluetooth
import time
from lcd_display import lcd

d = lcd()
d.clear()
d.display_string("Who's Home?", 1)

sleep_time = 600

while True:
    string = ''

    result = bluetooth.lookup_name('1C:66:AA:CF:DD:35', timeout=5)
    if (result != None):
        string = string + ' Dad'
    d.display_string(string, 2)

    result = bluetooth.lookup_name('94:3A:F0:63:2D:99', timeout=5)
    if (result != None):
        string = string + ' Mum'
    d.display_string(string, 2)

    result = bluetooth.lookup_name('34:BB:1F:39:DE:12', timeout=5)
    if (result != None):
        string = string + ' Sophie'
    d.display_string(string, 2)

    f = open('whoshome.log', 'a')
Exemple #42
0
        "Please specify the number of the device you want to track: ")

    # extract out the useful info on the desired device for use later
    addr, name = nearby_devices[device_num][0], nearby_devices[device_num][1]

print("The script will now scan for the device %s." % (addr))
print(
    "Feel free to move near and far away from the BeagleBone to see the state change on the LED.\nUse Ctrl+c to exit..."
)

GPIO.setup(led_pin, GPIO.OUT)
while True:
    # Try to gather information from the desired device.
    # We're using two different metrics (readable name and data services)
    # to reduce false negatives.
    state = bluetooth.lookup_name(addr, timeout=20)
    services = bluetooth.find_service(address=addr)
    # Flip the LED pin on or off depending on whether the device is nearby
    if state == None and services == []:
        print("No device detected in range...")
        GPIO.output(led_pin, GPIO.LOW)
    else:
        print("Device detected!")
        GPIO.output(led_pin, GPIO.HIGH)
    # Arbitrary wait time
    time.sleep(1)

#!/usr/bin/python

import bluetooth
import time
Exemple #43
0
	def searchForThinkGearDevices(self):
		
		#self.pushButtonBluetoothSearch.setText('Searching')
		
		mindset_devices = []
		
		if (sys.platform == 'win32'):
			
			for portname in self.enumerateSerialPorts():
				
				if portname not in mindset_devices:
					#portname = self.fullPortName(portname)
					mindset_devices.append(portname)
		
		
		else:
			
			# Bluetooth module doesn't compile properly under Windows
			
			bluetooth_devices = []
			
			#bluetooth_devices = bluetooth.discover_devices( \
				                    #duration=5, \
				                    #flush_cache=True, \
				                    #lookup_names=True)
			
			command = '%s con' % PATH_TO_HCITOOL
			
			output = os.popen(command, 'r')
			
			for line in output.readlines():
				try:
					address = line.split(' ')[2]
				except:
					pass
				else:
					bluetooth_devices.append(address)
			
			for address in bluetooth_devices:
				device_name = bluetooth.lookup_name(address)
				if ((device_name == 'MindSet') and \
				    (address not in mindset_devices)):
					mindset_devices.append(address)
			
			
			if self.DEBUG:
				print "Bluetooth MindSet devices found:",
				print mindset_devices
			
			
			self.comboBoxDeviceSelect.clear()
			
			self.comboBoxDeviceSelect.addItem('MindSet Emulator')
			
			if os.path.exists('/dev/ttyUSB0'):
				self.comboBoxDeviceSelect.addItem('/dev/ttyUSB0')
			if os.path.exists('/dev/ttyUSB1'):
				self.comboBoxDeviceSelect.addItem('/dev/ttyUSB1')
			if os.path.exists('/dev/ttyUSB2'):
				self.comboBoxDeviceSelect.addItem('/dev/ttyUSB2')
			if os.path.exists('/dev/ttyUSB3'):
				self.comboBoxDeviceSelect.addItem('/dev/ttyUSB3')
			if os.path.exists('/dev/ttyUSB4'):
				self.comboBoxDeviceSelect.addItem('/dev/ttyUSB4')
		
		
		for mindset_device in mindset_devices:
			self.comboBoxDeviceSelect.addItem(mindset_device)
Exemple #44
0
import bluetooth
import subprocess

if bluetooth.lookup_name("40:4E:36:4A:04:C4") != None:
    subprocess.call(["/home/student/server/bluetooth/beep"])


import bluetooth

target_name = "FYP_GLOVE"
target_address = None
rfcomm_port = 0

dataLine = []  # make byte array

print("Searching")

nearby_devices = bluetooth.discover_devices()

for bdaddr in nearby_devices:
    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)
    server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

    server_sock.connect((bdaddr, 1))
    print("Accepted connection from ", bdaddr)
    print("Hello World")

    server_sock.send("Hello World")
    # proves loop to take 6 bytes(3 hex numbers) to play midi note
    while 1:
        dataLine.clear
        print("------------------------")
        for num in range(30):
Exemple #46
0
import bluetooth

nearby_devices = bluetooth.discover_devices()

for bdaddr in nearby_devices:
    print(bluetooth.lookup_name(bdaddr))
Exemple #47
0
import bluetooth
import sys, pygame
from pygame.locals import *
pygame.init()

print "Searching for device..."
print ""
device = -1
while 1:
    print "doing pass"
    nearby_devices = bluetooth.discover_devices()
    for i in nearby_devices:
        if bluetooth.lookup_name(i) == "NORMAL":
            device = i
            print "found!"
    if device != -1:
        break
print bluetooth.lookup_name(device), " has been located"
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((device, 1))
pygame.init()
size = width, height = 320, 240

pygame.display.set_mode(size)

keys = pygame.key.get_pressed()

state = ["s", "s"]

while 1:
    for event in pygame.event.get():
Exemple #48
0
- sudo apt-get install bluez
- sudo apt-get install python-bluez

'''

from wia import Wia
import bluetooth
import time

wia = Wia()
wia.access_token = "" # Wia secret key.

print ("Proximity Check")

while True:
    print ("Checking " + time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()))

    nearby_devices = bluetooth.discover_devices()

    result = bluetooth.lookup_name("AA:BB:CC:DD:EE:FF", timeout=3)  # Enter your device MAC address found in mobile settings. [Settings -> about (if on iphone)].
    if (result != None):
        print ("Parent: Present")
        presence = 'Present'
    else:
        print ("Parent: Absent")
        presence = 'Absent'

    wia.Event.publish(name="Parent", data=presence)

    time.sleep(20)
Exemple #49
0
l_step = 1  #------
#-------------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------------
#Look for all Bluetooth devices
#the computer knows about.
print("Searching for devices...")
print("")
#Create an array with all the MAC
#addresses of the detected devices
nearby_devices = bluetooth.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, ": ", bluetooth.lookup_name(i))

#Allow the user to select their Arduino
#bluetooth module. They must have paired
#it before hand.
selection = int(input("> ")) - 1
print("You have selected", bluetooth.lookup_name(nearby_devices[selection]))
bd_addr = nearby_devices[selection]
l = [bd_addr]
print(l)

port = 1
#________________________________________________________________________________________________________________
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr, 1))
sock.send("F")
# ensure Bluetooth address has been provided as an argument
if len(sys.argv) < 2:
    print("Usage: btpl.py <bluetooth address>")
    sys.exit(1)

# get Bluetooth address of target device
BTAddress = sys.argv[1]

# tell user the program is running
print("Identifying device...")

try:
    # display device name, with the first part bold & green
    print("\033[1;32m[OK]\033[0m Device found:",
          bluetooth.lookup_name(BTAddress, timeout=5))

    # run forever
    while True:
        # reset previous status, so screen status is only changed when status changes
        prev_status = status
        # retrieve the current RSSI of the bluetooth device
        rssi = getRSSI()
        # if device is close enough:
        if rssi > (0 - rangeLimit):
            status = "near"
            BTInRange = True
            screenLocked = False
            awayCounter = 0
            if (prev_status == "gone") and not (firstRun):
                os.system(enteredRange)
Exemple #51
0
import bluetooth

target_name = "Galaxy J7"
target_address = None
# 한번에 찾아지지 않을 수 있음
nearby_devices = bluetooth.discover_devices()

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

if target_address is not None:
    print("Target Address:", target_address)
else:
    print("Not found")
Exemple #52
0

def leerComando():
    print 'Sintaxis: <C>'
    print 'Ejemplos: \nR012\nG055\nB255'
    c = raw_input('Ingrese comando:     ')
    return c


#Buscaremos conectarnos con mi dispositivo Bluetooth
miBT = 'IvanBT'
print 'Buscando dispositivos Bluetooth...'
dispositivosCercanos = bluetooth.discover_devices()

for btAddr in dispositivosCercanos:
    if miBT == bluetooth.lookup_name(btAddr):
        miAddr = btAddr
        break

if miAddr is not None:
    print 'Conectando a ' + miBT + '...'
    bt = conectarBT(miAddr)
    print 'Conectado!\n\n'
    try:
        while True:
            bt.send(leerComando())
    except KeyboardInterrupt:
        bt.close()
        print 'Adios!'
else:
    print 'Dispositivo no encontrado :('
Exemple #53
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 = eval(input("Please specify the number of the device you want to track: "))

    # extract out the useful info on the desired device for use later
    addr, name = nearby_devices[device_num][0], nearby_devices[device_num][1]

print(("The script will now scan for the device %s." % (addr)))
print("Feel free to move near and far away from the BeagleBone to see the state change on the LED.\nUse Ctrl+c to exit...")

GPIO.setup(led_pin, GPIO.OUT)
while True:
    # Try to gather information from the desired device.
    # We're using two different metrics (readable name and data services)
    # to reduce false negatives.
    state = bluetooth.lookup_name(addr, timeout=20)
    services = bluetooth.find_service(address=addr)
    # Flip the LED pin on or off depending on whether the device is nearby
    if state == None and services == []:
        print("No device detected in range...")
        GPIO.output(led_pin, GPIO.LOW)
    else:
        print("Device detected!")
        GPIO.output(led_pin, GPIO.HIGH)
    # Arbitrary wait time
    time.sleep(1)
Exemple #54
0
if len(sys.argv) < 2:
    print("usage bluefence.py <btaddr>")
    sys.exit(1)

btAddr = sys.argv[1]
btInRange = True
screenLocked = False
awayCounter = 0

print("Identifying device...")

try:
    # initial check, see if mentioned BT device active. If it's not, clean exit

    btName = bluetooth.lookup_name(btAddr, timeout=5)

    if btName:
        if VERBOSE:
            print('OK: Found your device', btName)

        while True:
            who = bluetooth.lookup_name(btAddr, timeout=2)

            if who:

                status = 'near'
                btInRange = True
                awayCounter = 0
                os.system(IF_BT_BACK)
Exemple #55
0
import home

import sys
from subprocess import call
import time
import bluetooth

call(['sudo', 'hciconfig', 'hci0', 'down'])
call(['sudo', 'hciconfig', 'hci0', 'up'])

home = home.Home()

while True:
    result = bluetooth.lookup_name("8C:1A:BF:92:EC:85", timeout=10)

    home.tick(result != None)

    if (result != None):
        time.sleep(5)
			name = None

                now = int(time.time())
                devices.append({ 'uuid' : uuid, 'name' : name, 'in_last_time' : now, 'out_last_time' : now, 'in_age' : 999, 'out_age' : 0})
                

while True:

    for device in devices:
        uuid = device['uuid']
        name = device['name']
        print('uuid = ' + uuid + " Name = " + name)
        
        if (device['in_age'] > 5):

            result = bluetooth.lookup_name(uuid, timeout=5) 
            if (result != None):  
                device['in'] = 1
                device['in_last_time'] = int(time.time())
                print "IN"
            else:
                device['in'] = 0
                device['out_last_time'] = int(time.time())
                print "OUT"

    
        
        

        now = int(time.time())
        device['out_age'] = now - device['in_last_time']  
Exemple #57
0
def lookUpNearbyBluetoothDevices():
    print("Scanning...")
    nearby_devices = bluetooth.discover_devices()
    for bdaddr in nearby_devices:
        print( str(bluetooth.lookup_name( bdaddr )) + " [" + str(bdaddr) + "]")
Exemple #58
0
IF_BT_BACK = 'xrandr --output eDP1 --brightness 1'  # The command to run when the device is back in range
MAX_MISSED = 3
VERBOSE = True

if len(sys.argv) < 2:
    print("usage bluefence.py <btaddr>")
    sys.exit(1)

btaddr = sys.argv[1]
btInRange = True
screenLocked = False
counter = 0

if VERBOSE:
    print "Identifying device..."
    print bluetooth.lookup_name(btaddr, timeout=10)

try:
    if bluetooth.lookup_name(btaddr, timeout=10):
        if VERBOSE:
            print 'OK: Your device is active.'
    else:
        if VERBOSE:
            print 'Your device is inactive.'
            print 'Activate your device and try again.'
        sys.exit(1)

    identify = bluetooth.lookup_name(btaddr, timeout=5).strip()

    if identify:
        if VERBOSE:
Exemple #59
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'Read battery values of the Samsung Galaxy Buds, Buds+, Buds Live or Buds Pro'
        '[Left, Right, Case (Buds+ or later)]')
    parser.add_argument('mac',
                        metavar='mac-address',
                        type=str,
                        nargs=1,
                        help='MAC-Address of your Buds')
    parser.add_argument('-m',
                        '--monitor',
                        action='store_true',
                        help="Notify on change")
    parser.add_argument('-t',
                        '--monitor-timestamp',
                        action='store_true',
                        help="Notify on change and print timestamps")
    parser.add_argument('-w',
                        '--wearing-status',
                        action='store_true',
                        help="Print wearing status instead")
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help="Print debug information")
    args = parser.parse_args()

    verbose = args.verbose

    if verbose:
        print("Checking device model...")
    islegacy = "Galaxy Buds (" in str(bluetooth.lookup_name(args.mac[0]))

    if verbose:
        print(str(bluetooth.lookup_name(args.mac[0])))
        print("Searching for RFCOMM interface...")

    uuid = ("00001101-0000-1000-8000-00805F9B34FB"
            if not islegacy else "00001102-0000-1000-8000-00805f9b34fd")
    service_matches = bluetooth.find_service(uuid=uuid,
                                             address=str(args.mac[0]))

    port = host = None
    for match in service_matches:
        if match["name"] == b"GEARMANAGER":
            port = match["port"]
            host = match["host"]
            break

    if port is None or host is None:
        print("Couldn't find the proprietary RFCOMM service")
        sys.exit(1)

    if verbose:
        print("RFCOMM interface found. Establishing connection...")

    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    sock.connect((host, port))

    if verbose:
        print("Connected. Waiting for incoming data...")

    try:
        while True:
            data = sock.recv(1024)
            if len(data) == 0:
                break
            if args.wearing_status:
                success = parse_message_wear_status(data, islegacy,
                                                    args.monitor_timestamp)
            else:
                success = parse_message(data, islegacy, args.monitor_timestamp)

            if success and not args.monitor and not args.monitor_timestamp:
                exit(0)

    except IOError:
        pass
#!/usr/bin/python3

import bluetooth

target_name = "CAT S31"
target_address = None

print("scanning for nearby bluetooth devices...")
nearby_devices = bluetooth.discover_devices()

print("checking for " + target_name + " device...")
for device in nearby_devices:
    if bluetooth.lookup_name(device) == target_name:
        target_address = device
        break

if target_address is not None:
    print("found target bluetooth device with address ", target_address)
else:
    print("could not find target bluetooth device nearby")