Skip to main content

Rule System

The Rule System is a rule engine designed to trigger actions when the rule's conditions are met.

Rule Group && Rule

Rule Group organization helps to streamline the management of rules that are related and ensures consistency in the state transitions they perform. here's the key points:

  • Rule Groups are used to manage related rules.
  • Each Rule Group contains multiple rules.
  • Rules within a Rule Group modify values for the same state name.
  • Rules can have different trigger types: Time-Triggered or Data-Triggered.
  • Rule Groups help to streamline the management of related rules and ensure consistency in state transitions.

There are 4 types of rule base on condition type:

  1. Time-Triggered: Activated based on specific time schedules. Uses a cron expression to define the trigger schedule.
  2. EventData-Triggered: Triggered in response to internal Seer platform events.
  • "new_data.http": New data from HTTP sources.
  • "new_data.mqtt": New data from MQTT sources.
  • "new_data.ws": New data from WebSocket sources.
  • "new_data.simulator": New data from simulator sources.
  • "new_data.internal": New data from internal sources.
  • "alert.trigger": Triggered when an alert is created.
  • "infer.rule": Triggered when an inference rule is evaluated.
  • "infer.link": Triggered when an inference link is evaluated.
  • "rule.state_change": Triggered when a rule's state changes.
  • "task.create": Triggered when a task is created.
  • "task.ack": Triggered when a task is acknowledged.
  • "task.close": Triggered when a task is closed.
  • "task.reopen": Triggered when a task is reopened.
  1. Data-Triggered: Activated when specified data conditions are met (e.g., sensor readings exceeding thresholds).
  2. State-Time Transition: Triggered based on a combination of device state and time-based conditions.Combines current device data values with time-based persistence or duration checks. Use Case: Detecting prolonged states (e.g., temperature above threshold for more than 5 minutes).

When a condition is met, the state transition will happen and the specified rule's actions (if any) triggered. All rule will be contained in Rule Group

Rule Group && Validity

Validity is a crucial entity that manages the activation times for a group of rules. This allows you to schedule when certain rule groups should be active, based on various parameters such as weekdays, hours of the day, and specific datetime ranges.

For example, a Validity entity that is active on weekdays from 9 AM to 5 PM UTC:

const validity = new ValidityEntity({
workspace: 'myWorkspace',
name: 'Weekday Business Hours',
monday: true,
tuesday: true,
wednesday: true,
thursday: true,
friday: true,
saturday: false,
sunday: false,
startHour: 9,
endHour: 17,
utcOffset: 0,
});

Associate a RuleGroup with a Validity entity provides a flexible way to schedule the activation times for rule groups. By using the provided fields, you can create complex scheduling rules that accommodate various use cases and time zones. Understanding how to use this entity will enable you to effectively manage the activation of rules in your application.

Rule Group Example

  • example rule group records
            {
"id": 28,
"rules": [
{
"id": 794,
"conditions": [
{
"field": "occupyStartDate",
"operator": "ISOTimePassed",
"value": "{\"seconds\":300}"
}
],
"conditionType": "and-case",
"workspace": "7b6a01b4-2cf3-4e29-998b-5b1ffd59a81e",
"triggerType": "data",
"crontabExpression": null,
"triggerState": 0,
"targetState": 1,
"actionEntity": [
{
"id": 6,
"workspace": "7b6a01b4-2cf3-4e29-998b-5b1ffd59a81e",
"description": null,
"type": "alert",
"meta": null,
}
]
},
{
"id": 793,
"conditions": [
{
"field": "occupyStartDate",
"operator": "isNull",
"value": ""
}
],
"conditionType": "and-case",
"workspace": "7b6a01b4-2cf3-4e29-998b-5b1ffd59a81e",
"triggerType": "data",
"crontabExpression": null,
"triggerState": 1,
"targetState": 0,
"actionEntity": []
}
],
"description": "some text",
"field": "occupyStartDate",
"stateName": "occupyStartDate",
"deviceIds": null,
"deviceTypes": null,
"extra": null,
"workspace": "7b6a01b4-2cf3-4e29-998b-5b1ffd59a81e",
"validityEntity": []
}
  • conditions

    • field : the field name of the Seer data
    • operator : the operator to compare the value
    • value : the value to compare with the field value
    • triggerState : the state of the field that trigger the rule, 0 is narmal, > 0 is abnormal
  • target device

    • deviceIds : the Seer device id , if it is null, it will match all device
    • deviceTypes : the Seer device type, if it is null, it will match all device type
    • workspace : the Seer workspace id, rule only work for device data that matched workspace
  • targetState
    If a rule is triggered, it will change the field state to targetState. This is useful to prevent the rule from triggering repeatedly, ensuring an action that must execute only once.

    • targetState: The state of the field after the rule trigger. 0 represents normal state, while > 0 indicates an abnormal state.
  • actions
    when condition is matched, it will trigger the actions. it can be null, one or more action,

