Skip to main content

dtek-blackout-client

Async Python client for DTEK regional electricity-outage schedule sites

CI PyPI version Python versions codecov License: MIT


What is DTEK?

DTEK is Ukraine's largest private electricity company. Its regional distribution system operators (DSOs) maintain websites that publish planned and confirmed disconnection schedules across Ukraine.

Unlike YASNO, DTEK sites use a Yii2 AJAX endpoint (/ua/ajax) rather than a public REST API. This library implements the Yii2 CSRF and AJAX protocol used by the frontend (discon-schedule.js) to provide a clean, typed, universal aiohttp interface that works standalone and inside Home Assistant.

Supported regions

site_key English name Ukrainian name Coverage
kem DTEK Kyiv City Networks ДТЕК Київські електромережі Kyiv city
krem DTEK Kyiv Regional Networks ДТЕК Київські регіональні Kyiv oblast (Ukrainka, Obukhiv, Irpin, Fastiv...)
dnem DTEK Dnipro Networks ДТЕК Дніпровські електромережі Dnipro, Dnipropetrovsk oblast
dem DTEK Donetsk Networks ДТЕК Донецькі електромережі Government-controlled Donetsk oblast
oem DTEK Odesa Networks ДТЕК Одеські електромережі Odesa, Odesa oblast

Region names are also available programmatically via const.REGION_NAMES, REGION_NAMES_EN, and REGION_NAMES_UA.


Features

  • Universal & Home Assistant ready — built on standard aiohttp.ClientSession with support for injected sessions and session_factory
  • Automatic Yii2 CSRF bootstrap — extracts _csrf-dtek-* cookies from /ua/ajax, masks tokens per Yii2 Security::maskToken, and refreshes expired tokens on HTTP 400 without needing a headless browser
  • Typed — every model uses pydantic v2 with strict validation and frozen=True
  • DST-safe timezone handling — resolves schedule dates in Europe/Kyiv via zoneinfo + tzdata, accurately handling 23-hour and 25-hour daylight saving transitions
  • Tolerant house matching — matches building numbers across Cyrillic/Latin lookalike characters and spacing variations (e.g. 8a -> 8а)
  • Resilient — automatic retry with linear back-off on 5xx errors
  • Stub included — StubDtekClient enables offline development without network access
  • Tested — 99%+ test coverage with all HTTP calls mocked in CI

Installation

pip install dtek-blackout-client

Or with Poetry:

poetry add dtek-blackout-client

Optional Playwright fallback (only if browser-based HTML cookie harvesting is needed):

pip install "dtek-blackout-client[browser]"
playwright install chromium

Quick start

import asyncio
from dtek_client import DtekClient

async def main() -> None:
    async with DtekClient("krem") as client:
        # 1. Get all streets in a settlement
        streets = await client.get_streets("м. Українка")
        print([s.name for s in streets[:5]])

        # 2. Get all houses, groups, and schedules for a street in a single request
        response = await client.get_home_num("м. Українка", "вул. Юності")
        for house, entry in sorted(response.houses.items()):
            status = "excluded" if entry.is_excluded else entry.primary_group
            print(f"  {house:6s} -> {status}")

        # 3. Reuse the fetched response to look up group and today's schedule
        result = await client.get_group_by_address(
            city="м. Українка",
            street="вул. Юності",
            house_number="1",
            response=response,
        )
        print(result)

        slots = await client.get_today_schedule(
            city="м. Українка",
            street="вул. Юності",
            house_number="1",
            response=response,
        )
        print(slots)

asyncio.run(main())

How DTEK sites work (protocol overview)

1. POST https://www.dtek-krem.com.ua/ua/ajax (without X-CSRF-Token)
   -> HTTP 400 + Set-Cookie: _csrf-dtek-krem=<signed Yii2 token>
   -> Client extracts raw 32-byte token and computes masked X-CSRF-Token:
      base64url(mask + (mask XOR token))

2. POST /ua/ajax  (application/x-www-form-urlencoded + X-CSRF-Token)
   method=getStreets
   -> {"result": true, "streets": {"м. Українка": ["вул. Юності", ...]}}
      (on kem, "streets" is a flat list of Kyiv streets)

3. POST /ua/ajax  (with X-CSRF-Token)
   method=getHomeNum
   data[0][name]=city       & data[0][value]=м. Українка
   data[1][name]=street     & data[1][value]=вул. Юності
   data[2][name]=updateFact & data[2][value]=01.01.2000 00:00
   -> {
        "result": true,
        "data": {
          "10": {"sub_type_reason": ["GPV3.1"], "sub_type": "", ...},
          "10А": {"sub_type_reason": ["GPV3.2"], ...}
        },
        "preset": { ...static weekly plan... },
        "fact":   { ...confirmed daily schedule... }
      }

API reference

DtekClient(site_key, *, ajax_url, timeout, retry_attempts, retry_delay, session, session_factory, user_agent, csrf_token, discover_ajax_url)

Parameter Type Default Description
site_key str "kem" One of the keys in DTEK_SITES (kem, krem, dnem, dem, oem)
ajax_url str | None None Explicit AJAX URL (defaults to base_url + /ua/ajax)
timeout float 15 Per-request timeout in seconds
retry_attempts int 3 Number of attempts on 5xx errors
retry_delay float 1.0 Base seconds between retries (linear back-off)
session aiohttp.ClientSession | None None Inject an external aiohttp.ClientSession
session_factory Callable[[], aiohttp.ClientSession] | None None Factory used to recreate the session if closed by the host
user_agent str | None None Custom User-Agent header
csrf_token str | None None Optional pre-configured CSRF token
discover_ajax_url bool False Discover ajaxUrl from HTML <meta> tags before falling back to /ua/ajax

