کلاینت REST

کلاینت REST

کلاینت REST API در ThingsConnect به شما کمک می‌کند تا از طریق برنامه‌های جاوای خود با REST API تعامل داشته باشید. با استفاده از کلاینت REST، می‌توانید به‌صورت برنامه‌نویسی، دارایی‌ها (Assets)، دستگاه‌ها (Devices)، مشتریان (Customers)، کاربران (Users)، و دیگر موجودیت‌ها و روابط آن‌ها را در ThingsConnect ایجاد کنید.

روش توصیه‌شده برای نصب کلاینت REST، استفاده از ابزارهای خودکارسازی ساخت مانند Maven است. نسخه کلاینت REST به نسخه پلتفرمی که استفاده می‌کنید، بستگی دارد.

کلاینت REST نسخه جامعه (Community Edition)

برای افزودن کلاینت REST به پروژه Maven/Gradle خود، باید از وابستگی (Dependency) زیر استفاده کنید:

				
					<dependencies>
    <dependency>
        <groupId>org.thingsboard</groupId>
        <artifactId>rest-client</artifactId>
        <version>3.8.1</version>
    </dependency>
</dependencies>
				
			

نکته: کلاینت REST بر پایه Spring RestTemplate ساخته شده است و در نتیجه به ماژول Spring Web (نسخه 5.1.5.RELEASE در زمان نگارش این مقاله) وابسته است.

برای دانلود وابستگی کلاینت REST، باید مخزن زیر را به پروژه خود اضافه کنید. همچنین، می‌توانید کلاینت REST را مستقیماً از کد منبع آن بسازید.

				
					<repositories>
    <repository>
        <id>thingsboard</id>
        <url>https://repo.thingsboard.io/artifactory/libs-release-public</url>
    </repository>
</repositories>
				
			

استفاده اولیه

نمونه کد زیر نشان می‌دهد که چگونه می‌توان کلاینت ThingsConnect را ایجاد کرد، وارد سیستم شد (Login) و جزئیات کاربر فعلی که وارد شده است را دریافت کرد:

				
					// ThingsBoard REST API URL
String url = "http://localhost:8080";

// Default Tenant Administrator credentials
String username = "tenant@thingsboard.org";
String password = "tenant";

// Creating new rest client and auth with credentials
RestClient client = new RestClient(url);
client.login(username, password);

// Get information of current logged in user and print it
client.getUser().ifPresent(System.out::println);

// Perform logout of current user and close the client
client.logout();
client.close();
				
			

مثال‌ها

دریافت دستگاه‌های Tenant

نمونه کد زیر نشان می‌دهد که چگونه می‌توان دستگاه‌های مستأجر را از طریق لینک صفحه دریافت کرد:

				
					// ThingsBoard REST API URL
String url = "http://localhost:8080";

// Default Tenant Administrator credentials
String username = "tenant@thingsboard.org";
String password = "tenant";

// Creating new rest client and auth with credentials
RestClient client = new RestClient(url);
client.login(username, password);

PageData<Device> tenantDevices;
PageLink pageLink = new PageLink(10);
do {
    // Fetch all tenant devices using current page link and print each of them
    tenantDevices = client.getTenantDevices("", pageLink);
    tenantDevices.getData().forEach(System.out::println);
    pageLink = pageLink.nextPageLink();
} while (tenantDevices.hasNext());

// Perform logout of current user and close the client
client.logout();
client.close();
				
			

دریافت داشبوردهای Tenant

نمونه کد زیر نشان می‌دهد که چگونه می‌توان داشبوردهای Tenant را با استفاده از پیوند صفحه (Page Link) دریافت کرد:

				
					// ThingsBoard REST API URL
String url = "http://localhost:8080";

// Default Tenant Administrator credentials
String username = "tenant@thingsboard.org";
String password = "tenant";

// Creating new rest client and auth with credentials
RestClient client = new RestClient(url);
client.login(username, password);

