Skip to main content

Rules Engine

Overview

The Rules Engine helps automate message processing using visual workflows composed of input sources, logic evaluations, and output destinations. Users can define rules by visually combining input, logic, and output nodes to determine how incoming messages are processed, evaluated, and responded to.

Features

  • Create Rules: Define the name of a new rule and initiate creation.
  • Quick Actions: View, copy ID, enable/disable, or delete a rule directly from the list.
  • Input Nodes: Attach an MQTT subscriber input by selecting the channel and topic.
  • Logic Nodes: Use either comparison blocks or Lua scripts to define logic conditions.
  • Output Nodes: Output processed data to MQTT publishers, Email recipients, or PostgreSQL databases.
  • Lua Script Integration: Use custom Lua scripts with a required logicFunction() for advanced logic.
  • Templated Messaging: Use {{result}}, {{result.key}}, and {{message.key}} to inject dynamic values into messages.
  • Scheduling: Define execution windows with start time, specific time, recurring intervals, and periods.
  • Connection Layout: Visually connect all nodes to complete and activate a rule.

Use Cases

Here are some practical examples of how you can use the Rules Engine:

  • Temperature Alerts: Notify users by email when temperature exceeds safe limits.

  • Message Filtering: Only forward messages with specific fields or values.

  • Unit Conversion: Convert sensor data from Celsius to Fahrenheit before publishing.

Create a Rule

Navigate to the Rules section and click on the + Create button. Provide a name for your rule and click Create.

Create a new Rule

Create a Rule Dialog

After creation, the rule appears in a list with the following details:

  1. Rule Name
  2. Status (Enabled/Disabled)
  3. Creation Date

Each rule entry also has quick actions for:

  • Viewing the rule
  • Copying the rule ID
  • Enabling/Disabling the rule
  • Deleting the rule

quick links

View a Rule

Click the rule name in the rules table to open the rule’s page.

View a rule

On the rule page, you can configure the following:

1. Input Node

  • Currently, only one input node is supported per rule.

select input

  • Select MQTT Subscriber as the input type.

  • Choose the channel and topic to subscribe to.

    input variables

  • The input node will appear in the layout.

    input node

2. Logic Node

After setting the input, you can define the logic of your rule using one of two options:

  1. Comparison Block
  2. Lua Script Editor

The logic nodes support different message payloads as inputs.
To utilize the message payload, you can use message.<key> in the input. e.g., if your message is a single SenML message, you can do message.payload.v to ge the value.

Comparison Block

Use if, and and or conditions to evaluate message payloads:

comparison node

We also support nested objects message.<key>.<key> e.g., message.payload.sensor.temperature.

For SenML message formats, you can have the following option of keys:

  1. v
  2. vs
  3. vb
  4. vd
  5. s

Depending on the type of data you have you can compare the two by changing the type of the comparison value. It can either be Num , Bool or String. The comparison block also supports multiple conditions using the and or or operator

Add multiple conditions

Lua Script Editor

To write custom logic, you can select the editor option of the logic node.

editor node

This allows you to write Lua script code to process your message. Your Lua script should be wrapped in a function called logicFunction() and return a result. The result can be a primitive value or an object.

The Lua script supports the utilization of the message object that we subscribe to by using Lua tables to get any values in the message.

The editor allows you to return either a lua script table or a primitive value. Example:

Returns an object
function logicFunction()
local converted_temp = (message.payload.v * 1.8 + 32)
return {n = "Temp_fahrenheit", v = converted_temp, u = "°F", }
end
Returns a primitive
function logicFunction()
return (message.payload.v * 1.8 + 32)
end

2. Output Node

You can add one or more output nodes. The following nodes are supported:

  1. Channel publisher
  2. Email
  3. PostgreSQL
  4. alarm
  5. Magistrala DB

select output

Channel Publisher

Enables you to specify the output channel and topic. The result of the logic node is published to this topic.

Select the Channel Publisher as the output node and enter the channel and topic.

publisher variables

publisher node

Email

Send the result of message processing to specified email recipients.. Select the Email output node and enter the following information:

email variables

  • Specify one or more recipient email addresses.
  • Specify subject and body message.
Subject: Current Temperature
  • Use dynamic template fields:
    • {{result}} — the entire result from logic block
    • {{result.key}} — a specific field from the result
    • {{message.key}} — a field from the original message
Message: Current temperature in degrees celsius is {{message.payload.v}} {{message.payload.u}} while the temperature in degrees fahrenheit is {{result.value}} {{result.unit}}.

email node

PostgreSQL

Store message processing results to your PostgreSQL database. Select the PostgreSQL output node option and enter the following information:

PostgreSQL variables

  • Host
  • Port
  • Username
  • Password
  • Database name
  • Table name
  • Map data to table columns using templates
{
"channel" = "{{message.channel}}",
"value" = "{{result.value}}",
"unit" = "{{result.unit}}"
}

PostgreSQL node

Magistrala DB

To be able to store messages in the internal Magistrala DB, you need to create a rule that processes the results. More information about this is in the Store Messages section.

Magistrala DB rule example

Alarms

An alarm output will enable you to be able to generate alarms in the case where a threshold has been exceeded. More information about this node is provided in the Alarms section.

Alarm rule example

Dynamic Variables and Templates

You can inject dynamic values from your message or logic result using templating variables.

Available template variables:

VariableDescription
{{result}}Entire object or primitive value returned from the logic node
{{result.key}}Specific field from the logic result object
{{message.key}}Field from the input message

These variables work in outputs like:

  • Email (body)

  • PostgreSQL (column mapping)

Example usage in Email message
Current temperature is {{message.payload.v}}°C  or ({{result.value}}°F).

Example usage in PostgreSQL column mapping
{
channel = "{{message.channel}}",
value = "{{result.value}}",
unit = "{{result.unit}}"
}

Connecting Nodes and Save

Once you've added the input, logic, and output nodes, connect them visually in the layout. Click Save to finalize the rule.

view final rule

Enable or Disable Rules

To enable or disable a rule:

  • Use the toggle at the top right of the rule page.

    Disable rule in rule page

  • You can also enable/disable directly from the rule list using the quick actions menu

    Disable rule in quick links

Add a Scheduler

You can configure a scheduler to define when a rule executes.

Scheduler

Fields:

  • Start Time: Date when the schedule becomes active
  • Time: Time of day the rule should run
  • Recurring Interval: Unit of recurrence (e.g., daily, hourly)
  • Recurring Period: Frequency of execution (e.g., every 2 intervals = every other day/hour)

This helps automate rule execution based on custom schedules.

Store Messages

To store messages in Magistrala's internal database, you must create a Rule for this.

  • Magistrala only stores messages in SenML format.

  • You can submit data in any format(e.g, JSON), but must convert it to SenML using a Lua script. SenML format fields:

    NameLabelCBOR LabelJSON TypeXML Type
    Base Namebn-2Stringstring
    Base Timebt-3Numberdouble
    Base Unitbu-4Stringstring
    Base Valuebv-5Numberdouble
    Base Sumbs-6Numberdouble
    Base Versionbver-1Numberint
    Namen0Stringstring
    Unitu1Stringstring
    Valuev2Numberdouble
    String Valuevs3Stringstring
    Boolean Valuevb4Booleanboolean
    Data Valuevd8String (*)string (*)
    Sums5Numberdouble
    Timet6Numberdouble
    Update Timeut7Numberdouble

Example: Convert JSON to SenML

Assume your incoming payload is:

{
"temperature": 28.5,
"unit": "C",
"sensor": "room-1"
}

Use the following Lua script to convert it:

function logicFunction()
return {
n = message.payload.sensor,
v = message.payload.temperature,
t = os.time()
}
end

This returns a valid SenML message the internal DB will accept.


Then set your output node to store this result using the Magistrala internal DB option.

Storage with json input

Example: Input is SenML

If your message payload is already SenML format, you can just return the message payload directly in your Lua script function:

function logicFunction()
return message.payload
end

Storage with senml input

info

With the Rules Engine, users can easily automate data processing pipelines in a powerful and visual way by combining inputs, logical conditions, and flexible outputs.