Using Function Mode in Message template

Use Javascript function to generate message contents

Using function mode

The logic of your IoT endpoint could be quite complex to be fit into a simple JSON structure. While dealing with complex simulations such as Connected bus, we felt the need to provide more power and flexibility to our users.

Function mode enables a flexible and easy way of creating message contents when your template complexity is higher.

Simply choose the radio button Function while in your message template to enable function mode.

The idea of function mode is simple. In your template code, you provide the body of a function which returns a string. This string will be sent as the payload of the generated message contents.

You could call any helper in function mode without the need for double brackets.

The signature of the function is predefined as follows

function (state)
{
//Your contents goes here
// return '{ "Hello": "World"}';
}

The state is a Javascript Object which is intialized empty by default. The state is persistent across each function call, so you could add any local storage or tempory value inside it.

Using state as a scratchpad

The state can be used in any way you want to store your internal representation of device. E.g.

function (state)

{
if (state.temperature === undefined)
{
// Your one time initialization code goes here
state.temperature = 100;
}
state.temperature++;
return JSON.stringify(state);
}

It is not necesary to return values only in state variable. You could choose any return values you deem suitable. The return value must be a string.

Calling helper in function mode

You could use any chancejs or momentjs function within your function as well. Take a look at the template guides to see what helper functions can be used.

Example

Here is a simple example of showcasing the function mode

Let’s create a simple MQTT template which publishes on the topic /iotify/demo with following contents

function (state)

{
if (state.temperature === undefined)
{
// One time initialization
state.factor = Math.floor(10*Math.random());
state.temperature = 10;
}
var retval = {};
retval.temperature = Math.random()*state.factor + state.temperature;
state.temperature++;
return JSON.stringify(retval);
}

You could now even have your own helper function inside.

function (state)

{
var doubler = function(x){
return x*x;
};
// getting current iteration index
state.value = doubler(index());
return JSON.stringify(state);
}

Our connected truck simulator could now be written in function mode as follows

function (state)

{
var path = drive({start:'Geneva,CH',end:'Hamburg,DE',accuracy:5});
var retval = {};
retval.time = { "$date" : moment.now()};
retval.data = {};
retval.data.location = path.latitude + ","+path.longitude;
retval.data.speed = path.speed ;
retval.data.temperature = chance.integer({min:10, max:45});
//return a string value which will be sent as the message payload
return JSON.stringify(retval, null, 2);
}