IoT Device Model

This section describes the IoT device model functions in more detail

We have discussed that a device model describes the behavior of a device to the system with 4 Javascript functions. Each of these functions are called with a common Javascript Object called state which remains persistent through the simulation run.

The state Object

Every IoT device has several important parameters to be reported to the cloud platform. An example could be a temperature value read through a sensor or the current CPU load. The device has also some internal parameters such as available SSD and memory usage, which are required to be tracked. While modelling the device, you will need a local store to save these values and any other intermediate variable which needs to be preserved through the life of the simulation. state is a JSON object which can be used to save device status. E.g. consider following code snippet of a simple template:

{
// if temperature has not been defined previously
if (state.temperature === undefined ) {
state.temperature = 50;
}
state.temperature++;
return JSON.stringify(state);
}

In the very first iteration when this function is invoked, the state object will be empty. The if condition checks this and initializes the temperature with a default value of 50. Since state is preserved across iterations, the temperature value will be found to be set to 51 and in the next call and hence in each subsequent call of the function, the temperature variable will increment by 1. At the end, the function simply stringifies the JSON object and return the string as a payload. Here is how the first payload sent from this function will look like

{
temperature: 51
}

The state object is available through all of the function calls. It is important not to use a similar named variable in your local function or scope to avoid confusion and namespace conflicts.

It is not necessary to always stringify and return state as a payload. You could choose to send any string or even a Node.js Buffer as a return value of the function.

In this example, we are only sending two properties of the state as a payload and not the entire object.

{
var retVal = {
myval: state.myval,
myString: state.myString
}
return JSON.stringify(retVal);
}