Scripting inside the dSS

Bind your script to a highlevel event

The dSS has the ability to run scripts inside it using the JavaScript interpreter SpiderMonkey. While it doesn't support running a script using a dedicated api, scripts can be run as a result to a "highlevel event".

The following excerpt is from data/subscriptions.xml. It shows how to run a script (data/initialize.js) on startup.

  <subscription event-name="model_ready" handler-name="javascript">
    <parameter>
      <parameter name="filename1">data/initialize.js</parameter>
    </parameter>
  </subscription>

It is also possible to execute several script files in the same context, the order of script execution is defined by the index number that is appended to the filename parameter, it allows to have 1-255 scripts in the same context, "holes" in the enumeration are not allowed. The following examples show how to run two scripts in the same context for a given event:

  <subscription event-name="model_ready" handler-name="javascript">
    <parameter>
      <parameter name="filename1">data/funclibrary.js</parameter>
      <parameter name="filename2">data/initialize.js</parameter>
    </parameter>
  </subscription>
  <subscription event-name="callScene" handler-name="javascript">
    <parameter>
      <parameter name="filename1">data/scripts/userlib.js</parameter>
      <parameter name="filename2">data/scripts/callscene-user-action.js</parameter>
      <parameter name="script_id">callscene-user-action</parameter>
    </parameter>
  </subscription>

Event handlers

If a script gets invoked by a event handler the following variables are made available:

  • raisedEvent.name
  • raisedEvent.parameter.paramname
  • raisedEvent.source.one-of-the-following
    set, dsid, zoneID, groupID, isApartment, isZone, isDevice
  • subscription.name

Global functions

  • print
    print(arg1, ..., argn)
    Prints arg1 ... argn to the dss logfile. The log entries are prefixed by JS:
  • setTimeout
    setTimeout(func, timeoutMS)
    Calls the function func after at least timeoutMS milliseconds have elapsed. Note that the script will need to be run completely for the callback to happen.

Logger

This class provides a convenient way to write log messages to different files. The logfiles are written to the default dss js log directory, this cannot be changed.

  • constructor
    var L = new Logger(logFileName);
    creates a new log file
  • logln
    logln(message)
    writes the message to the logfile

Event

Event classes allow to create and send new events to the dSS. To execute an Event in a later point in time there are two ways with different event subclasses, the TimedEvent and TimedICalEvent.

Functions

  • constructor
    Event Event(name [, parameters])
    The name is mandantory and identifies the event. The parameter list is optional.
  • raise
    raise()
    Raises the event.

Example

   var evt = new Event("testevent", {
     zoneID: raisedEvent.source.zoneID,
     groupID: raisedEvent.source.groupID, 
     sceneID: raisedEvent.parameter.sceneID
   });
   evt.raise();

TimedEvent

To execute the Event in a later point in time the TimedEvent class has an additional time parameter. For example the string "+10" will raise the event after 10 seconds.

The event object is stored in the property tree, where it can be cancelled by deleting the node represting the TimedEvent. The node is stored in /system/EventInterpreter/ScheduledEvents/ID. A TimedEvent returns its ID when the raise() function is executed.

Functions

  • constructor
    TimedEvent TimedEvent(name, time [, parameters])
    Name and time are mandatory. The time argument is a relative time duration in seconds and must be given as a string (e.g. "+5"). The event is executed after this duration.
  • raise
    num raise();
    Raises the event and returns the ID.

TimedICalEvent

To execute an event periodically or at defined date and time the TimedICalEvent uses an iCal recurrence rule and an iCal start time according to RFC 2445.

The event object is stored in the property tree, where it can be cancelled by deleting the node represting the TimedICalEvent. The node is stored in /system/EventInterpreter/ScheduledEvents/ID. A TimedICalEvent returns its ID when the raise() function is executed.

  • constructor
    TimedICalEvent TimedICalEvent(name, iCalStartTime, iCalRRule [, parameters])
    Name, iCalStartTime and iCalRRule are mandatory. Similar to the TimedEvent it is executed, but an absolute point in time can be specified with the iCalRRule and the iCalStartTime.
  • raise
    num raise();
    Raises the event and returns the ID.

Example

   var timerEvent = new TimedICalEvent("timer", "20120101T161500", "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR", {
      timername: 'Test1',
      action_type: 'execute'
   });
   var timedID = timerEvent.raise();

Apartment

Apartment and data model functions in the global namespace.

