Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Comments & pep8 cleanup #22

Merged
merged 2 commits into from
Nov 4, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 64 additions & 50 deletions SConstruct
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/python

# arscons: scons script for the Arduino sketch
# arscons: SCons script for Arduino
# http://github.com/suapapa/arscons
#
# Copyright (C) 2010-2013 by Homin Lee <homin.lee@suapapa.net>
Expand All @@ -13,7 +13,7 @@
# You'll need the serial module: http://pypi.python.org/pypi/pyserial

# Basic Usage:
# 1. make a folder which have same name of the sketch (ex. Blink/ for Blink.pde)
# 1. make a folder with the same name as the sketch (ex. Blink/ for Blink.ino)
# 2. put the sketch and SConstruct(this file) under the folder.
# 3. to make the HEX. do following in the folder.
# $ scons
Expand Down Expand Up @@ -59,6 +59,7 @@ try:
except IOError:
config = None


def config_get(varname, returns):
if config:
result = config.get(varname, returns)
Expand All @@ -67,22 +68,24 @@ def config_get(varname, returns):

return result


def resolve_var(varname, default_value):
global VARTAB
# precedence: scons argument -> env. variable -> json config -> default value
ret = ARGUMENTS.get(varname, None)
VARTAB[varname] = ('arg', ret)
if ret == None:
if ret is None:
ret = os.environ.get(varname, None)
VARTAB[varname] = ('env', ret)
if ret == None:
if ret is None:
ret = config_get(varname, None)
VARTAB[varname] = ('cnf', ret)
if ret == None:
if ret is None:
ret = default_value
VARTAB[varname] = ('dfl', ret)
return ret


def getUsbTty(rx):
usb_ttys = glob(rx)
return usb_ttys[0] if len(usb_ttys) == 1 else None
Expand Down Expand Up @@ -119,18 +122,18 @@ else:
path.join(ARDUINO_HOME, 'hardware/tools/'))

ARDUINO_BOARD = resolve_var('ARDUINO_BOARD', 'atmega328')
ARDUINO_VER = resolve_var('ARDUINO_VER', 0) # Default to 0 if nothing is specified
RST_TRIGGER = resolve_var('RST_TRIGGER', None) # use built-in pulseDTR() by default
EXTRA_LIB = resolve_var('EXTRA_LIB', None) # handy for adding another arduino-lib dir
ARDUINO_VER = resolve_var('ARDUINO_VER', 0) # Default to 0 if nothing is specified
RST_TRIGGER = resolve_var('RST_TRIGGER', None) # Use built-in pulseDTR() by default
EXTRA_LIB = resolve_var('EXTRA_LIB', None) # Handy for adding another Arduino-lib dir

if not ARDUINO_HOME:
print 'ARDUINO_HOME must be defined.'
raise KeyError('ARDUINO_HOME')

ARDUINO_CONF = path.join(ARDUINO_HOME, 'hardware/arduino/boards.txt')
# check given board name, ARDUINO_BOARD is valid one
arduino_boards = path.join(ARDUINO_HOME,'hardware/*/boards.txt')
custom_boards = path.join(SKETCHBOOK_HOME,'hardware/*/boards.txt')
# check if given board name, ARDUINO_BOARD is a valid one
arduino_boards = path.join(ARDUINO_HOME, 'hardware/*/boards.txt')
custom_boards = path.join(SKETCHBOOK_HOME, 'hardware/*/boards.txt')
board_files = glob(arduino_boards) + glob(custom_boards)
ptnBoard = re.compile(r'^([^#]*)\.name=(.*)')
boards = {}
Expand All @@ -141,7 +144,7 @@ for bf in board_files:
boards[result.group(1)] = (result.group(2), bf)

if ARDUINO_BOARD not in boards:
print "ERROR! the given board name, %s is not in the supported board list:" % ARDUINO_BOARD
print "ERROR! the given board name, %s is not in the supported boards list:" % ARDUINO_BOARD
print "all available board names are:"
for name, description in boards.iteritems():
print "\t%s for %s" % (name.ljust(14), description[0])
Expand All @@ -150,15 +153,16 @@ if ARDUINO_BOARD not in boards:

ARDUINO_CONF = boards[ARDUINO_BOARD][1]

def getBoardConf(conf, default = None):

def getBoardConf(conf, default=None):
for line in open(ARDUINO_CONF):
line = line.strip()
if '=' in line:
key, value = line.split('=')
if key == '.'.join([ARDUINO_BOARD, conf]):
return value
ret = default
if ret == None:
if ret is None:
print "ERROR! can't find %s in %s" % (conf, ARDUINO_CONF)
assert(False)
return ret
Expand All @@ -179,7 +183,7 @@ if ARDUINO_VER == 0:
else:
print "Arduino version " + ARDUINO_VER + " specified"

