Help us shape the future of Go! Take the 2026 Go Developer Survey

dtekkrem

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 12 Imported by: 0

README

dtek-krem-shutdowns

Go-модуль для отримання інформації про відключення світла за адресою з сайту ДТЕК Київські регіональні електромережі:

  • поточне відключення за адресою: причина, час початку й орієнтовний час відновлення;
  • черги (групи) графіка, до яких належить будинок;
  • погодинний графік черги на сьогодні й завтра та готові інтервали відключень.

Вимоги

Сайт захищений Imperva Incapsula, яка не пропускає звичайні HTTP-клієнти. Тому модуль відкриває сторінку в headless Google Chrome (або Chromium) через chromedp. Chrome має бути встановлений на машині, де працює програма.

Встановлення

go get github.com/shatylos/dtek-krem-shutdowns

Використання

client := dtekkrem.NewClient()
defer client.Close()

res, err := client.Lookup(ctx, dtekkrem.Address{
	City:   "м. Бориспіль",
	Street: "вул. Київський Шлях",
	House:  "6",
})
if err != nil {
	return err
}

if res.Outage != nil {
	fmt.Printf("Світла немає до %s: %s\n", res.Outage.End.Format("15:04"), res.Outage.Reason)
}
for _, group := range res.Groups {
	fmt.Println(group.Name) // "Черга 2.2"
	for _, in := range group.Outages() {
		fmt.Printf("  %s – %s (можливо: %t)\n", in.Start.Format("02.01 15:04"), in.End.Format("02.01 15:04"), in.Maybe)
	}
}

Місто, вулицю та будинок треба писати так само, як на сайті: м. Бориспіль, с. Горенка, вул. Київський Шлях. Повний список міст і вулиць повертає client.Streets(ctx). Регістр і пробіли в номері будинку не важливі. Для адрес без номерів будинків House залишають порожнім.

Якщо адресу не знайдено, Lookup повертає ErrUnknownCity, ErrUnknownStreet або ErrUnknownHouse.

Будинок, який живиться від кількох ліній, належить до кількох черг. Квартири в ньому можуть відключатися за різними графіками, тому Result.Groups містить усі черги будинку.

Обмеження

  • Кожен запит відкриває сторінку в новій вкладці, це займає приблизно 4–5 секунд. Браузер запускається під час першого запиту й працює до Close.
  • Якщо звертатися до сайту часто (десятки завантажень за пів години), Incapsula на якийсь час блокує запити, і Lookup повертає ErrBlocked. Опитуйте сайт не частіше ніж раз на кілька хвилин.
  • Модуль повторює запити, які робить форма на сайті. Якщо ДТЕК змінить сайт, модуль може перестати працювати.

Documentation

Overview

Package dtekkrem looks up power outages and outage schedules for an address served by DTEK Kyiv Regional Electric Networks (https://www.dtek-krem.com.ua/ua/shutdowns).

The site is protected by Imperva Incapsula, which rejects plain HTTP clients, so the package drives a headless Google Chrome (or Chromium) via the DevTools protocol. Chrome must be installed on the host.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnknownCity   = errors.New("dtekkrem: city not found")
	ErrUnknownStreet = errors.New("dtekkrem: street not found")
	ErrUnknownHouse  = errors.New("dtekkrem: house not found")
	// ErrBlocked is returned when the site's bot protection rejects the request. It happens
	// when the site is queried too often (dozens of page loads within half an hour); retry later.
	ErrBlocked = errors.New("dtekkrem: request was blocked by the site's bot protection")
)

Functions

This section is empty.

Types

type Address

type Address struct {
	City   string
	Street string
	House  string
}

Address of a house as spelled on the site, e.g. {"м. Бориспіль", "вул. Київський Шлях", "6"}. House may be empty for addresses the site lists without house numbers.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client looks up outages on the DTEK KREM site. The browser is started on the first request and kept running until Close; each request uses its own tab, so a Client is safe for concurrent use.

func NewClient

func NewClient(opts ...Option) *Client

func (*Client) Close

func (c *Client) Close()

Close stops the browser. The Client can be reused afterwards: the next request starts a new one.

func (*Client) Lookup

func (c *Client) Lookup(ctx context.Context, addr Address) (*Result, error)

Lookup returns the current outage and today's/tomorrow's schedules for the address. City, street and house must be spelled exactly as on the site (see Streets).

func (*Client) Streets

func (c *Client) Streets(ctx context.Context) (map[string][]string, error)

Streets returns all cities served by DTEK KREM, each mapped to its streets, spelled as the site expects them.

type Day

type Day struct {
	Date time.Time // midnight in Europe/Kyiv
	// Hours[h] is the status of the hour starting at h:00.
	Hours [24]Status
}

type Group

type Group struct {
	ID   string // e.g. "GPV2.2"
	Name string // e.g. "Черга 2.2"
	// Days holds the published schedules, today first; tomorrow's appears once DTEK publishes it.
	Days []Day
}

func (Group) Outages

func (g Group) Outages() []Interval

Outages merges the group's schedule into outage intervals, joining those that continue past midnight.

type Interval

type Interval struct {
	Start time.Time
	End   time.Time
	// Maybe marks a possible outage rather than a scheduled one.
	Maybe bool
}

Interval is a period without power.

type Option

type Option func(*Client)

func WithAllocatorOptions

func WithAllocatorOptions(opts ...chromedp.ExecAllocatorOption) Option

WithAllocatorOptions appends chromedp allocator options, e.g. chromedp.ExecPath to point at a non-default Chrome binary or chromedp.Flag("headless", false) for debugging.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout limits the duration of a single request (page load included). Default is one minute.

type Outage

type Outage struct {
	// Planned is true for planned repair works; otherwise Reason tells the kind of outage,
	// e.g. "Стабілізаційне відключення (Згідно графіку погодинних відключень)".
	Planned bool
	Reason  string
	Start   time.Time
	// End is the expected restoration time.
	End time.Time
}

func (*Outage) IsEmergency

func (o *Outage) IsEmergency() bool

IsEmergency reports an emergency outage, during which the group schedules do not apply.

type Result

type Result struct {
	Address Address
	// Outage is the outage currently reported for the address, nil when there is none.
	Outage *Outage
	// Groups are the outage schedule groups (черги) the house belongs to. A house fed by
	// several lines has several groups, and its apartments may follow different schedules.
	Groups []Group
	// UpdatedAt is when the site last refreshed the current outage information.
	UpdatedAt time.Time
	// ScheduleUpdatedAt is when the group schedules were last published.
	ScheduleUpdatedAt time.Time
}

type Status

type Status string
const (
	StatusOn              Status = "yes"
	StatusOff             Status = "no"
	StatusMaybe           Status = "maybe"
	StatusOffFirstHalf    Status = "first"   // off for the first 30 minutes of the hour
	StatusOffSecondHalf   Status = "second"  // off for the second 30 minutes of the hour
	StatusMaybeFirstHalf  Status = "mfirst"  // possibly off for the first 30 minutes
	StatusMaybeSecondHalf Status = "msecond" // possibly off for the second 30 minutes
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL