Power Outage Data in HaloPSA

To get power outage data into HaloPSA, run a Python poller every 15 minutes that sends your client sites' coordinates to the PowerOutage.us v2 REST API and logs a Halo ticket against the client and site when a utility outage covers it. The outage is on the service desk before the calls about dead Wi-Fi and offline servers start. The poller signs in with an API application's client ID and secret, adds a private action when the cause or restoration estimate changes, and sets your closed status once the outage no longer covers the site. It keeps a map of outage keys to ticket IDs, so a site gets one ticket per outage however many runs see it.

What you'll have

  • A ticket on the right client and site, with your outage ticket type, when a utility outage covers it, naming the utility, cause, customers out and estimated restoration.
  • One ticket per site and outage, keyed on the site plus utilityId and outageId.
  • Private actions when the cause or restoration estimate changes, and the ticket closed when power returns.
  • Client credentials only: no agent has to stay signed in for the poller to work.

What you need

An API key (request one with the form below) and these endpoints. Full details are in the API reference.

EndpointMethodUsed forPackage
/geojson/at-pointPOSTChecks up to 100 client sites per request and returns, in request order, the active outages covering each one and the utilities that serve it.Standard + Locations

Step 1: Check what you need

The poller relies on /geojson/at-point, which is in the Standard + Locations package. In Halo you need admin access to Configuration to add an API application, an agent account for the poller to act as, and a ticket type for outage tickets. The poller runs on any host with Python 3.9 or later and outbound HTTPS to poweroutage.us and your Halo address, such as yourcompany.halopsa.com.

Step 2: Add an API application

Go to Configuration > Integrations > HaloPSA API, select View Applications, then New. Set Authentication Method to Client ID and Secret (Services), Login Type to Agent, and Agent to Log In As to the poller's agent. Halo records tickets and actions as that agent and also applies the agent's own permissions, so it must be able to log and close tickets for your clients. On the Permissions tab, tick read:tickets and edit:tickets, save, and copy the client ID and secret. The scope the poller requests must name only permissions the application has, so set HALO_SCOPE to the ones you ticked, as listed on your instance's HaloPSA API page. Its API Details section shows your Authorisation Server, Resource Server and, on hosted instances, Tenant, and links to the API documentation for your own instance, which is the reference for every field below.

Step 3: Pick the ticket type and closed status

Choose or create a ticket type for outage tickets and note its ID, and the ID of the status that closes them. Make sure that ticket type asks for nothing at closure, such as a closure category or a resolution field, because the poller closes tickets with the status alone and Halo rejects a closure that is missing a mandatory field. Check the type's automatic emails too, so a new outage ticket does not email the client unless you want it to.

Step 4: List the client sites to watch

Keep the coordinates the poller checks in a CSV beside it, one row per client site: a unique site label for the ticket summary, latitude and longitude in decimal degrees, the Halo client_id, and the site_id when the ticket belongs on a particular site. Geocode each site's address once. Removing a row closes its open outage tickets on the next run.

text
site,lat,lon,client_id,site_id
"Acme Dental, Plano",33.0198,-96.6989,12,40
"Acme Dental, Frisco",33.1507,-96.8236,12,44
"Brightline Logistics, Atlanta",33.749,-84.388,27,

Step 5: Write the poller

Save this as /opt/poweroutage/poweroutage_halopsa.py; it needs only the Python standard library. It checks every site first, 100 per request, and waits out a 429 for its Retry-After seconds, so a failed check stops the run before Halo is touched. It then gets a token from /auth/token with the client credentials grant and HALO_SCOPE. Halo's Tickets and Actions resources take a JSON array, and a record with an id updates while one without creates, so the poller posts one record at a time and reads the new ticket's id from the answer. Outages are keyed <site>|poweroutage:<utilityId>:<outageId>; the state file maps each key to its ticket and is written in a finally block. A ticket Halo rejects is written to standard error and retried next run.

