# Create a rule

> Write a rule that watches data, device status, logs or gateway metrics, and raises an alert and runs actions each time its condition matches.

Source: https://proxus.io/docs/automate/rules

At the end of this guide, a rule raises an alert when zone 1 of a tunnel oven has been above 200 °C for five minutes,
at most once every five minutes. You build the condition as a sentence, check what it would have done over the last
24 hours, choose the gateways that check it, and turn it on.

A rule checks each message as it arrives. Per device it remembers only two things: how long the condition has held,
for the [wait](#wait-before-the-alarm), and whether its alarm is open, so the alarm can
[close by itself](#close-the-alarm) when the value is back to normal. For logic that spans several messages or devices,
use a [pipeline](https://proxus.io/docs/automate/pipelines).

## Before you start

You need:

- A device that sends values, on a connected edge gateway.
- The tag name you want to check (here `Zone1Temp`) and the device name (here `MFB_LYS_TUNNEL_OVEN`).
- A user role that may create rules.

## Step 1: Create the rule

Go to **Automate > Rules** and select **New** (1).

*Screenshot: The rule list with the New button marked in the toolbar and the demo rules below it*

The list shows each rule's **Status**, what it **Watches**, its **Condition**, how many **Open Alarms** it has, when
it **Last Fired** and where it **Runs On**. The demo rules, such as **Temperature Threshold Alert**, are good examples to open and read.

## Step 2: Fill in the form

*Screenshot: The rule form with the name, the event On Data Received, a trigger limit of 1 and a throttle period of five minutes, and below it the condition editor: the device, Zone1Temp above 200, the wait, and the Now, Last 24 hours and Check panels*

1. **Name**: a unique name, for example `Oven zone 1 above 200`.
2. **Event**: what the rule watches.

   | Event | The rule checks |
   | --- | --- |
   | **On Data Received** | Every message of tag values a device sends. |
   | **On Status Changed** | A device connecting or disconnecting. |
   | **On Log Received** | Every log entry of the gateway. |
   | **On Metrics Received** | The read statistics of each device (requests, errors, response time, data quality). |

   Changing the event clears the condition, because each event has its own fields.
3. **Trigger Limit**: how many times the rule may act within one throttle period. Here `1`.
4. **Throttle Period**: the length of that period, here five minutes (`00:05:00`). See [Throttling](#throttling).
5. Build the **Condition** as a sentence:
   - **Where**: **Device** and `MFB_LYS_TUNNEL_OVEN`. **Site** or **Area** checks every device there; **Any device**
     checks all of them.
   - **When**: the tag `Zone1Temp`, **above**, `200`. The tag list shows each tag's unit and how many devices in scope
     have it; under each comparison you see the tag's lowest, average and highest value of the last 24 hours and its
     value now, so you can pick a sensible limit. **Add comparison** adds another one; choose whether all of them or
     any one must hold. **Between** and **outside** take a lower and an upper limit.
   - Or type the condition in your own words in the box at the top (for example *Tunnel oven zone 1 above 200 degrees
     for 5 minutes*) and press Enter or select **Turn into a condition**. The Copilot fills in the sentence and the
     wait from your devices and tags; when the sentence describes a lost connection, a log entry or read errors, it
     switches the rule's event too. Check the result before saving; **Undo** brings back the condition, the wait and
     the event you had. When the sentence names a device or tag that does not exist, matches more than one device, or
     is not a condition, the Copilot says why and leaves the condition as it was. This needs a
     [Copilot provider](https://proxus.io/docs/administer/copilot-settings).
   - A new rule offers templates: **Above a limit**, **Outside a range**, **Connection lost**, **Error log** and
     **Read errors**.
6. **Wait before the alarm**: **5 minutes** (`300` seconds). See [Wait before the alarm](#wait-before-the-alarm).
7. **Close the alarm**: **With a margin**, **5** °C: the alarm closes once zone 1 is back below 195 °C. See
   [Close the alarm](#close-the-alarm).

**In words** repeats the condition as a sentence; check that it says what you mean. **Expression** shows the text the
gateway runs, and switches to typing it when you need something the sentence cannot say. All fields and operators are
in [Rule expressions](https://proxus.io/docs/automate/rule-expressions).

Beside the condition, three panels check it before you save:

- **Now**: whether the condition holds on the devices in scope with their latest values.
- **Last 24 hours, had this rule run**: the condition and the wait replayed over the stored history: a chart of the
  first tag with the limit and the times the alarm would have been on, the number of alarms, their total and longest
  time, and a hint when it would fire too often or never. History is replayed in 15-second steps, so a spike shorter
  than that can be missed; only devices whose data is stored (sent to **SYSTEM INTERNAL DB**) have history.
- **Check**: whether the gateway can compile the condition, what is still missing, and where the rule runs.

Leave **Engine** on **Criteria Expression**. **Trigger** always shows **Real-Time**: rules are checked as each event
arrives.

## Step 3: Choose the gateways

The **Gateways** tab below the form lists the gateways that check the rule. A new rule starts with **SYSTEM**, the
hub's own gateway. Add the gateway that reads your device. A rule only sees the data of the gateways it runs on.

## Step 4: Decide what happens

Each match, within the throttle, creates or updates an alert in [Alerts](https://proxus.io/docs/monitor/alerts):

- If the rule's latest alert is still **New**, its count goes up and its time is updated.
- If that alert was acknowledged, resolved or ignored, a new alert is created.

To get a message or forward the data as well, add an action on the **Actions** tab. See
[Add a rule action](https://proxus.io/docs/automate/rule-actions).

Tick **Enable UI Alerts** to also show a pop-up in the hub for each alert, with a **View Details** button.

## Step 5: Turn it on

1. Tick **Active**.
2. Select **Save**.

The rule is sent to its gateways and starts checking at once. Clear **Active** and save to stop it.

> **Note:**
While a rule is active, its settings are locked. To change the condition, the throttle or the gateways, clear
**Active** and save first, make the change, then turn it on again. To turn several rules on or off at once, select
them in the list and use **Status** > **Activate Selected** or **Deactivate Selected**.

## Wait before the alarm

**Wait before the alarm** fires the rule only when its condition has held on the same device, without a break, for
that long: a short spike above the limit raises nothing. A message that does not match starts the wait over, and so
does a silence longer than the wait. **At once** (`0`) fires on the first match, as rules did before. Status and
metric rules wait the same way; log rules always fire at once.

The wait needs gateways of version 2.0.0 or later; an older gateway ignores it and fires at once.

## Close the alarm

**Close the alarm** decides who resolves the alarm a rule opens:

- **By hand**: someone resolves it in **Alerts**, as before.
- **When the condition ends**: the gateway resolves it by itself on the first message where the condition no longer
  holds on that device.
- **With a margin**: the value must come back past the limit by the margin before the alarm closes. With *above 200*
  and a margin of 5 the alarm opens above 200 and closes below 195, so a value hovering around 200 does not open and
  close it over and over. Between and Outside conditions move both limits; a margin is offered only for numeric limits.

While nobody has taken the alarm, each new firing on that device counts on it; once it has closed, the next time the
condition holds opens a new alarm. The resolved alarm keeps the time it closed. **Last 24 hours, had this rule run**
replays the closing too, and draws the closing limit as a dashed line, so you can choose a margin that keeps the alarm
count low. An alarm left open while a gateway restarts closes the first time its value is back to normal.

Log rules have no closing: a log entry is a moment. Closing needs gateways of version 2.0.0 or later.

## Throttling

**Trigger Limit** and **Throttle Period** work as a counting window per rule:

1. The first match starts a window of **Throttle Period** and acts.
2. Further matches act until **Trigger Limit** is reached.
3. Matches after that are skipped until the period has passed. The gateway writes one warning to the log
   ("limit reached for rule ...") per window.
4. The first match after the period starts a new window.

Alerts and notifications share one counter; forwarding to outbound targets has its own. Set **Trigger Limit** or
**Throttle Period** to `0` for no limit. A new rule starts with one action per minute.

> **Warning:**
A rule on **On Log Received** whose action writes a log entry can fire itself again and again. Keep its condition
narrow (for example a **ReasonCode**) and keep a throttle.

## Find out why a rule did or did not fire

- The top of the rule shows **Open alarms**, **Last fired**, the number of **Actions** and the **Throttle**.
- The **Alerts** tab lists the alerts this rule raised.
- **Logs** in the toolbar opens the gateway log entries for this rule, for example a condition that could not be
  read or a throttle that was reached.

A condition with a typing error never matches; the log then says the criteria could not be compiled.

## Spot unusual values

Set **Engine** to **Anomaly Detection** to fire on values that do not fit a tag's recent pattern instead of a
fixed limit. It only works with **On Data Received**. The condition still decides which messages are looked at;
if it names one tag (`[Payload][Key = 'Zone1Temp']`), only that tag is analysed.

The **Anomaly Detection** tab lists the methods. Switch on the ones you want; the first that fires wins.

| Method | Fires when | Settings (default) |
| --- | --- | --- |
| **Use Gap** | No new value for longer than expected | **Expected Interval Seconds** (60), **Gap Factor Threshold** (1.8) |
| **Use ZScore** | A value is far from the average, measured in standard deviations | **ZScore Threshold** (3.0) |
| **Use Rolling Median** | A value is far from the median | **Rolling Median Multiplier** (1.2) |
| **Use Rate Of Change** | A value jumps by more than a share of the previous one | **Rate Of Change Threshold** (0.25) |
| **Use Ema** | A value moves away from its smoothed average | **Ema Alpha** (0.1), **Ema Difference Multiplier** (0.01) |
| **Use Iqr** | A value is outside the usual range of the middle half of values | **Iqr Multiplier** (1.5) |
| **Use Moving Average** | A value is far from the moving average | **Moving Average Threshold** (1.5) |
| **Use Drift** | Several values in a row stay on one side of the average | **Drift Run Length** (3), **Drift Threshold Percent** (1.0) |
| **Use Flatline** | The value stops moving | **Flatline Window** (6), **Flatline Tolerance Percent** (0.25) |

**Analysis Window** (1000) is how many past values are kept per tag. Apart from **Use Gap**, no method fires until
that many values have arrived, so a large window takes a while to start. The history is kept per tag name, so
devices with the same tag name share it; narrow the condition to one device when that matters.

## What's next

- [Rule expressions](https://proxus.io/docs/automate/rule-expressions): fields, operators and examples.
- [Add a rule action](https://proxus.io/docs/automate/rule-actions): send a message or forward data.
- [Alerts](https://proxus.io/docs/monitor/alerts): acknowledge and resolve what rules raise.
