Search…
⌃K
Links

IoT Device Model

This section describes the IoT device model functions in more detail
We have discussed that a device model describes the behaviour of a device by using different stages. Each of these functions is 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 that can be reported to the cloud platform. An example could be a temperature value read through a sensor or the current CPU load. The device also has 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 the 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 set to 51 in the next iteration and it will keep getting incremented by 1 with each subsequent iteration. At the end of each iteration, the function simply stringifies the JSON object and return the string as a payload. Here is what 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 similarly 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);
}