更新时间:2023-04-07 GMT+08:00
分享

Agent Lite SDK使用指南(Java)(联通用户专用)

非联通用户请查看设备接入服务

按照本文档的指导,开发者可以体验直连设备通过集成Agent Lite快速接入平台,体验“数据上报”“命令接收”“添加非直连设备”等功能。

Agent Lite以SDK的形式嵌入第三方软件中。本文档以Agent Lite Java Demo为例,指导开发者使用Agent Lite SDK中的接口,实现“直连设备登录”“数据上报”“命令下发”等功能。

  • 开发者可以基于Agent Lite Java Demo开发,也可参考Agent Lite Java Demo,自行集成Agent Lite SDK(Java)。
  • Agent Lite java Demo使用的IDE工具为Eclipse

使用必读

开发环境要求

使用的SDK版本为jdk1.8.0_45,适用的操作系统为Windows系统。

工程目录结构及文件说明:

目录结构

目录

说明

AgentLiteDemo

├─src

│ └─com

│ └─huawei

│ └─agentlitedemo

├─libs

│ └─agentlite-0.0.1-SNAPSHOT

│ └─usp_agentlite.jar

│ └─.dll

└─workdir

│ └─conf

src

存放Agentlite Demo代码。

libs

存放Agentlite提供的jar包和第三方jar包,以及.dll动态库(工程必须的三个文件,“agentlite-0.0.1-SNAPSHOT”“usp_agentlite.jar”“.dll”文件)。

workdir

存放工程日志文件,由agentlite初始化资源设置。

conf

存放TLS证书文件。

如果开发者没有设备,可以直接在X86 Linux系统进行开发。

导入代码样例

  1. Agent Lite Demo(Java)解压到本地。

  2. 导入AgentLiteDemo工程。

    • 打开Eclipse,单击File > Import进入导入现有工程界面。
    • 选择General > Existing Projects into Workspace ,点击“Next”

    • 点击“Browse”,选择AgentLiteDemo解压后的路径,点击“Finish”

初始化

在发起业务前,需要先初始化Agent Lite相关资源,调用API接口BaseService.init(),初始化Agent Lite资源,具体API的参数使用参考Agent Lite API接口文档。

调用BaseService.init(String workPath, String logPath)初始化AgentLite资源。

1
res = BaseService.init("./workdir", null);

绑定和登录

