embox

Форк
0
/
import_stm32_cube_example.py 
207 строк · 6.8 Кб
1
#!/usr/bin/env python2
2

3
import sys
4
import os
5
import argparse
6
import shutil
7
import subprocess
8
import textwrap
9

10
class ExampleInfo:
11
	def __init__(self, src, dst, script_dir, example_name, platform):
12
		self.src = src
13
		self.dst = dst
14
		self.script_dir = script_dir
15
		self.example_name = example_name
16
		self.platform = platform
17

18
# We want to obtain something like this:
19
#
20
# ...
21
# extern int embox_stm32_setup_irq_handlers(void);
22
# int BSP_main(void){
23
# 	uint8_t  lcd_status = LCD_OK;
24
#
25
# 	if (0 != embox_stm32_setup_irq_handlers()) {
26
# 		printf("embox_stm32_setup_irq_handlers error!\n");
27
# 	}
28
# 	//CPU_CACHE_Enable();
29
# 	//HAL_Init();
30
# 	//SystemClock_Config();
31
# ...
32
def fix_main(info):
33
	with open(info.dst + '/Src/main.c', 'r') as f:
34
		lines = f.readlines()
35

36
	def find_line(pattern):
37
		l = [i for i in range(len(lines)) if pattern in lines[i]]
38
		return l[0] if l else None
39

40
	def comment_line_out_if_any(pattern):
41
		id = find_line(pattern)
42
		if id is not None:
43
			lines[id] = '  //' + lines[id]
44

45
	id = find_line('main(void)')
46
	if id is not None:
47
		lines[id] = 'int %s_main(void)' % info.example_name
48
		lines.insert(id, 'extern int embox_stm32_setup_irq_handlers(void);\r\n')
49

50
	id = find_line('HAL_Init();')
51
	if id is not None:
52
		lines.insert(id,
53
					('  if (0 != embox_stm32_setup_irq_handlers()) {\r\n'
54
					 '    printf("embox_stm32_setup_irq_handlers error!\\n");\r\n'
55
					 '  }\r\n'))
56

57
	comment_line_out_if_any('CPU_CACHE_Enable();')
58
	comment_line_out_if_any('HAL_Init();')
59
	comment_line_out_if_any('SystemClock_Config();')
60

61
	with open(info.dst + '/Src/main.c', 'w') as f:
62
		f.write(''.join(lines))
63

64
def generate_Mybuild(info):
65
	with open(info.script_dir + '/Mybuild_template', 'r') as f:
66
		mybuild = f.read()
67

68
	mybuild = mybuild.replace('_EXAMPLE_', info.example_name)
69
	mybuild = mybuild.replace('_PLATFORM_', info.platform)
70

71
	sources = 'source'
72
	for file in os.listdir(info.src + '/Src'):
73
		if file.endswith('.c'):
74
			sources += '		"Src/%s",\n' % file
75
	sources += '		"Src/embox_stm32%sxx_it.c"\n' % info.platform
76
	mybuild = mybuild.replace('_SOURCES_', sources)
77

78
	with open(info.dst + '/Mybuild', 'w') as f:
79
		f.write(mybuild)
80

81
def find_irq_handlers_in_file(info, file):
82
	# Get path of STM32 Cube directory
83
	stm32_path = info.src.rsplit('/Projects', 1)[0]
84

85
	# First of all, we need to preprocess file
86
	compiler = 'arm-none-eabi-cpp'
87
	include = {'f7' :
88
				' -DSTM32F746xx'											+ \
89
				' -I_SRC_/Inc'												+ \
90
				' -I_STM32_PATH_/Drivers/STM32F7xx_HAL_Driver/Inc'			+ \
91
				' -I_STM32_PATH_/Drivers/BSP/STM32746G-Discovery'			+ \
92
				' -I_STM32_PATH_/Drivers/CMSIS/Device/ST/STM32F7xx/Include'	+ \
93
				' -I_STM32_PATH_/Drivers/CMSIS/Include'						+ \
94
				' -I_STM32_PATH_/Utilities/Log'								+ \
95
				' -I_STM32_PATH_/Middlewares/Third_Party/FatFs/src'			+ \
96
				' -I_STM32_PATH_/Middlewares/ST/STM32_USB_Device_Library/Core/Inc' + \
97
				' -I_STM32_PATH_/Middlewares/ST/STM32_USB_Device_Library/Class/MSC/Inc' + \
98
				' -I_STM32_PATH_/Middlewares/ST/STM32_USB_Host_Library/Core/Inc' + \
99
				' -I_STM32_PATH_/Middlewares/ST/STM32_USB_Host_Library/Class/MSC/Inc',
100
				'f4' :
101
				' -DSTM32F407xx'											+ \
102
				' -I_SRC_/Inc'												+ \
103
				' -I_STM32_PATH_/Drivers/STM32F4xx_HAL_Driver/Inc'			+ \
104
				' -I_STM32_PATH_/Drivers/BSP/STM32F4-Discovery'				+ \
105
				' -I_STM32_PATH_/Drivers/CMSIS/Device/ST/STM32F4xx/Include'	+ \
106
				' -I_STM32_PATH_/Drivers/CMSIS/Include'}[info.platform]
