State Object
We have discussed that a device model describes the behaviour of a device by using different stages. The state object allows us to access data and functions throughout all the different stages.
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:
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:
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.
Last updated