0e5659bc1519ce2633323ca683faa7bcb524d690
[renesas-ra-flasher] / src / RAFlasher.py
1 import os
2 import math
3 import time
4 import argparse
5 from tqdm import tqdm
6 from RAConnect import *
7 from RAPacker import *
8
9 SECTOR_SIZE = 2048
10
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)]
15     return hex_list
16
17 def inquire_connection(dev):
18     packed = pack_pkt(INQ_CMD, "")
19     dev.send_data(packed)
20     info = dev.recv_data(7)
21     if info == bytearray(b'\x00') or info == bytearray(b''):
22         return False
23     msg = unpack_pkt(info)
24     #print("Connection already established")
25     return True
26
27 def get_area_info(dev):
28     for i in [0,1,2]:
29         packed = pack_pkt(ARE_CMD, [str(i)])
30         dev.send_data(packed)
31         info = dev.recv_data(23)
32         msg = unpack_pkt(info)
33         fmt = '>BIIII'
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)})')
36
37 def get_dev_info(dev):
38     packed = pack_pkt(SIG_CMD, "")
39     dev.send_data(packed)
40     info = dev.recv_data(18)
41     fmt = '>IIIBBHH'
42     _HEADER, SCI, RMB, NOA, TYP, BFV, _FOOTER = struct.unpack(fmt, info)
43     print('====================')
44     if TYP == 0x02:
45         print('Chip: RA MCU + RA2/RA4 Series')
46     elif TYP == 0x03:
47         print('Chip: RA MCU + RA6 Series')
48     else:
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}')
56
57
58 def verify_img(dev, img, start_addr, end_addr):
59     raise Exception("Not implemented")
60
61 def read_img(dev, img, start_addr, end_addr):
62     
63     # calculate / check start and end address 
64     if start_addr == None or end_addr == None:
65         if start_addr == None:
66             start_addr = 0
67         # align start addr
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
72     
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")
77     
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)
82     dev.send_data(packed)
83
84     # calculate how many packets are have to be received
85     nr_packet = (end_addr - start_addr) // 1024 # TODO: set other than just 1024
86
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)
92             f.write(chunky)
93             packed = pack_pkt(REA_CMD, ['0x00'], ack=True)
94             dev.send_data(packed)
95
96
97 def write_img(dev, img, start_addr, end_addr, verify=False):
98
99     if os.path.exists(img):
100         file_size = os.path.getsize(img)
101     else:
102         raise Exception(f'file {img} does not exist')
103
104     # calculate / check start and end address 
105     if start_addr == None or end_addr == None:
106         if start_addr == None:
107             start_addr = 0
108         # align start addr
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
113     
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")
119
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)
127     unpack_pkt(ret) 
128
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))
133             while 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)
139                 reply_len = 7
140                 reply = dev.recv_data(reply_len)
141                 msg = unpack_pkt(reply)
142                 chunk = f.read(chunk_size)
143                 pbar.update(len(chunk))
144
145
146 def main():
147     parser = argparse.ArgumentParser(description="RA Flasher Tool")
148
149     subparsers = parser.add_subparsers(dest="command", title="Commands")
150
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")
157
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")
163
164     # Subparser for the info command
165     subparsers.add_parser("info", help="Show flasher information")
166
167     args = parser.parse_args()
168
169     if args.command == "write":
170         dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
171         status_con = inquire_connection(dev)
172         if not status_con:
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)
178         if not status_con:
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)
184         if not status_con:
185             dev.confirm_connection()
186         get_dev_info(dev)
187         get_area_info(dev)
188     else:
189         parser.print_help()
190
191 if __name__ == "__main__":
192     main()
193