Working example of downloadFirmwareBinary method in Particle JS API?

I am trying to call the downloadFirmwareBinary() method to download the binary after calling compileCode(), the compile succeeds, but the download does not. My code which I am executing with node is currently:

/*jslint node: true */
"use strict";

var auth = require('./auth.js');
var Particle = require('particle-api-js');
var fs = require('fs');

var particle = new Particle();

particle.compileCode({
    files: {
        'tinker.ino': './tinker.ino'
    },
    platformId: 6,
    auth: auth.token
}).then(
    function(data) {
        console.log('Compile succeeded: ' + data.body.binary_id);
        var request = particle.downloadFirmwareBinary({
            binaryId: data.body.binary_id,
            auth: auth.token
        });
        console.log('Writing file');
        var wstream = fs.createWriteStream('./test3.bin');
        request.pipe(wstream);
        wstream.end();
        console.log("Done");
    },
    function(err) {
        console.log('An error occurred while compiling the code:', err);
    });

auth.js contains:

module.exports = {
    token: '<my token>'
};

I see nothing in the console after the ‘Compile suceeded’ message, the program exits normally, but no file is generated. The use of request.pipe is based on piping data. Can anyone help?

Chris

Hey @mdma are you able to help with this?

Running this in a debugger I have found that this.prefix at this line is undefined, its expecting it to be a function based on the message in debug console:

Uncaught (in promise) TypeError: fn is not a function(…)

On further investigation I think the downloadFirmwareBinary() method implementation reflects an older way of doing things, it has no tests, and so has been left behind. I got a particle-js-api dev environment going and managed to get a working version:

downloadFirmwareBinary({ binaryId, auth, stream }) {
	const req = request.get(`/v1/binaries/${binaryId}`);
	req.use(this.agent.prefix);
	req.set({Authorization: `Bearer ${auth}`});
	req.pipe(stream);
}

which I call like this:

var wstream = fs.createWriteStream('./test3.bin');
particle.downloadFirmwareBinary({
    binaryId: data.body.binary_id,
    auth: auth.token,
    stream: wstream
});

Does this seem like a reasonable solution? I am not a Javascript expert.

Chris

cc: @jvanier

Definitely go with your solution if it works. I don’t have a better answer for how this could be done differently.

I opened an issue to look at this in more details: https://github.com/spark/particle-api-js/issues/46

2 Likes