Back to Top

NEEO SDK 0.53.8

NEEO Brain SDK. For examples see https://github.com/NEEOInc/neeo-sdk-examples.

startServer(configuration)

Starts the internal REST server (based on Express.js) and register this adapter on the NEEO Brain - so the Brain can find this adapter

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.brain NEEOBrain

NEEOBrain object

configuration.port Number

listening port

configuration.name String

device name

configuration.devices Array

all associated devices for this driver Optionally you can add baseurl to define the listening ip - handy if you have multiple IP's or running in a docker container.

Examples

neeoapi.startServer({
  brain,
  port: 6336,
  name: 'custom-adapter',
  devices: [device1, device2]
});

Returns

Promise

will be resolved when adapter is registered and REST server is started

addListHeader(configuration)

This function adds a header to the list, which can be used as a visual separator. A ListHeader is a pure visual informational object.

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.title String

title that will be shown on the list item entry

Examples

   .addListHeader({
     title: 'My Header',
   })

Returns

ListBuilder

ListBuilder for chaining.

addListItem(configuration)

This function adds an item to the list. To avoid downloading and resizing large images on the Brain you should provide an image of 80x80px. These guidelines are specifically for the remote, a larger (maybe double) resolution might offer a good compromise for mobile devices.

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.title String

title that will be shown on the list item entry

configuration.label String

optional, additional label

configuration.thumbnailUri String

optional, URL that points to an image that will be displayed on the list item

configuration.browseIdentifier String

optional, identifier that is passed with a browse request to identify which "path" should be browsed

configuration.actionIdentifier String

optional, string passed back to handling function when item is clicked

configuration.uiAction ListUIAction

optional, string representing action GUI should take after item is clicked, can be any of "goToRoot" (going back to the root of the directory), "goBack" (going back one step in history), "close" (closing the modal), "reload" (reloading the current view with same browseIdentifier)

Examples

   .addListItem({
     title: 'First List Item',
     thumbnailUri: 'https://www.image.com/image.jpg',
     uiAction: 'close',
   })

Returns

ListBuilder

ListBuilder for chaining.

setListTitle(name)

This function sets the name of the list. The list title is only displayed when you add the directory as shortcut.

Parameters

Name Type Description
name String

the list name

Examples

   .setListTitle('it is a name!')

Returns

ListBuilder

ListBuilder for chaining.

setTotalMatchingItems(totalMatchingItems)

This function updates the totalMatchingItems number of the list (used for pagination).

Parameters

Name Type Description
totalMatchingItems Integer

the total length of the list

Examples

   .setTotalMatchingItems(100)

Returns

ListBuilder

ListBuilder for chaining.

addListItems(Array)

add an array of ListItem to a list. this function limits the amount of items to add depending on the options.limit setting (it never adds more than options.limit entires).

Parameters

Name Type Description
Array Array

of ListItem JSON elements

Examples

   .addListItems([
     { title: 'foo' },
     { title: 'bar' }
   ])

Returns

ListBuilder

ListBuilder for chaining.

addListTiles(configuration)

This function adds a row of tiles to the list. It takes an array of up to two tiles. A ListTile shows a large thumbnail and the defined action will be executed when the ListTile element is selected. To avoid downloading and resizing large images on the Brain you should provide an image of 215x215px. These guidelines are specifically for the remote, a larger (maybe double) resolution might offer a good compromise for mobile devices.

Parameters

Name Type Description
configuration Array

Configuration Array

configuration.thumbnailUri String

optional, URL that points to an image that will be displayed on the list item

configuration.actionIdentifier String

optional, string passed back to handling function when item is clicked

configuration.uiAction ListUIAction

optional, string representing action GUI should take after the tile is clicked, can be any of "goToRoot" (going back to the root of the directory), "goBack" (going back one step in history), "close" (closing the modal), "reload" (reloading the current view with same browseIdentifier)

Examples

   .addListTile([{
     thumbnailUri: 'https://www.image.com/image.jpg',
     uiAction: 'reload'
   }])

Returns

ListBuilder

ListBuilder for chaining.

addListInfoItem(configuration)

This function adds an info item to the list. Pressing this element will open a popup with the defined text.

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.title String

title that will be shown on the list item entry

configuration.text String

text that will be shown in the resulting popup. This is the only text that will be shown on the NEEO remote.

configuration.affirmativeButtonText String

optional, will be shown on the OK popup button

configuration.negativeButtonText String

optional, will be shown on the CANCEL popup button

configuration.actionIdentifier String

