Sometimes you need Data to persist between the call of a payload decoder. This is normally done by using global environment variables that store the data between function calls.
Access Database Fields
On Datacake this can be achieved by creating a dedicated field in the Database Section of your Datacake Device and by using this as the storage for this data.
functiondecoder() {// get current value from field in Databasevar numberOfCalls =measurements.NUMBER_OF_CALLS.value;// do some processing numberOfCalls = numberOfCalls +1;// return that field in order to write new value into databasereturn [ { "field":"NUMBER_OF_CALLS","value": numberOfCalls } ]}
Time between changes
Storing data between payload decoder function calls can also be used to measure the time elapsed between a change of a value. This can be done by accessing not only the current value of a Database-Field but also the timestamp.
functiondecoder() {// pseudo code here - removed the parts before// get number of changes happened before from Databasevar lastNumberOfChanges =measurements.NUMBER_OF_CHANGES.value;// get state stored in Databasevar lastState =measurements.RO1_STATUS.value;// when new state is not equal state in database -> change happenedif (lastState != current_RO1_STATUS) {// increase number of changes lastNumberOfChanges +=1;// store number of changes in databasedecoded.push({ "field":"NUMBER_OF_CHANGES","value":lastNumberOfChanges });// calculate the time between changesvar currentTimestamp =Math.floor(Date.now() /1000);var lastTimestamp =measurements.RO1_STATUS.timestamp;var timeDelta = (currentTimestamp - lastTimestamp) /60;var timeBetweenChanges =Math.abs(Math.round(timeDelta));// store new time between last changes in databasedecoded.push({ "field":"TIME_BETWEEN_CHANGES","value":timeBetweenChanges }); }return decoded;}