all files / lib/lifx/ client.js

91.24% Statements 302/331
88.29% Branches 181/205
91.67% Functions 33/36
91.24% Lines 302/331
3 statements, 3 branches Ignored     
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 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746                                                        44×   44× 44× 44× 44× 44× 44× 44× 44× 44× 44× 44× 44×                   44× 44× 44× 44× 44× 44× 44× 44× 44× 44×                                                 35×                                   35× 35×   35× 34×     32×   31×   31×   30×   30×   29×   29×   28×   28×   27×   27× 26×   25×   25× 24×   22×   22×   20×     19×   19×   18×       18×             16× 15×   14×   14× 13×   12×   12×               12×                                                         12× 12× 12× 12× 12×     12×   12× 12×               44×   44× 44× 35×   44× 12×                   143×   143× 35×   143×                 35×   35× 35×                                                       49×   49×   31× 31×               38×   38× 31× 31×                                                                                               22×                               20×                                                                                               46× 46×                                         49×               49×   49× 41× 41×             49× 49× 49× 11× 11× 11×   49×   49× 49× 49×   49×   49×             10× 10× 10×   10×                                       35×   34×     33× 33×     32×           32× 31×   30×       31×                                               53× 53×       51×       50×         48× 48×       43×   43×    
'use strict';
 
var util = require('util');
var dgram = require('dgram');
var EventEmitter = require('eventemitter3');
 
var _require = require('lodash'),
    defaults = _require.defaults,
    isArray = _require.isArray,
    isBoolean = _require.isBoolean,
    isString = _require.isString,
    isNil = _require.isNil,
    result = _require.result,
    find = _require.find,
    bind = _require.bind,
    forEach = _require.forEach,
    keys = _require.keys,
    every = _require.every,
    includes = _require.includes,
    filter = _require.filter;
 
var Packet = require('../lifx').packet;
 
var _require2 = require('../lifx'),
    Light = _require2.Light,
    constants = _require2.constants,
    utils = _require2.utils;
 
/**
 * Creates a lifx client
 * @extends EventEmitter
 */
 
 
function Client() {
  EventEmitter.call(this);
 
  this.debug = false;
  this.socket = dgram.createSocket('udp4');
  this.isSocketBound = false;
  this.devices = {};
  this.port = null;
  this.messageQueues = {};
  this.sendTimers = {};
  this.messageRateLimit = 50; // ms
  this.discoveryTimer = null;
  this.discoveryInterval = 5000; // ms
  this.discoveryPacketSequence = 0;
  this.messageHandlers = [{
    type: 'stateService',
    callback: this.processDiscoveryPacket.bind(this)
  }, {
    type: 'stateLabel',
    callback: this.processLabelPacket.bind(this)
  }, {
    type: 'stateLight',
    callback: this.processLabelPacket.bind(this)
  }];
  this.sequenceNumber = 0;
  this.lightOfflineTolerance = 3;
  this.messageHandlerTimeout = 45000; // 45 sec
  this.resendPacketDelay = 150;
  this.resendMaxTimes = 5;
  this.source = utils.getRandomHexString(8);
  this.broadcastAddress = '255.255.255.255';
  this.lightAddresses = [];
  this.stopAfterDiscovery = false;
  this.discoveryCompleted = false;
}
util.inherits(Client, EventEmitter);
 
/**
 * Creates a new socket and starts discovery
 * @example
 * init({debug: true}, function() {
 *   console.log('Client started');
 * })
 * @param {Object} [options] Configuration to use
 * @param {String} [options.address] The IPv4 address to bind to
 * @param {Number} [options.port] The port to bind to
 * @param {Boolean} [options.debug] Show debug output
 * @param {Number} [options.lightOfflineTolerance] If light hasn't answered for amount of discoveries it is set offline
 * @param {Number} [options.messageHandlerTimeout] Message handlers not called will be removed after this delay in ms
 * @param {String} [options.source] The source to send to light, must be 8 chars lowercase or digit
 * @param {Boolean} [options.startDiscovery] Weather to start discovery after initialization or not
 * @param {Array} [options.lights] Pre set list of ip addresses of known addressable lights
 * @param {Boolean} [options.stopAfterDiscovery] Stop discovery after discovering known addressable lights defined with options.light
 * @param {String} [options.broadcast] The broadcast address to use for light discovery
 * @param {Number} [options.sendPort] The port to send messages to
 * @param {Number} [options.messageRateLimit] The minimum delay (in ms) between sending any two packets to a single light
 * @param {Number} [options.discoveryInterval] Interval (in ms) between discovery operations
 * @param {Function} [callback] Called after initialation
 */
