Minor refactor, print STDERR in red

This commit is contained in:
Earle F. Philhower, III
2023-09-29 17:29:18 -07:00
parent ac92013a12
commit 5726dab863
3 changed files with 208 additions and 206 deletions

View File

@ -7,7 +7,7 @@ LittleFS uploader compatible with Arduino IDE 2.2.1 or higher. For use with the
## Usage ## Usage
`[Ctrl]+[Shift]+[P]`, then "`Upload LittleFS to Pico/ESP8266`" `[Ctrl]` + `[Shift]` + `[P]`, then "`Upload LittleFS to Pico/ESP8266`"
## Glitches ## Glitches

Binary file not shown.

View File

@ -8,238 +8,240 @@ const writeEmitter = new vscode.EventEmitter<string>();
let writerReady : boolean = false; let writerReady : boolean = false;
function makeTerminal(title : string) { function makeTerminal(title : string) {
// If it exists, move it to the front // If it exists, move it to the front
let w = vscode.window.terminals.find( (w) => ((w.name === title) && (w.exitStatus === undefined))); let w = vscode.window.terminals.find( (w) => ((w.name === title) && (w.exitStatus === undefined)));
if (w !== undefined) { if (w !== undefined) {
w.show(false); w.show(false);
return; return;
} }
// Not found, make a new terminal // Not found, make a new terminal
const pty = { const pty = {
onDidWrite: writeEmitter.event, onDidWrite: writeEmitter.event,
open: () => { writerReady = true; }, open: () => { writerReady = true; },
close: () => { writerReady = false; }, close: () => { writerReady = false; },
handleInput: () => {} handleInput: () => {}
}; };
let terminal = (<any>vscode.window).createTerminal({name: title, pty}); const terminal = (<any>vscode.window).createTerminal({name: title, pty});
terminal.show(); terminal.show();
} }
function findTool(ctx: ArduinoContext, match : string) : string | undefined { function findTool(ctx: ArduinoContext, match : string) : string | undefined {
let found = false; let found = false;
let ret = undefined; let ret = undefined;
if (ctx.boardDetails !== undefined) { if (ctx.boardDetails !== undefined) {
Object.keys(ctx.boardDetails.buildProperties).forEach( (elem) => { Object.keys(ctx.boardDetails.buildProperties).forEach( (elem) => {
if (elem.startsWith(match) && !found && (ctx.boardDetails?.buildProperties[elem] !== undefined)) { if (elem.startsWith(match) && !found && (ctx.boardDetails?.buildProperties[elem] !== undefined)) {
ret = ctx.boardDetails.buildProperties[elem]; ret = ctx.boardDetails.buildProperties[elem];
found = true; found = true;
} }
}); });
} }
return ret; return ret;
}
// Execute a command and display it's output in the terminal
async function runCommand(exe : string, opts : any[]) {
const cmd = spawn(exe, opts);
for await (const chunk of cmd.stdout) {
writeEmitter.fire(String(chunk).replace(/\n/g, "\r\n"));
}
for await (const chunk of cmd.stderr) {
// Write stderr in red
writeEmitter.fire("\x1b[31m" + String(chunk).replace(/\n/g, "\r\n") + "\x1b[0m");
}
// Wait until the executable finishes
let exitCode = await new Promise( (resolve, reject) => {
cmd.on('close', resolve);
});
return exitCode;
} }
export function activate(context: vscode.ExtensionContext) { export function activate(context: vscode.ExtensionContext) {
// Get the Arduino info extension loaded // Get the Arduino info extension loaded
const arduinoContext: ArduinoContext = vscode.extensions.getExtension('dankeboy36.vscode-arduino-api')?.exports; const arduinoContext: ArduinoContext = vscode.extensions.getExtension('dankeboy36.vscode-arduino-api')?.exports;
if (!arduinoContext) { if (!arduinoContext) {
// Failed to load the Arduino API. // Failed to load the Arduino API.
vscode.window.showErrorMessage("Unable to load the Arduino IDE Context extension."); vscode.window.showErrorMessage("Unable to load the Arduino IDE Context extension.");
return; return;
} }
// Register the command // Register the command
const disposable = vscode.commands.registerCommand('arduino-littlefs-upload.uploadLittleFS', async () => { const disposable = vscode.commands.registerCommand('arduino-littlefs-upload.uploadLittleFS', async () => {
//let str = JSON.stringify(arduinoContext, null, 4); //let str = JSON.stringify(arduinoContext, null, 4);
//console.log(str); //console.log(str);
if ((arduinoContext.boardDetails === undefined) || (arduinoContext.fqbn === undefined)){ if ((arduinoContext.boardDetails === undefined) || (arduinoContext.fqbn === undefined)){
vscode.window.showErrorMessage("Board details not available. Compile the sketch once."); vscode.window.showErrorMessage("Board details not available. Compile the sketch once.");
return; return;
} }
makeTerminal("LittleFS Upload"); makeTerminal("LittleFS Upload");
// Wait for the terminal to become active.
while (!writerReady) {
await new Promise( resolve => setTimeout(resolve, 100) );
}
// Clear the terminal // Wait for the terminal to become active.
writeEmitter.fire('\x1b[2J\x1b[3J\x1b[;H'); let cnt = 0;
while (!writerReady) {
if (cnt++ >= 50) { // Give it 5 seconds and then give up
vscode.window.showErrorMessage("Unable to open upload terminal");
return;
}
await new Promise( resolve => setTimeout(resolve, 100) );
}
writeEmitter.fire("LittleFS Filesystem Uploader\r\n\r\n"); // Clear the terminal
writeEmitter.fire('\x1b[2J\x1b[3J\x1b[;H');
// Need to have a data folder present, or this isn't gonna work... writeEmitter.fire("LittleFS Filesystem Uploader\r\n\r\n");
let dataFolder = arduinoContext.sketchPath + "/data";
if (!fs.existsSync(dataFolder)) {
writeEmitter.fire("ERROR: No data folder found\r\n");
return;
}
// Figure out what we're running on // Need to have a data folder present, or this isn't gonna work...
let pico = false; let dataFolder = arduinoContext.sketchPath + "/data";
let esp8266 = false; if (!fs.existsSync(dataFolder)) {
switch (arduinoContext.fqbn.split(':')[1]) { writeEmitter.fire("ERROR: No data folder found\r\n");
case "rp2040": { return;
pico = true; }
break;
}
case "esp8266": {
esp8266 = true;
break;
}
default: {
writeEmitter.fire("ERROR: Only Arduino-Pico RP2040 and ESP8266 supported.\r\n");
return;
}
}
// Need to find the selected menu item, then get the associated build values for the FS configuration // Figure out what we're running on
let fsStart = 0; let pico = false;
let fsEnd = 0; let esp8266 = false;
let page = 0; switch (arduinoContext.fqbn.split(':')[1]) {
let blocksize = 0; case "rp2040": {
let uploadSpeed = 115200; // ESP8266-only pico = true;
arduinoContext.boardDetails.configOptions.forEach( (opt) => { break;
let optSeek = pico ? "flash" : "eesz"; }
let startMarker = pico ? "fs_start" : "spiffs_start"; case "esp8266": {
let endMarker = pico ? "fs_end" : "spiffs_end"; esp8266 = true;
if (String(opt.option) === String(optSeek)) { break;
opt.values.forEach( (itm) => { }
if (itm.selected) { default: {
let menustr = "menu." + optSeek + "." + itm.value + ".build."; writeEmitter.fire("ERROR: Only Arduino-Pico RP2040 and ESP8266 supported.\r\n");
fsStart = Number(arduinoContext.boardDetails?.buildProperties[menustr + startMarker]); return;
fsEnd = Number(arduinoContext.boardDetails?.buildProperties[menustr + endMarker]); }
if (pico) { // Fixed-size always }
page = 256;
blocksize = 4096;
} else if (esp8266) {
page = Number(arduinoContext.boardDetails?.buildProperties[menustr + "spiffs_pagesize"]);
blocksize = Number(arduinoContext.boardDetails?.buildProperties[menustr + "spiffs_blocksize"]);
}
}
});
} else if (String(opt.option) === "baud") {
opt.values.forEach( (itm) => {
if (itm.selected) {
uploadSpeed = Number(itm.value);
}
});
}
});
if (!fsStart || !fsEnd || !page || !blocksize || (fsEnd <= fsStart)) {
writeEmitter.fire("ERROR: No filesystem specified, check flash size menu\r\n");
return;
}
// Windows exes need ".exe" suffix // Need to find the selected menu item, then get the associated build values for the FS configuration
let ext = (platform() === 'win32') ? ".exe" : ""; let fsStart = 0;
let mklittlefs = "mklittlefs" + ext; let fsEnd = 0;
let page = 0;
let blocksize = 0;
let uploadSpeed = 115200; // ESP8266-only
arduinoContext.boardDetails.configOptions.forEach( (opt) => {
let optSeek = pico ? "flash" : "eesz";
let startMarker = pico ? "fs_start" : "spiffs_start";
let endMarker = pico ? "fs_end" : "spiffs_end";
if (String(opt.option) === String(optSeek)) {
opt.values.forEach( (itm) => {
if (itm.selected) {
let menustr = "menu." + optSeek + "." + itm.value + ".build.";
fsStart = Number(arduinoContext.boardDetails?.buildProperties[menustr + startMarker]);
fsEnd = Number(arduinoContext.boardDetails?.buildProperties[menustr + endMarker]);
if (pico) { // Fixed-size always
page = 256;
blocksize = 4096;
} else if (esp8266) {
page = Number(arduinoContext.boardDetails?.buildProperties[menustr + "spiffs_pagesize"]);
blocksize = Number(arduinoContext.boardDetails?.buildProperties[menustr + "spiffs_blocksize"]);
}
}
});
} else if (String(opt.option) === "baud") {
opt.values.forEach( (itm) => {
if (itm.selected) {
uploadSpeed = Number(itm.value);
}
});
}
});
if (!fsStart || !fsEnd || !page || !blocksize || (fsEnd <= fsStart)) {
writeEmitter.fire("ERROR: No filesystem specified, check flash size menu\r\n");
return;
}
let tool = undefined; // Windows exes need ".exe" suffix
if (pico) { let ext = (platform() === 'win32') ? ".exe" : "";
tool = findTool(arduinoContext, "runtime.tools.pqt-mklittlefs"); let mklittlefs = "mklittlefs" + ext;
} else { // ESP826
tool = findTool(arduinoContext, "runtime.tools.mklittlefs");
}
if (tool) {
mklittlefs = tool + "/" + mklittlefs;
}
// TBD - add non-serial UF2 upload via OpenOCD let tool = undefined;
let serialPort = ""; if (pico) {
if (arduinoContext.port?.address === undefined) { tool = findTool(arduinoContext, "runtime.tools.pqt-mklittlefs");
writeEmitter.fire("ERROR: No port specified, check IDE menus.\r\n"); } else { // ESP8266
return; tool = findTool(arduinoContext, "runtime.tools.mklittlefs");
} else { }
serialPort = arduinoContext.port?.address; if (tool) {
} mklittlefs = tool + "/" + mklittlefs;
if (arduinoContext.port?.protocol !== "serial") { }
writeEmitter.fire("ERROR: Only serial port upload supported at this time.\r\n");
return;
}
let python3 = "python3" + ext; // TBD - add non-serial UF2 upload via OpenOCD
let python3Path = undefined; let serialPort = "";
if (pico) { if (arduinoContext.port?.address === undefined) {
python3Path = findTool(arduinoContext, "runtime.tools.pqt-python3"); writeEmitter.fire("ERROR: No port specified, check IDE menus.\r\n");
} else if (esp8266) { return;
python3Path = findTool(arduinoContext, "runtime.tools.python3"); } else {
} serialPort = arduinoContext.port?.address;
if (python3Path) { }
python3 = python3Path + "/" + python3; if (arduinoContext.port?.protocol !== "serial") {
} writeEmitter.fire("ERROR: Only serial port upload supported at this time.\r\n");
return;
}
// We can't always know where the compile path is, so just use a temp name let python3 = "python3" + ext;
const tmp = require('tmp'); let python3Path = undefined;
tmp.setGracefulCleanup(); if (pico) {
let imageFile = tmp.tmpNameSync({postfix: ".littlefs.bin"}); python3Path = findTool(arduinoContext, "runtime.tools.pqt-python3");
} else if (esp8266) {
python3Path = findTool(arduinoContext, "runtime.tools.python3");
}
if (python3Path) {
python3 = python3Path + "/" + python3;
}
let buildOpts = ["-c", dataFolder, "-p", String(page), "-b", String(blocksize), "-s", String(fsEnd - fsStart), imageFile]; // We can't always know where the compile path is, so just use a temp name
const tmp = require('tmp');
tmp.setGracefulCleanup();
let imageFile = tmp.tmpNameSync({postfix: ".littlefs.bin"});
// All mklittlefs take the same options, so run in common let buildOpts = ["-c", dataFolder, "-p", String(page), "-b", String(blocksize), "-s", String(fsEnd - fsStart), imageFile];
writeEmitter.fire("Building LittleFS filesystem\r\n");
writeEmitter.fire(mklittlefs + " " + buildOpts.join(" ") + "\r\n");
const mkfs = spawn(mklittlefs, buildOpts); // All mklittlefs take the same options, so run in common
for await (const chunk of mkfs.stdout) { writeEmitter.fire("Building LittleFS filesystem\r\n");
writeEmitter.fire(String(chunk).replace(/\n/g, "\r\n")); writeEmitter.fire(mklittlefs + " " + buildOpts.join(" ") + "\r\n");
}
for await (const chunk of mkfs.stderr) {
writeEmitter.fire(String(chunk).replace(/\n/g, "\r\n"));
}
// Wait until the executable finishes
let exitCode = await new Promise( (resolve, reject) => {
mkfs.on('close', resolve);
});
if (exitCode) { let exitCode = await runCommand(mklittlefs, buildOpts);
writeEmitter.fire("ERROR: Mklittlefs failed, error code: " + String(exitCode) + "\r\n\r\n"); if (exitCode) {
return; writeEmitter.fire("ERROR: Mklittlefs failed, error code: " + String(exitCode) + "\r\n\r\n");
} return;
}
// Upload stage differs per core // Upload stage differs per core
let uploadOpts : any[] = []; let uploadOpts : any[] = [];
if (pico) { if (pico) {
let uf2conv = "tools/uf2conv.py"; let uf2conv = "tools/uf2conv.py";
let uf2Path = findTool(arduinoContext, "runtime.platform.path"); let uf2Path = findTool(arduinoContext, "runtime.platform.path");
if (uf2Path) { if (uf2Path) {
uf2conv = uf2Path + "/" + uf2conv; uf2conv = uf2Path + "/" + uf2conv;
} }
uploadOpts = [uf2conv, "--base", String(fsStart), "--serial", serialPort, "--family", "RP2040", imageFile]; uploadOpts = [uf2conv, "--base", String(fsStart), "--serial", serialPort, "--family", "RP2040", imageFile];
} else { } else {
let upload = "tools/upload.py"; let upload = "tools/upload.py";
let uploadPath = findTool(arduinoContext, "runtime.platform.path"); let uploadPath = findTool(arduinoContext, "runtime.platform.path");
if (uploadPath) { if (uploadPath) {
upload = uploadPath + "/" + upload; upload = uploadPath + "/" + upload;
} }
uploadOpts = [upload, "--chip", "esp8266", "--port", serialPort, "--baud", String(uploadSpeed), "write_flash", String(fsStart), imageFile]; uploadOpts = [upload, "--chip", "esp8266", "--port", serialPort, "--baud", String(uploadSpeed), "write_flash", String(fsStart), imageFile];
} }
writeEmitter.fire("\r\n\r\nUploading LittleFS filesystem\r\n"); writeEmitter.fire("\r\n\r\nUploading LittleFS filesystem\r\n");
writeEmitter.fire(python3 + " " + uploadOpts.join(" ") + "\r\n"); writeEmitter.fire(python3 + " " + uploadOpts.join(" ") + "\r\n");
const upld = spawn(python3, uploadOpts);
for await (const chunk of upld.stdout) {
writeEmitter.fire(String(chunk).replace(/\n/g, "\r\n"));
}
for await (const chunk of upld.stderr) {
writeEmitter.fire(String(chunk).replace(/\n/g, "\r\n"));
}
// Wait until the executable finishes
exitCode = await new Promise( (resolve, reject) => {
upld.on('close', resolve);
});
if (exitCode) { exitCode = await runCommand(python3, uploadOpts);
writeEmitter.fire("ERROR: Upload failed, error code: " + String(exitCode) + "\r\n\r\n"); if (exitCode) {
return; writeEmitter.fire("ERROR: Upload failed, error code: " + String(exitCode) + "\r\n\r\n");
} return;
}
writeEmitter.fire("\r\n\Completed upload.\r\n\r\n"); writeEmitter.fire("\r\n\Completed upload.\r\n\r\n");
vscode.window.showInformationMessage("LittleFS upload completed!"); vscode.window.showInformationMessage("LittleFS upload completed!");
}); });
context.subscriptions.push(disposable); context.subscriptions.push(disposable);
} }
export function deactivate() { } export function deactivate() { }