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.os.Bundle;
32 import android.util.Log;
33 import android.view.LayoutInflater;
34 import android.view.View;
35 import android.view.ViewGroup;
36 import android.widget.Button;
37 import android.widget.CheckBox;
38 import android.widget.CompoundButton;
39 import android.widget.EditText;
40 import android.widget.LinearLayout;
41 import android.widget.ScrollView;
42 import android.widget.Switch;
43 import android.widget.TextView;
44 import android.widget.Toast;
46 import org.iotivity.base.EntityHandlerResult;
47 import org.iotivity.base.ErrorCode;
48 import org.iotivity.base.ModeType;
49 import org.iotivity.base.OcAccountManager;
50 import org.iotivity.base.OcConnectivityType;
51 import org.iotivity.base.OcException;
52 import org.iotivity.base.OcHeaderOption;
53 import org.iotivity.base.OcPlatform;
54 import org.iotivity.base.OcPresenceHandle;
55 import org.iotivity.base.OcRepresentation;
56 import org.iotivity.base.OcResource;
57 import org.iotivity.base.OcResourceHandle;
58 import org.iotivity.base.OcRDClient;
59 import org.iotivity.base.PlatformConfig;
60 import org.iotivity.base.QualityOfService;
61 import org.iotivity.base.ResourceProperty;
62 import org.iotivity.base.ServiceType;
64 import java.util.ArrayList;
65 import java.util.EnumSet;
66 import java.util.HashMap;
67 import java.util.LinkedList;
68 import java.util.List;
70 import java.util.Objects;
71 import java.util.regex.Pattern;
74 * This class is for messaging between the cloud server and the client.
75 * It can handle cloud API manually.
77 public class CloudFragment extends Fragment implements
78 View.OnClickListener, CompoundButton.OnCheckedChangeListener,
79 OcResource.OnObserveListener,
80 OcResource.OnMQTopicFoundListener, OcResource.OnMQTopicCreatedListener,
81 OcResource.OnMQTopicSubscribeListener {
83 private static final String TAG = "OIC_SIMPLE_CLOUD";
84 private final String EOL = System.getProperties().getProperty("line.separator");
85 private final Pattern ADDRESS_PORT
87 "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])" +
88 "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)" +
89 "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)" +
90 "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])" +
93 private Activity mActivity;
94 private Context mContext;
96 private QualityOfService mQos = QualityOfService.LOW;
97 private boolean mSecured = false;
99 private LinearLayout mAccountLayout;
100 private LinearLayout mRDLayout;
101 private LinearLayout mMQLayout;
103 private TextView mAccountText;
104 private TextView mRDText;
105 private TextView mMQText;
106 private ScrollView mScrollView;
107 private TextView mActionLog;
108 private TextView mResultLog;
110 private OcAccountManager mAccountManager;
111 private String mAccessToken;
112 private String mRefreshToken;
113 private String mUserUuid;
114 private String mGroupId;
115 private String mGroupMasterId;
116 private String mInviterUserId;
117 private String mInviteeUuid;
118 private final int REQUEST_LOGIN = 1;
120 private OcResourceHandle localLightResourceHandle = null;
121 private List<OcResourceHandle> mResourceHandleList = new LinkedList<>();
122 private OcPresenceHandle mOcPresenceHandle = null;
123 private Button mDevicePresenceButton;
125 private OcResource MQbrokerResource = null;
126 private OcResource currentTopicResource = null;
127 private boolean switchingFlag = true;
128 private int roomNum = 1;
129 private String defaultTopicFullName = Common.MQ_DEFAULT_TOPIC_URI;
131 // variables related observer
132 private int maxSequenceNumber = 0xFFFFFF;
135 public void onCreate(Bundle savedInstanceState) {
136 super.onCreate(savedInstanceState);
138 mActivity = getActivity();
139 mContext = mActivity.getBaseContext();
140 initOcPlatform(ModeType.CLIENT_SERVER);
143 private void initOcPlatform(ModeType type) {
144 PlatformConfig cfg = new PlatformConfig(mActivity, mContext,
150 OcPlatform.Configure(cfg);
153 private void signUp() {
155 mAccountManager = OcPlatform.constructAccountManagerObject(
157 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
158 } catch (OcException e) {
162 Intent intentLogin = new Intent(mContext, LoginActivity.class);
163 startActivityForResult(intentLogin, REQUEST_LOGIN);
166 private void signIn() {
169 mAccountManager.signIn(mUserUuid, mAccessToken, onSignIn);
170 } catch (OcException e) {
175 private void signOut() {
178 mAccountManager.signOut(mAccessToken, onSignOut);
179 } catch (OcException e) {
184 private void createGroup() {
187 mAccountManager.createGroup(onCreateGroup);
188 } catch (OcException e) {
193 private void deleteGroup() {
194 if (mGroupId == null) {
195 msg("there is no any group");
199 mAccountManager.deleteGroup(mGroupId, onDeleteGroup);
200 } catch (OcException e) {
206 private void inviteUser() {
207 if (mGroupId == null) {
208 msg("there is no any group");
214 private void addPropertyValueToGroup() {
215 if (mGroupId == null) {
216 msg("there is no any group");
218 showPostPropertyValueToGroup(0);
222 private void deletePropertyValueFromGroup() {
223 if (mGroupId == null) {
224 msg("there is no any group");
226 showPostPropertyValueToGroup(1);
230 private void updatePropertyValueOnGroup() {
231 if (mGroupId == null) {
232 msg("there is no any group");
234 showPostPropertyValueToGroup(2);
239 public void onActivityResult(int requestCode, int resultCode, Intent data) {
240 super.onActivityResult(requestCode, resultCode, data);
241 if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
242 String authCode = data.getStringExtra("authCode");
243 msg("\tauthCode: " + authCode);
247 mAccountManager.signUp("github", authCode, onSignUp);
248 } catch (OcException e) {
254 OcAccountManager.OnPostListener onSignUp = new OcAccountManager.OnPostListener() {
256 public synchronized void onPostCompleted(List<OcHeaderOption> list,
257 OcRepresentation ocRepresentation) {
258 msg("signUp was successful");
260 mUserUuid = ocRepresentation.getValue("uid");
261 mAccessToken = ocRepresentation.getValue("accesstoken");
262 mRefreshToken = ocRepresentation.getValue("refreshtoken");
263 String tokenType = ocRepresentation.getValue("tokentype");
264 msg("\tuserID: " + mUserUuid);
265 msg("\taccessToken: " + mAccessToken);
266 msg("\trefreshToken: " + mRefreshToken);
267 msg("\ttokenType: " + tokenType);
269 if (ocRepresentation.hasAttribute("expiresin")) {
270 int expiresIn = ocRepresentation.getValue("expiresin");
271 msg("\texpiresIn: " + expiresIn);
273 } catch (OcException e) {
274 Log.e(TAG, e.toString());
279 public synchronized void onPostFailed(Throwable throwable) {
280 msg("Failed to signUp");
281 if (throwable instanceof OcException) {
282 OcException ocEx = (OcException) throwable;
283 Log.e(TAG, ocEx.toString());
284 ErrorCode errCode = ocEx.getErrorCode();
285 msg("Error code: " + errCode);
290 OcAccountManager.OnPostListener onSignIn = new OcAccountManager.OnPostListener() {
292 public synchronized void onPostCompleted(List<OcHeaderOption> list,
293 OcRepresentation ocRepresentation) {
294 msg("signIn was successful");
296 msg("observeInvitation");
297 mAccountManager.observeInvitation(onObserveInvitation);
299 mAccountManager.observeGroup(onObserveGroup);
301 mAccountManager.getGroupInfoAll(onGetGroupInfoAll);
302 } catch (OcException e) {
303 Log.e(TAG, e.toString());
308 public synchronized void onPostFailed(Throwable throwable) {
309 msg("Failed to signIn");
310 if (throwable instanceof OcException) {
311 OcException ocEx = (OcException) throwable;
312 Log.e(TAG, ocEx.toString());
313 ErrorCode errCode = ocEx.getErrorCode();
314 msg("Error code: " + errCode);
319 OcAccountManager.OnPostListener onSignOut = new OcAccountManager.OnPostListener() {
321 public synchronized void onPostCompleted(List<OcHeaderOption> list,
322 OcRepresentation ocRepresentation) {
323 msg("signOut was successful");
327 public synchronized void onPostFailed(Throwable throwable) {
328 msg("Failed to signOut");
329 if (throwable instanceof OcException) {
330 OcException ocEx = (OcException) throwable;
331 Log.e(TAG, ocEx.toString());
332 ErrorCode errCode = ocEx.getErrorCode();
333 msg("Error code: " + errCode);
338 OcAccountManager.OnGetListener onGetGroupInfoAll = new OcAccountManager.OnGetListener() {
340 public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
341 msg("getGroupInfoAll was successful");
344 OcRepresentation[] gidlist = ocRepresentation.getValue("groups");
345 if (gidlist == null || gidlist.length == 0) {
346 msg("\tgroup list is empty");
351 for (OcRepresentation group : gidlist) {
352 String gid = group.getValue("gid");
353 String gname = group.getValue("gname");
354 String owner = group.getValue("owner");
356 msg("\t\t-GroupID : " + gid);
357 msg("\t\t Group name : " + gname);
358 msg("\t\t Owner : " + owner);
360 String[] members = group.getValue("members");
361 if (members != null && members.length != 0) {
362 msg("\t\t members :");
363 for (String member : members) {
364 msg("\t\t\t" + member);
368 String[] devices = group.getValue("devices");
369 if (devices != null && devices.length != 0) {
371 for (String device : devices) {
372 msg("\t\t\t" + device);
376 if (group.hasAttribute("parent")) {
377 msg("\t\t parent group : " + group.getValue("parent"));
382 msg("\tcurrent group is " + mGroupId);
384 } catch (OcException e) {
390 public void onGetFailed(Throwable throwable) {
391 msg("Failed to getGroupInfoAll");
392 if (throwable instanceof OcException) {
393 OcException ocEx = (OcException) throwable;
394 Log.e(TAG, ocEx.toString());
395 ErrorCode errCode = ocEx.getErrorCode();
396 msg("Error code: " + errCode);
401 OcAccountManager.OnGetListener onGetGroupInfo = new OcAccountManager.OnGetListener() {
403 public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
404 msg("getGroupInfo was successful");
406 Map<String, Object> valueMap = ocRepresentation.getValues();
408 for (Map.Entry<String, Object> entry : valueMap.entrySet()) {
409 msg("\tproperty: " + entry.getKey() + " value: " + entry.getValue());
414 public void onGetFailed(Throwable throwable) {
415 msg("Failed to getGroupInfo");
416 if (throwable instanceof OcException) {
417 OcException ocEx = (OcException) throwable;
418 Log.e(TAG, ocEx.toString());
419 ErrorCode errCode = ocEx.getErrorCode();
420 msg("Error code: " + errCode);
425 OcAccountManager.OnObserveListener onObserveInvitation =
426 new OcAccountManager.OnObserveListener() {
428 public void onObserveCompleted(List<OcHeaderOption> list,
429 OcRepresentation ocRepresentation, int i) {
430 msg("observeInvitation was successful");
433 msg("REGISTER was successful");
435 OcRepresentation[] sendInvitationList =
436 ocRepresentation.getValue("invite");
437 if (sendInvitationList != null && sendInvitationList.length != 0) {
438 msg("\tList of invitation that I sent");
439 for (OcRepresentation invitation : sendInvitationList) {
440 String gid = invitation.getValue("gid");
441 String mid = invitation.getValue("mid");
442 msg("\t\t-GroupID : " + gid);
443 msg("\t\t InviteeID : " + mid);
447 OcRepresentation[] receiveInvitationList =
448 ocRepresentation.getValue("invited");
449 if (receiveInvitationList != null && receiveInvitationList.length != 0) {
450 msg("\tList of invitation that I received");
451 for (OcRepresentation invitation : receiveInvitationList) {
452 String gid = invitation.getValue("gid");
453 String mid = invitation.getValue("mid");
454 msg("\t\t-GroupID : " + gid);
455 msg("\t\t InviterID : " + mid);
458 } else if (DEREGISTER == i) {
459 msg("DEREGISTER was successful");
461 OcRepresentation[] sendInvitationList =
462 ocRepresentation.getValue("invite");
463 if (sendInvitationList != null && sendInvitationList.length != 0) {
464 msg("\tList of invitation that I sent");
465 for (OcRepresentation invitation : sendInvitationList) {
466 String gid = invitation.getValue("gid");
467 String mid = invitation.getValue("mid");
468 msg("\t\t-GroupID : " + gid);
469 msg("\t\t InviteeID : " + mid);
473 OcRepresentation[] receivInvitationList =
474 ocRepresentation.getValue("invited");
475 if (receivInvitationList != null && receivInvitationList.length != 0) {
476 msg("\tList of invitation that I received");
477 for (OcRepresentation invitation : receivInvitationList) {
478 mGroupId = invitation.getValue("gid");
479 mGroupMasterId = invitation.getValue("mid");
480 msg("\t\t-GroupID : " + mGroupId);
481 msg("\t\t InviterID : " + mGroupMasterId);
484 mAccountManager.searchUser(mGroupMasterId, onSearchUserForInvitee);
487 } catch (OcException e) {
493 public void onObserveFailed(Throwable throwable) {
494 msg("Failed to observeInvitation");
495 if (throwable instanceof OcException) {
496 OcException ocEx = (OcException) throwable;
497 Log.e(TAG, ocEx.toString());
498 ErrorCode errCode = ocEx.getErrorCode();
499 msg("Error code: " + errCode);
504 OcAccountManager.OnGetListener onSearchUserForInvitee = new OcAccountManager.OnGetListener() {
506 public synchronized void onGetCompleted(List<OcHeaderOption> list,
507 OcRepresentation ocRepresentation) {
508 msg("searchUser was successful");
510 OcRepresentation[] userList = ocRepresentation.getValue("ulist");
511 for (OcRepresentation user : userList) {
512 String inviterUuid = user.getValue("uid");
513 Log.d(TAG, "inviterUuid : " + inviterUuid);
515 OcRepresentation userInfo = user.getValue("uinfo");
516 mInviterUserId = userInfo.getValue("userid");
519 mActivity.runOnUiThread(new Runnable() {
521 showInviteMsg(mInviterUserId);
525 } catch (OcException e) {
531 public synchronized void onGetFailed(Throwable throwable) {
532 msg("Failed to searchUser");
533 if (throwable instanceof OcException) {
534 OcException ocEx = (OcException) throwable;
535 Log.e(TAG, ocEx.toString());
536 ErrorCode errCode = ocEx.getErrorCode();
537 msg("Error code: " + errCode);
542 OcAccountManager.OnDeleteListener onDeleteGroup = new OcAccountManager.OnDeleteListener() {
544 public void onDeleteCompleted(List<OcHeaderOption> list) {
545 msg("deleteGroup was successful");
549 public void onDeleteFailed(Throwable throwable) {
550 msg("Failed to deleteGroup");
554 OcAccountManager.OnDeleteListener onReplyToInvitation = new OcAccountManager.OnDeleteListener() {
556 public void onDeleteCompleted(List<OcHeaderOption> list) {
557 msg("replyToInvitation was successful");
559 mAccountManager.getGroupInfoAll(onGetGroupInfoAll);
560 } catch (OcException e) {
566 public void onDeleteFailed(Throwable throwable) {
567 msg("Failed to deleteInvitation");
571 OcAccountManager.OnGetListener onSearchUserForInviter = new OcAccountManager.OnGetListener() {
573 public synchronized void onGetCompleted(List<OcHeaderOption> list,
574 OcRepresentation ocRepresentation) {
575 msg("searchUser was successful");
577 OcRepresentation[] userList = ocRepresentation.getValue("ulist");
578 for (OcRepresentation user : userList) {
579 mInviteeUuid = user.getValue("uid");
580 OcRepresentation userInfo = user.getValue("uinfo");
581 String inviteeUserId = userInfo.getValue("userid");
582 Log.d(TAG, "inviteeUserId : " + inviteeUserId);
584 msg("sendInvitation");
585 mAccountManager.sendInvitation(mGroupId, mInviteeUuid, onSendInvitation);
586 } catch (OcException e) {
592 public synchronized void onGetFailed(Throwable throwable) {
593 msg("Failed to searchUser");
594 if (throwable instanceof OcException) {
595 OcException ocEx = (OcException) throwable;
596 Log.e(TAG, ocEx.toString());
597 ErrorCode errCode = ocEx.getErrorCode();
598 msg("Error code: " + errCode);
603 OcAccountManager.OnPostListener onCreateGroup = new OcAccountManager.OnPostListener() {
605 public synchronized void onPostCompleted(List<OcHeaderOption> list,
606 OcRepresentation ocRepresentation) {
607 msg("createGroup was successful");
609 mGroupId = ocRepresentation.getValue("gid");
610 msg("\tgroupId: " + mGroupId);
613 mAccountManager.getGroupInfo(mGroupId, onGetGroupInfo);
614 } catch (OcException e) {
615 Log.e(TAG, e.toString());
620 public synchronized void onPostFailed(Throwable throwable) {
621 msg("Failed to createGroup");
622 if (throwable instanceof OcException) {
623 OcException ocEx = (OcException) throwable;
624 Log.e(TAG, ocEx.toString());
625 ErrorCode errCode = ocEx.getErrorCode();
626 msg("Error code: " + errCode);
631 OcAccountManager.OnObserveListener onObserveGroup = new OcAccountManager.OnObserveListener() {
633 public void onObserveCompleted(List<OcHeaderOption> list,
634 OcRepresentation ocRepresentation, int i) {
635 msg("observeGroup was successful");
638 msg("REGISTER was successful");
639 } else if (DEREGISTER == i) {
640 msg("DEREGISTER was successful");
642 String gid = ocRepresentation.getValue("gid");
643 msg("\tGroupID: " + gid);
645 String gmid = ocRepresentation.getValue("gmid");
646 msg("\tGroupMasterID: " + gmid);
648 String[] midlist = ocRepresentation.getValue("midlist");
649 if (midlist == null || midlist.length == 0) {
650 msg("\tMember List is empty");
652 msg("\tMember List(" + midlist.length + ")");
653 for (String mid : midlist) {
658 String[] dilist = ocRepresentation.getValue("dilist");
659 if (dilist == null || dilist.length == 0) {
660 msg("\tDevice List is empty");
662 msg("\tDevice List(" + dilist.length + ")");
663 for (String di : dilist) {
668 } catch (OcException e) {
674 public void onObserveFailed(Throwable throwable) {
675 msg("Failed to observeGroup");
676 if (throwable instanceof OcException) {
677 OcException ocEx = (OcException) throwable;
678 Log.e(TAG, ocEx.toString());
679 ErrorCode errCode = ocEx.getErrorCode();
680 msg("Error code: " + errCode);
685 OcAccountManager.OnPostListener onPostPropertyValue = new OcAccountManager.OnPostListener() {
687 public synchronized void onPostCompleted(List<OcHeaderOption> list,
688 OcRepresentation ocRepresentation) {
689 msg("Post was successful (changed property value)");
693 public synchronized void onPostFailed(Throwable throwable) {
694 msg("Failed to Post (changed property value)");
695 if (throwable instanceof OcException) {
696 OcException ocEx = (OcException) throwable;
697 Log.e(TAG, ocEx.toString());
698 ErrorCode errCode = ocEx.getErrorCode();
699 msg("Error code: " + errCode);
704 OcAccountManager.OnPostListener onSendInvitation = new OcAccountManager.OnPostListener() {
706 public synchronized void onPostCompleted(List<OcHeaderOption> list,
707 OcRepresentation ocRepresentation) {
708 msg("sendInvitation was successful");
712 public synchronized void onPostFailed(Throwable throwable) {
713 msg("Failed to sendInvitation");
714 if (throwable instanceof OcException) {
715 OcException ocEx = (OcException) throwable;
716 Log.e(TAG, ocEx.toString());
717 ErrorCode errCode = ocEx.getErrorCode();
718 msg("Error code: " + errCode);
723 // ******************************************************************************
724 // End of the Account Manager specific code
725 // ******************************************************************************
727 OcRDClient.OnPublishResourceListener resourcePublishListener =
728 new OcRDClient.OnPublishResourceListener() {
730 public void onPublishResourceCompleted(OcRepresentation ocRepresentation) {
731 msg("onPublishResourceCompleted");
733 for (OcRepresentation child : ocRepresentation.getChildren()) {
735 msg("\tPublished Resource URI : " + child.getValue("href"));
736 } catch (OcException e) {
743 public void onPublishResourceFailed(Throwable throwable) {
744 msg("onPublishResourceFailed has failed");
748 OcRDClient.OnDeleteResourceListener resourceDeleteListener =
749 new OcRDClient.OnDeleteResourceListener() {
751 public void onDeleteResourceCompleted(int resultCode) {
752 msg("onDeleteResourceCompleted, result is " + resultCode);
756 private void createResource() {
757 if (localLightResourceHandle == null) {
759 localLightResourceHandle = OcPlatform.registerResource(
760 Common.RESOURCE_URI, //resource URI
761 Common.RESOURCE_TYPE, //resource type name
762 Common.RESOURCE_INTERFACE, //using default interface
763 null, //use default entity handler
764 EnumSet.of(ResourceProperty.DISCOVERABLE)
766 mResourceHandleList.add(localLightResourceHandle);
767 msg("Create Local Resource is success.");
768 } catch (OcException e) {
769 Log.e(TAG, e.toString());
774 private void publishResourceToRD() {
775 // Create Local Resource.
779 // Publish Virtual Resource to Resource-Directory.
780 Log.d(TAG, "Publish Virtual Resource to Resource-Directory.");
781 OcRDClient.publishResourceToRD(
782 Common.HOST, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP),
783 resourcePublishListener
786 // Publish Local Resource to Resource-Directory.
787 Log.d(TAG, "Publish Local Resource to Resource-Directory.");
788 OcRDClient.publishResourceToRD(
789 Common.HOST, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP), mResourceHandleList,
790 resourcePublishListener
792 } catch (OcException e) {
793 Log.e(TAG, e.toString());
797 private void deleteResourceFromRD() {
799 // Delete Resource from Resource-Directory.
800 Log.d(TAG, "Delete Resource from Resource-Directory.");
801 OcRDClient.deleteResourceFromRD(
802 Common.HOST, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP),
803 resourceDeleteListener
805 } catch (OcException e) {
806 Log.e(TAG, e.toString());
810 private void subscribeDevicePresence() {
812 if (null == mOcPresenceHandle) {
813 List<String> di = new ArrayList<>();
814 mOcPresenceHandle = OcPlatform.subscribeDevicePresence(
815 Common.HOST, di, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP), this);
816 mDevicePresenceButton.setText(R.string.unsub_presence);
818 OcPlatform.unsubscribePresence(mOcPresenceHandle);
819 mOcPresenceHandle = null;
820 mDevicePresenceButton.setText(R.string.sub_presence);
822 } catch (OcException e) {
828 public void onObserveCompleted(List<OcHeaderOption> list,
829 OcRepresentation ocRepresentation, int sequenceNumber) {
830 if (sequenceNumber != maxSequenceNumber + 1) {
831 msg("OBSERVE Result:");
832 msg("\tSequenceNumber:" + sequenceNumber);
834 if (ocRepresentation.hasAttribute("prslist")) {
835 OcRepresentation[] prslist = ocRepresentation.getValue("prslist");
836 if (prslist != null) {
837 msg("\tDevice Presence");
838 for (OcRepresentation prs : prslist) {
839 msg("\t\tDevice ID : " + prs.getValue("di"));
840 msg("\t\tState : " + prs.getValue("state"));
844 } catch (OcException e) {
848 msg("Successful unsubscribePresence");
853 public void onObserveFailed(Throwable throwable) {
857 // ******************************************************************************
858 // End of the Resource Directory specific code
859 // ******************************************************************************
862 List<String> resourceTypeList = new ArrayList<>();
863 List<String> resourceInterfaceList = new ArrayList<>();
864 resourceInterfaceList.add(Common.RESOURCE_INTERFACE);
865 resourceTypeList.add("ocf.wk.ps");
867 MQbrokerResource = OcPlatform.constructResourceObject(
869 Common.MQ_BROKER_URI,
870 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
872 resourceTypeList, resourceInterfaceList);
874 msg("found MQ broker : " + MQbrokerResource.getHost());
878 } catch (OcException e) {
883 void discoveryMQTopics() {
885 if (null != MQbrokerResource) {
886 MQbrokerResource.discoveryMQTopics(
887 new HashMap<String, String>(),
888 this, QualityOfService.LOW);
891 } catch (OcException e) {
897 synchronized public void onTopicDiscoveried(OcResource ocResource) {
898 synchronized (this) {
899 String resourceUri = ocResource.getUri();
901 msg("onTopicDiscoveried : " + resourceUri + " found");
906 public void onDiscoveryTopicFailed(Throwable ex, String uri) {
907 Log.e(TAG, "onFindTopicFailed : ", ex);
909 if (ex instanceof OcException) {
910 OcException ocEx = (OcException) ex;
911 ErrorCode errCode = ocEx.getErrorCode();
912 Log.d(TAG, "onFindTopicFailed Code: " + errCode);
913 Log.d(TAG, "onFindTopicFailed Code: " + errCode.ordinal());
914 Log.d(TAG, "onFindTopicFailed uri: " + uri);
917 Log.e(TAG, ex.getMessage());
921 void createMQTopic() {
923 if (null != MQbrokerResource) {
924 Map<String, String> queryParameters = new HashMap<>();
925 queryParameters.put("rt", "light");
926 MQbrokerResource.createMQTopic(
927 new OcRepresentation(),
928 defaultTopicFullName,
931 QualityOfService.LOW);
933 } catch (OcException e) {
939 synchronized public void onTopicResourceCreated(OcResource ocResource) {
940 synchronized (this) {
941 Log.d(TAG, "onTopicResourceCreated");
942 currentTopicResource = ocResource;
944 msg("onTopicResourceCreated : " + currentTopicResource.getUri());
949 public void onCreateTopicFailed(Throwable ex, String uri) {
950 Log.e(TAG, "onCreateTopicFailed : ", ex);
952 if (ex instanceof OcException) {
953 OcException ocEx = (OcException) ex;
954 ErrorCode errCode = ocEx.getErrorCode();
955 Log.d(TAG, "onCreateTopicFailed error Code: " + errCode);
956 Log.d(TAG, "onCreateTopicFailed error Code: " + errCode.ordinal());
957 Log.d(TAG, "onCreateTopicFailed error uri: " + uri);
959 // retry to create after increase room number
960 defaultTopicFullName = Common.MQ_DEFAULT_TOPIC_URI + (roomNum++);
963 Log.e(TAG, ex.getMessage());
967 void subscribeMQTopic() {
968 Map<String, String> queryParameters = new HashMap<>();
969 queryParameters.put("rt", "light");
972 if (null != currentTopicResource) {
973 currentTopicResource.subscribeMQTopic(
976 QualityOfService.LOW);
979 } catch (OcException e) {
985 synchronized public void onSubScribeCompleted(List<OcHeaderOption> headerOptionList,
986 OcRepresentation ocRepresentation,
987 int sequenceNumber) {
988 synchronized (this) {
989 String resourceUri = ocRepresentation.getUri();
990 Log.d(TAG, "onSubScribeCompleted sequenceNumber : " + sequenceNumber);
994 OcRepresentation val = ocRepresentation.getValue("message");
996 if (sequenceNumber == 0) {
997 Log.d(TAG, "onSubScribeCompleted : " + resourceUri);
1004 msg("onSubScribeCompleted : " + resourceUri);
1006 Log.d(TAG, "onSubScribeCompleted : " + resourceUri);
1007 Log.d(TAG, "onSubScribeCompleted : " + val.getValue("blue"));
1008 Log.d(TAG, "onSubScribeCompleted : " + val.getValue("red"));
1010 msg("onSubScribeCompleted : " + resourceUri + ", blue light is "
1011 + val.getValue("blue").toString());
1012 msg("onSubScribeCompleted : " + resourceUri + ", red light is "
1013 + val.getValue("red").toString());
1015 } catch (OcException e) {
1016 e.printStackTrace();
1022 synchronized public void onUnsubScribeCompleted(OcRepresentation ocRepresentation,
1023 int sequenceNumber) {
1024 synchronized (this) {
1025 String resourceUri = ocRepresentation.getUri();
1026 Log.d(TAG, "onUnsubScribeCompleted sequenceNumber : " + sequenceNumber);
1028 if (sequenceNumber == maxSequenceNumber + 1) {
1029 Log.d(TAG, "onUnsubScribeCompleted : " + resourceUri);
1030 msg("onUnsubScribeCompleted : " + resourceUri);
1036 public void onSubScribeFailed(Throwable ex) {
1037 Log.d(TAG, "onSubScribeFailed : ", ex);
1039 if (ex instanceof OcException) {
1040 OcException ocEx = (OcException) ex;
1041 ErrorCode errCode = ocEx.getErrorCode();
1042 Log.d(TAG, "onSubScribeFailed error Code: " + errCode);
1043 Log.d(TAG, "onSubScribeFailed error Code: " + errCode.ordinal());
1047 Log.e(TAG, ex.getMessage());
1052 void unsubscribeMQTopic() {
1055 if (null != currentTopicResource) {
1056 currentTopicResource.unsubscribeMQTopic(QualityOfService.LOW);
1059 } catch (OcException e) {
1060 e.printStackTrace();
1064 void publishMQTopic() {
1067 OcRepresentation rep = new OcRepresentation();
1068 OcRepresentation msg = new OcRepresentation();
1070 if (switchingFlag) {
1071 msg.setValue("blue", "on");
1072 msg.setValue("red", "off");
1073 switchingFlag = false;
1075 msg.setValue("blue", "off");
1076 msg.setValue("red", "on");
1077 switchingFlag = true;
1079 rep.setValue("message", msg);
1081 if (null != currentTopicResource) {
1082 currentTopicResource.publishMQTopic(rep,
1083 new HashMap<String, String>(),
1085 QualityOfService.LOW);
1088 } catch (OcException e) {
1089 e.printStackTrace();
1093 OcResource.OnPostListener mqPublishListener =
1094 new OcResource.OnPostListener() {
1096 public void onPostCompleted(List<OcHeaderOption> list,
1097 OcRepresentation ocRepresentation) {
1098 Log.i(TAG, "onPublish completed");
1099 msg("onPublish completed");
1103 public void onPostFailed(Throwable throwable) {
1104 Log.e(TAG, "onPublish failed");
1105 msg("onPublish failed");
1109 void requestMQPublish() {
1112 if (null != currentTopicResource) {
1113 currentTopicResource.requestMQPublish(
1114 new HashMap<String, String>(),
1116 QualityOfService.LOW);
1118 } catch (OcException e) {
1119 e.printStackTrace();
1123 OcResource.OnPostListener mqReqPubListener =
1124 new OcResource.OnPostListener() {
1126 public void onPostCompleted(List<OcHeaderOption> list,
1127 OcRepresentation ocRepresentation) {
1128 Log.i(TAG, "onRequestPublish completed");
1129 msg("onPublish completed");
1133 public void onPostFailed(Throwable throwable) {
1134 Log.e(TAG, "onRequestPublish failed");
1135 msg("onRequestPublish failed");
1139 // ******************************************************************************
1140 // End of the Message Queue specific code
1141 // ******************************************************************************
1143 private void showTCPInput() {
1145 LayoutInflater layoutInflater = LayoutInflater.from(mContext);
1146 View inputView = layoutInflater.inflate(R.layout.input, null);
1147 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
1148 alertDialogBuilder.setView(inputView);
1150 final EditText editText = (EditText) inputView.getRootView().findViewById(R.id.inputText);
1151 final CheckBox isSecured = (CheckBox) inputView.getRootView().findViewById(R.id.secured);
1153 StringBuilder sb = new StringBuilder();
1154 sb.append(Common.TCP_ADDRESS);
1155 sb.append(Common.PORT_SEPARATOR);
1156 sb.append(Common.TCP_PORT);
1157 editText.setText(sb.toString());
1159 isSecured.setVisibility(View.VISIBLE);
1160 isSecured.setChecked(mSecured);
1163 .setCancelable(true)
1164 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
1165 public void onClick(DialogInterface dialog, int id) {
1166 if (editText.getText().length() != 0) {
1167 final String hosts = editText.getText().toString();
1168 boolean isValid = ADDRESS_PORT.matcher(hosts).matches();
1170 final String host[] = hosts.split(Common.PORT_SEPARATOR);
1171 Common.TCP_ADDRESS = host[0];
1172 Common.TCP_PORT = host[1];
1173 mSecured = isSecured.isChecked();
1175 StringBuilder sb = new StringBuilder();
1177 sb.append(Common.COAPS_TCP);
1179 sb.append(Common.COAP_TCP);
1181 sb.append(Common.TCP_ADDRESS);
1182 sb.append(Common.PORT_SEPARATOR);
1183 sb.append(Common.TCP_PORT);
1184 Common.HOST = sb.toString();
1186 Toast.makeText(mContext, "Invalid IP", Toast.LENGTH_SHORT).show();
1192 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
1193 public void onClick(DialogInterface dialog, int id) {
1198 AlertDialog alert = alertDialogBuilder.create();
1202 private void showInviteUser() {
1204 LayoutInflater layoutInflater = LayoutInflater.from(mContext);
1205 View inputView = layoutInflater.inflate(R.layout.input, null);
1206 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
1207 alertDialogBuilder.setView(inputView);
1209 final TextView textView = (TextView) inputView.getRootView().findViewById(R.id.inputView);
1210 textView.setText("Please enter user ID to invite.");
1211 final EditText editText = (EditText) inputView.getRootView().findViewById(R.id.inputText);
1214 .setCancelable(true)
1215 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
1216 public void onClick(DialogInterface dialog, int id) {
1217 if (editText.getText().length() != 0) {
1218 final String userID = editText.getText().toString();
1221 Map<String, String> option = new HashMap<>();
1222 option.put("userid", userID);
1224 msg("searchUser (User ID: " + userID + ")");
1225 mAccountManager.searchUser(option, onSearchUserForInviter);
1226 } catch (OcException e) {
1227 e.printStackTrace();
1232 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
1233 public void onClick(DialogInterface dialog, int id) {
1238 AlertDialog alert = alertDialogBuilder.create();
1243 private void showPostPropertyValueToGroup(int operation) {
1244 LayoutInflater layoutInflater = LayoutInflater.from(mContext);
1245 View inputView = layoutInflater.inflate(R.layout.input, null);
1246 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
1247 alertDialogBuilder.setView(inputView);
1249 final int op = operation;
1251 final TextView textView = (TextView) inputView.getRootView().findViewById(R.id.inputView);
1252 final EditText editText = (EditText) inputView.getRootView().findViewById(R.id.inputText);
1253 final TextView textView2 = (TextView) inputView.getRootView().findViewById(R.id.inputView2);
1254 final EditText editText2 = (EditText) inputView.getRootView().findViewById(R.id.inputText2);
1256 textView.setText("Please enter property.");
1257 textView2.setText("Please enter value(String Array).");
1258 textView2.setVisibility(View.VISIBLE);
1259 editText2.setVisibility(View.VISIBLE);
1263 .setCancelable(true)
1264 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
1265 public void onClick(DialogInterface dialog, int id) {
1266 if (editText.getText().length() != 0 && editText2.getText().length() != 0){
1267 final String property = editText.getText().toString();
1268 final String value = editText2.getText().toString();
1269 String[] values = {value};
1272 OcRepresentation propertyValue = new OcRepresentation();
1273 propertyValue.setValue(property, values);
1276 msg("addPropertyValueToGroup");
1277 mAccountManager.addPropertyValueToGroup(mGroupId, propertyValue, onPostPropertyValue);
1278 } else if (op == 1){
1279 msg("deletePropertyValueFromGroup");
1280 mAccountManager.deletePropertyValueFromGroup(mGroupId, propertyValue, onPostPropertyValue);
1281 } else if (op == 2){
1282 msg("updatePropertyValueOnGroup");
1283 mAccountManager.updatePropertyValueOnGroup(mGroupId, propertyValue, onPostPropertyValue);
1285 } catch (OcException e) {
1286 e.printStackTrace();
1291 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
1292 public void onClick(DialogInterface dialog, int id) {
1297 AlertDialog alert = alertDialogBuilder.create();
1301 private void showInviteMsg(String userID) {
1303 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
1304 alertDialogBuilder.setTitle("Invitation");
1305 StringBuilder sb = new StringBuilder();
1306 sb.append("Invited from ");
1309 sb.append("Accept?");
1310 alertDialogBuilder.setMessage(sb.toString());
1312 .setCancelable(true)
1313 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
1314 public void onClick(DialogInterface dialog, int id) {
1316 msg("replyToInvitation (accept:yes)");
1317 mAccountManager.replyToInvitation(mGroupId, true, onReplyToInvitation);
1318 } catch (OcException e) {
1319 e.printStackTrace();
1323 .setNegativeButton("No", new DialogInterface.OnClickListener() {
1324 public void onClick(DialogInterface dialog, int id) {
1327 msg("replyToInvitation (accept:no)");
1328 mAccountManager.replyToInvitation(mGroupId, false, onReplyToInvitation);
1329 } catch (OcException e) {
1330 e.printStackTrace();
1335 AlertDialog alert = alertDialogBuilder.create();
1339 private void msg(final String text) {
1340 mActivity.runOnUiThread(new Runnable() {
1342 mResultLog.append(EOL);
1343 mResultLog.append(text);
1344 mScrollView.fullScroll(View.FOCUS_DOWN);
1351 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
1355 visible = View.VISIBLE;
1357 visible = View.GONE;
1360 switch (buttonView.getId()) {
1361 case R.id.account_switch:
1362 mAccountLayout.setVisibility(visible);
1364 case R.id.rd_switch:
1365 mRDLayout.setVisibility(visible);
1367 case R.id.mq_switch:
1368 mMQLayout.setVisibility(visible);
1374 public void onClick(View view) {
1375 mActionLog.setText("[Action Log]" + EOL);
1377 int viewID = view.getId();
1378 if (mAccountManager == null && (viewID == R.id.signin_button
1379 || viewID == R.id.signout_button || viewID == R.id.creategroup_button
1380 || viewID == R.id.invite_button || viewID == R.id.addpropertyvalue_button
1381 || viewID == R.id.deletepropertyvalue_button || viewID == R.id.updatepropertyvalue_button)) {
1382 mActionLog.append("Do 'SignUp' first" + EOL);
1388 case R.id.setip_button:
1389 mActionLog.append("Set IP" + EOL);
1392 case R.id.signup_button:
1393 mActionLog.append("Sign Up" + EOL);
1396 case R.id.signin_button:
1397 mActionLog.append("Sign In" + EOL);
1400 case R.id.signout_button:
1401 mActionLog.append("Sign Out" + EOL);
1404 case R.id.creategroup_button:
1405 mActionLog.append("Create Group" + EOL);
1408 case R.id.deletegroup_button:
1409 mActionLog.append("Delete Group" + EOL);
1412 case R.id.invite_button:
1413 mActionLog.append("Invite User" + EOL);
1416 case R.id.addpropertyvalue_button:
1417 mActionLog.append("Add Property Value To Group" + EOL);
1418 addPropertyValueToGroup();
1420 case R.id.deletepropertyvalue_button:
1421 mActionLog.append("Delete Property Value From Group" + EOL);
1422 deletePropertyValueFromGroup();
1424 case R.id.updatepropertyvalue_button:
1425 mActionLog.append("Update Property Value On Group" + EOL);
1426 updatePropertyValueOnGroup();
1430 case R.id.rdpub_button:
1431 mActionLog.append("Publish Resource To RD" + EOL);
1432 publishResourceToRD();
1434 case R.id.rddel_button:
1435 mActionLog.append("Delete Resource From RD" + EOL);
1436 deleteResourceFromRD();
1438 case R.id.rddp_button:
1439 mActionLog.append("Subscribe Device Presence" + EOL);
1440 subscribeDevicePresence();
1444 case R.id.mqget_button:
1445 mActionLog.append("Get MQ Broker" + EOL);
1448 case R.id.mqcreate_button:
1449 mActionLog.append("Create MQ Topic" + EOL);
1452 case R.id.mqsub_button:
1453 mActionLog.append("Subscribe MQ Topic" + EOL);
1456 case R.id.mqunsub_button:
1457 mActionLog.append("Un-subscribe MQ Topic" + EOL);
1458 unsubscribeMQTopic();
1460 case R.id.mqpub_button:
1461 mActionLog.append("Publish MQ Topic" + EOL);
1464 case R.id.mqreq_button:
1465 mActionLog.append("Request MQ Publish" + EOL);
1472 public View onCreateView(LayoutInflater inflater, ViewGroup container,
1473 Bundle savedInstanceState) {
1474 View rootView = inflater.inflate(R.layout.fragment_cloud, container, false);
1476 mAccountLayout = (LinearLayout) rootView.findViewById(R.id.account_layout);
1477 mRDLayout = (LinearLayout) rootView.findViewById(R.id.rd_layout);
1478 mMQLayout = (LinearLayout) rootView.findViewById(R.id.mq_layout);
1480 Switch accountSwitch = (Switch) rootView.findViewById(R.id.account_switch);
1481 Switch RDSwitch = (Switch) rootView.findViewById(R.id.rd_switch);
1482 Switch MQSwitch = (Switch) rootView.findViewById(R.id.mq_switch);
1483 accountSwitch.setOnCheckedChangeListener(this);
1484 RDSwitch.setOnCheckedChangeListener(this);
1485 MQSwitch.setOnCheckedChangeListener(this);
1487 mAccountText = (TextView) rootView.findViewById(R.id.account_view);
1488 mRDText = (TextView) rootView.findViewById(R.id.rd_view);
1489 mMQText = (TextView) rootView.findViewById(R.id.mq_view);
1490 mScrollView = (ScrollView) rootView.findViewById(R.id.scroll_view);
1491 mActionLog = (TextView) rootView.findViewById(R.id.action_log_view);
1492 mResultLog = (TextView) rootView.findViewById(R.id.result_log_view);
1494 Button setIPButton = (Button) rootView.findViewById(R.id.setip_button);
1495 Button signUpButton = (Button) rootView.findViewById(R.id.signup_button);
1496 Button signInButton = (Button) rootView.findViewById(R.id.signin_button);
1497 Button signOutButton = (Button) rootView.findViewById(R.id.signout_button);
1498 Button createGroupButton = (Button) rootView.findViewById(R.id.creategroup_button);
1499 Button inviteButton = (Button) rootView.findViewById(R.id.invite_button);
1500 Button addValueToGroup = (Button) rootView.findViewById(R.id.addpropertyvalue_button);
1501 Button deleteValueFromGroup = (Button) rootView.findViewById(R.id.deletepropertyvalue_button);
1502 Button updateValueOnGroup = (Button) rootView.findViewById(R.id.updatepropertyvalue_button);
1503 setIPButton.setOnClickListener(this);
1504 signUpButton.setOnClickListener(this);
1505 signInButton.setOnClickListener(this);
1506 signOutButton.setOnClickListener(this);
1507 createGroupButton.setOnClickListener(this);
1508 inviteButton.setOnClickListener(this);
1509 addValueToGroup.setOnClickListener(this);
1510 deleteValueFromGroup.setOnClickListener(this);
1511 updateValueOnGroup.setOnClickListener(this);
1513 Button rdPubButton = (Button) rootView.findViewById(R.id.rdpub_button);
1514 Button rdDelButton = (Button) rootView.findViewById(R.id.rddel_button);
1515 mDevicePresenceButton = (Button) rootView.findViewById(R.id.rddp_button);
1516 rdPubButton.setOnClickListener(this);
1517 rdDelButton.setOnClickListener(this);
1518 mDevicePresenceButton.setOnClickListener(this);
1520 Button mqBrokerButton = (Button) rootView.findViewById(R.id.mqget_button);
1521 Button createTopicButton = (Button) rootView.findViewById(R.id.mqcreate_button);
1522 Button subTopicButton = (Button) rootView.findViewById(R.id.mqsub_button);
1523 Button unsubTopicButton = (Button) rootView.findViewById(R.id.mqunsub_button);
1524 Button pubToicButton = (Button) rootView.findViewById(R.id.mqpub_button);
1525 mqBrokerButton.setOnClickListener(this);
1526 createTopicButton.setOnClickListener(this);
1527 subTopicButton.setOnClickListener(this);
1528 unsubTopicButton.setOnClickListener(this);
1529 pubToicButton.setOnClickListener(this);
1535 public void onResume() {
1540 public void onDestroy() {