From fb487ef0f0ee072438f1b08d5a4fbccd4453fd81 Mon Sep 17 00:00:00 2001 From: sayliraut Date: Thu, 20 Mar 2025 12:01:01 +0530 Subject: [PATCH 1/2] device createorupdate --- .../APIS/CustomerApi/CustomerController.php | 2 +- .../APIS/CustomerApi/DeviceController.php | 112 +++++++++++++++++- app/Services/DeviceService.php | 94 +++++++++++++++ routes/admin_api.php | 6 + 4 files changed, 212 insertions(+), 2 deletions(-) create mode 100644 app/Services/DeviceService.php diff --git a/app/Http/Controllers/APIS/CustomerApi/CustomerController.php b/app/Http/Controllers/APIS/CustomerApi/CustomerController.php index 7ba5e70..3432d8c 100644 --- a/app/Http/Controllers/APIS/CustomerApi/CustomerController.php +++ b/app/Http/Controllers/APIS/CustomerApi/CustomerController.php @@ -46,7 +46,7 @@ class CustomerController extends Controller if (!empty($request->id) && is_array($request->id) && isset($request->id['id'])) { $userData['id'] = [ - 'id' => $request->id['id'], + 'id' => $request->id['id'], 'entityType' => 'CUSTOMER', ]; } diff --git a/app/Http/Controllers/APIS/CustomerApi/DeviceController.php b/app/Http/Controllers/APIS/CustomerApi/DeviceController.php index 068e891..8791495 100644 --- a/app/Http/Controllers/APIS/CustomerApi/DeviceController.php +++ b/app/Http/Controllers/APIS/CustomerApi/DeviceController.php @@ -3,9 +3,119 @@ namespace App\Http\Controllers\APIS\CustomerApi; use App\Http\Controllers\Controller; +use App\Models\Device; +use App\Services\DeviceService; use Illuminate\Http\Request; +use Illuminate\Support\Str; +use Illuminate\Support\Facades\Log; +use Exception; + class DeviceController extends Controller { - // + + protected $deviceService; + + public function __construct(DeviceService $deviceService) + { + $this->deviceService = $deviceService; + } + + + public function createOrUpdateDevice(Request $request) + { + try { + Log::info('Request Data: ', $request->all()); + $deviceData = [ + 'name' => $request->name, + 'type' => $request->type, + 'label' => $request->label, + 'version' => $request->version ?? 1, + 'additionalInfo' => $request->additionalInfo ?? [], + 'deviceData' => [ + 'configuration' => ['type' => 'DEFAULT'], + 'customerId' => [ + 'id' => $request->customerId['id'] ?? null, + 'entityType' => 'CUSTOMER' + ], + 'tenantId' => [ + 'id' => $request->tenantId['id'] ?? null, + 'entityType' => 'TENANT' + ], + 'transportConfiguration' => [ + 'type' => 'DEFAULT', + 'powerMode' => 'PSM', + 'psmActivityTimer' => $request->transportConfiguration['psmActivityTimer'] ?? 9007199254740991, + 'edrxCycle' => $request->transportConfiguration['edrxCycle'] ?? 9007199254740991, + 'pagingTransmissionWindow' => $request->transportConfiguration['pagingTransmissionWindow'] ?? 9007199254740991, + ] + ], + // 'deviceProfileId' => [ + // 'id' => $request->deviceProfileId['id'] ?? null, + // 'entityType' => 'DEVICE_PROFILE' + // ], + // 'firmwareId' => [ + // 'id' => $request->firmwareId['id'] ?? null, + // 'entityType' => 'OTA_PACKAGE' + // ], + // 'softwareId' => [ + // 'id' => $request->softwareId['id'] ?? null, + // 'entityType' => 'OTA_PACKAGE' + // ] + ]; + + if (!empty($request->id) && isset($request->id['id'])) { + $deviceData['id'] = [ + 'id' => $request->id['id'], + 'entityType' => 'DEVICE' + ]; + } + Log::info('Device Data:', ['device_data' => $deviceData]); + // Call Service to create/update device + $apiResponse = $this->deviceService->createOrUpdateDevice($deviceData); + Log::info("API Response Data:", ['response' => $apiResponse]); + + + + // if (!is_array($apiResponse)) { + // return jsonResponseWithErrorMessage('Unexpected API response format', 500); + // } + + + // Store device in the database + $device = Device::updateOrCreate( + ['id' => $apiResponse['id']['id'] ?? Str::uuid()->toString()], + [ + 'entity_type' => $apiResponse['id']['entityType'] ?? 'DEVICE', + 'created_time' => $apiResponse['createdTime'] ?? now()->timestamp, + 'customer_id' => $apiResponse['customerId']['id'] ?? null, + 'name' => $apiResponse['name'] ?? null, + 'type' => $apiResponse['type'] ?? null, + 'label' => $apiResponse['label'] ?? null, + 'device_profile_id' => $apiResponse['deviceProfileId']['id'] ?? null, + 'firmware_id' => $apiResponse['firmwareId']['id'] ?? null, + 'software_id' => $apiResponse['softwareId']['id'] ?? null, + 'version' => $apiResponse['version'] ?? 1, + 'tenant_id' => $apiResponse['tenantId']['id'] ?? null, + 'device_data' => json_encode($apiResponse['deviceData'] ?? []), + 'additional_info' => json_encode($apiResponse['additionalInfo'] ?? []) + ] + ); + + + return jsonResponseWithSuccessMessage( + isset($request->id) ? 'Device updated successfully' : 'Device created successfully', + ['device' => $device, 'api_response' => $apiResponse] + ); + } catch (Exception $e) { + Log::error("Error: " . $e->getMessage()); + + $errorResponse = json_decode($e->getMessage(), true); + if (json_last_error() === JSON_ERROR_NONE) { + return jsonResponseWithErrorMessage($errorResponse['message'] ?? 'Something went wrong', 400, $errorResponse); + } + + return jsonResponseWithErrorMessage($e->getMessage(), 500); + } + } } diff --git a/app/Services/DeviceService.php b/app/Services/DeviceService.php new file mode 100644 index 0000000..b11e5f2 --- /dev/null +++ b/app/Services/DeviceService.php @@ -0,0 +1,94 @@ +baseUrl = env('THINGSBOARD_URL', 'http://65.0.131.117:8080'); + $this->username = env('THINGSBOARD_USERNAME', 'tenant1@thingsboard.org'); + $this->password = env('THINGSBOARD_PASSWORD', 'tenant1'); + } + + public function getToken() + { + if (Cache::has('thingsboard_token')) { + return Cache::get('thingsboard_token'); + } + + $response = Http::withHeaders([ + 'accept' => 'application/json', + 'Content-Type' => 'application/json', + ]) + ->post("{$this->baseUrl}/api/auth/login", [ + 'username' => $this->username, + 'password' => $this->password, + ]); + + + if ($response->successful()) { + $token = $response->json('token'); + Cache::put('thingsboard_token', $token, now()->addMinutes(15)); + return $token; + } else { + Log::error("ThingsBoard Authentication Failed: " . $response->body()); + throw new Exception('Unable to authenticate with ThingsBoard: ' . $response->body()); + } + } + + + public function createOrUpdateDevice(array $data) + { + $token = $this->getToken(); + + Log::info('Payload before API call:', ['payload' => json_encode($data, JSON_PRETTY_PRINT)]); + + $payload = [ + 'name' => $data['name'], + 'type' => $data['type'], + 'label' => $data['label'], + 'version' => $data['version'] ?? 1, + // 'deviceProfileId' => $data['deviceProfileId'], + // 'firmwareId' => $data['firmwareId'], + // 'softwareId' => $data['softwareId'], + 'deviceData' => $data['deviceData'], + 'additionalInfo' => $data['additionalInfo'] ?? [], + ]; + + if (!empty($data['id']) && isset($data['id']['id'])) { + $payload['id'] = $data['id']; + } + + $url = "{$this->baseUrl}/api/device"; + $method = 'post'; + + $response = Http::withHeaders([ + 'Authorization' => "Bearer $token", + 'Accept' => 'application/json', + 'Content-Type' => 'application/json', + ])->post($url, $payload); + + if (!$response->successful()) { + Log::error("API Error Response:", ['body' => $response->body()]); + throw new Exception('API Error: ' . $response->body()); + } + + $apiResponse = $response->json(); + + if (!is_array($apiResponse)) { + Log::error("Invalid API Response:", ['response' => $apiResponse]); + throw new Exception('Unexpected API response format'); + } + } +} diff --git a/routes/admin_api.php b/routes/admin_api.php index edb1a2a..034e0a4 100644 --- a/routes/admin_api.php +++ b/routes/admin_api.php @@ -2,6 +2,7 @@ use App\Http\Controllers\APIS\CustomerApi\CustomerController; use App\Http\Controllers\APIS\AdminApi\UsersController; +use App\Http\Controllers\APIS\CustomerApi\DeviceController; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; @@ -25,3 +26,8 @@ Route::delete('/customer/delete/{customerId}', [CustomerController::class, 'dele Route::post('/users-store', [UsersController::class, 'store'])->name('user_create'); Route::get('/users-list', [UsersController::class, 'list'])->name('user_list'); Route::delete('/users-delete/{userId}', [UsersController::class, 'delete']); + + +//******************************************************* User API******************************************************** +Route::post('/device/create-or-update', [DeviceController::class, 'createOrUpdateDevice'])->name('customer.create-or-update'); + -- 2.34.1 From 79f3059c7b446ab1831f85bda187bb266e02b4be Mon Sep 17 00:00:00 2001 From: sayliraut Date: Fri, 21 Mar 2025 19:24:02 +0530 Subject: [PATCH 2/2] device delete list --- .../APIS/CustomerApi/CustomerController.php | 1 - .../APIS/CustomerApi/DeviceController.php | 112 +++++++++++------- app/Http/Requests/CreateCustomerRequest.php | 14 --- app/Http/Requests/CreateDeviceRequest.php | 36 ++++++ app/Models/Device.php | 1 + app/Services/AdminService.php | 4 +- app/Services/DeviceService.php | 82 ++++++++++--- routes/admin_api.php | 15 ++- 8 files changed, 187 insertions(+), 78 deletions(-) create mode 100644 app/Http/Requests/CreateDeviceRequest.php diff --git a/app/Http/Controllers/APIS/CustomerApi/CustomerController.php b/app/Http/Controllers/APIS/CustomerApi/CustomerController.php index 3432d8c..e48fce1 100644 --- a/app/Http/Controllers/APIS/CustomerApi/CustomerController.php +++ b/app/Http/Controllers/APIS/CustomerApi/CustomerController.php @@ -60,7 +60,6 @@ class CustomerController extends Controller // Call API to create/update customer $response = $this->adminService->createOrUpdateCustomer($userData); - Log::info("API Response: ", $response); if (is_array($response)) { $apiData = $response; // If it's an array, use it directly diff --git a/app/Http/Controllers/APIS/CustomerApi/DeviceController.php b/app/Http/Controllers/APIS/CustomerApi/DeviceController.php index 8791495..646c03e 100644 --- a/app/Http/Controllers/APIS/CustomerApi/DeviceController.php +++ b/app/Http/Controllers/APIS/CustomerApi/DeviceController.php @@ -3,6 +3,7 @@ namespace App\Http\Controllers\APIS\CustomerApi; use App\Http\Controllers\Controller; +use App\Http\Requests\CreateDeviceRequest; use App\Models\Device; use App\Services\DeviceService; use Illuminate\Http\Request; @@ -22,65 +23,48 @@ class DeviceController extends Controller } - public function createOrUpdateDevice(Request $request) + public function createOrUpdateDevice(CreateDeviceRequest $request) { try { - Log::info('Request Data: ', $request->all()); + $deviceData = [ - 'name' => $request->name, - 'type' => $request->type, - 'label' => $request->label, + 'name' => $request->name ?? null, + 'type' => $request->type ?? null, + 'label' => $request->label ?? null, 'version' => $request->version ?? 1, + 'customerId' => $request->customerId ?? 1, 'additionalInfo' => $request->additionalInfo ?? [], 'deviceData' => [ 'configuration' => ['type' => 'DEFAULT'], - 'customerId' => [ - 'id' => $request->customerId['id'] ?? null, - 'entityType' => 'CUSTOMER' - ], - 'tenantId' => [ - 'id' => $request->tenantId['id'] ?? null, - 'entityType' => 'TENANT' - ], 'transportConfiguration' => [ 'type' => 'DEFAULT', - 'powerMode' => 'PSM', + 'powerMode' => $request->transportConfiguration['powerMode'] ?? 'PSM', 'psmActivityTimer' => $request->transportConfiguration['psmActivityTimer'] ?? 9007199254740991, 'edrxCycle' => $request->transportConfiguration['edrxCycle'] ?? 9007199254740991, 'pagingTransmissionWindow' => $request->transportConfiguration['pagingTransmissionWindow'] ?? 9007199254740991, ] ], - // 'deviceProfileId' => [ - // 'id' => $request->deviceProfileId['id'] ?? null, - // 'entityType' => 'DEVICE_PROFILE' - // ], - // 'firmwareId' => [ - // 'id' => $request->firmwareId['id'] ?? null, - // 'entityType' => 'OTA_PACKAGE' - // ], - // 'softwareId' => [ - // 'id' => $request->softwareId['id'] ?? null, - // 'entityType' => 'OTA_PACKAGE' - // ] + 'deviceProfileId' => $request->deviceProfileId ?? 1, + ]; - if (!empty($request->id) && isset($request->id['id'])) { - $deviceData['id'] = [ - 'id' => $request->id['id'], - 'entityType' => 'DEVICE' - ]; + // Optional Fields + + + // Handle updating existing devices + if (!empty($request->id)) { + $deviceData['id'] = $request->id; } - Log::info('Device Data:', ['device_data' => $deviceData]); + if (!empty($request->firmwareId)) { + $deviceData['firmwareId'] = $request->firmwareId; + } + if (!empty($request->softwareId)) { + $deviceData['softwareId'] = $request->softwareId; + } + + // Call Service to create/update device $apiResponse = $this->deviceService->createOrUpdateDevice($deviceData); - Log::info("API Response Data:", ['response' => $apiResponse]); - - - - // if (!is_array($apiResponse)) { - // return jsonResponseWithErrorMessage('Unexpected API response format', 500); - // } - // Store device in the database $device = Device::updateOrCreate( @@ -92,6 +76,7 @@ class DeviceController extends Controller 'name' => $apiResponse['name'] ?? null, 'type' => $apiResponse['type'] ?? null, 'label' => $apiResponse['label'] ?? null, + 'asset_id' => $apiResponse['asset_id'] ?? 'a5daeb60-f36c-11ef-a9dc-45dd276e4cd5', 'device_profile_id' => $apiResponse['deviceProfileId']['id'] ?? null, 'firmware_id' => $apiResponse['firmwareId']['id'] ?? null, 'software_id' => $apiResponse['softwareId']['id'] ?? null, @@ -102,9 +87,8 @@ class DeviceController extends Controller ] ); - return jsonResponseWithSuccessMessage( - isset($request->id) ? 'Device updated successfully' : 'Device created successfully', + !empty($request->id) ? 'Device updated successfully' : 'Device created successfully', ['device' => $device, 'api_response' => $apiResponse] ); } catch (Exception $e) { @@ -118,4 +102,48 @@ class DeviceController extends Controller return jsonResponseWithErrorMessage($e->getMessage(), 500); } } + + + + public function listDevices(Request $request) + { + try { + $devices = Device::all(); + + return jsonResponseWithSuccessMessage('Devices fetched successfully', [ + 'devices' => $devices + ]); + } catch (Exception $e) { + Log::error("An error occurred: " . $e->getMessage()); + return jsonResponseWithErrorMessage($e->getMessage(), 500); + } + } + + + public function deleteDevice($deviceId) + { + + try { + if (!$deviceId) { + return jsonResponseWithErrorMessage('Device ID is required', 400); + } + $response = $this->deviceService->deleteDevice(['deviceId' => $deviceId]); + + + $Device = Device::where('id', $deviceId)->first(); + if ($Device) { + $Device->delete(); + } + + return jsonResponseWithSuccessMessage('Device deleted successfully', ['api_response' => $response]); + } catch (Exception $e) { + Log::error("An error occurred: " . $e->getMessage()); + $errorResponse = json_decode($e->getMessage(), true); + if (json_last_error() === JSON_ERROR_NONE) { + return jsonResponseWithErrorMessage($errorResponse['message'] ?? 'Something went wrong', 400, $errorResponse); + } + + return jsonResponseWithErrorMessage($e->getMessage(), 500); + } + } } diff --git a/app/Http/Requests/CreateCustomerRequest.php b/app/Http/Requests/CreateCustomerRequest.php index bd0d008..b4bafea 100644 --- a/app/Http/Requests/CreateCustomerRequest.php +++ b/app/Http/Requests/CreateCustomerRequest.php @@ -24,12 +24,7 @@ class CreateCustomerRequest extends FormRequest */ public function rules(): array { - Log::info("CreateCustomerRequest: " . json_encode($this->all())); return [ - // 'id' => 'required|array', - // 'id.id' => 'required|uuid', - // 'id.entityType' => 'required|string|in:CUSTOMER', - 'country' => 'required|string', 'state' => 'required|string|max:255', 'city' => 'required|string|max:255', @@ -38,16 +33,7 @@ class CreateCustomerRequest extends FormRequest 'zip' => 'required|string|max:20', 'phone' => 'nullable|string|max:20', 'email' => 'required|email|max:255', - 'title' => 'required|string|max:255', - - // 'tenantId' => 'required', - // 'tenantId.id' => 'required|uuid', - // 'tenantId.entityType' => 'required|string|in:TENANT', - - // 'version' => 'required|integer|min:1', - - // 'additionalInfo' => 'nullable|array', ]; } diff --git a/app/Http/Requests/CreateDeviceRequest.php b/app/Http/Requests/CreateDeviceRequest.php new file mode 100644 index 0000000..751e989 --- /dev/null +++ b/app/Http/Requests/CreateDeviceRequest.php @@ -0,0 +1,36 @@ +|string> + */ + public function rules(): array + { + // Log::info("CreateDeviceRequest: " . json_encode($this->all())); + return [ + + 'name' => 'required|string', + 'type' => 'required|string|max:255', + 'label' => 'required|string|max:255', + 'customerId' => 'required', + + ]; + } +} diff --git a/app/Models/Device.php b/app/Models/Device.php index 0171d22..22bef8f 100644 --- a/app/Models/Device.php +++ b/app/Models/Device.php @@ -18,6 +18,7 @@ class Device extends Model 'tenant_id', 'customer_id', 'name', + 'asset_id', 'type', 'label', 'device_profile_id', diff --git a/app/Services/AdminService.php b/app/Services/AdminService.php index 189cac9..a685d44 100644 --- a/app/Services/AdminService.php +++ b/app/Services/AdminService.php @@ -138,7 +138,7 @@ class AdminService public function createOrUpdateCustomer(array $data) { $token = $this->getToken(); - Log::info('Getting data before payload', ['data' => json_encode($data, JSON_PRETTY_PRINT)]); + // Log::info('Getting data before payload', ['data' => json_encode($data, JSON_PRETTY_PRINT)]); $payload = [ 'title' => $data['title'] ?? 'Default Title', @@ -175,7 +175,7 @@ class AdminService ]; } - Log::info('Final Payload:', ['payload' => json_encode($payload, JSON_PRETTY_PRINT)]); + // Log::info('Final Payload:', ['payload' => json_encode($payload, JSON_PRETTY_PRINT)]); diff --git a/app/Services/DeviceService.php b/app/Services/DeviceService.php index b11e5f2..cfe4362 100644 --- a/app/Services/DeviceService.php +++ b/app/Services/DeviceService.php @@ -50,25 +50,51 @@ class DeviceService public function createOrUpdateDevice(array $data) { + $token = $this->getToken(); - Log::info('Payload before API call:', ['payload' => json_encode($data, JSON_PRETTY_PRINT)]); - $payload = [ - 'name' => $data['name'], - 'type' => $data['type'], - 'label' => $data['label'], + 'name' => $data['name'] ?? null, + 'type' => $data['type'] ?? null, + 'label' => $data['label'] ?? null, 'version' => $data['version'] ?? 1, - // 'deviceProfileId' => $data['deviceProfileId'], - // 'firmwareId' => $data['firmwareId'], - // 'softwareId' => $data['softwareId'], - 'deviceData' => $data['deviceData'], + 'deviceProfileId' => isset($data['deviceProfileId']['id']) ? $data['deviceProfileId'] : null, + 'customerId' => [ + 'id' => $data['customerId'] ?? null, + 'entityType' => 'CUSTOMER' + ], + 'deviceProfileId' => [ + 'id' => $data['deviceProfileId'] ?? null, + 'entityType' => 'DEVICE_PROFILE' + ], + 'deviceData' => $data['deviceData'] ?? [], 'additionalInfo' => $data['additionalInfo'] ?? [], ]; - if (!empty($data['id']) && isset($data['id']['id'])) { - $payload['id'] = $data['id']; + + // Optional fields + if (!empty($data['id'])) { + $payload['id'] = [ + 'id' => $data['id'], + 'entityType' => 'DEVICE' + ]; } + if (!empty($data['firmwareId'])) { + $payload['firmwareId'] = [ + 'id' => $data['firmwareId'], + 'entityType' => 'OTA_PACKAGE' + ]; + } + if (!empty($data['softwareId'])) { + $payload['softwareId'] = [ + 'id' => $data['softwareId'], + 'entityType' => 'OTA_PACKAGE' + ]; + } + + + + $url = "{$this->baseUrl}/api/device"; $method = 'post'; @@ -86,9 +112,37 @@ class DeviceService $apiResponse = $response->json(); - if (!is_array($apiResponse)) { - Log::error("Invalid API Response:", ['response' => $apiResponse]); - throw new Exception('Unexpected API response format'); + return $apiResponse; + } + + + + public function deleteDevice(array $data) + { + $token = $this->getToken(); + + + $url = "{$this->baseUrl}/api/device/{$data['deviceId']}"; + + $response = Http::withHeaders([ + 'Authorization' => "Bearer $token", + 'Accept' => 'application/json', + ])->delete($url); + + + + // If response body is empty, assume success + if ($response->status() === 200 && empty($response->body())) { + return ['message' => 'Device deleted successfully']; } + + if ($response->successful()) { + return $response->json(); + } else { + throw new Exception('Failed to create Device: ' . $response->body()); + Log::info('API Response:', ['response' => $response]); + } + + throw new Exception('Failed to create user: ' . $response->body()); } } diff --git a/routes/admin_api.php b/routes/admin_api.php index e3461c9..878160a 100644 --- a/routes/admin_api.php +++ b/routes/admin_api.php @@ -31,10 +31,15 @@ Route::delete('/customer/delete/{customerId}', [CustomerController::class, 'dele Route::post('/users-store', [UsersController::class, 'store'])->name('user_create'); Route::get('/users-list', [UsersController::class, 'list'])->name('user_list'); Route::delete('/users-delete/{userId}', [UsersController::class, 'delete']); - - -//******************************************************* User API******************************************************** -Route::post('/device/create-or-update', [DeviceController::class, 'createOrUpdateDevice'])->name('customer.create-or-update'); - Route::post('/activate/{id}', [UsersController::class, 'activate'])->name('activate.user'); Route::post('/users-login', [UsersController::class, 'loginUser']); + + + +//******************************************************* Device API******************************************************** +Route::post('/device/create-or-update', [DeviceController::class, 'createOrUpdateDevice'])->name('device.create-or-update'); +Route::get('/device/list', [DeviceController::class, 'listDevices'])->name('device.list'); +Route::delete('/device/delete/{deviceId}', [DeviceController::class, 'deleteDevice'])->name('device.delete'); + + + -- 2.34.1