Giter Site home page Giter Site logo

peter-murray / node-hue-api Goto Github PK

View Code? Open in Web Editor NEW
1.2K 40.0 144.0 1.53 MB

Node.js Library for interacting with the Philips Hue Bridge and Lights

License: Apache License 2.0

JavaScript 40.59% TypeScript 59.41%
hue-bridge hue-api hue-lights javascript nodejs scene schedule hue lights smarthome

node-hue-api's Introduction

node-hue-api

npm

An API library for Node.js that interacts with the Philips Hue Bridge to control Lights, schedules, sensors and the various other features of the Hue Bridge.

This library abstracts away the actual Philips Hue Bridge REST API and provides all of the features of the Philips API and a number of useful functions to control/configure its various features.

The library fully supports local network and remote internet access to the Hue Bridge API and has 100% coverage of the documented Hue API.

Contents

Change Log

For a list of changes, and details of the fixes/improvements, bugs resolved, please refer to the change log; Change Log

Installation

Node.js using npm:

$ npm install node-hue-api

Node.js using yarn:

$ yarn add node-hue-api

v3 API

The V3 API is written to support JavaScript native Promises, as such you can use standard Promise chaining with then() and catch() or utilize synchronous async and await in your own code base.

As of release 4.0.0 in December 2019, the library now has complete coverage for the Hue REST API.

Connections to the Bridge

By default all connections to the Hue Bridge are done over TLS, after the negotiation of the Bridge certificate being verified to the expected format and subject contents.

The Bridge certificate is self-signed, so this will cause issues when validating it normally. The library will process the certificate, validate the issuer and the subject and if happy will then allow the connection over TLS with the Hue Bridge.

When using the remote API functionality of the library, the certificate is validated normally as the https://api.meethue.com site has an externally valid certificate and CA chain.

Note: There is an option to connect over HTTP using createInsecureLocal() as there are some instances of use of the library against software the pretends to be a Hue Bridge. Using this method to connect will output warnings on the console that you are connecting in an insecure way.

Rate Limiting

As of version 4.0+ of the library there are Rate limiters being used in three places:

  • For the whole library, API calls are limited to 12 per second
  • For lights.setLightState(), API calls are limited to 10 per second
  • For groups.setState(), API calls are limited to 1 per second

These defaults are not currently configurable, but have been implemented to conform to the best practices defined in the Hue API documentation. If you are facing issues with this, then raise a support ticket via an Issue.

Note: these do NOT (and cannot) take into account all access to the Hue Bridge, so if you have other softare that also accesses the bridge, it is still possible to overload it with requests.

Debug Bridge Communications

You can put the library in to debug mode which will print out the placeholder and request details that it is using to talk to the Hue Bridge.

To do this, you need to define an environment variable of NODE_DEBUG and ensure that it is set to a string that contains node-hue-api in it.

Once the debug mode is active you will see output like the following on the console:

Bridge Certificate:
  subject:       {"C":"NL","O":"Philips Hue","CN":"xxxxxxxxx"}
  issuer:        {"C":"NL","O":"Philips Hue","CN":"xxxxxxxxx"}
  valid from:    Jan  1 00:00:00 2017 GMT
  valid to:      Jan  1 00:00:00 2038 GMT
  serial number: xxxxxxx

Performing validation of bridgeId "xxx" against certifcate subject "xxx"; matched? true
URL Placeholders:
  username: { type:string, optional:false, defaultValue:null }
Headers: {"Accept":"application/json"}
{
  "method": "get",
  "baseURL": "https://192.xxx.xxx.xxx:443/api",
  "url": "/xxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
URL Placeholders:
  username: { type:string, optional:false, defaultValue:null }
Headers: {"Accept":"application/json","Content-Type":"application/json"}
{
  "method": "post",
  "baseURL": "https://192.xxx.xxx.xxx:443/api",
  "url": "/xxxxxxxxxxxxxxxxxxxxxxxx/schedules",
  "data": {
    "name": "Test Schedule Recurring",
    "description": "A node-hue-api test schedule that can be removed",
    "command": {
      "address": "/api/xxxxxxxxxxxxxxxxxxxxxxxxxx/lights/0/state",
      "method": "PUT",
      "body": {
        "on": true
      }
    },
    "localtime": "W124/T12:00:00",
    "status": "enabled",
    "recycle": true
  }
}

Note: You should be careful as to who can gain access to this output as it will contain sensative data including the MAC Address of the bridge, IP Address and username values.

The above warning applies here with respect to schedule when not in debug mode, as the schedule endpoints will contain the username value (that can be used to authenticate against the bridge) in the payloads of the command.

v2 API Compatibility

In the version 4.x releases of this library all backwards compatibility to the much older Q promise and callback functionality was removed (as was indicated in the 3.x documentation).

What was provided in the 3.x versions of this library to provide some backward comaptibility has now been moved into another library node-hue-api-v2-shim.

The node-hue-api-v2-shim is only provided to allow you to continue to use the older v2 API functionality in code you may have had previously written and there are downsides to using it. You are strongly encouraged to migrate to the v3 API provided in this library (which is where any new features and improvements will be made going forward).

API Documentation

Examples

The v3 APIs are documented using example code and links to more complex/complete examples for each API calls, consult the documentation links above.

Alternatively take a look at the examples directory in this repository for complete self contained runnable example code.


Discover and connect to the Hue Bridge for the first time

For getting started interacting with the Hue Bridge, you will need to discover and then connect to the Hue Bridge as an authorized user. To do this you need to either know the IP Address of the Hue Bridge in advance, or use the discovery features to locate it.

Once you know the IP Address of the Bridge, you need to create a user that is authorized to interact with the Hue Bridge, this is typically done by pressing the Link button on the bridge and then attempting to register a new user via code.

Below is example code that can be used to achieve this (using async/await to avoid nested Promises):

const v3 = require('node-hue-api').v3
  , discovery = v3.discovery
  , hueApi = v3.api 
;

const appName = 'node-hue-api';
const deviceName = 'example-code';

async function discoverBridge() {
  const discoveryResults = await discovery.nupnpSearch();

  if (discoveryResults.length === 0) {
    console.error('Failed to resolve any Hue Bridges');
    return null;
  } else {
    // Ignoring that you could have more than one Hue Bridge on a network as this is unlikely in 99.9% of users situations
    return discoveryResults[0].ipaddress;
  }
}

async function discoverAndCreateUser() {
  const ipAddress = await discoverBridge();

  // Create an unauthenticated instance of the Hue API so that we can create a new user
  const unauthenticatedApi = await hueApi.createLocal(ipAddress).connect();
  
  let createdUser;
  try {
    createdUser = await unauthenticatedApi.users.createUser(appName, deviceName);
    console.log('*******************************************************************************\n');
    console.log('User has been created on the Hue Bridge. The following username can be used to\n' +
                'authenticate with the Bridge and provide full local access to the Hue Bridge.\n' +
                'YOU SHOULD TREAT THIS LIKE A PASSWORD\n');
    console.log(`Hue Bridge User: ${createdUser.username}`);
    console.log(`Hue Bridge User Client Key: ${createdUser.clientkey}`);
    console.log('*******************************************************************************\n');

    // Create a new API instance that is authenticated with the new user we created
    const authenticatedApi = await hueApi.createLocal(ipAddress).connect(createdUser.username);

    // Do something with the authenticated user/api
    const bridgeConfig = await authenticatedApi.configuration.getConfiguration();
    console.log(`Connected to Hue Bridge: ${bridgeConfig.name} :: ${bridgeConfig.ipaddress}`);

  } catch(err) {
    if (err.getHueErrorType() === 101) {
      console.error('The Link button on the bridge was not pressed. Please press the Link button and try again.');
    } else {
      console.error(`Unexpected Error: ${err.message}`);
    }
  }
}

// Invoke the discovery and create user code
discoverAndCreateUser();

The complete code sample above is available from here.

For more details on discovery of Hue Bridges, check out the discovery API and referenced examples along with the users API.


Set a Light State on a Light

Once you have created your user account and know the IP Address of the Hue Bridge you can interact with things on it. To interact with light on the Hue Bridge you can use the following:

const v3 = require('node-hue-api').v3;
const LightState = v3.lightStates.LightState;

const USERNAME = 'your username to authenticating with the bridge'
  // The name of the light we wish to retrieve by name
  , LIGHT_ID = 1
;

v3.discovery.nupnpSearch()
  .then(searchResults => {
    const host = searchResults[0].ipaddress;
    return v3.api.createLocal(host).connect(USERNAME);
  })
  .then(api => {
    // Using a LightState object to build the desired state
    const state = new LightState()
      .on()
      .ct(200)
      .brightness(100)
    ;
    
    return api.lights.setLightState(LIGHT_ID, state);
  })
  .then(result => {
    console.log(`Light state change was successful? ${result}`);
  })
;

For more details on interacting with lights, see the lights API and LightState documentation and examples referenced within.

Using Hue Remote API

This library has support for interacting with the Hue Remote API as well as local network connections. There are some limitations on the remote endpoints, but the majority of them will function as they would on a local network.

It can be rather involved to set up a remote connection, but not too onerous if you desire such a thing.

The complete documentation for doing this is detailed in the Remote API and associated links.

Philips Hue Resources

There are a number of resources where users have detailed documentation on the Philips Hue Bridge;

License

Copyright 2013-2019. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this library except in compliance with the License.

You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

node-hue-api's People

Contributors

abwaters avatar asifrc avatar bitdeli-chef avatar bschlief avatar connor-knabe avatar ctobolski avatar dpogni avatar fernandox7 avatar hildjj avatar ilari-makimattila avatar jmshal avatar johanb avatar knisterpeter avatar mwittig avatar nrcrast avatar osirisoft-pmurray avatar peter-murray avatar sbejga avatar starak avatar stephenyeargin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-hue-api's Issues

Missleading error Message

I created a LightState for a single lamp using an invalid id (for example 0 instead of 1). The error message is a bit missleading, here's the stack trace:

   "error":"Cannot call method 'hasRGB' of undefined",
   "stack":"TypeError: Cannot call method 'hasRGB' of undefined\n    at HueApi._getLightStateOptions (
   /a-project/node_modules/node-hue-api/hue-api/index.js:996:15)\n    at HueApi.setLightState (
   /a-project/node_modules/node-hue-api/hue-api/index.js:322:24)\n    at Object.exports.lampDim (

Get the light types to handle Lux lights

I'm just starting to play around with this API (thanks a lot for writing this), at the moment getting the lights, I'm not receiving any info on the type of lights, is this something I'm doing wrong?

hueApi.lights()
    .then(function(result) {
      this.log('Lights = ' + JSON.stringify(result));
      cb(null, result);
    }.bind(this))
    .fail(function(err) {
      this.log('getLights error: ', err);
      cb(err);
    }.bind(this))
    .done();

Code looks like this, so is just the example from the readme.

The only reason I'd like this info is that Lux lamps look like they may only like having a brightness state applied to them.

options.timeout in httpPromise.js

httpPromise.js contains the following line for setting a HTTP request timeout:
options.timeout = 10000; //TODO make adjustable

I am using your library with Node-RED and under certain conditions the Hue hub is unable to answer in under 10 sec. This causes the whole Node-RED server to crash since the thrown TIMEOUT exception is not catched. For now I have commented out this line and have no issues anymore.
Hence I would make this setting strongly optional.

Support for the scenes API

First of all. Thanks for a great project! Great functionality that really made the work with implementing the hue lights into my home automation system quite fun!

Now I am trying to unleash the creativity of my family when it comes to setting the lights to nice colors and combinations. For that I would like to use the scenes API which is not yet supported by your API.

Instead of doing a my own wrapper I have tried to enhance your API, I am about to create a pull request with those changes.

Thanks again for your work with this!

Group RGB support

Hi Peter - I see you've started implementing this, but there's a chunk commented out.
If you can quickly help me understand:

  1. What the complexity is with RGB specifically wrt groups
  2. The way you'd planned on tackling it

...I'll see if I can get it finished off this weekend, and can send you a PR?

Request "self.req.abort is not a function"

I'm running into an issue when using node-hue-api from within Electron. It seems that every function I run (e.g. api.config(), or api.registerUser()) returns the following error:

Uncaught TypeError: self.req.abort is not a function

The error is thrown from node_modules/request/request.js:1340 and I'm not running into this issue when going to the project in Chrome via Browsersync.

I'm running the latest version of node-hue-api (1.2.1), and I'm using Electron v0.35.4.

Any ideas on what's causing this and how to fix it?

Api Error: body contains invalid json

Thanks for sharing such a great project! It seems to be very well written and well documented.

However I'm having a bit of trouble running some basic functions such as registerUser() and setLightState(). It constantly throws a Api Error: body contains invalid json error. I have however been successful in running functions like connect() and deleteUser().

I'm running on a Windows 8.1 environment, with node version 0.10.35 and bridge swversion 01018228.

Respect location ssdp header

I'm writing a proxy for my hue bridge that augments it with a new non-hue networked lights - when doing discovery of hue bridges, they respond with a location header which is a URL to a description document. That document contains useful information like bridge serial number and the URLBase property.

Right now node-hue-api does a ssdp search for bridges, then requests /description.xml from port 80 of the hosts that respond to the search in order to get the bridge id - this happens to follow the hue implementation but doesn't seems to be in the spirit of the protocol - it should follow the location header instead.

So, for example, the ssdp search node-hue-api generates is:

M-SEARCH * HTTP/1.1
HOST: 239.255.255.250:1900
MAN: ssdp:discover
MX: 10
ST: urn:schemas-upnp-org:device:Basic:1

The response is then:

HTTP/1.1 200 OK
ST: urn:schemas-upnp-org:device:Basic:1
USN: uuid:07a50742-5a89-4b27-9a9e-374df1191a61::urn:schemas-upnp-org:device:Basic:1
LOCATION: http://192.168.1.67:64764
CACHE-CONTROL: max-age=100
DATE: Sat, 18 Jul 2015 11:43:43 GMT
SERVER: FreeRTOS/7.4.2 UPnP/1.0 IpBridge/1.8.0
EXT: 

The next request from node-hue-api should be to http://192.168.1.67:64764, instead it's to http://192.168.1.67/description.xml

I think this is because when makes the request to the host and then has the path to /description.xml hard coded.

As a shameless plug I've written an ssdp implementation that automagically goes off, fetches and parses the contents of the location header for you - might solve the problem..

API error crash

Hello,

Every now and then I get this error:
Api Error: parameter, xy, is not modifiable. Device is set to off.

I'm not sure what is causing it, as it seems to be random. One thought is I'm calling the API too quickly, but if I do the calls quickly on purpose it doesn't always crash.

transistiontime should be transitiontime

Hi,

We noticed that the transitiontime did not work.
You misspelled it in hue-api/commands/traits/tLightStateBody.js

I also wondered why you don't just pass the json directly to the Hue Bridge?

registerUser() triggers ApiError "link button not pressed" immediately

The following code triggers the .fail() callback immediately:

var hue = require("node-hue-api");
var api = new hue.HueApi();

// ip = '192.168.2.1'
api.registerUser(ip, null, null).then(function(result) {
    d.resolve();
    console.log('registerUser result:', result);
}).fail(function(result) {
    d.reject('button not pressed');
    console.error('registerUser error:', result);
}).done();

Which results in an immediate ApiError {message: "link button not pressed", type: 101} in my console. I'm still working on the same project as described in #51, so maybe gulp-browserify is messing something up again?

Any ideas on how to solve this?

Changes to Whitelist username creation

Hi Peter,

I work for Philips Hue Developer Support. In case you were not aware, in a few months time we will be changing the way usernames are created on the bridge (for security reasons). Custom whitelist usernames will no longer be allowed and the bridge randomly generated username must be used instead. Please see below link for more information:
http://www.developers.meethue.com/documentation/important-whitelist-changes

I had a quick look at your code and it looks like you are POSTng the "username" (index.js line 1124 in _setCreateUserOptions method). This will start failing around February 2016 so it should be removed. Looking at your description on your project page (Registering without an existing Device ID/User ID section) it appears you already have the code to using the Bridge Randomly generated username, so hopefully it should be a simple case of just removing the option to generate custom usernames. Apologies for the inconvenience.

Thanks
Steve

https://www.meethue.com/api/nupnp is now HTTPS

It looks like the https://www.meethue.com/api/nupnp endpoint has now changed to require https - requests to http://www.meethue.com/api/nupnp get redirected - this causes an error when attempting to use node-hue-api.locateBridges:

/path/node_modules/node-hue-api/node_modules/q/q.js:126
throw e;
^
Api Error: Unexpected response status; 302
at _checkResponse (/path/node_modules/node-hue-api/hue-api/httpPromise.js:93:15)
at _fulfilled (/path/node_modules/node-hue-api/node_modules/q/q.js:798:54)
at self.promiseDispatch.done (/path/node_modules/node-hue-api/node_modules/q/q.js:827:30)
at Promise.promise.promiseDispatch (/path/node_modules/node-hue-api/node_modules/q/q.js:760:13)
at /path/node_modules/node-hue-api/node_modules/q/q.js:574:44
at flush (/path/node_modules/node-hue-api/node_modules/q/q.js:108:17)
at process._tickCallback (node.js:415:13)

upnpSearch

When performing some sequential upnpSearch (e.g. to force reconnection upon link going down), node.js EventEmitter gives up since it reaches the maxListeners limit.

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
    at process.addListener (events.js:160:15)
    at process.on.process.addListener (node.js:796:26)
    at new SSDPSearch (/.../node_modules/node-hue-api/hue-api/search.js:57:14)
    at Object.locateBridges (/.../node_modules/node-hue-api/hue-api/search.js:15:18)
    at Object.module.exports.networkSearch [as upnpSearch] (/.../node_modules/node-hue-api/hue-api/bridge-discovery.js:20:19)
    at Firefly.searchForBridge (/.../backend/server/firefly.js:15:13)
    at /.../backend/server/firefly.js:18:22
    at _fulfilled (/.../node_modules/node-hue-api/node_modules/q/q.js:787:54)
    at self.promiseDispatch.done (/.../node_modules/node-hue-api/node_modules/q/q.js:816:30)
    at Promise.promise.promiseDispatch (/.../node_modules/node-hue-api/node_modules/q/q.js:749:13)
    at /.../node_modules/node-hue-api/node_modules/q/q.js:509:49
    at flush (/.../node_modules/node-hue-api/node_modules/q/q.js:108:17)
    at process._tickCallback (node.js:442:13)

Does creating / activating scenes work?

I'm trying to store and recall scenes. The scenes are created with the correct lamp selection on the bridge, but when I call api.activateScene using the scene id, the lamps do not respond.

Unfortunately I cannot verify the light states that are stored for each scene, only the lamp set that makes up the scene.

This is my code. It shows each scene once (because the first time the light states are set separately using setLightState instead of using the scene mechanism). After that the scenes mechanism (api.createScene, api.activateScene) should take over, but the lamps do not change according to the called scenes.

index.js:

var hue = require("node-hue-api"),
    HueApi = hue.HueApi,
    lightState = hue.lightState;

var displayResult = function (result) {
    console.log(JSON.stringify(result, null, 2));
};
var displayError = function (err) {
    console.log(JSON.stringify(err, null, 2));
};

var hostname = "xxx.xxx.xxx.xxx",
    username = "someusername",
    api;
api = new HueApi(hostname, username);

//load initial config from json
var sceneConfig = require('./scenes.json');

//set the lightstate for each light separately when they're not stored as a scene yet
var setStates = function (lightStates, callback) {
    var todo = Object.keys(lightStates).length;
    console.log(todo);

    //safety function to make sure all states are set before saving to scene
    var lightDone = function () {
        todo--;
        console.log(todo);
        if (todo === 0) {
            callback();
        }
    };

    for (var lightId in lightStates) {
        api.setLightState(lightId, lightStates[lightId])
            .then(lightDone)
            .fail(displayError)
            .done();
    }
};

//activate a scene from the scene config. if it has no Hue scene id yet,
//set the states separately and store them as a Hue scene
var activateScene = function (sceneName) {
    var scene = sceneConfig[sceneName];
    if (scene !== null) {
        if (scene.id !== undefined) {
            console.log('using predefined scene id ' + scene.id);

            api.activateScene(scene.id)
                .then('predefined scene result: ' + console.log)
                .done();
        } else if (scene.states !== undefined) {
            setStates(scene.states, function () {
                var lightIds = Object.keys(scene.states);
                api.createScene(lightIds, '', function (err, result) {
                    if (err) throw err;

                    //store the created scene id in the scenes config object
                    scene.id = result.id;
                    sceneConfig[sceneName] = scene;
                    console.log('scene created.');
                    console.log(result);
                });
            });
        }
    }
};

//switch between scenes every 4 seconds
var switchBool = true;
setInterval(function () {
    var sceneToActivate = switchBool ? 'gold' : 'sleep';
    activateScene(sceneToActivate);
    switchBool = !switchBool;
}, 4000);

scenes.json:

{
    "gold": {
        "states": {
            "4": {
                "on": true,
                "bri": 123,
                "hue": 14582,
                "sat": 251
            },
            "5": {
                "on": true,
                "bri": 123,
                "hue": 14582,
                "sat": 251
            },
            "6": {
                "on": true,
                "bri": 123,
                "hue": 14582,
                "sat": 251
            }
        }
    },
    "sleep": {
        "states": {
            "1": {
                "on": false
            },
            "2": {
                "on": true,
                "bri": 254
            },
            "3": {
                "on": true,
                "bri": 123,
                "hue": 14582,
                "sat": 251
            },
            "4": {
                "on": false
            },
            "5": {
                "on": false
            },
            "6": {
                "on": false
            }
        }
    }
}

Can't connect to my Bridge, both nupnpSearch and upnpSearch return (different) errors

When I run this code:

var hue = require("node-hue-api"),
    timeout = 200;

var displayBridges = function(bridge) {
    console.log("Hue Bridges Found: " + JSON.stringify(bridge));
};

hue.nupnpSearch().then(displayBridges).done();
hue.upnpSearch(timeout).then(displayBridges).done();

I get the following errors for the nupnpSearch:

XMLHttpRequest cannot load https://www.meethue.com/api/nupnp. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access.
Uncaught TypeError: Cannot convert undefined or null to object
Uncaught Error: Network error

and these for the upnpSearch:

Uncaught TypeError: dgram.createSocket is not a function

But when I go to https://www.meethue.com/api/nupnp in my browser I get a JSON object containing an id and an internalipaddress, which seems right as http://192.168.2.2/ shows a Philips Hue page on my network...

I'm using this in an Angular project (although it results in the same errors when I completely remove Angular) in combination with Browserify on a XAMPP stack.

Any ideas on what's causing these erros and how to get either (or both, preferably) of these working on my end?

Version information
node-hue-api: 1.0.5
Hue Bridge: latest I guess, I can't update it

Chai problem, cant find module

Hi
Thanks for the great work
I have a problem
If i run bridge-connect i get an Chai error

Module.js 340 throw error
Cannot find module 'chai'
At function module _resolvefilename (module.js 338:15)
At function module _load (module.js 280:15)
Etc.

Hope you can give a hint
Thanks
pieter

group 0 does return lights

The readme says:

The "Lightset 0" Group is a special instance and will always exist and have the id of "0" as specified in the Hue Api documentation. Due to this internal group being maintained by the bridge internally, it will not return an array of light ids like any of the other types of Groups.

However, on my hue bridge, when I issue a GET request for /api/newdeveloper/groups/0 in CLIP, the result does include the list of lights:

{
    "name": "Lightset 0",
    "lights": [
        "1",
        "2",
        "3"
    ],
    "type": "LightGroup",
    "action": {
        "on": false,
        "bri": 150,
        "hue": 2049,
        "sat": 0,
        "effect": "none",
        "xy": [
            0.3804,
            0.3768
        ],
        "ct": 248,
        "colormode": "xy"
    }
}

UPnP

I notice that the locateBridges function uses the meethue.com NUPnP service. Have you considered also using UPnP as shown in the Hue developer documentation? Their flowchart shows using UPnP, and if no results are returned, then use NUPnP. Alternately, they suggest running the UPnP and NUPnP queries simultaneously.

Save state of lights

Save the presumed state of the lights on the server so we don't have to send requests and wait to learn the state of the lights before mutating them.

hsl(hue, sat, briPercent) is hsb

Hi,

I found a problem with the API,

If I set hsl(0, 100, 100) it make the light Red but the good value in HSL for red is hsl(0, 100, 50).

Anyone agree with this ?

ECONNRESET for many lightStatus calls

Hi,

I have this case, where I get a connection reset when obtaining the lightStatus for many lamps (around 8).
My current solution is to use a queue, but it would be nice to bind it to the open connections or unresolved promises.

Error: write ECONNRESET
at exports._errnoException (util.js:746:11)
at Socket._writeGeneric (net.js:681:26)
at Socket. (net.js:637:12)
at Socket.g (events.js:199:16)
at Socket.emit (events.js:129:20)
at TCPConnectWrap.afterConnect as oncomplete

Lights return to max brightness with color change

I noticed the following:
krtek:~ steven$ hue lights 1,2,3,4 -99
light 1 brightness 104 -> 5
light 2 brightness 104 -> 5
light 3 brightness 104 -> 5
light 4 brightness 104 -> 5

krtek:~ steven$ hue lights 1,2,3,4 00FF99
light 1 success
light 2 success
light 3 success
light 4 success

krtek:~ steven$ hue lights 1,2,3,4 -99
light 1 brightness 254 -> 155
light 2 brightness 254 -> 155
light 3 brightness 254 -> 155
light 4 brightness 254 -> 155

Notice how after changing the color then the brightness they we're back at 254.

Update the Schedules API implementation

The Schedules API implementation needs to be updated to support the changes in the underlying Bridge API.

Attention is required to times and how they re specified in the schedule as this area has changed a lot.

Not working as expected when using one state for multiple lamps

Hi Peter,

First of all, awesome API! Great job! ๐Ÿ‘

Alright, so I recently started making a Hue CLI using your API and got some unexpected behaviour when using one state object for multiple lamps. I fixed this by creating a new state for each lamp. Have a look at the commit message below, any idea why this is happening?

Fixes unexpected behaviour issue when changing multiple lamps

We were using one state object to change multiple lamps. This turned out to give unexpected behaviour.
When for example doing something like './hue all --rgba=255,0.0' one lamp would turn red and the other
one would turn blue. They did however get the same state object with the same color x,y values.

This version creates a new state object for each lamp which seems to work as you'd expect.

New error after updating bridge software

Hello,

Made the mistake of upgrading my bridge yesterday without checking if it had breaking issues. Here's the error that's being thrown from my code - which had been working fine for months. I do have the latest node-hug-api installed.

Sorry for the weak issue title. I don't know how else to describe the error.

C:\jobs\node_modules\node-hue-api\node_modules\q\q.js:126
throw e;
^
Api Error: Internal error, 404
at checkForError (C:\jobs\node_modules\node-hue-api\hue-api\httpPromise.js:9
3:15)
at C:\jobs\node_modules\node-hue-api\hue-api\httpPromise.js:140:26
at _fulfilled (C:\jobs\node_modules\node-hue-api\node_modules\request-util\node_modules\q\q.js:787:54)
at self.promiseDispatch.done (C:\jobs\node_modules\node-hue-api\node_modules
\request-util\node_modules\q\q.js:816:30)
at Promise.promise.promiseDispatch (C:\jobs\node_modules\node-hue-api\node_modules\request-util\node_modules\q\q.js:749:13)
at C:\jobs\node_modules\node-hue-api\node_modules\request-util\node_modules\q\q.js:557:44
at flush (C:\jobs\node_modules\node-hue-api\node_modules\request-util\node_modules\q\q.js:108:17)
at process._tickCallback (node.js:419:13)

And here's the method that produces the error:

function BlinkNotificationLights() {
  api.getGroup(1, function(err, result) {
      if (err) throw err;
    var lightList = result.lights;
    var lightStatus = [];
    lightList.forEach(function(lx) {
      api.lightStatus(lx, function(err, result) {
        lightStatus[lx] = result.state; 
      });
    });

    for (var lightloop = 2000; lightloop < 9000; lightloop+=2000 ) {

    setTimeout(function() {
      api.setGroupLightState(1, lsNotify, function(err, lights) { });
    }, lightloop - 2000);     

    setTimeout(function() {
      api.setGroupLightState(1, lsNotify2, function(err, lights) { });
    }, lightloop);

    }

    setTimeout(function() {
      lightList.forEach(function(lx) {
      api.setLightState(lx, lightStatus[lx], function(err, lights) {
          if (err) throw err;   
      });
      })
    }, 10500);

  });
}

lightState.rgb(255,255,255) produces red light

Produces a red light after passing white rgb colors

lightState
.create()
.on()
.rgb(255,255,255)
.brightness(100)

Produces a white light after passing black rgb colors

lightState
.create()
.on()
.rgb(0, 0, 0)
.brightness(100)

Comments markup

Simple question: what is the markup you are using in code comments, particularly in index.js, and how does it work?

patch file in npm package

There is a new file named 'patch' in the 1.0.0 npm package. I don't think it's supposed to be there.

Short flash when light is turned on

I noticed the following:

  • Set a light to a bright white
  • Turn it off with on:false
  • Then turn it on with a state like {"on":true,"bri":128,"colormode":"hs","hue":65535,"sat":254} (Dark Red)
    The light does a short flash then turns to the desired state.

It seems that it first turns on, so the light wants to return to its previous bright white state. After that it gets its new color state.

Using the Hue Tab, when i do the same (one button is bright white, the second is dark red and the main is off), the flash doesn't happen. It turns from off to dark red directly,

Does anybody know why this happens with the node-hue-api but not with the Hue Tab? Are I am doing something wrong?

alert() does not work (nothing happens, api says true)

using api v1.0.2, if I use api.setLightState(1, lightState.create().alert()); or return api.setGroupLightState(0, lightState.create().alert());nothing happens.

Edit: However lightState.create().longAlert()does work!

Luminaire, not luminarie

The readme and comments in the code refer to "luminaries" but the correct term is "luminaires". The actual code seems to have this correct, it's just a documentation/comment problem.

created scene id is 'NaN'

I'm using node-hue-api 1.0.3 and I have not set a custom scene id prefix.

When calling api.createScene, the resulting id is a NaN, whereas this should be a unique string.

Example result json:

{ lights: [ '4', '5', '6' ], id: 'NaN' }

I think the problem is in

HueApi.prototype._getScenePrefix = function () {
    return this._getConfig().scene_prefix;
};

I think it should be

HueApi.prototype._getScenePrefix = function () {
    return this._getConfig().scenePrefix;
};

Update copyright date

The copyright year at the bottom of the readme is still "2013". That should probably be updated to be "2013-2015". Same anywhere else you might list the copyright date.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.