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