Rules

Introduction

A rule is primarily composed of conditions and actions. When a rule is defined, a rule type can be specified, which determines the structure of the rule.

  • DATASTREAM: This type of rule would be evaluated if data were collected in the South API.
  • OPERATION: This type of rule would be evaluated if an operation were executed on the Opengate platform.
  • EVENT: This type of rule would be evaluated if an event were sent to the Opengate platform.

Automation rules

The set of conditions and actions can be defined in EASY mode using a JSON structure, or alternatively, an advanced rule can be written in JavaScript code.

Easy mode

The “easy mode” allows users to define new rules using the JSON format. Firstly, the rule type must be specified, as this will determine the structure of the rule.

  • Data stream: If this option is selected, the rules engine will evaluate data stream rules if an entity is modified using the north OpenGate API or when OpenGate collects data through any of the south connectors. In this case, the data streams that the rule will use must be configured in the condition.
  • Operation: If this option is selected, the rules engine will evaluate operation responses after they have been managed by the OpenGate operations engine.

Configure data stream and parameters in the rule

It is possible to utilise data streams and parameter values within the configuration of rules. This can be done in a number of ways, including in conditions and some attributes in rule actions.

  • datastream: $datastream:<id_datastream>
  • parameter: $parameter:<id_parameter>

Example:

  • datastream: $datastream:device.identifier._current.value
  • parameter: $parameter:threshnew

Further examples can be found in the schemas’ objects.

Comprehensive API actions

Updating a rule

All fields may be updated in accordance with the same validations as a POST request, with the exception of identifier, organisation and channel. Furthermore, an ADVANCED rule cannot be changed to EASY mode.

API specification

Subsections of Rules

Advanced Rules Mode

Rules in Advanced Mode

In advanced rules, you can write conditions and actions in javascript language.

In this javascript code, it is possible to call some defined functions to execute the same actions that you can do in easy mode. On the other hand, we also have some help functions. We will explain them below.

The main function will receive a flattened entity representation, adding the _received and _previous values to each datastream. The _received field is a simple object in provision datastreams and an array object in any other case.

We will use the following entity as an example:

entity = {
  "provision.administration.channel": {
    "_value": {
      "_current": {
        "value": "battery_channel",
        "date": "2017-12-01T08:52:37.563Z",
        "at": "2017-12-01T08:52:37.563Z"
      },
      "_previous": {
        "value": "battery_channel",
        "date": "2017-12-01T08:52:37.563Z",
        "at": "2017-12-01T08:52:37.563Z"
      }
    }
  },
  "provision.administration.identifier": {
    "_value": {
      "_current": {
        "value": "device_battery_id",
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.57Z",
        "at": "2017-12-01T08:52:37.57Z"
      },
      "_previous": {
        "value": "battery_organization",
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.566Z",
        "at": "2017-12-01T08:52:37.566Z"
      }
    }
  },
  "provision.administration.organization": {
    "_value": {
      "_current": {
        "value": "battery_organization",
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.566Z",
        "at": "2017-12-01T08:52:37.566Z"
      },
      "_previous": {
        "value": "battery_organization",
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.566Z",
        "at": "2017-12-01T08:52:37.566Z"
      }
    }
  },
  "provision.administration.plan": {
    "_value": {
      "_current": {
        "value": "FLOW_RATE_100",
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.565Z",
        "at": "2017-12-01T08:52:37.565Z"
      },
      "_previous": {
        "value": "FLOW_RATE_100",
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.565Z",
        "at": "2017-12-01T08:52:37.565Z"
      }
    }
  },
  "provision.administration.serviceGroup": {
    "_value": {
      "_current": {
        "value": "emptyServiceGroup",
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.561Z",
        "at": "2017-12-01T08:52:37.561Z"
      },
      "_previous": {
        "value": "emptyServiceGroup",
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.561Z",
        "at": "2017-12-01T08:52:37.561Z"
      }
    }
  },
  "provision.device.communicationModules[].identifier": [
    {
      "_index": {
        "path": "provision.device.communicationModules[].identifier",
        "value": {
          "_current": {
            "value": "commsMod_battery_id",
            "provType": "MONITORING",
            "date": "2017-12-01T08:52:37.577Z",
            "at": "2017-12-01T08:52:37.577Z"
          }
        }
      },
      "_value": {
        "_current": {
          "value": "commsMod_battery_id",
          "provType": "MONITORING",
          "date": "2017-12-01T08:52:37.577Z",
          "at": "2017-12-01T08:52:37.577Z"
        },
        "_previous": {
          "value": "commsMod_battery_id",
          "provType": "MONITORING",
          "date": "2017-12-01T08:52:37.577Z",
          "at": "2017-12-01T08:52:37.577Z"
        }
      }
    }
  ],
  "provision.device.communicationModules[].subscription.address": [
    {
      "_index": {
        "path": "provision.device.communicationModules[].identifier",
        "value": {
          "_current": {
            "value": "commsMod_battery_id",
            "provType": "MONITORING",
            "date": "2017-12-01T08:52:37.577Z",
            "at": "2017-12-01T08:52:37.577Z"
          }
        }
      },
      "_value": {
        "_current": {
          "value": {
            "type": "IPV4",
            "value": "99.1.1.71",
            "apn": "myapnprov.es"
          },
          "provType": "REFERENCE",
          "date": "2017-12-01T08:52:37.624Z",
          "at": "2017-12-01T08:52:37.624Z"
        },
        "_previous": {
          "value": {
            "type": "IPV4",
            "value": "99.1.1.71",
            "apn": "myapnprov.es"
          },
          "provType": "REFERENCE",
          "date": "2017-12-01T08:52:37.624Z",
          "at": "2017-12-01T08:52:37.624Z"
        }
      }
    }
  ],
  "provision.device.communicationModules[].subscription.identifier": [
    {
      "_index": {
        "path": "provision.device.communicationModules[].identifier",
        "value": {
          "_current": {
            "value": "commsMod_battery_id",
            "provType": "MONITORING",
            "date": "2017-12-01T08:52:37.577Z",
            "at": "2017-12-01T08:52:37.577Z"
          }
        }
      },
      "_value": {
        "_current": {
          "value": "subscription_battery_id",
          "provType": "MONITORING",
          "date": "2017-12-01T08:52:37.626Z",
          "at": "2017-12-01T08:52:37.626Z"
        },
        "_previous": {
          "value": "subscription_battery_id",
          "provType": "MONITORING",
          "date": "2017-12-01T08:52:37.626Z",
          "at": "2017-12-01T08:52:37.626Z"
        }
      }
    }
  ],
  "provision.device.identifier": {
    "_value": {
      "_current": {
        "value": "device_battery_id",
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.636Z",
        "at": "2017-12-01T08:52:37.636Z"
      },
      "_previous": {
        "value": "device_battery_id",
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.636Z",
        "at": "2017-12-01T08:52:37.636Z"
      }
    }
  },
  "provision.device.location": {
    "_value": {
      "_current": {
        "value": {
          "position": {
            "type": "Point",
            "coordinates": [
              -3.7028,
              40.41675
            ]
          },
          "postal": "28013"
        },
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.64Z",
        "at": "2017-12-01T08:52:37.64Z"
      },
      "_previous": {
        "value": {
          "position": {
            "type": "Point",
            "coordinates": [
              -3.7028,
              40.41675
            ]
          },
          "postal": "28013"
        },
        "provType": "MONITORING",
        "date": "2017-12-01T08:52:37.64Z",
        "at": "2017-12-01T08:52:37.64Z"
      }
    }
  },
  "resourceType": {
    "_value": {
      "_current": {
        "value": "entity.device",
        "provType": "IDENTIFIER",
        "date": "2017-12-01T08:52:37.643Z",
        "at": "2017-12-01T08:52:37.643Z"
      },
      "_previous": {
        "value": "entity.device",
        "provType": "IDENTIFIER",
        "date": "2017-12-01T08:52:37.643Z",
        "at": "2017-12-01T08:52:37.643Z"
      }
    }
  },
  "device.communicationModules[].identifier": [
    {
      "_index": {
        "path": "device.communicationModules[].identifier",
        "value": {
          "_current": {
            "value": "commsMod_battery_id",
            "date": "2017-12-01T08:52:37.577Z",
            "at": "2017-12-01T08:52:37.577Z"
          }
        }
      },
      "_value": {
        "_current": {
          "value": "commsMod_battery_id",
          "date": "2017-12-01T08:52:37.577Z",
          "at": "2017-12-01T08:52:37.577Z"
        },
        "_previous": {
          "value": "commsMod_battery_id",
          "date": "2017-12-01T08:52:37.577Z",
          "at": "2017-12-01T08:52:37.577Z"
        }
      }
    }
  ],
  "device.communicationModules[].subscription.address": [
    {
      "_index": {
        "path": "device.communicationModules[].identifier",
        "value": {
          "_current": {
            "value": "commsMod_battery_id",
            "date": "2017-12-01T08:52:37.577Z",
            "at": "2017-12-01T08:52:37.577Z"
          }
        }
      },
      "_value": {
        "_current": {
          "value": {
            "type": "IPV4",
            "value": "99.1.1.71",
            "apn": "myapn.es"
          },
          "date": "2017-12-01T08:52:37.624Z",
          "at": "2017-12-01T08:52:37.624Z",
          "source": "DEVICE_OPENGATE_HTTP",
          "sourceInfo": "IoT Data Message Received"
        },
        "_previous": {
          "value": {
            "type": "IPV4",
            "value": "99.1.1.71",
            "apn": "myapn.es"
          },
          "date": "2017-12-01T08:52:37.624Z",
          "at": "2017-12-01T08:52:37.624Z",
          "source": "DEVICE_OPENGATE_HTTP",
          "sourceInfo": "IoT Data Message Received"
        }
      }
    }
  ],
  "device.communicationModules[].subscription.identifier": [
    {
      "_index": {
        "path": "device.communicationModules[].identifier",
        "value": {
          "_current": {
            "value": "commsMod_battery_id",
            "date": "2017-12-01T08:52:37.577Z",
            "at": "2017-12-01T08:52:37.577Z"
          }
        }
      },
      "_value": {
        "_current": {
          "value": "subscription_battery_id",
          "date": "2017-12-01T08:52:37.626Z",
          "at": "2017-12-01T08:52:37.626Z",
          "source": "DEVICE_OPENGATE_HTTP",
          "sourceInfo": "IoT Data Message Received"
        },
        "_previous": {
          "value": "subscription_battery_id",
          "date": "2017-12-01T08:52:37.626Z",
          "at": "2017-12-01T08:52:37.626Z",
          "source": "DEVICE_OPENGATE_HTTP",
          "sourceInfo": "IoT Data Message Received"
        }
      }
    }
  ],
  "device.identifier": {
    "_value": {
      "_received": [{
        "value": "device_battery_id",
        "date": "2017-12-01T08:52:37.636Z",
        "at": "2017-12-01T08:52:37.636Z",
        "source": "DEVICE_OPENGATE_HTTP",
        "sourceInfo": "IoT Data Message Received"
      }],
      "_current": {
        "value": "device_battery_id",
        "date": "2017-12-01T08:52:37.636Z",
        "at": "2017-12-01T08:52:37.636Z",
        "source": "DEVICE_OPENGATE_HTTP",
        "sourceInfo": "IoT Data Message Received"
      },
      "_previous": {
        "value": "device_battery_id",
        "date": "2017-12-01T08:52:37.636Z",
        "at": "2017-12-01T08:52:37.636Z",
        "source": "DEVICE_OPENGATE_HTTP",
        "sourceInfo": "IoT Data Message Received"
      }
    }
  },
  "device.temperature.value": {
    "_value": {
      "_received": [{
        "value": 25.3,
        "date": "2017-12-01T08:52:37.64Z",
        "at": "2017-12-01T08:52:37.64Z",
        "source": "DEVICE_OPENGATE_HTTP",
        "sourceInfo": "IoT Data Message Received"
      }],
      "_current": {
        "value": 25.3,
        "date": "2017-12-01T08:52:37.64Z",
        "at": "2017-12-01T08:52:37.64Z",
        "source": "DEVICE_OPENGATE_HTTP",
        "sourceInfo": "IoT Data Message Received"
      },
      "_previous": {
        "value": 23.3,
        "date": "2017-12-01T05:52:37.64Z",
        "at": "2017-12-01T05:52:37.64Z",
        "source": "DEVICE_OPENGATE_HTTP",
        "sourceInfo": "IoT Data Message Received"
      }
    }
  }
}
  

