- Use Our Data
- Integrations
- Everbridge
Power Outage Data in Everbridge
To get power outage alerts into Everbridge, run a Python poller every 15 minutes that sends your sites' coordinates to the PowerOutage.us v2 REST API and, when a utility reports an outage covering a site, launches an Everbridge Suite notification to the groups and contacts you assigned to that site. The poller sends one notification when a site loses power and one when the utility no longer reports the outage, through the Launch Mass Notification endpoint with an API user's credentials. Everbridge then delivers it over the paths your contacts have, such as SMS, voice, email and the app.
What you'll have
- A notification to the people at a branch, store or office as soon as a utility reports an outage covering it, naming the utility, customers out, cause and estimated restoration.
- One message when a site goes dark and one when the outage is no longer reported, not one every 15 minutes.
- Recipients chosen per site, by Everbridge group id or contact External ID.
- Up to 100 sites checked per request, with nothing launched when a check fails.
What you need
An API key (request one with the form below) and these endpoints. Full details are in the API reference.
| Endpoint | Method | Used for | Package |
|---|---|---|---|
/geojson/at-point | POST | Checks up to 100 site coordinates per request and returns, in request order, the active outages covering each one and the utilities serving it. | Standard + Locations |
Step 1: Check what you need
/geojson/at-point is in the Standard + Locations package, and the poller depends on it. In Everbridge Suite you need an organization with the groups or contacts to notify, and an Account Admin or Organization Admin who can add users. The poller runs on any host with Python 3.8 or later and outbound HTTPS to poweroutage.us and api.everbridge.net. If your organization is hosted in the EU, the API host is api.everbridge.eu instead; your Everbridge admin can confirm which one you use.
Step 2: Create an API user
In the Manager Portal, go to Users > Add User and create a user for the poller, for example poweroutage-api, with a role that may launch notifications; Everbridge's getting-started guide uses Organization Admin, and a user can hold only one role. Send the invitation, register the account from the email to set its username and password, then edit the user and turn on API Access. The poller signs in with Basic authentication over HTTPS, built from that username and password. API users' passwords don't expire unless someone signs in to the Manager Portal with them, so keep this user for the API only.
Step 3: Assign recipients to each site
Copy your Organization ID from Settings > Organization > Base Information, then list your groups' ids with the Everbridge API, as below. In the sites file, give each site a unique id, the name people will see, its coordinates in decimal degrees, and at least one recipient: groupIds for Everbridge groups, such as everyone based at that branch, and externalIds for individual contacts, using the External ID shown on the contact in the Manager Portal. Write both as lists of strings. A site with neither has no one to notify.
# The organization id is under Settings > Organization > Base Information.
# curl asks for the API user's password, so it stays out of your shell history.
# Groups come back in pages: if totalPageCount is more than 1, repeat with
# ?pageNumber=2, ?pageNumber=3 and so on.
curl -s -u 'poweroutage-api' 'https://api.everbridge.net/rest/groups/<organizationId>?pageNumber=1' \
| jq '{totalPageCount: .page.totalPageCount, groups: [.page.data[] | {id: (.id | tostring), name}]}' Step 4: List your sites
The poller reads this file on every run, so edit it whenever a site opens, closes or changes its group. It checks the sites in batches of 100, the endpoint maximum.
[
{"id": "branch-101", "name": "Branch 101, Atlanta", "lat": 33.749, "lon": -84.388,
"groupIds": ["2451915224907929"], "externalIds": []},
{"id": "branch-214", "name": "Branch 214, Savannah", "lat": 32.0809, "lon": -81.0912,
"groupIds": ["2455763515605121"], "externalIds": ["facilities.savannah"]}
] Step 5: Write the poller
Save this as /opt/poweroutage/poweroutage_everbridge.py. It uses only the Python standard library. It checks every site first and waits the Retry-After seconds after a 429, three tries at most, so a failed check stops the run before anything is launched. For each site inside one or more outages that it hasn't notified yet, it launches one Standard notification listing every outage covering the site, each identified by utilityId and outageId. When no outage covers a notified site any more, it launches a second notification and forgets the site. The state file records which sites have been notified, only after Everbridge accepts the launch, and is saved even if the run fails partway. If Everbridge refuses a launch, the error goes to stderr and the site is tried again on the next run.
import base64
import json
import os
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
os.umask(0o077) # the state file is readable by this account only
API_KEY = os.environ['POWEROUTAGE_API_KEY']
EVERBRIDGE_API = os.environ['EVERBRIDGE_API'] # https://api.everbridge.net/rest, or .eu for EU accounts
ORGANIZATION_ID = os.environ['EVERBRIDGE_ORGANIZATION_ID']
CREDENTIALS = base64.b64encode(
f"{os.environ['EVERBRIDGE_USERNAME']}:{os.environ['EVERBRIDGE_PASSWORD']}".encode()
).decode()
SITES = json.loads(Path(os.environ['SITES_FILE']).read_text())
STATE_FILE = Path(os.environ['STATE_FILE']) # sites already notified, kept between runs
def outages_at(points):
"""Up to 100 points per call; waits out a 429 for as long as Retry-After says."""
request = urllib.request.Request(
'https://poweroutage.us/api/v2/geojson/at-point',
data=json.dumps({'points': points}).encode(),
headers={'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json'},
)
for attempt in range(3):
try:
with urllib.request.urlopen(request, timeout=30) as response:
return json.load(response)['data']['points']
except urllib.error.HTTPError as err:
if err.code != 429 or attempt == 2:
raise
time.sleep(int(err.headers.get('Retry-After', '10')))
def launch(site, title, text):
"""Launch a notification to the site's groups and contacts. False: try again next run."""
request = urllib.request.Request(
f'{EVERBRIDGE_API}/notifications/{ORGANIZATION_ID}',
data=json.dumps({
'launchtype': 'SendNow',
'type': 'Standard',
'message': {'title': title, 'textMessage': text},
'broadcastContacts': {
'groupIds': site.get('groupIds', []),
'externalIds': site.get('externalIds', []),
},
}).encode(),
headers={'Authorization': f'Basic {CREDENTIALS}', 'Content-Type': 'application/json'},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
print(f"Everbridge notification {json.load(response)['id']}: {title}")
return True
except urllib.error.HTTPError as err:
print(f"Everbridge answered {err.code} for {site['id']}: {err.read()[:300]!r}", file=sys.stderr)
return False
# Outages covering each site, keyed poweroutage:<utilityId>:<outageId>.
# A failed request stops the run here, before any notification is launched.
current = {}
for i in range(0, len(SITES), 100):
batch = SITES[i : i + 100]
points = outages_at([{'lat': s['lat'], 'lon': s['lon']} for s in batch])
for site, point in zip(batch, points): # same order as the request
names = {u['utilityId']: u['name'] for u in point['utilities']}
for outage in point['outages']:
utility = names.get(outage['utilityId']) or f"Utility {outage['utilityId']}"
key = f"poweroutage:{outage['utilityId']}:{outage['outageId']}"
current.setdefault(site['id'], {})[key] = (outage, utility)
by_id = {site['id']: site for site in SITES}
notified = json.loads(STATE_FILE.read_text()) if STATE_FILE.exists() else {}
try:
for site_id, outages in current.items():
if site_id in notified: # still in an outage: no second message
notified[site_id] = sorted(outages)
continue
site = by_id[site_id]
lines = []
for outage, utility in outages.values():
out = 'an unreported number of' if outage['customersOut'] is None else f"{outage['customersOut']:,}"
lines.append(
f"{utility}: {out} customers out, cause: {outage['cause'] or 'not reported'}, "
f"estimated restoration (UTC): {outage['estimatedRestorationAt'] or 'not given'}."
)
text = f"The utility reports a power outage covering {site['name']}. " + ' '.join(lines)
if launch(site, f"Power outage at {site['name']}", text):
notified[site_id] = sorted(outages)
for site_id in [s for s in notified if s not in current]:
site = by_id.get(site_id)
if site is None: # removed from the sites file
del notified[site_id]
elif launch(site, f"Power outage no longer reported at {site['name']}",
f"The utility no longer reports an outage covering {site['name']}."):
del notified[site_id]
finally:
STATE_FILE.write_text(json.dumps(notified, indent=2))
print(f'{len(current)} site(s) in an outage; {len(notified)} notified') Step 6: Know what each notification carries
This is the whole request body the poller sends to POST /notifications/{organizationId}, matching Everbridge's Title and Message example. customersOut, cause and estimatedRestorationAt can be empty when the utility doesn't report them. Everbridge's API description marks broadcastSettings as required when no notification template is used, though its own example leaves it out: if a launch returns 400 about delivery paths or sender details, add broadcastSettings as described in the tips. Keep site names short if your contacts receive notifications by SMS.
Everbridge field value
launchtype SendNow
type Standard
message.title Power outage at <site name>, then
Power outage no longer reported at <site name>
message.textMessage The utility reports a power outage covering <site name>.
<utility name>: <customersOut> customers out, cause: <cause>,
estimated restoration (UTC): <estimatedRestorationAt>.
One sentence per outage covering the site
broadcastContacts.groupIds groupIds from the sites file
broadcastContacts.externalIds externalIds from the sites file
broadcastSettings not sent (see the tips) Step 7: Run it every 15 minutes
Put the API key and the Everbridge credentials in an environment file that only the job's account can read, with every value in single quotes: the shell reads the file, so an unquoted &, ; or backtick in a password breaks the run, and an unquoted $, backslash or double quote changes the password Everbridge receives. Run the poller from that account's crontab. cron mails anything the poller writes to stderr, such as a refused launch or a failed check, to MAILTO, so set it to a mailbox someone reads. Every 15 minutes is enough for most sites. The data updates every minute, so for the latest answers run it every 1 or 2 minutes (* * * * * or */2 * * * *). The first run notifies every site that is already inside an outage, so point the sites file at a test group before you go live.
# /opt/poweroutage/everbridge.env: owned by the account that runs the job, chmod 600.
# Put every value in single quotes, as below; write a single quote inside a value as '\''.
POWEROUTAGE_API_KEY='...'
EVERBRIDGE_API='https://api.everbridge.net/rest'
EVERBRIDGE_ORGANIZATION_ID='...'
EVERBRIDGE_USERNAME='poweroutage-api'
EVERBRIDGE_PASSWORD='...'
SITES_FILE='/opt/poweroutage/everbridge-sites.json'
STATE_FILE='/opt/poweroutage/everbridge-notified.json'
# crontab -e, as that account. Errors go to MAILTO, the run summary to the log.
# flock -n skips a run while the previous one still holds the lock.
MAILTO=ops-alerts@example.com
*/15 * * * * set -a && . /opt/poweroutage/everbridge.env && flock -n /opt/poweroutage/everbridge.lock /usr/bin/python3 /opt/poweroutage/poweroutage_everbridge.py >> /opt/poweroutage/poweroutage_everbridge.log Tips for Everbridge
- Start with one site whose
groupIdsholds a test group with only your own contact in it, and check the delivered message on every path before adding real recipients. - To choose delivery paths, sender email or caller ID, add
broadcastSettingsto the launch body withdeliverPathsids fromGET /contactPaths/{organizationId},senderEmailandsenderCallerInfos, as in Everbridge's Override Delivery Paths example. - Before going live, look at the
utilitieslist the check returns for each site. Where every utility showsprovidesGeospatialData: false, the poller can never launch for that site, because those utilities publish counts by area only; tell that site's Everbridge group to keep reporting outages the way they do today. - Back up
everbridge-notified.jsonwith the poller. Without it, the next run launches again to every group whose site is still dark, and the second notification for outages that ended in the meantime is never sent. - Give the poller its own PowerOutage.us key, restricted to the areas your sites are in, and its own Everbridge API user, so either can be revoked without touching your other integrations.
Used by
Related integrations
FAQ
Here are some commonly asked questions
Request API access
Tell us what you're building and we'll set you up with a trial key.