Compare commits

...

11 Commits

Author SHA1 Message Date
Jing Li b86efdc00b Update 2023-08-04 18:27:15 +08:00
Jing Li c2475f4baa Fix 2023-08-04 12:11:06 +08:00
Jing Li cd16fbf658 设备厂家和项目 2023-08-04 09:38:57 +08:00
Jing Li 29502e0d4a Fix 2023-08-03 22:55:39 +08:00
Jing Li a4f814bfac Update 2023-08-03 22:49:00 +08:00
Jing Li ab75c4e7b4 比昂大数据平台 2023-08-03 21:10:41 +08:00
李静 d7459ec032 Update 2023-08-03 15:36:22 +08:00
Jing Li 7820f01b32 Update 2023-08-02 22:31:51 +08:00
Jing Li 025cea099e Update 2023-08-02 22:18:37 +08:00
李静 a2da7a73cd linkos 数据同步及处理 2023-08-02 17:51:49 +08:00
李静 e2b7bdc6e6 设备厂商 2023-08-02 15:15:59 +08:00
22 changed files with 1384 additions and 16 deletions

View File

@ -0,0 +1,127 @@
<?php
namespace App\Console\Commands;
use App\Enums\DeviceType;
use App\Models\Device;
use App\Models\MeteorologicalMonitoringDailyLog;
use App\Models\MeteorologicalMonitoringLog;
use App\Models\SoilMonitoringDailyLog;
use App\Models\SoilMonitoringLog;
use App\Models\WaterQualityMonitoringDailyLog;
use App\Models\WaterQualityMonitoringLog;
use App\Services\BiAngDeviceLogService;
use App\Services\DeviceLogService;
use Illuminate\Console\Command;
class DeviceLogDailyReportCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'device-log:daily-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()
{
$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(['supplier'])->supplierBy("device-supplier-{$factory}")->get();
foreach ($devices as $device) {
switch ($device->supplier?->key) {
case 'device-supplier-biang':
$this->createReportToBiAngDevice($device);
break;
}
}
sleep($sleep);
};
}
/**
* 创建 linkos 设备报告
*/
protected function createReportToBiAngDevice(Device $device): void
{
[$lastReportedAt, $latestReportedAt] = value(function (Device $device) {
$lastReportedAt = null;
$latestReportedAt = null;
switch ($device->type) {
case DeviceType::Meteorological:
$lastReportedAt = MeteorologicalMonitoringDailyLog::where('device_id', $device->id)
->latest('monitored_at')
->value('monitored_at');
$lastReportedAt ??= MeteorologicalMonitoringLog::where('device_id', $device->id)
->oldest('monitored_at')
->value('monitored_at');
if ($lastReportedAt) {
$latestReportedAt = MeteorologicalMonitoringLog::where('device_id', $device->id)
->latest('monitored_at')
->value('monitored_at');
}
break;
case DeviceType::Soil:
$lastReportedAt = SoilMonitoringDailyLog::where('device_id', $device->id)
->latest('monitored_at')
->value('monitored_at');
$lastReportedAt ??= SoilMonitoringLog::where('device_id', $device->id)
->oldest('monitored_at')
->value('monitored_at');
if ($lastReportedAt) {
$latestReportedAt = SoilMonitoringLog::where('device_id', $device->id)
->latest('monitored_at')
->value('monitored_at');
}
break;
}
return [$lastReportedAt, $latestReportedAt];
}, $device);
if ($lastReportedAt === null || $latestReportedAt === null) {
return;
}
$service = new BiAngDeviceLogService();
/** @var \Carbon\Carbon */
$startAt = $lastReportedAt->copy()->startOfDay();
do {
$service->createDailyReport($device, $startAt->copy());
$startAt->addDay();
} while ($latestReportedAt->gte($startAt));
}
}

View File

@ -0,0 +1,91 @@
<?php
namespace App\Console\Commands;
use App\Enums\DeviceType;
use App\Models\Device;
use App\Models\DeviceLog;
use App\Models\MeteorologicalMonitoringLog;
use App\Models\SoilMonitoringLog;
use App\Services\BiAngDeviceLogService;
use Illuminate\Console\Command;
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()
{
$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(['supplier'])->supplierBy("device-supplier-{$factory}")->get();
foreach ($devices as $device) {
switch ($device->supplier?->key) {
case 'device-supplier-biang':
$this->createReportToBiAngDevice($device);
break;
}
}
sleep($sleep);
};
}
/**
* 创建比昂设备报告
*/
protected function createReportToBiAngDevice(Device $device): void
{
$lastReportedAt = match ($device->type) {
DeviceType::Soil => SoilMonitoringLog::where('device_id', $device->id)->latest('monitored_at')->value('monitored_at'),
DeviceType::Meteorological => MeteorologicalMonitoringLog::where('device_id', $device->id)->latest('monitored_at')->value('monitored_at'),
default => null,
};
if (is_null($lastReportedAt ??= DeviceLog::where('device_id', $device->id)->oldest('reported_at')->value('reported_at'))) {
return;
}
if (is_null($latestReportedAt = DeviceLog::where('device_id', $device->id)->latest('reported_at')->value('reported_at'))) {
return;
}
$service = new BiAngDeviceLogService();
/** @var \Carbon\Carbon */
$startAt = $lastReportedAt->copy()->startOfHour();
do {
$service->createReport($device, $startAt->copy());
$startAt->addHour();
} while ($latestReportedAt->gte($startAt));
}
}

View File

@ -0,0 +1,92 @@
<?php
namespace App\Console\Commands;
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 = 'device-log:sync
{factory}
{--sleep=60 : 设备数据同步完成后的休眠时间(秒)}';
/**
* The console command description.
*
* @var string
*/
protected $description = '按设备厂商同步数据';
/**
* Execute the console command.
*/
public function handle()
{
$factory = $this->argument('factory');
$sleep = (int) value(fn ($sleep) => is_numeric($sleep) ? $sleep : 60, $this->option('sleep'));
while (true) {
$this->runSync($factory);
sleep($sleep);
};
}
/**
* 执行同步
*/
protected function runSync(string $factory): void
{
$end = now();
$start = $end->copy()->subHours(1);
$this->info('------------------------------------------');
$this->info('开始时间: '. $start);
$this->info('结束时间: '. $end);
/** @var \Illuminate\Database\Eloquent\Collection */
$devices = Device::with(['supplier', 'project'])->supplierBy("device-supplier-{$factory}")->get();
/** @var \App\Models\Device */
foreach ($devices as $device) {
$this->info('==========================================');
$this->info('设备编号: ' . $device->sn);
$this->info('设备名称: ' . $device->name);
$this->info('设备类型: ' . match ($device->type) {
DeviceType::Soil => '土壤设备',
DeviceType::WaterQuality => '水质设备',
DeviceType::Meteorological => '气象设备',
default => '其它',
});
try {
switch ($device->supplier?->key) {
case 'device-supplier-biang':
(new BiAngDeviceLogService())->sync($device);
break;
}
$this->info('同步成功!');
} catch (Throwable $e) {
report($e);
$this->error('同步失败: '. $e->getMessage());
}
$this->info('==========================================');
}
$this->info('------------------------------------------');
$this->newLine();
}
}

View File

@ -8,6 +8,7 @@ enum DeviceType: int
case Soil = 2; // 土壤设备
case WaterQuality = 3; // 水质设备
case Meteorological = 4; // 气象设备
case Insect = 5; // 虫情设备
/**
* @return string
@ -27,6 +28,7 @@ enum DeviceType: int
static::Soil->value => '土壤设备',
static::WaterQuality->value => '水质设备',
static::Meteorological->value => '气象设备',
static::Insect->value => '虫情设备',
];
}
}

View File

@ -4,29 +4,29 @@ namespace App\Http\Controllers;
use App\Enums\DeviceStatus;
use App\Enums\DeviceType;
use App\Enums\OperationType;
use App\Helpers\Paginator;
use App\Http\Requestes\DeviceRequest;
use App\Http\Resources\DeviceResource;
use App\Models\Device;
use App\Models\MeteorologicalMonitoringLog;
use App\Models\MeteorologicalMonitoringDailyLog;
use App\Models\SoilMonitoringLog;
use App\Models\SoilMonitoringDailyLog;
use App\Models\WaterQualityMonitoringLog;
use App\Models\WaterQualityMonitoringDailyLog;
use App\Models\AgriculturalBase;
use App\Models\Device;
use App\Models\MeteorologicalMonitoringDailyLog;
use App\Models\MeteorologicalMonitoringLog;
use App\Models\SoilMonitoringDailyLog;
use App\Models\SoilMonitoringLog;
use App\Models\WaterQualityMonitoringDailyLog;
use App\Models\WaterQualityMonitoringLog;
use App\Services\OperationLogService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Services\OperationLogService;
use App\Enums\OperationType;
use Peidikeji\Setting\Models\Setting;
class DeviceController extends Controller
{
public function index(Request $request)
{
$query = Device::with('base')->filter($request->input())->orderBy('sort', 'desc');
$query = Device::with(['base', 'supplier', 'project'])->filter($request->input())->orderBy('sort', 'desc');
$list = $query->paginate(Paginator::resolvePerPage('per_page', 20, 50));
return $this->json(DeviceResource::collection($list));
@ -51,6 +51,7 @@ class DeviceController extends Controller
public function show(Device $device)
{
$device->loadMissing(['base', 'supplier', 'project']);
return $this->json(DeviceResource::make($device));
}

View File

@ -22,6 +22,7 @@ class DeviceRequest extends FormRequest
'agricultural_base_id' => 'required|integer|min:0',
'sn' => 'required|string|max:64',
'monitoring_point' => 'required|string|max:100',
'supplier_key' => 'required',
'extends' => 'required_if:type,1',
'extends.ip' => 'required_if:type,1|string',
'extends.port' => 'required_if:type,1|string',
@ -34,6 +35,13 @@ class DeviceRequest extends FormRequest
];
}
public function attributes()
{
return [
'supplier_key' => '设备厂商',
];
}
public function messages()
{
$messages = [

View File

@ -31,6 +31,18 @@ class DeviceResource extends JsonResource
'created_at' => strtotime($this->created_at) ?? 0, //录入时间
'is_recommend' => $this->is_recommend,
'sort' => $this->sort ?? 0,
'supplier' => $this->whenLoaded('supplier', function () {
return $this->supplier ? [
'id' => $this->supplier->key,
'name' => $this->supplier->name,
] : null;
}),
'project' => $this->whenLoaded('project', function () {
return $this->project ? [
'id' => $this->project->key,
'name' => $this->project->name,
] : null;
}),
];
}
}

View File

@ -0,0 +1,123 @@
<?php
namespace App\Iot\BiAng;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use RuntimeException;
class HttpClient
{
public function __construct(
protected readonly string $username,
protected readonly string $password,
) {
}
/**
* 获取最新的土壤数据
*/
public function getLatestSoilReport(string $deviceId)
{
$result = $this->get(
$this->apiUrl('/api/open-api/open/soilMoisture/getCurrentDeviceData'),
[
'deviceId' => $deviceId,
]
);
if (data_get($result, 'code') === 200) {
return $result['data'];
}
throw new RuntimeException(
sprintf("%s:%s", data_get($result, 'code', 500), data_get($result, 'msg', '出错啦!'))
);
}
/**
* 获取最新的气象数据
*/
public function getLatestMeteorologicalReport(string $deviceId)
{
$result = $this->get(
$this->apiUrl('/api/open-api/open/weather/getCurrentDeviceData'),
[
'deviceId' => $deviceId,
]
);
if (data_get($result, 'code') === 200) {
return $result['data'];
}
throw new RuntimeException(
sprintf("%s:%s", data_get($result, 'code', 500), data_get($result, 'msg', '出错啦!'))
);
}
public function get(string $url, array $query = []): array
{
return $this->request('GET', $url, [
'query' => $query,
]);
}
/**
* @param string $url
* @param array $data
* @return array
*/
public function post(string $url, array $data = []): array
{
return $this->request('POST', $url, [
'json' => $data,
]);
}
/**
* @param string $method
* @param string $url
* @param array $options
* @return array
*
* @throws \Illuminate\Http\Client\RequestException
* @throws \RuntimeException
*/
public function request(string $method, string $url, array $options = []): array
{
switch (strtoupper($method)) {
case 'GET':
$options['query'] = array_merge($options['query'], [
'username' => $this->username,
'password' => $this->password,
]);
break;
case 'POST':
$options['json'] = array_merge($options['json'], [
'username' => $this->username,
'password' => $this->password,
]);
break;
}
/** @var \Illuminate\Http\Client\Response */
$response = Http::withHeaders([
'Content-Type' => 'application/json',
])->send($method, $url, $options);
return $response->throw()->json();
}
protected function apiUrl(string $path): string
{
return 'http://yun.bigdata5s.com'.Str::start($path, '/');
}
protected function apiUrl2(string $path): string
{
return 'http://yun-api.bigdata5s.com'.Str::start($path, '/');
}
}

View File

