all files / Insteon/ X10.js

96.97% Statements 32/33
100% Branches 0/0
83.33% Functions 5/6
96.97% Lines 32/33
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                                                                              
var Q = require('q');
var utils = require('./utils');
var debug = require('debug')('home-controller:insteon:x10');
var toByte = utils.toByte;
 
 
var CODES = [0x6, 0xE, 0x2, 0xA, 0x1, 0x9, 0x5, 0xD, 0x7, 0xF, 0x3, 0xB, 0x0, 0x8, 0x4, 0xC];
var ON_CODE = 0x2;
var OFF_CODE = 0x3;
 
 
function X10(id, insteon) {
  this.id = id;
  this.house = id.substring(0,1);
  this.unit = id.substring(1);
 
  var houseCodeIndex = this.house.toUpperCase().charCodeAt(0) - 'A'.charCodeAt(0);
  var unitCodeIndex = parseInt(this.unit) - 1;
 
  this.houseCode = CODES[houseCodeIndex] << 4;
  this.unitCode = CODES[unitCodeIndex];
 
  this.unitCmd = {
    exitOnAck: true,
    raw: '0263' + toByte(this.houseCode + this.unitCode) + '00',
    id: this.id
  };
 
  this.insteon = insteon;
}
X10.prototype.turnOn = function (next) {
  return this.send(ON_CODE, next);
};
 
X10.prototype.turnOff = function (next) {
  return this.send(OFF_CODE, next);
};
 
X10.prototype.send = function(code, next) {
  var insteon = this.insteon;
 
  var cmd = {
    exitOnAck: true,
    raw: '0263' + toByte(this.houseCode + code) + '80',
    id: this.id
  };
 
  debug('sending x10 unit', this.unitCmd);
 
  var deferred = Q.defer();
  deferred.resolve(
    insteon.sendCommand(this.unitCmd)
    .delay(500)
    .then(function () {
      debug('sending x10 cmd', cmd);
      return insteon.sendCommand(cmd);
    })
  );
 
  return deferred.promise.nodeify(next);
};
 
 
 
 
X10.prototype.cancelPending = function() {
  this.insteon.cancelPending(this.id);
};
 
 
module.exports = X10;