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

Added files for the jCoAP hands on

parent 722b9ff8
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="lib" path="lib/jcoap-1.1.0-SNAPSHOT.jar" sourcepath="lib/jcoap-1.1.0-SNAPSHOT-sources.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ws4d-jcoap-handsOn</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO"><!-- ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: -->
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="INFO"><!-- ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: -->
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
\ No newline at end of file
package org.ws4d.coap.handsOn;
import java.net.InetAddress;
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;
public class Client implements CoapClient {
// TODO 12: Skip for now! In the 2nd step we change this to false.
/**
* if you want to send multiple requests you should set this to false
* otherwise the program will terminate after the first response arrives
*/
private boolean exitAfterResponse = true;
/** A manager to keep track of our connections */
private CoapChannelManager channelManager;
/** The target where we want to send our request to */
private CoapClientChannel clientChannel;
/** The method containing the creation of our requests */
public void start(String serverAddress, int serverPort) {
/* FIXME 4: Initialize the ChannelManager and get a client channel to the server */
// this.channelManager = BasicCoapChannelManager.getInstance();
this.clientChannel = null;
try {
/* FIXME 5: Connect to the server */
// this.clientChannel = this.channelManager.connect(this, InetAddress.getByName(serverAddress), serverPort);
/* Make sure that the channel is not null */
if (this.clientChannel == null) {
System.err.println("Connect failed: clientChannel in null!");
System.exit(-1);
}
} catch (Exception e) {
System.err.println(e.getLocalizedMessage());
System.exit(-1);
}
/* Create an empty request and prepare parameters */
// do we expect an acknowledgement
boolean reliable = true;
/* FIXME 6: What kind of request do we want to send? */
// CoapRequestCode requestCode = CoapRequestCode.GET;
/* FIXME 7: Create the request */
// CoapRequest request = this.clientChannel.createRequest(reliable, requestCode);
/* FIXME 8: At least we have to set the path of the requested resource */
// request.setUriPath("/temperature");
/* TODO 13: Skip for now! In the 2nd step we add the observe option here */
// request.setObserveOption(0);
/* For further exploration: other interesting options */
// request.setPayload(payload); // for PUT and POST operations you need to provide some payload
// request.setContentType(CoapMediaType.text_plain); // to define the media type of the payload
// request.setUriQuery(query); // query parameters; known from e.g.: http://server.domain/resource?query=parameter
// request.addAccept(CoapMediaType.text_plain); // only accept certain media types as response; you can add multiple
// request.setProxyUri(proxyUri); // send this request through a proxy
/* FIXME 9: Send your Message here! */
// this.clientChannel.sendMessage(request);
}
/* *************************************************************************
* Some callback functions that are invoked by the jCoAP-Framework
* ************************************************************************/
@Override
public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) {
System.err.println("Connection Failed");
System.exit(-1);
}
@Override
public void onResponse(CoapClientChannel channel, CoapResponse response) {
// We just print out the response
if (response.getPayload() != null) {
/* TODO 15: Skip for now! In the 3rd step we replace this behavior.*/
System.out.println("Response: " + response.toString() + " (" + new String(response.getPayload()) + ")");
} else {
System.out.println("Response: " + response.toString());
}
if (this.exitAfterResponse) {
System.out.println("=== STOP Client ===");
System.exit(0);
}
}
/* ignore me, I'm only for multicast communication */
@Override
public void onMCResponse(CoapClientChannel channel, CoapResponse response, InetAddress srcAddress, int srcPort) {
/* do nothing */
}
/* *************************************************************************
* Last but not least the main method to get things running
* ************************************************************************/
public static void main(String[] args) {
Client coapClient = new Client();
System.out.println("=== START Client ===");
coapClient.start("127.0.0.1", CoapConstants.COAP_DEFAULT_PORT);
}
}
package org.ws4d.coap.handsOn;
import org.ws4d.coap.core.enumerations.CoapMediaType;
import org.ws4d.coap.core.rest.BasicCoapResource;
import org.ws4d.coap.core.rest.CoapResourceServer;
public class Server {
private static Server coapServer;
private CoapResourceServer resourceServer;
public void startServer() {
System.out.println("=== START Server ===");
if (this.resourceServer != null){
this.resourceServer.stop();
}
/* FIXME 1: Instantiate a CoapResourceServer */
// this.resourceServer = new CoapResourceServer();
/* FIXME 2: Instantiate a TemperatureResource */
// TemperatureResource resource = new TemperatureResource();
/* TODO 10: Skip for now! In the 2nd step we will make this resource observable right here */
// resource.setObservable(true);
/* FIXME 3: Add our resource to the server */
// this.resourceServer.createResource(resource);
/* TODO 14: Skip for now! In the 3rd step we will add another resource here*/
// this.resourceServer.createResource( new BasicCoapResource("/ACControl","off",CoapMediaType.text_plain));
/* this starts the server */
try {
this.resourceServer.start();
} catch (Exception e) {
System.err.println(e.getLocalizedMessage());
}
/* TODO 11: Skip for now! In the 2nd step we will notify about a changed resource right here */
// while(true){
// try {Thread.sleep(5000);}
// catch (InterruptedException e) {/*do nothing*/}
// resource.changed();
// }
}
/* *************************************************************************************************** */
/* Last but not least the main method to get things running */
/* *************************************************************************************************** */
public static void main(String[] args) {
coapServer = new Server();
coapServer.startServer();
}
}
package org.ws4d.coap.handsOn;
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;
public class TemperatureResource extends BasicCoapResource {
private static double MAX_TEMP = 30.0;
private static double MIN_TEMP = 20.0;
private TemperatureResource(String path, byte[] value, CoapMediaType mediaType) {
// resource path, initial value, media type
super( path, value, mediaType);
//disallow POST, PUT and DELETE
this.setDeletable(false);
this.setPostable(false);
this.setPutable(false);
}
public TemperatureResource(){
// resource path, initial value, media type
this( "/temperature", "0.0".getBytes(), CoapMediaType.text_plain);
}
@Override
public synchronized CoapData get(List<CoapMediaType> mediaTypesAccepted) {
double randomTemperature = MIN_TEMP + ( Math.random() * (MAX_TEMP-MIN_TEMP) );
String result = String.format(Locale.US, "%1$,.1f", randomTemperature);
return new CoapData(result.getBytes(), CoapMediaType.text_plain);
}
@Override
public synchronized CoapData get(List<String> query, List<CoapMediaType> mediaTypesAccepted) {
/* we just ignore query parameters*/
return get(mediaTypesAccepted);
}
@Override
public synchronized String getResourceType() {
return "Temperature";
}
}
package org.ws4d.coap.handsOn.multicastDiscovery;
import java.net.InetAddress;
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.CoapRequestCode;
import org.ws4d.coap.core.messages.api.CoapRequest;
import org.ws4d.coap.core.messages.api.CoapResponse;
public class MulticastDiscoveryClient implements CoapClient {
private CoapChannelManager channelManager;
private CoapClientChannel clientChannel;
public static void main(String[] args) {
MulticastDiscoveryClient coapClient = new MulticastDiscoveryClient();
System.out.println("=== START Multicast Discovery Client ===");
/* *************************************************************************************************** */
/* Use multicast address */
/* *************************************************************************************************** */
// coapClient.start(CoapConstants.COAP_ALL_NODES_IPV4_MC_ADDR, CoapConstants.COAP_DEFAULT_PORT);
coapClient.start(CoapConstants.COAP_ALL_NODES_IPV6_LL_MC_ADDR, CoapConstants.COAP_DEFAULT_PORT);
// coapClient.start(CoapConstants.COAP_ALL_NODES_IPV6_SL_MC_ADDR, CoapConstants.COAP_DEFAULT_PORT);
}
public void start(String serverAddress, int serverPort) {
this.channelManager = BasicCoapChannelManager.getInstance();
this.clientChannel = null;
try {
this.clientChannel = this.channelManager.connect(this, InetAddress.getByName(serverAddress), serverPort);
if (this.clientChannel == null) {
System.err.println("Connect failed: clientChannel in null!");
System.exit(-1);
}
} catch (Exception e) {
System.err.println(e.getLocalizedMessage());
System.exit(-1);
}
/* *************************************************************************************************** */
/* Create request to /.well-known/core resource */
/* *************************************************************************************************** */
// set reliablity and request method
CoapRequest request = this.clientChannel.createRequest(false, CoapRequestCode.GET);
// set resource path
request.setUriPath("/.well-known/core");
// add a token to match outgoing multicast message and incoming unicast messages
request.setToken("MCToken".getBytes());
// send the request
this.clientChannel.sendMessage(request);
}
/* *************************************************************************************************** */
/* Implement callback methods */
/* *************************************************************************************************** */
@Override
public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) {
System.err.println("Connection Failed");
System.exit(-1);
}
@Override
public void onResponse(CoapClientChannel channel, CoapResponse response) {
if (response.getPayload() != null) {
System.out.println("Response: " + response.toString() + " (" + new String(response.getPayload()) + ")");
} else {
System.out.println("Response: " + response.toString());
}
}
@Override
public void onMCResponse(CoapClientChannel channel, CoapResponse response, InetAddress srcAddress, int srcPort) {
if (response.getPayload() != null) {
System.out.println("Response from "+ srcAddress.toString() + ":" + srcPort + " - " + response.toString() + " (" + new String(response.getPayload()) + ")");
} else {
System.out.println("Response from "+ srcAddress.toString() + ":" + srcPort + " - " + response.toString());
}
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment