replace : iotivity -> iotivity-sec
[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 if (OcConnectivityType.CT_ADAPTER_GATT_BTLE == connectivityType) {
173                         if (null != Common.getLeAddress())
174                         {
175                             OcPlatform.findResource("",
176                                     Common.getLeAddress() + OcPlatform.WELL_KNOWN_QUERY,
177                                     EnumSet.of(OcConnectivityType.CT_ADAPTER_GATT_BTLE),
178                                     resourceFoundListener, QualityOfService.LOW);
179                         } else {
180                             Common.showToast(mContext, "Please scan ble device");
181                             Log.e(TAG, "invalid ble device");
182                         }
183                     } else {
184                         OcPlatform.findResource("",
185                                 OcPlatform.WELL_KNOWN_QUERY,
186                                 EnumSet.of(connectivityType),
187                                 resourceFoundListener, mQos);
188                     }
189                 } catch (OcException e) {
190                     e.printStackTrace();
191                 }
192
193                 mActivity.runOnUiThread(new Runnable() {
194                     @Override
195                     public void run() {
196                         mActionLog.setText("[Action Log]" + EOL);
197                         mActionLog.append("Find resource()" + EOL);
198                         mActionLog.append("Connectivity : " + connectivityType + EOL);
199
200                         mResultLog.setText("[Result Log]" + EOL);
201                         mResultLog.append("Start Time : ");
202                         mResultLog.append(Common.getDateCurrentTimeZone() + EOL);
203                         mStartTime = System.currentTimeMillis();
204                     }
205                 });
206                 mServerLayout.setVisibility(View.GONE);
207             }
208         };
209     }
210
211     void sendGetToFoundResource(String command) {
212         try {
213             Log.i(TAG, "sendGetToFoundResource");
214
215             Map<String, String> queryParameters = new HashMap<String, String>();
216             queryParameters.put(Common.GET_COMMAND, command);
217
218             mFoundResource.get(queryParameters, this, mQos);
219
220             mActionLog.setText("[Action Log]" + EOL + "Send get()"+ EOL + "To : ");
221             mActionLog.append(mFoundResource.getHost() + mFoundResource.getUri() + EOL);
222         } catch (OcException e) {
223             e.printStackTrace();
224         }
225     }
226
227     void sendPutToFoundResource() {
228         try {
229             Log.i(TAG, "sendPutToFoundResource");
230
231             OcRepresentation rep = new OcRepresentation();
232             rep.setValue(Common.STATE_KEY, !mState);
233
234             Map<String, String> queryParams = new HashMap<>();
235
236             mFoundResource.put(rep, queryParams, this);
237             mActionLog.setText("[Action Log]" + EOL);
238             mActionLog.append("Send put()" + EOL + "To : ");
239             mActionLog.append(mFoundResource.getHost() + mFoundResource.getUri() + EOL);
240         } catch (OcException e) {
241             e.printStackTrace();
242         }
243     }
244
245     OcPlatform.OnResourceFoundListener resourceFoundListener =
246             new OcPlatform.OnResourceFoundListener() {
247                 @Override
248                 public void onResourceFound(OcResource ocResource) {
249                     synchronized (mActivity) {
250                         final String resourceUri = ocResource.getUri();
251                         Log.i(TAG, "onResourceFound : " + ocResource.getUri());
252
253                         if (resourceUri.contains(Common.RESOURCE_URI)
254                                 && ocResource.getConnectivityTypeSet().contains(mCurrConnectivity)) {
255                             mFoundResource = ocResource;
256                             mActivity.runOnUiThread(new Runnable() {
257                                 @Override
258                                 public void run() {
259                                     mEndTime = System.currentTimeMillis();
260                                     double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
261                                     mResultLog.append("Discovery Time : ");
262                                     mResultLog.append(String.format("%.3f", flightTime) + "sec" + EOL);
263                                     mActionLog.append(mFoundResource.getHost() + resourceUri + EOL);
264                                 }
265                             });
266                         }
267                     }
268                 }
269
270                 @Override
271                 public void onFindResourceFailed(Throwable throwable, String uri) {
272                     synchronized (mActivity) {
273                         Log.i(TAG, "findResource request has failed");
274                         Log.e(TAG, throwable.toString());
275                     }
276                 }
277             };
278
279     @Override
280     public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
281         String repUri = ocRepresentation.getUri();
282         Log.i(TAG, "onGetCompleted : " + repUri);
283
284         try {
285             final String command = ocRepresentation.getValue(Common.GET_COMMAND);
286
287             if (command == null || command.isEmpty()) {
288                 Log.e(TAG, "Get command is null");
289                 return;
290             } else if (command.equals(Common.STATE_GET)) {
291                 mState = ocRepresentation.getValue(Common.STATE_KEY);
292                 mLargeData = "";
293             } else if (command.equals(Common.LARGE_GET)) {
294                 mLargeData = ocRepresentation.getValue(Common.LARGE_KEY);
295             }
296         } catch (OcException e) {
297             e.printStackTrace();
298         }
299
300         mActivity.runOnUiThread(new Runnable() {
301             @Override
302             public void run() {
303                 mEndTime = System.currentTimeMillis();
304                 double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
305
306                 if (mLargeData == null || mLargeData.isEmpty()) {
307                     mResultLog.append(EOL + "Get Light State : " + mState + EOL);
308                 } else {
309                     mResultLog.append(EOL + "Payload Size : " + mLargeData.length() + EOL);
310                 }
311
312                 mResultLog.append("Get Time : " + String.format("%.3f", flightTime) + "sec" + EOL);
313             }
314         });
315     }
316
317     @Override
318     public void onGetFailed(Throwable throwable) {
319         Log.e(TAG, "Get failed");
320     }
321
322     @Override
323     public void onPutCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
324         String repUri = ocRepresentation.getUri();
325         Log.i(TAG, "onPutCompleted : " + repUri);
326
327         try {
328             mState = ocRepresentation.getValue(Common.STATE_KEY);
329         } catch (OcException e) {
330             e.printStackTrace();
331         }
332
333         mActivity.runOnUiThread(new Runnable() {
334             @Override
335             public void run() {
336                 mEndTime = System.currentTimeMillis();
337                 double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
338                 mResultLog.append(EOL + "Set Light State : " + !mState + EOL + "Put Time : ");
339                 mResultLog.append(String.format("%.3f", flightTime) + "sec" + EOL);
340             }
341         });
342     }
343
344     @Override
345     public void onPutFailed(Throwable throwable) {
346         Log.e(TAG, "Put failed");
347     }
348
349     // ******************************************************************************
350     // End of the OCF Client specific code
351     // ******************************************************************************
352
353     private void createResource() {
354         mEntityHandler = new OcPlatform.EntityHandler() {
355             @Override
356             public EntityHandlerResult handleEntity(
357                     OcResourceRequest ocResourceRequest) {
358                 return mEntityHandler(ocResourceRequest);
359             }
360         };
361
362         try {
363             mResourceHandle = OcPlatform.registerResource(Common.RESOURCE_URI,
364                     Common.RESOURCE_TYPE, Common.RESOURCE_INTERFACE,
365                     mEntityHandler, Common.RESOURCE_PROPERTIES);
366
367         } catch (OcException e) {
368             String errString = "Error : " + e.getErrorCode().toString();
369             Log.e(TAG, errString);
370             StringWriter sw = new StringWriter();
371             e.printStackTrace(new PrintWriter(sw));
372             String exceptionAsString = sw.toString();
373             Log.e(TAG, exceptionAsString);
374             mResourceText.setText(errString);
375         }
376
377         StringBuilder sb = new StringBuilder();
378         for (int i = 0; i < Common.DATA_SIZE; i++) {
379             sb.append('j');
380         }
381         mLargeData = sb.toString();
382
383         sb.setLength(0);
384         sb.append("URI :   " + Common.RESOURCE_URI + EOL);
385         sb.append("Type :   " + Common.RESOURCE_TYPE + EOL);
386         sb.append("Interface :   " + Common.RESOURCE_INTERFACE + EOL);
387         sb.append("Properties :   " + Common.RESOURCE_PROPERTIES.toString() + EOL);
388         mResourceText.setText(sb.toString());
389         mActionLog.setText("");
390         mResultLog.setText("Created resource" + EOL);
391     }
392
393     protected EntityHandlerResult mEntityHandler(OcResourceRequest ocResourceRequest) {
394         EntityHandlerResult result = EntityHandlerResult.ERROR;
395         final StringBuilder sb = new StringBuilder();
396         switch (ocResourceRequest.getRequestType()) {
397             case GET:
398                 sb.append("Type :   GET");
399                 if (sendGetResponse(ocResourceRequest)) {
400                     result = EntityHandlerResult.OK;
401                 }
402                 break;
403             case PUT:
404                 sb.append("Type :   PUT");
405                 if (sendPutResponse(ocResourceRequest)) {
406                     result = EntityHandlerResult.OK;
407                 }
408                 break;
409             case DELETE:
410                 sb.append("Type :   DELETE");
411                 break;
412             case POST:
413                 sb.append("Type :   POST");
414                 break;
415             default:
416                 break;
417         }
418         sb.append(EOL + "Light State :   " + mState);
419         sb.append(EOL + "Time :   " + Common.getDateCurrentTimeZone());
420         if (result == EntityHandlerResult.ERROR) {
421             sb.append(EOL + "!! Error occurred during sending the response !!");
422         }
423
424         mActivity.runOnUiThread(new Runnable() {
425             @Override
426             public void run() {
427                 mResultLog.setText(sb.toString());
428             }
429         });
430
431         return result;
432     }
433
434     private boolean sendGetResponse(OcResourceRequest ocResourceRequest) {
435         mActivity.runOnUiThread(new Runnable() {
436             @Override
437             public void run() {
438                 Common.showToast(mContext, "received get command, send response");
439             }
440         });
441
442         Map<String, String> queryParameters = ocResourceRequest.getQueryParameters();
443         final String command = queryParameters.get(Common.GET_COMMAND);
444
445         if (command == null
446                 || (!command.equals(Common.STATE_GET) && !command.equals(Common.LARGE_GET))) {
447             return false;
448         }
449
450         OcRepresentation rep = new OcRepresentation();
451         try {
452             rep.setValue(Common.GET_COMMAND, command);
453             if (command.equals(Common.STATE_GET)) {
454                 rep.setValue(Common.STATE_KEY, mState);
455             } else if (command.equals(Common.LARGE_GET)) {
456                 rep.setValue(Common.LARGE_KEY, mLargeData);
457             }
458         } catch (OcException e) {
459             e.printStackTrace();
460         }
461
462         OcResourceResponse response = new OcResourceResponse();
463
464         response.setRequestHandle(ocResourceRequest.getRequestHandle());
465         response.setResourceHandle(ocResourceRequest.getResourceHandle());
466         response.setResourceRepresentation(rep);
467         try {
468             OcPlatform.sendResponse(response);
469             return true;
470         } catch (OcException e) {
471             e.printStackTrace();
472             return false;
473         }
474     }
475
476     private boolean sendPutResponse(OcResourceRequest ocResourceRequest) {
477         mActivity.runOnUiThread(new Runnable() {
478             @Override
479             public void run() {
480                 Common.showToast(mContext, "received put command, send response");
481             }
482         });
483
484         try {
485             OcRepresentation rep = ocResourceRequest.getResourceRepresentation();
486             if (rep.hasAttribute(Common.STATE_KEY)) {
487                 mState = rep.getValue(Common.STATE_KEY);
488             }
489         } catch (OcException e) {
490             e.printStackTrace();
491         }
492
493         OcResourceResponse response = new OcResourceResponse();
494         OcRepresentation rep = new OcRepresentation();
495
496         response.setRequestHandle(ocResourceRequest.getRequestHandle());
497         response.setResourceHandle(ocResourceRequest.getResourceHandle());
498         response.setResourceRepresentation(rep);
499         try {
500             OcPlatform.sendResponse(response);
501             return true;
502         } catch (OcException e) {
503             e.printStackTrace();
504             return false;
505         }
506     }
507
508     // ******************************************************************************
509     // End of the OCF Server specific code
510     // ******************************************************************************
511
512     private void initOcPlatform(ModeType type) {
513         PlatformConfig cfg = new PlatformConfig(mActivity, mContext,
514                 ServiceType.IN_PROC,
515                 type,
516                 Common.IP_ADDRESS,
517                 Common.IP_PORT,
518                 mQos);
519         OcPlatform.Configure(cfg);
520     }
521
522     @Override
523     public View onCreateView(LayoutInflater inflater, ViewGroup container,
524                              Bundle savedInstanceState) {
525         View rootView = inflater.inflate(R.layout.fragment_message, container, false);
526
527         mServerLayout = (LinearLayout) rootView.findViewById(R.id.server_layout);
528         mClientLayout = (LinearLayout) rootView.findViewById(R.id.client_layout);
529
530         mResourceText = (TextView) rootView.findViewById(R.id.resource_view);
531         mActionLog = (TextView) rootView.findViewById(R.id.action_log_view);
532         mResultLog = (TextView) rootView.findViewById(R.id.result_log_view);
533
534         mDiscoverIPButton = (Button) rootView.findViewById(R.id.ip_button);
535         mDiscoverBTButton = (Button) rootView.findViewById(R.id.bt_button);
536         mDiscoverLEButton = (Button) rootView.findViewById(R.id.le_button);
537         mDiscoverTCPButton = (Button) rootView.findViewById(R.id.tcp_button);
538         mDiscoverNFCButton = (Button) rootView.findViewById(R.id.nfc_button);
539
540         mRegisterButton = (Button) rootView.findViewById(R.id.register_button);
541         mGetButton = (Button) rootView.findViewById(R.id.get_button);
542         mPutButton = (Button) rootView.findViewById(R.id.put_button);
543         mLargeButton = (Button) rootView.findViewById(R.id.large_button);
544
545         mQosToggle = (ToggleButton) rootView.findViewById(R.id.qos_toggle_button);
546
547         mDiscoverIPButton.setOnClickListener(
548                 discoverButtonListener(OcConnectivityType.CT_ADAPTER_IP));
549         mDiscoverBTButton.setOnClickListener(
550                 discoverButtonListener(OcConnectivityType.CT_ADAPTER_RFCOMM_BTEDR));
551         mDiscoverLEButton.setOnClickListener(
552                 discoverButtonListener(OcConnectivityType.CT_ADAPTER_GATT_BTLE));
553         mDiscoverTCPButton.setOnClickListener(
554                 discoverButtonListener(OcConnectivityType.CT_ADAPTER_TCP));
555         mDiscoverNFCButton.setOnClickListener(
556                 discoverButtonListener(OcConnectivityType.CT_ADAPTER_NFC));
557
558         mRegisterButton.setOnClickListener(new View.OnClickListener() {
559             @Override
560             public void onClick(View view) {
561                 if (mResourceHandle == null) {
562                     initOcPlatform(ModeType.SERVER);
563                     createResource();
564                     mClientLayout.setVisibility(View.GONE);
565                 } else {
566                     Common.showToast(mContext, "Already created resource");
567                 }
568             }
569         });
570         mGetButton.setOnClickListener(getButtonListener());
571         mPutButton.setOnClickListener(putButtonListener());
572         mLargeButton.setOnClickListener(getLargeListener());
573
574         mQosToggle
575                 .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
576                     @Override
577                     public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
578                         if (b) {
579                             mQos = QualityOfService.HIGH;
580                         } else {
581                             mQos = QualityOfService.LOW;
582                         }
583                     }
584                 });
585
586         return rootView;
587     }
588
589     @Override
590     public void onResume() {
591         super.onResume();
592     }
593
594     @Override
595     public void onDestroy() {
596         super.onDestroy();
597     }
598 }