lcly-data-admin/app/Console/Commands/YunFei/DeviceLogReportCommand.php

88 lines
2.3 KiB
PHP

<?php
namespace App\Console\Commands\YunFei;
use App\Enums\DeviceType;
use App\Models\Device;
use App\Models\DeviceLog;
use App\Models\InsecticidalLampReport;
use App\Services\YunFeiDeviceService;
use Illuminate\Console\Command;
use Throwable;
class DeviceLogReportCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'yunfei:device-log-report
{--sleep=300 : 监控报告生产后的休眠时间(秒)}';
/**
* The console command description.
*
* @var string
*/
protected $description = '按设备厂商生成监控报告';
/**
* @var \App\Services\DeviceLogService
*/
protected $deviceLogService;
/**
* Execute the console command.
*/
public function handle()
{
$seconds = (int) value(fn ($seconds) => is_numeric($seconds) ? $seconds : 300, $this->option('sleep'));
while (true) {
try {
/** @var \Illuminate\Database\Eloquent\Collection */
$devices = Device::supplierBy('device-supplier-yunfei')->get();
foreach ($devices as $device) {
$this->createReport($device);
}
} catch (Throwable $e) {
report($e);
}
sleep($seconds);
};
}
/**
* 创建比昂设备报告
*/
protected function createReport(Device $device): void
{
$lastReportedAt = match ($device->type) {
DeviceType::InsecticidalLamp => InsecticidalLampReport::where('device_id', $device->id)->latest('reported_at')->value('reported_at'),
default => null,
};
if (is_null($lastReportedAt ??= DeviceLog::where('device_id', $device->id)->oldest('reported_at')->value('reported_at'))) {
return;
}
if (is_null($latestReportedAt = DeviceLog::where('device_id', $device->id)->latest('reported_at')->value('reported_at'))) {
return;
}
$service = new YunFeiDeviceService();
/** @var \Carbon\Carbon */
$startAt = $lastReportedAt->copy()->startOfHour();
do {
$service->createReport($device, $startAt->copy());
$startAt->addHour();
} while ($latestReportedAt->gte($startAt));
}
}