Zen的小站

小舟从此逝,江海寄余生

0%

【pybluez】python控制PC蓝牙

pybluez库可以像操纵串口一样控制电脑自带蓝牙,可以搜索周围蓝牙、连接并收发数据。

对我来说能用电脑蓝牙和 HC05 这样的蓝牙模块连接了,之前一直觉得很奇怪,因为用蓝牙通信都是两个蓝牙模块,一个插电脑并用串口调试助手连接,另一个连接小车或机器人。现在可以做一个蓝牙调试助手了。

安装过程略

搜索蓝牙

​ 保证自己开启蓝牙后,nearby_devices = bluetooth.discover_devices(lookup_names=True),返回附近可连接蓝牙的地址名字(返回数组,里面是元组)

通过RFCOMM方式进行通信(客户端)

操作方式类似 socket

连接蓝牙

  1. 实例化一个对象 sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

  2. 提供连接地址并连接 sock.connect((target_address, 1))

收发数据

  • 发送数据 sock.send("xxxxxxx".encode())
  • 接收数据 data = sock.recv(1024)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import datetime
import time

# win10 安装蓝牙依赖包 https://blog.csdn.net/weixin_38676276/article/details/113027104
import bluetooth


class BluetoothConnection:
def __init__(self):
# 是否找到到设备
self.find = False
# 附近蓝牙设备
self.nearby_devices = None

def find_nearby_devices(self):
print("Detecting nearby Bluetooth devices...")
# 可传参数 duration--持续时间 lookup-name=true 显示设备名
# 大概查询10s左右
# 循环查找次数
loop_num = 3
i = 0
try:
self.nearby_devices = bluetooth.discover_devices(lookup_names=True, duration=5)
while self.nearby_devices.__len__() == 0 and i < loop_num:
self.nearby_devices = bluetooth.discover_devices(lookup_names=True, duration=5)
if self.nearby_devices.__len__() > 0:
break
i = i + 1
time.sleep(2)
print("No Bluetooth device around here! trying again {}...".format(str(i)))
if not self.nearby_devices:
print("There's no Bluetooth device around here. Program stop!")
else:
print("{} nearby Bluetooth device(s) has(have) been found:".format(self.nearby_devices.__len__()),
self.nearby_devices) # 附近所有可连的蓝牙设备s
except Exception as e:
# print(traceback.format_exc())
# 不知是不是Windows的原因,当附近没有蓝牙设备时,bluetooth.discover_devices会报错。
print("There's no Bluetooth device around here. Program stop(2)!")

def find_target_device(self, target_name, target_address):
self.find_nearby_devices()
if self.nearby_devices:
for addr, name in self.nearby_devices:
if target_name == name and target_address == addr:
print("Found target bluetooth device with address:{} name:{}".format(target_address, target_name))
self.find = True
break
if not self.find:
print("could not find target bluetooth device nearby. "
"Please turn on the Bluetooth of the target device.")

def connect_target_device(self, target_name, target_address):
self.find_target_device(target_name=target_name, target_address=target_address)
if self.find:
print("Ready to connect")
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

try:
sock.connect((target_address, 1))
print("Connection successful. Now ready to get the data")
data_dtr = ""
while True:
# sock.send("qwer".encode())
# print("send qwer")
data = sock.recv(1024)
data_dtr += data.decode()
if '\n' in data.decode():
# data_dtr[:-2] 截断"\t\n",只输出数据
print(datetime.datetime.now().strftime("%H:%M:%S") + "->" + data_dtr[:-2])
data_dtr = ""
except Exception as e:
print("connection fail\n", e)
sock.close()


if __name__ == '__main__':
target_name = "=car"
target_address = '18:A3:25:02:6B:B6'
BluetoothConnection().connect_target_device(target_name=target_name, target_address=target_address)

其他

不知怎么弄服务端,也不明白

此外还有通过L2CAP方式进行通信,不太清楚这两种都是啥,后续再补

多想多做,发篇一作

-------------本文结束感谢您的阅读-------------
// 在最后添加