OneNET Internet of things platform 11 uses the API provided by OneNET platform to send commands to devices

Posted by TurtleDove on Thu, 24 Feb 2022 16:12:04 +0100

1. API introduction

Use the device command API provided by onenet platform to directly issue instructions to the device. When the device receives the instructions and responds, the API returns the response content of the device

Request API: POST

http://api.heclouds.com/v1/synccmds?device_id=866760442&timeout=30

The request body carries: user-defined command data content

  • device_id: device id
  • timeout: the maximum waiting time of the synchronization API. The value range is 5-30, in seconds

Return syntax obtained by the provider:

Content-type: application/json

{
    "errno": 0,
    "error": "success",
    "data": {
        "cmd_uuid": "3b6ab6e6-f729-4825-83e6-397d8c27c284",
        "cmd_resp": "cmVjZWl2ZSBjbWQuLi4="
    }
}

Return parameters:

  • errno: error code
  • Error: error description
  • cmd_uuid: Command ID
  • cmd_resp: device response content, base64 encoding format

Return error code

Error codeError descriptionexplain
12device not foundDevice does not exist
13device not onlineDevice not online
15sync cmd timeoutDevice command response timeout

Return error example

{
    "errno": 15,
    "error": "sync cmd timeout"
}

Use restrictions

  • The command request body data length must be less than 1k
  • When the device answers, the payload length must be less than 1k

2. New access URL tool class

package com.wzkj.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;

/**
 * HTTP tool
 *
 * @author hyh
 */
public class HttpUtils {
    /**
     * Send data to POST request path
     *
     * @param url     Request path
     * @param headers Request header
     * @param params  Request parameters
     * @return String
     */
    @SuppressWarnings("unchecked")
    public static String SendPost(String url, JSONObject headers, JSONObject params) {
        String ret = "";
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);

        for (Map.Entry<String, Object> entry : headers.entrySet()) {
            String key = entry.getKey();
            method.addRequestHeader(key, headers.getString(key));
        }

        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            method.addParameter(key, params.getString(key));
        }

        try {
            client.executeMethod(method);
            BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            StringBuffer stringBuffer = new StringBuffer();
            String str = "";
            while ((str = reader.readLine()) != null) {
                stringBuffer.append(str);
            }
            ret = stringBuffer.toString();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }

        return ret;
    }

    /**
     * Send data to POST request
     *
     * @param url     http address of sending device command
     * @param headers Request header
     * @param params  Request parameters
     * @return String Return results
     */
    @SuppressWarnings({"unchecked", "deprecation"})
    public static String SendPost(String url, net.sf.json.JSONObject headers, String params) {
        String ret = "";
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        Iterator<String> header = headers.keys();
        while (header.hasNext()) {
            String key = header.next();
            method.addRequestHeader(key, headers.getString(key));
        }

        method.setRequestBody(params);

        try {
            client.executeMethod(method);
            BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
            StringBuffer stringBuffer = new StringBuffer();
            String str = "";
            while ((str = reader.readLine()) != null) {
                stringBuffer.append(str);
            }
            ret = stringBuffer.toString();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }

        return ret;
    }
}

3. Generate access authorization method

This method is available in the demo. The token class is the class that generates authorization. In onenet, there are two kinds of tokens, one is the token of API access, and the other is the token of device connection.

There is a parameter resourceName in its main method. Different design formats can generate different access token s

sceneres parameter formatExamplesexplain
API accessproducts/{pid}products/123123
Device connectionproducts/{pid}/devices/{device_name}products/123123/devices/mydevDevice level key required

The current scenario is accessed using API, so the format of resourceName is products/{pid}

My product ID is 480701, and my accessKey is ZQjnxxt0B5Rrdn17Kzz11+UOM3UhJePYMYEgkHtXpV4 =. The code is as follows: change the productId and accessKey parameters to your own

public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    // Product ID of oneNet
    String productId = "480701";
    // Product access_key
    String accessKey = "ZQjnxxt0B5Rrdn17Kzz11+UOM3UhJePYMYEgkHtXpV4=";

    // Version number, no modification required
    String version = "2018-10-31";
    // API access resource
    String resourceName = "products/" + productId;
    // Access expiration time
    String expirationTime = System.currentTimeMillis() / 1000 + 100 * 24 * 60 * 60 + "";
    //Signature method, supporting md5, sha1 and sha256
    String signatureMethod = SignatureMethod.SHA1.name().toLowerCase();
    String token = assembleToken(version, resourceName, expirationTime, signatureMethod, accessKey);

    System.out.println("Authorization: " + token);
}

The token s generated after running are: version = 2018-10-31 & res = products% 2f480701 & ET = 1653707690 & method = SHA1 & sign = jahknkd6% 2fxuvbpva3fij3a% 2fotia% 3D

4. Access API

HttpUtils provides two ways to access URL s:

Method 1: the request header uses com alibaba. fastjson. Jsonobject. The request body is in JSON format

@Test
public void dispatchOrders(){
    String deviceId = "866760442";
    String token = "version=2018-10-31&res=products%2F480701&et=1712112818&method=sha1&sign=89dqMv4ygwfq5dUZXEHsv88m%2BGI%3D";

    JSONObject headers = new JSONObject();
    headers.put("Authorization", token);
    JSONObject jsonObject = new JSONObject();
    // Command parameters sent to the device
    jsonObject.put("color", "-101");

    String url = "http://api.heclouds.com/v1/synccmds?device_id=" + deviceId + "&timeout=30";
    System.out.println(jsonObject);
    String sendPost = HttpUtils.SendPost(url, headers, jsonObject);

    System.out.println(sendPost);
}

Method 2: the request header uses net sf. json. Jsonobject. The request body is in String format

@Test
public void dispatchOrders2(){
    net.sf.json.JSONObject headers = new net.sf.json.JSONObject();
    String token = "version=2018-10-31&res=products%2F480701&et=1712112818&method=sha1&sign=89dqMv4ygwfq5dUZXEHsv88m%2BGI%3D";
    headers.put("Authorization", token);

    String deviceId = "724860362";
    // Command parameters sent to the device
    String param = "0";

    String params = String.format("\"S1:%s\"", param);
    String url = "http://api.heclouds.com/v1/synccmds?device_id=" + deviceId + "&timeout=30";
    String sendPost = HttpUtils.SendPost(url, headers, params);

    System.out.println(sendPost);
}

Returned results after running:

The response content of the device is cmVjZWl2ZSBjbWQuLi4 =, base64 encoding format, and decrypted as: receive cmd, The translation is to receive orders

5. Parse request results

Add Base64 parsing tool class:

package com.yuyun.utils;

import sun.misc.BASE64Decoder;

import java.io.IOException;

/**
 * Base64 Tool class
 *
 * @author hyh
 */
public class Base64Utils {

    /**
     * Base64 decode
     *
     * @param bytes Base64 Encrypted bytecode
     * @return String
     * @throws IOException IOException
     */
    public static String Base64Decode(byte[] bytes)
            throws IOException {
        BASE64Decoder base64decoder = new BASE64Decoder();
        byte[] bs = base64decoder.decodeBuffer(new String(bytes));
        return new String(bs, "UTF-8");
    }
}

Resolve sendPost:

JSONObject sp = JSONObject.parseObject(sendPost);
int errno = sp.containsKey("errno") ? sp.getInteger("errno") : -1;
String error = sp.containsKey("error") ? sp.getString("error") : "";
if (errno != 0 && StringUtils.isNotBlank(error)) {
    System.out.println(error);
}
JSONObject data = sp.containsKey("data") ? sp.getJSONObject("data") : new JSONObject();
if (data.containsKey("cmd_resp")) {
    String cmdResp = data.getString("cmd_resp");
    try {
        String str = Base64Utils.Base64Decode(cmdResp.getBytes());

        System.out.println("Decoded cmd_resp: " + str);
    } catch (Exception e) {
        System.out.println("Decoding failed!");
    }
}

Output result:

Complete code

@Test
public void dispatchOrders() {
    String deviceId = "866760442";
    String token = "version=2018-10-31&res=products%2F480701&et=1712112818&method=sha1&sign=89dqMv4ygwfq5dUZXEHsv88m%2BGI%3D";

    JSONObject headers = new JSONObject();
    headers.put("Authorization", token);
    JSONObject jsonObject = new JSONObject();

    // Command parameters sent to the device
    jsonObject.put("color", "-101");

    String url = "http://api.heclouds.com/v1/synccmds?device_id=" + deviceId + "&timeout=30";
    System.out.println(jsonObject);
    String sendPost = HttpUtils.SendPost(url, headers, jsonObject);

    System.out.println(sendPost);

    JSONObject sp = JSONObject.parseObject(sendPost);
    int errno = sp.containsKey("errno") ? sp.getInteger("errno") : -1;
    System.out.println("errno:" + errno);

    String error = sp.containsKey("error") ? sp.getString("error") : "";
    System.out.println("error:" + error);

    if (errno != 0 && StringUtils.isNotBlank(error)) {
        System.out.println(error);
    }
    JSONObject data = sp.containsKey("data") ? sp.getJSONObject("data") : new JSONObject();
    System.out.println(data);

    if (data.containsKey("cmd_resp")) {
        String cmdResp = data.getString("cmd_resp");
        try {
            String str = Base64Utils.Base64Decode(cmdResp.getBytes());

            System.out.println("Decoded cmd_resp: " + str);
        } catch (Exception e) {
            System.out.println("Decoding failed!");
        }
    }
}

demo address: https://gitee.com/hyh17808770899/spring-boot/tree/master/springboot-onenet

Topics: IoT