Example #1
0
HueApi.nupnpSearch(function(err, result) {
    if (err) throw err;

    if (result.length == 0)
    {
        console.log("No Hue bridges found");
        return;
    }

    if (result.length > 1)
    {
        console.log("Multiple bridges found. Select the bridge id that you want to use and enter it in the BridgeIdToUse configuration variable.");
        displayBridges(result);
        return;
    }

    var hostIp = result[0].ipaddress;
    
    api = new HueApi.HueApi(hostIp, Username);
    
    api.config(function(err, config) {
        if (err) throw err;

        if (config.ipaddress === undefined)
        {
            // User not registered
            registerUser(hostIp);
        }
        turnOnLights();
        HueInitialized = true;
    });

    
});
Example #2
0
    client.on('message', function (topic, message) {
        var topicParts = topic.match(topicRegex);
        if(topicParts == null) {
            // These are not the topics you are looking for
            return;
        }
        var identifier = topicParts[1];
        var property   = topicParts[2];
        var value      = message.toString();

        // Determine state change from MQTT topic
        var newState = state;
        if(property == 'state') {
            if(value == 'on' || value == '1') {
                newState = state.on();
            }
            if(value == 'off' || value == '0') {
                newState = state.off();
            }
        } else if(property == 'brightness') {
            newState = state.brightness(value);
        }

        var regexInteger = new RegExp('^\\d+$');
        if(identifier == "all") {
            // Group 0 is always all lights
            api.setGroupLightState(0, newState).done();
        } else if(regexInteger.test(identifier)) {
            api.setLightState(identifier, newState).done();
        }
    });
Example #3
0
Users.prototype.listUsers = function(){

  var self = this;

  if(!config.auth.hostname){
    console.error('✘ No hostname found in config. Run the init command first.');
    this.process.exit(1);
  }

  if(!config.auth.hash){
    console.error('✘ No hash found in config. Run the init command first.');
    this.process.exit(1);
  }

  var api = new hue.HueApi(config.auth.hostname, config.auth.hash);
  api.registeredUsers(function(err, users) {
    if(err){
      console.error(err);
      self.process.exit(1);
    }

    console.log(users);
    self.process.exit(0);
  });

};
        hue.locateBridges(function(err, result) {
            var msg = {};
            if (err) throw err;
            //check for found bridges
            if(result[0]!=null) {
                //save the IP address of the 1st bridge found
                this.gw_ipaddress = result[0].ipaddress;
                msg.payload = this.gw_ipaddress;

                //get light info:
                var api = new HueApi(this.gw_ipaddress, node.username);
                api.lights(function(err, lights) {
                    var msg2 = {};
                    if (err) throw err;
                    var lights_discovered = JSON.stringify(lights, null, 2);
                    msg2.topic = "Lights";
                    msg2.payload = lights_discovered;
                    node.send([msg, msg2]);

                });
            }
            else {
                //bridge not found:
                var msg = {};
                msg.payload = "Bridge not found!";
                node.send(msg);
            }

        });
Example #5
0
  function(){

    hue = new hue.HueApi();
    hue.createUser(bridge.ipaddress, null, null, function(err, user) {
      if(err){
        console.error(err);
        self.process.exit(1);
      }

      console.log('\nUser created: '+JSON.stringify(user));

      config.auth.hash = user;
      console.log('Writing to config...');

      fs.writeFile('./config.json', JSON.stringify(config, null, 2), function(err) {
        if(err){
          console.error(err);
          self.process.exit(1);
        }

        console.log('✔ User saved to config. You can now start using the CLI.');
        self.process.exit(0);
      });
    });

  });
