Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1,386 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Smart Home FSM Platform

CI codecov Python Versions License Version

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

🎉 What's New in v3.0.0

The v3.0.0 release brings major architectural improvements and powerful new features:

Core Enhancements

  • 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

Architecture Improvements

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

🏗 Architecture Overview

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
Loading

Слои и composition root

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

Data Flow

  1. Event Source: Home Assistant entity changes state (e.g., motion sensor triggers)
  2. Adapter Capture: HAAdapter.on_state_change() receives the event, generates trace_id
  3. Event Publishing: EventBus distributes event to all subscribers with trace context
  4. FSM Processing: FSMEngine evaluates guards, executes actions, schedules timeouts
  5. Action Execution: Registered action functions call HAAdapter.call_service()
  6. Service Call: Adapter invokes HA service to control devices

✨ Key Features

  • 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_id for 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, /problems page and one anti-spam persistent notification in Home Assistant

📚 Documentation

Guides

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

References

📁 Project Structure

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) — нужен собранный фронт и платформа

📖 Specifications

Device Import Workflow

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.

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Write tests for new functionality
  4. Ensure all tests pass: make test
  5. Submit a pull request

License

This project is licensed under the Apache License 2.0 — see the LICENSE file for details.

🙏 Acknowledgments

  • Home Assistant community for Pyscript
  • Loguru for excellent logging
  • Pydantic for schema validation

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages