ThingsBoard Java客户端

# ThgingsBoard

https://iothub.org.cn/docs/iot/
https://iothub.org.cn/docs/iot/api/api-java-client/

一、概述

1.工程配置

pom.xml

    <properties>
        <java.version>11</java.version>
    </properties>

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

    <repositories>
        <repository>
            <id>thingsboard</id>
            <url>https://repo.thingsboard.io/artifactory/libs-release-public</url>
        </repository>
    </repositories>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.iiotos</groupId>
    <artifactId>tb-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>tb-client</name>
    <description>tb-client</description>

    <properties>
        <java.version>11</java.version>
    </properties>

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

    <dependencies>
        <dependency>
            <groupId>org.thingsboard</groupId>
            <artifactId>rest-client</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

二、程序测试

1.客户端登录

public class Login {

    public static void main(String[] args) {
        // ThingsBoard REST API URL
        String url = "http://192.168.202.188:8080";

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

        // 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();
    }
}

在这里插入图片描述

2.租户设备

public class TenantDevice {

    public static void main(String[] args) {

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

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

        // 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();
    }
}

在这里插入图片描述

3.租户仪表板

public class TenantDashboard {

    public static void main(String[] args) {

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

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

        // 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();
    }
}

在这里插入图片描述

4.客户设备

public class CustomerDevice {

    public static void main(String[] args) {

        // ThingsBoard REST API URL
        String url = "http://192.168.202.188: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();
    }
}

在这里插入图片描述

5.实体计数

使用实体数据查询API对实体进行计数

下面的示例代码显示了如何使用实体数据查询API来计算设备总数、活动设备总数。

public class CountEntities {

    public static void main(String[] args) {

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

        // Perform login with default Customer User credentials
        String username = "tenant@thingsboard.org";
        String password = "tenant";
        //String username = "iiotos@thingsboard.org";
        //String password = "iiotos";

        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();
    }
}

在这里插入图片描述

6.查询实体

使用实体数据查询API查询实体

以下示例代码显示如何使用实体数据查询API获取所有活动设备。

public class QueryEntities {

    public static void main(String[] args) {

        // ThingsBoard REST API URL
        String url = "http://192.168.202.188: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();
    }
}

在这里插入图片描述

7.管理设备

管理设备示例

以下示例代码演示了设备管理API的基本概念(添加/获取/删除设备,获取/保存设备属性)。

public class ManageDevice {

    public static void main(String[] args) {

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

        // Perform login with default Customer User credentials
        //String username = "tenantg@thingsboard.org";
        //String password = "tenant";
        String username = "iiotos@thingsboard.org";
        String password = "iiotos";

        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();
    }
}

在这里插入图片描述

8.其他实例

public class RestClientExample {
    public static void main(String[] args) {
        // 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);

        // Creating an Asset
        Asset asset = new Asset();
        asset.setName("Building 1");
        asset.setType("building");
        asset = client.saveAsset(asset);

        // creating a Device
        Device device = new Device();
        device.setName("Thermometer 1");
        device.setType("thermometer");
        device = client.saveDevice(device);

        // creating relations from device to asset
        EntityRelation relation = new EntityRelation();
        relation.setFrom(asset.getId());
        relation.setTo(device.getId());
        relation.setType("Contains");
        client.saveRelation(relation);
    }
}
# ThgingsBoard

https://iothub.org.cn/docs/iot/
https://iothub.org.cn/docs/iot/api/api-java-client/
接触Thingsboard用得到!!! 目录 1  参考资料 5  文档目的 6 第一章 项目框架整理说明 7 1.1 项目框架说明 7 1.1.1 package包功能描述 8 1.1.2 thingsboard开发主要涉及到的包 10 1.1.3 thingsboard代码类及接口说明 10 第二章 thingsboard涉及到的流程图 12 2.1 物联网网关架构 12 2.2 ThingsBoard微服务架构 13 2.3 Thingsboard产品架构 13 2.4 Thingsboard规则引擎 14 2.5 ThingsBoard Architecture 15 第三章 项目框架涉及到的第三方包或插件 17 3.1 Thingsboard 包 17 第四章 ThingsBoard设备连接协议 23 4.1 订阅消息传递协议(MQTT) 23 4.2 请求响应模式(CoAP) 23 4.3 请求响应模式(HTTP ) 24 第五章 ThingsBoard打包 25 5.1 后端打包 25 5.2 前端打包方UI 25 第六章 ThingsBoard框架日志 26 第七章 ThingsBoard数据库 目录 目录 1  参考资料 5  文档目的 6 第一章 项目框架整理说明 7 第二章 thingsboard涉及到的流程图 12 第三章 项目框架涉及到的第三方包或插件 17 第四章 ThingsBoard设备连接协议 23 第五章 ThingsBoard打包 25 第六章 ThingsBoard框架日志 26 第七章 ThingsBoard数据库 27 第八章 官网主要文档目录 28 第九章 前端技术概述 29 第十章 关于Thingsboard开发环境部署 30 第十一章 数据库表结构 32 错误!未定义书签。 7.1 关系数据库(使用了2个数据库) 27 7.2 非关系数据库(redis) 27 第八章 官网主要文档目录 28 第九章 前端技术概述 29 9.1 前端包括哪些技术点 29 9.2 前端技术描述 29 第十章 关于Thingsboard开发环境部署 30 第十一章 数据库表结构 32
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IoTHub - 物联网开源技术社区

支持开源技术! 传播开源文化!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值