Executing Actions

Executing actions

openAlarm(subEntityIdentifier, alarmName, ruleName, severity, priority, alarmDescription, extraInfo)

Deprecated: Use alarm object functions instead.

Opens an alarm for the selected entity.

Kind: global function
Returns: void

Param Type Description
subEntityIdentifier String You can open an alarm on device, subscription or subscriber identifier. With subEntityIdentifier you define selected identifier. If is undefined it will open on provision.administration.identifier identifier.
alarmName String Name that you want to see in opened alarm
ruleName String Name of rule that produce opening of alarm.
severity String Alarm severity. Values can be INFORMATIVE, URGENT or CRITICAL.
priority String Alarm priority. Values can be LOW, MEDIUM or HIGH.
alarmDescription String Alarm description.
extraInfo String Extra information.

Examples of use This example open alarm apnMismatch to subscription.

openAlarm('subscription_battery_id', 'apnMismatch' , 'apnMismatchRule', 'URGENT', 'MEDIUM', 'APN mismatch with provisioned value')

And this example open alarm highTemperature to device.

openAlarm(undefined, 'highTemperature' , 'highTemperatureRule', 'URGENT', 'MEDIUM', 'Device temperature is high')

closeAlarmByRuleName(entityIdDatastream, ruleName)

Deprecated: Use alarm object functions instead.

Closes an alarm for the selected entity using rule name.

Kind: global function
Returns: void

Param Type Description
entityIdDatastream String You can close an alarm on device, subscription or subscriber identifier. With entityIdDatastream you define selected identifier. If is undefined it will close on provision.administration.identifier identifier.
ruleName String Name of rule that open alarm.

Example of use:

closeAlarmByRuleName(undefined, 'highTemperatureRule')

closeAlarmByAlarmName(entityIdDatastream, alarmName)

Deprecated: Use alarm object functions instead.

Closes an alarm for the selected entity using alarm name.

Kind: global function
Returns: void

Param Type Description
entityIdDatastream String You can close an alarm on device, subscription or subscriber identifier. With entityIdDatastream you define selected identifier. If is undefined it will close on provision.administration.identifier identifier.
alarmName String Name of alarm to close.

Example of use:

closeAlarmByAlarmName(undefined, 'alarm name')

addEmailNotification(recipients, notificationName, notificationBody, ruleName, mailParameters)

Deprecated: Use notification object functions instead.

Sends email notification to defined recipients.

Kind: global function
Returns: void

Param Type Description
recipients Array Array of recipients to send email. This param has same format as defined in easy mode.
notificationName String Name of notification that will be received in subject field.
notificationBody String Mustache template with email’s body
ruleName String Name of rule that launch email request.
mailParameters Object Json object with key-value pairs that will be replaces in mustache evaluation.

Example of use:

The example send email to example@recipient.es with highTemperature notification.

parameters = {};
parameters['deviceIdentifier'] = getDatastreamFromEntity('device.identifier')._current.value;
parameters['deviceTemperature'] = getDatastreamFromEntity('device.temperature')._current.value;
addEmailNotification(['example@recipient.es'], 'highTemperature', 'Received high temperature from {{deviceIdentifier}} with value {{deviceTemperature}}', 'highTemperatureRule', parameters);