optional, passed back to handling function when item is clicked

Examples

   .addListInfoItem({
     title: 'This is only an information and I will open a popup',
     text: 'I am the popup text',
     affirmativeButtonText: 'OK',
     negativeButtonText: 'Cancel',
     actionIdentifier: 'OK_CLICKED',
   })

Returns

ListBuilder

ListBuilder for chaining.

addListButtons(configuration)

This function adds a row of buttons to the list. It takes an array of up to three buttons. The defined action will be executed when the button is pressed.

Parameters

Name Type Description
configuration Array

Configuration Array

configuration.iconName String

icon that will be shown on the list item entry instead of the text - available icons: 'Shuffle', 'Repeat'. Note: either iconName or title must be defined

configuration.title String

title that will be shown on the list item entry. Note: either iconName or title must be defined

configuration.actionIdentifier String

optional, string passed back to handling function when button is clicked

configuration.inverse Boolean

optional, removes the background color of the button

Examples

   .addListButtons([{
     iconName: 'Shuffle',
     actionIdentifier: 'ROW1_SHUFFLE',
   }])
   .addListButtons([{
     iconName: 'Repeat',
     actionIdentifier: 'ROW2_REPEAT',
   }, {
     title: 'Play All',
     inverse: true,
     actionIdentifier: 'ROW2_PLAYALL',
   }])

Returns

ListBuilder

ListBuilder for chaining.

buildDevice(DeviceName)

Create new device factory, builds a searchable device for the NEEO Brain

Parameters

Name Type Description
DeviceName String

The device name

Examples

 neeoapi.buildDevice('simpleDevice1')
   .setManufacturer('NEEO')
   .addAdditionalSearchToken('foo')
   .setType('light')
   .addButton({ name: 'example-button', label: 'my button' }, controller.button)
   .addSwitch({ name: 'example-switch', label: 'my switch' },
     { setter: controller.switchSet, getter: controller.switchGet })
   .addSlider({ name: 'example-slider', label: 'my slider', range: [0,110], unit: '%' },
     { setter: controller.sliderSet, getter: controller.sliderGet });

Returns

DeviceBuilder

factory methods to build device

buildBrowseList(configuration)

Create new list factory, builds a browsable list which can be used for a specific device, for example to browse a playlist

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.title String

title of the list

configuration.totalMatchingItems Number

how many results the query included in total (used for pagination)

configuration.limit Number

optional, how many items should be queried per page (used for pagination). The default and maximum is 64.

configuration.offset Number

optional, default starting offset (used for pagination)

configuration.browseIdentifier String

optional, identifier that is passed with a browse request to identify which "path" should be browsed

Examples

 neeoapi.buildBrowseList({
     title: 'list title',
     totalMatchingItems: 100,
     limit: 20,
     offset: 0,
     browseIdentifier: 'browseEverything'
   })
   .addListHeader('NEEO Header')
   .addListItem({
     title: 'foo'
   })

Returns

ListBuilder

factory methods to build list

buildDeviceState(cacheTimeMs)

This function builds a new DeviceState Object which helps organise client states, cache states and reachability

Parameters

Name Type Description
cacheTimeMs integer

how long should a devicestate be cached (optional, default is 2000ms)

Examples

 const deviceState = neeoapi.buildDeviceState(2000);

Returns

DeviceState

a new DeviceState instance

stopServer(configuration)

Stops the internal REST server and unregister this adapter on the NEEO Brain

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.brain NEEOBrain

NEEOBrain object

configuration.name String

device name

Examples

neeoapi.stopServer({ brain: brain, name: 'custom-adapter' });

Returns

Promise

will be resolved when adapter is unregistered and REST server is stopped

discoverOneBrain(multiInterface)

Returns a promise to the first NEEO Brain discovered on the local network.

Parameters

Name Type Description
multiInterface Boolean

to allow to search for a brain on all interfaces (optional, default is false). If you have a mdns discovery service e.g. Bonjour, it must be turned off in advance.

Examples

