Skip to content

Java SDK使用指南

概述

本文档介绍Universal IoT Platform的Java SDK使用方法,包括SDK安装、API调用、示例代码等内容。

功能特性

  • 🔧 设备管理: 支持设备的注册、查询、更新和删除
  • 📡 设备通信: 支持设备上线、下线状态管理
  • 📊 数据上报: 支持属性上报和事件上报
  • 🔐 安全认证: 支持OAuth2客户端认证和密码认证
  • 🛠️ 易于集成: 提供简洁的API接口,易于集成到现有系统

环境要求

  • Java 8 或更高版本
  • Maven 3.6+ 或 Gradle 6.0+
  • 网络连接(用于访问IoT平台API)

快速开始

1. 添加依赖

Maven

xml
<dependency>
    <groupId>cc.teambee</groupId>
    <artifactId>universal-iot-openapi-sdk</artifactId>
    <version>1.0.0</version>
</dependency>

2. 配置认证信息

src/main/resources/config/ 目录下创建 uiot.properties 文件:

properties
# 服务地址
universal.iot.host=host:port

# 客户端认证参数
universal.iot.clientId=your-client-id
universal.iot.clientSecret=your-client-secret

# 密码认证参数(可选)
universal.iot.username=your-username
universal.iot.password=your-password

# 认证类型:password 或 client_credentials
universal.iot.grantType=client_credentials

3. 创建IoT客户端

java
import cc.teambee.iot.http.IoTClient;
import cc.teambee.iot.http.IoTClientImpl;
import cc.teambee.iot.common.exception.ClientException;

