6 from RAConnect import *
11 def int_to_hex_list(num):
12 hex_string = hex(num)[2:].upper() # convert to hex string
13 hex_string = hex_string.zfill(8) # pad for 8 char's long
14 hex_list = [f'0x{hex_string[c:c+2]}' for c in range(0, 8, 2)]
17 def inquire_connection(dev):
18 packed = pack_pkt(INQ_CMD, "")
20 info = dev.recv_data(7)
21 if info == bytearray(b'\x00') or info == bytearray(b''):
23 msg = unpack_pkt(info)
24 #print("Connection already established")
27 def get_area_info(dev):
29 print("===================")
30 packed = pack_pkt(ARE_CMD, [str(i)])
32 info = dev.recv_data(23)
33 msg = unpack_pkt(info)
35 KOA, SAD, EAD, EAU, WAU = struct.unpack(fmt, bytes(int(x, 16) for x in msg))
36 print(f'Area {KOA} - {hex(SAD)}:{hex(EAD)}')
37 print(f'Erase {hex(EAU)} bytes - write {hex(WAU)} bytes')
39 def get_dev_info(dev):
41 packed = pack_pkt(SIG_CMD, "")
43 info = dev.recv_data(18)
45 _HEADER, SCI, RMB, NOA, TYP, BFV, _FOOTER = struct.unpack(fmt, info)
47 print('====================')
48 print(f'Serial interface speed: {SCI} Hz')
49 print(f'Recommend max UART baud rate {RMB} bps')
50 print(f'User area in Code flash [{NOA & 0x1}|{NOA & 0x02 >> 1}]')
51 print(f'User area in Data flash [{NOA & 0x03 >> 2}]')
52 print(f'Config area [{NOA & 0x04 >> 3}]')
54 print('RA MCU + RA2/RA4 Series')
56 print('RA MCU + RA6 Series')
58 print('Unknown MCU type')
59 print(f'Boot firmware version {BFV >> 8}.{BFV & 0xFF}')
60 print('====================')
63 def verify_img(dev, img, start_addr, end_addr):
64 raise Exception("Not implemented")
66 def read_img(dev, img, start_addr, end_addr):
68 # calculate / check start and end address
69 if start_addr == None or end_addr == None:
70 if start_addr == None:
73 if start_addr % SECTOR_SIZE:
74 raise ValueError(f"start addr not aligned on sector size {SECTOR_SIZE}")
75 blocks = (file_size + SECTOR_SIZE - 1) // SECTOR_SIZE
76 end_addr = blocks * SECTOR_SIZE + start_addr
78 if (start_addr > 0xFF800): # for RA4 series
79 raise ValueError("start address value error")
80 if (end_addr <= start_addr or end_addr > 0xFF800):
81 raise ValueError("end address value error")
83 # setup initial communication
84 SAD = int_to_hex_list(start_addr)
85 EAD = int_to_hex_list(end_addr)
86 packed = pack_pkt(REA_CMD, SAD + EAD)
89 # calculate how many packets are have to be received
90 nr_packet = (end_addr - start_addr) // 1024 # TODO: set other than just 1024
92 with open('output.bin', 'wb') as f:
93 for i in tqdm(range(0, nr_packet+1), desc="Reading progess"):
94 ret = dev.recv_data(1024 + 6)
95 chunk = unpack_pkt(ret)
96 chunky = bytes(int(x, 16) for x in chunk)
98 packed = pack_pkt(REA_CMD, ['0x00'], ack=True)
102 def write_img(dev, img, start_addr, end_addr, verify=False):
104 if os.path.exists(img):
105 file_size = os.path.getsize(img)
107 raise Exception(f'file {img} does not exist')
109 # calculate / check start and end address
110 if start_addr == None or end_addr == None:
111 if start_addr == None:
114 if start_addr % SECTOR_SIZE:
115 raise ValueError(f"start addr not aligned on sector size {SECTOR_SIZE}")
116 blocks = (file_size + SECTOR_SIZE - 1) // SECTOR_SIZE
117 end_addr = blocks * SECTOR_SIZE + start_addr - 1
119 chunk_size = 1024 # max is 1024
120 #if (start_addr > 0xFF800): # for RA4 series
121 # raise ValueError("start address value error")
122 #if (end_addr <= start_addr or end_addr > 0xFF800):
123 # raise ValueError("end address value error")
125 # setup initial communication
126 SAD = int_to_hex_list(start_addr)
127 EAD = int_to_hex_list(end_addr)
128 #packed = pack_pkt(ERA_CMD, SAD + EAD) # actually works
129 packed = pack_pkt(WRI_CMD, SAD + EAD)
130 dev.send_data(packed)
131 ret = dev.recv_data(7)
134 with open(img, 'rb') as f:
135 with tqdm(total=file_size, desc="Sending chunks") as pbar:
136 chunk = f.read(chunk_size)
137 pbar.update(len(chunk))
139 if len(chunk) != chunk_size:
140 padding_length = chunk_size - len(chunk)
141 chunk += b'\0' * padding_length
142 packed = pack_pkt(WRI_CMD, chunk, ack=True)
143 dev.send_data(packed)
145 reply = dev.recv_data(reply_len)
146 msg = unpack_pkt(reply)
147 chunk = f.read(chunk_size)
148 pbar.update(len(chunk))
152 parser = argparse.ArgumentParser(description="RA Flasher Tool")
154 subparsers = parser.add_subparsers(dest="command", title="Commands")
156 # Subparser for the write command
157 write_parser = subparsers.add_parser("write", help="Write data to flash")
158 write_parser.add_argument("--start_address", type=int, default=0x0000, help="Start address")
159 write_parser.add_argument("--end_address", type=int, help="End address")
160 write_parser.add_argument("--verify", action="store_true", help="Verify after writing")
161 write_parser.add_argument("file_name", type=str, help="File name")
163 # Subparser for the read command
164 read_parser = subparsers.add_parser("read", help="Read data from flash")
165 read_parser.add_argument("--start_address", type=int, default=0x000, help="Start address")
166 read_parser.add_argument("--size", type=int, default=1024, help="Size in bytes")
167 read_parser.add_argument("file_name", type=str, help="File name")
169 # Subparser for the info command
170 subparsers.add_parser("info", help="Show flasher information")
172 args = parser.parse_args()
174 if args.command == "write":
175 dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
176 status_con = inquire_connection(dev)
178 dev.confirm_connection()
179 write_img(dev, "src/sample.bin", 0x8000, None)
180 elif args.command == "read":
181 dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
182 status_con = inquire_connection(dev)
184 dev.confirm_connection()
185 read_img(dev, "save.bin", 0x0000, 0x3FFFF)
186 elif args.command == "info":
187 dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
188 status_con = inquire_connection(dev)
190 dev.confirm_connection()
196 if __name__ == "__main__":