/openhab-js

openHAB Javascript Library

Primary LanguageJavaScriptEclipse Public License 2.0EPL-2.0

Build Status

openHAB Javascript Library

This library aims to be a fairly high-level ES6 library to support automation in openHAB. It provides convenient access to common openHAB functionality within rules including items, things, action, logging and more.

This library is included by default in the openHAB JavaScript binding

Contents

Requirements

Installation

Default Installation

  • Install the openHAB JavaScript binding, a version of this library will be automatically installed and available to all javascript rules by default.

Custom Installation

  • Ensure you have the correct path created mkdir -p $OPENHAB_CONF/automation/lib/javascript/personal/node_modules
  • Go to the javascript personal lib directory: cd $OPENHAB_CONF/automation/lib/javascript/personal/node_modules
  • Run npm i openhab (you may need to install npm)

Usage

This library provides an easy to use API for common automation activities that interact with items, things, activities and other openHAB concepts.

Basic Usage

Using the openHAB UI, first create a new rule and set a trigger condition OpenHAB Rule Configuration

Then select "Add Action" and then select "ECMAScript". This will bring up a empty script editor where you can enter your javascript. OpenHAB Rule Script

This library is automatically imported, so you can directly access items, actions and more in your logic.

For example, turning a light on:

items.getItem("KitchenLight").sendCommand("ON");
console.log("Kitchen Light State", items.getItem("KitchenLight").state);

Sending a notification

actions.NotificationAction.sendNotification("romeo@montague.org", "Balcony door is open");

Querying the status of a thing

const thingStatusInfo = actions.Things.getThingStatusInfo("zwave:serial_zstick:512");
console.log("Thing status",thingStatusInfo.getStatus());

See API for a complete list of functionality

Advanced Usage

Scripting may be done via the openHAB UI or by creating scripts in $OPENHAB_CONF/automation/jsr223/javascript/personal.

For file based scripts this API provides two ways of writing rules, a fluent Rule Builder API and a declarative syntax using JSRule.

By default the JS Scripting binding will export objects in the current scope, so no additional importing is necessary. This behavior can be configured on or off in the binding's configuration options.

The injected import is roughly equivalent to:

const {rules, items, things, log, triggers, actions, metadata, osgi} = require('openhab')

Rule Builder API

The Rule Builder provides a convenient API to write rules in a high-level, readable style using a builder pattern. This is particularly useful when writing rules using files as opposed to using the UI which provides its own rule creation interface.

For a declarative style creation of rules, see using the JSRule API.

Rules are started by calling rules.when() and can chain together triggers, conditions and operations in the following pattern:

rules.when().triggerType()...if().conditionType().then().operationType()...build(name,description);

A simple example of this would look like:

rules.when().item("F1_Light").changed().then().send("changed").toItem("F2_Light").build("My Rule", "My First Rule");

Operations and conditions can also optionally take functions:

rules.when().item("F1_light").changed().then(event => {
console.log(event);
}).build("Test Rule", "My Test Rule");

see Examples for further patterns

Rule Builder Triggers

  • channel(channelName) Specifies a channel event as a source for the rule to fire.
    • .triggered(event) Trigger on a specific event name
  • cron(cronExpression) Specifies a cron schedule for the rule to fire.
  • item(itemName) Specifies an item as the source of changes to trigger a rule.
    • .for(duration)
    • .from(state)
    • .to(state)
    • .fromOff()
    • .toOn()
    • .receivedCommand()
    • .receivedUpdate()
  • memberOf(groupName)
    • .for(duration)
    • .from(state)
    • .to(state)
    • .fromOff()
    • .toOn()
    • .receivedCommand()
    • .receivedUpdate()
  • system()
    • .ruleEngineStarted()
    • .rulesLoaded()
    • .startupComplete()
    • .thingsInitialized()
    • .userInterfacesStarted()
    • .startLevel(level)
  • thing(thingName)
    • changed()
    • updated()
    • from(state)
    • to(state)

Additionally all the above triggers have the following functions:

Rule Builder Conditions

  • stateOfItem(state)

Rule Builder Operations

  • build(name, description)
  • copyAndSendState()
  • copyState()
  • inGroup(groupName)
  • postIt()
  • postUpdate(state)
  • send(command)
  • sendIt()
  • sendOff()
  • sendOn()
  • sendToggle()

Rule Builder Examples

