Дашборд с реальными данными + ручное управление устройствами

device-control-service: HTTP/JSON API (internal/httpapi) рядом с gRPC —
POST /devices/{id}/turn-on|turn-off|set-level, тот же server.Server внутри,
без дублирования логики. Решение вместо gRPC-клиента на PHP: grpc/grpc
через PECL компилируется в Alpine 10-20+ минут и утяжеляет образ, а
диаграмма архитектуры в ТЗ и так допускала HTTP для Laravel→device-control.

Laravel: DeviceShadow (чтение Device Shadow из Redis, MGET одним запросом
для списка устройств), ClickHouseClient (HTTP-интерфейс ClickHouse,
параметризованные {name:Type}-запросы), DeviceControlClient (HTTP-вызовы
к новому Go-эндпоинту). Redis-клиент — predis (чистый PHP), а не phpredis,
по той же причине, что и решение по gRPC — не добавлять ещё одну
C-компиляцию в образ.

DeviceController::show — страница устройства: live-статус/last_seen/
desired-reported state из Redis, история показаний из ClickHouse (для
сенсоров), кнопки ручного управления (для актуаторов, только owner,
с проверкой capability устройства). В devices/index — бейдж online/
offline/unknown. Дашборд дополнен счётчиком онлайн-устройств.

Два реальных бага найдены и исправлены при сквозной проверке:
1. Пустой action_params сериализовался в JSON-массив "[]" (PHP не
   различает пустой список и пустой объект), а Go ждёт объект —
   rule-engine-service падал на unmarshal. Фикс — JsonObjectCast
   (JSON_FORCE_OBJECT) на AutomationRule::action_params.
2. Redis-ключи device shadow — общее пространство имён с Go-сервisами
   (сырые ключи без префикса), а Laravel по умолчанию добавляет ко всем
   ключам префикс "app-name-database-" — Laravel никогда не видел
   реальные данные. Фикс — REDIS_PREFIX="" в окружении контейнера
   (важно: пустое значение в docker-compose YAML нужно задавать явно
   через "", просто "KEY:" означает "взять из окружения хоста").

Проверено сквозным тестом через docker compose: полный цикл телеметрия →
правило → команда воспроизведён вживую с реальным исправлением на лету;
ручное управление (turn_on/turn_off/set_level) из Laravel UI подтверждено
через браузер — HTTP-вызов к device-control-service, обновление
desired_state (merge-patch), реальная MQTT-команда поймана мониторингом
топика. 38/38 тестов Laravel, все Go-тесты device-control-service зелёные.
This commit is contained in:
2026-08-11 19:48:17 +05:00
parent 467a05542c
commit 3ade5c2512
25 changed files with 970 additions and 39 deletions
+2 -1
View File
@@ -30,8 +30,9 @@ RABBITMQ_PASSWORD=change_me
MQTT_HOST=mosquitto MQTT_HOST=mosquitto
MQTT_PORT=1883 MQTT_PORT=1883
# --- device-control-service (gRPC) --- # --- device-control-service (gRPC + HTTP) ---
DEVICE_CONTROL_GRPC_PORT=50051 DEVICE_CONTROL_GRPC_PORT=50051
DEVICE_CONTROL_HTTP_PORT=8090
DEVICE_CONTROL_MQTT_CLIENT_ID=device-control-service DEVICE_CONTROL_MQTT_CLIENT_ID=device-control-service
DEVICE_CONTROL_HEALTHCHECK_TIMEOUT=60s DEVICE_CONTROL_HEALTHCHECK_TIMEOUT=60s
DEVICE_CONTROL_HEALTHCHECK_INTERVAL=15s DEVICE_CONTROL_HEALTHCHECK_INTERVAL=15s
+16
View File
@@ -121,8 +121,10 @@ services:
dockerfile: services/device-control-service/Dockerfile dockerfile: services/device-control-service/Dockerfile
ports: ports:
- "${DEVICE_CONTROL_GRPC_PORT}:50051" - "${DEVICE_CONTROL_GRPC_PORT}:50051"
- "${DEVICE_CONTROL_HTTP_PORT}:8090"
environment: environment:
DEVICE_CONTROL_GRPC_PORT: 50051 DEVICE_CONTROL_GRPC_PORT: 50051
DEVICE_CONTROL_HTTP_PORT: 8090
MQTT_HOST: mosquitto MQTT_HOST: mosquitto
MQTT_PORT: 1883 MQTT_PORT: 1883
REDIS_HOST: redis REDIS_HOST: redis
@@ -193,15 +195,29 @@ services:
SESSION_DRIVER: database SESSION_DRIVER: database
CACHE_STORE: database CACHE_STORE: database
QUEUE_CONNECTION: sync QUEUE_CONNECTION: sync
REDIS_CLIENT: predis
REDIS_HOST: redis REDIS_HOST: redis
REDIS_PORT: 6379 REDIS_PORT: 6379
REDIS_PASSWORD: ${REDIS_PASSWORD} REDIS_PASSWORD: ${REDIS_PASSWORD}
# Device Shadow keys are a cross-service keyspace (device-control-service
# writes them raw) — Laravel's default per-app key prefix would hide them.
REDIS_PREFIX: ""
CLICKHOUSE_HOST: clickhouse
CLICKHOUSE_HTTP_PORT: 8123
CLICKHOUSE_DB: ${CLICKHOUSE_DB}
CLICKHOUSE_USER: ${CLICKHOUSE_USER}
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD}
DEVICE_CONTROL_HTTP_URL: http://device-control-service:8090
LOG_CHANNEL: stderr LOG_CHANNEL: stderr
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
redis: redis:
condition: service_started condition: service_started
clickhouse:
condition: service_healthy
device-control-service:
condition: service_started
networks: networks:
- home-automation - home-automation
restart: unless-stopped restart: unless-stopped
+14 -1
View File
@@ -42,11 +42,24 @@ CACHE_STORE=database
MEMCACHED_HOST=127.0.0.1 MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis REDIS_CLIENT=predis
# Device Shadow keys are a cross-service keyspace (device-control-service
# writes them raw) — Laravel's default per-app key prefix would hide them.
REDIS_PREFIX=
REDIS_HOST=127.0.0.1 REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null REDIS_PASSWORD=null
REDIS_PORT=6379 REDIS_PORT=6379
# --- ClickHouse (telemetry history) ---
CLICKHOUSE_HOST=127.0.0.1
CLICKHOUSE_HTTP_PORT=8123
CLICKHOUSE_DB=telemetry
CLICKHOUSE_USER=default
CLICKHOUSE_PASSWORD=change_me
# --- device-control-service (manual device commands, HTTP transport) ---
DEVICE_CONTROL_HTTP_URL=http://127.0.0.1:8090
MAIL_MAILER=log MAIL_MAILER=log
MAIL_SCHEME=null MAIL_SCHEME=null
MAIL_HOST=127.0.0.1 MAIL_HOST=127.0.0.1
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
/**
* Like the built-in 'array' cast, but always serializes as a JSON object
* ({}), never a JSON array ([]). PHP can't tell an empty list from an empty
* map, so `json_encode([])` gives "[]" Go's `json.Unmarshal` into
* map[string]any rejects that. automation_rules.action_params is always a
* flat key-value map (never a genuine list), so forcing object encoding is
* safe here.
*/
class JsonObjectCast implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes): array
{
return $value === null ? [] : json_decode($value, true);
}
public function set($model, string $key, $value, array $attributes): string
{
return json_encode($value ?? [], JSON_FORCE_OBJECT);
}
}
@@ -6,16 +6,44 @@ use App\Http\Requests\DeviceRequest;
use App\Models\Device; use App\Models\Device;
use App\Models\DeviceType; use App\Models\DeviceType;
use App\Models\Zone; use App\Models\Zone;
use App\Services\ClickHouseClient;
use App\Services\DeviceControlClient;
use App\Services\DeviceShadow;
use Illuminate\Http\Request;
class DeviceController extends Controller class DeviceController extends Controller
{ {
public function index() public function index(DeviceShadow $shadow)
{ {
$this->authorize('viewAny', Device::class); $this->authorize('viewAny', Device::class);
$devices = Device::with(['zone', 'deviceType'])->orderBy('name')->get(); $devices = Device::with(['zone', 'deviceType'])->orderBy('name')->get();
$statuses = $shadow->statuses($devices->pluck('external_id')->all());
return view('devices.index', compact('devices')); return view('devices.index', compact('devices', 'statuses'));
}
public function show(Device $device, DeviceShadow $shadow, ClickHouseClient $clickHouse)
{
$this->authorize('view', $device);
$device->load(['zone', 'deviceType']);
$telemetry = [];
if ($device->deviceType->category->value === 'sensor') {
$telemetry = $clickHouse->query(
'SELECT sensor_type, value, recorded_at FROM telemetry
WHERE device_id = {device_id:String}
ORDER BY recorded_at DESC LIMIT 50',
['device_id' => $device->external_id],
);
}
return view('devices.show', [
'device' => $device,
'shadow' => $shadow->snapshot($device->external_id),
'telemetry' => $telemetry,
]);
} }
public function create() public function create()
@@ -57,6 +85,52 @@ class DeviceController extends Controller
return redirect()->route('devices.index')->with('status', 'Устройство удалено.'); return redirect()->route('devices.index')->with('status', 'Устройство удалено.');
} }
public function turnOn(Device $device, DeviceControlClient $client)
{
$this->authorize('update', $device);
$this->ensureCapability($device, 'turn_on');
return $this->respondToCommand($client->turnOn($device->external_id));
}
public function turnOff(Device $device, DeviceControlClient $client)
{
$this->authorize('update', $device);
$this->ensureCapability($device, 'turn_off');
return $this->respondToCommand($client->turnOff($device->external_id));
}
public function setLevel(Request $request, Device $device, DeviceControlClient $client)
{
$this->authorize('update', $device);
$this->ensureCapability($device, 'set_level');
$validated = $request->validate(['level' => ['required', 'numeric']]);
return $this->respondToCommand($client->setLevel($device->external_id, (float) $validated['level']));
}
private function ensureCapability(Device $device, string $capability): void
{
abort_unless(
in_array($capability, $device->deviceType->capabilities ?? [], true),
422,
"Устройство не поддерживает действие «{$capability}».",
);
}
/**
* @param array{success: bool, error: ?string} $result
*/
private function respondToCommand(array $result)
{
return back()->with(
$result['success'] ? 'status' : 'error',
$result['success'] ? 'Команда отправлена.' : ($result['error'] ?? 'Команда не выполнена.'),
);
}
/** /**
* @return array<string, mixed> * @return array<string, mixed>
*/ */
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models; namespace App\Models;
use App\Casts\JsonObjectCast;
use App\Enums\ConditionOperator; use App\Enums\ConditionOperator;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -27,7 +28,7 @@ class AutomationRule extends Model
return [ return [
'condition_operator' => ConditionOperator::class, 'condition_operator' => ConditionOperator::class,
'condition_value' => 'float', 'condition_value' => 'float',
'action_params' => 'array', 'action_params' => JsonObjectCast::class,
'is_active' => 'boolean', 'is_active' => 'boolean',
'created_at' => 'datetime', 'created_at' => 'datetime',
]; ];
@@ -2,6 +2,8 @@
namespace App\Providers; namespace App\Providers;
use App\Services\ClickHouseClient;
use App\Services\DeviceControlClient;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
@@ -11,7 +13,16 @@ class AppServiceProvider extends ServiceProvider
*/ */
public function register(): void public function register(): void
{ {
// $this->app->singleton(ClickHouseClient::class, fn () => new ClickHouseClient(
baseUrl: config('clickhouse.url'),
database: config('clickhouse.database'),
username: config('clickhouse.username'),
password: config('clickhouse.password'),
));
$this->app->singleton(DeviceControlClient::class, fn () => new DeviceControlClient(
baseUrl: config('services.device_control.url'),
));
} }
/** /**
@@ -0,0 +1,49 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use RuntimeException;
/**
* Minimal client for ClickHouse's HTTP interface used instead of a
* ClickHouse composer package to avoid an extra dependency for what's just
* "POST a query, get JSONEachRow back". Queries are parameterized via
* ClickHouse's own {name:Type} placeholders (sent as param_name=value query
* params), never string-concatenated, so this is safe against injection.
*/
class ClickHouseClient
{
public function __construct(
private readonly string $baseUrl,
private readonly string $database,
private readonly string $username,
private readonly string $password,
) {}
/**
* @param array<string, scalar> $params Bound to {name:Type} placeholders in $sql.
* @return array<int, array<string, mixed>>
*/
public function query(string $sql, array $params = []): array
{
$query = array_merge(
['database' => $this->database, 'default_format' => 'JSONEachRow'],
collect($params)->mapWithKeys(fn ($value, $key) => ["param_{$key}" => $value])->all(),
);
$response = Http::withBasicAuth($this->username, $this->password)
->withBody($sql, 'text/plain')
->post("{$this->baseUrl}/?".http_build_query($query));
if ($response->failed()) {
throw new RuntimeException("ClickHouse query failed ({$response->status()}): {$response->body()}");
}
// JSONEachRow: one JSON object per line, not a JSON array.
return collect(explode("\n", trim($response->body())))
->filter(fn (string $line) => $line !== '')
->map(fn (string $line) => json_decode($line, true))
->all();
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
/**
* HTTP client for device-control-service's manual-command API (see that
* service's README for why HTTP instead of gRPC here). Mirrors the
* gRPC CommandResult contract: {success, error} in the body always
* returned as an array here too, never an exception, so callers don't need
* to distinguish "device rejected it" from "service unreachable" to render
* a flash message.
*/
class DeviceControlClient
{
public function __construct(private readonly string $baseUrl) {}
/** @return array{success: bool, error: ?string} */
public function turnOn(string $externalId): array
{
return $this->post("/devices/{$externalId}/turn-on");
}
/** @return array{success: bool, error: ?string} */
public function turnOff(string $externalId): array
{
return $this->post("/devices/{$externalId}/turn-off");
}
/** @return array{success: bool, error: ?string} */
public function setLevel(string $externalId, float $level): array
{
return $this->post("/devices/{$externalId}/set-level", ['level' => $level]);
}
/**
* @param array<string, mixed> $body
* @return array{success: bool, error: ?string}
*/
private function post(string $path, array $body = []): array
{
try {
$response = Http::timeout(5)->post("{$this->baseUrl}{$path}", $body);
} catch (\Illuminate\Http\Client\ConnectionException $e) {
Log::error('device-control-service unreachable', ['path' => $path, 'error' => $e->getMessage()]);
return ['success' => false, 'error' => 'device-control-service недоступен'];
}
if ($response->failed()) {
Log::error('device-control-service returned an error status', ['path' => $path, 'status' => $response->status()]);
return ['success' => false, 'error' => 'device-control-service вернул ошибку'];
}
return [
'success' => (bool) $response->json('success'),
'error' => $response->json('error'),
];
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Services;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Redis;
/**
* Read-only access to device-control-service's Device Shadow in Redis.
* Laravel never writes these keys device-control-service owns them; this
* is purely for the dashboard/device pages to show live state.
*/
class DeviceShadow
{
/**
* Full shadow snapshot for one device, one round-trip via pipeline.
*
* @return array{status: string, last_seen: ?CarbonImmutable, desired_state: array<string, mixed>, reported_state: array<string, mixed>}
*/
public function snapshot(string $externalId): array
{
$results = Redis::pipeline(function ($pipe) use ($externalId) {
$pipe->get("device:{$externalId}:status");
$pipe->get("device:{$externalId}:last_seen");
$pipe->get("device:{$externalId}:desired_state");
$pipe->get("device:{$externalId}:reported_state");
});
[$status, $lastSeen, $desired, $reported] = $results;
return [
'status' => $status ?: 'unknown',
'last_seen' => $lastSeen ? CarbonImmutable::createFromTimestamp((int) $lastSeen) : null,
'desired_state' => $desired ? json_decode($desired, true) : [],
'reported_state' => $reported ? json_decode($reported, true) : [],
];
}
/**
* Status for many devices in a single round-trip (MGET), so the device
* list doesn't do one Redis call per row.
*
* @param array<int, string> $externalIds
* @return array<string, string> external_id => status ("online"/"offline"/"unknown")
*/
public function statuses(array $externalIds): array
{
if (empty($externalIds)) {
return [];
}
$keys = array_map(fn (string $id) => "device:{$id}:status", $externalIds);
$values = Redis::mget($keys);
return array_combine($externalIds, array_map(fn ($v) => $v ?: 'unknown', $values));
}
}
+2 -1
View File
@@ -9,7 +9,8 @@
"php": "^8.3", "php": "^8.3",
"laravel/framework": "^13.8", "laravel/framework": "^13.8",
"laravel/sanctum": "^4.0", "laravel/sanctum": "^4.0",
"laravel/tinker": "^3.0" "laravel/tinker": "^3.0",
"predis/predis": "^3.5"
}, },
"require-dev": { "require-dev": {
"fakerphp/faker": "^1.23", "fakerphp/faker": "^1.23",
+83 -20
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "f1ab046cb80318325a9735c77c07672f", "content-hash": "483f1bf17688fcc178b8c1849ff31ddc",
"packages": [ "packages": [
{ {
"name": "brick/math", "name": "brick/math",
@@ -642,21 +642,21 @@
}, },
{ {
"name": "guzzlehttp/guzzle", "name": "guzzlehttp/guzzle",
"version": "7.15.1", "version": "7.15.3",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/guzzle/guzzle.git", "url": "https://github.com/guzzle/guzzle.git",
"reference": "61443dfb33c62f308ee8add20f45b4d6e4bf8d2f" "reference": "ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/61443dfb33c62f308ee8add20f45b4d6e4bf8d2f", "url": "https://api.github.com/repos/guzzle/guzzle/zipball/ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc",
"reference": "61443dfb33c62f308ee8add20f45b4d6e4bf8d2f", "reference": "ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"ext-json": "*", "ext-json": "*",
"guzzlehttp/promises": "^2.5.1", "guzzlehttp/promises": "^2.5.2",
"guzzlehttp/psr7": "^2.13", "guzzlehttp/psr7": "^2.13",
"php": "^7.2.5 || ^8.0", "php": "^7.2.5 || ^8.0",
"psr/http-client": "^1.0", "psr/http-client": "^1.0",
@@ -750,7 +750,7 @@
], ],
"support": { "support": {
"issues": "https://github.com/guzzle/guzzle/issues", "issues": "https://github.com/guzzle/guzzle/issues",
"source": "https://github.com/guzzle/guzzle/tree/7.15.1" "source": "https://github.com/guzzle/guzzle/tree/7.15.3"
}, },
"funding": [ "funding": [
{ {
@@ -766,20 +766,20 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2026-07-18T11:23:11+00:00" "time": "2026-08-05T19:48:21+00:00"
}, },
{ {
"name": "guzzlehttp/promises", "name": "guzzlehttp/promises",
"version": "2.5.1", "version": "2.5.2",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/guzzle/promises.git", "url": "https://github.com/guzzle/promises.git",
"reference": "9ad1e4fc607446a055b95870c7f668e93b5cff29" "reference": "2823687acff28b2dbe67b2508a6b300e2c3fa4ce"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/guzzle/promises/zipball/9ad1e4fc607446a055b95870c7f668e93b5cff29", "url": "https://api.github.com/repos/guzzle/promises/zipball/2823687acff28b2dbe67b2508a6b300e2c3fa4ce",
"reference": "9ad1e4fc607446a055b95870c7f668e93b5cff29", "reference": "2823687acff28b2dbe67b2508a6b300e2c3fa4ce",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@@ -834,7 +834,7 @@
], ],
"support": { "support": {
"issues": "https://github.com/guzzle/promises/issues", "issues": "https://github.com/guzzle/promises/issues",
"source": "https://github.com/guzzle/promises/tree/2.5.1" "source": "https://github.com/guzzle/promises/tree/2.5.2"
}, },
"funding": [ "funding": [
{ {
@@ -850,7 +850,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2026-07-08T15:48:39+00:00" "time": "2026-08-05T19:30:54+00:00"
}, },
{ {
"name": "guzzlehttp/psr7", "name": "guzzlehttp/psr7",
@@ -1538,16 +1538,16 @@
}, },
{ {
"name": "league/commonmark", "name": "league/commonmark",
"version": "2.8.3", "version": "2.9.2",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/thephpleague/commonmark.git", "url": "https://github.com/thephpleague/commonmark.git",
"reference": "1902f60f984235023acbe03db6ad614a37b3c3e7" "reference": "72e9a87efcf41a8e83be3ed0866b69d77565cb12"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/thephpleague/commonmark/zipball/1902f60f984235023acbe03db6ad614a37b3c3e7", "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/72e9a87efcf41a8e83be3ed0866b69d77565cb12",
"reference": "1902f60f984235023acbe03db6ad614a37b3c3e7", "reference": "72e9a87efcf41a8e83be3ed0866b69d77565cb12",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@@ -1584,7 +1584,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-main": "2.9-dev" "dev-main": "2.10-dev"
} }
}, },
"autoload": { "autoload": {
@@ -1641,7 +1641,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2026-07-12T15:29:16+00:00" "time": "2026-08-11T00:58:45+00:00"
}, },
{ {
"name": "league/config", "name": "league/config",
@@ -2680,6 +2680,69 @@
], ],
"time": "2025-12-27T19:41:33+00:00" "time": "2025-12-27T19:41:33+00:00"
}, },
{
"name": "predis/predis",
"version": "v3.5.1",
"source": {
"type": "git",
"url": "https://github.com/predis/predis.git",
"reference": "5c996db191ee2d9bafe651f454b1fca16754271b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/predis/predis/zipball/5c996db191ee2d9bafe651f454b1fca16754271b",
"reference": "5c996db191ee2d9bafe651f454b1fca16754271b",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0",
"psr/http-message": "^1.0|^2.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.3",
"phpstan/phpstan": "^1.9",
"phpunit/phpcov": "^6.0 || ^8.0",
"phpunit/phpunit": "^8.0 || ~9.4.4"
},
"suggest": {
"ext-relay": "Faster connection with in-memory caching (>=0.6.2)"
},
"type": "library",
"autoload": {
"psr-4": {
"Predis\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Till Krüss",
"homepage": "https://till.im",
"role": "Maintainer"
}
],
"description": "A flexible and feature-complete Redis/Valkey client for PHP.",
"homepage": "http://github.com/predis/predis",
"keywords": [
"nosql",
"predis",
"redis"
],
"support": {
"issues": "https://github.com/predis/predis/issues",
"source": "https://github.com/predis/predis/tree/v3.5.1"
},
"funding": [
{
"url": "https://github.com/sponsors/tillkruss",
"type": "github"
}
],
"time": "2026-06-11T16:56:53+00:00"
},
{ {
"name": "psr/clock", "name": "psr/clock",
"version": "1.0.0", "version": "1.0.0",
+8
View File
@@ -0,0 +1,8 @@
<?php
return [
'url' => 'http://'.env('CLICKHOUSE_HOST', 'localhost').':'.env('CLICKHOUSE_HTTP_PORT', '8123'),
'database' => env('CLICKHOUSE_DB', 'telemetry'),
'username' => env('CLICKHOUSE_USER', 'default'),
'password' => env('CLICKHOUSE_PASSWORD', ''),
];
+4
View File
@@ -35,4 +35,8 @@ return [
], ],
], ],
'device_control' => [
'url' => env('DEVICE_CONTROL_HTTP_URL', 'http://localhost:8090'),
],
]; ];
@@ -6,7 +6,7 @@
</x-slot> </x-slot>
<div class="py-12"> <div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 grid grid-cols-1 sm:grid-cols-3 gap-6"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 grid grid-cols-1 sm:grid-cols-4 gap-6">
<a href="{{ route('zones.index') }}" class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6 hover:shadow-md transition"> <a href="{{ route('zones.index') }}" class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6 hover:shadow-md transition">
<div class="text-sm text-gray-500">{{ __('Зоны') }}</div> <div class="text-sm text-gray-500">{{ __('Зоны') }}</div>
<div class="text-3xl font-semibold text-gray-900">{{ $zonesCount }}</div> <div class="text-3xl font-semibold text-gray-900">{{ $zonesCount }}</div>
@@ -15,6 +15,10 @@
<div class="text-sm text-gray-500">{{ __('Устройства') }}</div> <div class="text-sm text-gray-500">{{ __('Устройства') }}</div>
<div class="text-3xl font-semibold text-gray-900">{{ $devicesCount }}</div> <div class="text-3xl font-semibold text-gray-900">{{ $devicesCount }}</div>
</a> </a>
<a href="{{ route('devices.index') }}" class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6 hover:shadow-md transition">
<div class="text-sm text-gray-500">{{ __('Онлайн') }}</div>
<div class="text-3xl font-semibold text-green-600">{{ $onlineDevicesCount }}</div>
</a>
<a href="{{ route('automation-rules.index') }}" class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6 hover:shadow-md transition"> <a href="{{ route('automation-rules.index') }}" class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6 hover:shadow-md transition">
<div class="text-sm text-gray-500">{{ __('Активных правил') }}</div> <div class="text-sm text-gray-500">{{ __('Активных правил') }}</div>
<div class="text-3xl font-semibold text-gray-900">{{ $activeRulesCount }}</div> <div class="text-3xl font-semibold text-gray-900">{{ $activeRulesCount }}</div>
@@ -18,6 +18,9 @@
@if (session('status')) @if (session('status'))
<div class="mb-4 text-sm text-green-600">{{ session('status') }}</div> <div class="mb-4 text-sm text-green-600">{{ session('status') }}</div>
@endif @endif
@if (session('error'))
<div class="mb-4 text-sm text-red-600">{{ session('error') }}</div>
@endif
<table class="w-full text-left text-sm"> <table class="w-full text-left text-sm">
<thead> <thead>
@@ -25,19 +28,29 @@
<th class="py-2">{{ __('Название') }}</th> <th class="py-2">{{ __('Название') }}</th>
<th class="py-2">{{ __('Зона') }}</th> <th class="py-2">{{ __('Зона') }}</th>
<th class="py-2">{{ __('Тип') }}</th> <th class="py-2">{{ __('Тип') }}</th>
<th class="py-2">{{ __('Статус') }}</th>
<th class="py-2">{{ __('External ID') }}</th> <th class="py-2">{{ __('External ID') }}</th>
<th class="py-2">{{ __('Протокол') }}</th>
<th class="py-2"></th> <th class="py-2"></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@forelse ($devices as $device) @forelse ($devices as $device)
@php $status = $statuses[$device->external_id] ?? 'unknown'; @endphp
<tr class="border-b"> <tr class="border-b">
<td class="py-2">{{ $device->name }}</td> <td class="py-2">
<a href="{{ route('devices.show', $device) }}" class="text-indigo-600 hover:underline">{{ $device->name }}</a>
</td>
<td class="py-2">{{ $device->zone->name }}</td> <td class="py-2">{{ $device->zone->name }}</td>
<td class="py-2">{{ $device->deviceType->code }}</td> <td class="py-2">{{ $device->deviceType->code }}</td>
<td class="py-2">
<span @class([
'inline-block px-2 py-0.5 rounded text-xs',
'bg-green-100 text-green-800' => $status === 'online',
'bg-gray-100 text-gray-600' => $status === 'offline',
'bg-yellow-100 text-yellow-800' => $status === 'unknown',
])>{{ $status }}</span>
</td>
<td class="py-2 font-mono text-xs">{{ $device->external_id }}</td> <td class="py-2 font-mono text-xs">{{ $device->external_id }}</td>
<td class="py-2">{{ $device->protocol }}</td>
<td class="py-2 text-right space-x-2"> <td class="py-2 text-right space-x-2">
@can('update', $device) @can('update', $device)
<a href="{{ route('devices.edit', $device) }}" class="text-indigo-600 hover:underline">{{ __('Изменить') }}</a> <a href="{{ route('devices.edit', $device) }}" class="text-indigo-600 hover:underline">{{ __('Изменить') }}</a>
@@ -0,0 +1,105 @@
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">{{ $device->name }}</h2>
</x-slot>
<div class="py-12">
<div class="max-w-4xl mx-auto sm:px-6 lg:px-8 space-y-6">
@if (session('status'))
<div class="text-sm text-green-600">{{ session('status') }}</div>
@endif
@if (session('error'))
<div class="text-sm text-red-600">{{ session('error') }}</div>
@endif
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
<h3 class="font-semibold mb-4">{{ __('Живое состояние (Redis device shadow)') }}</h3>
<dl class="grid grid-cols-2 gap-4 text-sm">
<div>
<dt class="text-gray-500">{{ __('Статус') }}</dt>
<dd @class([
'inline-block px-2 py-0.5 rounded text-xs mt-1',
'bg-green-100 text-green-800' => $shadow['status'] === 'online',
'bg-gray-100 text-gray-600' => $shadow['status'] === 'offline',
'bg-yellow-100 text-yellow-800' => $shadow['status'] === 'unknown',
])>{{ $shadow['status'] }}</dd>
</div>
<div>
<dt class="text-gray-500">{{ __('Последняя активность') }}</dt>
<dd>{{ $shadow['last_seen']?->diffForHumans() ?? __('нет данных') }}</dd>
</div>
<div>
<dt class="text-gray-500">{{ __('Желаемое состояние (desired)') }}</dt>
<dd class="font-mono text-xs">{{ json_encode($shadow['desired_state']) }}</dd>
</div>
<div>
<dt class="text-gray-500">{{ __('Подтверждённое состояние (reported)') }}</dt>
<dd class="font-mono text-xs">{{ json_encode($shadow['reported_state']) }}</dd>
</div>
</dl>
</div>
@can('update', $device)
@php $capabilities = $device->deviceType->capabilities ?? []; @endphp
@if (!empty(array_intersect($capabilities, ['turn_on', 'turn_off', 'set_level'])))
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
<h3 class="font-semibold mb-4">{{ __('Ручное управление') }}</h3>
<div class="flex items-center gap-4 flex-wrap">
@if (in_array('turn_on', $capabilities))
<form method="POST" action="{{ route('devices.turn-on', $device) }}">
@csrf
<x-primary-button>{{ __('Включить') }}</x-primary-button>
</form>
@endif
@if (in_array('turn_off', $capabilities))
<form method="POST" action="{{ route('devices.turn-off', $device) }}">
@csrf
<x-secondary-button>{{ __('Выключить') }}</x-secondary-button>
</form>
@endif
@if (in_array('set_level', $capabilities))
<form method="POST" action="{{ route('devices.set-level', $device) }}" class="flex items-center gap-2">
@csrf
<input type="number" step="any" name="level" required
class="border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm text-sm"
placeholder="{{ __('уровень') }}">
<x-primary-button>{{ __('Установить уровень') }}</x-primary-button>
</form>
@endif
</div>
</div>
@endif
@endcan
@if ($device->deviceType->category->value === 'sensor')
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
<h3 class="font-semibold mb-4">{{ __('Последние показания (ClickHouse)') }}</h3>
<table class="w-full text-left text-sm">
<thead>
<tr class="border-b">
<th class="py-2">{{ __('Тип') }}</th>
<th class="py-2">{{ __('Значение') }}</th>
<th class="py-2">{{ __('Время') }}</th>
</tr>
</thead>
<tbody>
@forelse ($telemetry as $row)
<tr class="border-b">
<td class="py-2">{{ $row['sensor_type'] }}</td>
<td class="py-2">{{ $row['value'] }}</td>
<td class="py-2">{{ $row['recorded_at'] }}</td>
</tr>
@empty
<tr>
<td colspan="3" class="py-4 text-gray-500">{{ __('Показаний пока нет.') }}</td>
</tr>
@endforelse
</tbody>
</table>
</div>
@endif
<a href="{{ route('devices.index') }}" class="text-sm text-gray-600 hover:underline">{{ __('← Назад к устройствам') }}</a>
</div>
</div>
</x-app-layout>
+14 -3
View File
@@ -7,26 +7,37 @@ use App\Http\Controllers\ZoneController;
use App\Models\AutomationRule; use App\Models\AutomationRule;
use App\Models\Device; use App\Models\Device;
use App\Models\Zone; use App\Models\Zone;
use App\Services\DeviceShadow;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::get('/', function () { Route::get('/', function () {
return view('welcome'); return view('welcome');
}); });
Route::get('/dashboard', function () { Route::get('/dashboard', function (DeviceShadow $shadow) {
$devices = Device::all();
$onlineCount = collect($shadow->statuses($devices->pluck('external_id')->all()))
->filter(fn (string $status) => $status === 'online')
->count();
return view('dashboard', [ return view('dashboard', [
'zonesCount' => Zone::count(), 'zonesCount' => Zone::count(),
'devicesCount' => Device::count(), 'devicesCount' => $devices->count(),
'onlineDevicesCount' => $onlineCount,
'activeRulesCount' => AutomationRule::where('is_active', true)->count(), 'activeRulesCount' => AutomationRule::where('is_active', true)->count(),
]); ]);
})->middleware(['auth', 'verified'])->name('dashboard'); })->middleware(['auth', 'verified'])->name('dashboard');
Route::middleware(['auth', 'verified'])->group(function () { Route::middleware(['auth', 'verified'])->group(function () {
Route::resource('zones', ZoneController::class)->except('show'); Route::resource('zones', ZoneController::class)->except('show');
Route::resource('devices', DeviceController::class)->except('show'); Route::resource('devices', DeviceController::class);
Route::resource('automation-rules', AutomationRuleController::class) Route::resource('automation-rules', AutomationRuleController::class)
->except('show') ->except('show')
->parameters(['automation-rules' => 'automation_rule']); ->parameters(['automation-rules' => 'automation_rule']);
Route::post('/devices/{device}/turn-on', [DeviceController::class, 'turnOn'])->name('devices.turn-on');
Route::post('/devices/{device}/turn-off', [DeviceController::class, 'turnOff'])->name('devices.turn-off');
Route::post('/devices/{device}/set-level', [DeviceController::class, 'setLevel'])->name('devices.set-level');
}); });
Route::middleware('auth')->group(function () { Route::middleware('auth')->group(function () {
@@ -59,11 +59,13 @@ class AutomationRuleControllerTest extends TestCase
]); ]);
$response->assertRedirect(route('automation-rules.index')); $response->assertRedirect(route('automation-rules.index'));
// '{}', not '[]' — Go's json.Unmarshal into map[string]any rejects an
// empty JSON array, so empty action_params must serialize as an object.
$this->assertDatabaseHas('automation_rules', [ $this->assertDatabaseHas('automation_rules', [
'condition_source_device_id' => $sensor->id, 'condition_source_device_id' => $sensor->id,
'target_device_id' => $fan->id, 'target_device_id' => $fan->id,
'action_type' => 'turn_on', 'action_type' => 'turn_on',
'action_params' => '[]', 'action_params' => '{}',
]); ]);
} }
@@ -0,0 +1,129 @@
<?php
namespace Tests\Feature;
use App\Enums\DeviceCategory;
use App\Enums\UserRole;
use App\Models\Device;
use App\Models\DeviceType;
use App\Models\User;
use App\Models\Zone;
use App\Services\ClickHouseClient;
use App\Services\DeviceControlClient;
use App\Services\DeviceShadow;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class DeviceControllerTest extends TestCase
{
use RefreshDatabase;
private function makeDevice(User $owner, array $capabilities): Device
{
$zone = Zone::forceCreate(['user_id' => $owner->id, 'name' => 'Гроубокс']);
$type = DeviceType::create([
'code' => 'fan',
'category' => DeviceCategory::Actuator,
'capabilities' => $capabilities,
]);
return Device::forceCreate([
'user_id' => $owner->id, 'zone_id' => $zone->id, 'device_type_id' => $type->id,
'name' => 'Вентилятор', 'external_id' => 'fan-1', 'protocol' => 'mqtt',
]);
}
public function test_owner_can_turn_on_device(): void
{
$owner = User::factory()->create(['role' => UserRole::Owner]);
$device = $this->makeDevice($owner, ['turn_on', 'turn_off']);
$this->mock(DeviceControlClient::class, function ($mock) {
$mock->shouldReceive('turnOn')->once()->with('fan-1')
->andReturn(['success' => true, 'error' => null]);
});
$response = $this->actingAs($owner)->post(route('devices.turn-on', $device));
$response->assertRedirect();
$response->assertSessionHas('status');
}
public function test_turn_on_rejected_when_device_lacks_capability(): void
{
$owner = User::factory()->create(['role' => UserRole::Owner]);
$device = $this->makeDevice($owner, ['turn_off']); // no turn_on
$this->mock(DeviceControlClient::class, function ($mock) {
$mock->shouldNotReceive('turnOn');
});
$response = $this->actingAs($owner)->post(route('devices.turn-on', $device));
$response->assertStatus(422);
}
public function test_viewer_cannot_turn_on_device(): void
{
$owner = User::factory()->create(['role' => UserRole::Owner]);
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
$device = $this->makeDevice($owner, ['turn_on']);
$this->mock(DeviceControlClient::class, function ($mock) {
$mock->shouldNotReceive('turnOn');
});
$response = $this->actingAs($viewer)->post(route('devices.turn-on', $device));
$response->assertForbidden();
}
public function test_failed_command_flashes_error(): void
{
$owner = User::factory()->create(['role' => UserRole::Owner]);
$device = $this->makeDevice($owner, ['turn_on']);
$this->mock(DeviceControlClient::class, function ($mock) {
$mock->shouldReceive('turnOn')->once()
->andReturn(['success' => false, 'error' => 'device offline']);
});
$response = $this->actingAs($owner)->post(route('devices.turn-on', $device));
$response->assertSessionHas('error', 'device offline');
}
public function test_show_page_renders_shadow_and_telemetry(): void
{
$owner = User::factory()->create(['role' => UserRole::Owner]);
$zone = Zone::forceCreate(['user_id' => $owner->id, 'name' => 'Гроубокс']);
$type = DeviceType::create([
'code' => 'sensor_temp_humidity',
'category' => DeviceCategory::Sensor,
'capabilities' => ['temperature'],
]);
$device = Device::forceCreate([
'user_id' => $owner->id, 'zone_id' => $zone->id, 'device_type_id' => $type->id,
'name' => 'Датчик', 'external_id' => 'sensor-1', 'protocol' => 'mqtt',
]);
$this->mock(DeviceShadow::class, function ($mock) {
$mock->shouldReceive('snapshot')->once()->with('sensor-1')->andReturn([
'status' => 'online',
'last_seen' => null,
'desired_state' => [],
'reported_state' => [],
]);
});
$this->mock(ClickHouseClient::class, function ($mock) {
$mock->shouldReceive('query')->once()
->andReturn([['sensor_type' => 'temperature', 'value' => 24.5, 'recorded_at' => '2026-01-01 00:00:00']]);
});
$response = $this->actingAs($owner)->get(route('devices.show', $device));
$response->assertOk();
$response->assertSee('online');
$response->assertSee('24.5');
}
}
+13 -2
View File
@@ -5,8 +5,11 @@
Зона ответственности: Зона ответственности:
- Предоставляет gRPC API (см. `proto/device_control/device_control.proto`: - Предоставляет gRPC API (см. `proto/device_control/device_control.proto`:
`TurnOn`, `TurnOff`, `SetLevel``CommandResult`) для отправки команд `TurnOn`, `TurnOff`, `SetLevel``CommandResult`) для отправки команд
устройствам — вызывается из Laravel (ручное управление) и из устройствам — вызывается из rule-engine-service (действия по срабатыванию
rule-engine-service (действия по срабатыванию правил). правил).
- Тот же функционал доступен и по HTTP/JSON (`internal/httpapi`,
`POST /devices/{device_id}/turn-on|turn-off|set-level`) — для Laravel
(ручное управление из UI), см. «Архитектурные решения» почему не gRPC.
- Публикует команду в MQTT-топик устройства (`devices/{device_id}/commands`) - Публикует команду в MQTT-топик устройства (`devices/{device_id}/commands`)
и слушает подтверждения (`devices/{device_id}/ack`). и слушает подтверждения (`devices/{device_id}/ack`).
- Поддерживает паттерн Device Shadow в Redis: `desired_state` (чего хочет - Поддерживает паттерн Device Shadow в Redis: `desired_state` (чего хочет
@@ -37,6 +40,14 @@
телеметрии/ack, а не выгружается из таблицы `devices`. Это удерживает телеметрии/ack, а не выгружается из таблицы `devices`. Это удерживает
сервис в границах MQTT+Redis+RabbitMQ+gRPC, как и в диаграмме архитектуры сервис в границах MQTT+Redis+RabbitMQ+gRPC, как и в диаграмме архитектуры
корневого README. корневого README.
- **HTTP рядом с gRPC, а не вместо.** ТЗ подразумевало gRPC-вызов и от
Laravel тоже, но `grpc/grpc` под PHP требует PECL-расширение, которое в
Alpine компилируется мучительно долго (C-код, 10-20+ минут) и утяжеляет
образ. `internal/httpapi` — тонкий транспорт поверх ТОГО ЖЕ
`server.Server` (никакой логики не дублируется, просто JSON вместо
Protobuf): диаграмма архитектуры в ТЗ и так допускала «HTTP/очередь» для
Laravel→device-control. gRPC-контракт между Go-сервисами (rule-engine)
не тронут.
## Запуск ## Запуск
@@ -9,6 +9,7 @@ import (
"fmt" "fmt"
"log/slog" "log/slog"
"net" "net"
"net/http"
"os" "os"
"os/signal" "os/signal"
"strings" "strings"
@@ -20,6 +21,7 @@ import (
devicecontrol "git.cactoz.su/cacto/home_automatization/proto/device_control" devicecontrol "git.cactoz.su/cacto/home_automatization/proto/device_control"
"git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/config" "git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/config"
"git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/healthcheck" "git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/healthcheck"
"git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/httpapi"
"git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/mqttclient" "git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/mqttclient"
"git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/rabbitmq" "git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/rabbitmq"
"git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/server" "git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/server"
@@ -81,20 +83,36 @@ func run(logger *slog.Logger) error {
checker.Start() checker.Start()
defer checker.Stop() defer checker.Stop()
srv := server.New(shadowStore, mqttClient, logger)
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", cfg.GRPCPort)) lis, err := net.Listen("tcp", fmt.Sprintf(":%d", cfg.GRPCPort))
if err != nil { if err != nil {
return fmt.Errorf("listen on grpc port %d: %w", cfg.GRPCPort, err) return fmt.Errorf("listen on grpc port %d: %w", cfg.GRPCPort, err)
} }
grpcServer := grpc.NewServer() grpcServer := grpc.NewServer()
devicecontrol.RegisterDeviceControlServer(grpcServer, server.New(shadowStore, mqttClient, logger)) devicecontrol.RegisterDeviceControlServer(grpcServer, srv)
// Same server instance, second transport — for callers where a full
// gRPC client is impractical (Laravel/PHP; see README).
httpServer := &http.Server{
Addr: fmt.Sprintf(":%d", cfg.HTTPPort),
Handler: httpapi.NewRouter(srv, logger),
}
go func() { go func() {
logger.Info("device-control-service started", "grpc_port", cfg.GRPCPort) logger.Info("grpc server started", "grpc_port", cfg.GRPCPort)
if err := grpcServer.Serve(lis); err != nil { if err := grpcServer.Serve(lis); err != nil {
logger.Error("grpc server stopped", "error", err) logger.Error("grpc server stopped", "error", err)
} }
}() }()
go func() {
logger.Info("http server started", "http_port", cfg.HTTPPort)
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error("http server stopped", "error", err)
}
}()
stop := make(chan os.Signal, 1) stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop <-stop
@@ -102,6 +120,12 @@ func run(logger *slog.Logger) error {
logger.Info("shutting down") logger.Info("shutting down")
grpcServer.GracefulStop() grpcServer.GracefulStop()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
logger.Error("http server shutdown failed", "error", err)
}
return nil return nil
} }
@@ -11,6 +11,7 @@ import (
type Config struct { type Config struct {
GRPCPort int GRPCPort int
HTTPPort int
MQTTBrokerURL string MQTTBrokerURL string
MQTTClientID string MQTTClientID string
@@ -45,6 +46,9 @@ func Load() (Config, error) {
if cfg.GRPCPort, err = getEnvInt("DEVICE_CONTROL_GRPC_PORT", 50051); err != nil { if cfg.GRPCPort, err = getEnvInt("DEVICE_CONTROL_GRPC_PORT", 50051); err != nil {
return Config{}, err return Config{}, err
} }
if cfg.HTTPPort, err = getEnvInt("DEVICE_CONTROL_HTTP_PORT", 8090); err != nil {
return Config{}, err
}
if cfg.RedisDB, err = getEnvInt("REDIS_DB", 0); err != nil { if cfg.RedisDB, err = getEnvInt("REDIS_DB", 0); err != nil {
return Config{}, err return Config{}, err
} }
@@ -0,0 +1,80 @@
// Package httpapi exposes the same device commands as the gRPC server over
// plain HTTP/JSON, for callers where a full gRPC client is impractical
// (Laravel/PHP, in this platform's case — see the service README for why).
// It's a thin transport: all the actual logic (Device Shadow patch + MQTT
// publish) lives in internal/server and is reused as-is.
package httpapi
import (
"context"
"encoding/json"
"log/slog"
"net/http"
devicecontrol "git.cactoz.su/cacto/home_automatization/proto/device_control"
)
// Dispatcher is the subset of server.Server this package needs.
type Dispatcher interface {
TurnOn(ctx context.Context, req *devicecontrol.TurnOnRequest) (*devicecontrol.CommandResult, error)
TurnOff(ctx context.Context, req *devicecontrol.TurnOffRequest) (*devicecontrol.CommandResult, error)
SetLevel(ctx context.Context, req *devicecontrol.SetLevelRequest) (*devicecontrol.CommandResult, error)
}
type commandResult struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
func NewRouter(dispatcher Dispatcher, logger *slog.Logger) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /devices/{device_id}/turn-on", func(w http.ResponseWriter, r *http.Request) {
deviceID := r.PathValue("device_id")
res, err := dispatcher.TurnOn(r.Context(), &devicecontrol.TurnOnRequest{DeviceId: deviceID})
writeResult(w, logger, res, err)
})
mux.HandleFunc("POST /devices/{device_id}/turn-off", func(w http.ResponseWriter, r *http.Request) {
deviceID := r.PathValue("device_id")
res, err := dispatcher.TurnOff(r.Context(), &devicecontrol.TurnOffRequest{DeviceId: deviceID})
writeResult(w, logger, res, err)
})
mux.HandleFunc("POST /devices/{device_id}/set-level", func(w http.ResponseWriter, r *http.Request) {
deviceID := r.PathValue("device_id")
var body struct {
Level float64 `json:"level"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(commandResult{Success: false, Error: "invalid JSON body: expected {\"level\": number}"})
return
}
res, err := dispatcher.SetLevel(r.Context(), &devicecontrol.SetLevelRequest{DeviceId: deviceID, Level: body.Level})
writeResult(w, logger, res, err)
})
return mux
}
// writeResult always answers 200 with the command's success/error in the
// body — the wire contract mirrors devicecontrol.CommandResult exactly, the
// same as the gRPC transport. A non-nil err here is a transport-layer bug in
// the dispatcher (it isn't supposed to return one), logged and surfaced as a
// generic failure rather than leaking internals to the caller.
func writeResult(w http.ResponseWriter, logger *slog.Logger, res *devicecontrol.CommandResult, err error) {
w.Header().Set("Content-Type", "application/json")
if err != nil {
logger.Error("dispatcher returned unexpected error", "error", err)
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(commandResult{Success: false, Error: "internal error"})
return
}
_ = json.NewEncoder(w).Encode(commandResult{Success: res.GetSuccess(), Error: res.GetError()})
}
@@ -0,0 +1,161 @@
package httpapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
devicecontrol "git.cactoz.su/cacto/home_automatization/proto/device_control"
)
type fakeDispatcher struct {
turnOnReq *devicecontrol.TurnOnRequest
turnOffReq *devicecontrol.TurnOffRequest
setLevelReq *devicecontrol.SetLevelRequest
result *devicecontrol.CommandResult
err error
}
func (f *fakeDispatcher) TurnOn(_ context.Context, req *devicecontrol.TurnOnRequest) (*devicecontrol.CommandResult, error) {
f.turnOnReq = req
return f.result, f.err
}
func (f *fakeDispatcher) TurnOff(_ context.Context, req *devicecontrol.TurnOffRequest) (*devicecontrol.CommandResult, error) {
f.turnOffReq = req
return f.result, f.err
}
func (f *fakeDispatcher) SetLevel(_ context.Context, req *devicecontrol.SetLevelRequest) (*devicecontrol.CommandResult, error) {
f.setLevelReq = req
return f.result, f.err
}
func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
func decodeResult(t *testing.T, rec *httptest.ResponseRecorder) commandResult {
t.Helper()
var res commandResult
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode response body %q: %v", rec.Body.String(), err)
}
return res
}
func TestTurnOn_Success(t *testing.T) {
fake := &fakeDispatcher{result: &devicecontrol.CommandResult{Success: true}}
router := NewRouter(fake, discardLogger())
req := httptest.NewRequest(http.MethodPost, "/devices/fan-1/turn-on", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("got status %d, want 200", rec.Code)
}
if fake.turnOnReq == nil || fake.turnOnReq.DeviceId != "fan-1" {
t.Fatalf("got TurnOn request %+v, want device_id=fan-1", fake.turnOnReq)
}
if res := decodeResult(t, rec); !res.Success {
t.Fatalf("got %+v, want success", res)
}
}
func TestTurnOff_Success(t *testing.T) {
fake := &fakeDispatcher{result: &devicecontrol.CommandResult{Success: true}}
router := NewRouter(fake, discardLogger())
req := httptest.NewRequest(http.MethodPost, "/devices/fan-1/turn-off", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("got status %d, want 200", rec.Code)
}
if fake.turnOffReq == nil || fake.turnOffReq.DeviceId != "fan-1" {
t.Fatalf("got TurnOff request %+v, want device_id=fan-1", fake.turnOffReq)
}
}
func TestSetLevel_Success(t *testing.T) {
fake := &fakeDispatcher{result: &devicecontrol.CommandResult{Success: true}}
router := NewRouter(fake, discardLogger())
body := bytes.NewBufferString(`{"level": 42.5}`)
req := httptest.NewRequest(http.MethodPost, "/devices/light-1/set-level", body)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("got status %d, want 200", rec.Code)
}
if fake.setLevelReq == nil || fake.setLevelReq.Level != 42.5 {
t.Fatalf("got SetLevel request %+v, want level=42.5", fake.setLevelReq)
}
}
func TestSetLevel_InvalidBody(t *testing.T) {
fake := &fakeDispatcher{}
router := NewRouter(fake, discardLogger())
req := httptest.NewRequest(http.MethodPost, "/devices/light-1/set-level", bytes.NewBufferString(`not json`))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("got status %d, want 400", rec.Code)
}
if fake.setLevelReq != nil {
t.Fatal("dispatcher should not have been called with an invalid body")
}
}
func TestBusinessFailure_PassesThroughAs200(t *testing.T) {
fake := &fakeDispatcher{result: &devicecontrol.CommandResult{Success: false, Error: "device offline"}}
router := NewRouter(fake, discardLogger())
req := httptest.NewRequest(http.MethodPost, "/devices/fan-1/turn-on", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("got status %d, want 200 (business failures aren't transport errors)", rec.Code)
}
res := decodeResult(t, rec)
if res.Success || res.Error != "device offline" {
t.Fatalf("got %+v, want business failure passed through", res)
}
}
func TestDispatcherError_Returns500(t *testing.T) {
fake := &fakeDispatcher{err: errors.New("boom")}
router := NewRouter(fake, discardLogger())
req := httptest.NewRequest(http.MethodPost, "/devices/fan-1/turn-on", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("got status %d, want 500", rec.Code)
}
}
func TestUnknownRoute_404(t *testing.T) {
router := NewRouter(&fakeDispatcher{}, discardLogger())
req := httptest.NewRequest(http.MethodGet, "/devices/fan-1/turn-on", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusMethodNotAllowed && rec.Code != http.StatusNotFound {
t.Fatalf("got status %d for GET on a POST-only route, want 404 or 405", rec.Code)
}
}