Using extra scripts to save files to directory specified in platformio.ini environment

I have a script that saves the .hex output to a directory when I build a project, for use with an external programmer.

Rather than always simply saving to ./output.hex, I would like to know how to do two things:

  1. Save relative to the main.cpp file (containing loop() and setup() for an AVR)
  2. Save to a directory specified in platformio.ini

For the first option, I don’t know how to determine the directory of the main file.

For the second option, I think I can use configparser to read custom configuration variables, but I don’t know how to do it for the specific environment called, e.g. main vs test1, since I don’t know how to determine which environment is being built within the script.

src_filter = +<*> -<.git/> -<src/> -<tests/> -<example/> -<examples/> -<lib/>
extra_scripts =

src_filter = ${env.src_filter} +<src/>
savedir = ${workspacedir}

src_filter = ${env.src_filter} +<test/test1/>
savedir = ./test/


Import("env", "projenv")
from shutil import copyfile

def save_hex(*args, **kwargs):
    print("Copying hex output to project directory...")
    target = str(kwargs['target'][0])
    copyfile(target, 'output.hex')

env.AddPostAction("$BUILD_DIR/${PROGNAME}.hex", save_hex)   #post action for .hex
1 Like

I’ve worked out a temporary solution, but it’s kludgy and fragile. Any help/suggestions for a “real” and more robust solution are still welcome!

    import configparser
except ImportError:
    import ConfigParser as configparser

config = configparser.ConfigParser()"platformio.ini")

def save_hex(**kwargs):
    target = str(kwargs['target'][0])
    savename = target.split('\\')[-2]   # name of environment
    savepath = config.get('env:{}'.format(savename), "savepath")
    savefile = '{}\{}.hex'.format(savepath, savename)
    copyfile(target, savefile)
1 Like