All files / lib interchange.js

97.79% Statements 133/136
83.54% Branches 66/79
97.06% Functions 33/34
97.78% Lines 132/135

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 4573x 3x 3x 3x 3x 3x   3x 3x   3x 3x 3x         3x 39x 39x     3x     1x 1x       3x     2x 2x 6x             2x     3x 13x 13x   11x     2x         3x             1x     3x       3x 1x     2x 2x 2x   2x           2x 6x     2x 2x     1x               1x           1x           1x   1x 1x   1x     3x       2x 2x   1x   1x     3x     3x 3x   3x   3x           3x 3x 1x       3x 1x   3x         3x     6x 1x     5x                       5x   5x 5x           5x           4x   3x 2x   3x     1x       3x           2x 1x 1x     2x       3x       6x 6x 1x     6x   6x 2x     6x 5x   4x 1x     1x     3x 8x       3x   2x 2x               3x   3x 3x 3x 3x 3x 3x     3x     3x             3x       7x 7x 1x     6x 1x   5x 1x   4x 1x       3x   3x 1x 1x     3x   2x 2x 2x   1x 1x     2x             2x 2x 2x                                                                                                                                                                                                                                                           3x  
const _ = require('lodash');
const Avrgirl = require('avrgirl-arduino');
const Serialport = require('serialport');
const child_process = require('child_process');
const colors = require('colors');
const fsextra = require('fs-extra');
 
const interchange_client = require('./interchange_client');
const Downloader = require('./downloader');
 
const creators = require('./firmwares.json').creators;
const firmwares = require('./firmwares.json').firmwares;
const version = require('../package.json').version;
 
// I think this can be refactored to be purely in the function where it is needed
let ic_client;//  = new interchange_client.Client();
 
const Interchange = function() {
  this.firmwares = firmwares;
  ic_client = new interchange_client.Client();
};
 
Interchange.prototype.clean_temp_dir = function(tmpdir) {
  // takes a temporary directory and cleans up any files within it and
  // then calls the callback to remove itself.
  Eif (tmpdir != undefined && tmpdir !== null && tmpdir !== '') {
    fsextra.removeSync(tmpdir.name);
  }
};
 
Interchange.prototype.list_devices = function() {
  // this method returns the list of available firmwares as a JSON object
 
  const fws = [];
  firmwares.forEach((firmware) => {
    fws.push({
      name: firmware.name,
      firmata: (firmware.firmata ? true : false),
      description: firmware.description
    });
  });
 
  return (fws);
};
 
