通过Python使用蓝牙发送消息或数据
我怎么能用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()
4 个回答
0
你有没有试过从pybluez的基本rfcomm-client和rfcomm-server示例代码开始呢?
http://code.google.com/p/pybluez/source/browse/trunk/examples/simple/rfcomm-client.py
这个代码基本上就是你写的代码在做的事情,不过它使用了服务发现的功能,确保连接到正确的端口。
3
我也遇到过同样的错误。在绑定地址之后,错误就消失了。
rfcomm bind 0 <address> 1
这里的0指的是你的蓝牙设备,1则是端口号。如果你在使用Linux系统,可以运行 hciconfig 来查看设备编号。
9
正如 @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',
...}]
根据这些信息,你就可以连接到设备上运行的服务。根据服务的规范,你需要发送特定的命令,然后从设备那里获取信息。例如,在上面的列表中,你可以看到“耳机音频网关”和编号为“1108”的配置文件,这个编号是这个服务的简短标识符。现在你可以查找这个配置文件的命令,应该就能正常工作了。