python调用蓝牙_在python中将蓝牙设备与Passkey / Password配对-RFCOMM(Linux)

本文介绍如何使用Python的PyBlueZ库发现并连接带有密码保护的蓝牙设备。通过结合使用subprocess模块调用命令行工具,成功实现了与受密码保护的蓝牙设备建立RFCOMM连接的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

But if tried to connect to a specific device using:

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.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值