1.2.2 • Published 5 years ago

mqtt-scripts v1.2.2

Weekly downloads
6
License
MIT
Repository
github
Last release
5 years ago

mqtt-scripts

mqtt-smarthome NPM version dependencies Status Build Status Coverage Status XO code style License

mqtt-scripts is a Node.js based script runner for use in mqtt based smart home environments.

It's intentended to be used as the "logic layer" in your smart home, and offers a zero-boilerplate, straight forward scripting environment.

It follows the mqtt-smarthome architecture. Mqtt-scripts could be seen as something like "Node-RED without GUI"

Getting started

Prerequisites: mqtt-scripts needs Node.js >= 6.0.

  • Install mqtt-scripts globally:

sudo npm install -g mqtt-scripts

  • Create a folder from where mqtt-scripts will load the scripts:

mkdir -p /opt/mqtt-smarthome/scripts

  • Create a folder to install node modules that can be used in the scripts:

mkdir /opt/mqtt-smarthome/scripts/node_modules
(You can then just use npm install in the directory /opt/mqtt-smarthome/scripts)

  • Put some files in you script dir:
echo "log.info('my first script!')" > /opt/mqtt-smarthome/scripts/test1.js
echo "log.info 'get ma a coffee' > /opt/mqtt-smarthome/scripts/test1.coffee
  • Start mqtt-scripts

mqtt-scripts -d /opt/mqtt-smarthome/scripts

Command Line Options

If you're running multiple instances of mqtt-scripts you have to decide which one should handle variables and disable the variables on all other instances with the --disable-variable option.

Script Examples

Use hm2mqtt and hue2mqtt to control a hue lamp with a homematic remote control

link('hm//RC4:1/PRESS_CONT', 'hue//lights/Hobbyraum/bri_inc', -16);

subscribe('hm//RC4:2/PRESS_CONT', function () {
    if (!getValue('hue//lights/Hobbyraum')) {
        setValue('hue//lights/Hobbyraum', 1);
    } else {
        setValue('hue//lights/Hobbyraum/bri_inc', 16);
    }
});

link('hm//RC4:1/PRESS_SHORT', 'hue//lights/Hobbyraum', 0);
link('hm//RC4:2/PRESS_SHORT', 'hue//lights/Hobbyraum', 254);
link('hm//RC4:3/PRESS_CONT', 'hue//lights/Hobbyraum/ct_inc', -16);
link('hm//RC4:4/PRESS_CONT', 'hue//lights/Hobbyraum/ct_inc', 16);
link('hm//RC4:3/PRESS_SHORT', 'hue//lights/Hobbyraum/ct', 153);
link('hm//RC4:4/PRESS_SHORT', 'hue//lights/Hobbyraum/ct', 500);

retrieve fuel prices from tankerkoenig

var request =   require('request');
var cred =      require('./lib/credentials.js');

var url = 'https://creativecommons.tankerkoenig.de/json/detail.php';

var tankstellen = {
    'OMV': 'cb1f0588-d517-40f0-8ce3-3edadebea40d',
    'Shell': '4267c196-eea1-47be-96b7-d790b2fbd17a'
};

schedule('0/12 * * * *', function () {
    for (var topic in tankstellen) {
        getData(topic, tankstellen[topic]);
    }
});

function getData(topic, id) {
    request.get(url + '?id=' + id + '&apikey=' + cred.tankerkoenig.apikey, function (err, res) {
        if (err) {
            log.error(err);
            return;
        }
        var data = JSON.parse(res.body).station;
        setValue('$Tankstelle/' + topic + '/Diesel',    data.diesel);
        setValue('$Tankstelle/' + topic + '/E5',        data.e5);
        setValue('$Tankstelle/' + topic + '/Offen',     data.isOpen);
    });
}

Send a variables state changes to Pushover

var cred = require('./lib/credentials.js');

var pushoverNotifications = require('pushover-notifications');

var push = new pushoverNotifications( {
    user: cred.pushover.user,
    token: cred.pushover.token,
    onerror: function (error) {
        log.error(error);
    }
});

function pushover(msg) {
    if (typeof msg !== 'object' || typeof msg.message !== 'string') msg = {message: '' + msg};
    msg.title = msg.title || "Smart Home";
    msg.priority = msg.priority || 0;
    msg.device = msg.device || 'iphone5';
    push.send(msg, function(err, result) {
        if (err) {
            log.error(err);
        }
    });
}

subscribe('$Anwesenheit', {change: true}, function () {
    pushover({
        title:'Anwesenheit',
        message: getProp($Anwesenheit, 'logic_textual'),
        priority: -1
    });
});

API

Classes

Functions

Typedefs

log

Log to stdout/stderr. Messages are prefixed with a timestamp and the calling scripts path.

Kind: global class

log.debug()

Log a debug message

Kind: static method of log

Type
*

log.info()

Log an info message

Kind: static method of log

Type
*

log.warn()

Log a warning message

Kind: static method of log

Type
*

log.error()

Log an error message

Kind: static method of log