neeoapi.discoverOneBrain(true)
  .then((brain) => {
   ...
 }

Returns

promise

promise contains the found NEEOBrain.

setManufacturer(manufacturerName)

Optional parameter to set the device manufacturer. Default manufacturer is NEEO

Parameters

Name Type Description
manufacturerName string

used to find and add the device in the NEEO app.

Examples

.setManufacturer('NEEO')

Returns

DeviceBuilder

DeviceBuilder for chaining.

setDriverVersion(version)

Setting the version allows you to tell the Brain about changes to your devices components. If you for example add new buttons to a device, you can increase the version and this will let the Brain know to fetch the new components (NOTE: the Brain will only add new components, updating or removing old components is not supported). You do not need to update the version if you do not change the components. When adding the version to a device that was previously not versioned, start with 1. The NEEO Brain will assume it was previously 0 and update.

Parameters

Name Type Description
version Number

Integer identifying current driver version, used by NEEO Brain to detect a newer version of your device.

Examples

.setDriverVersion(1)

Returns

DeviceBuilder

DeviceBuilder for chaining.

setType(type)

Optional parameter to define the device type. Default type is ACCESSORY. It is used to determine the display style and wiring suggestions in the NEEO app. Please note, ACCESSORY devices do not generate a view but can be used in other views as shortcut.

Parameters

Name Type Description
type string

supported device classes:

  • ACCESSORY
  • AUDIO
  • AVRECEIVER
  • DVB (aka. satellite receiver)
  • DVD (aka. disc player)
  • GAMECONSOLE
  • HDMISWITCH
  • LIGHT
  • MEDIAPLAYER
  • MUSICPLAYER
  • PROJECTOR
  • TUNER
  • TV
  • VOD (aka. Video-On-Demand box like Apple TV, Fire TV...)
  • SOUNDBAR

Examples

.setType('light')

Returns

DeviceBuilder

DeviceBuilder for chaining.

setIcon(icon)

Optional parameter to define the device icon. The default icon is defined according to the device type if no custom icon is set.

Parameters

Name Type Description
icon string

string identifying the icon, the following icons are currently available: 'sonos', 'neeo-brain'

Examples

.setIcon('sonos')

Returns

DeviceBuilder

DeviceBuilder for chaining.

setSpecificName(specificname)

Parameters

Name Type Description
specificname string

Optional name to use when adding the device to a room (a name based on the type will be used by default, for example: 'Accessory'). Note this does not apply to devices using discovery.

Examples

.setSpecificName('Specific Device Name')

Returns

DeviceBuilder

DeviceBuilder for chaining.

addAdditionalSearchToken(token)

Optional parameter define additional search tokens the user can enter in the NEEO App "Add Device" section.

Parameters

Name Type Description
token string

additional search keyword

Examples

neeoapi.buildDevice('My Device Name')
       .addAdditionalSearchToken('MDN')

Returns

DeviceBuilder

DeviceBuilder for chaining.

enableDiscovery(configuration, discoverFunction)

Register a discovery function for your devicedriver. This function can be only defined once per device definition.

Parameters

Name Type Description
configuration Object

A configuration object

configuration.headerText String

this text will be displayed before the user starts the discovery process

configuration.description String

this text will be displayed before the user starts the discovery process

configuration.enableDynamicDeviceBuilder Boolean

if set to true, the discovery itself will return a devices itself (as .device attribute). This is handy if you have a Hub device which returns different devices with different capabilities. No additional capabilities on the device must be enabled. If set to false the driver returns one static device definition. (optional, default: false)

discoverFunction Function

Callback function which will return the discovered devices as Array. This Array contains JSON Objects with this content:

  • id unique device identifier, for example mac address
  • name display name which is visible in the frontend
  • reachable true: device is reachable, false: device is not reachable (optional)
  • device if enableDynamicDeviceBuilder is set to true, return the dynamic disovered and build device using the ".buildDevice" function

NOTE: if you set enableDynamicDeviceBuilder to true - then the NEEO Brain will query your discovery function with a specific device Id the first time this device is requested. You can either

  • ignore this option completly and return the discovered devices (might not be the ideal solution as potentially unused devices are build)
  • or build only the requested device and return that device
  • You can also use the .registerDeviceSubscriptionHandler function and prebuild the needed devices

Examples

.enableDiscovery(
  {
    headerText: 'HELLO HEADER',
    description: 'ADD SOME ADDITIONAL INFORMATION HOW TO PREPARE YOUR DEVICE',
    enableDynamicDeviceBuilder: false,
  },
  function(optionalDeviceId) {
   return [
     {
       id: 'unique-device-id-001',
       name: 'first device',
     },
     {
       id: 'unique-device-id-002',
       name: 'second device, but not reachable',
       reachable: false,
     }
   ];
  }
)

Returns

DeviceBuilder

DeviceBuilder for chaining.

supportsTiming()

This function allows you to check if the current device type supports timing related information.

Examples

   if (device.supportsTiming()) { }

Returns

Boolean

Whether timing is supported or not

supportsFavorites()

This function allows you to check if the current device type supports favorites.

Examples

   if (device.supportsFavorites()) { }

Returns

Boolean

Whether favorites are supported or not for this device type.

defineTiming(configuration)

This function allows you to define timing related information, which will be used to generate the recipe.

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.powerOnDelayMs Number

how long does it take (in ms) until the device is powered on and is ready to accept new commands

configuration.sourceSwitchDelayMs Number

how long does it take (in ms) until the device switched input and is ready to accept new commands

configuration.shutdownDelayMs Number

how long does it take (in ms) until the device is powered off and is ready to accept new commands

Examples

   .defineTiming({ powerOnDelayMs: 2000, sourceSwitchDelayMs: 500, shutdownDelayMs: 1000 })

Returns

DeviceBuilder

DeviceBuilder for chaining.

registerSubscriptionFunction(controller)

Registering this allows sending updated component values to the NEEO Brain (for example switches or sliders state changes). This function can be only defined once per device definition.

When the SDK is registered with a Brain the callback will be triggered with an update function as argument (aka. inject the function) and power state update functions. The update function can be used to then send updates to the Brain when the value device components changes (for example a physical slider is moved on the device, the digital slider is updated to the same value). The power updates can be used to notifiy the Brain when a device turns on or off (for example a light is turned off with a physical button).

NOTE: if you use ES6 classes, make sure to wrap your callback in an arrow function, for example: .registerSubscriptionFunction((...args) => controller.setNotificationCallbacks(...args))

Parameters

Name Type Description
controller Function

Called with the notification and optional power state callback functions:

  • The first argument is the component update callback updateCallback(options)
  • The Second argument contains optional power state callbacks: if the device supports power state (see addPowerStateSensor) 2 additional callbacks are present:
    • powerOnNotificationFunction, usage: powerOnNotificationFunction(deviceId)
    • powerOffNotificationFunction, usage: powerOffNotificationFunction(deviceId)

Examples

let sendComponentUpdate, markDeviceOn, markDeviceOff;
deviceBuilder.registerSubscriptionFunction((updateCallback, optionalCallbacks) => {
  sendComponentUpdate = updateCallback;
  if (optionalCallbacks && optionalCallbacks.powerOnNotificationFunction) {
    markDeviceOn = optionalCallbacks.powerOnNotificationFunction;
  }
  if (optionalCallbacks && optionalCallbacks.powerOffNotificationFunction) {
    markDeviceOff = optionalCallbacks.powerOffNotificationFunction;
  }
});

// Update sensor at some later point
if (sendComponentUpdate) {
  sendComponentUpdate({
    uniqueDeviceId: 'default',  // If enableDiscovery is used, use matching deviceId.
    component: 'VOLUME_SENSOR', // Name of the component added on start
                                // with the device builder (see `addSlider()` for example)
    value: 50,                  // Value to update component to
                                // Should match component type (boolean for switch, ...)
  }).catch((error) => {
    // sendComponentUpdate returns a Promise
    // adding a catch is needed to prevent an unhandled rejection.
    console.error('NOTIFICATION_FAILED', error.message);
  });
}
// Update device powerState
if (markDeviceOn) {
  markDeviceOn('default'); // again if enableDiscovery is used, use matching deviceId
}

Returns

DeviceBuilder

DeviceBuilder for chaining.

registerInitialiseFunction(controller)

for example: start polling for devicestate, initialise service

Parameters

Name Type Description
controller Function

Callback function which will be called when the device should be initialised.

Examples


.registerInitialiseFunction(controller.initialise)

// Example code in the controller:
module.exports.initialise = function() {
  debug('initialise LIFX service, start polling');
  lifxService = new LifxService(deviceState);
  setInterval(pollAllLifxDevices, DEVICE_POLL_TIME_MS);
};

Returns

DeviceBuilder

DeviceBuilder for chaining.

addButton(configuration)

Add a button for this device, can be called multiple times for multiple buttons. addButton can be combined with addButtonGroups. You need to be call the addButtonHandler function. IMPORTANT: If your device supports a discrete "Power On" and "Power Off" command, name the macros like in the example below. In that case the NEEO Brain automatically recognise this feature and those commands to in the prebuild Recipes.

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.name String

identifier of this element

configuration.label String

optional, visible label in the mobile app or on the NEEO Remote

Examples

.addButton({ name: 'POWER ON', label: 'Power On' })
.addButton({ name: 'POWER OFF', label: 'Power Off' })
.addButtonHandler((deviceid, name) => {
  // handle button events here
})

Returns

DeviceBuilder

DeviceBuilder for chaining.

addButtonGroup(name)

Add multiple buttons defined by the button group name. The UI elements on the NEEO Brain are build automatically depending on the existing buttons of a device. You can add multiple ButtonGroups to a device and you can combine ButtonGroups with addButton calls. You need to be call the addButtonHandler function.

Parameters

Name Type Description
name String

A button name group, see validation/buttongroup.js for valid options

Examples

.addButtonGroup('Numpad')
.addButtonHandler((name, deviceId) => {
  // handle button events here
})

Returns

DeviceBuilder

DeviceBuilder for chaining.

addButtonHandler(controller)

Handles the events for all the registered buttons. This function can be only defined once per device definition and MUST be defined if you have added at least one button.

Parameters

Name Type Description
controller function

Callback function which will be called one of the registered button triggered from the Brain.

Examples

.addButtonHandler((name, deviceId) => {
   if (name === 'power-on') {
     // Power on
   } else {
     // Power off
   }
});

Returns

DeviceBuilder

DeviceBuilder for chaining.

addSlider(configuration, controller)

Add a (range) slider to your custom device

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.name String

identifier of this element

configuration.label String

optional, visible label in the mobile app or on the NEEO Remote

configuration.range Array

optional, custom range of slider, default 0..100

configuration.unit String

optional, user readable label, default %

controller Object

Controller callbacks Object

controller.getter Function

return the current slider value

controller.action Function

update the current slider value

Examples

.addSlider(
  { name: 'example-slider', label: 'my slider', range: [0,200], unit: '%' },
  {
    setter: (deviceId, newValue) => sliderValue = newValue,
    getter: (deviceId) => sliderValue,
  }
)

Returns

DeviceBuilder

DeviceBuilder for chaining.

addSensor(configuration, controller)

Add a range/binary sensor to your custom device

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.name String

Identifier of this element

configuration.label String

Optional, visible label in the mobile app or on the NEEO Remote

configuration.type String

Type of sensor, the available types are binary, range, power (should be done using addPowerStateSensor), string, array

configuration.range Array

Optional, custom range of sensor, default 0..100

configuration.unit String

Optional, user readable label, default %

controller Object

Controller callbacks Object

controller.getter Function

A Function that returns the current sensor value

Examples

.addSensor(
  { name: 'example-sensor', label: 'my sensor', type: 'range', range: [0,200], unit: '%' },
  { getter: (deviceId) => sensorValue ) }
)

