Global Variables

Concept

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.
1
function decoder() {
2
3
// get current value from field in Database
4
var numberOfCalls = measurements.NUMBER_OF_CALLS.value;
5
6
// do some processing
7
numberOfCalls = numberOfCalls + 1;
8
9
// return that field in order to write new value into database
10
return [
11
{ "field": "NUMBER_OF_CALLS", "value": numberOfCalls }
12
]
13
}
Copied!

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.
1
function decoder() {
2
3
// pseudo code here - removed the parts before
4
5
// get number of changes happened before from Database
6
var lastNumberOfChanges = measurements.NUMBER_OF_CHANGES.value;
7
8
// get state stored in Database
9
var lastState = measurements.RO1_STATUS.value;
10
11
// when new state is not equal state in database -> change happened
12
if (lastState != current_RO1_STATUS) {
13
14
// increase number of changes
15
lastNumberOfChanges += 1;
16
17
// store number of changes in database
18
decoded.push({ "field":"NUMBER_OF_CHANGES","value":lastNumberOfChanges });
19
20
// calculate the time between changes
21
var currentTimestamp = Math.floor(Date.now() / 1000);
22
var lastTimestamp = measurements.RO1_STATUS.timestamp;
23
var timeDelta = (currentTimestamp - lastTimestamp) / 60;
24
var timeBetweenChanges = Math.abs(Math.round(timeDelta));
25
26
// store new time between last changes in database
27
decoded.push({ "field":"TIME_BETWEEN_CHANGES","value":timeBetweenChanges });
28
}
29
30
return decoded;
31
}
Copied!