All files / src/lifx/packets stateDeviceChain.js

96.42% Statements 27/28
75% Branches 3/4
100% Functions 4/4
96.42% Lines 27/28

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    1x 1x   1x                                 1x 2x     2x 2x 2x 2x 2x 2x 26x 26x 26x   2x 2x               1x 2x 2x   2x   2x 2x 2x 2x 26x   2x     1x  
'use strict';
 
const Tile = require('./tile');
const {validate} = require('../../lifx');
 
const Packet = {
  size: 2 + (Tile.size * 16),
  Tile
};
 
/**
 * @typedef {Object} StateDeviceChain
 * @property {Number} startIndex - UInt8 startIndex
 * @property {Number} totalCount - UInt8 totalCount
 * @property {Tile[]} tileDevices- Array of Tiles
 */
 
/**
 * Converts packet specific data from a buffer to an object
 * @param  {Buffer} buf Buffer containing only packet specific data no header
 * @return {StateDeviceChain}     Information contained in packet
 */
Packet.toObject = function(buf) {
  Iif (buf.length !== this.size) {
    throw new Error(`Invalid length given for stateDeviceChain LIFX packet:${buf.length}:${this.size}`);
  }
  let offset = 0;
  const obj = {};
  obj.startIndex = buf.readUInt8(offset);
  obj.totalCount = Math.min(buf.readUInt8(buf.length - 1), 16);
  offset += 1;
  obj.tileDevices = Array(obj.totalCount).fill(undefined).map(() => {
    const ret = Packet.Tile.toObject(buf, offset);
    offset = ret.offset;
    return ret.tile;
  });
  offset += 1;
  return obj;
};
 
/**
 * Converts packet specific data from a buffer to an object
 * @param  {StateDeviceChain} obj - as Object
 * @return {Buffer} - Buffer of the packet
 */
Packet.toBuffer = function(obj) {
  const buf = Buffer.alloc(this.size);
  buf.fill(0);
 
  validate.isUInt8(obj.startIndex, 'stateDeviceChain:start_index');
 
  buf.writeUInt8(obj.startIndex, 0);
  const len = Math.min(obj.tileDevices.length, obj.totalCount || 16);
  buf.writeUInt8(len, Packet.size - 1);
  obj.tileDevices.slice(0, len).reduce((ofs, tile) => {
    return Packet.Tile.toBuffer(buf, ofs, tile).offset;
  }, 1);
  return buf;
};
 
module.exports = Packet;