1# Copyright (c) 2021, ATL-Electronics
2# SPDX-License-Identifier: Apache-2.0
3
4'''GigaDevice ISP tool (gd32isp) runner for serial boot ROM'''
5
6from runners.core import ZephyrBinaryRunner, RunnerCaps
7
8DEFAULT_GD32ISP_CLI   = 'GD32_ISP_Console'
9DEFAULT_GD32ISP_PORT  = '/dev/ttyUSB0'
10DEFAULT_GD32ISP_SPEED = '57600'
11DEFAULT_GD32ISP_ADDR  = '0x08000000'
12
13class Gd32ispBinaryRunner(ZephyrBinaryRunner):
14    '''Runner front-end for gd32isp.'''
15
16    def __init__(self, cfg, device,
17                 isp=DEFAULT_GD32ISP_CLI,
18                 port=DEFAULT_GD32ISP_PORT,
19                 speed=DEFAULT_GD32ISP_SPEED,
20                 addr=DEFAULT_GD32ISP_ADDR):
21        super().__init__(cfg)
22        self.device = device
23        self.isp = isp
24        self.port = port
25        self.speed = speed
26        self.addr = addr
27
28    @classmethod
29    def name(cls):
30        return 'gd32isp'
31
32    @classmethod
33    def capabilities(cls):
34        return RunnerCaps(commands={'flash'})
35
36    @classmethod
37    def do_add_parser(cls, parser):
38        # Required:
39        parser.add_argument('--device', required=True,
40                            help='device part number')
41
42        # Optional:
43        parser.add_argument('--isp', default=DEFAULT_GD32ISP_CLI,
44                            help='path to gd32 isp console program')
45        parser.add_argument('--port', default=DEFAULT_GD32ISP_PORT,
46                            help='serial port to use, default is ' +
47                            str(DEFAULT_GD32ISP_PORT))
48        parser.add_argument('--speed', default=DEFAULT_GD32ISP_SPEED,
49                            help='serial port speed to use, default is ' +
50                            DEFAULT_GD32ISP_SPEED)
51        parser.add_argument('--addr', default=DEFAULT_GD32ISP_ADDR,
52                            help='flash address, default is ' +
53                            DEFAULT_GD32ISP_ADDR)
54
55    @classmethod
56    def do_create(cls, cfg, args):
57        return Gd32ispBinaryRunner(cfg,
58                                   device=args.device,
59                                   isp=args.isp,
60                                   port=args.port,
61                                   speed=args.speed,
62                                   addr=args.addr)
63
64    def do_run(self, command, **kwargs):
65        self.require(self.isp)
66        self.ensure_output('bin')
67
68        cmd_flash = [self.isp,
69                     '-c',
70                     '--pn', self.port,
71                     '--br', self.speed,
72                     '--sb', '1',
73                     '-i', self.device,
74                     '-e',
75                     '--all',
76                     '-d',
77                     '--a', self.addr,
78                     '--fn', self.cfg.bin_file]
79
80        self.check_call(cmd_flash)
81