dev
Jing Li 2023-08-11 20:35:23 +08:00
parent 7715f5213c
commit 6e8b53e50d
9 changed files with 203 additions and 74 deletions

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Console\Commands; namespace App\Console\Commands\BiAng;
use App\Enums\DeviceType; use App\Enums\DeviceType;
use App\Models\Device; use App\Models\Device;
@ -8,10 +8,7 @@ use App\Models\MeteorologicalMonitoringDailyLog;
use App\Models\MeteorologicalMonitoringLog; use App\Models\MeteorologicalMonitoringLog;
use App\Models\SoilMonitoringDailyLog; use App\Models\SoilMonitoringDailyLog;
use App\Models\SoilMonitoringLog; use App\Models\SoilMonitoringLog;
use App\Models\WaterQualityMonitoringDailyLog;
use App\Models\WaterQualityMonitoringLog;
use App\Services\BiAngDeviceLogService; use App\Services\BiAngDeviceLogService;
use App\Services\DeviceLogService;
use Illuminate\Console\Command; use Illuminate\Console\Command;
class DeviceLogDailyReportCommand extends Command class DeviceLogDailyReportCommand extends Command
@ -21,8 +18,7 @@ class DeviceLogDailyReportCommand extends Command
* *
* @var string * @var string
*/ */
protected $signature = 'device-log:daily-report protected $signature = 'biang:device-log-daily-report
{factory}
{--sleep=300 : 监控报告生产后的休眠时间(秒)}'; {--sleep=300 : 监控报告生产后的休眠时间(秒)}';
/** /**
@ -42,30 +38,21 @@ class DeviceLogDailyReportCommand extends Command
*/ */
public function handle() public function handle()
{ {
$factory = $this->argument('factory');
$sleep = (int) value(fn ($sleep) => is_numeric($sleep) ? $sleep : 300, $this->option('sleep')); $sleep = (int) value(fn ($sleep) => is_numeric($sleep) ? $sleep : 300, $this->option('sleep'));
while (true) { while (true) {
/** @var \Illuminate\Database\Eloquent\Collection */ /** @var \Illuminate\Database\Eloquent\Collection */
$devices = Device::with(['supplier'])->supplierBy("device-supplier-{$factory}")->get(); $devices = Device::supplierBy("device-supplier-biang")->get();
foreach ($devices as $device) { foreach ($devices as $device) {
switch ($device->supplier?->key) { $this->createReport($device);
case 'device-supplier-biang':
$this->createReportToBiAngDevice($device);
break;
}
} }
sleep($sleep); sleep($sleep);
}; };
} }
/** protected function createReport(Device $device): void
* 创建 linkos 设备报告
*/
protected function createReportToBiAngDevice(Device $device): void
{ {
[$lastReportedAt, $latestReportedAt] = value(function (Device $device) { [$lastReportedAt, $latestReportedAt] = value(function (Device $device) {
$lastReportedAt = null; $lastReportedAt = null;

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Console\Commands; namespace App\Console\Commands\BiAng;
use App\Enums\DeviceType; use App\Enums\DeviceType;
use App\Models\Device; use App\Models\Device;
@ -17,8 +17,7 @@ class DeviceLogReportCommand extends Command
* *
* @var string * @var string
*/ */
protected $signature = 'device-log:report protected $signature = 'biang:device-log-report
{factory}
{--sleep=300 : 监控报告生产后的休眠时间(秒)}'; {--sleep=300 : 监控报告生产后的休眠时间(秒)}';
/** /**
@ -38,20 +37,14 @@ class DeviceLogReportCommand extends Command
*/ */
public function handle() public function handle()
{ {
$factory = $this->argument('factory');
$sleep = (int) value(fn ($sleep) => is_numeric($sleep) ? $sleep : 300, $this->option('sleep')); $sleep = (int) value(fn ($sleep) => is_numeric($sleep) ? $sleep : 300, $this->option('sleep'));
while (true) { while (true) {
/** @var \Illuminate\Database\Eloquent\Collection */ /** @var \Illuminate\Database\Eloquent\Collection */
$devices = Device::with(['supplier'])->supplierBy("device-supplier-{$factory}")->get(); $devices = Device::supplierBy("device-supplier-biang")->get();
foreach ($devices as $device) { foreach ($devices as $device) {
switch ($device->supplier?->key) { $this->createReport($device);
case 'device-supplier-biang':
$this->createReportToBiAngDevice($device);
break;
}
} }
sleep($sleep); sleep($sleep);
@ -61,7 +54,7 @@ class DeviceLogReportCommand extends Command
/** /**
* 创建比昂设备报告 * 创建比昂设备报告
*/ */
protected function createReportToBiAngDevice(Device $device): void protected function createReport(Device $device): void
{ {
$lastReportedAt = match ($device->type) { $lastReportedAt = match ($device->type) {
DeviceType::Soil => SoilMonitoringLog::where('device_id', $device->id)->latest('monitored_at')->value('monitored_at'), DeviceType::Soil => SoilMonitoringLog::where('device_id', $device->id)->latest('monitored_at')->value('monitored_at'),

View File

@ -1,7 +1,8 @@
<?php <?php
namespace App\Console\Commands; namespace App\Console\Commands\BiAng;
use App\Enums\DeviceStatus;
use App\Enums\DeviceType; use App\Enums\DeviceType;
use App\Models\Device; use App\Models\Device;
use App\Services\BiAngDeviceLogService; use App\Services\BiAngDeviceLogService;
@ -15,8 +16,7 @@ class DeviceLogSyncCommand extends Command
* *
* @var string * @var string
*/ */
protected $signature = 'device-log:sync protected $signature = 'biang:device-log-sync
{factory}
{--sleep=60 : 设备数据同步完成后的休眠时间(秒)}'; {--sleep=60 : 设备数据同步完成后的休眠时间(秒)}';
/** /**
@ -31,12 +31,10 @@ class DeviceLogSyncCommand extends Command
*/ */
public function handle() public function handle()
{ {
$factory = $this->argument('factory');
$sleep = (int) value(fn ($sleep) => is_numeric($sleep) ? $sleep : 60, $this->option('sleep')); $sleep = (int) value(fn ($sleep) => is_numeric($sleep) ? $sleep : 60, $this->option('sleep'));
while (true) { while (true) {
$this->runSync($factory); $this->runSync();
sleep($sleep); sleep($sleep);
}; };
@ -45,36 +43,40 @@ class DeviceLogSyncCommand extends Command
/** /**
* 执行同步 * 执行同步
*/ */
protected function runSync(string $factory): void protected function runSync(): void
{ {
$end = now(); $now = now();
$start = $end->copy()->subHours(1);
$this->info('------------------------------------------'); $this->info('------------------------------------------');
$this->info('开始时间: '. $start); $this->info('同步时间: '. $now);
$this->info('结束时间: '. $end);
/** @var \Illuminate\Database\Eloquent\Collection */ /** @var \Illuminate\Database\Eloquent\Collection */
$devices = Device::with(['supplier', 'project'])->supplierBy("device-supplier-{$factory}")->get(); $devices = Device::with(['project'])
->supplierBy("device-supplier-biang")
->whereIn('status', [DeviceStatus::Online, DeviceStatus::Offline])
->get();
/** @var \App\Models\Device */ /** @var \App\Models\Device */
foreach ($devices as $device) { foreach ($devices as $device) {
if (! in_array($device->type, [
DeviceType::Soil,
DeviceType::Meteorological,
DeviceType::InsecticidalLamp,
])) {
continue;
}
$this->info('=========================================='); $this->info('==========================================');
$this->info('设备编号: ' . $device->sn); $this->info('设备编号: ' . $device->sn);
$this->info('设备名称: ' . $device->name); $this->info('设备名称: ' . $device->name);
$this->info('设备类型: ' . match ($device->type) { $this->info('设备类型: ' . match ($device->type) {
DeviceType::Soil => '土壤设备', DeviceType::Soil => '土壤设备',
DeviceType::WaterQuality => '水质设备',
DeviceType::Meteorological => '气象设备', DeviceType::Meteorological => '气象设备',
default => '其它', DeviceType::InsecticidalLamp => '杀虫灯设备',
}); });
try { try {
switch ($device->supplier?->key) { (new BiAngDeviceLogService())->sync($device, $now);
case 'device-supplier-biang':
(new BiAngDeviceLogService())->sync($device, $start, $end);
break;
}
$this->info('同步成功!'); $this->info('同步成功!');
} catch (Throwable $e) { } catch (Throwable $e) {

View File

@ -8,7 +8,9 @@ enum DeviceType: int
case Soil = 2; // 土壤设备 case Soil = 2; // 土壤设备
case WaterQuality = 3; // 水质设备 case WaterQuality = 3; // 水质设备
case Meteorological = 4; // 气象设备 case Meteorological = 4; // 气象设备
case Insect = 5; // 虫情设备 case Worm = 5; // 虫情设备
case InsectSexLure = 6; // 昆虫性诱设备
case InsecticidalLamp = 7; // 杀虫灯设备
/** /**
* @return string * @return string
@ -28,7 +30,9 @@ enum DeviceType: int
static::Soil->value => '土壤设备', static::Soil->value => '土壤设备',
static::WaterQuality->value => '水质设备', static::WaterQuality->value => '水质设备',
static::Meteorological->value => '气象设备', static::Meteorological->value => '气象设备',
static::Insect->value => '虫情设备', static::Worm->value => '虫情设备',
static::InsectSexLure->value => '昆虫性诱设备',
static::InsecticidalLamp->value => '杀虫灯设备',
]; ];
} }
} }

View File

@ -0,0 +1,9 @@
<?php
namespace App\Exceptions;
use RuntimeException;
class BiAngException extends RuntimeException
{
}

View File

@ -2,7 +2,8 @@
namespace App\Iot\BiAng; namespace App\Iot\BiAng;
use Carbon\Carbon; use App\Exceptions\BiAngException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use RuntimeException; use RuntimeException;
@ -27,13 +28,7 @@ class HttpClient
] ]
); );
if (data_get($result, 'code') === 200) { return $result['data'];
return $result['data'];
}
throw new RuntimeException(
sprintf("%s:%s", data_get($result, 'code', 500), data_get($result, 'msg', '出错啦!'))
);
} }
/** /**
@ -48,13 +43,56 @@ class HttpClient
] ]
); );
if (data_get($result, 'code') === 200) { return $result['data'];
return $result['data']; }
}
throw new RuntimeException( /**
sprintf("%s:%s", data_get($result, 'code', 500), data_get($result, 'msg', '出错啦!')) * 获取最新的杀虫灯数据
*/
public function getLatestLampReport(string $deviceId)
{
$result = $this->get(
$this->apiUrl2('/open-api/open/getCurrentLampData'),
[
'deviceId' => $deviceId,
]
); );
return $result['data'];
}
/**
* 虫情设备/昆虫性诱设备 - 查询某个时间段内的图片
*/
public function getWormPhotos(string $deviceId, Carbon $start, Carbon $end)
{
$result = $this->get(
$this->apiUrl('/api/open-api/open/getDevicePhotos'),
[
'deviceId' => $deviceId,
'startTime' => $start->toDateString(),
'endTime' => $end->toDateString(),
]
);
return $result['data'];
}
/**
* 虫情设备 - (识别款)图片虫数识别统计
*/
public function getWormStatistics(string $deviceId, Carbon $start, Carbon $end)
{
$result = $this->get(
$this->apiUrl('/api/open-api/open/getAllStatistics'),
[
'imei' => $deviceId,
'startAt' => $start->toDateString(),
'endAt' => $end->toDateString(),
]
);
return $result['data'];
} }
public function get(string $url, array $query = []): array public function get(string $url, array $query = []): array
@ -108,7 +146,13 @@ class HttpClient
'Content-Type' => 'application/json', 'Content-Type' => 'application/json',
])->send($method, $url, $options); ])->send($method, $url, $options);
return $response->throw()->json(); $result = $response->throw()->json();
if (data_get($result, 'code') === 200) {
return $result;
}
throw new BiAngException($result['code'].':'.($result['msg']??'出错啦!'), 500);
} }
protected function apiUrl(string $path): string protected function apiUrl(string $path): string

View File

@ -0,0 +1,28 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class InsecticidalLampReport extends Model
{
use HasFactory;
protected $casts = [
'reported_at' => 'datetime',
];
protected $fillable = [
'device_id',
'battery_vol',
'killed_num',
'air_temperature',
'air_humidity',
'lng',
'lat',
'solar_panel_vol',
'high_vol',
'reported_at',
];
}

View File

@ -7,6 +7,7 @@ use App\Enums\DeviceType;
use App\Iot\BiAng\HttpClient as BiAngHttpClient; use App\Iot\BiAng\HttpClient as BiAngHttpClient;
use App\Models\Device; use App\Models\Device;
use App\Models\DeviceLog; use App\Models\DeviceLog;
use App\Models\InsecticidalLampReport;
use App\Models\MeteorologicalMonitoringDailyLog; use App\Models\MeteorologicalMonitoringDailyLog;
use App\Models\MeteorologicalMonitoringLog; use App\Models\MeteorologicalMonitoringLog;
use App\Models\SoilMonitoringDailyLog; use App\Models\SoilMonitoringDailyLog;
@ -17,7 +18,7 @@ use Illuminate\Support\Facades\DB;
class BiAngDeviceLogService class BiAngDeviceLogService
{ {
public function sync(Device $device, Carbon $startAt, Carbon $endAt): void public function sync(Device $device, Carbon $syncTime): void
{ {
$config = json_decode($device->project?->value, true); $config = json_decode($device->project?->value, true);
if (! isset($config['username'], $config['password'])) { if (! isset($config['username'], $config['password'])) {
@ -36,11 +37,9 @@ class BiAngDeviceLogService
'data' => Arr::except($data, ['deviceId', 'time']), 'data' => Arr::except($data, ['deviceId', 'time']),
]); ]);
if (in_array($device->status, [DeviceStatus::Online, DeviceStatus::Offline])) { $device->update([
$device->update([ 'status' => $syncTime->subMinutes(60)->lt($log->reported_at) ? DeviceStatus::Online : DeviceStatus::Offline,
'status' => $startAt->lt($log->reported_at) ? DeviceStatus::Online : DeviceStatus::Offline, ]);
]);
}
break; break;
case DeviceType::Meteorological: case DeviceType::Meteorological:
$data = $httpClient->getLatestMeteorologicalReport($device->sn); $data = $httpClient->getLatestMeteorologicalReport($device->sn);
@ -52,11 +51,33 @@ class BiAngDeviceLogService
'data' => Arr::except($data, ['deviceId', 'time']), 'data' => Arr::except($data, ['deviceId', 'time']),
]); ]);
if (in_array($device->status, [DeviceStatus::Online, DeviceStatus::Offline])) { $device->update([
$device->update([ 'status' => $syncTime->subMinutes(60)->lt($log->reported_at) ? DeviceStatus::Online : DeviceStatus::Offline,
'status' => $startAt->lt($log->reported_at) ? DeviceStatus::Online : DeviceStatus::Offline, ]);
break;
case DeviceType::InsecticidalLamp:
$data = $httpClient->getLatestLampReport($device->sn);
if ($data['status'] === 'online') {
InsecticidalLampReport::updateOrCreate([
'device_id' => $device->id,
'reported_at' => $syncTime->copy()->startOfHour(),
], [
'battery_vol' => $data['vol'],
'killed_num' => $data['dct'],
'air_temperature' => $data['temp'],
'air_humidity' => $data['humidity'],
'lng' => $data['lng'],
'lat' => $data['lat'],
'solar_panel_vol' => $data['sunVol'],
'high_vol' => $data['highVol'],
]); ]);
} }
$device->update([
'status' => $data['status'] === 'online' ? DeviceStatus::Online : DeviceStatus::Offline,
]);
break; break;
} }
} }

View File

@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('insecticidal_lamp_reports', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('device_id');
$table->double('battery_vol')->nullable()->comment('蓄电池电压');
$table->unsignedInteger('killed_num')->default(0)->comment('杀虫树');
$table->double('air_temperature')->nullable()->comment('大气气温');
$table->double('air_humidity')->nullable()->comment('大气湿度');
$table->double('lng')->nullable()->comment('经度');
$table->double('lat')->nullable()->comment('纬度');
$table->double('solar_panel_vol')->nullable()->comment('太阳板电压');
$table->double('high_vol')->nullable()->comment('高压值');
$table->timestamp('reported_at')->comment('监控日期');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('insecticidal_lamp_reports');
}
};