107
	include = include.replace('_SRC_', info.src)
108
	include = include.replace('_STM32_PATH_', stm32_path)
109
	# Compile and find implementations of IRQHandler's, not declarations
110
	command = compiler + ' ' + include + ' ' + file + ' | grep "IRQHandler(void)" | grep -v ";"'
111

112
	# Search for 'IRQHandler' in the obtained preprocessed file
113
	p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
114
	result = [w for w in p.stdout.read().replace('(', ' ').replace(')', ' ').split() if "IRQHandler" in w]
115

116
	return result
117

118
def generate_stm32_irq_handlers(info):
119
	stm32_it_file = info.src + '/Src/stm32%sxx_it.c' % info.platform
120
	irq_handlers = find_irq_handlers_in_file(info, stm32_it_file)
121

122
	with open(info.script_dir + '/embox_stm32_it_template.c', 'r') as f:
123
		stm32_it = f.read()
124

125
	stm32_it = stm32_it.replace('_PLATFORM_', info.platform)
126

127
	irq_attach = ''
128
	irq_handlers_declare = ''
129
	for h in irq_handlers:
130
		prefix = h.rsplit('_IRQHandler', 1)[0]
131
		irq_attach += '	res |= irq_attach(%s_IRQn + 16, embox_%s, 0, NULL, "%s");\n' % (prefix, h, h)
132
		irq_handlers_declare += 'EMBOX_STM32_IRQ_HANDLER(%s)\n' % prefix
133

134
	stm32_it = stm32_it.replace('_IRQ_HANDLERS_DECLARE_', irq_handlers_declare)
135
	stm32_it = stm32_it.replace('_STM32_IRQ_ATTACH_', irq_attach)
136

137
	with open(info.dst + '/Src/embox_stm32%sxx_it.c' % info.platform, 'w') as f:
138
		f.write(stm32_it)
139

140
def generate_new_main(info):
141
	with open(info.script_dir + '/embox_main_template.c', 'r') as f:
142
		embox_main = f.read()
143

144
	embox_main = embox_main.replace('_EXAMPLE_', info.example_name)
145

146
	with open(info.dst + '/Src/embox_main.c', 'w') as f:
147
		f.write(embox_main)
148

149
def import_example(info):
150
	if os.path.exists(info.dst):
151
		print 'Destination directory %s is already exists' % info.dst
152
		return
153
	elif not os.path.exists(info.src):
154
		print 'Source directory %s does not exist' % info.src
155
		return
156

157
	shutil.copytree(info.src + '/Src', info.dst + '/Src')
158
	shutil.copytree(info.src + '/Inc', info.dst + '/Inc')
159
	shutil.copyfile(info.src + '/readme.txt', info.dst + '/readme.txt')
160

161
	fix_main(info)
162
	generate_Mybuild(info)
163
	generate_stm32_irq_handlers(info)
164
	generate_new_main(info)
165

166
def main():
167
	parser = argparse.ArgumentParser(
168
		prog='import_stm32_cube_example.py',
169
		formatter_class=argparse.RawDescriptionHelpFormatter,
170
		description=textwrap.dedent('''\
171
			Example of use
172
			--------------------------------
173
			Do the following to import LTDC_Display_1Layer example:
174
			# ./scripts/stm32/import_stm32_cube_example.py --name LTDC_Display_1Layer --platform f7
175
			<path to>/STM32Cube_FW_F7_V1.5.0/Projects/STM32746G-Discovery/Examples/LTDC/LTDC_Display_1Layer
176
			''')
177
	)
178
	parser.add_argument('--platform', help='f4 or f7')
179
	parser.add_argument('src', help='Source folder containing Cube example')
180
	parser.add_argument('dest', nargs='?', default='', help='Destination folder '
181
						'(./platform/stm32<platform>/cmds by default)')
182
	parser.add_argument('--name', default='', help='Imported example name '
183
						'(corresponds to Cube\'s example name by default)')
184
	args = parser.parse_args()
185

186
	platform = args.platform
187

188
	if args.dest == '':
189
		args.dest = os.getcwd() + '/platform/stm32%s/cmds' % platform
190

191
	src = os.path.normpath(args.src)
192

193
	if args.name == '':
194
		example_name = os.path.basename(src)
195
	else:
196
		example_name = args.name
197

198
	dst = '%s/%s' % (os.path.normpath(args.dest), example_name)
199
	script_dir = os.path.dirname(sys.argv[0])
200

201
	print "src=%s, dest=%s, platform=%s" % (src, dst, platform)
202
	info = ExampleInfo(src, dst, script_dir, example_name, platform)
203

204
	import_example(info)
205

206
if __name__ == "__main__":
207
	main()
208

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.