def ble_find(pipe0, pipe1): i = 0 while True: if i == 0: service_matches = bluetooth.find_service( address="00:1B:10:F1:FB:D4") while len(service_matches) == 0: service_matches = bluetooth.find_service( address="00:1B:10:F1:FB:D4") time.sleep(0.5) print "find ok" i = 1 pipe0.send(1) #扫描到会向数据处理程序发送信号,提示可以进行蓝牙连接 print "send ok" if i == 1: #在没有收到信号时 rlist, wlist, elist = select.select( [ pipe0, pipe1, ], [], [], ) for fd in rlist: if fd == pipe0: i = pipe0.recv() print "A" if fd == pipe1: i = pipe1.recv() print "B"
def run(self): print('Start send sms') if self.sms is None or self.sms.is_empty(): print('Missing required argument sms, or not sms is empty') self.done.emit() self.terminate() return address = self.sms.device.host dun_port = 0 services = bluetooth.find_service(address=address) # for service in services: # if service["name"] == "Dial-up Networking": # dun_port = service["port"] # print("BT Profile: %s" % service["name"]) # print(" Host: %s" % service["host"]) # print(" Description: %s" % service["description"]) # print(" Provided By: %s" % service["provider"]) # print(" Protocol: %s" % service["protocol"]) # print(" channel/PSM: %s" % service["port"]) # print(" service classes: %s " % service["service-classes"]) # print(" profiles: %s " % service["profiles"]) # print(" service id: %s " % service["service-id"]) dial_up = bluetooth.find_service(address=address, uuid=bluetooth.DIALUP_NET_CLASS) if len(dial_up): dun_port = dial_up[0]['port'] if dun_port is 0: self.error.emit(self.NO_SERVICE_FOUND) self.done.emit() self.terminate() return socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) connection = socket.connect((address, dun_port)) socket.send("AT\r") print(socket.recv(1024)) socket.send("AT+CMGF=1\r") print(socket.recv(1024)) socket.send('AT+CMGS="' + self.sms.to_phone + '"\r') print(socket.recv(1024)) socket.send(self.sms.message + chr(26)) print(socket.recv(1024)) print(socket.recv(1024)) socket.close() self.sms.complete = True self.done.emit()
def bluetooth(): service_matches = bluetooth.find_service(address="00:1B:10:F1:FB:D4") while len(service_matches) == 0: print "couldn't find the FooBar service" service_matches = bluetooth.find_service(address="00:1B:10:F1:FB:D4") time.sleep(1) first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] print "connecting to \"%s\" on %s port:%s" % (name, host, port) return port
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")
def services(): ''' Modulo para descubrir los servicios de un dispositivo ''' print 'Give me an address bluetooth' addr = raw_input('>> ') target = addr try: services = bluetooth.find_service(address=target) except: services = '' if len(services) > 0: print '[!] Found %d services on %s\n' % (len(services),target) else: print 'No services found' return print '---------------------------------------------------' for svc in services: 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 '' print '---------------------------------------------------'
def run(self): while True: info = self._person_info_queue.get() if isinstance(info, str): message = json.dumps({'umanPersonID': info}) else: message = json.dumps({ 'umanPersonID': ', '.join(info['umanPersonID']), 'givenName': ', '.join(info['givenName']), 'sn': ', '.join(info['sn']), 'mail': ', '.join(info['mail']), 'ou': ', '.join(info['ou']), 'employeeType': ', '.join(info['employeeType']) }) _logger.info('Sending: %s', message) try: service_matches = bluetooth.find_service(uuid=SWIPE_UP_UUID, address=self._address) if service_matches: first_match = service_matches[0] if service_matches: socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) socket.connect((first_match["host"], first_match["port"])) socket.send(message + '\n') socket.close() time.sleep(1) else: _logger.error('Could not find service.') else: _logger.error('Service not found.') except Exception as e: _logger.error("Failed to request signature from SwipeUp: %s", e) else: _logger.debug("Request for signature made to SwipeUp: %s", message) self._person_info_queue.task_done()
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 ))
def connect(self, address): services = bluetooth.find_service(uuid = '1101', address = address) port = services[0]["port"] name = services[0]["name"] host = services[0]["host"] self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) self.socket.connect((host, port))
def findSerialDevices(self): devices = bluetooth.discover_devices(duration=5, lookup_names=False, flush_cache=True) serialDevices = [] for address in devices: services = bluetooth.find_service(uuid=bluetooth.SERIAL_PORT_CLASS, address=address) services.extend(bluetooth.find_service(uuid=bluetooth.DIALUP_NET_CLASS)) for service in services: serialDevices.append( BluetoothDevice( service["host"], service["port"], bluetooth.lookup_name(service["host"]), service["name"] ) ) return serialDevices
def run(self): self.device.updating = True services = [] while len(services) is 0 and self.retry > 0: services = bluetooth.find_service(address=self.device.host) if len(services) > 0: self.retry = 0 if len(services) is 0: print('No services found for device, stop connect') self.device.updating = False self.error.emit(self.NO_SERVICE_FOUND) self.done.emit() return a = json.dumps(services) self.device.services = services # If device not yet know it's manufacturer it's first connect if len(self.device.vendor) == 0: pnp_info_service = self.device.get_service_by_name('PnPInformation') if pnp_info_service: print('PnpService found') self.device.updating = False
def lookUpForDUN(self): # Look up for services offerted by the mobile device choosed services = bluetooth.find_service(address=self.address) # Sometimes there's no services offerted, so we need to know that if len(services) > 0: self.info = self.tr('Please wait ...\n') self.info += self.tr( 'Looking for Dial-up networking service...\n\n') for service in services: # The service name can be found in three ways name = service["name"] if name == "Dial-up networking" or name == "Dial-Up Networking" or name == "Dial-up Networking": # Store the port self.channel = service["port"] self.info += self.tr( "Found Dial-up networking at channel ") self.info += self.channel message_title = self.tr("Information") QMessageBox.information(self, message_title, self.info) break else: error = self.tr( "No available services\nTry another device, please.") message_title = self.tr("Error message") QMessageBox.critical(self, message_title, error) return # There's no Dial-up networking if self.channel == 0: error = self.tr( "No Dial-up networking service detected!\nTry another device, please." ) message_title = self.tr("Error message") QMessageBox.critical(self, message_title, error) return
def sdpbrowse(macid=None): # this function determines the available service profiles at the specified bluetooth macid. target = macid print "Determining service profiles at " + str(target) if target == "all": target = None services = bluetooth.find_service(address=target) if len(services) > 0: print ("found %d services on %s" % (len(services), target)) print () else: print ("no services found") for svc in services: 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 ()
def find_bluetooth_services(self): services = bluetooth.find_service(address=self.bluetooth_address) if len(services) > 0: print("found %d services on %s" % (len(services), self.bluetooth_address)) print(services) else: print("no services found")
def is_phone_present(phone, service=HEADSET): try: phone_present = len(bluetooth.find_service(address=phone, name=service)) except Exception as e: phone_present = 0 print("Got exception %s in is_phone_present() - ignoring" % e) return phone_present > 0
def scan_services(): print("Scanning for bluetooth devices: ") devices = bluetooth.discover_devices(lookup_names=True) number_of_devices = len(devices) print(number_of_devices, "devices found") for addr, name in devices: print("\n") print("Device Name: %s" % (name)) print("Device MAC Address: %s" % (addr)) print("Services Found:") services = bluetooth.find_service(address=addr) if len(services) <= 0: print("zero services found on", addr) else: for serv in services: print(serv['name']) print("\n") return
def main(text): vals = [] for t in text: try: pat = character_map[t] vals.append(pat) except ValueError: print( 'VAlue %s, not recognized' %t) raise service_matches = bluetooth.find_service(uuid=uuid, address=serverMACAddress) if len(service_matches) == 0: print("Couldn't find the SampleServer service.") sys.exit(0) first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] print(first_match) s = bluetooth.BluetoothSocket(bluetooth.RFCOMM) s.connect((serverMACAddress, port)) s.send(bytes([len(vals)] + vals))
def start_client(): print("Starting Client...") service_matches = bluetooth.find_service(uuid=uuid, address=None) if len(service_matches) == 0: print("Couldn't find the SampleServer service.") sys.exit(0) first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] print("Connecting to \"{}\" on {}".format(name, host)) # Create the client socket sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) sock.connect((host, port)) print("Connected. Type something...") while True: data = input() if not data: break sock.send(data) if data == "q": break sock.close()
def service_discover(device): services = blue.find_service(address=device) for service in services: name = str(service['name']) protocol = str(service['protocol']) port = str(service['port']) print("[+] found service: [{}][{}][{}]".format(name, protocol, port))
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)
def _create_client(self): assert self.uuid is not None logger.info("searching service %s (UUID: %s) @ %s" % (self.name, self.uuid, self.upstream_addr or 'anywhere')) service_matches = [] while len(service_matches) == 0: try: service_matches = bt.find_service(uuid=self.uuid, address=self.upstream_addr) if len(service_matches) == 0: sleep(1) except KeyboardInterrupt: break first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] logger.info("connecting to App \"%s\" on %s" % (name, host)) # Create the client socket sock = BluetoothSocket(bt.RFCOMM) sock.connect((host, port)) return sock
def spp_client(self): global G_connected print("BT: start spp client") print(f"BT: search for spp server on {self.addr}") uuid = UUID_SPP services = bluetooth.find_service(uuid=uuid, address=self.addr) if len(services) == 0: print("BT: could not find spp server") G_connected = False return s = services[0] port = s['port'] name = s['name'] host = s['host'] print(f"BT: connect to {name} on {host}") self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) self.sock.connect((host, port)) print("BT: connected") G_connected = True #---- thread ---- self.thread = BtRxThread(self.sock) self.thread.start() return
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)
def connect(addr): services = bluetooth.find_service(address=addr) if len(services) > 0: print("found %d services" % len(services)) print() else: print("no services found") for svc in services: 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() host = svc["host"] port = svc["port"] import binascii print binascii.hexlify(svc["name"]) if svc["protocol"] == "RFCOMM" and svc["name"] == "AMP-SPP\x00": print("Trying to connect") sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) sock.connect((host, port)) total_size = 0 while True: data = sock.recv(1024) total_size += len(data) print "received [%s], size %i" % (data, total_size) sock.close()
def scanservices(self): logging.info("Searching for services...") if system() == "Darwin": return self.scanservices_osx() # Example find_service() output on raspbian buster: # {'service-classes': ['1101'], 'profiles': [], 'name': 'Port', 'description': None, # 'provider': None, 'service-id': None, 'protocol': 'RFCOMM', 'port': 1, # 'host': 'A1:B2:C3:D4:E5:F6'} service_matches = find_service(uuid=self.service_uuid, address=self.address) valid_service = list( filter( lambda s: 'protocol' in s and 'name' in s and s[ 'protocol'] == 'RFCOMM' and (s['name'] == 'SerialPort' or s['name'] == 'Port'), service_matches)) print(valid_service[0]) if len(valid_service) == 0: logging.error("Cannot find valid services on device with MAC %s." % self.address) return False logging.info("Found a valid service") self.service = valid_service[0] return True
def send(self, messageToSend, destinationServiceName, destinationMAC, destinationUUID): logger.write('DEBUG', '[BLUETOOTH] Buscando el servicio \'%s\'.' % destinationServiceName) # Buscamos un servicio Bluetooth específico serviceMatches = bluetooth.find_service(uuid = destinationUUID, address = destinationMAC) # Verificamos si hubo alguna coincidencia if len(serviceMatches) > 0: try: firstMatch = serviceMatches[0] name = firstMatch['name'] host = firstMatch['host'] port = firstMatch['port'] # Crea un nuevo socket Bluetooth que usa el protocolo de transporte especificado clientSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) # Conecta el socket con el dispositivo remoto (host) sobre el puerto (channel) especificado clientSocket.connect((host, port)) logger.write('DEBUG', '[BLUETOOTH] Conectado con la dirección \'%s\'.' % host) return self.bluetoothTransmitter.send(messageToSend, clientSocket) except bluetooth.btcommon.BluetoothError as bluetoothError: # (11, 'Resource temporarily unavailable') # (16, 'Device or resource busy') logger.write('WARNING','[BLUETOOTH] %s.' % bluetoothError) return False else: logger.write('DEBUG', '[BLUETOOTH] No se pudo encontrar el servicio \'%s\'.' % destinationServiceName) return False
def find_service(self, name: str = None, addr: str = None, uuid: str = None) -> BluetoothLookupServiceResponse: """ Look up for a service published by a nearby bluetooth device. If all the parameters are null then all the published services on the nearby devices will be returned. See `:class:platypush.message.response.bluetoothBluetoothLookupServiceResponse` for response structure reference. :param name: Service name :param addr: Service/device address :param uuid: Service UUID """ import bluetooth from bluetooth import find_service services = find_service(name=name, address=addr, uuid=uuid) self._port_and_protocol_by_addr_and_srv_uuid.update({ (srv['host'], srv['service-id']): (srv['port'], getattr(bluetooth, srv['protocol'])) for srv in services if srv.get('service-id') }) self._port_and_protocol_by_addr_and_srv_name.update({ (srv['host'], srv['name']): (srv['port'], getattr(bluetooth, srv['protocol'])) for srv in services if srv.get('name') }) return BluetoothLookupServiceResponse(services)
def sendOut(port,text): backlog = 1 size = 1024 #Needs a loop somehow others = bluetooth.find_service(name='spartacus') for other in others: thread.start_new_thread( beClient, (other['host'],port,text) )
def sdpBrowse(addr): services = bluetooth.find_service(address=addr) for service in services: name = service['name'] proto = service['protocol'] port = str(service['port']) print('[+] Found ' + str(name)+' on '+ str(proto) + ':'+port)
def __init__(self, mac, uuid="00001101-0000-1000-8000-00805f9b34fb"): self.uuid = uuid self.mac = mac self.service = bluetooth.find_service(uuid=uuid, address=mac) if len(self.service) < 1: raise Exception("Could not find Bluetooth service!") self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
def do_connect(self, line, opts={}): """Connects to BIP Server""" server_address = line if not server_address: raise TypeError("server_address cannot be empty") logger.info("Finding BIP service ...") services = bluetooth.find_service(address=server_address, uuid=headers.COVERART_UUID) if not services: sys.stderr.write("No BIP (CoverArts) service found\n") sys.exit(1) host = services[0]["host"] port = services[0]["port"] logger.info("BIP service found!") self.client = BIPClient(host, port) logger.info("Connecting to bip server = (%s, %s)", host, port) result = self.client.connect( header_list=[headers.Target(headers.COVERART_UUID)]) if not isinstance(result, responses.ConnectSuccess): logger.error("Connect Failed, Terminating the bip client..") sys.exit(2) logger.info("Connect success") self.prompt = self.colorize("bip> ", "green")
def __init__(self, strType): if strType == 'bluez': bd_addr = "00:1A:7D:DA:71:05" port = bluetooth.find_service(name = "ADC Service")[0]['port'] try: self.sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) self.sock.connect((bd_addr, port)) except bluetooth.btcommon.BluetoothError as error: print "Could not connect: ", error sys.exit(1) elif strType == 'tcp': host = socket.gethostbyname("raspberrypi") port = 6789 try: self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) except socket.error, msg: self.sock = None try: self.sock.connect((host,port)) # Verbinden except socket.error, msg: self.sock.close() self.sock = None
def call_service(self): r = rospy.Rate(1 / 3.0) rospy.loginfo("connecting to service {}...".format(self.uuid)) while not rospy.is_shutdown(): service_matches = bluetooth.find_service(uuid=self.uuid, address=self.faddr) if len(service_matches) == 0: rospy.loginfo( "couldn't find the service = {}, try again".format(uuid)) else: rospy.loginfo("service found") break r.sleep() first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] rospy.loginfo("connecting to {} on {} on port {}".format( name, host, port)) sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) sock.connect((host, port)) return sock
def sdp(self, target): print("BT: sdp begin") if target == 'all': target = None services = bluetooth.find_service(address=target) if len(services) > 0: print("BT: found %d services on %s" % (len(services), target)) else: print("BT: no services found") for s in services: print("service name: %s" % (s['name'])) print("host: %s" % (s['host'])) print("description: %s" % (s['description'])) print("provider: %s" % (s['provider'])) print("protocol: %s" % (s['protocol'])) print("channel/psm: %s" % (s['port'])) # psm - protocol and service multiplexer print("profiles: %s" % (s['profiles'])) print("service classes: %s" % (s['service-classes'])) print("service id: %s" % (s['service-id'])) print("BT: sdp end") return
def find_free_ports(target='localhost'): free_ports=range(1,31) services = bluetooth.find_service(address=target) for svc in services: if svc['port'] in free_ports: free_ports.remove(svc['port']) return free_ports
def connect(self, hardware_address=None): if self.listerner is not None: # Set state self.listerner.on_state_changed(self.CONNECTION_STATE_CONNECTING) logger.debug(f"Connect to server on {hardware_address}") # service_matches = bluetooth.find_service(uuid=self.uuid) service_matches = bluetooth.find_service(uuid=self.uuid, address=hardware_address) if len(service_matches) == 0: logger.error("Couldn't find the RFCOMM service.") sys.exit(1) first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] logger.info(f"Connecting to '{name}' on {host}:{port}") # Create the client socket self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) try: self.sock.connect((host, port)) self.listerner.on_connect_success(param_string=name) self.listerner.on_state_changed(self.CONNECTION_STATE_CONNECTED) except Exception as e: self.listerner.on_state_changed(self.CONNECTION_STATE_NONE) self.listerner.on_connect_failed(e) self.start_communication() else: logger.debug("No ChatListener attached!!") sys.exit(1)
def __init__(self,addr=None): uuid = "0ef0f502-f0ee-46c9-986c-54ed027807fb" 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) 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 entity2uuid(entity_id): """ Return all the UUIDs (i.e. SDP service-id) for the device with the given MAC """ services = bluetooth.find_service(address=entity_id) return [ uuid.UUID(svc['service-id']) for svc in services if svc['service-id'] ]
def connect(hardware_address): logger.debug(f"Connect to server on {hardware_address}") service_matches = bluetooth.find_service( uuid="00001101-0000-1000-8000-00805F9B34FB", address=hardware_address) # logger.debug(service_matches) if len(service_matches) == 0: logger.error("Couldn't find the RFCOMM service.") sys.exit(1) first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] logger.info(f"Connecting to '{name}' on {host}:{port}") # Create the client socket socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) try: logger.debug(socket.connect((host, port))) logger.debug("CONNECTED") except Exception as e: logger.exception(e) raise e return socket
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 RFCOMM_Sendfile(address, fname="test.txt", fdata=b'Hello world\n'): print("Searching for OBEX service on %s" % address) # Use the server named "OBEX Object Push" to send file service_matches = bluetooth.find_service(name="OBEX Object Push", address=address) if len(service_matches) == 0: print("Couldn't find the service") sys.exit(0) match = service_matches[0] name = match["name"] host = match["host"] port = match["port"] print("Service Name: %s" % match["name"]) print(" Host: %s" % match["host"]) print(" Description: %s" % match["description"]) print(" Provided By: %s" % match["provider"]) print(" Protocol: %s" % match["protocol"]) print(" channel/PSM: %s" % match["port"]) print(" svc classes: %s " % match["service-classes"]) print(" profiles: %s " % match["profiles"]) print(" service id: %s " % match["service-id"]) print("Connecting to \"%s\" on %s" % (name, host)) client = Client(host, port) client.connect() # The parameter [file_data] must be bytes type like [b'****'],otherwise there will be some error occur in Python3 client.put(name=fname, file_data=fdata) client.disconnect() return
def do_connect(self, line, opts): profile_id = "1130" # profile id of PBAP service_id = "\x79\x61\x35\xf0\xf0\xc5\x11\xd8\x09\x66\x08\x00\x20\x0c\x9a\x66" server_address = line if not server_address: raise ValueError("server_address should not be empty") logger.info("Finding PBAP service ...") services = bluetooth.find_service(address=server_address, uuid=profile_id) if not services: sys.stderr.write("No PBAP service found\n") sys.exit(1) host = services[0]["host"] port = services[0]["port"] logger.info("PBAP service found!") self.client = PBAPClient(host, port) logger.info("Connecting to pbap server = (%s, %s)", host, port) result = self.client.connect(header_list=[headers.Target(service_id)]) if not isinstance(result, responses.ConnectSuccess): logger.error("Connect Failed, Terminating the Pbap client..") sys.exit(2) logger.info("Connect success") self.prompt = self.colorize("pbap> ", "green")
def find_bt_services(self, name=None, uuid=None, address=None): """ Shows services supported by target device (by name/uuid/address) or shows services for all near devices if None is provided. """ print "\nLooking for BlueTooth services...\n" if address: if not self.check_address_validity(address): # should not try to connect if address is not valid print "\nExiting..." sys.exit(0) self.bt_services = bluetooth.find_service(name, uuid, address) if self.bt_services: for service in self.bt_services: print "Service Name: %s" % service["name"] print " Host: %s" % service["host"] print " Description: %s" % service["description"] print " Provided By: %s" % service["provider"] print " Protocol: %s" % service["protocol"] print " Channel/PSM: %s" % service["port"] print " Svc classes: %s" % service["service-classes"] print " Profiles: %s" % service["profiles"] print " Service ID: %s" % service["service-id"] print "--------------------------------------------" else: print "No BlueTooth services were found."
def send_bluetooth_to_device(my_thread): uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee" # arbitrary set service_matches = bluetooth.find_service(uuid=uuid, address=addr) if len(service_matches) == 0: print("Couldn't find the SampleServer service.") sys.exit(0) first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] print("Connecting to \"{}\" on {}".format(name, host)) # Create the client socket sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) sock.connect((host, port)) print("Connected. Type something...") while True: data = my_thread.read_data_out() if not data: break sock.send(data) my_thread.yield() sock.close()
def connect(self): if self.sock: return True service_matches = bluetooth.find_service( address=self.addr, uuid=bluetooth.SERIAL_PORT_CLASS) if len(service_matches) == 0: self.printError("BT device not found.") return False first_match = service_matches[0] self.port = first_match["port"] self.name = first_match["name"] self.host = first_match["host"] self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) try: ret = self.sock.connect((self.addr, self.port)) except bluetooth.btcommon.BluetoothError as e: self.printError(e) self.sock.close() self.sock = None return False self.printWarning("Connected to \"{}\" on {} port {}".format( self.name, self.host, self.port)) self.sock.settimeout(0.3) return True
def dowork(device_address): services = bluetooth.find_service(address=device_address, uuid="1105",) port = None if services: port = services[0]["port"] if not port: print "Service not provided" return print "Connecting to", device_address, port c = client.Client(device_address, port) response = c.connect() if not isinstance(response, responses.ConnectSuccess): print "Failed to connect" return reply = c.get(header_list=[headers.Type("text/x-vcard"),])[1] if reply and type(reply)==str: result = VCard(reply) print result.values doput(c) c.disconnect()
def connect(self, address): services = bluetooth.find_service(uuid='1101', address=address) port = services[0]["port"] name = services[0]["name"] host = services[0]["host"] self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) self.socket.connect((host, port))
def dowork(device_address): services = bluetooth.find_service( address=device_address, uuid="1105", ) port = None if services: port = services[0]["port"] if not port: print "Service not provided" return print "Connecting to", device_address, port c = client.Client(device_address, port) response = c.connect() if not isinstance(response, responses.ConnectSuccess): print "Failed to connect" return reply = c.get(header_list=[ headers.Type("text/x-vcard"), ])[1] if reply and type(reply) == str: result = VCard(reply) print result.values doput(c) c.disconnect()
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))
def setup_bluetooth_socket(addr): # search for the SampleServer service # uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee" # uuid = "MakeBlock" # service_matches = find_service( uuid = uuid, address = addr ) # service_matches = find_service( name = uuid, address = addr ) #import pdb;pdb.set_trace() print('addr: {}'.format(addr)) service_matches = bluetooth.find_service(address=addr) print('All service matches:') print(service_matches) if len(service_matches) == 0: print("couldn't find the Origibot2 bluetooth service =(") sys.exit(0) 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)) # Create the client socket global sock sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) sock.connect((host, port))
def find_services(addr): data ='[' for services in bluetooth.find_service(address = addr): data+= '{"name":"'+str(services["name"])+'","description":"'+str(services["description"])+'"' data+=',"provider":"'+str(services["provider"])+',"protocol":"'+str(services["protocol"])+'"' data+=',"port":"'+str(services["port"])+',"service-id":"'+str(services["service-id"])+'"}' data+=']' return data
def service_discover(addr): services = bluetooth.find_service(address=addr) if len(services) > 0: return services else: return "No Services"
def __init__(self, strType): if strType == 'bluez': bd_addr = "00:1A:7D:DA:71:05" port = bluetooth.find_service(name = "ADC Service")[0]['port'] self.sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) self.sock.connect((bd_addr, port))
def connect_bluetooth_device(self, bd_addr): """ Connect to a Bluetooth device specified by the bd_addr address and display the control view for the device. """ service = bluetooth.find_service(uuid=CELLBOT_UUID, address=bd_addr)[0] self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) self.socket.connect((service["host"], service["port"])) self.droid.webViewShow(CONTROL_VIEW)
def find_service(self, serviceId, addr): isFound = False while (isFound == False): target = bluetooth.find_service(address = addr, uuid = serviceId) if (len(target) > 0): return target[0] isFound = True time.sleep(1)
def initRFCOMM(): print("Scanning for devices (3s)...") devices = [] try: devices = bluetooth.discover_devices(duration = 3, lookup_names = True) except Exception as e: print("Error: %s\n" % str(e)) return None devicesLength = len(devices) print("Found %d devices!" % devicesLength) if devicesLength is 0: return None i = 0 for addr, name in devices: print("%d: %s [%s]" % (i, name, addr)) i+=1 key = input("Enter index of device to connect to: ") try: key = int(key) except Exception as e: print("Bad input!") return None if (key < 0) or (key > devicesLength): print("Bad input!") return None (deviceAddr, deviceName) = devices[key] print("Searching for services on device: %s [%s]" % (deviceName, deviceAddr)) services = bluetooth.find_service(address = deviceAddr) port = None if len(services) is 0: key = input("No services found, input port number: ") try: port = int(key) except Exception as e: print("Bad input!") return None else: for i in range(len(services)): print("%d: %s - Port: %s" % (i, services[i]["name"], services[i]["port"])) key = input("Enter index of service to conect to: ") try: key = int(key) except Exception as e: print("Bad input!") return None port = services[key]["port"] print("Connecting...") connection = bluetooth.BluetoothSocket(bluetooth.RFCOMM) connection.connect((deviceAddr, port)) connection.settimeout(5.0) print("Connected to %s (%s)" % connection.getpeername()) return connection
def find_port(host): services = bluetooth.find_service(address=host) for service in services: print service if service['name'] == 'SL4A': print service port = service['port'] print port return port
def find_ska_service(device_address=None): print('Searching for devices with the SKA secure service') service_matches = bluetooth.find_service(uuid=SKA_PAIRING_UUID, address=device_address) print 'Services found: ' + str(service_matches) if len(service_matches) == 0: print("couldn't find the SKA service =(") return service_matches
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))