7 from RAConnect import *
12 def int_to_hex_list(num):
13 hex_string = hex(num)[2:].upper() # convert to hex string
14 hex_string = hex_string.zfill(8) # pad for 8 char's long
15 hex_list = [f'0x{hex_string[c:c+2]}' for c in range(0, 8, 2)]
18 def inquire_connection(dev):
19 packed = pack_pkt(INQ_CMD, "")
21 info = dev.recv_data(7)
22 if info == bytearray(b'\x00') or info == bytearray(b''):
24 msg = unpack_pkt(info)
25 #print("Connection already established")
28 def get_area_info(dev):
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)} (erase {hex(EAU)} - write {hex(WAU)})')
38 def get_dev_info(dev):
39 packed = pack_pkt(SIG_CMD, "")
41 info = dev.recv_data(18)
43 _HEADER, SCI, RMB, NOA, TYP, BFV, _FOOTER = struct.unpack(fmt, info)
44 print('====================')
46 print('Chip: RA MCU + RA2/RA4 Series')
48 print('Chip: RA MCU + RA6 Series')
50 print('Unknown MCU type')
51 print(f'Serial interface speed: {SCI} Hz')
52 print(f'Recommend max UART baud rate: {RMB} bps')
53 print(f'User area in Code flash [{NOA & 0x1}|{NOA & 0x02 >> 1}]')
54 print(f'User area in Data flash [{NOA & 0x03 >> 2}]')
55 print(f'Config area [{NOA & 0x04 >> 3}]')
56 print(f'Boot firmware: version {BFV >> 8}.{BFV & 0xFF}')
59 def verify_img(dev, img, start_addr, end_addr):
60 raise Exception("Not implemented")
62 def read_img(dev, img, start_addr, end_addr):
64 # calculate / check start and end address
65 if start_addr == None or end_addr == None:
66 if start_addr == None:
69 if start_addr % SECTOR_SIZE:
70 raise ValueError(f"start addr not aligned on sector size {SECTOR_SIZE}")
71 blocks = (file_size + SECTOR_SIZE - 1) // SECTOR_SIZE
72 end_addr = blocks * SECTOR_SIZE + start_addr
74 if (start_addr > 0xFF800): # for RA4 series
75 raise ValueError("start address value error")
76 if (end_addr <= start_addr or end_addr > 0xFF800):
77 raise ValueError("end address value error")
79 # setup initial communication
80 SAD = int_to_hex_list(start_addr)
81 EAD = int_to_hex_list(end_addr)
82 packed = pack_pkt(REA_CMD, SAD + EAD)
85 # calculate how many packets are have to be received
86 nr_packet = (end_addr - start_addr) // 1024 # TODO: set other than just 1024
88 with open(img, 'wb') as f:
89 for i in tqdm(range(0, nr_packet+1), desc="Reading progess"):
90 ret = dev.recv_data(1024 + 6)
91 chunk = unpack_pkt(ret)
92 chunky = bytes(int(x, 16) for x in chunk)
94 packed = pack_pkt(REA_CMD, ['0x00'], ack=True)
98 def write_img(dev, img, start_addr, end_addr, verify=False):
100 if os.path.exists(img):
101 file_size = os.path.getsize(img)
103 raise Exception(f'file {img} does not exist')
105 # calculate / check start and end address
106 if start_addr == None or end_addr == None:
107 if start_addr == None:
110 if start_addr % SECTOR_SIZE:
111 raise ValueError(f"start addr not aligned on sector size {SECTOR_SIZE}")
112 blocks = (file_size + SECTOR_SIZE - 1) // SECTOR_SIZE
113 end_addr = blocks * SECTOR_SIZE + start_addr - 1
115 chunk_size = 1024 # max is 1024
116 #if (start_addr > 0xFF800): # for RA4 series
117 # raise ValueError("start address value error")
118 #if (end_addr <= start_addr or end_addr > 0xFF800):
119 # raise ValueError("end address value error")
121 # setup initial communication
122 SAD = int_to_hex_list(start_addr)
123 EAD = int_to_hex_list(end_addr)
124 #packed = pack_pkt(ERA_CMD, SAD + EAD) # actually works
125 packed = pack_pkt(WRI_CMD, SAD + EAD)
126 dev.send_data(packed)
127 ret = dev.recv_data(7)
130 with open(img, 'rb') as f:
131 with tqdm(total=file_size, desc="Writing progress") as pbar:
132 chunk = f.read(chunk_size)
133 pbar.update(len(chunk))
135 if len(chunk) != chunk_size:
136 padding_length = chunk_size - len(chunk)
137 chunk += b'\0' * padding_length
138 packed = pack_pkt(WRI_CMD, chunk, ack=True)
139 dev.send_data(packed)
141 reply = dev.recv_data(reply_len)
142 msg = unpack_pkt(reply)
143 chunk = f.read(chunk_size)
144 pbar.update(len(chunk))
148 with tempfile.NamedTemporaryFile(prefix='.hidden_', delete=False) as tmp_file, open(img, 'rb') as cmp_file:
149 read_img(dev, tmp_file.name, start_addr, end_addr)
150 c1 = tmp_file.read(file_size) # due to byte alignment read file is longer
153 print("Verify complete")
155 print("Verify failed")
158 parser = argparse.ArgumentParser(description="RA Flasher Tool")
160 subparsers = parser.add_subparsers(dest="command", title="Commands")
162 # Subparser for the write command
163 write_parser = subparsers.add_parser("write", help="Write data to flash")
164 write_parser.add_argument("--start_address", type=int, default=0x0000, help="Start address")
165 write_parser.add_argument("--end_address", type=int, help="End address")
166 write_parser.add_argument("--verify", action="store_true", help="Verify after writing")
167 write_parser.add_argument("file_name", type=str, help="File name")
169 # Subparser for the read command
170 read_parser = subparsers.add_parser("read", help="Read data from flash")
171 read_parser.add_argument("--start_address", type=int, default=0x000, help="Start address")
172 read_parser.add_argument("--size", type=int, default=1024, help="Size in bytes")
173 read_parser.add_argument("file_name", type=str, help="File name")
175 # Subparser for the info command
176 subparsers.add_parser("info", help="Show flasher information")
178 args = parser.parse_args()
180 if args.command == "write":
181 dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
182 status_con = inquire_connection(dev)
184 dev.confirm_connection()
185 write_img(dev, "src/sample.bin", 0x8000, None, True)
186 elif args.command == "read":
187 dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
188 status_con = inquire_connection(dev)
190 dev.confirm_connection()
191 read_img(dev, "save.bin", 0x0000, 0x3FFFF)
192 elif args.command == "info":
193 dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
194 status_con = inquire_connection(dev)
196 dev.confirm_connection()
202 if __name__ == "__main__":