@ -0,0 +1,160 @@
<?php
namespace App\Iot\Linkos;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class HttpClient
{
public const ENDPOINT_URL = 'http://service.easylinkin.com';
public function __construct(
protected readonly string $apiKey,
protected readonly string $apiSecret,
) {
}
/**
* 获取设备的历史数据
*
* @param string $deviceId
* @param \Illuminate\Support\Carbon $start
* @param \Illuminate\Support\Carbon $end
* @param int $page
* @param int $perPage
* @return array
*/
public function deviceFlowList(string $deviceId, Carbon $start, Carbon $end, int $page = 1, int $perPage = 50): array
{
$result = $this->post('/api/deviceFlow/v1/list', [
'device_id' => $deviceId,
'start_time' => $start->unix() * 1000,
'end_time' => $end->unix() * 1000,
'pageable' => [
'page' => $page - 1,
'size' => $perPage,
],
]);
if (data_get($result, 'success') !== true) {
throw new RuntimeException(data_get($result, 'msg', '出错啦!'));
}
return $result['data'];
}
/**
* 设备数据下行
*
* @param string $deviceId
* @param string $service
* @param array $data
* @param boolean $confirm
* @param boolean $clear
* @param boolean $schedule
* @return array
*/
public function deviceDataDownlink(string $deviceId, string $service, array $data = [], bool $confirm = true, bool $clear = true, bool $schedule = false): array
{
return $this->post('/api/down', [
'device_id' => $deviceId,
'service_id' => $service,
'parameter' => $data,
'clear' => (int) $clear,
'schedule' => (int) $schedule,
'confirm' => (int) $confirm,
]);
}
/**
* 获取设备最新属性数据
*/
public function getDeviceStatus(string $deviceId, array $props): array
{
$result = $this->get('/api/deviceStatus/v1/getDeviceStatus', [
'deviceCode' => $deviceId,
'prop' => implode(",", $props),
]);
if (data_get($result, 'success') !== true) {
throw new RuntimeException(data_get($result, 'msg', '出错啦!'));
}
return $result['data'];
}
public function get(string $url, array $query = []): array
{
return $this->request('GET', $url, [
'query' => $query,
]);
}
/**
* @param string $url
* @param array $data
* @return array
*/
public function post(string $url, array $data = []): array
{
return $this->request('POST', $url, [
'json' => $data,
]);
}
/**
* @param string $method
* @param string $url
* @param array $options
* @return array
*
* @throws \Illuminate\Http\Client\RequestException
* @throws \RuntimeException
*/
public function request(string $method, string $url, array $options = []): array
{
$nonce = $this->nonce();
$timestamp = now()->getTimestampMs();
/** @var \Illuminate\Http\Client\Response */
$response = Http::withHeaders([
'Content-Type' => 'application/json',
'api-key' => $this->apiKey,
'Nonce' => $nonce,
'Timestamp' => $timestamp,
'Signature' => $this->sign(compact('nonce', 'timestamp')),
])->baseUrl(self::ENDPOINT_URL)->send($method, $url, $options);
return $response->throw()->json();
}
/**
* @param array $data
* @return string
*/
protected function sign(array $data): string
{
return sha1(
sprintf(
'%s%s%s',
$data['nonce'] ?? '',
$data['timestamp'] ?? '',
$this->apiSecret
)
);
}
protected function nonce(): string
{
$nonce = '';
for ($i = 0; $i < 8; $i++) {
$nonce .= mt_rand(0, 9);
}
return $nonce;
}
}

View File

