Flic Hub SDK
JS API Documentation

Object types

Button Object Type

bdaddr String Device address of button
serialNumber String: Serial number
color String: Colour of the button (lowercase)
name String: The user assigned button name
activeDisconnect Boolean: The user has explicitly disconnected the button
connected Boolean: The connection to the button is currently established
ready Boolean: The connection is verified (see buttonReady)
batteryStatus Integer or Null: Battery level in percent (0-100), or null if unknown
firmwareVersion Integer or Null: Firmware version of button, or null if unknown
flicVersion Integer: Flic version (1 or 2)
uuid String: A 32 characters long hex string, unique for every button
key Integer: A 40 characters long hex string (only for Flic 2)

Buttons Module

The buttons module is responsible for adding and removing buttons and sending button events.

The module object is an instance of the class Buttons.

Buttons Class

Extends EventEmitter

Events

buttonAdded

Emitted when a button has successfully been added to the hub by any source.

Parameters:

buttonUpdated

Emitted when a button has successfully been updated by any source.

Parameters:

buttonDeleted

Emitted when a button has been removed.

Parameters:

buttonConnected

Emitted as soon as the button has made a physical connection to the hub (not yet fully verified).

Parameters:

buttonReady

Emitted when the connection has been verified. From now on button press events may be delivered.

Parameters:

buttonDisconnected

Emitted when the physical connection to the button has ended for any reason. This will happen either if the signal strength to the button is not good enough, if it lost synchronization with the button or if the button went into sleep mode.

Parameters:

buttonDown

Emitted when the button was pressed. If the button was disconnected while pressed and couldn’t connect within 15 seconds, the event is not emitted but lost. Use this to get the minimum latency.

Parameters:

buttonUp

Emitted when the button was released. If the button was disconnected while pressed and couldn’t connect within 15 seconds, the event is not emitted but lost.

Parameters:

buttonClickOrHold

For the use case to differentiate between click and hold, use this event type. Two clicks after each other will emit two events of this kind, compared to the events designed to handle double click. Only one of the boolean variables will be true.

If the button was disconnected while pressed and couldn’t connect within 15 seconds, the event is not emitted but lost.

Parameters:

buttonSingleOrDoubleClick

For the use case to differentiate between single and double click, use this event type. If the button is held down for a long time before released, this simply counts as a single click. Only one of the boolean variables will be true.

If the button was disconnected while pressed and couldn’t connect within 15 seconds, the event is not emitted but lost.

Parameters:

buttonSingleOrDoubleClickOrHold

For the use case to differentiate between all three event types. Only one of the boolean variables will be true.

If the button was disconnected while pressed and couldn’t connect within 15 seconds, the event is not emitted but lost.

Parameters:

Methods

getButtons()

Method that collects info about all buttons.

Returns Button[]: List of buttons
getButton(bdaddr)

Parameters:

Returns Button: The Button or null if not found
startScanWizard()

Method that starts a scan wizard and returns an object that is used for monitoring the progress and can be used for canceling.

Returns ScanWizard

importFlic2Pairings(pairings)

Parameters:

ScanWizard Class

Extends EventEmitter

Class that represents an ongoing scan wizard. Use the startScanWizard() method to create and start one.

Events

foundPrivateButton

Emitted when a private button is found. The user should be told to press and hold down the Flic button for at least 8 seconds. If the user does that, the button becomes a public button and the hub will then automatically connect to it.

foundPublicButton

Emitted when a public button is found. That is either a button new from factory (or factory reset) or a button that has been pressed and held down for at least 8 seconds during at most 30 seconds ago.

buttonConnect

Emitted when as soon as a connection to the previously found public button has been physically established (it must however first be verified before use).

complete

Emitted when the button has been successfully verified and is now ready to use. At this point the button is now also paired with the hub and the hub will listen to its events until it is explicitly disconnected (can currently only be done from within the Flic app) or removed. Use the Buttons class to get more info about the button. The buttonAdded event will be emitted right after this event is emitted.

fail

Emitted when the scan wizard has failed.

Parameters:

Methods

cancel()

Cancels the ongoing scan wizard. The fail event will be emitted with CancelledByUser as reason (unless it completes or fails before it gets cancelled).


IR Module

Module name: ir.

The IR module is used to record and play signals using the IR accessory. The module object is an instance of the class IR.

IR Class

Extends: EventEmitter

Events

recordComplete

Emitted when a record has completed.

Parameters:

Methods

record()

Starts recording IR signals. The IR receiver will be turned on and start listen for a signal. As soon as a signal is detected, it starts recording and will continue to record until there is a silence of 125 ms. There is otherwise no timeout currently for detecting the signal. The recorded signal will be delivered using the recordComplete event.

cancelRecord()