Methods

Method Returns Description
get_all_streets(*, refresh=False) dict[str, list[str]] Complete settlement-to-streets dictionary for the region (cached on client)
get_streets(city=None, *, refresh=False) list[StreetSuggestion] Streets in a city (or all streets when city=None / on kem, cached)
get_home_num(city, street) HomeNumResponse All houses, groups, and schedules for a street
get_group_by_address(city, street, house_number, *, response=None) AddressResult Disconnection group for a specific address
get_today_schedule(city, street, house_number, *, response=None) dict[str, SlotStatus] | None Today's slot map for one address
get_tomorrow_schedule(city, street, house_number, *, response=None) dict[str, SlotStatus] | None Tomorrow's confirmed schedule slot map
get_schedule_for_date(city, street, house_number, date, *, response=None) dict[str, SlotStatus] | None Confirmed schedule for a specific datetime.date
get_available_fact_dates(response) list[date] Calendar dates present in HomeNumResponse.fact (static method)

Key models

Model Purpose
HouseEntry One house: group_ids, primary_group, is_excluded, is_multi_group, has_current_outage, external_operator
HomeNumResponse Full AJAX response: houses, preset, fact, find_house(), schedule visibility flags
PresetSchedule Static weekly plan: groups[group_id].days[weekday].slots[tz_key]
FactSchedule Confirmed daily schedule: get_group_today(group_id), get_group_for_date(date, group_id)
FactDaySchedule One group on one day: slots, outage_slot_count, day_date
SlotStatus YES / NO / MAYBE / FIRST / SECOND / MFIRST / MSECOND / UNKNOWN
AddressResult site_key, city, street, house_number, group_id, group_display_name
StreetSuggestion name: str — one street from getStreets

Exceptions

DtekClientError                  <- base (status_code: int | None)
├── DtekConnectionError
│   ├── DtekTimeoutError         (timeout: float)
│   ├── DtekSSLError
│   └── DtekBlockedError         (WAF challenge page)
├── DtekAPIError
│   ├── DtekUnauthorizedError    (HTTP 401)
│   ├── DtekNotFoundError        (HTTP 404, path: str)
│   ├── DtekRateLimitError       (HTTP 429, retry_after: float | None)
│   └── DtekServerError          (HTTP 5xx)
├── DtekDataError                (JSON parse / validation failure, raw: object)
└── DtekSiteError                (unknown site_key / configuration error)

Usage inside Home Assistant

In manifest.json:

{
  "domain": "dtek_outage",
  "name": "DTEK Outage Schedule",
  "requirements": ["dtek-blackout-client==0.2.0"],
  "dependencies": []
}

In coordinator.py:

import aiohttp
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from dtek_client import DtekClient

def create_dtek_session() -> aiohttp.ClientSession:
    return async_create_clientsession(hass, cookie_jar=aiohttp.CookieJar())

client = DtekClient(
    config["site_key"],
    session=create_dtek_session(),
    session_factory=create_dtek_session,
)

response = await client.get_home_num(config["city"], config["street"])
result = await client.get_group_by_address(
    city=config["city"],
    street=config["street"],
    house_number=config["house_number"],
    response=response,
)
slots = await client.get_today_schedule(
    city=config["city"],
    street=config["street"],
    house_number=config["house_number"],
    response=response,
)

Development stub

from dtek_client.stub_client import StubDtekClient as DtekClient

async with DtekClient("krem") as client:
    result = await client.get_group_by_address("м. Українка", "вул. Юності", "1")
    slots  = await client.get_today_schedule("м. Українка", "вул. Юності", "1")

Development

See CONTRIBUTING.md for the developer guide.

git clone https://github.com/shed-crypto/dtek-blackout-client.git
cd dtek-blackout-client
poetry install
poetry run pytest

License

MIT 2026 Rachenko

Metadata

Release files for dtek-blackout-client 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dtek-blackout-client 0.2.0
File Size Uploaded Provenance Actions
dtek_blackout_client-0.2.0.tar.gz 27.5 kB With provenance Details for dtek_blackout_client-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dtek-blackout-client 0.2.0
File Interpreter ABI Platform Actions
dtek_blackout_client-0.2.0-py3-none-any.whl Python 3 none any Details for dtek_blackout_client-0.2.0-py3-none-any.whl

Total release size: 55.7 kB

Release files / dtek_blackout_client-0.2.0.tar.gz

Download URL dtek_blackout_client-0.2.0.tar.gz
Size 27.5 kB
Tags Source
SHA-256 checksum
How to use checksums
db00c0a428a4338c52bfac58b5006504ec884bd84529b0179f32a8c95919b062
BLAKE2b-256 checksum
How to use checksums
106b9693b17623e0410ca41a65c38b2c84dc1f7ccef1efb3fabf42b9dfa5bb3d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Release files / dtek_blackout_client-0.2.0-py3-none-any.whl

Download URL dtek_blackout_client-0.2.0-py3-none-any.whl
Size 28.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9fca0e9547ffa228ad12807ebf572affb43ae569cf1a94b346c48b666c1289be
BLAKE2b-256 checksum
How to use checksums
74aa2c32d272f932d9c5bbb255ab811a0977d822776d42ff30bee938aa40bcd9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Security for dtek-blackout-client 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for dtek_blackout_client-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page