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
|
244
|
26 hexwriteparser = subparsers.add_parser('hexwrite', help='write hexfile to flash')
|
|
27 hexwriteparser.add_argument('filename', type=argparse.FileType('r'))
|
|
28
|
116
|
29 verifyparser = subparsers.add_parser('verify', help='verify flash contents')
|
|
30 verifyparser.add_argument('filename', type=argparse.FileType('rb'))
|
|
31 verifyparser.add_argument('address', type=hex2int)
|
|
32
|
115
|
33 eraseparser = subparsers.add_parser('erase', help='erase flash contents')
|
113
|
34
|
|
35 args = parser.parse_args()
|
115
|
36 if not args.command:
|
|
37 parser.print_usage()
|
|
38 sys.exit(1)
|
113
|
39
|
115
|
40 # In any command case, open a device:
|
128
|
41 stl = stlink.STLink2()
|
116
|
42 stl.open()
|
115
|
43
|
|
44 # Enter the right mode:
|
|
45 if stl.CurrentMode == stlink.DFU_MODE:
|
|
46 stl.exitDfuMode()
|
|
47
|
|
48 if stl.CurrentMode != stlink.DEBUG_MODE:
|
|
49 stl.enterSwdMode()
|
113
|
50
|
115
|
51 if stl.ChipId != 0x10016413:
|
|
52 print('Only working on stm32f4discovery board for now.')
|
|
53 sys.exit(2)
|
113
|
54
|
128
|
55 # Retrieve the connected device, if any:
|
129
|
56 dev = stl.createDevice()
|
128
|
57
|
115
|
58 if args.command == 'read':
|
128
|
59 dev_content = dev.readFlash(args.address, args.size)
|
116
|
60 args.filename.write(dev_content)
|
115
|
61 elif args.command == 'write':
|
|
62 content = args.filename.read()
|
128
|
63 dev.writeFlash(args.address, content)
|
116
|
64 elif args.command == 'verify':
|
|
65 content = args.filename.read()
|
128
|
66 dev.verifyFlash(args.address, content)
|
115
|
67 elif args.command == 'erase':
|
128
|
68 dev.eraseFlash()
|
115
|
69 else:
|
|
70 print('unknown command', args.command)
|
241
|
71
|
|
72 stl.reset()
|
|
73 stl.run()
|
115
|
74 stl.exitDebugMode()
|
|
75
|