Add Fragment for cloud test
[platform/upstream/iotivity.git] / android / examples / simplebase / src / main / java / org / iotivity / base / examples / MessageFragment.java
1 /*
2  * ******************************************************************
3  *
4  * Copyright 2016 Samsung Electronics All Rights Reserved.
5  *
6  * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22
23 package org.iotivity.base.examples;
24
25 import android.app.Activity;
26 import android.app.Fragment;
27 import android.content.Context;
28 import android.os.Bundle;
29 import android.util.Log;
30 import android.view.LayoutInflater;
31 import android.view.View;
32 import android.view.ViewGroup;
33 import android.widget.Button;
34 import android.widget.CompoundButton;
35 import android.widget.LinearLayout;
36 import android.widget.TextView;
37 import android.widget.ToggleButton;
38
39 import org.iotivity.base.EntityHandlerResult;
40 import org.iotivity.base.ModeType;
41 import org.iotivity.base.OcConnectivityType;
42 import org.iotivity.base.OcException;
43 import org.iotivity.base.OcHeaderOption;
44 import org.iotivity.base.OcPlatform;
45 import org.iotivity.base.OcRepresentation;
46 import org.iotivity.base.OcResource;
47 import org.iotivity.base.OcResourceHandle;
48 import org.iotivity.base.OcResourceRequest;
49 import org.iotivity.base.OcResourceResponse;
50 import org.iotivity.base.PlatformConfig;
51 import org.iotivity.base.QualityOfService;
52 import org.iotivity.base.ServiceType;
53
54 import java.io.PrintWriter;
55 import java.io.StringWriter;
56 import java.util.EnumSet;
57 import java.util.HashMap;
58 import java.util.List;
59 import java.util.Map;
60
61 /**
62  * This class is for messaging between the server and the client.
63  * It can handle message manually.
64  */
65 public class MessageFragment extends Fragment implements OcResource.OnGetListener,
66         OcResource.OnPutListener {
67
68     private static final String TAG          = "OIC_SIMPLE_MESSAGE";
69     private final String        EOL          = System.getProperties().getProperty("line.separator");
70     private final double        MILLI_PER_SEC = 1000.0;
71
72     private Activity            mActivity;
73     private Context             mContext;
74
75     OcPlatform.EntityHandler    mEntityHandler;
76     private OcResourceHandle    mResourceHandle;
77     private OcResource          mFoundResource;
78     private OcConnectivityType  mCurrConnectivity;
79
80     private QualityOfService    mQos         = QualityOfService.LOW;
81
82     private LinearLayout        mServerLayout;
83     private LinearLayout        mClientLayout;
84     private TextView            mResourceText;
85     private TextView            mActionLog;
86     private TextView            mResultLog;
87     private ToggleButton        mQosToggle;
88     private Button              mRegisterButton;
89     private Button              mGetButton;
90     private Button              mPutButton;
91     private Button              mLargeButton;
92     private Button              mDiscoverIPButton;
93     private Button              mDiscoverBTButton;
94     private Button              mDiscoverLEButton;
95     private Button              mDiscoverTCPButton;
96     private Button              mDiscoverNFCButton;
97
98     private String              mLargeData;
99     private boolean             mState;
100     private long                mStartTime;
101     private long                mEndTime;
102
103     @Override
104     public void onCreate(Bundle savedInstanceState) {
105         super.onCreate(savedInstanceState);
106
107         mActivity = getActivity();
108         mContext = mActivity.getBaseContext();
109     }
110
111     View.OnClickListener getButtonListener() {
112         return new View.OnClickListener() {
113             @Override
114             public void onClick(View view) {
115                 if (mFoundResource != null) {
116                     mStartTime = System.currentTimeMillis();
117                     sendGetToFoundResource(Common.STATE_GET);
118                 } else {
119                     Common.showToast(mContext, "Please discovery first");
120                     Log.e(TAG, "get() : resource is null");
121                 }
122             }
123         };
124     }
125
126     View.OnClickListener putButtonListener() {
127         return new View.OnClickListener() {
128             @Override
129             public void onClick(View view) {
130                 if (mFoundResource != null) {
131                     mStartTime = System.currentTimeMillis();
132                     sendPutToFoundResource();
133                 } else {
134                     Common.showToast(mContext, "Please discovery first");
135                     Log.e(TAG, "put() : resource is null");
136                 }
137             }
138         };
139     }
140
141     View.OnClickListener getLargeListener() {
142         return new View.OnClickListener() {
143             @Override
144             public void onClick(View view) {
145                 if (mFoundResource != null) {
146                     mStartTime = System.currentTimeMillis();
147                     sendGetToFoundResource(Common.LARGE_GET);
148                 } else {
149                     Common.showToast(mContext, "Please discovery first");
150                     Log.e(TAG, "large() : resource is null");
151                 }
152             }
153         };
154     }
155
156     View.OnClickListener discoverButtonListener(
157             final OcConnectivityType connectivityType) {
158         return new View.OnClickListener() {
159             @Override
160             public void onClick(View view) {
161                 Log.i(TAG, "discoverButtonListener");
162                 initOcPlatform(ModeType.CLIENT);
163                 mFoundResource = null;
164                 mCurrConnectivity = connectivityType;
165
166                 try {
167                     if (OcConnectivityType.CT_ADAPTER_TCP == connectivityType) {
168                         OcPlatform.findResource("",
169                                 OcPlatform.WELL_KNOWN_QUERY,
170                                 EnumSet.of(OcConnectivityType.CT_ADAPTER_IP),
171                                 resourceFoundListener, mQos);
172                     } else {
173                         OcPlatform.findResource("",
174                                 OcPlatform.WELL_KNOWN_QUERY,
175                                 EnumSet.of(connectivityType),
176                                 resourceFoundListener, mQos);
177                     }
178                 } catch (OcException e) {
179                     e.printStackTrace();
180                 }
181
182                 mActivity.runOnUiThread(new Runnable() {
183                     @Override
184                     public void run() {
185                         mActionLog.setText("[Action Log]" + EOL);
186                         mActionLog.append("Find resource()" + EOL);
187                         mActionLog.append("Connectivity : " + connectivityType + EOL);
188
189                         mResultLog.setText("[Result Log]" + EOL);
190                         mResultLog.append("Start Time : ");
191                         mResultLog.append(Common.getDateCurrentTimeZone() + EOL);
192                         mStartTime = System.currentTimeMillis();
193                     }
194                 });
195                 mServerLayout.setVisibility(View.GONE);
196             }
197         };
198     }
199
200     void sendGetToFoundResource(String command) {
201         try {
202             Log.i(TAG, "sendGetToFoundResource");
203
204             Map<String, String> queryParameters = new HashMap<String, String>();
205             queryParameters.put(Common.GET_COMMAND, command);
206
207             mFoundResource.get(queryParameters, this, mQos);
208
209             mActionLog.setText("[Action Log]" + EOL + "Send get()"+ EOL + "To : ");
210             mActionLog.append(mFoundResource.getHost() + mFoundResource.getUri() + EOL);
211         } catch (OcException e) {
212             e.printStackTrace();
213         }
214     }
215
216     void sendPutToFoundResource() {
217         try {
218             Log.i(TAG, "sendPutToFoundResource");
219
220             OcRepresentation rep = new OcRepresentation();
221             rep.setValue(Common.STATE_KEY, !mState);
222
223             Map<String, String> queryParams = new HashMap<>();
224
225             mFoundResource.put(rep, queryParams, this);
226             mActionLog.setText("[Action Log]" + EOL);
227             mActionLog.append("Send put()" + EOL + "To : ");
228             mActionLog.append(mFoundResource.getHost() + mFoundResource.getUri() + EOL);
229         } catch (OcException e) {
230             e.printStackTrace();
231         }
232     }
233
234     OcPlatform.OnResourceFoundListener resourceFoundListener =
235             new OcPlatform.OnResourceFoundListener() {
236                 @Override
237                 public void onResourceFound(OcResource ocResource) {
238                     synchronized (mActivity) {
239                         final String resourceUri = ocResource.getUri();
240                         Log.i(TAG, "onResourceFound : " + ocResource.getUri());
241
242                         if (resourceUri.contains(Common.RESOURCE_URI)
243                                 && ocResource.getConnectivityTypeSet().contains(mCurrConnectivity)) {
244                             mFoundResource = ocResource;
245                             mActivity.runOnUiThread(new Runnable() {
246                                 @Override
247                                 public void run() {
248                                     mEndTime = System.currentTimeMillis();
249                                     double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
250                                     mResultLog.append("Discovery Time : ");
251                                     mResultLog.append(String.format("%.3f", flightTime) + "sec" + EOL);
252                                     mActionLog.append(mFoundResource.getHost() + resourceUri + EOL);
253                                 }
254                             });
255                         }
256                     }
257                 }
258
259                 @Override
260                 public void onFindResourceFailed(Throwable throwable, String uri) {
261                     synchronized (mActivity) {
262                         Log.i(TAG, "findResource request has failed");
263                         Log.e(TAG, throwable.toString());
264                     }
265                 }
266             };
267
268     @Override
269     public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
270         String repUri = ocRepresentation.getUri();
271         Log.i(TAG, "onGetCompleted : " + repUri);
272
273         try {
274             final String command = ocRepresentation.getValue(Common.GET_COMMAND);
275
276             if (command == null || command.isEmpty()) {
277                 Log.e(TAG, "Get command is null");
278                 return;
279             } else if (command.equals(Common.STATE_GET)) {
280                 mState = ocRepresentation.getValue(Common.STATE_KEY);
281                 mLargeData = "";
282             } else if (command.equals(Common.LARGE_GET)) {
283                 mLargeData = ocRepresentation.getValue(Common.LARGE_KEY);
284             }
285         } catch (OcException e) {
286             e.printStackTrace();
287         }
288
289         mActivity.runOnUiThread(new Runnable() {
290             @Override
291             public void run() {
292                 mEndTime = System.currentTimeMillis();
293                 double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
294
295                 if (mLargeData == null || mLargeData.isEmpty()) {
296                     mResultLog.append(EOL + "Get Light State : " + mState + EOL);
297                 } else {
298                     mResultLog.append(EOL + "Payload Size : " + mLargeData.length() + EOL);
299                 }
300
301                 mResultLog.append("Get Time : " + String.format("%.3f", flightTime) + "sec" + EOL);
302             }
303         });
304     }
305
306     @Override
307     public void onGetFailed(Throwable throwable) {
308         Log.e(TAG, "Get failed");
309     }
310
311     @Override
312     public void onPutCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
313         String repUri = ocRepresentation.getUri();
314         Log.i(TAG, "onPutCompleted : " + repUri);
315
316         try {
317             mState = ocRepresentation.getValue(Common.STATE_KEY);
318         } catch (OcException e) {
319             e.printStackTrace();
320         }
321
322         mActivity.runOnUiThread(new Runnable() {
323             @Override
324             public void run() {
325                 mEndTime = System.currentTimeMillis();
326                 double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
327                 mResultLog.append(EOL + "Set Light State : " + !mState + EOL + "Put Time : ");
328                 mResultLog.append(String.format("%.3f", flightTime) + "sec" + EOL);
329             }
330         });
331     }
332
333     @Override
334     public void onPutFailed(Throwable throwable) {
335         Log.e(TAG, "Put failed");
336     }
337
338     // ******************************************************************************
339     // End of the OCF Client specific code
340     // ******************************************************************************
341
342     private void createResource() {
343         mEntityHandler = new OcPlatform.EntityHandler() {
344             @Override
345             public EntityHandlerResult handleEntity(
346                     OcResourceRequest ocResourceRequest) {
347                 return mEntityHandler(ocResourceRequest);
348             }
349         };
350
351         try {
352             mResourceHandle = OcPlatform.registerResource(Common.RESOURCE_URI,
353                     Common.RESOURCE_TYPE, Common.RESOURCE_INTERFACE,
354                     mEntityHandler, Common.RESOURCE_PROPERTIES);
355
356         } catch (OcException e) {
357             String errString = "Error : " + e.getErrorCode().toString();
358             Log.e(TAG, errString);
359             StringWriter sw = new StringWriter();
360             e.printStackTrace(new PrintWriter(sw));
361             String exceptionAsString = sw.toString();
362             Log.e(TAG, exceptionAsString);
363             mResourceText.setText(errString);
364         }
365
366         StringBuilder sb = new StringBuilder();
367         for (int i = 0; i < Common.DATA_SIZE; i++) {
368             sb.append('j');
369         }
370         mLargeData = sb.toString();
371
372         sb.setLength(0);
373         sb.append("URI :   " + Common.RESOURCE_URI + EOL);
374         sb.append("Type :   " + Common.RESOURCE_TYPE + EOL);
375         sb.append("Interface :   " + Common.RESOURCE_INTERFACE + EOL);
376         sb.append("Properties :   " + Common.RESOURCE_PROPERTIES.toString() + EOL);
377         mResourceText.setText(sb.toString());
378         mActionLog.setText("");
379         mResultLog.setText("Created resource" + EOL);
380     }
381
382     protected EntityHandlerResult mEntityHandler(OcResourceRequest ocResourceRequest) {
383         EntityHandlerResult result = EntityHandlerResult.ERROR;
384         final StringBuilder sb = new StringBuilder();
385         switch (ocResourceRequest.getRequestType()) {
386             case GET:
387                 sb.append("Type :   GET");
388                 if (sendGetResponse(ocResourceRequest)) {
389                     result = EntityHandlerResult.OK;
390                 }
391                 break;
392             case PUT:
393                 sb.append("Type :   PUT");
394                 if (sendPutResponse(ocResourceRequest)) {
395                     result = EntityHandlerResult.OK;
396                 }
397                 break;
398             case DELETE:
399                 sb.append("Type :   DELETE");
400                 break;
401             case POST:
402                 sb.append("Type :   POST");
403                 break;
404             default:
405                 break;
406         }
407         sb.append(EOL + "Light State :   " + mState);
408         sb.append(EOL + "Time :   " + Common.getDateCurrentTimeZone());
409         if (result == EntityHandlerResult.ERROR) {
410             sb.append(EOL + "!! Error occurred during sending the response !!");
411         }
412
413         mActivity.runOnUiThread(new Runnable() {
414             @Override
415             public void run() {
416                 mResultLog.setText(sb.toString());
417             }
418         });
419
420         return result;
421     }
422
423     private boolean sendGetResponse(OcResourceRequest ocResourceRequest) {
424         mActivity.runOnUiThread(new Runnable() {
425             @Override
426             public void run() {
427                 Common.showToast(mContext, "received get command, send response");
428             }
429         });
430
431         Map<String, String> queryParameters = ocResourceRequest.getQueryParameters();
432         final String command = queryParameters.get(Common.GET_COMMAND);
433
434         if (command == null
435                 || (!command.equals(Common.STATE_GET) && !command.equals(Common.LARGE_GET))) {
436             return false;
437         }
438
439         OcRepresentation rep = new OcRepresentation();
440         try {
441             rep.setValue(Common.GET_COMMAND, command);
442             if (command.equals(Common.STATE_GET)) {
443                 rep.setValue(Common.STATE_KEY, mState);
444             } else if (command.equals(Common.LARGE_GET)) {
445                 rep.setValue(Common.LARGE_KEY, mLargeData);
446             }
447         } catch (OcException e) {
448             e.printStackTrace();
449         }
450
451         OcResourceResponse response = new OcResourceResponse();
452
453         response.setRequestHandle(ocResourceRequest.getRequestHandle());
454         response.setResourceHandle(ocResourceRequest.getResourceHandle());
455         response.setResourceRepresentation(rep);
456         try {
457             OcPlatform.sendResponse(response);
458             return true;
459         } catch (OcException e) {
460             e.printStackTrace();
461             return false;
462         }
463     }
464
465     private boolean sendPutResponse(OcResourceRequest ocResourceRequest) {
466         mActivity.runOnUiThread(new Runnable() {
467             @Override
468             public void run() {
469                 Common.showToast(mContext, "received put command, send response");
470             }
471         });
472
473         try {
474             OcRepresentation rep = ocResourceRequest.getResourceRepresentation();
475             if (rep.hasAttribute(Common.STATE_KEY)) {
476                 mState = rep.getValue(Common.STATE_KEY);
477             }
478         } catch (OcException e) {
479             e.printStackTrace();
480         }
481
482         OcResourceResponse response = new OcResourceResponse();
483         OcRepresentation rep = new OcRepresentation();
484
485         response.setRequestHandle(ocResourceRequest.getRequestHandle());
486         response.setResourceHandle(ocResourceRequest.getResourceHandle());
487         response.setResourceRepresentation(rep);
488         try {
489             OcPlatform.sendResponse(response);
490             return true;
491         } catch (OcException e) {
492             e.printStackTrace();
493             return false;
494         }
495     }
496
497     // ******************************************************************************
498     // End of the OCF Server specific code
499     // ******************************************************************************
500
501     private void initOcPlatform(ModeType type) {
502         PlatformConfig cfg = new PlatformConfig(mActivity, mContext,
503                 ServiceType.IN_PROC,
504                 type,
505                 Common.IP_ADDRESS,
506                 Common.IP_PORT,
507                 mQos);
508         OcPlatform.Configure(cfg);
509     }
510
511     @Override
512     public View onCreateView(LayoutInflater inflater, ViewGroup container,
513                              Bundle savedInstanceState) {
514         View rootView = inflater.inflate(R.layout.fragment_message, container, false);
515
516         mServerLayout = (LinearLayout) rootView.findViewById(R.id.server_layout);
517         mClientLayout = (LinearLayout) rootView.findViewById(R.id.client_layout);
518
519         mResourceText = (TextView) rootView.findViewById(R.id.resource_view);
520         mActionLog = (TextView) rootView.findViewById(R.id.action_log_view);
521         mResultLog = (TextView) rootView.findViewById(R.id.result_log_view);
522
523         mDiscoverIPButton = (Button) rootView.findViewById(R.id.ip_button);
524         mDiscoverBTButton = (Button) rootView.findViewById(R.id.bt_button);
525         mDiscoverLEButton = (Button) rootView.findViewById(R.id.le_button);
526         mDiscoverTCPButton = (Button) rootView.findViewById(R.id.tcp_button);
527         mDiscoverNFCButton = (Button) rootView.findViewById(R.id.nfc_button);
528
529         mRegisterButton = (Button) rootView.findViewById(R.id.register_button);
530         mGetButton = (Button) rootView.findViewById(R.id.get_button);
531         mPutButton = (Button) rootView.findViewById(R.id.put_button);
532         mLargeButton = (Button) rootView.findViewById(R.id.large_button);
533
534         mQosToggle = (ToggleButton) rootView.findViewById(R.id.qos_toggle_button);
535
536         mDiscoverIPButton.setOnClickListener(
537                 discoverButtonListener(OcConnectivityType.CT_ADAPTER_IP));
538         mDiscoverBTButton.setOnClickListener(
539                 discoverButtonListener(OcConnectivityType.CT_ADAPTER_RFCOMM_BTEDR));
540         mDiscoverLEButton.setOnClickListener(
541                 discoverButtonListener(OcConnectivityType.CT_ADAPTER_GATT_BTLE));
542         mDiscoverTCPButton.setOnClickListener(
543                 discoverButtonListener(OcConnectivityType.CT_ADAPTER_TCP));
544         mDiscoverNFCButton.setOnClickListener(
545                 discoverButtonListener(OcConnectivityType.CT_ADAPTER_NFC));
546
547         mRegisterButton.setOnClickListener(new View.OnClickListener() {
548             @Override
549             public void onClick(View view) {
550                 if (mResourceHandle == null) {
551                     initOcPlatform(ModeType.SERVER);
552                     createResource();
553                     mClientLayout.setVisibility(View.GONE);
554                 } else {
555                     Common.showToast(mContext, "Already created resource");
556                 }
557             }
558         });
559         mGetButton.setOnClickListener(getButtonListener());
560         mPutButton.setOnClickListener(putButtonListener());
561         mLargeButton.setOnClickListener(getLargeListener());
562
563         mQosToggle
564                 .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
565                     @Override
566                     public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
567                         if (b) {
568                             mQos = QualityOfService.HIGH;
569                         } else {
570                             mQos = QualityOfService.LOW;
571                         }
572                     }
573                 });
574
575         return rootView;
576     }
577
578     @Override
579     public void onResume() {
580         super.onResume();
581     }
582
583     @Override
584     public void onDestroy() {
585         super.onDestroy();
586     }
587 }