adminService = $adminService; } public function index() { try { $token = readHeaderToken(); // Fetch user with assets and device counts $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'); foreach ($user->assets as $asset) { foreach ($asset->devices as $device) { $device->health_status = null; // Fetch device details from API using customer_id and device_id $deviceResponse = Http::withHeaders([ 'accept' => 'application/json', 'Authorization' => 'Bearer ' . $bearerToken, ])->get("$apiBaseUrl/api/customer/{$device->customer_id}/deviceInfos", [ 'pageSize' => 100, // Fetch more devices in one request 'page' => 0 ]); if (!$deviceResponse->successful()) { Log::error("Failed to fetch device info for Customer ID: {$device->customer_id}, Error: " . $deviceResponse->body()); $device->online = null; // Set to false if API call fails continue; } $deviceData = $deviceResponse->json(); $matchingDevice = collect($deviceData['data'] ?? []) ->firstWhere('id.id', $device->id); // Explicitly set online status for all devices $device->online = $matchingDevice['active'] ?? null; // Fetch telemetry data for the device $telemetryResponse = Http::withHeaders([ 'accept' => 'application/json', 'Authorization' => 'Bearer ' . $bearerToken, ])->get("$apiBaseUrl/api/plugins/telemetry/DEVICE/{$device->id}/values/timeseries", [ 'useStrictDataTypes' => 'false' ]); if (!$telemetryResponse->successful()) { Log::error("Failed to fetch telemetry for Device ID: {$device->id}, Error: " . $telemetryResponse->body()); $device->health_status = null; continue; } $telemetryData = $telemetryResponse->json(); $device->health_status = !empty($telemetryData['MechanicalHealth_valueInPercent']) ? (float) $telemetryData['MechanicalHealth_valueInPercent'][0]['value'] : null; } } return response()->json($user); } catch (Exception $e) { Log::error('Error fetching telemetry data: ' . $e->getMessage()); return response()->json(['error' => 'Failed to fetch data'], 500); } } }