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

125 lines
3.8 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;
use Illuminate\Support\Arr;
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':
switch ($device->type) {
case Device::TYPE_METEOROLOGICAL:
$this->createReportToLinkosMeteorologicalDevice($device);
break;
case Device::TYPE_WATER_QUALITY:
$this->createReportToLinkosWaterQualityDevice($device);
break;
}
break;
}
}
sleep($sleep);
};
}
protected function createReportToLinkosMeteorologicalDevice(Device $device): void
{
$lastReportedAt = MeteorologicalReport::where('device_id', $device->id)->latest('reported_at')->value('reported_at')
?: $device->logs()->oldest('reported_at')->value('reported_at');
if ($lastReportedAt === null) {
return;
}
$latestReportedAt = $device->logs()->latest('reported_at')->value('reported_at');
if ($latestReportedAt === null) {
return;
}
/** @var \Carbon\Carbon */
$startAt = $lastReportedAt->copy()->startOfHour();
/** @var \Carbon\Carbon */
$endAt = $latestReportedAt->copy()->startOfHour();
do {
$this->deviceLogService->createReportToLinkosMeteorologicalDevice($device, $startAt->copy());
$startAt->addHour();
} while ($endAt->gte($startAt));
}
protected function createReportToLinkosWaterQualityDevice(Device $device): void
{
$lastReportedAt = WaterQualityReport::where('device_id', $device->id)->latest('reported_at')->value('reported_at')
?: $device->logs()->oldest('reported_at')->value('reported_at');
if ($lastReportedAt === null) {
return;
}
$latestReportedAt = $device->logs()->latest('reported_at')->value('reported_at');
if ($latestReportedAt === null) {
return;
}
/** @var \Carbon\Carbon */
$startAt = $lastReportedAt->copy()->startOfHour();
/** @var \Carbon\Carbon */
$endAt = $latestReportedAt->copy()->startOfHour();
do {
$this->deviceLogService->createReportToLinkosWaterQualityDevice($device, $startAt->copy());
$startAt->addHour();
} while ($endAt->gte($startAt));
}
}