Cancels an ongoing recording. The recordComplete event will thus not be emitted.

play(arr, callback)

Plays a recorded signal.

The first element of the array should contain a carrier frequency in Hz (usually 38000 Hz). The following elements indicate in microseconds how long each pulse should be active or silent, alternating. The first of these represents how long time the IR LEDs are on, the second how long they are off, the third how long time on and so on. The last one must represent an on part. Therefore the length of the array must be even. If another play is started before a previous one has completed, it gets enqueued and starts as soon as the previous completes (max 100 enqueued signals). If the IR is currently recording, the play is also enqueued.

Parameters:


HTTP Module

Module name: http.

The HTTP module can be used to perform HTTP and HTTPS requests. The module object is an instance of the class HTTP.

HTTP Class

Methods

makeRequest(options[, callback])

This method performs an HTTP/HTTPS request. Note that if the request could be successfully completed, but the server responded with an HTTP error code (such as 500), that doesn’t count as an error, and hence the error callback parameter will be null. It only counts as an error if the request couldn’t be performed at all, or if the connection broke before it completed.

Parameters:


TCP Module

Module name: net.

This module API is based on Node.js’s net module.

net.Server Class

Extends: EventEmitter

This class is used to create a TCP server.

Events

close

Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended.

connection

Emitted when a new connection is made. `socket` is an instance of `net.Socket`.

Parameters:

error

Emitted when an error occurs in case of a call to `listen` fails. Unlike `net.Socket`, the `close` event will not be emitted directly following this event.

Parameters:

listening

Emitted when the server has been bound after calling `server.listen()`.

Methods

new net.Server([options][, connectionListener])

Creates a new TCP server.

If `allowHalfOpen` is set to `true`, when the other end of the socket sends a FIN packet, the server will only send a FIN packet back when `socket.end()` is explicitly called, until then the connection is half-closed (non-readable but still writable). See `end` event and RFC 1122 (section 4.2.2.13) for more information.

If `pauseOnConnect` is set to `true`, then the socket associated with each incoming connection will be paused, and no data will be read from its handle. To begin reading data from a paused socket, call `socket.resume()`.

Parameters:

Returns net.Server

address()

Returns the bound address of the server as reported by the operating system (useful to find which port was assigned when getting an OS-assigned address).

`server.address()` returns `null` before a successful `listen` has been called or after calling `server.close()`.

Returns Object or Null:

close([callback])

Immediately stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a `close` event. The optional `callback` will be called once the `close` event occurs. Unlike that event, it will be called with an `Error` as its only argument if the server was not open when it was closed.

getConnections(callback)

Asynchronously get the number of concurrent connections on the server.

Parameters:

Returns net.Server: The socket itself

listen(options[, callback])

Start a TCP server listening for connections on the given `port` and `host`.

If `port` is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using `server.address().port` after the `listening` event has been emitted.

If `host` is omitted, the server will accept connections on the unspecified IPv4 address (0.0.0.0).

All servers are set to `SO_REUSEADDR` (see socket(7) for details).

The `server.listen()` method can be called again if and only if there was an error during the first `server.listen()` call or `server.close()` has been called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown.

If the OS returned an error when setting up the listening, an `error` event will be emitted. One of the most common errors raised is `EADDRINUSE`. This happens when another server is already listening on the requested port. One way to handle this would be to retry after a certain amount of time.

Parameters:

Returns net.Server

listen([port[, host[, backlog]]][, callback])

Alternative way of calling the above function without using an options object.

Properties

listening Boolean

Indicates whether or not the server is listening for connections.

net.Socket Class

Extends: EventEmitter

This class is an abstraction of a TCP socket.

`net.Socket` can be created by the user and used directly to interact with a server. For example, it is returned by `net.createConnection()`, so the user can use it to talk to the server.

It can also be created internally by a `net.Server` and passed to the user when a connection is received. It is passed to the listeners of a `connection` event emitted on a `net.Server`, so the user can use it to interact with the client.

Events

close

Emitted once the socket is fully closed. The argument `hadError` is a boolean which says if the socket was closed due to a transmission error.

Parameters:

connect

Emitted when a socket connection is successfully established.

data

Emitted when data is received. The argument `data` will be a `Buffer` or `string`. By default the raw bytes are given in a `Buffer`, but if `socket.setEncoding()` has been called a string will be given. In case of UTF-8 encoding and a character that spans multiple bytes, and the incoming data is split in the middle of a character, the socket object will internally buffer the non-terminated bytes until more data is received.

The data will be lost if there is no listener when a `Socket` emits a `data` event.

Parameters:

drain

Emitted when the write buffer (in user space) becomes empty. Can be used to throttle uploads.

See also: the return values of `socket.write()`.

end

Emitted when the other end of the socket sends a FIN packet, thus ending the readable side of the socket.

By default (`allowHalfOpen` is false) the socket will send a FIN packet back and destroy its file descriptor once it has written out its pending write queue. However, if `allowHalfOpen` is set to `true`, the socket will not automatically `end()` its writable side, allowing the user to write arbitrary amounts of data. The user must call `end()` explicitly to close the connection (i.e. sending a FIN packet back).

error

Emitted when an error occurs. The `close` event will be called directly following this event.

This will be emitted either as a result of dns lookup failure, a connection establishment error, or when the socket is unexpectedly closed.

Parameters:

lookup

Emitted after resolving the host name but before connecting.

Parameters:

ready

Emitted when a socket is ready to be used.

Triggered immediately after `connect`.

Methods

address()

For an open socket, returns the locally bound address of the socket as reported by the operating system.

Returns Object | Null:

new net.Socket([options])

Creates a new socket object.

Parameters:

Returns: net.Socket

connect(options[, connectListener])

Initiate a connection on a given socket.

This function is asynchronous. When the connection is established, the `connect` event will be emitted. If there is a problem connecting, instead of a `connect` event, an `error` event will be emitted with the error passed to the `error` listener (followed by a `close` event).

Only call this method when the socket is closed.

Parameters:

Returns: net.Socket The socket itself