addTrapNotification(recipients, variables, notificationName, trapOID, enterpriseOID, ruleName)

Deprecated: Use notification object functions instead.

Sends trap notification to defined recipients.

Kind: global function
Returns: void

Param Type Description
recipients Array Array of recipients (<ip>:<port>) to send trap. This param has same format as defined in easy mode.
variables Object Map of variables. Each pair defines OID variable and sent value for this OID.
notificationName String Name of notification
trapOID String OID of trap
enterpriseOID String OID of enterprise
ruleName String Name of rule

Example of use:

The example send trap to 25.35.98.5:8585 with highTemperature notification.

var recipients = ['25.35.98.5:8585'];
var trapVariables = {
  '1.1.1': entity['provision.administration.organization']._value._current.value,
  '1.1.2': entity['provision.administration.channel']._value._current.value,
  '1.1.3': entity['provision.administration.identifier']._value._current.value,
  '1.1.4': entity['device.temperature']._value._current.value,
  '1.1.5': entity['device.temperature']._value._previous.value,
  '1.1.6': Date.now()
};         

addTrapNotification(recipients, trapVariables, 'highTemperature', '1.100.1', '1.2.7.3.1.2.25841', 'highTemperatureRule');

sendHttp(httpJson)

Deprecated: Use notification object functions instead.

Sends http notification to defined recipients.

Kind: global function
Returns: void

Param Type Description
httpJson Object Same json that easy mode.

Example of use:

The example send http request to http://myService/request with highTemperature notification.

httpJson = {
  'url': 'http://myService/request',
  'method' : 'POST',
  'headers': {
    'Content-type': 'application/json'
  },
  'queryParams' : {
    'deviceId' : entity['provision.device.identifier']._value._current.value
  },
  'body' : 'New alert received by high temperature received. Current value: ' + entity['device.temperature']._value._current.value
};
sendHttp(httpJson);

executeOperation(subEntityIdentifier, operationType, operationTimeout, jobUser, retries, ackTimeout, retriesDelay, stopValue, stopMode, parameters, callback)

Deprecated: Use operation object functions instead.

Executes selected operation to received identifier.

Kind: global function
Returns: void

Param Type Description
subEntityIdentifier String You can execute operation on device, subscription or subscriber identifier. With subEntityIdentifier you define selected identifier. If is undefined it will open on provision.administration.identifier identifier.
operationType String Operation Identifier. You can get this values getting operation catalog. Mandatory field. The rule will be created, but the operation will not.
operationTimeout Number Operation timeout in milliseconds. Default: 60000 milliseconds
jobUser String User apiKey that launch this operation. Mandatory field. The rule will be created, but the operation will not.
retries Number Operation retries number. Default: 0.
ackTimeout Number ACK timeout in milliseconds. Default: null.
retriesDelay Number Delay in seconds between retries. Default: null.
stopValue Number Stop value, this value depends of stop mode selected. Default: Operation timeout + 5000.
stopMode String Stop mode. Default: delayed. Possible values: date (stop value is a date in YYYY-MM-DDThh:mm:ssTZD format) and delayed (stop value is a time defined in milliseconds).
parameters Object This value is a json with accepted value in selected operation. You can see parameters getting operation catalog.
callback String URI where the result of the operation execution is received.

NOTE: The Job of the operation will be created with an active status by default.

Example of use:

The example execute REFRESH_PRESENCE operation to received device.

apiKey = getVariableValue(parameters['apiKey']);
parameters = {
  'active': false
};
executeOperation(entity['provision.administration.identifier']._value._current.value, 'REFRESH_PRESENCE', 20000, apiKey, 0, null, null, 25000, 'delayed', parameters, callback);

cancelDelay(ruleName)

Deprecated: Use utils object functions instead.

Cancels active delayed action produced by another rule activation.

Kind: global function
Returns: void

Param Type Description
ruleName String Name of rule that produce delayed actions.

Example of use:

The example cancel delay of ‘highTemperatureRule’ rule.

cancelDelay('highTemperatureRule');

Alarm utils

Alarm

The alarm object is the main object for managing alarms.

alarm.open(alarmConfig)

Opens an alarm.

Returns: void

This function takes as parameter an object with the following fields:

Property Type Default Mandatory Description
subEntityIdentifier String entityId No You can open an alarm on device, subscription or subscriber identifier. With subEntityIdentifier you define selected identifier. If is undefined it will open on provision.administration.identifier identifier
alarmName String No Name that you want to see in opened alarm
ruleName String No Name of rule that produce opening of alarm
severity String ‘INFORMATIVE’ No Severity of alarm. Values can be INFORMATIVE, URGENT or CRITICAL
priority String ‘LOW’ No Priority of alarm. Values can be LOW, MEDIUM or HIGH
description String No Alarm description
extraInfo String No Extra information.

Example of use:

This example open alarm apnMismatch to subscription.

alarmConfig = {
    subEntityIdentifier: "id",
    alarmName: "apnMismatch",
    ruleName: "apnMismatchRule",
    severity: "URGENT",
    priority: "MEDIUM",
    description: "APN mismatch with provisioned value",
    extraInfo: "Extra information"
}
  
alarm.open(alarmConfig);

And this example open alarm highTemperature to device.

