Power Outage Data in ConnectWise PSA

To get power outage data into ConnectWise PSA (formerly Manage), run a Python poller every 15 minutes that sends your client sites' coordinates to the PowerOutage.us v2 REST API and opens a service ticket on the client's company when a utility outage covers one of their sites. Your techs see that the utility has the site dark before they start working through offline-device alerts. The poller signs in as an API member, adds an internal note when the utility changes the cause or restoration estimate, and moves the ticket to a closed status once the outage no longer covers the site. It remembers which ticket belongs to which outage, so each site gets one ticket per outage however many runs see it.

What you'll have

  • A service ticket on the client's company, your chosen board and the affected site when a utility outage covers it, with the utility, cause, customers out and estimated restoration in the description.
  • One ticket per site and outage, keyed on the site plus utilityId and outageId, with the outage key also in the ticket's externalXRef.
  • Internal notes when the cause or restoration estimate changes, and the ticket moved to your closed status when the outage clears.
  • 100 client sites checked per PowerOutage.us request, so a few hundred sites take a handful of requests every 15 minutes.

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 depends on /geojson/at-point, which is in the Standard + Locations package. In ConnectWise PSA you need rights to create security roles and API members, and a service board for the outage tickets. Every REST request must also carry a clientId, which you create once on the ConnectWise Developer Network (developer.connectwise.com); it identifies the integration, not a member. The poller runs on any host with Python 3.9 or later that can reach poweroutage.us and your PSA's API host over HTTPS. Cloud instances use api-na.myconnectwise.net, api-eu.myconnectwise.net or api-au.myconnectwise.net; on-premises instances use your own server's name.

Step 2: Create an API member and keys

Go to System > Security Roles and add a role for the poller. Under Service Desk, give it Add, Edit and Inquire on Service Tickets and Close Service Ticket, at level All; under Companies, Inquire on Company Maintenance; and under System, Inquire on Table Setup, which the board and status lookups need. Permission names can vary between versions, so if a lookup or a close answers 403, check this role first. Then go to System > Members, open the API Members tab and add an API member with that role. On the member's API Keys tab, generate a key pair and copy the private key at once: ConnectWise shows it only when it is created. The poller signs every request with HTTP Basic auth, sending your company ID (the one you sign in with) and the public key joined by + as the user name, and the private key as the password, plus the clientId header.

Step 3: Look up the board, status and company IDs

The poller works with record IDs, not names. Fill in the environment file from the last step, leaving the board and status IDs for now, then run these lookups once on the poller's host and note the id of each record. The cw function hands the keys to curl on standard input, and --data-urlencode encodes the conditions filters. Choose a closed status whose email template sends nothing to the client contact, so a cleared outage closes quietly.

bash
set -a && . /opt/poweroutage/connectwise.env && set +a
cw() {
  # the keys reach curl on standard input, so they never show in the process list
  printf 'user = "%s+%s:%s"\nheader = "clientId: %s"\n' \
    "$CW_COMPANY_ID" "$CW_PUBLIC_KEY" "$CW_PRIVATE_KEY" "$CW_CLIENT_ID" |
    curl -sSG -K - "$CW_API_URL/$1" "${@:2}"
  echo
}

# The board for outage tickets: its id goes in CW_BOARD_ID
cw service/boards --data-urlencode 'conditions=name="Utility outages"'
# That board's statuses (7 is the board id): one with "closedStatus": true -> CW_CLOSED_STATUS_ID
cw service/boards/7/statuses
# A client company: its id goes in the company_id column
cw company/companies --data-urlencode 'conditions=identifier="AcmeDental"'
# That company's sites (250 is its id), with addresses but no coordinates -> site_id column
cw company/companies/250/sites

Step 4: List the client sites to watch

Company sites in ConnectWise PSA hold a street address but no latitude or longitude, so the poller reads coordinates from a CSV that you keep next to it. Add one row per site with a unique site label (it appears in the ticket summary), coordinates in decimal degrees, the company's company_id, and the site_id if you want the ticket on that site rather than the company's default. Geocode each address once, or read the coordinates off a map. Removing a row closes that site's open outage tickets on the next run.

text
site,lat,lon,company_id,site_id
"Acme Dental, Plano",33.0198,-96.6989,250,312
"Acme Dental, Frisco",33.1507,-96.8236,250,318
"Brightline Logistics, Atlanta",33.749,-84.388,412,

Step 5: Write the poller

Save this as /opt/poweroutage/poweroutage_connectwise.py; it uses only the Python standard library. It checks every site first, 100 per request, and waits out a 429 for the Retry-After seconds (three tries at most), so a failed check stops the run before any ticket changes. Each outage covering a site is keyed <site>|poweroutage:<utilityId>:<outageId>. A new key gets a ticket; a key whose cause or restoration estimate changed gets an internal note; a key that no longer appears gets a closing note and the closed status. The state file maps each key to its ticket ID and is written in a finally block, so tickets created before an error are remembered. If ConnectWise rejects a ticket, the error goes to standard error and the run carries on with the rest; a close that fails is retried next run without a second closing note.

