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