Files
backend_vib360_laravel/app/Http/Controllers/APIS/CustomerApi/TelemetryController.php

841 lines
36 KiB
PHP
Raw Normal View History

2025-03-24 13:31:06 +05:30
<?php
namespace App\Http\Controllers\APIS\CustomerApi;
use App\Http\Controllers\Controller;
use App\Models\Asset;
2025-04-01 15:37:41 +05:30
use App\Models\Customer;
2025-03-24 13:31:06 +05:30
use App\Models\Device;
2025-04-01 19:42:42 +05:30
use App\Models\TimeseriesAlertMessage;
2025-03-25 11:34:55 +05:30
use App\Models\TimeseriesKeyMaster;
2025-04-01 15:37:41 +05:30
use App\Models\User;
2025-04-07 12:10:14 +05:30
use App\Models\UserAssetLink;
2025-04-07 17:46:56 +05:30
use App\Services\AdminService;
2025-04-01 12:14:03 +05:30
use App\Services\AlarmService;
2025-03-24 13:31:06 +05:30
use App\Services\CustomerInfoService;
2025-03-25 11:34:55 +05:30
use Illuminate\Container\Attributes\DB;
2025-03-24 13:31:06 +05:30
use Illuminate\Http\Request;
2025-03-25 11:34:55 +05:30
use Illuminate\Support\Facades\DB as FacadesDB;
2025-03-24 13:31:06 +05:30
use Illuminate\Support\Facades\Http;
2025-03-28 13:52:02 +05:30
use Illuminate\Support\Facades\Log;
2025-03-26 12:18:45 +05:30
use Illuminate\Support\Facades\Validator;
2025-03-24 13:31:06 +05:30
class TelemetryController extends Controller
{
2025-04-07 17:46:56 +05:30
protected $customerInfoService, $alarmService, $adminService;
2025-03-24 13:31:06 +05:30
2025-04-01 12:14:03 +05:30
// public function __construct(CustomerInfoService $customerInfoService)
// {
// $this->customerInfoService = $customerInfoService;
// }
2025-04-07 17:46:56 +05:30
public function __construct(CustomerInfoService $customerInfoService, AlarmService $alarmService, AdminService $adminService)
2025-03-24 13:31:06 +05:30
{
$this->customerInfoService = $customerInfoService;
2025-04-07 17:46:56 +05:30
$this->alarmService = $alarmService;
$this->adminService = $adminService;
2025-03-24 13:31:06 +05:30
}
2025-03-25 11:34:55 +05:30
2025-04-07 17:46:56 +05:30
// 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)
2025-04-07 12:10:14 +05:30
{
try {
$token = readHeaderToken();
$userId = $token['sub'];
$customerId = User::where('id', $userId)->value('customer_id');
2025-03-24 13:31:06 +05:30
2025-04-07 12:10:14 +05:30
// Validate request
$validator = Validator::make($request->all(), [
'asset_id' => 'required|string',
]);
2025-04-02 19:45:39 +05:30
2025-04-07 12:10:14 +05:30
if ($validator->fails()) {
return jsonResponseWithErrorMessage($validator->errors()->first(), 400);
}
2025-04-01 12:14:03 +05:30
2025-04-07 12:10:14 +05:30
$assetId = $request->input('asset_id');
2025-04-04 13:29:54 +05:30
2025-04-07 12:10:14 +05:30
// Verify asset ownership
$assetLinkExists = UserAssetLink::where('user_id', $userId)
->where('asset_id', $assetId)
->exists();
2025-04-04 13:29:54 +05:30
2025-04-07 12:10:14 +05:30
if (!$assetLinkExists) {
return response()->json([
'error' => 'You are not authorized to access this asset',
'code' => 'UNAUTHORIZED_ACCESS'
], 403);
2025-04-01 15:37:41 +05:30
}
2025-04-02 19:45:39 +05:30
2025-04-07 12:10:14 +05:30
// Set timestamps in milliseconds for database query
2025-04-07 17:46:56 +05:30
$endTsMs = now()->timestamp * 1000;
$startTsMs = $endTsMs - (30 * 60 * 1000);
2025-04-07 12:10:14 +05:30
// Get devices with their telemetry keys
$devices = Device::with([
2025-04-07 17:46:56 +05:30
'deviceProfile:id,name',
2025-04-07 12:10:14 +05:30
'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']);
2025-04-02 19:45:39 +05:30
}
2025-04-07 12:10:14 +05:30
])->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);
2025-04-04 13:29:54 +05:30
}
2025-04-02 19:45:39 +05:30
2025-04-07 12:10:14 +05:30
// Process telemetry data for each device
$response = $devices->map(function ($device) use ($startTsMs, $endTsMs) {
2025-04-07 17:46:56 +05:30
// 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}");
}
}
2025-04-07 12:10:14 +05:30
$keysData = $device->timeseriesKeys;
$keyNames = $keysData->pluck('key_name')->toArray();
2025-04-07 17:46:56 +05:30
// 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);
}
2025-04-07 12:10:14 +05:30
$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');
2025-04-07 17:46:56 +05:30
$telemetry = $keysData->map(function ($keyData) use ($startTelemetry, $endTelemetry, $alarmMap, $alertMessages, $isActive) {
$startValue = 0;
$endValue = 0;
$timestamp = now()->timestamp;
2025-04-07 12:10:14 +05:30
$trend = null;
2025-04-07 17:46:56 +05:30
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';
}
2025-04-07 12:10:14 +05:30
}
2025-04-07 17:46:56 +05:30
// Format timestamp
$currentData = $endData ?? $startData ?? ['ts' => now()->timestamp * 1000];
$timestamp = is_float($currentData['ts']) || $currentData['ts'] > 9999999999
? intval($currentData['ts'] / 1000)
: $currentData['ts'];
}
2025-04-07 12:10:14 +05:30
// Color code logic
2025-04-07 17:46:56 +05:30
$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;
}
2025-04-07 12:10:14 +05:30
}
2025-04-07 17:46:56 +05:30
} else {
$colorCode = 'green';
2025-04-07 12:10:14 +05:30
}
2025-03-28 13:35:40 +05:30
}
2025-04-01 16:57:19 +05:30
2025-04-07 12:10:14 +05:30
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,
2025-04-07 17:46:56 +05:30
'value' => $isActive ? $endValue : 0,
'start_value' => $isActive && $startValue > 0 ? $startValue : null,
2025-04-07 12:10:14 +05:30
'trend' => $trend,
'alert' => isset($alarmMap[$keyData->key_name]),
2025-04-07 17:46:56 +05:30
'color_code' => $colorCode,
2025-04-07 12:10:14 +05:30
];
})->filter()->values();
return [
'device_id' => (string) $device->id,
2025-04-07 17:46:56 +05:30
'device_name' => (string) $device->deviceProfile->name,
2025-04-07 12:10:14 +05:30
'device_profile_name' => (string) $device->deviceProfile->name,
'asset_id' => (string) $device->asset_id,
'device_profile_id' => (string) $device->device_profile_id,
2025-04-07 17:46:56 +05:30
'is_active' => $isActive,
2025-04-07 12:10:14 +05:30
'telemetry' => $telemetry,
];
});
return response()->json([
'telemetry' => $response,
'time_range' => [
'startTs' => intval($startTsMs / 1000),
'endTs' => intval($endTsMs / 1000),
]
]);
} catch (\Exception $e) {
2025-04-07 17:46:56 +05:30
Log::error('Telemetry data fetch failed: ' . $e->getMessage());
2025-04-07 12:10:14 +05:30
return response()->json([
'error' => 'Failed to fetch telemetry data',
'code' => 'SERVER_ERROR'
], 500);
}
}
2025-04-01 12:14:03 +05:30
private function getDeviceAlarmsForTelemetry($deviceId)
{
Log::info("Fetching alarms for device: {$deviceId}");
$pageSize = 1000;
$page = 0;
// Fetch ThingsBoard token
$token = $this->alarmService->getToken();
if (!$token) {
Log::error("Failed to fetch ThingsBoard token.");
return [];
}
Log::info("Token fetched successfully.");
$baseUrl = env('THINGSBOARD_URL');
$endTime = now()->timestamp * 1000; // Current time in ms
$startTime = now()->subHours(24)->timestamp * 1000; // 24 hours ago in ms
Log::info("Time range: Start => {$startTime}, End => {$endTime}");
// Fetch alarms from ThingsBoard API
try {
$response = Http::withHeaders([
'Authorization' => "Bearer $token",
'Accept' => 'application/json',
])->get("$baseUrl/api/v2/alarms", [
'statusList' => 'ACTIVE',
'severityList' => 'CRITICAL,MAJOR,MINOR,WARNING',
'pageSize' => $pageSize,
'page' => $page,
'startTime' => $startTime,
'endTime' => $endTime,
'sortProperty' => 'createdTime',
'sortOrder' => 'DESC',
'originator' => $deviceId // Filter by device ID
]);
if (!$response->successful()) {
Log::error("Failed to fetch alarms. Status: " . $response->status());
return [];
}
// Parse the response
$alarms = $response->json()['data'] ?? [];
Log::info("Fetched " . count($alarms) . " alarms for device ID: {$deviceId}");
// Map alarms by `type` field
$alarmMap = [];
foreach ($alarms as $alarm) {
if (isset($alarm['type'])) {
$alarmMap[$alarm['type']] = true;
}
}
Log::info("Mapped alarm types: ", $alarmMap);
return $alarmMap;
} catch (\Exception $e) {
Log::error("Error fetching alarms: " . $e->getMessage());
return [];
}
}
// public function telemetryDataDevice(Request $request)
// {
// try {
// $token = readHeaderToken();
// if (!$token) {
// return response()->json([
// 'success' => false,
// 'error' => 'Authorization token required'
// ], 401);
// }
// $validator = Validator::make($request->all(), [
// 'device_id' => 'required|string',
// 'startTs' => 'nullable|string',
// 'endTs' => 'nullable|string',
// ]);
// if ($validator->fails()) {
// return response()->json([
// 'success' => false,
// 'error' => $validator->errors()->first()
// ], 400);
// }
// $deviceId = $request->input('device_id');
// $startTs = $request->input('startTs') ?: null;
// $endTs = $request->input('endTs') ?: null;
// try {
// $deviceWithTelemetry = Device::with([
// 'deviceProfile',
// 'timeseriesKeys' => function ($query) {
// $query->select('key_name', 'display_name', 'device_profile_xid', 'display_on_dashboard','display_on_dashboard');
// }
// ])
// ->where('id', $deviceId)
// ->firstOrFail();
// $telemetryResponse = $this->customerInfoService->getTelemetryDataDevice(
// $deviceWithTelemetry,
// $deviceWithTelemetry->timeseriesKeys->pluck('key_name')->toArray(),
// $startTs,
// $endTs,
// $token
// );
// if (!is_array($telemetryResponse)) {
// throw new \Exception("Invalid telemetry data format received from service");
// }
// $telemetry = collect($telemetryResponse)
// ->flatMap(function ($items, $keyName) use ($deviceWithTelemetry) {
// $displayName = $deviceWithTelemetry->timeseriesKeys
// ->firstWhere('key_name', $keyName)?->display_name ?? $keyName;
// return collect($items)->map(function ($item) use ($keyName, $displayName) {
// return [
// 'key_name' => $keyName,
// 'timestamp' => $item['ts'] ?? null,
// 'value' => $item['value'] ?? null,
// 'display_name' => $displayName,
// 'display_on_dashboard'
// ];
// });
// })
// ->values()
// ->all();
// return response()->json([
// 'success' => true,
// 'telemetry' => [
// 'device_id' => (string) $deviceWithTelemetry->id,
// 'device_name' => $deviceWithTelemetry->name,
// 'device_profile_name' => $deviceWithTelemetry->deviceProfile->name,
// 'device_profile_id' => (string) $deviceWithTelemetry->device_profile_id,
// 'telemetry_data' => $telemetry,
// ]
// ], 200);
// } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
// return response()->json([
// 'success' => false,
// 'error' => 'Device not found'
// ], 404);
// } catch (\Exception $e) {
// return response()->json([
// 'success' => false,
// 'error' => 'Failed to fetch telemetry data',
// 'details' => config('app.debug') ? $e->getMessage() : null
// ], 503);
// }
// } catch (\Exception $e) {
// return response()->json([
// 'success' => false,
// 'error' => 'Internal server error',
// 'details' => config('app.debug') ? $e->getMessage() : null
// ], 500);
// }
// }
2025-04-01 12:14:03 +05:30
2025-03-27 11:43:12 +05:30
public function telemetryDataDevice(Request $request)
{
try {
2025-04-07 12:53:20 +05:30
$token = readHeaderToken();
$customerId = User::where('id', $token['sub'])->value('customer_id');
2025-04-01 20:06:28 +05:30
Log::info('Telemetry request received', ['request_data' => $request->all()]);
2025-03-27 18:54:06 +05:30
$token = readHeaderToken();
if (!$token) {
2025-04-01 20:06:28 +05:30
Log::warning('Unauthorized access attempt: Missing token');
2025-03-27 18:54:06 +05:30
return response()->json([
'success' => false,
2025-04-01 20:06:28 +05:30
'error' => 'Authorization token required'
2025-03-27 18:54:06 +05:30
], 401);
}
2025-03-27 11:43:12 +05:30
$validator = Validator::make($request->all(), [
'device_id' => 'required|string',
2025-04-01 20:06:28 +05:30
'startTs' => 'nullable|string',
'endTs' => 'nullable|string',
2025-03-27 11:43:12 +05:30
]);
if ($validator->fails()) {
2025-04-01 20:06:28 +05:30
Log::error('Validation failed', ['errors' => $validator->errors()]);
2025-03-27 11:43:12 +05:30
return response()->json([
2025-03-27 18:54:06 +05:30
'success' => false,
2025-04-01 20:06:28 +05:30
'error' => $validator->errors()->first()
2025-03-27 18:54:06 +05:30
], 400);
2025-03-25 12:19:43 +05:30
}
2025-03-25 11:34:55 +05:30
2025-03-27 11:43:12 +05:30
$deviceId = $request->input('device_id');
2025-03-28 13:52:02 +05:30
$startTs = $request->input('startTs') ?: null;
$endTs = $request->input('endTs') ?: null;
2025-03-27 11:43:12 +05:30
try {
2025-04-01 20:06:28 +05:30
Log::info('Fetching device telemetry', ['device_id' => $deviceId]);
2025-03-28 13:52:02 +05:30
$deviceWithTelemetry = Device::with([
'deviceProfile',
'timeseriesKeys' => function ($query) {
$query->where(function ($q) {
$q->where('display_on_dashboard', true)
->orWhere('display_on_popup', true);
})
->select('key_name', 'display_name', 'device_profile_xid', 'display_on_dashboard', 'display_on_popup');
2025-03-28 13:52:02 +05:30
}
])
2025-03-27 11:43:12 +05:30
->where('id', $deviceId)
2025-04-07 12:53:20 +05:30
->where('customer_id', $customerId)
2025-03-27 18:54:06 +05:30
->firstOrFail();
2025-03-27 11:43:12 +05:30
$displayKeys = $deviceWithTelemetry->timeseriesKeys->pluck('key_name')->toArray();
2025-04-01 20:06:28 +05:30
$deviceProfileName = strtolower($deviceWithTelemetry->deviceProfile->name ?? '');
2025-04-01 20:06:28 +05:30
Log::info('Device profile and keys retrieved', [
'device_profile' => $deviceProfileName,
'display_keys' => $displayKeys
]);
// Pressure key condition
$pressureKey = 'Pressure_value';
$pressureActive = false;
2025-03-27 11:43:12 +05:30
$telemetryResponse = $this->customerInfoService->getTelemetryDataDevice(
$deviceWithTelemetry,
$displayKeys,
2025-03-27 11:43:12 +05:30
$startTs,
2025-03-27 18:54:06 +05:30
$endTs,
$token
2025-03-27 11:43:12 +05:30
);
if (!is_array($telemetryResponse)) {
2025-04-01 20:06:28 +05:30
Log::error('Invalid telemetry data format received');
2025-03-27 11:43:12 +05:30
throw new \Exception("Invalid telemetry data format received from service");
}
2025-04-01 20:06:28 +05:30
// Check if the device has "Gas Engine Profile" or "Engine Profile" in its profile name
if (
(strpos($deviceProfileName, 'gas engine profile') !== false || strpos($deviceProfileName, 'engine profile') !== false)
&& isset($telemetryResponse[$pressureKey])
&& is_array($telemetryResponse[$pressureKey])
) {
foreach ($telemetryResponse[$pressureKey] as $pressureData) {
if (!empty($pressureData['value']) && floatval($pressureData['value']) > 0) {
$pressureActive = true;
break;
}
}
}
Log::info('Telemetry data processed', [
'pressure_value' => $pressureActive,
'telemetry_keys' => array_keys($telemetryResponse)
]);
// Filter telemetry data based on display keys
$filteredResponse = array_intersect_key($telemetryResponse, array_flip($displayKeys));
2025-04-01 20:06:28 +05:30
// Add Pressure key if condition is met
if (isset($telemetryResponse[$pressureKey])) {
$filteredResponse[$pressureKey] = $telemetryResponse[$pressureKey];
}
$telemetry = collect($filteredResponse)
2025-03-27 11:43:12 +05:30
->flatMap(function ($items, $keyName) use ($deviceWithTelemetry) {
$keyData = $deviceWithTelemetry->timeseriesKeys->firstWhere('key_name', $keyName);
2025-03-27 11:43:12 +05:30
return collect($items)->map(function ($item) use ($keyName, $keyData) {
2025-03-27 11:43:12 +05:30
return [
2025-04-01 20:06:28 +05:30
'key_name' => $keyName,
'timestamp' => $item['ts'] ?? null,
'value' => $item['value'] ?? null,
'display_name' => $keyData->display_name ?? $keyName,
'display_on_dashboard' => $keyData->display_on_dashboard ?? false,
'display_on_popup' => $keyData->display_on_popup ?? false
2025-03-27 11:43:12 +05:30
];
});
})
->values()
->all();
2025-04-01 20:06:28 +05:30
Log::info('Telemetry response successfully generated', ['device_id' => $deviceId]);
2025-03-27 11:43:12 +05:30
return response()->json([
2025-03-27 18:54:06 +05:30
'success' => true,
2025-03-27 11:43:12 +05:30
'telemetry' => [
2025-04-01 20:06:28 +05:30
'device_id' => (string) $deviceWithTelemetry->id,
'device_name' => $deviceWithTelemetry->name,
'device_profile_name' => $deviceWithTelemetry->deviceProfile->name,
'device_profile_id' => (string) $deviceWithTelemetry->device_profile_id,
'pressure_value' => $pressureActive, // Updated response
'telemetry_data' => $telemetry,
2025-03-27 11:43:12 +05:30
]
2025-03-27 18:54:06 +05:30
], 200);
2025-03-27 11:43:12 +05:30
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
2025-04-01 20:06:28 +05:30
Log::error('Device not found', ['device_id' => $deviceId]);
2025-03-27 11:43:12 +05:30
return response()->json([
2025-03-27 18:54:06 +05:30
'success' => false,
2025-04-01 20:06:28 +05:30
'error' => 'Device not found'
2025-03-27 18:54:06 +05:30
], 404);
2025-03-27 11:43:12 +05:30
} catch (\Exception $e) {
2025-04-01 20:06:28 +05:30
Log::error('Failed to fetch telemetry data', [
'device_id' => $deviceId,
'error' => $e->getMessage()
]);
2025-03-27 11:43:12 +05:30
return response()->json([
2025-03-27 18:54:06 +05:30
'success' => false,
2025-04-01 20:06:28 +05:30
'error' => 'Failed to fetch telemetry data',
2025-03-27 11:43:12 +05:30
'details' => config('app.debug') ? $e->getMessage() : null
2025-03-27 18:54:06 +05:30
], 503);
2025-03-25 12:19:43 +05:30
}
2025-03-27 11:43:12 +05:30
} catch (\Exception $e) {
2025-04-01 20:06:28 +05:30
Log::critical('Internal server error', ['error' => $e->getMessage()]);
2025-03-27 11:43:12 +05:30
return response()->json([
2025-03-27 18:54:06 +05:30
'success' => false,
2025-04-01 20:06:28 +05:30
'error' => 'Internal server error',
2025-03-27 18:54:06 +05:30
'details' => config('app.debug') ? $e->getMessage() : null
], 500);
2025-03-27 11:43:12 +05:30
}
2025-03-25 12:19:43 +05:30
}
2025-04-01 20:06:28 +05:30
// public function telemetryDataDeviceDiagnostic(Request $request, $deviceId)
// {
// $devices = Device::with('deviceProfile')
// ->where('id', $deviceId)
// ->get();
2025-03-26 11:21:24 +05:30
// if ($devices->isEmpty()) {
// return response()->json(['error' => 'No devices found'], 404);
// }
2025-03-26 11:21:24 +05:30
// $startTs = $request->has('start_date') ? strtotime($request->start_date) * 1000 : null;
// $endTs = $request->has('end_date') ? strtotime($request->end_date) * 1000 : null;
2025-03-26 11:21:24 +05:30
// $response = [];
2025-03-26 11:21:24 +05:30
// foreach ($devices as $device) {
// $telemetry = [];
2025-03-26 11:21:24 +05:30
// $keyNames = TimeseriesKeyMaster::where('device_profile_xid', $device->device_profile_id)
// ->pluck('key_name', 'display_name')
// ->toArray();
2025-03-26 11:21:24 +05:30
// $telemetryResponse = $this->customerInfoService->getTelemetryDataDeviceDiagonostic($device, $keyNames, $startTs, $endTs);
2025-03-26 11:21:24 +05:30
// foreach ($keyNames as $keyName) {
// if (isset($telemetryResponse[$keyName])) {
// foreach ($telemetryResponse[$keyName] as $item) {
// $timestamp = $item['ts'] ?? null;
2025-03-26 11:21:24 +05:30
// // ✅ Filter telemetry by timestamp range
// if ($timestamp && $timestamp >= $startTs && $timestamp <= $endTs) {
// $telemetry[] = [
// 'key_name' => $keyName,
// 'timestamp' => $timestamp,
// 'start_date' => $startTs,
// 'end_date' => $endTs,
// 'value' => $item['value'] ?? null,
// 'display_name' => $keyName,
// ];
// }
// }
// }
// }
2025-03-26 11:21:24 +05:30
// if (!empty($telemetry)) {
// $response[] = [
// 'device_id' => (string) $device->id,
// 'device_name' => $device->name,
// 'device_profile_name' => (string) $device->deviceProfile->name,
// 'device_profile_id' => (string) $device->device_profile_id,
// 'telemetry' => $telemetry,
// ];
// }
// }
2025-03-25 11:34:55 +05:30
// return response()->json(['telemetry' => $response]);
// }
2025-03-25 11:34:55 +05:30
2025-03-26 17:36:30 +05:30
// public function telemetryDataDeviceDiagnostic(Request $request, $deviceId)
// {
// // Fetch devices
// $devices = Device::with('deviceProfile')
// ->where('id', $deviceId)
// ->get();
// if ($devices->isEmpty()) {
// return response()->json(['error' => 'No devices found'], 404);
// }
// // Get start and end timestamps from request parameters
// $startTs = $request->has('start_date') ? strtotime($request->start_date) * 1000 : null;
// $endTs = $request->has('end_date') ? strtotime($request->end_date) * 1000 : null;
// if (!$startTs || !$endTs) {
// return response()->json(['error' => 'Start date and end date are required'], 400);
// }
// $response = [];
// foreach ($devices as $device) {
// $telemetry = [];
// $keyNames = TimeseriesKeyMaster::where('device_profile_xid', $device->device_profile_id)
// ->pluck('key_name', 'display_name')
// ->toArray();
// $telemetryResponse = $this->customerInfoService->getTelemetryDataDeviceDiagonostic($device, $keyNames, $startTs, $endTs);
// foreach ($keyNames as $displayName => $keyName) {
// if (isset($telemetryResponse[$keyName])) {
// foreach ($telemetryResponse[$keyName] as $item) {
// $itemTs = $item['timestamp'] ?? null;
// // ✅ Filter only telemetry within the date range
// if ($itemTs >= $startTs && $itemTs <= $endTs) {
// $telemetry[] = [
// 'key_name' => $keyName,
// 'value' => $item['value'] ?? null,
// 'display_name' => $displayName,
// 'timestamp' => $itemTs,
// 'start_date' => $startTs,
// 'end_date' => $endTs
// ];
// }
// }
// }
// }
// if (!empty($telemetry)) {
// $response[] = [
// 'device_id' => (string) $device->id,
// 'device_name' => $device->name,
// 'device_profile_name' => (string) $device->deviceProfile->name,
// 'device_profile_id' => (string) $device->device_profile_id,
// 'telemetry' => $telemetry,
// ];
// }
// }
// return response()->json(['telemetry' => $response]);
// }
2025-03-25 11:34:55 +05:30
2025-04-01 12:14:03 +05:30
}