Building Python Bluetooth Script for IoT Devices
To build a Python script for an IoT device that communicates over Bluetooth, you'll need to use libraries that facilitate Bluetooth communication. One popular library for Bluetooth communication in Python is pybluez.
Below is a simple example demonstrating how to create a Bluetooth server and client using pybluez. This script assumes you're using a system with Bluetooth capabilities, such as a Raspberry Pi.
First, install the pybluez library:
pip install pybluez
Now, let's create the Bluetooth server script. This script will host a Bluetooth socket and wait for incoming connections.
bluetooth_server.py
import bluetooth
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
port = bluetooth.PORT_ANY
server_sock.bind(("", port))
server_sock.listen(1)
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
bluetooth.advertise_service(
server_sock, "SampleServer",
service_id=uuid,
service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
profiles=[bluetooth.SERIAL_PORT_PROFILE]
)
print("Waiting for connection on RFCOMM channel %d" % port)
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0:
break
print("received [%s]" % data)
client_sock.send(data) # Echo back to client
except OSError:
pass
print("Disconnected.")
client_sock.close()
server_sock.close()
print("All done.")
Next, create the Bluetooth client script. This script will connect to the Bluetooth server and send a message.
bluetooth_client.py
import bluetooth
addr = "XX:XX:XX:XX:XX:XX" # Replace with server's MAC address
port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((addr, port))
try:
while True:
msg = input("Enter a message to send: ")
if msg == "exit":
break
sock.send(msg)
data = sock.recv(1024)
print("Received [%s]" % data)
except OSError:
pass
print("Disconnected.")
sock.close()
Explanation:
-
Server Script:
- Creates a Bluetooth socket and binds it to any available port.
- Advertises the service with a specific UUID.
- Waits for a client connection and then enters a loop to receive and echo messages.
-
Client Script:
- Connects to the server using its Bluetooth address and port.
- Sends messages input by the user and prints any responses received from the server.
Ensure Bluetooth is enabled on your device and replace the addr variable in the client script with your server's Bluetooth MAC address. Also, ensure that you have appropriate permissions to use Bluetooth on your system.
This is a very basic example. In a real-world application, you might want to handle exceptions more gracefully, implement authentication, and add more complex communication protocols.