14
votes

Python 3.3 came with native support for bluetooth sockets. Unfortunately, it's not too well documented yet (there is only one mention of it in the documentation).

Googling it there is a blog post about implementing a client, but I couldn't find anything about creating a server.

More specifically, how to set the user-friendly name and advertise the service.

So, something like

import socket

serverSocket = socket.socket(socket.AF_BLUETOOTH,
                             socket.SOCK_STREAM,
                             socket.BTPROTO_RFCOMM)
serverSocket.setTimeout(1)
serverSocket.bind(("", 1))
serverSocket.listen(1)

something.advertise_service(something something)

Any ideas?

1
It looks like they basically integrated pybluez. Take a look at those examples: code.google.com/p/pybluez/source/browse/trunk/examples/simple/… - TJD
'advertise_service' doesn't exist in the socket module nor in the server socket, and searching 'advert' in the python's source code finds only three unrelated comments. - A. Borgna
I came across the same problem. I could make a simple server, but couldn't carryout tasks such as advertise services. You can see code for a client-server application here, if you are interested: kevindoran1.blogspot.co.nz/2013/04/… - Kevin
@TJD, PyBluez was copied from PyAffix which was in turn copied from python2.2. - Felipe

1 Answers

14
votes

Bad news: Python doesn't appear to support what you want to do out of the box. (At least not in socketmodule.c).

Most of the python/bluetooth users I've seen use pybluez although it hasn't been updated since 2009.

Good news: I went through their source (for Linux connections), and found the relevant bits for advertising services. Most of the code is essentially copy-pasted from the python 2.2 version of socketmodule.c.

pybluez does define some additional functionality for a socket object to implement all those bluetooth goodies. It doesn't get too low-level, and instead depends on BlueZ for that. From what I can tell, it basically takes python objects and creates the data structures expected by BlueZ and just calls that. If you don't want to/can't use pybluez, you'll have to somehow implement this missing functionality. I think you may be able to do it with c-types. The relevant parts for advertising the service are in btmodule.c, lines 2562-2642.

There is a python-3 branch in the source for pybluez, although I don't know if it works or not.

If you do decide to use pybluez, an example taken from their source

server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service(server_sock, "SampleServer",
                  service_id = uuid,
                  service_classes = [ uuid, SERIAL_PORT_CLASS ],
                  profiles = [ SERIAL_PORT_PROFILE ], 
                  )

As google code is closing, the code can also be found on github here.