You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派运行Python蓝牙配对脚本时Bluetooth agent无法正常工作求助

问题核心原因

你当前的代码每一次调用os.system()执行bluetoothctl指令都是独立的会话,前一次执行的agent on、default-agent配置不会保留到后续的bluetoothctl调用中,这就是手动执行正常、脚本执行报“No agent is registered”错误的根本原因。

可行解决方案

方案1:合并bluetoothctl指令为单次调用

把所有需要执行的bluetoothctl指令一次性传入,共用同一个会话,适配简单配对场景:

import os
import subprocess

# 启动蓝牙基础服务
os.system('sudo systemctl enable bluetooth')
os.system('sudo systemctl start bluetooth')

# 一次性执行蓝牙配置+扫描指令
bt_cmds = '''
discoverable on
agent on
default-agent
pairable on
scan on
'''
subprocess.run(['bluetoothctl'], input=bt_cmds.encode(), timeout=30)

# 执行配对、信任、连接流程
mac_addr = "XX:XX:XX:XX:XX:XX"
pair_cmds = f'''
pair {mac_addr}
trust {mac_addr}
connect {mac_addr}
'''
subprocess.run(['bluetoothctl'], input=pair_cmds.encode(), timeout=60)

方案2:使用pexpect维持交互式会话

如果需要动态处理配对验证码、自动识别扫描到的设备等复杂逻辑,可以用pexpect库维持长期的bluetoothctl交互会话,避免会话中断导致agent失效:

  1. 先安装依赖:pip install pexpect
  2. 参考代码:
import os
import time
import pexpect

# 启动蓝牙基础服务
os.system('sudo systemctl enable bluetooth')
os.system('sudo systemctl start bluetooth')

# 启动bluetoothctl交互进程
child = pexpect.spawn('bluetoothctl')
child.expect('#')

# 初始化蓝牙配置
child.sendline('discoverable on')
child.expect('#')
child.sendline('agent on')
child.expect('#')
child.sendline('default-agent')
child.expect('#')
child.sendline('pairable on')
child.expect('#')

# 扫描30秒
child.sendline('scan on')
time.sleep(30)
child.sendline('scan off')
child.expect('#')

# 配对指定设备
mac_addr = "XX:XX:XX:XX:XX:XX"
child.sendline(f'pair {mac_addr}')
# 自动处理配对交互
res = child.expect(['Confirm passkey', 'Enter PIN', 'Pairing successful'], timeout=60)
if res == 0:
    # 自动确认两端验证码一致
    child.sendline('yes')
    child.expect('Pairing successful')
elif res == 1:
    # 自定义输入PIN码,常用默认PIN为0000/1234
    child.sendline('0000')
    child.expect('Pairing successful')

# 配对完成后信任并连接设备
child.sendline(f'trust {mac_addr}')
child.expect('#')
child.sendline(f'connect {mac_addr}')
child.expect('#')
child.sendline('exit')
注意事项
  • 脚本需要加sudo权限运行,避免蓝牙操作权限不足
  • 新版树莓派系统可先修改/etc/bluetooth/main.conf,将#AutoEnable=false改为AutoEnable=true,修改后执行sudo systemctl restart bluetooth生效,避免蓝牙服务异常

内容的提问来源于stack exchange,提问作者JorgeAcebron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:09:03