PageData<DashboardInfo> pageData;
PageLink pageLink = new PageLink(10);
do {
    // Fetch all tenant dashboards using current page link and print each of them
    pageData = client.getTenantDashboards(pageLink);
    pageData.getData().forEach(System.out::println);
    pageLink = pageLink.nextPageLink();
} while (pageData.hasNext());

// Perform logout of current user and close the client
client.logout();
client.close();
				
			

دریافت دستگاه‌های مشتری

نمونه کد زیر نشان می‌دهد که چگونه می‌توان دستگاه‌های مشتری را از طریق لینک صفحه دریافت کرد:

				
					// ThingsBoard REST API URL
String url = "http://localhost:8080";
// Perform login with default Customer User credentials
String username = "customer@thingsboard.org";
String password = "customer";
RestClient client = new RestClient(url);
client.login(username, password);

PageData<Device> pageData;
PageLink pageLink = new PageLink(10);
do {
    // Get current user
    User user = client.getUser().orElseThrow(() -> new IllegalStateException("No logged in user has been found"));
    // Fetch customer devices using current page link
    pageData = client.getCustomerDevices(user.getCustomerId(), "", pageLink);
    pageData.getData().forEach(System.out::println);
    pageLink = pageLink.nextPageLink();
} while (pageData.hasNext());

// Perform logout of current user and close the client
client.logout();
client.close();
				
			

شمارش موجودیت‌ها با استفاده از Entity Data Query API

نمونه کد زیر نشان می‌دهد که چگونه می‌توان از Entity Data Query API برای شمارش دستگاه‌های کل و دستگاه‌های فعال استفاده کرد:

				
					// ThingsBoard REST API URL
String url = "http://localhost:8080";

// Perform login with default Customer User credentials
String username = "tenant@thingsboard.org";
String password = "tenant";
RestClient client = new RestClient(url);
client.login(username, password);

// Create entity filter to get all devices
EntityTypeFilter typeFilter = new EntityTypeFilter();
typeFilter.setEntityType(EntityType.DEVICE);

// Create entity count query with provided filter
EntityCountQuery totalDevicesQuery = new EntityCountQuery(typeFilter);

// Execute entity count query and get total devices count
Long totalDevicesCount = client.countEntitiesByQuery(totalDevicesQuery);
System.out.println("Total devices by the first query: " + totalDevicesCount);

// Set key filter to existing query to get only active devices
KeyFilter keyFilter = new KeyFilter();
keyFilter.setKey(new EntityKey(EntityKeyType.ATTRIBUTE, "active"));
keyFilter.setValueType(EntityKeyValueType.BOOLEAN);

BooleanFilterPredicate filterPredicate = new BooleanFilterPredicate();
filterPredicate.setOperation(BooleanFilterPredicate.BooleanOperation.EQUAL);
filterPredicate.setValue(new FilterPredicateValue<>(true));
        
keyFilter.setPredicate(filterPredicate);

// Create entity count query with provided filter
EntityCountQuery totalActiveDevicesQuery = 
        new EntityCountQuery(typeFilter, List.of(keyFilter));
        
// Execute active devices query and print total devices count
Long totalActiveDevicesCount = client.countEntitiesByQuery(totalActiveDevicesQuery);
System.out.println("Total devices by the second query: " + totalActiveDevicesCount);
        
// Perform logout of current user and close the client
client.logout();
client.close();
				
			

پرس‌وجو موجودیت‌ها با استفاده از Entity Data Query API

نمونه کد زیر نشان می‌دهد که چگونه می‌توان از Entity Data Query API برای دریافت تمام دستگاه‌های فعال استفاده کرد:

				
					// ThingsBoard REST API URL
String url = "http://localhost:8080";

// Perform login with default Customer User credentials
String username = "tenant@thingsboard.org";
String password = "tenant";
RestClient client = new RestClient(url);
client.login(username, password);

// Create entity filter to get only devices
EntityTypeFilter typeFilter = new EntityTypeFilter();
typeFilter.setEntityType(EntityType.DEVICE);

// Create key filter to query only active devices
KeyFilter keyFilter = new KeyFilter();
keyFilter.setKey(new EntityKey(EntityKeyType.ATTRIBUTE, "active"));
keyFilter.setValueType(EntityKeyValueType.BOOLEAN);