Returns

DeviceBuilder

DeviceBuilder for chaining.

addPowerStateSensor(controller)

Adds a special sensor that can be used to update device power state.

Parameters

Name Type Description
controller Object

Controller callbacks Object

controller.getter Function

return current value of the power sensor

controller.setter Function

update current value of the power sensor

Examples

.addPowerStateSensor({
  setter: (deviceId, newValue) => sensorState = newValue,
  getter: (deviceId) => sensorState ),
 })

Returns

DeviceBuilder

DeviceBuilder for chaining.

addSwitch(configuration, controller)

Add a (binary) switch to your custom element

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.name String

identifier of this element

configuration.label String

optional, visible label in the mobile app or on the NEEO Remote

controller Object

Controller callbacks Object

controller.getter Function

return current value of the Switch

controller.setter Function

update current value of the Switch

Examples

.addSwitch(
  { name: 'example-switch', label: 'my switch' },
  {
    setter: (deviceId, newValue) => switchState = newValue,
    getter: (deviceId) => switchState,
  }
 )

Returns

DeviceBuilder

DeviceBuilder for chaining.

addTextLabel(configuration, controller)

Add a text label to your custom element (for example to display the current artist)

Parameters

Name Type Description
configuration Object

JSON Configuration Object

configuration.name String

