通过python使用蓝牙发送消息或数据

bul*_*ric 10 python bluetooth

我如何通过python通过蓝牙发送消息而无需类型号码等密钥验证?

我使用了pybluez,但是我收到了这个错误:

File "./send", line 12, in <module>
    connect()
File "./send", line 8, in connect
    sock.connect((bd_addr, port))
File "<string>", line 5, in connect
    bluetooth.btcommon.BluetoothError: (111, 'Connection refused')
Run Code Online (Sandbox Code Playgroud)

这是代码

#!/usr/bin/python

import bluetooth

def connect ():
    bd_addr = "x:x:x:x:x:x"
    port = 1
    sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    sock.connect((bd_addr, port))
    sock.send("hello!!")
    sock.close()

connect()
Run Code Online (Sandbox Code Playgroud)

lai*_*ack 8

正如@TJD所说,您需要确保使用正确的端口绑定所需的服务.

>>> from bluetooth import *
>>> from pprint import pprint
>>>
>>> devices = discover_devices()
>>> devices
['xx:yy:tt:zz:44:BD', '00:yy:72:zz:bb:aa']
Run Code Online (Sandbox Code Playgroud)

然后,第二步尝试在要连接的设备上查找服务.

>>> service = find_service(address='00:yy:72:zz:bb:aa')
>>> pprint(service)
[{'description': None,
  'host': '00:yy:72:zz:bb:aa',
  'name': 'Headset Audio Gateway',
  'port': 12,
  'profiles': [('1108', 258)],
  ...},
 {'description': None,
  'host': '00:yy:72:zz:bb:aa',
  'name': 'Dial-Up Networking',
  'port': 1,
  'profiles': [('1103', 256)],
  'protocol': 'RFCOMM',
  ...}]
Run Code Online (Sandbox Code Playgroud)

根据此信息,您可以连接到设备上运行的服务.根据服务/配置文件规范,您可以发送特定于服务的命令并从设备获取信息.例如,在上面的列表中,您可以看到"Headset Audio Gateway"和配置文件列表,其中包含数字"1108",这是服务的简短uuid.您现在可以查找此配置文件的命令,它应该可以工作.