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

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
+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\DeviceType;
use App\Models\Zone;
use App\Services\ClickHouseClient;
use App\Services\DeviceControlClient;
use App\Services\DeviceShadow;
use Illuminate\Http\Request;
class DeviceController extends Controller
{
public function index()
public function index(DeviceShadow $shadow)
{
$this->authorize('viewAny', Device::class);
$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()
@@ -57,6 +85,52 @@ class DeviceController extends Controller
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>
*/
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Casts\JsonObjectCast;
use App\Enums\ConditionOperator;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
@@ -27,7 +28,7 @@ class AutomationRule extends Model
return [
'condition_operator' => ConditionOperator::class,
'condition_value' => 'float',
'action_params' => 'array',
'action_params' => JsonObjectCast::class,
'is_active' => 'boolean',
'created_at' => 'datetime',
];
@@ -2,6 +2,8 @@
namespace App\Providers;
use App\Services\ClickHouseClient;
use App\Services\DeviceControlClient;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
@@ -11,7 +13,16 @@ class AppServiceProvider extends ServiceProvider
*/
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));
}
}