71 lines
2.6 KiB
PHP
71 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\SortingHistory;
|
|
use Illuminate\Http\Request;
|
|
|
|
class IoTController extends Controller
|
|
{
|
|
public function store(Request $request)
|
|
{
|
|
$validated = $request->validate([
|
|
'raw_banana_weight' => 'required|numeric',
|
|
'ripe_banana_weight' => 'required|numeric',
|
|
'raw_orange_weight' => 'required|numeric',
|
|
'ripe_orange_weight' => 'required|numeric',
|
|
]);
|
|
|
|
$activeSession = \App\Models\SortingSession::active()->first();
|
|
$sessionId = $activeSession ? (string) $activeSession->_id : null;
|
|
|
|
// 1. Abaikan data jika semua berat adalah 0 (timbangan kosong)
|
|
$hasWeight = (float) $validated['raw_banana_weight'] > 0 ||
|
|
(float) $validated['ripe_banana_weight'] > 0 ||
|
|
(float) $validated['raw_orange_weight'] > 0 ||
|
|
(float) $validated['ripe_orange_weight'] > 0;
|
|
|
|
if (!$hasWeight) {
|
|
return response()->json([
|
|
'message' => 'Data skipped (all weights 0)',
|
|
'data' => null
|
|
], 200);
|
|
}
|
|
|
|
// 2. Cegah duplikasi jika ada sesi aktif
|
|
if ($sessionId) {
|
|
$lastRecord = SortingHistory::where('session_id', $sessionId)
|
|
->latest('classification_date')
|
|
->first();
|
|
|
|
if ($lastRecord) {
|
|
$timeDiff = now()->diffInSeconds($lastRecord->classification_date);
|
|
if ($timeDiff < 3) {
|
|
$isDuplicate = abs((float)$lastRecord->raw_banana_weight - (float)$validated['raw_banana_weight']) < 0.1 &&
|
|
abs((float)$lastRecord->ripe_banana_weight - (float)$validated['ripe_banana_weight']) < 0.1 &&
|
|
abs((float)$lastRecord->raw_orange_weight - (float)$validated['raw_orange_weight']) < 0.1 &&
|
|
abs((float)$lastRecord->ripe_orange_weight - (float)$validated['ripe_orange_weight']) < 0.1;
|
|
|
|
if ($isDuplicate) {
|
|
return response()->json([
|
|
'message' => 'Data skipped (duplicate)',
|
|
'data' => null
|
|
], 200);
|
|
}
|
|
}
|
|
}
|
|
$validated['session_id'] = $sessionId;
|
|
}
|
|
|
|
$validated['classification_date'] = now();
|
|
|
|
$history = SortingHistory::create($validated);
|
|
|
|
return response()->json([
|
|
'message' => 'Data saved successfully',
|
|
'data' => $history
|
|
], 201);
|
|
}
|
|
}
|