# Some OSs need bundle with IDE tool-chain
# On some OSs we need to reuse parts of the original IDE tool-chain
if platform == 'darwin' or platform == 'win32':
AVRDUDE_CONF = path.join(ARDUINO_HOME, 'hardware/tools/avr/etc/avrdude.conf')

Expand All @@ -197,7 +201,7 @@ MCU = ARGUMENTS.get('MCU', getBoardConf('build.mcu'))
F_CPU = ARGUMENTS.get('F_CPU', getBoardConf('build.f_cpu'))

# There should be a file with the same name as the folder and
# with the extension .pde or .ino
# with the extension .ino (or .pde)
# Or, one can specify it via the ARSCONS_TARGET environment
# variable..

Expand All @@ -222,31 +226,33 @@ extra_cflags = [
cFlags += extra_cflags

if ARDUINO_BOARD == "leonardo":
cFlags += ["-DUSB_VID="+getBoardConf('build.vid')]
cFlags += ["-DUSB_PID="+getBoardConf('build.pid')]

envArduino = Environment(CC = AVR_BIN_PREFIX + 'gcc',
CXX = AVR_BIN_PREFIX + 'g++',
AS = AVR_BIN_PREFIX + 'gcc',
CPPPATH = ['build/core'],
CPPDEFINES = {'F_CPU': F_CPU, 'ARDUINO': ARDUINO_VER},
CFLAGS = cFlags + ['-std=gnu99'],
CCFLAGS = cFlags,
ASFLAGS = ['-assembler-with-cpp','-mmcu=%s' % MCU],
TOOLS = ['gcc','g++', 'as'])
cFlags += ["-DUSB_VID=" + getBoardConf('build.vid')]
cFlags += ["-DUSB_PID=" + getBoardConf('build.pid')]

envArduino = Environment(CC=AVR_BIN_PREFIX + 'gcc',
CXX=AVR_BIN_PREFIX + 'g++',
AS=AVR_BIN_PREFIX + 'gcc',
CPPPATH=['build/core'],
CPPDEFINES={'F_CPU': F_CPU, 'ARDUINO': ARDUINO_VER},
CFLAGS=cFlags + ['-std=gnu99'],
CCFLAGS=cFlags,
ASFLAGS=['-assembler-with-cpp', '-mmcu=%s' % MCU],
TOOLS=['gcc', 'g++', 'as'])

hwVariant = path.join(ARDUINO_HOME, 'hardware/arduino/variants',
getBoardConf("build.variant", ""))
if hwVariant:
envArduino.Append(CPPPATH = hwVariant)
envArduino.Append(CPPPATH=hwVariant)


# Show version
def printVersion(target, source, env):
print "arscons v%s"%__version__
print "arscons v%s" % __version__

version = envArduino.Alias('version', None, [printVersion])
AlwaysBuild(version)


def run(cmd):
"""Run a command and decipher the return code. Exit by default."""
# print ' '.join(cmd)
Expand All @@ -256,14 +262,16 @@ def run(cmd):
print "Error: return code: " + str(cpe.returncode)
sys.exit(cpe.returncode)

# WindowXP not supported path.samefile

# WindowXP does not support 'path.samefile'
def sameFile(p1, p2):
if platform == 'win32':
ap1 = path.abspath(p1)
ap2 = path.abspath(p2)
return ap1 == ap2
return path.samefile(p1, p2)


def fnProcessing(target, source, env):
wp = open(str(target[0]), 'wb')
wp.write(open(ARDUINO_SKEL).read())
Expand Down Expand Up @@ -304,48 +312,52 @@ def fnProcessing(target, source, env):
wp.write('#line 1 "%s"\r\n' % sourcePath)
wp.write(open(str(source[0])).read())


def fnCompressCore(target, source, env):
core_prefix = 'build/core/'.replace('/', os.path.sep)
core_files = (x for x in imap(str, source)
if x.startswith(core_prefix))
for file in core_files:
run([AVR_BIN_PREFIX + 'ar', 'rcs', str(target[0]), file])


def fnPrintInfo(target, source, env):
for k in VARTAB:
cameFrom, value = VARTAB[k]
print "* %s: %s (%s)"%(k, value, cameFrom)
print "* %s: %s (%s)" % (k, value, cameFrom)
print "* avr-size:"
run([AVR_BIN_PREFIX + 'size', '--target=ihex', str(source[0])])
# TODO: check binary size
print "* maximum size for hex file: %s bytes" % getBoardConf('upload.maximum_size')


bldProcessing = Builder(action = fnProcessing) #, suffix = '.cpp', src_suffix = sketchExt)
bldCompressCore = Builder(action = fnCompressCore)
bldELF = Builder(action = AVR_BIN_PREFIX + 'gcc -mmcu=%s ' % MCU +
bldProcessing = Builder(action=fnProcessing) # suffix = '.cpp', src_suffix = sketchExt)
bldCompressCore = Builder(action=fnCompressCore)
bldELF = Builder(action=AVR_BIN_PREFIX + 'gcc -mmcu=%s ' % MCU +
'-Os -Wl,--gc-sections -lm %s -o $TARGET $SOURCES -lc' % ' '.join(extra_cflags))
bldHEX = Builder(action = AVR_BIN_PREFIX + 'objcopy -O ihex -R .eeprom $SOURCES $TARGET')
bldInfo = Builder(action = fnPrintInfo)
bldHEX = Builder(action=AVR_BIN_PREFIX + 'objcopy -O ihex -R .eeprom $SOURCES $TARGET')
bldInfo = Builder(action=fnPrintInfo)

envArduino.Append(BUILDERS = {'Processing' : bldProcessing})
envArduino.Append(BUILDERS = {'CompressCore': bldCompressCore})
envArduino.Append(BUILDERS = {'Elf' : bldELF})
envArduino.Append(BUILDERS = {'Hex' : bldHEX})
envArduino.Append(BUILDERS = {'BuildInfo' : bldInfo})
envArduino.Append(BUILDERS={'Processing': bldProcessing})
envArduino.Append(BUILDERS={'CompressCore': bldCompressCore})
envArduino.Append(BUILDERS={'Elf': bldELF})
envArduino.Append(BUILDERS={'Hex': bldHEX})
envArduino.Append(BUILDERS={'BuildInfo': bldInfo})

ptnSource = re.compile(r'\.(?:c(?:pp)?|S)$')


def gatherSources(srcpath):
return [path.join(srcpath, f) for f
in os.listdir(srcpath) if ptnSource.search(f)]

# add arduino core sources
# Add Arduino core sources
VariantDir('build/core', ARDUINO_CORE)
core_sources = gatherSources(ARDUINO_CORE)
core_sources = [x.replace(ARDUINO_CORE, 'build/core/') for x
in core_sources if path.basename(x) != 'main.cpp']

# add libraries
# Add libraries
libCandidates = []
ptnLib = re.compile(r'^[ ]*#[ ]*include [<"](.*)\.h[>"]')
for line in open(TARGET + sketchExt):
Expand All @@ -372,12 +384,12 @@ for index, orig_lib_dir in enumerate(ARDUINO_LIBS):
libName = path.basename(libPath)
if not libName in libCandidates:
continue
envArduino.Append(CPPPATH = libPath.replace(orig_lib_dir, lib_dir))
envArduino.Append(CPPPATH=libPath.replace(orig_lib_dir, lib_dir))
lib_sources = gatherSources(libPath)
utilDir = path.join(libPath, 'utility')
if path.exists(utilDir) and path.isdir(utilDir):
lib_sources += gatherSources(utilDir)
envArduino.Append(CPPPATH = utilDir.replace(orig_lib_dir, lib_dir))
envArduino.Append(CPPPATH=utilDir.replace(orig_lib_dir, lib_dir))
lib_sources = (x.replace(orig_lib_dir, lib_dir) for x in lib_sources)
all_libs_sources.extend(lib_sources)

Expand All @@ -387,9 +399,9 @@ VariantDir('build/local/', build_top)
local_sources = gatherSources(build_top)
local_sources = [x.replace(build_top, 'build/local/') for x in local_sources]
if local_sources:
envArduino.Append(CPPPATH = 'build/local')
envArduino.Append(CPPPATH='build/local')

# Convert sketch(.pde) to cpp
# Convert sketch(.ino) to cpp
envArduino.Processing('build/' + TARGET + '.cpp', 'build/' + TARGET + sketchExt)
VariantDir('build', '.')

Expand All @@ -400,12 +412,13 @@ sources += all_libs_sources

# Finally Build!!
core_objs = envArduino.Object(core_sources)
objs = envArduino.Object(sources) #, LIBS=libs, LIBPATH='.')
objs = envArduino.Object(sources) # LIBS=libs, LIBPATH='.')
objs = objs + envArduino.CompressCore('build/core.a', core_objs)
envArduino.Elf(TARGET + '.elf', objs)
envArduino.Hex(TARGET + '.hex', TARGET + '.elf')
envArduino.BuildInfo(None, TARGET + '.hex')


# Reset
def pulseDTR(target, source, env):
import serial
Expand Down Expand Up @@ -434,8 +447,9 @@ avrdudeOpts = ['-V', '-F', '-c %s' % UPLOAD_PROTOCOL, '-b %s' % UPLOAD_SPEED,
if AVRDUDE_CONF:
avrdudeOpts.append('-C %s' % AVRDUDE_CONF)


if AVR_HOME_DUDE:
AVR_BIN_PREFIX=AVR_HOME_DUDE
AVR_BIN_PREFIX = AVR_HOME_DUDE

fuse_cmd = '%s %s' % (path.join(path.dirname(AVR_BIN_PREFIX), 'avrdude'),
' '.join(avrdudeOpts))
Expand Down