Seer Variable

  • action meta variable
    • It provides a mechanism to dynamically fetch relevant data based on Seer variable codes within the meta context of rule actions.

    • To use SEER variable, name must look like "$(VAR_NAME)" , available variable list as below

      VariableDescription
      idUnique identifier for the device.
      shortNameDenotes the device short name
      nameDenotes the device name
      typeRepresents the device type of the identified device.
      extraAny additional data or information associated with the device. like "$(extra.diameter)"
      decoderThe decoder or protocol used by the device.
      extNameDenotes the external id or label assigned to the identified device.
      enableAlertIndicates whether alerts are enabled for the device.
      timeoutThe timeout period for the device.
      stateRefOnline state references for the identified device.
      RULE_CONDITIONJSON.stringify the rule condition.
      RULE_DESCRIPTIONRepresents the rule description.
      RULE_STATE_NAMERepresents the rule state name.
      TRIGGER_FIELD_NAMERepresents the field name that tiggered the rule.
      TRIGGER_FIELD_VALUERepresents the field value that tiggered the rule.
      UNIX_TIMEConverts the payload timestamp to Unix time (seconds).
      UNIX_TIME_MSConverts the payload timestamp to Unix time in milliseconds.
      UTC_DATEConverts the payload timestamp to MMMM d, yyyy (EEEE)
      UTC_TIMEConverts the payload timestamp to HH:mm:ss 'GMT'Z
      WS_EMAIL_LIST_1Represents the email list 1 defined by the user in the workspace.
      WS_EMAIL_LIST_2Represents the email list 2 defined by the user in the workspace.
      WS_EMAIL_LIST_3Represents the email list 3 defined by the user in the workspace.
      WS_EMAIL_LIST_4Represents the email list 4 defined by the user in the workspace.
      WS_EMAIL_LIST_5Represents the email list 5 defined by the user in the workspace.
      ZONEIDIndicates the unique ID of the zone related to the identified device.
      ZONENAMERepresents the zone name associated with the identified device.

Time-Triggered Rule

Users can specify a cron job expression to schedule the trigger time for a rule.

The cron expression is validated using the cron-parser library.


* * * * *
┬ ┬ ┬ ┬
│ │ │ │ |
│ │ │ │ └── Day of week (0 - 7, 1L - 7L) (0 or 7 is Sunday)
│ │ │ └───── Month (1 - 12)
│ │ └────────── Day of month (1 - 31, L)
│ └─────────────── Hour (0 - 23)
└──────────────────── Minute (0 - 59)

Note that although the cron-parser library supports second precision (0 - 59, optional), our rule system checks every minute, so second precision is not supported.

Important Note: If the rule group is not activated, the cron job will not be triggered even if the cron expression is scheduled.

Data-Triggered Rule

For a data-triggered rule, users specify a set of conditions that must be met to trigger the rule.

A data-triggered rule is composed of the following elements:

  • conditionType: Specifies whether all conditions must be met ("and-case") or if any condition can trigger the rule ("or-case").
  • Field: The data attribute to evaluate.
  • Operator: The logical operation to perform (e.g., equals, greater than, etc.).
  • Value: The value to compare against the specified field.

Supported Operators

The following operators are supported:

OperatorDescription
=extract matches
>greater than value
<less than value
>=greater than or equal to value
<=less than or equal to value
!=not equal to value
rangewithin a range of values
!rangeoutside the range of values
existfield exists in data
isNullfield is null
containsdata field contains this string
!containsdata field does not contain this string
startsWithdata field starts with this string
!startsWithdata field does not start with this string
endsWithdata field ends with this string
!endsWithdata field does not end with this string
ISOTimePassedISO time has passed within a duration
UnixTimestampMsPassedUnix timestamp in milliseconds has passed within a duration
UnixTimestampPassedUnix timestamp has passed within a duration

