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