Skip to content

Commit eee3983

Browse files
author
andy
committed
add bluetooth
1 parent 3549212 commit eee3983

File tree

3 files changed

+73
-2
lines changed

3 files changed

+73
-2
lines changed

devices/wtvb01_bt50.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,13 @@ def __init__(self):
1313
self.baud = 115200
1414
self.serial: Optional[SerialDriver, None] = None
1515

16-
def build_device(self):
16+
def build_device_by_serial(self):
1717
self.serial = SerialDriver()
1818
self.serial.init(self.baud)
1919

20+
def build_device_by_bluetooth(self):
21+
pass
22+
2023
def read_data(self):
2124
"""
2225
read buffer
@@ -87,7 +90,7 @@ def get_viration_hz(self, data) -> dict:
8790

8891
if __name__ == '__main__':
8992
device = WVTB01_BT50()
90-
device.build_device()
93+
device.build_device_by_serial()
9194
while True:
9295
data = device.read_data()
9396

drivers/bluetooth_driver.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import bluetooth
2+
3+
4+
class BluetoothDevice:
5+
6+
@classmethod
7+
def find_deveces(cls):
8+
print("Finding nearby bluetooth devices, please wait for several seconds...")
9+
devices = bluetooth.discover_devices(duration=30, lookup_names=True)
10+
for address, name in devices:
11+
print(address, name)
12+
13+
def __init__(self):
14+
self.sock = None
15+
16+
def build_device(self, device_mac_addr):
17+
print(f"Connecting {device_mac_addr}...")
18+
try:
19+
self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
20+
self.sock.connect((device_mac_addr, 1))
21+
except Exception as e:
22+
print(f"Connecting {device_mac_addr} failed")
23+
print(e)
24+
25+
def send(self, data):
26+
self.sock.send(data)
27+
28+
def receive(self, lenth):
29+
data = self.sock.recv(lenth)
30+
return data
31+
32+
33+
if __name__ == '__main__':
34+
b = BluetoothDevice()
35+
devices = b.find_deveces()
36+
37+
addr = "06:9C:F5:AC:F7:BC"
38+
b.build_device(addr)
39+
# print(b.receive(28))
40+
# for i in devices:
41+
# b.build_device(i)
42+
# # print(b.receive(28))

drivers/test.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import bluetooth
2+
3+
# 创建一个蓝牙服务端套接字
4+
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
5+
6+
# 绑定本地的一个端口
7+
port = bluetooth.PORT_ANY
8+
server_sock.bind(port)
9+
10+
# 开始监听,最多允许1个连接
11+
server_sock.listen(1)
12+
13+
print("Waiting for connection...")
14+
15+
# 接受客户端的连接请求
16+
client_sock, address = server_sock.accept()
17+
18+
print("Connected to ", address)
19+
20+
# 接收数据
21+
data = client_sock.recv(1024)
22+
print("Received data:", data)
23+
24+
# 关闭套接字
25+
client_sock.close()
26+
server_sock.close()

0 commit comments

Comments
 (0)