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

PyBluez2蓝牙设备连接求助:无法找到连接方法,需接收数据

PyBluez2蓝牙设备连接与数据接收实现方案

一、优化设备信息存储(避免脆弱的字符串切片)

你当前通过字符串切片提取MAC地址的方式容易因格式变化出错,建议直接存储设备的地址和名称元组,后续提取更可靠:

import bluetooth as bt

nearby_devices = bt.discover_devices(lookup_names=True)
print(f"Found {len(nearby_devices)} devices.")

# 直接存储(编号, 地址, 名称)的元组,避免字符串拼接
bluetooth_devices = []
for idx, (addr, name) in enumerate(nearby_devices, start=1):
    bluetooth_devices.append((idx, addr, name))
    print(f"{idx} - Address: {addr} - Name: {name}\n")

# 选择设备
device_number = int(input("\nWhich bluetooth device do you want to connect to? (enter number) ")) - 1
selected_idx, selected_addr, selected_name = bluetooth_devices[device_number]
print(f"Selected device: {selected_name} ({selected_addr})")

二、PyBluez2设备连接与数据接收

PyBluez2中没有直接的connect函数,需通过BluetoothSocket创建RFCOMM套接字实现连接(这是蓝牙串口通信的标准方式),完整实现代码如下:

# 接上面的设备选择代码
try:
    # 创建RFCOMM类型的蓝牙套接字
    sock = bt.BluetoothSocket(bt.RFCOMM)
    # 连接设备,端口号通常为1,若连接失败可尝试2-10范围
    sock.connect((selected_addr, 1))
    print(f"Successfully connected to {selected_name}")

    # 循环接收数据
    print("Receiving data... (Press Ctrl+C to stop)")
    while True:
        data = sock.recv(1024)  # 每次接收1024字节
        if not data:
            break
        print(f"Received: {data.decode('utf-8')}")  # 根据设备编码调整解码方式

except bt.BluetoothError as e:
    print(f"Connection error: {str(e)}")
finally:
    # 关闭套接字
    sock.close()
    print("Connection closed")

三、关键注意事项

  • 确保目标蓝牙设备开启了RFCOMM串口服务,并处于可连接状态
  • 若连接失败,尝试更换端口号(1-10之间),部分设备可能使用非默认端口
  • 数据解码方式需匹配设备发送的编码(如gbk、ascii等),出现乱码时调整decode参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:10:48