@ -2,13 +2,15 @@
namespace App\Models;
use App\Enums\DeviceType;
use App\Enums\DeviceStatus;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Model;
use App\Enums\DeviceType;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use EloquentFilter\Filterable;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Peidikeji\Keywords\Models\Keywords;
class Device extends Model
{
@ -37,8 +39,15 @@ class Device extends Model
'created_by',
'updated_by',
'sort',
'supplier_key',
'project_key',
];
public function scopeSupplierBy(Builder $query, string $supplier): void
{
$query->whereHas('supplier', fn ($query) => $query->where('supplier_key', $supplier));
}
public function base()
{
return $this->belongsTo(AgriculturalBase::class, 'agricultural_base_id');
@ -53,4 +62,24 @@ class Device extends Model
{
return $this->belongsTo(AdminUser::class, 'updated_by');
}
public function supplier(): BelongsTo
{
return $this->belongsTo(Keywords::class, 'supplier_key', 'key');
}
public function project(): BelongsTo
{
return $this->belongsTo(Keywords::class, 'project_key', 'key');
}
public function isTypeSoil(): bool
{
return $this->type === DeviceType::Soil;
}
public function isTypeMeteorological(): bool
{
return $this->type === DeviceType::Meteorological;
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class DeviceLog extends Model
{
use HasFactory;
protected $casts = [
'data' => 'json',
'reported_at' => 'datetime',
];
protected $fillable = [
'device_id',
'data',
'reported_at',
];
}

View File

@ -10,6 +10,15 @@ class MeteorologicalMonitoringDailyLog extends Model
{
use HasFactory;
const WIND_DIRECTION_NORTH = 0;
const WIND_DIRECTION_NORTHEAST = 1;
const WIND_DIRECTION_EAST = 2;
const WIND_DIRECTION_SOUTHEAST = 3;
const WIND_DIRECTION_SOUTH = 4;
const WIND_DIRECTION_SOUTHWEST = 5;
const WIND_DIRECTION_WEST = 6;
const WIND_DIRECTION_NORTHWEST = 7;
protected $casts = [
'wind_direction' => WindDirection::class,
'monitored_at' => 'date',

View File

@ -6,6 +6,7 @@ use App\Services\LinkosService;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
use App\Iot\Linkos\HttpClient as LinkosHttpClient;
class AppServiceProvider extends ServiceProvider
{
@ -22,6 +23,8 @@ class AppServiceProvider extends ServiceProvider
return new LinkosService($config['key'] ?? '', $config['secret'] ?? '');
});
$this->registerLinkos();
}
/**
@ -48,4 +51,14 @@ class AppServiceProvider extends ServiceProvider
// ]);
}
protected function registerLinkos(): void
{
$this->app->singleton(LinkosHttpClient::class, function ($app) {
return new LinkosHttpClient(
(string) $app['config']->get('services.linkos.key'),
(string) $app['config']->get('services.linkos.secret')
);
});
}
}

View File

@ -0,0 +1,430 @@
<?php
namespace App\Services;
use App\Enums\DeviceStatus;
use App\Enums\DeviceType;
use App\Iot\BiAng\HttpClient as BiAngHttpClient;
use App\Models\Device;
use App\Models\DeviceLog;
use App\Models\MeteorologicalMonitoringDailyLog;
use App\Models\MeteorologicalMonitoringLog;
use App\Models\SoilMonitoringDailyLog;
use App\Models\SoilMonitoringLog;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class BiAngDeviceLogService
{
public function sync(Device $device): 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;
case DeviceType::Meteorological:
$data = $httpClient->getLatestMeteorologicalReport($device->sn);
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;
}
}
}
/**
* 创建设备报告
*/
public function createReport(Device $device, Carbon $time): void
{
switch ($device->type) {
case DeviceType::Soil:
$this->createSoilReport($device, $time);
break;
case DeviceType::Meteorological:
$this->createMeteorologicalReport($device, $time);
break;
}
}
/**
* 创建土壤设备报告
*/
protected function createSoilReport(Device $device, Carbon $time): void
{
$reportedAt = $time->copy()->startOfHour();
/** @var \Illuminate\Database\Eloquent\Collection */
$logs = DeviceLog::where('device_id', $device->id)
->whereBetween('reported_at', [$reportedAt, $reportedAt->copy()->endOfHour()])
->oldest('reported_at')
->get();
if ($logs->isEmpty()) {
return;
}
$attributes = $logs->reduce(function (array $attributes, DeviceLog $log) {
if (is_array($data = $log->data)) {
foreach ($data as $k => $v) {
$attribute = match ($k) {
'soilAlkalineHydrolyzedNitrogen' => 'n',
'soilAvailablePotassium' => 'k',
'soilAvailablePhosphorus' => 'p',
'soilConductivity' => 'conductivity',
'soilTemperature' => 'temperature',
'soilMoisture' => 'humidity',
default => null,
};
if ($attribute) {
$attributes[$attribute] = $v;
}
}
}
return $attributes;
}, []);
$soilReport = SoilMonitoringLog::where([
'device_id' => $device->id,
'monitored_at' => $reportedAt,
])->first();
if ($soilReport === null) {
$lastSoilReport = SoilMonitoringLog::where([
'device_id' => $device->id,
'monitored_at' => $reportedAt->copy()->subHour(),
])->first();
$soilReport = $lastSoilReport?->replicate() ?: new SoilMonitoringLog();
$soilReport->fill([
'device_id' => $device->id,
'monitored_at' => $reportedAt,
'agricultural_base_id' => $device->agricultural_base_id,
]);
}
$soilReport->fill($attributes)->save();
}
/**
* 创建气象设备报告
*/
protected function createMeteorologicalReport(Device $device, Carbon $time): void
{
$reportedAt = $time->copy()->startOfHour();
/** @var \Illuminate\Database\Eloquent\Collection */
$logs = DeviceLog::where('device_id', $device->id)
->whereBetween('reported_at', [$reportedAt, $reportedAt->copy()->endOfHour()])
->oldest('reported_at')
->get();
if ($logs->isEmpty()) {
return;
}
$attributes = $logs->reduce(function (array $attributes, DeviceLog $log) {
if (is_array($data = $log->data)) {
foreach ($data as $k => $v) {
$attribute = match ($k) {
'rainfall' => 'moment_rainfall', //瞬时降雨量
'lightIntensity' => 'illumination',
'airTemperature' => 'air_temperature',
'airHumidity' => 'air_humidity',
'windDirection' => 'wind_degree',
'windSpeed' => 'wind_speed',
default => null,
};
if ($attribute) {
if ($attribute == 'moment_rainfall') {
$attributes[$attribute] = bcadd($attributes[$attribute] ?? '0.00', $v, 2);
} else {
$attributes[$attribute] = $v;
}
}
}
}
return $attributes;
}, []);
# 累计雨量求和
$attributes['current_rainfall'] = DeviceLog::select(DB::raw("SUM((data->>'rainfall')::NUMERIC) as aggregate"))->where('device_id', $device->id)
->whereBetween('reported_at', [$reportedAt->copy()->startOfDay(), $reportedAt->copy()->endOfHour()])
->value('aggregate') ?: 0;
$meteorologicalReport = MeteorologicalMonitoringLog::where([
'device_id' => $device->id,
'monitored_at' => $reportedAt,
])->first();
if ($meteorologicalReport === null) {
$lastMeteorologicalReport = MeteorologicalMonitoringLog::where([
'device_id' => $device->id,
'monitored_at' => $reportedAt->copy()->subHour(),
])->first();
$meteorologicalReport = $lastMeteorologicalReport?->replicate() ?: new MeteorologicalMonitoringLog();
$meteorologicalReport->fill([
'device_id' => $device->id,
'monitored_at' => $reportedAt,
'agricultural_base_id' => $device->agricultural_base_id,
]);
}
$meteorologicalReport->fill($attributes)->save();
}
/**
* 创建设备每日报告
*/
public function createDailyReport(Device $device, Carbon $time): void
{
switch ($device->type) {
case DeviceType::Meteorological:
$this->createMeteorologicalDailyReport($device, $time);
break;
case DeviceType::Soil:
$this->createSoilDailyReport($device, $time);
break;
}
}
/**
* 创建土壤设备每日报告
*/
protected function createSoilDailyReport(Device $device, Carbon $date): void
{
/** @var \Illuminate\Database\Eloquent\Collection */
$soilReports = SoilMonitoringLog::where('device_id', $device->id)
->whereDate('monitored_at', $date)
->oldest('monitored_at')
->get();
if ($soilReports->isEmpty()) {
return;
}
$attributes = value(function ($soilReports) {
$data = [
'n' => ['sum' => 0, 'count' => 0],
'p' => ['sum' => 0, 'count' => 0],
'k' => ['sum' => 0, 'count' => 0],
'conductivity' => ['sum' => 0, 'count' => 0],
'temperature' => ['sum' => 0, 'count' => 0],
'humidity' => ['sum' => 0, 'count' => 0],
'moisture' => ['sum' => 0, 'count' => 0],
];
foreach ($soilReports as $soilReport) {
foreach ($data as $k => $item) {
if (is_null($v = $soilReport->{$k})) {
continue;
}
$item['sum'] = bcadd($item['sum'], $v, 2);
$item['count']++;
$data[$k] = $item;
}
}
$attributes = [];
foreach ($data as $key => $item) {
$attributes[$key] = $item['count'] > 0 ? round(bcdiv($item['sum'], $item['count'], 2), 2) : null;
}
return $attributes;
}, $soilReports);
/** @var \App\Models\SoilDailyReport */
$soilDailyReport = SoilMonitoringDailyLog::firstOrNew([
'device_id' => $device->id,
'monitored_at' => $date->format('Y-m-d'),
], [
'agricultural_base_id' => $device->agricultural_base_id,
]);
$soilDailyReport->fill($attributes)->save();
}
/**
* 创建气象设备每日报告
*/
protected function createMeteorologicalDailyReport(Device $device, Carbon $date): void
{
/** @var \Illuminate\Database\Eloquent\Collection */
$meteorologicalReports = MeteorologicalMonitoringLog::where('device_id', $device->id)
->whereDate('monitored_at', $date)
->oldest('monitored_at')
->get();
if ($meteorologicalReports->isEmpty()) {
return;
}
$attributes = value(function ($meteorologicalReports) {
$data = [
'current_rainfall' => 0,
'illumination' => ['sum' => 0, 'count' => 0],
'air_temperature' => ['sum' => 0, 'count' => 0],
'air_humidity' => ['sum' => 0, 'count' => 0],
'wind_speed' => ['sum' => 0, 'count' => 0],
'wind_samples' => [],
];
foreach ($meteorologicalReports as $meteorologicalReport) {
foreach ($data as $k => $item) {
if ($k === 'wind_samples') {
if (is_null($meteorologicalReport->wind_degree) || is_null($meteorologicalReport->wind_speed)) {
continue;
}
$item[] = [
'wind_degree' => $meteorologicalReport->wind_degree, // 风向度数
'wind_speed' => $meteorologicalReport->wind_speed, // 风速
];
} elseif (! is_null($v = $meteorologicalReport->{$k})) {
if ($k === 'current_rainfall') {
$item = $v;
} else {
$item['sum'] = bcadd($item['sum'], $v, 2);
$item['count']++;
}
}
$data[$k] = $item;
}
}
$attributes = [];
foreach ($data as $key => $item) {
switch ($key) {
case 'current_rainfall':
$attributes['daily_rainfall'] = $item;
break;
case 'wind_samples':
if (! empty($item)) {
$attributes['wind_degree'] = value(function (array $windSamples) {
if (empty($windSamples)) {
return null;
}
$x = 0;
$y = 0;
foreach ($windSamples as $sample) {
if ($sample['wind_degree'] == 0 && $sample['wind_speed'] == 0) {
continue;
}
// 角度转弧度
$radian = deg2rad($sample['wind_degree']);
// $x += $sample['wind_speed'] * sin($radian);
// $y += $sample['wind_speed'] * cos($radian);
$x += sin($radian);
$y += cos($radian);
}
$degree = round(rad2deg(atan2($y, $x)));
if (($x > 0 || $x < 0) && $y < 0) {
$degree += 180;
} elseif ($x < 0 && $y > 0) {
$degree += 360;
}
return $degree;
}, $item);
$attributes['wind_direction'] = value(function ($windDegree) {
if (is_null($windDegree)) {
return null;
}
if ($windDegree >= 22.5 && $windDegree < 67.5) {
return MeteorologicalMonitoringDailyLog::WIND_DIRECTION_NORTHEAST;
} elseif ($windDegree >= 67.5 && $windDegree < 112.5) {
return MeteorologicalMonitoringDailyLog::WIND_DIRECTION_EAST;
} elseif ($windDegree >= 112.5 && $windDegree < 157.5) {
return MeteorologicalMonitoringDailyLog::WIND_DIRECTION_SOUTHEAST;
} elseif ($windDegree >= 157.5 && $windDegree < 202.5) {
return MeteorologicalMonitoringDailyLog::WIND_DIRECTION_SOUTH;
} elseif ($windDegree >= 202.5 && $windDegree < 247.5) {
return MeteorologicalMonitoringDailyLog::WIND_DIRECTION_SOUTHWEST;
} elseif ($windDegree >= 247.5 && $windDegree < 292.5) {
return MeteorologicalMonitoringDailyLog::WIND_DIRECTION_WEST;
} elseif ($windDegree >= 292.5 && $windDegree < 337.5) {
return MeteorologicalMonitoringDailyLog::WIND_DIRECTION_NORTHWEST;
}
return MeteorologicalMonitoringDailyLog::WIND_DIRECTION_NORTH;
}, $attributes['wind_degree']);
}
break;
default:
$attributes[$key] = $item['count'] > 0 ? round(bcdiv($item['sum'], $item['count'], 2), 2) : null;
break;
}
}
return $attributes;
}, $meteorologicalReports);
/** @var \App\Models\MeteorologicalMonitoringDailyLog */
$meteorologicalDailyReport = MeteorologicalMonitoringDailyLog::firstOrNew([
'device_id' => $device->id,
'monitored_at' => $date,
], [
'agricultural_base_id' => $device->agricultural_base_id,
]);
$meteorologicalDailyReport->fill($attributes)->save();
}
}

View File

@ -2,6 +2,7 @@
namespace App\Services;
use App\Enums\DeviceStatus;
use App\Enums\DeviceType;
use App\Enums\WindDirection;
use App\Exceptions\BizException;
@ -89,6 +90,8 @@ class LinkosDeviceLogService
throw new BizException("设备未找到, 设备编号: {$deviceId}");
}
Device::where('sn', $deviceId)->update(['status' => DeviceStatus::Online]);
$log = LinkosDeviceLog::create([
'device_id' => $deviceId,
'device_unit' => $deviceUnit,
@ -235,7 +238,7 @@ class LinkosDeviceLogService
}
$log->save();
}
/**

View File

@ -0,0 +1,32 @@
<?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::table('devices', function (Blueprint $table) {
$table->string('supplier_key')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('devices', function (Blueprint $table) {
$table->dropColumn(['supplier_key']);
});
}
};

View File

@ -0,0 +1,37 @@
<?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('device_logs', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('device_id');
$table->json('data')->nullable();
$table->timestamp('reported_at');
$table->timestamps();
$table->index(['device_id', 'reported_at']);
$table->index('reported_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('device_logs');
}
};

View File

@ -0,0 +1,32 @@
<?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::table('devices', function (Blueprint $table) {
$table->string('project_key')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('devices', function (Blueprint $table) {
$table->dropColumn(['project_key']);
});
}
};

View File

@ -0,0 +1,32 @@
<?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::table('meteorological_monitoring_daily_logs', function (Blueprint $table) {
$table->decimal('wind_degree', 5, 2)->nullable()->comment('风向度数')->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('meteorological_monitoring_daily_logs', function (Blueprint $table) {
$table->integer('wind_degree')->nullable()->comment('风向度数')->change();
});
}
};

View File

@ -0,0 +1,34 @@
<?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::table('meteorological_monitoring_logs', function (Blueprint $table) {
$table->decimal('wind_degree', 5, 2)->nullable()->comment('风向度数')->change();
$table->decimal('illumination', 10, 2)->nullable()->comment('光照度 (单位: Lux)')->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('meteorological_monitoring_logs', function (Blueprint $table) {
$table->integer('wind_degree')->nullable()->comment('风向度数')->change();
$table->integer('illumination')->nullable()->comment('光照度 (单位: Lux)')->change();
});
}
};

View File

@ -0,0 +1,36 @@
<?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::table('soil_monitoring_logs', function (Blueprint $table) {
$table->decimal('n', 8, 2)->nullable()->comment('氮 (单位: mg/kg)')->change();
$table->decimal('p', 8, 2)->nullable()->comment('磷 (单位: mg/kg)')->change();
$table->decimal('k', 8, 2)->nullable()->comment('钾 (单位: mg/kg)')->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('soil_monitoring_logs', function (Blueprint $table) {
$table->integer('n')->nullable()->comment('氮 (单位: mg/kg)')->change();
$table->integer('p')->nullable()->comment('磷 (单位: mg/kg)')->change();
$table->integer('k')->nullable()->comment('钾 (单位: mg/kg)')->change();
});
}
};

View File

@ -32,6 +32,48 @@ class KeywordsTableSeeder extends Seeder
['key' => 'crops-cate-lingye', 'name' => '林业', 'type_key' => 'crops-category', 'value' => ''],
['key' => 'crops-cate-activity', 'name' => '其他', 'type_key' => 'crops-category', 'value' => ''],
]],
[
'key' => 'device-supplier',
'name' => '设备供应商',
'value' => '',
'list' => [
['key' => 'device-supplier-linkos', 'name' => '慧联无限', 'value' => ''],
['key' => 'device-supplier-biang', 'name' => '比昂', 'value' => ''],
['key' => 'device-supplier-other', 'name' => '其它', 'value' => ''],
],
],
[
'key' => 'device-project',
'name' => '设备项目',
'value' => '',
'list' => [
[
'key' => 'device-project-cyxdnyyq',
'name' => '成渝现代高效特色农业带合作园区',
'value' => json_encode([
'username' => '成渝现代高效特色农业带合作园区',
'password' => '888888',
]),
],
[
'key' => 'device-project-nyncj',
'name' => '隆昌市农业农村局',
'value' => json_encode([
'username' => '隆昌市农业农村局',
'password' => '888888',
]),
],
[
'key' => 'device-project-syqshc',
'name' => '隆昌市石燕桥镇三合村股份经济联合社',
'value' => json_encode([
'username' => '隆昌市石燕桥镇三合村股份经济联合社',
'password' => '888888',
]),
],
['key' => 'device-project-other', 'name' => '其它', 'value' => ''],
],
]
];
$list[] = value(function () {
@ -61,6 +103,7 @@ class KeywordsTableSeeder extends Seeder
'type_key' => $parentType->key,
'level' => ($parentType->level ?? 1) + 1,
'parent_id' => $parentType->id,
'value' => $item['value'],
]);
} else {
$type = Keywords::create(Arr::except($item, 'list'));