我建议你先找到 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)