Skip to main content

aioTNSE

PyPI Python License: MIT CI

Асинхронная Python-библиотека для работы с мобильным API ТНС-Энерго (российская энергосбытовая компания).

Используется как бэкенд для интеграции hass-tnse в Home Assistant.

Возможности

  • Аутентификация по email/паролю с JWT-токенами
  • Автоматическое обновление токенов (access token → refresh token → re-login)
  • Получение списка лицевых счетов, баланса, показаний счётчиков
  • Передача показаний счётчиков
  • Получение квитанций (PDF) и истории операций
  • Полная поддержка всех регионов ТНС-Энерго
  • CLI для работы с API из командной строки

Установка

pip install aiotnse

Быстрый старт

import asyncio

import aiohttp

from aiotnse import SimpleTNSEAuth, TNSEApi, async_get_regions


async def main() -> None:
    async with aiohttp.ClientSession() as session:
        # Получить список регионов (авторизация не требуется)
        regions = await async_get_regions(session)
        for r in regions:
            print(f"{r['name']} ({r['code']})")

        # Авторизация
        auth = SimpleTNSEAuth(
            session, region="rostov", email="user@example.com", password="password"
        )
        await auth.async_login()

        api = TNSEApi(auth)

        # Лицевые счета
        accounts = await api.async_get_accounts()
        account_number = accounts[0]["number"]

        # Баланс
        balance = await api.async_get_balance(account_number)
        print(f"К оплате: {balance['sumToPay']} руб.")

        # Счётчики
        counters = await api.async_get_counters(account_number)
        for counter in counters:
            print(f"Счётчик {counter['counterId']}: {counter['lastReadings']}")


asyncio.run(main())

Авторизация

Логин по email/паролю

auth = SimpleTNSEAuth(
    session, region="rostov", email="user@example.com", password="password"
)
await auth.async_login()

Восстановление сессии из сохранённых токенов

async_get_access_token() автоматически обновляет токены или выполняет повторную аутентификацию при необходимости:

from datetime import datetime


def on_token_update(token_data: dict) -> None:
    """Вызывается после логина или обновления токена — сохраните токены."""
    save_to_storage(token_data)


auth = SimpleTNSEAuth(
    session,
    region="rostov",
    email="user@example.com",
    password="password",
    access_token="saved_access_token",
    refresh_token="saved_refresh_token",
    access_token_expires=datetime.fromisoformat("2026-06-09T19:42:16"),
    refresh_token_expires=datetime.fromisoformat("2026-10-09T19:42:16"),
    token_update_callback=on_token_update,
)
# Вызов async_login() не нужен — токены обновятся автоматически при первом API-запросе

Автоматическое управление токенами

async_get_access_token() реализует трёхуровневую логику:

  1. Возвращает кэшированный токен, если он ещё действителен
  2. Обновляет через async_refresh_token(), если access token истёк
  3. Выполняет повторный логин через async_login(), если оба токена истекли

asyncio.Lock предотвращает параллельное обновление токенов.

API-методы

Публичные (без авторизации)

Функция Описание
async_get_regions(session) Список доступных регионов
async_check_version(session, region) Проверка совместимости версии приложения

Лицевые счета

Метод Описание
async_get_accounts() Список лицевых счетов пользователя
async_get_account_info(account_id) Детальная информация по ID
async_get_information(account) Общая информация по номеру ЛС
async_get_main_page_debt_info() Информация о задолженности

Счётчики и показания

Метод Описание
async_get_counters(account) Счётчики для лицевого счёта
async_get_counter_readings(counter_id, account) История показаний счётчика
async_send_readings(account, row_id, readings) Передача показаний

Платежи и баланс

Метод Описание
async_get_balance(account) Баланс и начисления
async_get_history(account, year, month) История операций за месяц

Квитанции

Метод Описание
async_get_invoices(account, year) Список квитанций за год
async_get_invoice_file(account, date) Квитанция в формате PDF (base64)
async_get_invoice_settings(account) Настройки email-доставки квитанций

Пользователь

Метод Описание
async_get_user_info() Информация о текущем пользователе

Подробная документация API: docs/API.md

Исключения

TNSEApiError                    — базовая ошибка API
├── TNSEAuthError               — ошибка авторизации
│   ├── TNSETokenExpiredError   — токен истёк
│   └── TNSETokenRefreshError   — ошибка обновления токена
├── RegionNotFound              — регион не найден
├── InvalidAccountNumber        — неверный номер ЛС
└── RequiredApiParamNotFound    — отсутствует обязательный параметр

CLI

Библиотека включает CLI для работы с API из командной строки:

# Список регионов (авторизация не требуется)
aiotnse-cli --regions

# Лицевые счета
aiotnse-cli --email user@example.com --password pass --region rostov --accounts

# Баланс
aiotnse-cli --email user@example.com --password pass --region rostov --balance 610000000001

# Счётчики
aiotnse-cli --email user@example.com --password pass --region rostov --counters 610000000001

# Передача показаний
aiotnse-cli --email user@example.com --password pass --region rostov send 610000000001 2000001 2690 1023

# Подробный вывод (отладка)
aiotnse-cli -vvv --email user@example.com --password pass --region rostov --accounts

Если --region не указан, CLI предложит выбрать регион интерактивно.

Таймауты

aiotnse не задаёт таймауты для запросов. Управление таймаутами — ответственность вызывающего кода:

import asyncio

async with asyncio.timeout(10):
    data = await api.async_get_counters(account)

Разработка

# Клонирование
git clone https://github.com/lizardsystems/aiotnse.git
cd aiotnse

# Установка зависимостей для тестирования
pip install -e ".[test]"

# Запуск тестов
pytest tests/ -v

Ссылки

Metadata

Release files for aiotnse 2.1.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 aiotnse 2.1.0
File Size Uploaded Provenance Actions
aiotnse-2.1.0.tar.gz 20.5 kB With provenance Details for aiotnse-2.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aiotnse 2.1.0
File Interpreter ABI Platform Actions
aiotnse-2.1.0-py3-none-any.whl Python 3 none any Details for aiotnse-2.1.0-py3-none-any.whl

Total release size: 36.2 kB

Release files / aiotnse-2.1.0.tar.gz

Download URL aiotnse-2.1.0.tar.gz
Size 20.5 kB
Tags Source
SHA-256 checksum
How to use checksums
4f06b4ab8e8c9b6e932e1aaa0a24ef48dc40970f15f70b3c7567d07872f0eb3a
BLAKE2b-256 checksum
How to use checksums
e41fb4e89150b0e9ca19d9aec6b34052af6d40744cb41b8f43fb6a38cbdb67dc
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 18, 2026.

Transparency log

Release files / aiotnse-2.1.0-py3-none-any.whl

Download URL aiotnse-2.1.0-py3-none-any.whl
Size 15.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
70cb7b2f3d0bcd14781d574c81ce64f765bbeec0a9631d8d49623385b61a96cb
BLAKE2b-256 checksum
How to use checksums
851ecfee475d0982ecc8a4e9c08c25198f7c559ee34fca66ab6da842b0ae3769
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 18, 2026.

Transparency log

Security for aiotnse 2.1.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 aiotnse-2.1.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 18, 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