Project

General

Profile

Feature #10505 » test.py

Bogdan N., 04/17/2023 12:44 AM

 
import struct
import serial
import time
def print_hex(data):
for i in range(0, len(data), 8):
print(" ".join(["%02x" % b for b in data[i:i+8]]))

def print_hex_ascii(data):
for i in range(0, len(data), 8):
print(" ".join(["%02x" % b for b in data[i:i+8]]), "\t", "".join([chr(b) if 32 <= b < 127 else "." for b in data[i:i+8]]))

def _init(ser):
magic = bytearray([0x50, 0xbb, 0xff, 0x20, 0x12, 0x07, 0x25])
ser.write(magic)
time.sleep(0.02)

ack = ser.read(1)
if ack != b"\x06":
if ack:
print("wrong ack", repr(ack))
exit()

ser.write(b"\x02")

response = b""
for i in range(1, 13):
byte = ser.read(1)
response += byte
if byte == b"\xDD":
break

if len(response) in [8, 12]:
print("Valid response, got this:")
print(response)
if len(response) == 12:
ident = (bytes([response[0], response[3], response[5]]) + response[7:])
else:
ident = response
else:
# bad response
msg = "Unexpected response:"
msg += " ".join(["%02x" % b for b in response])
print(msg)


print("Sending ACK")
ser.write(b"\x06")
ack = ser.read(1)
if ack != b"\x06":
print("Radio refused clone")
exit()
return ident

def _read_block(radio, start, size, first_command=False):
msg = struct.pack(">BHB", ord("S"), start, size)
radio.write(msg)

if first_command is False:
ack = radio.read(1)
if ack != b"\x06":
print("Radio refused to send second block 0x%04x" % start)
exit()

answer = radio.read(4)

if len(answer) != 4:
print("Radio refused to send block 0x%04x" % start)
exit()

cmd, addr, length = struct.unpack(">BHB", answer)

if cmd != ord("X") or addr != start or length != size:
print("Invalid answer for block 0x%04x:" % start)
print("CMD: %s ADDR: %04x SIZE: %02x" % (cmd, addr, length))
exit()

chunk = radio.read(size)

if not chunk:
print("Radio did not send block 0x%04x" % start)
exit()
elif len(chunk) != size:
print("Chunk length was 0x%04i" % len(chunk))
exit()

radio.write(b"\x06")
#time.sleep(0.01)
return chunk

ser = serial.Serial('COM3', 9600, bytesize=8, parity='N', stopbits=1, timeout=None)

_init(ser)


'''
block = _read_block(ser, 0x1EC0, 0x40, True)
print_hex_ascii(block)
print()
block = _read_block(ser, 0x1E80, 0x40, False)
print_hex_ascii(block)
print()
block = _read_block(ser, 0x1EC0, 0x40, False)
print_hex_ascii(block)
print()
'''


print("=====================================================")
_read_block(ser, 0x0000, 0x40, True)

for i in range(0x0000, 0x2000, 0x40):
block1 = _read_block(ser, i, 0x40, False)
dummy = _read_block(ser, 0x0000, 0x40, False)
block2 = _read_block(ser, i, 0x40, False)
print("\nBlock: %04x" % i)
print_hex_ascii(block1)

# compare block1 and block2
if block1 != block2:
print("\n========================================")
print("--> Block 1 and 2 are different!")
print("\nBlock 1:")
print_hex_ascii(block1)
print("\nBlock 2:")
print_hex_ascii(block2)
print("\nDummy:")
print_hex_ascii(dummy)
print("========================================")

ser.close()
(9-9/41)