Rule Action

There are several type of action:

  • alert: create a alert in seer platform
  • alarm : send alarm to alarmbox in seer platform
  • alarmAlert : send alarm to alarmbox in seer platform and create a alert in seer platform
  • cancelAlarm : cancel a alarm in seer platform
  • email : send a email to target email address with template (default template is openAlert.hbs)
  • http : send a http request to target url through seer control
  • inferData : infer data from the rule condition and send to seer platform
  • mqtt : create a mqtt payload and send to workspace mqtt topic
  • sms : send an SMS message
  • task : create a task in seer platform

Action-alert

  • it will create an alert in the Seer platform

  • fields available in the meta object

    FieldDescriptionOptionalDefault
    descriptionAlert descriptiontrue${category.toLowerCase()} detected from ${shortName ?? extName ?? deviceId}
    titleAlert titletrue${category} Alarm from ${shortName ?? extName ?? deviceId}
    categoryAlert categorytrueUnclassified
    locationAlert locationtruethe zoneName of the device
  • example:

    {
    "actions": [
    {
    "type": "alert",
    "meta": {
    "category": "high temperature",
    "description": "温度过高",
    "title": "Temperature Alert",
    "location": "Room 101"
    }
    }
    ]
    }

Action-alarm

  • it will create a alarm to an alarmbox in seer platform

  • field avaiable in meta object

    FieldDescriptionOptional
    controlUrlSeer control URL for target alarmDevicestrue
    alarmDevicesAlarmDevices Seer device IDfalse
    alarmTopicMQTT topic for alarmfalse
  • example:

    {
    "actions": [
    {
    "type": "alarm",
    "meta": {
    "controlUrl": "http://controller-office-mqtt",
    "alarmTopic": "alarmbox/alarm",
    "alarmDevices": ["ALARM_BOX_01"]
    }
    }
    ]
    }

Action-alarmAlert

  • it will create a alarm to an alarmbox in seer platform and create a alert in seer platform
  • field avaiable in meta object
    FieldDescriptionOptional
    controlUrlSeer control URL for target alarmDevicestrue
    alarmDevicesAlarmDevices Seer device IDfalse
    alarmTopicMQTT topic which alarmbox is subscribed tofalse
    categoryAlert categorytrue
    descriptionAlert descriptiontrue
    addition field*Any additional field to be sent to alarmboxtrue
  • example:
    {
    "actions": [
    {
    "type": "alarmAlert",
    "meta": {
    "category": "high temperature",
    "description": "温度过高",
    "controlUrl": "http://controller-office-mqtt",
    "alarmTopic": "alarmbox/alarm",
    "alarmDevices": [
    "ALARM_BOX_01"
    ]
    },
    }
    ]
    }

Action-cancelAlarm

  • it will cancel a alarm in seer platform
  • field avaiable in meta object
    FieldDescriptionOptional
    controlUrlSeer control URL for target alarmDevicestrue
    alarmDevicesAlarmDevices Seer device IDfalse
    alarmTopicMQTT topic for alarmfalse
    addition field*Any additional field to be sent to alarmboxtrue
  • example:
    {
    "actions": [
    {
    "type": "cancelAlarm",
    "meta": {
    "controlUrl": "http://controller-office-mqtt",
    "alarmTopic": "alarmbox/alarm",
    "alarmDevices": [
    "ALARM_BOX_01"
    ]
    },
    }
    ]
    }

Action-email

  • it will send a email to target email address
  • field avaiable in meta object , Refence nodemailer
FieldDescriptionOptional
subjectEmail subjecttrue
templateEmail template name which is stored in Seer, please also refer to hbs formattrue
contextEmail template contexttrue
fromThe email address of the sendertrue
toComma-separated list or an array of recipient email addressestrue
ccComma-separated list or an array of CC email addressestrue
bccComma-separated list or an array of BCC email addressestrue
textThe plaintext version of the messagetrue
htmlThe HTML version of the messagetrue
addition field*Any additional field available in nodemailertrue
  • example:
    {
    "actions": [
    {
    "type": "email",
    "meta": {
    "subject": "warning: $(extName) is too hot",
    "template": "openAlert.hbs",
    "to": "$(WS_EMAIL_LIST_1)", // please refer to the Seer variable list
    "context": {
    "temp": "$(TEMPERATURE)",
    "category": "高温",
    "timeZone": "HongKong"
    }
    }
    }
    ]
    }

