esptool-wrapper
Version:
Super minimal wrapper around esptool.py write_flash
121 lines (89 loc) • 2.78 kB
JavaScript
const async = require("async");
const args = require("minimist")(process.argv);
const debug = require("debug")("esptool-wrapper");
const fs = require("fs");
const spawn = require("child_process").spawn;
const EXEC = "esptool.py";
module.exports = function(config, cb) {
async.waterfall([
function versionCheck(next) {
debug("creating results and starting");
var results = {
args: config.args || []
};
// run `esptoo.py version` to ensure it is; in PATH, executable, maybe version check?
esptoolVersion(function(err, version) {
if(err) {
return cb(new Error("Unable to determine esptool.py version. Ensure it is available in $PATH"));
}
results.version = version;
next(null, results);
});
},
function(results, next) {
if(!config.files) {
return next(new Error("No files to flash! Not sure what to do. Giving up."));
}
debug("verifying files");
async.each(config.files, function(file, done) {
fs.access(file, fs.constants.R_OK, done);
}, function(err) {
next(err, results);
});
},
function(results, next) {
var args = results.args;
debug("building command args");
config.chip && args.push("--chip", config.chip);
config.port && args.push("--port", config.port);
config.baud && args.push("--baud", config.baud);
args.push("write_flash");
if(config.cmdArgs && Array.isArray(config.cmdArgs)) {
args = args.concat(config.cmdArgs);
}
for(var addr in config.files) {
let file = config.files[addr];
args.push(addr, file);
}
results.args = args;
next(null, results);
},
function(results, next) {
debug("flashing");
if(process.env.DRY) {
console.log("%s %s", EXEC, results.args.join(" "));
return next(null);
}
var cp = spawn(EXEC, results.args);
var err = "";
cp.stderr.on("data", function(c) {
err += c.toString();
});
cp.on("close", function(code) {
if(code > 0) {
process.stderr.write(err);
return next(new Error("esptool exited with: " + code));
}
next(null, results);
});
}
], cb);
function esptoolVersion(cb) {
debug("spawning esptool to check version");
var sp = spawn(EXEC, [ "version" ]);
var buf = "";
sp.stdout.on("data", function(c) {
buf += c.toString();
});
sp.on("close", function(code) {
if(code !== 0) {
return cb(code);
}
var parts = buf.split("\n");
// shed last new line
parts.pop();
// return version (hopefully)
cb(null, parts.pop());
});
}
}