A modern, state-machine based automation platform for smart home systems. This platform provides a robust framework for defining, managing, and executing complex home automation scenarios using finite state machines (FSM). Built with Python 3.12+, it features strict schema validation via Pydantic, declarative configuration support through YAML, structured logging with Loguru, and comprehensive testing capabilities.
📚 Документация: docs/README.md · 🔧 Разработка: .ai/00_START_HERE.md · 📋 Конституция: CLAUDE.md
The v3.0.0 release brings major architectural improvements and powerful new features:
- FSM Engine v3 — Immutable state machines with enhanced transition logic, guard conditions, and timeout handling
- EventRouter Integration — Flexible sensor-to-FSM mapping with entity resolution from device configurations
- Behavior Composition — Multiple behaviors per device with priority-based conflict resolution (Critical: 20+, Night: 20, Standard: 10, Background: 1-9)
- Middleware System — Global rules applied automatically, including ManualLockoutMiddleware for preventing automation conflicts
- State Persistence — JSON-based storage with graceful shutdown and concurrent access handling
- Pydantic v2 Validation — Strict schema validation with automatic migrations for legacy manifests
- Clean
src/layout consolidation with proper entry points - CommandDispatcher with priority-based command resolution
- EventBus for async event distribution with end-to-end tracing
- Enhanced error isolation and exponential backoff for reconnection
See CHANGELOG.md for the complete list of changes and Migration Guide for migration instructions from v2.x.
flowchart TB
subgraph HomeAssistant["Home Assistant"]
HA[HA Entities<br/>binary_sensor.kitchen_motion]
PSS[Pyscript Service<br/>hass.services.async_call]
end
subgraph Adapter["HA Adapter Layer"]
HAA[HAAdapter<br/>Pyscript/WebSocket Mode]
end
subgraph Core["Smart Home Core"]
EB[EventBus<br/>Event Distribution]
FSM[FSM Engine<br/>State Machine Logic]
SCH[Scheduler<br/>Timer Management]
REG[Registry<br/>Guard/Action Functions]
end
subgraph Actions["Action Handlers"]
ACT[Action Functions<br/>turn_on_light, notify]
end
HA -->|state_changed| HAA
HAA -->|publish event| EB
EB -->|subscribe| FSM
FSM -->|trigger transition| SCH
FSM -->|execute action| ACT
ACT -->|call_service| HAA
HAA -->|async_call| PSS
PSS -->|update| HA
style HomeAssistant fill:#41bdf5,stroke:#333,stroke-width:2px,color:#fff
style Adapter fill:#f9a825,stroke:#333,stroke-width:2px
style Core fill:#7cb342,stroke:#333,stroke-width:2px,color:#fff
style Actions fill:#5c6bc0,stroke:#333,stroke-width:2px,color:#fff
core/— домен: FSM, guards, actions, events, persistence; не импортирует адаптеры и WebUI.adapters/— Home Assistant: WebSocket, команды, discovery.services/— устройства, синхронизация, сторож.webui/— FastAPI, ingress, доступ и ответы.app/— composition root:container.py,factories.py,lifecycle.py,house_services.py,context.py.
Границы проверяются tests/architecture: зависимости, модели манифеста и
бюджет размера модулей. Ошибки API — единый JSON-конверт с trace_id.
- Event Source: Home Assistant entity changes state (e.g., motion sensor triggers)
- Adapter Capture:
HAAdapter.on_state_change()receives the event, generatestrace_id - Event Publishing: EventBus distributes event to all subscribers with trace context
- FSM Processing: FSMEngine evaluates guards, executes actions, schedules timeouts
- Action Execution: Registered action functions call
HAAdapter.call_service() - Service Call: Adapter invokes HA service to control devices
- Immutable State Machines: Thread-safe FSM definitions using dataclasses
- Dual-Mode Adapter: Pyscript (recommended) or WebSocket connectivity
- End-to-End Tracing: Every event/action has a
trace_idfor debugging - Exponential Backoff: Automatic reconnection with backoff strategy
- Graceful Shutdown: Clean timer cancellation and resource cleanup
- Error Isolation: Service call failures don't crash the FSM engine
- Guard Conditions: Complex logic evaluation before transitions
- Timeout Transitions: Automatic state transitions after delay
- Debounce Protection: Prevents rapid state bouncing
- Composition Pattern: Multiple behaviors per device with priority-based conflict resolution
- Middleware System: Global rules applied to all commands automatically
- Migrations: Automatic manifest updates for backward compatibility
- FSM Visualization: Export FSM diagrams in Mermaid and Graphviz formats for documentation and debugging
- House Health Check: Sensor silence with per-sensor expectations, battery/warnings, command-not-applied detection,
/api/v1/problems,/problemspage and one anti-spam persistent notification in Home Assistant
| Guide | Description |
|---|---|
| Quick Start: Adding Devices | Bulk import 200+ devices from Home Assistant |
| FSM Visualization | Export FSM diagrams (Mermaid / Graphviz) |
| Example Manifest Configurations | Manifest examples: composition, middleware, migrations |
| How to Add New Behavior | Create and register your own behavior template |
| Understanding Trace IDs | End-to-end event debugging |
| Migration Guide v2.x → v3.0.0 | Migrate existing v2.x configurations |
| Local Development | Tests, linting, quality checks |
| HA Adapter Modes | Pyscript vs WebSocket connectivity |
| Advanced Features | Manual override, debounce, timeout chains |
| Monitoring and Debugging | Log configuration, trace search |
- docs/README.md — API reference and specifications
- .ai/00_START_HERE.md — development workflow for AI assistants
- CHANGELOG.md — release history
- CONTRIBUTING.md — contribution guidelines
smart-home-platform/
├── src/
│ ├── adapters/ # Integrations: HAAdapter (Pyscript/WebSocket), MockAdapter
│ ├── core/ # Business logic
│ │ ├── fsm/ # FSM engine, factory, Mermaid/Graphviz visualizer
│ │ ├── events/ # EventBus, EventRouter, device events
│ │ ├── commands/ # CommandDispatcher + middleware
│ │ ├── scheduling/ # Scheduler (timeout transitions)
│ │ ├── discovery/ # Device discovery from Home Assistant
│ │ ├── persistence/ # State storage, WebSocket event batcher
│ │ ├── guards/ # Guard functions (composite, numeric)
│ │ └── models/ # Domain models
│ ├── cli/ # CLI entry point (shp): bulk-import, export-fsm, shell
│ ├── services/ # Config watcher, backup, watchdog, FSM state bridge
│ ├── dashboard/ # Lovelace dashboard generator
│ ├── webui/ # Web UI: API + раздача статики фронтенда (FastAPI)
│ ├── features/ # YAML behavior templates (lighting, climate, ...)
│ ├── smart_home/ # Installable package (CLI entry point)
│ └── bootstrap.py # Platform initialization
├── tests/ # unit/ integration/ contract/ security/ validation/
├── instances/leonids_house/ # Example manifest instance
├── examples/ # Code examples (batcher, pyscript, sample plugin)
├── fsm_demo/ # Runnable demos (kitchen_demo, full_house_demo)
├── docs/ # Documentation (start at docs/README.md)
├── frontend/ # Web UI (Next.js, статическая сборка) — спека 017
├── deploy/ # Docker deployment for Home Assistant
├── .ai/ # AI context: workflow, rules, enhancements backlog
├── specs/ # Feature specifications (Spec Kit)
├── Makefile # Build/test/lint aliases
└── pyproject.toml # Dependencies and tool configuration
Пульт инженера: пять разделов — «Дом», «Автоматика», «Журнал», «Настройка»,
«Система» (спека specs/017-webui-redesign).
Фронтенд — Next.js со статической сборкой (frontend/), раздаётся тем же
процессом FastAPI с того же адреса: внешних CDN нет, интерфейс работает без
выхода в интернет. Старый серверный Jinja+HTMX интерфейс удалён.
make frontend-install # один раз: зависимости фронтенда
make frontend-build # сборка статики в frontend/out
make run-webui # http://localhost:8000 — интерфейс и API на одном порту
make frontend-test # юнит-тесты фронтенда (Vitest)
make test-browser # E2E (Playwright) — нужен собранный фронт и платформаFor detailed information on bulk device import, classification, and room assignment, see docs/api/device-import-spec.md.
This specification covers:
- Discovery Phase: How devices are scanned from Home Assistant
- Classification Phase: Automatic device type detection
- Room Assignment: Mapping devices to rooms
- FSM Application: Behavior template selection
- Safety Mechanisms: Backup, dry-run, validation
- User Workflows: CLI, Web UI, and programmatic APIs
The platform also uses GitHub spec kit to document major workflows — see the specs/ directory.
- Fork the repository
- Create a feature branch
- Write tests for new functionality
- Ensure all tests pass:
make test - Submit a pull request
This project is licensed under the Apache License 2.0 — see the LICENSE file for details.
- Home Assistant community for Pyscript
- Loguru for excellent logging
- Pydantic for schema validation