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.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;
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;
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;
62 * This class is for messaging between the server and the client.
63 * It can handle message manually.
65 public class MessageFragment extends Fragment implements OcResource.OnGetListener,
66 OcResource.OnPutListener {
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;
72 private Activity mActivity;
73 private Context mContext;
75 OcPlatform.EntityHandler mEntityHandler;
76 private OcResourceHandle mResourceHandle;
77 private OcResource mFoundResource;
78 private OcConnectivityType mCurrConnectivity;
80 private QualityOfService mQos = QualityOfService.LOW;
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;
98 private String mLargeData;
99 private boolean mState;
100 private long mStartTime;
101 private long mEndTime;
104 public void onCreate(Bundle savedInstanceState) {
105 super.onCreate(savedInstanceState);
107 mActivity = getActivity();
108 mContext = mActivity.getBaseContext();
111 View.OnClickListener getButtonListener() {
112 return new View.OnClickListener() {
114 public void onClick(View view) {
115 if (mFoundResource != null) {
116 mStartTime = System.currentTimeMillis();
117 sendGetToFoundResource(Common.STATE_GET);
119 Common.showToast(mContext, "Please discovery first");
120 Log.e(TAG, "get() : resource is null");
126 View.OnClickListener putButtonListener() {
127 return new View.OnClickListener() {
129 public void onClick(View view) {
130 if (mFoundResource != null) {
131 mStartTime = System.currentTimeMillis();
132 sendPutToFoundResource();
134 Common.showToast(mContext, "Please discovery first");
135 Log.e(TAG, "put() : resource is null");
141 View.OnClickListener getLargeListener() {
142 return new View.OnClickListener() {
144 public void onClick(View view) {
145 if (mFoundResource != null) {
146 mStartTime = System.currentTimeMillis();
147 sendGetToFoundResource(Common.LARGE_GET);
149 Common.showToast(mContext, "Please discovery first");
150 Log.e(TAG, "large() : resource is null");
156 View.OnClickListener discoverButtonListener(
157 final OcConnectivityType connectivityType) {
158 return new View.OnClickListener() {
160 public void onClick(View view) {
161 Log.i(TAG, "discoverButtonListener");
162 initOcPlatform(ModeType.CLIENT);
163 mFoundResource = null;
164 mCurrConnectivity = connectivityType;
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);
173 OcPlatform.findResource("",
174 OcPlatform.WELL_KNOWN_QUERY,
175 EnumSet.of(connectivityType),
176 resourceFoundListener, mQos);
178 } catch (OcException e) {
182 mActivity.runOnUiThread(new Runnable() {
185 mActionLog.setText("[Action Log]" + EOL);
186 mActionLog.append("Find resource()" + EOL);
187 mActionLog.append("Connectivity : " + connectivityType + EOL);
189 mResultLog.setText("[Result Log]" + EOL);
190 mResultLog.append("Start Time : ");
191 mResultLog.append(Common.getDateCurrentTimeZone() + EOL);
192 mStartTime = System.currentTimeMillis();
195 mServerLayout.setVisibility(View.GONE);
200 void sendGetToFoundResource(String command) {
202 Log.i(TAG, "sendGetToFoundResource");
204 Map<String, String> queryParameters = new HashMap<String, String>();
205 queryParameters.put(Common.GET_COMMAND, command);
207 mFoundResource.get(queryParameters, this, mQos);
209 mActionLog.setText("[Action Log]" + EOL + "Send get()"+ EOL + "To : ");
210 mActionLog.append(mFoundResource.getHost() + mFoundResource.getUri() + EOL);
211 } catch (OcException e) {
216 void sendPutToFoundResource() {
218 Log.i(TAG, "sendPutToFoundResource");
220 OcRepresentation rep = new OcRepresentation();
221 rep.setValue(Common.STATE_KEY, !mState);
223 Map<String, String> queryParams = new HashMap<>();
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) {
234 OcPlatform.OnResourceFoundListener resourceFoundListener =
235 new OcPlatform.OnResourceFoundListener() {
237 public void onResourceFound(OcResource ocResource) {
238 synchronized (mActivity) {
239 final String resourceUri = ocResource.getUri();
240 Log.i(TAG, "onResourceFound : " + ocResource.getUri());
242 if (resourceUri.contains(Common.RESOURCE_URI)
243 && ocResource.getConnectivityTypeSet().contains(mCurrConnectivity)) {
244 mFoundResource = ocResource;
245 mActivity.runOnUiThread(new Runnable() {
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);
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());
269 public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
270 String repUri = ocRepresentation.getUri();
271 Log.i(TAG, "onGetCompleted : " + repUri);
274 final String command = ocRepresentation.getValue(Common.GET_COMMAND);
276 if (command == null || command.isEmpty()) {
277 Log.e(TAG, "Get command is null");
279 } else if (command.equals(Common.STATE_GET)) {
280 mState = ocRepresentation.getValue(Common.STATE_KEY);
282 } else if (command.equals(Common.LARGE_GET)) {
283 mLargeData = ocRepresentation.getValue(Common.LARGE_KEY);
285 } catch (OcException e) {
289 mActivity.runOnUiThread(new Runnable() {
292 mEndTime = System.currentTimeMillis();
293 double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
295 if (mLargeData == null || mLargeData.isEmpty()) {
296 mResultLog.append(EOL + "Get Light State : " + mState + EOL);
298 mResultLog.append(EOL + "Payload Size : " + mLargeData.length() + EOL);
301 mResultLog.append("Get Time : " + String.format("%.3f", flightTime) + "sec" + EOL);
307 public void onGetFailed(Throwable throwable) {
308 Log.e(TAG, "Get failed");
312 public void onPutCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
313 String repUri = ocRepresentation.getUri();
314 Log.i(TAG, "onPutCompleted : " + repUri);
317 mState = ocRepresentation.getValue(Common.STATE_KEY);
318 } catch (OcException e) {
322 mActivity.runOnUiThread(new Runnable() {
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);
334 public void onPutFailed(Throwable throwable) {
335 Log.e(TAG, "Put failed");
338 // ******************************************************************************
339 // End of the OCF Client specific code
340 // ******************************************************************************
342 private void createResource() {
343 mEntityHandler = new OcPlatform.EntityHandler() {
345 public EntityHandlerResult handleEntity(
346 OcResourceRequest ocResourceRequest) {
347 return mEntityHandler(ocResourceRequest);
352 mResourceHandle = OcPlatform.registerResource(Common.RESOURCE_URI,
353 Common.RESOURCE_TYPE, Common.RESOURCE_INTERFACE,
354 mEntityHandler, Common.RESOURCE_PROPERTIES);
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);
366 StringBuilder sb = new StringBuilder();
367 for (int i = 0; i < Common.DATA_SIZE; i++) {
370 mLargeData = sb.toString();
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);
382 protected EntityHandlerResult mEntityHandler(OcResourceRequest ocResourceRequest) {
383 EntityHandlerResult result = EntityHandlerResult.ERROR;
384 final StringBuilder sb = new StringBuilder();
385 switch (ocResourceRequest.getRequestType()) {
387 sb.append("Type : GET");
388 if (sendGetResponse(ocResourceRequest)) {
389 result = EntityHandlerResult.OK;
393 sb.append("Type : PUT");
394 if (sendPutResponse(ocResourceRequest)) {
395 result = EntityHandlerResult.OK;
399 sb.append("Type : DELETE");
402 sb.append("Type : POST");
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 !!");
413 mActivity.runOnUiThread(new Runnable() {
416 mResultLog.setText(sb.toString());
423 private boolean sendGetResponse(OcResourceRequest ocResourceRequest) {
424 mActivity.runOnUiThread(new Runnable() {
427 Common.showToast(mContext, "received get command, send response");
431 Map<String, String> queryParameters = ocResourceRequest.getQueryParameters();
432 final String command = queryParameters.get(Common.GET_COMMAND);
435 || (!command.equals(Common.STATE_GET) && !command.equals(Common.LARGE_GET))) {
439 OcRepresentation rep = new OcRepresentation();
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);
447 } catch (OcException e) {
451 OcResourceResponse response = new OcResourceResponse();
453 response.setRequestHandle(ocResourceRequest.getRequestHandle());
454 response.setResourceHandle(ocResourceRequest.getResourceHandle());
455 response.setResourceRepresentation(rep);
457 OcPlatform.sendResponse(response);
459 } catch (OcException e) {
465 private boolean sendPutResponse(OcResourceRequest ocResourceRequest) {
466 mActivity.runOnUiThread(new Runnable() {
469 Common.showToast(mContext, "received put command, send response");
474 OcRepresentation rep = ocResourceRequest.getResourceRepresentation();
475 if (rep.hasAttribute(Common.STATE_KEY)) {
476 mState = rep.getValue(Common.STATE_KEY);
478 } catch (OcException e) {
482 OcResourceResponse response = new OcResourceResponse();
483 OcRepresentation rep = new OcRepresentation();
485 response.setRequestHandle(ocResourceRequest.getRequestHandle());
486 response.setResourceHandle(ocResourceRequest.getResourceHandle());
487 response.setResourceRepresentation(rep);
489 OcPlatform.sendResponse(response);
491 } catch (OcException e) {
497 // ******************************************************************************
498 // End of the OCF Server specific code
499 // ******************************************************************************
501 private void initOcPlatform(ModeType type) {
502 PlatformConfig cfg = new PlatformConfig(mActivity, mContext,
508 OcPlatform.Configure(cfg);
512 public View onCreateView(LayoutInflater inflater, ViewGroup container,
513 Bundle savedInstanceState) {
514 View rootView = inflater.inflate(R.layout.fragment_message, container, false);
516 mServerLayout = (LinearLayout) rootView.findViewById(R.id.server_layout);
517 mClientLayout = (LinearLayout) rootView.findViewById(R.id.client_layout);
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);
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);
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);
534 mQosToggle = (ToggleButton) rootView.findViewById(R.id.qos_toggle_button);
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));
547 mRegisterButton.setOnClickListener(new View.OnClickListener() {
549 public void onClick(View view) {
550 if (mResourceHandle == null) {
551 initOcPlatform(ModeType.SERVER);
553 mClientLayout.setVisibility(View.GONE);
555 Common.showToast(mContext, "Already created resource");
559 mGetButton.setOnClickListener(getButtonListener());
560 mPutButton.setOnClickListener(putButtonListener());
561 mLargeButton.setOnClickListener(getLargeListener());
564 .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
566 public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
568 mQos = QualityOfService.HIGH;
570 mQos = QualityOfService.LOW;
579 public void onResume() {
584 public void onDestroy() {