akenza.io
WebsiteAPI DocumentationWhat's newLogin
  • Overview
  • Getting Started
    • Connect a Device
  • Changelog
  • General
    • Applications
    • Organization context
    • Workspace Context
    • Users
      • User Roles
  • Device Management
    • Managing an organization
      • API keys
      • Users (Organization)
        • Add & removing users from your organization
    • Managing a workspace
      • General Settings
        • Device Lifecycle Reports
        • Workspace properties
        • Occupancy settings
        • Device Setup Assistant
      • Custom fields
      • Tags
      • Users (Workspace)
    • Devices
      • Device
      • Device Simulator
      • Bulk actions
      • Bulk import CSV templates
    • Rules
      • Input
      • Logic blocks
        • Comparison
        • Custom Logic
          • Logic Block Scripting
      • Timed Rules
      • Rule Actions
        • Downlink
    • Data Flows
      • Device Connectors
        • Device Security
          • Using Device Credentials
            • Creating Public/Private Key Pairs
            • Using JSON Web Tokens (JWTs)
              • Python
              • Java
        • HTTP
        • MQTT
        • CoAP
        • LoRaWAN
          • Connectivity Management
          • Swisscom LoRaWAN
          • The Things Network
          • Loriot
          • Actility’s ThingPark Wireless
          • EWZ
          • Cibicom
          • Helium
          • ChirpStack
        • NB-IoT
        • mioty
        • Disruptive Technologies
        • VergeSense
        • Spaceti
        • Haltian
      • Device Types
        • Custom Device Types
          • Uplink
          • Downlink
          • Scripting
        • Library
      • Output Connectors
        • Databases
          • akenza DB
          • InfluxDB
          • SQL Databases
        • Streaming
          • Webhook
          • Azure IoT Hub
          • AWS Kinesis
          • Google Cloud Pub/Sub
          • Apache Kafka
        • Notifications
          • E-Mail
          • SMS
          • Microsoft Teams
          • Slack
    • Custom Components
    • Integrations
    • Reference
      • REST API
        • Filtering
        • Querying Device Data
      • WebSocket API
      • Scripting
        • Stateful Operations
        • Utility Functions
      • Payload Templating
  • Reference
  • Dashboard Builder
    • Managing Dashboards
      • Embedding dashboards
    • Components
      • Map
      • Floorplan
  • Device Setup Assistant
    • Device Setup Assistant - Overview
  • Tutorials
    • BI Tools
      • Grafana Data Source Plugin
      • How to build a dashboard with Retool
      • How to analyze data with AWS QuickSight
    • Devices
      • How to integrate the XDK device from Legic via MQTT on akenza
      • How to connect the Disruptive Technologies-cloud on akenza
      • How to send Downlinks to the Kuando Busylight device
      • How to integrate an Arduino device via MQTT on akenza
      • Integrate a MClimate Vicki LoRaWAN Radiator Thermostat on akenza
      • How to integrate an ERS Elsys device with Loriot on akenza
      • How to integrate the IAM Decentlab device with TTN on akenza
      • How to integrate the Seeed SenseCAP T1000 tracker on akenza
      • How to integrate a Swisscom Multisense device on akenza
    • Notifications
      • How to send SMS notifications
      • How to send notifications to Slack
      • How to send notifications to Microsoft Teams
    • Enterprise solutions
      • How to send data to Azure IoT Hub
      • How to send data to the Google Cloud Pub/Sub
      • How to send data to InfluxDB
      • How to send data to AWS Kinesis
      • How to send data to Azure Event Hubs with Apache Kafka
    • IoT Starter Kits
      • How to integrate the IAQ Kit with Actility on akenza
      • How to integrate the CoWork Kit with Actility on akenza
      • How to integrate the Smart Building Kit with Actility on akenza
      • How to integrate the Pepperl+Fuchs Kit with Actility on akenza
  • Support Center
    • FAQ
    • Status Page
    • Service Desk
    • Request a feature
  • Deprecated
    • SIM-Cards
    • Everynet
    • Sigfox
    • How to connect the Yanzi Lifecycle cloud on akenza
Powered by GitBook
On this page
  • Example Stateful Custom Logic Block
  • Event Object

Was this helpful?

  1. Device Management
  2. Reference
  3. Scripting

Stateful Operations

Sharing data between uplink decodings or rule executions

Alongside user-defined inputs and parameters for Custom Device Types and Custom Logic Blocks, the implicit event property called state is provided. Using the state allows users to persist and share data ("memory") between different uplinks (state per device) and rule executions (state per rule). This can be achieved by emitting the state which will be accessible in the next invocation. The state property is shared between uplinks of the same device or for the rule engine for runs of the same rule, regardless of the source that triggered a rule execution.

Accessing the rule state property from a Custom Device Type or Custom Logic Block script:

function consume(event) { 
    var state = 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:

function consume(event) { 
    var state = event.state || {};
    //your implementation goes here...
    state["numOfSamples"] = numOfSamples;
    emit('state', state);
}

or

function consume(event) { 
    //your implementation goes here...
    emit('state', { "numOfSamples":  numOfSamples });
}

Example Stateful Custom Logic Block

An example of a Custom Logic Block script that makes use of the state property:

function consume(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 number
        if (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 temperature
function consume(event) {
  const alpha = 0.2;
  const initialThreshold = event.properties.initialThreshold;
  const currentTemperature = 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 average
  const currentThreshold = 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);
}

Event Object

PreviousScriptingNextUtility Functions

Last updated 11 months ago

Was this helpful?

Refer to for all available properties.

Event Object in Rule Logic - Custom Logic Blocks