Skip to content

How to create a module

Gregory Sitnin edited this page Oct 22, 2013 · 5 revisions

Automation modules are intended to incapsulate functionality of some kind, bind to the Event Bus to emit and response to events. Also only a module is able to spawn one or more virtual device instances.

Every module has a folder named after the module itself under the modules/ folder in the ZAutomation's code folder (typically: automation).

For example: the module named "BatteryPolling" resides in "modules/BatteryPolling" folder.

Minimal module consists of two files:

  • index.js which should setup a _module variable which should be a reference to the module's class module.json` which defines module's meta
  • `information and default settings

Step 1. Provide an AutomationModule subclass

// Important: constructor SHOULD always be successful
function BatteryPolling (id, controller) {
    // Always call superconstructor first
    BatteryPolling.super_.call(this, id, controller);

    // Perform internal structures initialization...
}

inherits(BatteryPolling, AutomationModule);

_module = BatteryPolling;

Special function named inherits is a routine which creates a super_ property thich is reference to the superclass and does other prototypal inheritance preparations.

The last line of code exposes BatteryPolling class as a _module variable which will be requested at module's loading time.

Step 2. Define .init function

// Init is a designated initializer and will be called once for each module's instance
// at the end of the ZAutomation startup process
BatteryPolling.prototype.init = function (config) {
    // Always call superclass' init first
    BatteryPolling.super_.prototype.init.call(this, config);

    // Subscribe to events, setup timers, instantiate virtual devices, register widgets and so on...

    this.batIds = this.scanForBatteries();
}

Step 3. Define other routines

BatteryPolling.prototype.scanForBatteries = function () {
    var self = this;
    return Object.keys(this.controller.devices).filter(function (vdevId) {
        var vdev = self.controller.devices[vdevId];
        return vdev.deviceType === "probe" && vdev.deviceSubType === "battery";
    });
}

Every AutomationModule has a controller property which refers to the AutomationController's singleton.

In the example above, this reference used to get the virtual devices list and interate through it in case of searching for the virtual devices which type/subtype is "probe" and "battery" accordingly.

Clone this wiki locally