Compare commits
2
Commits
938700cf86
...
28ca67f42c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28ca67f42c | ||
|
|
8c5ebe2967 |
@@ -1,31 +1,32 @@
|
||||
# Home Automation Platform
|
||||
# Платформа домашней автоматизации
|
||||
|
||||
A microservice-based home automation platform, built as a portfolio project
|
||||
demonstrating Go (concurrency, message queues, MQTT), PHP/Laravel (API,
|
||||
authorization), and polyglot persistence (PostgreSQL, ClickHouse, Redis).
|
||||
Pet-проект на микросервисной архитектуре для портфолио, демонстрирующий Go
|
||||
(конкурентность, очереди сообщений, MQTT), PHP/Laravel (API, авторизация)
|
||||
и работу с разными БД по назначению (PostgreSQL, ClickHouse, Redis).
|
||||
|
||||
**This is not a "growbox project."** A growbox is the first implemented
|
||||
**zone** with a first set of **device types** (light, pump, fan, temperature
|
||||
sensor). The core system — device management, telemetry, automation rules,
|
||||
users, notifications — operates purely on the abstractions *zone*, *device*,
|
||||
*device type*, *sensor reading*, *command*, *rule*. Nothing growbox-specific
|
||||
is hardcoded in the core: adding a "living room" zone with a "smart plug"
|
||||
device type should require zero changes to service code, only new rows in
|
||||
**Это не «проект гроубокса».** Гроубокс — первая реализованная **зона**
|
||||
с первым набором **типов устройств** (свет, полив, вентиляция, датчик
|
||||
температуры). Ядро системы — управление устройствами, телеметрия, правила
|
||||
автоматизации, пользователи, уведомления — оперирует исключительно
|
||||
абстракциями *зона*, *устройство*, *тип устройства*, *показание датчика*,
|
||||
*команда*, *правило*. Ничего специфичного для гроубокса не зашито в ядре:
|
||||
добавление зоны «гостиная» с типом устройства «умная розетка» не должно
|
||||
требовать изменений в коде сервисов — только новые строки в
|
||||
`device_types` / `zones` / `devices`.
|
||||
|
||||
## Architecture
|
||||
## Архитектура
|
||||
|
||||
```
|
||||
ESP32 (or emulator)
|
||||
ESP32 (или эмулятор)
|
||||
│ MQTT
|
||||
▼
|
||||
ingest-service (Go) ──► ClickHouse (raw telemetry)
|
||||
ingest-service (Go) ──► ClickHouse (сырая телеметрия)
|
||||
│
|
||||
▼ RabbitMQ ("new reading" event)
|
||||
rule-engine-service (Go) ──► PostgreSQL (rules, cached)
|
||||
│ gRPC (on rule match)
|
||||
▼ RabbitMQ (событие "новое показание")
|
||||
rule-engine-service (Go) ──► PostgreSQL (правила, кэшируются)
|
||||
│ gRPC (при срабатывании правила)
|
||||
▼
|
||||
device-control-service (Go) ──► MQTT (command) ──► device
|
||||
device-control-service (Go) ──► MQTT (команда) ──► устройство
|
||||
│
|
||||
▼
|
||||
Redis (device shadow: desired/reported state, status, last_seen)
|
||||
@@ -33,68 +34,69 @@ Redis (device shadow: desired/reported state, status, last_seen)
|
||||
Laravel API (PHP) ──► PostgreSQL / ClickHouse / Redis
|
||||
│ gRPC / HTTP
|
||||
▼
|
||||
device-control-service (manual commands from the UI)
|
||||
device-control-service (ручные команды из UI)
|
||||
```
|
||||
|
||||
## Stack
|
||||
## Стек
|
||||
|
||||
| Concern | Technology |
|
||||
| Назначение | Технология |
|
||||
|---|---|
|
||||
| Device firmware / emulator | Go (`services/esp32-emulator`) |
|
||||
| Device ↔ server protocol | MQTT (Mosquitto) |
|
||||
| Telemetry / commands / rules backend | Go |
|
||||
| Business logic / API / dashboard | PHP (Laravel) |
|
||||
| Users, zones, devices, rules | PostgreSQL |
|
||||
| Telemetry (time-series) | ClickHouse |
|
||||
| Real-time device state | Redis (Device Shadow pattern) |
|
||||
| Inter-service async events | RabbitMQ |
|
||||
| Inter-service sync calls | gRPC / Protobuf |
|
||||
| Metrics (stage 2.5) | Prometheus + Grafana |
|
||||
| Containerization | Docker Compose |
|
||||
| Web frontend (stage 3) | Vue.js + Inertia.js |
|
||||
| Mobile app (stage 3) | Flutter |
|
||||
| Notifications | Telegram Bot (MVP) / Firebase Cloud Messaging (later) |
|
||||
| Прошивка устройства / эмулятор | Go (`services/esp32-emulator`) |
|
||||
| Протокол устройство ↔ сервер | MQTT (Mosquitto) |
|
||||
| Backend телеметрии / команд / правил | Go |
|
||||
| Бизнес-логика / API / дашборд | PHP (Laravel) |
|
||||
| Пользователи, зоны, устройства, правила | PostgreSQL |
|
||||
| Телеметрия (time-series) | ClickHouse |
|
||||
| Состояние устройств в реальном времени | Redis (паттерн Device Shadow) |
|
||||
| Асинхронные события между сервисами | RabbitMQ |
|
||||
| Синхронные вызовы между сервисами | gRPC / Protobuf |
|
||||
| Метрики (этап 2.5) | Prometheus + Grafana |
|
||||
| Контейнеризация | Docker Compose |
|
||||
| Веб-фронтенд (этап 3) | Vue.js + Inertia.js |
|
||||
| Мобильное приложение (этап 3) | Flutter |
|
||||
| Уведомления | Telegram-бот (MVP) / Firebase Cloud Messaging (позже) |
|
||||
|
||||
## Layout
|
||||
## Структура репозитория
|
||||
|
||||
```
|
||||
services/
|
||||
ingest-service/ Go — MQTT → ClickHouse + RabbitMQ
|
||||
device-control-service/ Go — gRPC + MQTT + Redis device shadow
|
||||
rule-engine-service/ Go — RabbitMQ consumer + rule evaluation
|
||||
health-check-service/ Go — offline detection ticker
|
||||
esp32-emulator/ Go — fake device for local dev
|
||||
laravel-app/ PHP/Laravel — API, auth, dashboard (stage 2)
|
||||
proto/ Shared gRPC contracts (device_control.proto)
|
||||
rule-engine-service/ Go — консьюмер RabbitMQ + оценка правил
|
||||
health-check-service/ Go — тикер обнаружения офлайн-устройств
|
||||
esp32-emulator/ Go — фейковое устройство для локальной разработки
|
||||
laravel-app/ PHP/Laravel — API, авторизация, дашборд (этап 2)
|
||||
proto/ Общие gRPC-контракты (device_control.proto)
|
||||
migrations/
|
||||
postgres/ users, zones, devices, device_types, automation_rules
|
||||
clickhouse/ telemetry table
|
||||
configs/mosquitto/ MQTT broker config
|
||||
monitoring/ Prometheus + Grafana config (stage 2.5)
|
||||
clickhouse/ таблица telemetry
|
||||
configs/mosquitto/ Конфиг MQTT-брокера
|
||||
monitoring/ Конфиги Prometheus + Grafana (этап 2.5)
|
||||
```
|
||||
|
||||
Each `services/*/README.md` describes that service's responsibility and
|
||||
explicit non-responsibilities before any code exists there.
|
||||
Каждый `services/*/README.md` описывает зону ответственности сервиса и явно
|
||||
то, что в неё не входит, — ещё до того, как там появится код.
|
||||
|
||||
## Build stages
|
||||
## Этапы разработки
|
||||
|
||||
1. **Go services** — ingest, rule-engine, device-control, ESP32 emulator.
|
||||
2. **Laravel** — auth (Sanctum, owner/viewer), CRUD for zones/devices/rules,
|
||||
Blade dashboard, manual device control. MVP is considered done here.
|
||||
3. *(optional, high value)* **Observability** — Prometheus metrics from the
|
||||
Go services, a Grafana dashboard or two.
|
||||
4. **Extensions** (no rush) — Telegram notifications, Vue.js/Inertia
|
||||
frontend, Flutter app, real ESP32 hardware.
|
||||
1. **Go-сервисы** — ingest, rule-engine, device-control, эмулятор ESP32.
|
||||
2. **Laravel** — авторизация (Sanctum, owner/viewer), CRUD для зон/устройств/
|
||||
правил, Blade-дашборд, ручное управление устройствами. MVP считается
|
||||
готовым на этом этапе.
|
||||
3. *(опционально, но сильно повышает ценность)* **Observability** — метрики
|
||||
Prometheus с Go-сервисов, один-два дашборда в Grafana.
|
||||
4. **Расширения** (не спеша) — Telegram-уведомления, фронтенд на
|
||||
Vue.js/Inertia, приложение на Flutter, подключение реального ESP32.
|
||||
|
||||
## Running locally
|
||||
## Запуск локально
|
||||
|
||||
Infrastructure only for now (app services are added to `docker-compose.yml`
|
||||
as they're implemented):
|
||||
Пока только инфраструктура (сервисы добавляются в `docker-compose.yml` по
|
||||
мере реализации):
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
This brings up Mosquitto (`1883`), PostgreSQL (`5432`), ClickHouse (`8123`/`9000`),
|
||||
Redis (`6379`), and RabbitMQ (`5672`, management UI on `15672`).
|
||||
Поднимутся Mosquitto (`1883`), PostgreSQL (`5432`), ClickHouse (`8123`/`9000`),
|
||||
Redis (`6379`) и RabbitMQ (`5672`, веб-интерфейс управления на `15672`).
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
# device-control-service (Go)
|
||||
|
||||
Status: not implemented yet.
|
||||
Статус: пока не реализован.
|
||||
|
||||
Responsibility:
|
||||
- Expose a gRPC API (see `proto/device_control.proto`) for issuing commands
|
||||
to devices — called by Laravel (manual control) and rule-engine-service
|
||||
(rule-triggered actions).
|
||||
- Publish the command to the device's MQTT topic (`devices/{device_id}/commands`)
|
||||
and listen for acknowledgements (`devices/{device_id}/ack`).
|
||||
- Maintain the Device Shadow pattern in Redis: `desired_state` (what the user
|
||||
wants) vs `reported_state` (what the device confirmed), plus `status` and
|
||||
`last_seen`.
|
||||
- Owns the health-check loop (or delegates to health-check-service): a ticker
|
||||
goroutine that flips a device to `offline` when `last_seen` exceeds a
|
||||
timeout, and emits an event for notification-service.
|
||||
Зона ответственности:
|
||||
- Предоставляет gRPC API (см. `proto/device_control.proto`) для отправки
|
||||
команд устройствам — вызывается из Laravel (ручное управление) и из
|
||||
rule-engine-service (действия по срабатыванию правил).
|
||||
- Публикует команду в MQTT-топик устройства (`devices/{device_id}/commands`)
|
||||
и слушает подтверждения (`devices/{device_id}/ack`).
|
||||
- Поддерживает паттерн Device Shadow в Redis: `desired_state` (чего хочет
|
||||
пользователь) против `reported_state` (что подтвердило устройство), плюс
|
||||
`status` и `last_seen`.
|
||||
- Владеет циклом health-check (либо делегирует его health-check-service):
|
||||
горутина-тикер переводит устройство в `offline`, когда `last_seen`
|
||||
превышает таймаут, и генерирует событие для notification-service.
|
||||
|
||||
Not this service's job: deciding *when* to send a command based on sensor
|
||||
thresholds — that's rule-engine-service's logic. This service only executes
|
||||
and tracks state for whatever command it's given.
|
||||
Не входит в зону ответственности: решение о том, *когда* отправлять команду
|
||||
на основе показаний датчиков — это логика rule-engine-service. Этот сервис
|
||||
только исполняет команды и отслеживает состояние для той команды, что ему дали.
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# esp32-emulator (Go)
|
||||
|
||||
Status: not implemented yet.
|
||||
Статус: пока не реализован.
|
||||
|
||||
Responsibility:
|
||||
- Stand in for real ESP32 hardware during MVP development.
|
||||
- Publish plausible telemetry (temperature/humidity/etc.) to
|
||||
`devices/{device_id}/telemetry` over MQTT on an interval.
|
||||
- Subscribe to `devices/{device_id}/commands` and reply on
|
||||
`devices/{device_id}/ack`, so device-control-service has something real
|
||||
to talk to.
|
||||
Зона ответственности:
|
||||
- Заменяет реальное железо ESP32 на время разработки MVP.
|
||||
- Публикует правдоподобную телеметрию (температура/влажность/и т.д.) в
|
||||
`devices/{device_id}/telemetry` по MQTT с заданным интервалом.
|
||||
- Подписывается на `devices/{device_id}/commands` и отвечает в
|
||||
`devices/{device_id}/ack`, чтобы device-control-service было с кем
|
||||
по-настоящему взаимодействовать.
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
# health-check-service (Go)
|
||||
|
||||
Status: not implemented yet. May start as a goroutine inside
|
||||
device-control-service and get split out into its own container later —
|
||||
kept as a separate directory from day one so the split is a non-event.
|
||||
Статус: пока не реализован. Может начаться как горутина внутри
|
||||
device-control-service и позже выделиться в отдельный контейнер — поэтому
|
||||
с первого дня держим отдельную директорию, чтобы это разделение прошло
|
||||
безболезненно.
|
||||
|
||||
Responsibility:
|
||||
- Periodically (ticker) check `last_seen` for every device in Redis.
|
||||
- When a device exceeds the offline timeout, flip its `status` to `offline`
|
||||
and publish an event for notification-service.
|
||||
- Good place to demonstrate goroutines + graceful shutdown in Go.
|
||||
Зона ответственности:
|
||||
- Периодически (по тикеру) проверяет `last_seen` каждого устройства в Redis.
|
||||
- Когда устройство превышает таймаут офлайна, переводит его `status` в
|
||||
`offline` и публикует событие для notification-service.
|
||||
- Хороший повод продемонстрировать горутины + graceful shutdown в Go.
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
# ingest-service (Go)
|
||||
|
||||
Status: implemented (MVP).
|
||||
Статус: реализован (MVP).
|
||||
|
||||
Responsibility:
|
||||
- Subscribe to MQTT topics `devices/{device_id}/telemetry`.
|
||||
- Validate/parse payload (device_id, sensor_type, value, timestamp).
|
||||
- Batch-write raw readings into ClickHouse `telemetry` table.
|
||||
- Publish a "new reading" event to RabbitMQ for rule-engine-service.
|
||||
Зона ответственности:
|
||||
- Подписка на MQTT-топики `devices/{device_id}/telemetry`.
|
||||
- Валидация/парсинг payload (device_id, sensor_type, value, timestamp).
|
||||
- Батч-запись сырых показаний в таблицу ClickHouse `telemetry`.
|
||||
- Публикация события «новое показание» в RabbitMQ для rule-engine-service.
|
||||
|
||||
Not this service's job: interpreting what a sensor reading *means* (thresholds,
|
||||
actions) — that belongs to rule-engine-service. This service only ingests and
|
||||
stores.
|
||||
Не входит в зону ответственности: интерпретация того, что *означает*
|
||||
показание датчика (пороги, действия) — это задача rule-engine-service. Этот
|
||||
сервис только принимает и сохраняет данные.
|
||||
|
||||
Note on `zone_id`: the telemetry payload carries `zone_id` directly (the
|
||||
publishing device/emulator is configured with its own zone), rather than
|
||||
ingest-service looking it up from PostgreSQL. This keeps ingest-service's
|
||||
dependencies limited to MQTT/ClickHouse/RabbitMQ, matching the architecture
|
||||
diagram in the root README. A real fleet where devices don't know their own
|
||||
zone would need a device-registry lookup (cached, like rule-engine caches
|
||||
rules) — that's a natural follow-up, not implemented yet.
|
||||
Про `zone_id`: payload телеметрии несёт `zone_id` напрямую (публикующее
|
||||
устройство/эмулятор само знает свою зону), а не ingest-service ищет его в
|
||||
PostgreSQL. Это удерживает зависимости ingest-service в рамках
|
||||
MQTT/ClickHouse/RabbitMQ, как и на диаграмме архитектуры в корневом README.
|
||||
Для реального парка устройств, которые не будут знать свою зону,
|
||||
понадобится lookup через реестр устройств (с кэшированием, как rule-engine
|
||||
кэширует правила) — это естественное развитие, пока не реализовано.
|
||||
|
||||
## Running
|
||||
## Запуск
|
||||
|
||||
```bash
|
||||
cd services/ingest-service
|
||||
@@ -28,7 +28,8 @@ go test ./...
|
||||
go build ./cmd/ingest-service
|
||||
```
|
||||
|
||||
Configuration is env-var driven (see the ingest-service section of the
|
||||
repo-root `.env.example`). Via `docker compose up ingest-service` it talks to
|
||||
the `mosquitto`/`clickhouse`/`rabbitmq` containers directly; connect from a
|
||||
local `go run` by exporting `MQTT_HOST=localhost`, `CLICKHOUSE_HOST=localhost`, etc.
|
||||
Конфигурация читается из переменных окружения (см. секцию ingest-service в
|
||||
корневом `.env.example`). Через `docker compose up ingest-service` сервис
|
||||
обращается напрямую к контейнерам `mosquitto`/`clickhouse`/`rabbitmq`; для
|
||||
локального запуска через `go run` выставь `MQTT_HOST=localhost`,
|
||||
`CLICKHOUSE_HOST=localhost` и т.д.
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
# rule-engine-service (Go)
|
||||
|
||||
Status: not implemented yet.
|
||||
Статус: пока не реализован.
|
||||
|
||||
Responsibility:
|
||||
- Consume "new reading" events from RabbitMQ (async — delivery reliability
|
||||
matters more than latency here).
|
||||
- Load active `automation_rules` for the relevant zone/device from PostgreSQL,
|
||||
caching in memory/Redis to avoid a DB round-trip per event.
|
||||
- Evaluate rule conditions generically: `sensor_type X operator value` against
|
||||
the reading — no hardcoded sensor/device names, everything comes from the
|
||||
`automation_rules` row.
|
||||
- On match: call device-control-service over gRPC (needs a fast pass/fail
|
||||
result) and publish an event to notification-service over RabbitMQ (not
|
||||
latency-critical).
|
||||
Зона ответственности:
|
||||
- Потребляет события «новое показание» из RabbitMQ (асинхронно — здесь
|
||||
надёжность доставки важнее задержки).
|
||||
- Загружает активные `automation_rules` для нужной зоны/устройства из
|
||||
PostgreSQL, кэшируя в памяти/Redis, чтобы не ходить в БД на каждое событие.
|
||||
- Оценивает условия правил обобщённо: `sensor_type X operator value` против
|
||||
показания — никаких зашитых названий датчиков/устройств, всё берётся из
|
||||
строки `automation_rules`.
|
||||
- При срабатывании: вызывает device-control-service по gRPC (нужен быстрый
|
||||
результат успех/неудача) и публикует событие в notification-service через
|
||||
RabbitMQ (не критично к задержке).
|
||||
|
||||
Not this service's job: talking to MQTT or Redis directly — device state
|
||||
changes always go through device-control-service's gRPC API.
|
||||
Не входит в зону ответственности: прямое взаимодействие с MQTT или Redis —
|
||||
изменения состояния устройства всегда идут через gRPC API device-control-service.
|
||||
|
||||
Reference in New Issue
Block a user