# Configuration

Create event targets, rules, and actions.

## Targets

The event handler **Target** defines which SIMs or subscribers should be included. This allows you to control whether an event handler configuration should apply to a single SIM or subscriber, a group of SIMs or subscribers, or to all SIMs or subscribers in your account.

- **Subscriber** - Matches a single subscriber in your account. The `IMSI` of the subscriber is required.

> [!NOTE]
>
> The **Subscriber** target does not apply to subscription containers such as planP1, planX1, planX2, planX3, plan-US-max, or plan-US-NA. If you want to configure an event handler to target a subscription container, use the **SIM**, **Group**, or **Operator** targets instead.

- **SIM** - Matches a single SIM in your account, which itself may contain one or more [Subscription Containers](https://docs.soracom.io/en/services/air/subscription-containers). The `SIM ID` of the SIM is required.
- **Group** - Matches one or more SIMs or subscribers in your account, which belong to a particular group. The `Group ID` of the group is required.
- **Operator** - Matches all SIMs or subscribers in your account.

## Rules

The event handler **Rule** defines a condition that will be evaluated for the specified target. When the rule condition is met, the action(s) in the event handler will be performed. The available rules depend on which **Target** you select.

> [!WARNING]
>
> Data usage rules for daily and monthly limits are evaluated according to **UTC** (Coordinated Universal Time).

> [!NOTE]
>
> Rules that monitor data traffic are not evaluated in real time. There may be up to a **5 minute** delay between the time your data usage exceeds the threshold, and when the configured action is triggered. Data usage that occurs in this window cannot be prevented and customers will still be responsible for payment of data usage fees.

- Available rules for **Subscriber**, **Group**, and **Operator** targets:

  - **Subscriber first traffic** - Executes when a subscriber sends or receives data for the first time after the event handler is created.

  - **Subscriber Daily traffic** - Executes when a subscriber's daily data usage exceeds a specified value.

  - **Subscriber Monthly traffic** - Executes when a subscriber's monthly data usage exceeds a specified value.

  - **Subscriber Cumulative traffic** - Executes when a subscriber's lifetime cumulative data usage exceeds a specified value.

  - **Subscriber status attribute** - Executes when a subscriber's [status](https://docs.soracom.io/en/services/air/subscriber-status) changes and (optionally) matches a specified source (before) and/or target (after) value.

  - **Subscriber speed class attribute** - Executes when a subscriber's [speed class](https://docs.soracom.io/en/services/air/speed-class) changes and (optionally) matches a specified value.

  - **Subscriber expired** - Executes when a subscriber expires based on its [Expiration](https://docs.soracom.io/en/services/air/expiration) settings.

  - **Subscriber IMEI mismatched** - Executes when the IMEI of the device using the subscriber does not match the subscriber's [IMEI Lock](https://docs.soracom.io/en/services/air/imei-lock) settings.

  - **Subscriber session status changed** - Executes when a subscriber session status changes to `Created` (online) or `Deleted` (offline). Requires session events to be enabled for the group. See [Enabling Session Events for a Group](https://docs.soracom.io/en/services/event-handler/configuration/#enabling-session-events-for-a-group). Optionally, you can limit the rule to session events that include an IMEI. See [Automatically Apply IMEI Lock When a SIM Comes Online](https://docs.soracom.io/en/services/event-handler/examples#automatically-apply-imei-lock-when-a-sim-comes-online) for an onboarding example.

    > [!NOTE]
    >
    > **Support request required**: To use the **Subscriber session status changed** rule, [contact Soracom Support](https://docs.soracom.io/en/services/account/support#creating-a-support-request) with your use case and expected event frequency.

  > [!NOTE]
  >
  > The **Subscriber** rules do not apply to subscription containers such as planP1, planNT1, planX1, planX2, planX3, plan-US-max, or plan-US-NA. If you want to use a rule that targets a subscription container, use one of the **SIM**, **Group**, or **Operator** rules below instead.

- Available rules for **SIM**, **Group**, and **Operator** targets:

  - **Sim Daily total traffic** - Executes when a SIM's total daily data usage across all of its subscriptions exceeds a specified value.

  - **Sim Monthly total traffic** - Executes when a SIM's total monthly data usage across all of its subscriptions exceeds a specified value.

  - **Sim Cumulative total traffic** - Executes when a SIM's total lifetime cumulative data usage across all of its subscriptions exceeds a specified value.

  - **Sim status attribute** - Executes when a SIM's [status](https://docs.soracom.io/en/services/air/subscriber-status) changes and (optionally) matches a specified source (before) and/or target (after) value.

  - **Sim speed class attribute** - Executes when a SIM's [speed class](https://docs.soracom.io/en/services/air/speed-class) changes and (optionally) matches a specified value.

  - **Sim expired** - Executes when a SIM expires based on its [Expiration](https://docs.soracom.io/en/services/air/expiration) settings.

  - **Sim subscription status** - Executes when a SIM's [Subscription Containers](https://docs.soracom.io/en/services/air/subscription-containers) status changes and (optionally) matches a specified value.

  - **Sim IMEI mismatched** - Executes when the IMEI of the device using the SIM does not match the SIM's [IMEI Lock](https://docs.soracom.io/en/services/air/imei-lock) settings.

  - **Sim session status changed** - Executes when a SIM session status changes to `Created` (online) or `Deleted` (offline). Requires session events to be enabled for the group. See [Enabling Session Events for a Group](https://docs.soracom.io/en/services/event-handler/configuration/#enabling-session-events-for-a-group). Optionally, you can limit the rule to session events that include an IMEI. See [Automatically Apply IMEI Lock When a SIM Comes Online](https://docs.soracom.io/en/services/event-handler/examples#automatically-apply-imei-lock-when-a-sim-comes-online) for an onboarding example.

    > [!NOTE]
    >
    > **Support request required**: To use the **Sim session status changed** rule, [contact Soracom Support](https://docs.soracom.io/en/services/account/support#creating-a-support-request) with your use case and expected event frequency.

- Available rules for **Group** and **Operator** targets:

  - **Daily total traffic** - Executes when the total daily data usage across all SIMs and subscriptions exceeds a specified value.
  - **Monthly total traffic** - Executes when the total monthly data usage across all SIMs and subscriptions exceeds a specified value.

  > [!NOTE]
  >
  > When a rule targets a **Group**, if a SIM is removed from the group partway through the Event Handler’s daily or monthly period, any data usage prior to its removal will still be included in the group’s total. Conversely, if a SIM is added to the group during the period, any usage that occurred before it was added will not be counted.

- Available rules for the **Operator** target:

  - **Monthly bill amount** - Executes when the current month's bill total exceeds a specified value.

    > [!NOTE]
    >
    > When using the **Monthly bill amount** rule, the monthly bill total is not calculated in real time. There may be up to a 24-hour delay between the time when your service usage exceeds the threshold configured in your rule, and when the monthly bill total is updated and the configured action is triggered. Usage charges that exceed the defined amount in this window cannot be prevented and customers will still be responsible for payment of these charges.

In addition to selecting one of the above rules, you must also specify when the rule should be checked again using the **Re-evaluate** parameter. After the rule condition is met, this parameter defines how long the event handler should wait before it evaluates the rule again. You can configure longer intervals in order to prevent the event handler from executing actions too frequently. You can also specify the **Offset** parameter to add an additional delay, in minutes.

> [!NOTE]
>
> **Offset Parameter Billing Warning**: To avoid unexpected billing charges, do not use the **Offset** parameter to compensate for the time difference between UTC and your local timezone. Event handlers and billing use UTC as their time reference, where day boundaries occur at 00:00 UTC. Setting offset values to account for timezone differences may result in rules being re-evaluated on different billing days than expected.

### UTC Timing Example

For example, if you want rule re-evaluation to occur at 00:00 EST, you would set the **Offset** to 300 minutes (5 hours). However, consider this scenario:

- **Rule trigger**: 20:00 EST 11/1 (01:00 UTC 11/2) - A SIM exceeds its data limit and is set to Inactive
- **Next billing day**: 19:00 EST 11/2 (00:00 UTC 11/3) - New daily billing period begins
- **Rule re-evaluation**: 00:00 EST 11/3 (05:00 UTC 11/3) - Rule is re-evaluated 5 hours after the next day boundary

In this example, the SIM remains inactive throughout the entire billing day of 11/3, potentially resulting in unexpected charges if the SIM continues to incur daily fees while inactive.

| Re-evaluate | The event handler will check the rule again... |
| - | - |
| **Immediately** | right away |
| **Beginning of next month** | at the beginning of the next month |
| **Beginning of next day** | at the beginning of the next day (at 00:00 UTC) |
| **After one day** | one day (24 hours) later |
| **Never** | never (the rule will not be checked again) |

By default, when the event handler **Target** includes multiple subscribers (such as setting a **SIM**, **Group**, or **Operator** target), the **Rule** will be applied to each subscriber _individually_. For example, you can use the **Sim Monthly total traffic** rule to receive an email notification when a SIM uses too much data within any given month. By setting the re-evaluate parameter to **Beginning of next month**, once a SIM exceeds the data usage threshold, the event handler will wait until the following month before it checks _that SIM's_ monthly data usage again. During that time, the event handler will still check the data usage of other SIMs in the target, ensuring that you will still receive additional emails if other SIMs use too much data, which may be useful for identifying which devices should be inspected for abnormal behavior.

If you prefer the action to be performed only once _for the entire target_ regardless of which SIM or subscriber triggers the rule, you can check the **Do not execute again until next re-evaluation** option to suppress additional actions. In the example above, enabling this option will result in sending an email when a SIM exceeds the data usage threshold, but without sending any other emails even if other SIMs also use too much data. This may be useful in identifying trends, such as how quickly a SIM reaches a particular data usage amount.

## Enabling Session Events for a Group

The **Subscriber session status changed** and **Sim session status changed** rules require session events to be enabled for the group. Session events are not configurable in the User Console at this time. To enable session events, use the Soracom API to update the group configuration:

**Global**

```bash
curl -X PUT \
    -H 'Content-Type: application/json' \
    -H 'X-Soracom-API-Key: <MY-API-KEY>' \
    -H 'X-Soracom-Token: <MY-TOKEN>' \
    -d '[{ "key": "sessionEventEnabled", "value": true }]' \
    https://g.api.soracom.io/v1/groups/<GROUP-ID>/configuration/SoracomAir
```

**Japan**

```bash
curl -X PUT \
    -H 'Content-Type: application/json' \
    -H 'X-Soracom-API-Key: <MY-API-KEY>' \
    -H 'X-Soracom-Token: <MY-TOKEN>' \
    -d '[{ "key": "sessionEventEnabled", "value": true }]' \
    https://jp.api.soracom.io/v1/groups/<GROUP-ID>/configuration/SoracomAir
```

## Actions

The event handler **Action** defines one or more actions to perform once the **Rule** condition is met. You can specify up to 5 actions for each event handler configuration.

- Actions for sending emails:

  - **Send email** - Send an email to a specified email address.
  - **Send email to Operator** - Send an email to the Operator email address.

- Actions for changing a SIM's properties:

  - **Activation** - Set the SIM's [status](https://docs.soracom.io/en/services/air/subscriber-status) to Active.

  - **Deactivation** - Set the SIM's [status](https://docs.soracom.io/en/services/air/subscriber-status) to Inactive.

  - **Suspend** - Set the SIM's [status](https://docs.soracom.io/en/services/air/subscriber-status) to Suspended.

  - **Standby** - Set SIM's [status](https://docs.soracom.io/en/services/air/subscriber-status) to Standby.

  - **Change speed class** - Change the SIM's [speed class](https://docs.soracom.io/en/services/air/speed-class).

  - **IMEI Lock** - Automatically configures [IMEI Lock](https://docs.soracom.io/en/services/air/imei-lock) using the IMEI reported in the session event, preventing subsequent connections from a different device.

    > [!NOTE]
    >
    > **Support request required**: To use the **IMEI Lock action**, [contact Soracom Support](https://docs.soracom.io/en/services/account/support#creating-a-support-request) with your use case and expected event frequency.

    > [!NOTE]
    >
    > **Prerequisite**: The **IMEI Lock action** must be used with the **Subscriber session status changed** or **Sim session status changed** rule configured for `Created` (using `targetSessionStatus`), and the rule must be set to execute only when the session event includes an IMEI (set `hasImei` to `true`).

    See [Automatically Apply IMEI Lock When a SIM Comes Online](https://docs.soracom.io/en/services/event-handler/examples#automatically-apply-imei-lock-when-a-sim-comes-online) for a complete onboarding example.

- Actions for calling external actions:

  - **Execute web request** - Execute a specified HTTP request.
  - **Invoke AWS Lambda** - Invoke a specified AWS Lambda function.

For each action, you must also specify the timing of when the action should be performed using the **Run** parameter. When the rule condition is met, this parameter defines how long the event handler should wait before performing the action. You can use this parameter to add a delay between when the rule is matched and when the action is performed. You can also specify the **Run in** to add an additional delay, in minutes.

> [!NOTE]
>
> **Action Offset UTC Consideration**: Unlike rule offsets, you should consider UTC and local timezone differences when setting action offsets if you want actions to execute at a specific local time. Remember that action timing uses UTC as the reference, where day boundaries occur at 00:00 UTC.

| Run | The event handler will perform the action... |
| - | - |
| **Immediately** | right away |
| **Beginning of next month** | at the beginning of the next month |
| **Beginning of next day** | at the beginning of the next day (at 00:00 UTC) |
| **After one day** | one day (24 hours) later |
| **Never** | never (do not perform the action) |

## Variables

When using an event handler to send an email or call an external action, you can customize the contents of the action, such as specifying the subject and body of an email, or the payload of a webhook or the parameters of a Lambda function call. In many cases, you may want to include details about the particular SIM and the rule condition that triggered the action. By using the following **Variables** directly inside the action parameters, the event handler will fill in the corresponding value.

- `${imsi}` - The IMSI of the subscriber that met the rule condition.
- `${simId}` - The SIM ID of the SIM that met the rule condition.
- `${operatorId}` - The Operator ID that the SIM or subscriber is registered to.
- `${coverage}` - The coverage type that the SIM or subscriber is registered to (`g` for Global coverage, or `jp` for Japan coverage).
- `${date}` - The date that the rule condition is met (format: `yyyy/m/d`).
- `${year}` - The year that the rule condition is met (format: `yyyy`).
- `${month}` - The month that the rule condition is met (format: `m`).
- `${day}` - The day that the rule condition is met (format: `d`).
- `${tags.<key>}` - The value of a specific tag belonging to the SIM, such as `${tags.name}` for the SIM name, or `${tags.myCustomTag}` for a [custom tag](https://docs.soracom.io/en/services/air/tags) with the tag name `myCustomTag` that you have set.

When using the **Subscriber status attribute**, **Sim status attribute**, **Subscriber expired**, or **Sim expired** rules, you can also use these variables in the actions:

- `${oldStatus}` - The SIM or subscriber's previous [status](https://docs.soracom.io/en/services/air/subscriber-status).
- `${newStatus}` - The SIM or subscriber's current [status](https://docs.soracom.io/en/services/air/subscriber-status).

Similarly, when using the **Subscriber speed class attribute** or **Sim speed class attribute** rules, you can use these variables in the actions:

- `${oldSpeedClass}` - The SIM or subscriber's previous [speed class](https://docs.soracom.io/en/services/air/speed-class).
- `${newSpeedClass}` - The SIM or subscriber's current [speed class](https://docs.soracom.io/en/services/air/speed-class).

When using the **Subscriber session status changed** or **Sim session status changed** rule, you can use the following variable in the actions:

- `${sessionStatus}` - The session status that triggered the rule (`Created` or `Deleted`).

The **Sim subscription status** rule contains additional variables useful for checking the [Subscription Container](https://docs.soracom.io/en/services/air/subscription-containers) status:

- `${subscription}` - The name of the subscription container being added to the SIM.

- `${otaStatus}` - The delivery status of the subscription container (one of the following: `started`, `finished`, or `failed`).

- `${imsi}` - The IMSI of the newly added subscription container, or of the original plan01s or plan-US subscription, based on the OTA status:

  - If the OTA status is `started` or `failed`, this variable will return the IMSI of the plan01s or plan-US subscription.
  - If the OTA status is `finished`, this variable will return the IMSI of the newly added subscription container.

- `${primaryImsi}` - The IMSI of the original plan01s or plan-US subscription.

When using the **Monthly bill amount** rule, you can use the following variables in the actions:

- `${operatorId}` - The Operator ID where the billing alert occurred.
- `${coverage}` - The coverage type where the billing alert occurred (`g` for Global coverage, or `jp` for Japan coverage).
- `${limitTotalAmount}` - The bill alert threshold that was exceeded.
- `${currentTotalAmount}` - The actual current monthly bill amount, at the time the billing alert was triggered.

Variables can be used in the following action parameters:

- **Send email** and **Send email to Operator** actions:

  - **Title**
  - **Message**

- **Execute web request** action:

  - **URL**
  - **Headers**
  - **Body**

- **Invoke AWS Lambda** action:

  - **parameter1** value
  - **parameter2** value
  - **parameter3** value
  - **parameter4** value
  - **parameter5** value

## Creating an Event Handler

1. Sign in to the **[User Console](https://console.soracom.io/?coverage_type=g)**. From the **☰ Menu**, open the **Event Handler** screen.

   ![Create Event Handler](https://docs.soracom.io/_astro/create-event-handler.Djnn6kxN_cSfLV.webp)

2. Click the +**Create Event** button.

3. Enter the event handler **configuration parameters**:

   ![Event Handler Configuration](https://docs.soracom.io/_astro/event-handler-configuration.DKbCEjj2_Jx94i.webp)

   - **Name** (required) - A name that uniquely identifies the event handler.
   - **Description** (optional) - A brief description that describes the behavior of the event handler.
   - **Target** (required) - The subscribers that the event handler should be applied to.
   - **Rule** (required) - The condition that must be met in order for the event handler configuration to execute its actions.
   - **Action** (one or more required) - One or more actions to perform when an event handler configuration's rule condition is met.
   - **Active** - Enables or disables the event handler.

4. Click the **Create** button.

## Editing an Event Handler

1. Sign in to the **[User Console](https://console.soracom.io/?coverage_type=g)**. From the **☰ Menu**, open the **Event Handler** screen.

2. From the list of event handlers, click the **name** of the event handler that you want to edit.

   ![Edit Event Handler](https://docs.soracom.io/_astro/edit-event-handler.BhRMSNkf_M5eIi.webp)

3. Enter the event handler **configuration parameters**.

4. Click the **Update** button.

## Deleting an Event Handler

1. Sign in to the **[User Console](https://console.soracom.io/?coverage_type=g)**. From the **☰ Menu**, open the **Event Handler** screen.

2. From the list of event handlers, click the **☑** for the event handler you want to delete, then click the **Delete** button.

   ![Delete Event Handler](https://docs.soracom.io/_astro/delete-event-handler.BOwR3Ikj_2gmYFn.webp)

3. Click the **Delete** button again to confirm.

   ![Delete Event Handler](https://docs.soracom.io/_astro/delete-event-handler-confirm.z62P3-d6_Z1lV5fH.webp)

## Advanced Configuration

Configuring an event handler can also be done using either the Soracom API or Soracom CLI. Each event handler configuration is defined using a JSON object, which contains the **Target**, **Name** and **Description**, **Rule**, **Action**, and **Status** properties.

## Configuration Structure

```json
{
  "name": "My event handler name",
  "description": "My event handler description",
  "targetImsi": "295050012345678", // match a single subscriber
  "targetSimId": "8942310000012345678", // match a single SIM
  "targetGroupId": "abcdef00-0000-0000-0000-000012345678", // match a group of SIMs or subscribers
  "targetOperatorId": "OP0012345678", // match all SIMs or subscribers
  "ruleConfig": {
    "type": "ruleType",
    "properties": {
      "inactiveTimeoutDateConst": "IMMEDIATELY",
      "inactiveTimeoutOffsetMinutes": "0"
      // ...additional rule parameters
    }
  },
  "actionConfigList": [
    {
      "type": "actionType",
      "properties": {
        "key": "value"
        // ...additional action parameters
      }
    }
    // ...additional actions
  ],
  "status": "active"
}
```

## Event Handler Parameters

Regardless of which rule or actions you want to configure, all event handler configurations will contain the following parameters:

- **name** (_string_, required) - A unique name for the event handler.

- **description** (_string_, optional) - A brief description for the event handler.

- **targetImsi** (_string_, required) - The IMSI of a single subscriber.

- **targetSimId** (_string_, required) - The SIM ID of a single SIM.

- **targetGroupId** (_string_, required) - The Group ID of a group.

- **targetOperatorId** (_string_, required) - Your Operator ID.

- **ruleConfig** (_object_, required) - The rule configuration.

  - **type** (_string_, required) - The rule to use.
  - **properties** (_object_, required) - The settings for the rule. The attributes within this object depend on what rule you use. See the [Rule Parameters](https://docs.soracom.io/en/services/event-handler/configuration/#rule-parameters) below.

- **actionConfigList** (_array_ of _objects_, required) - An array of actions to perform. Each action will consist of:

  - **type** (_string_, required) - The action to perform.
  - **properties** (_object_, required) - The settings for the action. The attributes within this object depend on what action you use. See [Action Parameters](https://docs.soracom.io/en/services/event-handler/configuration/#action-parameters) below.

- **status** (_string_, required) - Enables or disables the event handler. Valid options: `"active"` or `"inactive"`.

> [!WARNING]
>
> Only one of **targetImsi**, **targetSimId**, **targetGroupId**, and **targetOperatorId** needs to be specified.

## Rule Parameters

Each event handler's **ruleConfig** parameter should follow one of the following rule schemas.

Execute actions when a subscriber sends or receives data for the first time:

**Schema**

- **type** (_string_, required) - `SubscriberFirstTrafficRule`

- **properties** (_object_, required) - The settings for the rule.

  - **inactiveTimeoutDateConst** (_string_, required) - See **Additional Rule Properties** below.
  - **inactiveTimeoutOffsetMinutes** (_string_, optional) - See **Additional Rule Properties** below.
  - **runOnceAmongTarget** (_boolean_, optional) - See **Additional Rule Properties** below.

**Example**

```json
  // Matches whenever a subscriber uses data for the first time, and does not repeat again for that subscriber
  "ruleConfig": {
    "type": "SubscriberFirstTrafficRule",
    "properties": {
      "inactiveTimeoutDateConst": "NEVER"
    }
  }
```

Execute actions based on a SIM or subscriber's data usage, or total data usage across all SIMs and subscribers:

**Schema**

- **type** (_string_, required) - The data usage rule. Valid options:

  - `SubscriberDailyTrafficRule` - Matches when a subscriber's daily data usage exceeds a specified value.
  - `SubscriberMonthlyTrafficRule` - Matches when a subscriber's monthly data usage exceeds a specified value.
  - `SubscriberCumulativeTrafficRule` - Matches when a subscriber's lifetime cumulative data usage exceeds a specified value.
  - `SimDailyTotalTrafficRule` - Matches when a SIM's total daily data usage across all of its subscriptions exceeds a specified value.
  - `SimMonthlyTotalTrafficRule` - Matches when a SIM's total monthly data usage across all of its subscriptions exceeds a specified value.
  - `SimCumulativeTotalTrafficRule` - Matches when a SIM's total lifetime cumulative data usage across all of its subscriptions exceeds a specified value.
  - `DailyTotalTrafficRule` - Matches when the total daily data usage across all SIMs and subscriptions exceeds a specified value.
  - `MonthlyTotalTrafficRule` - Matches when the total monthly data usage across all SIMs and subscriptions exceeds a specified value.

- **properties** (_object_, required) - The settings for the rule.

  - **limitTotalTrafficMegaByte** (_integer_ in MB, required) - Execute action(s) when data usage exceeds this value.
  - **inactiveTimeoutDateConst** (_string_, required) - See **Additional Rule Properties** below.
  - **inactiveTimeoutOffsetMinutes** (_string_, optional) - See **Additional Rule Properties** below.
  - **runOnceAmongTarget** (_boolean_, optional) - See **Additional Rule Properties** below.

> [!NOTE]
>
> When using a data usage rule, the **inactiveTimeoutDateConst** parameter cannot be set as `IMMEDIATELY`.

**Example**

```json
  // Matches whenever a SIM exceeds 100 MB of data usage in a day, and waits until the next day before checking that SIM again
  "ruleConfig": {
    "type": "SimDailyTotalTrafficRule",
    "properties": {
      "limitTotalTrafficMegaByte": 100,
      "inactiveTimeoutDateConst": "BEGINNING_OF_NEXT_DAY"
    }
  }
```

Execute actions based on a SIM or subscriber's [status](https://docs.soracom.io/en/services/air/subscriber-status) (`active`, `inactive`, etc.):

**Schema**

- **type** (_string_, required) - `SubscriberStatusAttributeRule` or `SimStatusAttributeRule`

- **properties** (_object_, required) - The settings for the rule.

  - **sourceStatus** (_string_ or `null`, optional) - Execute action(s) when the status is changed from this value. Valid options:

    - `null` or _not set_ - Matches anytime a SIM or subscriber's status changes, regardless of the old status.
    - `ready` - Matches when a SIM or subscriber's status changes from **Ready**.
    - `active` - Matches when a SIM or subscriber's status changes from **Active**.
    - `inactive` - Matches when a SIM or subscriber's status changes from **Inactive**.
    - `standby` - Matches when a SIM or subscriber's status changes from **Standby**.
    - `suspended` - Matches when a SIM or subscriber's status changes from **Suspended**.
    - `terminated` - Matches when a SIM or subscriber's status changes from **Terminated**.

  - **targetStatus** (_string_ or `null`, optional) - Execute action(s) when the status is changed to this value. Valid options:

    - `null` or _not set_ - Matches anytime a SIM or subscriber's status changes, regardless of the new status.
    - `ready` - Matches when a SIM or subscriber's status changes to **Ready**.
    - `active` - Matches when a SIM or subscriber's status changes to **Active**.
    - `inactive` - Matches when a SIM or subscriber's status changes to **Inactive**.
    - `standby` - Matches when a SIM or subscriber's status changes to **Standby**.
    - `suspended` - Matches when a SIM or subscriber's status changes to **Suspended**.
    - `terminated` - Matches when a SIM or subscriber's status changes to **Terminated**.

  - **inactiveTimeoutDateConst** (_string_, required) - See **Additional Rule Properties** below.

  - **inactiveTimeoutOffsetMinutes** (_string_, optional) - See **Additional Rule Properties** below.

  - **runOnceAmongTarget** (_boolean_, optional) - See **Additional Rule Properties** below.

**Example**

```json
  // Matches whenever a subscriber's status changes to Active, and does not repeat again for that subscriber
  "ruleConfig": {
    "type": "SubscriberStatusAttributeRule",
    "properties": {
      "targetStatus": "active",
      "inactiveTimeoutDateConst": "NEVER"
    }
  }
```

Execute actions based on a SIM's [Subscription Container](https://docs.soracom.io/en/services/air/subscription-containers) status (`started`, `finished`, etc.):

**Schema**

- **type** (_string_, required) - `SimSubscriptionStatusRule`

- **properties** (_object_, required) - The settings for the rule.

  - **targetStatus** (_string_ or `null`, optional) - Execute action(s) when the status is changed to this value. Valid options:

    - `null` or _not set_ - Matches anytime a SIM's subscription container status changes, regardless of the new status.
    - `started` - Matches when a subscription container delivery is initiated.
    - `finished` - Matches when a subscription container is successfully delivered.
    - `failed` - Matches when a subscription container delivery failed.

  - **inactiveTimeoutDateConst** (_string_, required) - See **Additional Rule Properties** below.

  - **inactiveTimeoutOffsetMinutes** (_string_, optional) - See **Additional Rule Properties** below.

  - **runOnceAmongTarget** (_boolean_, optional) - See **Additional Rule Properties** below.

**Example**

```json
  // Matches whenever a subscription container is successfully added to a SIM, and does not repeat again for that SIM
  "ruleConfig": {
    "type": "SimSubscriptionStatusRule",
    "properties": {
      "targetStatus": "finished",
      "inactiveTimeoutDateConst": "NEVER"
    }
  }
```

Execute actions based on a SIM or subscriber's [speed class](https://docs.soracom.io/en/services/air/speed-class) (`s1.minimum`, `s1.standard`, etc.):

**Schema**

- **type** (_string_, required) - `SubscriberSpeedClassAttributeRule` or `SimSpeedClassAttributeRule`

- **properties** (_object_, required) - The settings for the rule.

  - **targetSpeedClass** (_string_ or `null`, optional) - Execute action(s) when the speed class is changed to this value. Valid options:

    - `null` or _not set_ - Matches anytime a SIM or subscriber's speed class changes, regardless of the new speed class.
    - `s1.minimum` - Matches when a SIM or subscriber's speed class changes to **s1.minimum**.
    - `s1.slow` - Matches when a SIM or subscriber's speed class changes to **s1.slow**.
    - `s1.standard` - Matches when a SIM or subscriber's speed class changes to **s1.standard**.
    - `s1.fast` - Matches when a SIM or subscriber's speed class changes to **s1.fast**.
    - `s1.4xfast` - Matches when a SIM or subscriber's speed class changes to **s1.4xfast**.
    - `s1.8xfast` - Matches when a SIM or subscriber's speed class changes to **s1.8xfast**.

  - **inactiveTimeoutDateConst** (_string_, required) - See **Additional Rule Properties** below.

  - **inactiveTimeoutOffsetMinutes** (_string_, optional) - See **Additional Rule Properties** below.

  - **runOnceAmongTarget** (_boolean_, optional) - See **Additional Rule Properties** below.

**Example**

```json
  // Matches whenever a SIM's speed class is changed, and waits 5 minutes before checking again for that SIM
  "ruleConfig": {
    "type": "SimSpeedClassAttributeRule",
    "properties": {
      "targetSpeedClass": null,
      "inactiveTimeoutDateConst": "IMMEDIATELY",
      "inactiveTimeoutOffsetMinutes": "5"
    }
  }
```

Execute actions when a subscriber has expired as a result of its [Expiration](https://docs.soracom.io/en/services/air/expiration) settings:

**Schema**

- **type** (_string_, required) - `SubscriberExpiredRule` or `SimExpiredRule`

- **properties** (_object_, required) - The settings for the rule.

  - **inactiveTimeoutDateConst** (_string_, required) - See **Additional Rule Properties** below.
  - **inactiveTimeoutOffsetMinutes** (_string_, optional) - See **Additional Rule Properties** below.
  - **runOnceAmongTarget** (_boolean_, optional) - See **Additional Rule Properties** below.

**Example**

```json
  // Matches only the first SIM that expires, and does not repeat again even for other SIMs
  "ruleConfig": {
    "type": "SimExpiredRule",
    "properties": {
      "inactiveTimeoutDateConst": "NEVER",
      "runOnceAmongTarget": true
    }
  }
```

Execute actions when the IMEI of the device using a subscriber does not match the subscriber's [IMEI Lock](https://docs.soracom.io/en/services/air/imei-lock) settings:

**Schema**

- **type** (_string_, required) - `SubscriberImeiMismatchedRule` or `SimImeiMismatchedRule`

- **properties** (_object_, required) - The settings for the rule.

  - **inactiveTimeoutDateConst** (_string_, required) - See **Additional Rule Properties** below.
  - **inactiveTimeoutOffsetMinutes** (_string_, optional) - See **Additional Rule Properties** below.
  - **runOnceAmongTarget** (_boolean_, optional) - See **Additional Rule Properties** below.

**Example**

```json
  // Matches whenever the IMEI of a device does not match a SIM's IMEI Lock setting, and waits until the next day before checking again for that SIM
  "ruleConfig": {
    "type": "SimImeiMismatchedRule",
    "properties": {
      "inactiveTimeoutDateConst": "BEGINNING_OF_NEXT_DAY",
      "runOnceAmongTarget": false
    }
  }
```

Execute actions when a subscriber or SIM session status changes:

**Schema**

- **type** (_string_, required) - `SubscriberSessionStatusRule` or `SimSessionStatusRule`

- **properties** (_object_, required) - The settings for the rule.

  - **targetSessionStatus** (_string_, required) - The session status that will trigger the rule. Valid options:

    - `Created` - Matches when a subscriber or SIM session is created (device comes online).
    - `Deleted` - Matches when a subscriber or SIM session is deleted (device goes offline).

  - **hasImei** (_boolean_, optional) - When set to `true`, execute action(s) only when the session event includes an IMEI.

  - **inactiveTimeoutDateConst** (_string_, required) - See **Additional Rule Properties** below.

  - **inactiveTimeoutOffsetMinutes** (_string_, optional) - See **Additional Rule Properties** below.

  - **runOnceAmongTarget** (_boolean_, optional) - See **Additional Rule Properties** below.

**Example**

```json
  // Matches when a SIM session is created and includes an IMEI, and does not repeat again for that SIM
  "ruleConfig": {
    "type": "SimSessionStatusRule",
    "properties": {
      "targetSessionStatus": "Created",
      "hasImei": true,
      "inactiveTimeoutDateConst": "NEVER"
    }
  }
```

Execute actions when the current monthly bill total exceeds a specific amount:

**Schema**

- **type** (_string_, required) - `MonthlyChargeRule`

- **properties** (_object_, required) - The settings for the rule.

  - **limitTotalAmount** (_string_, required) - Execute action(s) when the current monthly bill total exceeds this value.
  - **inactiveTimeoutDateConst** (_string_, required) - See **Additional Rule Properties** below.
  - **inactiveTimeoutOffsetMinutes** (_string_, optional) - See **Additional Rule Properties** below.

**Example**

```json
  // Matches whenever the current month's bill total exceeds 100 USD, and waits until the next month before checking again
  "ruleConfig": {
    "type": "MonthlyChargeRule",
    "properties": {
      "limitTotalAmount": "100",
      "inactiveTimeoutDateConst": "BEGINNING_OF_NEXT_MONTH"
    }
  }
```

### Additional Rule Properties

- **inactiveTimeoutDateConst** (_string_, required) - Controls how long the event handler should wait before it re-evaluates the rule. Valid options:

  - `IMMEDIATELY` - Re-evaluate the rule immediately.
  - `BEGINNING_OF_NEXT_MONTH` - Re-evaluate the rule at the beginning of the next month.
  - `BEGINNING_OF_NEXT_DAY` - Re-evaluate the rule at the beginning of the next day (at 00:00 UTC).
  - `AFTER_ONE_DAY` - Re-evaluate the rule one day (24 hours) later.
  - `NEVER` - Do not re-evaluate.

- **inactiveTimeoutOffsetMinutes** (_string_, optional) - Adds an additional delay in minutes after **inactiveTimeoutDateConst**, before the event handler re-evaluates the rule.

- **runOnceAmongTarget** (_boolean_, optional) - When enabled, specifies that the event handler should run only one across all SIMs or subscribers in the target, rather than for each SIM or subscriber individually, until the event handler is scheduled to re-evaluate. This parameter has no effect for **Subscriber** targets.

## Action Parameters

Each event handler's **actionConfigList** parameter should be an array that consists of one or more actions, each of which follows one of the following action schemas.

Send an email:

**Schema**

- **type** (_string_, required) - `SendMailAction` or `SendMailToOperatorAction`

- **properties** (_object_, required) - The settings for the action.

  - **to** (_string_, required) - The email address where the message will be sent (not required when using `SendMailToOperatorAction`).
  - **title** (_string_, required) - The email subject.
  - **message** (_string_, required) - The email body.
  - **executionDateTimeConst** (_string_, required) - See **Additional Action Properties** below.
  - **executionOffsetMinutes** (_string_, optional) - See **Additional Action Properties** below.

**Example**

```json
  // Send an email right away
  "actionConfigList": [
    {
      "type": "SendMailAction",
      "properties": {
        "to": "sora@soracom.io",
        "title": "Event Handler Called",
        "message": "This email was sent to inform you that your event handler was called.",
        "executionDateTimeConst": "IMMEDIATELY"
      }
    }
  ]
```

Change a SIM or subscriber's status:

**Schema**

- **type** (_string_, required) - The status to change the SIM or subscriber to. Valid options:

  - `ActivationAction` - Changes the SIM or subscriber's status to **Active**.
  - `DeactivationAction` - Changes the SIM or subscriber's status to **Inactive**.
  - `StandbyAction` - Changes the SIM or subscriber's status to **Standby**.
  - `SuspendAction` - Changes the SIM or subscriber's status to **Suspended**.

- **properties** (_object_, required) - The settings for the action.

  - **executionDateTimeConst** (_string_, required) - See **Additional Action Properties** below.
  - **executionOffsetMinutes** (_string_, optional) - See **Additional Action Properties** below.

**Example**

```json
  // Wait 1440 minutes (24 hours), then change the SIM or subscriber status to Standby
  "actionConfigList": [
    {
      "type": "StandbyAction",
      "properties": {
        "executionDateTimeConst": "IMMEDIATELY",
        "executionOffsetMinutes": "1440"
      }
    }
  ]
```

Change a SIM or subscriber's speed class:

**Schema**

- **type** (_string_, required) - `ChangeSpeedClassAction`

- **properties** (_object_, required) - The settings for the action.

  - **speedClass** (_string_, required) - Change the subscriber's speed class to the specified speed class. Possible values:

    - `"s1.minimum"` - Changes the subscriber's speed class to **s1.minimum**.
    - `"s1.slow"` - Changes the subscriber's speed class to **s1.slow**.
    - `"s1.standard"` - Changes the subscriber's speed class to **s1.standard**.
    - `"s1.fast"` - Changes the subscriber's speed class to **s1.fast**.
    - `"s1.4xfast"` - Changes the subscriber's speed class to **s1.4xfast**.
    - `"s1.8xfast"` - Changes the subscriber's speed class to **s1.4xfast**.

  - **executionDateTimeConst** (_string_, required) - See **Additional Action Properties** below.

  - **executionOffsetMinutes** (_string_, optional) - See **Additional Action Properties** below.

**Example**

```json
  // Change the SIM or subscriber speed class to s1.minimum right away
  "actionConfigList": [
    {
      "type": "ChangeSpeedClassAction",
      "properties": {
        "speedClass": "s1.minimum",
        "executionDateTimeConst": "IMMEDIATELY"
      }
    }
  ]
```

Run a Webhook:

**Schema**

- **type** (_string_, required) - `ExecuteWebRequestAction`

- **properties** (_object_, required) - The settings for the action.

  - **url** (_string_, required) - The URL to execute, including any parameters.
  - **httpMethod** (_string_, required) - The type of HTTP request. Possible values: `GET`, `POST`, `PUT`, or `DELETE`.
  - **contentType** (_string_, required) - The HTTP request content type such as `application/json`.
  - **headers** (_hash_, optional) - The HTTP request header values. This value should be a string containing an escaped JSON object, with each key-value pair representing the HTTP request header name and header value, such as `"{\"x-header-name\": \"header-value\"}"`.
  - **body** (_string_, optional) - A character string to be set in the body of the request. Only used when **httpMethod** is set to `POST` or `PUT`.
  - **executionDateTimeConst** (_string_, required) - See **Additional Action Properties** below.
  - **executionOffsetMinutes** (_string_, optional) - See **Additional Action Properties** below.

**Example**

```json
  // Wait 1 minute, then execute a webhook
  "actionConfigList": [
    {
      "type": "ExecuteWebRequestAction",
      "properties": {
        "url": "https://www.example.com/my/api",
        "httpMethod": "POST",
        "contentType": "application/json",
        "body": "{ \"text\": \"The event handler was called from SIM ${simId}\" }",
        "executionDateTimeConst": "IMMEDIATELY",
        "executionOffsetMinutes": "1"
      }
    }
  ]
```

Invoke an AWS Lambda Function:

**Schema**

- **type** (_string_, required) - `InvokeAWSLambdaAction`

- **properties** (_object_, required) - The settings for the action.

  - **endpoint** (_string_, required) - AWS Lambda function endpoint URL.
  - **functionName** (_string_, required) - AWS Lambda function name (optional version number or function alias can also be set).
  - **accessKey** (_string_, required) - AWS Lambda access key.
  - **secretAccessKey** (_string_, required) - AWS Lambda secret access key.
  - **parameter1** (_string_, optional) - Optional parameter.
  - **parameter2** (_string_, optional) - Optional parameter.
  - **parameter3** (_string_, optional) - Optional parameter.
  - **parameter4** (_string_, optional) - Optional parameter.
  - **parameter5** (_string_, optional) - Optional parameter.
  - **executionDateTimeConst** (_string_, required) - See **Additional Action Properties** below.
  - **executionOffsetMinutes** (_string_, optional) - See **Additional Action Properties** below.

When the **InvokeAWSLambdaAction** action is executed, the following JSON is passed to the Lambda function:

```json
{
  "imsi": "295050012345678",
  "parameter1": "my parameter 1",
  "parameter2": "my parameter 2",
  "parameter3": "my parameter 3",
  "parameter4": "my parameter 4",
  "parameter5": "my parameter 5"
}
```

The values can be accessed in the Lambda function as properties of the `event` parameter:

```js
exports.handler = function(event, context) {
  console.log('Function called from IMSI ', event.imsi);
  console.log('The value of parameter1 is ', event.parameter1);
  context.succeed(event.imsi);
};
```

**Example**

```json
  // Invoke an AWS Lambda function right away
  "actionConfigList": [
    {
      "type": "InvokeAWSLambdaAction",
      "properties": {
        "endpoint": "https://lambda.us-east-2.amazonaws.com",
        "functionName": "my-lambda-function",
        "accessKey": "ABC123XXXXXXXXXX",
        "secretAccessKey": "ABC123XXXXXXXXXX",
        "parameter1": "my value",
        "executionDateTimeConst": "IMMEDIATELY"
      }
    }
  ]
```

### Variables

The `SendMailAction`, `SendMailToOperatorAction`, `ExecuteWebRequestAction`, and `InvokeAWSLambdaAction` actions allow you to define custom values or parameters that will be used in the email, webhook, or Lambda function.

See [Variables](https://docs.soracom.io/en/services/event-handler/configuration/#variables) above for the list of available variables.

### Additional Action Properties

- **executionDateTimeConst** (_string_, required) - Controls how long the event handler should wait before it performs the action. Valid options:

  - `IMMEDIATELY` - Execute the action immediately.
  - `BEGINNING_OF_NEXT_MONTH` - Execute the action at the beginning of the next month.
  - `BEGINNING_OF_NEXT_DAY` - Execute the action at the beginning of the next day (at 00:00 UTC).
  - `AFTER_ONE_DAY` - Execute the action one day (24 hours) later.
  - `NEVER` - Do not execute.

- **executionOffsetMinutes** (_string_, optional) - Adds an additional delay in minutes after **executionDateTimeConst**, before the event handler performs the action.

Once your event handler JSON configuration is ready, you can pass it into the Soracom API or Soracom CLI.

## Programmatic Usage

You can also create, delete, and modify Event Handlers programmatically.

### Soracom API

To access the Soracom API, first use the [**auth**](https://docs.soracom.io/en/api#!/Auth/auth) API to obtain an API Key and Token. Refer to the [**API Usage Guide**](https://docs.soracom.io/en/developers/soracom-api) for instructions on how to use the API Key and Token in API requests.

Then, use the [createEventHandler](https://docs.soracom.io/en/api#!/EventHandler/createEventHandler) API to create a new event handler:

**Global**

```bash
curl -X POST \
  -H 'X-Soracom-API-Key: <MY-API-KEY>' \
  -H 'X-Soracom-Token: <MY-TOKEN>' \
  -H 'Content-Type: application/json' \
  -d '{
        "name": "...",
        "targetGroupId": "abcdef00-0000-0000-0000-000012345678",
        "ruleConfig": { ... },
        "actionConfigList": [ ... ],
        "status": "active"
      }' \
  https://g.api.soracom.io/v1/event_handlers
```

**Japan**

```bash
curl -X POST \
  -H 'X-Soracom-API-Key: <MY-API-KEY>' \
  -H 'X-Soracom-Token: <MY-TOKEN>' \
  -H 'Content-Type: application/json' \
  -d '{
        "name": "...",
        "targetGroupId": "abcdef00-0000-0000-0000-000012345678",
        "ruleConfig": { ... },
        "actionConfigList": [ ... ],
        "status": "active"
      }' \
  https://jp.api.soracom.io/v1/event_handlers
```

To edit an existing event handler, use the [updateEventHandler](https://docs.soracom.io/en/api#!/EventHandler/updateEventHandler) API.

To delete an event handler, use the [deleteEventHandler](https://docs.soracom.io/en/api#!/EventHandler/deleteEventHandler) API.

### Soracom CLI

To use the Soracom CLI, you must first configure it to authenticate with your account information, authorization key, or SAM user credentials.

Then, run the following command to create an event handler:

**Global**

```bash
soracom event-handlers create --body "<CONFIG>" --coverage-type g
```

**Japan**

```bash
soracom event-handlers create --body "<CONFIG>" --coverage-type jp
```

Here, the JSON array from the API example above should be passed in to the `--body` parameter.

To edit an existing event handler, use the `soracom event-handlers update` command.

To delete an event handler, use the `soracom event-handlers delete` command.
