Update navigation.c
[inav.git] / src / utils / openocd_flash.py
blobf2dc2391df9e32ac3f06bd3053372b3d0c25ffe1
1 #!/usr/bin/env python
3 from __future__ import print_function
5 import os
6 import socket
7 import subprocess
8 import sys
10 def openocd_telnet_await_prompt(s):
11 prev = None
12 while True:
13 b = s.recv(1)
14 if b == '':
15 # Closed
16 return False
17 if prev == '>' and b == ' ':
18 # Prompt for next command
19 return True
20 prev = b
21 print(b, end='')
23 def openocd_telnet_command(s, cmd):
24 s.send(cmd + '\n')
25 openocd_telnet_await_prompt(s)
27 def openocd_flash_telnet(port, filename):
28 try:
29 s = socket.create_connection(('localhost', port))
30 except socket.error:
31 return False
33 openocd_telnet_await_prompt(s)
34 openocd_telnet_command(s, 'halt')
35 openocd_telnet_command(s, 'program {} verify reset\n'.format(filename))
36 openocd_telnet_command(s, 'exit')
37 s.close()
38 return True
40 def openocd_flash_cmd(openocd, args, filename):
41 cmd = [openocd]
42 cmd.extend(args)
43 cmd.extend(('-c', 'program {} verify reset exit'.format(filename)))
44 status = subprocess.call(cmd)
45 return status == 0
47 def usage():
48 print('Usage: {} <openocd_args> <elf_file>'.format(sys.argv[0]))
49 print('Environment variables: OPENOCD_CMD = path to openocd')
50 sys.exit(1)
52 def main():
53 import sys
55 # Default openocd telnet port
56 # TODO: Parse arguments and check if we
57 # should use a non-default port
58 port = 4444
59 openocd = os.environ.get('OPENOCD_CMD') or 'openocd'
61 openocd_args = []
62 flag = None
63 elf = None
64 for arg in sys.argv[1:]:
65 if flag:
66 openocd_args.append(arg)
67 flag = None
68 else:
69 if arg.startswith('-'):
70 openocd_args.append(arg)
71 flag = arg
72 elif elf is None:
73 elf = arg
74 else:
75 usage()
77 if len(openocd_args) == 0 or elf is None:
78 usage()
80 if not openocd_flash_telnet(port, elf):
81 if not openocd_flash_cmd(openocd, openocd_args, elf):
82 print('could not flash')
83 sys.exit(1)
85 if __name__ == '__main__':
86 main()