设备或网关第一次接入物联网平台时需要进行绑定操作,从而将设备或网关与平台进行关联。开发者通过传入设备验证码以及设备信息,将设备或网关绑定到物联网平台。

  1. 修改绑定参数。

    绑定时使用的设备固有信息(如设备型号等)是从“AgentLiteBind.java”文件中读取的,所以需要修改./src/main目录下“AgentLiteBind.java”文件中的如下信息:

    物联网平台的设备对接地址(MQTTS)和端口,可参考平台对接信息获取。

    1
    2
    3
    //设置配置参数
    private static final String  PLATFORM_IP = "100.100.100.100";
    private static final String  HTTPS_PORT = "8943";
    
    “verifyCode”(设备验证码)和必要的设备信息,包括“nodeId”(设备标识码)、“manufactureId”(厂商Id)、“deviceType”(设备类型)、“model”(设备模型)和“protocolType”(协议类型)。“verifyCode”的值与“nodeId”保持一致,“manufactureId”(厂商Id)、“deviceType”(设备类型)、“model”(设备模型)和“protocolType”(协议类型)与Profile文件中的定义保持一致。
    • 如果开发者通过“设备管理服务控制台”注册设备,则“verifyCode”填写为设备注册时的“preSecret”(预置密钥)。
    • 如果通过开发中心注册设备,则“verifyCode”填写为设备注册时设置的“nodeId”(设备标识)。
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    public void bindAction() {
    	System.out.println(" =============   start  bind ============== ");
    	String nodeId = "1234568";
    	String verifyCode = "1234568";
    	String manufactrueId = "Huawei";
    	String deviceType = "Gateway";
    	String model = "AgentLite01";
    	String protocolType = "LWM2M";
    	deviceInfo = new IotaDeviceInfo(nodeId, manufactrueId, deviceType, model, protocolType);
            ...
    }
    

  2. 绑定设备。

    注册观察者对设备绑定结果进行相应处理。

    1
    2
    3
    4
    5
    6
    //注册观察者
    AgentLiteBind agentLiteBind = AgentLiteBind.getInstance();
    BindService bindService = BindService.getInstance();
    bindService.registerObserver(agentLiteBind);
    //网关绑定
    agentLiteBind.bindAction();
    

    调用API接口BindConfig.setConfig()设置绑定配置,接着调用API接口BindService .bind(String verifyCode, IotaDeviceInfo deviceInfo)绑定设备。

    1
    2
    3
    4
    5
    6
    7
    8
    public void bindAction() {
        System.out.println(" =============   start  bind ============== ");
        ...
        //绑定配置
        configBindPara();
        //发起绑定请求
        BindService.bind(verifyCode, deviceInfo);
    }
    
    1
    2
    3
    4
    5
    6
    7
    //绑定配置
    private static void configBindPara() {
    	boolean res = false;
    	res = BindConfig.setConfig(BindConfig.BIND_CONFIG_ADDR, PLATFORM_IP);
    	res = BindConfig.setConfig(BindConfig.BIND_CONFIG_PORT, HTTPS_PORT);
    	...		
    }
    

    设备或网关绑定成功,后续就不需要再绑定了,除非设备或网关被删除,才需要重新绑定。

    设备绑定成功会收到BindService发出的通知,通知内容请参考Agent Lite API接口文档中设备绑定接口的返回结果说明和demo中update函数的处理。

  3. 修改登录参数。

    在demo的./src/main/AgentLiteLogin.java设置物联网平台的接入IP与端口。

    1
    2
    3
    private static final String  PLATFORM_IP = "100.100.100.100";
    private static final String  MQTTS_PORT = "8883";
    private static final String  HTTPS_PORT = "8943";
    

  4. 设备登录。

    注册观察者对设备登录结果进行相应处理。

    1
    2
    3
    4
    5
    6
    //注册观察者
    AgentLiteLogin agentLiteLogin = AgentLiteLogin.getInstance();
    LoginService loginService = LoginService.getInstance();
    loginService.registerObserver(agentLiteLogin);
    //网关登录
    agentLiteLogin.loginAction();
    

    调用API接口LoginConfig.setConfig()传入所需的登录信息,接着调用API接口LoginService.login()进行直连设备登录,具体API的参数使用参考Agent Lite接口文档中的设备登录接口说明。

    • “设备Id”(即网关Id, “LOGIN_CONFIG_DEVICEID”),“appId”“LOGIN_CONFIG_APPID”)和“密码”“LOGIN_CONFIG_SECRET”),这些信息是都是从网关绑定成功的通知中得到的。
    • “平台HTTP地址”“LOGIN_CONFIG_IOCM_ADDR”)和“MQTT地址”“LOGIN_CONFIG_MQTT_ADDR”)一般是同一个地址。
    1
    2
    3
    4
    5
    public void loginAction() {
        System.out.println(" =============   start  login ============== ");
        configLoginPara();
        LoginService.login();		
    }
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    private static void configLoginPara() {
        if(AgentLiteUtil.isStringEmpty(GatewayInfo.getDeviceID())
                    || AgentLiteUtil.isStringEmpty(GatewayInfo.getAppID())
                    || AgentLiteUtil.isStringEmpty(GatewayInfo.getSecret())){
            String jsonStr = AgentLiteUtil.readToString("./workdir/gwbindinfo.json");
            JsonObject json = new Gson().fromJson(jsonStr, JsonObject.class);
            GatewayInfo.setDeviceID(json.get("deviceId").getAsString());
            GatewayInfo.setAppID(json.get("appId").getAsString());
            GatewayInfo.setSecret(json.get("deviceSecret").getAsString());
        }
        LoginConfig.setConfig(LoginConfig.LOGIN_CONFIG_DEVICEID,  GatewayInfo.getDeviceID());
        LoginConfig.setConfig(LoginConfig.LOGIN_CONFIG_APPID, GatewayInfo.getAppID());
        LoginConfig.setConfig(LoginConfig.LOGIN_CONFIG_SECRET, GatewayInfo.getSecret());
        LoginConfig.setConfig(LoginConfig.LOGIN_CONFIG_IOCM_ADDR, PLATFORM_IP);
        LoginConfig.setConfig(LoginConfig.LOGIN_CONFIG_IOCM_PORT, HTTPS_PORT);
        LoginConfig.setConfig(LoginConfig.LOGIN_CONFIG_MQTT_ADDR, PLATFORM_IP);
        LoginConfig.setConfig(LoginConfig.LOGIN_CONFIG_MQTT_PORT, MQTTS_PORT);
    }
    

上传Profile并注册设备

下载Profile开发示例,并上传模板中的profile文件:“Gateway_Huawei_AgentLite01.zip”“Motion_Huawei_test01.zip”

  1. 登录开发中心,创建一个项目,在该项目空间内,选择产品 > 产品开发,点击“新建产品”

  2. “创建产品”中,选择“本地导入产品创建”,单击“上传Profile”上传“Gateway_Huawei_AgentLite01.zip”“Motion_Huawei_test01.zip”

  3. 选择产品 > 设备管理,单击“添加真实设备”,进入“新建增实设备”页面。

  4. 根据向导注册设备。

    1. 选择产品。

      产品:AgentLite001

    2. 填写设备相关信息,单击“确定”
      • 设备名称:AgentLiteDevice
      • 设备标识:aaa123456,需要与AgentLiteDemo中网关的设备标识一致。
      • 接入方式:网关(Agentlite)

  5. 注册设备后,Agent Lite SDK发送bind消息,则在开发中心的产品 > 设备管理 > 设备列表界面可以看到设备状态变成“在线”

    如果demo日志中出现“Iota_BindDestroy”,说明Agent Lite SDK多次发送bind消息,并且没有收到正确响应,设备绑定已超时。这时需要再次运行“sdk.out”程序(先用“ctrl+c”退出,再用“./sdk.out”运行程序),Agent Lite SDK就会再发起bind消息。平台收到正确的bind消息后设备就会变成“在线”状态。

数据上报和数据发布

设备或网关向物联网平台上报数据可以通过调用SDK的“设备服务数据上报”接口或“数据发布”接口:

  • “设备服务数据上报”接口:deviceId,requstId和serviceId由SDK组装为消息的header;serviceProperties由SDK组装为消息的body。消息组装格式为JSON。

    注册观察者对网关数据上报结果进行相应处理。

    1
    2
    3
    4
    5
    6
    //注册观察者
    AgentLiteDataTrans agentLiteDataTrans = AgentLiteDataTrans.getInstance();
    DataTransService dataTransService = DataTransService.getInstance();
    dataTransService.registerObserver(agentLiteDataTrans);
    //数据上报
    agentLiteDataTrans.gwDataReport();
    

    设备或网关登录成功后可以调用DataTransService.dataReport(int cookie, String requstId, String deviceId, String serviceId, String serviceProperties)接口上报数据。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    public void gwDataReport() {
        System.out.println(" =============   gwDataReport! ============== ");
        int cookie;
        Random random = new Random();
        cookie = random.nextInt(65535);
    
        String deviceId = GatewayInfo.getDeviceID();
    
        JsonObject data = new JsonObject();
        data.addProperty("storage", "10240");
        data.addProperty("usedPercent", "20");
        DataTransService.dataReport(cookie, null, deviceId, "Storage", data.toString());
    }
    

    数据上报成功后可以在设备的“历史数据” 中看到上报的数据了。

  • “数据发布”接口:topic固定为“/cloud/signaltrans/v2/categories/data”“serviceData”参数作为消息体(包括header和body),SDK只进行透传,不进行格式调整和组装。

    注册观察者对网关数据上报结果进行相应处理。

    1
    2
    3
    4
    5
    6
    //注册观察者
    AgentLiteDataTrans agentLiteDataTrans = AgentLiteDataTrans.getInstance();
    DataTransService dataTransService = DataTransService.getInstance();
    dataTransService.registerObserver(agentLiteDataTrans);
    //数据发布
    agentLiteDataTrans.gwDataReportByMqttDataPub();
    

    设备或网关登录成功后可以调用DataTransService. mqttDataPub(int cookie, String topic, int qos, byte[] serviceData)接口发布数据。

    • “topic”是要发布数据的topic。
    • “qos”是mqtt协议的一个参数。
    • “serviceData”实际上是一个json字符串,内容是健值对(可以有多组健值对)。每个健是profile中定义的属性名(propertyName),值就是具体要上报的内容了。
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    public void gwDataReportByMqttDataPub() {
        System.out.println(" =============   gwDataReportByMqttDataPub! ============== ");
        int cookie;
        Random random = new Random();
        cookie = random.nextInt(65535);
    
        String deviceId = GatewayInfo.getDeviceID();
    
        JsonObject headerData = new JsonObject();
        headerData.addProperty("method", "PUT");
        String fromStr = "/device/"+deviceId+"/services/Storage";
        String toStr = "/data/v1.1.0/devices/"+deviceId+"/services/Storage";
        headerData.addProperty("from", fromStr);
        headerData.addProperty("to", toStr);
    
        headerData.addProperty("access_token", GatewayInfo.getAccessToken());
    
        SimpleDateFormat df = new SimpleDateFormat(MSG_TIMESTAMP_FORMAT);
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        String curTime = df.format(new Date(System.currentTimeMillis()));
        headerData.addProperty("timestamp", curTime);
        headerData.addProperty("eventTime", curTime);
    
        JsonObject bodyData = new JsonObject();
        bodyData.addProperty("storage", "10240");
        bodyData.addProperty("usedPercent", "18");
    
        JsonObject mqttMsg = new JsonObject();
        mqttMsg.add("header", headerData);
        mqttMsg.add("body", bodyData);
    
        DataTransService.mqttDataPub(cookie, "/cloud/signaltrans/v2/categories/data", 1, mqttMsg.toString().getBytes());
    }
    

命令接收

当开发者希望设备或网关只接收topic为“/gws/deviceid/signaltrans/v2/categories/”的消息,且对消息中的header进行解析时,可以调用“设备命令接收”接口。

