7c534abfa485aea822e6f0746b8cd352c7e6f900
[renesas-ra-flasher] / src / RAFlasher.py
1 import os
2 import math
3 import argparse
4 from RAConnect import *
5 from RAPacker import *
6
7 SECTOR_SIZE = 2048
8
9 def int_to_hex_list(num):
10     hex_string = hex(num)[2:].upper()  # convert to hex string
11     hex_string = hex_string.zfill(8) # pad for 8 char's long
12     hex_list = [f'0x{hex_string[c:c+2]}' for c in range(0, 8, 2)]
13     return hex_list
14
15 def inquire_connection(dev):
16     packed = pack_pkt(INQ_CMD, "")
17     dev.send_data(packed)
18     info = dev.recv_data(7)
19     print(info)
20     if info == bytearray(b'\x00') or info == bytearray(b''):
21         return False
22     msg = unpack_pkt(info)
23     print("Connection already established")
24     print(msg)
25     return True
26
27 def get_dev_info(dev):
28
29     packed = pack_pkt(SIG_CMD, "")
30     dev.send_data(packed)
31     print(packed)
32     info = dev.recv_data(18)
33     print(info, len(info))
34     #info = b'\x81\x00\x0D\x3A\x01\x31\x2d\x00\x00\x1e\x84\x80\x04\x02\x0a\x08' # test
35     fmt = '>IIIBBHH'
36     _HEADER, SCI, RMB, NOA, TYP, BFV, _FOOTER = struct.unpack(fmt, info)
37     print('Chip info:')
38     print('====================')
39     print(f'Serial interface speed: {SCI} Hz')
40     print(f'Recommend max UART baud rate {RMB} bps')
41     if TYP == 0x02:
42         print('RA MCU + RA2/RA4 Series')
43     elif TYP == 0x03:
44         print('RA MCU + RA6 Series')
45     else:
46         print('Unknown MCU type')
47     print(f'Boot firmware version {BFV >> 8}.{BFV & 0xFF}')
48     print('====================')
49
50
51 def verify_img(dev, img, start_addr, end_addr):
52     raise Exception("Not implemented")
53
54 def write_img(dev, img, start_addr, end_addr, verify=False):
55
56     if os.path.exists(img):
57         file_size = os.path.getsize(img)
58     else:
59         raise Exception(f'file {img} does not exist')
60
61     # calculate / check start and end address 
62     if start_addr == None or end_addr == None:
63         if start_addr == None:
64             start_addr = 0
65         # align start addr
66         if start_addr % SECTOR_SIZE:
67             raise ValueError(f"start addr not aligned on sector size {SECTOR_SIZE}")
68         blocks = (file_size + SECTOR_SIZE - 1) // SECTOR_SIZE
69         end_addr = blocks * SECTOR_SIZE + start_addr
70         print(end_addr)
71     
72     chunk_size = 64 # max is 1024
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(WRI_CMD, SAD + EAD)
82     dev.send_data(packed)
83     ret = dev.recv_data(7)
84
85     with open(img, 'rb') as f:
86         chunk = f.read(chunk_size)
87         while chunk:
88             packed = pack_pkt(WRI_CMD, chunk)
89             print(f'Sending {len(chunk)} bytes')
90             dev.send_data(packed)
91             reply_len = 7
92             reply = dev.recv_data(reply_len)
93             #reply = b'\x81\x00\x02\x00\x00\xFE\x03' # test reply
94             if not reply == False:
95                 msg = unpack_pkt(reply)
96                 print(msg)
97             chunk = f.read(chunk_size)
98
99 def main():
100     parser = argparse.ArgumentParser(description="RA Flasher Tool")
101
102     subparsers = parser.add_subparsers(dest="command", title="Commands")
103
104     # Subparser for the write command
105     write_parser = subparsers.add_parser("write", help="Write data to flash")
106     write_parser.add_argument("--start_address", type=int, default=0x0000, help="Start address")
107     write_parser.add_argument("--end_address", type=int, help="End address")
108     write_parser.add_argument("--verify", action="store_true", help="Verify after writing")
109     write_parser.add_argument("file_name", type=str, help="File name")
110
111     # Subparser for the read command
112     read_parser = subparsers.add_parser("read", help="Read data from flash")
113     read_parser.add_argument("--start_address", type=int, default=0x000, help="Start address")
114     read_parser.add_argument("--size", type=int, default=1024, help="Size in bytes")
115     read_parser.add_argument("file_name", type=str, help="File name")
116
117     # Subparser for the info command
118     subparsers.add_parser("info", help="Show flasher information")
119
120     args = parser.parse_args()
121
122     if args.command == "write":
123         dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
124         print(args)
125         write_img(dev, args.file_name, args.start_address, args.end_address, args.verify)
126     elif args.command == "read":
127         print('read command')
128     elif args.command == "info":
129         dev = RAConnect(vendor_id=0x045B, product_id=0x0261)
130         status_con = inquire_connection(dev)
131         if not status_con:
132             #dev.establish_connection()
133             dev.confirm_connection()
134         get_dev_info(dev)
135     else:
136         parser.print_help()
137
138 if __name__ == "__main__":
139     main()
140