python中的蓝牙设备名称和相应的串口名称

时间:2015-11-11 15:03:30

标签: python windows bluetooth serial-port spp

我的蓝牙设备具有用户友好名称" Sensor1"。此设备使用SPP配置文件。为了让设备通过蓝牙启动数据流,我必须在与此设备对应的COM端口上写下' 10111011' ,如下所示:

ser = serial.Serial('COM5') 
ser.write('10111011')     

问题是我不知道哪个COM端口对应于" Sensor1"。所以,我读了Windows注册表来获取设备名称:

import _winreg as reg
from itertools import count

key = reg.OpenKey(reg.HKEY_LOCAL_MACHINE, 'HARDWARE\\DEVICEMAP\\SERIALCOMM')
for i in count():
    device, port = reg.EnumValue(key, i)[:2]
    print "Device name \"%s\" found at %s" % (device, port)

我得到的只是:

Device name \Device\Serial0 found at COM3
Device name \Device\BthModem16 found at COM4
Device name \Device\BthModem17 found at COM5

如何获取设备名称,如下所示:

service = bluetooth.find_service()
print service["name"]

3 个答案:

答案 0 :(得分:1)

我建议您先查找MAC地址,然后再按MAC地址查找COM端口。 但是我不确定这是否是最好的方法。我在Windows 10和Python 3.5中测试了此代码。

要从友好名称中查找MAC地址,请使用以下功能:

import bluetooth
def find_bt_address_by_target_name(name):
    # sometimes bluetooth.discover_devices() failed to find all the devices
    MAX_COUNT = 3
    count = 0
    while True:
        nearby_devices = bluetooth.discover_devices()

        for btaddr in nearby_devices:
            if name == bluetooth.lookup_name( btaddr ):
                return btaddr

        count += 1
        if count > MAX_COUNT:
            return None
        print("Try one more time to find target device..")            

然后通过MAC地址找到COM端口。假设您已经与目标设备配对并启用了SPP端口:

import winreg
import serial
import time

class BluetoothSpp:
    key_bthenum = r"SYSTEM\CurrentControlSet\Enum\BTHENUM"
    # IMPORTANT!! 
    # you need to change this by searching the registry
    DEBUG_PORT = 'C00000001'

    def get_spp_com_port(self, bt_mac_addr):
        print(bt_mac_addr)
        bt_mac_addr = bt_mac_addr.replace(':', '').upper()
        for i in self.gen_enum_key('', 'LOCALMFG'):
            print(i)
            for j in self.gen_enum_key(i, bt_mac_addr):
                print(j)
                if self.DEBUG_PORT in j:
                    subkey = self.key_bthenum+'\\'+ i+'\\'+j
                    port = self.get_reg_data(subkey, 'FriendlyName')
                    assert('Standard Serial over Bluetooth link' in port[0])
                    items = port[0].split()
                    port = items[5][1:-1]
                    print(port)
                    return port

    def gen_enum_key(self, subkey, search_str):
        hKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.key_bthenum + '\\' + subkey)

        try:
            i = 0
            while True:
                output = winreg.EnumKey(hKey, i)
                if search_str in output:
                    yield output
                i += 1

        except:
            pass

        winreg.CloseKey(hKey)

    def get_reg_data(self, subkey, name):
        hKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 
                            subkey)
        output = winreg.QueryValueEx(hKey, name) 
        winreg.CloseKey(hKey)
        return output

if __name__ == '__main__':
    mac_addr = '11:22:33:44:55:66'
    bt_spp = BluetoothSpp()
    com_port = bt_spp.get_spp_com_port(mac_addr)

答案 1 :(得分:0)

import bluetooth
decices = bluetooth.discover_devices()

使用以下库:https://pypi.python.org/pypi/PyBluez/
以下是一些很好的用法示例:https://people.csail.mit.edu/albert/bluez-intro/c212.html

如果您对使用其他库不感兴趣,可以尝试提取与Windows相关的发现功能,可在此处找到:https://github.com/karulis/pybluez/blob/2a22e61fb21c27b47898c2674662de65162b485f/bluetooth/widcomm.py#L109

答案 2 :(得分:0)

另一个对我有用的解决方案。

import serial.tools.list_ports

#Find COM port with LookFor name
lookFor = "DG-1"
nb=discover_devices(lookup_names=True)
for addr,name in list(nb):
    if lookFor == name:
        break
    else:
        name = None
        addr = None
if name == lookFor:
    comPorts=list(serial.tools.list_ports.comports())
    addr=addr.translate(None,":")
    for COM,des,hwenu in comPorts :
        if addr in hwenu:
            break
if name!=None:
    print "COM=",COM,"   BTid=",name
else:
    print LookFor," not found."