Example #6
0
Users.prototype.rmUser = function(userHash){

  var self = this;

  if(!userHash){
    console.error('✘ Please specify a user hash/username.');
    this.process.exit(1);
  }

  if(!config.auth.hostname){
    console.error('✘ No hostname found in config. Run the init command first.');
    this.process.exit(1);
  }

  if(!config.auth.hash){
    console.error('✘ No hash found in config. Run the init command first.');
    this.process.exit(1);
  }

  var api = new hue.HueApi(config.auth.hostname, config.auth.hash);
  api.unregisterUser(userHash, function(err, success) {
    if(err){
      console.error(err);
      this.process.exit(1);
    }

    console.log('✔ User removed.');
    self.process.exit(0);
  });

};
Example #7
0
job(function(done) {
    var api = new HueApi(this.config.hue.hostname, this.config.hue.username);

    api.setLightState(this.config.hue.lightId, states.off);

    done();
}).at('45 8 * * *').defer();
Example #8
0
		var returnDevices=function(){
			var api=new hue.HueApi(ip,config[req.params.serverid]);
			api.getFullState(function(err, config) {
				if (err) throw err;
				res.end(JSON.stringify({lights:config.lights,groups:config.groups}));
			});	
		}
Example #9
0
setInterval(function () {
  
    //Checking for update in remote sensor values 
   if(jsonWeb[0].val1 !== lastValue[0] || jsonWeb[0].val2 !== lastValue[1]){
    //console.log("newStuff");
    update = true;

   }


   if(update){
      // Turn the light on only if outside light is less than 2000 Lumens
   		if(jsonWeb[0].val1 < 2000){
        //Brightness value from remote light sensor.
   			var britVal = map_range(1*jsonWeb[0].val1,0,2000,255,0);
        // Final brightness value after adding tuning from Serial controller
        britVal = britVal + brightTune;

        // Hue value from remote temperature sensor
        var hueVal = map_range(1*jsonWeb[0].val2,15,30,100,135);
        // Final Hue value after adding tuning from serial controller
        hueVal = hueVal + hueTune;

        // Set limits to values
        if (britVal>255) britVal = 255;
        if (britVal<0) britVal = 0;
        // Turn the lights on if OFF
   			if(off){
   				api.setGroupLightState(1, {"on": true}) // provide a value of false to turn off
      		.then(displayResult)
      		.fail(displayError)
      		.done();
      		off = false;	
   			}

      // Update the state of the lights  
    	api.setGroupLightState(1, {"bri": britVal , "hue": 255*hueVal, "sat":120}) // provide a value of false to turn off
      		.then(displayResult)
      		.fail(displayError)
      		.done();
    	
      update = false;
  		}else{
        // Turn off lights if ON (and outside lighting is >2000 Lumens)
  			if(!off){
  		api.setGroupLightState(1, {"on": false}) // provide a value of false to turn off
      		.then(displayResult)
      		.fail(displayError)
      		.done();
      		off = true;	
      	}

  		}
    }

  //  store last values for update checking
  lastValue[0] = jsonWeb[0].val1;
  lastValue[1] = jsonWeb[0].val2;
}, 1000);
Example #10
0
function sendBridgeDetails(connection, res) {
  const api = new hue.HueApi(connection.ip, connection.user);
  api.config().then((bridge) => {
    res.json({ connection, bridge });
  }).fail((err) => {
    res.status(400).json({ error: err, connection });
  }).done();
}
Example #11
0
job(function(done, cold) {
    var api = new HueApi(this.config.hue.hostname, this.config.hue.username);

    if (cold) {
        api.setLightState(this.config.hue.coldLightId, states.cold, done);
    } else {
        api.setLightState(this.config.hue.coldLightId, states.sunny, done);
    }
}).after('is cold?');
Example #12
0
job(function(done, rainy) {
    var api = new HueApi(this.config.hue.hostname, this.config.hue.username);

    if (rainy) {
        api.setLightState(this.config.hue.rainLightId, states.rainy, done);
    } else {
        api.setLightState(this.config.hue.rainLightId, states.sunny, done);
    }
}).after('will rain?');
Example #13
0
exports.connectBridge = function(models, req, res) {
    var user = req.user;
    var hue_user = user.hue_user;
    var hostname = req.params.hostname;
    var hue_api = new hue.HueApi();

    hue_api.registerUser(hostname, hue_user)
        .then(function(hue_res) {
            if (hue_res === hue_user) {
                var Bridge = models.Bridge;
                var handleErrors = function(err) {
                    console.error(err);
                    res.json(500, { message: 'Internal server error '});
                };

                Bridge.find({ limit: 1})
                    .then(function(bridge) {
                        if (bridge) {
                            console.info('Removing old bridge.');
                            return bridge.destroy();
                        }
                        return true;
                    }, handleErrors)
                    .then(function() {
                        return Bridge.create({
                            hostname: hostname
                        });
                    }, handleErrors)
                    .then(function(bridge) {
                        res.json({
                            message: 'Success!',
                            bridge: hostname,
                            user: user.hue_user
                        });
                    }, handleErrors);
            } else {
                res.json(200, {
                    code: 2,
                    message: 'Request rejected by bridge.'
                });
            }
        })
        .fail(function(err) {
            if (err.name === 'Api Error') {
                res.json(200, {
                    code: 1,
                    message: 'Press link button on bridge and try again.'
                });
            } else {
                console.error(err);
                res.json(500, { message: 'Internal server error' });
            }
        })
        .done();
};
Example #14
0
exports.setLightPowerState = function(lights,newState){
    lights = (lights instanceof Array) ? lights : [lights];
    var newPowerState = newState ? lightState.create().on() : lightState.create().off();
    for(var x = 0; x < lights.length; x++){
        api.setLightState(lights[0],newPowerState).done();
    }
}
Example #15
0
HueHubDriver.prototype.register = function(cb) {
  var self = this;
  var hue = new HueApi();
  hue.createUser(this.data.ipaddress, null, null, function(err, user) {
    if (err)
      return cb(err);

    self.data.user = user;
    self.data.registered = true;
    self.state = 'registered';
    self.hue = new HueApi(self.data.ipaddress, self.data.user);
    self.findLights(function(){
      cb(null);
    });
  });
};
Example #16
0
var getLights = function(ipaddr, userId, callback) {
    var api = new HueApi(ipaddr, userId);
	var lightAddresses = [];
    api.lights(function(err, result) {
        if (!!err)
            console.log("api.lights " + err);
        else {
            for (var light of result.lights) {
				var laddress = new LightAddress( light.uniqueid, ipaddr, userId);
                lightAddresses.push(laddress);
            }
			callback(lightAddresses);
            return;
        }
    });
};
Example #17
0
var updateLightsToAlbum = function () {
	if (currentlyNormalLights) {
		api.getFullState(function (err, config) {
			if (err) { console.log("ERROR: ", err); }
			originalLightStates = config.lights;
		});
		currentlyNormalLights = false;
	}
	applescript("getItunesCover.applescript", function () {
		sys("getDominantCoverColors.rb", function (colors) {

			var bestColor = colors.sort(function (a, b) {
				return getLumSatValue(b) - getLumSatValue(a);
			})[0];

			if (bestColor.min() > (bestColor.max() - 5) ) {
				console.log("BLACK+WHITE=GOLD");
				bestColor = [243, 166, 63];
			} else {
				console.log("best color: ", bestColor);
			}

			sys("rgb2hue.js '[" + bestColor + "]'")
		});
	});
}
Example #18
0
            rl.on('line', function(line) {
                var hueapi = new HueApi();
                hueapi.createUser(ipaddr, function(err, userId) {
                    if (err) {
						if (errorCallback) {
                           errorCallback('Create User Error', JSON.stringify(err));
                           return;
                        }
                    } else {
                        console.log("Created User: %s", userId);

                        // Step 3: get the lights attached to the Hue
                        getLights(ipaddr, userId, function(lights) {
					
                            if (!!lights && lights.length > 0) {
								var choices = lights.map(function(light) {
									return JSON.stringify(light);
                                });

                                // ask the user to select a light
                                inquirer.prompt([
                                    {
                                        type: "list",
                                        name: "selectedLight",
                                        message: "Which light do you want to onboard?",
                                        choices: choices
                                    }
                                ], function(answers) {
                                    // all done. Now we have all the parameters we needed.
                                    var selectedLight = JSON.parse(answers.selectedLight);

                                    if (successCallback) {
										successCallback(selectedLight.ipAddress, selectedLight.userId, selectedLight.uniqueId, 'All done. Happy coding!');
                                        return;
                                    }
                                });

                            } else {
                                if (errorCallback) {
                                    errorCallback('NotFound', 'No devices found.');
                                    return;
                                }
                            }
                        });
                    }
                });
            });
