lcly-data-admin/app/Console/Commands/BiAng/DeviceLogSyncCommand.php

95 lines
2.6 KiB
PHP

<?php
namespace App\Console\Commands\BiAng;
use App\Enums\DeviceStatus;
use App\Enums\DeviceType;
use App\Models\Device;
use App\Services\BiAngDeviceLogService;
use Illuminate\Console\Command;
use Throwable;
class DeviceLogSyncCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'biang:device-log-sync
{--sleep=60 : 设备数据同步完成后的休眠时间(秒)}';
/**
* The console command description.
*
* @var string
*/
protected $description = '按设备厂商同步数据';
/**
* Execute the console command.
*/
public function handle()
{
$sleep = (int) value(fn ($sleep) => is_numeric($sleep) ? $sleep : 60, $this->option('sleep'));
while (true) {
$this->runSync();
sleep($sleep);
};
}
/**
* 执行同步
*/
protected function runSync(): void
{
$now = now();
$this->info('------------------------------------------');
$this->info('同步时间: '. $now);
/** @var \Illuminate\Database\Eloquent\Collection */
$devices = Device::with(['project'])
->supplierBy("device-supplier-biang")
->whereIn('status', [DeviceStatus::Online, DeviceStatus::Offline])
->get();
/** @var \App\Models\Device */
foreach ($devices as $device) {
if (! in_array($device->type, [
DeviceType::Soil,
DeviceType::Meteorological,
DeviceType::InsecticidalLamp,
])) {
continue;
}
$this->info('==========================================');
$this->info('设备编号: ' . $device->sn);
$this->info('设备名称: ' . $device->name);
$this->info('设备类型: ' . match ($device->type) {
DeviceType::Soil => '土壤设备',
DeviceType::Meteorological => '气象设备',
DeviceType::InsecticidalLamp => '杀虫灯设备',
});
try {
(new BiAngDeviceLogService())->sync($device, $now);
$this->info('同步成功!');
} catch (Throwable $e) {
report($e);
$this->error('同步失败: '. $e->getMessage());
}
$this->info('==========================================');
}
$this->info('------------------------------------------');
$this->newLine();
}
}