CoAP协议接入 - Java代码示例
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapHandler;
import org.eclipse.californium.core.CoapObserveRelation;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.coap.CoAP.Code;
import org.eclipse.californium.core.coap.CoAP.Type;
import org.eclipse.californium.core.coap.Request;
import org.eclipse.californium.elements.exception.ConnectorException;
import java.io.IOException;
import java.net.URISyntaxException;
public class IotCoapClientWithDocument {
//需要确认coap ip与端口号
private static String ip = "127.0.0.1:5683";
private static String clientid = "V6BHPcM3GBuYm8GaCBiudrVv3.DcYTq21176109566006710274**securemode*2,signmethod*hmacsha256,timestamp*1700472181602**";
private static String username = "DcYTq21176109566006710274$V6BHPcM3GBuYm8GaCBiudrVv3";
private static String password = "bde537588a6867cfc0b2f319bc6dc7654a9716ebf1c2c5d497404fb98134b598";
private static String PUBLISH_TOPIC = "/ps/product1/device1/thing/heart";
private static String SUBSCRIBE_TOPIC = "/ps/product1/device1/thing/heart/response";
// CoAP客户端。
private CoapClient coapClient = new CoapClient();
private String token = "1";
public static void main(String[] args) throws InterruptedException, URISyntaxException {
IotCoapClientWithDocument client = new IotCoapClientWithDocument();
client.setToken();
// start a new thread to client.get();
var thread = new Thread(client::get);
thread.start();
Thread.sleep(1000);
client.publishDas("{\"data\":{\"heart\":1}}");
thread.join();
}
/**
* 发送消息。
*
* @param payload,消息内容。
*/
public void publishDas(String payload) {
try {
String uri = "coap://" + ip + PUBLISH_TOPIC + "?clientid=" + clientid + "&token=" + token;
Request request = new Request(Code.POST, Type.CON);
// 设置消息发布uri。
request.setURI(uri);
// 设置消息payload。
request.setPayload(payload);
// 发送消息。
CoapResponse response = coapClient.advanced(request);
} catch (ConnectorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void get() {
String uri = "coap://" + ip + SUBSCRIBE_TOPIC + "?clientid=" + clientid + "&token=" + token;
final CoapClient client = new CoapClient(uri);
CoapObserveRelation relation = client.observe(new CoapHandler() {
@Override
public void onLoad(CoapResponse response) {
// 处理接收到的消息
String payload = response.getResponseText();
// 在这里执行您的逻辑
System.out.println(payload);
}
@Override
public void onError() {
// 处理错误
}
});
}
public String setToken() throws URISyntaxException {
Request request = new Request(Code.POST, Type.CON);
// 设置消息发布uri。
request.setURI("coap://" + ip + "/mqtt/connection?clientid=" + clientid + "&username=" + username + "&password=" + password);
// 发送消息。
CoapResponse response = null;
try {
response = coapClient.advanced(request);
} catch (ConnectorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
token = response.getResponseText();
return response.getResponseText();
}
}
最后修改时间: 1 年前