alarmConfigDevice = {
    alarmName: "highTemperature",
    ruleName: "highTemperatureRule",
    severity: "URGENT",
    priority: "MEDIUM",
    description: "Device temperature is high"
}

alarm.open(alarmConfigDevice);

alarm.closeByRuleName(closeByRuleConfig)

Closes alarm by rule name.

Returns: void

This function takes as parameter an object with the following fields:

Property Type Default Mandatory Description
ruleName String Yes Rule name that open alarm.
entityIdDatastream String No You can close an alarm on device, subscription or subscriber identifier. With entityIdDatastream you define selected identifier. If is undefined it will close on provision.administration.identifier identifier.

Example of use:

The example close alarm generated by highTemperatureRule to device.

closeByRuleConfig = {
    ruleName: "highTemperatureRule"
}

alarm.closeByRuleName(closeByRuleConfig);

alarm.closeByAlarmName(closeByNameConfig)

Closes alarm by alarm name.

Returns: void

This function takes as parameter an object with the following fields:

Property Type Default Mandatory Description
alarmName String Yes Opened alarm name.
entityIdDatastream String No You can close an alarm on device, subscription or subscriber identifier. With entityIdDatastream you define selected identifier. If is undefined it will close on provision.administration.identifier identifier.

Example of use:

The example close opened alarm apnMismatch to device.

closeByNameConfig = {
    alarmName: "highTemperatureRule"
}

alarm.closeByAlarmName(closeByNameConfig);

Notifications utils

Notification

The notification object is the main object for managing notifications.

notification.addEmailNotification(emailConfig)

Sends an email notification to defined recipients.

Returns: void

This function takes as parameter an object with the following fields:

Property Type Default Mandatory Description
jsRecipients List Yes Array of recipients to send email. This param has same format as defined in easy mode
notificationName String Yes Name of notification that will be received in subject field
notificationBody String Yes Mustache template with email’s body
ruleName String Yes Name of rule that launch email request
mailParameters Object No Json object with key-value pairs that will be replaces in mustache evaluation

Example of use:

The example send email to example@recipient.es with highTemperature notification.

emailNotifConfig = {
    jsRecipients: ['example@recipient.es'],
    notificationName: 'highTemperature',
    notificationBody: 'Received high temperature from {{deviceIdentifier}} with value {{deviceTemperature}}',
    ruleName: 'highTemperatureRule',
    mailParameters: {
        deviceIdentifier: getDatastreamFromEntity('device.identifier')._current.value,
        deviceTemperature: getDatastreamFromEntity('device.temperature')._current.value
    }
}
    
notification.addEmailNotification(emailNotifConfig);

notification.addTrapNotification(trapConfig)

Sends an SNMP trap notification to defined recipients.

This function takes as parameter an object with the following fields:

Property Type Default Mandatory Description
jsRecipients List Yes Array of recipients (<ip>:<port>) to send trap. This param has same format as defined in easy mode
jsVariables Object Yes Map of variables. Each pair defines OID variable and sent value for this OID
notificationName String Yes Name of notification
trapOID String Yes OID of trap
enterpriseOID String Yes OID of enterprise
ruleName String Yes Name of rule

Example of use:

The example send trap to 25.35.98.5:8585 with highTemperature notification.

trapNotifConfig = {
    jsRecipients: ['25.35.98.5:8585'],
    jsVariables: {
      '1.1.1': entity['provision.administration.organization']._value._current.value,
      '1.1.2': entity['provision.administration.channel']._value._current.value,
      '1.1.3': entity['provision.administration.identifier']._value._current.value,
      '1.1.4': entity['device.temperature']._value._current.value,
      '1.1.5': entity['device.temperature']._value._previous.value,
      '1.1.6': Date.now()
    },
    notificationName: 'highTemperature',
    trapOID: '1.100.1',
    enterpriseOID: '1.2.7.3.1.2.25841',
    ruleName: 'highTemperatureRule'
}

notification.addTrapNotification(trapNotifConfig);

notification.sendHttp(httpConfig)

Sends an HTTP request notification to a specified URL.

Returns: void

This function takes as parameter an object with the following fields:

Property Type Default Mandatory Description
url String Yes URL to which the HTTP request will be sent
method String Yes HTTP method to be used for the request
headers Object No Key-value pairs representing HTTP headers
queryParams Object No Key-value pairs representing query parameters
body String No Body of the HTTP request

Example of use:

The example sends http request to http://myService/request with highTemperature notification.

httpJson = {
  'url': 'http://myService/request',
  'method' : 'POST',
  'headers': {
    'Content-type': 'application/json'
  },
  'queryParams' : {
    'deviceId' : entity['provision.device.identifier']._value._current.value
  },
  'body' : 'New alert received by high temperature received. Current value: ' + entity['device.temperature']._value._current.value
};

notification.sendHttp(httpJson);

Operation utils

Operation

The operation object is the main object for executing operations.

operation.execute(operationConfig)

Execute selected operation to received identifier.

Returns: void

This function takes as parameter an object with the following fields:

Property Type Default Mandatory Description
subEntityIdentifier String No You can execute operation on device, subscription or subscriber identifier. With subEntityIdentifier you define selected identifier. Default: If is undefined it will open on provision.administration.identifier identifier.
operationType String Yes Operation Identifier. You can get this values getting operation catalog. Mandatory field. The rule will be created, but the operation will not.
operationTimeout Number 60000 No Operation timeout in milliseconds.
jobUser String Yes User apiKey that launch this operation. Mandatory field. The rule will be created, but the operation will not.
retries Number 0 No Operation retries number.
ackTimeout Number null No ACK timeout in milliseconds.
retriesDelay Number 0 No Delay in seconds between retries.
stopValue String operationTimeout + 5000 No Stop value, this value depends of stop mode selected.
stopMode String delayed No Stop mode. Possible values are: date: If this mode is selected, stop value is a date in YYYY-MM-DDThh:mm:ssTZD format. delayed: If this mode is selected, stop value is a time defined in milliseconds.
parameters Object {} No This value is a json with accepted value in selected operation. You can see parameters getting operation catalog.
callback String null No URI where the result of the operation execution is received.

NOTE: The Job of the operation will be created with an active status by default.

Example of use:

The example execute ADMINISTRATIVE_STATUS_CHANGE operation to received device.

operationConfig = {
    subEntityIdentifier: entity['provision.administration.identifier']._value._current.value,
    operationType: 'ADMINISTRATIVE_STATUS_CHANGE',     
    operationTimeout: 20000,   
    jobUser: apiKey,           
    retries: 1,            
    ackTimeout: 5000,        
    retriesDelay: 0,      
    stopValue: '25000',         
    stopMode: 'delayed',
    callback: 'http://127.0.0.1:7070/directory',
    parameters: {
        admsts: 'BANNED'
    }
}

operation.execute(operationConfig);

Another example with stopMode = date

operationConfig = {
    subEntityIdentifier: entity['provision.administration.identifier']._value._current.value,
    operationType: 'REFRESH_PRESENCE',     
    operationTimeout: 20000,   
    jobUser: apiKey,           
    retries: 1,            
    ackTimeout: 5000,        
    retriesDelay: 0,      
    stopMode: 'date',
    stopValue: '2045-11-08T08:30:00+02:00',
    callback: 'http://127.0.0.1:7070/directory',
    parameters: {}
}

operation.execute(operationConfig);

Provision utils

Provision

The provision object is the main object for changing provision data.

provision.datastreams(provisionConfig)

Returns: void

This function takes as parameter an object with the following fields:

Property Type Mandatory Description
datastreams Object Yes Map where key is datastreamId and value is value to set in provision.
apiKey String Yes User apiKey that launches this provision.

Example of use:

var provisionConfig = {
    datastreams: {'datastream1':'value1','datastreamN':'valueN'},
    apiKey: 'the_api_key'
}

provision.datastreams(provisionConfig);

Datastreams and values

Getting and formatting datastreams and values

getVariableValue(variable)

This method reads a variable value.

Kind: global function
Returns: The read value, or undefined if the variable is not found.

Param Type Description
variable String Variable to obtain value.

Examples of use:

var myVar = undefined;
var finalVar = getVariableValue(myVar);

Result is ‘’;

This function returns the same value

var myVar = 2;
var finalVar = getVariableValue(myVar);

Result is 2;

getDatastreamFromEntity(datastreamId)

This method returns completed datastream of received entity.

Kind: global function
Returns: Completed datastream or undefined if the datastream is not found.

Param Type Description
datastreamId String Datastream to obtain value.

Example of use:

var deviceTemperature = getDatastreamFromEntity('device.temperature');

Result:

{
  "_received": [
    {
      "value": 25.3,
      "date": "2017-12-01T08:52:37.64Z",
      "at": "2017-12-01T08:52:37.64Z",
      "source": "DEVICE_OPENGATE_HTTP",
      "sourceInfo": "IoT Data Message Received"
    }
  ],
  "_current": {
    "value": 25.3,
    "date": "2017-12-01T08:52:37.64Z",
    "at": "2017-12-01T08:52:37.64Z",
    "source": "DEVICE_OPENGATE_HTTP",
    "sourceInfo": "IoT Data Message Received"
  },
  "_previous": {
    "value": 23.3,
    "date": "2017-12-01T05:52:37.64Z",
    "at": "2017-12-01T05:52:37.64Z",
    "source": "DEVICE_OPENGATE_HTTP",
    "sourceInfo": "IoT Data Message Received"
  }
}

getDatastreamValueFromEntity(datastreamObject)

Returns _value._current._value from datastream object

Kind: global function
Returns: Value object from datastream object.

Param Type Description
datastreamObject Object Datastream object.

Example of use:

var deviceTemperature = getDatastreamFromEntity('device.temperature');
var deviceTemperatureValue = getDatastreamValueFromEntity(deviceTemperature);

Result:

{
  "value": 25.3,
  "date": "2017-12-01T08:52:37.64Z",
  "at": "2017-12-01T08:52:37.64Z",
  "source": "DEVICE_OPENGATE_HTTP",
  "sourceInfo": "IoT Data Message Received"
}

getCommsDatastreamFromEntity(datastreamId, commsId)

Returns complete datastream in selected communication module of received entity.

Kind: global function
Returns: Complete datastream or undefined if the datastream is not found.

Param Type Description
datastreamId String Datastream to obtain value.
commsId String Communication module identifier.

Example of use:

datastream = getCommsDatastreamFromEntity('device.communicationModules[].subscription.address', 'commsMod_battery_id');

