dev
Jing Li 2023-08-11 19:44:51 +08:00
parent f95a64535c
commit d304f30a52
2 changed files with 27 additions and 34 deletions

View File

@ -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;
}

View File

@ -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;
}
}
}
/**