python
import base64
import csv
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']
CW_API = os.environ['CW_API_URL']  # https://api-na.myconnectwise.net/v4_6_release/apis/3.0
CW_HEADERS = {
    'Authorization': 'Basic ' + base64.b64encode(
        f"{os.environ['CW_COMPANY_ID']}+{os.environ['CW_PUBLIC_KEY']}:{os.environ['CW_PRIVATE_KEY']}".encode()
    ).decode(),
    'clientId': os.environ['CW_CLIENT_ID'],
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}
BOARD_ID = int(os.environ['CW_BOARD_ID'])
CLOSED_STATUS_ID = int(os.environ['CW_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,company_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 connectwise(method, path, body):
    request = urllib.request.Request(
        f'{CW_API}/{path}', data=json.dumps(body).encode(), method=method, headers=CW_HEADERS
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)


def open_ticket(site, key, text):
    ticket = {
        'summary': f"Utility power outage at {site['site']}"[:100],
        'board': {'id': BOARD_ID},
        'company': {'id': int(site['company_id'])},
        'initialDescription': text,
        'externalXRef': key.split('|')[1],  # poweroutage:<utilityId>:<outageId>
    }
    if site.get('site_id'):
        ticket['site'] = {'id': int(site['site_id'])}
    return connectwise('POST', 'service/tickets', ticket)['id']


def add_note(ticket_id, text):
    connectwise('POST', f'service/tickets/{ticket_id}/notes', {'text': text, 'internalAnalysisFlag': 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)

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:
                text = f"PowerOutage.us reports a utility outage at {site['site']}. {details} {customers}"
                state[key] = {'ticket': open_ticket(site, key, f'{text} Outage key: {key}'), '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'ConnectWise 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
            status = [{'op': 'replace', 'path': 'status', 'value': {'id': CLOSED_STATUS_ID}}]
            connectwise('PATCH', f"service/tickets/{entry['ticket']}", status)
            del state[key]
        except urllib.error.HTTPError as err:
            print(f"ConnectWise answered {err.code} closing ticket {entry['ticket']}", file=sys.stderr)
            if err.code == 404:
                del state[key]  # the ticket was deleted in ConnectWise
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 sets. cause, customersOut and estimatedRestorationAt are left out by some utilities, and the text then says "not reported" or "not given". To set a priority, type or team, add priority, type or team references with your own IDs where open_ticket builds the ticket.

text
service ticket field    value
summary                 Utility power outage at <site> (100 characters at most)
board                   CW_BOARD_ID
company                 company_id from the sites file
site                    site_id from the sites file, when it is filled in
initialDescription      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>
externalXRef            poweroutage:<utilityId>:<outageId>
status                  the board's default on creation; CW_CLOSED_STATUS_ID when power returns

note (internal)         PowerOutage.us update. <utility>. Cause: ... Estimated restoration ...
                        Customers out: ... Added when the cause or restoration estimate changes
note (internal)         PowerOutage.us no longer reports this outage at the site.
                        Added once, just before the ticket moves to CW_CLOSED_STATUS_ID

Step 7: Run it every 15 minutes

Keep the keys in an environment file that only the job's account can read, and run the poller from that account's crontab. Cron mails anything the poller writes to standard error to MAILTO, while the run summary goes to the log. The shell reads the file, so keep every value in single quotes, as shown. flock -n stops two runs from writing the state file at the same time. 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 opens tickets for every site already inside an outage.

bash
# /opt/poweroutage/connectwise.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='...'
CW_API_URL='https://api-na.myconnectwise.net/v4_6_release/apis/3.0'
CW_COMPANY_ID='...'
CW_PUBLIC_KEY='...'
CW_PRIVATE_KEY='...'
CW_CLIENT_ID='...'
CW_BOARD_ID='...'
CW_CLOSED_STATUS_ID='...'
SITES_FILE='/opt/poweroutage/connectwise-sites.csv'
STATE_FILE='/opt/poweroutage/connectwise-tickets.json'

# crontab -e, as that account. The run summary goes to the log and errors to MAILTO.
# flock -n skips a run while the last one still holds the lock.
MAILTO=alerts@yourmsp.example
*/15 * * * * set -a && . /opt/poweroutage/connectwise.env && flock -n /opt/poweroutage/connectwise.lock /usr/bin/python3 /opt/poweroutage/poweroutage_connectwise.py >> /opt/poweroutage/poweroutage_connectwise.log

Tips for ConnectWise PSA

  • Workflow rules, status email templates and board auto-responses apply to these tickets like any other. Check the board's settings before the first run so that a utility outage doesn't email the client unless you want it to.
  • The state file is the only record of which ConnectWise ticket belongs to which outage, so back it up with the host. If it is lost, the next run opens fresh tickets for outages still in progress and the old ones stay open; each holds its outage key in externalXRef, so the conditions externalXRef like "poweroutage:%" and closedFlag = false list them for closing by hand.
  • Some utilities publish outage counts by area only, and the utilities list marks them with providesGeospatialData: false. A client site served only by such a utility never gets a ticket, so keep your device-offline monitoring for it.
  • Utilities sometimes report overlapping outages, so one site can get two tickets with different outage keys. Merge them in ConnectWise if you prefer one; the poller still closes each when its outage clears.
  • Cron mail is what tells you the poller has a problem: a 403 from a missing permission or a rejected ticket arrives the first time it happens. If the host has no mail relay, send standard error to a file your monitoring watches instead.
  • Give the poller its own PowerOutage.us key, restricted to the areas your clients are in, so other tools don't share its rate limit and a leaked key exposes less.

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.