def __supports_push(self, address): ## # first look in cache ## if not self.__cache == None: device = self.__cache.get(address) if not device == None: if(device.supports_obex() == True): self.__logger.debug("# * Found in cache") return device.get_service() ## # Do a double search with different libraries to ensure support ## # Nokia "OBEX Object Push" # Android "Object Push" ## all_services = bluetooth.find_service(address=address) if not all_services == None: for services in all_services: if not services["name"] == None: #print "%s %s" % (services["name"], services["port"]) if(services["name"].find("Object Push")>=0): return {"host": str(address), "port":services["port"]} services = lightblue.findservices(addr=address, name=None, servicetype=_lightbluecommon.OBEX) if(services != None): for service in services: if not service[2] == None: if(services[2].find("Object Push")>=0): return {"host": str(address), "port":service[1]} return None
def find_pbap_port(device_address): """ Find which bluetooth port PBAP is usning on the device. """ for (_, port, service) in lightblue.findservices(device_address): match = re.search("Phonebook Access", service) if match is not None: return port return None
def run(self): """ run the plugin """ logging.debug(str(self.__class__) + " run()") for target in self._pcc.read_all_without_info(SdpDiscovery.SECTION): try: logging.debug( str(self.__class__) + " Executing SDP browse for target " + target.addr) services = [] for sdp in lightblue.findservices(target.addr): service = SdpService() service.name = sdp[2] service.channel = sdp[1] services.append(service) if services.count > 0: self.result = services self._pcc.add_info(target, SdpDiscovery.SECTION, services) self._pcc.fire_event(SdpDiscovery.EVENT) except IOError: pass
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 services of %d devices using hci%s..." % (len(self.addresses), devid) try: doneAddresses = {} for addr in self.addresses: services = lightblue.findservices(addr) services2 = {} for serv in services: services2[serv[1]] = serv[2] self.knownDevices.setInfo(address=addr, services=services2) doneAddresses[addr] = services2 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 services 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 "there are no devices to get its services" self.cv.acquire() self.cv.wait() self.cv.release()
def __supports_push(self, address): ## # first look in cache ## if not self.__cache == None: device = self.__cache.get(address) if not device == None: if (device.supports_obex() == True): self.__logger.debug("# * Found in cache") return device.get_service() ## # Do a double search with different libraries to ensure support ## # Nokia "OBEX Object Push" # Android "Object Push" ## all_services = bluetooth.find_service(address=address) if not all_services == None: for services in all_services: if not services["name"] == None: #print "%s %s" % (services["name"], services["port"]) if (services["name"].find("Object Push") >= 0): return {"host": str(address), "port": services["port"]} services = lightblue.findservices(addr=address, name=None, servicetype=_lightbluecommon.OBEX) if (services != None): for service in services: if not service[2] == None: if (services[2].find("Object Push") >= 0): return {"host": str(address), "port": service[1]} return None
def _connect_BT(self): """ self._BT_device = lb.selectservice() if self._BT_device: device_address, port, name = self._BT_device self._BT_state.setText(name) self._socket = lb.socket() while 1: try: self._socket.connect((device_address, port)) except: print "faild." break else: break """ try: self._socket = lb.socket() services = lb.findservices(self._BT_ID) port = filter(lambda x: x[2] == u"BTHello", services)[0][1] self._socket.connect((self._BT_ID, port)) self._BT_state.setText("connected") except: print "connect to " + self._BT_ID + "faild." self._BT_state.setText("no connection")
def __init__(self,addr=None): uuid = "0ef0f502-f0ee-46c9-986c-54ed027807fb" if sys.platform == "darwin": service_matches = lightblue.findservices( name = "RFCOMM", addr = addr ) else: service_matches = bluetooth.find_service( uuid = uuid, address = addr ) if len(service_matches) == 0: print "Failed to find Parrot Zik RFCOMM service" self.sock ="" return first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] print "Connecting to \"%s\" on %s" % (name, host) if sys.platform == "darwin": self.sock=lightblue.lightblueSocket( lightblue.RFCOMM ) else: self.sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) self.sock.connect((host, port)) self.sock.send('\x00\x03\x00') data = self.sock.recv(3) self.BatteryLevel = 100 self.BatteryCharging = False print "Connected"
def find_service(name=None, uuid=None, address=None): if address is not None: addresses = [address] else: addresses = discover_devices(lookup_names=False) results = [] for address in addresses: # print "[DEBUG] Browsing services on %s..." % (addr) dresults = lightblue.findservices(addr=address, name=name) for tup in dresults: service = {} # LightBlue performs a service discovery and returns the found # services as a list of (device-address, service-port, # service-name) tuples. service["host"] = tup[0] service["port"] = tup[1] service["name"] = tup[2] # Add extra keys for compatibility with PyBluez API. service["description"] = None service["provider"] = None service["protocol"] = None service["service-classes"] = [] service["profiles"] = [] service["service-id"] = None results.append(service) return results
def service_discover(address): services = lightblue.findservices(addr=address) if len(services) > 0: return services else: return "No Services"
def sdp_scan(self, btid): global btmac global btsdp print "BTID: " + str(btid) + "\n" + btmac[btid] if (platform.system() == "Darwin"): # Lightblue Output: [('00:0D:93:19:C8:68', 10, 'OBEX Object Push')]. Yet to be tested. sdpservices = lightblue.findservices(address=btmac[btid]) else: sdpservices = bluetooth.find_service(address=btmac[btid]) btsdp.append(sdpservices)
def sdp_scan(self, btid): global btmac global btsdp print "BTID: " + str(btid) + "\n" + btmac[btid] if(platform.system()=="Darwin"): # Lightblue Output: [('00:0D:93:19:C8:68', 10, 'OBEX Object Push')]. Yet to be tested. sdpservices = lightblue.findservices(address=btmac[btid]) else: sdpservices = bluetooth.find_service(address=btmac[btid]) btsdp.append(sdpservices)
def enumerate_services(device): print("Find services on device: %s" % device) if usingBluetooth: services = bluetooth.find_service(bdaddr=device) # name ? if usingLightBlue: services = lightblue.findservices(device) print(services) return services
def get_channel(self, device): # If we already have the device in the DB the bluetooth channel never change, so I use it from DB (no findservices required) channel = self.db.get_channel(device) if (channel): return channel else: services = lightblue.findservices(device) # Regular expression to get the obex push channel for service in services: if (service[2] != None): service_name = service[2] if (re.search("^obex.*push$|^.*objetos obex$", service_name.lower())): return service[1] # Return the channel # We didn't find the obex push channel, so I can't send to this device return None
def showservices(self, address): self.__items = [] self._controller.clear() if address is None: return services = self._sessioncache.get(address) if not services: import lightblue services = lightblue.findservices(address) #services = [("", 1, "one"), ("", 2, "two"), ("", 3, "three")] self._sessioncache[address] = services if len(services) > 0: for service in services: self._additem(service)
def connect(): logger.debug("Connect!") mac = get_parrot_zik_mac() logger.debug("MAC: {}".format(mac)) if sys.platform == "darwin": service_matches = lightblue.findservices(name="Parrot RFcomm service", addr=mac) else: uuids = [ "0ef0f502-f0ee-46c9-986c-54ed027807fb", "8B6814D3-6CE7-4498-9700-9312C1711F63", "8B6814D3-6CE7-4498-9700-9312C1711F64" ] service_matches = [] for uuid in uuids: try: logger.debug("finding service %s %s", uuid, mac) service_matches = bluetooth.find_service(uuid=uuid, address=mac) except bluetooth.btcommon.BluetoothError as e: logger.exception(e) if service_matches: break logger.debug("Service match: %s", service_matches) if len(service_matches) == 0: raise ConnectionFailure first_match = service_matches[0] if sys.platform == "darwin": host = first_match[0] port = first_match[1] sock = lightblue.socket() else: port = first_match["port"] host = first_match["host"] sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) try: sock.connect((host, port)) except bluetooth.btcommon.BluetoothError: raise ConnectionFailure sock.send('\x00\x03\x00') sock.recv(1024) return GenericResourceManager(sock)
def findObexPort(self, address): if USE_PYBLUEZ: services = bluetooth.find_service(address=address, name="OBEX File Transfer") # Windows (Widcomm) seems to ignore the name argument... for service in services: if service["name"] == "OBEX File Transfer": return service["port"] return None elif USE_LIGHTBLUE: services = lightblue.findservices(addr=address, name="OBEX File Transfer") if service: return services[0][1] else: return None else: return None
def attack(): try: print "Searching nearby devices....\n" near_by_devices = bluetooth.discover_devices() for bdaddr in near_by_devices: print bluetooth.lookup_name(bdaddr) print "\n" if target_name == bluetooth.lookup_name(bdaddr): print "Found the target device" target_addr = bdaddr print target_addr print "\n" break print "Searching services available in target device " services = lightblue.findservices(target_addr) print services print "\n" for service in services: if service[2] == "OBEX Object Push": obex_port = service[1] print "OK, service '", service[2], "' is in port", service[ 1], "!" break #To send and receive files over OBEX: f = 1 while f == 1: print "Sending a file... " try: #print file_to_send lightblue.obex.sendfile(target_addr, service[1], file_to_send) print "*** Hit crtl+z to stop ***" time.sleep(2) print "completed!\n" f = 0 except: print "An error occured while sending \n" print "*** Hit crtl+z to stop ***" except: print "Not paired or discoverbale mode"
def __init__(self, addr=None): uuid = "" # Not used ... if sys.platform == "darwin": service_matches = lightblue.findservices( name="Parrot RFcomm service", addr=addr) else: service_matches = bluetooth.find_service( name="Parrot RFcomm service", address=addr) if len(service_matches) == 0: print "Failed to find Parrot Zik RFCOMM service" self.sock = "" return if sys.platform == "darwin": first_match = service_matches[0] port = first_match[1] name = first_match[2] host = first_match[0] else: first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] print "Connecting to \"%s\" on %s" % (name, host) if sys.platform == "darwin": self.sock = lightblue.socket() else: self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) self.sock.connect((host, port)) self.sock.send('\x00\x03\x00') data = self.sock.recv(1024) self.BatteryLevel = 100 self.BatteryCharging = False print "Connected"
def __init__(self,addr=None): uuid = "" # Not used ... if sys.platform == "darwin": service_matches = lightblue.findservices( name = "Parrot RFcomm service", addr = addr ) else: service_matches = bluetooth.find_service(name = "Parrot RFcomm service", address = addr ) if len(service_matches) == 0: print "Failed to find Parrot Zik RFCOMM service" self.sock ="" return if sys.platform == "darwin": first_match = service_matches[0] port = first_match[1] name = first_match[2] host = first_match[0] else: first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] print "Connecting to \"%s\" on %s" % (name, host) if sys.platform == "darwin": self.sock=lightblue.socket() else: self.sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) self.sock.connect((host, port)) self.sock.send('\x00\x03\x00') data = self.sock.recv(1024) self.BatteryLevel = 100 self.BatteryCharging = False print "Connected"
def prati_fajl(self,ured,vcard=False): """Го праќа фајлот преку Obex Object Push""" servisi = lightblue.findservices(addr=ured,servicetype=lightblue.OBEX) port = '' for servis in servisi: if servis[2]=='OBEX Object Push': port = servis[1] break if not port: logging.debug("Uredov %s nema OBEX Object push. Ne mu prativ nishto" % ured) return False # ako nema Obex Object push if vcard: fajl = self.vcard_fajl else: fajl = self.random_slika() client = lightblue.obex.OBEXClient(ured,port) fobj = file(fajl,'rb') headers = {"name":os.path.basename(fajl), "length":os.stat(fajl).st_size, "type":mimetypes.guess_type(fajl)[0] } try: client.connect() # kolku sekundi da cheka dur prakja slikata nekoj da mu go odbie ili prifati client._OBEXClient__client.timeout=30 resp = client.put(headers,fobj) if resp.code != lightblue.obex.OK: raise lightblue.obex.OBEXError("Uredot me odbi") except lightblue.obex.OBEXError, e: logging.error("Ne uspeav da mu pratam na %s. Greshkata: %s" % (ured,str(e)))
def connect(): mac = get_parrot_zik_mac() if sys.platform == "darwin": service_matches = lightblue.findservices( name="Parrot RFcomm service", addr=mac) else: uuids = ["0ef0f502-f0ee-46c9-986c-54ed027807fb", "8B6814D3-6CE7-4498-9700-9312C1711F63", "8B6814D3-6CE7-4498-9700-9312C1711F64"] service_matches = [] for uuid in uuids: try: service_matches = bluetooth.find_service(uuid=uuid, address=mac) except bluetooth.btcommon.BluetoothError: pass if service_matches: break if len(service_matches) == 0: raise ConnectionFailure first_match = service_matches[0] if sys.platform == "darwin": host = first_match[0] port = first_match[1] sock = lightblue.socket() else: port = first_match["port"] host = first_match["host"] sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) try: sock.connect((host, port)) except bluetooth.btcommon.BluetoothError: raise ConnectionFailure sock.send('\x00\x03\x00') sock.recv(1024) return GenericResourceManager(sock)
def scan(self): """ Scans the devices and returns a list of (id, friendlyname, obexchannel) tuples. """ transfer_services = ['OBEX Object Push', 'OBEX File Transfer'] results = [] for (devid, devname, classid) in lightblue.finddevices(): try: device = Device.objects.get(device_id = devid) if device.obexchannel != -1: results.append( (devid, devname, device.obexchannel) ) continue # already scanned this one, go on with next --> assumes person has not turned it off! except Device.DoesNotExist: pass services = lightblue.findservices(devid) for (did, obexchannel, srvname) in services: if srvname in transfer_services: results.append( (devid, devname, obexchannel) ) break return results
def run(self): """ run the plugin """ logging.debug(str(self.__class__) + " run()") for target in self._pcc.read_all_without_info(SdpDiscovery.SECTION): try: logging.debug(str(self.__class__) + " Executing SDP browse for target " + target.addr) services = [] for sdp in lightblue.findservices(target.addr): service = SdpService() service.name = sdp[2] service.channel = sdp[1] services.append(service) if services.count > 0: self.result = services self._pcc.add_info(target, SdpDiscovery.SECTION, services) self._pcc.fire_event(SdpDiscovery.EVENT) except IOError: pass
continue print target_name obex_port = None target_address = None print "searching for nearby devices..." nearby_devices = bluetooth.discover_devices() print nearby_devices for bdaddr in nearby_devices: if target_name == bluetooth.lookup_name(bdaddr): target_address = bdaddr break print "searching for the object push service..." print target_address services = lightblue.findservices(None) # print services for service in services: if service[2] == "OBEX Object Push" and service[ 0] == target_address: obex_port = service[1] print "OK, service '", service[2], "' is in port", service[ 1], "!" break elif service[2] == "OPP" and service[0] == target_address: obex_port = service[1] print "OK, service '", service[2], "' is in port", service[ 1], "!" break while True:
def process_devices(device_list, loc): """ This function gets a list of discovered devices and gets it ready for storing on the database. The services discovering happens here. """ global debug global verbose global threadbreak global flag_gps global flag_internet global flag_sound global list_devices global queue_devices location_gps = "" location_address = "" ftime = "" #this flag will help us identify if we found a new device or we already seen the device before. #with this we can play different sounds. flag_new_device = False try: if device_list: if debug: print '# In process_devices(device_list,loc) function' print '# device_list len={}'.format(len(device_list)) print '# loc={}'.format(loc) # We process all devices retrieved in one run of the discovery function for d in device_list: flag_new_device = False try: #if the device is on list devices, then we already see it. list_devices[d[0]] flag_new_device = False except: #if the device is not in the list is a new device list_devices[d[0]] = d[1] flag_new_device = True if debug: print 'New device found' # We setup the timestamp ftime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # We get location's related information if flag_gps: if debug: print "# flag_gps={}".format(flag_gps) try: location_gps = str(loc.get('lat')) + "," + str( loc.get('lon')) if debug: print "# location_gps={}".format(location_gps) if flag_internet: location_address = get_address_from_gps( location_gps) if debug: print "# location_address={}".format( location_gps) except: location_address = "" if debug: print "# location_address={}".format(location_gps) else: if loc: location_gps = loc if debug: print "# flag_gps={}".format(flag_gps) print "# location_gps={}".format(location_gps) if flag_internet: location_address = get_address_from_gps( location_gps) if debug: print "# location_address={}".format( location_gps) # We try to lookup more information about the device device_services = [] if flag_lookup_services: if debug: print '# flag_lookup_services={}'.format( flag_lookup_services) try: services_data = lightblue.findservices(d[0]) except: print 'Exception in process_devices, lightblue.findservices(d[0])' services_data = [] if services_data: for i in services_data: device_services.append(i[2]) if len(device_services) > 1: print ' {:<24} {:<17} {:<30} {:<27} {:<30} {:<20}'.format( ftime, d[0], d[1], location_gps, location_address.split(',')[0], device_services[0]) for service in device_services[1:]: print ' {:<24} {:<17} {:<30} {:<27} {:<30} {:<20}'.format( '', '', '', '', '', service) #print '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{:<30}'.format(service) else: print ' {:<24} {:<17} {:<30} {:<27} {:<30} {:<20}'.format( ftime, d[0], d[1], location_gps, location_address.split(',')[0], device_services) if flag_sound: if flag_new_device: pygame.mixer.music.load('new.ogg') pygame.mixer.music.play() else: pygame.mixer.music.load('old.ogg') pygame.mixer.music.play() queue_devices.put([ ftime, d[0], d[1], location_gps, location_address, device_services ]) if debug: print 'Data loaded to queue' # no devices? except KeyboardInterrupt: print 'Exiting. It may take a few seconds.' threadbreak = True except Exception as inst: print 'Exception in process_devices() function' threadbreak = True print 'Ending threads, exiting when finished' print type(inst) # the exception instance print inst.args # arguments stored in .args print inst # _str_ allows args to printed directly x, y = inst # _getitem_ allows args to be unpacked directly print 'x =', x print 'y =', y sys.exit(1)
def sendFile(self, parent, device, file): if self.main == None: return try: assert device.bluetoothAddress() except: message = QMessageBox.critical(parent, self.tr("File transfer failed!"), self.tr("""File transer failed!\n No device was specified!\n You have to send the file %1 in the folder mobile manuelly to your mobile phone!""").arg(file), QMessageBox.StandardButtons(\ QMessageBox.Ok), QMessageBox.Ok) return found = False path = self.findFolder(file, "mobile") if path == None: message = QMessageBox.critical(parent, self.tr("Can't find file!"), self.tr("""The file %1 couldn't be found!\n If you're using the SVN version of the application you have to create the file yourself\n If you downloaded a pre-built package please report the error to [email protected] !""").arg(file), QMessageBox.StandardButtons(\ QMessageBox.Ok), QMessageBox.Ok) return port = 11 try: if USE_PYBLUEZ: services = bluetooth.find_service(address=address, name="OBEX File Transfer") # Windows (Widcomm) seems to ignore the name argument... for service in services: if service["name"] == "OBEX File Transfer": port = service["port"] elif USE_LIGHTBLUE: services = lightblue.findservices(addr=address, name="OBEX File Transfer") if service: port = services[0][1] except: pass self.log.info(QString("Sending file %1 to host %2 on port %3").arg(path).arg(device.bluetoothAddress()).arg(port)) errormsg = None client = lib.obex_wrapper.ObexClient(device.bluetoothAddress(), port) try: ret = client.connect() except BluetoothError, msg: try: error = eval(str(msg)) # Doesn't work on Windows, why? errormsg = error[1] errormsg = unicode(errormsg, "utf8") except: errormsg = "None"
target_name = raw_input() print("enter file name to send with path") file_to_send = raw_input() for bdaddr in nearby_devices: #print(bluetooth.lookup_name(bdaddr)) if (target_name == bluetooth.lookup_name(bdaddr)): print("found the target device !!") target_address = bdaddr print(target_address) break #target_address = "48:D2:24:61:A6:4D" print("searching for the object push service") services = lightblue.findservices(target_address) #print("till here connected") #services = lightblue.findservices(addr=lightblue.selectdevice()[0],servicetype=lightblue.OBEX) #services = lightblue.findservices(addr=target_address,servicetype=lightblue.OBEX) #address, serviceport, servicename = lightblue.selectservice() #lightblue.obex.sendfile(address, serviceport, file_to_send) for service in services: if (service[2] == "OBEX Object Push"): obex_port = service[1] print("ok service '", service[2], "' is in port", service[1], "!") break print("sending a file")
def _find_service(): for addr, port, service in lightblue.findservices(name=SERVICE): yield addr, port, lightblue.finddevicename(addr)
continue print target_name obex_port = None target_address = None print "searching for nearby devices..." nearby_devices = bluetooth.discover_devices() print nearby_devices for bdaddr in nearby_devices: if target_name == bluetooth.lookup_name(bdaddr): target_address = bdaddr break print "searching for the object push service..." print target_address services = lightblue.findservices(None) # print services for service in services: if service[2] == "OBEX Object Push" and service[0] == target_address: obex_port = service[1] print "OK, service '", service[2], "' is in port", service[1], "!" break elif service[2] == "OPP" and service[0] == target_address: obex_port = service[1] print "OK, service '", service[2], "' is in port", service[1], "!" break while True: if os.path.exists("/home/pi/Desktop/receipts/receipt.jpg"): print "sending a file..." if target_address:
print "Error looking up devices: %s" % e return phones = [] for device in allDevices: print device foo, isPhone, bar = self.splitclass(device[2]) # TODO # This needs to be changed back to "2" after my Android testing # is done if ((isPhone == 2) or (isPhone == 1)): phones.append(device) for phone in phones: log.write("Looking at phone %s" % str(phone)) services = lightblue.findservices(phone[0]) port = None for service in services: if service[2] is not None and service[2] == 'FluidNexus': port = service[1] break else: port = None log.write("at end of service search") if port is not None: print "before server" serverMessageHashes = self.getServerMessageHashes(services) print "before our" ourMessageHashes = self.getOurMessageHashes() print "before not our"
# we don't know yet obex_port = None target_address = None print "serching for near by devices... !" nearby_devices = bluetooth.discover_devices() for bdaddr in nearby_devices: print bluetooth.lookup_name( bdaddr ) if target_name == bluetooth.lookup_name( bdaddr ): print "found the target device!" target_address = bdaddr break print "searching for the object push service ..." services = lightblue.findservices(target_address) for service in services: if service[2] == "OBEX Object Push": obex_port = service[1] print "OK, service'",service[2],"'is in port", service[1], "!" break print "sending a file..." try: print "trying..." lightblue.obex.sendfile( target_address, service[1], file_to_send ) print "completed! \n" except: print "an error occurred while sending file \n"
def process_devices(device_list): global debug global verbose global threadbreak global flag_gps global flag_internet global flag_sound global global_location global list_devices global queue_devices global flag_fake_gps location_gps = "NO GPS INFORMATION" location_address = "NO ADDRESS RETRIEVED" ftime = "" flag_new_device = False try: if device_list: for d in device_list: flag_new_device = False try: list_devices[d[0]] flag_new_device = False except: list_devices[d[0]]=d[1] flag_new_device = True if debug: print 'New device found' #ftime = time.asctime() ftime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) # We get location's related information if flag_gps: if flag_internet: [location_gps,location_address] = get_address_from_gps(global_location) if flag_fake_gps and location_gps == "": try: float(global_location.split(',')[1]) float(global_location.split(',')[2]) location_gps = global_location except ValueError: location_gps = 'GPS NOT ACTIVE' location_address = global_location elif flag_fake_gps: try: float(global_location.split(',')[1]) float(global_location.split(',')[2]) location_gps = global_location except ValueError: location_gps = 'GPS NOT ACTIVE' location_address = global_location # We try to lookup more information about the device device_services = [] if flag_lookup_services: services_data = lightblue.findservices(d[0]) if services_data: for i in services_data: device_services.append(i[2]) if len(device_services) > 1: print print ' {:<24} {:<17} {:<30} {:<27} {:<30} {:<20}'.format(ftime,d[0],d[1],location_gps,location_address.split(',')[0],device_services[0]) for service in device_services[1:]: print ' {:<24} {:<17} {:<30} {:<27} {:<30} {:<20}'.format('','','','','',service) #print '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{:<30}'.format(service) else: print print ' {:<24} {:<17} {:<30} {:<27} {:<30} {:<20}'.format(ftime,d[0],d[1],location_gps,location_address.split(',')[0],device_services) if flag_sound: if flag_new_device: pygame.mixer.music.load('new.ogg') pygame.mixer.music.play() else: pygame.mixer.music.load('old.ogg') pygame.mixer.music.play() queue_devices.put([ftime,d[0],d[1],location_gps,location_address,device_services]) if debug: print 'Data loaded to queue' time.sleep(0.5) except KeyboardInterrupt: print 'Exiting. It may take a few seconds.' threadbreak = True except Exception as inst: print 'Exception in process_devices() function' threadbreak = True print 'Ending threads, exiting when finished' print type(inst) # the exception instance print inst.args # arguments stored in .args print inst # _str_ allows args to printed directly x, y = inst # _getitem_ allows args to be unpacked directly print 'x =', x print 'y =', y sys.exit(1)
def process_devices(device_list,loc): """ This function gets a list of discovered devices and gets it ready for storing on the database. The services discovering happens here. """ global debug global verbose global threadbreak global flag_gps global flag_internet global flag_sound global list_devices global queue_devices location_gps = "" location_address = "" ftime = "" #this flag will help us identify if we found a new device or we already seen the device before. #with this we can play different sounds. flag_new_device = False try: if device_list: if debug: print '# In process_devices(device_list,loc) function' print '# device_list len={}'.format(len(device_list)) print '# loc={}'.format(loc) # We process all devices retrieved in one run of the discovery function for d in device_list: flag_new_device = False try: #if the device is on list devices, then we already see it. list_devices[d[0]] flag_new_device = False except: #if the device is not in the list is a new device list_devices[d[0]]=d[1] flag_new_device = True if debug: print 'New device found' # We setup the timestamp ftime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) # We get location's related information if flag_gps: if debug: print "# flag_gps={}".format(flag_gps) try: location_gps = str(loc.get('lat'))+","+str(loc.get('lon')) if debug: print "# location_gps={}".format(location_gps) if flag_internet: location_address = get_address_from_gps(location_gps) if debug: print "# location_address={}".format(location_gps) except: location_address="" if debug: print "# location_address={}".format(location_gps) else: if loc: location_gps=loc if debug: print "# flag_gps={}".format(flag_gps) print "# location_gps={}".format(location_gps) if flag_internet: location_address = get_address_from_gps(location_gps) if debug: print "# location_address={}".format(location_gps) # We try to lookup more information about the device device_services = [] if flag_lookup_services: if debug: print '# flag_lookup_services={}'.format(flag_lookup_services) try: services_data = lightblue.findservices(d[0]) except: print 'Exception in process_devices, lightblue.findservices(d[0])' services_data=[] if services_data: for i in services_data: device_services.append(i[2]) if len(device_services) > 1: print ' {:<24} {:<17} {:<30} {:<27} {:<30} {:<20}'.format(ftime,d[0],d[1],location_gps,location_address.split(',')[0],device_services[0]) for service in device_services[1:]: print ' {:<24} {:<17} {:<30} {:<27} {:<30} {:<20}'.format('','','','','',service) #print '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{:<30}'.format(service) else: print ' {:<24} {:<17} {:<30} {:<27} {:<30} {:<20}'.format(ftime,d[0],d[1],location_gps,location_address.split(',')[0],device_services) if flag_sound: if flag_new_device: pygame.mixer.music.load('new.ogg') pygame.mixer.music.play() else: pygame.mixer.music.load('old.ogg') pygame.mixer.music.play() queue_devices.put([ftime,d[0],d[1],location_gps,location_address,device_services]) if debug: print 'Data loaded to queue' # no devices? except KeyboardInterrupt: print 'Exiting. It may take a few seconds.' threadbreak = True except Exception as inst: print 'Exception in process_devices() function' threadbreak = True print 'Ending threads, exiting when finished' print type(inst) # the exception instance print inst.args # arguments stored in .args print inst # _str_ allows args to printed directly x, y = inst # _getitem_ allows args to be unpacked directly print 'x =', x print 'y =', y sys.exit(1)
def sendFile(self, parent, device, file): if self.main == None: return try: assert device.bluetoothAddress() except: message = QMessageBox.critical(parent, self.tr("File transfer failed!"), self.tr("""File transer failed!\n No device was specified!\n You have to send the file %1 in the folder mobile manuelly to your mobile phone!""").arg(file), QMessageBox.StandardButtons(\ QMessageBox.Ok), QMessageBox.Ok) return found = False path = self.findFolder(file, "mobile") if path == None: message = QMessageBox.critical(parent, self.tr("Can't find file!"), self.tr("""The file %1 couldn't be found!\n If you're using the SVN version of the application you have to create the file yourself\n If you downloaded a pre-built package please report the error to [email protected] !""").arg(file), QMessageBox.StandardButtons(\ QMessageBox.Ok), QMessageBox.Ok) return port = 11 try: if USE_PYBLUEZ: services = bluetooth.find_service(address=address, name="OBEX File Transfer") # Windows (Widcomm) seems to ignore the name argument... for service in services: if service["name"] == "OBEX File Transfer": port = service["port"] elif USE_LIGHTBLUE: services = lightblue.findservices(addr=address, name="OBEX File Transfer") if service: port = services[0][1] except: pass self.log.info( QString("Sending file %1 to host %2 on port %3").arg(path).arg( device.bluetoothAddress()).arg(port)) errormsg = None client = lib.obex_wrapper.ObexClient(device.bluetoothAddress(), port) try: ret = client.connect() except BluetoothError, msg: try: error = eval(str(msg)) # Doesn't work on Windows, why? errormsg = error[1] errormsg = unicode(errormsg, "utf8") except: errormsg = "None"
import lightblue hostaddr = lightblue.selectdevice()[0] service = lightblue.findservices(addr=hostaddr, name='Wireless iAP')[0] print 'service:', service serviceport = service[1] s = lightblue.socket() s.connect((hostaddr, serviceport)) d = "\xFF\x55\x02\x00\xEE\x10" print "Send data:", d.encode('hex') s.send(d) data = s.recv(1024) print "Got data:", data.encode('hex') s.close()
""" Shows how to send "Hello world" over a RFCOMM client socket. """ import lightblue # ask user to choose the device to connect to hostaddr = lightblue.selectdevice()[0] # find the EchoService advertised by the simple_server.py example echoservice = lightblue.findservices(addr=hostaddr, name="EchoService")[0] serviceport = echoservice[1] s = lightblue.socket() s.connect((hostaddr, serviceport)) s.send("Hello world!") print "Sent data, waiting for echo..." data = s.recv(1024) print "Got data:", data s.close() # Note: # Instead of calling selectdevice() and findservices(), you could do: # hostaddr, serviceport, servicename = lightblue.selectservice() # to ask the user to choose a service (instead of just choosing the device).