应用服务器可以调用物联网平台的应用侧API接口给设备或网关下发命令,所以网关得随时监听命令下发的广播,以便接收到命令时进行相应业务处理。

注册观察者对命令接收进行相应处理。

1
2
3
4
5
6
//注册观察者
AgentLiteDataTrans agentLiteDataTrans = AgentLiteDataTrans.getInstance();
DataTransService dataTransService = DataTransService.getInstance();
dataTransService.registerObserver(agentLiteDataTrans);
//命令接收
agentLiteDataTrans.getCmdReceive();

被动接收命令的方法getCmdReceive

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
private void getCmdReceive(IotaMessage iotaMsg) {
    System.out.println("=========receive iotCMD ============");
    String deviceId = iotaMsg.getString(DataTransService.DATATRANS_IE_DEVICEID);
    String requestId = iotaMsg.getString(DataTransService.DATATRANS_IE_REQUSTID);
    String serviceId = iotaMsg.getString(DataTransService.DATATRANS_IE_SERVICEID);
    String method = iotaMsg.getString(DataTransService.DATATRANS_IE_METHOD);
    String cmd = iotaMsg.getString(DataTransService.DATATRANS_IE_CMDCONTENT);
    if (method.equals("REMOVE_GATEWAY")) {
        //rmvGateway(context);
    }
    System.out.println ("Receive cmd :"
                    + "ndeviceId  = " + deviceId
                    + "nrequestId = " + requestId
                    + "nserviceId = " + serviceId
                    + "nmethod    = " + method
                    + "ncmd       = " + cmd);
}

添加非直连设备

在添加非直连设备前,确认非直连设备的profile已经上传了,详见上传Profile并注册设备步骤。

修改非直连设备信息,包括“nodeId”(设备标识码)、“manufactureId”(厂商Id)、“deviceType”(设备类型)、“model”(设备模型)和“protocolType”(协议类型)。这里非直连设备的设备固有信息是测试数据,真实情况下,网关往往需要跟具体的非直连设备交互,才能得到具体的设备固有信息。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public void addSensor() {
    System.out.println(" ============= addSensor! ============== ");
    int cookie;
    Random random = new Random();
    cookie = random.nextInt(65535);

    String nodeId = "5432154321";
    String manufatrueId = "Huawei";
    String deviceType = "Motion";
    String model = "test01";
    String protocolType = "MQTT";
    deviceInfo = new IotaDeviceInfo(nodeId, manufatrueId, deviceType, model, protocolType);
    ...
}

注册观察者对添加设备结果进行相应处理。

1
2
3
4
5
6
//注册观察者
AgentLiteHub agentLiteHub = AgentLiteHub.getInstance();
HubService hubService = HubService.getInstance();
hubService.registerObserver(agentLiteHub);
//sensor添加
agentLiteHub.addSensor();

在设备或网关登录成功后就可以调用HubService.addDevice(int cookie, IotaDeviceInfo deviceInfo)接口添加非直连设备。添加非直连设备成功后就能从广播中得到非直连设备的“deviceId”

1
2
3
4
5
6
7
8
public void addSensor() {
    System.out.println(" ============= addSensor! ============== ");
    int cookie;
    Random random = new Random();
    cookie = random.nextInt(65535);
    ...
    HubService.addDevice(cookie, deviceInfo);
}

非直连设备添加成功后在“设备列表”中看到新增一条记录。

非直连设备状态更新

注册观察者对非直连设备状态更新结果进行相应处理。

1
2
3
4
5
6
//注册观察者
AgentLiteHub agentLiteHub = AgentLiteHub.getInstance();
HubService hubService = HubService.getInstance();
hubService.registerObserver(agentLiteHub);
//sensor状态更新
agentLiteHub.updataDeviceStatus();

非直连设备添加上时,一般情况下是“离线”状态。所以在非直连设备添加成功后,或者在非直连设备上报数据前,要调用HubService.updateDeviceStatus(int cookie, String deviceId, String status, String statusDetail)进行设备状态更新。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public void updataDeviceStatus() {
	System.out.println(" =============  updataDeviceStatus  ============== ");
    int cookie;
    Random random = new Random();
    cookie = random.nextInt(65535);
    String sensorId = GatewayInfo.getSensorId();
    System.out.println("cookie = " + cookie);
    System.out.println("sensorId = " + sensorId);

    HubService.updateDeviceStatus(cookie, sensorId, "ONLINE", "NONE");
}

非直连设备数据上报

请参考数据上报和数据发布章节,调用DataTransService.dataReportDataTransService. mqttDataPub接口进行数据上报,各个参数使用非直连设备的相关数据即可,此处不再复述。

设备数据上报成功后,可以在非直连设备的“历史数据”中查看上报的数据。

分享:

    相关文档

    相关产品