c2b9cf095860bdf50742b873e9fe370cc18f953d
[platform/upstream/iotivity.git] / service / things-manager / sampleapp / android / Sample / src / com / tm / sample / GroupClient.java
1 /******************************************************************
2  *
3  * Copyright 2015 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20 package com.tm.sample;
21
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Vector;
26
27 import org.iotivity.base.ObserveType;
28 import org.iotivity.base.OcException;
29 import org.iotivity.base.OcHeaderOption;
30 import org.iotivity.base.OcPlatform;
31 import org.iotivity.base.OcRepresentation;
32 import org.iotivity.base.OcResource;
33 import org.iotivity.base.OcResource.OnObserveListener;
34 import org.iotivity.base.OcResourceHandle;
35 import org.iotivity.service.tm.Action;
36 import org.iotivity.service.tm.ActionSet;
37 import org.iotivity.service.tm.Capability;
38 import org.iotivity.service.tm.GroupSynchronization;
39 import org.iotivity.service.tm.GroupSynchronization.*;
40 import org.iotivity.service.tm.OCStackResult;
41 import org.iotivity.service.tm.GroupManager;
42 import org.iotivity.service.tm.GroupManager.*;
43 import org.iotivity.service.tm.Time.ActionSetType;
44
45 import android.os.Message;
46 import android.util.Log;
47
48 /**
49  * For calling the group APIs as per user selection on UI and for updating the
50  * UI
51  */
52 public class GroupClient {
53
54     private static final String        LOG_TAG             = "[TMSample] GroupClient";
55     private static Message             msg;
56     public String                      logMessage;
57
58     private final String               groupResourceType   = "b.collection";
59
60     private final GroupManager         groupManagerObj;
61     private final GroupSynchronization groupSynObj;
62     private final ActionListener       actionListener;
63     private final ObserveListener      observeListener;
64     private OcResource                 groupResource;
65     private OcResourceHandle           groupResourceHandle;
66     private OcResourceHandle           foundLightHandle;
67     private static GroupApiActivity    groupApiActivityObj = null;
68     public static Vector<String>       lights              = new Vector<String>();
69     public static Vector<String>       bookmarks           = new Vector<String>();
70
71     /**
72      * Listener for receiving observe notifications.
73      */
74     private class ObserveListener implements OnObserveListener {
75         @Override
76         public void onObserveCompleted(List<OcHeaderOption> headerOptionList,
77                 OcRepresentation ocRepresentation, int sequenceNumber) {
78             Log.i(LOG_TAG, "onObserveCompleted invoked");
79             if (0 == ocRepresentation.getValueInt("level")) {
80                 createActionSetBulbOn();
81                 executeActionSetBulbOn(0);
82             } else if (5 == ocRepresentation.getValueInt("level")) {
83                 createActionSetBulbOff();
84                 executeActionSetBulbOff(0);
85             }
86         }
87
88         @Override
89         public void onObserveFailed(Throwable arg0) {
90         }
91     }
92
93     /**
94      * Listener for receiving groups discovered in network.
95      */
96     private class FindGroupListener implements IFindGroupListener {
97         @Override
98         public void onGroupFindCallback(OcResource resource) {
99             Log.i(LOG_TAG, "onGroupFindCallback invoked");
100             if (resource != null) {
101                 String uri = resource.getUri();
102                 if (uri.equals("/b/collection") == true) {
103                     String hostAddress = resource.getHost();
104                     Log.d(LOG_TAG, "onGroupFindCallback URI : " + uri);
105                     Log.d(LOG_TAG, "onGroupFindCallback HOST : " + hostAddress);
106
107                     groupResource = resource;
108                     Message msg = Message.obtain();
109                     msg.what = 0;
110                     groupApiActivityObj.getHandler().sendMessage(msg);
111
112                     logMessage = "onGroupFind" + "\n";
113                     logMessage += "URI : " + uri + "\n";
114                     logMessage += "Host :" + hostAddress;
115                     GroupApiActivity.setMessageLog(logMessage);
116                     msg = Message.obtain();
117                     msg.what = 1;
118                     groupApiActivityObj.getHandler().sendMessage(msg);
119                 } else {
120                     Log.d(LOG_TAG, "onGroupFindCallback URI : " + uri);
121                 }
122             } else {
123                 Log.i(LOG_TAG, "Resource is NULL");
124             }
125         }
126     };
127
128     /**
129      * Listener for receiving Light resource and Observe resources discovered in
130      * network.
131      */
132     private class FindCadidateResourceListener implements
133             IFindCandidateResourceListener {
134
135         @Override
136         public void onResourceFoundCallback(Vector<OcResource> resources) {
137             // TODO Auto-generated method stub
138             Log.i(LOG_TAG, "onResourceCallback invoked");
139
140             if (resources != null) {
141                 for (int i = 0; i < resources.size(); i++) {
142                     Log.d(LOG_TAG, "Resource information");
143                     OcResource ocResource = resources.get(i);
144                     String resourceURI = ocResource.getUri();
145                     String hostAddress = ocResource.getHost();
146
147                     logMessage = "API RESULT : " + "OC_STACK_OK" + "\n";
148                     logMessage += "URI: " + resourceURI + "\n";
149                     logMessage += "Host:" + hostAddress;
150                     GroupApiActivity.setMessageLog(logMessage);
151                     msg = Message.obtain();
152                     msg.what = 1;
153                     groupApiActivityObj.getHandler().sendMessage(msg);
154
155                     if (resourceURI.equals("/a/light") == true) {
156                         if (lights.contains((hostAddress + resourceURI)) == false) {
157                             lights.add((hostAddress + resourceURI));
158                             if (groupApiActivityObj != null) {
159
160                                 logMessage = "API RESULT : " + "OC_STACK_OK"
161                                         + "\n";
162                                 logMessage += "URI: " + resourceURI + "\n";
163                                 logMessage += "Host:" + hostAddress;
164                                 GroupApiActivity.setMessageLog(logMessage);
165                                 msg = Message.obtain();
166                                 msg.what = 1;
167                                 groupApiActivityObj.getHandler().sendMessage(
168                                         msg);
169                                 try {
170                                     foundLightHandle = groupManagerObj
171                                             .bindResourceToGroup(ocResource,
172                                                     groupResourceHandle);
173
174                                 } catch (OcException e) {
175                                     Log.i(LOG_TAG,
176                                             "bindResourceToGroup Exception!");
177                                 }
178                             }
179                         } else {
180                             Log.i(LOG_TAG, "Resource is already registered!");
181                         }
182                     } else if (resourceURI.equalsIgnoreCase("/core/bookmark")) {
183                         if (bookmarks.contains((hostAddress + resourceURI)) == false) {
184                             bookmarks.add((hostAddress + resourceURI));
185                             if (groupApiActivityObj != null) {
186                                 logMessage = "API RESULT : " + "OC_STACK_OK"
187                                         + "\n";
188                                 logMessage += "URI: " + resourceURI + "\n";
189                                 logMessage += "Host:" + hostAddress;
190                                 GroupApiActivity.setMessageLog(logMessage);
191                                 msg = Message.obtain();
192                                 msg.what = 1;
193                                 groupApiActivityObj.getHandler().sendMessage(
194                                         msg);
195
196                             }
197                             observe(ocResource);
198                         }
199                     }
200                 }
201             }
202
203         }
204     };
205
206     private final FindCadidateResourceListener findCandidateResourceListener;
207     private final FindGroupListener            findGroupListener;
208
209     public GroupClient() {
210         groupManagerObj = new GroupManager();
211         groupSynObj = GroupSynchronization.getInstance();
212         findGroupListener = new FindGroupListener();
213         actionListener = new ActionListener();
214         observeListener = new ObserveListener();
215         findCandidateResourceListener = new FindCadidateResourceListener();
216
217         groupSynObj.setGroupListener(findGroupListener);
218         groupManagerObj
219                 .setFindCandidateResourceListener(findCandidateResourceListener);
220         groupManagerObj.setActionListener(actionListener);
221
222         groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
223     }
224
225     /**
226      * This method creates group of the type "b.collection" handling light
227      * resources.
228      */
229     public void createGroup() {
230         Map<String, OcResourceHandle> groupList = new HashMap<String, OcResourceHandle>();
231
232         // creating group of type b.collection
233         // OcPlatform.registerResource(ocResource);
234         OCStackResult result = groupSynObj.createGroup(groupResourceType);
235         if ((OCStackResult.OC_STACK_OK != result)) {
236             Log.e(LOG_TAG, "createGroup returned error: " + result.name());
237             return;
238         } else {
239             Log.e(LOG_TAG, "createGroup success: " + result.name());
240         }
241
242         // getting the Created group Handle
243         groupList = groupSynObj.getGroupList();
244         if (groupList.containsKey(groupResourceType)) {
245             groupResourceHandle = groupList.get(groupResourceType);
246         } else {
247             Log.e(LOG_TAG, "group does not contain groupResourceType: "
248                     + result.name());
249         }
250     }
251
252     /**
253      * This method finds the group of type "b.collection".
254      */
255     public void findGroup() {
256         Log.d(LOG_TAG, "finding group");
257
258         Vector<String> resourceTypes = new Vector<String>();
259         resourceTypes.add(groupResourceType);
260         OCStackResult result = groupSynObj.findGroup(resourceTypes);
261         if (OCStackResult.OC_STACK_OK != result) {
262             Log.e(LOG_TAG, "findGroup returned error: " + result.name());
263             return;
264         }
265
266         logMessage = "API RESULT : " + result.toString();
267         GroupApiActivity.setMessageLog(logMessage);
268         logMessage = "";
269         if (groupApiActivityObj != null) {
270             msg = Message.obtain();
271             msg.what = 1;
272             groupApiActivityObj.getHandler().sendMessage(msg);
273         }
274     }
275
276     /**
277      * This method finds the light resources of type "core.light".
278      */
279     public void findLightResources() {
280         Log.d(LOG_TAG, "finding light resources");
281
282         Vector<String> types = new Vector<String>();
283         types.add("core.light");
284         OCStackResult result = groupManagerObj.findCandidateResources(types, 5);
285         if (OCStackResult.OC_STACK_OK != result) {
286             Log.e(LOG_TAG,
287                     "findCandidateResources returned error: " + result.name());
288         }
289     }
290
291     /**
292      * This method finds the bookmark resources of type "core.bookmark".
293      */
294     public void findBookMarkResources() {
295         Log.d(LOG_TAG, "finding bookmark resources");
296
297         Vector<String> types = new Vector<String>();
298         types.add("core.bookmark");
299         OCStackResult result = groupManagerObj.findCandidateResources(types, 5);
300         if (OCStackResult.OC_STACK_OK != result) {
301             Log.e(LOG_TAG,
302                     "findCandidateResources returned error: " + result.name());
303         }
304     }
305
306     /**
307      * This method creates the action set for bulb on action.
308      */
309     public void createActionSetBulbOn() {
310         Log.i(LOG_TAG, "creating action set for bulb on action");
311
312         if (lights.size() == 0) {
313             groupApiActivityObj
314                     .displayToastMessage("No Light server found in network!");
315             return;
316         }
317
318         ActionSet actionSet = new ActionSet();
319         actionSet.actionsetName = "AllBulbOn";
320
321         // Create actions list
322         for (int i = 0; i < lights.size(); i++) {
323             Action action = new Action();
324             action.target = lights.get(i);
325
326             Capability capability = new Capability();
327             capability.capability = "power";
328             capability.status = "on";
329
330             action.listOfCapability.add(capability);
331             actionSet.listOfAction.add(action);
332         }
333
334         try {
335             OCStackResult result = groupManagerObj.addActionSet(groupResource,
336                     actionSet);
337             if (OCStackResult.OC_STACK_OK != result) {
338                 Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
339                 return;
340             }
341         } catch (OcException e) {
342             e.printStackTrace();
343             return;
344         }
345     }
346
347     /**
348      * This method creates the action set for bulb off action.
349      */
350     public void createActionSetBulbOff() {
351         Log.i(LOG_TAG, "creating action set for bulb off action");
352
353         if (lights.size() == 0) {
354             groupApiActivityObj
355                     .displayToastMessage("No Light server found in network!");
356             return;
357         }
358
359         ActionSet actionSet = new ActionSet();
360         actionSet.actionsetName = "AllBulbOff";
361
362         // Create actions list
363         for (int i = 0; i < lights.size(); i++) {
364             Action action = new Action();
365             action.target = lights.get(i);
366
367             Capability capability = new Capability();
368             capability.capability = "power";
369             capability.status = "off";
370
371             action.listOfCapability.add(capability);
372             actionSet.listOfAction.add(action);
373         }
374
375         try {
376             OCStackResult result = groupManagerObj.addActionSet(groupResource,
377                     actionSet);
378             if (OCStackResult.OC_STACK_OK != result) {
379                 Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
380                 return;
381             }
382         } catch (OcException e) {
383             e.printStackTrace();
384             return;
385         }
386     }
387
388     /**
389      * This method creates the recursive action set for bulb on action.
390      */
391     public void createRecursiveActionSetBulbOn() {
392         Log.i(LOG_TAG, "creating recursive action set for bulb on action");
393
394         if (lights.size() == 0) {
395             groupApiActivityObj
396                     .displayToastMessage("No Light server found in network!");
397             return;
398         }
399
400         ActionSet actionSet = new ActionSet();
401         actionSet.actionsetName = "AllBulbOnRecursive";
402         actionSet.setType(ActionSetType.RECURSIVE);
403         actionSet.mYear = 0;
404         actionSet.mMonth = 0;
405         actionSet.mDay = 0;
406         actionSet.mHour = 0;
407         actionSet.mMin = 0;
408         actionSet.mSec = 5;
409         actionSet.setDelay(actionSet.getSecAbsTime());
410
411         // Create actions list
412         for (int i = 0; i < lights.size(); i++) {
413             Action action = new Action();
414             action.target = lights.get(i);
415
416             Capability capability = new Capability();
417             capability.capability = "power";
418             capability.status = "on";
419
420             action.listOfCapability.add(capability);
421             actionSet.listOfAction.add(action);
422         }
423
424         try {
425             OCStackResult result = groupManagerObj.addActionSet(groupResource,
426                     actionSet);
427             if (OCStackResult.OC_STACK_OK != result) {
428                 Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
429                 return;
430             }
431         } catch (OcException e) {
432             e.printStackTrace();
433             return;
434         }
435     }
436
437     /**
438      * This method creates the scheduled action set for bulb off action.
439      */
440     public void createScheduledActionSetBulbOff(long delay) {
441         Log.i(LOG_TAG, "creating scheduled action set for bulb off action");
442
443         if (lights.size() == 0) {
444             groupApiActivityObj
445                     .displayToastMessage("No Light server found in network!");
446             return;
447         }
448
449         ActionSet actionSet = new ActionSet();
450         actionSet.actionsetName = "AllBulbOffScheduled";
451         actionSet.setType(ActionSetType.SCHEDULED);
452         actionSet.setDelay(delay);
453         Log.i(LOG_TAG, "Set the delay of " + delay + " seconds");
454
455         // Create actions list
456         for (int i = 0; i < lights.size(); i++) {
457             Action action = new Action();
458             action.target = lights.get(i);
459
460             Capability capability = new Capability();
461             capability.capability = "power";
462             capability.status = "off";
463
464             action.listOfCapability.add(capability);
465             actionSet.listOfAction.add(action);
466         }
467
468         try {
469             OCStackResult result = groupManagerObj.addActionSet(groupResource,
470                     actionSet);
471             if (OCStackResult.OC_STACK_OK != result) {
472                 Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
473                 return;
474             }
475         } catch (OcException e) {
476             e.printStackTrace();
477             return;
478         }
479     }
480
481     /**
482      * This method is for executing the action Set "AllBulbOn".
483      */
484     public void executeActionSetBulbOn(long delay) {
485         Log.i(LOG_TAG, "executing the action set of bulb on action");
486
487         if (lights.size() == 0) {
488             groupApiActivityObj
489                     .displayToastMessage("No Light server found in network!");
490             return;
491         }
492
493         executeActionSet("AllBulbOn", delay);
494     }
495
496     /**
497      * This method is for executing the action Set "AllBulbOff".
498      */
499     public void executeActionSetBulbOff(long delay) {
500         Log.i(LOG_TAG, "executing the action set of bulb off action");
501
502         if (lights.size() == 0) {
503             groupApiActivityObj
504                     .displayToastMessage("No Light server found in network!");
505             return;
506         }
507
508         executeActionSet("AllBulbOff", delay);
509     }
510
511     /**
512      * This method is for executing the recursive action Set
513      * "AllBulbOnRecursive".
514      */
515     public void executeRecursiveActionSetBulbOn(long delay) {
516         Log.i(LOG_TAG, "executing the recursive action set of bulb on action");
517
518         if (lights.size() == 0) {
519             groupApiActivityObj
520                     .displayToastMessage("No Light server found in network!");
521             return;
522         }
523
524         executeActionSet("AllBulbOnRecursive", delay);
525     }
526
527     /**
528      * This method is for executing the schedule action Set
529      * "AllBulbOffScheduled".
530      */
531     public void executeScheduledActionSetBulbOff(long delay) {
532         Log.i(LOG_TAG, "executing the schedule action set of bulb off action");
533
534         if (lights.size() == 0) {
535             groupApiActivityObj
536                     .displayToastMessage("No Light server found in network!");
537             return;
538         }
539
540         executeActionSet("AllBulbOffScheduled", delay);
541     }
542
543     /**
544      * This method is for canceling the action Set "AllBulbOn".
545      */
546     public void cancelActionSetBulbOn() {
547         Log.i(LOG_TAG, "cancelling the action set of bulb on action");
548
549         if (lights.size() == 0) {
550             groupApiActivityObj
551                     .displayToastMessage("No Light server found in network!");
552             return;
553         }
554
555         cancelActionSet("AllBulbOn");
556     }
557
558     /**
559      * This method is for canceling the action Set "AllBulbOff".
560      */
561     public void cancelActionSetBulbOff() {
562         Log.i(LOG_TAG, "cancelling the action set of bulb off action");
563
564         if (lights.size() == 0) {
565             groupApiActivityObj
566                     .displayToastMessage("No Light server found in network!");
567             return;
568         }
569
570         cancelActionSet("AllBulbOff");
571     }
572
573     /**
574      * This method is for canceling the recursive action Set
575      * "AllBulbOnRecursive".
576      */
577     public void cancelRecursiveActionSetBulbOn() {
578         Log.i(LOG_TAG, "cancelling the recursive action set of bulb on action");
579
580         if (lights.size() == 0) {
581             groupApiActivityObj
582                     .displayToastMessage("No Light server found in network!");
583             return;
584         }
585
586         cancelActionSet("AllBulbOnRecursive");
587     }
588
589     /**
590      * This method is for canceling the scheduled action Set
591      * "AllBulbOffScheduled".
592      */
593     public void cancelScheduledActionSetBulbOff() {
594         Log.i(LOG_TAG, "cancelling the scheduled action set of bulb off action");
595
596         if (lights.size() == 0) {
597             groupApiActivityObj
598                     .displayToastMessage("No Light server found in network!");
599             return;
600         }
601
602         cancelActionSet("AllBulbOffScheduled");
603     }
604
605     /**
606      * This method is for getting the action Set "AllBulbOn".
607      */
608     public void getActionSetBulbOn() {
609         Log.i(LOG_TAG, "getting the action set of bulb on action");
610
611         try {
612             OCStackResult result = groupManagerObj.getActionSet(groupResource,
613                     "AllBulbOn");
614             if (OCStackResult.OC_STACK_OK != result) {
615                 Log.e(LOG_TAG,
616                         "getActionSetOn returned error: " + result.name());
617                 return;
618             }
619         } catch (OcException e) {
620             e.printStackTrace();
621         }
622     }
623
624     /**
625      * This method is for getting the action Set "AllBulbOff".
626      */
627     public void getActionSetBulbOff() {
628         Log.i(LOG_TAG, "getting the action set of bulb off action");
629
630         try {
631             OCStackResult result = groupManagerObj.getActionSet(groupResource,
632                     "AllBulbOff");
633             if (OCStackResult.OC_STACK_OK != result) {
634                 Log.e(LOG_TAG,
635                         "getActionSetOn returned error: " + result.name());
636                 return;
637             }
638         } catch (OcException e) {
639             e.printStackTrace();
640         }
641     }
642
643     /**
644      * This method is for deleting the action Set "AllBulbOn".
645      */
646     public void deleteActionSetBulbOn() {
647         Log.i(LOG_TAG, "deleting the action set of bulb on action");
648
649         try {
650             OCStackResult result = groupManagerObj.deleteActionSet(
651                     groupResource, "AllBulbOn");
652             if (OCStackResult.OC_STACK_OK != result) {
653                 Log.e(LOG_TAG,
654                         "deleteActionSet returned error : " + result.name());
655                 return;
656             }
657         } catch (OcException e) {
658             e.printStackTrace();
659         }
660     }
661
662     /**
663      * This method is for deleting the action Set "AllBulbOff".
664      */
665     public void deleteActionSetBulbOff() {
666         Log.i(LOG_TAG, "deleting the action set of bulb off action");
667
668         try {
669             OCStackResult result = groupManagerObj.deleteActionSet(
670                     groupResource, "AllBulbOff");
671             if (OCStackResult.OC_STACK_OK != result) {
672                 Log.e(LOG_TAG,
673                         "deleteActionSet returned error : " + result.name());
674                 return;
675             }
676         } catch (OcException e) {
677             e.printStackTrace();
678         }
679     }
680
681     /**
682      * This method is for observing the bulb on/off status.
683      */
684     public void observe(OcResource resource) {
685         Log.i(LOG_TAG, "Registering observer for bookmark resources status");
686
687         Map<String, String> queryMap = new HashMap<String, String>();
688         try {
689             resource.observe(ObserveType.OBSERVE, queryMap, observeListener);
690         } catch (OcException e) {
691             e.printStackTrace();
692         }
693     }
694
695     /**
696      * This method is for unbinding and unregister all the found resources and
697      * groups.
698      */
699     public void leaveGroup() {
700         groupSynObj.setGroupListener(null);
701         groupManagerObj.setFindCandidateResourceListener(null);
702         groupManagerObj.setActionListener(null);
703
704         if (null != foundLightHandle) {
705             try {
706                 OcPlatform.unregisterResource(foundLightHandle);
707             } catch (OcException e) {
708                 e.printStackTrace();
709                 Log.i(LOG_TAG, "Resource Unregister Exception");
710             }
711         } else {
712             Log.i(LOG_TAG, "foundLightHandle is NULL");
713         }
714         if (null != groupResourceHandle) {
715
716             groupSynObj.deleteGroup(groupResourceType);
717         } else {
718             Log.i(LOG_TAG, "groupResourceHandle is NULL");
719         }
720     }
721
722     private void executeActionSet(String actonSetName, long delay) {
723         try {
724             OCStackResult result = groupManagerObj.executeActionSet(
725                     groupResource, actonSetName, delay);
726             if (OCStackResult.OC_STACK_OK != result) {
727                 Log.e(LOG_TAG,
728                         "executeActionSet retuned error : " + result.name());
729                 return;
730             }
731         } catch (OcException e) {
732             e.printStackTrace();
733         }
734     }
735
736     private void cancelActionSet(String actionSetName) {
737         try {
738             OCStackResult result = groupManagerObj.cancelActionSet(
739                     groupResource, actionSetName);
740             if (OCStackResult.OC_STACK_OK != result) {
741                 Log.e(LOG_TAG,
742                         "cancelActionSet returned error : " + result.name());
743                 return;
744             }
745         } catch (OcException e) {
746             e.printStackTrace();
747         }
748     }
749 }