Example #19
0
File: hue.js Project: SBejga/hueper
var registerToBridge = function() {

    if(app.state.connect.hue && !app.state.connect.hueRegistered) {

        console.log('[hue] Registering new user on the Hue bridge');

        api = new hue.HueApi();

        api.createUser(host, null, null, function(err, user) {

            // registration error (link button not pressed)
            if(err) {
                console.log('[hue] Hue register error:', err);
                setTimeout(registerToBridge, 5000);
            }

            // registration successful
            else {
                console.log('[hue] Hue registration successful:', user);

                // first registration
                if(typeof(app.config.hueUser) === 'undefined') {
                    new Config({
                        name: 'hueUser',
                        value: user,
                        hidden: true
                    }).save();
                }
                else {
                    Config.update(
                        { name: 'hueUser' },
                        { value: user }
                    ).exec();
                }

                app.config.hueUser = user;
                app.state.connect.hueRegistered = true;

                connectToBridge();
            }

        });

    }

};
Example #20
0
	function off(){
		api.setLightState(lightid, {
			bri: 0,
			transitiontime: 0
		}, function (err, lights) {
			if (err) console.log(err);
		});
	}
Example #21
0
function turnOnLight(lightid){
	api.setLightState(lightid, {
		on: true,
		transitiontime: 0
	}, function (err, lights) {
		if (err) return console.log(err);
	});
}
Example #22
0
function stoplooping(callback){
	api.setLightState(1, {
		effect: 'none'
	}, function (err, lights) {
		if (err) console.log(err);
		if(callback) callback();
	});
}
Example #23
0
api.lights(function(err, result) {
    console.log("Get Light Status of all");
    for (var i = 0; i < result.lights.length; i++) {
        api.lightStatus(result.lights[i].id, function(err, result) {
            if (err) throw err;
        });
    }
});
Example #24
0
function off() {
  api.setGroupLightState(0, {
    "on":true,
    "bri": 255,
    "hue": 30000,
    "sat": 255,
    "transitiontime": 2
  });
}
Example #25
0
 // Connect to Hue
 function(callback){
   hueClient.connect()
   .then(function(result){
     devCaveOptions.hue = hueClient;
     log(null, 'Hue client connected');
     callback(null, result);
   })
   .done();
 },