connect(port[, host][, connectListener)

Alternative way of calling the above function without using an options object.

destroy([exception])

Ensures that no more I/O activity happens on this socket. Only necessary in case of errors (parse error or so), to abruptly close the socket.

Parameters:


UDP/Datagram Module

Module name: dgram

This module is based on Node.js’s dgram module. The UDP/Datagram module is an instance of the class Dgram.

Dgram Class

Methods

createSocket(options[, callback])

Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram messages. When `address` and `port` are not passed to `socket.bind()` the method will bind the socket to the "all interfaces" address on a random port. The bound address and port can be retrieved using `socket.address().address` and `socket.address().port`.

Parameters:

Returns: dgram.Socket

createSocket(type[, callback])

See above.

Parameters:

Returns: dgram.Socket

Socket Class

Extends: EventEmitter

Encapsulates the datagram functionality.

New instances of `dgram.Socket` are created using `dgram.createSocket()`. The `new` keyword is not to be used to create `dgram.Socket` instances.

Methods

addMembership(multicastAddress[, multicastInterface])

Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not specified, the operating system will choose one interface and will add membership to it. To add membership to every available interface, call `addMembership` multiple times, once per interface.

Parameters:

address()

Returns an object containing the address information for a socket. For UDP sockets, this object will contain `address`, `family` and `port` properties.

Returns: Object

bind(options[, callback])

For UDP sockets, causes the `dgram.Socket` to listen for datagram messages on a named `port` and optional `address`. If `port` is not specified or is `0`, the operating system will attempt to bind to a random port. If `address` is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a `’listening’` event is emitted and the optional `callback` function is called.

Specifying both a `’listening’` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very useful.

If binding fails, an `Error` will be thrown.

Parameters:

bind([port][, address][, callback])

See above.

Parameters:

close([callback])

Close the underlying socket and stop listening for data on it. If a callback is provided, it is added as a listener for the `’close’` event.

Parameters:

dropMembership(multicastAddress[, multicastInterface])

Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the kernel when the socket is closed or the process terminates, so most apps will never have reason to call this.

If `multicastInterface` is not specified, the operating system will attempt to drop membership on all valid interfaces.

Parameters:

send(msg[, offset, length], port[, address][, callback])

Broadcasts a datagram on the socket. The destination `port` and `address` must be specified.

The `msg` argument contains the message to be sent. Depending on its type, different behavior can apply. If `msg` is a `Buffer` or `Uint8Array`, the `offset` and `length` specify the offset within the `Buffer` where the message begins and the number of bytes in the message, respectively. If `msg` is a `String`, then it is automatically converted to a `Buffer` with `utf8` encoding. With messages that contain multi-byte characters, `offset` and `length` will be calculated with respect to byte length and not the character position. If `msg` is an array, `offset` and `length` must not be specified.

The `address` argument is a string. If the value of `address` is a host name, DNS will be used to resolve the address of the host. If `address` is not provided or otherwise falsy, “127.0.0.1” will be used by default.

If the socket has not been previously bound with a call to `bind`, the socket is assigned a random port number and is bound to the “all interfaces” address (“0.0.0.0”).

An optional `callback` function may be specified to as a way of reporting DNS errors or for determining when it is safe to reuse the `buf` object.

The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be passed as the first argument to the `callback`. If a `callback` is not given, the error is emitted as an `’error’` event on the `socket` object.

Offset and length are optional but both must be set if either are used. They are supported only when the first argument is a `Buffer` or `Uint8Array`.

Parameters:

setBroadcast(flag)

Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP packets may be sent to a local interface’s broadcast address.

Parameters:

setMulticastInterface(multicastInterface)

Sets the default outgoing multicast interface of the socket to a chosen interface or back to system interface selection. The `multicastInterface` must be a valid string representation of an IP from the socket’s family.

This should be the IP configured for the desired physical interface. All packets sent to multicast on the socket will be sent on the interface determined by the most recent successful use of this call.

A call on a socket that is not ready to send or no longer open may throw a Not running `Error`.

If `multicastInterface` can not be parsed into an IP then EINVAL `System Error` is thrown.

If `multicastInterface` is a valid address but does not match any interface, or if the address does not match the family then a `System Error` such as `EADDRNOTAVAIL` or `EPROTONOSUP` is thrown.

The ANY address (“0.0.0.0”) can be used to return control of the socket’s default outgoing interface to the system for future multicast packets.

Parameters:

setMulticastLoopback(flag)

Sets or clears `IP_MULTICAST_LOOP` socket option. When set to `true`, multicast packets will also be received on the local interface.

Parameters:

setMulticastTTL(ttl)

Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for “Time to Live”, in this context it specifies the number of IP hops that a packet is allowed to travel through, specifically for multicast traffic. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.

Parameters:

setTTL(ttl)

Sets the `IP_TTL` socket option. While TTL generally stands for “Time to Live”, in this context it specifies the number of IP hops that a packet is allowed to travel through. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. Changing TTL values is typically done for network probes or when multicasting.

Parameters:

Events

close

The `close` event is emitted after a socket is closed with `close()`. Once triggered, no new `message` events will be emitted on this socket.

error

The `error` event is emitted whenever any error occurs. The event handler function is passed a single `Error` object.

Parameters:

listening

The `listening` event is emitted once the `dgram.Socket` is addressable and can receive data. This happens either explicitly with `socket.bind()` or implicitly the first time data is sent using `socket.send()`. Until the `dgram.Socket` is listening, the underlying system resources do not exist and calls such as `socket.address()` and `socket.setTTL()` will fail.

message

The `message` event is emitted when a new datagram is available on the socket. The event handler function is passed two arguments: `msg` and `rinfo`.

Parameters:


Datastore Module

Module name: datastore

The Datastore module can be used to store string values identified by a key (string) in persistent storage. The storage is individual for each package. The Datastore module is an instance of the class Datastore.

Datastore Class

Methods

put(key, value[, callback])

Parameters:

get(key, callback)

Parameters:


Network Module

Module name: network

The Network module can be used to configure the hub’s Wi-Fi and to obtain status about the wired and wireless Ethernet interfaces. The module object is an instance of the class Network.

The hub maintains a list of saved networks. While not connected to any network, it regularly scans the surrounding area for a network matching one in the list of saved networks and automatically tries to connect if it discovers one. As long as being connected, it will not try to connect to other networks in the list.

Network Class

Methods

scan(callback)

This method performs a scan which usually only takes a few seconds and then delivers the result to the callback.

Parameters:

connect(network, callback)

This method connects to a network. If the hub is already connected to some network, this network is temporarily disconnected. If the connection could be established to the new network, it is saved in the list and remains connected. If the connection cannot be established within a short time frame, the operation is aborted and the hub goes back to regularly trying to connect to networks in the saved list as usual.

If the network provided is already exists in the list but is currently not connected to, the same as above applies but instead of storing a duplicate the options are just updated.

Note that the WRONG_PASSWORD is based on heuristics so WRONG_PASSWORD and TIMEOUT should be treated interchangeably since it has proven to be hard to differentiate between a wrong password and a timeout. Wrong password can hence mean that the password was correct but it timed out for another reason.

Parameters:

cancelConnect()

Cancels an ongoing connect attempt (see above).

addNetwork(network)

Adds a network to the hub’s internal list of networks. See the general description above how this list works. The network parameter is an object of the same format as in the connect method.

removeNetwork(network)

Removes a network from the hub’s internal list of networks.

Parameters:

wpsPushButton(callback)

This method initiates a WPS push button attempt. Once this method has been called the user has 120 seconds to also press the WPS push button on a nearby router (or if the user first pressed WPS button on the router, this method should be called within 120 seconds). When that occurs, the router will send over its SSID and WPA key to the hub.

Parameters:

wpsCancel()

Cancels an ongoing WPS push button attempts

getNetworks()

Returns a copy of the hub’s internal list of networks as an array (WiFiNetwork[]). See the scan method callback for the format of every WiFiNetwork.

getState()

Returns the current connectivity state.

Returns: