业务侧调用设备服务样例

package yourpackage;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import okhttp3.*;
// 本样例涉及两个物联网平台开放接口
// 1. 获取JWT https://www.thingshub.com.cn/openapi/v2/token/jwt/create
// 2. 异步调用设备服务 https://www.thingshub.com.cn/openapi/v2/function/InvokeCustomizedService
@Slf4j
public class InvokeServiceSample {
  public static void main(String[] args) {
    // 调用设备服务 endpoint
    String url = "https://www.thingshub.com.cn/openapi/v2/function/InvokeCustomizedService";

    OkHttpClient client = new OkHttpClient(); // http client

    ObjectMapper objectMapper = new ObjectMapper();
    String productKey = "your ProductKey"; // ProductKey
    String deviceName = "your DeviceName"; // DeviceName 
    String identifier = "your service identifier"; // 服务标识
    Integer deviceAddr = 246;

    // 这是业务侧需要传给设备的控制指令参数
    Map<String, Object> params = new HashMap<>();
    params.put("deviceName", deviceName);
    params.put("device_addr", deviceAddr);
    params.put("timestamp", System.currentTimeMillis());
    params.put("seq_id", RandomUtil.randomInt(10000, 99999));

    try {
      String jwt = getJwt(client); // 获得 调用服务使用的 JWT
      if (jwt == null) {
        log.error("获取jwt失败");
        return;
      }
      String json = objectMapper.writeValueAsString(params);
      log.info(json); // 发送给设备的控制指令

      FormBody body =
          new FormBody.Builder()
              .add("requestId", UUID.randomUUID().toString())
              .add("productKey", productKey)
              .add("deviceName", deviceName)
              .add("identifier", identifier)
              .addEncoded("args", json)
              .build();

      Headers headers =
          new Headers.Builder()
              .add("Authorization", jwt) // 要在请求头中设置JWT,安全认证
              .add("Content-Type", "application/x-www-form-urlencoded")
              .build();

      Request request = new Request.Builder().url(url).post(body).headers(headers).build();

      Call call = client.newCall(request);

      try (Response response = call.execute()) {
        ResponseBody responseBody = response.body();
        if (responseBody != null) {
          String responseText = responseBody.string();
          log.info(responseText); // 异步调用服务的返回结果code 200标识成功
          responseBody.close();
        }
      } catch (IOException ex) {
        log.error(ex.getMessage());
      }

    } catch (Exception e) {
      log.error(e.getMessage());
    }
  }

  //
  public static String getJwt(OkHttpClient client) throws IOException {
    val username = "your accesskey"; // Accesskey
    val password = "your password"; // Password

    ObjectMapper objectMapper = new ObjectMapper();
    FormBody body =
        new FormBody.Builder().add("username", username).add("password", password).build();
    Request request =
        new Request.Builder()
            .post(body)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .url("https://www.thingshub.com.cn/openapi/v2/token/jwt/create")
            .build();
    Call call = client.newCall(request);

    try (Response response = call.execute()) {
      if (response.isSuccessful()) {
        ResponseBody responseBody = response.body();
        if (responseBody != null) {
          String responseText = responseBody.string();
          log.info(responseText);
          Map<String, Object> data =
              objectMapper.readValue(responseText, new TypeReference<Map<String, Object>>() {});
          return (String) data.get("data");
        }
      }
    }

    return null;
  }
}