BluetoothCtl 在 Raspberry Pi 上使用 python 子进程与 pin 配对

问题描述 投票:0回答:2

我正在开发一个项目,通过蓝牙连接使用 HC-05 蓝牙模块在树莓派和一系列 Arduino 之间进行通信。我可以使用 bluetoothctl 配对 arduino,并使用 python 脚本进行通信,但我也想将配对过程包含在我的脚本中,但我还没有找到在脚本中包含蓝牙配对引脚的解决方案。

我尝试过的:

  1. PyBluez 库,但无法配对。
  2. 子进程,但我无法响应 pin 请求(下面的代码),但这会导致错误 参数太多(对于 bluetoothctl)。
import subprocess, shlex
addr = "00:14:03:06:12:84"
pinCode = "1234"

args = ["bluetoothctl", f"pair {addr}", pinCode]
args = shlex(args)
subprocess.Popen(args)
  1. 我也尝试使用 bluetoothctl 包装器,但这里也没有 pin 选项。

可以通过Python配对吗?

bluetooth subprocess raspberry-pi3 hc-05
2个回答
1
投票

Bluez 希望通过 D-Bus Agent API 来完成此操作,该 API 记录在 https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/agent-api。 txt

Bluez 源代码树中还有一个 Python 示例:https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/test/simple-agent

由于配对通常是一次性配置/安全步骤,其中交换密钥并将设备建立为可信设备,因此我质疑自动化配对过程的价值。您真的想与随机出现且在范围内的设备配对吗?

RPi 和 HC-05 之间的后续连接不需要先进行配对步骤。 Raspberry Pi 只需要调用连接命令,因为两个设备已经配对并受信任。


0
投票

这是一个 python 脚本,它使用 pexpect 来配对 HC 05(给定 MAC 地址作为在 Pi Zero 上测试的参数)。

要安装 pexpect 模块,请运行:

sudo apt install python3-pexpect

要将 HC 05 模块与 MAC XX:XX:XX:XX:XX:XX 配对,请运行:

./btpair.py XX:XX:XX:XX:XX:XX

#-------------btpair.py--------------------
#!/usr/bin/python3

import pexpect,sys,os
address = sys.argv[1]
btpin="1234"
tries=3
os.system("bluetoothctl -- remove "+address)

def setbt(address):
  p = pexpect.spawn('bluetoothctl', encoding='utf-8')
  p.logfile_read = sys.stdout
  p.expect('#')
  p.sendline("scan on")
  p.expect("Device "+address)
  p.sendline("pair "+address)
  p.expect("code")
  p.sendline(btpin)
  p.expect("success")
  p.sendline("quit")
  p.close()
  return

for i in range(0,tries):
  setbt(address)
  t=os.popen("bluetoothctl -- paired-devices|awk '{print $2}'").read().strip()
  if t == address: 
    break
 #-----------------------------------------
© www.soinside.com 2019 - 2024. All rights reserved.