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);
172 } else if (OcConnectivityType.CT_ADAPTER_GATT_BTLE == connectivityType) {
173 if (null != Common.getLeAddress())
175 OcPlatform.findResource("",
176 Common.getLeAddress() + OcPlatform.WELL_KNOWN_QUERY,
177 EnumSet.of(OcConnectivityType.CT_ADAPTER_GATT_BTLE),
178 resourceFoundListener, QualityOfService.LOW);
180 Common.showToast(mContext, "Please scan ble device");
181 Log.e(TAG, "invalid ble device");
184 OcPlatform.findResource("",
185 OcPlatform.WELL_KNOWN_QUERY,
186 EnumSet.of(connectivityType),
187 resourceFoundListener, mQos);
189 } catch (OcException e) {
193 mActivity.runOnUiThread(new Runnable() {
196 mActionLog.setText("[Action Log]" + EOL);
197 mActionLog.append("Find resource()" + EOL);
198 mActionLog.append("Connectivity : " + connectivityType + EOL);
200 mResultLog.setText("[Result Log]" + EOL);
201 mResultLog.append("Start Time : ");
202 mResultLog.append(Common.getDateCurrentTimeZone() + EOL);
203 mStartTime = System.currentTimeMillis();
206 mServerLayout.setVisibility(View.GONE);
211 void sendGetToFoundResource(String command) {
213 Log.i(TAG, "sendGetToFoundResource");
215 Map<String, String> queryParameters = new HashMap<String, String>();
216 queryParameters.put(Common.GET_COMMAND, command);
218 mFoundResource.get(queryParameters, this, mQos);
220 mActionLog.setText("[Action Log]" + EOL + "Send get()"+ EOL + "To : ");
221 mActionLog.append(mFoundResource.getHost() + mFoundResource.getUri() + EOL);
222 } catch (OcException e) {
227 void sendPutToFoundResource() {
229 Log.i(TAG, "sendPutToFoundResource");
231 OcRepresentation rep = new OcRepresentation();
232 rep.setValue(Common.STATE_KEY, !mState);
234 Map<String, String> queryParams = new HashMap<>();
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) {
245 OcPlatform.OnResourceFoundListener resourceFoundListener =
246 new OcPlatform.OnResourceFoundListener() {
248 public void onResourceFound(OcResource ocResource) {
249 synchronized (mActivity) {
250 final String resourceUri = ocResource.getUri();
251 Log.i(TAG, "onResourceFound : " + ocResource.getUri());
253 if (resourceUri.contains(Common.RESOURCE_URI)
254 && ocResource.getConnectivityTypeSet().contains(mCurrConnectivity)) {
255 mFoundResource = ocResource;
256 mActivity.runOnUiThread(new Runnable() {
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);
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());
280 public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
281 String repUri = ocRepresentation.getUri();
282 Log.i(TAG, "onGetCompleted : " + repUri);
285 final String command = ocRepresentation.getValue(Common.GET_COMMAND);
287 if (command == null || command.isEmpty()) {
288 Log.e(TAG, "Get command is null");
290 } else if (command.equals(Common.STATE_GET)) {
291 mState = ocRepresentation.getValue(Common.STATE_KEY);
293 } else if (command.equals(Common.LARGE_GET)) {
294 mLargeData = ocRepresentation.getValue(Common.LARGE_KEY);
296 } catch (OcException e) {
300 mActivity.runOnUiThread(new Runnable() {
303 mEndTime = System.currentTimeMillis();
304 double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
306 if (mLargeData == null || mLargeData.isEmpty()) {
307 mResultLog.append(EOL + "Get Light State : " + mState + EOL);
309 mResultLog.append(EOL + "Payload Size : " + mLargeData.length() + EOL);
312 mResultLog.append("Get Time : " + String.format("%.3f", flightTime) + "sec" + EOL);
318 public void onGetFailed(Throwable throwable) {
319 Log.e(TAG, "Get failed");
323 public void onPutCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
324 String repUri = ocRepresentation.getUri();
325 Log.i(TAG, "onPutCompleted : " + repUri);
328 mState = ocRepresentation.getValue(Common.STATE_KEY);
329 } catch (OcException e) {
333 mActivity.runOnUiThread(new Runnable() {
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);
345 public void onPutFailed(Throwable throwable) {
346 Log.e(TAG, "Put failed");
349 // ******************************************************************************
350 // End of the OCF Client specific code
351 // ******************************************************************************
353 private void createResource() {
354 mEntityHandler = new OcPlatform.EntityHandler() {
356 public EntityHandlerResult handleEntity(
357 OcResourceRequest ocResourceRequest) {
358 return mEntityHandler(ocResourceRequest);
363 mResourceHandle = OcPlatform.registerResource(Common.RESOURCE_URI,
364 Common.RESOURCE_TYPE, Common.RESOURCE_INTERFACE,
365 mEntityHandler, Common.RESOURCE_PROPERTIES);
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);
377 StringBuilder sb = new StringBuilder();
378 for (int i = 0; i < Common.DATA_SIZE; i++) {
381 mLargeData = sb.toString();
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);
393 protected EntityHandlerResult mEntityHandler(OcResourceRequest ocResourceRequest) {
394 EntityHandlerResult result = EntityHandlerResult.ERROR;
395 final StringBuilder sb = new StringBuilder();
396 switch (ocResourceRequest.getRequestType()) {
398 sb.append("Type : GET");
399 if (sendGetResponse(ocResourceRequest)) {
400 result = EntityHandlerResult.OK;
404 sb.append("Type : PUT");
405 if (sendPutResponse(ocResourceRequest)) {
406 result = EntityHandlerResult.OK;
410 sb.append("Type : DELETE");
413 sb.append("Type : POST");
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 !!");
424 mActivity.runOnUiThread(new Runnable() {
427 mResultLog.setText(sb.toString());
434 private boolean sendGetResponse(OcResourceRequest ocResourceRequest) {
435 mActivity.runOnUiThread(new Runnable() {
438 Common.showToast(mContext, "received get command, send response");
442 Map<String, String> queryParameters = ocResourceRequest.getQueryParameters();
443 final String command = queryParameters.get(Common.GET_COMMAND);
446 || (!command.equals(Common.STATE_GET) && !command.equals(Common.LARGE_GET))) {
450 OcRepresentation rep = new OcRepresentation();
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);
458 } catch (OcException e) {
462 OcResourceResponse response = new OcResourceResponse();
464 response.setRequestHandle(ocResourceRequest.getRequestHandle());
465 response.setResourceHandle(ocResourceRequest.getResourceHandle());
466 response.setResourceRepresentation(rep);
468 OcPlatform.sendResponse(response);
470 } catch (OcException e) {
476 private boolean sendPutResponse(OcResourceRequest ocResourceRequest) {
477 mActivity.runOnUiThread(new Runnable() {
480 Common.showToast(mContext, "received put command, send response");
485 OcRepresentation rep = ocResourceRequest.getResourceRepresentation();
486 if (rep.hasAttribute(Common.STATE_KEY)) {
487 mState = rep.getValue(Common.STATE_KEY);
489 } catch (OcException e) {
493 OcResourceResponse response = new OcResourceResponse();
494 OcRepresentation rep = new OcRepresentation();
496 response.setRequestHandle(ocResourceRequest.getRequestHandle());
497 response.setResourceHandle(ocResourceRequest.getResourceHandle());
498 response.setResourceRepresentation(rep);
500 OcPlatform.sendResponse(response);
502 } catch (OcException e) {
508 // ******************************************************************************
509 // End of the OCF Server specific code
510 // ******************************************************************************
512 private void initOcPlatform(ModeType type) {
513 PlatformConfig cfg = new PlatformConfig(mActivity, mContext,
519 OcPlatform.Configure(cfg);
523 public View onCreateView(LayoutInflater inflater, ViewGroup container,
524 Bundle savedInstanceState) {
525 View rootView = inflater.inflate(R.layout.fragment_message, container, false);
527 mServerLayout = (LinearLayout) rootView.findViewById(R.id.server_layout);
528 mClientLayout = (LinearLayout) rootView.findViewById(R.id.client_layout);
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);
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);
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);
545 mQosToggle = (ToggleButton) rootView.findViewById(R.id.qos_toggle_button);
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));
558 mRegisterButton.setOnClickListener(new View.OnClickListener() {
560 public void onClick(View view) {
561 if (mResourceHandle == null) {
562 initOcPlatform(ModeType.SERVER);
564 mClientLayout.setVisibility(View.GONE);
566 Common.showToast(mContext, "Already created resource");
570 mGetButton.setOnClickListener(getButtonListener());
571 mPutButton.setOnClickListener(putButtonListener());
572 mLargeButton.setOnClickListener(getLargeListener());
575 .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
577 public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
579 mQos = QualityOfService.HIGH;
581 mQos = QualityOfService.LOW;
590 public void onResume() {
595 public void onDestroy() {