1 # Copyright (C) Robin Krens - 2024
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 from RAConnect import *
25 from RAPacker import *
31 "write": lambda dev, args: write_img(dev, args.file_name, args.start_address, args.size, args.verify),
32 "read": lambda dev, args: read_img(dev, args.file_name, args.start_address, args.size),
33 "erase": lambda dev, args: erase_chip(dev, args.start_address, args.size),
34 "info": lambda dev, args: (get_dev_info(dev), dev.set_chip_layout(get_area_info(dev, output=True)))
37 def int_to_hex_list(num):
38 hex_string = hex(num)[2:].upper() # convert to hex string
39 hex_string = hex_string.zfill(8) # pad for 8 char's long
40 hex_list = [f'0x{hex_string[c:c+2]}' for c in range(0, 8, 2)]
45 value = int(string, 16)
48 raise argparse.ArgumentTypeError(f"'{string}' is not a valid hexadecimal value.")
50 def set_size_boundaries(dev, start_addr, size):
52 sector_size = dev.chip_layout[dev.sel_area]['ALIGN'] # currently only area 0 supported
54 if start_addr % sector_size:
55 raise ValueError(f"start addr not aligned on sector size {sector_size}")
57 if size < sector_size:
58 print("Warning: you are trying to write something that is less than one sector size: padding with zeroes")
60 blocks = (size + sector_size - 1) // sector_size
61 end_addr = blocks * sector_size + start_addr - 1
63 if (end_addr <= start_addr):
64 raise ValueError(f"End address smaller or equal than start_address")
66 if (end_addr > dev.chip_layout[dev.sel_area]['EAD']):
67 raise ValueError(f"Binary file is bigger than available ROM space")
69 return (start_addr, end_addr)
71 def get_area_info(dev, output=False):
74 packed = pack_pkt(ARE_CMD, [str(i)])
76 info = dev.recv_data(23)
77 msg = unpack_pkt(info)
79 KOA, SAD, EAD, EAU, WAU = struct.unpack(fmt, bytes(int(x, 16) for x in msg))
80 cfg[i] = {"SAD": SAD, "EAD": EAD, "ALIGN": EAU}
82 print(f'Area {KOA}: {hex(SAD)}:{hex(EAD)} (erase {hex(EAU)} - write {hex(WAU)})')
86 def get_dev_info(dev):
87 packed = pack_pkt(SIG_CMD, "")
89 info = dev.recv_data(18)
91 _HEADER, SCI, RMB, NOA, TYP, BFV, _FOOTER = struct.unpack(fmt, info)
92 print('====================')
94 print('Chip: RA MCU + RA2/RA4 Series')
96 print('Chip: RA MCU + RA6 Series')
98 print('Unknown MCU type')
99 print(f'Serial interface speed: {SCI} Hz')
100 print(f'Recommend max UART baud rate: {RMB} bps')
101 print(f'User area in Code flash [{NOA & 0x1}|{NOA & 0x02 >> 1}]')
102 print(f'User area in Data flash [{NOA & 0x03 >> 2}]')
103 print(f'Config area [{NOA & 0x04 >> 3}]')
104 print(f'Boot firmware: version {BFV >> 8}.{BFV & 0xFF}')
106 def erase_chip(dev, start_addr, size):
109 size = dev.chip_layout[dev.sel_area]['EAD'] - start_addr # erase all
111 (start_addr, end_addr) = set_size_boundaries(dev, start_addr, size)
112 print(f'Erasing {hex(start_addr)}:{hex(end_addr)}')
114 # setup initial communication
115 SAD = int_to_hex_list(start_addr)
116 EAD = int_to_hex_list(end_addr)
117 packed = pack_pkt(ERA_CMD, SAD + EAD)
118 dev.send_data(packed)
120 ret = dev.recv_data(7, timeout=1000) # erase takes usually a bit longer
122 print("Erase complete")
124 def read_img(dev, img, start_addr, size):
127 size = 0x3FFFF - start_addr # read maximum possible
129 (start_addr, end_addr) = set_size_boundaries(dev, start_addr, size)
131 # setup initial communication
132 SAD = int_to_hex_list(start_addr)
133 EAD = int_to_hex_list(end_addr)
134 packed = pack_pkt(REA_CMD, SAD + EAD)
135 dev.send_data(packed)
137 # calculate how many packets are have to be received
138 nr_packet = (end_addr - start_addr) // 1024 # TODO: set other than just 1024
140 with open(img, 'wb') as f:
141 for i in tqdm(range(0, nr_packet+1), desc="Reading progress"):
142 ret = dev.recv_data(1024 + 6)
143 chunk = unpack_pkt(ret)
144 chunky = bytes(int(x, 16) for x in chunk)
146 packed = pack_pkt(REA_CMD, ['0x00'], ack=True)
147 dev.send_data(packed)
150 def write_img(dev, img, start_addr, size, verify=False):
152 if os.path.exists(img):
153 file_size = os.path.getsize(img)
155 raise Exception(f'file {img} does not exist')
161 raise ValueError("Write size > file size")
163 (start_addr, end_addr) = set_size_boundaries(dev, start_addr, size)
165 chunk_size = 1024 # max is 1024 according to protocol
167 # setup initial communication
168 SAD = int_to_hex_list(start_addr)
169 EAD = int_to_hex_list(end_addr)
170 packed = pack_pkt(WRI_CMD, SAD + EAD)
171 dev.send_data(packed)
172 ret = dev.recv_data(7)
176 with open(img, 'rb') as f:
177 with tqdm(total=size, desc="Writing progress") as pbar:
178 chunk = f.read(chunk_size)
179 pbar.update(len(chunk))
180 while chunk and totalread < size:
181 if len(chunk) != chunk_size:
182 padding_length = chunk_size - len(chunk)
183 chunk += b'\0' * padding_length
184 packed = pack_pkt(WRI_CMD, chunk, ack=True)
185 dev.send_data(packed)
187 reply = dev.recv_data(reply_len)
188 msg = unpack_pkt(reply)
189 chunk = f.read(chunk_size)
190 totalread += chunk_size
191 pbar.update(len(chunk))
195 with tempfile.NamedTemporaryFile(prefix='.hidden_', delete=False) as tmp_file, open(img, 'rb') as cmp_file:
196 read_img(dev, tmp_file.name, start_addr, size)
197 c1 = tmp_file.read(file_size) # due to byte alignment read file is longer
200 print("Verify complete")
202 print("Verify failed")
205 parser = argparse.ArgumentParser(description="RA Flasher Tool")
207 subparsers = parser.add_subparsers(dest="command", title="Commands")
209 write_parser = subparsers.add_parser("write", help="Write data to flash")
210 write_parser.add_argument("--start_address", type=hex_type, default='0x0000', help="Start address")
211 write_parser.add_argument("--size", type=hex_type, default=None, help="Size in bytes")
212 write_parser.add_argument("--verify", action="store_true", help="Verify after writing")
213 write_parser.add_argument("file_name", type=str, help="File name")
215 read_parser = subparsers.add_parser("read", help="Read data from flash")
216 read_parser.add_argument("--start_address", type=hex_type, default='0x0000', help="Start address")
217 read_parser.add_argument("--size", type=hex_type, default=None, help="Size in bytes")
218 read_parser.add_argument("file_name", type=str, help="File name")
220 erase_parser = subparsers.add_parser("erase", help="Erase sectors")
221 erase_parser.add_argument("--start_address", default='0x0000', type=hex_type, help="Start address")
222 erase_parser.add_argument("--size", type=hex_type, help="Size")
224 subparsers.add_parser("info", help="Show flasher information")
226 args = parser.parse_args()
228 if args.command in commands:
229 dev = RAConnect(VENDOR_ID, PRODUCT_ID)
230 area_cfg = get_area_info(dev)
231 dev.set_chip_layout(area_cfg)
232 commands[args.command](dev, args)
236 if __name__ == "__main__":