npmtest-homebridge-legacy-plugins (v0.0.1)

Code coverage report for node-npmtest-homebridge-legacy-plugins/node_modules/homebridge-legacy-plugins/platforms/Domoticz.js

Statements: 4.1% (5 / 122)      Branches: 0% (0 / 74)      Functions: 0% (0 / 23)      Lines: 4.2% (5 / 119)      Ignored: none     

All files » node-npmtest-homebridge-legacy-plugins/node_modules/homebridge-legacy-plugins/platforms/ » Domoticz.js
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                                                                                                        2     1                                 1                                             1                                                                                                                                                 1                                                                                                                                                                                                                                                                                                                                                                                                                                      
// Domoticz Platform Shim for HomeBridge
// Written by Joep Verhaeg (http://www.joepverhaeg.nl)
//
// Revisions:
//
// 12 June 2015 [GizMoCuz]
// - Added support for RGB lights
// - Added support for Scenes
// - Sorting device names
//
// 22 July 2015 [lukeredpath]
// - Added SSL and basic auth support
//
// 26 August 2015 [EddyK69]
// - Added parameter in config.json: 'loadscenes' for enabling/disabling loading scenes
// - Fixed issue with dimmer-range; was 0-100, should be 0-16
//
// 27 August 2015 [EddyK69]
// - Fixed issue that 'on/off'-type lights showed as dimmers in HomeKit. Checking now on SwitchType instead of HaveDimmer
// - Fixed issue that 'on-off'-type lights would not react on Siri 'Switch on/off light'; On/Off types are now handled as Lights instead of Switches
//   (Cannot determine if 'on/off'-type device is a Light or a Switch :( )
//
// 14 September 2015 [lukeredpath]
// - Fixed incorrect dimmer range for LightwaveRF lights (0-32 required, MaxDimLevel should be honored)
//
//
// Domoticz JSON API required
// https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Lights_and_switches
//
// Remember to add platform to config.json. Example:
// "platforms": [
//     {
//         "platform": "Domoticz",
//         "name": "Domoticz",
//         "server": "127.0.0.1",
//         "port": "8080",
//         "roomid": 123,  (0=no roomplan)
//         "loadscenes": 1 (0=disable scenes)
//     }
// ],
//
// If your server uses HTTPS, you can specify "ssl": true in your config. If
// your server uses a self-signed certificate, you'll need to run the following
// before starting the server or you will get an error:
//
//    export NODE_TLS_REJECT_UNAUTHORIZED=0
//
// For basic auth support, specify the "user" and "password" in your config.
//
// When you attempt to add a device, it will ask for a "PIN code".
// The default code for all HomeBridge accessories is 031-45-154.
//
var types = require("../api").homebridge.hapLegacyTypes;
var request = require("request");
 
function DomoticzPlatform(log, config){
	this.log     = log;
	this.user = config["user"];
	this.password = config["password"];
	this.server  = config["server"];
	this.port    = config["port"];
	this.protocol = config["ssl"] ? "https" : "http";
	this.roomid  = 0;
	if (typeof config["roomid"] != 'undefined') {
		this.roomid = config["roomid"];
	}
	this.loadscenes = 1;
	if (typeof config["loadscenes"] != 'undefined') {
		this.loadscenes = config["loadscenes"];
	}
}
 
function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}
 
