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:
- Time-Triggered: Activated based on specific time schedules. Uses a cron expression to define the trigger schedule.
- 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.
- Data-Triggered: Activated when specified data conditions are met (e.g., sensor readings exceeding thresholds).
- 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 dataoperator: the operator to compare the valuevalue: the value to compare with the field valuetriggerState: 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 devicedeviceTypes: the Seer device type, if it is null, it will match all device typeworkspace: 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 totargetState. 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.0represents normal state, while> 0indicates 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
metacontext of rule actions. -
To use SEER variable, name must look like "$(VAR_NAME)" , available variable list as below
Variable Description id Unique identifier for the device. shortName Denotes the device short name name Denotes the device name type Represents the device type of the identified device. extra Any additional data or information associated with the device. like "$(extra.diameter)"decoder The decoder or protocol used by the device. extName Denotes the external id or label assigned to the identified device. enableAlert Indicates whether alerts are enabled for the device. timeout The timeout period for the device. stateRef Online state references for the identified device. RULE_CONDITION JSON.stringify the rule condition. RULE_DESCRIPTION Represents the rule description. RULE_STATE_NAME Represents the rule state name. TRIGGER_FIELD_NAME Represents the field name that tiggered the rule. TRIGGER_FIELD_VALUE Represents the field value that tiggered the rule. UNIX_TIME Converts the payload timestamp to Unix time (seconds). UNIX_TIME_MS Converts the payload timestamp to Unix time in milliseconds. UTC_DATE Converts the payload timestamp to MMMM d, yyyy (EEEE)UTC_TIME Converts the payload timestamp to HH:mm:ss 'GMT'ZWS_EMAIL_LIST_1 Represents the email list 1 defined by the user in the workspace. WS_EMAIL_LIST_2 Represents the email list 2 defined by the user in the workspace. WS_EMAIL_LIST_3 Represents the email list 3 defined by the user in the workspace. WS_EMAIL_LIST_4 Represents the email list 4 defined by the user in the workspace. WS_EMAIL_LIST_5 Represents the email list 5 defined by the user in the workspace. ZONEID Indicates the unique ID of the zone related to the identified device. ZONENAME Represents 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:
| Operator | Description |
|---|---|
= | extract matches |
> | greater than value |
< | less than value |
>= | greater than or equal to value |
<= | less than or equal to value |
!= | not equal to value |
range | within a range of values |
!range | outside the range of values |
exist | field exists in data |
isNull | field is null |
contains | data field contains this string |
!contains | data field does not contain this string |
startsWith | data field starts with this string |
!startsWith | data field does not start with this string |
endsWith | data field ends with this string |
!endsWith | data field does not end with this string |
ISOTimePassed | ISO time has passed within a duration |
UnixTimestampMsPassed | Unix timestamp in milliseconds has passed within a duration |
UnixTimestampPassed | Unix timestamp has passed within a duration |
Rule Action
There are several type of action:
alert: create a alert in seer platformalarm: send alarm to alarmbox in seer platformalarmAlert: send alarm to alarmbox in seer platform and create a alert in seer platformcancelAlarm: cancel a alarm in seer platformemail: send a email to target email address with template (default template isopenAlert.hbs)http: send a http request to target url through seer controlinferData: infer data from the rule condition and send to seer platformmqtt: create a mqtt payload and send to workspace mqtt topicsms: send an SMS messagetask: create a task in seer platform
Action-alert
-
it will create an alert in the Seer platform
-
fields available in the
metaobjectField Description Optional Default descriptionAlert description true ${category.toLowerCase()} detected from ${shortName ?? extName ?? deviceId}titleAlert title true ${category} Alarm from ${shortName ?? extName ?? deviceId}categoryAlert category true Unclassified locationAlert location true the 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
metaobjectField Description Optional controlUrlSeer control URL for target alarmDevices true alarmDevicesAlarmDevices Seer device ID false alarmTopicMQTT topic for alarm false -
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
metaobjectField Description Optional controlUrlSeer control URL for target alarmDevices true alarmDevicesAlarmDevices Seer device ID false alarmTopicMQTT topic which alarmbox is subscribed to false categoryAlert category true descriptionAlert description true addition field* Any additional field to be sent to alarmbox true - 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
metaobjectField Description Optional controlUrlSeer control URL for target alarmDevices true alarmDevicesAlarmDevices Seer device ID false alarmTopicMQTT topic for alarm false addition field* Any additional field to be sent to alarmbox true - 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
metaobject , Refence nodemailer
| Field | Description | Optional |
|---|---|---|
subject | Email subject | true |
template | Email template name which is stored in Seer, please also refer to hbs format | true |
context | Email template context | true |
from | The email address of the sender | true |
to | Comma-separated list or an array of recipient email addresses | true |
cc | Comma-separated list or an array of CC email addresses | true |
bcc | Comma-separated list or an array of BCC email addresses | true |
text | The plaintext version of the message | true |
html | The HTML version of the message | true |
| addition field* | Any additional field available in nodemailer | true |
- 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
metaobjectField Description Optional controlUrlSeer control URL to send the http true urltarget url false methodhttp method false headershttp header true bodyhttp body true - 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
metaobjectField Description Optional infer data field the data infered from the rule condition true - 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
metaobjectField Description Optional controlUrlSeer control URL to send the mqtt true topicmqtt topic true 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
metaobjectField Description Optional phoneNumbersPhone number(s) to send SMS to (string or array) false messageContent of the SMS message false 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
metaobjectField Description Optional categorytask category true descriptiontask description true - example
{
"actions": [
{
"type": "task",
"meta": {
"description": "$(extName) is too hot"
}
}
]
}