edge_Equipment/yzq(手柄闭环算法验证)/bt_test.py

77 lines
2.3 KiB
Python

import bluetooth
import time
# 蓝牙服务器地址 (接收设备的 MAC 地址)
server_address = '0C:B7:89:58:8E:6E' # 替换为接收设备的蓝牙地址
# 文件路径 (需要从此文件中读取数据)
file_path = 'data.txt'
# 数据块大小 (1 KB)
chunk_size = 1024 # 每次发送 1 KB 数据块
def find_rfcomm_port(server_address):
"""查找蓝牙服务的RFCOMM端口"""
services = bluetooth.find_service(address=server_address)
for svc in services:
# 假设服务名称为 'Serial Port',根据实际情况进行调整
if svc['name'] == 'Classic BlueTooth':
return svc['port']
return None
def send_file_contents(file_path, chunk_size, sock):
"""从文件中读取整个内容并分块发送"""
total_bytes_sent = 0
try:
with open(file_path, 'r') as file:
start_time = time.time() # 记录开始时间
while True:
# 读取数据块
data_chunk = file.read(chunk_size)
if not data_chunk:
# 文件读取完毕
break
# 发送数据块
sock.send(data_chunk.encode('utf-8'))
# 累计发送的字节数
total_bytes_sent += len(data_chunk)
end_time = time.time() # 记录结束时间
# 计算并打印累计发送速率
elapsed_time = end_time - start_time
if elapsed_time > 0:
total_send_rate = total_bytes_sent / elapsed_time
print(f"累计发送速率: {total_send_rate / 1024:.2f} KB/s")
except Exception as e:
print(f"读取文件时出错: {e}")
try:
# 查找RFCOMM端口
port = find_rfcomm_port(server_address)
if port is None:
print("无法找到蓝牙服务端口")
else:
# 创建蓝牙 socket
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
# 连接到蓝牙设备
sock.connect((server_address, port))
print(f"已连接到蓝牙设备,端口: {port}")
# 发送整个文件内容
send_file_contents(file_path, chunk_size, sock)
finally:
# 关闭 socket
if 'sock' in locals():
sock.close()
print("已断开蓝牙连接")