Imported Upstream version 0.9.1
[platform/upstream/iotivity.git] / build_common / arduino / SConscript
1 ##
2 # This script includes arduino specific config
3 ##
4 import os
5 import platform
6
7 Import('env')
8
9 def __parse_config(f):
10         dict = {}
11
12         if not os.path.isfile(f):
13                 return dict
14
15         file = open(f, 'r')
16         strs = file.readlines()
17         for str in strs:
18                 str = str.strip()
19                 if len(str) > 0 and str[0] == '#':
20                         continue
21
22                 idx = str.find('=')
23                 if idx > 0:
24                         dict.setdefault(str[0:idx], str[idx + 1:])
25
26         return dict
27
28 def __get_boards(dict):
29         boards = []
30         keys = dict.keys()
31         for key in keys:
32                 idx = key.find('.name')
33                 if idx > 0:
34                         if key.endswith('.name'):
35                                 boards.append(key[0:idx])
36         return boards
37
38 def __get_cpu(dict, board):
39         cpus = []
40         keys = dict.keys()
41         for key in keys:
42                 idx = key.find(board + '.menu.cpu.')
43                 start = len(board + '.menu.cpu.')
44                 if idx >= 0:
45                         end = key.find('.', start)
46                         if end > 0:
47                                 cpu = key[start:end]
48                                 exist = False
49                                 for c in cpus:
50                                         if c == cpu:
51                                                 exist = True
52                                                 break
53
54                                 if not exist:
55                                         cpus.append(cpu)
56         return cpus
57
58 def __get_board_info(board, key):
59         if cpu:
60                 v = boards_info.get(board + '.menu.cpu.' + cpu + key)
61                 if not v:
62                         v = boards_info.get(board + key)
63         else:
64                 v = boards_info.get(board + key)
65         return v
66
67 def __search_files(path, pattern, ondisk=True, source=True, strings=False, recursive=True):
68         if not recursive:
69                 return Glob(pattern, ondisk, source, strings)
70
71         matches = []
72         for root, dirnames, filenames in os.walk(path):
73                 matches.extend(Glob(root + '/' + pattern, ondisk, source, strings))
74
75         return matches
76
77 # To make sure the src is built in 'BUILD_DIR' (by default it will be built at
78 # the same directory as the .c .cpp .S)
79 def __src_to_obj(env, srcs):
80         objs = []
81         prefix = env.get('BOARD') + '_'
82         if env.get('CPU'):
83                 prefix += env.get('CPU') + '_'
84
85         build_dir = env.get('BUILD_DIR') + '/arduino/'
86         for src in srcs:
87                 obj = src.path.replace(arduino_home, build_dir)
88                 i = obj.rfind('.')
89                 obj = obj[0:i]
90                 if env.get('OBJSUFFIX'):
91                         obj += env.get('OBJSUFFIX')
92                 objs.extend(env.Object(obj, src, OBJPREFIX=prefix))
93         return objs
94
95 def __import_lib(env, lib):
96         lib_path = arduino_home + '/libraries/' + lib
97         if not os.path.exists(lib_path):
98                 if target_arch == 'avr':
99                         lib_path = arduino_home + '/hardware/arduino/avr/libraries/' + lib
100                 else:
101                         lib_path = arduino_home + '/hardware/arduino/sam/libraries/' + lib
102
103         if os.path.exists(lib_path + '/src'):
104                 lib_path = lib_path + '/src'
105
106         env.AppendUnique(CPPPATH = [lib_path])
107
108         if os.path.exists(lib_path + '/utility'):
109                 env.AppendUnique(CPPPATH = [lib_path + '/utility'])
110
111         lib_src = []
112         lib_src.extend(__search_files(lib_path, '*.S'))
113         lib_src.extend(__search_files(lib_path, '*.c'))
114         lib_src.extend(__search_files(lib_path, '*.cpp'))
115
116         lib_obj = __src_to_obj(env, lib_src)
117         build_dir = env.get('BUILD_DIR')
118         if build_dir:
119                 lib_a = env.StaticLibrary(build_dir + lib, lib_obj)
120         else:
121                 lib_a = env.StaticLibrary(lib, lib_obj)
122
123         # If we link libSPI.a, the final binary is not getting launched
124         # on the board.  Which is not the case if we directly use SPI.o.
125
126         if env.get('TARGET_ARCH') == 'arm':
127                 if lib == 'SPI':
128                         for obj in lib_obj:
129                                 if obj.name.endswith('SPI.o'):
130                                         env.PrependUnique(LIBS = [File(obj)])
131                 else:
132
133                         env.AppendUnique(LIBS = [File(lib_a[0])])
134         else:
135                 env.PrependUnique(LIBS = [File(lib_a[0])])
136
137         #env.AppendUnique(LIBS = [File(lib_a[0])])
138
139 def __build_core(env):
140         core_src = __search_files(core_folder, '*.S')
141         core_src.extend(__search_files(core_folder, '*.c'))
142         core_src.extend(__search_files(core_folder, '*.cpp'))
143
144         core_src.extend(__search_files(variant_folder, '*.S'))
145         core_src.extend(__search_files(variant_folder, '*.c'))
146         core_src.extend(__search_files(variant_folder, '*.cpp'))
147
148         core_obj = __src_to_obj(env, core_src)
149
150         prefix = env.get('BOARD') + '_'
151         if env.get('CPU'):
152                 prefix += env.get('CPU') + '_'
153
154         core = env.get('BUILD_DIR', '.') + '/arduino/' + prefix + 'core'
155         s_core = env.StaticLibrary(core, core_obj)
156
157         env.AppendUnique(LIBS = [File(s_core[0])])
158
159         # To avoid compiler issue. Otherewise there may be warnings:
160         #       undefined reference to '_exit' '_close', '_getpid' ...
161         # Above functions are used in libc.a and implemented in syscalls_sam3.c
162         if env.get('TARGET_ARCH') == 'arm':
163                 for obj in core_obj:
164                         if obj.name.endswith('syscalls_sam3.o'):
165                                 env.AppendUnique(LIBS = [File(obj)])
166
167 def __create_bin(env, source):
168         name = source
169         if env.get('TARGET_ARCH') == 'avr':
170                 eep = env.Command(name + '.eep', source, 'avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $SOURCE $TARGET')
171                 hex = env.Command(name + '.hex', source, 'avr-objcopy -O ihex -R .eeprom $SOURCE $TARGET')
172         else:
173                 hex = env.Command(name + '.hex', source, 'arm-none-eabi-objcopy -O binary $SOURCE $TARGET')
174
175 #Currently supporting only mega (ie. Arduino ATMega2560) and arduino_due_x/arduino_due_x_dbg (i.e. Arduino Due) builds
176 def __upload(env, binary):
177         if target_arch == 'avr':
178                 protocol = __get_board_info(board, '.upload.protocol')
179                 speed = __get_board_info(board, '.upload.speed')
180                 port = '/dev/ttyACM0'
181                 upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -p' \
182                 + mcu + ' -c' + protocol + ' -P' + port + ' -b' + speed + ' -D -Uflash:w:' + binary + ':i'
183                 print "Upload command: %s" %upload_cmd
184                 install_cmd = env.Command('install_cmd', None, upload_cmd)
185                 env.Default('install_cmd')
186         elif target_arch == 'arm':
187                 protocol = __get_board_info(board, '.upload.protocol')
188                 speed = __get_board_info(board, '.upload.speed')
189                 port = 'ttyACM0'
190                 uu = __get_board_info(board, '.upload.native_usb')
191                 os.system('stty -F /dev/' + port + ' speed 1200 cs8 -cstopb -parenb')
192                 os.system(arduino_home + '/hardware/tools/bossac -i --port=' + port + ' -U false -e -w -b ' + binary + ' -R')
193
194 # Print the command line that to upload binary to the board
195 def __upload_help(env):
196         if target_arch == 'avr':
197                 protocol = __get_board_info(board, '.upload.protocol')
198                 speed = __get_board_info(board, '.upload.speed')
199
200                 upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -p' \
201         + mcu + ' -c' + protocol + ' -P<serial_port>' + ' -b' + speed + ' -D -Uflash:w:<hex_file>:i'
202         else:
203                 uu = __get_board_info(board, '.upload.native_usb')
204                 upload_cmd = arduino_home + '/hardware/tools/bossac -i -d --port=<serial_port> -U ' + uu + ' -e -w -v -b <bin file> -R'
205
206         Help('''
207 ===============================================================================
208 You can upload the bin file with following command line:
209 ''')
210         Help('\n   $ ' + upload_cmd)
211         Help('''
212 \nPlease replace <xxx> according to the actual situation.
213 ===============================================================================
214 ''')
215
216 # ARDUINO_HOME build option
217 help_vars = Variables()
218 help_vars.Add(PathVariable('ARDUINO_HOME', 'ARDUINO root directory', os.environ.get('ARDUINO_HOME')))
219 help_vars.Update(env)
220 Help(help_vars.GenerateHelpText(env))
221
222 target_arch = env.get('TARGET_ARCH')
223
224 # Verify that the arduino, time, red bear, and nordic libraries are
225 # installed.  If not, get them and install them.
226 SConscript(env.get('SRC_DIR') + '/extlibs/arduino/SConscript')
227 arduino_home = env.get('ARDUINO_HOME')
228 print 'ARDUINO_HOME = ' + env.get('ARDUINO_HOME')
229
230 # Overwrite suffixes and prefixes
231 if env['HOST_OS'] == 'win32':
232         env['OBJSUFFIX'] = '.o'
233         env['SHOBJSUFFIX'] = '.os'
234         env['LIBPREFIX'] = 'lib'
235         env['LIBSUFFIX'] = '.a'
236         env['SHLIBPREFIX'] = 'lib'
237         env['SHLIBSUFFIX'] = '.so'
238         env['LIBPREFIXES'] = ['lib']
239         env['LIBSUFFIXES'] = ['.a', '.so']
240         env['PROGSUFFIX'] = ''
241 elif platform.system().lower() == 'darwin':
242         env['SHLIBSUFFIX'] = '.so'
243         env['LIBSUFFIXES'] = ['.a', '.so']
244         env['PROGSUFFIX'] = ''
245
246 # Debug/release relative flags
247 if env.get('RELEASE'):
248         env.AppendUnique(CCFLAGS = ['-Os'])
249         env.AppendUnique(CPPDEFINES = ['NDEBUG'])
250 else:
251         env.AppendUnique(CCFLAGS = ['-g'])
252
253 # BOARD / CPU option
254
255 # Get IDE version
256 if os.path.exists(arduino_home + '/lib/version.txt'):
257         vf = open(arduino_home + '/lib/version.txt', 'r')
258         version = vf.readline().replace('.', '').strip()
259 else:
260         print '''
261 ************************************* Error ***********************************
262 * Can't find version file (lib/version.txt), please check if (%s)
263 * is arduino root directory.                                                  *
264 *******************************************************************************
265 ''' % arduino_home
266         Exit(1)
267
268 if version[0:2] == '10':
269         is_1_0_x = True
270         boards_info = __parse_config(arduino_home + '/hardware/arduino/boards.txt')
271         env.PrependENVPath('PATH', arduino_home + '/hardware/tools/avr/bin/')
272         env.Replace(CC = 'avr-gcc')
273         env.Replace(CXX = 'avr-g++')
274         env.Replace(AR = 'avr-ar')
275         env.Replace(AS = 'avr-as')
276         env.Replace(LINK = 'avr-gcc')
277         env.Replace(RANLIB = 'avr-ranlib')
278         if target_arch != 'avr':
279                 print '''
280 ************************************* Error ***********************************
281 * Arduino 1.0.x IDE only support 'avr', to support other arch at least 1.5.x  *
282 * is required.
283 *******************************************************************************
284 '''
285                 Exit(1)
286 else:
287         is_1_0_x = False
288         if target_arch == 'avr':
289                 boards_info = __parse_config(arduino_home + '/hardware/arduino/avr/boards.txt')
290                 platform_info = __parse_config(arduino_home + '/hardware/arduino/avr/platform.txt')
291         elif target_arch == 'arm':
292                 boards_info = __parse_config(arduino_home + '/hardware/arduino/sam/boards.txt')
293                 platform_info = __parse_config(arduino_home + '/hardware/arduino/sam/platform.txt')
294         else:
295                 print '''
296 ************************************* Error ***********************************
297 * CPU arch %s isn't supported currently.
298 *******************************************************************************
299 ''' % target_arch
300
301 #Board option, let user to select the board
302 boards = __get_boards(boards_info)
303 help_vars = Variables()
304 help_vars.Add(EnumVariable('BOARD', 'arduino board', boards[0], boards))
305 help_vars.Update(env)
306 Help(help_vars.GenerateHelpText(env))
307
308 #CPU option
309 board = env.get('BOARD')
310 cpus = __get_cpu(boards_info, board)
311 if len(cpus) > 0:
312         help_vars = Variables()
313         help_vars.Add(EnumVariable('CPU', 'arduino board cpu', cpus[0], cpus))
314         help_vars.Update(env)
315         Help(help_vars.GenerateHelpText(env))
316
317 # Arduino commom flags
318 cpu = env.get('CPU')
319 board = env.get('BOARD')
320 mcu = __get_board_info(board, '.build.mcu')
321 f_cpu = __get_board_info(board, '.build.f_cpu')
322 usb_vid = __get_board_info(board, '.build.vid')
323 usb_pid = __get_board_info(board, '.build.pid')
324 variant = __get_board_info(board, '.build.variant')
325
326 if not usb_vid:
327         usb_vid = __get_board_info(board, '.vid.0')
328 if not usb_pid:
329         usb_pid = __get_board_info(board, '.pid.0')
330
331 if is_1_0_x:
332         core_base = arduino_home + '/hardware/arduino/'
333 else:
334         if target_arch == 'avr':
335                 core_base = arduino_home + '/hardware/arduino/avr/'
336         else:
337                 core_base = arduino_home + '/hardware/arduino/sam/'
338
339 variant_folder = core_base + 'variants/' + variant
340 env.AppendUnique(CPPPATH = [variant_folder])
341
342 core = __get_board_info(board, '.build.core')
343 core_folder = core_base + 'cores/' + core + '/'
344 env.AppendUnique(CPPPATH = [core_folder])
345
346 if is_1_0_x:
347         comm_flags = ['-std=c99']
348         if mcu:
349                 comm_flags.extend(['-mmcu=' + mcu])
350         if f_cpu:
351                 comm_flags.extend(['-DF_CPU=' + f_cpu])
352         comm_flags.extend(['-DARDUINO=' + version])
353         if usb_vid:
354                 comm_flags.extend(['-DUSB_VID=' + usb_vid])
355         if usb_pid:
356                 comm_flags.extend(['-DUSB_PID=' + usb_pid])
357
358         env.AppendUnique(ASFLAGS = ['-x', 'assembler-with-cpp'])
359         env.AppendUnique(ASFLAGS = comm_flags)
360
361         env.AppendUnique(CFLAGS = ['-Os', '-ffunction-sections', '-fdata-sections', '-MMD'])
362         env.AppendUnique(CFLAGS = comm_flags)
363
364         env.AppendUnique(CXXFLAGS = ['-Os', '-fno-exceptions', '-ffunction-sections', '-fdata-sections','-MMD'])
365         env.AppendUnique(CXXFLAGS = comm_flags)
366
367         env.AppendUnique(LINKFLAGS = ['-Os'])
368         if mcu == 'atmega2560':
369                 env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections,--relax'])
370         else:
371                 env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections'])
372         env.AppendUnique(LINKFLAGS = ['-mmcu=' + mcu])
373 else:
374         if target_arch == 'avr':
375                 cpu_flag = '-mmcu=' + mcu
376         else:
377                 cpu_flag = '-mcpu=' + mcu
378
379         comm_flag = [cpu_flag, '-DF_CPU=' + f_cpu, '-DARDUINO=' + version, '-DARDUINO_' + __get_board_info(board, '.build.board')]
380         if target_arch == 'arm':
381                 # As of 1.5.8 the arduino headers for arm had _asm_ bugs with ARM and
382                 # require gnu99 to be used
383                 comm_flag.extend(['-std=gnu99', '-DARDUINO_ARCH_SAM'])
384         else:
385                 comm_flag.extend(['-std=c99', '-DARDUINO_ARCH_AVR'])
386
387         compiler_path = platform_info.get('compiler.path')
388         compiler_path = compiler_path.replace('{runtime.ide.path}', arduino_home)
389         env.PrependENVPath('PATH', compiler_path)
390         env.Replace(CC = platform_info.get('compiler.c.cmd'))
391         env.Replace(CXX = platform_info.get('compiler.cpp.cmd'))
392         env.Replace(AR = platform_info.get('compiler.ar.cmd'))
393         if target_arch == 'arm':
394                 env.AppendUnique(CPPPATH = [arduino_home + '/hardware/arduino/sam/system/libsam',
395                                                         arduino_home + '/hardware/arduino/sam/system/CMSIS/CMSIS/Include/',
396                                                         arduino_home + '/hardware/arduino/sam/system//CMSIS/Device/ATMEL'])
397         env.AppendUnique(ASFLAGS = ['-x', 'assembler-with-cpp'])
398         env.AppendUnique(ASFLAGS = comm_flag)
399         env.AppendUnique(CFLAGS = Split(platform_info.get('compiler.c.flags')))
400         env.AppendUnique(CXXFLAGS = Split(platform_info.get('compiler.cpp.flags')))
401         env.AppendUnique(ARFLAGS = Split(platform_info.get('compiler.ar.flags')))
402         env.AppendUnique(CCFLAGS = comm_flag)
403
404         extra_flags = __get_board_info(board, '.build.extra_flags')
405         if extra_flags:
406                 extra_flags = extra_flags.replace('{build.usb_flags}', '')
407                 env.AppendUnique(CCFLAGS = Split(extra_flags))
408                 usb_flags = ['-DUSB_VID=' + usb_vid, '-DUSB_PID=' + usb_pid, '-DUSBCON', '-DUSB_MANUFACTURER="Unknown"']
409                 env.AppendUnique(CCFLAGS = usb_flags)
410
411         if target_arch == 'arm':
412                 env.AppendUnique(LINKFLAGS = ['-Os', '-Wl,--gc-sections', cpu_flag,
413                                         '-T' + variant_folder + '/' + __get_board_info(board, '.build.ldscript')])
414                 env.AppendUnique(LINKFLAGS = Split('-lm -lgcc -mthumb -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group'))
415
416                 variant_system_lib = __get_board_info(board, '.build.variant_system_lib')
417                 if variant_system_lib:
418                         if variant_folder.find(' ') >= 0:
419                                 variant_folder = '"' + variant_folder + '"'
420                         env.Replace(LINKCOM = '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS '
421                                         + variant_folder + '/' + variant_system_lib + ' -Wl,--end-group')
422                 else:
423                         env.Replace(LINKCOM = '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS -Wl,--end-group')
424         else:
425                 env.AppendUnique(LINKFLAGS = Split(platform_info.get('compiler.c.elf.flags')))
426                 env.AppendUnique(LINKFLAGS = [cpu_flag])
427                 env.AppendUnique(LIBS = 'm')
428         env.Replace(ARCOM = '$AR ' + platform_info.get('compiler.ar.flags') + ' $TARGET $SOURCES')
429
430
431 __build_core(env)
432
433 env.AddMethod(__import_lib, "ImportLib") #import arduino library
434 env.AddMethod(__build_core, "BuildCore") #build arduino core
435 env.AddMethod(__create_bin, "CreateBin") #create binary files(.eep and .hex)
436 env.AddMethod(__upload, "Upload") #Upload binary to board
437 env.AddMethod(__upload_help, "UploadHelp") #print the command line that to upload binary to the boardf