Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

OM2M/one/App

< OM2M‎ | one
Revision as of 06:39, 27 October 2017 by Benalaya.sensinov.com (Talk | contribs) (MyManager)

To do this tutorial you have to clone and build OM2M using Eclipse

oneM2M JAVA applications

Create a new Maven project

  • Open Eclipse IDE
  • Got to File -> New -> other -> Maven Project
  • Select "Create a simple Project (skip archetype selection)" then click Next
  • Enter "org.eclipse.om2m" as Group Id and "org.eclipse.om2m.app" as "Artifact Id" then click on Finish
  • Create package "org.eclipse.om2m.app" inside the folder src/main/java

Configure project dependencies

  • Add dependencies for HTTP and JSON to your project by adding the following section to your pom.xml file inside the <project> tag.
<dependencies>
   <dependency>
      <groupId>com.sun.net.httpserver</groupId>
      <artifactId>http</artifactId>
      <version>20070405</version>
   </dependency>
   <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.1</version>
   </dependency>
   <dependency>
   <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20160212</version>
   </dependency>
</dependencies>

Project classes

RestHttpClient

package org.eclipse.om2m.app;
 
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
public class RestHttpClient {
 
	public static HttpResponse get(String originator, String uri) {
		System.out.println("HTTP GET "+uri);
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpGet= new HttpGet(uri);
 
		httpGet.addHeader("X-M2M-Origin",originator);
		httpGet.addHeader("Accept","application/json");
 
		HttpResponse httpResponse = new HttpResponse();
 
		try {
			CloseableHttpResponse closeableHttpResponse = httpclient.execute(httpGet);
			try{
				httpResponse.setStatusCode(closeableHttpResponse.getStatusLine().getStatusCode());
				httpResponse.setBody(EntityUtils.toString(closeableHttpResponse.getEntity()));
			}finally{
				closeableHttpResponse.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		System.out.println("HTTP Response "+httpResponse.getStatusCode()+"\n"+httpResponse.getBody());
		return httpResponse;	
	}
 
	public static HttpResponse post(String originator, String uri, String body, int ty) {
		System.out.println("HTTP POST "+uri+"\n"+body);
 
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(uri);
 
		httpPost.addHeader("X-M2M-Origin",originator);
		httpPost.addHeader("Accept","application/json");	
		httpPost.addHeader("Content-Type","application/json;ty="+ty);
 
		HttpResponse httpResponse = new HttpResponse();
		try {
			CloseableHttpResponse closeableHttpResponse=null;
			try{
				httpPost.setEntity(new StringEntity(body));
				closeableHttpResponse = httpclient.execute(httpPost);
			httpResponse.setStatusCode(closeableHttpResponse.getStatusLine().getStatusCode());
				httpResponse.setBody(EntityUtils.toString(closeableHttpResponse.getEntity()));
 
			}finally{
				closeableHttpResponse.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		System.out.println("HTTP Response "+httpResponse.getStatusCode()+"\n"+httpResponse.getBody());
		return httpResponse ;	
	}
}

HttpResponse

package org.eclipse.om2m.app;
 
public class HttpResponse {
	private int statusCode;
	private String body;
 
	public int getStatusCode() {
		return statusCode;
	}
 
	public void setStatusCode(int statusCode) {
		this.statusCode = statusCode;
	}
 
	public String getBody() {
		return body;
	}
 
	public void setBody(String body) {
		this.body = body;
	}
}

MySensor example

package org.eclipse.om2m.app;
 
import org.json.JSONObject;
 
public class MySensor {
 
	public static int sensorValue;
 
	private static String originator="admin:admin";
	private static String cseProtocol="http";
	private static String cseIp = "127.0.0.1";
	private static int csePort = 8282;
	private static String cseId = "mn-cse";
	private static String cseName = "mn-name";
 
	private static String aeName = "mysensor";
	private static String cntName = "data";
 
	private static String csePoa = cseProtocol+"://"+cseIp+":"+csePort;
 
	public static void main(String[] args) {
 
		JSONObject obj = new JSONObject();
		obj.put("rn", aeName);
		obj.put("api", 12345);
		obj.put("rr", false);
		JSONObject resource = new JSONObject();
		resource.put("m2m:ae", obj);
		RestHttpClient.post(originator, csePoa+"/~/"+cseId+"/"+cseName, resource.toString(), 2);
 
	        obj = new JSONObject();
	        obj.put("rn", cntName);
		resource = new JSONObject();
	        resource.put("m2m:cnt", obj);
		RestHttpClient.post(originator, csePoa+"/~/"+cseId+"/"+cseName+"/"+aeName, resource.toString(), 3);
 
		while (true){
 
			obj = new JSONObject();
			obj.put("cnf", "application/text");
			obj.put("con", getSensorValue());
			resource = new JSONObject();
			resource.put("m2m:cin", obj);
			RestHttpClient.post(originator, csePoa+"/~/"+cseId+"/"+cseName+"/"+aeName+"/"+cntName, resource.toString(), 4);
 
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
 
	public static int getSensorValue(){
		sensorValue = (int)(Math.random()*500);
		System.out.println("Sensor value = "+sensorValue);
		return sensorValue;
	}
}

MyActuator example

package org.eclipse.om2m.app;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.json.JSONArray;
import org.json.JSONObject;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
 
public class MyActuator {
 
	private static boolean actuatorValue;
 
	private static String originator="admin:admin";
	private static String cseProtocol="http";
	private static String cseIp = "127.0.0.1";
	private static int csePort = 8282;
	private static String cseId = "mn-cse";
	private static String cseName = "mn-name";
 
	private static String aeName = "myactuator";
	private static String cntName = "data";
 
	private static String aeProtocol="http";
	private static String aeIp = "127.0.0.1";
	private static int aePort = 1400;	
	private static String subName="actuatorsub";
 
	private static String csePoa = cseProtocol+"://"+cseIp+":"+csePort;
	private static String appPoa = aeProtocol+"://"+aeIp+":"+aePort;
 
	public static void main(String[] args) {
 
		HttpServer server = null;
		try {
			server = HttpServer.create(new InetSocketAddress(aePort), 0);
		} catch (IOException e) {
			e.printStackTrace();
		}
		server.createContext("/", new MyHandler());
		server.setExecutor(Executors.newCachedThreadPool());
		server.start();
 
		JSONArray array = new JSONArray();
		array.put(appPoa);
		JSONObject obj = new JSONObject();
		obj.put("rn", aeName);
		obj.put("api", 12345);
		obj.put("rr", true);
		obj.put("poa",array);
		JSONObject resource = new JSONObject();
		resource.put("m2m:ae", obj);
		RestHttpClient.post(originator, csePoa+"/~/"+cseId+"/"+cseName, resource.toString(), 2);
 
                obj = new JSONObject();
                obj.put("rn", cntName);
		resource = new JSONObject();
                resource.put("m2m:cnt", obj);
		RestHttpClient.post(originator, csePoa+"/~/"+cseId+"/"+cseName+"/"+aeName, resource.toString(), 3);
 
		array = new JSONArray();
		array.put("/"+cseId+"/"+cseName+"/"+aeName);
		obj = new JSONObject();
		obj.put("nu", array);
		obj.put("rn", subName);
		obj.put("nct", 2);
		resource = new JSONObject();		
		resource.put("m2m:sub", obj);
		RestHttpClient.post(originator, csePoa+"/~/"+cseId+"/"+cseName+"/"+aeName+"/"+cntName, resource.toString(), 23);
	}
 
	static class MyHandler implements HttpHandler {
 
		public void handle(HttpExchange httpExchange)  {
			System.out.println("Event Recieved!");
 
			try{
				InputStream in = httpExchange.getRequestBody();
 
				String requestBody = "";
				int i;char c;
				while ((i = in.read()) != -1) {
					c = (char) i;
					requestBody = (String) (requestBody+c);
				}
 
				System.out.println(requestBody);
 
				JSONObject json = new JSONObject(requestBody);
				if (json.getJSONObject("m2m:sgn").has("vrq")) {
					System.out.println("Confirm subscription");
				} else {
					JSONObject rep = json.getJSONObject("m2m:sgn").getJSONObject("nev")
							.getJSONObject("rep");
					int ty = rep.getInt("ty");
					System.out.println("Resource type: "+ty);
 
					if (ty == 4) {
						String con = rep.getString("con");
						System.out.println("Actuator state = "+con);
						setActuatorValue(Boolean.parseBoolean(con));
					}
				}	
 
				String responseBudy ="";
				byte[] out = responseBudy.getBytes("UTF-8");
				httpExchange.sendResponseHeaders(200, out.length);
				OutputStream os = httpExchange.getResponseBody();
				os.write(out);
				os.close();
 
			} catch(Exception e){
				e.printStackTrace();
			}		
		}
	}
 
	public static void setActuatorValue(boolean actuatorValue) {
		MyActuator.actuatorValue = actuatorValue;
	}
}

MyManager example

package org.eclipse.om2m.app;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.json.JSONArray;
import org.json.JSONObject;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
 
public class MyManager {
 
	private static String originator="admin:admin";
	private static String cseProtocol="http";
	private static String cseIp = "127.0.0.1";
	private static int csePort = 8080;
	private static String cseId = "in-cse";
	private static String cseName = "in-name";
 
	private static String aeName = "mymanager";
	private static String aeProtocol="http";
	private static String aeIp = "127.0.0.1";
	private static int aePort = 1500;	
	private static String subName="managersub";
	private static String targetSensorContainer="mn-cse/mn-name/mysensor/data";
	private static String targetActuatorContainer="mn-cse/mn-name/myactuator/data";
 
	private static String csePoa = cseProtocol+"://"+cseIp+":"+csePort;
	private static String appPoa = aeProtocol+"://"+aeIp+":"+aePort;
 
	public static void main(String[] args) {
 
		HttpServer server = null;
		try {
			server = HttpServer.create(new InetSocketAddress(aePort), 0);
		} catch (IOException e) {
			e.printStackTrace();
		}
		server.createContext("/", new MyHandler());
		server.setExecutor(Executors.newCachedThreadPool());
		server.start();
 
		JSONArray array = new JSONArray();
		array.put(appPoa);
		JSONObject obj = new JSONObject();
		obj.put("rn", aeName);
		obj.put("api", 12346);
		obj.put("rr", true);
		obj.put("poa",array);
		JSONObject resource = new JSONObject();
		resource.put("m2m:ae", obj);
		RestHttpClient.post(originator, csePoa+"/~/"+cseId+"/"+cseName, resource.toString(), 2);
 
		array = new JSONArray();
		array.put("/"+cseId+"/"+cseName+"/"+aeName);
		obj = new JSONObject();
		obj.put("nu", array);
		obj.put("rn", subName);
		obj.put("nct", 2);
		resource = new JSONObject();		
		resource.put("m2m:sub", obj);
		RestHttpClient.post(originator, csePoa+"/~/"+targetSensorContainer, resource.toString(), 23);
	}
 
	static class MyHandler implements HttpHandler {
 
		public void handle(HttpExchange httpExchange)  {
			System.out.println("Event Recieved!");
 
			try{
				InputStream in = httpExchange.getRequestBody();
 
				String requestBody = "";
				int i;char c;
				while ((i = in.read()) != -1) {
					c = (char) i;
					requestBody = (String) (requestBody+c);
				}
 
				System.out.println(requestBody);
 
				JSONObject json = new JSONObject(requestBody);
				if (json.getJSONObject("m2m:sgn").has("vrq")) {
					System.out.println("Confirm subscription");
				} else {
					JSONObject rep = json.getJSONObject("m2m:sgn").getJSONObject("nev")
							.getJSONObject("rep");
					int ty = rep.getInt("ty");
					System.out.println("Resource type: "+ty);
 
					if (ty == 4) {
						String con = rep.getString("con");
						int sensorValue = Integer.parseInt(con);
						System.out.print("OBSERVATION: Sensor Value "+sensorValue);
 
						boolean actuatorState;
						if(sensorValue<250){
							System.out.println(" -> LOW");
							actuatorState=true;
 
						}else{
							System.out.println(" -> HIGH");
							actuatorState=false;
						}
						System.out.println("ACTION: switch actuator state to "+actuatorState+"\n");
 
						JSONObject obj = new JSONObject();
						obj = new JSONObject();
						obj.put("cnf", "application/text");
						obj.put("con", actuatorState);
						JSONObject resource = new JSONObject();
						resource.put("m2m:cin", obj);
						RestHttpClient.post(originator, csePoa+"/~/"+targetActuatorContainer, resource.toString(), 4);
					}
				}	
 
				String responseBudy ="";
				byte[] out = responseBudy.getBytes("UTF-8");
				httpExchange.sendResponseHeaders(200, out.length);
				OutputStream os = httpExchange.getResponseBody();
				os.write(out);
				os.close();
 
			} catch(Exception e){
				e.printStackTrace();
			}		
		}
	}
}

MyMonitor

package org.eclipse.om2m.app;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
 
import org.json.JSONArray;
import org.json.JSONObject;
 
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
 
public class MyMonitor {
 
	private static String originator="admin:admin";
	private static String cseProtocol="http";
	private static String cseIp = "127.0.0.1";
	private static int csePort = 8080;
	private static String cseId = "in-cse";
	private static String cseName = "in-name";
 
	private static String aeMonitorName = "mymonitor";
	private static String aeProtocol="http";
	private static String aeIp = "127.0.0.1";
	private static int aePort = 1600;	
	private static String subName="monitorsub";
	private static String targetCse = "mn-cse/mn-name";
 
	private static String csePoa = cseProtocol+"://"+cseIp+":"+csePort;
	private static String appPoa = aeProtocol+"://"+aeIp+":"+aePort;
 
	private static JSONObject ae;
	private static JSONObject sub;	
 
	public static void main(String[] args) {
 
		HttpServer server = null;
		try {
			server = HttpServer.create(new InetSocketAddress(aePort), 0);
		} catch (IOException e) {
			e.printStackTrace();
		}
		server.createContext("/", new MyHandler());
		server.setExecutor(Executors.newCachedThreadPool());
		server.start();
 
		JSONArray array = new JSONArray();
		array.put(appPoa);
		JSONObject obj = new JSONObject();
		obj.put("rn", aeMonitorName);
		obj.put("api", 12346);
		obj.put("rr", true);
		obj.put("poa",array);
		ae = new JSONObject();
		ae.put("m2m:ae", obj);
		RestHttpClient.post(originator, csePoa+"/~/"+cseId+"/"+cseName, ae.toString(), 2);
 
		array = new JSONArray();
		array.put("/"+cseId+"/"+cseName+"/"+aeMonitorName);
		obj = new JSONObject();
		obj.put("nu", array);
		obj.put("rn", subName);
		obj.put("nct", 2);
		sub = new JSONObject();	
		sub.put("m2m:sub", obj);
		RestHttpClient.post(originator, csePoa+"/~/"+targetCse, sub.toString(), 23);
 
		System.out.println("[INFO] Discover all containers in "+csePoa);
 
		HttpResponse httpResponse = RestHttpClient.get(originator, csePoa+"/~/"+targetCse+"?fu=1&ty=3");
		JSONObject result = new JSONObject(httpResponse.getBody());
		String[] uril = result.getString("m2m:uril").split(" ");
		for (int i=0;i<uril.length;i++){
			RestHttpClient.post(originator, csePoa+"/~"+uril[i], sub.toString(), 23);
		}
	}
 
	static class MyHandler implements HttpHandler {
 
		public void handle(HttpExchange httpExchange)  {
			System.out.println("Event Recieved!");
 
			try{
				InputStream in = httpExchange.getRequestBody();
 
				String requestBody = "";
				int i;char c;
				while ((i = in.read()) != -1) {
					c = (char) i;
					requestBody = (String) (requestBody+c);
				}
 
				System.out.println(requestBody);
 
				JSONObject json = new JSONObject(requestBody);
				if (json.getJSONObject("m2m:sgn").has("vrq")) {
					System.out.println("Confirm subscription");
				} else {
					JSONObject rep = json.getJSONObject("m2m:sgn").getJSONObject("nev")
							.getJSONObject("rep");
					int ty = rep.getInt("ty");
					System.out.println("Resource type: "+ty);
 
					if (ty == 2) {
							String aeName = rep.getString("rn");
							System.out.println("[INFO] New AE has been registred: "+aeName+"\n");
							System.out.println("[INFO] Wait 3 seconds\n");
							Thread.sleep(3000);
							System.out.println("[INFO] Monitor AE "+aeName+" containers");
							HttpResponse httpResponse = RestHttpClient.get(originator, csePoa+"/~/"+targetCse+"/"+aeName+"?rcn=5");
							JSONObject ae = new JSONObject(httpResponse.getBody());
							if(!ae.getJSONObject("m2m:ae").isNull("ch")){
								JSONArray aeChild = ae.getJSONObject("m2m:ae").getJSONArray("ch");
								System.out.println("[INFO] AE "+aeName+" has "+aeChild.length()+" child:");
								for (int j=0; j<aeChild.length(); j++){
									if(aeChild.getJSONObject(j).getInt("ty")==3){
										String cntName = aeChild.getJSONObject(j).getString("rn");
										System.out.println("[INFO] Container: "+cntName+"\n");					
										RestHttpClient.post(originator, csePoa+"/~/"+targetCse+"/"+aeName+"/"+cntName, sub.toString(), 23);
									}
								}
							}
					}else if(ty == 4){
						String ciName = rep.getString("rn");
						String content = rep.getString("con");
 
						System.out.println("[INFO] New Content Instance "+ciName+" has been created");
						System.out.println("[INFO] Content: "+content);
 
					}
				}	
 
				String responseBudy ="";
				byte[] out = responseBudy.getBytes("UTF-8");
				httpExchange.sendResponseHeaders(200, out.length);
				OutputStream os = httpExchange.getResponseBody();
				os.write(out);
				os.close();
 
			} catch(Exception e){
				e.printStackTrace();
			}		
		}
	}
}

oneM2M Arduino application

#include <ESP8266WiFi.h>
 
// WIFI network
const char* ssid = "Pi3-AP";
const char* password = "raspberry";
 
// Target CSE
const char* host = "172.24.1.1";
const int httpPort = 8282;
 
// AE-ID
const char* origin   = "Clight_ae1";
 
// AE listening port
WiFiServer server(80);
 
void setup() {
 
  Serial.begin(115200);
  delay(10);
 
  // Configure pin 5 for LED control
  pinMode(5, OUTPUT);
  digitalWrite(5, 0);
 
  Serial.println();
  Serial.println();
 
  // Connect to WIFI network
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.persistent(false);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
 
  // Start HTTP server
  server.begin();
  Serial.println("Server started");
 
  // Create AE resource
  String resulat = send("/~/gateway-1/gateway-1",2,"{\"m2m:ae\":{\"rn\":\"light_ae1\",\"acpi\":[\"/gateway-1/gateway-1/MN-CSEAcp\"],\"api\":\"A01.com.company.lightApp01\",\"rr\":\"true\",\"poa\":[\"http://"+WiFi.localIP().toString()+":80\"]}}");
 
  if(resulat=="HTTP/1.1 201 Created"){
    // Create Container resource
    send("/~/gateway-1/gateway-1/light_ae1",3,"{\"m2m:cnt\":{\"rn\":\"light\"}}");
 
    // Create ContentInstance resource
    send("/~/gateway-1/gateway-1/light_ae1/light",4,"{\"m2m:cin\":{\"con\":\"OFF\"}}");
 
    // Create Subscription resource
    send("/~/gateway-1/gateway-1/light_ae1/light",23,"{\"m2m:sub\":{\"rn\":\"lightstate_sub\",\"nu\":[\"Clight_ae1\"],\"nct\":1}}");
  }
}
 
// Method in charge of receiving event from the CSE
void loop(){
  // Check if a client is connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
 
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
 
  // Read the request
  String req = client.readString();
  Serial.println(req);
  client.flush();
 
  // Switch the LED state according to the received value
  if (req.indexOf("ON") != -1){
    digitalWrite(5, 1);
  }else if (req.indexOf("OFF") != -1){
    digitalWrite(5, 0);
  }else{
    Serial.println("invalid request");
    client.stop();
    return;
  }
 
  client.flush();
 
  // Send HTTP response to the client
  String s = "HTTP/1.1 200 OK\r\n";
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");
 
}
 
 
// Method in charge of sending request to the CSE
String send(String url,int ty, String rep) {
 
  // Connect to the CSE address
  Serial.print("connecting to ");
  Serial.println(host);
 
  WiFiClient client;
 
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return "error";
  }
 
 
  // prepare the HTTP request
  String req = String()+"POST " + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "X-M2M-Origin: " + origin + "\r\n" +
               "Content-Type: application/json;ty="+ty+"\r\n" +
               "Content-Length: "+ rep.length()+"\r\n"
               "Connection: close\r\n\n" + 
               rep;
 
  Serial.println(req+"\n");
 
  // Send the HTTP request
  client.print(req);
 
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return "error";
    }
  }
 
  // Read the HTTP response
  String res="";
  if(client.available()){
    res = client.readStringUntil('\r');
    Serial.print(res);
  }
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }
 
  Serial.println();
  Serial.println("closing connection");
  Serial.println();
  return res;
}

Copyright © Eclipse Foundation, Inc. All Rights Reserved.