public class IoTExample {
    public static void main(String[] args) {
        try {
            // 创建IoT客户端
            IoTClient iotClient = new IoTClientImpl();

            // 使用客户端进行操作...

        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

API 使用指南

设备注册(添加)

设备注册是使用SDK的第一步,需要提供设备的基本信息。

java
import cc.teambee.iot.entity.v2025.CreateDeviceRequest;

// 创建设备注册请求
String productKey = "your-product-key";
CreateDeviceRequest request = new CreateDeviceRequest(productKey);

// 设置设备基本信息
request.setDeviceId("device-001");
request.setDeviceName("智能传感器");
request.setLatitude("31.207561");
request.setLongitude("120.23475");

// 可选:添加自定义数据
request.addData("entity", "123456");

// 执行注册
String result = iotClient.register(request);
System.out.println("设备注册结果: " + result);

必填参数:

  • deviceId: 设备唯一标识符
  • deviceName: 设备名称
  • latitude: 设备纬度
  • longitude: 设备经度

可选参数:

  • ignoreRepeat: 是否忽略重复注册
  • detail: 设备备注信息
  • code: 摄像头类设备验证码
  • deviceKey: 设备密钥

设备上线

设备上线表示设备已连接到IoT平台,可以开始接收和发送数据。

java
import cc.teambee.iot.entity.GeneralResponse;

// 设备上线
GeneralResponse response = iotClient.online(productKey, deviceId);

if (response.getCode() == 0) {
    System.out.println("设备上线成功");
} else {
    System.out.println("设备上线失败: " + response.getMessage());
}

属性上报

属性上报用于向平台报告设备的当前状态和属性值。

java
import java.util.HashMap;
import java.util.Map;

// 构建属性数据
Map<String, Object> properties = new HashMap<>();
properties.put("temperature", 25.5);
properties.put("humidity", 60.0);
properties.put("switchStatus", 1);

// 上报属性
GeneralResponse response = iotClient.reportProperties(productKey, deviceId, properties);

if (response.getCode() == 0) {
    System.out.println("属性上报成功");
} else {
    System.out.println("属性上报失败: " + response.getMessage());
}

事件上报

事件上报用于向平台报告设备发生的特定事件。

java
// 构建事件数据
Map<String, Object> eventData = new HashMap<>();
eventData.put("alarmLevel", "high");
eventData.put("alarmMessage", "温度过高");

// 上报事件
GeneralResponse response = iotClient.reportEvent(
    productKey,
    deviceId,
    "temperatureAlarm",
    eventData
);

if (response.getCode() == 0) {
    System.out.println("事件上报成功");
} else {
    System.out.println("事件上报失败: " + response.getMessage());
}

设备查询

查询设备的详细信息。

java
// 查询设备信息
GeneralResponse response = iotClient.query(productKey, deviceId);

if (response.getCode() == 0) {
    System.out.println("设备信息: " + response.getResult());
} else {
    System.out.println("查询失败: " + response.getMessage());
}

设备更新

更新设备的基本信息,如名称、位置、备注等。

java
import cc.teambee.iot.entity.v2025.UpdateDeviceRequest;

// 创建更新请求
UpdateDeviceRequest updateRequest = new UpdateDeviceRequest(productKey, deviceId);

// 设置更新信息
updateRequest.setDeviceName("更新后的设备名称");
updateRequest.setLatitude("31.207562");
updateRequest.setLongitude("120.23476");
updateRequest.setDetail("设备备注信息");

// 执行更新
GeneralResponse response = iotClient.update(updateRequest);

if (response.getCode() == 0) {
    System.out.println("设备更新成功");
} else {
    System.out.println("设备更新失败: " + response.getMessage());
}

设备删除

从IoT平台删除设备。

java
// 删除设备
GeneralResponse response = iotClient.delete(productKey, deviceId);

if (response.getCode() == 0) {
    System.out.println("设备删除成功");
} else {
    System.out.println("设备删除失败: " + response.getMessage());
}

完整示例

以下是一个完整的设备生命周期管理示例:

java
import cc.teambee.iot.http.IoTClient;
import cc.teambee.iot.http.IoTClientImpl;
import cc.teambee.iot.entity.GeneralResponse;
import cc.teambee.iot.entity.v2025.CreateDeviceRequest;
import cc.teambee.iot.entity.v2025.UpdateDeviceRequest;
import cc.teambee.iot.common.exception.ClientException;
import java.util.HashMap;
import java.util.Map;

public class IoTDeviceLifecycleExample {

    private static final String PRODUCT_KEY = "your-product-key";
    private static final String DEVICE_ID = "test-device-001";

    public static void main(String[] args) {
        try {
            // 1. 创建IoT客户端
            IoTClient iotClient = new IoTClientImpl();

            // 2. 注册设备
            registerDevice(iotClient);

            // 3. 设备上线
            onlineDevice(iotClient);

            // 4. 上报属性
            reportProperties(iotClient);

            // 5. 上报事件
            reportEvent(iotClient);

            // 6. 查询设备信息
            queryDevice(iotClient);

            // 7. 更新设备信息
            updateDevice(iotClient);

            // 8. 删除设备
            deleteDevice(iotClient);

        } catch (ClientException e) {
            System.err.println("IoT操作失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void registerDevice(IoTClient iotClient) throws ClientException {
        CreateDeviceRequest request = new CreateDeviceRequest(PRODUCT_KEY);
        request.setDeviceId(DEVICE_ID);
        request.setDeviceName("测试设备");
        request.setLatitude("31.207561");
        request.setLongitude("120.23475");
        request.setIgnoreRepeat(true);

        String result = iotClient.register(request);
        System.out.println("设备注册成功: " + result);
    }

    private static void onlineDevice(IoTClient iotClient) throws ClientException {
        GeneralResponse response = iotClient.online(PRODUCT_KEY, DEVICE_ID);
        if (response.getCode() == 0) {
            System.out.println("设备上线成功");
        }
    }

    private static void reportProperties(IoTClient iotClient) throws ClientException {
        Map<String, Object> properties = new HashMap<>();
        properties.put("temperature", 25.5);
        properties.put("humidity", 60.0);

        GeneralResponse response = iotClient.reportProperties(PRODUCT_KEY, DEVICE_ID, properties);
        if (response.getCode() == 0) {
            System.out.println("属性上报成功");
        }
    }

    private static void reportEvent(IoTClient iotClient) throws ClientException {
        Map<String, Object> eventData = new HashMap<>();
        eventData.put("alarmLevel", "medium");
        eventData.put("alarmMessage", "温度异常");

        GeneralResponse response = iotClient.reportEvent(PRODUCT_KEY, DEVICE_ID, "temperatureAlarm", eventData);
        if (response.getCode() == 0) {
            System.out.println("事件上报成功");
        }
    }

    private static void queryDevice(IoTClient iotClient) throws ClientException {
        GeneralResponse response = iotClient.query(PRODUCT_KEY, DEVICE_ID);
        if (response.getCode() == 0) {
            System.out.println("设备信息: " + response.getResult());
        }
    }

    private static void updateDevice(IoTClient iotClient) throws ClientException {
        UpdateDeviceRequest updateRequest = new UpdateDeviceRequest(PRODUCT_KEY, DEVICE_ID);
        updateRequest.setDeviceName("更新后的测试设备");
        updateRequest.setDetail("设备已更新");

        GeneralResponse response = iotClient.update(updateRequest);
        if (response.getCode() == 0) {
            System.out.println("设备更新成功");
        }
    }

    private static void deleteDevice(IoTClient iotClient) throws ClientException {
        GeneralResponse response = iotClient.delete(PRODUCT_KEY, DEVICE_ID);
        if (response.getCode() == 0) {
            System.out.println("设备删除成功");
        }
    }
}

认证方式

SDK支持两种认证方式:

1. 客户端认证 (Client Credentials)

适用于服务间调用,使用客户端ID和密钥进行认证。

properties
universal.iot.grantType=client_credentials
universal.iot.clientId=your-client-id
universal.iot.clientSecret=your-client-secret

2. 密码认证 (Password)

适用于用户登录场景,使用用户名和密码进行认证。

properties
universal.iot.grantType=password
universal.iot.username=your-username
universal.iot.password=your-password
universal.iot.pwdClientId=your-pwd-client-id
universal.iot.pwdClientSecret=your-pwd-client-secret

错误处理

SDK可能抛出的异常类型:

ClientException

客户端异常,通常由以下原因引起:

  • 网络连接失败
  • 认证信息错误
  • 请求参数无效
java
try {
    IoTClient iotClient = new IoTClientImpl();
    // 执行操作...
} catch (ClientException e) {
    System.err.println("客户端异常: " + e.getMessage());
    // 处理异常...
}

ServerException

服务器异常,通常由以下原因引起:

  • 服务器内部错误
  • API调用频率超限
  • 服务器维护
java
try {
    // 执行操作...
} catch (ServerException e) {
    System.err.println("服务器异常: " + e.getMessage());
    // 处理异常...
}

最佳实践

1. 异常处理

始终使用try-catch块包装SDK调用,并适当处理异常。

2. 资源管理

确保在应用关闭时正确释放资源。

3. 重试机制

对于网络相关的操作,建议实现重试机制。

java
public class IoTClientWithRetry {
    private static final int MAX_RETRIES = 3;
    private static final long RETRY_DELAY = 1000; // 1秒

    public static GeneralResponse onlineWithRetry(IoTClient client, String productKey, String deviceId) {
        for (int i = 0; i < MAX_RETRIES; i++) {
            try {
                return client.online(productKey, deviceId);
            } catch (ClientException e) {
                if (i == MAX_RETRIES - 1) {
                    throw e;
                }
                try {
                    Thread.sleep(RETRY_DELAY);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new ClientException("重试被中断", e);
                }
            }
        }
        throw new ClientException("重试次数已用完");
    }
}

4. 日志记录

建议使用日志框架记录SDK操作,便于问题排查。

java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IoTService {
    private static final Logger logger = LoggerFactory.getLogger(IoTService.class);

    public void registerDevice(String deviceId, String deviceName) {
        try {
            logger.info("开始注册设备: {}", deviceId);
            // 执行注册操作...
            logger.info("设备注册成功: {}", deviceId);
        } catch (Exception e) {
            logger.error("设备注册失败: {}", deviceId, e);
            throw e;
        }
    }
}

5. 配置管理

将配置信息外部化,便于不同环境的部署。

java
public class IoTConfig {
    private String host;
    private String clientId;
    private String clientSecret;
    private String grantType;

    // 从配置文件或环境变量加载配置
    public static IoTConfig load() {
        // 实现配置加载逻辑
        return new IoTConfig();
    }
}

常见问题

Q1: 如何获取产品密钥 (productKey)?

A: 产品密钥需要在IoT平台的 北向应用 创建产品后获得,请联系平台管理员获取。

Q2: 设备ID可以重复吗?

A: 设备ID在同一产品下必须唯一,建议使用有意义的标识符。

Q3: 如何处理网络超时?

A: 建议实现重试机制,并设置合理的超时时间。

Q4: 支持哪些数据类型的属性上报?

A: 支持基本数据类型(String、Integer、Double、Boolean等)和复杂对象。

Q5: 如何批量操作设备?

A: 目前SDK支持单个设备操作,批量操作需要循环调用API。

技术支持

如果您在使用过程中遇到问题,可以通过以下方式获取帮助:

  • 💬 社区: 加入开发者社区讨论
  • 🐛 问题反馈: 在GitHub上提交Issue

更新日志

v1.0.0

  • 初始版本发布
  • 支持设备生命周期管理
  • 支持属性上报和事件上报
  • 支持OAuth2认证

本文档基于 Universal IoT SDK v1.0.0 编写,如有更新请参考最新版本文档。