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 packed = pack_pkt(ARE_CMD, [str(i)])
31 info = dev.recv_data(23)
32 msg = unpack_pkt(info)
34 KOA, SAD, EAD, EAU, WAU = struct.unpack(fmt, bytes(int(x, 16) for x in msg))
35 print(f'Area {KOA}: {hex(SAD)}:{hex(EAD)} (erase {hex(EAU)} - write {hex(WAU)})')
37 def get_dev_info(dev):
38 packed = pack_pkt(SIG_CMD, "")
40 info = dev.recv_data(18)
42 _HEADER, SCI, RMB, NOA, TYP, BFV, _FOOTER = struct.unpack(fmt, info)
43 print('====================')
45 print('Chip: RA MCU + RA2/RA4 Series')
47 print('Chip: RA MCU + RA6 Series')
49 print('Unknown MCU type')
50 print(f'Serial interface speed: {SCI} Hz')
51 print(f'Recommend max UART baud rate: {RMB} bps')
52 print(f'User area in Code flash [{NOA & 0x1}|{NOA & 0x02 >> 1}]')
53 print(f'User area in Data flash [{NOA & 0x03 >> 2}]')
54 print(f'Config area [{NOA & 0x04 >> 3}]')
55 print(f'Boot firmware: version {BFV >> 8}.{BFV & 0xFF}')
58 def verify_img(dev, img, start_addr, end_addr):
59 raise Exception("Not implemented")
61 def read_img(dev, img, start_addr, end_addr):
63 # calculate / check start and end address
64 if start_addr == None or end_addr == None:
65 if start_addr == None:
68 if start_addr % SECTOR_SIZE:
69 raise ValueError(f"start addr not aligned on sector size {SECTOR_SIZE}")
70 blocks = (file_size + SECTOR_SIZE - 1) // SECTOR_SIZE
71 end_addr = blocks * SECTOR_SIZE + start_addr
73 if (start_addr > 0xFF800): # for RA4 series
74 raise ValueError("start address value error")
75 if (end_addr <= start_addr or end_addr > 0xFF800):
76 raise ValueError("end address value error")
78 # setup initial communication
79 SAD = int_to_hex_list(start_addr)
80 EAD = int_to_hex_list(end_addr)
81 packed = pack_pkt(REA_CMD, SAD + EAD)
84 # calculate how many packets are have to be received
85 nr_packet = (end_addr - start_addr) // 1024 # TODO: set other than just 1024
87 with open('output.bin', 'wb') as f:
88 for i in tqdm(range(0, nr_packet+1), desc="Reading progess"):
89 ret = dev.recv_data(1024 + 6)
90 chunk = unpack_pkt(ret)
91 chunky = bytes(int(x, 16) for x in chunk)
93 packed = pack_pkt(REA_CMD, ['0x00'], ack=True)
97 def write_img(dev, img, start_addr, end_addr, verify=False):
99 if os.path.exists(img):
100 file_size = os.path.getsize(img)
102 raise Exception(f'file {img} does not exist')
104 # calculate / check start and end address
105 if start_addr == None or end_addr == None:
106 if start_addr == None:
109 if start_addr % SECTOR_SIZE:
110 raise ValueError(f"start addr not aligned on sector size {SECTOR_SIZE}")
111 blocks = (file_size + SECTOR_SIZE - 1) // SECTOR_SIZE
112 end_addr = blocks * SECTOR_SIZE + start_addr - 1
114 chunk_size = 1024 # max is 1024
115 #if (start_addr > 0xFF800): # for RA4 series
116 # raise ValueError("start address value error")
117 #if (end_addr <= start_addr or end_addr > 0xFF800):
118 # raise ValueError("end address value error")
120 # setup initial communication
121 SAD = int_to_hex_list(start_addr)
122 EAD = int_to_hex_list(end_addr)
123 #packed = pack_pkt(ERA_CMD, SAD + EAD) # actually works
124 packed = pack_pkt(WRI_CMD, SAD + EAD)
125 dev.send_data(packed)
126 ret = dev.recv_data(7)
129 with open(img, 'rb') as f:
130 with tqdm(total=file_size, desc="Sending chunks") as pbar:
131 chunk = f.read(chunk_size)
132 pbar.update(len(chunk))
134 if len(chunk) != chunk_size:
135 padding_length = chunk_size - len(chunk)
136 chunk += b'\0' * padding_length
137 packed = pack_pkt(WRI_CMD, chunk, ack=True)
138 dev.send_data(packed)
140 reply = dev.recv_data(reply_len)
141 msg = unpack_pkt(reply)
142 chunk = f.read(chunk_size)
143 pbar.update(len(chunk))
147 parser = argparse.ArgumentParser(description="RA Flasher Tool")
149 subparsers = parser.add_subparsers(dest="command", title="Commands")
151 # Subparser for the write command
152 write_parser = subparsers.add_parser("write", help="Write data to flash")
153 write_parser.add_argument("--start_address", type=int, default=0x0000, help="Start address")
154 write_parser.add_argument("--end_address", type=int, help="End address")
155 write_parser.add_argument("--verify", action="store_true", help="Verify after writing")
156 write_parser.add_argument("file_name", type=str, help="File name")
158 # Subparser for the read command
159 read_parser = subparsers.add_parser("read", help="Read data from flash")
160 read_parser.add_argument("--start_address", type=int, default=0x000, help="Start address")
161 read_parser.add_argument("--size", type=int, default=1024, help="Size in bytes")
162 read_parser.add_argument("file_name", type=str, help="File name")
164 # Subparser for the info command
165 subparsers.add_parser("info", help="Show flasher information")
167 args = parser.parse_args()
169 if args.command == "write":
170 dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
171 status_con = inquire_connection(dev)
173 dev.confirm_connection()
174 write_img(dev, "src/sample.bin", 0x8000, None)
175 elif args.command == "read":
176 dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
177 status_con = inquire_connection(dev)
179 dev.confirm_connection()
180 read_img(dev, "save.bin", 0x0000, 0x3FFFF)
181 elif args.command == "info":
182 dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
183 status_con = inquire_connection(dev)
185 dev.confirm_connection()
191 if __name__ == "__main__":