DomoticzPlatform.prototype = {
  urlForQuery: function(query) {
    var serverString = this.server;
    if (this.user && this.password) {
      serverString = this.user + ":" + this.password + "@" + serverString;
    }
    return this.protocol + "://" + serverString + ":" + this.port + "/json.htm?" + query;
  },
  
	accessories: function(callback) {
		this.log("Fetching Domoticz lights and switches...");
		var that = this;
		var foundAccessories = [];
		
		// mechanism to ensure callback is only executed once all requests complete
		var asyncCalls = 0;
		function callbackLater() { if (--asyncCalls == 0) callback(foundAccessories); }
		
		if (this.roomid == 0) {
			//Get Lights
			asyncCalls++;
			request.get({
				url: this.urlForQuery("type=devices&filter=light&used=true&order=Name"),
				json: true
			}, function(err, response, json) {
				if (!err && response.statusCode == 200) {
					if (json['result'] != undefined) {
						var sArray=sortByKey(json['result'],"Name");
						sArray.map(function(s) {
							var havedimmer = (s.SwitchType == 'Dimmer')
							accessory = new DomoticzAccessory(that.log, that, false, s.idx, s.Name, havedimmer, s.MaxDimLevel, (s.SubType=="RGB")||(s.SubType=="RGBW"));
							foundAccessories.push(accessory);
						})
					}
					callbackLater();
				} else {
					that.log("There was a problem connecting to Domoticz. (" + err + ")");
				}
			});
		}
		else {
			//Get all devices specified in the room
			asyncCalls++;
			request.get({
				url: this.urlForQuery("type=devices&plan=" + this.roomid),
				json: true
			}, function(err, response, json) {
				if (!err && response.statusCode == 200) {
					if (json['result'] != undefined) {
						var sArray=sortByKey(json['result'],"Name");
						sArray.map(function(s) {
							//only accept switches for now
							if (typeof s.SwitchType != 'undefined') {
								var havedimmer = (s.SwitchType == 'Dimmer')
								accessory = new DomoticzAccessory(that.log, that, false, s.idx, s.Name, havedimmer, s.MaxDimLevel, (s.SubType=="RGB")||(s.SubType=="RGBW"));
								foundAccessories.push(accessory);
							}
						})
					}
					callbackLater();
				} else {
					that.log("There was a problem connecting to Domoticz.");
				}
			});
		}
		//Get Scenes
		if (this.loadscenes == 1) {
			asyncCalls++;
			request.get({
				url: this.urlForQuery("type=scenes"),
				json: true
			}, function(err, response, json) {
				if (!err && response.statusCode == 200) {
					if (json['result'] != undefined) {
						var sArray=sortByKey(json['result'],"Name");
						sArray.map(function(s) {
							accessory = new DomoticzAccessory(that.log, that, true, s.idx, s.Name, false, 0, false);
							foundAccessories.push(accessory);
						})
					}
					callbackLater();
				} else {
					that.log("There was a problem connecting to Domoticz.");
				}
			});
		}
	}
}
 
function DomoticzAccessory(log, platform, IsScene, idx, name, HaveDimmer, MaxDimLevel, HaveRGB) {
  // device info
  this.IsScene		= IsScene;
  this.idx			= idx;
  this.name			= name;
  this.HaveDimmer	= HaveDimmer;
  this.MaxDimLevel	= MaxDimLevel;
  this.HaveRGB		= HaveRGB;
  this.log 			= log;
  this.platform = platform;
}
 