identifier of this element

configuration.label String

optional, visible label in the mobile app or on the NEEO Remote

configuration.isLabelVisible Boolean

should the label be visible

controller Function

A function which returns the content of the text label.

Examples

.addTextLabel(
  { name: 'artistname', label: 'Artist name', isLabelVisible: false },
  (deviceId) => 'Rude Tins'
 )

Returns

Object

DeviceBuilder

addImageUrl(configuration, controller)

Add an image to your custom element (for example to display the album cover of the current track). To avoid downloading and resizing large images on the Brain use these general guidelines:

  • Large images: 480x480px
  • Small: 100x100px

If you want to optimize for a specific target:

  • img url large: 454x454px
  • img url small: 100x100px
  • player: 480x480px
  • Mini player: 80x80px
  • list tile images: 215 x 215

These guidelines are specifically for the remote, a larger (maybe double) resolution might offer a good compromise for mobile devices.

Parameters

Name Type Description
configuration Object

JSON Configuration Object.

configuration.name String

identifier of this element.

configuration.label String

optional, visible label in the mobile app or on the NEEO Remote.

configuration.uri String

HTTP URI pointing to an image resource. JPG and PNG images are supported.

configuration.size String

image size in the ui, either 'small' or 'large'. The small image has the size of a button while the large image is a square image using full width of the client.