Client.prototype.init = function (options, callback) {
  var defaultOpts = {
    address: '0.0.0.0',
    port: 0,
    debug: false,
    lightOfflineTolerance: 3,
    messageHandlerTimeout: 45000,
    source: '',
    startDiscovery: true,
    lights: [],
    stopAfterDiscovery: false,
    broadcast: '255.255.255.255',
    sendPort: constants.LIFX_DEFAULT_PORT,
    resendPacketDelay: 150,
    resendMaxTimes: 3,
    messageRateLimit: 50,
    discoveryInterval: 5000
  };
 
  options = options || {};
  var opts = defaults(options, defaultOpts);
 
  if (typeof opts.port !== 'number') {
    throw new TypeError('LIFX Client port option must be a number');
  } else if (opts.port > 65535 || opts.port < 0) {
    throw new RangeError('LIFX Client port option must be between 0 and 65535');
  }
 
  if (typeof opts.debug !== 'boolean') {
    throw new TypeError('LIFX Client debug option must be a boolean');
  }
  this.debug = opts.debug;
 
  if (typeof opts.lightOfflineTolerance !== 'number') {
    throw new TypeError('LIFX Client lightOfflineTolerance option must be a number');
  }
  this.lightOfflineTolerance = opts.lightOfflineTolerance;
 
  if (typeof opts.messageHandlerTimeout !== 'number') {
    throw new TypeError('LIFX Client messageHandlerTimeout option must be a number');
  }
  this.messageHandlerTimeout = opts.messageHandlerTimeout;
 
  if (typeof opts.resendPacketDelay !== 'number') {
    throw new TypeError('LIFX Client resendPacketDelay option must be a number');
  }
  this.resendPacketDelay = opts.resendPacketDelay;
 
  if (typeof opts.resendMaxTimes !== 'number') {
    throw new TypeError('LIFX Client resendMaxTimes option must be a number');
  }
  this.resendMaxTimes = opts.resendMaxTimes;
 
  if (typeof opts.broadcast !== 'string') {
    throw new TypeError('LIFX Client broadcast option must be a string');
  } else if (!utils.isIpv4Format(opts.broadcast)) {
    throw new TypeError('LIFX Client broadcast option does only allow IPv4 address format');
  }
  this.broadcastAddress = opts.broadcast;
 
  if (typeof opts.sendPort !== 'number') {
    throw new TypeError('LIFX Client sendPort option must be a number');
  } else if (opts.sendPort > 65535 || opts.sendPort < 1) {
    throw new RangeError('LIFX Client sendPort option must be between 1 and 65535');
  }
  this.sendPort = opts.sendPort;
 
  if (!isArray(opts.lights)) {
    throw new TypeError('LIFX Client lights option must be an array');
  } else {
    opts.lights.forEach(function (light) {
      if (!utils.isIpv4Format(light)) {
        throw new TypeError('LIFX Client lights option array element \'' + light + '\' is not expected IPv4 format');
      }
    });
    this.lightAddresses = opts.lights;
 
    if (!isBoolean(opts.stopAfterDiscovery)) {
      throw new TypeError('LIFX Client stopAfterDiscovery must be a boolean');
    } else {
      this.stopAfterDiscovery = opts.stopAfterDiscovery;
    }
  }
 
  if (opts.source !== '') {
    if (typeof opts.source === 'string') {
      if (/^[0-9A-F]{8}$/.test(opts.source)) {
        this.source = opts.source;
      } else {
        throw new RangeError('LIFX Client source option must be 8 hex chars');
      }
    } else {
      throw new TypeError('LIFX Client source option must be given as string');
    }
  }
 
  if (typeof opts.messageRateLimit !== 'number') {
    throw new TypeError('LIFX Client messageRateLimit option must be a number');
  } else if (opts.messageRateLimit <= 0) {
    throw new RangeError('LIFX Client messageRateLimit option must greater than 0');
  }
  this.messageRateLimit = opts.messageRateLimit;
 
  if (typeof opts.discoveryInterval !== 'number') {
    throw new TypeError('LIFX Client discoveryInterval option must be a number');
  } else if (opts.discoveryInterval <= 0) {
    throw new RangeError('LIFX Client discoveryInterval option must greater than 0');
  }
  this.discoveryInterval = opts.discoveryInterval;
 
  this.socket.on('error', function (err) {
    this.isSocketBound = false;
    console.error('LIFX Client UDP error');
    console.trace(err);
    this.socket.close();
    this.emit('error', err);
  }.bind(this));
 
  this.socket.on('message', function (msg, rinfo) {
    // Ignore own messages and false formats
    Eif (utils.getHostIPs().indexOf(rinfo.address) >= 0 || !Buffer.isBuffer(msg)) {
      return;
    }
 
    /* istanbul ignore if  */
    if (this.debug) {
      console.log('DEBUG - ' + msg.toString('hex') + ' from ' + rinfo.address);
    }
 
    // Parse packet to object
    var parsedMsg = Packet.toObject(msg);
 
    // Check if packet is read successfully
    if (parsedMsg instanceof Error) {
      console.error('LIFX Client invalid packet header error');
      console.error('Packet: ', msg.toString('hex'));
      console.trace(parsedMsg);
    } else {
      // Convert type before emitting
      var messageTypeName = result(find(Packet.typeList, { id: parsedMsg.type }), 'name');
      if (messageTypeName !== undefined) {
        parsedMsg.type = messageTypeName;
      }
      // Check for handlers of given message and rinfo
      this.processMessageHandlers(parsedMsg, rinfo);
 
      this.emit('message', parsedMsg, rinfo);
    }
  }.bind(this));
 
  this.socket.bind(opts.port, opts.address, function () {
    this.isSocketBound = true;
    this.socket.setBroadcast(true);
    this.emit('listening');
    this.port = opts.port;
 
    // Start scanning
    if (opts.startDiscovery) {
      this.startDiscovery(opts.lights);
    }
    Eif (typeof callback === 'function') {
      return callback();
    }
  }.bind(this));
};
 
