> For the complete documentation index, see [llms.txt](https://developer.relaypro.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.relaypro.com/integrations/perry-weather-alerts.md).

# 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)
