Power Outage Data in Kaseya and Datto

To get power outage data into Kaseya's Datto stack, send it to Autotask PSA: a Python poller sends your client sites' coordinates to the PowerOutage.us v2 REST API every 15 minutes and creates an Autotask ticket on the client's company when a utility outage covers one of their sites. Your dispatchers see the utility outage in the queue next to the device alerts it explains. The poller rewrites the ticket description when the cause or restoration estimate changes, and completes the ticket when the outage no longer covers the site. Datto RMM's API can read and resolve alerts but cannot raise one, which is why the outage lands in Autotask.

What you'll have

  • An Autotask ticket on the client's company and location, in your chosen queue, when a utility outage covers one of their sites.
  • One ticket per site and outage, keyed on the site plus utilityId and outageId, however many runs see it.
  • The description kept current with the cause and estimated restoration, and the ticket set to Complete with a resolution when power returns.
  • A few REST calls per outage, far inside the 10,000 requests per hour Autotask allows each database.

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 Autotask you need a security level with admin rights to Resources/Users (HR), so you can add an API user, and a queue for the outage tickets. The poller runs on any host with Python 3.9 or later and outbound HTTPS to poweroutage.us, webservices.autotask.net for the one-time zone lookup, and your zone's webservices<n>.autotask.net host.

Step 2: Add an API user

Go to Admin > Organization Settings & Users > Resources/Users (HR) > Resources/Users, then New > New API User. Set the security level to API User (system) Can't Read Costs (API-only), unless you have a narrower copy of it. Select Generate Key and Generate Secret for the Username (Key) and Password (Secret). Under API Tracking Identifier, choose Custom (Internal Integration), name the integration, and copy the Tracking Identifier it generates; it cannot be changed once you save. The poller sends the tracking identifier in the ApiIntegrationCode header, the API user's Username (Key) including its @domain in UserName, and the secret in Secret.

Step 3: Look up your zone and picklist values

Every Autotask database lives in one zone, and API calls must go to that zone's host. Ask zoneInformation once; it needs no credentials. Picklist values such as queues, priorities and statuses can differ between databases, so read them from the Tickets field list. The poller uses 1 for New and 5 for Complete; if your status list differs, change NEW_STATUS and COMPLETE_STATUS at the top of the script. The two query calls find the IDs for the sites file.

text
# 1. Your zone. No credentials needed; use the API user's Username (Key), with its @domain.
GET https://webservices.autotask.net/atservicesrest/v1.0/zoneInformation?user=<API user name>
    "url": "https://webservices<n>.autotask.net/atservicesrest/"   -> AUTOTASK_ZONE_URL

# 2. Picklist values, with the ApiIntegrationCode, UserName and Secret headers.
GET <AUTOTASK_ZONE_URL>v1.0/Tickets/entityInformation/fields
    "name": "queueID"   picklistValues -> the queue for outage tickets  -> AUTOTASK_QUEUE_ID
    "name": "priority"  picklistValues -> the priority to use           -> AUTOTASK_PRIORITY
    "name": "status"    picklistValues -> the poller expects New = 1, Complete = 5

# 3. Company and location IDs for the sites file.
POST <AUTOTASK_ZONE_URL>v1.0/Companies/query
    {"filter": [{"op": "contains", "field": "companyName", "value": "Acme"}]}  -> company_id
POST <AUTOTASK_ZONE_URL>v1.0/CompanyLocations/query
    {"filter": [{"op": "eq", "field": "companyID", "value": 29683501}]}        -> location_id

Step 4: List the client sites to watch

Autotask company locations hold a street address but no coordinates, so keep a CSV beside the poller with one row per site: a unique site label for the ticket title, coordinates in decimal degrees, the company_id, and the location_id (a CompanyLocations ID) if you want the ticket on that location. Geocode each address once. Removing a row completes its open outage tickets on the next run.

text
site,lat,lon,company_id,location_id
"Acme Dental, Plano",33.0198,-96.6989,29683501,88
"Acme Dental, Frisco",33.1507,-96.8236,29683501,91
"Brightline Logistics, Atlanta",33.749,-84.388,29683544,

Step 5: Write the poller

Save this as /opt/poweroutage/poweroutage_autotask.py; it uses only the Python standard library. It checks all sites first, 100 per request, and waits out a 429 for its Retry-After seconds, so a failed check ends the run before Autotask is touched. Each outage covering a site is keyed <site>|poweroutage:<utilityId>:<outageId>. A new key creates a ticket with POST, which returns its itemId; a changed cause or estimate rewrites the description with PATCH, which updates only the fields sent; a key that no longer appears gets PATCH with the Complete status and a resolution. The state file maps keys to ticket IDs and is written in a finally block. A ticket Autotask rejects is written to standard error and retried next run while the rest go ahead.

python
import csv
import json
import os
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path