controller Function

A function which returns the address (URL) to the current image.

Examples

.addImageUrl(
  { name: 'albumcover', label: 'Cover for current album', size: 'small' },
  (deviceId) => 'http://imageurl'
)

Returns

Object

DeviceBuilder

addDirectory(configuration, controller)

Define additional device directories which can be browsed on the device

Parameters

Name Type Description
configuration Object

JSON Configuration Object.

configuration.name String

identifier of this element.

configuration.label String

optional, visible label in the mobile app or on the NEEO Remote.

configuration.role String

optional, specific role of the directory (supported roles are 'ROOT' or 'QUEUE')

controller Object

Controller callbacks Object

controller.getter Function

should return a list built by listBuilder so the App/NEEO Remote can display the browse result as a list. If the getter callback encounters an error, you can build a list with a 'ListInfoItem' to inform the user about the error

controller.action Function

will be called when an item is clicked

Examples

.addDirectory({
  name: 'DEVICE_PLAY_QUEUE_DIRECTORY',
  label: 'Queue',
  role: 'QUEUE'
}, {
  getter: (deviceId, params) => controller.browse(deviceId, params),
  action: (deviceId, params) => controller.listAction(deviceId, params),
})

Returns

Object

DeviceBuilder

addQueueDirectory(configuration, controller)

deprecated: this funciton is for backwards compatibility, use addDirectory() instead.

Parameters

Name Type Description
configuration Object

JSON Configuration Object, see addDirectory() for details.

controller Object

Controller callbacks Object, see addDirectory() for details.

Returns

Object

DeviceBuilder

addRootDirectory(configuration, controller)

deprecated: this funciton is for backwards compatibility, use addDirectory() instead.

Parameters

Name Type Description
configuration Object

JSON Configuration Object, see addDirectory() for details.

controller Object

Controller callbacks Object, see addDirectory() for details.

Returns

Object

DeviceBuilder

addCapability(capability)

Define additional device capabilities, currently supported capabilities (case sensitive):

  • "alwaysOn" – the device does not need to be powered on to be useable. You don't need to specify 'POWER ON' and 'POWER OFF' buttons and the device is not identified as "Not so smart device"
  • "bridgeDevice" – This capability is used after you add a new device, then you have the option to select "Add more from this bridge". For example Philips Hue - the discovered device (Gateway) supports multiple devices (Lamps).
  • "dynamicDevice" - if dynamicDeviceBuilderEnabled is enabled, the dynamically defined devices should set this capability
  • "addAnotherDevice" - This capability is used after you add a new device that uses discovery. It gives the option to select "Add another ${device name}"

Parameters

Name Type Description
capability String

Examples

.addCapability('alwaysOn')

Returns

object

DeviceBuilder

addPlayerWidget(controller)

This is a helper to implement a player widget, it's similar to the button groups because it defines multiple sub components (buttons, sensors, sliders, ...). The player can only be added for the MUSICPLAYER / MEDIAPLAYER / VOD device types.

PLEASE NOTE: this is a BETA feature, development is still in progress

The following components will be registered:

  • Buttons: PLAY, PLAY TOGGLE, PAUSE, VOLUME UP, VOLUME DOWN, MUTE TOGGLE, NEXT TRACK, PREVIOUS TRACK, SHUFFLE TOGGLE, REPEAT TOGGLE, CLEAR QUEUE
  • Directories: root, (optional) queue
  • Slider: VOLUME
  • Sensors: COVER_ART_SENSOR, TITLE_SENSOR, DESCRIPTION_SENSOR
  • Switches: PLAYING, MUTE, SHUFFLE, REPEAT

Note: it is also possible to add all the required components manually without using addPlayerWidget(), it can be more flexible for advanced use but it is more error prone.

Parameters

Name Type Description
controller PlayerWidget.Controller

Controller and player settings definition.

Examples