Result:

{
  "_current": {
    "value": {
      "type": "IPV4",
      "value": "99.1.1.71",
      "apn": "myapn.es"
    },
    "date": "2017-12-01T08:52:37.624Z",
    "at": "2017-12-01T08:52:37.624Z",
    "source": "DEVICE_OPENGATE_HTTP",
    "sourceInfo": "IoT Data Message Received"
  },
  "_previous": {
    "value": {
      "type": "IPV4",
      "value": "99.1.1.71",
      "apn": "myapn.es"
    },
    "date": "2017-12-01T08:52:37.624Z",
    "at": "2017-12-01T08:52:37.624Z",
    "source": "DEVICE_OPENGATE_HTTP",
    "sourceInfo": "IoT Data Message Received"
  }
}

getCounterValue(datastreamValue, incValue, resetDate)

Obtains incValue if datastreamValue date is before than resetDate or increments received value in datastream to incValue if the date is after.

Kind: global function
Returns: Incremented value or reset value.

Param Type Description
datastreamValue Object Datastream value.
incValue Number Value to increment.
resetDate Date Date of reset.

Example of use:

var datastream = {'value':3, 'date': toDate('2021-06-30T11:20:21.352Z')}
var resetDate = toDate('2021-06-30T00:00:0.000Z');
var counter = getCounterValue(datastream, 1, resetDate); 

Result: 4

This example get reseted daily counter to myCounterDatastream datastream:

var datastream = {'value':3, 'date': toDate('2021-06-29T11:20:21.352Z')}
var resetDate = toDate('2021-06-30T00:00:0.000Z');
var counter = getCounterValue(datastream, 1, resetDate); 

Result: 1

Dates manipulation

Dates manipulation

toDate(localDateTime)

Obtain date type from string date representation with format YYYY-MM-DDThh:mm:ssTZD.

Kind: global function
Returns: Date

Param Type Description
localDateTime string Date string representation with format YYYY-MM-DDThh:mm:ssTZD.

Example of use:

var date = toDate('2021-06-30T10:10:23.256Z');

getDailyResetDate()

Obtains date to reset daily counters.

This function returns date with current date, but with 00:00:00 hours.

Kind: global function
Returns: Date

Example of use:

var date = getDailyResetDate();

getDailyResetDateWithZuluHour(hour)

Obtains date to reset daily counters with defined hour in gmt+0.

Kind: global function
Returns: Date

Param Type Description
hour string Hour in format HH:mm:ss.

Example of use:

var date = getDailyResetDateWithZuluHour('02:00:00');

This function returns date with current date, but with 2:00:00 hours. For example, if current day is 2021-06-30, the returned date in previously called function is 2021-06-30T02:00:00Z

getMonthlyResetDate()

Obtains date to reset monthly counters.

This function returns date with first day of current month and 00:00:00 hours.

Kind: global function
Returns: Date

Example of use:

var date = getMonthlyResetDate();

getMonthlyResetDateWithZuluHour(hour)

Obtains date to reset monthly counters with defined hour in gmt+0.

Kind: global function
Returns: Date

Param Type Description
hour string Hour in format HH:mm:ss.
var date = getMonthlyResetDateWithZuluHour('02:00:00');

This function returns date with first day of current month, but with 2:00:00 hours. For example, if current day is 2021-06-30, the returned date in previously called function is 2021-06-01T02:00:00Z

getMonthlyResetDateWithZuluHourAndDayOfMonth(hour, dayOfMonth)

Obtains date to reset monthly counters with defined hour in gmt+0.

Kind: global function
Returns: Date

Param Type Description
hour string Hour in format HH:mm:ss.
dayOfMonth number Day of Month.
var date = getMonthlyResetDateWithZuluHourAndDayOfMonth('02:00:00', 21);

This function returns date of the day 21 of current month, but with 2:00:00 hours, when day of the month is null, then return first day of the month. For example, the returned date in previously called function is 2023-02-21T02:00:00Z

Logging utils

Logging

The logger object is the main object for logging functions.

logger.trace(…msg)

Creates TRACE level logging messages. It concatenates msg parameters to compound message to be logged.

Returns: void

Param Type Description
msg string list of elements to be concatenated to generate the string message to be printed.

Example of use:

logger.trace('Operation sent to', host_var, ' and port ', port_var, '. Operation content: ', operation_var);

logger.debug(…msg)

Creates DEBUG level logging messages. It concatenates msg parameters to compound message to be logged.

Returns: void

Param Type Description
msg string list of elements to be concatenated to generate the string message to be printed.

Example of use:

logger.debug('Operation sent to', host_var, ' and port ', port_var, '. Operation content: ', operation_var);

logger.info(…msg)

Creates INFO level logging messages. It concatenates msg parameters to compound message to be logged.

Returns: void

Param Type Description
msg string list of elements to be concatenated to generate the string message to be printed.

Example of use:

logger.info('Operation sent to', host_var, ' and port ', port_var, '. Operation content: ', operation_var);

logger.warn(…msg)

Creates WARN level logging messages. It concatenates msg parameters to compound message to be logged.

Returns: void

Param Type Description
msg string list of elements to be concatenated to generate the string message to be printed.

Example of use:

logger.warn('Operation sent to', host_var, ' and port ', port_var, '. Operation content: ', operation_var);

