92 lines
2.7 KiB
Python
92 lines
2.7 KiB
Python
import bluetooth
|
||
import time
|
||
import random
|
||
|
||
# 蓝牙服务器地址 (接收设备的 MAC 地址)
|
||
server_address = '0C:B7:89:58:8E:6E' # 替换为接收设备的蓝牙地址
|
||
port = 8 # 一般使用RFCOMM的端口号
|
||
|
||
# 文件路径 (需要从此文件中随机读取数据)
|
||
file_path = 'data.txt'
|
||
|
||
# 数据块大小 (1 KB)
|
||
chunk_size = 1024 # 每次发送 1 KB 数据
|
||
|
||
# 发送持续时间(秒),0 表示无限持续发送
|
||
duration = 0 # 例如:持续发送 60 秒
|
||
|
||
# 创建蓝牙 socket
|
||
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
|
||
|
||
# 函数:从文件中随机读取一块数据
|
||
def read_random_chunk(file_path, chunk_size):
|
||
with open(file_path, 'r') as file:
|
||
# 获取文件大小
|
||
file.seek(0, 2) # 将文件指针移动到文件末尾
|
||
file_size = file.tell()
|
||
|
||
# 生成随机的起始位置
|
||
random_start = random.randint(0, file_size - chunk_size)
|
||
|
||
# 从随机位置读取 chunk_size 大小的数据块
|
||
file.seek(random_start)
|
||
data_chunk = file.read(chunk_size)
|
||
|
||
# 如果读取的数据不足 chunk_size,则补足
|
||
if len(data_chunk) < chunk_size:
|
||
data_chunk += " " * (chunk_size - len(data_chunk))
|
||
|
||
return data_chunk
|
||
|
||
try:
|
||
# 连接到蓝牙设备
|
||
sock.connect((server_address, port))
|
||
print("已连接到蓝牙设备")
|
||
|
||
# 记录开始时间
|
||
start_time = time.time()
|
||
last_time = start_time
|
||
|
||
# 初始化总发送字节数
|
||
total_bytes_sent = 0
|
||
|
||
while True:
|
||
# 随机读取一个数据块
|
||
data_chunk = read_random_chunk(file_path, chunk_size)
|
||
|
||
# 记录发送前的时间
|
||
send_time = time.time()
|
||
|
||
# 发送数据块
|
||
sock.send(data_chunk.encode('utf-8'))
|
||
|
||
# 记录发送后的时间
|
||
end_time = time.time()
|
||
|
||
# 计算发送该数据块的时延
|
||
latency = end_time - send_time
|
||
|
||
# 累计发送的字节数
|
||
total_bytes_sent += len(data_chunk)
|
||
|
||
# 计算发送速率 (字节/秒)
|
||
send_rate = len(data_chunk) / latency
|
||
|
||
# 计算并打印实时发送速率
|
||
print(f"发送数据块,大小: {len(data_chunk)} 字节,用时: {latency:.6f} 秒,速率: {send_rate / 1024:.2f} KB/s")
|
||
|
||
# 计算并打印累计发送速率
|
||
elapsed_time = time.time() - start_time
|
||
if elapsed_time > 0:
|
||
total_send_rate = total_bytes_sent / elapsed_time
|
||
print(f"累计发送速率: {total_send_rate / 1024:.2f} KB/s")
|
||
|
||
# 如果设置了持续时间,则检查是否超时
|
||
if duration > 0 and elapsed_time >= duration:
|
||
break
|
||
|
||
finally:
|
||
# 关闭 socket
|
||
sock.close()
|
||
print("已断开蓝牙连接")
|