Control Lights With Code

Home Automation has been trending for years. I've had my Philips Hue Smart Lights for several years now and I've wonder how they function and if it's possible for me to change the color or brightness via code. Turns out, it is possible. Philips have a public API for their lights. In this blog, I will be using a client (Huejay to be specific) that uses Philips Hue API.

API: aka Application Programming Interface. It allow applications to communicate with each other. In this case, It serves as intermediary between the software on the Hue Bridge and the software we are going to create.

Client: Software that accesses a service. In this case, Huejay accesses Philips's API service.

1. INSTALL NODE.JS

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. What does that mean? Well, instead of running JavaScript in the browser, you just run it via command line. NPM comes with the installation of Node. It is a package manager (Node Package Manager) that allows you to install dependencies for your project.

Link to Node.js

2. CREATE A PROJECT

Create a project from the command line. Open Git Bash (Windows) or Terminal (MacOS). Run the first four commands and go through the prompts.

You can use Command Prompt that comes with Windows. I personally like to use Git Bash

Link to Git Bash for Windows

$ mkdir new-project
$ cd new-project
$ touch index.js
$ npm init

3. INSTALL DEPENDENCIES

We will be installing a loadable JavaScript package and use it in our code to communicate with Phillips Hue Lights. The name of the package is “huejay“. Some projects have libraries and source code from other projects (doesn’t have to be theirs) and without it, their code will NOT work. In this case, huejay package is a dependency of our project.

$ npm install huejay

4. OPEN PROJECT IN CODE EDITOR

I prefer Visual Studio Code, but feel free to use what you like. After opening the project, open index.js. Insert the following code.

let huejay = require('huejay'); // import huejay package we installed

// looks for hue bridge & return info such as IP Address. 
// Need info to communicate with lights
huejay.discover().then(bridges => {
  for (let bridge of bridges) {
    console.log(`Id: ${bridge.id}, IP: ${bridge.ip}`);
  }
}).catch(error => {
  console.log(`An error occurred: ${error.message}`);
});

5. KEEP CODING

First, run the project to get the IP Address of Hue Bridge.

$ node .

Copy the IP Address. Next we will create a user, but first we must instantiate a client.

let client = new huejay.Client({
    host: "<HUE-BRIDGE-IP-ADDRESS-HERE>",
    username: "<USERNAME-HERE>",
});

let user = new client.users.User;

// Optionally configure a device type / agent on the user
user.deviceType = 'my_device_type'; // Default is 'huejay'

client.users.create(user)
  .then(user => {
    console.log(`New user created - Username: ${user.username}`);
  })
  .catch(error => {
    if (error instanceof huejay.Error && error.type === 101) {
      return console.log(`Link button not pressed. Try again...`);
    }
    console.log(error.stack);
  });

After getting the IP Address and creating a user, Run the code below and run to turn on all of your lights.

let client = new huejay.Client({
    host: "<HUE-BRIDGE-IP-ADDRESS-HERE>",
    username: "<USERNAME-HERE>",
});

// let user = new client.users.User;

// Optionally configure a device type / agent on the user
// user.deviceType = 'my_device_type'; // Default is 'huejay'

// client.users.create(user)
//   .then(user => {
//     console.log(`New user created - Username: ${user.username}`);
//   })
//   .catch(error => {
//     if (error instanceof huejay.Error && error.type === 101) {
//       return console.log(`Link button not pressed. Try again...`);
//     }
//     console.log(error.stack);
//   });

client.lights.getAll().then(lights => {
    for (let light of lights) {
        console.log(`Light [${light.id}]: ${light.name}`);
        console.log(`  Type:             ${light.type}`);
        console.log('  State:');
        console.log(`    On:         ${light.on}`);
        console.log(`    Reachable:  ${light.reachable}`);
        console.log(`    Brightness: ${light.brightness}`);

        // turn light on to highest brightness
        light.on = true 
        light.brightness =  254;
        client.lights.save(light);
    }
});

Refer to Huejay's Documentation to see what other things you can do with the client.

QUESTIONS FOR YOU

What brand of smart lights do you have?

What color do you usually change the light to?