Files
backend_vib360_laravel/app/Services/DeviceService.php
2025-03-20 12:01:01 +05:30

95 lines
2.9 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Exception;
use Illuminate\Support\Facades\Log;
class DeviceService
{
private $baseUrl;
private $username;
private $password;
public function __construct()
{
$this->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');
}
}
}