Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Kamio v1.0.0b1

Python Version Version License MQTT Tests

Kamio — декларативный асинхронный IoT-фреймворк для Python на базе MQTT. Описывайте устройства классами, подключайте оборудование драйверами, автоматизируйте правилами.

Возможности

  • Декларативные устройства — поля state, telemetry, event, config через аннотации Python
  • Драйверы — GPIO, Serial, Telnet, HTTP, UDP, Modbus TCP, Mock (latency/failure simulation)
  • MQTT v5 — надёжная коммуникация, авто-реконнект, обратная совместимость с legacy-топиками
  • Асинхронность — полностью asyncio, никаких блокирующих вызовов в event loop
  • Правила автоматизации — реакция на изменения полей и периодические интервалы
  • Plugin System — изолированные плагины с автоматическим cleanup через PluginContext
  • Hot-Reload — перезагрузка правил и устройств без остановки приложения
  • Custom MQTT Nodes — произвольные MQTT-узлы с маршрутизацией сообщений
  • Home Assistant Discovery — lazy-init, активируется только при вызове enable_ha_discovery()
  • Конфигурация — JSON-файлы + переменные окружения Kamio_*

Установка

pip install kamio

Требования

  • Python 3.9+
  • MQTT брокер (рекомендуется Mosquitto)
# Ubuntu/Debian
sudo apt-get install mosquitto mosquitto-clients
# macOS
brew install mosquitto
# Windows: https://mosquitto.org/download/

Дополнительные зависимости

pip install kamio[gpio]           # GPIO (gpiod)
pip install kamio[serial]          # Serial (pyserial)
pip install kamio[http]            # HTTP (aiohttp)
pip install kamio[all-drivers]   # все внешние зависимости драйверов (gpiod, pyserial, aiohttp)
pip install kamio[dev]            # форматирование, типизация
pip install kamio[test]           # pytest, pytest-asyncio

UDPDriver, TelnetDriver и ModbusTCPDriver используют только стандартную библиотеку Python и доступны без extras.

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

import asyncio
from kamio import KamioApp, Device, command, state, telemetry

app = KamioApp(mqtt_broker="mqtt://localhost:1883")


class SmartLight(Device):
    power:      bool  = state(default=False, writable=True)
    brightness: int   = state(default=100, min=0, max=255, writable=True)
    energy_wh:  float = telemetry(default=0.0, unit="Wh")

    @command
    async def toggle(self):
        self.power = not self.power
        return {"power": self.power}


class MotionSensor(Device):
    motion_detected: bool = state(default=False, writable=True)


@app.rule(device=MotionSensor, fields=["motion_detected"])
async def on_motion(event, app):
    if event.data["motion_detected"]:
        light = app.devices.get("living_room")
        if light:
            await light.handle_state({"power": True, "brightness": 200})


async def main():
    # Можно передать драйвер: Serial/Telnet/HTTP/UDP/Modbus TCP
    # await app.add_device("living_room", SmartLight, driver=TelnetDriver("10.0.0.10"))
    await app.add_device("living_room", SmartLight)
    await app.add_device("hall_sensor", MotionSensor)
    await app.start()


if __name__ == "__main__":
    asyncio.run(main())
    # ИЛИ блокирующий запуск с обработкой SIGINT/SIGTERM:
    # app.run()

Примеры использования

Плагины

from kamio.plugins.builtin.metrics_plugin import MetricsPlugin

metrics = await app.load_plugin(MetricsPlugin)
print(metrics.get_counter("device_state_changed"))

Hot-reload правил

app.watch_directory("rules/", "*.py", app.hot_reload.make_rules_handler())
app.enable_hot_reload()

Home Assistant Discovery

app.enable_ha_discovery(prefix="homeassistant")
# HADiscovery создаётся только здесь, не при инициализации KamioApp

Кастомный MQTT-узел

from kamio.core.custom_nodes import CustomNode

class BridgeNode(CustomNode):
    async def handle_message(self, topic: str, payload: bytes):
        print(f"Bridge received: {topic}")

app.register_custom_node("bridge", BridgeNode(app.mqtt_client, "bridge"))

Конфигурация через файл

app = KamioApp(config_path="config.json")
{
  "mqtt_broker": "mqtt://broker.local:1883",
  "log_level": "INFO"
}

Или через переменные окружения:

Kamio_MQTT_BROKER=mqtt://broker.local:1883
Kamio_LOG_LEVEL=DEBUG

Структура тестов

tests/
  unit/         # изолированные тесты компонентов
  stress/       # тесты под нагрузкой
pytest                          # все тесты
pytest tests/unit/              # только unit
pytest tests/stress/            # только stress

Документация

  • API — справочник по всем классам и методам
  • Архитектура — детальный обзор архитектуры v1.0.0b1

Лицензия

Apache-2.0 — см. файл LICENSE

Metadata

Release files for kamio 1.0.0b1

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

Source distribution (sdist)

Source distribution for kamio 1.0.0b1
File Size Uploaded Provenance Actions
kamio-1.0.0b1.tar.gz 69.7 kB Without provenance Details for kamio-1.0.0b1.tar.gz

Built distribution (wheel)

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

Total release size: 154.8 kB

Release files / kamio-1.0.0b1.tar.gz

Download URL kamio-1.0.0b1.tar.gz
Size 69.7 kB
Tags Source
SHA-256 checksum
How to use checksums
3d97dd3c366b264d6205454c1e5b0e335aadef466c37e0f1506bfcde88968b34
BLAKE2b-256 checksum
How to use checksums
b14c83a67196240bbcc0ef82f8fcf5741d8ec0a07cf5c44badd64e357c6f9663
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.14

Release files / kamio-1.0.0b1-py3-none-any.whl

Download URL kamio-1.0.0b1-py3-none-any.whl
Size 85.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1d3541850b9f77ee73b4bcecd3e31486547a5d7c8180893a0736eef0a149dcb9
BLAKE2b-256 checksum
How to use checksums
0e308f8b07a583a5ec5d339643b9f5e6c9ca7c6440089720d75df4862224ed52
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.14

Security for kamio 1.0.0b1

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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