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