Action-http

  • it will send a http request to target url
  • field avaiable in meta object
    FieldDescriptionOptional
    controlUrlSeer control URL to send the httptrue
    urltarget urlfalse
    methodhttp methodfalse
    headershttp headertrue
    bodyhttp bodytrue
  • example
    {
    "actions": [
    {
    "type": "http",
    "meta": {
    "method": "GET",
    "url": "$(TEST_URL)/radar/#(TD_extName)",
    "headers": {
    "Authorization": "Bearer $(TEST_TOKEN)"
    },
    "body": {
    "id": ""
    },
    "targetDevice": "99c115f4-9ba9-4f82-a8c6-56966ebb45dc" // need to provide whenever you want to use Seer variable with TD_ prefix, i.e. TD_extName
    }
    }
    ]
    }

Action-inferData

  • infer data from the rule condition and send to seer platform
  • field avaiable in meta object
    FieldDescriptionOptional
    infer data fieldthe data infered from the rule conditiontrue
  • example:
    {
    "actions": [
    {
    "type": "inferData",
    "meta": {
    "online": false, // infered data field, it can be any field that you want to infer from the rule condition
    "customField": "customValue", // you can add any custom field to the infered data
    "customField2": true // it can be any type
    }
    }
    ]
    }

Action-mqtt

  • it will create mqtt payload send to MQTT Broker by seer-controller

  • field avaiable in meta object

    FieldDescriptionOptional
    controlUrlSeer control URL to send the mqtttrue
    topicmqtt topictrue
    typemqtt payload type e.g. "cmd","data"false
    payloadmqtt payload (single object or array of objects)false
  • mqtt payload format depends on usage, below shows device "cmd" control usage

  • example (single payload):

    {
    "actions": [
    {
    "type": "mqtt",
    "meta": {// this is the mqtt payload, format depends on usage, below shows device cmd control usage
    "type": "cmd",
    "payload": {
    "id": "d686a6ad-c1e2-4fe0-9c18-5aa56606cdf0", //seer id
    "description": "testing mqtt",
    "condition":"$(RULE_CONDITION)",
    "POWER_ON": true, //false
    "SWING": false
    }
    }
    }
    ]
    }
  • example (array of payloads):

    {
    "actions": [
    {
    "type": "mqtt",
    "meta": {
    "type": "cmd",
    "payload": [
    {
    "id": "d686a6ad-c1e2-4fe0-9c18-5aa56606cdf0", //seer id
    "description": "testing mqtt 1",
    "condition":"$(RULE_CONDITION)",
    "POWER_ON": true,
    "SWING": false
    },
    {
    "id": "d686a6ad-c1e2-4fe0-9c18-5aa56606cdf1", //seer id
    "description": "testing mqtt 2",
    "condition":"$(RULE_CONDITION)",
    "POWER_ON": false,
    "SWING": true
    }
    ]
    }
    }
    ]
    }

Action-sms

  • it will send an SMS message
  • field avaiable in meta object
    FieldDescriptionOptional
    phoneNumbersPhone number(s) to send SMS to (string or array)false
    messageContent of the SMS messagefalse
    senderIdSMS sender ID (optional)true
    messageTypeType of message (optional)true
  • example
    {
    "actions": [
    {
    "type": "sms",
    "meta": {
    "phoneNumbers": ["+1234567890", "+0987654321"],
    "message": "Alert: Device is offline!",
    "senderId": "SeerAlert"
    }
    }
    ]
    }

Action-task

  • it will create a task in seer platform
  • field avaiable in meta object
    FieldDescriptionOptional
    categorytask categorytrue
    descriptiontask descriptiontrue
  • example
    {
    "actions": [
    {
    "type": "task",
    "meta": {
    "description": "$(extName) is too hot"
    }
    }
    ]
    }