DomoticzAccessory.prototype = {
	command: function(c,value) {
		this.log(this.name + " sending command " + c + " with value " + value);
		if (this.IsScene == false) {
			//Lights
			if (c == "On" || c == "Off") {
				url = this.platform.urlForQuery("type=command&param=switchlight&idx=" + this.idx + "&switchcmd=" + c + "&level=0");
			}
			else if (c == "setHue") {
				url = this.platform.urlForQuery("type=command&param=setcolbrightnessvalue&idx=" + this.idx + "&hue=" + value + "&brightness=100" + "&iswhite=false");
			}
			else if (c == "setLevel") {
                                value = this.dimmerLevelForValue(value)
				url = this.platform.urlForQuery("type=command&param=switchlight&idx=" + this.idx + "&switchcmd=Set%20Level&level=" + value);
			}
			else if (value != undefined) {
				this.log(this.name + " Unhandled Light command! cmd=" + c + ", value=" + value);
			}
		}
		else {
			//Scenes
			if (c == "On" || c == "Off") {
				url = this.platform.urlForQuery("type=command&param=switchscene&idx=" + this.idx + "&switchcmd=" + c);
			}
			else if (value != undefined) {
				this.log(this.name + " Unhandled Scene command! cmd=" + c + ", value=" + value);
			}
		}
 
    var that = this;
		request.put({ url: url }, function(err, response) {
			if (err) {
				that.log("There was a problem sending command " + c + " to" + that.name);
				that.log(url);
			} else {
				that.log(that.name + " sent command " + c + " (value: " + value + ")");
      		}
      	})
  	},
 
  // translates the HomeKit dim level as a percentage to whatever scale the device requires
  dimmerLevelForValue: function(value) {
    if (this.MaxDimLevel == 100) {
      return value;
    }
    return Math.round((value / 100.0) * this.MaxDimLevel) 
  },
 
  informationCharacteristics: function() {
    return [
      {
        cType: types.NAME_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: this.name,
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Name of the accessory",
        designedMaxLength: 255
      },{
        cType: types.MANUFACTURER_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "Domoticz",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Manufacturer",
        designedMaxLength: 255
      },{
        cType: types.MODEL_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "Rev-1",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Model",
        designedMaxLength: 255
      },{
        cType: types.SERIAL_NUMBER_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "A1S2NASF88EW",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "SN",
        designedMaxLength: 255
      },{
        cType: types.IDENTIFY_CTYPE,
        onUpdate: null,
        perms: ["pw"],
        format: "bool",
        initialValue: false,
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Identify Accessory",
        designedMaxLength: 1
      }
    ]
  },
 
  controlCharacteristics: function(that) {
    cTypes = [{
      cType: types.NAME_CTYPE,
      onUpdate: null,
      perms: ["pr"],
      format: "string",
      initialValue: this.name,
      supportEvents: true,
      supportBonjour: false,
      manfDescription: "Name of service",
      designedMaxLength: 255
    }]
 
    if (this.idx != undefined) {
      cTypes.push({
        cType: types.POWER_STATE_CTYPE,
        onUpdate: function(value) {
          if (value == 0) {
            that.command("Off")
          } else {
            that.command("On")
          }
        },
        perms: ["pw","pr","ev"],
        format: "bool",
        initialValue: 0,
        supportEvents: true,
        supportBonjour: false,
        manfDescription: "Change the power state",
        designedMaxLength: 1
      })
    }
 
    if (this.HaveDimmer == true) {
      cTypes.push({
        cType: types.BRIGHTNESS_CTYPE,
        onUpdate: function(value) { that.command("setLevel", value); },
        perms: ["pw","pr","ev"],
        format: "int",
        initialValue:  0,
        supportEvents: true,
        supportBonjour: false,
        manfDescription: "Adjust Brightness of Light",
        designedMinValue: 0,
        designedMaxValue: this.MaxDimLevel,
        designedMinStep: 1,
        unit: "%"
      })
    }
    if (this.HaveRGB == true) {
      cTypes.push({
        cType: types.HUE_CTYPE,
        onUpdate: function(value) { that.command("setHue", value); },
        perms: ["pw","pr","ev"],
        format: "int",
        initialValue:  0,
        supportEvents: true,
        supportBonjour: false,
        manfDescription: "Adjust Hue of Light",
        designedMinValue: 0,
        designedMaxValue: 360,
        designedMinStep: 1,
        unit: "arcdegrees"
      })
    }
 
    return cTypes
  },
 
  sType: function() {
    //if (this.HaveDimmer == true) {
      return types.LIGHTBULB_STYPE
    //} else {
    //  return types.SWITCH_STYPE
    //}
  },
 
  getServices: function() {
    var that = this;
    var services = [{
      sType: types.ACCESSORY_INFORMATION_STYPE,
      characteristics: this.informationCharacteristics(),
    },
    {
      sType: this.sType(),
      characteristics: this.controlCharacteristics(that)
    }];
    this.log("Loaded services for " + this.name)
    return services;
  }
};
 
module.exports.accessory = DomoticzAccessory;
module.exports.platform = DomoticzPlatform;