import bluetooth
import time
try:
target_address = '7A:01:4A:FF:FF:FF'
target_port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((target_address, target_port))
sock.settimeout(0.5)
buffer_size = 1024
received_data = b""
hex_string = "0x24 0x52 0x55 0x49"
ascii_string = ''.join(chr(int(i, 16)) for i in hex_string.split())
message = ascii_string.encode() + b"\xF0" + b"#\r\n"
# message = b"$RDI" + b"\xDF#" + b"\r\n"
print(message)
while True:
sock.send(message)
try:
received_data = sock.recv(buffer_size)
if received_data:
print("Received data:", received_data.decode())
else:
print("No data received...")
except bluetooth.btcommon.BluetoothError as e:
print("Error receiving data:", e)
print("Resending command...")
time.sleep(1)
except bluetooth.btcommon.BluetoothError as e:
print("Connection failed:", e)
finally:
sock.close()
若进程阻塞在sock.recv(),则需要设置sock.settimeout(0.5)。