Interchange.prototype.get_ports = function(cb) {
  return new Promise((resolve, reject) => {
    Serialport.list()
      .then((ports) => {
        resolve(ports);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
 
Interchange.prototype.list_ports = function() {
  // this function lists out all the ports available to flash firmware
  // this function  is now deprecated
  /* istanbul ignore next */
  if (!process.env.TEST) {
    console.warn('list_ports method deprecated - use get_ports instead');
  }
  return this.get_ports();
};
 
Interchange.prototype.check_firmware = (firmware, options = {}) => {
  // checks if the firmware makes sense and downloads the hex file
  // to a temporary location
 
  if (firmware == undefined || firmware == null) {
    throw new Error('Must define a firmware to flash');
  }
 
  const board = options.board || 'nano'; // assumes nano if none provided
  const useFirmata = (firmware.indexOf('Firmata') > 0) || options.firmata || false;
  let firmataName = options.firmata || '';
  // check for default where no firmata name is supplied or default is implied.
  Iif (firmataName === true) {
    // set it to empty string
    firmataName = '';
  }
 
  // see if the firmware is in the directory
  fw = _.find(firmwares, function(f) {
    return f.name == firmware;
  });
 
  Eif (fw == undefined) {
    if (firmware.indexOf('git+https') >= 0) {
      // command has been passed with a git repo so make a temp object for
      // fw with appropriate stuff in it.
      fw = {
        'name': firmware,
        'deviceID': 0x01,
        'creatorID': 0x00,
        'repo': firmware,
        'firmata': useFirmata
      };
    } else {
      throw new Error('No firmware found: ' + firmware);
    }
  }
 
  // we have a firmware - check if we need firmata
  // this is not currently an issue as all firmwares provide firmata support
  Iif (useFirmata) {
    if (! fw.firmata) {
      throw new Error(`Firmware ${fw.name} does not support custom firmata`);
    }
  }
 
  const opts = options || {};
 
  opts['useFirmata'] = useFirmata;
  opts['firmataName'] = firmataName;
 
  return {fw, opts};
};
 
Interchange.prototype.download_firmware = (fw, opts) => {
  // Figure out how to download and locate the appropriate firmware
  // then return the path to the file and optionally the temporary directory
  // returns the promise to download which will fulfill later.
  const dl = new Downloader({fw});
  return dl.download(fw, opts)
    .then(({hexpath, tmpdir}) => {
      return ({hexpath, tmpdir});
    })
    .catch((err) => { throw err });
};
 
Interchange.prototype.flash_firmware = function(firmware, opts) {
  // flashes the board with the options provided.
 
  const board = opts.board || 'nano'; // assumes nano if none provided
  let port = opts.port || ''; // will leave empty and sees what happens.
 
  return new Promise((resolve, reject) => {
    // wrap this in a promise to handle the callback flow a bit better.
    const avrgirl = new Avrgirl({
      board,
      port,
      debug: () => {}
    });
 
    avrgirl.flash(firmware, (err) => {
      if (err) {
        reject(err);
      }
 
      //  send the port back to be able to configure it.
      if (port == '') {
        port = avrgirl.options.port;
      }
      resolve(port);
    });
  });
};
 
Interchange.prototype.install_firmware = async function(firmware, options = {}) {
  // manages the firmware installation process
 
  if (!firmware) {
    throw new Error('Please supply a firmware to install');
  }
 
  const settings = {
    board: options.board || process.env.INTERCHANGE_BOARD || 'nano',
    port: options.port || process.env.INTERCHANGE_PORT,
    firmata: options.firmata,
    i2c_address: options.address
  };
 
  // check firmware
  // download firmware
  // flash firmware to device
  // optionally do interchange client configuration
 
  try {
    // check the firmware
    const {fw, opts} = await this.check_firmware(firmware, settings);
    const usingFirmata = opts.useFirmata || false; // Assumes not unless explicit
 
    /* istanbul ignore next */
    if (!process.env.TEST) {
      console.log('Downloading firmware');
    }
    const {hexpath, tmpdir} = await this.download_firmware(fw, opts);
 
    /* istanbul ignore next */
    if (!process.env.TEST) {
      console.log('Flashing firmware to board');
    }
    const port = await this.flash_firmware(hexpath, options)
      .then((serport) => {
        if (tmpdir) {
          this.clean_temp_dir(tmpdir);
        }
        return serport;
      })
      .catch((err) => {
        throw err;
      });
 
    // now we should configure it if required.
    if (!usingFirmata) {
      /* istanbul ignore next */
      if (!process.env.TEST) {
        console.log('Configuring the firmware'.magenta);
      }
      // combine options and firmware details together and pass across
      return this.set_firmware_details(port, {...opts, ...fw})
        .then(() => { return true })
        .catch(err => { throw err });
    }
  } catch (e) {
    throw e;
  }
};
 
Interchange.prototype.get_firmware_info = function(port) {
  // attempts to connect to an interchange firmware and get the
  // installed details.
 
  return new Promise((resolve, reject) => {
    if (!port) {
      reject(new Error('No port specified'));
    }
 
    ic_client.port = port;
 
    ic_client.on('error', (err) => {
      reject(err);
    });
 
    ic_client.on('ready', () => {
      ic_client.get_info((err, data) => {
        // json is returned
        if (err) {
          ic_client.close();
          // emit this as we're inside the handler and need to pass it
          // back outwards appropriately due to context
          ic_client.emit('error', err);
        } else {
          // look up the details from the various resources
          let fw_details = _.find(firmwares, (f) => {
            return ((parseInt(f.creatorID, 16) == data.creatorID) &&
                            (parseInt(f.firmwareID, 16) == data.firmwareID));
          });
 
          if (typeof(fw_details) === 'undefined') {
            // Cannot find firmware match from library. Best guess follows
            Eif (data.creatorID == undefined || data.creatorID == 'undefined') data.creatorID = '0x00';
            fw_details = {
              name: 'Unknown',
              firmwareID: data.firmwareID || 0,
              creatorID: data.creatorID,
              description: 'This is an unknown backpack firmware'
            };
          }
 
          const creator = _.find(creators, {id: fw_details.creatorID});
 
          fw_details.creator = creator;
          fw_details.firmware_version = data.fw_version;
          fw_details.interchange_version = data.ic_version;
          fw_details.compile_date = data.compile_date;
          fw_details.i2c_address = data.i2c_address;
          fw_details.use_custom_addr = data.use_custom_addr;
 
          // close the serial port.
          ic_client.close();
 
          // send the data back.
          resolve(fw_details);
        }
      });
    })
  })
};
 
Interchange.prototype.set_firmware_details = (port, opts) => {
  // sets the firmware details on the hardware as needed
  // opts has values set as hex strings
 
  return new Promise((resolve, reject) => {
    if (!port) {
      reject(new Error('No port specified'));
    } else {
      // check that the shape of the opts is correct.
      if (typeof(opts.address) === 'undefined') {
        return reject(new Error('No default address supplied'));
      }
      if (typeof(opts.firmwareID) === 'undefined') {
        return reject(new Error('No firmware ID supplied'));
      }
      if (typeof(opts.creatorID) === 'undefined') {
        return reject(new Error('No creator ID supplied'));
      }
 
      // now the shape of the object is checked then we can proceed
      ic_client.port = port;
 
      ic_client.on('error', (err) => {
        ic_client.close();
        reject(err);
      });
 
      ic_client.on('ready', () => {
        // use defaults and then check if we need otherwise
        let address = parseInt(opts.address, 16);
        let use_custom = 0;
        if (opts.i2c_address != undefined && opts.i2c_address != 0) {
          // override with the custom one.
          address = parseInt(opts.i2c_address, 16);
          use_custom = 1;
        }
 
        const settings = {
          firmwareID: parseInt(opts.firmwareID, 16),
          creatorID: parseInt(opts.creatorID, 16),
          i2c_address: address,
          use_custom_address: use_custom
        };
 
        ic_client.set_details(settings, () => {
          ic_client.close();
          resolve();
        });
      });
    }
  });
};
 
/**
Interchange.prototype.download_from_github = function(firmware, options, cb) {
  // downloads the firmware from the GH repo
 
  const self = this;
  let manifest_uri = null;
  let base_uri = null;
  let branch = 'master';
  let repo = '';
 
  console.info('Retrieving manifest data from GitHub'.magenta);
 
  if (firmware.repo.indexOf('git+https') == 0) {
    if (firmware.repo.indexOf('#') > 0 ) {
      // we want a branch so get that detail.
      branch = '/' + firmware.repo.substring(firmware.repo.indexOf('#') + 1);
      repo = firmware.repo.substring(22, firmware.repo.indexOf('#'));
    } else {
      repo = firmware.repo.substring(22);
      branch = '/master';
    }
 
    base_uri = 'https://raw.githubusercontent.com' + repo + branch;
    manifest_uri = base_uri + '/manifest.json?' + (new Date().getTime());
  }
 
  if (manifest_uri == null) {
    throw new Error('Cannot find manifest of ' + firmware);
  }
  // download the manifest file and then hand it over to then
  // download the hex file ready to be written to the board
  const tmp_dir = tmp.dirSync();
  const manifest_file_path = tmp_dir.name + '/manifest.json';
 
  Download(manifest_uri).then(data => {
    let manifest = null;
    try {
      manifest = JSON.parse(data);
    } catch (e) {
      console.error('Manifest file incorrect');
      self.clean_temp_dir(tmp_dir);
      throw new Error('Manifest file error');
    }
 
    // now we need to download the hex file.
    let manifest_objects = (options.useFirmata ? manifest.firmata : manifest.backpack);
 
    if (manifest_objects == undefined) {
      console.error("An appropriate bin can't be found to flash in the manifest file.".red);
      console.error("This is likely because either the maintainer hasn't provided the right " +
                "path to the hex file or because you've passed in an innapropriate selector " +
                'on the --firmata= switch');
      console.log('Firmware types available from this manifest file:');
      if (manifest.firmata) {
        console.log('FIRMATA:'.blue);
        if (manifest.firmata.multi) {
          Object.keys(manifest.firmata).forEach(function(key) {
            if (key != 'multi') {
              console.log('\t "' + key + '" use --firmata=' + key);
            }
          });
        } else {
          console.log('\t default use --firmata');
        }
      }
      if (manifest.backpack) {
        console.log('I2C BACKPACK'.blue);
      }
      throw new Error("Can't find binary to flash");
    }
 
    // this deals with a firmata object supplied that isn't the default
    // one in order to grab the right hex file.
    if (options.useFirmata && options.firmataName != '') {
      manifest_objects = manifest.firmata[options.firmataName];
    } else if (options.useFirmata && options.firmataName == '' && manifest.firmata.multi != undefined) {
      // we have multiple firmatas and none have been supplied.
      throw new Error('Multiple firmatas are available, please supply a name');
    }
 
    if (manifest_objects.hexPath == undefined) {
      console.error(manifest_objects);
      self.clean_tmp_dir(tmp_dir);
      throw new Error('Hex path cannot be found');
    }
 
    if (manifest_objects.hexPath.indexOf('/') != 0) {
      manifest_objects.hexPath = '/' + manifest_objects.hexPath;
    }
    const hex_uri = base_uri + manifest_objects.bins + options.board +
                        manifest_objects.hexPath + '?' + (new Date().getTime());
 
    console.info('Downloading hex file')
 
    Download(hex_uri).then(hex_data => {
      const hex_path = tmp_dir.name + '/bin.hex';
      try {
        fs.writeFileSync(hex_path, hex_data);
      } catch (e) {
        console.error("Can't write hex file to file system".red);
        self.clean_tmp_dir(tmp_dir);
        throw new Error('HexWriteError');
      }
 
      // about to call the writer.
      cb(hex_path, tmp_dir, options);
    }).catch(function() {
      console.error("Can't download the hex file (%s)".red, hex_uri);
      self.clean_tmp_dir(tmp_dir);
      throw new Error('HexDownloadError');
    });
  }).catch(function(err) {
    console.error('There was an error downloading or processing the the manifest file.'.red);
    console.log(err);
  });
};
**/
 
 
module.exports = Interchange;