Pairing bluetooth devices with Passkey/Password in python - RFCOMM (Linux)
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 - listening to a pairing even in a Linux device in Python
Good morning, there is a library written in Python that handle Bluetooth connection for you already PyBluez
to install use sudo pip install pybluez
here is an example on how to use sockets to communicate with bluetooth devices
import bluetooth
bd_addr = "01:23:45:67:89:AB"
port = 1
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))
sock.send("hello!!")
sock.close()
the complete guide is at Bluetooth Programming with PyBluez
`
Related Topics
Generating Variable Names on Fly in Python
How to Modify Lines in a File In-Place
How to Shoot a Bullet With Space Bar
What Is a Clean "Pythonic" Way to Implement Multiple Constructors
Importerror: Cannot Import Name X
How to Read a (Static) File from Inside a Python Package
Why Does Range(Start, End) Not Include End
Pytesseract Ocr Multiple Config Options
Beautiful Soup: 'Resultset' Object Has No Attribute 'Find_All'
How to Delete a File or Folder in Python
What Is the Naming Convention in Python For Variable and Function
How to Load All Modules in a Folder
Is There a Simple Way to Remove Multiple Spaces in a String
Changes in Import Statement Python3
How to Declare Custom Exceptions in Modern Python