.addPlayerWidget({
  rootDirectory: {
    name: 'PLAYER_ROOT_DIRECTORY', // Optional: will default to ROOT_DIRECTORY
    label: 'My Library', // Optional: will default to ROOT
    controller: { getter: (deviceId, params) => ..., action: (deviceId, params) => ...},
  },
  // Optional:
  queueDirectory: {
    name: 'PLAYER_QUEUE_DIRECTORY', // Optional: will default to QUEUE_DIRECTORY
    label: 'Queue', // Optional: will default to QUEUE
    controller: { getter: (deviceId, params) => ..., action: (deviceId, params) => ...},
  },
  volumeController: { getter: (deviceId) => ..., setter: (deviceId, params) => ...},
  coverArtController: { getter: (deviceId) => ... },
  titleController: { getter: (deviceId) => ... },
  descriptionController: { getter: (deviceId) => ... },
  playingController: { getter: (deviceId) => ..., setter: (deviceId, params) => ...},
  muteController: { getter: (deviceId) => ..., setter: (deviceId, params) => ...},
  shuffleController: { getter: (deviceId) => ..., setter: (deviceId, params) => ...},
  repeatController: { getter: (deviceId) => ..., setter: (deviceId, params) => ...},
})
.addButtonHandler(((deviceid, name) => {
  // The button handler is needed, but still registered separately.
}));

Returns

DeviceBuilder

DeviceBuilder for chaining.

enableRegistration(options, controller)

Enable a registration or pairing step before discovery your device, for example if the device you want support needs to a pairing code to work. This function can be only defined once per device definition. enableRegistration can only be used when enableDiscovery is also used - for the user registration takes place before discovery

Parameters

Name Type Description
options object

An object which contains

options.type String

Defines the type of registration. The currently supported registration types are:

  • SECURITY_CODE
  • ACCOUNT
options.headerText String

This header will be displayed when the user starts the register process

options.description String

Text displayed during registration, should guide the user through how to find and enter the credentials needed.

controller Object

Controller callbacks Object

controller.register Function

Callback function which will be called when the user starts the registration. The callback has one parameter, credentials which either contains:

  • securityCode for the registration type of SECURITY_CODE
  • username, password for the registration type of ACCOUNT
controller.isRegistered Function

Callback function that must resolve true if valid credentials already exists, so the user does not need to register again. Note: if you always return false, the user can provide credentials each time a new device is added.

Examples

.enableRegistration(
  {
    type: 'SECURITY_CODE',
    headerText: 'DEVICE REGISTRATION',
    description: 'Please enter the pairing code of your device',
  },
  {
    register: (credentials) => myCredentials = credentials,
    isRegistered: () => booleanIfValidCredentialsAlreadyExists,
  }
)

Returns

DeviceBuilder

DeviceBuilder for chaining.

registerDeviceSubscriptionHandler(controller)

This allows tracking which devices are currently used on the Brain, it can be used to avoid sending Brain notifications for devices not added on the Brain, to remove registration credentials when the last device is removed, or to free up resources if no devices are used by the Brain.

Parameters

Name Type Description
controller Object

Controller callbacks Object

controller.deviceAdded Function

Callback function used when a device from this SDK is added on the Brain. Can be used to start listening to updates for that device. The callback has one parameter: deviceId: string identifying the device.

controller.deviceRemoved Function

Callback function used when a device from this SDK is removed from the Brain. Can be used to stop listening to updates for that device. The callback has one parameter: deviceId: string identifying the device.

controller.initializeDeviceList Function

Callback function used on startup once the SDK can reach the Brain, this is called on startup with the current subscriptions removing the need to save them in the SDK. The callback has one parameter: deviceIds: Array of deviceId string for all devices of this SDK currently on the Brain.

Examples

.registerDeviceSubscriptionHandler(
  {
    deviceAdded: (deviceId) => debug('device added', deviceId),
    deviceRemoved: (deviceId) => debug('device removed', deviceId),
    initializeDeviceList: (deviceIds) => debug('existing devices', deviceIds),
  }
)

Returns

DeviceBuilder

DeviceBuilder for chaining.

registerFavoriteHandlers(controller)

This allows a device that supports favorites (only TV, DVB or TUNER) to implement a custom handler, for example for channel "42", rather than 2 buttonHandler calls for "4" and "2", a single call with "42" will be made to the favoriteHandler.

Parameters

Name Type Description
controller FavoritesHandler.Controller

Controller callbacks Object

controller.execute Function