Type
*

subscribe(topic, options, callback)

Subscribe to MQTT topic(s)

Kind: global function

ParamTypeDescription
topicstring | Array.<string>topic or array of topics to subscribe
optionsObject | string | functionOptions object or as shorthand to options.condition a function or string
options.shiftnumberdelay execution in seconds. Has to be positive
options.randomnumberrandom delay execution in seconds. Has to be positive
options.changebooleanif set to true callback is only called if val changed
options.retainbooleanif set to true callback is also called on retained messages
options.conditionstring | functionconditional function or condition string
callbacksubscribeCallback

schedule(pattern, options, callback)

Schedule recurring and one-shot events

Kind: global function
See: sunSchedule for scheduling based on sun position.

ParamTypeDescription
patternstring | Date | Object | Array.<mixed>pattern or array of patterns. May be cron style string, Date object or node-schedule object literal. See https://github.com/tejasmanohar/node-schedule/wiki
optionsObject
options.randomnumberrandom delay execution in seconds. Has to be positive
callbackfunctionis called with no arguments

Example

// every full Hour.
schedule('0 * * * *', callback);

// Monday till friday, random between 7:30am an 8:00am
schedule('30 7 * * 1-5', {random: 30 * 60}, callback);

// once on 21. December 2018 at 5:30am
schedule(new Date(2018, 12, 21, 5, 30, 0), callback);

// every Sunday at 2:30pm
schedule({hour: 14, minute: 30, dayOfWeek: 0}, callback);

sunSchedule(pattern, options, callback)

Schedule a recurring event based on sun position

Kind: global function
See: schedule for time based scheduling.

ParamTypeDescription
patternstring | Array.<string>a suncalc event or an array of suncalc events. See https://github.com/mourner/suncalc
optionsObject
options.shiftnumberdelay execution in seconds. Allowed Range: -86400...86400 (+/- 24h)
options.randomnumberrandom delay execution in seconds.
callbackfunctionis called with no arguments

Example

// Call callback 15 minutes before sunrise
sunSchedule('sunrise', {shift: -900}, callback);

// Call callback random 0-15 minutes after sunset
sunSchedule('sunset', {random: 900}, callback);

publish(topic, payload, options)

Publish a MQTT message

Kind: global function

ParamTypeDefaultDescription
topicstring | Array.<string>topic or array of topics to publish to
payloadstring | Objectthe payload string. If an object is given it will be JSON.stringified
optionsObjectthe options to publish with
options.qosnumber0QoS Level
options.retainbooleanfalseretain flag

setValue(topic, val)

Set a value on one or more topics

Kind: global function

ParamTypeDescription
topicstring | Array.<string>topic or array of topics to set value on
valmixed

getValue(topic) ⇒ mixed

Kind: global function
Returns: mixed - the topics value

ParamType
topicstring

getProp(topic, ...property) ⇒ mixed

Get a specific property of a topic

Kind: global function
Returns: mixed - the topics properties value

ParamTypeDescription
topicstring
...propertystringthe property to retrieve. May be repeated for nested properties. If omitted the whole topic object is returned.

Example

// returns the timestamp of a given topic
getProp('hm//Bewegungsmelder Keller/MOTION', 'ts');

now() ⇒ number

Kind: global function
Returns: number - ms since epoch

age(topic) ⇒ number

Kind: global function
Returns: number - seconds since last change

ParamType
topicstring

link(source, target, value)

Link topic(s) to other topic(s)

Kind: global function

ParamTypeDescription
sourcestring | Array.<string>topic or array of topics to subscribe
targetstring | Array.<string>topic or array of topics to publish
valuemixedvalue to publish. If omitted the sources value is published. A function can be used to transform the value.

combineBool(srcs, targets)

Combine topics through boolean or

Kind: global function

ParamTypeDescription
srcsArray.<string>array of topics to subscribe
targetsstringtopic to publish

combineMax(srcs, targets)

Publish maximum of combined topics

Kind: global function

ParamTypeDescription
srcsArray.<string>array of topics to subscribe
targetsstringtopic to publish

timer(src, target, time)

Publishes 1 on target for specific time after src changed to true

Kind: global function

ParamTypeDescription
srcstring | Array.<string>topic or array of topics to subscribe
targetstringtopic to publish
timenumbertimeout in milliseconds

subscribeCallback : function

Kind: global typedef

ParamTypeDescription
topicstringthe topic that triggered this callback. +/status/# will be replaced by +//#
valmixedthe val property of the new state
objobjectnew state - the whole state object (e.g. {"val": true, "ts": 12346345, "lc": 12346345} )
objPrevobjectprevious state - the whole state object
msgobjectthe mqtt message as received from MQTT.js

License

MIT © Sebastian Raff

1.2.2

5 years ago

1.2.1

5 years ago

1.2.0

5 years ago

1.1.0

6 years ago

1.0.5

6 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago

0.11.0

7 years ago

0.10.2

9 years ago

0.10.1

9 years ago

0.10.0

9 years ago