diff --git a/app/Console/Commands/DeviceLogSyncCommand.php b/app/Console/Commands/DeviceLogSyncCommand.php index b55233e..b596575 100644 --- a/app/Console/Commands/DeviceLogSyncCommand.php +++ b/app/Console/Commands/DeviceLogSyncCommand.php @@ -72,7 +72,7 @@ class DeviceLogSyncCommand extends Command try { switch ($device->supplier?->key) { case 'device-supplier-biang': - (new BiAngDeviceLogService())->sync($device); + (new BiAngDeviceLogService())->sync($device, $start, $end); break; } diff --git a/app/Services/BiAngDeviceLogService.php b/app/Services/BiAngDeviceLogService.php index d314a43..b448bdc 100644 --- a/app/Services/BiAngDeviceLogService.php +++ b/app/Services/BiAngDeviceLogService.php @@ -17,54 +17,47 @@ use Illuminate\Support\Facades\DB; class BiAngDeviceLogService { - public function sync(Device $device): void + public function sync(Device $device, Carbon $startAt, Carbon $endAt): void { $config = json_decode($device->project?->value, true); if (! isset($config['username'], $config['password'])) { return; } - $httpClient = new BiAngHttpClient($config['username'], $config['password']); - $data = null; - switch ($device->type) { case DeviceType::Soil: $data = $httpClient->getLatestSoilReport($device->sn); - break; + $log = DeviceLog::firstOrCreate([ + 'device_id' => $device->id, + 'reported_at' => $data['time'], + ], [ + 'data' => Arr::except($data, ['deviceId', 'time']), + ]); + + if (in_array($device->status, [DeviceStatus::Online, DeviceStatus::Offline])) { + $device->update([ + 'status' => $startAt->lt($log->reported_at) ? DeviceStatus::Online : DeviceStatus::Offline, + ]); + } case DeviceType::Meteorological: $data = $httpClient->getLatestMeteorologicalReport($device->sn); + + $log = DeviceLog::firstOrCreate([ + 'device_id' => $device->id, + 'reported_at' => $data['time'], + ], [ + 'data' => Arr::except($data, ['deviceId', 'time']), + ]); + + if (in_array($device->status, [DeviceStatus::Online, DeviceStatus::Offline])) { + $device->update([ + 'status' => $startAt->lt($log->reported_at) ? DeviceStatus::Online : DeviceStatus::Offline, + ]); + } break; } - - if (is_array($data) && isset($data['time'])) { - $log = DeviceLog::firstOrCreate([ - 'device_id' => $device->id, - 'reported_at' => $data['time'], - ], [ - 'data' => Arr::except($data, ['deviceId', 'time']), - ]); - - switch ($device->status) { - case DeviceStatus::Online: - // 如果设备数据在线时,最近60分钟内没有数据,则视为离线 - if (now()->subMinutes(60)->gt($log->reported_at)) { - $device->update([ - 'status' => DeviceStatus::Offline, - ]); - } - break; - case DeviceStatus::Offline: - // 如果设备数据离线时,最近60分钟内有数据,则视为在线 - if (now()->subMinutes(60)->lt($log->reported_at)) { - $device->update([ - 'status' => DeviceStatus::Online, - ]); - } - break; - } - } } /**