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.0.4

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.0.4
File Size Uploaded Provenance
aiotnse-2.0.4.tar.gz 19.7 kB With provenance Details

Built distribution (wheel)

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

Total release size: 35.0 kB

Release files / aiotnse-2.0.4.tar.gz

Download URL aiotnse-2.0.4.tar.gz
Size 19.7 kB
Tags Source
SHA-256 checksum
How to use checksums
c0893f7a9f60d32e5ecd1031e82c950356884fb489b2fd9de7f762fb98971b79
BLAKE2b-256 checksum
How to use checksums
8edad596bd8c0982f2e01185665fa93104b451ed17bcc9e2bbe686b2659719af
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

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 Jun 28, 2026.

Transparency log

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

Download URL aiotnse-2.0.4-py3-none-any.whl
Size 15.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d05d427636a217510ae77df3e3edbeb76679a91ecb40ec6efd5cf94e57a02c30
BLAKE2b-256 checksum
How to use checksums
319fe72204f99ef1f0d606d6de977bc7afd488621cbd8c04cc917c00e74caf4d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

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 Jun 28, 2026.

Transparency log

Security for aiotnse 2.0.4

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

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for aiotnse-2.0.4.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 Jun 28, 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.

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