113
|
1 #!/usr/bin/python
|
|
2
|
115
|
3 import argparse, sys
|
128
|
4 import stlink, stm32
|
113
|
5
|
|
6 def hex2int(s):
|
115
|
7 if s.startswith('0x'):
|
|
8 s = s[2:]
|
|
9 return int(s, 16)
|
128
|
10 raise ValueError('Hexadecimal value must begin with 0x')
|
113
|
11
|
116
|
12 parser = argparse.ArgumentParser(
|
|
13 description='ST-link flash utility by Windel Bouwman')
|
115
|
14 subparsers = parser.add_subparsers(title='commands',
|
|
15 description='possible commands', dest='command')
|
|
16
|
|
17 readparser = subparsers.add_parser('read', help='read flash contents')
|
116
|
18 readparser.add_argument('filename', type=argparse.FileType('wb', 0))
|
115
|
19 readparser.add_argument('address', type=hex2int)
|
|
20 readparser.add_argument('size', type=hex2int)
|
|
21
|
|
22 writeparser = subparsers.add_parser('write', help='write flash contents')
|
116
|
23 writeparser.add_argument('filename', type=argparse.FileType('rb'))
|
115
|
24 writeparser.add_argument('address', type=hex2int)
|
|
25
|
116
|
26 verifyparser = subparsers.add_parser('verify', help='verify flash contents')
|
|
27 verifyparser.add_argument('filename', type=argparse.FileType('rb'))
|
|
28 verifyparser.add_argument('address', type=hex2int)
|
|
29
|
115
|
30 eraseparser = subparsers.add_parser('erase', help='erase flash contents')
|
113
|
31
|
|
32 args = parser.parse_args()
|
|
33 print(args)
|
115
|
34 if not args.command:
|
|
35 parser.print_usage()
|
|
36 sys.exit(1)
|
113
|
37
|
115
|
38 # In any command case, open a device:
|
128
|
39 stl = stlink.STLink2()
|
116
|
40 stl.open()
|
115
|
41
|
|
42 # Enter the right mode:
|
|
43 if stl.CurrentMode == stlink.DFU_MODE:
|
|
44 stl.exitDfuMode()
|
|
45
|
|
46 if stl.CurrentMode != stlink.DEBUG_MODE:
|
|
47 stl.enterSwdMode()
|
113
|
48
|
115
|
49 if stl.ChipId != 0x10016413:
|
|
50 print('Only working on stm32f4discovery board for now.')
|
|
51 sys.exit(2)
|
113
|
52
|
128
|
53 # Retrieve the connected device, if any:
|
129
|
54 dev = stl.createDevice()
|
128
|
55
|
115
|
56 if args.command == 'read':
|
128
|
57 dev_content = dev.readFlash(args.address, args.size)
|
116
|
58 args.filename.write(dev_content)
|
115
|
59 elif args.command == 'write':
|
|
60 content = args.filename.read()
|
128
|
61 dev.writeFlash(args.address, content)
|
116
|
62 elif args.command == 'verify':
|
|
63 content = args.filename.read()
|
128
|
64 dev.verifyFlash(args.address, content)
|
115
|
65 elif args.command == 'erase':
|
128
|
66 dev.eraseFlash()
|
115
|
67 else:
|
|
68 print('unknown command', args.command)
|
|
69
|
|
70 stl.exitDebugMode()
|
|
71
|