Advertisement
maxiwu

sampleClientClass

Jul 1st, 2016
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 22.40 KB | None | 0 0
  1. package iotivity.cloudstack.client;
  2.  
  3. import java.io.IOException;
  4. import java.net.InetSocketAddress;
  5. import java.nio.ByteBuffer;
  6. import java.nio.charset.Charset;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.HashMap;
  10. import java.util.Iterator;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.Map.Entry;
  14. import java.util.Random;
  15. import java.util.Scanner;
  16. import java.util.UUID;
  17.  
  18. import org.iotivity.cloud.base.CoapClient;
  19. import org.iotivity.cloud.base.protocols.coap.CoapRequest;
  20. import org.iotivity.cloud.base.protocols.coap.CoapResponse;
  21. import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
  22. import org.iotivity.cloud.base.protocols.coap.enums.CoapOption;
  23. import org.iotivity.cloud.util.Cbor;
  24. import org.iotivity.cloud.util.JSONUtil;
  25. import org.iotivity.cloud.util.Logger;
  26. import org.iotivity.cloud.util.Net;
  27.  
  28. import com.fasterxml.jackson.core.JsonParseException;
  29. import com.fasterxml.jackson.core.JsonParser;
  30. import com.fasterxml.jackson.core.JsonProcessingException;
  31. import com.fasterxml.jackson.databind.JsonMappingException;
  32. import com.fasterxml.jackson.databind.JsonNode;
  33. import com.fasterxml.jackson.databind.ObjectMapper;
  34. import com.fasterxml.jackson.databind.node.ArrayNode;
  35. import com.fasterxml.jackson.databind.node.ObjectNode;
  36. import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
  37.  
  38. import io.netty.channel.ChannelHandlerContext;
  39.  
  40. public class SampleCloudClient implements HandleCompleteListener {
  41.  
  42.     public static final int APPLICATION_JSON = 50;
  43.     Scanner scan = new Scanner(System.in);
  44.     IotivityCloudSession session = new IotivityCloudSession();
  45.     int deltaTime = 0;
  46.     MachineState ms = MachineState.INIT;
  47.     CoapClient coapc = new CoapClient();
  48.     String hostname = "127.0.0.1";
  49.     int CIServerPort = 5683;
  50.     int MAX_TOKEN_LEN = 8;
  51.  
  52.     public enum MachineState {
  53.         INIT, EXIT, REG, /* LOGIN, */COMMAND, PUBLISH, DISCOVER, WAIT, RESULT
  54.     };
  55.  
  56.     public SampleCloudClient(String ipaddr, int port)
  57.     {
  58.         this.hostname = ipaddr;
  59.         this.CIServerPort = port;
  60.     }
  61.  
  62.     public void Run() throws InterruptedException {
  63.         while (ms != MachineState.EXIT) {
  64.             switch (ms) {
  65.             case INIT:
  66.                 // print usage
  67.                 // System.out.println("Usage");
  68.  
  69.                 // prepare coap client
  70.                 prepareClient();
  71.  
  72.                 ms = MachineState.REG;
  73.                 break;
  74.             case REG:
  75.                 try {
  76.                     RegisterLogin();
  77.                 } catch (JsonParseException e1) {
  78.                     // TODO Auto-generated catch block
  79.                     e1.printStackTrace();
  80.                 } catch (JsonMappingException e1) {
  81.                     // TODO Auto-generated catch block
  82.                     e1.printStackTrace();
  83.                 } catch (IOException e1) {
  84.                     // TODO Auto-generated catch block
  85.                     e1.printStackTrace();
  86.                 }
  87.                 break;
  88.             /*
  89.              * case LOGIN: try { loginCloud(); ms = MachineState.WAIT; } catch
  90.              * (JsonParseException e1) { // TODO Auto-generated catch block
  91.              * e1.printStackTrace(); } catch (JsonMappingException e1) { // TODO
  92.              * Auto-generated catch block e1.printStackTrace(); } catch
  93.              * (IOException e1) { // TODO Auto-generated catch block
  94.              * e1.printStackTrace(); } break;
  95.              */
  96.             case COMMAND:
  97.                 // wait for user command
  98.                 System.out.println("Waiting for next command: c-discover s-publish q-query u-update");
  99.                 String cmd = scan.next();
  100.                 if (cmd.equals("EXIT")) {
  101.                     ms = MachineState.EXIT;
  102.                 }
  103.                 if (cmd.equals("c")) {
  104.                     try {
  105.                         SendDiscoveryRequest();
  106.                     } catch (JsonParseException e) {
  107.                         // TODO Auto-generated catch block
  108.                         e.printStackTrace();
  109.                     } catch (JsonMappingException e) {
  110.                         // TODO Auto-generated catch block
  111.                         e.printStackTrace();
  112.                     } catch (IOException e) {
  113.                         // TODO Auto-generated catch block
  114.                         e.printStackTrace();
  115.                     }
  116.                 }
  117.                 if (cmd.equals("s")) {
  118.                     SendPublishRequest();
  119.                 }
  120.                 // query for a resource
  121.                 if (cmd.equals("q")) {
  122.                     try {
  123.                         QueryResRequest();
  124.                     } catch (JsonParseException e) {
  125.                         // TODO Auto-generated catch block
  126.                         e.printStackTrace();
  127.                     } catch (JsonMappingException e) {
  128.                         // TODO Auto-generated catch block
  129.                         e.printStackTrace();
  130.                     } catch (IOException e) {
  131.                         // TODO Auto-generated catch block
  132.                         e.printStackTrace();
  133.                     }
  134.                 }
  135.                 // update resource
  136.                 if (cmd.equals("u")) {
  137.                     try {
  138.                         UpdateResRequest();
  139.                     } catch (JsonParseException e) {
  140.                         // TODO Auto-generated catch block
  141.                         e.printStackTrace();
  142.                     } catch (JsonMappingException e) {
  143.                         // TODO Auto-generated catch block
  144.                         e.printStackTrace();
  145.                     } catch (IOException e) {
  146.                         // TODO Auto-generated catch block
  147.                         e.printStackTrace();
  148.                     }
  149.                 }
  150.                 if (cmd.equals("MAN")) {
  151.                     try {
  152.                         System.out.println("sample: GET /oic/res rt=core.light null");
  153.                         // String command = scan.nextLine();
  154.                         // String[] tokens = command.split("\\s+");
  155.                         String method = scan.next();
  156.                         String uri = scan.next();
  157.                         String temp = scan.next();
  158.                         String query = temp.equals("null") ? null : temp;
  159.                         temp = scan.next();
  160.                         String payload = temp.equals("null") ? null : temp;
  161.                         CustomRequest(CoapMethod.valueOf(method), uri, query, payload);
  162.                     } catch (JsonParseException e) {
  163.                         // TODO Auto-generated catch block
  164.                         e.printStackTrace();
  165.                     } catch (JsonMappingException e) {
  166.                         // TODO Auto-generated catch block
  167.                         e.printStackTrace();
  168.                     } catch (IOException e) {
  169.                         // TODO Auto-generated catch block
  170.                         e.printStackTrace();
  171.                     }
  172.                 }
  173.                 break;
  174.             case WAIT:
  175.                 if (deltaTime > 150000) {
  176.                     // timeout
  177.                     ms = MachineState.EXIT;
  178.                     System.out.println("Client timeout");
  179.                     // should go back to wait for command -> session
  180.                 }
  181.                 try {
  182.                     if (deltaTime == 0) {
  183.                         System.out.println("Waiting for response.");
  184.                     }
  185.                     Thread.sleep(500);
  186.                     deltaTime += 500;
  187.                 } catch (InterruptedException e) {
  188.                     // TODO Auto-generated catch block
  189.                     e.printStackTrace();
  190.                 }
  191.                 break;
  192.             default:
  193.                 break;
  194.             }
  195.         }
  196.         coapc.stopClient();
  197.        
  198.         System.out.println("Exit");
  199.        
  200.         System.exit(0);
  201.         return;
  202.  
  203.     }
  204.  
  205.     // use request token to match correct handler
  206.     @SuppressWarnings("static-access")
  207.     public void OnComplete(CoapResponse msg) {
  208.  
  209.         deltaTime = 0;
  210.         Cbor<HashMap<Object, Object>> cborhmap = new Cbor<HashMap<Object, Object>>();
  211.         byte[] payload = msg.getPayload();
  212.  
  213.         switch (msg.getResponseCode().getCode()) {
  214.         case 128:
  215.             // see enum CoapStatus
  216.             System.out.println("bad request");
  217.             break;
  218.         case 69:
  219.             /*
  220.              * Cbor<ArrayList<Object>> cboral = new Cbor<ArrayList<Object>>();
  221.              * ArrayList<Object> decodedPayload =
  222.              * cboral.parsePayloadFromCbor(payload, ArrayList.class); JSONUtilf
  223.              * util = new JSONUtilf();
  224.              * util.config(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
  225.              */
  226.  
  227.             // !! it is hot Arraylist Or JOSN??
  228.             /*
  229.              * Map<String, String> jo; try { jo =
  230.              * util.parseJSON(decodedPayload.get(0).toString()); for
  231.              * (Map.Entry<String, String> e : jo.entrySet()) {
  232.              * System.out.println(String.format("%s:%s", e.getKey(),
  233.              * e.getValue())); } } catch (JsonParseException e1) { // TODO
  234.              * Auto-generated catch block e1.printStackTrace(); } catch
  235.              * (JsonMappingException e1) { // TODO Auto-generated catch block
  236.              * e1.printStackTrace(); } catch (IOException e1) { // TODO
  237.              * Auto-generated catch block e1.printStackTrace(); }
  238.              */
  239.             // Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object,
  240.             // Object>>();
  241.             if (payload != null) {
  242.                 CBORFactory f = new CBORFactory();
  243.                 ObjectMapper mapper = new ObjectMapper(f);
  244.                 JsonNode jnode;
  245.                 try {
  246.                     jnode = mapper.readTree(payload);
  247.                     printAll(jnode);
  248.                 } catch (JsonProcessingException e) {
  249.                     // TODO Auto-generated catch block
  250.                     e.printStackTrace();
  251.                 } catch (IOException e) {
  252.                     // TODO Auto-generated catch block
  253.                     e.printStackTrace();
  254.                 }
  255.  
  256.                 /*
  257.                  * try { HashMap<Object, Object> payloadData =
  258.                  * cborhmap.parsePayloadFromCbor(payload, HashMap.class);
  259.                  *
  260.                  * for (Map.Entry<Object, Object> entry :
  261.                  * payloadData.entrySet()) { if
  262.                  * (entry.getKey().toString().toLowerCase().equals("session")) {
  263.                  * session.setSessionId(entry.getValue().toString()); } } }
  264.                  * catch (Exception e) { CBORFactory f = new CBORFactory();
  265.                  * ObjectMapper mapper = new ObjectMapper(f); try { JsonNode
  266.                  * jnode = mapper.readTree(payload); printAll(jnode); String
  267.                  * nodetext = jnode.asText();
  268.                  *
  269.                  * Iterator<Entry<String,JsonNode>> it = jnode.fields();
  270.                  * while(it.hasNext()) { Entry<String,JsonNode> treenode =
  271.                  * it.next(); System.out.println(String.format("%s - %s",
  272.                  * treenode.getKey(), treenode.getValue().asText())); } } catch
  273.                  * (JsonProcessingException e1) { // TODO Auto-generated catch
  274.                  * block e1.printStackTrace(); } catch (IOException e1) { //
  275.                  * TODO Auto-generated catch block e1.printStackTrace(); }
  276.                  * System.out.println(msg.getPayloadString());
  277.                  * System.out.println("not a hashmap " +
  278.                  * msg.getContentFormatString()); }
  279.                  */
  280.  
  281.             }
  282.             break;
  283.         default:
  284.  
  285.             if (payload != null) {
  286.                 try {
  287.                     HashMap<Object, Object> payloadData = cborhmap.parsePayloadFromCbor(payload, HashMap.class);
  288.  
  289.                     for (Map.Entry<Object, Object> entry : payloadData.entrySet()) {
  290.                         // System.out.println(String.format("%s - %s",
  291.                         // entry.getKey(), entry.getValue()));
  292.                         if (entry.getKey().toString().toLowerCase().equals("session")) {
  293.                             session.setSessionId(entry.getValue().toString());
  294.  
  295.                             // You can login using received session variable
  296.                             // after
  297.                             // disconnected or reboot
  298.                             // ms = MachineState.LOGIN;
  299.                         }
  300.                     }
  301.                 } catch (Exception e) {
  302.  
  303.                     /*
  304.                      * // TODO Auto-generated catch block String utf = new
  305.                      * String(payload, Charset.forName("UTF-8")); String ascii =
  306.                      * new String(payload, Charset.forName("US-ASCII"));
  307.                      *
  308.                      * // cbor -97 -1? // ArrayList? Cbor<ArrayList<Object>>
  309.                      * cboral = new Cbor<ArrayList<Object>>(); ArrayList<Object>
  310.                      * decodedPayload = cboral.parsePayloadFromCbor(payload,
  311.                      * ArrayList.class); String test1 =
  312.                      * decodedPayload.get(0).toString();
  313.                      */
  314.  
  315.                     e.printStackTrace();
  316.                 }
  317.             }
  318.             break;
  319.         }
  320.  
  321.         // CoapDecoder coapdecoder = new CoapDecoder();
  322.         /*
  323.          * Map<String, String> response = JSONUtil .parseJSON(new
  324.          * String(msg.getPayload(), StandardCharsets.UTF_8));
  325.          */
  326.  
  327.         // 15:55:20:126 [D] userId: maxiwu, sessionCode: xl7qbTPgYwqQnvAM
  328.         // 15:55:20:127 [D] responseJson:
  329.         // {"session":"xl7qbTPgYwqQnvAM","userid":"maxiwu"}
  330.  
  331.         // session login return code 128 bad request, dont know why
  332.  
  333.         // TODO Auto-generated method stub
  334.         ms = MachineState.COMMAND;
  335.     }
  336.  
  337.     public void printAll(JsonNode node) {
  338.         // TODO Auto-generated method stub
  339.         switch (node.getNodeType()) {
  340.         case ARRAY:
  341.             Iterator<JsonNode> elements = node.elements();
  342.             while (elements.hasNext()) {
  343.                 printAll(elements.next());
  344.             }
  345.             break;
  346.         case OBJECT:
  347.             Iterator<String> fieldNames = node.fieldNames();
  348.             while (fieldNames.hasNext()) {
  349.                 String fieldName = fieldNames.next();
  350.                 JsonNode fieldValue = node.get(fieldName);
  351.                 if (fieldValue.isObject()) {
  352.                     System.out.println(fieldName + " :");
  353.                     printAll(fieldValue);
  354.                 } else if (fieldValue.isArray()) {
  355.                     System.out.println(fieldName + " :");
  356.                     printAll(fieldValue);
  357.                 } else {
  358.                     String value = fieldValue.asText();
  359.                     System.out.println(fieldName + " : " + value);
  360.                 }
  361.             }
  362.             break;
  363.         default:
  364.             Iterator<String> f = node.fieldNames();
  365.             while (f.hasNext()) {
  366.                 String fieldName = f.next();
  367.                 JsonNode fieldValue = node.get(fieldName);
  368.                 if (fieldValue.isObject()) {
  369.                     System.out.println(fieldName + " :");
  370.                     printAll(fieldValue);
  371.                 } else {
  372.                     String value = fieldValue.asText();
  373.                     System.out.println(fieldName + " : " + value);
  374.                 }
  375.             }
  376.             break;
  377.         }
  378.     }
  379.  
  380.     public void RegisterLogin() throws JsonParseException, JsonMappingException, IOException {
  381.         // create a dialog system and handle user command
  382.         System.out.println("Please Choose Register(r) or login(l):");
  383.         String rl = scan.next();
  384.         if (rl.equals("r")) {
  385.             System.out.print("github Auth Code:");
  386.             String authcode = scan.next();
  387.             // login to iotivity cloud
  388.             registerCloud(authcode);
  389.             // start a session
  390.             ms = MachineState.WAIT;
  391.         } else if (rl.equals("l")) {
  392.             System.out.print("Session Code:");
  393.             String sid = scan.next();
  394.  
  395.             // login to iotivity cloud
  396.             loginCloud(sid);
  397.             // start a session
  398.             ms = MachineState.WAIT;
  399.         }
  400.         // session.setSessionId(sessionId);
  401.     }
  402.  
  403.     private void prepareClient() throws InterruptedException {
  404.         // TODO Auto-generated method stub
  405.         SimpleTextResponseHandler simHandler = new SimpleTextResponseHandler();
  406.  
  407.         InetSocketAddress inetSocketAddress = new InetSocketAddress(hostname, CIServerPort);
  408.         simHandler.addListener(this);
  409.         coapc.addHandler(simHandler);
  410.         coapc.startClient(inetSocketAddress);
  411.     }
  412.  
  413.     public void registerCloud(String authcode) throws JsonParseException, JsonMappingException, IOException {
  414.  
  415.         Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
  416.  
  417.         CoapRequest request = new CoapRequest(CoapMethod.POST);
  418.  
  419.         // auth code changes!
  420.         // String authcode = "b152d6b860b12e73f5e8";
  421.         String jsonString = "{\"authcode\":\"" + authcode + "\",\"authprovider\":\"github\"}";
  422.  
  423.         Map<String, String> payloadMap = JSONUtil.parseJSON(jsonString);
  424.         // json in byte
  425.         // look at coap message builder, application/json is 50 in bytes
  426.         byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
  427.         request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
  428.  
  429.         request.setUriPath("/oic/auth");
  430.         request.setUriQuery("reqtype=register");
  431.  
  432.         // generate 0~8 bytes random token for Coap
  433.         byte[] ranToken = new byte[MAX_TOKEN_LEN];
  434.         new Random().nextBytes(ranToken);
  435.         request.setToken(ranToken);
  436.  
  437.         request.setPayload(cbor.encodingPayloadToCbor(payloadMap));
  438.         coapc.sendRequest(request);
  439.     }
  440.  
  441.     private void loginCloud(String sid) throws JsonParseException, JsonMappingException, IOException {
  442.  
  443.         session.setSessionId(sid);
  444.  
  445.         Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
  446.  
  447.         CoapRequest request = new CoapRequest(CoapMethod.POST);
  448.  
  449.         String jsonString = String.format("{\"session\":\"%s\"}", session.getSessionId());
  450.  
  451.         Map<String, String> payloadMap = JSONUtil.parseJSON(jsonString);
  452.         // json in byte
  453.         // look at coap message builder, application/json is 50 in bytes
  454.         byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
  455.         request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
  456.  
  457.         request.setUriPath("/oic/auth");
  458.         request.setUriQuery("reqtype=login");
  459.  
  460.         // generate 0~8 bytes random token for Coap
  461.         byte[] ranToken = new byte[MAX_TOKEN_LEN];
  462.         new Random().nextBytes(ranToken);
  463.         request.setToken(ranToken);
  464.  
  465.         request.setPayload(cbor.encodingPayloadToCbor(payloadMap));
  466.         coapc.sendRequest(request);
  467.  
  468.     }
  469.  
  470.     private void SendDiscoveryRequest() throws JsonParseException, JsonMappingException, IOException {
  471.  
  472.         Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
  473.  
  474.         CoapRequest request = new CoapRequest(CoapMethod.GET);
  475.  
  476.         if (session.getSessionId() == null) {
  477.             System.out.println("invalid session or null");
  478.             ms = MachineState.EXIT;
  479.         }
  480.         // need an empty payload
  481.         request.setPayload(null);
  482.  
  483.         // json in byte
  484.         // look at coap message builder, application/json is 50 in bytes
  485.         byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
  486.         request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
  487.  
  488.         // other discovery /oic/rts /oic/ifs
  489.         request.setUriPath("/oic/res");
  490.         // rt = oic.r.light?
  491.         request.setUriQuery("if=oic.if.baseline");
  492.  
  493.         // generate 0~8 bytes random token for Coap
  494.         byte[] ranToken = new byte[MAX_TOKEN_LEN];
  495.         new Random().nextBytes(ranToken);
  496.         request.setToken(ranToken);
  497.  
  498.         coapc.sendRequest(request);
  499.  
  500.     }
  501.  
  502.     private void QueryResRequest() throws JsonParseException, JsonMappingException, IOException {
  503.  
  504.         Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
  505.  
  506.         CoapRequest request = new CoapRequest(CoapMethod.GET);
  507.  
  508.         if (session.getSessionId() == null) {
  509.             System.out.println("invalid session or null");
  510.             ms = MachineState.EXIT;
  511.         }
  512.         // need an empty payload
  513.         request.setPayload(null);
  514.  
  515.         // json in byte
  516.         // look at coap message builder, application/json is 50 in bytes
  517.         byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
  518.         request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
  519.  
  520.         // other discovery /oic/rts /oic/ifs
  521.         // request.setUriPath("/a/light/0");
  522.         request.setUriPath("/oic/res");
  523.         request.setUriQuery("rt=core.light");
  524.  
  525.         // generate 0~8 bytes random token for Coap
  526.         byte[] ranToken = new byte[MAX_TOKEN_LEN];
  527.         new Random().nextBytes(ranToken);
  528.         request.setToken(ranToken);
  529.  
  530.         coapc.sendRequest(request);
  531.  
  532.     }
  533.  
  534.     private void UpdateResRequest() throws JsonParseException, JsonMappingException, IOException {
  535.  
  536.         Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
  537.  
  538.         CoapRequest request = new CoapRequest(CoapMethod.PUT);
  539.  
  540.         if (session.getSessionId() == null) {
  541.             System.out.println("invalid session or null");
  542.             ms = MachineState.EXIT;
  543.         }
  544.  
  545.         //String jsonString = String.format("{\"n\":\"public_light\",\"state\":\"0\",\"\":\"\"}");
  546.         String jsonString = String.format("{\"n\":\"title\",\"title\":\"test\"}");
  547.         Map<String, String> payloadMap = JSONUtil.parseJSON(jsonString);
  548.         request.setPayload(cbor.encodingPayloadToCbor(payloadMap));
  549.  
  550.         // json in byte
  551.         // look at coap message builder, application/json is 50 in bytes
  552.         byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
  553.         request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
  554.  
  555.         // other discovery /oic/rts /oic/ifs
  556.         //request.setUriPath("/oic/res");
  557.         //uri should be that resource, for exmaple /a/light
  558.         String hostAddress = Net.getMyIpAddress().replace("/", "");
  559.         request.setUriPath(String.format("/%s/60d5bcfc-7844-40f9-8627-3fa19648e999/b/thermo/0",hostAddress));
  560.         // rt = oic.r.light?
  561.         request.setUriQuery("if=oic.if.baseline");
  562.  
  563.         // generate 0~8 bytes random token for Coap
  564.         byte[] ranToken = new byte[MAX_TOKEN_LEN];
  565.         new Random().nextBytes(ranToken);
  566.         request.setToken(ranToken);
  567.  
  568.         coapc.sendRequest(request);
  569.  
  570.     }
  571.  
  572.     private void CustomRequest(CoapMethod method, String uri, String query, String payload)
  573.             throws JsonParseException, JsonMappingException, IOException {
  574.  
  575.         Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
  576.  
  577.         CoapRequest request = new CoapRequest(method);
  578.  
  579.         if (session.getSessionId() == null) {
  580.             System.out.println("invalid session or null");
  581.             ms = MachineState.EXIT;
  582.         }
  583.  
  584.         request.setPayload(null);
  585.         if (payload != null) {
  586.             Map<String, String> payloadMap = JSONUtil.parseJSON(payload);
  587.             request.setPayload(cbor.encodingPayloadToCbor(payloadMap));
  588.         }
  589.  
  590.         // json in byte
  591.         // look at coap message builder, application/json is 50 in bytes
  592.         byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
  593.         request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
  594.  
  595.         // other discovery /oic/rts /oic/ifs
  596.         request.setUriPath(uri);
  597.         // rt = oic.r.light?
  598.         if (query != null) {
  599.             request.setUriQuery(query);
  600.         }
  601.  
  602.         // generate 0~8 bytes random token for Coap
  603.         byte[] ranToken = new byte[MAX_TOKEN_LEN];
  604.         new Random().nextBytes(ranToken);
  605.         request.setToken(ranToken);
  606.  
  607.         coapc.sendRequest(request);
  608.  
  609.     }
  610.  
  611.     private void SendPublishRequest() {
  612.  
  613.         // cloud accept ArrayList only... dont know why, tags and collection is
  614.         // mandatory?
  615.         // must have a query...
  616.  
  617.         ObjectMapper mapper = new ObjectMapper();
  618.         // ArrayNode collection = mapper.createArrayNode();
  619.         ArrayList<Object> collection = new ArrayList<Object>();
  620.  
  621.         HashMap<Object, Object> tag = new HashMap<Object, Object>();
  622.         ArrayList<HashMap<Object, Object>> links = new ArrayList<HashMap<Object, Object>>();
  623.  
  624.         HashMap<Object, Object> resRep = new HashMap<Object, Object>();
  625.  
  626.         resRep.put("n", "Thermometer");
  627.         /*
  628.          * String hostAddress = Net.getMyIpAddress().replace("/", "");
  629.          * resRep.put("href", String.format("%s/b/thermo/0"));
  630.          */
  631.         resRep.put("href", "/b/thermo/0");
  632.         List<String> rtl = Arrays.asList("oic.r.temperature");
  633.         resRep.put("rt", rtl);
  634.         List<String> ifl = Arrays.asList("oic.if.a");
  635.         resRep.put("if", ifl);
  636.         resRep.put("id", "LIVING_ROOM_TEMP");
  637.         byte policy = 0x03;
  638.         // policy = policy | (1 << 1); //observable
  639.         // policy = policy | (1 << 2); //discoverable
  640.  
  641.         resRep.put("bm", policy);
  642.         resRep.put("unit", "Celcius");
  643.         resRep.put("current_value", 27);
  644.         resRep.put("Set_value", 0);
  645.         // System.out.println(resRep.toString());
  646.  
  647.         tag.put("di", UUID.randomUUID().toString());
  648.         tag.put("n", "Single_device_collection");
  649.         tag.put("bm", policy);
  650.  
  651.         links.add(resRep);
  652.         collection.add(tag);
  653.         collection.add(links);
  654.         System.out.println(collection.toString());
  655.  
  656.         Cbor<ArrayList<Object>> cbor = new Cbor<ArrayList<Object>>();
  657.         byte[] encodedpayload = cbor.encodingPayloadToCbor(collection);
  658.  
  659.         // POST for create
  660.         CoapRequest request = new CoapRequest(CoapMethod.POST);
  661.  
  662.         if (session.getSessionId() == null) {
  663.             System.out.println("invalid session or null");
  664.             ms = MachineState.EXIT;
  665.         } // does GET
  666.  
  667.         request.setPayload(encodedpayload);
  668.  
  669.         byte[] bytes = ByteBuffer.allocate(4).putInt(APPLICATION_JSON).array();
  670.         request.addOption(CoapOption.CONTENT_FORMAT.getvalue(), bytes);
  671.  
  672.         // publish resource to RD should be
  673.         // /oic/rd, with 'tags' and did
  674.  
  675.         // oic://<Authority>/<Path>?<Query>
  676.  
  677.         // Logger.i("hostAddress : " + hostAddress);
  678.         request.setUriPath("/oic/rd");
  679.         // request.setUriPath(String.format("%s:5683/b/thermo/0",hostAddress));
  680.         request.setUriQuery("rt=oic.wk.rdpub&if=oic.if.baseline");
  681.  
  682.         // generate 0~8 bytes random token for Coap
  683.         byte[] ranToken = new byte[MAX_TOKEN_LEN];
  684.         new Random().nextBytes(ranToken);
  685.         request.setToken(ranToken);
  686.  
  687.         coapc.sendRequest(request);
  688.  
  689.     }
  690.     // not yet complete
  691.     /*
  692.      * private void SendPublishRequest() throws JsonParseException,
  693.      * JsonMappingException, IOException { //throw new
  694.      * UnsupportedOperationException();
  695.      *
  696.      * //Cbor<HashMap<Object, Object>> cbor = new
  697.      * Cbor<HashMap<Object,Object>>(); //use a json tree model to create a
  698.      * resources //JsonNode resRep = new JsonNode();
  699.      *
  700.      *
  701.      *
  702.      * }
  703.      */
  704. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement