sneha #67

Merged
Sneha.Yadav merged 2 commits from sneha into main 2025-04-07 12:18:14 +00:00
6 changed files with 463 additions and 127 deletions

View File

@@ -0,0 +1,199 @@
<?php
namespace App\Http\Controllers\APIS\AdminApi;
use App\Http\Controllers\Controller;
use App\Models\Asset;
use App\Models\Customer;
use App\Models\Device;
use App\Services\AdminService;
use Illuminate\Container\Attributes\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class AdminDashboardController extends Controller
{
protected $adminService;
public function __construct(AdminService $adminService)
{
$this->adminService = $adminService;
}
// public function adminDashboard()
// {
// try {
// $totalCustomers = Customer::count();
// $totalAssets = Asset::count();
// $totalDevices = Device::count();
// $customer = Customer::
// $token = $this->adminService->getToken();
// $activeDevices = 0;
// $inactiveDevices = 0;
// $activeAlarmsCount = 0;
// $warningAlarmsCount = 0;
// $criticalAlarmsCount = 0;
// if ($token) {
// $baseUrl = env('THINGSBOARD_URL');
// $deviceIds = Device::pluck('id')->toArray();
// foreach ($deviceIds as $deviceId) {
// $response = Http::withHeaders([
// 'Authorization' => "Bearer $token",
// 'Accept' => 'application/json',
// ])->get("$baseUrl/api/device/info/{$deviceId}");
// if ($response->successful()) {
// $deviceInfo = $response->json();
// $deviceInfo['active'] ? $activeDevices++ : $inactiveDevices++;
// } else {
// $inactiveDevices++;
// }
// }
// $alarmsResponse = Http::withHeaders([
// 'Authorization' => "Bearer $token",
// 'Accept' => 'application/json',
// ])->get("$baseUrl/api/v2/alarms", [
// 'pageSize' => 1000, // Adjust based on expected alarm count
// 'page' => 0,
// 'status' => 'ACTIVE'
// ]);
// if ($alarmsResponse->successful()) {
// $alarmsData = $alarmsResponse->json();
// $activeAlarmsCount = $alarmsData['totalElements'] ?? 0;
// if (isset($alarmsData['data'])) {
// foreach ($alarmsData['data'] as $alarm) {
// $severity = strtoupper($alarm['severity'] ?? '');
// if ($severity === 'CRITICAL') {
// $criticalAlarmsCount++;
// } elseif ($severity === 'WARNING') {
// $warningAlarmsCount++;
// }
// }
// }
// }
// }
// return response()->json([
// 'success' => true,
// 'total_customers' => $totalCustomers,
// 'total_assets' => $totalAssets,
// 'devices' => [
// 'total_devices' => $totalDevices,
// 'active_devices' => $activeDevices,
// 'inactive_devices' => $inactiveDevices,
// ],
// 'alarms' => [
// 'total_active' => $activeAlarmsCount,
// 'warning' => $warningAlarmsCount,
// 'critical' => $criticalAlarmsCount,
// 'other' => $activeAlarmsCount - ($warningAlarmsCount + $criticalAlarmsCount)
// ]
// ]);
// } catch (\Exception $e) {
// return response()->json([
// 'success' => false,
// 'message' => 'Failed to fetch dashboard statistics',
// 'error' => $e->getMessage()
// ], 500);
// }
// }
public function adminDashboard()
{
try {
$totalCustomers = Customer::count();
$totalAssets = Asset::count();
$totalDevices = Device::count();
// Fetch all customers with specific fields
$customers = Customer::select('name', 'country', 'state', 'city')->get();
$token = $this->adminService->getToken();
$activeDevices = 0;
$inactiveDevices = 0;
$activeAlarmsCount = 0;
$warningAlarmsCount = 0;
$criticalAlarmsCount = 0;
if ($token) {
$baseUrl = env('THINGSBOARD_URL');
$deviceIds = Device::pluck('id')->toArray();
foreach ($deviceIds as $deviceId) {
$response = Http::withHeaders([
'Authorization' => "Bearer $token",
'Accept' => 'application/json',
])->get("$baseUrl/api/device/info/{$deviceId}");
if ($response->successful()) {
$deviceInfo = $response->json();
$deviceInfo['active'] ? $activeDevices++ : $inactiveDevices++;
} else {
$inactiveDevices++;
}
}
$alarmsResponse = Http::withHeaders([
'Authorization' => "Bearer $token",
'Accept' => 'application/json',
])->get("$baseUrl/api/v2/alarms", [
'pageSize' => 1000,
'page' => 0,
'status' => 'ACTIVE'
]);
if ($alarmsResponse->successful()) {
$alarmsData = $alarmsResponse->json();
$activeAlarmsCount = $alarmsData['totalElements'] ?? 0;
if (isset($alarmsData['data'])) {
foreach ($alarmsData['data'] as $alarm) {
$severity = strtoupper($alarm['severity'] ?? '');
if ($severity === 'CRITICAL') {
$criticalAlarmsCount++;
} elseif ($severity === 'WARNING') {
$warningAlarmsCount++;
}
}
}
}
}
return response()->json([
'success' => true,
'total_customers' => $totalCustomers,
'total_assets' => $totalAssets,
'devices' => [
'total_devices' => $totalDevices,
'active_devices' => $activeDevices,
'inactive_devices' => $inactiveDevices,
],
'alarms' => [
'total_active' => $activeAlarmsCount,
'warning' => $warningAlarmsCount,
'critical' => $criticalAlarmsCount,
'other' => $activeAlarmsCount - ($warningAlarmsCount + $criticalAlarmsCount)
],
'customers' => $customers,
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Failed to fetch dashboard statistics',
'error' => $e->getMessage()
], 500);
}
}
}

View File

@@ -92,7 +92,7 @@ class AlarmController extends Controller
try {
// Get alarmId from request
$alarmId = $request->input('alarmId');
dd($alarmId);
// Validate alarmId
if (!$alarmId) {

View File

@@ -10,6 +10,7 @@ use App\Models\TimeseriesAlertMessage;
use App\Models\TimeseriesKeyMaster;
use App\Models\User;
use App\Models\UserAssetLink;
use App\Services\AdminService;
use App\Services\AlarmService;
use App\Services\CustomerInfoService;
use Illuminate\Container\Attributes\DB;
@@ -21,20 +22,181 @@ use Illuminate\Support\Facades\Validator;
class TelemetryController extends Controller
{
protected $customerInfoService, $alarmService;
protected $customerInfoService, $alarmService, $adminService;
// public function __construct(CustomerInfoService $customerInfoService)
// {
// $this->customerInfoService = $customerInfoService;
// }
public function __construct(CustomerInfoService $customerInfoService, AlarmService $alarmService)
public function __construct(CustomerInfoService $customerInfoService, AlarmService $alarmService, AdminService $adminService)
{
$this->customerInfoService = $customerInfoService;
$this->alarmService = $alarmService; // 💡 Add AlarmService
$this->alarmService = $alarmService;
$this->adminService = $adminService;
}
// public function telemetryDataAsset(Request $request)
// {
// try {
// $token = readHeaderToken();
// $userId = $token['sub'];
// $customerId = User::where('id', $userId)->value('customer_id');
// // Validate request
// $validator = Validator::make($request->all(), [
// 'asset_id' => 'required|string',
// ]);
// if ($validator->fails()) {
// return jsonResponseWithErrorMessage($validator->errors()->first(), 400);
// }
// $assetId = $request->input('asset_id');
// // Verify asset ownership
// $assetLinkExists = UserAssetLink::where('user_id', $userId)
// ->where('asset_id', $assetId)
// ->exists();
// if (!$assetLinkExists) {
// return response()->json([
// 'error' => 'You are not authorized to access this asset',
// 'code' => 'UNAUTHORIZED_ACCESS'
// ], 403);
// }
// // Set timestamps in milliseconds for database query
// $endTsMs = now()->timestamp * 1000; // Current time in milliseconds
// $startTsMs = $endTsMs - (30 * 60 * 1000); // 30 minutes ago in milliseconds
// // Get devices with their telemetry keys
// $devices = Device::with([
// 'deviceProfile' => function($query) {
// $query->select(['id', 'name']); // Only select needed fields
// },
// 'timeseriesKeys' => function ($query) {
// $query->where('display_on_dashboard', true)
// ->orWhere('display_on_popup', true)
// ->select(['id', 'device_profile_xid', 'key_name', 'display_name', 'display_on_dashboard', 'display_on_popup']);
// }
// ])->where('asset_id', $assetId)
// ->where('customer_id', $customerId)
// ->get();
// if ($devices->isEmpty()) {
// return response()->json([
// 'error' => 'No devices found for the specified asset',
// 'code' => 'DEVICES_NOT_FOUND'
// ], 404);
// }
// // Process telemetry data for each device
// $response = $devices->map(function ($device) use ($startTsMs, $endTsMs) {
// $keysData = $device->timeseriesKeys;
// $keyNames = $keysData->pluck('key_name')->toArray();
// // Get telemetry data for start and end times
// $startTelemetry = $this->customerInfoService->getTelemetryData($device, $keyNames, $startTsMs, $startTsMs);
// $endTelemetry = $this->customerInfoService->getTelemetryData($device, $keyNames, $endTsMs, $endTsMs);
// $alarmMap = $this->getDeviceAlarmsForTelemetry($device->id);
// $alertMessages = TimeseriesAlertMessage::whereIn('timeseries_key_master_xid', $keysData->pluck('id'))
// ->orderBy('min_value', 'asc')
// ->get()
// ->groupBy('timeseries_key_master_xid');
// $telemetry = $keysData->map(function ($keyData) use ($startTelemetry, $endTelemetry, $alarmMap, $alertMessages) {
// $startData = collect($startTelemetry[$keyData->key_name] ?? [])->last();
// $endData = collect($endTelemetry[$keyData->key_name] ?? [])->last();
// $startValue = floatval($startData['value'] ?? 0);
// $endValue = floatval($endData['value'] ?? 0);
// // Determine trend
// $trend = null;
// if ($startValue > 0) {
// if ($endValue > $startValue) {
// $trend = 'upward';
// } elseif ($endValue < $startValue) {
// $trend = 'downward';
// } else {
// $trend = 'stable';
// }
// }
// // Format timestamp
// $currentData = $endData ?? $startData ?? ['ts' => now()->timestamp * 1000];
// $timestamp = is_float($currentData['ts']) || $currentData['ts'] > 9999999999
// ? intval($currentData['ts'] / 1000)
// : $currentData['ts'];
// // Color code logic
// $colorCode = null;
// if ($endValue == 0) {
// $colorCode = "grey";
// } elseif (isset($alertMessages[$keyData->id])) {
// foreach ($alertMessages[$keyData->id] as $alertMsg) {
// if ((is_null($alertMsg->min_value) || $endValue >= floatval($alertMsg->min_value)) &&
// (is_null($alertMsg->max_value) || $endValue <= floatval($alertMsg->max_value))) {
// $colorCode = $alertMsg->color_code;
// break;
// }
// }
// }
// return [
// 'key_name' => $keyData->key_name,
// 'display_name' => $keyData->display_name,
// 'display_on_dashboard' => $keyData->display_on_dashboard,
// 'display_on_popup' => $keyData->display_on_popup,
// 'timestamp' => $timestamp,
// 'value' => $endValue,
// 'start_value' => $startValue > 0 ? $startValue : null,
// 'trend' => $trend,
// 'alert' => isset($alarmMap[$keyData->key_name]),
// 'color_code' => $colorCode ?: 'green', // Default to green if no alerts match
// ];
// })->filter()->values();
// return [
// 'device_id' => (string) $device->id,
// 'device_profile_name' => (string) $device->deviceProfile->name,
// 'asset_id' => (string) $device->asset_id,
// 'device_profile_id' => (string) $device->device_profile_id,
// 'telemetry' => $telemetry,
// ];
// });
// return response()->json([
// 'telemetry' => $response,
// 'time_range' => [
// 'startTs' => intval($startTsMs / 1000),
// 'endTs' => intval($endTsMs / 1000),
// ]
// ]);
// } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
// return response()->json([
// 'error' => 'User not found',
// 'code' => 'USER_NOT_FOUND'
// ], 404);
// } catch (\Exception $e) {
// Log::error('Telemetry data fetch failed: ' . $e->getMessage(), [
// 'exception' => $e,
// 'user_id' => $userId ?? null,
// 'asset_id' => $assetId ?? null
// ]);
// return response()->json([
// 'error' => 'Failed to fetch telemetry data',
// 'code' => 'SERVER_ERROR'
// ], 500);
// }
// }
public function telemetryDataAsset(Request $request)
{
try {
@@ -66,12 +228,12 @@ class TelemetryController extends Controller
}
// Set timestamps in milliseconds for database query
$endTsMs = now()->timestamp * 1000; // Current time in milliseconds
$startTsMs = $endTsMs - (30 * 60 * 1000); // 30 minutes ago in milliseconds
$endTsMs = now()->timestamp * 1000;
$startTsMs = $endTsMs - (30 * 60 * 1000);
// Get devices with their telemetry keys
$devices = Device::with([
'deviceProfile',
'deviceProfile:id,name',
'timeseriesKeys' => function ($query) {
$query->where('display_on_dashboard', true)
->orWhere('display_on_popup', true)
@@ -90,12 +252,36 @@ class TelemetryController extends Controller
// Process telemetry data for each device
$response = $devices->map(function ($device) use ($startTsMs, $endTsMs) {
// Check device active status directly
$deviceInfoToken = $this->adminService->getToken();
$isActive = false;
if ($deviceInfoToken) {
$baseUrl = env('THINGSBOARD_URL');
$deviceInfoResponse = Http::withHeaders([
'Authorization' => "Bearer $deviceInfoToken",
'Accept' => 'application/json',
])->get("$baseUrl/api/device/info/{$device->id}");
if ($deviceInfoResponse->successful()) {
$deviceInfo = $deviceInfoResponse->json();
$isActive = $deviceInfo['active'] ?? false;
} else {
Log::error("Failed to fetch device info for device ID: {$device->id}");
}
}
$keysData = $device->timeseriesKeys;
$keyNames = $keysData->pluck('key_name')->toArray();
// Get telemetry data for start and end times
$startTelemetry = $this->customerInfoService->getTelemetryData($device, $keyNames, $startTsMs, $startTsMs);
$endTelemetry = $this->customerInfoService->getTelemetryData($device, $keyNames, $endTsMs, $endTsMs);
// Only fetch telemetry if device is active
$startTelemetry = [];
$endTelemetry = [];
if ($isActive) {
$startTelemetry = $this->customerInfoService->getTelemetryData($device, $keyNames, $startTsMs, $startTsMs);
$endTelemetry = $this->customerInfoService->getTelemetryData($device, $keyNames, $endTsMs, $endTsMs);
}
$alarmMap = $this->getDeviceAlarmsForTelemetry($device->id);
$alertMessages = TimeseriesAlertMessage::whereIn('timeseries_key_master_xid', $keysData->pluck('id'))
@@ -103,42 +289,52 @@ class TelemetryController extends Controller
->get()
->groupBy('timeseries_key_master_xid');
$telemetry = $keysData->map(function ($keyData) use ($startTelemetry, $endTelemetry, $alarmMap, $alertMessages) {
$startData = collect($startTelemetry[$keyData->key_name] ?? [])->last();
$endData = collect($endTelemetry[$keyData->key_name] ?? [])->last();
$startValue = floatval($startData['value'] ?? 0);
$endValue = floatval($endData['value'] ?? 0);
// Determine trend
$telemetry = $keysData->map(function ($keyData) use ($startTelemetry, $endTelemetry, $alarmMap, $alertMessages, $isActive) {
$startValue = 0;
$endValue = 0;
$timestamp = now()->timestamp;
$trend = null;
if ($startValue > 0) {
if ($endValue > $startValue) {
$trend = 'upward';
} elseif ($endValue < $startValue) {
$trend = 'downward';
} else {
$trend = 'stable';
if ($isActive) {
$startData = collect($startTelemetry[$keyData->key_name] ?? [])->last();
$endData = collect($endTelemetry[$keyData->key_name] ?? [])->last();
$startValue = floatval($startData['value'] ?? 0);
$endValue = floatval($endData['value'] ?? 0);
// Determine trend only if device is active
if ($startValue > 0) {
if ($endValue > $startValue) {
$trend = 'upward';
} elseif ($endValue < $startValue) {
$trend = 'downward';
} else {
$trend = 'stable';
}
}
// Format timestamp
$currentData = $endData ?? $startData ?? ['ts' => now()->timestamp * 1000];
$timestamp = is_float($currentData['ts']) || $currentData['ts'] > 9999999999
? intval($currentData['ts'] / 1000)
: $currentData['ts'];
}
// Format timestamp
$currentData = $endData ?? $startData ?? ['ts' => now()->timestamp * 1000];
$timestamp = is_float($currentData['ts']) || $currentData['ts'] > 9999999999
? intval($currentData['ts'] / 1000)
: $currentData['ts'];
// Color code logic
$colorCode = null;
if ($endValue == 0) {
$colorCode = "grey";
} elseif (isset($alertMessages[$keyData->id])) {
foreach ($alertMessages[$keyData->id] as $alertMsg) {
if ((is_null($alertMsg->min_value) || $endValue >= floatval($alertMsg->min_value)) &&
(is_null($alertMsg->max_value) || $endValue <= floatval($alertMsg->max_value))) {
$colorCode = $alertMsg->color_code;
break;
$colorCode = 'grey';
if ($isActive) {
if ($endValue == 0) {
$colorCode = "grey";
} elseif (isset($alertMessages[$keyData->id])) {
foreach ($alertMessages[$keyData->id] as $alertMsg) {
if ((is_null($alertMsg->min_value) || $endValue >= floatval($alertMsg->min_value)) &&
(is_null($alertMsg->max_value) || $endValue <= floatval($alertMsg->max_value))) {
$colorCode = $alertMsg->color_code;
break;
}
}
} else {
$colorCode = 'green';
}
}
@@ -148,19 +344,21 @@ class TelemetryController extends Controller
'display_on_dashboard' => $keyData->display_on_dashboard,
'display_on_popup' => $keyData->display_on_popup,
'timestamp' => $timestamp,
'value' => $endValue,
'start_value' => $startValue > 0 ? $startValue : null,
'value' => $isActive ? $endValue : 0,
'start_value' => $isActive && $startValue > 0 ? $startValue : null,
'trend' => $trend,
'alert' => isset($alarmMap[$keyData->key_name]),
'color_code' => $colorCode ?: 'green', // Default to green if no alerts match
'color_code' => $colorCode,
];
})->filter()->values();
return [
'device_id' => (string) $device->id,
'device_name' => (string) $device->deviceProfile->name,
'device_profile_name' => (string) $device->deviceProfile->name,
'asset_id' => (string) $device->asset_id,
'device_profile_id' => (string) $device->device_profile_id,
'is_active' => $isActive,
'telemetry' => $telemetry,
];
});
@@ -173,18 +371,8 @@ class TelemetryController extends Controller
]
]);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
return response()->json([
'error' => 'User not found',
'code' => 'USER_NOT_FOUND'
], 404);
} catch (\Exception $e) {
Log::error('Telemetry data fetch failed: ' . $e->getMessage(), [
'exception' => $e,
'user_id' => $userId ?? null,
'asset_id' => $assetId ?? null
]);
Log::error('Telemetry data fetch failed: ' . $e->getMessage());
return response()->json([
'error' => 'Failed to fetch telemetry data',
'code' => 'SERVER_ERROR'
@@ -192,8 +380,6 @@ class TelemetryController extends Controller
}
}
private function getDeviceAlarmsForTelemetry($deviceId)
{
Log::info("Fetching alarms for device: {$deviceId}");

View File

@@ -334,75 +334,6 @@ class AdminService
throw new Exception('Failed to create user: ' . $response->body());
}
// public function createOrUpdateUser(array $data)
// {
// $token = $this->getToken();
// // First, check if the user exists in ThingsBoard by email
// $email = $data['email'];
// // ✅ Fetch ThingsBoard ID by email
// $response = Http::withHeaders([
// 'Authorization' => "Bearer $token",
// 'accept' => 'application/json'
// ])->get("{$this->baseUrl}/api/users?pageSize=1&page=0&textSearch=$email");
// $userExists = false;
// $thingsboardUserId = null;
// if ($response->successful()) {
// $users = $response->json()['data'] ?? [];
// if (!empty($users)) {
// $userExists = true;
// $thingsboardUserId = $users[0]['id']['id'];
// }
// }
// // ✅ Prepare payload
// $payload = [
// 'email' => $data['email'] ?? 'default@example.com',
// 'tenantId' => [
// 'id' => $data['tenantId'] ?? '6e9b7fde-0ca0-4d19-9d2a-fba98e3e12a0',
// 'entityType' => 'TENANT'
// ],
// 'customerId' => [
// 'id' => $data['customerId'],
// 'entityType' => 'CUSTOMER'
// ],
// 'authority' => $data['authority'] ?? 'TENANT_ADMIN',
// 'name' => $data['name'] ?? 'John Doe',
// 'phone' => $data['phone'] ?? '1234567890',
// 'additionalInfo' => [
// 'description' => $data['description'] ?? 'User description'
// ]
// ];
// if ($userExists && $thingsboardUserId) {
// // ✅ Update existing user in ThingsBoard
// $response = Http::withHeaders([
// 'Authorization' => "Bearer $token",
// 'accept' => 'application/json',
// 'Content-Type' => 'application/json',
// ])->withBody(json_encode($payload), 'application/json')
// ->post("{$this->baseUrl}/api/user/{$thingsboardUserId}");
// } else {
// // ✅ Create new user in ThingsBoard
// $response = Http::withHeaders([
// 'Authorization' => "Bearer $token",
// 'accept' => 'application/json',
// 'Content-Type' => 'application/json',
// ])->withBody(json_encode($payload), 'application/json')
// ->post("{$this->baseUrl}/api/user");
// }
// if ($response->successful()) {
// return $response->json();
// } else {
// throw new Exception('Failed to create or update user: ' . $response->body());
// }
// }
@@ -539,4 +470,21 @@ class AdminService
'message' => 'User not found in ThingsBoard by email.'
];
}
}
public function dashboardAdmin()
{
$token = $this->getToken();
$response = Http::withHeaders([
'Authorization' => "Bearer $token",
'accept' => 'application/json',
])->get("{$this->baseUrl}/api/users?pageSize=100&page=0");
if ($response->successful()) {
return $response->json();
} else {
throw new Exception('Failed to fetch users: ' . $response->body());
}
}
}

View File

@@ -389,4 +389,4 @@ class CustomerInfoService
}
}
}
}

View File

@@ -4,6 +4,7 @@
use App\Http\Controllers\APIS\AdminApi\AlarmController;
use App\Http\Controllers\AlarmControllerCommon;
use App\Http\Controllers\APIS\AdminApi\AdminDashboardController;
use App\Http\Controllers\APIS\AdminApi\CustomerController;
use App\Http\Controllers\APIS\AdminApi\UsersController;
use App\Http\Controllers\APIS\AdminApi\DeviceController;
@@ -13,12 +14,14 @@ use App\Http\Controllers\APIS\AdminApi\AssetadmintController;
use App\Http\Controllers\APIS\AdminApi\RuleChainController;
use App\Http\Controllers\APIS\AdminApi\DeviceProfileMasterController;
use App\Http\Controllers\APIS\AdminApi\LoginController;
use App\Services\AdminService;
Route::get('/adminapi', function () {
return ('Welcome to admin api routes.');
});
//******************************************************* Admin Assest API ********************************************************
Route::post('/admin-login', [LoginController::class, 'adminLogin'])->name('admin.login');
Route::get('/admin-dashboard', [AdminDashboardController::class, 'adminDashboard'])->name('admin.dashboard');
Route::post('/asset', [AssetadmintController::class, 'storeAssest'])->name('assest.create');
Route::get('/assets-list', [AssetadmintController::class, 'listAssest'])->name('assest.list');