We have seen that Bluetooth devices can locate other nearby devices, those that are in discovery mode. Rather than connecting by the address and port of a device and application, devices can discover the address and port by the service names.
The following version performs the same function but using SDP. On the server-side, the primary use of SDP to advertise the helloService as a serial port or RFCOMM protocols.
The client first finds a list of devices that provide the helloService (in reality, more than just helloService is returned). The list is then searched for the helloService, when found, the associated host address and port are used to connect to the service.
Client Code:
from bluetooth import *
services=find_service(name="helloService",
uuid=SERIAL_PORT_CLASS)
for i in range(len(services)):
match=services[i]
if(match["name"]=="helloService"):
port=match["port"]
name=match["name"]
host=match["host"]
print name, port, host
client_socket=BluetoothSocket( RFCOMM )
client_socket.connect((host, port))
client_socket.send("Hello world")
client_socket.close()
break
Server Code:
import bluetooth
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
server_sock.bind(("",bluetooth.PORT_ANY))
server_sock.listen(1)
bluetooth.advertise_service(server_sock, "helloService",
service_classes=[bluetooth.SERIAL_PORT_CLASS],
profiles=[bluetooth.SERIAL_PORT_PROFILE])
client_sock, address = server_sock.accept()
print "Accepted connection from ",address
data = client_sock.recv(1024)
print "received [%s]" % data
client_sock.close()
server_sock.close()
No comments:
Post a Comment