From 97141bd579a89e634118aae1aaeba3a68e74a184 Mon Sep 17 00:00:00 2001 From: sayaliparab Date: Tue, 8 Apr 2025 13:08:54 +0530 Subject: [PATCH] UserAssest --- .../CustomerApi/UserAssetLinkController.php | 183 +++++++++++++++--- 1 file changed, 152 insertions(+), 31 deletions(-) diff --git a/app/Http/Controllers/APIS/CustomerApi/UserAssetLinkController.php b/app/Http/Controllers/APIS/CustomerApi/UserAssetLinkController.php index 67eb051..b1bdeaa 100644 --- a/app/Http/Controllers/APIS/CustomerApi/UserAssetLinkController.php +++ b/app/Http/Controllers/APIS/CustomerApi/UserAssetLinkController.php @@ -14,7 +14,7 @@ use Illuminate\Container\Attributes\Auth; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Log; use Exception; - +use Illuminate\Support\Carbon; class UserAssetLinkController extends Controller { @@ -147,8 +147,107 @@ class UserAssetLinkController extends Controller // } // } + // public function index() + // { + // try { + // $token = readHeaderToken(); - + // $user = User::with(['assets.devices']) + // ->withCount([ + // 'assets as active_devices_count' => function ($query) { + // $query->whereHas('devices', function ($q) { + // $q->where('active', 1); + // }); + // }, + // 'assets as inactive_devices_count' => function ($query) { + // $query->whereHas('devices', function ($q) { + // $q->where('active', 0); + // }); + // } + // ]) + // ->where('id', $token['sub']) + // ->first(); + + // if (!$user) { + // return response()->json(['error' => 'User not found'], 404); + // } + + // $bearerToken = $this->adminService->getToken(); + // $apiBaseUrl = env('THINGSBOARD_URL', 'http://65.0.131.117:8080'); + // $thirtyDaysAgo = now()->subDays(30)->timestamp * 1000; + // $currentTime = now()->timestamp * 1000; + + + // $deviceParameters = [ + // 'Engine Health' => ['MechanicalHealth_valueInPercent', 'EngineEfficiency_valueInPercent', 'PowerLoss_value'], + // 'Bearing' => ['MBearing_valueInPercent', 'MElectromag_valueInPercent', 'MStressStability_valueInPercent'], + // 'Mechanical Health' => ['BearingGlobal_valueInPercent', 'GlobalMixed_valueInPercent', 'GlobalKurto_valueInPercent', '2KMixed_valueInPercent', '4KMixed_valueInPercent', '8KMixed_valueInPercent'], + // 'Regularity/Deviation' => ['RegularityDeviation_valueInPercent', 'BearingStatus_valueInPercent', 'BladeStatusGas_valueInPercent', 'CombustionKit_valueInPercent', 'TurbineCoupling_valueInPercent'], + // 'Bearing Status' => ['BearingStatus_valueInPercent', 'RegularityDeviation_valueInPercent', 'BladeStatusGas_valueInPercent', 'CombustionKit_valueInPercent', 'TurbineCoupling_valueInPercent'], + // 'Shaft/Blades Health' => ['BladeStatusGas_valueInPercent', 'RegularityDeviation_valueInPercent', 'BearingStatus_valueInPercent', 'CombustionKit_valueInPercent', 'TurbineCoupling_valueInPercent'], + // 'Combustion Kit' => ['CombustionKit_valueInPercent', 'RegularityDeviation_valueInPercent', 'BearingStatus_valueInPercent', 'BladeStatusGas_valueInPercent', 'TurbineCoupling_valueInPercent'], + // 'Coupling/Alignment' => ['TurbineCoupling_valueInPercent', 'RegularityDeviation_valueInPercent', 'BearingStatus_valueInPercent', 'BladeStatusGas_valueInPercent', 'CombustionKit_valueInPercent'], + // 'Electromagnetic Stress' => ['MElectromag_valueInPercent', 'MStressStability_valueInPercent', 'MBearing_valueInPercent'], + // 'Stability' => ['MStressStability_valueInPercent', 'MElectromag_valueInPercent', 'MBearing_valueInPercent'], + // 'Global (Unbalance/Alignment/Looseness)' => ['GlobalMixed_valueInPercent', 'BearingGlobal_valueInPercent', 'GlobalKurto_valueInPercent', '2KMixed_valueInPercent', '4KMixed_valueInPercent', '8KMixed_valueInPercent'], + // 'Shock Index' => ['GlobalKurto_valueInPercent', 'BearingGlobal_valueInPercent', 'GlobalMixed_valueInPercent', '2KMixed_valueInPercent', '4KMixed_valueInPercent', '8KMixed_valueInPercent'], + // 'Shaft/Clearance' => ['2KMixed_valueInPercent', 'BearingGlobal_valueInPercent', 'GlobalMixed_valueInPercent', 'GlobalKurto_valueInPercent', '4KMixed_valueInPercent', '8KMixed_valueInPercent'], + // 'Bearings' => ['4KMixed_valueInPercent', 'BearingGlobal_valueInPercent', 'GlobalMixed_valueInPercent', 'GlobalKurto_valueInPercent', '2KMixed_valueInPercent', '8KMixed_valueInPercent'], + // 'Friction' => ['8KMixed_valueInPercent', 'BearingGlobal_valueInPercent', 'GlobalMixed_valueInPercent', 'GlobalKurto_valueInPercent', '2KMixed_valueInPercent', '4KMixed_valueInPercent'], + // ]; + + // foreach ($user->assets as $asset) { + // $asset->celebration_message = null; + // $asset->celebration_icon = false; // Default to false + // $healthyDevices = []; + + // foreach ($asset->devices as $device) { + // $device->celebration_message = null; + // $device->celebration_icon = false; // Default to false + + // $telemetryResponse = Http::withHeaders([ + // 'accept' => 'application/json', + // 'Authorization' => 'Bearer ' . $bearerToken, + // ])->get("$apiBaseUrl/api/plugins/telemetry/DEVICE/{$device->id}/values/timeseries", [ + // 'startTs' => $thirtyDaysAgo, + // 'endTs' => $currentTime, + // 'useStrictDataTypes' => 'false' + // ]); + + // if (!$telemetryResponse->successful()) { + // Log::error("Failed to fetch telemetry for Device ID: {$device->id}, Error: " . $telemetryResponse->body()); + // continue; + // } + + // $telemetryData = $telemetryResponse->json(); + // $deviceType = trim($device->type) ?? 'Unknown'; + // $parameters = $deviceParameters[$deviceType] ?? []; + + // $averages = []; + // foreach ($parameters as $param) { + // $averages[$param] = collect($telemetryData[$param] ?? []) + // ->pluck('value')->map(fn($v) => (float)$v)->avg(); + // } + + // if (collect($averages)->filter(fn($avg) => $avg > 70)->isNotEmpty()) { + // $device->celebration_icon = true; // Set to true + // $device->celebration_message = "Your device '{$device->name}' has maintained good health for the past 30 days."; + // $healthyDevices[] = $device->name; + // } + // } + + // if (!empty($healthyDevices)) { + // $asset->celebration_icon = true; // Set to true + // $asset->celebration_message = "Your asset '{$asset->name}' has maintained good health for the past 30 days, along with the following devices: " . implode(", ", $healthyDevices) . "."; + // } + // } + + // return response()->json($user); + // } catch (Exception $e) { + // Log::error('Error fetching telemetry data: ' . $e->getMessage()); + // return response()->json(['error' => 'Failed to fetch data'], 500); + // } + // } public function index() { @@ -177,13 +276,13 @@ class UserAssetLinkController extends Controller $bearerToken = $this->adminService->getToken(); $apiBaseUrl = env('THINGSBOARD_URL', 'http://65.0.131.117:8080'); - $thirtyDaysAgo = now()->subDays(30)->timestamp * 1000; - $currentTime = now()->timestamp * 1000; + $currentDate = now(); + $currentMonth = $currentDate->month; + $currentYear = $currentDate->year; // $deviceParameters = [ // 'Engine Health' => ['MechanicalHealth_valueInPercent', 'EngineEfficiency_valueInPercent', 'PowerLoss_value'], - // 'Bearing' => ['MBearing_valueInPercent', 'MElectromag_valueInPercent', 'MStressStability_valueInPercent'], - // 'Mechanical Health' => ['BearingGlobal_valueInPercent', 'GlobalMixed_valueInPercent', 'GlobalKurto_valueInPercent', '2KMixed_valueInPercent', '4KMixed_valueInPercent', '8KMixed_valueInPercent'], + // // Add more device types and their parameters as needed // ]; $deviceParameters = [ 'Engine Health' => ['MechanicalHealth_valueInPercent', 'EngineEfficiency_valueInPercent', 'PowerLoss_value'], @@ -203,49 +302,71 @@ class UserAssetLinkController extends Controller 'Friction' => ['8KMixed_valueInPercent', 'BearingGlobal_valueInPercent', 'GlobalMixed_valueInPercent', 'GlobalKurto_valueInPercent', '2KMixed_valueInPercent', '4KMixed_valueInPercent'], ]; + foreach ($user->assets as $asset) { $asset->celebration_message = null; - $asset->celebration_icon = false; // Default to false + $asset->celebration_icon = false; $healthyDevices = []; foreach ($asset->devices as $device) { + $device->celebration_icon = false; $device->celebration_message = null; - $device->celebration_icon = false; // Default to false - $telemetryResponse = Http::withHeaders([ - 'accept' => 'application/json', - 'Authorization' => 'Bearer ' . $bearerToken, - ])->get("$apiBaseUrl/api/plugins/telemetry/DEVICE/{$device->id}/values/timeseries", [ - 'startTs' => $thirtyDaysAgo, - 'endTs' => $currentTime, - 'useStrictDataTypes' => 'false' - ]); - - if (!$telemetryResponse->successful()) { - Log::error("Failed to fetch telemetry for Device ID: {$device->id}, Error: " . $telemetryResponse->body()); - continue; - } - - $telemetryData = $telemetryResponse->json(); $deviceType = trim($device->type) ?? 'Unknown'; $parameters = $deviceParameters[$deviceType] ?? []; - $averages = []; + $allParametersHealthy = true; + foreach ($parameters as $param) { - $averages[$param] = collect($telemetryData[$param] ?? []) - ->pluck('value')->map(fn($v) => (float)$v)->avg(); + $allDaysHealthy = true; + + // Loop through each day of the current month + $daysInMonth = now()->daysInMonth; + + for ($day = 1; $day <= $daysInMonth; $day++) { + $startOfDay = Carbon::create($currentYear, $currentMonth, $day)->startOfDay(); + $endOfDay = Carbon::create($currentYear, $currentMonth, $day)->endOfDay(); + + $dailyResponse = Http::withHeaders([ + 'accept' => 'application/json', + 'Authorization' => 'Bearer ' . $bearerToken, + ])->get("$apiBaseUrl/api/plugins/telemetry/DEVICE/{$device->id}/values/timeseries", [ + 'startTs' => $startOfDay->timestamp * 1000, + 'endTs' => $endOfDay->timestamp * 1000, + 'useStrictDataTypes' => 'false' + ]); + + if (!$dailyResponse->successful()) { + Log::error("Failed to fetch daily telemetry for Device ID: {$device->id}, Day: $day, Error: " . $dailyResponse->body()); + $allDaysHealthy = false; + break; + } + + $dailyData = $dailyResponse->json(); + $dailyAvg = collect($dailyData[$param] ?? [])->pluck('value')->map(fn($v) => (float)$v)->avg(); + + if ($dailyAvg <= 70 || is_null($dailyAvg)) { + $allDaysHealthy = false; + break; + } + } + + if (!$allDaysHealthy) { + $allParametersHealthy = false; + break; + } } - if (collect($averages)->filter(fn($avg) => $avg > 70)->isNotEmpty()) { - $device->celebration_icon = true; // Set to true - $device->celebration_message = "Your device '{$device->name}' has maintained good health for the past 30 days."; + if ($allParametersHealthy && !empty($parameters)) { + $device->celebration_icon = true; + $device->celebration_message = "Your device '{$device->name}' maintained > 70 average for every parameter on all days of this month."; $healthyDevices[] = $device->name; } } if (!empty($healthyDevices)) { - $asset->celebration_icon = true; // Set to true - $asset->celebration_message = "Your asset '{$asset->name}' has maintained good health for the past 30 days, along with the following devices: " . implode(", ", $healthyDevices) . "."; + $asset->celebration_icon = true; + $asset->celebration_message = "Your asset '{$asset->name}' has healthy devices this month: " . implode(', ', $healthyDevices) . "."; } } -- 2.34.1