Python bluetooth connect device

Pairing bluetooth devices with Passkey/Password in python — RFCOMM (Linux)

I am working on a Python script to search for bluetooth devices and connect them using RFCOMM. This devices has Passkey/Password. I am using PyBlueZ and, as far as I know, this library cannot handle Passkey/Password connections (Python PyBluez connecting to passkey protected device). I am able to discover the devices and retrieve their names and addresses:

nearby_devices = bluetooth.discover_devices(duration=4,lookup_names=True, flush_cache=True, lookup_class=False) 
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM) s.connect((addr,port)) 

I get an error ‘Device or resource busy (16)’ . I tried some bash commands using the hcitool and bluetooth-agent, but I need to do the connection programmatically. I was able to connect to my device using the steps described here: How to pair a bluetooth device from command line on Linux. I want to ask if someone has connected to a bluetooth device with Passkey/Password using Python. I am thinking about to use the bash commands in Python using subprocess.call() , but I am not sure if it is a good idea. Thanks for any help.

2 Answers 2

Finally I am able to connect to a device using PyBlueZ. I hope this answer will help others in the future. I tried the following:

First, import the modules and discover the devices.

import bluetooth, subprocess nearby_devices = bluetooth.discover_devices(duration=4,lookup_names=True, flush_cache=True, lookup_class=False) 

When you discover the device you want to connect, you need to know port, the address and passkey. With that information do the next:

name = name # Device name addr = addr # Device Address port = 1 # RFCOMM port passkey = "1111" # passkey of the device you want to connect # kill any "bluetooth-agent" process that is already running subprocess.call("kill -9 `pidof bluetooth-agent`",shell=True) # Start a new "bluetooth-agent" process where XXXX is the passkey status = subprocess.call("bluetooth-agent " + passkey + " &",shell=True) # Now, connect in the same way as always with PyBlueZ try: s = bluetooth.BluetoothSocket(bluetooth.RFCOMM) s.connect((addr,port)) except bluetooth.btcommon.BluetoothError as err: # Error handler pass 

Now, you are connected!! You can use your socket for the task you need:

s.recv(1024) # Buffer size s.send("Hello World!") 

Official PyBlueZ documentation is available here

Источник

Bluetooth Programming with Python 3

This post presents basic techniques for communicating over Bluetooth with Python 3.3 and above (using Python sockets). Some simple examples of communicating over Bluetooth with sockets will be shown. PyBluez examples will also be presented for comparison.

The two options

Currently, the most widely documented way to communicate with Python over Bluetooth is to use PyBluez. Previously, PyBluez only supported Python 2. In January 2014, they released a Python 3 version.

Читайте также:  Беспроводной интерфейс wifi bluetooth

Python 3.3’s native Python sockets support Bluetooth communication. Unfortunately, there is very little documentation available describing how to use Python sockets to communicate over Bluetooth. While using Bluetooth with these sockets might be easy for someone who already knows how to use Python sockets, the lack of documentation leaves many people unaware that this method of using Bluetooth even exists. Since PyBluez was ported to Python 3, the use of native Python sockets has limited use.

Required skill: finding the MAC address of a bluetooth adapter

To run the examples, the MAC address of the Bluetooth adapter used by the server must be known. The client application uses this address to connect to the server. On Linux, you can get a list of all available Bluetooth devices and their MAC addresses using the command hciconfig , like so:

hciconfig output

Client sever messaging

This application connects two devices over Bluetooth and allows one to send messages to the other. The sending device runs socketClient.py , and the receiving device runs socketServer.py . These scripts are shown below, first using Python sockets, then using PyBluez:

Python sockets

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 
""" A simple Python script to send messages to a sever over Bluetooth using Python sockets (with Python 3.3 or above). """  import socket  serverMACAddress = '00:1f:e1:dd:08:3d' port = 3 s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) s.connect((serverMACAddress,port)) while 1:  text = input()  if text == "quit":  break  s.send(bytes(text, 'UTF-8')) s.close() 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 
""" 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. However, it must 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() 

As an aside, this code is almost identical to code required to create a client-server application over the internet. All that needs to be changed is the two lines:

# For the Server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("192.168.1.17",50001)) # The Bluetooth MAC Address and RFCOMM port is replaced with an IP Address and a TCP port.  # For the Client s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("192.168.1.17",50001))  # Note: these are arbitrary IP addresses and TCP ports. 

PyBluez

To compare, below is the functionally identical application written using the PyBluez library.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 
""" A simple Python script to send messages to a sever over Bluetooth using PyBluez (with Python 2). """  import bluetooth  serverMACAddress = '00:1f:e1:dd:08:3d' port = 3 s = bluetooth.BluetoothSocket(bluetooth.RFCOMM) s.connect((serverMACAddress, port)) while 1:  text = raw_input() # Note change to the old (Python 2) raw_input  if text == "quit":  break  s.send(text) sock.close() 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 
""" A simple Python script to receive messages from a client over Bluetooth using PyBluez (with Python 2). """  import bluetooth  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 backlog = 1 size = 1024 s = bluetooth.BluetoothSocket(bluetooth.RFCOMM) s.bind((hostMACAddress, port)) s.listen(backlog) try:  client, clientInfo = s.accept()  while 1:  data = client.recv(size)  if data:  print(data)  client.send(data) # Echo back to client except:  print("Closing socket")  client.close()  s.close() 

Conclusion

PyBluez is the most effective way of communicating over Bluetooth using Python. Python sockets can now be used for Bluetooth communication (since Python 3.3). For a simple application, the code is almost identical. For some tasks, however, such as device discovery and Bluetooth service advertisements, it does not seem possible to carry them out using Python sockets. Consequently, PyBluez surpassed Python sockets in most regards. This Stackoverflow question discusses some of the limitations of Python sockets for Bluetooth.

Читайте также:  Pioneer avic f900bt блютуз

Further reading

There is little to no information on Bluetooth programming with Python sockets. There is plenty of information on PyBluez. The following are some useful resources:

Bluetooth Essentials for Programmers Covers many programming languages and uses PyBluez with Python. Great for getting started fast and gaining understanding along the way. PyBluez examples Example code covering various Bluetooth tasks.

Источник

Python and Bluetooth – Part 1: Scanning For Devices And Services (Python)

“Track and Trace” has got some attention in recent times here in the UK as the Covid-19 (Coronavirus) lockdown level looks to be relaxed. Part of the “Track and Trace” program is a mobile application that uses low energy bluetooth beaconing to see what other devices running the application have been close by. This has inspired me to look at Bluetooth connectivity in Python.

Note: I’ve written before, and I’ll probably write again, geektechstuff.com is not a political site. If you have come to this page/site to discuss political opinions around the NHS Track and Trace app, then please take them to a more appropriate site. Thank you. Also note, I am looking at Bluetooth and Python – I am not saying these functions are in the NHS app!

With this blog post I am going to take a look at using a Raspberry Pi (in this case a ZeroW) and some Python to get the Pi to detect active bluetooth devices.

Installing

I installed the required libraries for this project on my Raspberry Pi using the commands:

sudo apt install bluetooth libbluetooth-dev pip3 install pybluez

Checking For Devices

geektechstuff_python_bluetooth

With the pybluez library installed and imported into Python, the Raspberry Pi can start to scan for active Bluetooth devices. This code can be tided up into a function, so that it can be expanded on later.

Читайте также:  Удалить устройства bluetooth windows 10

geektechstuff_python_bluetooth_2

#!/usr/bin/python3 # geektechstuff bluetooth import bluetooth def scan(): print("Scanning for bluetooth devices:") devices = bluetooth.discover_devices(lookup_names = True, lookup_class = True) number_of_devices = len(devices) print(number_of_devices,"devices found") for addr, name, device_class in devices: print("\n") print("Device:") print("Device Name: %s" % (name)) print("Device MAC Address: %s" % (addr)) print("Device Class: %s" % (device_class)) print("\n") return 

Checking For Services Running On Devices

geektechstuff_python_bluetooth_services

A function to scan for Bluetooth services on found devices can also be created.

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)  print("zero services found on", addr) else: for serv in services: print(serv['name']) print("\n") return()

When run this function returns the device details and the name of the services it finds on those active devices.

Scan results (with names and MAC addresses removed)

Although I am only returning the service name (using serv[‘name’]) there are also options to return:

  • host
  • description
  • provider
  • protocol
  • port
  • service-classes
  • profiles
  • service-id

To use these, place them in the same format as serv[‘name’] e.g. serv[‘host’]

The GitHub for pybluez (which contains examples of the library in action) can be found at:

The GitHub for NHSX Android Covid-19 app can be found at:

The GitHub for NHSX iOS Covid-19 app can be found at:

Источник

Оцените статью
Adblock
detector