Static functions

  • getName
    string getName()
    Returns the name of the apartment.
  • setName
    setName(name)
    Sets the name of the apartment.
  • getDevices
    Set getDevices();
    Returns a Set that contains all devices of the apartment.
  • getZones
    array getZones();
    Returns an array that contains all zones of the apartment.
  • getZoneByID
    Zone getZoneByID(ZoneID)
    Returns the zone object with the give numerical id, if present in the apartment.
  • getDSMeters
    array getDSMeters();
    Returns an array that contains all dSMeters of the apartment.
  • getDSMeterByDSID
    @dSMeter getDSMeterByDSID(MeterDSID)*
    Returns the dSMeter object with the give dSID, if present in the apartment.
  • getConsumption
    num getConsumption()
    Returns the current sum of all dSMeter power measurements.
  • getEnergyMeterValue
    num getEnergyMeterValue()
    Returns the sum of all dSMeter energy meter values.

Global Constants

  • Scene.User1
  • Scene.User2
  • Scene.User3
  • Scene.User4
  • Scene.Min
  • Scene.Max
  • Scene.DeepOff
  • Scene.Off
  • Scene.StandBy
  • Scene.Bell
  • Scene.Panic
  • Scene.Alarm
  • Scene.Inc
  • Scene.Dec
  • Scene.Present
  • Scene.Absent
  • Scene.Sleeping
  • Scene.WakeUp

Devices

The following properties can be read on device objects:

  • className: === "Device"
  • dsid: the unique dSID of this device
  • name: the user name for this device
  • zoneID: the zoneID in which the device is
  • circuitID: the dSID of the dSMeter to which the device is attached
  • functionID: the system defined functionality bitfield
  • revisionID: the firmware revision
  • productID: the product revision
  • isPresent: the present flag signalling if a device is currently accessible
  • lastCalledScene: the last scene command that was sent to this device

A device object supports the following methods:

  • callScene
    callScene(sceneNr)
  • saveScene
    saveScene(sceneNr)
  • undoScene
    undoScene(sceneNr)
  • turnOn
  • turnOff
  • blink
  • setValue
    setValue(value)
  • increaseValue
  • decreaseValue
  • getConfig
    num getConfig(configClass, configIndex)
  • getConfigWord
    num getConfigWord(configClass, configIndex)
  • setConfig
    setConfig(configClass, configIndex, configValue)
  • getOutputValue
    num getOutputValue(outvalIndex)
  • setOutputValue
    setOutputValue(outvalIndex, value)
  • getSensorValue
    num getSensorValue(sensorIndex)
  • getSensorType
    num getSensorType(sensorIndex)
  • getPropertyNode
    prop getPropertyNode();
    Returns the property tree object of this device.

Sets

  • perform
    perform(function)
    Calls function for every device contained in the set.
  • length
    -> resulttype is a integer
  • combine
    -> resulttype is a set-object
  • remove
    -> resulttype is a set-object
  • byName
    -> resulttype is a device-object
  • byDSID
    -> resulttype is a device-object
  • byFunctionID
    -> resulttype is a set-object
  • byZone
    -> resulttype is a set-object
  • byDSMeter
    -> resulttype is a set-object
  • byGroup
    -> resulttype is a set-object
  • byPresence
    -> resulttype is a set-object
  • byTag
    -> resulttype is a set-object

dSMeter

The following properties can be read on dSMeter objects:

  • className: === "dSMeter"
  • dsid: the unique dSID of this device
  • name: the user name for this device

A dSMeter object supports the following methods:

  • getPowerConsumption
    getPowerConsumption()
  • getEnergyMeterValue
    getEnergyMeterValue()
  • getCachedPowerConsumption
    getCachedPowerConsumption()
  • getCachedEnergyMeterValue
    getCachedEnergyMeterValue()
  • getPropertyNode
    prop getPropertyNode();
    Returns the property tree object of this dSMeter.

Zone

The following properties can be read on Zone objects:

  • className: === "Zone"
  • id: the numerical id of this zone
  • name: the user defined name for this zone

A Zone object supports the following methods:

  • getDevices
    array getDevices()
    Returns the list of device objects in this zone.
  • callScene
    @callScene(groupID, sceneID [, forceFlag])
    Executes the scene call in the zone according to group and scene id. The forceFlag set to 'true' enables local priority override.
  • getPowerConsumption
    Returns the current consumption as sum of all active devices in this zone. | This will mostly return 0 as long as single device consumption values are not available.
  • pushSensorValue
    pushSensorValue(SourceDSID, sensorType, sensorValue)
  • getPropertyNode
    prop getPropertyNode();
    Returns the property tree object of this Zone.

Metering

This class allows to access the metering data.