BooleanFilterPredicate filterPredicate = new BooleanFilterPredicate();
filterPredicate.setOperation(BooleanFilterPredicate.BooleanOperation.EQUAL);
filterPredicate.setValue(new FilterPredicateValue<>(true));

keyFilter.setPredicate(filterPredicate);

// Prepare list of queried device fields
List<EntityKey> fields = List.of(
        new EntityKey(EntityKeyType.ENTITY_FIELD, "name"),
        new EntityKey(EntityKeyType.ENTITY_FIELD, "type"),
        new EntityKey(EntityKeyType.ENTITY_FIELD, "createdTime")
);

// Prepare list of queried device attributes
List<EntityKey> attributes = List.of(
        new EntityKey(EntityKeyType.ATTRIBUTE, "active")
);

// Prepare page link
EntityDataSortOrder sortOrder = new EntityDataSortOrder();
sortOrder.setKey(new EntityKey(EntityKeyType.ENTITY_FIELD, "createdTime"));
sortOrder.setDirection(EntityDataSortOrder.Direction.DESC);
EntityDataPageLink entityDataPageLink = new EntityDataPageLink(10, 0, "", sortOrder);

// Create entity query with provided entity filter, key filter, queried fields and page link
EntityDataQuery dataQuery = 
        new EntityDataQuery(typeFilter, entityDataPageLink, fields, attributes, List.of(keyFilter));

PageData<EntityData> entityPageData;
do {
    // Fetch active devices using entities query and print them
    entityPageData = client.findEntityDataByQuery(dataQuery);
    entityPageData.getData().forEach(System.out::println);
    dataQuery = dataQuery.next();
} while (entityPageData.hasNext());

// Perform logout of current user and close client
client.logout();
client.close();
				
			

نمونه مدیریت دستگاه

نمونه کد زیر مفاهیم پایه‌ای API مدیریت دستگاه را نشان می‌دهد (اضافه کردن، دریافت، حذف دستگاه و دریافت/ذخیره ویژگی‌های دستگاه):

				
					// ThingsBoard REST API URL
String url = "http://localhost:8080";

// Perform login with default Customer User credentials
String username = "tenantg@thingsboard.org";
String password = "tenant";
RestClient client = new RestClient(url);
client.login(username, password);

// Construct device object
String newDeviceName = "Test Device";
Device newDevice = new Device();
newDevice.setName(newDeviceName);

// Create Json Object Node and set it as additional info
ObjectMapper mapper = new ObjectMapper();
ObjectNode additionalInfoNode = mapper.createObjectNode().put("description", "My brand new device");
newDevice.setAdditionalInfo(additionalInfoNode);

// Save device
Device savedDevice = client.saveDevice(newDevice);
System.out.println("Saved device: " + savedDevice);

// Find device by device id or throw an exception otherwise
Optional<DeviceInfo> optionalDevice = client.getDeviceInfoById(savedDevice.getId());
DeviceInfo foundDevice = optionalDevice
        .orElseThrow(() -> new IllegalArgumentException("Device with id " + newDevice.getId().getId() + " hasn't been found"));

// Save device shared attributes
ObjectNode requestNode = mapper.createObjectNode().put("temperature", 22.4).put("humidity", 57.4);
boolean isSuccessful = client.saveEntityAttributesV2(foundDevice.getId(), "SHARED_SCOPE", requestNode);
System.out.println("Attributes have been successfully saved: " + isSuccessful);

// Get device shared attributes
var attributes = client.getAttributesByScope(foundDevice.getId(), "SHARED_SCOPE", List.of("temperature", "humidity"));
System.out.println("Found attributes: ");
attributes.forEach(System.out::println);

// Delete the device
client.deleteDevice(savedDevice.getId());

// Perform logout of current user and close client
client.logout();
client.close();
				
			

نمونه‌های بیشتر

برای مشاهده نمونه‌های بیشتر و یادگیری نحوه استفاده از کلاینت REST ThingsConnect، می‌توانید به این لینک مراجعه کنید.

عناوین هر بخش