# What Relay Is: An Overview

<div><figure><img src="https://2387635908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FL7dimlztFKGWYQIaJ9DP%2Fuploads%2FWlvn5wAGO16hiu5ngCqO%2FDouble-Straight-On.png?alt=media&amp;token=4ca58072-2c22-4ac2-842d-ca52cdb47324" alt="" width="375"><figcaption><p>RelayX</p></figcaption></figure> <figure><img src="https://2387635908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FL7dimlztFKGWYQIaJ9DP%2Fuploads%2F4xUhRazmcjRwrL3H9qoQ%2FRelay%2Bduo-pile-lights.png?alt=media&amp;token=550c2108-2e34-4736-9bf5-5c07a9a365a7" alt="" width="375"><figcaption><p>Relay+</p></figcaption></figure></div>

Relay is a hardware-based platform for voice and mobile IoT applications. As an enterprise-first platform, it brings a modern software stack, an easy-to-use programming interface, and a quick path to integration. The goal of Relay is to enable your active workers to have two-way connections to the tools and people in the rest of your organization. And to do so with high capability, easy deployment, and low expense.

Relay's first success was in the voice communications space, with its push-to-talk capabilities and built-in connectivity. As a smart device, Relay can do more than push-to-talk communications. In the following sections we explain the "more".

### Jump right in

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Relay Capabilities</strong></td><td>More details on Relay products</td><td><a href="https://2387635908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FL7dimlztFKGWYQIaJ9DP%2Fuploads%2FJpFGkcSpyQPYhPAa2hoW%2Fdash_relay_landscape.png?alt=media&amp;token=9321e7e6-891a-4d2e-8917-fade55fd7b9c">dash_relay_landscape.png</a></td><td></td><td><a href="/introduction/relay-capabilities">Relay Capabilities</a></td></tr><tr><td><strong>FAQs</strong></td><td>Answers to commonly asked questions</td><td><a href="https://2387635908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FL7dimlztFKGWYQIaJ9DP%2Fuploads%2FmnYPkDMU78O790ahYg3q%2Fbutton_push_landscape.png?alt=media&amp;token=f3643412-219b-4664-930b-32dc8cd1bace">button_push_landscape.png</a></td><td></td><td><a href="/docs/relay-alerts-api">Relay HTTP APIs</a></td></tr><tr><td><strong>Alerts</strong></td><td>Use our API to send alerts via Relay</td><td><a href="https://2387635908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FL7dimlztFKGWYQIaJ9DP%2Fuploads%2FHtnM2FF1zUxuvq8C9lH6%2Frgb_circle_reverse.png?alt=media&amp;token=25462c59-61ad-4b1e-af64-5efad925cbc2">rgb_circle_reverse.png</a></td><td></td><td><a href="/docs/relay-alerts-api">Alerts</a></td></tr></tbody></table>


# Relay Capabilities

<figure><img src="https://2387635908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FL7dimlztFKGWYQIaJ9DP%2Fuploads%2F1w6nFJitjNErgkaRN8cI%2Frelay_connected_hardware_hero.png?alt=media&amp;token=d4b5fc01-358c-4fea-bf49-94b380c6c440" alt=""><figcaption></figcaption></figure>

With both cell and WiFi connectivity, Relay devices can go nationwide, extending beyond the reach of walkie talkies, without needing to install proprietary infrastructure. With IPX8 it survives moisture, dust, and shock, gracefully handling the active workplace. It is both uniquely portable, and at the same time capable and simplified. It includes the following:

* LTE connectivity over multiple cellular carriers included in the base price.
* Outdoor location positioning, including geofences.
* An enterprise solution for room-level indoor location that doesn't require an expensive infrastructure, and it can be self-deployed.
* Other sensors such as Bluetooth and NFC.
* Headsets for discreet audio communication via USB or Bluetooth.
* Generated speech (text to speech) and phrase recognition (speech to text).
* Playback of dynamic and pre-recorded audio.
* Push-to-talk audio communication.
* Relay-manufactured NFC tags with increased capabilities that can very inexpensively and securely identify your important locations.
* Controllable vibration and LED indicators (full color, individually addressable).
* A limited number of buttons for user simplicity, with detection of multi-tap sequences.


# FAQs

* Do I have to bring my own cellular connectivity?\
  No, we manage connectivity with leading cellular providers and include it on your devices.
* Are Relay devices rugged?\
  Our devices are rated IPX8, waterproof to more than 3 feet of water and dust resistant. Relay+ and RelayX are Military Standard Temperature, Drop, Vibration, Humidity and Fog certified (810G and 810H respectively).
* How is GPS data transmitted?\
  We provide Lat/Long coordinates updated as frequently as every 30 seconds (frequency is configurable)
* Do you support Speech-to-Text and Text-to-Speech?\
  Yes, we use our own proprietary algorithm to provide cloud-based text-to-speech and speech-to-text capability.