python
import csv
import json
import os
import sys
import time
import urllib.error
import urllib.parse
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']
HALO_URL = os.environ['HALO_URL'].rstrip('/')  # https://yourcompany.halopsa.com
TICKET_TYPE_ID = int(os.environ['HALO_TICKET_TYPE_ID'])
CLOSED_STATUS_ID = int(os.environ['HALO_CLOSED_STATUS_ID'])
STATE_FILE = Path(os.environ['STATE_FILE'])  # open tickets, kept between runs
with open(os.environ['SITES_FILE'], newline='') as file:
    SITES = list(csv.DictReader(file))  # site,lat,lon,client_id,site_id


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 halo_token():
    form = urllib.parse.urlencode({
        'grant_type': 'client_credentials',
        'client_id': os.environ['HALO_CLIENT_ID'],
        'client_secret': os.environ['HALO_CLIENT_SECRET'],
        'scope': os.environ['HALO_SCOPE'],  # only permissions the application has
    }).encode()
    tenant = os.environ.get('HALO_TENANT')  # only if the HaloPSA API page shows a Tenant
    url = f'{HALO_URL}/auth/token' + (f'?tenant={urllib.parse.quote(tenant)}' if tenant else '')
    with urllib.request.urlopen(url, data=form, timeout=30) as response:
        return json.load(response)['access_token']


