2 * ******************************************************************
4 * Copyright 2016 Samsung Electronics All Rights Reserved.
6 * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 package org.iotivity.base.examples;
25 import android.app.Activity;
26 import android.app.AlertDialog;
27 import android.app.Fragment;
28 import android.content.Context;
29 import android.content.DialogInterface;
30 import android.content.Intent;
31 import android.nfc.NfcAdapter;
32 import android.os.Bundle;
33 import android.util.Log;
34 import android.view.LayoutInflater;
35 import android.view.View;
36 import android.view.ViewGroup;
37 import android.widget.Button;
38 import android.widget.CompoundButton;
39 import android.widget.EditText;
40 import android.widget.LinearLayout;
41 import android.widget.TextView;
42 import android.widget.Toast;
43 import android.widget.ToggleButton;
45 import org.iotivity.base.EntityHandlerResult;
46 import org.iotivity.base.ModeType;
47 import org.iotivity.base.OcConnectivityType;
48 import org.iotivity.base.OcException;
49 import org.iotivity.base.OcHeaderOption;
50 import org.iotivity.base.OcPlatform;
51 import org.iotivity.base.OcRepresentation;
52 import org.iotivity.base.OcResource;
53 import org.iotivity.base.OcResourceHandle;
54 import org.iotivity.base.OcResourceRequest;
55 import org.iotivity.base.OcResourceResponse;
56 import org.iotivity.base.PlatformConfig;
57 import org.iotivity.base.QualityOfService;
58 import org.iotivity.base.ServiceType;
59 import org.iotivity.ca.CaEdrInterface;
60 import org.iotivity.ca.CaIpInterface;
61 import org.iotivity.ca.CaLeClientInterface;
63 import java.io.PrintWriter;
64 import java.io.StringWriter;
65 import java.util.ArrayList;
66 import java.util.EnumSet;
67 import java.util.HashMap;
68 import java.util.List;
72 * This class is for messaging between the server and the client.
73 * It can handle message manually.
75 public class MessageFragment extends Fragment implements OcResource.OnGetListener,
76 OcResource.OnPutListener {
78 private static final String TAG = "OIC_SIMPLE_MESSAGE";
79 private final String EOL = System.getProperties().getProperty("line.separator");
80 private final double MILLI_PER_SEC = 1000.0;
82 private Activity mActivity;
83 private Context mContext;
85 OcPlatform.EntityHandler mEntityHandler;
86 private OcResourceHandle mResourceHandle;
87 private OcResource mFoundResource;
89 private QualityOfService mQos = QualityOfService.LOW;
91 private LinearLayout mServerLayout;
92 private LinearLayout mClientLayout;
93 private TextView mResourceText;
94 private TextView mActionLog;
95 private TextView mResultLog;
96 private ToggleButton mQosToggle;
97 private Button mRegisterButton;
98 private Button mGetButton;
99 private Button mPutButton;
100 private Button mLargeButton;
101 private Button mDiscoverIPButton;
102 private Button mDiscoverBTButton;
103 private Button mDiscoverLEButton;
104 private Button mDiscoverTCPButton;
105 private Button mDiscoverNFCButton;
107 private String mLargeData;
108 private boolean mState;
109 private long mStartTime;
110 private long mEndTime;
113 public void onCreate(Bundle savedInstanceState) {
114 super.onCreate(savedInstanceState);
116 mActivity = getActivity();
117 mContext = mActivity.getBaseContext();
120 View.OnClickListener getButtonListener() {
121 return new View.OnClickListener() {
123 public void onClick(View view) {
124 if (mFoundResource != null) {
125 mStartTime = System.currentTimeMillis();
126 sendGetToFoundResource(Common.STATE_GET);
128 Common.showToast(mContext, "Please discovery first");
129 Log.e(TAG, "get() : resource is null");
135 View.OnClickListener putButtonListener() {
136 return new View.OnClickListener() {
138 public void onClick(View view) {
139 if (mFoundResource != null) {
140 mStartTime = System.currentTimeMillis();
141 sendPutToFoundResource();
143 Common.showToast(mContext, "Please discovery first");
144 Log.e(TAG, "put() : resource is null");
150 View.OnClickListener getLargeListener() {
151 return new View.OnClickListener() {
153 public void onClick(View view) {
154 if (mFoundResource != null) {
155 mStartTime = System.currentTimeMillis();
156 sendGetToFoundResource(Common.LARGE_GET);
158 Common.showToast(mContext, "Please discovery first");
159 Log.e(TAG, "large() : resource is null");
165 View.OnClickListener discoverButtonListener(
166 final OcConnectivityType connectivityType) {
167 return new View.OnClickListener() {
169 public void onClick(View view) {
170 initOcPlatform(ModeType.CLIENT);
171 mFoundResource = null;
173 if (OcConnectivityType.CT_ADAPTER_TCP == connectivityType) {
177 Log.i(TAG, "discoverButtonListener");
178 OcPlatform.findResource("",
179 OcPlatform.WELL_KNOWN_QUERY,
180 EnumSet.of(connectivityType),
181 resourceFoundListener, mQos);
183 mActivity.runOnUiThread(new Runnable() {
186 mActionLog.setText("[Action Log]" + EOL);
187 mActionLog.append("Find resource()" + EOL);
188 mActionLog.append("Connectivity : " + connectivityType + EOL);
190 mResultLog.setText("[Result Log]" + EOL);
191 mResultLog.append("Start Time : ");
192 mResultLog.append(Common.getDateCurrentTimeZone() + EOL);
193 mStartTime = System.currentTimeMillis();
196 } catch (OcException e) {
200 mServerLayout.setVisibility(View.GONE);
205 void makeTCPResource(String address) {
207 List<String> resourceTypeList = new ArrayList<String>();
208 List<String> resourceInterfaceList = new ArrayList<String>();
209 resourceInterfaceList.add(Common.RESOURCE_INTERFACE);
210 resourceTypeList.add(Common.RESOURCE_TYPE);
212 mFoundResource = OcPlatform.constructResourceObject(address,
214 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP), false,
215 resourceTypeList, resourceInterfaceList);
217 mActionLog.setText("[Action Log]" + EOL);
218 mActionLog.append("Found resource()" + EOL);
219 mActionLog.append("Connectivity : " + OcConnectivityType.CT_ADAPTER_TCP + EOL);
220 mActionLog.append(mFoundResource.getHost() + Common.RESOURCE_URI);
222 mResultLog.setText("[Result Log]" + EOL);
224 } catch (OcException e) {
229 void sendGetToFoundResource(String command) {
231 Log.i(TAG, "sendGetToFoundResource");
233 Map<String, String> queryParameters = new HashMap<String, String>();
234 queryParameters.put(Common.GET_COMMAND, command);
236 mFoundResource.get(queryParameters, this, mQos);
238 mActionLog.setText("[Action Log]" + EOL + "Send get()"+ EOL + "To : ");
239 mActionLog.append(mFoundResource.getHost() + mFoundResource.getUri() + EOL);
240 } catch (OcException e) {
245 void sendPutToFoundResource() {
247 Log.i(TAG, "sendPutToFoundResource");
249 OcRepresentation rep = new OcRepresentation();
250 rep.setValue(Common.STATE_KEY, !mState);
252 Map<String, String> queryParams = new HashMap<>();
254 mFoundResource.put(rep, queryParams, this);
255 mActionLog.setText("[Action Log]" + EOL);
256 mActionLog.append("Send put()" + EOL + "To : ");
257 mActionLog.append(mFoundResource.getHost() + mFoundResource.getUri() + EOL);
258 } catch (OcException e) {
263 OcPlatform.OnResourceFoundListener resourceFoundListener =
264 new OcPlatform.OnResourceFoundListener() {
266 public void onResourceFound(OcResource ocResource) {
267 synchronized (mActivity) {
268 final String resourceUri = ocResource.getUri();
269 Log.i(TAG, "onResourceFound : " + ocResource.getUri());
271 if (resourceUri.contains(Common.RESOURCE_URI)) {
272 mFoundResource = ocResource;
273 mActivity.runOnUiThread(new Runnable() {
276 mEndTime = System.currentTimeMillis();
277 double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
278 mResultLog.append("Discovery Time : ");
279 mResultLog.append(String.format("%.3f", flightTime) + "sec" + EOL);
280 mActionLog.append(mFoundResource.getHost() + resourceUri + EOL);
288 public void onFindResourceFailed(Throwable throwable, String uri) {
289 synchronized (mActivity) {
290 Log.i(TAG, "findResource request has failed");
291 Log.e(TAG, throwable.toString());
297 public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
298 String repUri = ocRepresentation.getUri();
299 Log.i(TAG, "onGetCompleted : " + repUri);
302 final String command = ocRepresentation.getValue(Common.GET_COMMAND);
304 if (command == null || command.isEmpty()) {
305 Log.e(TAG, "Get command is null");
307 } else if (command.equals(Common.STATE_GET)) {
308 mState = ocRepresentation.getValue(Common.STATE_KEY);
310 } else if (command.equals(Common.LARGE_GET)) {
311 mLargeData = ocRepresentation.getValue(Common.LARGE_KEY);
313 } catch (OcException e) {
317 mActivity.runOnUiThread(new Runnable() {
320 mEndTime = System.currentTimeMillis();
321 double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
323 if (mLargeData == null || mLargeData.isEmpty()) {
324 mResultLog.append(EOL + "Get Light State : " + mState + EOL);
326 mResultLog.append(EOL + "Payload Size : " + mLargeData.length() + EOL);
329 mResultLog.append("Get Time : " + String.format("%.3f", flightTime) + "sec" + EOL);
335 public void onGetFailed(Throwable throwable) {
336 Log.e(TAG, "Get failed");
340 public void onPutCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
341 String repUri = ocRepresentation.getUri();
342 Log.i(TAG, "onPutCompleted : " + repUri);
345 mState = ocRepresentation.getValue(Common.STATE_KEY);
346 } catch (OcException e) {
350 mActivity.runOnUiThread(new Runnable() {
353 mEndTime = System.currentTimeMillis();
354 double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
355 mResultLog.append(EOL + "Set Light State : " + !mState + EOL + "Put Time : ");
356 mResultLog.append(String.format("%.3f", flightTime) + "sec" + EOL);
362 public void onPutFailed(Throwable throwable) {
363 Log.e(TAG, "Put failed");
366 // ******************************************************************************
367 // End of the OCF Client specific code
368 // ******************************************************************************
370 private void createResource() {
371 mEntityHandler = new OcPlatform.EntityHandler() {
373 public EntityHandlerResult handleEntity(
374 OcResourceRequest ocResourceRequest) {
375 return mEntityHandler(ocResourceRequest);
380 mResourceHandle = OcPlatform.registerResource(Common.RESOURCE_URI,
381 Common.RESOURCE_TYPE, Common.RESOURCE_INTERFACE,
382 mEntityHandler, Common.RESOURCE_PROPERTIES);
384 } catch (OcException e) {
385 String errString = "Error : " + e.getErrorCode().toString();
386 Log.e(TAG, errString);
387 StringWriter sw = new StringWriter();
388 e.printStackTrace(new PrintWriter(sw));
389 String exceptionAsString = sw.toString();
390 Log.e(TAG, exceptionAsString);
391 mResourceText.setText(errString);
394 StringBuilder sb = new StringBuilder();
395 for (int i = 0; i < Common.DATA_SIZE; i++) {
398 mLargeData = sb.toString();
401 sb.append("URI : " + Common.RESOURCE_URI + EOL);
402 sb.append("Type : " + Common.RESOURCE_TYPE + EOL);
403 sb.append("Interface : " + Common.RESOURCE_INTERFACE + EOL);
404 sb.append("Properties : " + Common.RESOURCE_PROPERTIES.toString() + EOL);
405 mResourceText.setText(sb.toString());
406 mActionLog.setText("");
407 mResultLog.setText("Created resource" + EOL);
410 protected EntityHandlerResult mEntityHandler(OcResourceRequest ocResourceRequest) {
411 EntityHandlerResult result = EntityHandlerResult.ERROR;
412 final StringBuilder sb = new StringBuilder();
413 switch (ocResourceRequest.getRequestType()) {
415 sb.append("Type : GET");
416 if (sendGetResponse(ocResourceRequest)) {
417 result = EntityHandlerResult.OK;
421 sb.append("Type : PUT");
422 if (sendPutResponse(ocResourceRequest)) {
423 result = EntityHandlerResult.OK;
427 sb.append("Type : DELETE");
430 sb.append("Type : POST");
435 sb.append(EOL + "Light State : " + mState);
436 sb.append(EOL + "Time : " + Common.getDateCurrentTimeZone());
437 if (result == EntityHandlerResult.ERROR) {
438 sb.append(EOL + "!! Error occurred during sending the response !!");
441 mActivity.runOnUiThread(new Runnable() {
444 mResultLog.setText(sb.toString());
451 private boolean sendGetResponse(OcResourceRequest ocResourceRequest) {
452 mActivity.runOnUiThread(new Runnable() {
455 Common.showToast(mContext, "received get command, send response");
459 Map<String, String> queryParameters = ocResourceRequest.getQueryParameters();
460 final String command = queryParameters.get(Common.GET_COMMAND);
463 || (!command.equals(Common.STATE_GET) && !command.equals(Common.LARGE_GET))) {
467 OcRepresentation rep = new OcRepresentation();
469 rep.setValue(Common.GET_COMMAND, command);
470 if (command.equals(Common.STATE_GET)) {
471 rep.setValue(Common.STATE_KEY, mState);
472 } else if (command.equals(Common.LARGE_GET)) {
473 rep.setValue(Common.LARGE_KEY, mLargeData);
475 } catch (OcException e) {
479 OcResourceResponse response = new OcResourceResponse();
481 response.setRequestHandle(ocResourceRequest.getRequestHandle());
482 response.setResourceHandle(ocResourceRequest.getResourceHandle());
483 response.setResourceRepresentation(rep);
485 OcPlatform.sendResponse(response);
487 } catch (OcException e) {
493 private boolean sendPutResponse(OcResourceRequest ocResourceRequest) {
494 mActivity.runOnUiThread(new Runnable() {
497 Common.showToast(mContext, "received put command, send response");
502 OcRepresentation rep = ocResourceRequest.getResourceRepresentation();
503 if (rep.hasAttribute(Common.STATE_KEY)) {
504 mState = rep.getValue(Common.STATE_KEY);
506 } catch (OcException e) {
510 OcResourceResponse response = new OcResourceResponse();
511 OcRepresentation rep = new OcRepresentation();
513 response.setRequestHandle(ocResourceRequest.getRequestHandle());
514 response.setResourceHandle(ocResourceRequest.getResourceHandle());
515 response.setResourceRepresentation(rep);
517 OcPlatform.sendResponse(response);
519 } catch (OcException e) {
525 // ******************************************************************************
526 // End of the OCF Server specific code
527 // ******************************************************************************
529 private void initOcPlatform(ModeType type) {
530 PlatformConfig cfg = new PlatformConfig(mActivity, mContext,
536 OcPlatform.Configure(cfg);
540 public View onCreateView(LayoutInflater inflater, ViewGroup container,
541 Bundle savedInstanceState) {
542 View rootView = inflater.inflate(R.layout.fragment_message, container, false);
544 mServerLayout = (LinearLayout) rootView.findViewById(R.id.server_layout);
545 mClientLayout = (LinearLayout) rootView.findViewById(R.id.client_layout);
547 mResourceText = (TextView) rootView.findViewById(R.id.resource_view);
548 mActionLog = (TextView) rootView.findViewById(R.id.action_log_view);
549 mResultLog = (TextView) rootView.findViewById(R.id.result_log_view);
551 mDiscoverIPButton = (Button) rootView.findViewById(R.id.ip_button);
552 mDiscoverBTButton = (Button) rootView.findViewById(R.id.bt_button);
553 mDiscoverLEButton = (Button) rootView.findViewById(R.id.le_button);
554 mDiscoverTCPButton = (Button) rootView.findViewById(R.id.tcp_button);
555 mDiscoverNFCButton = (Button) rootView.findViewById(R.id.nfc_button);
557 mRegisterButton = (Button) rootView.findViewById(R.id.register_button);
558 mGetButton = (Button) rootView.findViewById(R.id.get_button);
559 mPutButton = (Button) rootView.findViewById(R.id.put_button);
560 mLargeButton = (Button) rootView.findViewById(R.id.large_button);
562 mQosToggle = (ToggleButton) rootView.findViewById(R.id.qos_toggle_button);
564 mDiscoverIPButton.setOnClickListener(
565 discoverButtonListener(OcConnectivityType.CT_ADAPTER_IP));
566 mDiscoverBTButton.setOnClickListener(
567 discoverButtonListener(OcConnectivityType.CT_ADAPTER_RFCOMM_BTEDR));
568 mDiscoverLEButton.setOnClickListener(
569 discoverButtonListener(OcConnectivityType.CT_ADAPTER_GATT_BTLE));
570 mDiscoverTCPButton.setOnClickListener(
571 discoverButtonListener(OcConnectivityType.CT_ADAPTER_TCP));
572 mDiscoverNFCButton.setOnClickListener(
573 discoverButtonListener(OcConnectivityType.CT_ADAPTER_NFC));
575 mRegisterButton.setOnClickListener(new View.OnClickListener() {
577 public void onClick(View view) {
578 if (mResourceHandle == null) {
579 initOcPlatform(ModeType.SERVER);
581 mClientLayout.setVisibility(View.GONE);
583 Common.showToast(mContext, "Already created resource");
587 mGetButton.setOnClickListener(getButtonListener());
588 mPutButton.setOnClickListener(putButtonListener());
589 mLargeButton.setOnClickListener(getLargeListener());
592 .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
594 public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
596 mQos = QualityOfService.HIGH;
598 mQos = QualityOfService.LOW;
606 private void showTCPInput() {
608 LayoutInflater layoutInflater = LayoutInflater.from(mContext);
609 View inputView = layoutInflater.inflate(R.layout.tcp_input, null);
610 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
611 alertDialogBuilder.setView(inputView);
613 final EditText editText = (EditText) inputView.getRootView().findViewById(R.id.ipText);
614 editText.setText(Common.TCP_ADDRESS);
616 .setCancelable(false)
617 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
618 public void onClick(DialogInterface dialog, int id) {
619 if (editText.getText().length() != 0) {
620 Common.TCP_ADDRESS = editText.getText().toString();
622 StringBuilder sb = new StringBuilder();
623 sb.append(Common.COAP_TCP);
624 sb.append(Common.TCP_ADDRESS);
625 sb.append(Common.TCP_PORT);
626 makeTCPResource(sb.toString());
630 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
631 public void onClick(DialogInterface dialog, int id) {
636 AlertDialog alert = alertDialogBuilder.create();
641 public void onResume() {
646 public void onDestroy() {