For questions on how to use your device or account management visit our [Customer Support page](https://support.relaypro.com/portal/en/kb/relay-pro).


# Alerts

## About

Relay’s Alert APIs notify your Relay users of any urgent events. Whether you’re a hotel, and want to quickly alert your housekeeping team or you’re a hospital, and need to alert the EVS team when a room needs to be turned over - the Relay Alert API can make it happen.

With the Alerts API, notifications are sent to specified groups on your account with a custom Text-to-Speech message and, optionally, an acknowledgement. The API allows you to send notifications that are either an **Alert** or a **Broadcast**. Notifications are done through a simple HTTP API. This allows you to effortlessly integrate these notifications into your own platform with an HTTP request. For example, if you had a ticketing system, broadcasting a message on a group of devices every time a ticket is added is done with an HTTP request to the `/broadcast` endpoint at the time of ticket creation.

Learn more below about how you can create different groups on your account, as well as how to make these API calls.

## Workflow Groups

Workflow Groups provide a way to organize users on your account.

A group is a set of one or more users on your account. In order to create a group, simply navigate to your Relay Dash home page and click on the **Incidents** section to the left. From there, you should see **Workflow Groups** option. Next, select **Create Workflow Group.** After entering a name for your group, select **No Type** and then you should be able to see your empty group in the **Workflow** **Groups** section. After selecting your group, you can then use the **Edit Membership** option to the left to add or remove users from the group.&#x20;

<figure><img src="https://2387635908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FL7dimlztFKGWYQIaJ9DP%2Fuploads%2FU6Bn9eklZ7XFxg8Xsax2%2FScreenshot%202025-09-03%20at%208.47.17%E2%80%AFAM.png?alt=media&amp;token=bb27d9c4-c6b6-4738-a656-187b97f93d78" alt=""><figcaption></figcaption></figure>


# Triggering an Alert

An alert is a message that is played out on devices within a specified group every 30 seconds until it is acknowledged.

An alert can be started through a simple `POST` request to our server into our `/alerts` endpoint.&#x20;

The `POST` command to send an alert should take the following form:

```http
POST /subscribers/{id}/api/v1/alerts
Authorization: RelayApiKey {apikey}
Content-type: application/json

{
   "notification": "hello world",
   "groups": ["mygroup"],
}
```

### Headers and Subscriber ID Path

* `apikey` : If you are on the enterprise plan, you can create an API key by navigating to **Help** → **API Keys** in [Relay Dash](https://dash.relaypro.com/api-keys). Your key should be included within the Authorization header. Don’t forget to include “RelayApiKey” before your actual key.
* `id` : your subscriber ID, which can be found on [Relay Dash](https://dash.relaypro.com/diagnostic-logs) through **Help** → **Diagnostic Logs** → **Server Details** under **Subscriber**

### **Required Content**

* `notification` : custom message to be spoken on the group of devices. The Relay server will automatically convert your written text into spoken audio (text-to-speech)
* `groups` : a list containing the group names or URNs to send the alert to.

### Example

The following example is a curl command that sends an alert request up to our server.

```sh
$ export subscriber_id=yourcustomersID
$ export apikey=myapikey123
$ curl -X POST -H "Authorization: RelayApiKey $apikey" "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts" -d '{"notification": "Cleanup needed in the lounge", "groups": ["housekeeping"]}' -i

HTTP/2 200 
date: Mon, 11 Dec 2023 14:31:36 GMT
content-type: application/json
content-length: 38
server: nginx/1.20.0
location: /subscribers/xxx/api/v1/alerts/P9CThKfTsEbJx23trAArHCD

{"task_id":"P9CThKfTsEbJx23trAArHCD"}
```

This curl command alerts the group “housekeeping” that there is “Cleanup needed in the lounge”. The alert will continue to sound on a user’s device every 30 seconds until it is acknowledged by the user tapping the talk button. Once the user taps the talk button, the alert will stop sounding on the device. If the user does not acknowledge the alert after 5 minutes, the alert will timeout and cease playing. See what this alert looks like on the device in the video below.

{% embed url="<https://www.youtube.com/watch?v=cvM9Oq4-t5g>" %}


# Customizing Your Alerts

In addition to the `notification` and `groups` keys, alerts give you the option to further customize your notification. There are 6 optional keys that you can include in your payload when sending the request:

* `on_ack` : custom message to be spoken on the device that acknowledged the alert (default: nothing is spoken)
* `quorum` : remaining alerts are canceled after this number of acknowledgements (default: all devices in the group must acknowledge the alert)
* `on_quorum` : custom message to be spoken on devices that have not yet acknowledged the alert after `quorum` is met (default: nothing is spoken)
* `timeout` : remaining alerts are canceled after this time (seconds) (default: 300)
* `on_timeout` : custom message to be spoken on the devices that have not acknowledged the alert after timeout (default: nothing is spoken)
* `name` : gives user agents control over serial / concurrent alerting. This also appears in the analytics events for correlation (default: “alerts”)

Upon adding these to the request, our `POST` command could take the following form:

```http
POST /subscribers/{id}/api/v1/alerts
Authorization: RelayApiKey {apikey}
Content-type: application/json

{
   "notification": "hello world",
   "groups": ["mygroup"],
   "on_ack": "thank you",
   "quorum": 1,
   "on_quorum": "already accepted",
   "timeout": 120,
   "on_timeout": "too slow",
   "name": "myname"
}
```

Let's see how we can customize our alert using some of these options. In the first example, we saw how we could send a simple alert to a group of devices using all of the default configuration settings. In the curl command below, we again trigger an alert with the message “Cleanup needed in the lounge” to the group “housekeeping”. However, this time we include four more key-value pairs into the request. We added in the `quorum` key with a value of 1, making it so our alert will only require that one device acknowledges the alert as opposed to all devices in the group. Once a device acknowledges the alert, the alert will terminate on all devices. We also included an `on_ack` key with a value of “thank you”. With this, after the user acknowledges the alert the device will say “thank you” to that user. This acts as a confirmation to the user that they acknowledged the alert. We also added in the `timeout` and `on_timeout` keys, making it so if the alert times out because no device tapped the talk button in an allocated 120 seconds, the devices will say “alert timed out!” on all of the devices in the group.

Putting all of this together, we get the curl command below.

```sh
$ export subscriber_id=yourcustomersID
$ export apikey=myapikey123
$ curl -X POST -H "Authorization: RelayApiKey $apikey" "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts" -d '{"notification": "Cleanup needed in the lounge", "groups": ["housekeeping"], "on_ack": "thank you","quorum": 1, "timeout": 120, "on_timeout": "alert timed out!" }' -i

HTTP/2 200 
date: Mon, 11 Dec 2023 14:31:36 GMT
content-type: application/json
content-length: 38
server: nginx/1.20.0
location: /subscribers/xxx/api/v1/alerts/P9CThKfTsEbJx23trAArHCD

{"task_id":"P9CThKfTsEbJx23trAArHCD"}
```

See this example in action below, where we run the curl command above to fire the alert, and a device acknowledges the alert by tapping the talk button. Notice that now, after a device acknowledges the alert, the device now says “thank you” to that user, and the alert terminates.

{% embed url="<https://www.youtube.com/watch?v=Q6DAMF5aIz0>" %}


# Advanced Configuration

### Cancel an Alert

Alerts will be repeated every 30 seconds on all devices that have not yet acknowledged the alert. However, you can explicitly cancel an alert on these devices through an API `DELETE` request.

The `DELETE` request should take the following form:

```http
DELETE /subscribers/{id}/api/v1/alerts/{task_id}
Authorization: RelayApiKey {apikey}
```

The following curl command deletes the alert we created above.

```sh
$ export subscriber_id=yourcustomersID
$ export apikey=myapikey123
$ curl -H "authorization: RelayApiKey $apikey" "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts/P9CThKfTsEbJx23trAArHCD" -X DELETE
```

{% hint style="info" %}
Notice that we add a `task_id` to the end of the path. This ID matches the returned `task_id` value from the response of the curl command that started the alert above, canceling that alert on all remaining devices.
{% endhint %}

### Analytics

An analytic event is created each time an alert has been acknowledged or has timed out. These events are logged on your account, and can be retrieved via the [Relay CLI](https://github.com/relaypro/relay-cli) command `relay analytics`.

For example, the following analytic event would be logged if the alert above has been acknowledged by a device named Mary:

```
  => Showing up to 20 events  
  Workflow ID                                           Type   Category Instance ID                Timestamp                   User ID Content  
  ───────────────────────────────────────────────────── ────── ──────── ────────────────────────── ─────────────────────────── ─────── ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────  
  ...  
  wf_y9CSxgI2V4goVt2Q9AemmEKA_YXcZ4rRCQxfS8QmpNUx9AYA   user   tasks    GzpGAKVPGlhfHt4H3kuWXA     2023-12-18T15:01:12.262552Z         {"device":"Mary","task":{"id":"P9CThKfTsEbJx23trAArHCD","name":"alerts","task_type":{"major":1,"minor":1,"name":"alerts","namespace":"system"}},"type":"acknowledged"}  
  ...
```

However, if the alert timed out before any acknowledgement, the following analytic event would be logged:

```
=> Showing up to 20 events  
  Workflow ID                                           Type   Category Instance ID                Timestamp                   User ID Content  
  ───────────────────────────────────────────────────── ────── ──────── ────────────────────────── ─────────────────────────── ─────── ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────  
  ...  
  wf_k6WtQtSdgU2vS1uIT9CED9CD_R8isRGD5R0da55PB7pgY4C    user   tasks    GzpGAKVPGlhfHt4H3kuWXA     2023-12-18T15:03:00.000345Z         {"task":{"id":"P9CThKfTsEbJx23trAArHCD","name":"alerts","task_type":{"major":1,"minor":1,"name":"alerts","namespace":"system"}},"type":"timed_out"}  
  ...
```

The workflow analytics command will show the 20 most recent events in the last 7 days by default. To view more events (up to 7 days), use the `--limit=100` option to increase the number of events displayed.


# Broadcasts

A broadcast is a message that is played out once on devices within the specified group, and no acknowledgement is needed.

A broadcast can be started through a simple `POST` request to our server into our `/broadcasts` endpoint. This can be done through an API platform like [Postman](https://www.postman.com/) or [Insomnia](https://insomnia.rest/), through simple curl commands in the shell, or within your codebase.

### Triggering a Broadcast

The `POST` command to send the broadcast should take the following form:

```http
POST /subscribers/{id}/api/v1/broadcasts
Authorization: RelayApiKey {apikey}
Content-type: application/json

{
   "notification": "hello world",
   "groups": ["mygroup"]
}
```

### Headers and Subscriber ID Path

* `apikey` : If you are on the enterprise plan, you can create an API key by navigating to **Help** → **API Keys** in [Relay Dash](https://dash.relaypro.com/api-keys). Your key should be included within the Authorization header. Don’t forget to include “RelayApiKey” before your actual key.
* `id` : your subscriber ID, which can be found on [Relay Dash](https://dash.relaypro.com/diagnostic-logs) through **Help** → **Diagnostic Logs** → **Server Details** under **Subscriber**

### Required Content

* `notification` : custom message to be spoken on the group of devices. The Relay server will automatically convert your written text into spoken audio (text-to-speech)
* `groups` : a list containing the group names or URNs to send the broadcast to

### Example

The following example shows a curl command that sends a broadcast request up to our server.

```sh
$ export subscriber_id=yourcustomersID
$ export apikey=myapikey123
$ curl -X POST -H "Authorization: RelayApiKey $apikey" "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/broadcasts" -d '{"notification": "All rounds must be done by 10pm tonight.", "groups": ["security1", "security2"]}' -i
```

This curl command broadcasts the message “All rounds must be done by 10pm tonight” to two different groups, security1 and security2. The message will only be broadcasted one time on all devices that are in either of those groups. See what this broadcast looks like on the device in the video below. Notice how no acknowledgement is needed from the user.

{% embed url="<https://www.youtube.com/watch?v=wFJOVJsZ9zE>" %}


# Events

An analytic event is created each time an alert has been triggered or acknowledged. Each event has an associated `task_id` that is the returned value from the response of an alert API call.&#x20;

{% hint style="info" %}
Analytic events also have an associated `name` field for correlation that can be programmatically set when an alert is sent via the `/alerts` endpoint. See [Customizing Your Alerts](/docs/relay-alerts-api/customizing-your-alerts).
{% endhint %}

Events can be retrieved through a simple `GET` request to our server into our `/events` endpoint.&#x20;

The `GET` command to send the broadcast should take the following form:

```http
GET /subscribers/{id}/api/v1/events
Authorization: RelayApiKey {apikey}
Content-type: application/json
```

### Headers and Subscriber ID Path

* `apikey` : If you are on the enterprise plan, you can create an API key by navigating to **Help** → **API Keys** in [Relay Dash](https://dash.relaypro.com/api-keys). Your key should be included within the Authorization header. Don’t forget to include “RelayApiKey” before your actual key.
* `id` : your subscriber ID, which can be found on [Relay Dash](https://dash.relaypro.com/diagnostic-logs) through **Help** → **Diagnostic Logs** → **Server Details** under **Subscriber**

### **Optional Query Parameters**

* `oldest`: An iso8601 timestamp which defaults to 7 days ago&#x20;
* `limit`: The maximum number of events returned which defaults to 100, the API will return no more than 100 events

### Example

The following example shows a curl command that retrieves the oldest analytic event from August 8th  from our server.

<pre class="language-sh"><code class="lang-sh"><strong>$ export subscriber_id=yourcustomersID
</strong>$ export apikey=apikey123
$ curl -s -H "authorization: RelayApiKey $apikey" "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/events?oldest=2024-08-08T12:00:30Z&#x26;limit=1" | jq
[
 {
  "category": "tasks",
  "content": {"type":"start"},
  "task": {"id": "mCcJawrh3shriXHombQxXA","name": "alerts","task_type": { "major": 1,
  "minor": 4, "name": "alerts", "namespace": "system"}},
  "event_id": "a195f66af5514cacbdbeea09c8e785f6",
  "timestamp": "2024-08-08T18:25:40.923947Z"
 }
]

</code></pre>

In the JSON object that gets returned details information about the event and the following fields determine what kind of analytic event it is:

* `content`: This field contains information on the event type as well as any external metadata that may have been sent with the event
  * `type`: This field represents the kind of event that is being returned and can equal the following:
    * `start`: event for when the alert was triggered
      * `end`: event for when the alert is completed (through time out, acknowledgement or error)
      * `acknowledged`: event for when device acknowledges an alert
      * `timed_out`: event for when an alert times out and no one has acknowledged it
  * `device`: This field will be present if the event `type` is `acknowledged` and represented the user profile associated with the device that acknowledged the alert
  * `status`: This field will be present if the event `type` is `end` and the alert has been completed, if the alert was completed without error this should equal `normal`
* `task` : The JSON object for the specific event
  * `id` : Identifier for the task that will be same for every event relevant to the triggered alert (start, acknowledge, time\_out, end), this allows you to track a task throughout each different stages
  * `name` : Correlation identifier that can be set when event is triggered, defaults to `alert`
* `event_id`: An unique identifier for the returned analytic event&#x20;
* `timestamp`: The time at which the event occured

The following is an example returned for an event for when an alert was triggered:

<pre class="language-json"><code class="lang-json">{
<strong>  "category": "tasks",
</strong>  "content": {  
              "type":"start"
              },
  "task": {
    "id": "mCcJawrh3shriXHombQxXA",
    "name": "alerts",
    "task_type": {
      "major": 1,
      "minor": 4,
      "name": "alerts",
      "namespace": "system"
    }
  },
  "event_id": "XXX",
  "timestamp": "2024-08-08T18:25:40.923947Z"
}
</code></pre>

The following is an example returned for an event for when an alert was acknowledged by user 'bob' on a device or virtual account:

```json
{
  "category": "tasks",
  "content": {
              "type":"acknowledged",
              "device": "bob" 
            },
  "task": {
    "id": "9C9AbxNELsQphK9Afhzr6yG6C",
    "name": "alerts",
    "task_type": {
      "major": 1,
      "minor": 2,
      "name": "alerts",
      "namespace": "system"
    }
  },
  "event_id": "XXX",
  "timestamp": "2024-08-08T18:25:40.923947Z"
}
```

The following is an example returned for an event for when an alert that timed out:

<pre class="language-json"><code class="lang-json">{
<strong>  "category": "tasks",
</strong>  "content": {  
              "type":"timed_out"
              },
  "task": {
    "id": "mCcJawrh3shriXHombQxXA",
    "name": "alerts",
    "task_type": {
      "major": 1,
      "minor": 2,
      "name": "alerts",
      "namespace": "system"
    }
  },
  "event_id": "XXX",
  "timestamp": "2024-08-08T18:25:40.923947Z"
}
</code></pre>

The following is an example returned for an event for when an alert was completed:

<pre class="language-json"><code class="lang-json">{
<strong>  "category": "tasks",
</strong>  "content": {  
              "type":"end",
              "status": "normal"
              },
  "task": {
    "id": "9C9AbxNELsQphK9Afhzr6yG6C",
    "name": "alerts",
    "task_type": {
      "major": 1,
      "minor": 2,
      "name": "alerts",
      "namespace": "system"
    }
  },
  "event_id": "XXX",
  "timestamp": "2024-08-08T18:25:40.923947Z"
}
</code></pre>


# Workflows


# Registering Your Workflows


# Triggers, Events and Commands


# Example Use Cases


# Telit DeviceWISE

## Overview

[Telit deviceWISE Cloud](https://www.telit.com/iot-platforms-overview/telit-devicewise-cloud/) is an industrial IoT platform that models equipment as **Things** carrying **properties**, **attributes**, and **alarms**. Its **Cloud Triggers** engine watches for changes to those objects and runs a sequence of actions in response.

One of those actions, `http.client`, can call any publicly reachable HTTPS endpoint. That is all you need to turn a PLC fault into a voice alert in a technician's hand: deviceWISE detects the alarm, posts to the [Relay Alerts API](https://developer.relaypro.com/docs/relay-alerts-api), and every device in the target Workflow Group speaks the message until someone taps the talk button to accept the job.

This page builds a complete, working **machine-down** alert.

```mermaid
flowchart LR
    A["PLC / equipment"] --> C["DeviceWISE<br/>Cloud Trigger<br/>alarm.change"]
    C --> E["Relay Server <br/>http.client action<br/>POST /alerts"]
    E --> F["Relay devices<br/>in Workflow Group"]
    F --> G["Acknowledged"]
```

### Why Alerts and not Broadcasts

Relay offers two notification types. Use **Alerts** for machine-down. An alert repeats every 30 seconds until a human acknowledges it and records who accepted the job, which is exactly the accountability a maintenance call needs. A [broadcast](https://developer.relaypro.com/docs/relay-broadcasts-api) plays once with no acknowledgement — fine for shift announcements, wrong for downtime.

***

## Prerequisites

<table><thead><tr><th width="180">Side</th><th>Requirement</th></tr></thead><tbody><tr><td>Relay</td><td>An <strong>enterprise plan</strong> account. API keys are not available on lower tiers.</td></tr><tr><td>Relay</td><td>A <strong>Workflow Group</strong> containing the users who should receive machine-down calls.</td></tr><tr><td>Relay</td><td>Your <strong>subscriber ID</strong> and an <strong>API key</strong>.</td></tr><tr><td>Telit</td><td>A deviceWISE Cloud organization with the <strong>Triggers</strong> feature enabled. If <code>/triggers</code> returns <em>"Triggers are not available. Please contact support to enable this feature,"</em> Triggers is not provisioned on your org — open a ticket with Telit before going further.</td></tr><tr><td>Telit</td><td>A <strong>Thing</strong> representing the machine, publishing an alarm when the machine faults.</td></tr><tr><td>Telit</td><td>A user with <strong>Developer</strong> permissions in the org.</td></tr></tbody></table>

{% hint style="info" %}
This guide assumes your gateway or edge application already publishes a machine-state alarm to the Thing. Modeling that alarm is a deviceWISE-side exercise; see Telit's [Adding a trigger](https://docs.devicewise.com/Content/Products/Management_Portal/Developer/Triggers/Adding-a-trigger.htm) walkthrough for a worked example of alarm publishing.
{% endhint %}

***

{% stepper %}
{% step %}

## Create the Relay Workflow Group

In [Relay Dash](https://dash.relaypro.com/), open **Incidents** in the left-hand navigation.

Select **Workflow Groups**, then **Create Workflow Group**.

Name the group — this guide uses `maintenance`.

Set the type to **No Type**.

Select the new group, choose **Edit Membership**, and add the users who should be called.

The group name is what you will put in the `groups` array of the API payload.
{% endstep %}

{% step %}

## Collect your Relay credentials

| Value           | Where to find it                                                                              |
| --------------- | --------------------------------------------------------------------------------------------- |
| `subscriber_id` | Relay Dash → **Help** → **Diagnostic Logs** → **Server Details**, listed under **Subscriber** |
| `apikey`        | Relay Dash → **Help** → [**API Keys**](https://dash.relaypro.com/api-keys) → create a key     |

{% hint style="warning" %}
Create a **dedicated API key for this integration** rather than reusing one. If the Telit org is ever compromised, or a contractor leaves with Developer access, you want to revoke one key without breaking every other integration you run.
{% endhint %}
{% endstep %}

{% step %}

## Prove the Relay side works

Fire the alert by hand first:

```sh
export subscriber_id=your_subscriber_id
export apikey=your_api_key

curl -X POST \
  -H "Authorization: RelayApiKey $apikey" \
  -H "Content-Type: application/json" \
  "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts" \
  -d '{"notification": "Test alert from deviceWISE integration", "groups": ["maintenance"]}' \
  -i
```

A successful call returns `HTTP/2 200`, and a task ID:

```json
{"task_id":"P9CThKfTsEbJx23trAArHCD"}
```

Devices in `maintenance` should now be speaking the message every 30 seconds. Tap the talk button on one to acknowledge, or cancel it from the terminal:

```sh
curl -X DELETE \
  -H "Authorization: RelayApiKey $apikey" \
  "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts/P9CThKfTsEbJx23trAArHCD"
```

{% hint style="success" %}
If this curl works and the Telit trigger does not, the problem is in the trigger — not in Relay.&#x20;
{% endhint %}
{% endstep %}

{% step %}

## Create the Cloud Trigger

In the deviceWISE Cloud portal, go to **Developer** → **Triggers** → **New Trigger**.

Enter the trigger metadata:

| Field           | Value                                                                    |
| --------------- | ------------------------------------------------------------------------ |
| **Name**        | `Machine down → Relay alert`                                             |
| **Description** | `Voice-alerts the maintenance group when a machine reports a down alarm` |
| **Tags**        | `relay`, `maintenance` (optional, but makes triggers findable at scale)  |
| {% endstep %}   |                                                                          |

{% step %}

## Configure the `alarm.change` event

Right-click the **Start** node on the canvas to open **Add trigger event**, set **Event type** to `alarm.change`, and fill in the form.

The [`alarm.change` event](https://docs.devicewise.com/Content/Products/Management_Portal/Developer/Triggers/Events/alarm.change-event.htm) fires whenever an alarm changes state.&#x20;

### Time in condition is important to configure

Manufacturing lines microstop constantly. Without debounce, a five-second jam pages four technicians, the alert repeats every 30 seconds, and within a week your maintenance team mutes their Relays.

**Time in condition** delays execution until the alarm has held the state for the specified number of seconds. The semantics are specific:

* If the alarm is republished at the **same** state during the window, the trigger still executes at the end of the window.
* If the alarm **changes** state during the window — the machine recovers — execution is **cancelled**.

Sixty seconds is a reasonable opening value for a production line. Tune it to your actual microstop distribution: long enough that self-clearing faults never page anyone, short enough that real downtime is not sitting unreported.

Click **Add**.
{% endstep %}

{% step %}

## Add the `http.client` action

Expand the **Networking** category in the trigger actions list, then click and drag [**http.client**](https://docs.devicewise.com/Content/Products/Management_Portal/Developer/Triggers/Actions/http.client-action.htm) onto the canvas.

<figure><img src="https://2387635908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FL7dimlztFKGWYQIaJ9DP%2Fuploads%2FwfW1EUDnjxqH3lDlsynK%2FScreenshot%202026-09-14%20at%2011.47.51%E2%80%AFAM.png?alt=media&amp;token=01e1d718-8d45-4a04-b92b-d04f1e3924da" alt=""><figcaption></figcaption></figure>

### Action parameters

| Parameter        | Value                                                                   |
| ---------------- | ----------------------------------------------------------------------- |
| **Method**       | `POST`                                                                  |
| **URL**          | `https://api.relaypro.com/subscribers/YOUR_SUBSCRIBER_ID/api/v1/alerts` |
| **Content type** | `application/json`                                                      |
| **Timeout**      | `30`                                                                    |
| **TLS cert**     | *(blank)*                                                               |
| **TLS key**      | *(blank)*                                                               |

Replace `YOUR_SUBSCRIBER_ID` with the subscriber ID from Step 2.

{% hint style="info" %}
**Timeout** is the deviceWISE HTTP request timeout, and it accepts **0–60 seconds** (default 30). It is unrelated to the Relay `timeout` key in the payload below, which controls how long the alert keeps sounding on devices.

The **TLS cert** and **TLS key** fields are for client-certificate authentication. Relay authenticates with an API key, so leave both empty.
{% endhint %}

### Headers

Add one header:

| Key             | Value                      |
| --------------- | -------------------------- |
| `Authorization` | `RelayApiKey YOUR_API_KEY` |

{% hint style="warning" %}
The literal string `RelayApiKey` and a space must precede the key. `Authorization: YOUR_API_KEY` returns 401.
{% endhint %}

### Body

Select **Body: Raw** and paste the following. Note that **Body: Raw takes precedence over Body: Form** — if you populate both, the form is ignored.

```json
{
  "notification": "Machine down. $(event.thing.name) has faulted. Please respond.",
  "groups": ["maintenance"],
  "quorum": 1,
  "on_ack": "Accepted. You are assigned to $(event.thing.name).",
  "on_quorum": "Another technician has taken this call.",
  "timeout": 600,
  "on_timeout": "Machine down call was not acknowledged.",
  "name": "machine-down"
}
```

Click **Add**.
{% endstep %}

{% step %}

## Wire the routes and activate

The `http.client` node has two routing points: **left/red is the failure route**, **right/green is the success route**.

Drag a route from the `alarm.change` event triangle to the `0.http.client` action.

Expand the **End** category and drag a **Success** node onto the canvas.

Drag the green success route from `0.http.client` to the Success node.

{% hint style="info" %}
A trigger needs **at least one Success route** before it will save. Any branch that does not terminate at a Success node is treated as a failure.

When connecting routes, drag over the destination node until it turns grey, then release.
{% endhint %}

Set **Reporting mode**. The default is **On failure**, which logs only failed executions. During rollout set it to **On** to capture every execution — note that **On** reverts to **On failure** automatically after 30 days.

Click **Add** to save the trigger.

Click **Start** to activate it. A saved trigger does nothing until it is started.

The Triggers list now shows a **Success count** and **Failure count** for the trigger. Those two numbers are your first diagnostic.
{% endstep %}
{% endstepper %}

***

## Payload reference

### Relay alert keys

`notification` and `groups` are required. Everything else is optional.

| Key            | Type          | Default                      | Behavior                                                                                         |
| -------------- | ------------- | ---------------------------- | ------------------------------------------------------------------------------------------------ |
| `notification` | string        | —                            | Spoken on every device in the group via text-to-speech.                                          |
| `groups`       | array         | —                            | Workflow Group names or URNs to alert.                                                           |
| `quorum`       | integer       | all devices must acknowledge | Cancels remaining alerts after this many acknowledgements. **Set this to `1` for machine-down.** |
| `on_ack`       | string        | nothing spoken               | Spoken on the device that acknowledged.                                                          |
| `on_quorum`    | string        | nothing spoken               | Spoken on devices that had not yet acknowledged once quorum is met.                              |
| `timeout`      | integer (sec) | `300`                        | Cancels remaining alerts after this long.                                                        |
| `on_timeout`   | string        | nothing spoken               | Spoken on devices that never acknowledged, after timeout.                                        |
| `name`         | string        | `alerts`                     | Controls serial/concurrent alerting behavior and appears in analytics events for correlation.    |

Leaving `quorum` at its default means the alert keeps sounding on every other device until **all** of them acknowledge — not needed for a machine-down call where one technician takes the job. Set `quorum: 1`.

### deviceWISE event variables available in the body

From the `alarm.change` event:

| Variable                    | Type    | Contents                                |
| --------------------------- | ------- | --------------------------------------- |
| `$(event.thing.key)`        | String  | Key of the Thing that fired the trigger |
| `$(event.thing.name)`       | String  | Human-readable name of the Thing        |
| `$(event.thing.type)`       | String  | Name of the Thing definition            |
| `$(event.alarm.key)`        | String  | Alarm key                               |
| `$(event.alarm.name)`       | String  | Alarm name                              |
| `$(event.alarm.msg)`        | String  | Alarm message                           |
| `$(event.alarm.state)`      | Integer | Numeric alarm state                     |
| `$(event.alarm.string)`     | String  | String form of the alarm state          |
| `$(event.alarm.ts)`         | String  | Alarm timestamp                         |
| `$(event.alarm.corrId)`     | String  | Correlation ID                          |
| `$(event.location.lat)`     | Float   | Latitude of the Thing                   |
| `$(event.location.lng)`     | Float   | Longitude of the Thing                  |
| `$(event.location.speed)`   | Integer | Speed of the Thing                      |
| `$(event.location.heading)` | Float   | Heading of the Thing                    |

Two global variables are available in any action: `$(trigger.exec_time)` and `$(time.now)`. On a failure route you also get `$(trigger.lastErrorMsg)` and `$(trigger.lastErrorCode)`.

{% hint style="warning" %}
**Write for text-to-speech, not for a log file.**

`$(event.thing.key)` is typically a machine-readable key like `press_07_lineB`. Spoken aloud, that is unintelligible. Use `$(event.thing.name)` in the `notification` string allows for more intellible TTS.&#x20;

For the same reason, avoid interpolating `$(event.alarm.msg)` into the spoken message unless you control what your gateway writes there. A message field containing an alarm code, a stack trace, or a double quote will produce either gibberish speech or — see the next warning — a 400.
{% endhint %}

{% hint style="danger" %}
**Variable substitution is textual, and the body is JSON.**

If an interpolated value contains a double quote, a backslash, or a newline, the substituted body is no longer valid JSON and Relay rejects the request with a 400. Values that originate in a PLC string tag or an operator-entered alarm message are the usual culprits.
{% endhint %}

***

For a full execution history, see Telit's [Viewing Trigger Report](https://docs.devicewise.com/Content/Products/Management_Portal/Developer/Triggers/Viewing-Trigger-Report.htm).

***

## Reference

### Telit deviceWISE Cloud

* [Cloud Trigger Events](https://docs.devicewise.com/Content/Products/Management_Portal/Developer/Triggers/Events/Cloud-Trigger-Events.htm)
* [`alarm.change` event](https://docs.devicewise.com/Content/Products/Management_Portal/Developer/Triggers/Events/alarm.change-event.htm)
* [Cloud Trigger Actions](https://docs.devicewise.com/Content/Products/Management_Portal/Developer/Triggers/Actions/Cloud-Trigger-Actions.htm)
* [`http.client` action](https://docs.devicewise.com/Content/Products/Management_Portal/Developer/Triggers/Actions/http.client-action.htm)
* [Adding a trigger](https://docs.devicewise.com/Content/Products/Management_Portal/Developer/Triggers/Adding-a-trigger.htm)
* [Scheduling a trigger](https://docs.devicewise.com/Content/Products/Management_Portal/Developer/Triggers/Scheduling-a-Trigger.htm)

### Relay

* [Alerts overview](https://developer.relaypro.com/docs/relay-alerts-api)
* [Triggering an Alert](https://developer.relaypro.com/docs/relay-alerts-api/triggering-an-alert)
* [Customizing Your Alerts](https://developer.relaypro.com/docs/relay-alerts-api/customizing-your-alerts)
* [Advanced Configuration](https://developer.relaypro.com/docs/relay-alerts-api/advanced-configuration)
* [Broadcasts](https://developer.relaypro.com/docs/relay-broadcasts-api)


# MaintainX Alerts

## Overview

[MaintainX](https://www.getmaintainx.com/) is a maintenance and work order platform. When something happens in MaintainX, such as a new high-priority work order, a job put on hold, or a work order going overdue, it can send a **webhook**: an HTTP `POST` to a URL you choose.

The [**maintainx-relay-bridge**](https://github.com/relaypro/maintainx-relay-bridge) template receives those webhooks and turns them into **Relay alerts and broadcasts**. Technicians hear the work order on their Relay device right away, and alerts keep repeating until someone acknowledges them.

```mermaid
flowchart LR
    MX[MaintainX] -- "signed webhook (POST)" --> B[maintainx-relay-bridge]
    B -- "verify signature,<br/>classify event" --> B
    B -- "Relay route:<br/>alert or broadcast" --> R[Relay API]
    R -- "text-to-speech" --> G1[Workflow Group A]
    R -- "text-to-speech" --> G2[Workflow Group B]
```

The bridge does four things:

1. **Verifies** each request really came from MaintainX by checking its HMAC signature.
2. **Classifies** the event: what happened and how urgent it is. For example, a high-priority work order is `urgent`, a medium-priority one is a `notice`, and a low-priority one is ignored.
3. **Hands it to a Relay route.** A route is defined on the Relay side. It says how the event is delivered (alert or broadcast) and which **Relay Workflow Groups** hear it. One route can reach several groups at once.
4. **Speaks** a short message on the devices through the Relay Alerts or Broadcasts API.

### Who hears it is a Relay decision

MaintainX knows *what* needs doing. Relay knows *who* is on shift, on the floor, and able to respond.&#x20;

* **MaintainX supplies the event:** what happened, its priority, and the details to speak.
* **Relay owns the audience:** routes and Workflow Groups are configured for Relay, not derived from MaintainX teams, locations, or categories.

{% hint style="warning" %}
Avoid routing on MaintainX assignment data (`teamIds`, `assigneeIds`, `locationId`, `categories`). It ties delivery to how work orders happen to be filled in, and bypasses what Relay knows about who is actually available.
{% endhint %}

{% hint style="info" %}
**Alerts vs. broadcasts.** An **alert** repeats on the device every 30 seconds until someone presses the talk button to acknowledge it, or until it times out. A **broadcast** plays once and needs no acknowledgement. Save alerts for work that needs someone to own it.
{% endhint %}

### Where to run it

The bridge is a small Node.js service with ready-to-use configuration for three hosts. Pick whichever fits your team:

<table><thead><tr><th width="140">Host</th><th>Good for</th><th>Included config</th></tr></thead><tbody><tr><td><strong>Replit</strong></td><td>Teams that want an all-in-one workspace: the code, an AI agent to customize it, secrets, and hosting in one place.</td><td><code>.replit</code></td></tr><tr><td><strong>Render</strong></td><td>One-click deploy from GitHub, with automatic redeploys when you push.</td><td><code>render.yaml</code></td></tr><tr><td><strong>Heroku</strong></td><td>Teams already on Heroku. One-click deploy that prompts for each setting.</td><td><code>app.json</code></td></tr></tbody></table>

The repo also includes a `Dockerfile`, so it runs anywhere that runs Node.js 20 or a container.

***

## Prerequisites

<table><thead><tr><th width="180">Side</th><th>Requirement</th></tr></thead><tbody><tr><td><strong>Relay</strong></td><td>A Relay account on the <strong>Enterprise</strong> plan (needed for API keys), access to <strong>Relay Dash</strong>, and at least one Relay device to test with.</td></tr><tr><td><strong>MaintainX</strong></td><td>Admin access to create webhooks (<strong>Settings → Integrations → Webhooks</strong>). <em>Optional:</em> a MaintainX API key to add work order titles and location names to alerts. MaintainX API access needs a Premium or Enterprise plan.</td></tr><tr><td><strong>Hosting</strong></td><td>An account on <a href="https://replit.com/">Replit</a>, <a href="https://render.com/">Render</a>, or <a href="https://www.heroku.com/">Heroku</a>. All three need a paid plan for an always-on service.</td></tr></tbody></table>

***

## Set up the bridge

{% stepper %}
{% step %}

## Create your Relay Workflow Groups

Alerts and broadcasts are sent to **Workflow Groups**. Create a group for each audience that should hear maintenance events.

1. In **Relay Dash**, open **Incidents** from the left menu.
2. Select **Workflow Groups** → **Create Workflow Group**.
3. Enter a name and select **No Type**.
4. Select the group, then use **Edit Membership** to add users.

A typical setup has a few groups that routes combine:

| Workflow Group | Who's in it                                    |
| -------------- | ---------------------------------------------- |
| `maintenance`  | Technicians on the floor                       |
| `supervisors`  | Supervisors who need to know about urgent work |
| `safety`       | Safety team, for escalations                   |
| {% endstep %}  |                                                |

{% step %}

## Collect your Relay credentials

| Value             | Where to find it                                                                  |
| ----------------- | --------------------------------------------------------------------------------- |
| **API key**       | Relay Dash → **Help** → **API Keys**                                              |
| **Subscriber ID** | Relay Dash → **Help** → **Diagnostic Logs** → **Server Details** → **Subscriber** |

Before deploying anything, check them with a broadcast:

```sh
export RELAY_SUBSCRIBER_ID=your-subscriber-id
export RELAY_API_KEY=your-api-key

curl -X POST "https://api.relaypro.com/subscribers/$RELAY_SUBSCRIBER_ID/api/v1/broadcasts" \
  -H "Authorization: RelayApiKey $RELAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"notification": "MaintainX integration test.", "groups": ["maintenance"]}'
```

If the devices in that group speak the message, you're ready.

{% hint style="warning" %}
The `Authorization` header must include the literal prefix `RelayApiKey`, followed by a space and then your key.
{% endhint %}
{% endstep %}

{% step %}

## Define your Relay routes

A route names a delivery mode and the Workflow Groups it reaches. The bridge ships with two routes, `urgent` and `notice`. Decide which groups each one should reach. In this example, urgent work goes to technicians and shift leads together, and the first person to acknowledge it takes it for everyone:

```json
{
  "urgent": {
    "mode": "alert",
    "groups": ["maintenance", "supervisors"],
    "timeout": 300,
    "quorum": 1,
    "on_quorum": "Someone else has this work order."
  },
  "notice": {
    "mode": "broadcast",
    "groups": ["maintenance"]
  }
}
```

You'll paste this, as a single line, into the `RELAY_ROUTES` setting in the next step. Group names must match your Workflow Groups exactly. If you leave `RELAY_ROUTES` unset, both routes go to `maintenance`.
{% endstep %}

{% step %}

## Deploy the bridge

Every option prompts for the same settings:

| Setting                    | Required | Value                                                                                             |
| -------------------------- | -------- | ------------------------------------------------------------------------------------------------- |
| `RELAY_API_KEY`            | Yes      | From step 2                                                                                       |
| `RELAY_SUBSCRIBER_ID`      | Yes      | From step 2                                                                                       |
| `MAINTAINX_WEBHOOK_SECRET` | Yes      | Enter `placeholder` for now. You'll get the real value in step 5.                                 |
| `RELAY_ROUTES`             | No       | Your routes from step 3, as one line of JSON                                                      |
| `MAINTAINX_API_KEY`        | No       | MaintainX **Settings → Integrations → API Keys**. Adds titles and locations to spoken alerts.     |
| `DRY_RUN`                  | No       | Leave at `true` while testing. The bridge logs what it would send to Relay instead of sending it. |

{% tabs %}
{% tab title="Replit" %}

1. Open [**replit.com/github.com/relaypro/maintainx-relay-bridge**](https://replit.com/github.com/relaypro/maintainx-relay-bridge), or go to [replit.com/import](https://replit.com/import), choose **GitHub**, and select the repo. Replit installs dependencies and reads the run command from `.replit`.
2. Open **Secrets** and add each setting from the table above.
3. Select **Publish**. The repo's `.replit` selects a **Reserved VM**, which stays on to receive webhooks. You can switch to **Autoscale**, which costs less but adds a short cold start after idle periods.
4. Once it's published, copy the app's URL, e.g. `https://maintainx-relay-bridge.replit.app`.

{% hint style="success" %}
**Customize with Replit Agent.** After importing, you can ask Agent to change the bridge in plain language, for example: *"Add a `critical` route and send `WORK_ORDER_OVERDUE` events to it."* See [Customizing](#customizing) for the rules to give it.
{% endhint %}
{% endtab %}

{% tab title="Render" %}

1. Select **Deploy to Render**:

   [![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/relaypro/maintainx-relay-bridge)

   Render reads `render.yaml` and sets up a **Blueprint** with a Node web service, `npm ci` / `npm start`, and a health check on `/health`.
2. Enter a value for each setting from the table above when prompted.
3. Select **Deploy Blueprint**.
4. Once the service is live, copy its URL, e.g. `https://maintainx-relay-bridge.onrender.com`.

To fork the repo first and deploy from your fork, go to **New → Blueprint** in the Render Dashboard and connect your fork instead. Render then redeploys every time you push.

{% hint style="warning" %}
`render.yaml` uses the **Starter** instance type. Render's free instances sleep when idle, and a webhook that wakes one can take longer than the 10 seconds MaintainX waits.
{% endhint %}
{% endtab %}

{% tab title="Heroku" %}

1. Select **Deploy to Heroku**:

   [![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/relaypro/maintainx-relay-bridge)

   Heroku reads `app.json` and shows a form with every setting. It pre-fills `RELAY_ROUTES` with the defaults and sets `DRY_RUN` to `true`.
2. Choose an app name and region, fill in the settings from the table above, and select **Deploy app**.
3. When the build finishes, select **View** and copy the URL, e.g. `https://maintainx-relay-bridge.herokuapp.com`. Newer Heroku apps add a random suffix to the hostname, so copy it exactly.

Heroku detects Node.js from `package.json` and runs `npm start`. No `Procfile` is needed.
{% endtab %}
{% endtabs %}

Open `https://<your-host>/health`. It should return `{"ok":true}`. Your webhook URL is:

```
https://<your-host>/webhooks/maintainx
```

{% endstep %}

{% step %}

## Register the webhook in MaintainX

1. In MaintainX, go to **Settings → Integrations → Webhooks** and select **+ New Webhook**.
2. In **Trigger Webhook On**, choose an event, such as **New Work Order**.
3. In **Endpoint**, paste your webhook URL and save.
4. Select **Copy secret**, then replace `placeholder` in `MAINTAINX_WEBHOOK_SECRET` with it:

| Host       | Where to update it                                                        |
| ---------- | ------------------------------------------------------------------------- |
| **Replit** | **Secrets**, then **Publish** again so the deployment picks up the change |
| **Render** | Service → **Environment**. Saving redeploys the service.                  |
| **Heroku** | App → **Settings** → **Reveal Config Vars**. Saving restarts the app.     |

{% hint style="info" %}
Each MaintainX webhook has **its own secret**, and the bridge accepts one. To handle several events, such as **New Work Order**, **Work Order Status Change**, and **Work Order Overdue**, deploy one bridge per event or extend `verifySignature` in `src/bridge.js` to accept a list of secrets.
{% endhint %}

You can also create webhooks through the MaintainX REST API (`POST https://api.getmaintainx.com/v1/subscriptions`), which can filter server-side. For example, this subscription fires only when a work order moves to `ON_HOLD`:

```json
{
  "type": "WORK_ORDER_STATUS_CHANGE",
  "url": "https://<your-host>/webhooks/maintainx",
  "filters": { "oneOfStatuses": ["ON_HOLD"] }
}
```

Get the secret with `GET /v1/subscriptions/{id}/secret`.
{% endstep %}

{% step %}

## Test end to end and go live

**1. Send a signed test event.** With `DRY_RUN` still `true`, clone the repo and run its test script against your deployment, using the same secret:

```sh
git clone https://github.com/relaypro/maintainx-relay-bridge && cd maintainx-relay-bridge && npm install

MAINTAINX_WEBHOOK_SECRET=your-secret \
WEBHOOK_URL=https://<your-host>/webhooks/maintainx \
npm run test:webhook            # or: npm run test:webhook -- on-hold | overdue
```

You should see `HTTP 200 {"status":"sent","route":"urgent"}`. The host's logs should show the Relay request it would have sent, with every group on the `urgent` route:

| Host       | Logs                     |
| ---------- | ------------------------ |
| **Replit** | Publishing → **Logs**    |
| **Render** | Service → **Logs**       |
| **Heroku** | **More** → **View logs** |

If you change the secret, you'll get `401` instead.

**2. Go live.** Set `DRY_RUN` to `false` and redeploy or restart. Then create a **High** priority work order in MaintainX. Devices in every group on the `urgent` route should speak the alert. Press the talk button to acknowledge it, and the alert stops repeating.
{% endstep %}
{% endstepper %}

***

## Customizing

Routing has two layers, and each one changes in its own place:

* **Relay routes** (`RELAY_ROUTES`) decide who hears an event and how. Change them in your host's settings, the same way you updated the secret in step 5. No code change is needed.
* **Event rules** (the **Event rules** section of [`src/bridge.js`](https://github.com/relaypro/maintainx-relay-bridge/blob/main/src/bridge.js)) decide which route an event belongs to, based only on what happened:

```js
const PRIORITY_ROUTE = { HIGH: "urgent", MEDIUM: "notice", LOW: null, NONE: null };
const STATUS_ROUTE = { ON_HOLD: "notice", DONE: null, OPEN: null, IN_PROGRESS: null };
// WORK_ORDER_OVERDUE -> "urgent"
```

| What you want                                                | Change                                                                                                             |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
| Urgent work also reaches the safety team                     | Add `"safety"` to `RELAY_ROUTES.urgent.groups`                                                                     |
| Shift leads hear notices too                                 | Add `"supervisors"` to `RELAY_ROUTES.notice.groups`                                                                |
| First responder takes it, across all groups                  | `"quorum": 1` on the route                                                                                         |
| Add a third tier, such as `critical` for overdue work        | Add a `critical` route to `RELAY_ROUTES`, then return `route: "critical"` for `WORK_ORDER_OVERDUE` in `classify()` |
| Medium-priority work orders should also need acknowledgement | `PRIORITY_ROUTE.MEDIUM = "urgent"`                                                                                 |
| Announce completed work                                      | `STATUS_ROUTE.DONE = "notice"`                                                                                     |
| Handle another event                                         | Add a `case` to `classify()`. Asset events such as `ASSET_STATUS_CHANGE` work the same way.                        |
| Change what's spoken                                         | Edit the `text:` templates in `classify()`. Keep them short, because they're read aloud.                           |

Code changes deploy the usual way for your host. On Replit, edit in the workspace and **Publish** again. On Render and Heroku, push to the connected GitHub repo, or redeploy from the dashboard.

{% hint style="info" %}
**Working with an AI agent?** Replit Agent, Claude Code, Cursor, and similar tools all work well on this repo. Give them the rule that matters most: *event rules return a route name, never a group.* Run `npm test` afterwards. The tests include a check that MaintainX assignment data doesn't change the audience.
{% endhint %}

{% hint style="success" %}
**Write for the ear.** Lead with what happened and where: "High priority work order: compressor 3 leaking oil, building B." Avoid IDs, URLs, and abbreviations that text-to-speech reads badly. The bridge cuts messages off at 600 characters.
{% endhint %}

### Alert route options

| Field        | Default                                | Behavior                                                                                                         |
| ------------ | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `timeout`    | `300`                                  | Seconds before unacknowledged alerts are cancelled                                                               |
| `on_ack`     | "Thanks, work order acknowledged."     | Spoken on the device that acknowledged                                                                           |
| `quorum`     | all devices                            | Number of acknowledgements needed to cancel the alert for everyone else. Use `1` for "first responder takes it". |
| `on_quorum`  | silent                                 | Spoken on the remaining devices once the quorum is met                                                           |
| `on_timeout` | "No one acknowledged this work order." | Spoken on unacknowledged devices when the timeout hits                                                           |

The bridge sets the Relay `name` field to `maintainx-<route>`, so analytics show which route fired. See [Customizing Your Alerts](https://developer.relaypro.com/docs/relay-alerts-api/customizing-your-alerts) for details.

***

## Payload reference

These are the fields you'll most often use for classification and spoken text. Assignment fields such as `teamIds` and `locationId` are listed for completeness. Use them in the spoken message, not to pick an audience. Every MaintainX webhook includes `eventType`, so a single endpoint can handle every event type.

### `NEW_WORK_ORDER`

| Field                                  | Type          | Notes                                                                 |
| -------------------------------------- | ------------- | --------------------------------------------------------------------- |
| `eventType`                            | string        | `"NEW_WORK_ORDER"`                                                    |
| `workOrderId`                          | number        | Global work order ID                                                  |
| `orgId`                                | number        | MaintainX organization                                                |
| `occurredAt`                           | ISO date-time | When the event happened                                               |
| `userId`                               | number        | Who created it. **Absent** when an automation or schedule created it. |
| `newWorkOrder.title`                   | string        |                                                                       |
| `newWorkOrder.priority`                | string        | `NONE`, `LOW`, `MEDIUM`, `HIGH`                                       |
| `newWorkOrder.dueDate`                 | ISO date-time |                                                                       |
| `newWorkOrder.locationId` / `assetId`  | number        | Look up names via `GET /v1/locations/{id}` and `GET /v1/assets/{id}`  |
| `newWorkOrder.teamIds` / `assigneeIds` | number\[]     | Assignment in MaintainX                                               |
| `newWorkOrder.categories`              | object\[]     | `{ id, name }`                                                        |

### `WORK_ORDER_STATUS_CHANGE`

Has the same identifiers and `newWorkOrder` object, plus `oldStatus`, `newStatus` (`OPEN`, `IN_PROGRESS`, `ON_HOLD`, `DONE`), and optionally `oldSubStatus` / `newSubStatus` (`CANCELED`, `SKIPPED`).

### `WORK_ORDER_OVERDUE`

Has only `eventType`, `workOrderId`, `orgId`, `dueDate`, and `occurredAt`. To speak a title or location, the bridge looks the work order up with `MAINTAINX_API_KEY`.

For the full event catalog, see the MaintainX API reference under **Subscriptions & Webhooks**.

***

## Security notes

{% hint style="danger" %}
**Always verify the signature.** The webhook URL is public. Without verification, anyone who finds it can make your devices speak.
{% endhint %}

* **Reject stale timestamps.** The bridge accepts signatures within 5 minutes, as MaintainX recommends, which blocks replay attacks.
* **Keep secrets in your host's secret store** (Replit Secrets, Render Environment, Heroku Config Vars), not in code, in the repo, or in chats with an AI agent.
* **Answer quickly.** MaintainX times out after 10 seconds and may delete a webhook that keeps failing, emailing your account when it does. The bridge caps outbound calls at 5 seconds and always replies `200` once the signature checks out.

***

## Troubleshooting

| Symptom                                                   | Likely cause                                                                                                                                |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| App won't start: `Missing required environment variables` | A required setting is empty. `RELAY_API_KEY` is optional only while `DRY_RUN=true`.                                                         |
| App won't start: `RELAY_ROUTES.<name> needs…`             | A route is missing `groups`, has an empty list, or has a `mode` other than `alert` or `broadcast`. Also check that the JSON is on one line. |
| `401 invalid signature` on real events                    | `MAINTAINX_WEBHOOK_SECRET` is still `placeholder`, belongs to a different webhook, or wasn't picked up (republish on Replit)                |
| MaintainX deliveries time out                             | The instance is asleep. Use Replit Reserved VM, Render Starter or higher, or an always-on Heroku dyno.                                      |
| `{"status":"ignored"}`                                    | Your event rules intentionally skipped the event, e.g. a low-priority work order                                                            |
| `{"status":"no_route"}`                                   | An event rule returned a route name that isn't in `RELAY_ROUTES`                                                                            |
| `relay_error` with HTTP `401` in logs                     | Wrong Relay API key                                                                                                                         |
| `relay_error` with HTTP `404`                             | Wrong subscriber ID                                                                                                                         |
| Relay accepts the request but no device speaks            | A group name in the route doesn't match a Workflow Group exactly, or the group has no members                                               |
| Alerts arrive twice                                       | Two webhooks are subscribed to the same event, or the bridge runs on several instances (duplicates are tracked per instance)                |
| Overdue alerts say "number 12345"                         | `MAINTAINX_API_KEY` isn't set, or the plan doesn't include API access                                                                       |

***

## Going further

* **Write acknowledgements back to MaintainX.** Use the [Relay Events API](https://developer.relaypro.com/docs/relay-events-api) to see who acknowledged, then post a comment on the work order through the MaintainX API.

## Reference

### Template

* [maintainx-relay-bridge on GitHub](https://github.com/relaypro/maintainx-relay-bridge)

### Relay

* [Triggering an Alert](https://developer.relaypro.com/docs/relay-alerts-api/triggering-an-alert)
* [Customizing Your Alerts](https://developer.relaypro.com/docs/relay-alerts-api/customizing-your-alerts)
* [Advanced Configuration](https://developer.relaypro.com/docs/relay-alerts-api/advanced-configuration)
* [Broadcasts](https://developer.relaypro.com/docs/relay-broadcasts-api)

### MaintainX

* [Webhooks guide](https://help.getmaintainx.com/build/webhooks)
* [REST API reference](https://api.getmaintainx.com/v1/docs)

### Hosting

* Replit: [Import from GitHub](https://docs.replit.com/build/import-from-providers) · [Secrets](https://docs.replit.com/core-concepts/project-editor/app-setup/secrets) · [Deployment types](https://docs.replit.com/features/publishing/deployment-types)
* Render: [Blueprints](https://render.com/docs/infrastructure-as-code) · [Environment variables](https://render.com/docs/configure-environment-variables)
* Heroku: [Heroku Button](https://devcenter.heroku.com/articles/heroku-button) · [Config Vars](https://devcenter.heroku.com/articles/config-vars) · [Deploying Node.js](https://devcenter.heroku.com/articles/deploying-nodejs)


# ServiceNow Alerts

## Overview

[ServiceNow](https://www.servicenow.com/) is an IT service management platform that tracks work as records on tables. Its **Business Rules** engine runs server-side JavaScript whenever a record is inserted or updated. Business Rules can make outbound REST calls with the built-in `sn_ws.RESTMessageV2` API, so a ServiceNow instance can call any publicly reachable HTTPS endpoint.

That is all you need to turn a critical ticket into a voice alert in a technician's hand: ServiceNow detects the priority change, posts to the [Relay Alerts API](https://developer.relaypro.com/docs/relay-alerts-api), and every device in the target Workflow Group speaks the message until someone taps the talk button to accept the job.

This page builds a complete, working **critical incident** alert.

```mermaid
flowchart LR
    A["Incident<br/>Priority = 1 - Critical"] --> C["ServiceNow<br/>Business Rule<br/>after insert/update, async"]
    C --> E["RESTMessageV2<br/>POST /alerts"]
    E --> F["Relay devices<br/>in Workflow Group"]
    F --> G["Acknowledged"]
```

### Why Alerts and not Broadcasts

Relay offers two notification types. Use **Alerts** for critical incidents. An alert repeats every 30 seconds until a human acknowledges it, and it records who accepted the job, which is the accountability an urgent ticket needs. A [broadcast](https://developer.relaypro.com/docs/relay-broadcasts-api) plays once with no acknowledgement. That is fine for shift announcements, but generally the wrong approach for a critical ticket.

### Why a Business Rule and not Flow Designer

ServiceNow's Flow Designer can also call REST endpoints, but its **REST step** is part of the **Integration Hub** spoke, which requires an Integration Hub subscription and is not installed on every instance. A Business Rule works on every ServiceNow instance with no additional licensing, so this guide uses one. If your organization already has Integration Hub, you can build the equivalent flow with the same endpoint, header, and JSON body shown below.

***

## Prerequisites

<table><thead><tr><th width="180">Side</th><th>Requirement</th></tr></thead><tbody><tr><td>Relay</td><td>An <strong>enterprise plan</strong> account. API keys are not available on lower tiers.</td></tr><tr><td>Relay</td><td>A <strong>Workflow Group</strong> containing the users who should receive critical incident calls.</td></tr><tr><td>Relay</td><td>Your <strong>subscriber ID</strong> and an <strong>API key</strong>.</td></tr><tr><td>ServiceNow</td><td>An instance where you have the <strong>admin</strong> role (a <a href="https://developer.servicenow.com/">Personal Developer Instance</a> works for trying this out). This guide was verified on the <strong>Brazil</strong> release.</td></tr><tr><td>ServiceNow</td><td>Outbound HTTPS access from the instance to <code>api.relaypro.com</code>. Hosted instances allow this by default; self-hosted or restricted instances may need an egress rule.</td></tr></tbody></table>

***

{% stepper %}
{% step %}

## Create the Relay Workflow Group

In [Relay Dash](https://dash.relaypro.com/), open **Incidents** in the left-hand navigation.

Select **Workflow Groups**, then **Create Workflow Group**.

Name the group. This guide uses `maintenance`.

Set the type to **No Type**.

Select the new group, choose **Edit Membership**, and add the users who should be called.

The group name is what ServiceNow will send in the `groups` array of the API payload.
{% endstep %}

{% step %}

## Collect your Relay credentials

| Value           | Where to find it                                                                              |
| --------------- | --------------------------------------------------------------------------------------------- |
| `subscriber_id` | Relay Dash → **Help** → **Diagnostic Logs** → **Server Details**, listed under **Subscriber** |
| `apikey`        | Relay Dash → **Help** → [**API Keys**](https://dash.relaypro.com/api-keys) → create a key     |

{% hint style="warning" %}
Create a **dedicated API key for this integration** rather than reusing one. If the ServiceNow instance is ever compromised, or an admin leaves with access, you want to revoke one key without breaking every other integration you run.
{% endhint %}
{% endstep %}

{% step %}

## Prove the Relay side works

Fire the alert by hand first:

```sh
export subscriber_id=your_subscriber_id
export apikey=your_api_key

curl -X POST \
  -H "Authorization: RelayApiKey $apikey" \
  -H "Content-Type: application/json" \
  "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts" \
  -d '{"notification": "Test alert from ServiceNow integration", "groups": ["maintenance"]}' \
  -i
```

A successful call returns `HTTP/2 200` and a task ID:

```json
{"task_id":"P9CThKfTsEbJx23trAArHCD"}
```

Devices in `maintenance` should now be speaking the message every 30 seconds. Tap the talk button on one to acknowledge, or cancel it from the terminal:

```sh
curl -X DELETE \
  -H "Authorization: RelayApiKey $apikey" \
  "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts/P9CThKfTsEbJx23trAArHCD"
```

{% hint style="success" %}
If this curl works and the ServiceNow rule does not, the problem is in the rule, not in Relay.
{% endhint %}
{% endstep %}

{% step %}

## Store the credentials as System Properties

Keep the subscriber ID, API key, and group name out of the script by storing them as system properties.

In ServiceNow, type `sys_properties.list` into the navigator filter and press Enter, then select **New** for each of the following:

| Name                  | Type        | Value                                              |
| --------------------- | ----------- | -------------------------------------------------- |
| `relay.subscriber_id` | `string`    | Your subscriber ID from Step 2                     |
| `relay.api_key`       | `password2` | Your API key from Step 2                           |
| `relay.group`         | `string`    | The Workflow Group name, for example `maintenance` |

Leave **Application** as **Global** and select **Submit** on each.

{% hint style="info" %}
Setting the type to **`password2`** stores the API key encrypted, so it is not readable in the property list. The script reads it with `gs.getProperty()` like any other property.
{% endhint %}

If `relay.group` is missing, the script falls back to a group named `maintenance`.
{% endstep %}

{% step %}

## Create the Business Rule

Type `sys_script.list` into the navigator filter, press Enter, and select **New**. Fill in the form as follows.

| Field        | Value                                |
| ------------ | ------------------------------------ |
| **Name**     | `Relay - Alert on Critical Incident` |
| **Table**    | `Incident [incident]`                |
| **Active**   | Checked                              |
| **Advanced** | Checked                              |

On the **When to run** tab:

| Field      | Value   |
| ---------- | ------- |
| **When**   | `async` |
| **Order**  | `100`   |
| **Insert** | Checked |
| **Update** | Checked |

On the **Advanced** tab, set **Condition** to:

```javascript
current.priority.changesTo(1)
```

Then replace the contents of the **Script** field with:

```javascript
(function executeRule(current, previous /*null when async*/ ) {

    var subscriberId = gs.getProperty('relay.subscriber_id');
    var apiKey = gs.getProperty('relay.api_key');
    var group = gs.getProperty('relay.group', 'maintenance');

    var num = current.getValue('number');
    var desc = (current.getValue('short_description') || '').replace(/[^A-Za-z0-9 .,'-]/g, ' ');

    var payload = {
        notification: 'Critical incident ' + num + '. ' + desc + '. Please respond.',
        groups: [group],
        quorum: 1,
        timeout: 600,
        name: 'servicenow-incident',
        on_ack: 'Accepted. You are assigned to ' + num + '.',
        on_quorum: 'Another technician has taken this call.',
        on_timeout: 'Critical incident ' + num + ' was not acknowledged.'
    };

    var req = new sn_ws.RESTMessageV2();
    req.setEndpoint('https://api.relaypro.com/subscribers/' + subscriberId + '/api/v1/alerts');
    req.setHttpMethod('POST');
    req.setRequestHeader('Authorization', 'RelayApiKey ' + apiKey);
    req.setRequestHeader('Content-Type', 'application/json');
    req.setRequestBody(JSON.stringify(payload));

    try {
        var res = req.execute();
        var code = res.getStatusCode();
        if (code === 200) {
            gs.info('Relay alert sent for ' + num + ', task_id=' + JSON.parse(res.getBody()).task_id);
        } else {
            gs.error('Relay alert failed for ' + num + ': HTTP ' + code + ' ' + res.getBody());
        }
    } catch (e) {
        gs.error('Relay alert exception for ' + num + ': ' + e.message);
    }

})(current, previous);
```

Select **Submit** to save the rule.

{% hint style="info" %}
**Why `async`?** An async rule runs in the background shortly after the record is saved, so a slow or failed call to Relay never delays or blocks the person saving the ticket. A `before` or `after` rule would hold the form until the HTTP call finished.
{% endhint %}

{% hint style="warning" %}
The literal string `RelayApiKey` and a space must precede the key. `Authorization: YOUR_API_KEY` returns 401.
{% endhint %}
{% endstep %}

{% step %}

## Test it end to end

Create a test incident (type `incident.do` into the navigator filter, or use **Incident → Create New**):

1. Set a **Caller** and a **Short description** such as `Press 7 on Line B is down`.
2. Set **Impact** to `1 - High` and **Urgency** to `1 - High`. **Priority** recalculates to `1 - Critical`.
3. Select **Submit**.

Within a few seconds a device in your Workflow Group should speak:

> Critical incident INC0010001. Press 7 on Line B is down. Please respond.

Tap the talk button to acknowledge. The device that accepts hears *Accepted. You are assigned to INC0010001.* and the other devices in the group stop alerting.

To confirm from the ServiceNow side, open **System Logs → System Log → All** and filter **Message** contains `Relay alert`. A successful call logs:

```
Relay alert sent for INC0010001, task_id=Q55jJRTWi3zPYtcFAaI5cD
```

{% hint style="success" %}
The `task_id` in the log is the same ID the Relay API returned. Use it to cancel the alert with the `DELETE` call from Step 3, or to correlate with analytics events (see [Advanced Configuration](https://developer.relaypro.com/docs/relay-alerts-api/advanced-configuration)).
{% endhint %}
{% endstep %}
{% endstepper %}

***

## How the trigger works

The **Condition** `current.priority.changesTo(1)` is true when an incident is **inserted with Priority 1** or **updated so that Priority becomes 1**. It does not fire on later edits to a ticket that is already Priority 1, so adding a comment or reassigning the ticket will not page the group again.

Two behaviors to be aware of:

* If a ticket moves from Priority 1 to another priority and later back to Priority 1, the rule fires again and a new alert is sent.
* Priority is normally calculated from **Impact** and **Urgency**. Changing either field can move Priority to 1 and trigger the rule.

### Changing what counts as urgent

Edit the **Condition** on the Business Rule. Some common variations:

| Goal                                            | Condition                                                                        |
| ----------------------------------------------- | -------------------------------------------------------------------------------- |
| Priority 1 or 2                                 | `current.priority.changesTo(1) \|\| current.priority.changesTo(2)`               |
| High urgency, regardless of priority            | `current.urgency.changesTo(1)`                                                   |
| Priority 1 only for a specific assignment group | `current.priority.changesTo(1) && current.assignment_group.name == 'Facilities'` |

To route different tickets to different Relay groups, replace the `group` variable in the script with a value computed from the record, for example from `current.getValue('category')`. The value must match a Workflow Group name (or URN) in Relay Dash.

***

## Payload reference

### Relay alert keys

`notification` and `groups` are required. Everything else is optional.

| Key            | Type          | Default                      | Behavior                                                                                           |
| -------------- | ------------- | ---------------------------- | -------------------------------------------------------------------------------------------------- |
| `notification` | string        | —                            | Spoken on every device in the group via text-to-speech.                                            |
| `groups`       | array         | —                            | Workflow Group names or URNs to alert.                                                             |
| `quorum`       | integer       | all devices must acknowledge | Cancels remaining alerts after this many acknowledgements. **Set this to `1` for incident calls.** |
| `on_ack`       | string        | nothing spoken               | Spoken on the device that acknowledged.                                                            |
| `on_quorum`    | string        | nothing spoken               | Spoken on devices that had not yet acknowledged once quorum is met.                                |
| `timeout`      | integer (sec) | `300`                        | Cancels remaining alerts after this long.                                                          |
| `on_timeout`   | string        | nothing spoken               | Spoken on devices that never acknowledged, after timeout.                                          |
| `name`         | string        | `alerts`                     | Controls serial/concurrent alerting behavior and appears in analytics events for correlation.      |

Leaving `quorum` at its default means the alert keeps sounding on every other device until **all** of them acknowledge. That is not what you want for an incident call where one technician takes the job. Set `quorum: 1`.

### ServiceNow fields used in the message

The script reads these fields from the incident (`current`):

| Field                                   | Used for                                       |
| --------------------------------------- | ---------------------------------------------- |
| `current.getValue('number')`            | Spoken ticket number, for example `INC0010001` |
| `current.getValue('short_description')` | Spoken problem summary                         |

Other fields you can read the same way include `priority`, `category`, `location`, `cmdb_ci`, and `assignment_group`. For reference fields such as `location`, use `current.location.getDisplayValue()` to get the human-readable name rather than the record's `sys_id`.

{% hint style="warning" %}
**Write for text-to-speech, not for a log file.**

Use display names, not `sys_id` values or machine keys. A `sys_id` spoken aloud is 32 characters of noise.

Free-text fields such as `short_description` and `description` are typed by people and can contain codes, URLs, and punctuation that sound like gibberish when spoken. The script above replaces everything except letters, digits, spaces, and `. , ' -` with a space. Keep spoken messages to a sentence or two. Do not interpolate `description` or work notes.
{% endhint %}

{% hint style="info" %}
The script builds the request body with `JSON.stringify()`, so a double quote, backslash, or newline in a ticket field cannot produce invalid JSON. If you adapt this to build the body by string concatenation instead, those characters will cause Relay to reject the request with a 400.
{% endhint %}

***

## Troubleshooting

Start with the log: **System Logs → System Log → All**, filter **Message** contains `Relay alert`. Every run of the rule writes exactly one line.

| Symptom                                              | Likely cause and fix                                                                                                                                                                                                                 |
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| No `Relay alert` line in the log at all              | The rule did not run. Check that it is **Active**, that **Insert** and **Update** are checked, and that the incident's Priority actually changed to `1 - Critical` in this save. A ticket that was already Priority 1 will not fire. |
| `HTTP 401`                                           | The `Authorization` header is wrong. It must be `RelayApiKey <key>` with a space. Also confirm the key was copied completely and has not been revoked.                                                                               |
| `HTTP 400`                                           | The request body was rejected. If you changed the script to build JSON by hand, check for unescaped quotes or newlines in interpolated values.                                                                                       |
| `HTTP 404`                                           | The subscriber ID in `relay.subscriber_id` is wrong or has stray whitespace.                                                                                                                                                         |
| `Relay alert exception ...`                          | The call never reached Relay (DNS, firewall, or timeout). Confirm the instance can reach `api.relaypro.com` over HTTPS.                                                                                                              |
| Log says `sent`, but no device speaks                | The alert was accepted, so check the Relay side. The `relay.group` value must exactly match a Workflow Group name, and that group must have members whose devices are online.                                                        |
| The alert keeps repeating after someone started work | Alerts repeat every 30 seconds until acknowledged on a device or until `timeout`. Acknowledge on the device, or cancel with the `DELETE` call in Step 3.                                                                             |

{% hint style="success" %}
If the curl command in Step 3 works but the rule does not, the problem is in ServiceNow, not in Relay.
{% endhint %}

***

## Reference

### ServiceNow

* [Business rules](https://www.servicenow.com/docs/r/platform-administration/business-rules.html)
* [RESTMessageV2 API](https://developer.servicenow.com/dev.do#!/reference/api/latest/server/sn_ws-namespace/c_RESTMessageV2API)
* [Flow Designer REST step (requires Integration Hub)](https://www.servicenow.com/docs/r/build-workflows/workflow-studio/rest-request-action-designer.html)

### Relay

* [Alerts overview](https://developer.relaypro.com/docs/relay-alerts-api)
* [Triggering an Alert](https://developer.relaypro.com/docs/relay-alerts-api/triggering-an-alert)
* [Customizing Your Alerts](https://developer.relaypro.com/docs/relay-alerts-api/customizing-your-alerts)
* [Advanced Configuration](https://developer.relaypro.com/docs/relay-alerts-api/advanced-configuration)
* [Broadcasts](https://developer.relaypro.com/docs/relay-broadcasts-api)


# Mitti (SafetyCulture) Alerts

## Overview

[Mitti](https://mitti.com/) (formerly SafetyCulture) is a frontline operations platform used for inspections, issue reporting, and corrective actions. When a food safety problem is reported as an **Issue** in Mitti, you want the right people to hear about it immediately, wherever they are standing.

Mitti's [webhooks](https://developer.mitti.com/reference/webhooks) send an HTTP POST to a URL you choose whenever an event happens in your organization, including when an Issue is created. This page connects that event to the [Relay Alerts API](https://developer.relaypro.com/docs/relay-alerts-api): a food safety Issue is created in Mitti, a small receiver you host checks it, and every device in the target Workflow Group speaks the message until someone taps the talk button to accept the job.

This page builds a complete, working **food safety alert**.

```mermaid
flowchart LR
    A["Mitti<br/>Issue created<br/>category: Food safety"] --> B["Mitti webhook<br/>POST to your URL"]
    B --> C["Receiver<br/>verify signature<br/>fetch issue<br/>filter + de-duplicate"]
    C --> D["Relay Alerts API<br/>POST /alerts"]
    D --> E["Relay devices<br/>in Workflow Group"]
    E --> F["Acknowledged"]
```

### Why Alerts and not Broadcasts

Relay offers two notification types. Use **Alerts** for food safety. An alert repeats every 30 seconds until a human acknowledges it, and it records who accepted the job, which is the accountability a food safety response needs. A [broadcast](https://developer.relaypro.com/docs/relay-broadcasts-api) plays once with no acknowledgement. That is fine for shift announcements, but wrong for a cooler failure.

### Why a receiver sits in the middle

Unlike many integrations, Mitti cannot call Relay directly. A Mitti webhook registration takes only a list of events and a destination URL. It cannot add a custom `Authorization` header or reshape the body, and Relay requires both. Mitti's payloads are also deliberately small, so details such as the issue title, category, and site must be fetched from the Mitti API.

The receiver in this guide is a small piece of JavaScript with a thin adapter for **Azure Functions**, **AWS Lambda**, or **Cloudflare Workers**. It does four jobs:

1. **Verifies** that the request really came from Mitti, using the HMAC signature Mitti attaches to every webhook.
2. **Fetches the issue** from the Mitti API and checks that it is a food safety issue.
3. **De-duplicates**, because Mitti retries failed deliveries and may deliver the same event more than once.
4. **Calls Relay** with a message written for text-to-speech.

***

## Prerequisites

<table><thead><tr><th width="180">Side</th><th>Requirement</th></tr></thead><tbody><tr><td>Relay</td><td>An <strong>enterprise plan</strong> account. API keys are not available on lower tiers.</td></tr><tr><td>Relay</td><td>A <strong>Workflow Group</strong> containing the users who should receive food safety calls.</td></tr><tr><td>Relay</td><td>Your <strong>subscriber ID</strong> and an <strong>API key</strong>.</td></tr><tr><td>Mitti</td><td>A <strong>Premium or Enterprise plan</strong>. API tokens are not available on lower plans.</td></tr><tr><td>Mitti</td><td>An Issue <strong>category</strong> used for food safety (this guide uses <code>Food safety</code>). Categories are configured in your Mitti organization.</td></tr><tr><td>Mitti</td><td>An API token whose owner can receive webhooks. For a <strong>service user</strong> token, that means the <strong>Override permissions: Manage all data</strong> permission. For a <strong>user</strong> token, the user needs the <strong>Administrator</strong> permission. See Step 4.</td></tr><tr><td>Hosting</td><td>A place to run the receiver at a public <strong>HTTPS URL</strong>: an Azure Function App, an AWS Lambda function with a Function URL, or a Cloudflare Worker. Any other host that can run Node.js 20+ also works.</td></tr></tbody></table>

***

{% stepper %}
{% step %}

## Create the Relay Workflow Group

In [Relay Dash](https://dash.relaypro.com/), open **Incidents** in the left-hand navigation.

Select **Workflow Groups**, then **Create Workflow Group**.

Name the group. This guide uses `food-safety`.

Set the type to **No Type**.

Select the new group, choose **Edit Membership**, and add the users who should be called.

The group name is what the receiver will send in the `groups` array of the API payload.
{% endstep %}

{% step %}

## Collect your Relay credentials

| Value           | Where to find it                                                                              |
| --------------- | --------------------------------------------------------------------------------------------- |
| `subscriber_id` | Relay Dash → **Help** → **Diagnostic Logs** → **Server Details**, listed under **Subscriber** |
| `apikey`        | Relay Dash → **Help** → [**API Keys**](https://dash.relaypro.com/api-keys) → create a key     |

{% hint style="warning" %}
Create a **dedicated API key for this integration** rather than reusing one. If the receiver's hosting account is ever compromised, you want to revoke one key without breaking every other integration you run.
{% endhint %}
{% endstep %}

{% step %}

## Prove the Relay side works

Fire the alert by hand first:

```sh
export subscriber_id=your_subscriber_id
export apikey=your_api_key

curl -X POST \
  -H "Authorization: RelayApiKey $apikey" \
  -H "Content-Type: application/json" \
  "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts" \
  -d '{"notification": "Test alert from Mitti integration", "groups": ["food-safety"]}' \
  -i
```

A successful call returns `HTTP/2 200` and a task ID:

```json
{"task_id":"P9CThKfTsEbJx23trAArHCD"}
```

Devices in `food-safety` should now be speaking the message every 30 seconds. Tap the talk button on one to acknowledge, or cancel it from the terminal:

```sh
curl -X DELETE \
  -H "Authorization: RelayApiKey $apikey" \
  "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts/P9CThKfTsEbJx23trAArHCD"
```

{% hint style="success" %}
If this curl works and the Mitti integration does not, the problem is in the Mitti side or the receiver, not in Relay.
{% endhint %}
{% endstep %}

{% step %}

## Create a Mitti API token

The receiver uses a Mitti API token to read issues. You also use a token to register the webhook in Step 7. Mitti supports two kinds; for a shared, long-running integration, use a **service user** token.

1. Log in to the [Mitti web app](https://app.mitti.com/).
2. Click your organization name in the lower-left corner and select **Integrations**.
3. Select the **API tokens** tab, then **+ Create API token**.
4. Name the token (for example `Relay food safety alerts`) and choose an inactivity expiry (31, 45, 60, or 180 days).
5. Select the permission sets for the service user. Make sure **Override permissions: Manage all data** is included. Mitti requires this permission for a service user to receive webhook payloads, and it also lets the receiver read any issue.
6. Select **Create token**, then copy the token and store it securely before closing the window. It is not shown again.

{% hint style="info" %}
Creating a service user token requires the **Platform management: Organization**, **Permissions**, and **Users** permissions and a full seat. If you would rather use a **user** token, the user must have the **Administrator** permission, and user tokens expire after 30 days of inactivity.

Tokens also expire after a period of inactivity. Because the receiver calls the Mitti API every time an issue is created, a quiet organization could see a token lapse. Choose the longest inactivity window that fits your policy, and set a reminder to rotate it.
{% endhint %}

Set it aside as `MITTI_API_TOKEN`. For more detail see Mitti's [Authentication](https://developer.mitti.com/reference/authentication) guide.
{% endstep %}

{% step %}

## Get the webhook signature secret

Mitti signs every webhook so your receiver can confirm it is genuine. Fetch your organization's signature secret:

```sh
export MITTI_API_TOKEN=your_mitti_token

curl -H "Authorization: Bearer $MITTI_API_TOKEN" \
  "https://api.mitti.com/webhooks/v1/token"
```

The response contains the secret in a `token` field:

```json
{"token":"your-signature-secret"}
```

Set this aside as `MITTI_WEBHOOK_SECRET`.

{% hint style="warning" %}
Treat the signature secret like a password. Anyone who has it can send your receiver forged events that trigger real alerts on Relay devices. If it is exposed, regenerate it with Mitti's [Regenerate signature secret](https://developer.mitti.com/reference/webhooksservice_generatetoken) endpoint and update the receiver.
{% endhint %}
{% endstep %}

{% step %}

## Deploy the receiver

The receiver has two parts: a **platform-neutral core** (`receiver.js`) that holds all of the logic, and a **small adapter** for the platform you host on. The core requires Node.js 20 or later, because it uses the built-in `fetch`, `Request`, `Response`, and Web Crypto APIs.

### The core: `receiver.js`

Use this file unchanged on every platform.

```javascript
// receiver.js
// Mitti (formerly SafetyCulture) "Issue created" webhook -> Relay alert.
//
// Platform-neutral core. It takes a standard Request-like object (method, headers.get,
// text()) and an `env` object of settings, and returns a standard Response. A thin adapter
// for your platform (Azure Functions, AWS Lambda, or Cloudflare Workers) calls handle().
// Requires a runtime with global fetch, Request/Response, and Web Crypto (Node.js 20+,
// Cloudflare Workers).
//
// Settings (passed in `env`):
//   MITTI_WEBHOOK_SECRET    Signature secret from GET https://api.mitti.com/webhooks/v1/token
//   MITTI_API_TOKEN         Mitti API token (service user recommended)
//   RELAY_SUBSCRIBER_ID     Relay subscriber ID
//   RELAY_API_KEY           Relay API key
//   RELAY_GROUP             Relay Workflow Group name (default: food-safety)
//   FOOD_SAFETY_CATEGORIES  Comma-separated Mitti issue categories that should page
//                           (default: "Food safety")
// Optional:
//   SEEN                    A store with get(key) / put(key, value, { expirationTtl }) used to
//                           de-duplicate Mitti retries. Falls back to in-memory, which only
//                           protects a single warm instance.

const MITTI_API = 'https://api.mitti.com';
const RELAY_API = 'https://api.relaypro.com';
const DEDUPE_TTL_SECONDS = 24 * 60 * 60;

const memorySeen = new Map(); // fallback store: key -> expiry (ms)

async function handle(request, env, deps = {}) {
  const fetchFn = deps.fetch || fetch;

  if (request.method !== 'POST') return reply(405, 'Method not allowed');

  // 1. Verify the signature over the RAW body. Do not parse before verifying.
  const raw = await request.text();
  const signature = request.headers.get('x-safetyculture-signature') || '';
  if (!(await validSignature(env.MITTI_WEBHOOK_SECRET, raw, signature))) {
    return reply(401, 'Invalid signature');
  }

  let body;
  try {
    body = JSON.parse(raw);
  } catch {
    return reply(400, 'Invalid JSON');
  }

  // 2. Only act on "Issue created".
  const eventTypes = body?.event?.event_types || [];
  if (!eventTypes.includes('TRIGGER_EVENT_INCIDENT_CREATED')) {
    return reply(200, 'Ignored: not an issue-created event');
  }
  const issueId = body?.resource?.id;
  if (!issueId) return reply(200, 'Ignored: no resource id');

  // 3. De-duplicate. Mitti retries failed deliveries and may deliver duplicates.
  const dedupeKey = `mitti-issue:${issueId}`;
  if (await alreadySeen(env, dedupeKey)) return reply(200, 'Duplicate: already alerted');

  // 4. The webhook payload is small, so fetch the issue to filter and build the message.
  const issueRes = await fetchFn(
    `${MITTI_API}/tasks/v1/incident/${encodeURIComponent(issueId)}`,
    { headers: { Authorization: `Bearer ${env.MITTI_API_TOKEN}` } },
  );
  if (!issueRes.ok) {
    console.error(`Mitti get issue failed: HTTP ${issueRes.status} for ${issueId}`);
    return reply(502, 'Could not fetch issue'); // non-2xx makes Mitti retry
  }
  const issue = (await issueRes.json())?.incident || {};

  const wanted = (env.FOOD_SAFETY_CATEGORIES || 'Food safety')
    .split(',')
    .map((c) => c.trim().toLowerCase())
    .filter(Boolean);
  const category = (issue.category?.key || '').trim().toLowerCase();
  if (!wanted.includes(category)) {
    return reply(200, `Ignored: category "${issue.category?.key || ''}" is not a food safety category`);
  }

  // 5. Build a message that reads well when spoken.
  const title = speakable(issue.task?.title) || 'No description';
  const site = speakable(issue.task?.site?.name);
  const where = site ? ` at ${site}` : '';

  const payload = {
    notification: `Food safety alert${where}. ${title}. Please respond.`,
    groups: [env.RELAY_GROUP || 'food-safety'],
    quorum: 1,
    timeout: 600,
    name: 'mitti-food-safety',
    on_ack: `Accepted. You are responding to the food safety alert${where}.`,
    on_quorum: 'Another team member has taken this call.',
    on_timeout: `Food safety alert${where} was not acknowledged.`,
  };

  // 6. Call Relay.
  const relayRes = await fetchFn(
    `${RELAY_API}/subscribers/${env.RELAY_SUBSCRIBER_ID}/api/v1/alerts`,
    {
      method: 'POST',
      headers: {
        Authorization: `RelayApiKey ${env.RELAY_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    },
  );
  if (relayRes.status !== 200) {
    console.error(`Relay alert failed for issue ${issueId}: HTTP ${relayRes.status} ${await relayRes.text()}`);
    return reply(502, 'Relay alert failed'); // not marked seen, so Mitti's retry can try again
  }
  const taskId = (await relayRes.json())?.task_id;
  await markSeen(env, dedupeKey, taskId || '1');
  console.log(`Relay alert sent for issue ${issueId}, task_id=${taskId}`);
  return reply(200, 'Alert sent', { task_id: taskId });
}

// --- helpers ---------------------------------------------------------------

function reply(status, message, extra = {}) {
  return new Response(JSON.stringify({ message, ...extra }), {
    status,
    headers: { 'Content-Type': 'application/json' },
  });
}

// Keep only characters that speak cleanly; collapse whitespace; cap the length.
function speakable(value) {
  return String(value || '')
    .replace(/[^A-Za-z0-9 .,'-]/g, ' ')
    .replace(/\s+/g, ' ')
    .trim()
    .slice(0, 120);
}

async function validSignature(secret, rawBody, headerValue) {
  if (!secret || !headerValue) return false;
  const key = await crypto.subtle.importKey(
    'raw',
    new TextEncoder().encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign'],
  );
  const mac = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(rawBody));
  const expected = [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, '0')).join('');
  return timingSafeEqual(expected, headerValue.trim().toLowerCase());
}

function timingSafeEqual(a, b) {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return diff === 0;
}

async function alreadySeen(env, key) {
  if (env.SEEN) return (await env.SEEN.get(key)) != null;
  const expiry = memorySeen.get(key);
  if (expiry && expiry > Date.now()) return true;
  memorySeen.delete(key);
  return false;
}

async function markSeen(env, key, value) {
  if (env.SEEN) return env.SEEN.put(key, value, { expirationTtl: DEDUPE_TTL_SECONDS });
  memorySeen.set(key, Date.now() + DEDUPE_TTL_SECONDS * 1000);
}

module.exports = { handle };
```

### Settings

Every platform uses the same settings. Set them in the platform's configuration, not in source code.

| Setting                  | Purpose                                                                                                                        |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| `MITTI_WEBHOOK_SECRET`   | Signature secret from Step 5. Requests that do not match it are rejected.                                                      |
| `MITTI_API_TOKEN`        | Mitti API token from Step 4.                                                                                                   |
| `RELAY_SUBSCRIBER_ID`    | Subscriber ID from Step 2.                                                                                                     |
| `RELAY_API_KEY`          | Relay API key from Step 2.                                                                                                     |
| `RELAY_GROUP`            | Workflow Group to alert. Defaults to `food-safety`.                                                                            |
| `FOOD_SAFETY_CATEGORIES` | Comma-separated list of Mitti Issue categories that should trigger an alert. Matching ignores case. Defaults to `Food safety`. |

{% hint style="warning" %}
`MITTI_WEBHOOK_SECRET`, `MITTI_API_TOKEN`, and `RELAY_API_KEY` are credentials. Keep them in your platform's secret store (Azure Key Vault, AWS Secrets Manager, or Cloudflare secrets) and never commit them to source control.
{% endhint %}

### The adapter for your platform

Mitti may deliver the same event more than once, and the receiver sends only one alert per issue. To do that across restarts and multiple instances, it needs a small persistent store. Each adapter below wires up the natural choice for its platform. Without a store the receiver falls back to memory, which protects only a single running instance and is not suitable for production.

{% tabs %}
{% tab title="Azure Functions" %}
This adapter uses the Node.js **v4 programming model** and stores de-duplication records in **Azure Table Storage**.

Create a Function App that runs a supported Node.js version on Linux (see Microsoft's [Node.js developer reference](https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node) for supported versions and project setup). Lay the project out like this:

```
host.json
package.json
src/
  receiver.js          <- the core, from above
  functions/
    mitti.js           <- the adapter, below
```

`host.json`:

```json
{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}
```

`package.json`:

```json
{
  "name": "mitti-relay-food-safety",
  "version": "1.0.0",
  "private": true,
  "main": "src/functions/*.js",
  "dependencies": {
    "@azure/data-tables": "^13.3.2",
    "@azure/functions": "^4.0.0"
  }
}
```

`src/functions/mitti.js`:

```javascript
// src/functions/mitti.js
// Azure Functions (Node.js, v4 programming model) adapter for the Mitti -> Relay receiver.
const { app } = require('@azure/functions');
const { TableClient } = require('@azure/data-tables');
const { handle } = require('../receiver');

// De-duplication store: Azure Table Storage. By default this uses the Function App's own
// storage account (AzureWebJobsStorage). Set SEEN_STORAGE_CONNECTION to use another account.
const connection = process.env.SEEN_STORAGE_CONNECTION || process.env.AzureWebJobsStorage;
const seen = connection
  ? tableStore(TableClient.fromConnectionString(connection, 'mittiseen', { allowInsecureConnection: connection.includes('127.0.0.1') }))
  : undefined;
if (!seen) console.warn('No storage connection string found; de-duplication is in-memory only.');

app.http('mitti', {
  methods: ['POST'],
  authLevel: 'anonymous', // requests are authenticated by Mitti's HMAC signature
  handler: async (request) => {
    // Azure's HttpRequest already exposes method, headers.get(), and text().
    const res = await handle(request, { ...process.env, SEEN: seen });
    return {
      status: res.status,
      headers: { 'Content-Type': 'application/json' },
      body: await res.text(),
    };
  },
});

function tableStore(client) {
  let ready;
  const ensureTable = () => (ready ||= client.createTable());
  const rowKey = (key) => key.replace(/[^A-Za-z0-9_-]/g, '_');
  return {
    async get(key) {
      await ensureTable();
      try {
        const entity = await client.getEntity('seen', rowKey(key));
        return Number(entity.expires) > Date.now() ? String(entity.value) : null; // expired rows count as unseen
      } catch (err) {
        if (err.statusCode === 404) return null;
        throw err;
      }
    },
    async put(key, value, { expirationTtl }) {
      await ensureTable();
      await client.upsertEntity(
        { partitionKey: 'seen', rowKey: rowKey(key), value: String(value), expires: Date.now() + expirationTtl * 1000 },
        'Replace',
      );
    },
  };
}
```

**Configure.** In the Function App, open **Settings → Environment variables** and add the settings from the table above as app settings. For the three credentials, use [Key Vault references](https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references) rather than pasting the values.

**Deploy.** From the project folder:

```sh
npm install
func azure functionapp publish <your-function-app-name>
```

Your webhook URL is:

```
https://<your-function-app-name>.azurewebsites.net/api/mitti
```

**De-duplication store.** The adapter uses the Function App's own storage account (the `AzureWebJobsStorage` setting) and creates a table named `mittiseen` the first time it runs. Each alerted issue adds one small row, and rows older than 24 hours are ignored. Table Storage does not delete them automatically, so clear old rows occasionally if the volume matters to you. If your app uses identity-based storage and has no connection string, set `SEEN_STORAGE_CONNECTION` to a storage account connection string instead.

{% hint style="info" %}
The trigger uses `authLevel: 'anonymous'` because Mitti authenticates itself with its HMAC signature, and the receiver rejects anything that fails the check. For a second layer, change it to `'function'` and register the webhook URL with `?code=<function key>` on the end.
{% endhint %}

**Logs.** Use **Monitoring → Log stream**, or Application Insights if you have it enabled.
{% endtab %}

{% tab title="AWS Lambda" %}
This adapter handles a **Lambda Function URL** (payload format 2.0) and stores de-duplication records in **DynamoDB**.

**1. Create the DynamoDB table.** Create a table named `mitti-seen` with partition key `pk` (type String). Enable **Time to Live** on an attribute named `expires`.

**2. Create the function.** Create a Lambda function using the **Node.js 22.x** runtime and set the handler to `lambda.handler`. Upload a zip containing the two files below. The AWS SDK for JavaScript v3 is included in the Node.js runtime, so there is nothing to install.

```
lambda.js      <- the adapter, below
receiver.js    <- the core, from above
```

`lambda.js`:

```javascript
// lambda.js
// AWS Lambda (Function URL, payload format 2.0) adapter for the Mitti -> Relay receiver.
const { DynamoDBClient, GetItemCommand, PutItemCommand } = require('@aws-sdk/client-dynamodb');
const { handle } = require('./receiver');

// De-duplication store: DynamoDB table with partition key "pk" (String) and a TTL attribute
// named "expires". Set the SEEN_TABLE environment variable to the table name.
const table = process.env.SEEN_TABLE;
const ddb = table ? new DynamoDBClient({}) : undefined;
const seen = table
  ? {
      async get(key) {
        const out = await ddb.send(new GetItemCommand({ TableName: table, Key: { pk: { S: key } } }));
        const expires = Number(out.Item?.expires?.N || 0);
        return out.Item && expires * 1000 > Date.now() ? out.Item.value?.S || '1' : null; // DynamoDB TTL deletes lazily, so check expiry here
      },
      async put(key, value, { expirationTtl }) {
        await ddb.send(
          new PutItemCommand({
            TableName: table,
            Item: {
              pk: { S: key },
              value: { S: String(value) },
              expires: { N: String(Math.floor(Date.now() / 1000) + expirationTtl) },
            },
          }),
        );
      },
    }
  : undefined;
if (!seen) console.warn('SEEN_TABLE is not set; de-duplication is in-memory only.');

exports.handler = async (event) => {
  const method = event.requestContext?.http?.method || 'POST';
  // The signature is computed over the raw body, so decode it exactly as sent.
  const body = event.isBase64Encoded ? Buffer.from(event.body || '', 'base64').toString('utf8') : event.body || '';

  const request = new Request(
    `https://${event.requestContext?.domainName || 'lambda-url.invalid'}${event.rawPath || '/'}`,
    { method, headers: event.headers || {}, body: method === 'GET' || method === 'HEAD' ? undefined : body },
  );

  const res = await handle(request, { ...process.env, SEEN: seen });
  return {
    statusCode: res.status,
    headers: { 'content-type': 'application/json' },
    body: await res.text(),
  };
};
```

**3. Configure.** Add the settings from the table above as environment variables, plus `SEEN_TABLE` set to `mitti-seen`. Set the function **timeout to 30 seconds**. The default of 3 seconds is too short, because each delivery makes two outbound API calls. For the three credentials you can read them from AWS Secrets Manager instead of using plain environment variables if your policy requires it.

**4. Allow table access.** Attach a policy to the function's execution role that allows `dynamodb:GetItem` and `dynamodb:PutItem` on the `mitti-seen` table.

**5. Create the Function URL.** On the function's **Configuration → Function URL** page, create a URL with auth type **NONE**. Mitti cannot sign requests with AWS credentials, so the receiver authenticates Mitti with its HMAC signature instead. Your webhook URL is the function URL, which looks like:

```
https://<url-id>.lambda-url.<region>.on.aws/
```

{% hint style="info" %}
AWS requires both `lambda:InvokeFunctionUrl` and `lambda:InvokeFunction` permissions to invoke a function URL. If you create the URL with infrastructure-as-code or the CLI rather than the console, make sure the function's resource-based policy grants both for public access.
{% endhint %}

**De-duplication store.** Each alerted issue adds one item to `mitti-seen` that expires after 24 hours. DynamoDB deletes expired items lazily, sometimes well after expiry, so the adapter also checks the expiry time itself.

**Logs.** Output goes to the function's CloudWatch log group.
{% endtab %}

{% tab title="Cloudflare Workers" %}
This adapter runs as a **Cloudflare Worker** and stores de-duplication records in **Workers KV**.

Project files:

```
worker.js        <- the adapter, below
receiver.js      <- the core, from above
wrangler.toml
```

`worker.js`:

```javascript
// worker.js
// Cloudflare Workers adapter for the Mitti -> Relay receiver.
import { handle } from './receiver.js';

export default {
  async fetch(request, env) {
    return handle(request, env); // bind a KV namespace named SEEN for de-duplication
  },
};
```

`wrangler.toml`:

```toml
name = "mitti-relay-food-safety"
main = "worker.js"
compatibility_date = "2025-01-01"

[vars]
RELAY_GROUP = "food-safety"
FOOD_SAFETY_CATEGORIES = "Food safety"

# After running `npx wrangler kv namespace create SEEN`, add the binding it prints:
# [[kv_namespaces]]
# binding = "SEEN"
# id = "<your-namespace-id>"
```

**Configure.** Store the credentials as secrets:

```sh
npx wrangler secret put MITTI_WEBHOOK_SECRET
npx wrangler secret put MITTI_API_TOKEN
npx wrangler secret put RELAY_SUBSCRIBER_ID
npx wrangler secret put RELAY_API_KEY
```

**De-duplication store.** Create a KV namespace and add the binding it prints to `wrangler.toml` (the commented `kv_namespaces` block):

```sh
npx wrangler kv namespace create SEEN
```

**Deploy:**

```sh
npx wrangler deploy
```

The URL it prints (for example `https://mitti-relay-food-safety.<your-account>.workers.dev`) is your webhook destination.

**Logs.** Run `npx wrangler tail`.
{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Hosting somewhere else?** The core only needs a `Request`-like object (`method`, `headers.get()`, `text()`) and an object of settings. Write a short adapter for your platform that builds the request, calls `handle(request, env)`, and returns the response, as the adapters above do. Read the raw request body for signature checking, and do not let your framework parse and re-serialize the JSON before it reaches the receiver.
{% endhint %}

Note the public HTTPS URL for your platform. It is the webhook destination in the next step.
{% endstep %}

{% step %}

## Register the Mitti webhook

Register the receiver's URL from Step 6 for the **Issue created** event:

```sh
curl -X POST \
  -H "Authorization: Bearer $MITTI_API_TOKEN" \
  -H "Content-Type: application/json" \
  "https://api.mitti.com/webhooks/v1/webhooks" \
  -d '{
    "trigger_events": ["TRIGGER_EVENT_INCIDENT_CREATED"],
    "url": "https://<your-receiver-url>"
  }'
```

The response includes the new `webhook_id` and `"enabled": true`. To confirm the registration at any time, list your webhooks:

```sh
curl -H "Authorization: Bearer $MITTI_API_TOKEN" \
  "https://api.mitti.com/webhooks/v1/webhooks"
```

{% hint style="info" %}
Webhooks are set up at the **organization** level. Any Issue created in the top-level organization triggers it, regardless of who created it. The receiver's category filter is what narrows this down to food safety.
{% endhint %}
{% endstep %}

{% step %}

## Test it end to end

In the Mitti app, create a new **Issue**:

1. Give it a title such as `Walk-in cooler reading 52F`.
2. Set the **category** to `Food safety`.
3. Set a **site**, if your organization uses sites. The site name is spoken in the alert.
4. Save the issue.

Within a few seconds a device in your Workflow Group should speak:

> Food safety alert at Store 12 Downtown. Walk-in cooler reading 52F. Please respond.

Tap the talk button to acknowledge. The device that accepts hears *Accepted. You are responding to the food safety alert at Store 12 Downtown.* and the other devices in the group stop alerting.

To confirm from the receiver side, check its logs (Log stream or Application Insights on Azure, CloudWatch on AWS, `npx wrangler tail` on Cloudflare). A successful run logs:

```
Relay alert sent for issue <issue id>, task_id=Q55jJRTWi3zPYtcFAaI5cD
```

Then create a second Issue with a different category, such as `Maintenance`. No alert should sound, and the log shows the issue was ignored.
{% endstep %}
{% endstepper %}

***

## How the receiver behaves

| Situation                          | Receiver response | What happens                                                                       |
| ---------------------------------- | ----------------- | ---------------------------------------------------------------------------------- |
| Valid food safety issue            | `200`             | One Relay alert is sent and the issue is remembered.                               |
| Same issue delivered again         | `200`             | Ignored as a duplicate. No second alert.                                           |
| Issue in a different category      | `200`             | Ignored. Mitti does not retry.                                                     |
| Any event other than Issue created | `200`             | Ignored.                                                                           |
| Signature missing or wrong         | `401`             | Rejected before any outbound call.                                                 |
| Mitti API or Relay API call fails  | `502`             | Mitti retries. The issue is not remembered, so the retry can still send the alert. |

Mitti retries a failed delivery **up to 4 times, 100 seconds apart**, when the receiver returns a 4xx or 5xx response. Delivery is best-effort and events can arrive out of order, so the receiver is built to be safe to call repeatedly. That is why ignored events return `200`: a `4xx` for an issue you intentionally skip would only cause pointless retries.

{% hint style="warning" %}
Webhook delivery is not guaranteed. For a safety-critical process, periodically reconcile against Mitti's [List Issues](https://developer.mitti.com/reference/incidentsservice_getincidents) endpoint to catch any issue that never produced an alert.
{% endhint %}

***

## Customizing the alert

### Which issues page the team

The `FOOD_SAFETY_CATEGORIES` setting takes a comma-separated list, so one receiver can cover several categories:

```
FOOD_SAFETY_CATEGORIES = "Food safety, Hygiene, Pest control"
```

Categories are matched by name, ignoring case. They must match the category names in your Mitti organization exactly (apart from case).

### Different groups for different sites or categories

To route alerts to different Relay Workflow Groups, replace the `groups: [env.RELAY_GROUP || 'food-safety']` line with a lookup based on `issue.task?.site?.name` or `issue.category?.key`. Each value must match a Workflow Group name (or URN) in Relay Dash.

### Other Mitti events

The same receiver pattern works for other webhook events. For example, `TRIGGER_EVENT_ACTION_CREATED` covers new corrective actions, and `TRIGGER_EVENT_INSPECTION_COMPLETED_STATUS` covers completed inspections. Each event needs its own fetch-and-filter logic, because the webhook itself only carries identifiers. See [Supported webhook trigger events](https://developer.mitti.com/reference/webhooks#supported-webhook-trigger-events).

***

## Payload reference

### Mitti webhook envelope

Every Mitti webhook uses the same outer structure. The receiver uses the fields marked below.

| Field                  | Used for                                                                         |
| ---------------------- | -------------------------------------------------------------------------------- |
| `webhook_id`           | Identifies the webhook registration.                                             |
| `event.event_types`    | List of event types. The receiver acts only on `TRIGGER_EVENT_INCIDENT_CREATED`. |
| `event.date_triggered` | When the event occurred.                                                         |
| `resource.id`          | The ID of the issue. The receiver fetches the full issue with it.                |
| `resource.type`        | The kind of resource the event refers to.                                        |

### Mitti fields used from Get Issue

The receiver calls `GET https://api.mitti.com/tasks/v1/incident/{id}` (the [Get Issue](https://developer.mitti.com/reference/incidentsservice_getincidentbyid) endpoint) and reads:

| Field                     | Used for                                           |
| ------------------------- | -------------------------------------------------- |
| `incident.category.key`   | Matched against `FOOD_SAFETY_CATEGORIES`.          |
| `incident.task.title`     | Spoken as the problem description.                 |
| `incident.task.site.name` | Spoken as the location, when the issue has a site. |

In the Mitti API, Issues were previously called Incidents, so you will see `incident` in endpoint paths and response fields. They are the same thing.

### Relay alert keys

`notification` and `groups` are required. Everything else is optional.

| Key            | Type          | Default                      | Behavior                                                                                              |
| -------------- | ------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------- |
| `notification` | string        | —                            | Spoken on every device in the group via text-to-speech.                                               |
| `groups`       | array         | —                            | Workflow Group names or URNs to alert.                                                                |
| `quorum`       | integer       | all devices must acknowledge | Cancels remaining alerts after this many acknowledgements. **Set this to `1` for food safety calls.** |
| `on_ack`       | string        | nothing spoken               | Spoken on the device that acknowledged.                                                               |
| `on_quorum`    | string        | nothing spoken               | Spoken on devices that had not yet acknowledged once quorum is met.                                   |
| `timeout`      | integer (sec) | `300`                        | Cancels remaining alerts after this long.                                                             |
| `on_timeout`   | string        | nothing spoken               | Spoken on devices that never acknowledged, after timeout.                                             |
| `name`         | string        | `alerts`                     | Controls serial/concurrent alerting behavior and appears in analytics events for correlation.         |

Leaving `quorum` at its default means the alert keeps sounding on every other device until **all** of them acknowledge. That is not what you want when one person takes the job. Set `quorum: 1`.

{% hint style="warning" %}
**Write for text-to-speech, not for a log file.**

Issue titles are typed by people and can contain codes, symbols, and punctuation that sound like gibberish when spoken. The receiver keeps only letters, digits, spaces, and `. , ' -`, collapses extra whitespace, and cuts the title at 120 characters. Do not add the issue description or free-text fields to the spoken message.
{% endhint %}

{% hint style="info" %}
The receiver builds the Relay request body with `JSON.stringify()`, so a double quote, backslash, or newline in an issue title cannot produce invalid JSON. If you adapt this code to build the body by string concatenation instead, those characters will cause Relay to reject the request with a 400.
{% endhint %}

***

## Troubleshooting

Start with the receiver's logs. Every delivery produces one log line or one JSON response.

| Symptom                                                        | Likely cause and fix                                                                                                                                                                                                                                                                                                               |
| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| No requests reach the receiver at all                          | The webhook is not registered, is disabled, or points at the wrong URL. List your webhooks (Step 7) and check `enabled` and `url`. Confirm the token that registered it had the permissions in Step 4.                                                                                                                             |
| Receiver returns `401 Invalid signature`                       | The `MITTI_WEBHOOK_SECRET` is wrong or was regenerated, or the body was altered before verification. Fetch the secret again (Step 5), and make sure nothing parses and re-serializes the JSON before the signature check.                                                                                                          |
| Receiver returns `502 Could not fetch issue`                   | The Mitti API token is wrong, expired from inactivity, or its owner cannot access the issue. Check the status code in the log. Include **Manage all data** on a service user token so it can read every issue.                                                                                                                     |
| Log says `Ignored: category ... is not a food safety category` | The issue's category does not match `FOOD_SAFETY_CATEGORIES`. Compare against the exact category name in Mitti.                                                                                                                                                                                                                    |
| Receiver returns `502 Relay alert failed`                      | Check the logged Relay status. `401` means the `RelayApiKey` header or key is wrong, and `404` usually means a wrong subscriber ID. Run the curl from Step 3 with the same values.                                                                                                                                                 |
| Log says `Relay alert sent`, but no device speaks              | The alert was accepted, so check the Relay side. `RELAY_GROUP` must exactly match a Workflow Group name, and that group must have members whose devices are online.                                                                                                                                                                |
| The alert keeps repeating after someone started work           | Alerts repeat every 30 seconds until acknowledged on a device or until `timeout`. Acknowledge on the device, or cancel with the `DELETE` call in Step 3.                                                                                                                                                                           |
| Two alerts for one issue                                       | The receiver is falling back to its in-memory store across multiple instances. Check that the platform's store is configured (Table Storage connection on Azure, `SEEN_TABLE` and table permissions on AWS, the `SEEN` KV binding on Cloudflare). The Azure and AWS adapters log a warning at startup when their store is missing. |

{% hint style="success" %}
If the curl command in Step 3 works but the integration does not, the problem is in Mitti or the receiver, not in Relay.
{% endhint %}

***

## Reference

### Mitti

* [Webhooks](https://developer.mitti.com/reference/webhooks)
* [Create a webhook](https://developer.mitti.com/reference/webhooksservice_createwebhook)
* [Get signature secret](https://developer.mitti.com/reference/webhooksservice_gettoken)
* [Issues](https://developer.mitti.com/reference/issues)
* [Get Issue](https://developer.mitti.com/reference/incidentsservice_getincidentbyid)
* [Authentication](https://developer.mitti.com/reference/authentication)

### Relay

* [Alerts overview](https://developer.relaypro.com/docs/relay-alerts-api)
* [Triggering an Alert](https://developer.relaypro.com/docs/relay-alerts-api/triggering-an-alert)
* [Customizing Your Alerts](https://developer.relaypro.com/docs/relay-alerts-api/customizing-your-alerts)
* [Advanced Configuration](https://developer.relaypro.com/docs/relay-alerts-api/advanced-configuration)
* [Broadcasts](https://developer.relaypro.com/docs/relay-broadcasts-api)


# Perry Weather Alerts

## Overview

[Perry Weather](https://perryweather.com/) monitors on-site weather for your locations and raises **policy events** when conditions cross thresholds you set, such as lightning inside a given radius or a heat reading above a limit. Perry sends each event as a signed **webhook**: an HTTP `POST` to a URL you choose.

This guide connects those webhooks to the [Relay Alerts and Broadcasts APIs](https://developer.relaypro.com/docs/relay-alerts-api), so the people on the ground hear the instruction on their Relay device the moment it matters, in the location where they are standing. Alerts keep repeating until each person acknowledges.

It builds two complete safety workflows for a steel mill (or any outdoor or hot-process site):

* **Lightning.** A warning when lightning is detected within 6 miles. A **stop work** order when it is within 3 miles. An **all clear** only after 30 minutes with no lightning inside the 6-mile warning radius, which follows OSHA's guidance to wait at least 30 minutes after the last thunder.
* **Heat.** A caution tier and a high-heat tier, driven by WBGT (wet bulb globe temperature), with an end-of-alert message when conditions drop.

```mermaid
flowchart LR
    PW[Perry Weather<br/>policy event] -- "signed webhook (POST)" --> R[Receiver]
    R -- "verify signature,<br/>de-duplicate,<br/>apply rules and state" --> R
    R -- "broadcast" --> A[Relay API]
    R -- "alert (repeats until acknowledged)" --> A
    R -- "cancel alert on all clear" --> A
    A -- "text-to-speech" --> G1[Workflow Group:<br/>outdoor-crews]
    A -- "text-to-speech" --> G2[Workflow Group:<br/>supervisors]
```

The receiver does five things:

1. **Verifies** that each request came from Perry Weather by checking its HMAC-SHA256 signature.
2. **De-duplicates** by `event_id`, and ignores events older than the last one it applied.
3. **Maps the policy to a role**, for example "lightning stop" or "high heat".
4. **Tracks state per location**, so a stop-work alert is sent once, cancelled on the all clear, and never repeated for every strike.
5. **Speaks** a short message through the Relay Alerts or Broadcasts API.

### What Perry sends

Perry Weather webhooks (schema v1.2) have only two event types: `DELAY` when a policy triggers, and `ALL_CLEAR` when its countdown expires. Each policy carries **one threshold** and its own `all_clear_minutes`. Two lightning distances therefore means **two Perry policies**:

| Perry policy        | Threshold                   | All clear after | Relay role       | Delivery                                                   |
| ------------------- | --------------------------- | --------------- | ---------------- | ---------------------------------------------------------- |
| Lightning warning   | 6 mi                        | 30 min          | `lightning_warn` | Broadcast to crews                                         |
| Lightning stop work | 3 mi                        | 30 min          | `lightning_stop` | **Alert** to crews and supervisors, cancelled on all clear |
| Heat caution        | Your caution level (WBGT)   | Per policy      | `heat_caution`   | Broadcast to crews                                         |
| High heat           | Your high-heat level (WBGT) | Per policy      | `heat_high`      | **Alert** to crews and supervisors                         |

{% hint style="info" %}
**Alerts vs. broadcasts.** An **alert** repeats on the device every 30 seconds until the user presses the talk button to acknowledge it, or until it times out. A **broadcast** plays once and needs no acknowledgement. This guide uses alerts for the two conditions that require a person to stop or change what they are doing, and broadcasts for everything else.
{% endhint %}

### Know what is, and is not, a regulatory requirement

{% hint style="warning" %}
**The 6-mile and 3-mile distances are site policy, not OSHA numbers.** OSHA's [lightning fact sheet](https://www.osha.gov/sites/default/files/publications/OSHA3863.pdf) does not set distances. It advises that workers move to a fully enclosed building (or a hard-topped vehicle) and stay for **at least 30 minutes after the last thunder**, and it expects employers to cover lightning in their written Emergency Action Plan. Use the distances your safety team has adopted.

**The heat thresholds are examples.** There is no final federal OSHA heat standard. The August 2024 proposal defines an initial heat trigger (heat index of 80°F, or a WBGT at the NIOSH recommended alert limit) and a high-heat trigger (heat index of 90°F, or a WBGT at the NIOSH recommended exposure limit), and the rulemaking is still pending. Until then OSHA relies on the General Duty Clause and its heat [National Emphasis Program](https://www.osha.gov/enforcement/directives/cpl-03-00-024-0). Several states have their own rules. Set your thresholds from your written heat plan, and have your industrial hygienist confirm the WBGT limits for your work rates and acclimatization practice. See [OSHA's heat rulemaking page](https://www.osha.gov/heat-exposure/rulemaking) for current status.
{% endhint %}

### Where to run it

The receiver is one small Node.js file with no dependencies. It runs anywhere that runs Node.js 20 or a container. This guide includes a plain Node.js server adapter (`server.js`) for Render, Heroku, Replit, Docker or a VM. For Azure Functions, AWS Lambda, or Cloudflare Workers, use the adapters in the [Mitti (SafetyCulture) Alerts](https://developer.relaypro.com/integrations/mitti-safetyculture-alerts) guide. They call the same `handle(request, env)` entry point and take the same `STORE` binding.

***

## Prerequisites

<table><thead><tr><th width="180">Side</th><th>Requirement</th></tr></thead><tbody><tr><td><strong>Relay</strong></td><td>A Relay account on the <strong>Enterprise</strong> plan (needed for API keys), access to <strong>Relay Dash</strong>, and at least one Relay device to test with.</td></tr><tr><td><strong>Perry Weather</strong></td><td>An account with <strong>API and webhooks access</strong>. Perry's pricing page lists this under its Plus tier, so confirm your plan with Perry. At least one location with <strong>lightning detection</strong>, and for heat, a location that reports <strong>WBGT</strong> (a Perry station with a black globe sensor).</td></tr><tr><td><strong>Hosting</strong></td><td>A place to run the receiver at a public <strong>HTTPS URL</strong>, always on. Webhook receivers must answer quickly and cannot sleep.</td></tr></tbody></table>

***

## Set up the integration

{% stepper %}
{% step %}

## Create your Relay Workflow Groups

Alerts and broadcasts go to **Workflow Groups**. Create one for each audience.

1. In **Relay Dash**, open **Incidents** from the left menu.
2. Select **Workflow Groups** → **Create Workflow Group**.
3. Enter a name and select **No Type**.
4. Select the group, then use **Edit Membership** to add users.

| Workflow Group  | Who's in it                                                           | Default name the receiver looks for |
| --------------- | --------------------------------------------------------------------- | ----------------------------------- |
| `outdoor-crews` | Everyone who works outdoors or near heat sources                      | `RELAY_GROUP_CREW`                  |
| `supervisors`   | Shift leads and the safety officer, who need to know work has stopped | `RELAY_GROUP_SUPERVISORS`           |

Group names must match exactly. If your groups are named differently, set the two settings above.
{% endstep %}

{% step %}

## Collect your Relay credentials and test them

| Value             | Where to find it                                                                  |
| ----------------- | --------------------------------------------------------------------------------- |
| **API key**       | Relay Dash → **Help** → **API Keys**                                              |
| **Subscriber ID** | Relay Dash → **Help** → **Diagnostic Logs** → **Server Details** → **Subscriber** |

{% hint style="warning" %}
Create a **dedicated API key** for this integration, so you can revoke it without breaking anything else.
{% endhint %}

Before deploying anything, check them with a broadcast:

```sh
export RELAY_SUBSCRIBER_ID=your-subscriber-id
export RELAY_API_KEY=your-api-key

curl -X POST "https://api.relaypro.com/subscribers/$RELAY_SUBSCRIBER_ID/api/v1/broadcasts" \
  -H "Authorization: RelayApiKey $RELAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"notification": "Perry Weather integration test.", "groups": ["outdoor-crews"]}'
```

If devices in that group speak the message, Relay is ready. The `Authorization` header needs the literal prefix `RelayApiKey`, then a space, then your key.
{% endstep %}

{% step %}

## Create the Perry Weather policies

In Perry Weather, set up **four policies** for each location you want covered. Perry's [webhook data model](https://developers.perryweather.com/guides/webhooks) gives each policy a single threshold, so the two lightning distances are separate policies. If you need help configuring policies, contact <support@perryweather.com>.

| Policy              | Type      | Threshold            | All clear          |
| ------------------- | --------- | -------------------- | ------------------ |
| Lightning warning   | Lightning | **6 miles**          | **30 minutes**     |
| Lightning stop work | Lightning | **3 miles**          | **30 minutes**     |
| Heat caution        | WBGT      | Your caution level   | Per your heat plan |
| High heat           | WBGT      | Your high-heat level | Per your heat plan |

Give **both lightning policies a 30-minute all clear.** Perry restarts each countdown whenever another strike lands inside that policy's radius, and sends `ALL_CLEAR` only when it completes. The receiver releases the stop only after **both** countdowns have finished, so work resumes 30 minutes after the last lightning anywhere inside the 6-mile radius.

{% hint style="info" %}
**Why the all clear waits for the 6-mile policy.** OSHA guidance is to stay sheltered for at least 30 minutes after the last thunder, and thunder can be heard well beyond 3 miles. If the stop lifted on the 3-mile all clear alone, work could resume while strikes continue at 4 to 6 miles. By default the receiver therefore holds the stop until the 6-mile policy has also cleared. To use a wider margin, raise the warning policy's radius in Perry (and update its key in `DEFAULT_RULES`). To release on the 3-mile all clear alone, set `REQUIRE_WARN_CLEAR=false`.
{% endhint %}
{% endstep %}

{% step %}

## Deploy the receiver

Create the project with the three files below, `receiver.js`, `server.js`, and `package.json`. Then deploy it to any Node.js 20+ host.

### The core: `receiver.js`

```javascript
// receiver.js
// Perry Weather policy webhook (v1.2) -> Relay alerts and broadcasts.
//
// Platform-neutral core. It takes a standard Request-like object (method, headers.get,
// text()) and an `env` object of settings, and returns a standard Response.
// Requires a runtime with global fetch, Request/Response and Web Crypto (Node.js 20+,
// Cloudflare Workers).
//
// Settings (passed in `env`):
//   PERRY_SIGNING_SECRET     Signing secret from Perry Weather (Integrations > Perry Weather APIs)
//   RELAY_SUBSCRIBER_ID      Relay subscriber ID
//   RELAY_API_KEY            Relay API key
//   RELAY_GROUP_CREW         Workflow Group for outdoor crews (default: outdoor-crews)
//   RELAY_GROUP_SUPERVISORS  Workflow Group for supervisors (default: supervisors)
//   RELAY_RULES              JSON that maps Perry policies to roles (see the guide). Merged over
//                            the lightning defaults below.
//   REQUIRE_WARN_CLEAR       Keeps the stop in place until the 6-mile warning policy has also
//                            cleared, following OSHA's "30 minutes after the last thunder"
//                            guidance. Default: true. Set to "false" to release on the 3-mile
//                            all clear alone.
//   DRY_RUN                  "true" logs what would be sent to Relay instead of sending it
// Optional:
//   STORE                    A store with get(key) / put(key, value, { expirationTtl }). Holds
//                            de-duplication records and per-location state. Falls back to
//                            in-memory, which only protects a single warm instance.

const RELAY_API = 'https://api.relaypro.com';
const TTL_SECONDS = 24 * 60 * 60;
const memory = new Map(); // fallback store: key -> { value, expires }

// Rule keys are "<condition_type>:<threshold>:<threshold_units>" from the webhook's policy object.
// Only the lightning type code (LR1) appears in Perry's published examples. Heat keys are
// customer-specific: discover them with DRY_RUN (see the guide) and add them in RELAY_RULES.
const DEFAULT_RULES = {
  'LR1:6:mi': { role: 'lightning_warn' },
  'LR1:3:mi': { role: 'lightning_stop' },
};

const UNIT_WORDS = {
  mi: 'miles',
  km: 'kilometers',
  f: 'degrees Fahrenheit',
  '°f': 'degrees Fahrenheit',
  c: 'degrees Celsius',
  '°c': 'degrees Celsius',
};

async function handle(request, env, deps = {}) {
  if (request.method !== 'POST') return reply(405, 'Method not allowed');

  // 1. Verify the signature over the RAW body. Do not parse before verifying.
  const raw = await request.text();
  const signature = request.headers.get('x-pw-signature') || '';
  if (!(await validSignature(env.PERRY_SIGNING_SECRET, raw, signature))) {
    return reply(401, 'Invalid signature');
  }

  let body;
  try {
    body = JSON.parse(raw);
  } catch {
    return reply(400, 'Invalid JSON');
  }

  const eventType = body?.event_type;
  const p = body?.payload;
  if ((eventType !== 'DELAY' && eventType !== 'ALL_CLEAR') || !p?.policy) {
    return reply(200, 'Ignored: not a policy event');
  }

  const store = makeStore(env);

  // 2. De-duplicate on event_id.
  const dedupeKey = `perry-event:${body.event_id}`;
  if (body.event_id && (await store.get(dedupeKey)) != null) {
    return reply(200, 'Duplicate: already handled');
  }

  // 3. Map the policy to a role.
  const rules = { ...DEFAULT_RULES, ...parseJson(env.RELAY_RULES) };
  const ruleKey = `${p.condition_type}:${p.policy.threshold}:${p.policy.threshold_units}`;
  const rule = rules[ruleKey];
  if (!rule) {
    console.warn(`Unmapped Perry policy ${ruleKey} (${eventType} at ${p.location_name}). Add it to RELAY_RULES.`);
    return reply(200, 'Unmapped policy', { rule_key: ruleKey });
  }

  // 4. Load state for this location and ignore events older than the last one we applied.
  const stateKey = `perry-state:${p.location_id}`;
  const state = normalize(await store.getJson(stateKey));
  const eventTime = Date.parse(body.time) || Date.now();
  if (state.last[ruleKey] && eventTime < state.last[ruleKey]) {
    return reply(200, 'Ignored: older than the last event for this policy');
  }

  // 5. Decide what to do. This part is pure so it can be tested without any network.
  const cfg = {
    crew: env.RELAY_GROUP_CREW || 'outdoor-crews',
    sup: env.RELAY_GROUP_SUPERVISORS || 'supervisors',
    requireWarnClear: String(env.REQUIRE_WARN_CLEAR).toLowerCase() !== 'false',
  };
  const actions = plan(rule, eventType, p, state, cfg);

  // 6. Do it.
  const dryRun = String(env.DRY_RUN).toLowerCase() === 'true';
  const fetchFn = deps.fetch || fetch;
  for (const action of actions) {
    try {
      const taskId = await perform(action, env, fetchFn, dryRun);
      if (action.saveTaskAs) state.tasks[action.saveTaskAs] = taskId;
      if (action.kind === 'cancel') delete state.tasks[action.role];
    } catch (err) {
      console.error(`Relay ${action.kind} failed for ${ruleKey}: ${err.message}`);
      return reply(502, 'Relay request failed'); // state is not saved, so a retry can run again
    }
  }

  state.last[ruleKey] = eventTime;
  await store.putJson(stateKey, state);
  if (body.event_id) await store.put(dedupeKey, '1', { expirationTtl: TTL_SECONDS });
  return reply(200, actions.length ? 'Handled' : 'Handled: nothing to send', {
    rule_key: ruleKey,
    role: rule.role,
    sent: actions.map((a) => a.kind),
  });
}

// --- decision logic --------------------------------------------------------

function plan(rule, eventType, p, state, cfg) {
  const where = speakable(p.location_name);
  const at = where ? ` at ${where}` : '';
  const threshold = `${num(p.policy.threshold)} ${unitWords(p.policy.threshold_units)}`;
  const reading = `${num(p.value)} ${unitWords(p.value_units)}`;
  const label = rule.label || 'heat level';
  const both = [cfg.crew, cfg.sup];
  const out = [];
  const role = rule.role;
  const active = state.active;
  const wasActive = !!active[role];

  switch (role) {
    case 'lightning_warn':
      if (eventType === 'DELAY') {
        active.lightning_warn = true;
        if (!wasActive) {
          out.push(broadcast(role, [cfg.crew], `Lightning warning${at}. Lightning detected within ${threshold}. Prepare to move to shelter.`));
        }
      } else {
        active.lightning_warn = false;
        if (state.hold) {
          state.hold = false;
          out.push(broadcast(role, both, `All clear${at}. No lightning within ${threshold} for ${num(p.policy.all_clear_minutes)} minutes. Outdoor work may resume.`));
        } else if (!active.lightning_stop) {
          out.push(broadcast(role, [cfg.crew], `Lightning warning ended${at}.`));
        }
      }
      break;

    case 'lightning_stop':
      if (eventType === 'DELAY') {
        state.hold = false;
        active.lightning_stop = true;
        if (!wasActive) {
          out.push({
            kind: 'alert',
            role,
            saveTaskAs: role,
            body: {
              notification: `Lightning within ${threshold}${at}. Stop all outdoor work now and move to shelter.`,
              groups: both,
              timeout: 600,
              name: 'perry-lightning-stop',
              on_ack: 'Acknowledged. Stay in shelter until the all clear.',
              on_timeout: `The stop work alert${at} was not acknowledged by everyone.`,
            },
          });
        }
      } else {
        active.lightning_stop = false;
        if (state.tasks[role]) out.push({ kind: 'cancel', role, taskId: state.tasks[role] });
        if (cfg.requireWarnClear && active.lightning_warn) {
          state.hold = true;
          out.push(broadcast(role, both, `No lightning within ${threshold} for ${num(p.policy.all_clear_minutes)} minutes, but lightning is still within the warning range${at}. Remain in shelter.`));
        } else {
          out.push(broadcast(role, both, `All clear${at}. No lightning within ${threshold} for ${num(p.policy.all_clear_minutes)} minutes. Outdoor work may resume.`));
        }
      }
      break;

    case 'heat_caution':
      if (eventType === 'DELAY') {
        active.heat_caution = true;
        if (!wasActive) {
          out.push(broadcast(role, [cfg.crew], `Heat caution${at}. ${label} is ${reading}. ${rule.say || 'Drink water and take shade breaks.'}`));
        }
      } else {
        active.heat_caution = false;
        out.push(broadcast(role, [cfg.crew], `Heat caution ended${at}.`));
      }
      break;

    case 'heat_high':
      if (eventType === 'DELAY') {
        active.heat_high = true;
        if (!wasActive) {
          out.push({
            kind: 'alert',
            role,
            saveTaskAs: role,
            body: {
              notification: `High heat alert${at}. ${label} is ${reading}. ${rule.say || 'Follow the high heat plan.'}`,
              groups: both,
              timeout: 600,
              name: 'perry-high-heat',
              on_ack: 'Acknowledged. Follow the high heat plan.',
              on_timeout: `The high heat alert${at} was not acknowledged by everyone.`,
            },
          });
        }
      } else {
        active.heat_high = false;
        if (state.tasks[role]) out.push({ kind: 'cancel', role, taskId: state.tasks[role] });
        out.push(broadcast(role, both, `High heat alert ended${at}.${active.heat_caution ? ' Heat caution remains in effect.' : ''}`));
      }
      break;

    default:
      console.warn(`Unknown role "${role}" in RELAY_RULES`);
  }
  return out;
}

function broadcast(role, groups, notification) {
  return { kind: 'broadcast', role, body: { notification, groups } };
}

// --- Relay -----------------------------------------------------------------

async function perform(action, env, fetchFn, dryRun) {
  const base = `${RELAY_API}/subscribers/${env.RELAY_SUBSCRIBER_ID}/api/v1`;
  const headers = { Authorization: `RelayApiKey ${env.RELAY_API_KEY}`, 'Content-Type': 'application/json' };

  if (dryRun) {
    console.log(`DRY_RUN ${action.kind}: ${JSON.stringify(action.body || { taskId: action.taskId })}`);
    return 'dry-run';
  }
  if (action.kind === 'cancel') {
    const res = await fetchFn(`${base}/alerts/${encodeURIComponent(action.taskId)}`, { method: 'DELETE', headers });
    // 404 means the alert already ended (acknowledged or timed out). That is fine.
    if (!res.ok && res.status !== 404) throw new Error(`HTTP ${res.status}`);
    return null;
  }
  const path = action.kind === 'alert' ? 'alerts' : 'broadcasts';
  const res = await fetchFn(`${base}/${path}`, { method: 'POST', headers, body: JSON.stringify(action.body) });
  if (res.status !== 200) throw new Error(`HTTP ${res.status} ${await res.text()}`);
  if (action.kind !== 'alert') return null;
  return (await res.json().catch(() => ({})))?.task_id || null;
}

// --- helpers ---------------------------------------------------------------

function reply(status, message, extra = {}) {
  return new Response(JSON.stringify({ message, ...extra }), {
    status,
    headers: { 'Content-Type': 'application/json' },
  });
}

function parseJson(text) {
  if (!text) return {};
  try {
    return JSON.parse(text);
  } catch {
    console.error('RELAY_RULES is not valid JSON; ignoring it.');
    return {};
  }
}

function normalize(s) {
  return { active: {}, tasks: {}, last: {}, hold: false, ...(s || {}) };
}

function num(n) {
  const v = Number(n);
  return Number.isFinite(v) ? String(Math.round(v * 10) / 10) : '';
}

function unitWords(u) {
  const key = String(u || '').trim().toLowerCase();
  return UNIT_WORDS[key] || speakable(u);
}

// Keep only characters that speak cleanly; collapse whitespace; cap the length.
function speakable(value) {
  return String(value || '')
    .replace(/[^A-Za-z0-9 .,'-]/g, ' ')
    .replace(/\s+/g, ' ')
    .trim()
    .slice(0, 80);
}

async function validSignature(secret, rawBody, headerValue) {
  if (!secret || !headerValue) return false;
  const key = await crypto.subtle.importKey(
    'raw',
    new TextEncoder().encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign'],
  );
  const mac = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(rawBody));
  const expected = Buffer.from(mac).toString('base64');
  return timingSafeEqual(expected, headerValue.trim());
}

function timingSafeEqual(a, b) {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return diff === 0;
}

function makeStore(env) {
  const raw = env.STORE;
  return {
    async get(key) {
      if (raw) return raw.get(key);
      const hit = memory.get(key);
      if (hit && hit.expires > Date.now()) return hit.value;
      memory.delete(key);
      return null;
    },
    async put(key, value, opts = { expirationTtl: TTL_SECONDS }) {
      if (raw) return raw.put(key, value, opts);
      memory.set(key, { value, expires: Date.now() + opts.expirationTtl * 1000 });
    },
    async getJson(key) {
      const v = await this.get(key);
      try {
        return v ? JSON.parse(v) : null;
      } catch {
        return null;
      }
    },
    putJson(key, obj) {
      return this.put(key, JSON.stringify(obj), { expirationTtl: 7 * TTL_SECONDS });
    },
  };
}

module.exports = { handle, plan };
```

### The server adapter: `server.js`

```javascript
// server.js
// Minimal Node.js adapter: runs the receiver as a plain HTTPS-fronted web service
// (Render, Heroku, Replit, Docker, a VM). Put TLS in front of it with your host's router.
const http = require('node:http');
const { handle } = require('./receiver');

const PORT = process.env.PORT || 8080;

http
  .createServer(async (req, res) => {
    if (req.method === 'GET' && req.url === '/health') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      return res.end('{"ok":true}');
    }
    if (req.url !== '/webhooks/perryweather') {
      res.writeHead(404);
      return res.end();
    }

    // Read the raw bytes. The signature is computed over them, so do not parse first.
    const chunks = [];
    let size = 0;
    for await (const chunk of req) {
      size += chunk.length;
      if (size > 1_000_000) {
        res.writeHead(413);
        return res.end();
      }
      chunks.push(chunk);
    }
    const body = Buffer.concat(chunks).toString('utf8');

    const request = new Request(`http://${req.headers.host}${req.url}`, {
      method: req.method,
      headers: req.headers,
      body: req.method === 'GET' || req.method === 'HEAD' ? undefined : body,
    });
    const out = await handle(request, process.env);
    res.writeHead(out.status, { 'Content-Type': 'application/json' });
    res.end(await out.text());
  })
  .listen(PORT, () => console.log(`Listening on ${PORT}`));
```

### `package.json`

```json
{
  "name": "perryweather-relay-safety",
  "version": "1.0.0",
  "private": true,
  "main": "server.js",
  "engines": { "node": ">=20" },
  "scripts": { "start": "node server.js" }
}
```

### Settings

Set these in your host's secret or environment store, never in source code.

| Setting                   | Required  | Value                                                                                                                                                                                           |
| ------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PERRY_SIGNING_SECRET`    | Yes       | From step 5. Use `placeholder` for now.                                                                                                                                                         |
| `RELAY_SUBSCRIBER_ID`     | Yes       | From step 2                                                                                                                                                                                     |
| `RELAY_API_KEY`           | Yes       | From step 2                                                                                                                                                                                     |
| `RELAY_GROUP_CREW`        | No        | Defaults to `outdoor-crews`                                                                                                                                                                     |
| `RELAY_GROUP_SUPERVISORS` | No        | Defaults to `supervisors`                                                                                                                                                                       |
| `RELAY_RULES`             | Heat only | Maps Perry heat policies to roles. Set in step 6.                                                                                                                                               |
| `REQUIRE_WARN_CLEAR`      | No        | Keeps the stop in place until the 6-mile policy also clears, following OSHA's 30-minutes-after-last-thunder guidance. Defaults to `true`. Set `false` to release on the 3-mile all clear alone. |
| `DRY_RUN`                 | No        | Leave at `true` while testing. The receiver logs what it would send to Relay instead of sending it.                                                                                             |

{% hint style="info" %}
**State storage.** The receiver remembers which alerts are active so it can send one stop-work alert, cancel it on the all clear, and discard duplicates. Without a `STORE` binding it keeps this in memory, which is only safe on a single instance that never restarts. For production, pass a key-value store with `get(key)` and `put(key, value, { expirationTtl })`, such as Workers KV, DynamoDB or Azure Table Storage. The adapters in the [Mitti guide](https://developer.relaypro.com/integrations/mitti-safetyculture-alerts) show each one.
{% endhint %}

Once deployed, open `https://<your-host>/health`. It should return `{"ok":true}`. Your webhook URL is:

```
https://<your-host>/webhooks/perryweather
```

{% endstep %}

{% step %}

## Register the webhook and get the signing secret

1. In the Perry Weather dashboard, go to [**Integrations → Perry Weather APIs**](https://app.perryweather.com/Integrations/ApiManagement) and open the **Webhooks** tab.
2. Register your webhook URL from step 4 for the locations and policies you created in step 3.
3. Click **Signing Secret** and copy the key.
4. Replace `placeholder` in `PERRY_SIGNING_SECRET` with it, then restart or redeploy.

{% hint style="warning" %}
Treat the signing secret like an API key. The receiver rejects any request whose `x-pw-signature` header is missing or wrong, because the webhook URL is public. Without verification, anyone who finds it could make your devices announce a false stop-work or all-clear. To rotate a compromised secret, contact <support@perryweather.com>.
{% endhint %}
{% endstep %}

{% step %}

## Map your policies to roles

The receiver identifies each Perry policy by a key built from the webhook:

```
<condition_type>:<policy.threshold>:<policy.threshold_units>
```

For example, a 3-mile lightning policy arrives as `LR1:3:mi`. The two lightning policies from step 3 are built in, so lightning works without any mapping. **Heat policies need one.** Perry's published examples show only the lightning type code (`LR1`), so find the type code your heat policies use from a real event.

**1. Find the keys.** With `DRY_RUN=true`, trigger or wait for a heat event. The receiver logs the unmapped key:

```
Unmapped Perry policy WBGT:90:F (DELAY at Gary Works, IN). Add it to RELAY_RULES.
```

**2. Add them to `RELAY_RULES`**, as a single line of JSON. `label` is spoken as the name of the reading, and `say` replaces the default instruction. Replace the keys below with the ones you saw in the log:

```json
{
  "WBGT:80:F": {
    "role": "heat_caution",
    "label": "wet bulb globe temperature",
    "say": "Drink water and take shade breaks."
  },
  "WBGT:90:F": {
    "role": "heat_high",
    "label": "wet bulb globe temperature",
    "say": "Follow the high heat plan. Take your scheduled rest and water break now."
  }
}
```

{% hint style="info" %}
The `80` and `90` here are example values that follow the tiers in OSHA's 2024 heat proposal. Use the thresholds from your own heat plan. Spell out `label` the way it should be spoken, because text-to-speech reads "WBGT" as individual letters.
{% endhint %}

If a policy has no mapping, the receiver replies `200` with `"message": "Unmapped policy"` and sends nothing, so an unmapped policy fails quietly. Check your logs after setup.
{% endstep %}

{% step %}

## Test end to end and go live

**1. Send a signed test event.** With `DRY_RUN` still `true`, send a test 3-mile lightning event to your deployment, using the same signing secret:

```sh
SECRET=your-signing-secret
URL=https://<your-host>/webhooks/perryweather
BODY='{"event_id":"test-1","event_type":"DELAY","time":"2026-01-12T19:15:12.401Z","version":"1.2","payload":{"customer_id":1,"location_id":"loc-test","location_name":"Test Site","policy_trigger_id":"2ee204fd-6546-4be8-99eb-165bf90efa13","condition_type":"LR1","message":"Lightning strike 2.4 miles from Test Site.","additional_message":null,"value":2.4,"value_units":"mi","event_type":"DELAY","event_id":"test-1","policy":{"type":"LR1","threshold":3,"threshold_units":"mi","all_clear_minutes":30}}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" -binary | base64)

curl -X POST "$URL" -H "Content-Type: application/json" -H "x-pw-signature: $SIG" --data-binary "$BODY"
```

You should see `{"message":"Handled","rule_key":"LR1:3:mi","role":"lightning_stop","sent":["alert"]}`, and the host's logs show the stop-work alert the receiver would have sent. A wrong secret returns `401`.

**2. Go live.** Set `DRY_RUN` to `false` and restart. Then send the same test again with a new `event_id`. Devices in `outdoor-crews` and `supervisors` should speak:

> Lightning within 3 miles at Test Site. Stop all outdoor work now and move to shelter.

Press the talk button to acknowledge it. Then send an `ALL_CLEAR` for the same policy (change `event_type` in both places to `ALL_CLEAR`, `value` to `0`, and use a new `event_id`) to confirm the alert is cancelled and the all-clear message plays.

{% hint style="warning" %}
The test above changes real state for `loc-test`. Use a throwaway `location_id`, and send an `ALL_CLEAR` afterwards so the receiver does not hold a stale stop-work state.
{% endhint %}
{% endstep %}
{% endstepper %}

***

## How the lightning workflow behaves

```mermaid
stateDiagram-v2
    [*] --> Clear
    Clear --> Warning: 6 mi policy DELAY<br/>broadcast to crews
    Warning --> Stop: 3 mi policy DELAY<br/>alert crews + supervisors
    Clear --> Stop: 3 mi policy DELAY
    Stop --> Stop: more strikes inside 3 mi<br/>no repeat alert
    Stop --> Hold: 3 mi ALL_CLEAR and<br/>6 mi policy still active
    Stop --> Clear: 3 mi ALL_CLEAR and<br/>6 mi already clear<br/>cancel alert, broadcast all clear
    Hold --> Clear: 6 mi ALL_CLEAR<br/>broadcast all clear
```

| Event                                           | What the receiver does                                                                                                                                                                                        |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 6-mile `DELAY`                                  | Broadcasts a warning to `outdoor-crews`. Sent once while the warning is active.                                                                                                                               |
| 3-mile `DELAY`                                  | Sends a stop-work **alert** to `outdoor-crews` and `supervisors`. It repeats every 30 seconds on each device until acknowledged or 10 minutes pass. Further strikes inside 3 miles do not send another alert. |
| 3-mile `ALL_CLEAR`, 6-mile policy already clear | Cancels the stop-work alert on every device that has not acknowledged it, then broadcasts the all clear to both groups.                                                                                       |
| 3-mile `ALL_CLEAR`, 6-mile policy still active  | Cancels the stop-work alert and tells both groups to remain in shelter. The all clear is broadcast when the 6-mile policy clears. (With `REQUIRE_WARN_CLEAR=false`, the all clear is broadcast immediately.)  |
| 6-mile `ALL_CLEAR` while holding                | Broadcasts the all clear to both groups.                                                                                                                                                                      |
| 6-mile `ALL_CLEAR`, no stop active              | Broadcasts that the warning has ended.                                                                                                                                                                        |

## How the heat workflow behaves

| Event                    | What the receiver does                                                                                                                                     |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Caution policy `DELAY`   | Broadcasts the caution to `outdoor-crews`, with the reading (for example "wet bulb globe temperature is 82.4 degrees Fahrenheit"). Sent once while active. |
| High-heat policy `DELAY` | Sends a high-heat **alert** to `outdoor-crews` and `supervisors` until acknowledged or 10 minutes pass. Sent once while active.                            |
| High-heat `ALL_CLEAR`    | Cancels the alert, then broadcasts that high heat has ended, noting if the caution is still active.                                                        |
| Caution `ALL_CLEAR`      | Broadcasts that the caution has ended.                                                                                                                     |

***

## Customizing

| What you want                                       | Change                                                                                                                                                                                    |
| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A different warning or stop distance                | Change the threshold on the Perry policy, then change the key in `DEFAULT_RULES` in `receiver.js`, or override it in `RELAY_RULES` (for example `"LR1:5:mi": {"role": "lightning_warn"}`) |
| Only one person needs to acknowledge the stop order | Add `quorum: 1` to the alert body in `plan()`. Leaving it out requires every device in the groups to acknowledge, which is the safer default for a stop-work order.                       |
| A longer or shorter acknowledgement window          | Change `timeout` (seconds) in the alert body. The Relay default is 300.                                                                                                                   |
| Supervisors also hear the warning and caution tiers | Change `[cfg.crew]` to `both` in the matching `broadcast()` calls                                                                                                                         |
| Different crews per site                            | Replace `cfg.crew` with a lookup on `p.location_id`                                                                                                                                       |
| Different spoken wording                            | Edit the templates in `plan()`. Keep them short, because they are read aloud.                                                                                                             |

{% hint style="success" %}
**Write for the ear.** Lead with the instruction and the place: "Lightning within 3 miles at Gary Works. Stop all outdoor work now and move to shelter." The receiver strips symbols and caps names at 80 characters so text-to-speech reads them cleanly. See [Customizing Your Alerts](https://developer.relaypro.com/docs/relay-alerts-api/customizing-your-alerts) for every alert option.
{% endhint %}

### Alert options used

| Field        | Value used                                | Behavior                                                           |
| ------------ | ----------------------------------------- | ------------------------------------------------------------------ |
| `timeout`    | `600`                                     | Seconds before unacknowledged alerts are cancelled                 |
| `quorum`     | not set                                   | Every device in the groups must acknowledge before the alert stops |
| `on_ack`     | Spoken on the acknowledging device        | Confirms they should stay in shelter, or follow the heat plan      |
| `on_timeout` | Spoken on devices that never acknowledged | Tells them the alert expired unacknowledged                        |
| `name`       | `perry-lightning-stop`, `perry-high-heat` | Appears in Relay analytics so you can see which workflow fired     |

***

## Payload reference

Perry's v1.2 webhook body. See Perry's [API reference](https://developers.perryweather.com/apis/perry-weather-webhooks-1/versions) for the full schema.

| Field                                          | Type            | Notes                                                             |
| ---------------------------------------------- | --------------- | ----------------------------------------------------------------- |
| `event_id`                                     | string          | Unique per event. Used for de-duplication.                        |
| `event_type`                                   | string          | `DELAY` (policy triggered) or `ALL_CLEAR` (countdown completed)   |
| `time`                                         | ISO date-time   | When the event occurred. Used to discard out-of-order events.     |
| `version`                                      | string          | `"1.2"`                                                           |
| `payload.location_id` / `location_name`        | string          | Location. State is tracked per `location_id`.                     |
| `payload.condition_type`                       | string          | Policy type, for example `LR1` for lightning                      |
| `payload.value` / `value_units`                | number / string | The reading that triggered the event, for example `12.4` and `mi` |
| `payload.message` / `additional_message`       | string / null   | Perry's own text. The receiver does not speak it.                 |
| `payload.policy.threshold` / `threshold_units` | number / string | The policy's limit, for example `3` and `mi`                      |
| `payload.policy.all_clear_minutes`             | integer         | Length of the all-clear countdown                                 |

Perry signs the **entire raw JSON body** with HMAC-SHA256 using your signing secret and sends it Base64-encoded in `x-pw-signature`. If Perry cannot produce a signature, the header may be omitted. The receiver rejects those requests.

***

## Security notes

{% hint style="danger" %}
**Always verify the signature.** A forged `ALL_CLEAR` could tell a crew to go back out during a lightning event. The receiver compares signatures in constant time, over the raw body, before it parses anything.
{% endhint %}

* **Keep secrets in your host's secret store**, not in code or the repo.
* **Replays.** Perry's signature does not include a timestamp, so a captured request can be replayed. The receiver drops repeated `event_id` values and any event older than the last one applied for that policy and location.
* **Fail safe.** If Relay is unreachable the receiver replies `502` and saves nothing. It does not claim a stop-work alert was sent when it was not. Monitor for `502` responses and alert on them.
* **Do not rely on this alone.** Webhook delivery over the internet can fail. Keep Perry's own on-site horns, strobes and apps as your primary signal, and use Relay as an additional, personal channel.

***

## Troubleshooting

| Symptom                                                       | Likely cause                                                                                                                                                                                                                                                     |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `401 Invalid signature` on real events                        | `PERRY_SIGNING_SECRET` is still `placeholder`, was rotated, or the host altered the body before verification. Make sure nothing parses and re-serializes the JSON first.                                                                                         |
| Heat events do nothing, log says `Unmapped Perry policy`      | Add the logged key to `RELAY_RULES` (step 6).                                                                                                                                                                                                                    |
| Lightning events do nothing, log says `Unmapped Perry policy` | Your lightning policy uses a different type code or threshold than `LR1:6:mi` and `LR1:3:mi`. Add the logged key to `RELAY_RULES` with the role `lightning_warn` or `lightning_stop`.                                                                            |
| `{"message":"Handled: nothing to send"}`                      | Expected for repeat strikes while a stop or caution is already active.                                                                                                                                                                                           |
| `502 Relay request failed`                                    | Check the logged HTTP status. `401` is a wrong API key and `404` is usually a wrong subscriber ID. Run the curl from step 2.                                                                                                                                     |
| Relay accepts the request but no device speaks                | A group name does not match a Workflow Group exactly, or the group has no members.                                                                                                                                                                               |
| Stop-work alert keeps repeating after an all clear            | The all clear never arrived or the 3-mile policy is mapped to the wrong role. Check the logs, or cancel from the API with `DELETE /alerts/{task_id}`. See [Advanced Configuration](https://developer.relaypro.com/docs/relay-alerts-api/advanced-configuration). |
| Alerts arrive twice                                           | Two webhooks registered for the same policy, or several instances without a shared `STORE`                                                                                                                                                                       |
| Stop-work lifted but lightning still nearby                   | `REQUIRE_WARN_CLEAR` is set to `false`, so the 3-mile all clear released the stop while strikes continued at 4 to 6 miles. Remove the setting or set it to `true`.                                                                                               |

***

## Going further

* **Record who acknowledged.** Use the [Relay Events API](https://developer.relaypro.com/docs/relay-events-api) and the alert analytics to build a stop-work and all-clear acknowledgement log for your safety records.
* **Add more Perry policies.** The same receiver pattern works for other Perry policies, such as wind or air quality. Add a key to `RELAY_RULES` and a role in `plan()`.

## Reference

### Perry Weather

* [Webhooks guide](https://developers.perryweather.com/guides/webhooks)
* [Webhooks API reference (v1.2)](https://developers.perryweather.com/apis/perry-weather-webhooks-1/docs)
* [Developer portal](https://developers.perryweather.com/)

### Relay

* [Triggering an Alert](https://developer.relaypro.com/docs/relay-alerts-api/triggering-an-alert)
* [Customizing Your Alerts](https://developer.relaypro.com/docs/relay-alerts-api/customizing-your-alerts)
* [Advanced Configuration](https://developer.relaypro.com/docs/relay-alerts-api/advanced-configuration)
* [Broadcasts](https://developer.relaypro.com/docs/relay-broadcasts-api)

### Safety guidance

* [OSHA: Lightning Safety When Working Outdoors](https://www.osha.gov/sites/default/files/publications/OSHA3863.pdf)
* [OSHA: Heat injury and illness prevention rulemaking](https://www.osha.gov/heat-exposure/rulemaking)