/**
 * Destroy an instance
 */
Client.prototype.destroy = function () {
  var _this = this;
 
  this.stopDiscovery();
  forEach(keys(this.messageQueues), function (queueAddress) {
    _this.stopSendingProcess(queueAddress);
  });
  if (this.isSocketBound) {
    this.socket.close();
  }
};
 
/**
 * Gets the message queue for the given address. If no address  is defined,
 * defaults to broadcast address.
 * @param {String} queueAddress Message queue address
 * @return {Array} Message queue for the address
 */
Client.prototype.getMessageQueue = function () {
  var queueAddress = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.broadcastAddress;
 
  if (isNil(this.messageQueues[queueAddress])) {
    this.messageQueues[queueAddress] = [];
  }
  return this.messageQueues[queueAddress];
};
 
/**
 * Sends a packet from the messages queue or stops the sending process
 * if queue is empty
 * @param {String} queueAddress Message queue id
 * @return {Function} Sending process for the message queue
 **/
Client.prototype.sendingProcess = function (queueAddress) {
  var _this2 = this;
 
  var messageQueue = this.getMessageQueue(queueAddress);
  return function () {
    Iif (!_this2.isSocketBound) {
      _this2.stopSendingProcess(queueAddress);
      console.log('LIFX Client stopped sending due to unbound socket');
      return;
    }
 
    Eif (messageQueue.length > 0) {
      var msg = messageQueue.pop();
      Eif (msg.address === undefined) {
        msg.address = _this2.broadcastAddress;
      }
      if (msg.transactionType === constants.PACKET_TRANSACTION_TYPES.ONE_WAY) {
        _this2.socket.send(msg.data, 0, msg.data.length, _this2.sendPort, msg.address);
        /* istanbul ignore if  */
        Iif (_this2.debug) {
          console.log('DEBUG - ' + msg.data.toString('hex') + ' to ' + msg.address);
        }
      } else Eif (msg.transactionType === constants.PACKET_TRANSACTION_TYPES.REQUEST_RESPONSE) {
        if (msg.timesSent < _this2.resendMaxTimes) {
          Eif (Date.now() > msg.timeLastSent + _this2.resendPacketDelay) {
            _this2.socket.send(msg.data, 0, msg.data.length, _this2.sendPort, msg.address);
            msg.timesSent += 1;
            msg.timeLastSent = Date.now();
            /* istanbul ignore if  */
            Iif (_this2.debug) {
              console.log('DEBUG - ' + msg.data.toString('hex') + ' to ' + msg.address + ', send ' + msg.timesSent + ' time(s)');
            }
          }
          // Add to the end of the queue again
          messageQueue.unshift(msg);
        } else {
          _this2.messageHandlers.forEach(function (handler, hdlrIndex) {
            if (handler.type === 'acknowledgement' && handler.sequenceNumber === msg.sequence) {
              this.messageHandlers.splice(hdlrIndex, 1);
              var err = new Error('No LIFX response after max resend limit of ' + this.resendMaxTimes);
              return handler.callback(err, null, null);
            }
          }.bind(_this2));
        }
      }
    } else {
      _this2.stopSendingProcess(queueAddress);
    }
  };
};
 
