Слияние main: перевод README на русский

This commit is contained in:
2026-07-26 17:11:35 +05:00
6 changed files with 130 additions and 126 deletions
+16 -16
View File
@@ -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. Этот сервис
только исполняет команды и отслеживает состояние для той команды, что ему дали.
+8 -8
View File
@@ -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 было с кем
по-настоящему взаимодействовать.
+9 -8
View File
@@ -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.
+22 -21
View File
@@ -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` и т.д.
+14 -14
View File
@@ -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.