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