RAFlasher: minor cleanup print and debug statements
[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         print("===================")
30         packed = pack_pkt(ARE_CMD, [str(i)])
31         dev.send_data(packed)
32         info = dev.recv_data(23)
33         msg = unpack_pkt(info)
34         fmt = '>BIIII'
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')
38
39 def get_dev_info(dev):
40
41     packed = pack_pkt(SIG_CMD, "")
42     dev.send_data(packed)
43     info = dev.recv_data(18)
44     fmt = '>IIIBBHH'
45     _HEADER, SCI, RMB, NOA, TYP, BFV, _FOOTER = struct.unpack(fmt, info)
46     print('Chip 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}]')
53     if TYP == 0x02:
54         print('RA MCU + RA2/RA4 Series')
55     elif TYP == 0x03:
56         print('RA MCU + RA6 Series')
57     else:
58         print('Unknown MCU type')
59     print(f'Boot firmware version {BFV >> 8}.{BFV & 0xFF}')
60     print('====================')
61
62
63 def verify_img(dev, img, start_addr, end_addr):
64     raise Exception("Not implemented")
65
66 def read_img(dev, img, start_addr, end_addr):
67     
68     # calculate / check start and end address 
69     if start_addr == None or end_addr == None:
70         if start_addr == None:
71             start_addr = 0
72         # align start addr
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
77     
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")
82     
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)
87     dev.send_data(packed)
88
89     # calculate how many packets are have to be received
90     nr_packet = (end_addr - start_addr) // 1024 # TODO: set other than just 1024
91
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)
97             f.write(chunky)
98             packed = pack_pkt(REA_CMD, ['0x00'], ack=True)
99             dev.send_data(packed)
100
101
102 def write_img(dev, img, start_addr, end_addr, verify=False):
103
104     if os.path.exists(img):
105         file_size = os.path.getsize(img)
106     else:
107         raise Exception(f'file {img} does not exist')
108
109     # calculate / check start and end address 
110     if start_addr == None or end_addr == None:
111         if start_addr == None:
112             start_addr = 0
113         # align start addr
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
118     
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")
124
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)
132     unpack_pkt(ret) 
133
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))
138             while 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)
144                 reply_len = 7
145                 reply = dev.recv_data(reply_len)
146                 msg = unpack_pkt(reply)
147                 chunk = f.read(chunk_size)
148                 pbar.update(len(chunk))
149
150
151 def main():
152     parser = argparse.ArgumentParser(description="RA Flasher Tool")
153
154     subparsers = parser.add_subparsers(dest="command", title="Commands")
155
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")
162
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")
168
169     # Subparser for the info command
170     subparsers.add_parser("info", help="Show flasher information")
171
172     args = parser.parse_args()
173
174     if args.command == "write":
175         dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
176         status_con = inquire_connection(dev)
177         if not status_con:
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)
183         if not status_con:
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)
189         if not status_con:
190             dev.confirm_connection()
191         get_dev_info(dev)
192         get_area_info(dev)
193     else:
194         parser.print_help()
195
196 if __name__ == "__main__":
197     main()
198