Static functions

  • getResultions
    array getResolutions()
    Returns an array with the available sample rates and different series. The resolution field gives the interval time in seconds, the type field is either "energy", "energyDelta" or "consumption".
  • getSeries
    array getSeries()
    Returns the stored series.
  • getValues
    array getValues(dsid, type, resolution, unit, startTime, endTime, numValues)
    Returns an array with the stored metering values, each parameter selecting a subset of the metering series: * possible type values are "energy", "energyDelty" or "consumption" * the unit is either "Wh" (default) or "Ws" * the startTime and endTime allow to define a window with unix timestamps (both may be 0 to effectively disable the start or endtime function) * the numValues parameters give the maximum number of requested metering samples

Property

Static functions

  • Property.setProperty
    setProperty(propPath, value)
    Sets the property at propPath to value
  • Property.getProperty
    value getProperty(propPath)
    Returns the value at propPath, for example: Property.getProperty("/system/uptime")
  • Property.setListener
    listenerID setListener(propPath, func)
    Sets up a listener and calls func on any change to propPath or its children.
  • Property.removeListener
    removeListener(listenerID)
    Removes a previously installed listener.
  • Property.hasFlag
    bvalue Property.hasFlag(propPath, flagName)
    Returns true if the given flag is set.
  • Property.setFlag
    Property.setFlag(propPath, flagName, value)
    Sets the value (boolean) of the flag.
  • Property.getNode
    nodeObj Property.getNode(path)
    Returns a property-object
  • Property.store
    Property.store()
    Persists the properties of the private subtree
  • Property.load
    Property.load()
    Loads previously persisted properties
    Note: execute this only on the running event as otherwise, properties changed from GUIs (which will note be stored persistently until proper dSS shutdown) will be discarded.

Property object methods

  • getValue
    value getValue
    Returns the value of the property
  • setValue
    setValue(value)
    Sets the value of the property to value
  • setListener
    callbackIdent setListener(callbackFunction)
    Registers a callback that gets called if the property changes
  • removeListener
    removeListener(callbackIdent)
    Removes a previously registered callback
  • getChild
    nodeObj getChild(relativePathToNode)
    Returns a child-node or null if it doesn't exist
  • getChildren
    arrayOfChildren getChildren()
    Returns an array of children, an empty one if none present
  • getParent
    nodeObj getParent()
    Returns the parent or null
  • removeChild
    bool removeChild([nodeObj|string])
    Returns true if the child has been removed
  • Property.hasFlag
    bvalue hasFlag(flagName)
    Returns true if the given flag is set.
  • Property.setFlag
    setFlag(flagName, value)
    Sets the value (boolean) of the flag.
  • getName
    string getName()
    Returns the name of the property object.
  • getPath
    string getPath()
    Returns the full path of the property object.

Curl [available since 1.5.0]

The curl classes easycurl and easylist allow to use the easycurl interface from libcurl.

The easycurl class performs the network operations. Example scripts and a http wrapper can be found in the source code folder ./examples/scripts/.

  • constructor
    easycurl easyscurl()
  • setopt
    setopt(easycurl.option, value)
    Set a libcurl option, for CURLopt reference see here.
  • perform
    string perform()
    Executes the network operation. The return string contains the answer from the peer.
  • getinfo
    string getinfo(easycurl.info)
    Return informational text about the actions performed, for CURLinfo reference see here.
  • version
    string version()
    Return the curl library version.

The easycurl class provides three callback handlers for operation:

  • header
    c.header = function(string) {}
  • write
    c.write = function(string) {}
  • debug
    c.debug = function debug(itype, data) {}

The easylist class stores options arrays for the libcurl options.

  • constructor
    easylist easylist()
  • append
    append(option)
  • toArray
    array toArray()

TcpSocket

Class that allows communicating to other hosts using TCP. All calls are asynchronous.

Functions

  • connect
    connect(host, port[, function(success)])
    Opens a connection to host:port. When finished the optional function gets called with a boolean argument indicating success.
  • send
    send(data[, function(bytesSent)])
    Sends data over an already open socket. When finished the optional function gets called with the number of bytes actually sent (-1 on error).
  • receive
    receive(numberOfBytes[,function(data)])
    Receives data over an already open socket. When finished the optional function gets called with the data received ("" on error).
  • receiveLine
    receiveLine(numberOfBytes[,function(data),delimiter])
    Receives data over an already open socket, until \r\n, or the optional delimiter character is reached. When finished the optional function gets called with the data received ("" on error).
  • close
    close()
    Closes the socket.
  • bind
    bind(port[, function(success)])
    Opens a server-socket on the given port. When finished the optional function gets called with a boolean argument indicating success.
  • accept
    accept(function(socket))
    Waits for a connection on a previously bound port. The function provided will be called if somebody connects.

Static functions

  • sendTo
    sendTo(host, port, data[, function(success)])
    Opens a connection to host:port and sends data to it. When finished the optional function gets called with a boolean argument indicating success.