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