1
0
Fork 0
internet-everythings-agricu.../app/Console/Commands/DeviceLogReportCommand.php

92 lines
2.7 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Device;
use App\Models\MeteorologicalReport;
use App\Models\SoilReport;
use App\Models\WaterQualityReport;
use App\Services\DeviceLogService;
use Illuminate\Console\Command;
class DeviceLogReportCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'device-log:report
{factory}
{--sleep=300 : 监控报告生产后的休眠时间(秒)}';
/**
* The console command description.
*
* @var string
*/
protected $description = '按设备厂商生成监控报告';
/**
* @var \App\Services\DeviceLogService
*/
protected $deviceLogService;
/**
* Execute the console command.
*/
public function handle(DeviceLogService $deviceLogService)
{
$this->deviceLogService = $deviceLogService;
$factory = $this->argument('factory');
$sleep = (int) value(fn ($sleep) => is_numeric($sleep) ? $sleep : 300, $this->option('sleep'));
while (true) {
/** @var \Illuminate\Database\Eloquent\Collection */
$devices = Device::with(['factory'])->poweredBy($factory)->get();
foreach ($devices as $device) {
switch ($device->factory?->key) {
case 'link-os':
$this->createReportToLinkosDevice($device);
break;
}
}
sleep($sleep);
};
}
/**
* 创建 linkos 设备报告
*/
protected function createReportToLinkosDevice(Device $device): void
{
$lastReportedAt = match ($device->type) {
Device::TYPE_SOIL => SoilReport::where('device_id', $device->id)->latest('reported_at')->value('reported_at'),
Device::TYPE_WATER_QUALITY => WaterQualityReport::where('device_id', $device->id)->latest('reported_at')->value('reported_at'),
Device::TYPE_METEOROLOGICAL => MeteorologicalReport::where('device_id', $device->id)->latest('reported_at')->value('reported_at'),
default => null,
};
if (is_null($lastReportedAt ??= $device->logs()->oldest('reported_at')->value('reported_at'))) {
return;
}
if (is_null($latestReportedAt = $device->logs()->latest('reported_at')->value('reported_at'))) {
return;
}
/** @var \Carbon\Carbon */
$startAt = $lastReportedAt->copy()->startOfHour();
do {
$this->deviceLogService->createReportToLinkosDevice($device, $startAt->copy());
$startAt->addHour();
} while ($latestReportedAt->gte($startAt));
}
}