//turn on the kitchen light at SUNSET
rules.when().timeOfDay("SUNSET").then().sendOn().toItem("KitchenLight").build("Sunset Rule","turn on the kitchen light
at SUNSET");

//turn off the kitchen light at 9PM
rules.when().cron("0 0 21 * * ?").then().sendOff().toItem("KitchenLight").build("9PM Rule", "turn off the kitchen light
at 9PM");

//set the colour of the hall light to pink at 9PM
rules.when().cron("0 0 21 * * ?").then().send("300,100,100").toItem("HallLight").build("Pink Rule", "set the colour of
the hall light to pink at 9PM");

//when the switch S1 status changes to ON, then turn on the HallLight
rules.when().item('S1').changed().toOn().then(sendOn().toItem('HallLight')).build("S1 Rule");

//when the HallLight colour changes pink, if the function fn returns true, then toggle the state of the OutsideLight
rules.when().item('HallLight').changed().to("300,100,100").if(fn).then().sendToggle().toItem('OutsideLight').build();

//and some rules which can be toggled by the items created in the 'gRules' Group:

//when the HallLight receives a command, send the same command to the KitchenLight
rules.when(true).item('HallLight').receivedCommand().then().sendIt().toItem('KitchenLight').build("Hall Light", "");

//when the HallLight is updated to ON, make sure that BedroomLight1 is set to the same state as the BedroomLight2
rules.when(true).item('HallLight').receivedUpdate().then().copyState().fromItem('BedroomLight1').toItem('BedroomLight2').build();

//when the BedroomLight1 is changed, run a custom function
rules.when(true).item('BedroomLight1').changed().then(() => {
// do stuff
}.build();

JSRule API

JSRules provides a simple, declarative syntax for defining rules

rules.JSRule({
name: "Lights ON at 5pm",
description: "Light will turn on when it's 5:00pm",
triggers: [triggers.GenericCronTrigger("0 0 17 * * ?")],
execute: data => {
items.getItem("AllLights").sendCommand("ON");
}
});

See triggers in the API documentation for a full list of all triggers.

Logging

By default the JS Scripting binding supports console logging like console.log() and console.debug() to the openHAB default log. Additionally scripts may create their own native openHAB logs using the log namespace

//this is imported by default, shown here for clarity only
let log = require('openhab');

let logger = log('my_logger');

//prints "Hello World!"
logger.debug("Hello {}!", "world");

API

Classes

RuleBuilder

Creates rules in a fluent style.

TriggerBuilder

Builder for rule Triggers

ConditionBuilder

Condition that wraps a function to determine whether if passes

OperationBuilder

Operation to execute as part of a rule

Objects

log : object

Log namespace. This namespace provides loggers to log messages to the openHAB Log.

items : object
actions : object

Actions namespace. This namespace provides access to openHAB actions. All available actions can be accessed as direct properties of this object (via their simple class name).

triggers : object

Triggers namespace. This namespace allows creation of openHAB rule triggers.

rules : object

Rules namespace. This namespace allows creation of openHAB rules.

cache : object

Shared cache namespace. This namespace provides a default cache that can be use to set and retrieve objects that will be persisted between reloads of scripts.


RuleBuilder

Creates rules in a fluent style.


new RuleBuilder(toggleable)

Param Type Description
toggleable boolean if this builder is toggleable


ruleBuilder.when() ⇒ TriggerBuilder

Specifies when the rule should occur. Will create a standard rule.

Returns: TriggerBuilder - rule builder


TriggerBuilder

Builder for rule Triggers


triggerBuilder.channel(channelName) ⇒ ChannelTriggerConfig

Specifies a channel event as a source for the rule to fire.

Returns: ChannelTriggerConfig - the trigger config

Param Type Description
channelName String the name of the channel


triggerBuilder.cron(cronExpression) ⇒ CronTriggerConfig

Specifies a cron schedule for the rule to fire.

Returns: CronTriggerConfig - the trigger config

Param Type Description
cronExpression String the cron expression


triggerBuilder.item(itemName) ⇒ ItemTriggerConfig

Specifies an item as the source of changes to trigger a rule.

Returns: ItemTriggerConfig - the trigger config

Param Type Description
itemName String the name of the item


triggerBuilder.memberOf(groupName) ⇒ ItemTriggerConfig

Specifies an group member as the source of changes to trigger a rule.

Returns: ItemTriggerConfig - the trigger config

Param Type Description
groupName String the name of the group


triggerBuilder.thing(thingUID) ⇒ ThingTriggerConfig

Specifies a Thing status event as a source for the rule to fire.

Returns: ThingTriggerConfig - the trigger config

Param Type Description
thingUID String the UID of the Thing


triggerBuilder.system() ⇒ SystemTriggerConfig

Specifies a system event as a source for the rule to fire.

Returns: SystemTriggerConfig - the trigger config


TriggerBuilder.TriggerConf

{RuleBuilder} RuleBuilder triggers


triggerConf.or() ⇒ TriggerBuilder

Add an additional Trigger


triggerConf.then(function) ⇒ OperationBuilder

Move to the rule operations

Param Type Description
function * the optional function to execute


triggerConf.if(function) ⇒ ConditionBuilder

Move to the rule condition

Param Type Description
function * the optional function to execute


TriggerBuilder.ChannelTriggerConfig ⇐ TriggerConf

Extends: TriggerConf


channelTriggerConfig.to(eventName) ⇒ ChannelTriggerConfig

trigger a specific event name

Param Type
eventName string


channelTriggerConfig.triggered(eventName) ⇒ ChannelTriggerConfig

trigger a specific event name

Param Type
eventName string


channelTriggerConfig.or() ⇒ TriggerBuilder

Add an additional Trigger

Overrides: or


channelTriggerConfig.then(function) ⇒ OperationBuilder

Move to the rule operations

Overrides: then

Param Type Description
function * the optional function to execute


channelTriggerConfig.if(function) ⇒ ConditionBuilder

Move to the rule condition

Overrides: if

Param Type Description
function * the optional function to execute


TriggerBuilder.CronTriggerConfig ⇐ TriggerConf

Cron based trigger

Extends: TriggerConf


cronTriggerConfig.or() ⇒ TriggerBuilder

Add an additional Trigger

Overrides: or


cronTriggerConfig.then(function) ⇒ OperationBuilder

Move to the rule operations

Overrides: then

Param Type Description
function * the optional function to execute


cronTriggerConfig.if(function) ⇒ ConditionBuilder

Move to the rule condition

Overrides: if

Param Type Description
function * the optional function to execute


TriggerBuilder.ItemTriggerConfig ⇐ TriggerConf

item based trigger

Extends: TriggerConf


itemTriggerConfig.to(value) ⇒ ItemTriggerConfig

Item to

Param Type Description
value * this item should be triggered to


itemTriggerConfig.from(value) ⇒ ItemTriggerConfig

Item from

Param Type Description
value * this items should be triggered from


itemTriggerConfig.toOff() ⇒ ItemTriggerConfig

item changed to OFF


itemTriggerConfig.toOn() ⇒ ItemTriggerConfig

item changed to ON


itemTriggerConfig.receivedCommand() ⇒ ItemTriggerConfig

item recieved command


itemTriggerConfig.receivedUpdate() ⇒ ItemTriggerConfig

item recieved update


itemTriggerConfig.changed() ⇒ ItemTriggerConfig

item changed state


itemTriggerConfig.for(timespan) ⇒ ItemTriggerConfig

For timespan

Param Type
timespan *


itemTriggerConfig.or() ⇒ TriggerBuilder

Add an additional Trigger

Overrides: or


itemTriggerConfig.then(function) ⇒ OperationBuilder

Move to the rule operations

Overrides: then

Param Type Description
function * the optional function to execute


itemTriggerConfig.if(function) ⇒ ConditionBuilder

Move to the rule condition

Overrides: if

Param Type Description
function * the optional function to execute


TriggerBuilder.ThingTriggerConfig ⇐ TriggerConf

Thing based trigger

Extends: TriggerConf


thingTriggerConfig.changed() ⇒ ThingTriggerConfig

thing changed


thingTriggerConfig.updated() ⇒ ThingTriggerConfig

thing updates


thingTriggerConfig.from() ⇒ ThingTriggerConfig

thing status changed from


thingTriggerConfig.to() ⇒ ThingTriggerConfig

thing status changed to


thingTriggerConfig.or() ⇒ TriggerBuilder

Add an additional Trigger

Overrides: or


thingTriggerConfig.then(function) ⇒ OperationBuilder

Move to the rule operations

Overrides: then

Param Type Description
function * the optional function to execute


thingTriggerConfig.if(function) ⇒ ConditionBuilder

Move to the rule condition

Overrides: if

Param Type Description
function * the optional function to execute


TriggerBuilder.SystemTriggerConfig ⇐ TriggerConf

System based trigger

Extends: TriggerConf


systemTriggerConfig.rulesLoaded() ⇒ SystemTriggerConfig

System trigger


systemTriggerConfig.ruleEngineStarted() ⇒ SystemTriggerConfig

System trigger


systemTriggerConfig.userInterfacesStarted() ⇒ SystemTriggerConfig

System trigger


systemTriggerConfig.thingsInitialized() ⇒ SystemTriggerConfig

System trigger


systemTriggerConfig.startupComplete() ⇒ SystemTriggerConfig

System trigger


systemTriggerConfig.startLevel() ⇒ SystemTriggerConfig

System trigger


systemTriggerConfig.or() ⇒ TriggerBuilder

Add an additional Trigger

Overrides: or


systemTriggerConfig.then(function) ⇒ OperationBuilder

Move to the rule operations

Overrides: then

Param Type Description
function * the optional function to execute


systemTriggerConfig.if(function) ⇒ ConditionBuilder

Move to the rule condition

Overrides: if

Param Type Description
function * the optional function to execute


ConditionBuilder

Condition that wraps a function to determine whether if passes


conditionBuilder.then(function) ⇒ OperationBuilder

Move to the rule operations

Param Type Description
function * the optional function to execute


conditionBuilder.stateOfItem(itemName) ⇒ ItemStateConditionConf

Condition of an item in determining whether to process rule.

Returns: ItemStateConditionConf - the operation config

Param Type Description
itemName String the name of the item to assess the state


ConditionBuilder.ConditionConf

{RuleBuilder} RuleBuilder conditions


conditionConf.then(function) ⇒

Returns: ConditionBuilder

Param Type Description
function * an optional function


ConditionBuilder.FunctionConditionConf ⇐ ConditionConf

Condition that wraps a function to determine whether if passes

Extends: ConditionConf


new FunctionConditionConf(fn)

Creates a new function condition. Don't call directly.

Param Type Description
fn * callback which determines whether the condition passes


functionConditionConf.then(function) ⇒

Overrides: then
Returns: ConditionBuilder

Param Type Description
function * an optional function


ConditionBuilder.ItemStateConditionConf ⇐ ConditionConf

Condition that wraps a function to determine whether if passes

Extends: ConditionConf


itemStateConditionConf.is(value) ⇒ this

Checks if item state is equal to vlaue

Param Type
value *


itemStateConditionConf.in(...values) ⇒ this

Checks if item state matches any array of values

Param Type
...values any


itemStateConditionConf.then(function) ⇒

Overrides: then
Returns: ConditionBuilder

Param Type Description
function * an optional function


OperationBuilder

Operation to execute as part of a rule


operationBuilder.build(name, description)

Build this rule

Param Type Description
name string of the rules
description string of the rule


operationBuilder.inGroup(group) ⇒ OperationBuilder

Specify the rule group for this rule

Returns: OperationBuilder - this

Param Type Description
group string the group this rule belongs to.


operationBuilder.send(command) ⇒ SendCommandOrUpdateOperation

Specifies that a command should be sent as a result of this rule firing.

Returns: SendCommandOrUpdateOperation - the operation

Param Type Description
command String the command to send


operationBuilder.postUpdate(update) ⇒ SendCommandOrUpdateOperation

Specifies that an update should be posted as a result of this rule firing.

Returns: SendCommandOrUpdateOperation - the operation

Param Type Description
update String the update to send


operationBuilder.sendOn() ⇒ SendCommandOrUpdateOperation

Specifies the a command 'ON' should be sent as a result of this rule firing.

Returns: SendCommandOrUpdateOperation - the operation


operationBuilder.sendOff() ⇒ SendCommandOrUpdateOperation

Specifies the a command 'OFF' should be sent as a result of this rule firing.

Returns: SendCommandOrUpdateOperation - the operation


operationBuilder.sendToggle() ⇒ ToggleOperation

Specifies a command should be sent to toggle the state of the target object as a result of this rule firing.

Returns: ToggleOperation - the operation


operationBuilder.sendIt() ⇒ SendCommandOrUpdateOperation

Specifies a command should be forwarded to the state of the target object as a result of this rule firing. This relies on the trigger being the result of a command itself.

Returns: SendCommandOrUpdateOperation - the operation


operationBuilder.postIt() ⇒ SendCommandOrUpdateOperation

Specifies a command state should be posted to the target object as a result of this rule firing. This relies on the trigger being the result of a command itself.

Returns: SendCommandOrUpdateOperation - the operation


operationBuilder.copyState() ⇒ CopyStateOperation

Copies the state from one item to another. Can be used to proxy item state. State is updated, not sent as a command.

Returns: CopyStateOperation - the operation config


operationBuilder.copyAndSendState() ⇒ CopyStateOperation

Sends the state from one item to another. Can be used to proxy item state. State is sent as a command.

Returns: CopyStateOperation - the operation config


OperationBuilder.OperationConfig

{RuleBuilder} RuleBuilder triggers


operationConfig.inGroup(group) ⇒ OperationBuilder

Specify the rule group for this rule

Returns: OperationBuilder - this

Param Type Description
group string the group this rule belongs to.


operationConfig.build(name, description)

Build this rule

Param Type Description
name string of the rules
description string of the rule


OperationBuilder.CopyStateOperation ⇐ OperationConfig

Copies state from one item to another item

Extends: OperationConfig


new CopyStateOperation(send)

Creates a new operation. Don't use constructor directly.

Param Type Description
send Boolean whether to send (or post update) the state


copyStateOperation.fromItem(item_name) ⇒ CopyStateOperation

Sets the item to copy the state from

Returns: CopyStateOperation - this

Param Type Description
item_name String the item to copy state from


copyStateOperation.toItem(item_name) ⇒ CopyStateOperation

Sets the item to copy the state to

Returns: CopyStateOperation - this

Param Type Description
item_name String the item to copy state to


copyStateOperation.and() ⇒ CopyStateOperation

Appends another operation to execute when the rule fires

Returns: CopyStateOperation - this


copyStateOperation.inGroup(group) ⇒ OperationBuilder

Specify the rule group for this rule

Overrides: inGroup
Returns: OperationBuilder - this

Param Type Description
group string the group this rule belongs to.


copyStateOperation.build(name, description)

Build this rule

Overrides: build

Param Type Description
name string of the rules
description string of the rule


OperationBuilder.SendCommandOrUpdateOperation ⇐ OperationConfig

Sends a command or update to an item

Extends: OperationConfig


sendCommandOrUpdateOperation.toItems(itemsOrNames) ⇒ SendCommandOrUpdateOperation

Send command to multiple items

Returns: SendCommandOrUpdateOperation - this

Param Type Description
itemsOrNames * the items to send a command to


sendCommandOrUpdateOperation.toItem(itemOrName) ⇒ SendCommandOrUpdateOperation

Send command to an item

Returns: SendCommandOrUpdateOperation - this

Param Type Description
itemOrName * the item to send a command to


sendCommandOrUpdateOperation.and(next) ⇒ SendCommandOrUpdateOperation

Send another command

Returns: SendCommandOrUpdateOperation - this

Param Type
next *


sendCommandOrUpdateOperation.inGroup(group) ⇒ OperationBuilder

Specify the rule group for this rule

Overrides: inGroup
Returns: OperationBuilder - this

Param Type Description
group string the group this rule belongs to.


sendCommandOrUpdateOperation.build(name, description)

Build this rule

Overrides: build

Param Type Description
name string of the rules
description string of the rule


OperationBuilder.ToggleOperation ⇐ OperationConfig

Toggles the state of an item

Extends: OperationConfig


toggleOperation.doToggle() ⇒ SendCommandOrUpdateOperation

Toggle the state of an item

Returns: SendCommandOrUpdateOperation - this


toggleOperation.inGroup(group) ⇒ OperationBuilder

Specify the rule group for this rule

Overrides: inGroup
Returns: OperationBuilder - this

Param Type Description
group string the group this rule belongs to.


toggleOperation.build(name, description)

Build this rule

Overrides: build

Param Type Description
name string of the rules
description string of the rule


OperationBuilder.TimingItemStateOperation ⇐ OperationConfig

Timing Item state

Extends: OperationConfig


timingItemStateOperation.inGroup(group) ⇒ OperationBuilder

Specify the rule group for this rule

Overrides: inGroup
Returns: OperationBuilder - this

Param Type Description
group string the group this rule belongs to.


timingItemStateOperation.build(name, description)

Build this rule

Overrides: build

Param Type Description
name string of the rules
description string of the rule


log : object

Log namespace. This namespace provides loggers to log messages to the openHAB Log.

Example (Basic logging)

let log = require('openhab').log('my_logger');
log.info("Hello World!")


log.Logger

Logger class. A named logger providing the ability to log formatted messages.


new Logger(_name, _listener)

Creates a new logger. Don't use directly, use log on module.

Param Type Description
_name String the name of the logger. Will be prefixed by LOGGER_PREFIX
_listener * a callback to receive logging calls. Can be used to send calls elsewhere, such as escalate errors.


logger.listener ⇒ *

The listener function attached to this logger.

Returns: * - the listener function


logger.name ⇒ String

The name of this logger

Returns: String - the logger name


logger.error()

Logs at ERROR level.

See: atLevel


logger.warn()

Logs at ERROR level.

See: atLevel


logger.info()

Logs at INFO level.

See: atLevel


logger.debug()

Logs at DEBUG level.

See: atLevel


logger.trace()

Logs at TRACE level.

See: atLevel


logger.atLevel(level, msg, [...objects])

Logs a message at the supplied level. The message may include placeholders {} which will be substituted into the message string only if the message is actually logged.

Param Type Description
level String The level at which to log, such as 'INFO', or 'DEBUG'
msg String, Error the message to log, possibly with object placeholders
[...objects] Array.<Object> the objects to substitute into the log message

Example

log.atLevel('INFO', 'The widget was created as {}', widget);


log.default

Creates a logger.

See: Logger

Param Type Description
name string the name of the logger
[_listener] * an optional listener to process log events.


log.LOGGER_PREFIX

Logger prefix


items : object


items.OHItem

Class representing an openHAB Item


new OHItem(rawItem)

Create an OHItem, wrapping a native Java openHAB Item. Don't use this constructor, instead call getItem.

Param Type Description
rawItem HostItem Java Item from Host


ohItem.type ⇒ String

The type of the item: the Simple (without package) name of the Java item type, such as 'Switch'.

Returns: String - the type


ohItem.name ⇒ String

The name of the item.

Returns: String - the name


ohItem.label ⇒ String

The label attached to the item

Returns: String - the label


ohItem.state ⇒ String

The state of the item, as a string.

Returns: String - the item's state


ohItem.rawState ⇒ HostState

The raw state of the item, as a java object.

Returns: HostState - the item's state


ohItem.members ⇒ Array.<OHItem>

Members / children / direct descendents of the current group item (as returned by 'getMembers()'). Must be a group item.

Returns: Array.<OHItem> - member items


ohItem.descendents ⇒ Array.<OHItem>

All descendents of the current group item (as returned by 'getAllMembers()'). Must be a group item.

Returns: Array.<OHItem> - all descendent items


ohItem.isUninitialized ⇒

Whether this item is initialized.

Returns: true iff the item has not been initialized


ohItem.tags

Gets the tags from this item


ohItem.getMetadataValue(namespace) ⇒ String

Gets metadata values for this item.

Returns: String - the metadata associated with this item and namespace

Param Type Description
namespace String The namespace for the metadata to retreive


ohItem.updateMetadataValue(namespace, value) ⇒ String

Updates metadata values for this item.

Returns: String - the updated value

Param Type Description
namespace String The namespace for the metadata to update
value String the value to update the metadata to


ohItem.upsertMetadataValue(namespace, value) ⇒ Boolean

Inserts or updates metadata values for this item.

Returns: Boolean - true iff a new value was inserted

Param Type Description
namespace String The namespace for the metadata to update
value String the value to update the metadata to


ohItem.updateMetadataValues(namespaceToValues)

Updates metadata values for this item.

Param Type Description
namespaceToValues Map A map of namespaces to values to update


ohItem.sendCommand(value)

Sends a command to the item

See

  • sendCommandIfDifferent
  • postUpdate
Param Type Description
value String, HostState the value of the command to send, such as 'ON'


ohItem.sendCommandIfDifferent(value) ⇒ Boolean

Sends a command to the item, but only if the current state is not what is being sent. Note

Returns: Boolean - true if the command was sent, false otherwise
See: sendCommand

Param Type Description
value String, HostState the value of the command to send, such as 'ON'


ohItem.postUpdate(value)

Posts an update to the item

See: sendCommand

Param Type Description
value String, HostState the value of the command to send, such as 'ON'


ohItem.addGroups(...groupNamesOrItems)

Adds groups to this item

Param Type Description
...groupNamesOrItems Array.<(String|OHItem)> names of the groups (or the group items themselves)


ohItem.removeGroups(...groupNamesOrItems)

Removes groups from this item

Param Type Description
...groupNamesOrItems Array.<(String|OHItem)> names of the groups (or the group items themselves)


ohItem.addTags(...tagNames)

Adds tags to this item

Param Type Description
...tagNames Array.<String> names of the tags to add


ohItem.removeTags(...tagNames)

Removes tags from this item

Param Type Description
...tagNames Array.<String> names of the tags to remove


items.DYNAMIC_ITEM_TAG

Tag value to be attached to all dynamically created items.


items.createItem(itemName, [itemType], [category], [groups], [label], [tags], [giBaseType], [groupFunction], [itemMetadata])

Creates a new item within OpenHab. This item is not registered with any provider.

Note that all items created this way have an additional tag attached, for simpler retrieval later. This tag is created with the value DYNAMIC_ITEM_TAG.

Param Type Description
itemName String Item name for the Item to create
[itemType] String the type of the Item
[category] String the category (icon) for the Item
[groups] Array.<String> an array of groups the Item is a member of
[label] String the label for the Item
[tags] Array.<String> an array of tags for the Item
[giBaseType] HostItem the group Item base type for the Item
[groupFunction] HostGroupFunction the group function used by the Item
[itemMetadata] Map a map of metadata to set on the item


items.addItem(itemName, [itemType], [category], [groups], [label], [tags], [giBaseType], [groupFunction])

Creates a new item within OpenHab. This item will persist regardless of the lifecycle of the script creating it.

Note that all items created this way have an additional tag attached, for simpler retrieval later. This tag is created with the value DYNAMIC_ITEM_TAG.

Param Type Description
itemName String Item name for the Item to create
[itemType] String the type of the Item
[category] String the category (icon) for the Item
[groups] Array.<String> an array of groups the Item is a member of
[label] String the label for the Item
[tags] Array.<String> an array of tags for the Item
[giBaseType] HostItem the group Item base type for the Item
[groupFunction] HostGroupFunction the group function used by the Item


items.removeItem(itemOrItemName) ⇒ Boolean

Removes an item from OpenHab. The item is removed immediately and cannot be recoved.

Returns: Boolean - true iff the item is actually removed

Param Type Description
itemOrItemName String, HostItem the item to remove


items.replaceItem(itemName, [itemType], [category], [groups], [label], [tags], [giBaseType], [groupFunction])

Replaces (upserts) an item. If an item exists with the same name, it will be removed and a new item with the supplied parameters will be created in it's place. If an item does not exist with this name, a new item will be created with the supplied parameters.

This function can be useful in scripts which create a static set of items which may need updating either periodically, during startup or even during development of the script. Using fixed item names will ensure that the items remain up-to-date, but won't fail with issues related to duplicate items.

Param Type Description
itemName String Item name for the Item to create
[itemType] String the type of the Item
[category] String the category (icon) for the Item
[groups] Array.<String> an array of groups the Item is a member of
[label] String the label for the Item
[tags] Array.<String> an array of tags for the Item
[giBaseType] HostItem the group Item base type for the Item
[groupFunction] HostGroupFunction the group function used by the Item


items.getItem(name, nullIfMissing) ⇒ OHItem

Gets an openHAB Item.

Returns: OHItem - the item

Param Type Default Description
name String the name of the item
nullIfMissing String false whether to return null if the item cannot be found (default is to throw an exception)


items.getItemsByTag(...tagNames) ⇒ Array.<OHItem>

Gets all openHAB Items with a specific tag.

Returns: Array.<OHItem> - the items with a tag that is included in the passed tags

Param Type Description
...tagNames Array.<String> an array of tags to match against


items.safeItemName(s) ⇒ String

Helper function to ensure an item name is valid. All invalid characters are replaced with an underscore.

Returns: String - a valid item name

Param Type Description
s String the name to make value


actions : object

Actions namespace. This namespace provides access to openHAB actions. All available actions can be accessed as direct properties of this object (via their simple class name).

Example (Sends a broadcast notification)

let { actions } = require('openhab');
actions.NotificationAction.sendBroadcastNotification("Hello World!")

Example (Sends a PushSafer notification)

let { actions } = require('openhab');
 actions.Pushsafer.pushsafer("<your pushsafer api key>", "<message>", "<message title>", "", "", "", "")


triggers : object

Triggers namespace. This namespace allows creation of openHAB rule triggers.


triggers.ChannelEventTrigger

Creates a trigger that fires upon specific events in a channel.

Param Type Description
channel String the name of the channel
event String the name of the event to listen for
[triggerName] String the name of the trigger to create

Example

ChannelEventTrigger('astro:sun:local:rise#event', 'START')


triggers.ItemStateChangeTrigger

Creates a trigger that fires upon an item changing state.

Param Type Description
itemName String the name of the item to monitor for change
[oldState] String the previous state of the item
[newState] String the new state of the item
[triggerName] String the name of the trigger to create

Example

ItemStateChangeTrigger('my_item', 'OFF', 'ON')


triggers.ItemStateUpdateTrigger

Creates a trigger that fires upon an item receiving a state update. Note that the item does not need to change state.

Param Type Description
itemName String the name of the item to monitor for change
[state] String the new state of the item
[triggerName] String the name of the trigger to create

Example

ItemStateUpdateTrigger('my_item', 'OFF')


triggers.ItemCommandTrigger

Creates a trigger that fires upon an item receiving a command. Note that the item does not need to change state.

Param Type Description
itemName String the name of the item to monitor for change
[command] String the command received
[triggerName] String the name of the trigger to create

Example

ItemCommandTrigger('my_item', 'OFF')


triggers.GroupStateChangeTrigger

Creates a trigger that fires upon a member of a group changing state.

Param Type Description
groupName String the name of the group to monitor for change
[oldState] String the previous state of the group
[newState] String the new state of the group
[triggerName] String the name of the trigger to create

Example

GroupStateChangeTrigger('my_group', 'OFF', 'ON')


triggers.GroupStateUpdateTrigger

Creates a trigger that fires upon a member of a group receiving a state update. Note that group item does not need to change state.

Param Type Description
groupName String the name of the group to monitor for change
[state] String the new state of the group
[triggerName] String the name of the trigger to create

Example

GroupStateUpdateTrigger('my_group', 'OFF')


triggers.GroupCommandTrigger

Creates a trigger that fires upon a member of a group receiving a command. Note that the group does not need to change state.

Param Type Description
groupName String the name of the group to monitor for change
[command] String the command received
[triggerName] String the name of the trigger to create

Example

GroupCommandTrigger('my_group', 'OFF')


triggers.ThingStatusUpdateTrigger

Creates a trigger that fires upon an Thing status updating

Param Type Description
thingUID String the name of the thing to monitor for a status updating
[status] String the optional status to monitor for
[triggerName] String the name of the trigger to create

Example

ThingStatusUpdateTrigger('some:thing:uuid','OFFLINE')


triggers.ThingStatusChangeTrigger

Creates a trigger that fires upon an Thing status changing

Param Type Description
thingUID String the name of the thing to monitor for a status change
[status] String the optional status to monitor for
[previousStatus] String the optional previous state to monitor from
[triggerName] String the optional name of the trigger to create

Example

ThingStatusChangeTrigger('some:thing:uuid','ONLINE','OFFLINE')


triggers.SystemStartlevelTrigger

Creates a trigger that fires if a given start level is reached by the system

Param Type Description
startlevel String the system start level to be triggered on
[triggerName] String the name of the trigger to create

Example

SystemStartlevelTrigger(40)  //Rules loaded
...
SystemStartlevelTrigger(50)  //Rule engine started
...
SystemStartlevelTrigger(70)  //User interfaces started
...
SystemStartlevelTrigger(80)  //Things initialized
...
SystemStartlevelTrigger(100) //Startup Complete


triggers.GenericCronTrigger

Creates a trigger that fires on a cron schedule. The supplied cron expression defines when the trigger will fire.

Param Type Description
expression String the cron expression defining the triggering schedule

Example

GenericCronTrigger('0 30 16 * * ? *')


triggers.TimeOfDayTrigger

Creates a trigger that fires daily at a specific time. The supplied time defines when the trigger will fire.

Param Type Description
time String the time expression defining the triggering schedule

Example

TimeOfDayTrigger('19:00')


rules : object

Rules namespace. This namespace allows creation of openHAB rules.


rules.JSRule(ruleConfig) ⇒ HostRule

Creates a rule. The rule will be created and immediately available.

Returns: HostRule - the created rule

Param Type Description
ruleConfig Object The rule config describing the rule
ruleConfig.name String the name of the rule
ruleConfig.description String a description of the rule
ruleConfig.execute * callback that will be called when the rule fires
ruleConfig.triggers HostTrigger, Array.<HostTrigger> triggers which will define when to fire the rule

Example

import { rules, triggers } = require('openhab');

rules.JSRule({
 name: "my_new_rule",
 description": "this rule swizzles the swallows",
 triggers: triggers.GenericCronTrigger("0 30 16 * * ? *"),
 execute: triggerConfig => { //do stuff }
});


rules.SwitchableJSRule(ruleConfig) ⇒ HostRule

Creates a rule, with an associated SwitchItem that can be used to toggle the rule's enabled state. The rule will be created and immediately available.

Returns: HostRule - the created rule

Param Type Description
ruleConfig Object The rule config describing the rule
ruleConfig.name String the name of the rule
ruleConfig.description String a description of the rule
ruleConfig.execute * callback that will be called when the rule fires
ruleConfig.triggers Array.<HostTrigger> triggers which will define when to fire the rule
ruleConfig.ruleGroup String the name of the rule group to use.


rules.when(withToggle) ⇒ TriggerBuilder

Create a new {RuleBuilder} chain for easily creating rules.

Returns: TriggerBuilder - rule builder

Param Type Description
withToggle boolean rule can be toggled on or off (optional)

Example (Basic rule)

rules.when().item("F1_Light").changed().then().send("changed").toItem("F2_Light").build("My Rule", "My First Rule");

Example (Rule with function)

rules.when().item("F1_light").changed().to("100").then(event => {
  console.log(event)
 }).build("Test Rule", "My Test Rule");


cache : object

Shared cache namespace. This namespace provides a default cache that can be use to set and retrieve objects that will be persisted between reloads of scripts.


cache.get(key, [defaultSupplier]) ⇒ * | null

Returns the value to which the specified key is mapped

Returns: * | null - the current object for the supplied key, a default value if defaultSupplier is provided, or null

Param Type Description
key string the key whose associated value is to be returned
[defaultSupplier] function if the specified key is not already associated with a value, this function will return a default value

Example (Get a previously set value with a default value (times = 0))

let counter = cache.get("counter", () => ({ "times": 0 }));
console.log("Count",counter.times++);

Example (Get a previously set object)

let counter = cache.get("counter");
if(counter == null){
     counter = {times: 0};
     cache.put("counter", counter);
}
console.log("Count",counter.times++);


cache.put(key, value) ⇒ * | null

Associates the specified value with the specified key

Returns: * | null - the previous value associated with null, or null if there was no mapping for key

Param Type Description
key string key with which the specified value is to be associated
value * value value to be associated with the specified key


cache.remove(key) ⇒ * | null

Removes the mapping for a key from this map if it is present

Returns: * | null - the previous value associated with key or null if there was no mapping for key

Param Type Description
key string key whose mapping is to be removed from the map