AlCalzone / node-tradfri-client

Library to talk to IKEA Trådfri Gateways without external binaries
MIT License
264 stars 30 forks source link
ikea iot lighting smarthome tradfri

node-tradfri-client

Library to talk to IKEA Trådfri Gateways without external binaries

node npm

Build Status Coverage Status

Example usage

Discover a Gateway

import { discoverGateway } from "node-tradfri-client";

// later:
const result = await discoverGateway();

The result variable has the following properties:

{
    name: 'gw-abcdef012345',
    host: 'TRADFRI-Gateway-abcdef123456.local', // (optional!)
    version: '1.3.14',
    addresses: [
        // array of strings with IP addresses
    ]
}

Note about addresses and host attributes: the addresses array contains IPv4 and/or IPv6 addresses and will always contain at least one item. The host contains the mDNS name of the gateway - to use this host you need a working mDNS name resolution (should work out of the box for OSX, needs Name Service Switch service and Avahi).

Common code for all examples

import { TradfriClient, Accessory, AccessoryTypes } from "node-tradfri-client";

// connect
const tradfri = new TradfriClient("gw-abcdef012345");
try {
    await tradfri.connect(identity, psk);
} catch (e) {
    // handle error - see below for details
}

Make a lightbulb blink

// observe devices
tradfri
    .on("device updated", tradfri_deviceUpdated)
    .on("device removed", tradfri_deviceRemoved)
    .observeDevices()
;

const lightbulbs = {};
function tradfri_deviceUpdated(device: Accessory) {
    if (device.type === AccessoryTypes.lightbulb) {
        // remember it
        lightbulbs[device.instanceId] = device;
    }
}

function tradfri_deviceRemoved(instanceId: number) {
    // clean up
}

// later...
// at least after we have actually received the light object

const light = lightbulbs[65537].lightList[0];
// blink
setTimeout(() => light.toggle(), 0);
setTimeout(() => light.toggle(), 1000);
setTimeout(() => light.toggle(), 2000);
setTimeout(() => light.toggle(), 3000);

// even later...
// before shutting down the app
tradfri.destroy();

Rename a group

// observe devices
tradfri
    .on("group updated", tradfri_groupUpdated)
    .observeGroupsAndScenes()
;

const groups = {};
function tradfri_groupUpdated(group: Group) {
    // remember it
    groups[group.instanceId] = group;
}

// later...
// at least after we have actually received the group object

const group = groups[123456];
group.name = "new name";
await tradfri.updateGroup(group);

// even later...
// before shutting down the app
tradfri.destroy();

Detailed usage

Import the necessary methods

const tradfriLib = require("node-tradfri-client");
// for normal usage:
const TradfriClient = tradfriLib.TradfriClient;
// for discovery:
const discoverGateway = tradfriLib.discoverGateway;

// or with the new import syntax
import { discoverGateway, TradfriClient /*, more imports */ } from "node-tradfri-client";

Auto-detect your gateway

You can automatically discover a Trådfri gateway on the local network with the discoverGateway method. Discovery will return the first gateway found, finding multiple ones is not possible yet.

The method has the following signatures:

const discovered = await discoverGateway();
const discovered = await discoverGateway(timeout: number);
const discovered = await discoverGateway(false);

The timeout parameter is the time in milliseconds (default 10000) the discovery will run before returning null to indicate that no gateway was found. By passing a negative value or false you can instruct the discovery to run forever.

The return value is of the type DiscoveredGateway which looks as follows:

{
    // hostname of the gateway, has the form "gw-abcdef012345"
    name: string,
    // firmware version of the gateway
    version: string,
    // array of IP addresses the gateway responds to
    addresses: string[],
}

Create a client instance

// one of the following
const tradfri = new TradfriClient(hostnameOrAddress: string);
const tradfri = new TradfriClient(hostnameOrAddress: string, customLogger: LoggerFunction);
const tradfri = new TradfriClient(hostnameOrAddress: string, options: TradfriOptions);

Note: It seems that in some networks you need to connect to the gateway using its hostname, while in other networks only the IP address works. As a result you have to try out which one works best for you.

As the 2nd parameter, you can provide a custom logger function or an object with some or all of the options shown below. By providing a custom logger function to the constructor, all diagnostic output will be sent to that function. By default, the debug module is used instead. The logger function has the following signature:

type LoggerFunction = (
    message: string,
    [severity: "info" | "warn" | "debug" | "error" | "silly"]
) => void;

The options object looks as follows:

interface TradfriOptions {
    customLogger: LoggerFunction,
    useRawCoAPValues: boolean,
    watchConnection: boolean | ConnectionWatcherOptions,
}

You can provide all the options or just some of them:

The following code samples use the new async/await syntax which is available through TypeScript/Babel or in ES7. If that is no option for you, you can also consume the library by using promises:

try {
    const result = await asyncMethod(securityCode);
} catch (e) {
    // handle error
}

is equal to

asyncMethod(securityCode)
    .then((result) => {
        // work with the result
    })
    .catch((e) => {
        // handle error
    })
;

Authentication

As of firmware version 1.2.42, the Trådfri Gateway requires generation of a unique identity before serving any requests. This step is not necessary if you already have a valid identity/psk pair. To do so, call the authenticate method with the security code printed on the gateway:

try {
    const {identity, psk} = await tradfri.authenticate(securityCode);
    // store identity and psk
} catch (e) {
    // handle error
}

To comply with IKEA's requests, the security code must not be stored permanently in your application. Instead, store the returned identity and psk and use those for future connections to the gateway.

If the authentication was not successful, this method throws (or rather rejects with) an error which you should handle. The error e should be of type TradfriError and gives further information why the authentication failed. To check that, add TradfriError and TradfriErrorCodes to the list of imports and check as follows:

if (e instanceof TradfriError) {
    switch (e.code) {
        case TradfriErrorCodes.ConnectionTimedOut: {
            // The gateway is unreachable or did not respond in time
        }
        case TradfriErrorCodes.AuthenticationFailed: {
            // The security code is wrong or something else went wrong with the authentication.
            // Check the error message for details. It might be that this library has to be updated
            // to be compatible with a new firmware.
        }
        case TradfriErrorCodes.ConnectionFailed: {
            // An unknown error happened while trying to connect
        }
    }
}

Connecting to the gateway

When you have a valid identity and psk, you can connect to the gateway using the connect method:

try {
    await tradfri.connect(identity, psk);
} catch (e: TradfriError) {
    // handle error
    switch (e.code) {
        case TradfriErrorCodes.ConnectionTimedOut: {
            // The gateway is unreachable or did not respond in time
        }
        case TradfriErrorCodes.AuthenticationFailed: {
            // The provided credentials are not valid. You need to re-authenticate using `authenticate()`.
        }
        case TradfriErrorCodes.ConnectionFailed: {
            // An unknown error happened while trying to connect
        }
    }
}

If you have automatic reconnection enabled, this method can retry for a long time before resolving or rejecting, depending on the configuration.

NOTE: As of v0.6.0, this no longer resolves with false if the connection was unsuccessful. Instead, it throws (or rejects with) a TradfriError which contains details about why the connection failed.

Pinging the gateway

const success = await tradfri.ping(
    [timeout: number]
);

Check the reachability of the gateway using inexpensive CoAP pings. The optional timeout parameter sets the time in ms (default: 5000) after which the ping fails. This is only possible after an initial connection to the gateway.

Resetting the connection

tradfri.reset([preserveObservers: boolean]);

After a connection loss or reboot of the gateway, the currently active connection params might no longer be valid. In this case, use the reset method to invalidate the stored connection params, so the next request will use a fresh connection.

This causes all requests to be dropped and clears all observations. To preserve the observers, pass true to the method. When the connection is alive again, you can then call

await tradfri.restoreObservers();

to re-activate all observers and their callbacks.

Note: Promises belonging to any pending connections, requests or observers will not be fulfilled anymore and you should delete all references to them. In that case, the "error" event will be emitted (once or multiple times) with an error with code TradfriClient.NetworkReset.

Closing the connection

tradfri.destroy();

Call this before shutting down your application so the gateway may clean up its resources.

Subscribe to updates

The TradfriClient notifies registered listeners when observed resources are updated or removed. It is using the standard EventEmitter interface, so you can add listeners with on("event", handler) and remove them with removeListener and removeAllListeners. The currently supported events and their handler signatures are:

"device updated" - A device was added or changed

type DeviceUpdatedCallback = (device: Accessory) => void;

"device removed" - A device was removed

type DeviceRemovedCallback = (instanceId: number) => void;

"group updated" - A group was added or changed

type GroupUpdatedCallback = (group: Group) => void;

"group removed" - A group was removed

type GroupRemovedCallback = (instanceId: number) => void;

"scene updated" - A scene (or "mood") was added to a group or changed

type SceneUpdatedCallback = (groupId: number, scene: Scene) => void;

"scene removed" - A scene (or "mood") was removed from a group

type SceneRemovedCallback = (groupId: number, instanceId: number) => void;

Handle errors

The "error" event gets emitted when something unexpected happens. The callback has the following form:

type ErrorCallback = (e: Error) => void;

This doesn't have to be fatal, so you should check which kind of error happened. Some errors are of the type TradfriError and contain a code which provides more information about the nature of the error. To check that, add TradfriError and TradfriErrorCodes to the list of imports and check as follows:

if (e instanceof TradfriError) {
    // handle the error depending on `e.code`
} else {
    // handle the error as you normally would.
}

The currently supported error codes are:

Observe a resource

The standard way to receive updates to a Trådfri (or CoAP) resource is by observing it. The TradfriClient provides a couple of methods to observe resources, with the most generic one being

const success = await tradfri.observeResource(
    path: string,
    callback: (resp: CoapResponse) => void
);

The path argument determines which endpoint should be observed, e.g. "15001" for the list of devices. The callback is called for every response or update of the gateway. The method returns true if a new observer was set up, and false otherwise. If no new observer was set up, the provided callback will not be called.

To stop observing the resource and no longer receive updates, call

tradfri.stopObservingResource(path: string): void;

with the same path you used to setup the observer.

For a more detailed explanation of the CoapResponse object, please refer to the node-coap-client documentation.

NOTE: Prefer to use the specialized observer methods below whereever posible.

Observe devices

By calling (or awaiting)

tradfri.observeDevices(): Promise<void>;

you can set up an observer for all devices on the gateway. The callbacks registered with on("device updated") and on("device removed") will now be called for updates.

Calling stopObservingDevices() stops the observation of devices and the callbacks will no longer be invoked.

Observe groups and scenes ("moods")

By calling (or awaiting)

tradfri.observeGroupsAndScenes(): Promise<void>;

you can set up an observer for all groups and their scenes, which will call the callbacks for "group updated", "group removed", "scene updated" and "scene removed" on updates. Stopping this observer is possible by calling stopObservingGroups().

NOTE: Keep in mind that (due to the gateway only reporting changes to every single bulb) switching a group on or off does NOT result in a callback!

A "group updated" callback does occur when you:

Observing the gateway details

Using

tradfri.observeGateway(): Promise<void>

you can set up an observer for the gateway details, which in turn will call the registered callbacks for "gateway updated" when something changes. The observation can be stopped by calling tradfri.stopObservingGateway().

The object passed to the callback is of type GatewayDetails with the following properties:

Note: Many properties are not completely understood at the moment. If you can provide more information, feel free to open an issue.

Listening to notifications

Using

tradfri.observeNotifications(): Promise<void>

you can start listening to notifications events from the gateway. The observation can be stopped by calling tradfri.stopObservingNotifications().

You can add listeners with on("event", handler) and remove them with removeListener and removeAllListeners. The currently supported events and their handler signatures are:

"rebooting" - The gateway is rebooting

type RebootNotificationCallback = (reason: string) => void;

where reason is one of:

"internet connectivity changed" - The status of the internet connection has changed

type InternetConnectivityChangedCallback = (connected: boolean) => void;

This also gets called at every start start with the current status of the internet connection.

"firmware update available" - A new firmware is available

type FirmwareUpdateNotificationCallback = (releaseNotes: string, priority: string) => void;

The argument releaseNotes contains an URL with the official release notes, priority is one of the following

Updating a device on the gateway

You can change properties of a device on the gateway (e.g. rename it) by calling

const requestSent = await tradfri.updateDevice(accessory: Accessory);

If the accessory object is not changed in comparison to the one on the gateway, no request will be sent and the return value will be false. The usage of this method requires that the devices are already being observed.

NOTE: To switch a light on/off or to change its properties, prefer the operateLight method or the specialized methods defined on the lightbulb itself.

const requestSent = await tradfri.operateLight(accessory: Accessory, operation: LightOperation[, force: boolean]);

The parameter accessory is the device containing the lightbulb. The operation object contains the properties to be updated, e.g.

{
    onOff: value,
    transitionTime: 5,
}

By setting the optional third parameter (force) to true, the entire operation object will be transmitted, even if no values have changed.

Updating a group on the gateway

Similar to updating devices, you can update groups by calling

const requestSent = await tradfri.updateGroup(group: Group);

NOTE: To switch all lights in a group or to change their properties, prefer the operateGroup method.

const requestSent = await tradfri.operateGroup(
    group: Group,
    operation: GroupOperation,
    [force: boolean = false]
);

It is similar to the operateLight method, see the chapter Data structures below for a complete list of all properties. Because the gateway does not report back group properties, the sent payloads are computed using the old properties of the group. To ensure the entire GroupOperation is always present in the payload, set the force parameter to true. Note: force = true might become the default in a future release.

Custom requests

For all one-time requests currently not possible through specialized methods, you can use

const response = await tradfri.request(
    path: string,
    method: "get" | "post" | "put" | "delete",
    [payload: object]
);

The path is the CoAP endpoint to be requested, the payload (if provided) must be a valid CoAP payload in JSON form. Upon completion, the promise resolved with a response object of the following form

{
    code: string,
    payload: string | object,
}

where the code is the string representation of one of the defined CoAP message codes and the payload is either a string or a JSON object.

Rebooting the gateway

Using

tradfri.rebootGateway(): Promise<boolean>

you can reboot the gateway. The promise value determines if the reboot was started (true) or not (false). A successful reboot is also indicated by a reboot notification (not implemented yet).

Performing a factory reset on the gateway.

Using

tradfri.resetGateway(): Promise<boolean>

you can factory reset the gateway. The promise value determines if the reboot was started (true) or not (false).

Warning: This wipes all configuration, including paired devices, groups and moods/scenes!

Data structure

Accessory

An Accessory is a generic device connected to the gateway. It can have several sub-devices, such as

The properties available on an Accessory are:

Light

A light represents a single lightbulb and has several properties describing its state. The supported properties depend on the spectrum of the lightbulb. All of them support the most basic properties:

as well as a few readonly properties:

White spectrum lightbulbs also support

RGB lightbulbs have the following properties:

The additional properties are either for internal use (colorX/colorY) or not supported by the gateway. So don't use them!

If the light object was returned from a library function and not created by you, the following methods are available to change its appearance directly. You can await them to make sure the commands were sent or just fire-and-forget them. The returned Promises resolve to true if a command was sent, otherwise to false.

For the methods accepting a transitionTime, you can specify an optional transition time or use the default of 0.5s.

LightOperation

A LightOperation is an object containing at least one of a Light's properties, which are:

{
    onOff: boolean;
    dimmer: number;
    transitionTime: number;
    colorTemperature: number;
    color: string;
    hue: number;
    saturation: number;
}

or a subset thereof.

Plug

A plug represents a single outlet plug and has a single writable describing its state:

as well as a few readonly properties:

If the plug object was returned from a library function and not created by you, the following methods are available to change its state directly. Just like with lights, you can await them to make sure the commands were sent or just fire-and-forget them. The returned Promises resolve to true if a command was sent, otherwise to false.

PlugOperation

A PlugOperation is an object containing the desired on/off state of a Plug:

{
    onOff: boolean;
}

Group

A group contains several devices, usually a remote control or dimmer and some lightbulbs. To control the group's lightbulbs, use the following properties:

Note: The Trådfri gateway does not update those values when lights change, so they should be considered write-only.

Additionally, these properties are also supported:

Similar to lightbulbs, groups provide the following methods if they were returned from a library function. You can await them to make sure the commands were sent or just fire-and-forget them. The returned Promises resolve to true if a command was sent, otherwise to false.

GroupOperation

A GroupOperation is an object containing at least one of a Group's controllable properties, which are:

{
    onOff: boolean;
    dimmer: number;
    transitionTime: number;
    sceneId: number;
}

or a subset thereof.

Sensor - Not supported

DeviceInfo

A DeviceInfo object contains general information about a device. It has the following properties:

Automatically watching the connection and reconnecting

Note: This feature is currently experimental

This library allows you to watch the connection and automatically reconnect without shipping your own reconnection routine. Retrying the initial connection is also possible if you have already authenticated.

You can enable it by setting the watchConnection param of the constructor options to true or an options object with the following structure:

interface ConnectionWatcherOptions {
    /** The interval in ms between consecutive pings */
    pingInterval: number; // DEFAULT: 10000ms
    /** How many pings have to consecutively fail until the gateway is assumed offline */
    failedPingCountUntilOffline: number; // DEFAULT: 1
    /**
     * How much the interval between consecutive pings should be increased
     * while the gateway is offline. The actual interval is calculated by
     * <ping interval> * <backoff factor> ** <offline pings)>,
     * with the number of offline pings capped at 5.
     */
    failedPingBackoffFactor: number; // DEFAULT: 1.5

    /** Whether automatic reconnection and retrying the initial connection is enabled */
    reconnectionEnabled: boolean; // DEFAULT: enabled
    /**
     * How many pings have to consecutively fail while the gateway is offline
     * until a reconnection is triggered
     */
    offlinePingCountUntilReconnect: number; // DEFAULT: 3
    /** After how many failed reconnects we give up */
    maximumReconnects: number; // DEFAULT: infinite

    /** How many tries for the initial connection should be attempted */
    maximumConnectionAttempts: number; // DEFAULT: infinite
    /** The interval in ms between consecutive connection attempts */
    connectionInterval: number; // DEFAULT: 10000ms
    /**
     * How much the interval between consecutive connection attempts
     * should be increased. The actual interval is calculated by
     * <connection interval> * <backoff factor> ** <failed attempts>
     * with the number of failed attempts capped at 5
     */
    failedConnectionBackoffFactor: number; // DEFAULT: 1.5

}

All parameters of this object are optional and use the default values if not provided. Monitoring the connection state is possible by subscribing to the following events, similar to subscribing to updates:

Note: Reconnection internally calls the reset() method. This means pending connections and promises will be dropped and the "error" event may be emitted aswell. See resetting the connection for details.

The automatic reconnection tries to restore all previously defined observers as soon as the connection is alive again.