This callback is executed when a favorite channel is triggered on the Brain The callback has two parameters: deviceId: string identifying the device. favoriteId: string identifying the favorite channel to execute

Examples

.registerFavoriteHandlers(
  {
    execute: (deviceId, favoriteId) => debug('favorite executed', deviceId, favoriteId),
  }
)

Returns

DeviceBuilder

DeviceBuilder for chaining.

addDevice(id, clientobject, reachable)

Adds a new device state to the instance.

Parameters

Name Type Description
id integer

a unique key to identify an entry

clientobject object

any object which is linked to this unique identifier.

reachable boolean

this optional parameter defines if this device is currently reachable. Defaults to true.

Examples

  this.lifxClient.on('light-new', (lifx) => {
    debug('discovered new light', lifx.id);
    deviceState.addDevice(lifx.id, lifx);
  });

Returns

Void

getClientObjectIfReachable(id)

Gets the device state when the device is reachable. Used if you want to interact with the device state.

Parameters

Name Type Description
id integer

a unique key to identify an entry.

Examples

  const light = deviceState.getClientObjectIfReachable(deviceId);
  if (!light) {
    return BluePromise.reject(new Error('NOT_REACHABLE'));
  }
  return light.turnOn();

Returns

Object

The stored device state if the device is reachable OR undefined when device is NOT reachable.

getAllDevices()

Examples

  function discoverDevices() {
    const allDevices = deviceState.getAllDevices();
    return allDevices
      .map((deviceEntry) => {
        return {
          id: deviceEntry.id,
          name: deviceEntry.clientObject.label,
          reachable: deviceEntry.reachable
        };
      });
  };

Returns

Array

Returns all devices (client object, id, reachable state) this instance knows..

getCachePromise(id)

Fetching data from a network device is expensive. The cachePromise helps by caching the device state for a certain amount of time. The CachePromise wraps the expensive call - either the cached device state is returned or when the cache is empty or expired a new device state is fetched.

Parameters

Name Type Description
id integer

a unique key to identify an entry.

Examples

    getState(deviceId) {
      const light = this.deviceState.getClientObjectIfReachable(deviceId);

      function getLampState() {
        return new BluePromise((resolve, reject) => {
          light.getState((err, state) => {
            if (err) {
              reject(err);
            }
            resolve(state);
          });
        });
      }

      return deviceState
        .getCachePromise(deviceId)
        .getValue(getLampState);
    }

Returns

Object

A cachedPromise object, you can call the getValue function which either returns the cached state or fetches a new state.

updateReachable(id, reachable)

Update the reachability state (online/offline) of a device.

Parameters

Name Type Description
id integer

a unique key to identify an entry.

reachable boolean

this parameter defines if this device is online (true) or offline (false).

Examples

  this.lifxClient.on('light-online', (lifx) => {
    debug('light-online', lifx.id);
    deviceState.updateReachable(lifx.id, true);
  });
  this.lifxClient.on('light-offline', (lifx) => {
    debug('light-offline', lifx.id);
    deviceState.updateReachable(lifx.id, false);
  });

Returns

Void

registerStateUpdate(callback)

register callback function, that will be called with parameter id, clientObject when clientObject changed

Parameters

Name Type Description
callback function

function

Examples

  deviceState.registerStateUpdate((id, clientObject) => {
    console.log('state update for', id, clientObject);
  });

Returns

Void

getRecipesPowerState(NEEOBrain)

Deprecated: For backwards compatibility only, use getActiveRecipes() instead.

Parameters

Name Type Description
NEEOBrain Object String

to connect or an IP/hostname to connect

Examples

neeoapi.getRecipesPowerState(brain)
.then((poweredOnKeys) => {
  console.log('- Power state fetched, powered on recipes:', poweredOnKeys);
})

Returns

Promise

promise contains an array with powerKey's of the powered on recipes.

getActiveRecipes(NEEOBrain)

Get all powered on recipes of a NEEO Brain

Parameters

Name Type Description
NEEOBrain Object String

to connect or an IP/hostname to connect

Examples

neeoapi.getRecipesPowerState(brain)
.then((poweredOnKeys) => {
  console.log('- Power state fetched, powered on recipes:', poweredOnKeys);
})

Returns

Promise

promise contains an array with powerKey's of the powered on recipes.

getRecipes(NEEOBrain)

Get all existing recipes of a NEEO Brain

Parameters

Name Type Description
NEEOBrain Object String

to connect or an IP/hostname to connect

Returns

promise

promise contains an array of all recipes of the selected NEEO Brain.