Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package iotivity.cloudstack.client;
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import java.nio.ByteBuffer;
- import java.nio.charset.Charset;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Random;
- import java.util.Scanner;
- import java.util.UUID;
- import org.iotivity.cloud.base.CoapClient;
- import org.iotivity.cloud.base.protocols.coap.CoapRequest;
- import org.iotivity.cloud.base.protocols.coap.CoapResponse;
- import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
- import org.iotivity.cloud.base.protocols.coap.enums.CoapOption;
- import org.iotivity.cloud.util.Cbor;
- import org.iotivity.cloud.util.JSONUtil;
- import org.iotivity.cloud.util.Logger;
- import org.iotivity.cloud.util.Net;
- import com.fasterxml.jackson.core.JsonParseException;
- import com.fasterxml.jackson.core.JsonParser;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.JsonMappingException;
- import com.fasterxml.jackson.databind.JsonNode;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.fasterxml.jackson.databind.node.ArrayNode;
- import com.fasterxml.jackson.databind.node.ObjectNode;
- import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
- import io.netty.channel.ChannelHandlerContext;
- public class SampleCloudClient implements HandleCompleteListener {
- public static final int APPLICATION_JSON = 50;
- Scanner scan = new Scanner(System.in);
- IotivityCloudSession session = new IotivityCloudSession();
- int deltaTime = 0;
- MachineState ms = MachineState.INIT;
- CoapClient coapc = new CoapClient();
- String hostname = "127.0.0.1";
- int CIServerPort = 5683;
- int MAX_TOKEN_LEN = 8;
- public enum MachineState {
- INIT, EXIT, REG, /* LOGIN, */COMMAND, PUBLISH, DISCOVER, WAIT, RESULT
- };
- public SampleCloudClient(String ipaddr, int port)
- {
- this.hostname = ipaddr;
- this.CIServerPort = port;
- }
- public void Run() throws InterruptedException {
- while (ms != MachineState.EXIT) {
- switch (ms) {
- case INIT:
- // print usage
- // System.out.println("Usage");
- // prepare coap client
- prepareClient();
- ms = MachineState.REG;
- break;
- case REG:
- try {
- RegisterLogin();
- } catch (JsonParseException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (JsonMappingException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- break;
- /*
- * case LOGIN: try { loginCloud(); ms = MachineState.WAIT; } catch
- * (JsonParseException e1) { // TODO Auto-generated catch block
- * e1.printStackTrace(); } catch (JsonMappingException e1) { // TODO
- * Auto-generated catch block e1.printStackTrace(); } catch
- * (IOException e1) { // TODO Auto-generated catch block
- * e1.printStackTrace(); } break;
- */
- case COMMAND:
- // wait for user command
- System.out.println("Waiting for next command: c-discover s-publish q-query u-update");
- String cmd = scan.next();
- if (cmd.equals("EXIT")) {
- ms = MachineState.EXIT;
- }
- if (cmd.equals("c")) {
- try {
- SendDiscoveryRequest();
- } catch (JsonParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (JsonMappingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if (cmd.equals("s")) {
- SendPublishRequest();
- }
- // query for a resource
- if (cmd.equals("q")) {
- try {
- QueryResRequest();
- } catch (JsonParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (JsonMappingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- // update resource
- if (cmd.equals("u")) {
- try {
- UpdateResRequest();
- } catch (JsonParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (JsonMappingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if (cmd.equals("MAN")) {
- try {
- System.out.println("sample: GET /oic/res rt=core.light null");
- // String command = scan.nextLine();
- // String[] tokens = command.split("\\s+");
- String method = scan.next();
- String uri = scan.next();
- String temp = scan.next();
- String query = temp.equals("null") ? null : temp;
- temp = scan.next();
- String payload = temp.equals("null") ? null : temp;
- CustomRequest(CoapMethod.valueOf(method), uri, query, payload);
- } catch (JsonParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (JsonMappingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- break;
- case WAIT:
- if (deltaTime > 150000) {
- // timeout
- ms = MachineState.EXIT;
- System.out.println("Client timeout");
- // should go back to wait for command -> session
- }
- try {
- if (deltaTime == 0) {
- System.out.println("Waiting for response.");
- }
- Thread.sleep(500);
- deltaTime += 500;
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- break;
- default:
- break;
- }
- }
- coapc.stopClient();
- System.out.println("Exit");
- System.exit(0);
- return;
- }
- // use request token to match correct handler
- @SuppressWarnings("static-access")
- public void OnComplete(CoapResponse msg) {
- deltaTime = 0;
- Cbor<HashMap<Object, Object>> cborhmap = new Cbor<HashMap<Object, Object>>();
- byte[] payload = msg.getPayload();
- switch (msg.getResponseCode().getCode()) {
- case 128:
- // see enum CoapStatus
- System.out.println("bad request");
- break;
- case 69:
- /*
- * Cbor<ArrayList<Object>> cboral = new Cbor<ArrayList<Object>>();
- * ArrayList<Object> decodedPayload =
- * cboral.parsePayloadFromCbor(payload, ArrayList.class); JSONUtilf
- * util = new JSONUtilf();
- * util.config(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
- */
- // !! it is hot Arraylist Or JOSN??
- /*
- * Map<String, String> jo; try { jo =
- * util.parseJSON(decodedPayload.get(0).toString()); for
- * (Map.Entry<String, String> e : jo.entrySet()) {
- * System.out.println(String.format("%s:%s", e.getKey(),
- * e.getValue())); } } catch (JsonParseException e1) { // TODO
- * Auto-generated catch block e1.printStackTrace(); } catch
- * (JsonMappingException e1) { // TODO Auto-generated catch block
- * e1.printStackTrace(); } catch (IOException e1) { // TODO
- * Auto-generated catch block e1.printStackTrace(); }
- */
- // Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object,
- // Object>>();
- if (payload != null) {
- CBORFactory f = new CBORFactory();
- ObjectMapper mapper = new ObjectMapper(f);
- JsonNode jnode;
- try {
- jnode = mapper.readTree(payload);
- printAll(jnode);
- } catch (JsonProcessingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- /*
- * try { HashMap<Object, Object> payloadData =
- * cborhmap.parsePayloadFromCbor(payload, HashMap.class);
- *
- * for (Map.Entry<Object, Object> entry :
- * payloadData.entrySet()) { if
- * (entry.getKey().toString().toLowerCase().equals("session")) {
- * session.setSessionId(entry.getValue().toString()); } } }
- * catch (Exception e) { CBORFactory f = new CBORFactory();
- * ObjectMapper mapper = new ObjectMapper(f); try { JsonNode
- * jnode = mapper.readTree(payload); printAll(jnode); String
- * nodetext = jnode.asText();
- *
- * Iterator<Entry<String,JsonNode>> it = jnode.fields();
- * while(it.hasNext()) { Entry<String,JsonNode> treenode =
- * it.next(); System.out.println(String.format("%s - %s",
- * treenode.getKey(), treenode.getValue().asText())); } } catch
- * (JsonProcessingException e1) { // TODO Auto-generated catch
- * block e1.printStackTrace(); } catch (IOException e1) { //
- * TODO Auto-generated catch block e1.printStackTrace(); }
- * System.out.println(msg.getPayloadString());
- * System.out.println("not a hashmap " +
- * msg.getContentFormatString()); }
- */
- }
- break;
- default:
- if (payload != null) {
- try {
- HashMap<Object, Object> payloadData = cborhmap.parsePayloadFromCbor(payload, HashMap.class);
- for (Map.Entry<Object, Object> entry : payloadData.entrySet()) {
- // System.out.println(String.format("%s - %s",
- // entry.getKey(), entry.getValue()));
- if (entry.getKey().toString().toLowerCase().equals("session")) {
- session.setSessionId(entry.getValue().toString());
- // You can login using received session variable
- // after
- // disconnected or reboot
- // ms = MachineState.LOGIN;
- }
- }
- } catch (Exception e) {
- /*
- * // TODO Auto-generated catch block String utf = new
- * String(payload, Charset.forName("UTF-8")); String ascii =
- * new String(payload, Charset.forName("US-ASCII"));
- *
- * // cbor -97 -1? // ArrayList? Cbor<ArrayList<Object>>
- * cboral = new Cbor<ArrayList<Object>>(); ArrayList<Object>
- * decodedPayload = cboral.parsePayloadFromCbor(payload,
- * ArrayList.class); String test1 =
- * decodedPayload.get(0).toString();
- */
- e.printStackTrace();
- }
- }
- break;
- }
- // CoapDecoder coapdecoder = new CoapDecoder();
- /*
- * Map<String, String> response = JSONUtil .parseJSON(new
- * String(msg.getPayload(), StandardCharsets.UTF_8));
- */
- // 15:55:20:126 [D] userId: maxiwu, sessionCode: xl7qbTPgYwqQnvAM
- // 15:55:20:127 [D] responseJson:
- // {"session":"xl7qbTPgYwqQnvAM","userid":"maxiwu"}
- // session login return code 128 bad request, dont know why
- // TODO Auto-generated method stub
- ms = MachineState.COMMAND;
- }
- public void printAll(JsonNode node) {
- // TODO Auto-generated method stub
- switch (node.getNodeType()) {
- case ARRAY:
- Iterator<JsonNode> elements = node.elements();
- while (elements.hasNext()) {
- printAll(elements.next());
- }
- break;
- case OBJECT:
- Iterator<String> fieldNames = node.fieldNames();
- while (fieldNames.hasNext()) {
- String fieldName = fieldNames.next();
- JsonNode fieldValue = node.get(fieldName);
- if (fieldValue.isObject()) {
- System.out.println(fieldName + " :");
- printAll(fieldValue);
- } else if (fieldValue.isArray()) {
- System.out.println(fieldName + " :");
- printAll(fieldValue);
- } else {
- String value = fieldValue.asText();
- System.out.println(fieldName + " : " + value);
- }
- }
- break;
- default:
- Iterator<String> f = node.fieldNames();
- while (f.hasNext()) {
- String fieldName = f.next();
- JsonNode fieldValue = node.get(fieldName);
- if (fieldValue.isObject()) {
- System.out.println(fieldName + " :");
- printAll(fieldValue);
- } else {
- String value = fieldValue.asText();
- System.out.println(fieldName + " : " + value);
- }
- }
- break;
- }
- }
- public void RegisterLogin() throws JsonParseException, JsonMappingException, IOException {
- // create a dialog system and handle user command
- System.out.println("Please Choose Register(r) or login(l):");
- String rl = scan.next();
- if (rl.equals("r")) {
- System.out.print("github Auth Code:");
- String authcode = scan.next();
- // login to iotivity cloud
- registerCloud(authcode);
- // start a session
- ms = MachineState.WAIT;
- } else if (rl.equals("l")) {
- System.out.print("Session Code:");
- String sid = scan.next();
- // login to iotivity cloud
- loginCloud(sid);
- // start a session
- ms = MachineState.WAIT;
- }
- // session.setSessionId(sessionId);
- }
- private void prepareClient() throws InterruptedException {
- // TODO Auto-generated method stub
- SimpleTextResponseHandler simHandler = new SimpleTextResponseHandler();
- InetSocketAddress inetSocketAddress = new InetSocketAddress(hostname, CIServerPort);
- simHandler.addListener(this);
- coapc.addHandler(simHandler);
- coapc.startClient(inetSocketAddress);
- }
- public void registerCloud(String authcode) throws JsonParseException, JsonMappingException, IOException {
- Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
- CoapRequest request = new CoapRequest(CoapMethod.POST);
- // auth code changes!
- // String authcode = "b152d6b860b12e73f5e8";
- String jsonString = "{\"authcode\":\"" + authcode + "\",\"authprovider\":\"github\"}";
- Map<String, String> payloadMap = JSONUtil.parseJSON(jsonString);
- // json in byte
- // look at coap message builder, application/json is 50 in bytes
- byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
- request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
- request.setUriPath("/oic/auth");
- request.setUriQuery("reqtype=register");
- // generate 0~8 bytes random token for Coap
- byte[] ranToken = new byte[MAX_TOKEN_LEN];
- new Random().nextBytes(ranToken);
- request.setToken(ranToken);
- request.setPayload(cbor.encodingPayloadToCbor(payloadMap));
- coapc.sendRequest(request);
- }
- private void loginCloud(String sid) throws JsonParseException, JsonMappingException, IOException {
- session.setSessionId(sid);
- Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
- CoapRequest request = new CoapRequest(CoapMethod.POST);
- String jsonString = String.format("{\"session\":\"%s\"}", session.getSessionId());
- Map<String, String> payloadMap = JSONUtil.parseJSON(jsonString);
- // json in byte
- // look at coap message builder, application/json is 50 in bytes
- byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
- request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
- request.setUriPath("/oic/auth");
- request.setUriQuery("reqtype=login");
- // generate 0~8 bytes random token for Coap
- byte[] ranToken = new byte[MAX_TOKEN_LEN];
- new Random().nextBytes(ranToken);
- request.setToken(ranToken);
- request.setPayload(cbor.encodingPayloadToCbor(payloadMap));
- coapc.sendRequest(request);
- }
- private void SendDiscoveryRequest() throws JsonParseException, JsonMappingException, IOException {
- Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
- CoapRequest request = new CoapRequest(CoapMethod.GET);
- if (session.getSessionId() == null) {
- System.out.println("invalid session or null");
- ms = MachineState.EXIT;
- }
- // need an empty payload
- request.setPayload(null);
- // json in byte
- // look at coap message builder, application/json is 50 in bytes
- byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
- request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
- // other discovery /oic/rts /oic/ifs
- request.setUriPath("/oic/res");
- // rt = oic.r.light?
- request.setUriQuery("if=oic.if.baseline");
- // generate 0~8 bytes random token for Coap
- byte[] ranToken = new byte[MAX_TOKEN_LEN];
- new Random().nextBytes(ranToken);
- request.setToken(ranToken);
- coapc.sendRequest(request);
- }
- private void QueryResRequest() throws JsonParseException, JsonMappingException, IOException {
- Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
- CoapRequest request = new CoapRequest(CoapMethod.GET);
- if (session.getSessionId() == null) {
- System.out.println("invalid session or null");
- ms = MachineState.EXIT;
- }
- // need an empty payload
- request.setPayload(null);
- // json in byte
- // look at coap message builder, application/json is 50 in bytes
- byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
- request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
- // other discovery /oic/rts /oic/ifs
- // request.setUriPath("/a/light/0");
- request.setUriPath("/oic/res");
- request.setUriQuery("rt=core.light");
- // generate 0~8 bytes random token for Coap
- byte[] ranToken = new byte[MAX_TOKEN_LEN];
- new Random().nextBytes(ranToken);
- request.setToken(ranToken);
- coapc.sendRequest(request);
- }
- private void UpdateResRequest() throws JsonParseException, JsonMappingException, IOException {
- Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
- CoapRequest request = new CoapRequest(CoapMethod.PUT);
- if (session.getSessionId() == null) {
- System.out.println("invalid session or null");
- ms = MachineState.EXIT;
- }
- //String jsonString = String.format("{\"n\":\"public_light\",\"state\":\"0\",\"\":\"\"}");
- String jsonString = String.format("{\"n\":\"title\",\"title\":\"test\"}");
- Map<String, String> payloadMap = JSONUtil.parseJSON(jsonString);
- request.setPayload(cbor.encodingPayloadToCbor(payloadMap));
- // json in byte
- // look at coap message builder, application/json is 50 in bytes
- byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
- request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
- // other discovery /oic/rts /oic/ifs
- //request.setUriPath("/oic/res");
- //uri should be that resource, for exmaple /a/light
- String hostAddress = Net.getMyIpAddress().replace("/", "");
- request.setUriPath(String.format("/%s/60d5bcfc-7844-40f9-8627-3fa19648e999/b/thermo/0",hostAddress));
- // rt = oic.r.light?
- request.setUriQuery("if=oic.if.baseline");
- // generate 0~8 bytes random token for Coap
- byte[] ranToken = new byte[MAX_TOKEN_LEN];
- new Random().nextBytes(ranToken);
- request.setToken(ranToken);
- coapc.sendRequest(request);
- }
- private void CustomRequest(CoapMethod method, String uri, String query, String payload)
- throws JsonParseException, JsonMappingException, IOException {
- Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
- CoapRequest request = new CoapRequest(method);
- if (session.getSessionId() == null) {
- System.out.println("invalid session or null");
- ms = MachineState.EXIT;
- }
- request.setPayload(null);
- if (payload != null) {
- Map<String, String> payloadMap = JSONUtil.parseJSON(payload);
- request.setPayload(cbor.encodingPayloadToCbor(payloadMap));
- }
- // json in byte
- // look at coap message builder, application/json is 50 in bytes
- byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
- request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
- // other discovery /oic/rts /oic/ifs
- request.setUriPath(uri);
- // rt = oic.r.light?
- if (query != null) {
- request.setUriQuery(query);
- }
- // generate 0~8 bytes random token for Coap
- byte[] ranToken = new byte[MAX_TOKEN_LEN];
- new Random().nextBytes(ranToken);
- request.setToken(ranToken);
- coapc.sendRequest(request);
- }
- private void SendPublishRequest() {
- // cloud accept ArrayList only... dont know why, tags and collection is
- // mandatory?
- // must have a query...
- ObjectMapper mapper = new ObjectMapper();
- // ArrayNode collection = mapper.createArrayNode();
- ArrayList<Object> collection = new ArrayList<Object>();
- HashMap<Object, Object> tag = new HashMap<Object, Object>();
- ArrayList<HashMap<Object, Object>> links = new ArrayList<HashMap<Object, Object>>();
- HashMap<Object, Object> resRep = new HashMap<Object, Object>();
- resRep.put("n", "Thermometer");
- /*
- * String hostAddress = Net.getMyIpAddress().replace("/", "");
- * resRep.put("href", String.format("%s/b/thermo/0"));
- */
- resRep.put("href", "/b/thermo/0");
- List<String> rtl = Arrays.asList("oic.r.temperature");
- resRep.put("rt", rtl);
- List<String> ifl = Arrays.asList("oic.if.a");
- resRep.put("if", ifl);
- resRep.put("id", "LIVING_ROOM_TEMP");
- byte policy = 0x03;
- // policy = policy | (1 << 1); //observable
- // policy = policy | (1 << 2); //discoverable
- resRep.put("bm", policy);
- resRep.put("unit", "Celcius");
- resRep.put("current_value", 27);
- resRep.put("Set_value", 0);
- // System.out.println(resRep.toString());
- tag.put("di", UUID.randomUUID().toString());
- tag.put("n", "Single_device_collection");
- tag.put("bm", policy);
- links.add(resRep);
- collection.add(tag);
- collection.add(links);
- System.out.println(collection.toString());
- Cbor<ArrayList<Object>> cbor = new Cbor<ArrayList<Object>>();
- byte[] encodedpayload = cbor.encodingPayloadToCbor(collection);
- // POST for create
- CoapRequest request = new CoapRequest(CoapMethod.POST);
- if (session.getSessionId() == null) {
- System.out.println("invalid session or null");
- ms = MachineState.EXIT;
- } // does GET
- request.setPayload(encodedpayload);
- byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
- request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
- // publish resource to RD should be
- // /oic/rd, with 'tags' and did
- // oic://<Authority>/<Path>?<Query>
- // Logger.i("hostAddress : " + hostAddress);
- request.setUriPath("/oic/rd");
- // request.setUriPath(String.format("%s:5683/b/thermo/0",hostAddress));
- request.setUriQuery("rt=oic.wk.rdpub&if=oic.if.baseline");
- // generate 0~8 bytes random token for Coap
- byte[] ranToken = new byte[MAX_TOKEN_LEN];
- new Random().nextBytes(ranToken);
- request.setToken(ranToken);
- coapc.sendRequest(request);
- }
- // not yet complete
- /*
- * private void SendPublishRequest() throws JsonParseException,
- * JsonMappingException, IOException { //throw new
- * UnsupportedOperationException();
- *
- * //Cbor<HashMap<Object, Object>> cbor = new
- * Cbor<HashMap<Object,Object>>(); //use a json tree model to create a
- * resources //JsonNode resRep = new JsonNode();
- *
- *
- *
- * }
- */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement