Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e739ef5d38 | ||
|
|
81040eec62 | ||
|
|
3ade5c2512 | ||
|
|
467a05542c |
+10
-1
@@ -30,8 +30,9 @@ RABBITMQ_PASSWORD=change_me
|
||||
MQTT_HOST=mosquitto
|
||||
MQTT_PORT=1883
|
||||
|
||||
# --- device-control-service (gRPC) ---
|
||||
# --- device-control-service (gRPC + HTTP) ---
|
||||
DEVICE_CONTROL_GRPC_PORT=50051
|
||||
DEVICE_CONTROL_HTTP_PORT=8090
|
||||
DEVICE_CONTROL_MQTT_CLIENT_ID=device-control-service
|
||||
DEVICE_CONTROL_HEALTHCHECK_TIMEOUT=60s
|
||||
DEVICE_CONTROL_HEALTHCHECK_INTERVAL=15s
|
||||
@@ -42,10 +43,12 @@ INGEST_MQTT_TOPIC=devices/+/telemetry
|
||||
INGEST_BATCH_MAX_SIZE=500
|
||||
INGEST_BATCH_FLUSH_INTERVAL=5s
|
||||
INGEST_BATCH_FLUSH_TIMEOUT=10s
|
||||
INGEST_METRICS_PORT=9101
|
||||
|
||||
# --- rule-engine-service ---
|
||||
DEVICE_CONTROL_HOST=device-control-service
|
||||
RULE_ENGINE_CACHE_REFRESH_INTERVAL=15s
|
||||
RULE_ENGINE_METRICS_PORT=9102
|
||||
|
||||
# --- Laravel app (stage 2) ---
|
||||
# Regenerate for anything beyond local dev: php artisan key:generate --show
|
||||
@@ -54,3 +57,9 @@ APP_ENV=local
|
||||
APP_DEBUG=true
|
||||
APP_URL=http://localhost:8000
|
||||
LARAVEL_HTTP_PORT=8000
|
||||
|
||||
# --- Prometheus + Grafana (stage 2.5) ---
|
||||
PROMETHEUS_PORT=9090
|
||||
GRAFANA_PORT=3000
|
||||
GRAFANA_ADMIN_USER=admin
|
||||
GRAFANA_ADMIN_PASSWORD=change_me
|
||||
|
||||
@@ -8,6 +8,8 @@ volumes:
|
||||
redis-data:
|
||||
rabbitmq-data:
|
||||
mosquitto-data:
|
||||
prometheus-data:
|
||||
grafana-data:
|
||||
|
||||
services:
|
||||
mosquitto:
|
||||
@@ -92,6 +94,8 @@ services:
|
||||
|
||||
ingest-service:
|
||||
build: ./services/ingest-service
|
||||
ports:
|
||||
- "${INGEST_METRICS_PORT}:9101"
|
||||
environment:
|
||||
MQTT_HOST: mosquitto
|
||||
MQTT_PORT: 1883
|
||||
@@ -104,6 +108,7 @@ services:
|
||||
RABBITMQ_PORT: 5672
|
||||
RABBITMQ_USER: ${RABBITMQ_USER}
|
||||
RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD}
|
||||
INGEST_METRICS_PORT: 9101
|
||||
depends_on:
|
||||
mosquitto:
|
||||
condition: service_started
|
||||
@@ -121,8 +126,10 @@ services:
|
||||
dockerfile: services/device-control-service/Dockerfile
|
||||
ports:
|
||||
- "${DEVICE_CONTROL_GRPC_PORT}:50051"
|
||||
- "${DEVICE_CONTROL_HTTP_PORT}:8090"
|
||||
environment:
|
||||
DEVICE_CONTROL_GRPC_PORT: 50051
|
||||
DEVICE_CONTROL_HTTP_PORT: 8090
|
||||
MQTT_HOST: mosquitto
|
||||
MQTT_PORT: 1883
|
||||
REDIS_HOST: redis
|
||||
@@ -150,6 +157,8 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: services/rule-engine-service/Dockerfile
|
||||
ports:
|
||||
- "${RULE_ENGINE_METRICS_PORT}:9102"
|
||||
environment:
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_PORT: 5432
|
||||
@@ -163,6 +172,7 @@ services:
|
||||
RABBITMQ_USER: ${RABBITMQ_USER}
|
||||
RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD}
|
||||
RULE_ENGINE_CACHE_REFRESH_INTERVAL: ${RULE_ENGINE_CACHE_REFRESH_INTERVAL}
|
||||
RULE_ENGINE_METRICS_PORT: 9102
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -193,15 +203,57 @@ services:
|
||||
SESSION_DRIVER: database
|
||||
CACHE_STORE: database
|
||||
QUEUE_CONNECTION: sync
|
||||
REDIS_CLIENT: predis
|
||||
REDIS_HOST: redis
|
||||
REDIS_PORT: 6379
|
||||
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
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_started
|
||||
clickhouse:
|
||||
condition: service_healthy
|
||||
device-control-service:
|
||||
condition: service_started
|
||||
networks:
|
||||
- home-automation
|
||||
restart: unless-stopped
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.1.0
|
||||
ports:
|
||||
- "${PROMETHEUS_PORT}:9090"
|
||||
volumes:
|
||||
- ./monitoring/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||
- prometheus-data:/prometheus
|
||||
networks:
|
||||
- home-automation
|
||||
restart: unless-stopped
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:11.4.0
|
||||
ports:
|
||||
- "${GRAFANA_PORT}:3000"
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER}
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD}
|
||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||
volumes:
|
||||
- grafana-data:/var/lib/grafana
|
||||
- ./monitoring/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
depends_on:
|
||||
- prometheus
|
||||
networks:
|
||||
- home-automation
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -42,11 +42,24 @@ CACHE_STORE=database
|
||||
|
||||
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_PASSWORD=null
|
||||
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_SCHEME=null
|
||||
MAIL_HOST=127.0.0.1
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\UserResource;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AuthController extends Controller
|
||||
{
|
||||
/**
|
||||
* Issue a Sanctum personal access token for a mobile client. Each
|
||||
* client names its own token (device_name) so a user can see/revoke
|
||||
* per-device sessions later without logging everyone out at once.
|
||||
*/
|
||||
public function login(Request $request)
|
||||
{
|
||||
$credentials = $request->validate([
|
||||
'email' => ['required', 'email'],
|
||||
'password' => ['required', 'string'],
|
||||
'device_name' => ['required', 'string', 'max:255'],
|
||||
]);
|
||||
|
||||
$user = User::where('email', $credentials['email'])->first();
|
||||
|
||||
if (! $user || ! Hash::check($credentials['password'], $user->password)) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => ['Неверный email или пароль.'],
|
||||
]);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'token' => $user->createToken($credentials['device_name'])->plainTextToken,
|
||||
'user' => new UserResource($user),
|
||||
]);
|
||||
}
|
||||
|
||||
public function logout(Request $request)
|
||||
{
|
||||
$request->user()->currentAccessToken()->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
|
||||
public function me(Request $request)
|
||||
{
|
||||
return new UserResource($request->user());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\AutomationRuleRequest;
|
||||
use App\Http\Resources\AutomationRuleResource;
|
||||
use App\Models\AutomationRule;
|
||||
|
||||
class AutomationRuleController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$this->authorize('viewAny', AutomationRule::class);
|
||||
|
||||
$rules = AutomationRule::with(['zone', 'targetDevice', 'conditionSourceDevice'])
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
|
||||
return AutomationRuleResource::collection($rules);
|
||||
}
|
||||
|
||||
public function store(AutomationRuleRequest $request)
|
||||
{
|
||||
$rule = new AutomationRule($this->mapActionParams($request->validated()));
|
||||
$rule->user()->associate($request->user());
|
||||
$rule->save();
|
||||
|
||||
return (new AutomationRuleResource($rule))->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function update(AutomationRuleRequest $request, AutomationRule $automation_rule)
|
||||
{
|
||||
$automation_rule->update($this->mapActionParams($request->validated()));
|
||||
|
||||
return new AutomationRuleResource($automation_rule);
|
||||
}
|
||||
|
||||
public function destroy(AutomationRule $automation_rule)
|
||||
{
|
||||
$this->authorize('delete', $automation_rule);
|
||||
|
||||
$automation_rule->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors AutomationRuleController@mapActionParams on the web side —
|
||||
* "level" is a friendlier stand-in for action_params over the wire too,
|
||||
* so mobile clients don't need to know the {"level": ...} shape.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function mapActionParams(array $data): array
|
||||
{
|
||||
$data['action_params'] = $data['action_type'] === 'set_level'
|
||||
? ['level' => $data['level']]
|
||||
: [];
|
||||
|
||||
unset($data['level']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\DeviceRequest;
|
||||
use App\Http\Resources\DeviceResource;
|
||||
use App\Models\Device;
|
||||
use App\Services\ClickHouseClient;
|
||||
use App\Services\DeviceControlClient;
|
||||
use App\Services\DeviceShadow;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class DeviceController extends Controller
|
||||
{
|
||||
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());
|
||||
$devices->each(fn (Device $d) => $d->live_status = $statuses[$d->external_id] ?? 'unknown');
|
||||
|
||||
return DeviceResource::collection($devices);
|
||||
}
|
||||
|
||||
public function show(Device $device, DeviceShadow $shadow, ClickHouseClient $clickHouse)
|
||||
{
|
||||
$this->authorize('view', $device);
|
||||
|
||||
$device->load(['zone', 'deviceType']);
|
||||
$snapshot = $shadow->snapshot($device->external_id);
|
||||
$device->live_status = $snapshot['status'];
|
||||
|
||||
$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 (new DeviceResource($device))->additional([
|
||||
'shadow' => [
|
||||
'last_seen' => $snapshot['last_seen'],
|
||||
'desired_state' => $snapshot['desired_state'],
|
||||
'reported_state' => $snapshot['reported_state'],
|
||||
],
|
||||
'telemetry' => $telemetry,
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(DeviceRequest $request)
|
||||
{
|
||||
$device = new Device($request->validated());
|
||||
$device->user()->associate($request->user());
|
||||
$device->save();
|
||||
|
||||
return (new DeviceResource($device))->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function update(DeviceRequest $request, Device $device)
|
||||
{
|
||||
$device->update($request->validated());
|
||||
|
||||
return new DeviceResource($device);
|
||||
}
|
||||
|
||||
public function destroy(Device $device)
|
||||
{
|
||||
$this->authorize('delete', $device);
|
||||
|
||||
$device->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
if (! $result['success']) {
|
||||
return response()->json(['message' => $result['error'] ?? 'Команда не выполнена.'], 422);
|
||||
}
|
||||
|
||||
return response()->json(['message' => 'Команда отправлена.']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\DeviceTypeResource;
|
||||
use App\Models\DeviceType;
|
||||
|
||||
class DeviceTypeController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
return DeviceTypeResource::collection(DeviceType::orderBy('code')->get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\ZoneRequest;
|
||||
use App\Http\Resources\ZoneResource;
|
||||
use App\Models\Zone;
|
||||
|
||||
class ZoneController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$this->authorize('viewAny', Zone::class);
|
||||
|
||||
return ZoneResource::collection(Zone::withCount('devices')->orderBy('name')->get());
|
||||
}
|
||||
|
||||
public function store(ZoneRequest $request)
|
||||
{
|
||||
$zone = $request->user()->zones()->create($request->validated());
|
||||
|
||||
return (new ZoneResource($zone))->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function update(ZoneRequest $request, Zone $zone)
|
||||
{
|
||||
$zone->update($request->validated());
|
||||
|
||||
return new ZoneResource($zone);
|
||||
}
|
||||
|
||||
public function destroy(Zone $zone)
|
||||
{
|
||||
$this->authorize('delete', $zone);
|
||||
|
||||
$zone->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\DeviceCategory;
|
||||
use App\Http\Requests\AutomationRuleRequest;
|
||||
use App\Models\AutomationRule;
|
||||
use App\Models\Device;
|
||||
use App\Models\DeviceType;
|
||||
use App\Models\Zone;
|
||||
|
||||
class AutomationRuleController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$this->authorize('viewAny', AutomationRule::class);
|
||||
|
||||
$rules = AutomationRule::with(['zone', 'targetDevice', 'conditionSourceDevice'])
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
|
||||
return view('automation-rules.index', ['rules' => $rules]);
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$this->authorize('create', AutomationRule::class);
|
||||
|
||||
return view('automation-rules.create', $this->formOptions());
|
||||
}
|
||||
|
||||
public function store(AutomationRuleRequest $request)
|
||||
{
|
||||
$rule = new AutomationRule($this->mapActionParams($request->validated()));
|
||||
$rule->user()->associate($request->user());
|
||||
$rule->save();
|
||||
|
||||
return redirect()->route('automation-rules.index')->with('status', 'Правило создано.');
|
||||
}
|
||||
|
||||
public function edit(AutomationRule $automation_rule)
|
||||
{
|
||||
$this->authorize('update', $automation_rule);
|
||||
|
||||
return view('automation-rules.edit', [
|
||||
'rule' => $automation_rule,
|
||||
...$this->formOptions(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(AutomationRuleRequest $request, AutomationRule $automation_rule)
|
||||
{
|
||||
$automation_rule->update($this->mapActionParams($request->validated()));
|
||||
|
||||
return redirect()->route('automation-rules.index')->with('status', 'Правило обновлено.');
|
||||
}
|
||||
|
||||
public function destroy(AutomationRule $automation_rule)
|
||||
{
|
||||
$this->authorize('delete', $automation_rule);
|
||||
|
||||
$automation_rule->delete();
|
||||
|
||||
return redirect()->route('automation-rules.index')->with('status', 'Правило удалено.');
|
||||
}
|
||||
|
||||
/**
|
||||
* The "level" form field is a friendlier stand-in for action_params —
|
||||
* only set_level currently takes a parameter, so there's no need for a
|
||||
* raw JSON editor yet.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function mapActionParams(array $data): array
|
||||
{
|
||||
$data['action_params'] = $data['action_type'] === 'set_level'
|
||||
? ['level' => $data['level']]
|
||||
: [];
|
||||
|
||||
unset($data['level']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function formOptions(): array
|
||||
{
|
||||
$devices = Device::with(['zone', 'deviceType'])->orderBy('name')->get();
|
||||
|
||||
return [
|
||||
'zones' => Zone::orderBy('name')->get(),
|
||||
'devices' => $devices,
|
||||
'actionTypeOptions' => $this->capabilityOptions(DeviceCategory::Actuator),
|
||||
'sensorTypeOptions' => $this->capabilityOptions(DeviceCategory::Sensor),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Distinct capability values across device_types of the given category —
|
||||
* used as friendly select/datalist suggestions, not a hardcoded list.
|
||||
*
|
||||
* @return \Illuminate\Support\Collection<int, string>
|
||||
*/
|
||||
private function capabilityOptions(DeviceCategory $category)
|
||||
{
|
||||
return DeviceType::where('category', $category)
|
||||
->get()
|
||||
->pluck('capabilities')
|
||||
->flatten()
|
||||
->unique()
|
||||
->sort()
|
||||
->values();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
|
||||
abstract class Controller
|
||||
{
|
||||
//
|
||||
use AuthorizesRequests;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
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(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', '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()
|
||||
{
|
||||
$this->authorize('create', Device::class);
|
||||
|
||||
return view('devices.create', $this->formOptions());
|
||||
}
|
||||
|
||||
public function store(DeviceRequest $request)
|
||||
{
|
||||
$device = new Device($request->validated());
|
||||
$device->user()->associate($request->user());
|
||||
$device->save();
|
||||
|
||||
return redirect()->route('devices.index')->with('status', 'Устройство добавлено.');
|
||||
}
|
||||
|
||||
public function edit(Device $device)
|
||||
{
|
||||
$this->authorize('update', $device);
|
||||
|
||||
return view('devices.edit', ['device' => $device, ...$this->formOptions()]);
|
||||
}
|
||||
|
||||
public function update(DeviceRequest $request, Device $device)
|
||||
{
|
||||
$device->update($request->validated());
|
||||
|
||||
return redirect()->route('devices.index')->with('status', 'Устройство обновлено.');
|
||||
}
|
||||
|
||||
public function destroy(Device $device)
|
||||
{
|
||||
$this->authorize('delete', $device);
|
||||
|
||||
$device->delete();
|
||||
|
||||
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>
|
||||
*/
|
||||
private function formOptions(): array
|
||||
{
|
||||
return [
|
||||
'zones' => Zone::orderBy('name')->get(),
|
||||
'deviceTypes' => DeviceType::orderBy('code')->get(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Requests\ZoneRequest;
|
||||
use App\Models\Zone;
|
||||
|
||||
class ZoneController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$this->authorize('viewAny', Zone::class);
|
||||
|
||||
$zones = Zone::withCount('devices')->orderBy('name')->get();
|
||||
|
||||
return view('zones.index', compact('zones'));
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$this->authorize('create', Zone::class);
|
||||
|
||||
return view('zones.create');
|
||||
}
|
||||
|
||||
public function store(ZoneRequest $request)
|
||||
{
|
||||
$request->user()->zones()->create($request->validated());
|
||||
|
||||
return redirect()->route('zones.index')->with('status', 'Зона создана.');
|
||||
}
|
||||
|
||||
public function edit(Zone $zone)
|
||||
{
|
||||
$this->authorize('update', $zone);
|
||||
|
||||
return view('zones.edit', compact('zone'));
|
||||
}
|
||||
|
||||
public function update(ZoneRequest $request, Zone $zone)
|
||||
{
|
||||
$zone->update($request->validated());
|
||||
|
||||
return redirect()->route('zones.index')->with('status', 'Зона обновлена.');
|
||||
}
|
||||
|
||||
public function destroy(Zone $zone)
|
||||
{
|
||||
$this->authorize('delete', $zone);
|
||||
|
||||
$zone->delete();
|
||||
|
||||
return redirect()->route('zones.index')->with('status', 'Зона удалена.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Enums\ConditionOperator;
|
||||
use App\Models\AutomationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class AutomationRuleRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
$rule = $this->route('automation_rule');
|
||||
|
||||
return $rule
|
||||
? $this->user()->can('update', $rule)
|
||||
: $this->user()->can('create', AutomationRule::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'zone_id' => ['required', 'exists:zones,id'],
|
||||
'target_device_id' => ['required', 'exists:devices,id'],
|
||||
'condition_source_device_id' => ['required', 'exists:devices,id'],
|
||||
'condition_sensor_type' => ['required', 'string', 'max:255'],
|
||||
'condition_operator' => ['required', Rule::enum(ConditionOperator::class)],
|
||||
'condition_value' => ['required', 'numeric'],
|
||||
'action_type' => ['required', 'string', 'max:255'],
|
||||
'level' => ['nullable', 'numeric', 'required_if:action_type,set_level'],
|
||||
'is_active' => ['boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\Device;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class DeviceRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
$device = $this->route('device');
|
||||
|
||||
return $device
|
||||
? $this->user()->can('update', $device)
|
||||
: $this->user()->can('create', Device::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$device = $this->route('device');
|
||||
|
||||
return [
|
||||
'zone_id' => ['required', 'exists:zones,id'],
|
||||
'device_type_id' => ['required', 'exists:device_types,id'],
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'external_id' => [
|
||||
'required', 'string', 'max:255',
|
||||
Rule::unique('devices', 'external_id')->ignore($device),
|
||||
],
|
||||
'protocol' => ['required', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\Zone;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class ZoneRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
$zone = $this->route('zone');
|
||||
|
||||
return $zone
|
||||
? $this->user()->can('update', $zone)
|
||||
: $this->user()->can('create', Zone::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'description' => ['nullable', 'string'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Models\AutomationRule;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin AutomationRule */
|
||||
class AutomationRuleResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'zone' => new ZoneResource($this->whenLoaded('zone')),
|
||||
'target_device' => new DeviceResource($this->whenLoaded('targetDevice')),
|
||||
'condition_source_device' => new DeviceResource($this->whenLoaded('conditionSourceDevice')),
|
||||
'condition_sensor_type' => $this->condition_sensor_type,
|
||||
'condition_operator' => $this->condition_operator->value,
|
||||
'condition_value' => $this->condition_value,
|
||||
'action_type' => $this->action_type,
|
||||
'action_params' => $this->action_params,
|
||||
'is_active' => $this->is_active,
|
||||
'created_at' => $this->created_at,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Models\Device;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin Device
|
||||
*
|
||||
* `devices.status` in Postgres is only a stale snapshot (see migration
|
||||
* comment) — Redis (Device Shadow) is authoritative. The controller stamps
|
||||
* the live value onto the model as `live_status` before wrapping it here;
|
||||
* `status` in the JSON always prefers that when present.
|
||||
*/
|
||||
class DeviceResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'external_id' => $this->external_id,
|
||||
'protocol' => $this->protocol,
|
||||
'status' => $this->live_status ?? $this->status,
|
||||
'zone' => new ZoneResource($this->whenLoaded('zone')),
|
||||
'device_type' => new DeviceTypeResource($this->whenLoaded('deviceType')),
|
||||
'created_at' => $this->created_at,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Models\DeviceType;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin DeviceType */
|
||||
class DeviceTypeResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'category' => $this->category->value,
|
||||
'capabilities' => $this->capabilities,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin User */
|
||||
class UserResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'email' => $this->email,
|
||||
'role' => $this->role->value,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Models\Zone;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin Zone */
|
||||
class ZoneResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'description' => $this->description,
|
||||
'devices_count' => $this->whenCounted('devices'),
|
||||
'created_at' => $this->created_at,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
];
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\AutomationRule;
|
||||
use App\Models\User;
|
||||
|
||||
/** See ZonePolicy for the household-wide RBAC rationale. */
|
||||
class AutomationRulePolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function view(User $user, AutomationRule $automationRule): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return $user->isOwner();
|
||||
}
|
||||
|
||||
public function update(User $user, AutomationRule $automationRule): bool
|
||||
{
|
||||
return $user->isOwner();
|
||||
}
|
||||
|
||||
public function delete(User $user, AutomationRule $automationRule): bool
|
||||
{
|
||||
return $user->isOwner();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\Device;
|
||||
use App\Models\User;
|
||||
|
||||
/** See ZonePolicy for the household-wide RBAC rationale. */
|
||||
class DevicePolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function view(User $user, Device $device): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return $user->isOwner();
|
||||
}
|
||||
|
||||
public function update(User $user, Device $device): bool
|
||||
{
|
||||
return $user->isOwner();
|
||||
}
|
||||
|
||||
public function delete(User $user, Device $device): bool
|
||||
{
|
||||
return $user->isOwner();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\Zone;
|
||||
|
||||
/**
|
||||
* Household-wide RBAC, not per-user tenant isolation: every authenticated
|
||||
* user (owner or viewer) sees the same zones, only `owner` can write.
|
||||
* `zones.user_id` records who registered the zone, it isn't a visibility
|
||||
* boundary.
|
||||
*/
|
||||
class ZonePolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function view(User $user, Zone $zone): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return $user->isOwner();
|
||||
}
|
||||
|
||||
public function update(User $user, Zone $zone): bool
|
||||
{
|
||||
return $user->isOwner();
|
||||
}
|
||||
|
||||
public function delete(User $user, Zone $zone): bool
|
||||
{
|
||||
return $user->isOwner();
|
||||
}
|
||||
}
|
||||
@@ -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'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
"php": "^8.3",
|
||||
"laravel/framework": "^13.8",
|
||||
"laravel/sanctum": "^4.0",
|
||||
"laravel/tinker": "^3.0"
|
||||
"laravel/tinker": "^3.0",
|
||||
"predis/predis": "^3.5"
|
||||
},
|
||||
"require-dev": {
|
||||
"fakerphp/faker": "^1.23",
|
||||
|
||||
Generated
+83
-20
@@ -4,7 +4,7 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "f1ab046cb80318325a9735c77c07672f",
|
||||
"content-hash": "483f1bf17688fcc178b8c1849ff31ddc",
|
||||
"packages": [
|
||||
{
|
||||
"name": "brick/math",
|
||||
@@ -642,21 +642,21 @@
|
||||
},
|
||||
{
|
||||
"name": "guzzlehttp/guzzle",
|
||||
"version": "7.15.1",
|
||||
"version": "7.15.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/guzzle/guzzle.git",
|
||||
"reference": "61443dfb33c62f308ee8add20f45b4d6e4bf8d2f"
|
||||
"reference": "ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/61443dfb33c62f308ee8add20f45b4d6e4bf8d2f",
|
||||
"reference": "61443dfb33c62f308ee8add20f45b4d6e4bf8d2f",
|
||||
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc",
|
||||
"reference": "ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"ext-json": "*",
|
||||
"guzzlehttp/promises": "^2.5.1",
|
||||
"guzzlehttp/promises": "^2.5.2",
|
||||
"guzzlehttp/psr7": "^2.13",
|
||||
"php": "^7.2.5 || ^8.0",
|
||||
"psr/http-client": "^1.0",
|
||||
@@ -750,7 +750,7 @@
|
||||
],
|
||||
"support": {
|
||||
"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": [
|
||||
{
|
||||
@@ -766,20 +766,20 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2026-07-18T11:23:11+00:00"
|
||||
"time": "2026-08-05T19:48:21+00:00"
|
||||
},
|
||||
{
|
||||
"name": "guzzlehttp/promises",
|
||||
"version": "2.5.1",
|
||||
"version": "2.5.2",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/guzzle/promises.git",
|
||||
"reference": "9ad1e4fc607446a055b95870c7f668e93b5cff29"
|
||||
"reference": "2823687acff28b2dbe67b2508a6b300e2c3fa4ce"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/guzzle/promises/zipball/9ad1e4fc607446a055b95870c7f668e93b5cff29",
|
||||
"reference": "9ad1e4fc607446a055b95870c7f668e93b5cff29",
|
||||
"url": "https://api.github.com/repos/guzzle/promises/zipball/2823687acff28b2dbe67b2508a6b300e2c3fa4ce",
|
||||
"reference": "2823687acff28b2dbe67b2508a6b300e2c3fa4ce",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -834,7 +834,7 @@
|
||||
],
|
||||
"support": {
|
||||
"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": [
|
||||
{
|
||||
@@ -850,7 +850,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2026-07-08T15:48:39+00:00"
|
||||
"time": "2026-08-05T19:30:54+00:00"
|
||||
},
|
||||
{
|
||||
"name": "guzzlehttp/psr7",
|
||||
@@ -1538,16 +1538,16 @@
|
||||
},
|
||||
{
|
||||
"name": "league/commonmark",
|
||||
"version": "2.8.3",
|
||||
"version": "2.9.2",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/thephpleague/commonmark.git",
|
||||
"reference": "1902f60f984235023acbe03db6ad614a37b3c3e7"
|
||||
"reference": "72e9a87efcf41a8e83be3ed0866b69d77565cb12"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/thephpleague/commonmark/zipball/1902f60f984235023acbe03db6ad614a37b3c3e7",
|
||||
"reference": "1902f60f984235023acbe03db6ad614a37b3c3e7",
|
||||
"url": "https://api.github.com/repos/thephpleague/commonmark/zipball/72e9a87efcf41a8e83be3ed0866b69d77565cb12",
|
||||
"reference": "72e9a87efcf41a8e83be3ed0866b69d77565cb12",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1584,7 +1584,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "2.9-dev"
|
||||
"dev-main": "2.10-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
@@ -1641,7 +1641,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2026-07-12T15:29:16+00:00"
|
||||
"time": "2026-08-11T00:58:45+00:00"
|
||||
},
|
||||
{
|
||||
"name": "league/config",
|
||||
@@ -2680,6 +2680,69 @@
|
||||
],
|
||||
"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",
|
||||
"version": "1.0.0",
|
||||
|
||||
@@ -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', ''),
|
||||
];
|
||||
@@ -35,4 +35,8 @@ return [
|
||||
],
|
||||
],
|
||||
|
||||
'device_control' => [
|
||||
'url' => env('DEVICE_CONTROL_HTTP_URL', 'http://localhost:8090'),
|
||||
],
|
||||
|
||||
];
|
||||
|
||||
@@ -22,6 +22,15 @@ class DatabaseSeeder extends Seeder
|
||||
'role' => UserRole::Owner,
|
||||
]);
|
||||
|
||||
$this->call(DeviceTypeSeeder::class);
|
||||
User::factory()->create([
|
||||
'name' => 'Test Viewer',
|
||||
'email' => 'viewer@example.com',
|
||||
'role' => UserRole::Viewer,
|
||||
]);
|
||||
|
||||
$this->call([
|
||||
DeviceTypeSeeder::class,
|
||||
DemoGrowboxSeeder::class,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Seeders;
|
||||
|
||||
use App\Models\AutomationRule;
|
||||
use App\Models\Device;
|
||||
use App\Models\DeviceType;
|
||||
use App\Models\User;
|
||||
use App\Models\Zone;
|
||||
use Illuminate\Database\Seeder;
|
||||
|
||||
/**
|
||||
* Demo data for the growbox zone — the first zone implemented on the
|
||||
* platform. Purely example content so the CRUD screens aren't empty on
|
||||
* first run; nothing here is special-cased in application code.
|
||||
*/
|
||||
class DemoGrowboxSeeder extends Seeder
|
||||
{
|
||||
public function run(): void
|
||||
{
|
||||
$owner = User::where('email', 'owner@example.com')->firstOrFail();
|
||||
|
||||
$zone = Zone::query()->firstOrCreate(
|
||||
['name' => 'Гроубокс'],
|
||||
['user_id' => $owner->id, 'description' => 'Демо-зона для проверки платформы']
|
||||
);
|
||||
|
||||
$sensorType = DeviceType::where('code', 'sensor_temp_humidity')->firstOrFail();
|
||||
$fanType = DeviceType::where('code', 'fan')->firstOrFail();
|
||||
|
||||
$sensor = Device::query()->firstOrCreate(
|
||||
['external_id' => 'sensor-1'],
|
||||
[
|
||||
'user_id' => $owner->id,
|
||||
'zone_id' => $zone->id,
|
||||
'device_type_id' => $sensorType->id,
|
||||
'name' => 'Датчик температуры',
|
||||
'protocol' => 'mqtt',
|
||||
]
|
||||
);
|
||||
|
||||
$fan = Device::query()->firstOrCreate(
|
||||
['external_id' => 'fan-1'],
|
||||
[
|
||||
'user_id' => $owner->id,
|
||||
'zone_id' => $zone->id,
|
||||
'device_type_id' => $fanType->id,
|
||||
'name' => 'Вентилятор',
|
||||
'protocol' => 'mqtt',
|
||||
]
|
||||
);
|
||||
|
||||
AutomationRule::query()->firstOrCreate(
|
||||
[
|
||||
'condition_source_device_id' => $sensor->id,
|
||||
'target_device_id' => $fan->id,
|
||||
],
|
||||
[
|
||||
'user_id' => $owner->id,
|
||||
'zone_id' => $zone->id,
|
||||
'condition_sensor_type' => 'temperature',
|
||||
'condition_operator' => '>',
|
||||
'condition_value' => 28,
|
||||
'action_type' => 'turn_on',
|
||||
'action_params' => [],
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
@csrf
|
||||
@isset($rule)
|
||||
@method('PUT')
|
||||
@endisset
|
||||
|
||||
<div x-data="{ actionType: '{{ old('action_type', $rule->action_type ?? '') }}' }">
|
||||
<div>
|
||||
<x-input-label for="zone_id" :value="__('Зона')" />
|
||||
<select id="zone_id" name="zone_id" required
|
||||
class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">
|
||||
<option value="">{{ __('— выбрать —') }}</option>
|
||||
@foreach ($zones as $zone)
|
||||
<option value="{{ $zone->id }}" @selected(old('zone_id', $rule->zone_id ?? '') == $zone->id)>{{ $zone->name }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
<x-input-error :messages="$errors->get('zone_id')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<x-input-label for="condition_source_device_id" :value="__('Устройство-источник показания')" />
|
||||
<select id="condition_source_device_id" name="condition_source_device_id" required
|
||||
class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">
|
||||
<option value="">{{ __('— выбрать —') }}</option>
|
||||
@foreach ($devices as $device)
|
||||
<option value="{{ $device->id }}" @selected(old('condition_source_device_id', $rule->condition_source_device_id ?? '') == $device->id)>
|
||||
{{ $device->zone->name }} — {{ $device->name }} ({{ $device->deviceType->code }})
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
<x-input-error :messages="$errors->get('condition_source_device_id')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<x-input-label for="condition_sensor_type" :value="__('Тип показания')" />
|
||||
<input list="sensor-types" id="condition_sensor_type" name="condition_sensor_type" type="text"
|
||||
value="{{ old('condition_sensor_type', $rule->condition_sensor_type ?? '') }}" required
|
||||
class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm" />
|
||||
<datalist id="sensor-types">
|
||||
@foreach ($sensorTypeOptions as $option)
|
||||
<option value="{{ $option }}"></option>
|
||||
@endforeach
|
||||
</datalist>
|
||||
<x-input-error :messages="$errors->get('condition_sensor_type')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<x-input-label for="condition_operator" :value="__('Оператор')" />
|
||||
<select id="condition_operator" name="condition_operator" required
|
||||
class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">
|
||||
@foreach (\App\Enums\ConditionOperator::cases() as $operator)
|
||||
<option value="{{ $operator->value }}" @selected(old('condition_operator', $rule->condition_operator->value ?? '') == $operator->value)>
|
||||
{{ $operator->value }}
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
<x-input-error :messages="$errors->get('condition_operator')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<x-input-label for="condition_value" :value="__('Порог')" />
|
||||
<x-text-input id="condition_value" name="condition_value" type="number" step="any" class="mt-1 block w-full"
|
||||
:value="old('condition_value', $rule->condition_value ?? '')" required />
|
||||
<x-input-error :messages="$errors->get('condition_value')" class="mt-2" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<x-input-label for="target_device_id" :value="__('Устройство-исполнитель')" />
|
||||
<select id="target_device_id" name="target_device_id" required
|
||||
class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">
|
||||
<option value="">{{ __('— выбрать —') }}</option>
|
||||
@foreach ($devices as $device)
|
||||
<option value="{{ $device->id }}" @selected(old('target_device_id', $rule->target_device_id ?? '') == $device->id)>
|
||||
{{ $device->zone->name }} — {{ $device->name }} ({{ $device->deviceType->code }})
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
<x-input-error :messages="$errors->get('target_device_id')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<x-input-label for="action_type" :value="__('Действие')" />
|
||||
<select id="action_type" name="action_type" required x-model="actionType"
|
||||
class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">
|
||||
<option value="">{{ __('— выбрать —') }}</option>
|
||||
@foreach ($actionTypeOptions as $option)
|
||||
<option value="{{ $option }}">{{ $option }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
<x-input-error :messages="$errors->get('action_type')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div x-show="actionType === 'set_level'">
|
||||
<x-input-label for="level" :value="__('Уровень')" />
|
||||
<x-text-input id="level" name="level" type="number" step="any" class="mt-1 block w-full"
|
||||
:value="old('level', $rule->action_params['level'] ?? '')" />
|
||||
<x-input-error :messages="$errors->get('level')" class="mt-2" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<label class="inline-flex items-center">
|
||||
<input type="hidden" name="is_active" value="0">
|
||||
<input type="checkbox" name="is_active" value="1" class="rounded border-gray-300 text-indigo-600 shadow-sm"
|
||||
@checked(old('is_active', $rule->is_active ?? true))>
|
||||
<span class="ms-2 text-sm text-gray-600">{{ __('Правило активно') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex items-center gap-4">
|
||||
<x-primary-button>{{ __('Сохранить') }}</x-primary-button>
|
||||
<a href="{{ route('automation-rules.index') }}" class="text-sm text-gray-600 hover:underline">{{ __('Отмена') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,15 @@
|
||||
<x-app-layout>
|
||||
<x-slot name="header">
|
||||
<h2 class="font-semibold text-xl text-gray-800 leading-tight">{{ __('Новое правило автоматизации') }}</h2>
|
||||
</x-slot>
|
||||
|
||||
<div class="py-12">
|
||||
<div class="max-w-2xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
|
||||
<form method="POST" action="{{ route('automation-rules.store') }}">
|
||||
@include('automation-rules._form')
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-app-layout>
|
||||
@@ -0,0 +1,15 @@
|
||||
<x-app-layout>
|
||||
<x-slot name="header">
|
||||
<h2 class="font-semibold text-xl text-gray-800 leading-tight">{{ __('Изменить правило автоматизации') }}</h2>
|
||||
</x-slot>
|
||||
|
||||
<div class="py-12">
|
||||
<div class="max-w-2xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
|
||||
<form method="POST" action="{{ route('automation-rules.update', $rule) }}">
|
||||
@include('automation-rules._form')
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-app-layout>
|
||||
@@ -0,0 +1,72 @@
|
||||
<x-app-layout>
|
||||
<x-slot name="header">
|
||||
<div class="flex justify-between items-center">
|
||||
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
|
||||
{{ __('Правила автоматизации') }}
|
||||
</h2>
|
||||
@can('create', \App\Models\AutomationRule::class)
|
||||
<x-primary-button onclick="window.location='{{ route('automation-rules.create') }}'">
|
||||
{{ __('Добавить правило') }}
|
||||
</x-primary-button>
|
||||
@endcan
|
||||
</div>
|
||||
</x-slot>
|
||||
|
||||
<div class="py-12">
|
||||
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
|
||||
@if (session('status'))
|
||||
<div class="mb-4 text-sm text-green-600">{{ session('status') }}</div>
|
||||
@endif
|
||||
|
||||
<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>
|
||||
<th class="py-2">{{ __('Активно') }}</th>
|
||||
<th class="py-2"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@forelse ($rules as $rule)
|
||||
<tr class="border-b">
|
||||
<td class="py-2">{{ $rule->zone->name }}</td>
|
||||
<td class="py-2">
|
||||
{{ $rule->conditionSourceDevice->name }}:
|
||||
{{ $rule->condition_sensor_type }}
|
||||
{{ $rule->condition_operator->value }}
|
||||
{{ $rule->condition_value }}
|
||||
</td>
|
||||
<td class="py-2">
|
||||
{{ $rule->targetDevice->name }}: {{ $rule->action_type }}
|
||||
@if (!empty($rule->action_params))
|
||||
({{ json_encode($rule->action_params) }})
|
||||
@endif
|
||||
</td>
|
||||
<td class="py-2">{{ $rule->is_active ? __('да') : __('нет') }}</td>
|
||||
<td class="py-2 text-right space-x-2">
|
||||
@can('update', $rule)
|
||||
<a href="{{ route('automation-rules.edit', $rule) }}" class="text-indigo-600 hover:underline">{{ __('Изменить') }}</a>
|
||||
@endcan
|
||||
@can('delete', $rule)
|
||||
<form method="POST" action="{{ route('automation-rules.destroy', $rule) }}" class="inline" onsubmit="return confirm('{{ __('Удалить правило?') }}')">
|
||||
@csrf
|
||||
@method('DELETE')
|
||||
<button type="submit" class="text-red-600 hover:underline">{{ __('Удалить') }}</button>
|
||||
</form>
|
||||
@endcan
|
||||
</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr>
|
||||
<td colspan="5" class="py-4 text-gray-500">{{ __('Правил пока нет.') }}</td>
|
||||
</tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-app-layout>
|
||||
@@ -6,12 +6,23 @@
|
||||
</x-slot>
|
||||
|
||||
<div class="py-12">
|
||||
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
|
||||
<div class="p-6 text-gray-900">
|
||||
{{ __("You're logged in!") }}
|
||||
</div>
|
||||
</div>
|
||||
<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">
|
||||
<div class="text-sm text-gray-500">{{ __('Зоны') }}</div>
|
||||
<div class="text-3xl font-semibold text-gray-900">{{ $zonesCount }}</div>
|
||||
</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-gray-900">{{ $devicesCount }}</div>
|
||||
</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">
|
||||
<div class="text-sm text-gray-500">{{ __('Активных правил') }}</div>
|
||||
<div class="text-3xl font-semibold text-gray-900">{{ $activeRulesCount }}</div>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</x-app-layout>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
@csrf
|
||||
@isset($device)
|
||||
@method('PUT')
|
||||
@endisset
|
||||
|
||||
<div>
|
||||
<x-input-label for="name" :value="__('Название')" />
|
||||
<x-text-input id="name" name="name" type="text" class="mt-1 block w-full"
|
||||
:value="old('name', $device->name ?? '')" required autofocus />
|
||||
<x-input-error :messages="$errors->get('name')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<x-input-label for="zone_id" :value="__('Зона')" />
|
||||
<select id="zone_id" name="zone_id" required
|
||||
class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">
|
||||
<option value="">{{ __('— выбрать —') }}</option>
|
||||
@foreach ($zones as $zone)
|
||||
<option value="{{ $zone->id }}" @selected(old('zone_id', $device->zone_id ?? '') == $zone->id)>{{ $zone->name }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
<x-input-error :messages="$errors->get('zone_id')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<x-input-label for="device_type_id" :value="__('Тип устройства')" />
|
||||
<select id="device_type_id" name="device_type_id" required
|
||||
class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">
|
||||
<option value="">{{ __('— выбрать —') }}</option>
|
||||
@foreach ($deviceTypes as $deviceType)
|
||||
<option value="{{ $deviceType->id }}" @selected(old('device_type_id', $device->device_type_id ?? '') == $deviceType->id)>
|
||||
{{ $deviceType->code }} ({{ $deviceType->category->value }})
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
<x-input-error :messages="$errors->get('device_type_id')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<x-input-label for="external_id" :value="__('External ID (идентификатор физического устройства)')" />
|
||||
<x-text-input id="external_id" name="external_id" type="text" class="mt-1 block w-full font-mono"
|
||||
:value="old('external_id', $device->external_id ?? '')" required />
|
||||
<x-input-error :messages="$errors->get('external_id')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<x-input-label for="protocol" :value="__('Протокол')" />
|
||||
<x-text-input id="protocol" name="protocol" type="text" class="mt-1 block w-full"
|
||||
:value="old('protocol', $device->protocol ?? 'mqtt')" required />
|
||||
<x-input-error :messages="$errors->get('protocol')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex items-center gap-4">
|
||||
<x-primary-button>{{ __('Сохранить') }}</x-primary-button>
|
||||
<a href="{{ route('devices.index') }}" class="text-sm text-gray-600 hover:underline">{{ __('Отмена') }}</a>
|
||||
</div>
|
||||
@@ -0,0 +1,15 @@
|
||||
<x-app-layout>
|
||||
<x-slot name="header">
|
||||
<h2 class="font-semibold text-xl text-gray-800 leading-tight">{{ __('Новое устройство') }}</h2>
|
||||
</x-slot>
|
||||
|
||||
<div class="py-12">
|
||||
<div class="max-w-xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
|
||||
<form method="POST" action="{{ route('devices.store') }}">
|
||||
@include('devices._form')
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-app-layout>
|
||||
@@ -0,0 +1,15 @@
|
||||
<x-app-layout>
|
||||
<x-slot name="header">
|
||||
<h2 class="font-semibold text-xl text-gray-800 leading-tight">{{ __('Изменить устройство') }}</h2>
|
||||
</x-slot>
|
||||
|
||||
<div class="py-12">
|
||||
<div class="max-w-xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
|
||||
<form method="POST" action="{{ route('devices.update', $device) }}">
|
||||
@include('devices._form')
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-app-layout>
|
||||
@@ -0,0 +1,77 @@
|
||||
<x-app-layout>
|
||||
<x-slot name="header">
|
||||
<div class="flex justify-between items-center">
|
||||
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
|
||||
{{ __('Устройства') }}
|
||||
</h2>
|
||||
@can('create', \App\Models\Device::class)
|
||||
<x-primary-button onclick="window.location='{{ route('devices.create') }}'">
|
||||
{{ __('Добавить устройство') }}
|
||||
</x-primary-button>
|
||||
@endcan
|
||||
</div>
|
||||
</x-slot>
|
||||
|
||||
<div class="py-12">
|
||||
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
|
||||
@if (session('status'))
|
||||
<div class="mb-4 text-sm text-green-600">{{ session('status') }}</div>
|
||||
@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">
|
||||
<thead>
|
||||
<tr class="border-b">
|
||||
<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"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@forelse ($devices as $device)
|
||||
@php $status = $statuses[$device->external_id] ?? 'unknown'; @endphp
|
||||
<tr class="border-b">
|
||||
<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->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 text-right space-x-2">
|
||||
@can('update', $device)
|
||||
<a href="{{ route('devices.edit', $device) }}" class="text-indigo-600 hover:underline">{{ __('Изменить') }}</a>
|
||||
@endcan
|
||||
@can('delete', $device)
|
||||
<form method="POST" action="{{ route('devices.destroy', $device) }}" class="inline" onsubmit="return confirm('{{ __('Удалить устройство?') }}')">
|
||||
@csrf
|
||||
@method('DELETE')
|
||||
<button type="submit" class="text-red-600 hover:underline">{{ __('Удалить') }}</button>
|
||||
</form>
|
||||
@endcan
|
||||
</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr>
|
||||
<td colspan="6" class="py-4 text-gray-500">{{ __('Устройств пока нет.') }}</td>
|
||||
</tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-app-layout>
|
||||
@@ -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>
|
||||
@@ -15,6 +15,15 @@
|
||||
<x-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')">
|
||||
{{ __('Dashboard') }}
|
||||
</x-nav-link>
|
||||
<x-nav-link :href="route('zones.index')" :active="request()->routeIs('zones.*')">
|
||||
{{ __('Зоны') }}
|
||||
</x-nav-link>
|
||||
<x-nav-link :href="route('devices.index')" :active="request()->routeIs('devices.*')">
|
||||
{{ __('Устройства') }}
|
||||
</x-nav-link>
|
||||
<x-nav-link :href="route('automation-rules.index')" :active="request()->routeIs('automation-rules.*')">
|
||||
{{ __('Правила') }}
|
||||
</x-nav-link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -70,6 +79,15 @@
|
||||
<x-responsive-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')">
|
||||
{{ __('Dashboard') }}
|
||||
</x-responsive-nav-link>
|
||||
<x-responsive-nav-link :href="route('zones.index')" :active="request()->routeIs('zones.*')">
|
||||
{{ __('Зоны') }}
|
||||
</x-responsive-nav-link>
|
||||
<x-responsive-nav-link :href="route('devices.index')" :active="request()->routeIs('devices.*')">
|
||||
{{ __('Устройства') }}
|
||||
</x-responsive-nav-link>
|
||||
<x-responsive-nav-link :href="route('automation-rules.index')" :active="request()->routeIs('automation-rules.*')">
|
||||
{{ __('Правила') }}
|
||||
</x-responsive-nav-link>
|
||||
</div>
|
||||
|
||||
<!-- Responsive Settings Options -->
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
@csrf
|
||||
@isset($zone)
|
||||
@method('PUT')
|
||||
@endisset
|
||||
|
||||
<div>
|
||||
<x-input-label for="name" :value="__('Название')" />
|
||||
<x-text-input id="name" name="name" type="text" class="mt-1 block w-full"
|
||||
:value="old('name', $zone->name ?? '')" required autofocus />
|
||||
<x-input-error :messages="$errors->get('name')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<x-input-label for="description" :value="__('Описание')" />
|
||||
<textarea id="description" name="description" rows="3"
|
||||
class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">{{ old('description', $zone->description ?? '') }}</textarea>
|
||||
<x-input-error :messages="$errors->get('description')" class="mt-2" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex items-center gap-4">
|
||||
<x-primary-button>{{ __('Сохранить') }}</x-primary-button>
|
||||
<a href="{{ route('zones.index') }}" class="text-sm text-gray-600 hover:underline">{{ __('Отмена') }}</a>
|
||||
</div>
|
||||
@@ -0,0 +1,15 @@
|
||||
<x-app-layout>
|
||||
<x-slot name="header">
|
||||
<h2 class="font-semibold text-xl text-gray-800 leading-tight">{{ __('Новая зона') }}</h2>
|
||||
</x-slot>
|
||||
|
||||
<div class="py-12">
|
||||
<div class="max-w-xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
|
||||
<form method="POST" action="{{ route('zones.store') }}">
|
||||
@include('zones._form')
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-app-layout>
|
||||
@@ -0,0 +1,15 @@
|
||||
<x-app-layout>
|
||||
<x-slot name="header">
|
||||
<h2 class="font-semibold text-xl text-gray-800 leading-tight">{{ __('Изменить зону') }}</h2>
|
||||
</x-slot>
|
||||
|
||||
<div class="py-12">
|
||||
<div class="max-w-xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
|
||||
<form method="POST" action="{{ route('zones.update', $zone) }}">
|
||||
@include('zones._form')
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-app-layout>
|
||||
@@ -0,0 +1,60 @@
|
||||
<x-app-layout>
|
||||
<x-slot name="header">
|
||||
<div class="flex justify-between items-center">
|
||||
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
|
||||
{{ __('Зоны') }}
|
||||
</h2>
|
||||
@can('create', \App\Models\Zone::class)
|
||||
<x-primary-button onclick="window.location='{{ route('zones.create') }}'">
|
||||
{{ __('Добавить зону') }}
|
||||
</x-primary-button>
|
||||
@endcan
|
||||
</div>
|
||||
</x-slot>
|
||||
|
||||
<div class="py-12">
|
||||
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
|
||||
@if (session('status'))
|
||||
<div class="mb-4 text-sm text-green-600">{{ session('status') }}</div>
|
||||
@endif
|
||||
|
||||
<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>
|
||||
<th class="py-2"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@forelse ($zones as $zone)
|
||||
<tr class="border-b">
|
||||
<td class="py-2">{{ $zone->name }}</td>
|
||||
<td class="py-2 text-gray-500">{{ $zone->description }}</td>
|
||||
<td class="py-2">{{ $zone->devices_count }}</td>
|
||||
<td class="py-2 text-right space-x-2">
|
||||
@can('update', $zone)
|
||||
<a href="{{ route('zones.edit', $zone) }}" class="text-indigo-600 hover:underline">{{ __('Изменить') }}</a>
|
||||
@endcan
|
||||
@can('delete', $zone)
|
||||
<form method="POST" action="{{ route('zones.destroy', $zone) }}" class="inline" onsubmit="return confirm('{{ __('Удалить зону?') }}')">
|
||||
@csrf
|
||||
@method('DELETE')
|
||||
<button type="submit" class="text-red-600 hover:underline">{{ __('Удалить') }}</button>
|
||||
</form>
|
||||
@endcan
|
||||
</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr>
|
||||
<td colspan="4" class="py-4 text-gray-500">{{ __('Зон пока нет.') }}</td>
|
||||
</tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-app-layout>
|
||||
@@ -1,8 +1,38 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Controllers\Api\V1\AuthController;
|
||||
use App\Http\Controllers\Api\V1\AutomationRuleController;
|
||||
use App\Http\Controllers\Api\V1\DeviceController;
|
||||
use App\Http\Controllers\Api\V1\DeviceTypeController;
|
||||
use App\Http\Controllers\Api\V1\ZoneController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::get('/user', function (Request $request) {
|
||||
return $request->user();
|
||||
})->middleware('auth:sanctum');
|
||||
Route::prefix('v1')->group(function () {
|
||||
Route::post('/login', [AuthController::class, 'login']);
|
||||
|
||||
Route::middleware('auth:sanctum')->group(function () {
|
||||
Route::post('/logout', [AuthController::class, 'logout']);
|
||||
Route::get('/me', [AuthController::class, 'me']);
|
||||
|
||||
Route::get('/zones', [ZoneController::class, 'index']);
|
||||
Route::post('/zones', [ZoneController::class, 'store']);
|
||||
Route::put('/zones/{zone}', [ZoneController::class, 'update']);
|
||||
Route::delete('/zones/{zone}', [ZoneController::class, 'destroy']);
|
||||
|
||||
Route::get('/device-types', [DeviceTypeController::class, 'index']);
|
||||
|
||||
Route::get('/devices', [DeviceController::class, 'index']);
|
||||
Route::post('/devices', [DeviceController::class, 'store']);
|
||||
Route::get('/devices/{device}', [DeviceController::class, 'show']);
|
||||
Route::put('/devices/{device}', [DeviceController::class, 'update']);
|
||||
Route::delete('/devices/{device}', [DeviceController::class, 'destroy']);
|
||||
Route::post('/devices/{device}/turn-on', [DeviceController::class, 'turnOn']);
|
||||
Route::post('/devices/{device}/turn-off', [DeviceController::class, 'turnOff']);
|
||||
Route::post('/devices/{device}/set-level', [DeviceController::class, 'setLevel']);
|
||||
|
||||
Route::get('/automation-rules', [AutomationRuleController::class, 'index']);
|
||||
Route::post('/automation-rules', [AutomationRuleController::class, 'store']);
|
||||
Route::put('/automation-rules/{automation_rule}', [AutomationRuleController::class, 'update']);
|
||||
Route::delete('/automation-rules/{automation_rule}', [AutomationRuleController::class, 'destroy']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,16 +1,45 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Controllers\AutomationRuleController;
|
||||
use App\Http\Controllers\DeviceController;
|
||||
use App\Http\Controllers\ProfileController;
|
||||
use App\Http\Controllers\ZoneController;
|
||||
use App\Models\AutomationRule;
|
||||
use App\Models\Device;
|
||||
use App\Models\Zone;
|
||||
use App\Services\DeviceShadow;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::get('/', function () {
|
||||
return view('welcome');
|
||||
});
|
||||
|
||||
Route::get('/dashboard', function () {
|
||||
return view('dashboard');
|
||||
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', [
|
||||
'zonesCount' => Zone::count(),
|
||||
'devicesCount' => $devices->count(),
|
||||
'onlineDevicesCount' => $onlineCount,
|
||||
'activeRulesCount' => AutomationRule::where('is_active', true)->count(),
|
||||
]);
|
||||
})->middleware(['auth', 'verified'])->name('dashboard');
|
||||
|
||||
Route::middleware(['auth', 'verified'])->group(function () {
|
||||
Route::resource('zones', ZoneController::class)->except('show');
|
||||
Route::resource('devices', DeviceController::class);
|
||||
Route::resource('automation-rules', AutomationRuleController::class)
|
||||
->except('show')
|
||||
->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::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
|
||||
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\V1;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AuthTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_login_issues_a_token(): void
|
||||
{
|
||||
$user = User::factory()->create([
|
||||
'role' => UserRole::Owner,
|
||||
'password' => bcrypt('secret1234'),
|
||||
]);
|
||||
|
||||
$response = $this->postJson('/api/v1/login', [
|
||||
'email' => $user->email,
|
||||
'password' => 'secret1234',
|
||||
'device_name' => 'iphone-15',
|
||||
]);
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonStructure(['token', 'user' => ['id', 'name', 'email', 'role']]);
|
||||
$this->assertDatabaseHas('personal_access_tokens', [
|
||||
'tokenable_id' => $user->id,
|
||||
'name' => 'iphone-15',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_login_rejects_wrong_password(): void
|
||||
{
|
||||
$user = User::factory()->create(['password' => bcrypt('secret1234')]);
|
||||
|
||||
$response = $this->postJson('/api/v1/login', [
|
||||
'email' => $user->email,
|
||||
'password' => 'wrong-password',
|
||||
'device_name' => 'iphone-15',
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
$response->assertJsonValidationErrors('email');
|
||||
}
|
||||
|
||||
public function test_authenticated_token_can_reach_protected_route(): void
|
||||
{
|
||||
$user = User::factory()->create(['password' => bcrypt('secret1234')]);
|
||||
|
||||
$token = $this->postJson('/api/v1/login', [
|
||||
'email' => $user->email,
|
||||
'password' => 'secret1234',
|
||||
'device_name' => 'iphone-15',
|
||||
])->json('token');
|
||||
|
||||
$this->withHeader('Authorization', "Bearer {$token}")
|
||||
->getJson('/api/v1/me')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.email', $user->email);
|
||||
}
|
||||
|
||||
public function test_logout_revokes_the_current_token(): void
|
||||
{
|
||||
$user = User::factory()->create(['password' => bcrypt('secret1234')]);
|
||||
|
||||
$tokenModel = $user->createToken('iphone-15');
|
||||
|
||||
$this->withHeader('Authorization', "Bearer {$tokenModel->plainTextToken}")
|
||||
->postJson('/api/v1/logout')
|
||||
->assertNoContent();
|
||||
|
||||
$this->assertDatabaseMissing('personal_access_tokens', ['id' => $tokenModel->accessToken->id]);
|
||||
}
|
||||
|
||||
public function test_guest_cannot_reach_protected_route(): void
|
||||
{
|
||||
$this->getJson('/api/v1/me')->assertUnauthorized();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\V1;
|
||||
|
||||
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 Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AutomationRuleApiTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function makeZoneWithDevices(User $owner): array
|
||||
{
|
||||
$zone = Zone::forceCreate(['user_id' => $owner->id, 'name' => 'Гроубокс']);
|
||||
|
||||
$sensorType = DeviceType::create([
|
||||
'code' => 'sensor_temp_humidity',
|
||||
'category' => DeviceCategory::Sensor,
|
||||
'capabilities' => ['temperature', 'humidity'],
|
||||
]);
|
||||
$fanType = DeviceType::create([
|
||||
'code' => 'fan',
|
||||
'category' => DeviceCategory::Actuator,
|
||||
'capabilities' => ['turn_on', 'turn_off', 'set_level'],
|
||||
]);
|
||||
|
||||
$sensor = Device::forceCreate([
|
||||
'user_id' => $owner->id, 'zone_id' => $zone->id, 'device_type_id' => $sensorType->id,
|
||||
'name' => 'Датчик', 'external_id' => 'sensor-1', 'protocol' => 'mqtt',
|
||||
]);
|
||||
$fan = Device::forceCreate([
|
||||
'user_id' => $owner->id, 'zone_id' => $zone->id, 'device_type_id' => $fanType->id,
|
||||
'name' => 'Вентилятор', 'external_id' => 'fan-1', 'protocol' => 'mqtt',
|
||||
]);
|
||||
|
||||
return [$zone, $sensor, $fan];
|
||||
}
|
||||
|
||||
public function test_owner_can_create_rule_with_turn_on_action(): void
|
||||
{
|
||||
$owner = User::factory()->create(['role' => UserRole::Owner]);
|
||||
[$zone, $sensor, $fan] = $this->makeZoneWithDevices($owner);
|
||||
|
||||
$response = $this->actingAs($owner)->postJson('/api/v1/automation-rules', [
|
||||
'zone_id' => $zone->id,
|
||||
'condition_source_device_id' => $sensor->id,
|
||||
'condition_sensor_type' => 'temperature',
|
||||
'condition_operator' => '>',
|
||||
'condition_value' => 28,
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'turn_on',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$response->assertCreated();
|
||||
// '{}', not '[]' — same PHP/Go empty-array-vs-object gotcha as the web controller.
|
||||
$this->assertDatabaseHas('automation_rules', [
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'turn_on',
|
||||
'action_params' => '{}',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_set_level_action_requires_and_stores_level_param(): void
|
||||
{
|
||||
$owner = User::factory()->create(['role' => UserRole::Owner]);
|
||||
[$zone, $sensor, $fan] = $this->makeZoneWithDevices($owner);
|
||||
|
||||
$missingLevel = $this->actingAs($owner)->postJson('/api/v1/automation-rules', [
|
||||
'zone_id' => $zone->id,
|
||||
'condition_source_device_id' => $sensor->id,
|
||||
'condition_sensor_type' => 'temperature',
|
||||
'condition_operator' => '>',
|
||||
'condition_value' => 28,
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'set_level',
|
||||
]);
|
||||
$missingLevel->assertJsonValidationErrors('level');
|
||||
|
||||
$response = $this->actingAs($owner)->postJson('/api/v1/automation-rules', [
|
||||
'zone_id' => $zone->id,
|
||||
'condition_source_device_id' => $sensor->id,
|
||||
'condition_sensor_type' => 'temperature',
|
||||
'condition_operator' => '>',
|
||||
'condition_value' => 28,
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'set_level',
|
||||
'level' => 42,
|
||||
]);
|
||||
|
||||
$response->assertCreated();
|
||||
$this->assertDatabaseHas('automation_rules', [
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'set_level',
|
||||
'action_params' => '{"level":42}',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_viewer_cannot_create_rule(): void
|
||||
{
|
||||
$owner = User::factory()->create(['role' => UserRole::Owner]);
|
||||
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
|
||||
[$zone, $sensor, $fan] = $this->makeZoneWithDevices($owner);
|
||||
|
||||
$response = $this->actingAs($viewer)->postJson('/api/v1/automation-rules', [
|
||||
'zone_id' => $zone->id,
|
||||
'condition_source_device_id' => $sensor->id,
|
||||
'condition_sensor_type' => 'temperature',
|
||||
'condition_operator' => '>',
|
||||
'condition_value' => 28,
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'turn_on',
|
||||
]);
|
||||
|
||||
$response->assertForbidden();
|
||||
$this->assertDatabaseCount('automation_rules', 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\V1;
|
||||
|
||||
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 DeviceApiTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function makeDevice(User $owner, array $capabilities, string $category = DeviceCategory::Actuator->value): Device
|
||||
{
|
||||
$zone = Zone::forceCreate(['user_id' => $owner->id, 'name' => 'Гроубокс']);
|
||||
$type = DeviceType::create([
|
||||
'code' => 'fan',
|
||||
'category' => $category,
|
||||
'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_index_includes_live_status_from_shadow(): void
|
||||
{
|
||||
$owner = User::factory()->create(['role' => UserRole::Owner]);
|
||||
$device = $this->makeDevice($owner, ['turn_on']);
|
||||
|
||||
$this->mock(DeviceShadow::class, function ($mock) {
|
||||
$mock->shouldReceive('statuses')->once()->with(['fan-1'])->andReturn(['fan-1' => 'online']);
|
||||
});
|
||||
|
||||
$response = $this->actingAs($owner)->getJson('/api/v1/devices');
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonPath('data.0.status', 'online');
|
||||
$response->assertJsonPath('data.0.external_id', $device->external_id);
|
||||
}
|
||||
|
||||
public function test_show_includes_shadow_snapshot_and_telemetry(): void
|
||||
{
|
||||
$owner = User::factory()->create(['role' => UserRole::Owner]);
|
||||
$device = $this->makeDevice($owner, ['temperature'], DeviceCategory::Sensor->value);
|
||||
|
||||
$this->mock(DeviceShadow::class, function ($mock) {
|
||||
$mock->shouldReceive('snapshot')->once()->with('fan-1')->andReturn([
|
||||
'status' => 'online',
|
||||
'last_seen' => null,
|
||||
'desired_state' => [],
|
||||
'reported_state' => ['temperature' => 24.5],
|
||||
]);
|
||||
});
|
||||
$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)->getJson("/api/v1/devices/{$device->id}");
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonPath('data.status', 'online');
|
||||
$response->assertJsonPath('shadow.reported_state.temperature', 24.5);
|
||||
$response->assertJsonPath('telemetry.0.sensor_type', 'temperature');
|
||||
}
|
||||
|
||||
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)->postJson("/api/v1/devices/{$device->id}/turn-on");
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonPath('message', 'Команда отправлена.');
|
||||
}
|
||||
|
||||
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)->postJson("/api/v1/devices/{$device->id}/turn-on");
|
||||
|
||||
$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)->postJson("/api/v1/devices/{$device->id}/turn-on");
|
||||
|
||||
$response->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_failed_command_returns_422_with_message(): 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)->postJson("/api/v1/devices/{$device->id}/turn-on");
|
||||
|
||||
$response->assertStatus(422);
|
||||
$response->assertJsonPath('message', 'device offline');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\V1;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\User;
|
||||
use App\Models\Zone;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ZoneApiTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_owner_can_create_zone(): void
|
||||
{
|
||||
$owner = User::factory()->create(['role' => UserRole::Owner]);
|
||||
|
||||
$response = $this->actingAs($owner)->postJson('/api/v1/zones', [
|
||||
'name' => 'Гостиная',
|
||||
'description' => 'Тест',
|
||||
]);
|
||||
|
||||
$response->assertCreated();
|
||||
$response->assertJsonPath('data.name', 'Гостиная');
|
||||
$this->assertDatabaseHas('zones', ['name' => 'Гостиная', 'user_id' => $owner->id]);
|
||||
}
|
||||
|
||||
public function test_viewer_cannot_create_zone(): void
|
||||
{
|
||||
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
|
||||
|
||||
$response = $this->actingAs($viewer)->postJson('/api/v1/zones', ['name' => 'Гостиная']);
|
||||
|
||||
$response->assertForbidden();
|
||||
$this->assertDatabaseMissing('zones', ['name' => 'Гостиная']);
|
||||
}
|
||||
|
||||
public function test_viewer_can_list_zones(): void
|
||||
{
|
||||
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
|
||||
Zone::forceCreate(['user_id' => $viewer->id, 'name' => 'Гроубокс']);
|
||||
|
||||
$response = $this->actingAs($viewer)->getJson('/api/v1/zones');
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonPath('data.0.name', 'Гроубокс');
|
||||
}
|
||||
|
||||
public function test_viewer_cannot_delete_zone(): void
|
||||
{
|
||||
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
|
||||
$zone = Zone::forceCreate(['user_id' => $viewer->id, 'name' => 'Гроубокс']);
|
||||
|
||||
$response = $this->actingAs($viewer)->deleteJson("/api/v1/zones/{$zone->id}");
|
||||
|
||||
$response->assertForbidden();
|
||||
$this->assertDatabaseHas('zones', ['id' => $zone->id]);
|
||||
}
|
||||
|
||||
public function test_guest_gets_401(): void
|
||||
{
|
||||
$this->getJson('/api/v1/zones')->assertUnauthorized();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?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 Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AutomationRuleControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function makeZoneWithDevices(User $owner): array
|
||||
{
|
||||
$zone = Zone::forceCreate(['user_id' => $owner->id, 'name' => 'Гроубокс']);
|
||||
|
||||
$sensorType = DeviceType::create([
|
||||
'code' => 'sensor_temp_humidity',
|
||||
'category' => DeviceCategory::Sensor,
|
||||
'capabilities' => ['temperature', 'humidity'],
|
||||
]);
|
||||
$fanType = DeviceType::create([
|
||||
'code' => 'fan',
|
||||
'category' => DeviceCategory::Actuator,
|
||||
'capabilities' => ['turn_on', 'turn_off', 'set_level'],
|
||||
]);
|
||||
|
||||
$sensor = Device::forceCreate([
|
||||
'user_id' => $owner->id, 'zone_id' => $zone->id, 'device_type_id' => $sensorType->id,
|
||||
'name' => 'Датчик', 'external_id' => 'sensor-1', 'protocol' => 'mqtt',
|
||||
]);
|
||||
$fan = Device::forceCreate([
|
||||
'user_id' => $owner->id, 'zone_id' => $zone->id, 'device_type_id' => $fanType->id,
|
||||
'name' => 'Вентилятор', 'external_id' => 'fan-1', 'protocol' => 'mqtt',
|
||||
]);
|
||||
|
||||
return [$zone, $sensor, $fan];
|
||||
}
|
||||
|
||||
public function test_owner_can_create_rule_with_turn_on_action(): void
|
||||
{
|
||||
$owner = User::factory()->create(['role' => UserRole::Owner]);
|
||||
[$zone, $sensor, $fan] = $this->makeZoneWithDevices($owner);
|
||||
|
||||
$response = $this->actingAs($owner)->post(route('automation-rules.store'), [
|
||||
'zone_id' => $zone->id,
|
||||
'condition_source_device_id' => $sensor->id,
|
||||
'condition_sensor_type' => 'temperature',
|
||||
'condition_operator' => '>',
|
||||
'condition_value' => 28,
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'turn_on',
|
||||
'is_active' => '1',
|
||||
]);
|
||||
|
||||
$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', [
|
||||
'condition_source_device_id' => $sensor->id,
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'turn_on',
|
||||
'action_params' => '{}',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_set_level_action_requires_and_stores_level_param(): void
|
||||
{
|
||||
$owner = User::factory()->create(['role' => UserRole::Owner]);
|
||||
[$zone, $sensor, $fan] = $this->makeZoneWithDevices($owner);
|
||||
|
||||
// Missing level should fail validation.
|
||||
$missingLevel = $this->actingAs($owner)->post(route('automation-rules.store'), [
|
||||
'zone_id' => $zone->id,
|
||||
'condition_source_device_id' => $sensor->id,
|
||||
'condition_sensor_type' => 'temperature',
|
||||
'condition_operator' => '>',
|
||||
'condition_value' => 28,
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'set_level',
|
||||
]);
|
||||
$missingLevel->assertSessionHasErrors('level');
|
||||
|
||||
$response = $this->actingAs($owner)->post(route('automation-rules.store'), [
|
||||
'zone_id' => $zone->id,
|
||||
'condition_source_device_id' => $sensor->id,
|
||||
'condition_sensor_type' => 'temperature',
|
||||
'condition_operator' => '>',
|
||||
'condition_value' => 28,
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'set_level',
|
||||
'level' => 42,
|
||||
]);
|
||||
|
||||
$response->assertRedirect(route('automation-rules.index'));
|
||||
$this->assertDatabaseHas('automation_rules', [
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'set_level',
|
||||
'action_params' => '{"level":42}',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_viewer_cannot_create_rule(): void
|
||||
{
|
||||
$owner = User::factory()->create(['role' => UserRole::Owner]);
|
||||
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
|
||||
[$zone, $sensor, $fan] = $this->makeZoneWithDevices($owner);
|
||||
|
||||
$response = $this->actingAs($viewer)->post(route('automation-rules.store'), [
|
||||
'zone_id' => $zone->id,
|
||||
'condition_source_device_id' => $sensor->id,
|
||||
'condition_sensor_type' => 'temperature',
|
||||
'condition_operator' => '>',
|
||||
'condition_value' => 28,
|
||||
'target_device_id' => $fan->id,
|
||||
'action_type' => 'turn_on',
|
||||
]);
|
||||
|
||||
$response->assertForbidden();
|
||||
$this->assertDatabaseCount('automation_rules', 0);
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\User;
|
||||
use App\Models\Zone;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ZoneControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_owner_can_create_zone(): void
|
||||
{
|
||||
$owner = User::factory()->create(['role' => UserRole::Owner]);
|
||||
|
||||
$response = $this->actingAs($owner)->post(route('zones.store'), [
|
||||
'name' => 'Гостиная',
|
||||
'description' => 'Тест',
|
||||
]);
|
||||
|
||||
$response->assertRedirect(route('zones.index'));
|
||||
$this->assertDatabaseHas('zones', ['name' => 'Гостиная', 'user_id' => $owner->id]);
|
||||
}
|
||||
|
||||
public function test_viewer_cannot_create_zone(): void
|
||||
{
|
||||
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
|
||||
|
||||
$response = $this->actingAs($viewer)->post(route('zones.store'), [
|
||||
'name' => 'Гостиная',
|
||||
]);
|
||||
|
||||
$response->assertForbidden();
|
||||
$this->assertDatabaseMissing('zones', ['name' => 'Гостиная']);
|
||||
}
|
||||
|
||||
public function test_viewer_can_view_zones_index(): void
|
||||
{
|
||||
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
|
||||
Zone::forceCreate(['user_id' => $viewer->id, 'name' => 'Гроубокс']);
|
||||
|
||||
$response = $this->actingAs($viewer)->get(route('zones.index'));
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertSee('Гроубокс');
|
||||
}
|
||||
|
||||
public function test_viewer_cannot_delete_zone(): void
|
||||
{
|
||||
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
|
||||
$zone = Zone::forceCreate(['user_id' => $viewer->id, 'name' => 'Гроубокс']);
|
||||
|
||||
$response = $this->actingAs($viewer)->delete(route('zones.destroy', $zone));
|
||||
|
||||
$response->assertForbidden();
|
||||
$this->assertDatabaseHas('zones', ['id' => $zone->id]);
|
||||
}
|
||||
|
||||
public function test_guest_is_redirected_to_login(): void
|
||||
{
|
||||
$response = $this->get(route('zones.index'));
|
||||
|
||||
$response->assertRedirect(route('login'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"uid": "automation-devices",
|
||||
"title": "Automation & Devices",
|
||||
"tags": ["home-automation"],
|
||||
"timezone": "browser",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"refresh": "10s",
|
||||
"time": { "from": "now-30m", "to": "now" },
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Rules triggered (rate, by outcome)",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "Prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 0 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (outcome) (rate(rule_engine_rules_triggered_total[1m]))",
|
||||
"legendFormat": "{{outcome}}",
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "device-control-service dispatch duration (p95, by action)",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "Prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 0 },
|
||||
"fieldConfig": { "defaults": { "unit": "s" }, "overrides": [] },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "histogram_quantile(0.95, sum(rate(rule_engine_dispatch_duration_seconds_bucket[5m])) by (le, action_type))",
|
||||
"legendFormat": "{{action_type}}",
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "Device commands (rate, by action + outcome)",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "Prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 8 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (action, outcome) (rate(device_control_commands_total[1m]))",
|
||||
"legendFormat": "{{action}} / {{outcome}}",
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "Device online/offline transitions (rate)",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "Prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 8 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (direction) (rate(device_control_health_transitions_total[5m]))",
|
||||
"legendFormat": "{{direction}}",
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Automation rule cache refreshes (rate, by outcome)",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "Prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 16 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (outcome) (rate(rule_engine_cache_refresh_total[1m]))",
|
||||
"legendFormat": "{{outcome}}",
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: default
|
||||
orgId: 1
|
||||
folder: ""
|
||||
type: file
|
||||
disableDeletion: false
|
||||
updateIntervalSeconds: 30
|
||||
options:
|
||||
path: /etc/grafana/provisioning/dashboards
|
||||
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"uid": "ingest-telemetry",
|
||||
"title": "Ingest & Telemetry",
|
||||
"tags": ["home-automation"],
|
||||
"timezone": "browser",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"refresh": "10s",
|
||||
"time": { "from": "now-30m", "to": "now" },
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "MQTT messages received (rate)",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "Prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 0 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(ingest_mqtt_messages_received_total[1m]))",
|
||||
"legendFormat": "received/s",
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "MQTT messages invalid / dropped (rate)",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "Prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 0 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(ingest_mqtt_messages_invalid_total[1m]))",
|
||||
"legendFormat": "invalid/s",
|
||||
"refId": "A"
|
||||
},
|
||||
{
|
||||
"expr": "sum(rate(ingest_mqtt_messages_dropped_total[1m]))",
|
||||
"legendFormat": "dropped (backlog full)/s",
|
||||
"refId": "B"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "ClickHouse batch flushes (rate, by outcome)",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "Prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 8 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (outcome) (rate(ingest_batch_flush_total[1m]))",
|
||||
"legendFormat": "{{outcome}}",
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "ClickHouse batch flush duration (p95)",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "Prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 8 },
|
||||
"fieldConfig": { "defaults": { "unit": "s" }, "overrides": [] },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "histogram_quantile(0.95, sum(rate(ingest_batch_flush_duration_seconds_bucket[5m])) by (le))",
|
||||
"legendFormat": "p95",
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "RabbitMQ publishes (rate, by outcome)",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "Prometheus" },
|
||||
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 16 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (outcome) (rate(ingest_rabbitmq_publish_total[1m]))",
|
||||
"legendFormat": "{{outcome}}",
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
@@ -0,0 +1,15 @@
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
|
||||
scrape_configs:
|
||||
- job_name: ingest-service
|
||||
static_configs:
|
||||
- targets: ["ingest-service:9101"]
|
||||
|
||||
- job_name: device-control-service
|
||||
static_configs:
|
||||
- targets: ["device-control-service:8090"]
|
||||
|
||||
- job_name: rule-engine-service
|
||||
static_configs:
|
||||
- targets: ["rule-engine-service:9102"]
|
||||
@@ -5,8 +5,11 @@
|
||||
Зона ответственности:
|
||||
- Предоставляет gRPC API (см. `proto/device_control/device_control.proto`:
|
||||
`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`)
|
||||
и слушает подтверждения (`devices/{device_id}/ack`).
|
||||
- Поддерживает паттерн Device Shadow в Redis: `desired_state` (чего хочет
|
||||
@@ -37,6 +40,21 @@
|
||||
телеметрии/ack, а не выгружается из таблицы `devices`. Это удерживает
|
||||
сервис в границах MQTT+Redis+RabbitMQ+gRPC, как и в диаграмме архитектуры
|
||||
корневого 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)
|
||||
не тронут.
|
||||
|
||||
## Метрики
|
||||
|
||||
`GET /metrics` на том же порту, что и команды (`DEVICE_CONTROL_HTTP_PORT`)
|
||||
— не открывали отдельный порт ради этого. Счётчики/latency команд
|
||||
(TurnOn/TurnOff/SetLevel по action+outcome), MQTT-событий (telemetry/ack),
|
||||
переходов online/offline health-check.
|
||||
|
||||
## Запуск
|
||||
|
||||
|
||||
@@ -9,17 +9,21 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
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/healthcheck"
|
||||
"git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/httpapi"
|
||||
"git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/metrics"
|
||||
"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/server"
|
||||
@@ -72,6 +76,8 @@ func run(logger *slog.Logger) error {
|
||||
}
|
||||
|
||||
checker := healthcheck.New(shadowStore, cfg.HealthCheckTimeout, cfg.HealthCheckInterval, func(deviceID string) {
|
||||
metrics.HealthTransitionsTotal.WithLabelValues("offline").Inc()
|
||||
|
||||
pubCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := publisher.PublishStatusChanged(pubCtx, deviceID, shadow.StatusOffline); err != nil {
|
||||
@@ -81,20 +87,40 @@ func run(logger *slog.Logger) error {
|
||||
checker.Start()
|
||||
defer checker.Stop()
|
||||
|
||||
srv := server.New(shadowStore, mqttClient, logger)
|
||||
|
||||
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", cfg.GRPCPort))
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen on grpc port %d: %w", cfg.GRPCPort, err)
|
||||
}
|
||||
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). /metrics rides
|
||||
// along on this same port rather than opening a third one.
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/", httpapi.NewRouter(srv, logger))
|
||||
mux.Handle("/metrics", promhttp.Handler())
|
||||
httpServer := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", cfg.HTTPPort),
|
||||
Handler: mux,
|
||||
}
|
||||
|
||||
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 {
|
||||
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)
|
||||
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-stop
|
||||
@@ -102,6 +128,12 @@ func run(logger *slog.Logger) error {
|
||||
logger.Info("shutting down")
|
||||
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
|
||||
}
|
||||
|
||||
@@ -121,8 +153,10 @@ func telemetryHandler(store *shadow.Store, publisher *rabbitmq.Publisher, logger
|
||||
deviceID, ok := deviceIDFromTopic(topic)
|
||||
if !ok {
|
||||
logger.Warn("dropping telemetry from unparseable topic", "topic", topic)
|
||||
metrics.MQTTEventsTotal.WithLabelValues("telemetry", "invalid").Inc()
|
||||
return
|
||||
}
|
||||
metrics.MQTTEventsTotal.WithLabelValues("telemetry", "ok").Inc()
|
||||
touch(context.Background(), store, publisher, deviceID, logger)
|
||||
}
|
||||
}
|
||||
@@ -136,14 +170,17 @@ func ackHandler(store *shadow.Store, publisher *rabbitmq.Publisher, logger *slog
|
||||
deviceID, ok := deviceIDFromTopic(topic)
|
||||
if !ok {
|
||||
logger.Warn("dropping ack from unparseable topic", "topic", topic)
|
||||
metrics.MQTTEventsTotal.WithLabelValues("ack", "invalid").Inc()
|
||||
return
|
||||
}
|
||||
|
||||
var ack ackPayload
|
||||
if err := json.Unmarshal(payload, &ack); err != nil {
|
||||
logger.Warn("dropping invalid ack payload", "device_id", deviceID, "error", err)
|
||||
metrics.MQTTEventsTotal.WithLabelValues("ack", "invalid").Inc()
|
||||
return
|
||||
}
|
||||
metrics.MQTTEventsTotal.WithLabelValues("ack", "ok").Inc()
|
||||
|
||||
ctx := context.Background()
|
||||
if len(ack.State) > 0 {
|
||||
@@ -162,6 +199,8 @@ func touch(ctx context.Context, store *shadow.Store, publisher *rabbitmq.Publish
|
||||
return
|
||||
}
|
||||
if becameOnline {
|
||||
metrics.HealthTransitionsTotal.WithLabelValues("online").Inc()
|
||||
|
||||
pubCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := publisher.PublishStatusChanged(pubCtx, deviceID, shadow.StatusOnline); err != nil {
|
||||
|
||||
@@ -6,20 +6,27 @@ require (
|
||||
git.cactoz.su/cacto/home_automatization/proto v0.0.0
|
||||
github.com/alicebob/miniredis/v2 v2.38.0
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
github.com/rabbitmq/amqp091-go v1.13.0
|
||||
github.com/redis/go-redis/v9 v9.21.0
|
||||
google.golang.org/grpc v1.82.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/net v0.53.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
github.com/alicebob/miniredis/v2 v2.38.0 h1:nZAzCR+Lj+Vxk4ZXzm2NuKq2O33RXj1XxJ2e2uP9jiw=
|
||||
github.com/alicebob/miniredis/v2 v2.38.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
@@ -22,16 +24,30 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/rabbitmq/amqp091-go v1.13.0 h1:L8NA1WtF76C6KA3LAoufjfLgbist/If1UQYcsOjtxXA=
|
||||
github.com/rabbitmq/amqp091-go v1.13.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/redis/go-redis/v9 v9.21.0 h1:FPBE4hhbAke+TLmcY3WkpbDffJEomdqPn3HYiqAtL9E=
|
||||
github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
|
||||
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
@@ -52,14 +68,16 @@ go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw=
|
||||
@@ -68,3 +86,5 @@ google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
|
||||
google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
type Config struct {
|
||||
GRPCPort int
|
||||
HTTPPort int
|
||||
|
||||
MQTTBrokerURL string
|
||||
MQTTClientID string
|
||||
@@ -45,6 +46,9 @@ func Load() (Config, error) {
|
||||
if cfg.GRPCPort, err = getEnvInt("DEVICE_CONTROL_GRPC_PORT", 50051); err != nil {
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Package metrics defines device-control-service's Prometheus metrics.
|
||||
// Registered automatically (via promauto) into the default registry on
|
||||
// import; served alongside the command HTTP API's /metrics route.
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
)
|
||||
|
||||
var (
|
||||
CommandsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "device_control_commands_total",
|
||||
Help: "Total number of TurnOn/TurnOff/SetLevel commands dispatched, by action and outcome.",
|
||||
}, []string{"action", "outcome"})
|
||||
|
||||
CommandDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Name: "device_control_command_duration_seconds",
|
||||
Help: "Duration of a command dispatch (Redis desired_state patch + MQTT publish), by action.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}, []string{"action"})
|
||||
|
||||
MQTTEventsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "device_control_mqtt_events_total",
|
||||
Help: "Total number of telemetry/ack messages received, by event type and outcome.",
|
||||
}, []string{"event_type", "outcome"})
|
||||
|
||||
HealthTransitionsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "device_control_health_transitions_total",
|
||||
Help: "Total number of device online/offline transitions detected.",
|
||||
}, []string{"direction"})
|
||||
)
|
||||
@@ -9,8 +9,10 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
devicecontrol "git.cactoz.su/cacto/home_automatization/proto/device_control"
|
||||
"git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/metrics"
|
||||
)
|
||||
|
||||
// ShadowPatcher is the subset of shadow.Store the server needs.
|
||||
@@ -36,21 +38,21 @@ func New(shadow ShadowPatcher, mqtt CommandPublisher, logger *slog.Logger) *Serv
|
||||
}
|
||||
|
||||
func (s *Server) TurnOn(ctx context.Context, req *devicecontrol.TurnOnRequest) (*devicecontrol.CommandResult, error) {
|
||||
return s.dispatch(ctx, req.GetDeviceId(),
|
||||
return s.dispatch(ctx, "turn_on", req.GetDeviceId(),
|
||||
map[string]any{"power": "on"},
|
||||
map[string]any{"action": "turn_on"},
|
||||
)
|
||||
}
|
||||
|
||||
func (s *Server) TurnOff(ctx context.Context, req *devicecontrol.TurnOffRequest) (*devicecontrol.CommandResult, error) {
|
||||
return s.dispatch(ctx, req.GetDeviceId(),
|
||||
return s.dispatch(ctx, "turn_off", req.GetDeviceId(),
|
||||
map[string]any{"power": "off"},
|
||||
map[string]any{"action": "turn_off"},
|
||||
)
|
||||
}
|
||||
|
||||
func (s *Server) SetLevel(ctx context.Context, req *devicecontrol.SetLevelRequest) (*devicecontrol.CommandResult, error) {
|
||||
return s.dispatch(ctx, req.GetDeviceId(),
|
||||
return s.dispatch(ctx, "set_level", req.GetDeviceId(),
|
||||
map[string]any{"level": req.GetLevel()},
|
||||
map[string]any{"action": "set_level", "level": req.GetLevel()},
|
||||
)
|
||||
@@ -60,27 +62,41 @@ func (s *Server) SetLevel(ctx context.Context, req *devicecontrol.SetLevelReques
|
||||
// gets an instant, optimistic view even if the device is offline), then hand
|
||||
// the command to MQTT. Business failures come back as CommandResult.Error,
|
||||
// not a gRPC error — the wire contract is success/error in one message.
|
||||
func (s *Server) dispatch(ctx context.Context, deviceID string, desiredPatch, commandPayload map[string]any) (*devicecontrol.CommandResult, error) {
|
||||
func (s *Server) dispatch(ctx context.Context, action, deviceID string, desiredPatch, commandPayload map[string]any) (*devicecontrol.CommandResult, error) {
|
||||
start := time.Now()
|
||||
result := s.doDispatch(ctx, action, deviceID, desiredPatch, commandPayload)
|
||||
|
||||
metrics.CommandDuration.WithLabelValues(action).Observe(time.Since(start).Seconds())
|
||||
outcome := "success"
|
||||
if !result.Success {
|
||||
outcome = "error"
|
||||
}
|
||||
metrics.CommandsTotal.WithLabelValues(action, outcome).Inc()
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Server) doDispatch(ctx context.Context, action, deviceID string, desiredPatch, commandPayload map[string]any) *devicecontrol.CommandResult {
|
||||
if deviceID == "" {
|
||||
return &devicecontrol.CommandResult{Success: false, Error: "device_id is required"}, nil
|
||||
return &devicecontrol.CommandResult{Success: false, Error: "device_id is required"}
|
||||
}
|
||||
|
||||
if err := s.shadow.PatchDesiredState(ctx, deviceID, desiredPatch); err != nil {
|
||||
s.logger.Error("patch desired state failed", "device_id", deviceID, "error", err)
|
||||
return &devicecontrol.CommandResult{Success: false, Error: "failed to update desired state"}, nil
|
||||
s.logger.Error("patch desired state failed", "action", action, "device_id", deviceID, "error", err)
|
||||
return &devicecontrol.CommandResult{Success: false, Error: "failed to update desired state"}
|
||||
}
|
||||
|
||||
body, err := json.Marshal(commandPayload)
|
||||
if err != nil {
|
||||
s.logger.Error("encode command failed", "device_id", deviceID, "error", err)
|
||||
return &devicecontrol.CommandResult{Success: false, Error: "failed to encode command"}, nil
|
||||
s.logger.Error("encode command failed", "action", action, "device_id", deviceID, "error", err)
|
||||
return &devicecontrol.CommandResult{Success: false, Error: "failed to encode command"}
|
||||
}
|
||||
|
||||
topic := fmt.Sprintf("devices/%s/commands", deviceID)
|
||||
if err := s.mqtt.Publish(topic, 1, false, body); err != nil {
|
||||
s.logger.Error("publish command failed", "device_id", deviceID, "topic", topic, "error", err)
|
||||
return &devicecontrol.CommandResult{Success: false, Error: "failed to dispatch command"}, nil
|
||||
s.logger.Error("publish command failed", "action", action, "device_id", deviceID, "topic", topic, "error", err)
|
||||
return &devicecontrol.CommandResult{Success: false, Error: "failed to dispatch command"}
|
||||
}
|
||||
|
||||
return &devicecontrol.CommandResult{Success: true}, nil
|
||||
return &devicecontrol.CommandResult{Success: true}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/testutil"
|
||||
|
||||
devicecontrol "git.cactoz.su/cacto/home_automatization/proto/device_control"
|
||||
"git.cactoz.su/cacto/home_automatization/services/device-control-service/internal/metrics"
|
||||
)
|
||||
|
||||
type fakeShadow struct {
|
||||
@@ -122,3 +125,27 @@ func TestDispatch_PublishFailure(t *testing.T) {
|
||||
t.Fatal("expected failure when mqtt publish errors")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatch_RecordsMetrics(t *testing.T) {
|
||||
successCounter := metrics.CommandsTotal.WithLabelValues("turn_on", "success")
|
||||
errorCounter := metrics.CommandsTotal.WithLabelValues("turn_on", "error")
|
||||
before := testutil.ToFloat64(successCounter)
|
||||
|
||||
s := New(&fakeShadow{}, &fakeMQTT{}, discardLogger())
|
||||
if _, err := s.TurnOn(context.Background(), &devicecontrol.TurnOnRequest{DeviceId: "d1"}); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if got := testutil.ToFloat64(successCounter); got != before+1 {
|
||||
t.Fatalf("got turn_on/success counter %v, want %v", got, before+1)
|
||||
}
|
||||
|
||||
beforeErr := testutil.ToFloat64(errorCounter)
|
||||
s2 := New(&fakeShadow{err: errors.New("redis down")}, &fakeMQTT{}, discardLogger())
|
||||
if _, err := s2.TurnOn(context.Background(), &devicecontrol.TurnOnRequest{DeviceId: "d1"}); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := testutil.ToFloat64(errorCounter); got != beforeErr+1 {
|
||||
t.Fatalf("got turn_on/error counter %v, want %v", got, beforeErr+1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,13 @@ MQTT/ClickHouse/RabbitMQ, как и на диаграмме архитектур
|
||||
понадобится lookup через реестр устройств (с кэшированием, как rule-engine
|
||||
кэширует правила) — это естественное развитие, пока не реализовано.
|
||||
|
||||
## Метрики
|
||||
|
||||
`GET /metrics` (порт `INGEST_METRICS_PORT`, по умолчанию 9101) — формат
|
||||
Prometheus. Счётчики принятых/невалидных/отброшенных (backlog переполнен)
|
||||
MQTT-сообщений, флашей батча в ClickHouse (с latency и размером батча),
|
||||
публикаций в RabbitMQ.
|
||||
|
||||
## Запуск
|
||||
|
||||
```bash
|
||||
|
||||
@@ -5,16 +5,21 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
|
||||
"git.cactoz.su/cacto/home_automatization/services/ingest-service/internal/batch"
|
||||
chstore "git.cactoz.su/cacto/home_automatization/services/ingest-service/internal/clickhouse"
|
||||
"git.cactoz.su/cacto/home_automatization/services/ingest-service/internal/config"
|
||||
"git.cactoz.su/cacto/home_automatization/services/ingest-service/internal/metrics"
|
||||
"git.cactoz.su/cacto/home_automatization/services/ingest-service/internal/mqttclient"
|
||||
"git.cactoz.su/cacto/home_automatization/services/ingest-service/internal/rabbitmq"
|
||||
"git.cactoz.su/cacto/home_automatization/services/ingest-service/internal/telemetry"
|
||||
@@ -59,7 +64,7 @@ func run(logger *slog.Logger) error {
|
||||
}
|
||||
defer publisher.Close()
|
||||
|
||||
batcher := batch.New(cfg.BatchMaxSize, cfg.BatchFlushInterval, cfg.BatchFlushTimeout, store.InsertBatch, logger)
|
||||
batcher := batch.New(cfg.BatchMaxSize, cfg.BatchFlushInterval, cfg.BatchFlushTimeout, instrumentedInsert(store), logger)
|
||||
batcher.Start()
|
||||
defer batcher.Stop()
|
||||
|
||||
@@ -77,6 +82,9 @@ func run(logger *slog.Logger) error {
|
||||
cancel()
|
||||
if err != nil {
|
||||
logger.Error("publish reading event failed", "device_id", reading.DeviceID, "error", err)
|
||||
metrics.RabbitMQPublishes.WithLabelValues("error").Inc()
|
||||
} else {
|
||||
metrics.RabbitMQPublishes.WithLabelValues("success").Inc()
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -87,9 +95,12 @@ func run(logger *slog.Logger) error {
|
||||
Topic: cfg.MQTTTopic,
|
||||
QoS: 1,
|
||||
}, func(payload []byte, receivedAt time.Time) {
|
||||
metrics.MQTTMessagesReceived.Inc()
|
||||
|
||||
reading, err := telemetry.ParseReading(payload, receivedAt)
|
||||
if err != nil {
|
||||
logger.Warn("dropping invalid telemetry payload", "error", err)
|
||||
metrics.MQTTMessagesInvalid.Inc()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -97,12 +108,24 @@ func run(logger *slog.Logger) error {
|
||||
case incoming <- reading:
|
||||
default:
|
||||
logger.Error("dropping reading: worker backlog full", "device_id", reading.DeviceID)
|
||||
metrics.MQTTMessagesDropped.Inc()
|
||||
}
|
||||
}, logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
metricsServer := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", cfg.MetricsPort),
|
||||
Handler: promhttp.Handler(),
|
||||
}
|
||||
go func() {
|
||||
logger.Info("metrics server started", "metrics_port", cfg.MetricsPort)
|
||||
if err := metricsServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
logger.Error("metrics server stopped", "error", err)
|
||||
}
|
||||
}()
|
||||
|
||||
logger.Info("ingest-service started", "mqtt_topic", cfg.MQTTTopic)
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
@@ -114,5 +137,30 @@ func run(logger *slog.Logger) error {
|
||||
close(incoming)
|
||||
workerWG.Wait()
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := metricsServer.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error("metrics server shutdown failed", "error", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// instrumentedInsert wraps store.InsertBatch with duration/size/outcome
|
||||
// metrics, without teaching the batch or clickhouse packages about Prometheus.
|
||||
func instrumentedInsert(store *chstore.Store) batch.FlushFunc {
|
||||
return func(ctx context.Context, readings []telemetry.Reading) error {
|
||||
start := time.Now()
|
||||
err := store.InsertBatch(ctx, readings)
|
||||
|
||||
metrics.BatchFlushDuration.Observe(time.Since(start).Seconds())
|
||||
metrics.BatchSize.Observe(float64(len(readings)))
|
||||
if err != nil {
|
||||
metrics.BatchFlushes.WithLabelValues("error").Inc()
|
||||
} else {
|
||||
metrics.BatchFlushes.WithLabelValues("success").Inc()
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,26 +5,33 @@ go 1.25.0
|
||||
require (
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.47.0
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
github.com/rabbitmq/amqp091-go v1.13.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/ClickHouse/ch-go v0.73.0 // indirect
|
||||
github.com/andybalholm/brotli v1.2.1 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/go-faster/city v1.0.1 // indirect
|
||||
github.com/go-faster/errors v0.7.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/klauspost/compress v1.18.6 // indirect
|
||||
github.com/klauspost/compress v1.19.1 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/paulmach/orb v0.13.0 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.27 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
github.com/segmentio/asm v1.2.1 // indirect
|
||||
github.com/shopspring/decimal v1.4.0 // indirect
|
||||
go.opentelemetry.io/otel v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.44.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/net v0.56.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sync v0.21.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
|
||||
@@ -4,6 +4,8 @@ github.com/ClickHouse/clickhouse-go/v2 v2.47.0 h1:ZDAzrnKSOPTIsm4tdUNfrii2yc8dk4
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.47.0/go.mod h1:sPj7C7UYQ2MWHcfX+4eGN6nwnCqwUKfgO6PcwKpd6K8=
|
||||
github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro=
|
||||
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
@@ -20,14 +22,26 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/paulmach/orb v0.13.0 h1:r7n7mQGGF+cj/CbcivEj9J3HGK+XR+yXnvzRdq9saIw=
|
||||
github.com/paulmach/orb v0.13.0/go.mod h1:6scRWINywA2Jf05dcjOfLfxrUIMECvTSG2MVbRLxu/k=
|
||||
github.com/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk=
|
||||
github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/rabbitmq/amqp091-go v1.13.0 h1:L8NA1WtF76C6KA3LAoufjfLgbist/If1UQYcsOjtxXA=
|
||||
github.com/rabbitmq/amqp091-go v1.13.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
|
||||
@@ -44,14 +58,18 @@ go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
@@ -24,6 +24,8 @@ type Config struct {
|
||||
BatchMaxSize int
|
||||
BatchFlushInterval time.Duration
|
||||
BatchFlushTimeout time.Duration
|
||||
|
||||
MetricsPort int
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
@@ -55,6 +57,9 @@ func Load() (Config, error) {
|
||||
if cfg.BatchFlushTimeout, err = getEnvDuration("INGEST_BATCH_FLUSH_TIMEOUT", 10*time.Second); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if cfg.MetricsPort, err = getEnvInt("INGEST_METRICS_PORT", 9101); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// Package metrics defines ingest-service's Prometheus metrics. Registered
|
||||
// automatically (via promauto) into the default registry on import; served
|
||||
// by main.go's dedicated metrics HTTP server.
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
)
|
||||
|
||||
var (
|
||||
MQTTMessagesReceived = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "ingest_mqtt_messages_received_total",
|
||||
Help: "Total number of telemetry messages received from MQTT.",
|
||||
})
|
||||
|
||||
MQTTMessagesInvalid = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "ingest_mqtt_messages_invalid_total",
|
||||
Help: "Total number of telemetry messages dropped for failing validation.",
|
||||
})
|
||||
|
||||
MQTTMessagesDropped = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "ingest_mqtt_messages_dropped_total",
|
||||
Help: "Total number of readings dropped because the worker backlog was full.",
|
||||
})
|
||||
|
||||
BatchFlushes = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "ingest_batch_flush_total",
|
||||
Help: "Total number of batch flushes to ClickHouse, by outcome.",
|
||||
}, []string{"outcome"})
|
||||
|
||||
BatchFlushDuration = promauto.NewHistogram(prometheus.HistogramOpts{
|
||||
Name: "ingest_batch_flush_duration_seconds",
|
||||
Help: "Duration of ClickHouse batch insert calls.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
})
|
||||
|
||||
BatchSize = promauto.NewHistogram(prometheus.HistogramOpts{
|
||||
Name: "ingest_batch_size",
|
||||
Help: "Number of readings per flushed batch.",
|
||||
Buckets: []float64{1, 5, 10, 25, 50, 100, 250, 500, 1000},
|
||||
})
|
||||
|
||||
RabbitMQPublishes = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "ingest_rabbitmq_publish_total",
|
||||
Help: "Total number of new-reading events published to RabbitMQ, by outcome.",
|
||||
}, []string{"outcome"})
|
||||
)
|
||||
@@ -39,6 +39,12 @@
|
||||
- **Кэш правил — только для чтения активных правил**, никакой записи назад в
|
||||
Postgres. CRUD правил — это зона ответственности Laravel (этап 2).
|
||||
|
||||
## Метрики
|
||||
|
||||
`GET /metrics` (порт `RULE_ENGINE_METRICS_PORT`, по умолчанию 9102) —
|
||||
счётчики обработанных показаний, сработавших правил (по action_type и
|
||||
исходу), latency вызова device-control-service, обновлений кэша правил.
|
||||
|
||||
## Запуск
|
||||
|
||||
```bash
|
||||
|
||||
@@ -5,12 +5,16 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
|
||||
"git.cactoz.su/cacto/home_automatization/services/rule-engine-service/internal/config"
|
||||
"git.cactoz.su/cacto/home_automatization/services/rule-engine-service/internal/devicecontrolclient"
|
||||
@@ -63,6 +67,17 @@ func run(logger *slog.Logger) error {
|
||||
|
||||
eng := engine.New(cache, dcClient, mq, logger)
|
||||
|
||||
metricsServer := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", cfg.MetricsPort),
|
||||
Handler: promhttp.Handler(),
|
||||
}
|
||||
go func() {
|
||||
logger.Info("metrics server started", "metrics_port", cfg.MetricsPort)
|
||||
if err := metricsServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
logger.Error("metrics server stopped", "error", err)
|
||||
}
|
||||
}()
|
||||
|
||||
logger.Info("rule-engine-service started")
|
||||
|
||||
err = mq.ConsumeReadings(ctx, func(ctx context.Context, event rabbitmq.ReadingEvent) rabbitmq.HandleResult {
|
||||
@@ -84,5 +99,12 @@ func run(logger *slog.Logger) error {
|
||||
}
|
||||
|
||||
logger.Info("shutting down")
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := metricsServer.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error("metrics server shutdown failed", "error", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -5,18 +5,26 @@ go 1.25.0
|
||||
require (
|
||||
git.cactoz.su/cacto/home_automatization/proto v0.0.0-00010101000000-000000000000
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
github.com/rabbitmq/amqp091-go v1.13.0
|
||||
google.golang.org/grpc v1.82.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
golang.org/x/net v0.53.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
@@ -21,8 +23,22 @@ github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/rabbitmq/amqp091-go v1.13.0 h1:L8NA1WtF76C6KA3LAoufjfLgbist/If1UQYcsOjtxXA=
|
||||
github.com/rabbitmq/amqp091-go v1.13.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
@@ -44,14 +60,16 @@ go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09
|
||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw=
|
||||
|
||||
@@ -5,6 +5,7 @@ package config
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -16,6 +17,8 @@ type Config struct {
|
||||
RabbitMQURL string
|
||||
|
||||
RuleCacheRefreshInterval time.Duration
|
||||
|
||||
MetricsPort int
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
@@ -47,6 +50,10 @@ func Load() (Config, error) {
|
||||
}
|
||||
cfg.RuleCacheRefreshInterval = interval
|
||||
|
||||
if cfg.MetricsPort, err = getEnvInt("RULE_ENGINE_METRICS_PORT", 9102); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
@@ -57,6 +64,18 @@ func getEnv(key, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
func getEnvInt(key string, fallback int) (int, error) {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s: %w", key, err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func getEnvDuration(key string, fallback time.Duration) (time.Duration, error) {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.cactoz.su/cacto/home_automatization/services/rule-engine-service/internal/devicecontrolclient"
|
||||
"git.cactoz.su/cacto/home_automatization/services/rule-engine-service/internal/metrics"
|
||||
"git.cactoz.su/cacto/home_automatization/services/rule-engine-service/internal/rules"
|
||||
)
|
||||
|
||||
@@ -57,6 +58,8 @@ func New(ruleSource RuleSource, dispatcher Dispatcher, publisher TriggerPublishe
|
||||
// the whole reading for. A rule the device itself rejected (bad device_id,
|
||||
// unsupported action) is terminal and does not cause a retry.
|
||||
func (e *Engine) HandleReading(ctx context.Context, r Reading) error {
|
||||
metrics.ReadingsConsumed.Inc()
|
||||
|
||||
matched := e.rules.MatchingRules(r.DeviceID, r.SensorType)
|
||||
|
||||
var firstTransportErr error
|
||||
@@ -69,8 +72,11 @@ func (e *Engine) HandleReading(ctx context.Context, r Reading) error {
|
||||
if !matchesCondition {
|
||||
continue
|
||||
}
|
||||
metrics.RulesMatched.Inc()
|
||||
|
||||
start := time.Now()
|
||||
result, dispatchErr := e.dispatcher.Dispatch(ctx, rule.TargetDeviceID, rule.ActionType, rule.ActionParams)
|
||||
metrics.DispatchDuration.WithLabelValues(rule.ActionType).Observe(time.Since(start).Seconds())
|
||||
|
||||
success := dispatchErr == nil && result.Success
|
||||
errMsg := result.Error
|
||||
@@ -78,13 +84,16 @@ func (e *Engine) HandleReading(ctx context.Context, r Reading) error {
|
||||
case dispatchErr != nil:
|
||||
errMsg = dispatchErr.Error()
|
||||
e.logger.Error("dispatch action failed", "rule_id", rule.ID, "target_device_id", rule.TargetDeviceID, "error", dispatchErr)
|
||||
metrics.RulesTriggered.WithLabelValues(rule.ActionType, "transport_error").Inc()
|
||||
if firstTransportErr == nil {
|
||||
firstTransportErr = dispatchErr
|
||||
}
|
||||
case !result.Success:
|
||||
e.logger.Warn("device rejected command", "rule_id", rule.ID, "target_device_id", rule.TargetDeviceID, "error", result.Error)
|
||||
metrics.RulesTriggered.WithLabelValues(rule.ActionType, "rejected").Inc()
|
||||
default:
|
||||
e.logger.Info("rule triggered", "rule_id", rule.ID, "target_device_id", rule.TargetDeviceID, "action_type", rule.ActionType)
|
||||
metrics.RulesTriggered.WithLabelValues(rule.ActionType, "success").Inc()
|
||||
}
|
||||
|
||||
if pubErr := e.publisher.PublishRuleTriggered(ctx, rule.ID, rule.ZoneID, rule.TargetDeviceID, rule.ActionType, success, errMsg); pubErr != nil {
|
||||
|
||||
@@ -7,7 +7,10 @@ import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/testutil"
|
||||
|
||||
"git.cactoz.su/cacto/home_automatization/services/rule-engine-service/internal/devicecontrolclient"
|
||||
"git.cactoz.su/cacto/home_automatization/services/rule-engine-service/internal/metrics"
|
||||
"git.cactoz.su/cacto/home_automatization/services/rule-engine-service/internal/rules"
|
||||
)
|
||||
|
||||
@@ -154,3 +157,30 @@ func TestHandleReading_InvalidOperatorSkipsRuleButContinues(t *testing.T) {
|
||||
t.Fatalf("got dispatch calls %+v, want only the valid rule dispatched", dispatcher.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleReading_RecordsMetrics(t *testing.T) {
|
||||
source := &fakeRuleSource{rules: []rules.Rule{
|
||||
{ID: 1, ConditionOperator: ">", ConditionValue: 28, TargetDeviceID: "fan-1", ActionType: "turn_on"},
|
||||
}}
|
||||
dispatcher := &fakeDispatcher{result: devicecontrolclient.Result{Success: true}}
|
||||
e := New(source, dispatcher, &fakePublisher{}, discardLogger())
|
||||
|
||||
triggeredCounter := metrics.RulesTriggered.WithLabelValues("turn_on", "success")
|
||||
beforeConsumed := testutil.ToFloat64(metrics.ReadingsConsumed)
|
||||
beforeMatched := testutil.ToFloat64(metrics.RulesMatched)
|
||||
beforeTriggered := testutil.ToFloat64(triggeredCounter)
|
||||
|
||||
if err := e.HandleReading(context.Background(), Reading{Value: 30}); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if got := testutil.ToFloat64(metrics.ReadingsConsumed); got != beforeConsumed+1 {
|
||||
t.Fatalf("got readings_consumed %v, want %v", got, beforeConsumed+1)
|
||||
}
|
||||
if got := testutil.ToFloat64(metrics.RulesMatched); got != beforeMatched+1 {
|
||||
t.Fatalf("got rules_matched %v, want %v", got, beforeMatched+1)
|
||||
}
|
||||
if got := testutil.ToFloat64(triggeredCounter); got != beforeTriggered+1 {
|
||||
t.Fatalf("got rules_triggered{turn_on,success} %v, want %v", got, beforeTriggered+1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Package metrics defines rule-engine-service's Prometheus metrics.
|
||||
// Registered automatically (via promauto) into the default registry on
|
||||
// import; served by main.go's dedicated metrics HTTP server.
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
)
|
||||
|
||||
var (
|
||||
ReadingsConsumed = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "rule_engine_readings_consumed_total",
|
||||
Help: "Total number of telemetry.new_reading events consumed from RabbitMQ.",
|
||||
})
|
||||
|
||||
RulesMatched = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "rule_engine_rules_matched_total",
|
||||
Help: "Total number of rule conditions that evaluated true and were dispatched.",
|
||||
})
|
||||
|
||||
RulesTriggered = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "rule_engine_rules_triggered_total",
|
||||
Help: "Total number of rule dispatch attempts, by action type and outcome.",
|
||||
}, []string{"action_type", "outcome"})
|
||||
|
||||
DispatchDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Name: "rule_engine_dispatch_duration_seconds",
|
||||
Help: "Duration of the gRPC/HTTP call to device-control-service, by action type.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}, []string{"action_type"})
|
||||
|
||||
CacheRefreshes = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "rule_engine_cache_refresh_total",
|
||||
Help: "Total number of automation_rules cache refreshes from PostgreSQL, by outcome.",
|
||||
}, []string{"outcome"})
|
||||
)
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.cactoz.su/cacto/home_automatization/services/rule-engine-service/internal/metrics"
|
||||
"git.cactoz.su/cacto/home_automatization/services/rule-engine-service/internal/rules"
|
||||
)
|
||||
|
||||
@@ -88,12 +89,14 @@ func (c *Cache) loop() {
|
||||
func (c *Cache) refresh(ctx context.Context) error {
|
||||
dbRows, err := c.fetcher.FetchActiveRules(ctx)
|
||||
if err != nil {
|
||||
metrics.CacheRefreshes.WithLabelValues("error").Inc()
|
||||
return err
|
||||
}
|
||||
index := buildIndex(dbRows, c.logger)
|
||||
c.mu.Lock()
|
||||
c.index = index
|
||||
c.mu.Unlock()
|
||||
metrics.CacheRefreshes.WithLabelValues("success").Inc()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user