Commit 7ab46afd authored by Björn Butzin's avatar Björn Butzin
Browse files

added jCoAP examples

parent f8af42d1
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry combineaccessrules="false" kind="src" path="/ws4d-jcoap"/>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
/.settings
/log
/build.xml
/bin
/logref
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ws4d-jcoap-examples</name>
<comment></comment>
<projects>
<project>ws4d-jcoap</project>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.ws4d.coap</groupId>
<artifactId>example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jCoAP Example</name>
<description>Example using jCoAP</description>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6.1</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
/*
* Copyright 2015 University of Rostock
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ws4d.coap.example.basics;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.ws4d.coap.core.CoapClient;
import org.ws4d.coap.core.CoapConstants;
import org.ws4d.coap.core.connection.BasicCoapChannelManager;
import org.ws4d.coap.core.connection.api.CoapChannelManager;
import org.ws4d.coap.core.connection.api.CoapClientChannel;
import org.ws4d.coap.core.enumerations.CoapMediaType;
import org.ws4d.coap.core.enumerations.CoapRequestCode;
import org.ws4d.coap.core.messages.api.CoapRequest;
import org.ws4d.coap.core.messages.api.CoapResponse;
import org.ws4d.coap.core.tools.Encoder;
/**
* This class demonstrates a CoAP client
*
* @author Bjrn Konieczeck <bjoern.konieczeck@uni-rostock.de>
* @author Bjrn Butzin <bjoern.butzin@uni-rostock.de>
*/
public class Client implements CoapClient {
private static final boolean exitAfterResponse = false;
public static void main(String[] args) {
Client coapClient = new Client();
// binding client to address and port
if (args.length < 1)
coapClient.start("127.0.0.1", CoapConstants.COAP_DEFAULT_PORT);
else
coapClient.start(args[0], CoapConstants.COAP_DEFAULT_PORT);
}
public void start(String serverAddress, int serverPort) {
System.out.println("===START=== (Run Test Client)");
String sAddress = serverAddress;
int sPort = serverPort;
CoapChannelManager channelManager = BasicCoapChannelManager.getInstance();
CoapClientChannel clientChannel = null;
try {
clientChannel = channelManager.connect(this, InetAddress.getByName(sAddress), sPort);
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(-1);
}
CoapRequest request;
if (null == clientChannel) {
return;
}
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/temperature");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/multiType");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/multiType");
request.addAccept(CoapMediaType.exi);
request.addAccept(CoapMediaType.json);
request.addAccept(CoapMediaType.xml);
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/window");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.POST);
request.setUriPath("/window");
request.setContentType(CoapMediaType.text_plain);
request.setPayload("true");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/window");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/.well-known/core");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.POST);
request.setUriPath("/newResource");
request.setContentType(CoapMediaType.text_plain);
request.setPayload("newValue");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/newResource");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.PUT);
request.setUriPath("/newResource");
request.setContentType(CoapMediaType.text_plain);
request.setPayload("veryNewValue");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/newResource");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/.well-known/core");
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.DELETE);
request.setUriPath("/newResource");
request.setContentType(CoapMediaType.text_plain);
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/.well-known/core");
printRequest(request);
clientChannel.sendMessage(request);
String longpath = "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234";
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/sub/" + longpath);
printRequest(request);
clientChannel.sendMessage(request);
request = clientChannel.createRequest(true, CoapRequestCode.GET);
request.setUriPath("/ns:device/ns:service/operation/parameter");
printRequest(request);
clientChannel.sendMessage(request);
}
@Override
public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) {
System.out.println("Connection Failed");
System.exit(-1);
}
@Override
public void onResponse(CoapClientChannel channel, CoapResponse response) {
if (response.getPayload() != null) {
System.out.println(
"Response: " + response.toString() + " payload: " + Encoder.ByteToString(response.getPayload()));
} else {
System.out.println("Response: " + response.toString());
}
if (Client.exitAfterResponse) {
System.out.println("===END===");
System.exit(0);
}
}
@Override
public void onMCResponse(CoapClientChannel channel, CoapResponse response, InetAddress srcAddress, int srcPort) {
// TODO Auto-generated method stub
}
private static void printRequest(CoapRequest request){
if(request.getPayload() != null){
System.out.println("Request: "+request.toString() + " payload: " + Encoder.ByteToString(request.getPayload()) + " resource: " + request.getUriPath());
} else {
System.out.println("Request: "+request.toString() + " resource: " + request.getUriPath());
}
}
}
\ No newline at end of file
/*
* Copyright 2015 University of Rostock
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ws4d.coap.example.basics;
import java.util.List;
import org.ws4d.coap.core.enumerations.CoapMediaType;
import org.ws4d.coap.core.rest.BasicCoapResource;
import org.ws4d.coap.core.rest.CoapData;
import org.ws4d.coap.core.rest.CoapResourceServer;
import org.ws4d.coap.core.rest.MultiTypeResource;
import org.ws4d.coap.core.rest.api.ResourceHandler;
import org.ws4d.coap.core.tools.Encoder;
import org.ws4d.coap.example.basics.resources.ObservableResource;
import org.ws4d.coap.example.basics.resources.Window;
/**
* This class demonstrates a CoAP server
*
* @author Bjrn Konieczeck <bjoern.konieczeck@uni-rostock.de>
* @author Bjrn Butzin <bjoern.butzin@uni-rostock.de>
*/
public class Server {
/**
* @param args
*/
private static Server coapServer;
private CoapResourceServer resourceServer;
/**
* @param args
*/
public static void main(String[] args) {
coapServer = new Server();
coapServer.start();
}
public void start() {
System.out.println("===Run Test Server ===");
// create server
if (this.resourceServer != null) this.resourceServer.stop();
this.resourceServer = new CoapResourceServer();
// add additional resource while server is running
this.resourceServer.createResource(new Window());
// add a standard resource
this.resourceServer.createResource(new BasicCoapResource("/noMatchCase","noMatchCase", CoapMediaType.text_plain)
.setResourceType("Test interface"));
this.resourceServer.createResource(new BasicCoapResource("/noMatchUnsufficient","noMatchUnsufficient", CoapMediaType.text_plain)
.setResourceType("Test"));
this.resourceServer.createResource(new BasicCoapResource("/noMatchUnsufficient2","noMatchUnsufficient2", CoapMediaType.text_plain)
.setResourceType("Interface"));
this.resourceServer.createResource(new BasicCoapResource("/PerfectMatch","PerfectMatch", CoapMediaType.text_plain)
.setResourceType("Test Interface"));
this.resourceServer.createResource(new BasicCoapResource("/Match+","Match+", CoapMediaType.text_plain)
.setResourceType("Test Interface Foo"));
this.resourceServer.createResource(new BasicCoapResource("/Match*+","Match*+", CoapMediaType.text_plain)
.setResourceType("Test Intergalactic Foo"));
this.resourceServer.createResource(new BasicCoapResource("/Match-","Match-", CoapMediaType.text_plain)
.setResourceType("- Intergalactic Foo"));
this.resourceServer.createResource(new BasicCoapResource("/sub/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234",
"subresource".getBytes(), CoapMediaType.text_plain));
this.resourceServer.createResource(new BasicCoapResource("/ns:device/ns:service/operation/parameter",
"firstValue", CoapMediaType.text_plain));
ResourceHandler XMLhandler = new ResourceHandler(){
@Override
public CoapMediaType getMediaType() {
return CoapMediaType.xml;
}
@Override
public CoapData handleGet() {
return new CoapData(Encoder.StringToByte("<XML>Content</XML>"), this.getMediaType());
}
@Override
public CoapData handleGet(List<String> queryString) {
return new CoapData(Encoder.StringToByte("<XML>Content</XML>"), this.getMediaType());
}
@Override
public boolean handlePost(byte[] data) {
return false;
}
@Override
public boolean handlePut(byte[] data) {
return false;
}
@Override
public boolean handleDelete() {
return true;
}
};
ResourceHandler JSONhandler = new ResourceHandler(){
@Override
public CoapMediaType getMediaType() {
return CoapMediaType.json;
}
@Override
public CoapData handleGet() {
return new CoapData(Encoder.StringToByte("JSON{content:content}"), this.getMediaType());
}
@Override
public CoapData handleGet(List<String> queryString) {
return new CoapData(Encoder.StringToByte("JSON{content:content}"), this.getMediaType());
}
@Override
public boolean handlePost(byte[] data) {
return false;
}
@Override
public boolean handlePut(byte[] data) {
return false;
}
@Override
public boolean handleDelete() {
return true;
}
};
MultiTypeResource res = new MultiTypeResource("/multiType", XMLhandler);
res.addResourceHandler(JSONhandler);
this.resourceServer.createResource(res);
// initialize observable resource
ObservableResource temp = new ObservableResource();
// make resource observable
temp.setObservable(true);
// add resource to server
this.resourceServer.createResource(temp);
temp.registerServerListener(this.resourceServer);
// run the server
try {
this.resourceServer.start();
} catch (Exception e) {
e.printStackTrace();
}
// add additional resource while server is running
this.resourceServer.createResource(new BasicCoapResource(
"/added/at/runtime", "startValue",
CoapMediaType.text_plain));
// emulate data changes
while (true) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
//nothing
}
temp.changed();
}
}
}
/*
* Copyright 2015 University of Rostock
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ws4d.coap.example.basics.resources;
import java.util.List;
import java.util.Locale;
import org.ws4d.coap.core.enumerations.CoapMediaType;
import org.ws4d.coap.core.rest.BasicCoapResource;
import org.ws4d.coap.core.rest.CoapData;
/**
* This class demonstrates a CoAP ressource
*
* @author Bjrn Konieczeck <bjoern.konieczeck@uni-rostock.de>
* @author Bjrn Butzin <bjoern.butzin@uni-rostock.de>
*/
public class ObservableResource extends BasicCoapResource {
private static double MAX_TEMP = 30.0;
private static double MIN_TEMP = 20.0;
private ObservableResource(String path, String value, CoapMediaType mediaType) {
super(path, value, mediaType);
this.setResourceType("Temperature");
this.setInterfaceDescription("testInterface");
this.setObservable(true);
}
public ObservableResource() {
this("/temperature", "LongPathResource Payload", CoapMediaType.text_plain);
}
@Override
public synchronized CoapData get(List<String> query, List<CoapMediaType> mediaTypesAccepted) {
return get(mediaTypesAccepted);
}
@Override
public synchronized CoapData get(List<CoapMediaType> mediaTypesAccepted) {
double randTemp = MIN_TEMP + (Math.random() * (MAX_TEMP - MIN_TEMP));
String result = String.format(Locale.US, "%1$,.2f", randTemp);
return new CoapData(result.getBytes(), CoapMediaType.text_plain);
}
}
package org.ws4d.coap.example.basics.resources;
public enum State {
open, close
}
\ No newline at end of file
/*
* Copyright 2015 University of Rostock
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ws4d.coap.example.basics.resources;
import java.util.List;
import org.ws4d.coap.core.enumerations.CoapMediaType;
import org.ws4d.coap.core.rest.BasicCoapResource;
import org.ws4d.coap.core.rest.CoapData;
import org.ws4d.coap.core.tools.Encoder;
/**
* This class demonstrates a CoAP ressource
*
* @author Bjrn Konieczeck <bjoern.konieczeck@uni-rostock.de>
* @author Bjrn Butzin <bjoern.butzin@uni-rostock.de>
*/
public class Window extends BasicCoapResource {
private String open = "false";
private Window(String path, String value, CoapMediaType mediaType) {
super(path, value, mediaType);