今天学习windows下的蓝牙控制,安装pybluez
pip install pybluez
安装很顺利,没有遇见网上关于sdk之类的问题,可能是我的机子已经安装了vs各运行库的原因吧
使用库只需要import bluetooth即可,但我这里出现了
AtributeError: attribute '__doc__' of 'instancemethod' objects is not writable
解决方式是重新安装,指定版本为0.22
pip install pybluez==0.22
使用方式:
通过名字查找蓝牙设备
import bluetooth
def findDevByName(name)
devices = bluetooth.discover_devices()
devAddr=""
for addr in devices:
if bluetooth.lookup_name( addr)==name:
devAddr = addr
break
return devAddr
遍历所有设备服务
import bluetooth
devices = bluetooth.discover_devices(lookup_names=True)
for addr, name in devices:
print(" %s - %s" % (addr, name))
services = bluetooth.find_service(address=addr)
for service in services:
print("Service Name: %s" % service["name"])
print(" Host: %s" % service["host"])
print(" Description: %s" % service["description"])
print(" Provided By: %s" % service["provider"])
print(" Protocol: %s" % service["protocol"])
print(" channel/PSM: %s" % service["port"])
print(" svc classes: %s "% service["service-classes"])
print(" profiles: %s "% service["profiles"])
print(" service id: %s "% service["service-id"])
设备通信代码
设备通信分服务端和客户端
服务器端代码
import bluetooth
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
port = 1
server_sock.bind(("",port))
server_sock.listen(1)
client_sock,address = server_sock.accept()
print "Accepted connection from ",address
data = client_sock.recv(1024)
print "received [%s]" % data
client_sock.close()
server_sock.close()
客户端代码
import bluetooth
bd_addr = "01:23:45:67:89:AB"
port = 1
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))
sock.send("hello!!")
sock.close()
还有另一种方式是使用L2CAP方式,
区别只在端口的选择上,这里不再详述