【问题标题】:Sending messages or datas with bluetooth via python通过python使用蓝牙发送消息或数据
【发布时间】:2011-11-21 02:15:33
【问题描述】:

如何通过 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')

这里是代码

#!/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()

【问题讨论】:

  • 请编辑完整的错误消息,包括堆栈跟踪。

标签: python bluetooth


【解决方案1】:

正如@TJD 所说,您需要确保为所需服务绑定正确的端口。

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

然后作为第二步尝试在您要连接的设备上查找服务。

>>> 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',
  ...}]

根据这些信息,您可以连接到设备上运行的服务。根据服务/配置文件specification,您发送特定于服务的命令并从设备取回信息。例如。在上面的列表中,您会看到“耳机音频网关”和编号为“1108”的配置文件列表,这是服务的短 uuid。您现在可以查找此配置文件的命令,它应该可以工作。

【讨论】:

    【解决方案2】:

    我有同样的错误。绑定地址后,错误消失了。

    rfcomm bind 0 <address> 1
    

    0 表示您的蓝牙设备。 1 指的是端口号。 如果你运行的是 linux,你可以运行 hciconfig 到设备号。

    【讨论】:

    • 0 绑定到 /dev/rfcomm0,1 绑定到 /dev/rfcomm1。
    【解决方案3】:

    您是否尝试过从 pybluez 中的基本 rfcomm-client 和 rfcomm-server 示例代码开始?

    http://code.google.com/p/pybluez/source/browse/trunk/examples/simple/rfcomm-client.py

    这基本上就是您的代码正在做的事情,但它使用服务发现来确保连接到正确的端口。

    【讨论】:

    • 使用pip install pybluez
    猜你喜欢
    • 2018-01-16
    • 2019-07-26
    • 2021-07-17
    • 1970-01-01
    • 2015-04-21
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多