关于物联网:ThingsKit物联网平台模拟CoAP设备接入

应用Java模仿客户端实际CoAP

筹备工作

  • IDEA开发工具【IntelliJ IDEA 2023.1.1 (Community Edition)】
  • JDK11及以上
  • MAVEN【个别IDEA曾经集成】(有最好,不须要手动下载jar引入,没有的话手动引入)

PS: 【Community Edition】教育版收费

PS:在页面最上面

CoAP外围包

  • californium-core.jar : 包含CoAP外围局部
  • element-connector.jar 包含实用于UDP和DTLS的java套接字形象层
  • scandium.jar: 包含DTLS

    创立我的项目

  • Language– Java。
  • Build system– Maven。
  • JDK– JDK_version_11.XX.XX。

成果如下:

单击“Create”;创立胜利如下:

筹备代码

pom.xml代码中退出依赖包
代码块,放在之下

<dependencies>
  <dependency>
    <groupId>org.eclipse.californium</groupId>
    <artifactId>californium-core</artifactId>
    <version>2.0.0-M7</version>
  </dependency>
  <dependency>
    <groupId>org.eclipse.californium</groupId>
    <artifactId>element-connector</artifactId>
    <version>2.0.0-M7</version>
  </dependency>
  <dependency>
    <groupId>org.eclipse.californium</groupId>
    <artifactId>scandium</artifactId>
    <version>2.0.0-M7</version>
  </dependency>
</dependencies>

成果如下:

依赖包配置文件退出之后;执行一下install下载依赖包;成果如下:

Main.java中;替换所以代码

package org.example;

import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.Utils;
import org.eclipse.californium.core.coap.MediaTypeRegistry;

import java.net.URI;
import java.net.URISyntaxException;

public class Main {
    public static void main(String[] args) throws URISyntaxException, InterruptedException {
        //拜访令牌-与平台端保持一致
        String ACCESS_TOKEN = "Za3E3cfKZmXV5eBOzCRW";
        //服务器IP地址,填上你的IP
        String ip = "101.133.***.**";
        //遥测数据上传接口,留神默认端口为5683
        String url = "coap://" + ip + ":5683/api/v1/" + ACCESS_TOKEN + "/telemetry";

        //创立一个资源申请
        URI uri = new URI(url);
        CoapClient client = new CoapClient(uri);

        //POST申请
        CoapResponse response;

        //反对数据格式是{"key1":"value1", "key2":"value2"}
        String payload = "{\"temp\":\"21.5\", \"wet\":\"37.5\"}";
        while (true) {
            //每隔5秒循环发送
            Thread.currentThread().sleep(5000);
            //只反对POST申请,切为【JSON格局】
            response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON);
            if (response != null) {
                //打印申请状态码
                System.out.println(response.getCode());
                //选项参数
                System.out.println(response.getOptions());
                //获取响应内容文本信息
                System.out.println(response.getResponseText());
                System.out.println("\nAdvanced\n");
                //打印格局良好的输入
                System.out.println(Utils.prettyPrint(response));
            }
        }
    }
}

文章起源(首发地址):ThingsKit物联网平台

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理