Example #26
0
	// 2 helper functions:
	function bright(cb){
		api.setLightState(lightid, {
			"bri": 255,
			"transitiontime": 0
		}, function (err, lights) {
			if (err) console.log(err);
			if(cb) cb();
		});
	}
Example #27
0
function dimLight(lightid, callback){
	api.setLightState(lightid, {
		bri: 0,
		transitiontime: 0
	}, function (err, lights) {
		if (err) console.log(err);
		if(callback) callback();
	});
}
var displayBridges = function(bridge) {
  console.log("Hue Bridges Found: " + JSON.stringify(bridge));
  var host = bridge[0].ipaddress,
  username = "******",
  api = new HueApi(host, username);
  api.groups()
  .then(displayResults)
  .done();
  api.getGroup(0)
    .then(displayResults)
    .done();
    api.searchForNewLights()
    .then(displayResults)
    .done();
  api.newLights()
    .then(displayResults)
    .done();
};
Example #29
0
  setLightState: function(state){

    // Do not update the light if they are locked
    if(locked)return;

    locked = true;

    // Updating the lights based on the state passed in
    api.setLightState(1, state, function(){
      // Unlocking the lights after they have been set
      locked = false;
    });
    api.setLightState(2, state, function(){
      // Unlocking the lights after they have been set
      locked = false
    });

    console.log("setLightState");
  }
Example #30
0
	function on(){
		api.setLightState(lightid, {
			bri: 255,
			hue: 25717,
			sat: 254,
			transitiontime: 0
		}, function (err, lights) {
			if (err) console.log(err);
		});
	}