Alongside user-defined inputs and parameters for Custom Logic Blocks, the implicit event property called state is provided. Using the state allows users to persist and share data between different rule runs ("memory"). This can be achieved by the emitting state which will be accessible in the next rule run. The state property is shared only between runs of the same rule, regardless of the source that triggered a rule execution.
Accessing the rule state property from a Custom Logic Block script:
functionconsume(event) { var ruleState =event.state || {};//your implementation goes here...}
Initially event.state property is an empty object!
An example of updating a rule state property from Custom Logic Block script:
An example of a Custom Logic Block script that makes use of the state property:
functionconsume(event) { var temperature =event.inputs["temp1"]; var threshold =event.properties["tempT"]; var ruleState =event.state;if (temperature > threshold) {var numOfSamples =ruleState.numOfSamples;if (typeof numOfSamples !=="undefined") { numOfSamples = numOfSamples +1; } else { numOfSamples =1; }emit('state', { "numOfSamples": numOfSamples });//Emitting action when numOfSamples is an even numberif (numOfSamples %2===0) {emit('action', { "message":"Rule has triggered the action!","addedTemp": threshold + temperature }); } } }
The rule state will be reset on rule deactivation or deletion. Once a rule is activated again, the rule state property will be set to a default value.
A more advanced example of using rule state:
// rule that adaptively changes the threshold based on the average temperaturefunctionconsume(event) {constalpha=0.2;constinitialThreshold=event.properties.initialThreshold;constcurrentTemperature=event.inputs.temperature;let state =event.state || {};let movingAverage =state.movingAverage ||0;let threshold =state.threshold || initialThreshold;let numberOfSamples =state.numberOfSamples ||0;//compute a moving average movingAverage = (currentTemperature + numberOfSamples * movingAverage) / (numberOfSamples +1);// let's define the threshold by 20% above the averageconstcurrentThreshold= movingAverage *1.2;// exponentially smooth the threshold in order to account// for the phase where not much data is present threshold = alpha * currentThreshold + (1- alpha) * threshold;if (currentTemperature > threshold) {emit("action", { message:`temperature (${currentTemperature}°C) is above threshold (${threshold})`, }); } numberOfSamples +=1; state = { threshold, numberOfSamples, movingAverage };emit("state", state);}