July 26, 2013

Python 3.3 and Bluetooth native socket

I have posted earlier on how to run a simple serial server using Python 2.6 and PyBluez. Python 3.3 has natively available sockets class written for Bluetooth communication, eliminating the needs for PyBluez. I have not tested it yet myself, but if I'm not mistaken the native Bluetooth socket is only supported on unix based OS. So, if you're on Windows, my guess is best to stay with Python 2.6 and PyBluez.

A sample script for the server is as below:

"""
A simple Python script to receive messages from a client over
Bluetooth using Python sockets (with Python 3.3 or above).
"""

import socket

hostMACAddress = '00:1f:e1:dd:08:3d' 

#The MAC address of a Bluetooth adapter on the server. 
#The server might have multiple Bluetooth adapters.

port = 3 

#3 is an arbitrary choice. It should match the port used by the client.
backlog = 1
size = 1024 


s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.bind((hostMACAddress,port))
s.listen(backlog)


try:
       client, address = s.accept()
       while 1:
           data = client.recv(size)
           if data:
                   print(data)
                   client.send(data)
except:  
       print("Closing socket")  
       client.close()
       s.close()


The scripts was not written by me. The original page here discussed the difference between Python 2.6+PyBluez and native Bluetooth socket in Python 3.3.

Here's an example of how to use the native Bluetooth socket to send a few command bytes to control the speed and direction of a Bluetooth controlled car.

No comments:

Post a Comment

Write a reply