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

Python蓝牙扫描如何过滤已配对设备且保留原有配对记录

过滤未配对蓝牙设备实现方案

核心逻辑

  • 提前拉取本地所有已配对的蓝牙设备MAC地址存为集合
  • 扫描到蓝牙设备后,仅保留MAC不在已配对集合内的设备,无需删除原有配对记录

适配多平台的完整代码

import bluetooth
import subprocess
import sys
try:
    import winreg
    IS_WINDOWS = True
except ImportError:
    IS_WINDOWS = False

def get_paired_devices():
    paired_addrs = set()
    if IS_WINDOWS:
        # Windows下读取注册表获取已配对蓝牙设备
        reg_path = r"SYSTEM\CurrentControlSet\Services\BTHPORT\Parameters\Devices"
        try:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path)
            for i in range(0, winreg.QueryInfoKey(key)[0]):
                subkey_name = winreg.EnumKey(key, i)
                # 注册表中设备地址是去掉冒号的十六进制,转换为标准MAC格式
                addr = ':'.join([subkey_name[j:j+2] for j in range(0,12,2)]).upper()
                paired_addrs.add(addr)
            winreg.CloseKey(key)
        except Exception:
            # 无权限读取注册表时可以改用powershell命令获取
            cmd = ['powershell', 'Get-PnpDevice -Class Bluetooth | Select-Object -Property InstanceId']
            result = subprocess.run(cmd, capture_output=True, text=True).stdout
            for line in result.split('\n'):
                if 'BTH\\' in line:
                    addr_part = line.split('\\')[-1].strip()
                    if len(addr_part) == 12:
                        addr = ':'.join([addr_part[j:j+2] for j in range(0,12,2)]).upper()
                        paired_addrs.add(addr)
    else:
        # Linux/macOS下通过bluetoothctl获取已配对设备
        cmd = ['bluetoothctl', 'paired-devices']
        result = subprocess.run(cmd, capture_output=True, text=True).stdout
        for line in result.split('\n'):
            if line.strip():
                parts = line.split()
                if len(parts) >= 2 and len(parts[1]) == 17:
                    addr = parts[1].upper()
                    paired_addrs.add(addr)
    return paired_addrs

def search():
    devices = bluetooth.discover_devices(duration=1, lookup_names = True)
    return devices

if __name__=="__main__":
    # 先获取一次已配对设备列表,也可以定期刷新适配新增配对的情况
    paired_devices = get_paired_devices()
    while True:
        results = search()
        if results:
            for addr, name in results:
                # 过滤已配对设备
                if addr.upper() not in paired_devices:
                    print(f"设备名:{name}")
                    print(f"MAC地址:{addr}")
                    print("---")

注意事项

  • Windows下如果读取注册表失败,需要以管理员权限运行脚本,或者使用代码中提供的powershell方案
  • Linux环境需要确保已经安装了bluez套件,bluetoothctl命令可用
  • 如果你运行过程中需要新增配对设备,可以在循环中定期调用get_paired_devices()刷新已配对设备集合

内容的提问来源于stack exchange,提问作者a.h. hamedani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 02:57:03