Rule Engine Overview
Rule Engine in OCS360 platform is a highly customizable and configurable system for complex event processing. With rule engine user can able to filter, enrich and transform incoming messages originated by the devices and related assets. User can also able to trigger various actions, for example, notifications or communication with external systems.
Rule Engine is an easy-to-use framework for building event-based workflows. There are three main components:
-
Message - any incoming event. It can be an incoming data from devices, RPC request, etc.
-
Rule Node - a function that is executed on an incoming message. There are many different Node types that can filter, transform or execute some action on incoming Message.
-
Rule Chain - nodes are connected with each other with relations, so the outbound message from rule node is sent to next connected rule nodes.
Key Concepts
Rule Engine Message
Rule Engine Message is a serializable, immutable data structure that represent various messages in the system. For example:
-
Incoming telemetry, attribute update or RPC call from device from device
-
Entity life-cycle event: created, updated, deleted, assigned, unassigned, attributes updated.
-
Device status event: connected, disconnected, active, inactive, etc
-
Other system events
Rule Engine Message contains the following information:
-
Message ID: time based, universally unique identifier.
-
Originator of the message: Device, Asset or other Entity identifier;
-
Type of the message: “Post telemetry” or “Inactivity Event”, etc;
-
Payload of the message: JSON body with actual message payload;
-
Metadata: List of key-value pairs with additional data about the message.
Rule Node
Rule Node is a basic component of Rule Engine that process single incoming message at a time and produce one or more outgoing messages. Rule Node is a main logical unit of the Rule Engine. Rule Node can filter, enrich, transform incoming messages, perform action or communicate with external systems.
Rule Node Connection
Rule Nodes may be connected to other rule nodes. Each relation has relation type, a label used to identify logical meaning of the relation. When rule node produces the outgoing message, it always specifies the relation type which is used to route message to next nodes.
Typical rule node relations are “Success” and “Failure”. Rule nodes that represent logical operations may use “True” or “False”. Some specific rule nodes may use completely different relation types, for example: “Post Telemetry”, “Attributes Updated”, “Entity Created”, etc.
Some rule nodes support custom connection names. Just type your custom connection name and click the “Create a new one!” link.
Rule Chain is a logical group of rule nodes and their relations. For example, the rule chain below will:
-
Save all telemetry messages to the database
-
Raise “High Temperature Alarm” if temperature field in the message will be higher then 50 degrees
-
Raise “Low Temperature Alarm” if temperature field in the message will be lower then -40 degrees
-
Log failure to execute the temperature check scripts to console in case of logical or syntax error in the script.
Root rule chain handles all incoming messages and may forward them to other rule chains for additional processing. Other rule chains may also forward messages to different rule chains.
For example, the rule chain below will:
-
Raise “High Temperature Alarm” if temperature field in the message will be higher than 50 degrees.
-
Clear “High Temperature Alarm” if temperature field in the message will be less than 50 degrees.
-
Forward events about “Created” and “Cleared” alarms to external rule chain that handles notifications to corresponding users.
Message Processing Result
There are three possible results of message processing: Success, Failure and Timeout.
The message processing attempt is marked as “Success” when the last rule node in the processing chain successfully process the message.
The message processing attempt is marked as “Failure” if one of the rule nodes produce “Failure” of message processing, and there is no rule nodes to handle that failure.
The message processing attempt is marked as “Timeout” when overall time of processing exceed configurable threshold.
NOTE: If the “Transformation” script fails, the message is not marked as “Failed”, because there is a “Save to DB” node connected with “Failure” relation. If the “Transformation” script is successful, it will be pushed to “External System” with the REST API call. If the external system is overloaded, the REST API call may “hang” for some time. Let’s assume the overall timeout for message pack processing is 20 seconds. Let’s ignore Transformation script execution time because it is < 1ms. So, if the “External System” will reply within 20 seconds, the message will be successfully processed. Similar, if “Save to DB” call will succeed, the message will be successfully processed. However, if the external system will not reply within 20 seconds, the message processing attempt will be marked as “timed-out”. Similar, if “Save to DB” call will fail, the message will be marked as failed.
Predefined Message Types
List of the predefined Message Types is presented in the following table:
|
Message Type
|
Display Name |
Description |
Message Metadata |
|
POST_ATTRIBUTES_REQUEST |
Post Attributes |
Request from device to publish client side attributes |
deviceName - originator device name deviceType - originator device type
|
|
POST_TELEMETRY_REQUEST |
Post Telemetry |
Request from device to publish telemetry |
deviceName - originator device name deviceType - originator device type ts - timestamp (milliseconds)
|
|
TO_SERVER_RPC_REQUEST |
RPC Request from Device |
RPC request from device |
deviceName - originator device name deviceType - originator device type requestId - RPC request Id provided by client
|
|
RPC_CALL_FROM_SERVER_TO_DEVICE |
RPC Request to Device |
RPC request from server to device |
requestUUID - internal request id used by sustem to identify reply target expirationTime - time when request will be expired oneway - specifies request type: true - without response, false - with response
|
|
ACTIVITY_EVENT |
Activity Event |
Event indicating that device becomes active |
deviceName - originator device name deviceType - originator device type
|
|
INACTIVITY_EVENT |
Inactivity Event |
Event indicating that device becomes inactive |
deviceName - originator device name deviceType - originator device type
|
|
CONNECT_EVENT |
Connect Event |
Event produced when device is connected |
deviceName - originator device name deviceType - originator device type
|
|
DISCONNECT_EVENT |
Disconnect Event |
Event produced when device is disconnected |
deviceName - originator device name deviceType - originator device type
|
|
ENTITY_CREATED |
Entity Created |
Event produced when new entity was created in system |
userName - name of the user who created the entity userId - the user Id
|
|
ENTITY_UPDATED |
Entity Updated |
Event produced when existing entity was updated |
userName - name of the user who updated the entity userId - the user Id
|
|
ENTITY_DELETED |
Entity Deleted |
Event produced when existing entity was deleted |
userName - name of the user who deleted the entity userId - the user Id
|
|
ENTITY_ASSIGNED |
Entity Assigned |
Event produced when existing entity was assigned to customer |
userName - name of the user who performed assignment operation userId - the user Id assignedCustomerName - assigned customer name assignedCustomerId - Id of assigned customer
|
|
ENTITY_UNASSIGNED |
Entity Unassigned |
Event produced when existing entity was unassigned from customer |
userName - name of the user who performed unassignment operation userId - the user Id unassignedCustomerName - unassigned customer name unassignedCustomerId - Id of unassigned customer
|
|
ATTRIBUTES_UPDATED |
Attributes Updated |
Event produced when entity attributes update was performed |
userName - name of the user who performed attributes update userId - the user Id scope - updated attributes scope (can be either SERVER_SCOPE or SHARED_SCOPE)
|
|
ATTRIBUTES_DELETED |
Attributes Deleted |
Event produced when some of entity attributes were deleted |
userName - name of the user who deleted attributes userId - the user Id scope - deleted attributes scope (can be either SERVER_SCOPE or SHARED_SCOPE)
|
|
ALARM |
Alarm Event |
Event produced when an alarm was created, updated or deleted |
All fields from original Message Metadata isNewAlarm - true if a new alram was just created isExistingAlarm - true if an alarm is existing already isClearedAlarm - true if an alarm was cleared
|
|
ALARM_ASSIGNED |
Alarm Assigned |
Event produced when an alarm was assigned to some user |
All fields from original Message Metadata entityName - name of alarm entityType - ALARM userEmail - user email userFirstName - user first name userId - user id userLastName - user last name userName - user name
|
|
ALARM_UNASSIGNED |
Alarm Unassigned |
Event produced when an alarm was unassigned from user |
All fields from original Message Metadata entityName - name of alarm entityType - ALARM userEmail - user email userFirstName - user first name userId - user id userLastName - user last name userName - user name
|
|
COMMENT_CREATED |
Comment Created |
Event produced when an alarm comment was created |
All fields from original Message Metadata userId - user id userName - user name userFirstName - first name of user userLastName - last name of user userEmail - email of user comment - json object containing comment details and text of comment
|
|
COMMENT_UPDATED |
Comment Updated |
Event produced when an alarm comment was updated |
All fields from original Message Metadata userId - user id userName - user name userFirstName - first name of user userLastName - last name of user userEmail - email of user comment - json object containing comment details and text of comment
|
|
REST_API_REQUEST |
REST API Request to Rule Engine |
Event produced when user executes REST API call |
requestUUID - the unique request id expirationTime - the expiration time of the request
|
Rule Chain
Rule chain - nodes are connected with each other with relations, so the outbound message from rule node is sent to next connected rule nodes.
Rule chains page displays a table of configured tenant rule chains. User can create, export/import, delete, and mark the desired rule chain as root.
To add a new rule chain:
-
Navigate to the "Rule chains" page. Then click on the "plus" icon in the upper right corner, and select "Create new rule chain"
-
Specify a name for the rule chain. If necessary, enable "Debug mode". Click "Add"
-
The new rule chain is created. To open rule chain click on it.
Edit Rule Chain
User can edit the name and description rows as well as enable/disable debug mode:
-
Navigate to the "Rule chains" page and click on the "Rule chain details" icon opposite the rule chain`s name to edit
-
The rule chain details window will open. Click on the "pencil" icon to enter edit mode
-
Edit name for this rule chain and enable debug mode. After that, click on the "Apply changes" button
Export/Import Rule Chain
User can able to export rule chain to а JSON file and import it to the same or another OCS360 platform instance.
Export Rule Chain
To utilize the Export Rule Chain:
-
Navigate to the "Rule chains" page and click on the "Export rule chain" icon located on the particular rule chain row. A JSON file containing the rule chain configuration will be saved to PC.
Import Rule Chain
To utilize the Import Rule Chain from a JSON file:
-
Navigate to the "Rule chains" page and click on the "+" button in the upper right corner of the screen and then choose "Import rule chain" option
-
The toolbar import popup window will appear. Upload a JSON file and click on the "Import" button
-
The imported rule chain will open. Click on the "Apply changes" button to save the rule chain. Then, go back to the main "Rule chains" page
NOTE: All imported rule chains are not root rule chains.
Make Rule Chain Root
To make a Rule Chain Root:
-
Navigate to the "Rule chains" page and click on the "Make rule chain root" button located on the particular rule chain row
-
Please confirm your actions in the dialog box
-
The selected rule chain has now become the root.
Delete Rule Chain
User can delete a rule chain using one of the following ways:
First option:
-
Click a trash icon can opposite the rule chains`s name to delete
-
Confirm deleting the rule chain in the dialog box.
Second option:
-
Click on the "Rule chain details" button located on the particular rule chain row
-
In the rule chain details, click on the "Delete rule chain" button
-
Confirm deleting the rule chain in the dialog box.
-
To delete multiple rule chains, mark one or multiple rule chains to delete. Click on the trash bin icon in the top right corner
All available rule nodes are grouped in correspondence with their nature:
-
Filter Nodes are used for message filtering and routing
-
Enrichment Nodes are used to update meta-data of the incoming Message
-
Transformation Nodes are used for changing incoming Message fields like Originator, Type, Payload, Metadata
-
Action Nodes execute various actions based on incoming Message
Configuration
-
Each Rule Node may have specific configuration parameters that depend on the Rule Node Implementation.
-
Rule Node configuration window may be opened by double-clicking on the node in the Rule Chain editor:
Test Script Functions
-
Some rule nodes have specific UI feature that allow users to test Java script functions. Once user click on the Test Filter Function Java script editor will get displayed that allows users to substitute input parameters and verify the output of the function.
User can define:
• Message Type in the top left field.
• Message Payload in the left Message section.
• Metadata in right Metadata section.
After pressing Test output will be returned in right Output section.
Debugging
OCS360 Platform provides ability to review incoming and outgoing messages for each Rule Node. To enable debug, user need to ensure that “Debug mode” checkbox is selected in the main configuration window.
Once debug is enabled, user can see incoming and outgoing messages info as long as corresponding relation types.
Rule Node Types
Filter Nodes
Filter Nodes are used for Message filtering and routing. Available filter nodes are as below:
Asset Profile Switch
Route incoming messages based on the name of the asset profile. The asset profile name is case-sensitive.
Output - The output connection of the rule node corresponds to the asset profile name.
Device Profile Switch
Route incoming messages based on the name of the device profile. The device profile name is case-sensitive.
Output - The output connection of the rule node corresponds to the device profile name.
Check Alarm Status
Checks the Alarm status to match one of the specified statuses.
Configuration
• Alarm status filter - Contains list of alarms statuses:
Available statuses are “Active Acknowledged”, “Active Unacknowledged”, “Cleared Acknowledged”, “Cleared Unacknowledged”
Output
• Output connection types: “True” or “False”
Check Fields Presence
Checks the presence of the specified fields in the message and/or metadata. Both message and metadata is typically a JSON object. User specifies message and/or metadata field names in the configuration.
Configuration
• Message field names - list of field names that should be present in the message.
• Metadata field names - list of field names that should be present in the metadata.
• ‘Check that all specified fields are present’ checkbox - check the presence of all (if checked) or of at least one field (if unchecked).
Output
• Output connection types: “True” or “False”
Check Relation
Checks the presence of the Relation between the originator of the message and other entities. If ‘check relation to specific entity’ is selected, one must specify a related entity. Otherwise, the rule node checks the presence of a relation to any entity that matches the direction and relation type criteria.
Configuration
• ‘Check relation to specific entity’ checkbox enables configuration of specific entity used to check the relation.
• Direction - configures direction of the relation. It is either ‘From’ or ‘To’. The value corresponds to direction of the relation from the specific/any entity to the originator. See example.
• Relation type - arbitrary relation type. Default relation types are ‘Contains’ and ‘Manages’, but you may create relation of any type.
Output
• Output connection types: “True” or “False”
Entity Type
Filter incoming messages by the type of message originator entity. Checks that the entity type of the incoming message originator matches one of the values specified in the filter.
Configuration
• Originator types filter - list of entity types: Device, Asset, User, etc.
Output
• Output connection types: “True” or “False”
Entity Type Switch
Switch incoming messages by the type of message originator entity.
Output
• The output connection of the rule node corresponds to the entity type of the message originator. For example: “Device”, “Asset”, “User”, etc.
Message Type
Filter incoming messages based on one or more predefined or custom message types. Checks that the message type of the incoming message matches one of the values specified in the filter.
Configuration
• Message types filter - list of predefined message types. Custom message types are supported as well.
Output
• Output connection types: “True” or “False”
Message Type Switch
Route incoming messages by the message type value. If incoming Message has known message type, then it is sent to the corresponding chain, otherwise, message is sent to other chain.
Output
• The output connection of the rule node corresponds to the type of the message. For example: “Device”, “Asset”, “User”, etc.
Script
Evaluates Boolean function using incoming message. The function may be written using plain JavaScript.
Script function should return boolean value and accepts three parameters.
Configuration
JavaScript function receive 3 input parameters:
• msg - is a message payload, typically a JSON object or array.
• metadata - is a message metadata. Represented as a Key-Value map. Both keys and values are strings.
• msgType - is a message type, string.
Output
• Output connection types: “True” or “False”
Switch
Routes incoming message to one OR multiple output connections. Node executes configured JavaScript function that returns array of strings (connection names).
Configuration
JavaScript function receive 3 input parameters:
• msg - is a message payload, typically a JSON object or array.
• metadata - is a message metadata. Represented as a Key-Value map. Both keys and values are strings.
• msgType - is a message type, string.
The script should return an array of next Relation names where Message should be routed. If returned array is empty - message will not be routed to any Node and discarded.
Output
• The output connection of the rule node corresponds to the result of the script execution.
Calculate Delta
Calculates ‘delta’ based on the previous time-series reading and current reading and adds it to the message. Delta calculation is done in scope of the message originator, e.g. device, asset or customer. Useful for smart-metering use case. For example, when the water metering device reports the absolute value of the pulse counter once per day. To find out the consumption for the current day user need to compare value for the previous day with the value for current day.
Delta calculation is done in scope of the message originator, e.g. device, asset or customer.
Configuration Parameters:
-
Input value key (‘pulseCounter’ by default) - specifies the key that will be used to calculate the delta.
-
Output value key (‘delta’ by default) - specifies the key that will store the delta value in the enriched message.
-
Decimals - precision of the delta calculation.
-
Use cache for latest value (‘enabled’ by default) - enables caching of the latest values in memory.
-
Tell ‘Failure’ if delta is negative (‘enabled’ by default) - forces failure of message processing if delta value is negative.
-
Add period between messages (‘disabled’ by default) - adds value of the period between current and previous message.
Rule Node Relations:
The rule node produces message with one of the following relations:
-
Success - if the key configured via ‘Input value key’ parameter is present in the incoming message
-
Other - if the key configured via ‘Input value key’ parameter is not present in the incoming message
-
Failure - if the ‘Tell ‘Failure’ if delta is negative’ is set and the delta calculation returns negative value
Customer Attributes
Node finds Customer of the Message Originator entity and adds Customers Attributes or Latest Telemetry value into Message Metadata.
Administrator can configure the mapping between original attribute name and Metadata attribute name.
There is a 'Latest Telemetry' checkbox in the Node configuration. If this checkbox selected, Node will fetch Latest telemetry for configured keys. Otherwise, Node will fetch server scope attributes.
Outbound Message Metadata will contain configured attributes if they exist. To access fetched attributes in other nodes user can use this template ‘metadata.temperature’.
The following Message Originator types are allowed: Customer, User, Asset, Device.
If an unsupported Originator type is found, an error is thrown.
If the Originator does not have an assigned Customer Entity, the 'Failure' chain is used, otherwise the 'Success' chain is used.
NOTE: User use ${metadataKey} for value from metadata, $[messageKey] for value from the message body.
Device Attributes
Node finds the Related Device of the Message Originator Entity using configured query and adds Attributes (client\shared\server scope) and Latest Telemetry value into Message Metadata.
Attributes are added into metadata with scope prefix:
• shared attribute -> shared_
• client attribute -> cs_
• server attribute -> ss_
• telemetry -> no prefix used
For example, the shared attribute ‘version’ will be added into Metadata with the name ‘shared_version’. Client attributes will use ‘cs_’ prefix. Server attributes use ‘ss_’ prefix. Latest telemetry value added into Message Metadata as is, without prefix.
In ‘Device relations query’ configuration, the Administrator can select the required Direction and Relation Depth Level. Also Relation Type can be configured with required set of Device Types.
If multiple Related Entities were found, only the first Entity is used for attributes enrichment, other entities will be discarded.
Failure Chain is used if no Related Entity was found, otherwise - the Success Chain is used.
If attribute or telemetry was not found, it is not added into Message Metadata and still routed via the Success chain.
Outbound Message Metadata will contain configured attributes only if they exist.
To access fetched attributes in other nodes you can use this template ‘metadata.temperature’
NOTE: The Rule Node has the ability to enable/disable reporting Failure if at least one selected key doesn’t exist in the outbound message.
Originator Fields
Node fetches field values of the Message Originator Entity and adds them into Message Metadata. Administrator can configure the mapping between field name and Metadata attribute name. If specified field is not part of Message Originator entity fields, it will be ignored.
The following Message Originator types are allowed: Tenant, Customer, User, Asset, Device, Alarm, Rule Chain.
Failure Chain is used if an unsupported Originator Type is found, otherwise - the Success Chain is used.
If field value was not found, it is not added into Message Metadata and still routed via the Success Chain.
Outbound Message Metadata will contain configured attributes only if they exist.
To access fetched attributes in other nodes you can use this template ‘metadata.devType’
Related Attributes
Node finds Related Entity of the Message Originator Entity using configured query and adds Attributes or Latest Telemetry value into Message Metadata.
Administrator can configure the mapping between original attribute name and Metadata attribute name.
In ‘Relations query’ configuration Administrator can select required Direction and Relation Depth Level. Also set of Relation Filters can be configured with required Relation type and Entity Types.
There is Latest Telemetry checkbox in the Node configuration. If this checkbox selected, Node will fetch Latest telemetry for configured keys. Otherwise, Node will fetch server scope attributes.
If multiple Related Entities are found, only first Entity is used for attributes enrichment, other entities are discarded.
If no Related Entity is found the Failure Chain is used, otherwise the Success Chain is used.
Outbound Message Metadata will contain configured attributes if they exist.
To access fetched attributes in other nodes user can use this template ‘metadata.tempo’
NOTE: User can use ${metadataKey} for value from metadata, $[messageKey] for value from the message body.
Tenant Attributes
Node finds Tenant of the Message Originator entity and adds Tenant Attributes or Latest Telemetry value into Message Metadata.
Administrator can configure the mapping between original attribute name and Metadata attribute name.
There is a Latest Telemetry checkbox in the Node configuration. If this checkbox selected, Node will fetch Latest telemetry for configured keys. Otherwise, Node will fetch server scope attributes.
Outbound Message Metadata will contain configured attributes if they exist. To access fetched attributes in other nodes user can use this template ‘metadata.tempo’
Following Message Originator types are allowed: Tenant, Customer, User, Asset, Device, Alarm, Rule Chain.
If an unsupported Originator type is found, an error is thrown.
Failure Chain is used if Originator does not have an assigned Tenant Entity, otherwise - the Success Chain is used.
NOTE: User can use ${metadataKey} for value from metadata, $[messageKey] for value from the message body.
Originator Telemetry
Adds Message Originator telemetry values from a particular time range that was selected in Node Configuration to the Message Metadata.
Telemetry values added to Message Metadata without prefix.
The rule node has three fetch modes:
-
First: retrieves telemetry from the database that is closest to the beginning of the time range
-
Last: retrieves telemetry from the database that is closest to the end of the time range
-
All: retrieves all telemetry from the database, which is in the specified time range.
If selected fetch mode is First or Last, the Outbound Message Metadata would contain JSON elements(key/value)
Otherwise if the selected fetch mode is All, the telemetry would be fetched as an array.
NOTE: The rule node can extract a limit size of records into array: 1000 records
This array will contain JSON objects with the timestamp and value.
NOTE: The end of the interval must always be less than the beginning of the interval.
If selected checkbox: 'Use metadata interval patterns', Rule Node will use Start Interval and End Interval patterns from metadata.
Patterns units sets in the milliseconds since the UNIX epoch (January 1, 1970 00:00:00 UTC)
-
If any pattern will be absent in the Message metadata, the outbound message will be routed via failure chain.
-
In addition, if any pattern will have invalid data type, the outbound message will be also routed via failure chain.
Outbound Message Metadata will contain configured telemetry fields if they exist and belong to the selected range.
If attribute or telemetry was not found, it is not added into Message Metadata and is still routed via the Success Chain.
To access fetched telemetry in other nodes user can use this template: JSON.parse(metadata.temperature)
NOTE: The Rule Node has the ability to choose telemetry sampling order when selected Fetch mode: ALL.
Tenant Details
Rule Node Adds fields from Tenant details to the message body or metadata.
There is 'Add selected details to the message metadata' checkbox in the Node configuration. If this checkbox selected, existing fields will be added to the message metadata instead of message data.
Selected details are added into metadata with prefix: tenant_. Outbound Message will contain configured details if they exist.
To access fetched details in other nodes user can use one of the following template:
• metadata.tenant_address
• msg.tenant_address
Failure Chain is used if the Originator does not have an assigned Tenant Entity, otherwise - the Success Chain is used.
Customer Details
Rule Node Adds fields from Customer details to the message body or metadata.
There is 'Add selected details to the message metadata' checkbox in the Node configuration. If this checkbox selected, existing fields will be added to the message metadata instead of message data.
Selected details are added into metadata with prefix: customer_. Outbound Message will contain configured details if they exist.
To access fetched details in other nodes user can use one of the following template:
• metadata.customer_email
• msg.customer_email
Following Message Originator types are allowed: Asset, Device, Entity View.
If an unsupported Originator type is found, an error is thrown.
If Originator does not have an assigned Customer Entity, Failure Chain is used, otherwise the Success Chain is used.
Transformation Nodes are used for changing incoming Message fields like Originator, Message Type, Payload and Metadata.
Change Originator
All incoming Messages in the OCS360 platform have an Originator field that identifies an Entity that submits a Message. It could be a Device, Asset, Customer, Tenant, etc.
This node is used in cases when a submitted message should be processed as a message from another entity. For example, Device submits telemetry and telemetry should be copied into higher level Asset or to a Customer. In this case, Administrator should add this node before Saving the Timeseries Node.
The originator can be changed to:
• Originator’s Customer
• Originator’s Tenant
• Related Entity that is identified by Relations Query
In ‘Relations query’ configuration Administrator can select required Direction and Relation Depth Level. Also set of Relation Filters can be configured with required Relation Type and Entity Types.
If multiple Related Entities are found, only the first Entity is used as new originator, other entities are discarded.
Failure Chain is used if no Related Entity / Customer / Tenant was found, otherwise - the Success chain is used.
Outbound Message will have new Originator ID.
Script Transformation Node
Changes Message payload, Metadata or Message type using configured JavaScript function.
JavaScript function receives 3 input parameters:
• msg - is a Message payload.
• metadata - is a Message metadata.
• msgType - is a Message type.
Script should return the following structure:
{ msg: new payload, metadata: new metadata, msgType: new msgType }
All fields in resulting object are optional and will be taken from original message if not specified.
Outbound Message from this Node will be new Message that was constructed using configured JavaScript function.
Example:
Node receives Message with payload:
{ "temperature": 22.4,"humidity": 78 }
Original Metadata:
{ "sensorType" : "temperature" }
Original Message Type - POST_TELEMETRY_REQUEST
The following modifications should be performed:
• Change message type to ‘CUSTOM_UPDATE’
• Add additional attribute Version into payload with value v1.1
• Change SensorType attribute value in Metadata to RoomTemp
The following transform function will perform all necessary modifications:
var newType = "CUSTOM_UPDATE";
msg.version = "v1.1";
metadata.sensorType = "roomTemp"
return {msg: msg, metadata: metadata, msgType: newType};
To Email Node
Transforms message to Email Message by populating email fields using values derived from Message metadata. Set ‘SEND_EMAIL’ output Message type that can be accepted later by Send Email Node. All email fields can be configured to use values from metadata. Supports sending of HTML pages and images.
For example incoming message has deviceName field in metadata and email body should contain its value.
In this case value of deviceName can be referenced as ${deviceName} like in the following example:
Device ${deviceName} has high temperature
If user like to send html or image choose HTML or Dynamic in field Mail Body Type.
Action Node
Action Nodes execute various actions based on incoming Message.
Math Function Node
The Rule Node applies math function and saves the result into the message and/or database. See table of supported functions below:
|
Function
|
Number of Arguments |
Description |
|
ADD |
2 |
x + y |
|
SUBTRACT |
2 |
x - y |
|
MULTIPLY |
2 |
x * y |
|
DIVIDE |
2 |
x / y |
|
SIN |
1 |
Returns the trigonometric sine of an angle. |
|
SINH |
1 |
Returns the hyperbolic sine of a double value. The hyperbolic sine of x is defined to be (ex - e-x)/2 where e is Euler’s number. |
|
COS |
1 |
Returns the trigonometric cosine of an angle. |
|
COSH |
1 |
Returns the hyperbolic cosine of a double value. The hyperbolic cosine of x is defined to be (ex + e-x)/2 where e is Euler’s number. |
|
TAN |
1 |
Returns the trigonometric tangent of an angle. |
|
TANH |
1 |
Returns the hyperbolic tangent of a double value. |
|
ACOS |
1 |
Returns the arc cosine of a value; the returned angle is in the range 0.0 through pi. |
|
ASIN |
1 |
Returns the arc sine of a value; the returned angle is in the range -pi/2 through pi/2. |
|
ATAN |
1 |
Returns the arc tangent of a value; the returned angle is in the range -pi/2 through pi/2. |
|
ATAN2 |
2 |
Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta). |
|
EXP |
1 |
Returns the value ex, where e is the base of the natural logarithms. |
|
EXPM1 |
1 |
Returns ex-1. Note that for values of x near 0, the exact sum of expm1(x) + 1 is much closer to the true result of ex than exp(x). |
|
SQRT |
1 |
Returns the correctly rounded positive square root of a double value. |
|
CBRT |
1 |
Returns the cube root of a double value. |
|
GET_EXP |
1 |
Returns the unbiased exponent used in the representation of a double. |
|
HYPOT |
2 |
Returns sqrt(x2 +y2) without intermediate overflow or underflow. |
|
LOG |
1 |
Returns the natural logarithm (base e) of a double value. |
|
LOG10 |
1 |
Returns the base 10 logarithm of a double value. |
|
LOG1P |
1 |
Returns the natural logarithm of the sum of the argument and 1. Note that for small values x, the result of log1p(x) is much closer to the true result of ln(1 + x) than the floating-point evaluation of log(1.0+x). |
|
CEIL |
1 |
Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. |
|
FLOOR |
1 |
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. |
|
FLOOR_DIV |
2 |
Returns the largest (closest to positive infinity) long value that is less than or equal to the algebraic quotient. |
|
FLOOR_MOD |
2 |
Returns the floor modulus of the long arguments. |
|
ABS |
1 |
Returns the absolute value of a double value. |
|
MIN |
2 |
Returns the smaller of two double values. |
|
MAX |
2 |
Returns the greater of two double values. |
|
POW |
2 |
Returns the value of the first argument raised to the power of the second argument. |
|
SIGNUM |
1 |
Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero. |
|
RAD |
1 |
Converts an angle measured in degrees to an approximately equivalent angle measured in radians. |
|
DEG |
1 |
Converts an angle measured in radians to an approximately equivalent angle measured in degrees. |
|
CUSTOM |
1-16 |
Use this function to specify complex math expressions. For example, transform Fahrenheit to Celsius using (x - 32) / 1.8) |
5 types of arguments can be used:
-
Constant
-
Value from the message body
-
Value from the message meta data
-
Value of the attribute that belongs to the message originator (device, asset, etc). Value should be of Numeric type or string that is convertible to float
-
Value of the latest time-series that belongs to the message originator (device, asset, etc). Value should be of Numeric type or string that is convertible to float
Primary use case for this Rule Node is to take one or more values from the database and modify them based on data from the message.
Alternative use case is the replacement of simple JS script nodes with more lightweight and performant implementation. For example, to transform Fahrenheit to Celsius (C = (F - 32) / 1.8) using CUSTOM operation and expression: (x - 32) / 1.8).
The execution is synchronized in scope of the message originator (e.g. device) and server node. If user has Rule Nodes in different Rule Chains, they will process messages from the same originator synchronously in the scope of the server node.
The result of the function may be added to the message body or metadata. User may also save the result to the database as an attribute or time-series.
This Node tries to load the latest Alarm with configured Alarm Type for Message Originator. If Uncleared Alarm exist, then this Alarm will be updated, otherwise a new Alarm will be created.
Node Configuration:
-
Alarm Details Builder script
-
Alarm Type - any string that represents Alarm Type
-
Alarm Severity - {CRITICAL | MAJOR | MINOR | WARNING | INDETERMINATE}
-
Is Propagate - whether Alarm should be propagated to all parent related entities.
NOTE: Rule node has the ability to:
-
Read alarm config from message
-
Get alarm type using pattern with fields from message metadata
-
Filter propagation to parent entities by relation types
Alarm Details Builder - script used for generating Alarm Details JsonNode. It is useful for storing additional parameters inside Alarm. For example, user can save attribute name/value pair from Original Message payload or Metadata.
Alarm Details Builder script should return details object.
-
Message payload can be accessed via msg property. For example msg.temperature
-
Message metadata can be accessed via metadata property. For example metadata.customerName
-
Message type can be accessed via msgType property. For example msgType
Optional: previous Alarm Details can be accessed via metadata.prevAlarmDetails. If previous Alarm does not exist, this field will not be present in Metadata.
NOTE: Metadata.prevAlarmDetails is a raw String field and it needs to be converted into object using this construction:
var details = {};
if (metadata.prevAlarmDetails) { details = JSON.parse(metadata.prevAlarmDetails); }
Alarm Details Builder script function can be verified using Test JavaScript function.
Example of Details Builder Function:
This function takes count property from previous Alarm and increment it. Also put temperature attribute from inbound Message payload into Alarm details.
var details = {temperature: msg.temperature, count: 1};
if (metadata.prevAlarmDetails) {
var prevDetails = JSON.parse(metadata.prevAlarmDetails);
if(prevDetails.count) {
details.count = prevDetails.count + 1; }
} return details
Alarm created/updated with those properties:
-
Alarm details - object returned from Alarm Details Builder script
-
Alarm status - if New Alarm -> ACTIVE_UNACK. If Existing Alarm -> does not change
-
Severity - value from Node Configuration
-
Propagation - value from Node Configuration
-
Alarm type - value from Node Configuration
-
Alarm start time - if New Alarm -> current system time. If Existing Alarm -> does not change
-
Alarm end time - current system time
Outbound message will have the following structure:
-
Message Type - ALARM
-
Originator - the same originator from inbound Message
-
Payload - JSON representation of new Alarm that was created/updated
-
Metadata - all fields from original Message Metadata
After new Alarm created, Outbound message will contain additional property inside Metadata - isNewAlarm with true value. Message will be passed via Created Chain.
After existing Alarm updated, Outbound message will contain additional property inside Metadata - isExistingAlarm with true value. Message will be passed via Updated Chain.
This Node loads the latest Alarm with configured Alarm Type for Message Originator and Clear the Alarm if it exists.
Node Configuration:
-
Alarm Details Builder script
-
Alarm Type - any string that represents Alarm Type
NOTE: the rule node has the ability to get alarm type using pattern with fields from message metadata:
Alarm Details Builder script used for updating Alarm Details JsonNode. It is useful for storing additional parameters inside Alarm. For example user can save attribute name/value pair from Original Message payload or Metadata.
Alarm Details Builder script should return details object.
-
Message payload can be accessed via msg property. For example msg.temperature
-
Message metadata can be accessed via metadata property. For example metadata.customerName
-
Message type can be accessed via msgType property. For example msgType
-
Current Alarm Details can be accessed via metadata.prevAlarmDetails.
NOTE: Metadata.prevAlarmDetails is a raw String field and it needs to be converted into object using this construction:
var details = {};
if (metadata.prevAlarmDetails) {
details = JSON.parse(metadata.prevAlarmDetails);
}
Alarm Details Builder script function can be verified using TestJava Script function.
Example of Details Builder Function:
This function takes Count property from previous Alarm and increment it. Also put temperature attribute from inbound Message payload into Alarm details.
var details = {temperature: msg.temperature, count: 1};
if (metadata.prevAlarmDetails) {
var prevDetails = JSON.parse(metadata.prevAlarmDetails);
if(prevDetails.count) {
details.count = prevDetails.count + 1;
}
}
return details;
This Node updates Current Alarm:
-
Change alarm status to CLEARED_ACK if it was already acknowledged, otherwise to CLEARED_UNACK
-
Set clear time to current system time
-
Update Alarm details with new object returned from Alarm Details Builder script
In case when the Alarm does not exist or it is already a Cleared Alarm, original Message will be passed to the next nodes via False Chain.
Otherwise new Message will be passed via Cleared Chain.
Outbound message will have the following structure:
-
Message Type - ALARM
-
Originator - the same originator from inbound Message
-
Payload - JSON representation of Alarm that was cleared
-
Metadata - all fields from original Message Metadata. Also additional property inside Metadata will be added -> isClearedAlarm with true value.
Here is an example of Outbound Message payload
{
"tenantId": {
"entityType": "TENANT",
"id": "22cd8888-5dac-11e8-bbab-ad47060c9bbb"
},
"type": "High Temperature Alarm",
"originator": {
"entityType": "DEVICE",
"id": "11cd8777-5dac-11e8-bbab-ad55560c9ccc"
},
"severity": "CRITICAL",
"status": "CLEARED_UNACK",
"startTs": 1526985698000,
"endTs": 1526985698000,
"ackTs": 0,
"clearTs": 1526985712000,
"details": {
"temperature": 70,
"ts": 1526985696000
},
"propagate": true,
"id": "33cd8999-5dac-11e8-bbab-ad47060c9431",
"createdTime": 1526985698000,
"name": "High Temperature Alarm"
}
Generates Messages with configurable period. JavaScript function is used for message generation.
Node Configuration:
-
Message generation frequency in seconds
-
Message originator
-
JavaScript function that will generate the actual message.
JavaScript function receive 3 input parameters:
-
PrevMsg - is a previously generated Message payload.
-
PrevMetadata - is a previously generated Message metadata.
-
PrevMsgType - is a previously generated Message type.
Script should return the following structure:
{
msg: new payload,
metadata: new metadata,
msgType: new msgType
}
All fields in resulting object are optional and will be taken from previously generated Message if not specified.
Outbound Message from this Node will be new Message that was constructed using configured JavaScript function.
JavaScript generator function can be verified using Test JavaScript function.
This node can be used for Rule Chain debugging purposes.
Sends response to the RPC Call originator. All incoming RPC requests are passed through Rule Chain as Messages. Also all RPC requests have request ID field. It is used for mapping requests and responses. Message Originator must be a Device Entity because RPC response is initiated to the Message Originator.
Node configuration has special request ID field mapping. If the mapping is not specified, requestId metadata field is used by default.
Message will be routed via Failure Chain in the following cases:
-
Inbound Message originator is not a Device entity
-
Request id is not present in the Message metadata
-
Inbound Message payload is empty
Sends RPC requests to the Device and routing response to the next Rule nodes. Message Originator must be a Device entity as RPC request can be initiated only to device.
Node configuration has Timeout field used to specify timeout waiting for response from device.
Message payload must have correct format for RPC request. It must contains method and params fields.
If Message Payload contains requestId field, its value used to identify RPC request to the Device. Otherwise random requestId will be generated.
Outbound Message will have same originator and metadata as in inbound Message. Response from the Device will be added into Message payload.
Message will be routed via Failure Chain in the following cases:
-
Inbound Message originator is not a Device Entity
-
Inbound Message has missed method or params fields
-
If Node will not receive a response during configured timeout
Otherwise Message will be routed via Success Chain.
Stores attributes from incoming Message payload to the database and associate them to the Entity, that is identified by the Message Originator. Configured scope is used to identify attributes scope.
Supported scope types:
-
Client attributes
-
Shared attributes
-
Server attributes
Expects messages with POST_ATTRIBUTES_REQUEST message type. If message Type is not POST_ATTRIBUTES_REQUEST, Message will be routed via Failure Chain.
When attributes are uploaded over MQTT Message with correct payload and type will be passed into Input node of the Root Rule Chain.
In cases when it is required to trigger attributes saving inside Rule Chain, the Rule Chain should be configured to transform Message payload to the expected format and set message type to POST_ATTRIBUTES_REQUEST. It could be done using Script Transformation Node.
After successful attributes saving, original Message will be passed to the next nodes via Success Chain, otherwise the Failure Chain is used.
Stores Timeseries data from incoming Message payload to the database and associate them to the Entity, that is identified by the Message Originator. Configured TTL seconds is used for timeseries data expiration. 0 value means that data will never expire.
Additionally, user can disable updating values for incoming keys for the latest timeseries data if ‘Skip latest persistence’ flag is set to true. This could be helpful for highly loaded use-cases to decrease the load on the DB. Please note, this feature could be enabled when the use-case does not require advanced filtering on the Dashboards. For getting the latest value, the historical data could be fetched with limit 1 and DESC order.
Expects messages with POST_TELEMETRY_REQUEST message type. If message Type is not POST_TELEMETRY_REQUEST, Message will be routed via Failure chain.
When timeseries data is published over MQTT Message with correct payload and type will be passed into Input node of the Root Rule Chain.
In cases when it is required to trigger timeseries data saving inside Rule Chain, the Rule Chain should be configured to transform Message payload to the expected format and set message type to POST_TELEMETRY_REQUEST. It could be done using Script Transformation Node.
Message Metadata must contain ts field. This field identifies timestamp in milliseconds of published telemetry.
Also, if Message Metadata contains TTL field, its value is used for timeseries data expiration, otherwise TTL from Node Configuration is used.
User can enable ‘useServerTs’ param to use the timestamp of the message processing instead of the timestamp from the message. Useful for all sorts of sequential processing if user merge messages from multiple sources (devices, assets, etc).
Expected Message Payload example:
{
"values": {
"key1": "value1",
"key2": "value2"
}
}
After successful timeseries data saving, original Message will be passed to the next nodes via the Success Chain, otherwise the Failure Chain is used.
Assign Message Originator Entity to Customer.
Following Message Originator types are allowed: Asset, Device, Entity View, Dashboard.
Finds target Customer by customer name pattern and then assign Originator Entity to this customer.
Will create new Customer if it doesn’t exists and Create new Customer if not exists is set to true.
Configuration:
-
Customer name pattern - can be set direct customer name or pattern can be used, that will be resolved to the real customer name using Message metadata.
-
Create new customer if not exists - if checked will create new customer if it doesn’t exist.
-
Customers cache expiration time - specifies maximum time interval is seconds allowed to store found customers records. 0 value means that records will never expire.
-
Message will be routed via Failure Chain in the following cases:
-
When Originator entity type is not supported.
-
Target customer doesn’t exist and Create customer if not exists is unchecked.
In other cases Message will be routed via the Success Chain.
Unassign Message Originator Entity from Customer
Following Message Originator types are allowed: Asset, Device, Entity View, Dashboard.
Finds target Customer by customer name pattern and then unassign Originator Entity from this customer.
Configuration:
Customer name pattern - can be set direct customer name or pattern can be used, that will be resolved to the real customer name using Message metadata.
-
Customers cache expiration time - specifies maximum time interval is seconds allowed to store found customers records. 0 value means that records will never expire.
Message will be routed via theFailure Chain in the following cases:
-
When Originator entity type is not supported.
-
Target customer doesn’t exist.
In other cases Message will be routed via the Success Chain.