/**
 * Starts the sending of all packages in the queue
 * @param {String} queueAddress Message queue id
 */
Client.prototype.startSendingProcess = function () {
  var queueAddress = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.broadcastAddress;
 
  if (isNil(this.sendTimers[queueAddress])) {
    // Already running?
    var sendingProcess = this.sendingProcess(queueAddress);
    this.sendTimers[queueAddress] = setInterval(sendingProcess, this.messageRateLimit);
  }
};
 
/**
 * Stops sending of all packages in the queue
 * @param {String} queueAddress Message queue id
 */
Client.prototype.stopSendingProcess = function () {
  var queueAddress = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.broadcastAddress;
 
  if (!isNil(this.sendTimers[queueAddress])) {
    clearInterval(this.sendTimers[queueAddress]);
    delete this.sendTimers[queueAddress];
  }
};
 
/**
 * Start discovery of lights
 * This will keep the list of lights updated, finds new lights and sets lights
 * offline if no longer found
 * @param {Array} [lights] Pre set list of ip addresses of known addressable lights to request directly
 */
Client.prototype.startDiscovery = function (lights) {
  lights = lights || [];
  var sendDiscoveryPacket = function () {
    // Sign flag on inactive lights
    forEach(this.devices, bind(function (info, deviceId) {
      Eif (this.devices[deviceId].status !== 'off') {
        var diff = this.discoveryPacketSequence - info.seenOnDiscovery;
        Iif (diff >= this.lightOfflineTolerance) {
          this.devices[deviceId].status = 'off';
          this.emit('bulb-offline', info); // deprecated
          this.emit('light-offline', info);
        }
      }
    }, this));
 
    // Send a discovery packet broadcast
    this.send(Packet.create('getService', {}, this.source));
 
    // Send a discovery packet to each light given directly
    lights.forEach(function (lightAddress) {
      var msg = Packet.create('getService', {}, this.source);
      msg.address = lightAddress;
      this.send(msg);
    }, this);
 
    // Keep track of a sequent number to find not answering lights
    Iif (this.discoveryPacketSequence >= Number.MAX_VALUE) {
      this.discoveryPacketSequence = 0;
    } else {
      this.discoveryPacketSequence += 1;
    }
  }.bind(this);
 
  this.discoveryTimer = setInterval(sendDiscoveryPacket, this.discoveryInterval);
 
  sendDiscoveryPacket();
};
 
/**
 * Checks if light discovery is in progress
 * @return {Boolean} is discovery in progress
 */
Client.prototype.isDiscovering = function () {
  return this.discoveryTimer !== null;
};
 
/**
 * Checks all registered message handlers if they request the given message
 * @param  {Object} msg message to check handler for
 * @param  {Object} rinfo rinfo address info to check handler for
 */
Client.prototype.processMessageHandlers = function (msg, rinfo) {
  var messageQueue = this.getMessageQueue(rinfo.address);
  // Process only packages for us
  Iif (msg.source.toLowerCase() !== this.source.toLowerCase()) {
    return;
  }
  // We check our message handler if the answer received is requested
  this.messageHandlers.forEach(function (handler, hdlrIndex) {
    if (msg.type === handler.type) {
      if (handler.sequenceNumber !== undefined) {
        if (handler.sequenceNumber === msg.sequence) {
          // Remove if specific packet was request, since it should only be called once
          this.messageHandlers.splice(hdlrIndex, 1);
          messageQueue.forEach(function (packet, packetIndex) {
            if (packet.transactionType === constants.PACKET_TRANSACTION_TYPES.REQUEST_RESPONSE && packet.sequence === msg.sequence) {
              messageQueue.splice(packetIndex, 1);
            }
          });
 
          // Call the function requesting the packet
          return handler.callback(null, msg, rinfo);
        }
      } else {
        // Call the function requesting the packet
        return handler.callback(null, msg, rinfo);
      }
    }
 
    // We want to call expired request handlers for specific packages after the
    // messageHandlerTimeout set in options, to specify an error
    if (handler.sequenceNumber !== undefined) {
      if (Date.now() > handler.timestamp + this.messageHandlerTimeout) {
        this.messageHandlers.splice(hdlrIndex, 1);
 
        var err = new Error('No LIFX response in time');
        return handler.callback(err, null, null);
      }
    }
  }, this);
};
 
