lcly-data-admin/app/Http/Controllers/Callback/LinkosController.php

102 lines
2.6 KiB
PHP

<?php
namespace App\Http\Controllers\Callback;
use App\Enums\DeviceStatus;
use App\Http\Controllers\Controller;
use App\Models\Device;
use App\Services\LinkosDeviceLogService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
class LinkosController extends Controller
{
public function __invoke(Request $request)
{
$input = $request->input();
DB::transaction(function () use ($input) {
if (isset($input['notify_type'])) {
// 设备上线、离线通知
if ($input['notify_type'] === 'online_state_change') {
$this->handleOnlineStateChangeNotify($input);
}
} elseif (Arr::has($input, ['device_id', 'device_unit', 'device_category'])) {
$type = (int) ($input['type'] ?? 0);
switch ($type) {
case 0:
$this->handleDeviceDataNotify($input);
break;
}
}
});
return response()->json(['code' => 0, 'msg' => 'ok']);
}
/**
* 处理设备采集数据
*
* @param array $data
* @return void
*/
protected function handleDeviceDataNotify(array $data)
{
return;
if (! is_array($deviceData = $data['data'] ?? [])) {
$deviceData = [];
}
$reportedAt = isset($data['timestamp'])
? Carbon::createFromTimestampMs($data['timestamp'])
: now();
if (! is_array($deviceData = $data['data'] ?? [])) {
$deviceData = [];
}
(new LinkosDeviceLogService())->create(
$data['device_id'],
$data['device_unit'],
$data['device_category'],
$deviceData,
$reportedAt,
);
}
/**
* 处理设备离线、上线通知
*
* @param array $data
* @return void
*/
protected function handleOnlineStateChangeNotify(array $data)
{
$items = $data['data'] ?? [];
if (! is_array($items)) {
return;
}
foreach ($items as $item) {
if (! Arr::has($item, ['device_id', 'online_state'])) {
continue;
}
switch ($item['online_state']) {
case 0:
Device::where('sn', $item['device_id'])->update(['status' => DeviceStatus::Offline]);
break;
case 1:
Device::where('sn', $item['device_id'])->update(['status' => DeviceStatus::Online]);
break;
}
}
}
}