def halo(resource, record):
    """Halo takes an array; a record with an id updates, one without creates."""
    request = urllib.request.Request(
        f'{HALO_URL}/api/{resource}',
        data=json.dumps([record]).encode(),
        headers={'Authorization': f'Bearer {TOKEN}', 'Content-Type': 'application/json'},
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
    return result[0] if isinstance(result, list) else result


def add_note(ticket_id, text):
    halo('Actions', {'ticket_id': ticket_id, 'note': text, 'hiddenfromuser': True})


def outage_details(outage, utility):
    return (
        f"{utility}. Cause: {outage.get('cause') or 'not reported'}. "
        f"Estimated restoration (UTC): {outage.get('estimatedRestorationAt') or 'not given'}."
    )


# Every outage covering a site, keyed '<site>|poweroutage:<utilityId>:<outageId>'.
# A failed request stops the run here, before any ticket is opened or closed.
current = {}
for i in range(0, len(SITES), 100):
    batch = SITES[i : i + 100]
    points = outages_at([{'lat': float(s['lat']), 'lon': float(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']:
            key = f"{site['site']}|poweroutage:{outage['utilityId']}:{outage['outageId']}"
            utility = names.get(outage['utilityId']) or f"Utility {outage['utilityId']}"
            current[key] = (site, outage, utility)

TOKEN = halo_token()
state = json.loads(STATE_FILE.read_text()) if STATE_FILE.exists() else {}
try:
    for key, (site, outage, utility) in current.items():
        details = outage_details(outage, utility)
        customers = f"Customers out: {outage.get('customersOut') or 'not reported'}."
        try:
            if key not in state:
                ticket = {
                    'summary': f"Utility power outage at {site['site']}",
                    'details': f"PowerOutage.us reports a utility outage at {site['site']}. "
                    f'{details} {customers} Outage key: {key}',
                    'client_id': int(site['client_id']),
                    'tickettype_id': TICKET_TYPE_ID,
                }
                if site.get('site_id'):
                    ticket['site_id'] = int(site['site_id'])
                state[key] = {'ticket': halo('Tickets', ticket)['id'], 'details': details}
            elif state[key]['details'] != details:  # cause or restoration estimate changed
                add_note(state[key]['ticket'], f'PowerOutage.us update. {details} {customers}')
                state[key]['details'] = details
        except urllib.error.HTTPError as err:
            print(f'Halo answered {err.code} for {key}: {err.read()[:300]!r}', file=sys.stderr)
    for key in [k for k in state if k not in current]:
        entry = state[key]
        try:
            if not entry.get('closing_noted'):  # a retried close doesn't repeat the note
                add_note(entry['ticket'], 'PowerOutage.us no longer reports this outage at the site.')
                entry['closing_noted'] = True
            halo('Tickets', {'id': entry['ticket'], 'status_id': CLOSED_STATUS_ID})
            del state[key]
        except urllib.error.HTTPError as err:
            print(f"Halo answered {err.code} closing ticket {entry['ticket']}", file=sys.stderr)
            if err.code == 404:
                del state[key]  # the ticket was deleted in Halo
finally:
    STATE_FILE.write_text(json.dumps(state, indent=2))
print(f'{len(current)} site outage(s); {len(state)} ticket(s) open')

Step 6: Know what lands on each ticket

These are all the fields the poller sends. hiddenfromuser keeps every action off the end user's view of the ticket. cause, customersOut and estimatedRestorationAt can be missing, and the text then says so. To set a priority, team or agent, add the matching fields from your instance's API documentation where the poller builds the ticket.

text
Tickets field     value
summary           Utility power outage at <site>
details           PowerOutage.us reports a utility outage at <site>. <utility name>.
                  Cause: <cause>. Estimated restoration (UTC): <estimatedRestorationAt>.
                  Customers out: <customersOut>. Outage key: <site>|poweroutage:<utilityId>:<outageId>
client_id         client_id from the sites file
site_id           site_id from the sites file, when it is filled in
tickettype_id     HALO_TICKET_TYPE_ID
status_id         the ticket type's default on creation; HALO_CLOSED_STATUS_ID when power returns

Actions field     value
ticket_id         the ticket the poller opened
note              PowerOutage.us update. <utility>. Cause: ... Estimated restoration ...
                  Customers out: ... Added when the cause or restoration estimate changes.
                  Then, once, just before closing: PowerOutage.us no longer reports this
                  outage at the site.
hiddenfromuser    true

Step 7: Run it every 15 minutes

Keep the client secret in an environment file only the job's account can read, and schedule the poller from that account's crontab. The run summary goes to poweroutage_halopsa.log and errors to halopsa-errors.log. The shell reads the file, so keep every value in single quotes, as shown. flock -n stops overlapping runs from writing the state file together. 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 logs tickets for every site already inside an outage.

bash
# /opt/poweroutage/halopsa.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='...'
HALO_URL='https://yourcompany.halopsa.com'
HALO_CLIENT_ID='...'
HALO_CLIENT_SECRET='...'
HALO_SCOPE='read:tickets edit:tickets'   # only permissions the application has
HALO_TENANT=''                              # the Tenant from API Details, if shown
HALO_TICKET_TYPE_ID='...'
HALO_CLOSED_STATUS_ID='...'
SITES_FILE='/opt/poweroutage/halopsa-sites.csv'
STATE_FILE='/opt/poweroutage/halopsa-tickets.json'

# crontab -e, as that account. Summary to one log, errors to another.
# flock -n skips a run if the previous one is still going.
*/15 * * * * set -a && . /opt/poweroutage/halopsa.env && flock -n /opt/poweroutage/halopsa.lock /usr/bin/python3 /opt/poweroutage/poweroutage_halopsa.py >> /opt/poweroutage/poweroutage_halopsa.log 2>> /opt/poweroutage/halopsa-errors.log

Tips for HaloPSA

  • If your Halo authorisation server is not <your Halo address>/auth, which the HaloPSA API page shows, change the token URL in halo_token to match it.
  • The poller finds its Halo tickets again only through the state file. If you lose it, outages already in progress get a second ticket and the first ones stay open; their details end with the outage key, so a search on the summary "Utility power outage at" lists them for closing.
  • Halo gets no ticket for a site whose utilities report outages only as area counts; they show providesGeospatialData: false in the result's utilities. Keep your RMM's offline alerts for those sites.
  • Alert on halopsa-errors.log growing. An invalid_scope answer after someone changes the application's permissions, a regenerated client secret or a ticket type that now refuses closure otherwise shows up only as missing or open tickets.
  • Use a separate PowerOutage.us key for the poller, restricted to the areas your clients are in, so it doesn't share a rate limit with your other tools.

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.