/**
 * Processes a discovery report packet to update internals
 * @param  {Object} err Error if existant
 * @param  {Object} msg The discovery report package
 * @param  {Object} rinfo Remote host details
 */
Client.prototype.processDiscoveryPacket = function (err, msg, rinfo) {
  if (err) {
    return;
  }
  if (msg.service === 'udp' && msg.port === constants.LIFX_DEFAULT_PORT) {
    // Add / update the found gateway
    if (!this.devices[msg.target]) {
      var lightDevice = new Light({
        client: this,
        id: msg.target,
        address: rinfo.address,
        port: msg.port,
        seenOnDiscovery: this.discoveryPacketSequence
      });
      this.devices[msg.target] = lightDevice;
 
      // Request label
      var labelRequest = Packet.create('getLabel', {}, this.source);
      labelRequest.target = msg.target;
      this.send(labelRequest);
 
      this.emit('bulb-new', lightDevice); // deprecated
      this.emit('light-new', lightDevice);
    } else {
      if (this.devices[msg.target].status === 'off') {
        this.devices[msg.target].status = 'on';
        this.emit('bulb-online', this.devices[msg.target]); // deprecated
        this.emit('light-online', this.devices[msg.target]);
      }
      this.devices[msg.target].address = rinfo.address;
      this.devices[msg.target].seenOnDiscovery = this.discoveryPacketSequence;
    }
 
    // Check if discovery should be stopped
    if (this.stopAfterDiscovery && !this.discoveryCompleted) {
      if (this.predefinedDiscoveredAndOnline()) {
        this.emit('discovery-completed');
        this.stopDiscovery();
        this.discoveryCompleted = true;
      }
    }
  }
};
 
/**
 * Processes a state label packet to update internals
 * @param {Object} err Error if existant
 * @param {Object} msg The state label package
 */
Client.prototype.processLabelPacket = function (err, msg) {
  Iif (err) {
    return;
  }
  Eif (this.devices[msg.target] !== undefined) {
    this.devices[msg.target].label = msg.label;
  }
};
 
/**
 * This stops the discovery process
 * The client will be no longer updating the state of lights or find lights
 */
Client.prototype.stopDiscovery = function () {
  clearInterval(this.discoveryTimer);
  this.discoveryTimer = null;
};
 
/**
 * Checks if all predefined lights are discovered and online
 * @return {Boolean} are lights discovered and online
 */
Client.prototype.predefinedDiscoveredAndOnline = function () {
  var _this3 = this;
 
  var predefinedDevices = filter(this.devices, function (device) {
    return includes(_this3.lightAddresses, device.address);
  });
 
  var numDiscovered = keys(this.devices).length;
  var allDiscovered = numDiscovered >= this.lightAddresses.length;
  var allOnline = every(predefinedDevices, function (device) {
    return device.status === 'on';
  });
  var labelsReceived = every(predefinedDevices, function (device) {
    return isString(device.label);
  });
 
  return allDiscovered && allOnline && labelsReceived;
};
 
/**
 * Send a LIFX message objects over the network
 * @param  {Object} msg A message object or multiple with data to send
 * @param  {Function} [callback] Function to handle error and success after send
 * @return {Number} The sequence number of the request
 */
Client.prototype.send = function (msg, callback) {
  var packet = {
    timeCreated: Date.now(),
    timeLastSent: 0,
    timesSent: 0,
    transactionType: constants.PACKET_TRANSACTION_TYPES.ONE_WAY
  };
 
  // Add the target ip address if target given
  if (msg.address !== undefined) {
    packet.address = msg.address;
  }
  if (msg.target !== undefined) {
    var targetBulb = this.light(msg.target);
    if (targetBulb) {
      packet.address = targetBulb.address;
      // If we would exceed the max value for the int8 field start over again
      if (this.sequenceNumber >= constants.PACKET_HEADER_SEQUENCE_MAX) {
        this.sequenceNumber = 0;
      } else {
        this.sequenceNumber += 1;
      }
    }
  }
 
  msg.sequence = this.sequenceNumber;
  packet.sequence = this.sequenceNumber;
  if (typeof callback === 'function') {
    msg.ackRequired = true;
    this.addMessageHandler('acknowledgement', callback, msg.sequence);
    packet.transactionType = constants.PACKET_TRANSACTION_TYPES.REQUEST_RESPONSE;
  }
  packet.data = Packet.toBuffer(msg);
 
  var queueAddress = packet.address;
  var messageQueue = this.getMessageQueue(packet.address);
  messageQueue.unshift(packet);
 
  this.startSendingProcess(queueAddress);
 
  return this.sequenceNumber;
};
 
/**
 * Get network address data from connection
 * @return {Object} Network address data
 */
Client.prototype.address = function () {
  var address = null;
  try {
    address = this.socket.address();
  } catch (e) {}
  return address;
};
 
/**
 * Sets debug on or off at runtime
 * @param  {Boolean} debug debug messages on
 */
Client.prototype.setDebug = function (debug) {
  if (typeof debug !== 'boolean') {
    throw new TypeError('LIFX Client setDebug expects boolean as parameter');
  }
  this.debug = debug;
};
 
/**
 * Adds a message handler that calls a function when the requested
 * info was received
 * @param {String} type A type of packet to listen for, like stateLight
 * @param {Function} callback the function to call if the packet was received,
 *                   this will be called with parameters msg and rinfo
 * @param {Number} [sequenceNumber] Expects a specific sequenceNumber on which will
 *                                  be called, this will call it only once. If not
 *                                  given the callback handler is permanent
 */
Client.prototype.addMessageHandler = function (type, callback, sequenceNumber) {
  if (typeof type !== 'string') {
    throw new TypeError('LIFX Client addMessageHandler expects type parameter to be string');
  }
  if (typeof callback !== 'function') {
    throw new TypeError('LIFX Client addMessageHandler expects callback parameter to be a function');
  }
 
  var typeName = find(Packet.typeList, { name: type });
  if (typeName === undefined) {
    throw new RangeError('LIFX Client addMessageHandler unknown packet type: ' + type);
  }
 
  var handler = {
    type: type,
    callback: callback.bind(this),
    timestamp: Date.now()
  };
 
  if (sequenceNumber !== undefined) {
    if (typeof sequenceNumber !== 'number') {
      throw new TypeError('LIFX Client addMessageHandler expects sequenceNumber to be a integer');
    } else {
      handler.sequenceNumber = sequenceNumber;
    }
  }
 
  this.messageHandlers.push(handler);
};
 
/**
 * Returns the list of all known lights
 * @example client.lights()
 * @param {String} [status='on'] Status to filter for, empty string for all
 * @return {Array} Lights
 */
Client.prototype.lights = function (status) {
  if (status === undefined) {
    status = 'on';
  } else if (typeof status !== 'string') {
    throw new TypeError('LIFX Client lights expects status to be a string');
  }
 
  if (status.length > 0) {
    if (status !== 'on' && status !== 'off') {
      throw new TypeError('Lifx Client lights expects status to be \'on\', \'off\' or \'\'');
    }
 
    var _result = [];
    forEach(this.devices, function (light) {
      if (light.status === status) {
        _result.push(light);
      }
    });
    return _result;
  }
 
  return this.devices;
};
 
/**
 * Find a light by label, id or ip
 * @param {String} identifier label, id or ip to search for
 * @return {Object|Boolean} the light object or false if not found
 */
Client.prototype.light = function (identifier) {
  var result = void 0;
  if (typeof identifier !== 'string') {
    throw new TypeError('LIFX Client light expects identifier for LIFX light to be a string');
  }
 
  // There is no ip or id longer than 45 chars, no label longer than 32 bit
  if (identifier.length > 45 && Buffer.byteLength(identifier, 'utf8') > 32) {
    return false;
  }
 
  // Dots or colons is high likely an ip
  if (identifier.indexOf('.') >= 0 || identifier.indexOf(':') >= 0) {
    result = find(this.devices, { address: identifier }) || false;
    if (result !== false) {
      return result;
    }
  }
 
  // Search id
  result = find(this.devices, { id: identifier }) || false;
  if (result !== false) {
    return result;
  }
 
  // Search label
  result = find(this.devices, { label: identifier }) || false;
 
  return result;
};
 
exports.Client = Client;