logger.error(…msg)

Creates ERROR level logging messages. It concatenates msg parameters to compound message to be logged.

Returns: void

Param Type Description
msg string list of elements to be concatenated to generate the string message to be printed.

Example of use:

logger.error('Error connecting to host ', host_var, ' and port ', port_var, '. Stop processing');

Cypher utils

String utils

encryptString(originalValue, datastreamId, organization)

Deprecated: Use utils object functions instead.

Encrypt an original string with the configuration established by the datastream of the organization

Kind: global function
Returns: String

Param Type Description
originalValue string The original value to encrypt.
datastreamId string The datastream of provision type, of the datamodel that define this value.
organization string The organization name to which the datamodel belongs.

Example of use:

var encryptedValue = encryptString('text to encrypt', 'provision.data.encrypt', 'organization_name');

decryptString(encryptedValue, datastreamId, organization)

Deprecated: Use utils object functions instead.

Decrypt an encrypted string with the configuration established by the datastream of the organization

Kind: global function
Returns: String

Param Type Description
encryptedValue string The encrypted value to decrypt.
datastreamId string The datastream of provision type, of the datamodel that define this value.
organization string The organization name to which the datamodel belongs.

Example of use:

var decryptedValue = decryptString('text to decrypt', 'provision.data.encrypt', 'organization_name');

Utils

Utils

The utils object is the main object for utilities.

utils.cancelDelay(ruleName)

Cancels an active delayed action produced by another rule activation.

Returns: void

This function takes as parameter an object with the following fields:

Property Type Default Mandatory Description
ruleName String Yes Name of rule that produce delayed actions.

Example of use:

The example cancels delay of ‘highTemperatureRule’ rule.

utils.cancelDelay('highTemperatureRule');

utils.encryptString(encryptConfig)

Encrypt a value.

Returns: String

This function takes as parameter an object with the following fields:

Property Type Default Mandatory Description
originalValue String Yes The value to encrypt
datastreamId String Yes The datastream of provision type, of datamodel that define this value
organization String Yes The organization name to which the datamodel belongs

Example of use:

encryptConfig = {
    originalValue: 'text to encrypt',
    datastreamId: 'provision.data.encrypt',
    organization: 'organization_name'
}

var encryptedValue = utils.encryptString(encryptConfig);

utils.decryptString(decryptConfig)

Decrypt a value.

Returns: String

This function takes as parameter an object with the following fields:

Property Type Default Mandatory Description
encryptedValue String Yes The value to decrypt
datastreamId String Yes The datastream of provision type, of datamodel that define this value
organization String Yes The organization name to which the datamodel belongs

Example of use:

decryptConfig = {
    encryptedValue: 'text to decrypt',
    datastreamId: 'provision.data.encrypt',
    organization: 'organization_name'
}

var decryptedValue = utils.decryptString(decryptConfig);

Default rules catalog

Name Rule Type Mode Active Description
activityForbiddenDatastream DATASTREAM ADVANCED false Activity detected for an entity with administrative state disabled
activityForbiddenOperation OPERATION ADVANCED false Activity detected for an entity with administrative state disabled
areaInputWithParameter DATASTREAM ADVANCED false Checks if an entity has entered in a geofence
areaOutputWithParameter DATASTREAM ADVANCED false Checks if an entity has exitted of a geofence
batteryThreshold DATASTREAM EASY false Current value of datastream has an unusual value
cancelBatteryThreshold DATASTREAM EASY false Current value of datastream has is returned to usual value
changeCommsModuleOperationalStatusByNokPing DATASTREAM ADVANCED false Put selected operational status to communication module if consecutive NOK Ping reach selected value
changeCommsModuleOperationalStatusByOkPing DATASTREAM ADVANCED false Put selected operational status to communication module if OK Ping received
checkDistance DATASTREAM ADVANCED false Checks if entity is farther than a defined distance
collectAreas DATASTREAM ADVANCED false Calculate entity.area datastream (and its derivatives) based on entity.location datastream
countAccountingStart DATASTREAM ADVANCED false Count accounting start in subscription
countPings DATASTREAM ADVANCED false Count number of ping [OK/NOK/NOK consecutives] to get information in mobile net
diagnosticFailed OPERATION EASY false Diagnostic with error in some operation
messageFlowRateExceeded EVENT EASY false Message flow rate exceeded, not process message
mobileICCMismatch DATASTREAM EASY false Collected ICC does not match with provisioned
mobileICCValueChanged DATASTREAM EASY false Compare current with previous values of one datastream
presenceReachableAllInterfaces DATASTREAM ADVANCED true Current value of datastream has an unusual value with margen temporal or no
presenceUnreachableAllInterfaces DATASTREAM ADVANCED true Current value of datastream has an unusual value with margen temporal or no
receivedBanned DATASTREAM EASY false Received data for a banned entity
securityConfigMismatch EVENT EASY false Security error validate, device validation failedSecurity error validate, device validation failed
subscriptionActivation DATASTREAM ADVANCED false Check if subscription is administrativeState = ACTIVE for a configured operator
subscriptionSuspension DATASTREAM ADVANCED false Check if subscription is administrativeState = SUSPENSION for a configured operator
sumSessionBytes DATASTREAM ADVANCED true Sum traffic bytes can get information in mobile net