os.umask(0o077)  # the state file is readable by this account only
API_KEY = os.environ['POWEROUTAGE_API_KEY']
TICKETS_URL = os.environ['AUTOTASK_ZONE_URL'].rstrip('/') + '/v1.0/Tickets'
AUTOTASK_HEADERS = {
    'ApiIntegrationCode': os.environ['AUTOTASK_INTEGRATION_CODE'],
    'UserName': os.environ['AUTOTASK_USERNAME'],
    'Secret': os.environ['AUTOTASK_SECRET'],
    'Content-Type': 'application/json',
}
QUEUE_ID = int(os.environ['AUTOTASK_QUEUE_ID'])
PRIORITY = int(os.environ['AUTOTASK_PRIORITY'])
NEW_STATUS = 1  # New
COMPLETE_STATUS = 5  # Complete
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,location_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 autotask(method, body):
    request = urllib.request.Request(
        TICKETS_URL, data=json.dumps(body).encode(), method=method, headers=AUTOTASK_HEADERS
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)


def open_ticket(site, description):
    due = datetime.now(timezone.utc) + timedelta(hours=4)
    ticket = {
        'companyID': int(site['company_id']),
        'title': f"Utility power outage at {site['site']}"[:255],
        'description': description,
        'status': NEW_STATUS,
        'priority': PRIORITY,
        'queueID': QUEUE_ID,
        'dueDateTime': due.strftime('%Y-%m-%dT%H:%M:%SZ'),
    }
    if site.get('location_id'):
        ticket['companyLocationID'] = int(site['location_id'])
    return autotask('POST', ticket)['itemId']


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 completed.
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)
        description = (
            f"PowerOutage.us reports a utility outage at {site['site']}. {details} "
            f"Customers out: {outage.get('customersOut') or 'not reported'}. Outage key: {key}"
        )
        try:
            if key not in state:
                state[key] = {'ticket': open_ticket(site, description), 'details': details}
            elif state[key]['details'] != details:  # cause or restoration estimate changed
                autotask('PATCH', {'id': state[key]['ticket'], 'description': description})
                state[key]['details'] = details
        except urllib.error.HTTPError as err:
            print(f'Autotask 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]:
        try:
            autotask('PATCH', {
                'id': state[key]['ticket'],
                'status': COMPLETE_STATUS,
                'resolution': 'PowerOutage.us no longer reports this outage at the site.',
            })
            del state[key]
        except urllib.error.HTTPError as err:
            print(f"Autotask answered {err.code} completing ticket {state[key]['ticket']}", file=sys.stderr)
            if err.code == 404:
                del state[key]  # the ticket was deleted in Autotask
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 goes on each ticket

These are the fields the poller writes. dueDateTime is required unless the ticket category sets a default due date and time, so the poller always sends one; change the 4 hours to suit your SLA. The REST API ignores the category's required-field settings except Queue is Required, so a ticket is created even if your category normally asks for more. cause, customersOut and estimatedRestorationAt can be empty, and the text then says so.

text
Tickets field        value
companyID            company_id from the sites file
companyLocationID    location_id from the sites file, when it is filled in
title                Utility power outage at <site> (255 characters at most)
description          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>
                     Rewritten when the cause or restoration estimate changes
status               1 (New) on creation; 5 (Complete) when power returns
priority             AUTOTASK_PRIORITY
queueID              AUTOTASK_QUEUE_ID
dueDateTime          4 hours after creation, in UTC
resolution           PowerOutage.us no longer reports this outage at the site.
                     Set with the Complete status

Step 7: Run it every 15 minutes

Keep the API user's credentials in an environment file that only the job's account can read, and run the poller from that account's crontab. The run summary goes to poweroutage_autotask.log and anything on standard error to autotask-errors.log. The shell reads the file, so keep every value in single quotes, as shown. flock -n keeps two runs from writing the state file at once. 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 creates tickets for any site already inside an outage.

bash
# /opt/poweroutage/autotask.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='...'
AUTOTASK_ZONE_URL='https://webservices<n>.autotask.net/atservicesrest/'
AUTOTASK_INTEGRATION_CODE='...'
AUTOTASK_USERNAME='...'
AUTOTASK_SECRET='...'
AUTOTASK_QUEUE_ID='...'
AUTOTASK_PRIORITY='...'
SITES_FILE='/opt/poweroutage/autotask-sites.csv'
STATE_FILE='/opt/poweroutage/autotask-tickets.json'

# crontab -e, as that account. The run summary goes to one log and errors to another.
# flock -n skips a run while the last one is still going.
*/15 * * * * set -a && . /opt/poweroutage/autotask.env && flock -n /opt/poweroutage/autotask.lock /usr/bin/python3 /opt/poweroutage/poweroutage_autotask.py >> /opt/poweroutage/poweroutage_autotask.log 2>> /opt/poweroutage/autotask-errors.log

Tips for Kaseya and Datto

  • Autotask workflow rules and notification settings apply to these tickets. Check that a new ticket in your outage queue does not email the client contact unless you want it to.
  • Without the state file the poller cannot tell which Autotask ticket belongs to which outage: a lost file means new tickets for outages still running and old ones never completed. Every description ends with its outage key, so a search for titles beginning "Utility power outage at" in your outage queue turns up the old ones.
  • Tickets are created only where an outage can be placed at the site. Utilities with providesGeospatialData: false in the utilities list publish area counts only, so sites they serve get no ticket; leave Datto RMM's offline monitoring on for them.
  • Autotask adds a delay to each request once a database passes half its hourly limit. The poller makes only a few calls per run, but other integrations share the same 10,000 requests per hour.
  • Have your monitoring alert when autotask-errors.log grows. A regenerated API secret, a deactivated queue or a tracking identifier Autotask has disabled otherwise shows up only as tickets that never appear.

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.