我创建了一个可用于将 URL 动态添加到 CoAP 服务器的方法。这是我目前实施的方法。但是需要知道这是将资源添加到 CoAP 服务器的正确方法吗?假设coapendpoints/home/room1/sensor1是需要添加的。
// endpoint--> coapendpoints/home/room1/sensor1
String[] resources = endpoint.split("/");
Resource childResource = coapServer.getRoot().getChild(resources[0]);
Resource parentResource = childResource;
if (parentResource == null && (resources.length > 1)) {
coapServer.add(new CoAPResourcePath(resources));
}
if (parentResource == null && (resources.length == 1)) {
coapServer.add(new CoAPResourceServlet(resources[0]));
} else if (parentResource != null && resources.length > 1) {
int j = 1;
for (; j < resources.length; j++) {
if (childResource != null) {
parentResource = childResource;
childResource = childResource.getChild(resources[j]);
} else {
break;
}
}
String[] coapEndpoint = Arrays.copyOfRange(resources, j - 1, resources.length);
if (coapEndpoint.length > 1) {
parentResource.add(new CoAPResourcePath(coapEndpoint));
} else if (coapEndpoint.length == 1) {
parentResource.add(new CoAPResourceServlet(coapEndpoint[0]));
}
} else if (parentResource != null && resources.length == 1) {
parentResource.add(new CoAPResourceServlet(resources[0]));
}
这里 CoAPResourcePath 和 CoAPResourceServlet 类是从 CoapResource 扩展而来的。