Merge pull request 'sneha' (#50) from sneha into main
Reviewed-on: Nikhil.Kadam/vib360#50
This commit is contained in:
@@ -23,83 +23,237 @@ class CustomerDeviceInfoController extends Controller
|
||||
|
||||
|
||||
|
||||
// public function customerDeviceInfo(Request $request)
|
||||
// {
|
||||
// try {
|
||||
// $tokenPayload = getTokenFromHeader($request);
|
||||
|
||||
// if (isset($tokenPayload['error'])) {
|
||||
// return response()->json($tokenPayload, 401);
|
||||
// }
|
||||
|
||||
// $userId = $tokenPayload['sub'];
|
||||
|
||||
// // Get user with assets and devices
|
||||
// $user = User::with(['assets' => function($query) {
|
||||
// $query->with(['devices:id,name,asset_id']);
|
||||
// }])
|
||||
// ->where('id', $userId)
|
||||
// ->first();
|
||||
|
||||
// if (!$user) {
|
||||
// return response()->json(['error' => 'User not found'], 404);
|
||||
// }
|
||||
|
||||
// try {
|
||||
// // Get devices data from ThingsBoard service
|
||||
// $devicesArray = $this->customerInfoService->getThingsBoardDevices($user->customer_id);
|
||||
|
||||
// if (!is_array($devicesArray)) {
|
||||
// throw new \Exception("Invalid devices data received from service");
|
||||
// }
|
||||
|
||||
// $thingsBoardDevices = collect($devicesArray);
|
||||
|
||||
// // Process devices
|
||||
// $deviceDetails = $user->assets->flatMap(function ($asset) use ($thingsBoardDevices) {
|
||||
// return $thingsBoardDevices->whereIn('id.id', $asset->devices->pluck('id')->toArray())
|
||||
// ->map(function ($tbDevice) {
|
||||
// return [
|
||||
// 'device_id' => $tbDevice['id']['id'],
|
||||
// 'active' => $tbDevice['active'] ?? false
|
||||
// ];
|
||||
// });
|
||||
// });
|
||||
|
||||
// // Calculate counts
|
||||
// $good = $deviceDetails->where('active', true)->count();
|
||||
// $moderate = $deviceDetails->where('active', false)->count();
|
||||
// $total_count = $good + $moderate;
|
||||
|
||||
// // Successful response
|
||||
// return response()->json([
|
||||
// 'good' => $good,
|
||||
// 'moderate' => $moderate,
|
||||
// 'total_count' => $total_count
|
||||
// ], 200);
|
||||
|
||||
// } catch (\Exception $serviceException) {
|
||||
// Log::error("ThingsBoard service error: " . $serviceException->getMessage());
|
||||
// return response()->json([
|
||||
// 'error' => 'Failed to fetch device information',
|
||||
// 'details' => $serviceException->getMessage()
|
||||
// ], 503);
|
||||
// }
|
||||
|
||||
// } catch (\Exception $e) {
|
||||
// Log::error("Customer device info error: " . $e->getMessage());
|
||||
// return response()->json([
|
||||
// 'error' => 'An unexpected error occurred',
|
||||
// 'details' => $e->getMessage()
|
||||
// ], 500);
|
||||
// }
|
||||
|
||||
// }
|
||||
|
||||
|
||||
|
||||
// public function customerDeviceInfo(Request $request)
|
||||
// {
|
||||
// try {
|
||||
|
||||
|
||||
// $token = readHeaderToken();
|
||||
|
||||
// if (!$token) {
|
||||
// return response()->json([
|
||||
// 'success' => false,
|
||||
// 'error' => 'Authorization token required'
|
||||
// ], 401);
|
||||
// }
|
||||
|
||||
|
||||
// $user = User::with(['assets.devices:id,name,asset_id'])
|
||||
// ->find($token['sub']);
|
||||
|
||||
// if (!$user) {
|
||||
// return response()->json([
|
||||
// 'error' => 'user_not_found',
|
||||
// 'message' => 'User not found'
|
||||
// ], 404);
|
||||
// }
|
||||
|
||||
// $devicesArray = $this->customerInfoService->getThingsBoardDevices($user->customer_id);
|
||||
|
||||
// if (isset($devicesArray['error'])) {
|
||||
// throw new \Exception($devicesArray['message'] ?? 'Failed to fetch devices');
|
||||
// }
|
||||
|
||||
// if (!is_array($devicesArray)) {
|
||||
// throw new \Exception("Invalid devices data format received from service");
|
||||
// }
|
||||
|
||||
|
||||
// $userDeviceIds = $user->assets->flatMap->devices->pluck('id')->toArray();
|
||||
|
||||
// $activeCount = collect($devicesArray)
|
||||
// ->whereIn('id.id', $userDeviceIds)
|
||||
// ->where('active', true)
|
||||
// ->count();
|
||||
|
||||
// $deviceIdCount = count($userDeviceIds);
|
||||
// return response()->json([
|
||||
// 'data' => [
|
||||
// 'active_count' => $activeCount,
|
||||
// 'total_count' => $deviceIdCount,
|
||||
// ],
|
||||
// 'success' => true
|
||||
// ], 200);
|
||||
|
||||
// } catch (\Exception $e) {
|
||||
// Log::error("Device info error: " . $e->getMessage());
|
||||
// $statusCode = ($e->getMessage() === "Invalid devices data format received from service") ? 503 : 500;
|
||||
|
||||
// return response()->json([
|
||||
// 'error' => 'server_error',
|
||||
// 'message' => 'An error occurred',
|
||||
// 'details' => $e->getMessage()
|
||||
// ], $statusCode);
|
||||
// }
|
||||
// }
|
||||
|
||||
public function customerDeviceInfo(Request $request)
|
||||
{
|
||||
try {
|
||||
$tokenPayload = getTokenFromHeader($request);
|
||||
|
||||
if (isset($tokenPayload['error'])) {
|
||||
return response()->json($tokenPayload, 401);
|
||||
$token = readHeaderToken($request);
|
||||
if (!$token) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'error' => 'authorization_required',
|
||||
'message' => 'Authorization token required'
|
||||
], 401);
|
||||
}
|
||||
|
||||
$userId = $tokenPayload['sub'];
|
||||
|
||||
// Get user with assets and devices
|
||||
$user = User::with(['assets' => function($query) {
|
||||
$query->with(['devices:id,name,asset_id']);
|
||||
}])
|
||||
->where('id', $userId)
|
||||
->first();
|
||||
// Get user with devices
|
||||
$user = User::with(['assets.devices:id,name,asset_id'])
|
||||
->find($token['sub']);
|
||||
|
||||
if (!$user) {
|
||||
return response()->json(['error' => 'User not found'], 404);
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'error' => 'user_not_found',
|
||||
'message' => 'User not found'
|
||||
], 404);
|
||||
}
|
||||
|
||||
try {
|
||||
// Get devices data from ThingsBoard service
|
||||
$devicesArray = $this->customerInfoService->getThingsBoardDevices($user->customer_id);
|
||||
// Get user's device IDs
|
||||
$userDeviceIds = $user->assets->flatMap->devices->pluck('id')->toArray();
|
||||
|
||||
if (!is_array($devicesArray)) {
|
||||
throw new \Exception("Invalid devices data received from service");
|
||||
}
|
||||
|
||||
$thingsBoardDevices = collect($devicesArray);
|
||||
|
||||
// Process devices
|
||||
$deviceDetails = $user->assets->flatMap(function ($asset) use ($thingsBoardDevices) {
|
||||
return $thingsBoardDevices->whereIn('id.id', $asset->devices->pluck('id')->toArray())
|
||||
->map(function ($tbDevice) {
|
||||
return [
|
||||
'device_id' => $tbDevice['id']['id'],
|
||||
'active' => $tbDevice['active'] ?? false
|
||||
];
|
||||
});
|
||||
});
|
||||
|
||||
// Calculate counts
|
||||
$good = $deviceDetails->where('active', true)->count();
|
||||
$moderate = $deviceDetails->where('active', false)->count();
|
||||
$total_count = $good + $moderate;
|
||||
|
||||
// Successful response
|
||||
if (empty($userDeviceIds)) {
|
||||
return response()->json([
|
||||
'good' => $good,
|
||||
'moderate' => $moderate,
|
||||
'total_count' => $total_count
|
||||
'data' => [
|
||||
'active_count' => 0,
|
||||
'total_count' => 0,
|
||||
|
||||
'alarms_count' => 0
|
||||
],
|
||||
'success' => true
|
||||
], 200);
|
||||
|
||||
} catch (\Exception $serviceException) {
|
||||
Log::error("ThingsBoard service error: " . $serviceException->getMessage());
|
||||
return response()->json([
|
||||
'error' => 'Failed to fetch device information',
|
||||
'details' => $serviceException->getMessage()
|
||||
], 503);
|
||||
}
|
||||
|
||||
// Get devices and alarms from service
|
||||
$serviceResponse = $this->customerInfoService->getCustomerDevicesAndAlarms(
|
||||
$user->customer_id,
|
||||
$userDeviceIds
|
||||
);
|
||||
|
||||
// Handle service errors
|
||||
if (isset($serviceResponse['error'])) {
|
||||
throw new \Exception($serviceResponse['message'] ?? 'Service request failed');
|
||||
}
|
||||
|
||||
// Process devices
|
||||
$devices = $serviceResponse['devices'] ?? [];
|
||||
$activeCount = collect($devices)
|
||||
->whereIn('id.id', $userDeviceIds)
|
||||
->where('active', true)
|
||||
->count();
|
||||
|
||||
// Process alarms
|
||||
$alarms = $serviceResponse['alarms'] ?? [];
|
||||
|
||||
$recentAlarms = $this->filterRecentAlarms($alarms);
|
||||
|
||||
return response()->json([
|
||||
'data' => [
|
||||
'active_count' => $activeCount,
|
||||
'total_count' => count($userDeviceIds),
|
||||
|
||||
'alarms_count' => count($recentAlarms),
|
||||
|
||||
],
|
||||
'success' => true
|
||||
], 200);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Customer device info error: " . $e->getMessage());
|
||||
Log::error("Device info error: " . $e->getMessage());
|
||||
return response()->json([
|
||||
'error' => 'An unexpected error occurred',
|
||||
'success' => false,
|
||||
'error' => 'server_error',
|
||||
'message' => 'An error occurred while fetching device information',
|
||||
'details' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
private function filterRecentAlarms(array $alarms): array
|
||||
{
|
||||
$twentyFourHoursAgo = (time() - 86400) * 1000;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return array_values(array_filter($alarms, function($alarm) use ($twentyFourHoursAgo) {
|
||||
return ($alarm['createdTime'] ?? 0) >= $twentyFourHoursAgo;
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -322,4 +322,4 @@ class TelemetryController extends Controller
|
||||
// return response()->json(['telemetry' => $response]);
|
||||
// }
|
||||
|
||||
}
|
||||
}
|
||||
@@ -131,13 +131,13 @@ if (!function_exists('readHeaderToken')) {
|
||||
$tokenData = Session::get('vendorToken');
|
||||
$token = JWTAuth::setToken($tokenData)->getPayload();
|
||||
|
||||
// dd([
|
||||
// 'tokenData' => $tokenData,
|
||||
// 'sub' => $token['sub'], // This should be your UUID
|
||||
// 'sub_type' => gettype($token['sub']),
|
||||
// 'sub_length' => strlen($token['sub']),
|
||||
// 'iat' => date('Y-m-d H:i:s', $token['iat']),
|
||||
// ]);
|
||||
// dd([
|
||||
// 'tokenData' => $tokenData,
|
||||
// 'sub' => $token['sub'], // This should be your UUID
|
||||
// 'sub_type' => gettype($token['sub']),
|
||||
// 'sub_length' => strlen($token['sub']),
|
||||
// 'iat' => date('Y-m-d H:i:s', $token['iat']),
|
||||
// ]);
|
||||
//convert iat to readable format
|
||||
$iat = date('Y-m-d H:i:s', $token['iat']);
|
||||
|
||||
@@ -369,4 +369,4 @@ if (!function_exists('getTokenFromHeader')) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,39 +18,45 @@ class CustomerInfoService
|
||||
$this->adminService = $adminService;
|
||||
}
|
||||
|
||||
public function getThingsBoardDevices($customerId)
|
||||
{
|
||||
try {
|
||||
$token = $this->adminService->getToken();
|
||||
// public function getThingsBoardDevices($customerId)
|
||||
// {
|
||||
// try {
|
||||
// $token = $this->adminService->getToken();
|
||||
|
||||
if (!$token) {
|
||||
Log::error("Failed to authenticate with ThingsBoard.");
|
||||
return [];
|
||||
}
|
||||
// if (!$token) {
|
||||
// Log::error("Failed to authenticate with ThingsBoard.");
|
||||
// return response()->json([
|
||||
// 'error' => 'thingsboard_auth_failed',
|
||||
// 'message' => 'Failed to authenticate with ThingsBoard'
|
||||
// ], 401);
|
||||
// }
|
||||
|
||||
// Sending the request to ThingsBoard API
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'Accept' => 'application/json',
|
||||
])->get("http://65.0.131.117:8080/api/customer/{$customerId}/deviceInfos?pageSize=100&page=0");
|
||||
// $response = Http::withHeaders([
|
||||
// 'Authorization' => "Bearer $token",
|
||||
// 'Accept' => 'application/json',
|
||||
// ])->get("http://65.0.131.117:8080/api/customer/{$customerId}/deviceInfos?pageSize=100&page=0");
|
||||
|
||||
// Check if the response is successful
|
||||
if (!$response->successful()) {
|
||||
Log::error("Failed to fetch ThingsBoard devices: " . $response->body());
|
||||
return [];
|
||||
}
|
||||
// if (!$response->successful()) {
|
||||
// Log::error("Failed to fetch ThingsBoard devices: " . $response->body());
|
||||
// return response()->json([
|
||||
// 'error' => 'thingsboard_fetch_failed',
|
||||
// 'message' => 'Failed to fetch devices from ThingsBoard',
|
||||
// 'details' => $response->body()
|
||||
// ], $response->status());
|
||||
// }
|
||||
|
||||
// Convert the JSON response to an array by calling json()
|
||||
$data = $response->json(); // This will convert the response into an array
|
||||
|
||||
// Return only the 'data' key from the response or an empty array if it's not set
|
||||
return $data['data'] ?? [];
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Error fetching ThingsBoard devices: " . $e->getMessage());
|
||||
return [];
|
||||
}
|
||||
}
|
||||
// $data = $response->json();
|
||||
// return $data['data'] ?? [];
|
||||
|
||||
// } catch (\Exception $e) {
|
||||
// Log::error("Error fetching ThingsBoard devices: " . $e->getMessage());
|
||||
// return response()->json([
|
||||
// 'error' => 'thingsboard_error',
|
||||
// 'message' => 'Error fetching devices from ThingsBoard',
|
||||
// 'details' => $e->getMessage()
|
||||
// ], 500);
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
|
||||
@@ -231,4 +237,122 @@ class CustomerInfoService
|
||||
|
||||
return $telemetry;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function getCustomerDevicesAndAlarms($customerId)
|
||||
{
|
||||
$result = [
|
||||
'devices' => [],
|
||||
'alarms' => [],
|
||||
'errors' => []
|
||||
];
|
||||
|
||||
try {
|
||||
// Step 1: Get devices
|
||||
$devicesResponse = $this->getThingsBoardDevices($customerId);
|
||||
|
||||
if (isset($devicesResponse['error'])) {
|
||||
$result['errors']['devices'] = $devicesResponse;
|
||||
} else {
|
||||
$result['devices'] = $devicesResponse;
|
||||
|
||||
// Step 2: Get alarms if devices were fetched successfully
|
||||
$deviceIds = array_column($devicesResponse, 'id.id');
|
||||
if (!empty($deviceIds)) {
|
||||
$alarmsResponse = $this->getDeviceAlarms($deviceIds);
|
||||
|
||||
if (isset($alarmsResponse['error'])) {
|
||||
$result['errors']['alarms'] = $alarmsResponse;
|
||||
} else {
|
||||
$result['alarms'] = $alarmsResponse['data'] ?? [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::error("ThingsBoard service error: " . $e->getMessage());
|
||||
return [
|
||||
'error' => 'service_error',
|
||||
'message' => 'Failed to complete ThingsBoard operation',
|
||||
'details' => $e->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get devices for a customer
|
||||
*/
|
||||
private function getThingsBoardDevices($customerId)
|
||||
{
|
||||
try {
|
||||
$token = $this->adminService->getToken();
|
||||
if (!$token) {
|
||||
throw new \Exception("Failed to authenticate with ThingsBoard");
|
||||
}
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'Accept' => 'application/json',
|
||||
])->get("http://65.0.131.117:8080/api/customer/{$customerId}/deviceInfos?pageSize=100&page=0");
|
||||
|
||||
if (!$response->successful()) {
|
||||
throw new \Exception("Failed to fetch devices: " . $response->body());
|
||||
}
|
||||
|
||||
$data = $response->json();
|
||||
return $data['data'] ?? [];
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Device fetch error: " . $e->getMessage());
|
||||
return [
|
||||
'error' => 'device_fetch_failed',
|
||||
'message' => 'Failed to fetch devices',
|
||||
'details' => $e->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get alarms for specific devices (last 24 hours)
|
||||
*/
|
||||
private function getDeviceAlarms(array $deviceIds)
|
||||
{
|
||||
try {
|
||||
$token = $this->adminService->getToken();
|
||||
if (!$token) {
|
||||
throw new \Exception("Failed to authenticate with ThingsBoard");
|
||||
}
|
||||
|
||||
$startTime = (time() - 86400) * 1000; // 24 hours ago in milliseconds
|
||||
$deviceIdsParam = implode(',', $deviceIds);
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'Accept' => 'application/json',
|
||||
])->get("http://65.0.131.117:8080/api/v2/alarms", [
|
||||
'pageSize' => 100,
|
||||
'page' => 0,
|
||||
'startTime' => $startTime,
|
||||
'deviceIds' => $deviceIdsParam
|
||||
]);
|
||||
|
||||
if (!$response->successful()) {
|
||||
throw new \Exception("Failed to fetch alarms: " . $response->body());
|
||||
}
|
||||
|
||||
return $response->json();
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Alarm fetch error: " . $e->getMessage());
|
||||
return [
|
||||
'error' => 'alarm_fetch_failed',
|
||||
'message' => 'Failed to fetch alarms',
|
||||
'details' => $e->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -19,13 +19,14 @@ Route::get('/customerapi', function () {
|
||||
Route::post('user-login', [AuthController::class, 'login']);
|
||||
|
||||
Route::post('/telemetry-data-device-diagnostic',[TelemetryController::class,'telemePtryDataDeviceDiagnostic']);
|
||||
Route::get('/customer-device-info',[CustomerDeviceInfoController::class,'customerDeviceInfo']);
|
||||
|
||||
|
||||
|
||||
// Route::post('/user-login', [AuthController::class, 'login']);
|
||||
Route::middleware(['customerApiBasicAuth'])->group(function () {
|
||||
Route::get('/user-assets', [UserAssetLinkController::class, 'index']);
|
||||
Route::get('/customer-device-info',[CustomerDeviceInfoController::class,'customerDeviceInfo']);
|
||||
|
||||
Route::post('/telemetry-data-asset',[TelemetryController::class,'telemetryDataAsset']);
|
||||
Route::post('/telemetry-data-device',[TelemetryController::class,'telemetryDataDevice']);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user