Add method of Things-Manager.
[platform/upstream/iotivity.git] / service / things-manager / sdk / src / GroupManager.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 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
21 /// @file    GroupManager.cpp
22 ///  @brief
23
24 #include "GroupManager.h"
25 #include <algorithm>
26 #include <thread>
27 #include <unistd.h>
28
29 #include <string.h>
30
31 #define PLAIN_DELIMITER "\""
32 #define ACTION_DELIMITER "*"
33 #define DESC_DELIMITER "|"
34 #define ATTR_DELIMITER "="
35
36 using namespace OC;
37
38 namespace OIC
39 {
40 std::map< std::vector< std::string >, CandidateCallback > candidateRequest;
41 std::map< std::vector< std::string >, CandidateCallback > candidateRequestForTimer;
42 std::map< std::string, std::map< std::string, std::shared_ptr< OCResource > > > rtForResourceList;
43 std::vector< std::string > allFoundResourceTypes;
44
45 template< typename T >
46 bool IsSubset(std::vector< T > full, std::vector< T > sub)
47 {
48     std::sort(full.begin(), full.end());
49     std::sort(sub.begin(), sub.end());
50     return std::includes(full.begin(), full.end(), sub.begin(), sub.end());
51 }
52 std::vector< std::string > &str_split(const std::string &s, char delim,
53         std::vector< std::string > &elems)
54 {
55     std::stringstream ss(s);
56     std::string item;
57     while (std::getline(ss, item, delim))
58     {
59         elems.push_back(item);
60     }
61     return elems;
62 }
63
64 std::vector< std::string > str_split(const std::string &s, char delim)
65 {
66     std::vector< std::string > elems;
67     str_split(s, delim, elems);
68     return elems;
69 }
70
71 void GroupManager::onFoundResource(std::shared_ptr< OCResource > resource, int waitsec)
72 {
73
74     std::string resourceURI;
75     std::string hostAddress;
76     try
77     {
78         // Do some operations with resource object.
79         if (resource)
80         {
81
82             std::cout << "DISCOVERED Resource:" << std::endl;
83             // Get the resource URI
84             resourceURI = resource->uri();
85             std::cout << "\tURI of the resource: " << resourceURI << std::endl;
86
87             // Get the resource host address
88             hostAddress = resource->host();
89             std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
90
91             // Get the resource types
92             std::cout << "\tList of resource types: " << std::endl;
93
94             hostAddress.append(resourceURI);
95
96             for (auto &resourceTypes : resource->getResourceTypes())
97             {
98                 std::cout << "\t\t" << resourceTypes << std::endl;
99
100                 if (std::find(allFoundResourceTypes.begin(), allFoundResourceTypes.end(),
101                         resourceTypes) == allFoundResourceTypes.end())
102                 {
103                     allFoundResourceTypes.push_back(resourceTypes);
104                 }
105
106                 rtForResourceList[resourceTypes][hostAddress] = resource;
107             }
108
109             // Get the resource interfaces
110             std::cout << "\tList of resource interfaces: " << std::endl;
111             for (auto &resourceInterfaces : resource->getResourceInterfaces())
112             {
113                 std::cout << "\t\t" << resourceInterfaces << std::endl;
114             }
115
116             if (waitsec == -1)
117             {
118                 findPreparedRequest(candidateRequest);
119             }
120         }
121         else
122         {
123             // Resource is invalid
124             std::cout << "Resource is invalid" << std::endl;
125         }
126
127     }
128     catch (std::exception& e)
129     {
130         //log(e.what());
131     }
132 }
133
134 GroupManager::GroupManager(void)
135 {
136     ;
137 }
138
139 /**
140  * Virtual destructor
141  */
142 GroupManager::~GroupManager(void)
143 {
144     candidateRequest.clear();
145     candidateRequestForTimer.clear();
146     rtForResourceList.clear();
147     allFoundResourceTypes.clear();
148 }
149
150 void GroupManager::findPreparedRequest(
151         std::map< std::vector< std::string >, CandidateCallback > &request)
152 {
153     std::vector< std::shared_ptr< OCResource > > resources;
154
155     for (auto it = request.begin(); it != request.end();)
156     {
157
158         if (IsSubset(allFoundResourceTypes, it->first))
159         {
160             //std::cout << "IS SUBSET !!! \n";
161
162             for (unsigned int i = 0; i < it->first.size(); ++i)
163             {
164
165                 for (auto secondIt = rtForResourceList[it->first.at(i)].begin();
166                         secondIt != rtForResourceList[it->first.at(i)].end(); ++secondIt)
167                 {
168                     resources.push_back(secondIt->second);
169                 }
170             }
171
172             it->second(resources);
173
174             //TODO : decide policy - callback only once
175             request.erase(it++);
176         }
177         else
178         {
179             ++it;
180         }
181
182     }
183
184 }
185
186 void GroupManager::lazyCallback(int second)
187 {
188     sleep(second);
189     findPreparedRequest(candidateRequestForTimer);
190
191 }
192
193 OCStackResult GroupManager::findCandidateResources(std::vector< std::string > resourceTypes,
194         CandidateCallback callback, int waitsec)
195 {
196     if (resourceTypes.size() < 1)
197     {
198         return OC_STACK_ERROR;
199     }
200     if(callback == NULL)
201     {
202         return OC_STACK_ERROR;
203     }
204
205     std::sort(resourceTypes.begin(), resourceTypes.end());
206     resourceTypes.erase(std::unique(resourceTypes.begin(), resourceTypes.end()),
207             resourceTypes.end());
208
209     if (waitsec >= 0)
210     {
211         candidateRequestForTimer.insert(std::make_pair(resourceTypes, callback));
212     }
213     else
214     {
215         candidateRequest.insert(std::make_pair(resourceTypes, callback));
216     }
217
218     for (unsigned int i = 0; i < resourceTypes.size(); ++i)
219     {
220         std::cout << "resourceTypes : " << resourceTypes.at(i) << std::endl;
221         std::string query = "coap://224.0.1.187/oc/core?rt=";
222         query.append(resourceTypes.at(i));
223         OCPlatform::findResource("", query.c_str(),
224                 std::function < void(std::shared_ptr < OCResource > resource)
225                         > (std::bind(&GroupManager::onFoundResource, this,
226                                 std::placeholders::_1, waitsec)));
227     }
228
229     if (waitsec >= 0)
230     {
231         std::thread exec(
232                 std::function< void(int second) >(
233                         std::bind(&GroupManager::lazyCallback, this, std::placeholders::_1)),
234                 waitsec);
235         exec.detach();
236     }
237
238     return OC_STACK_OK;
239 }
240
241
242 OCStackResult GroupManager::bindResourceToGroup(OCResourceHandle& childHandle, std::shared_ptr< OCResource > resource, OCResourceHandle& collectionHandle)
243 {
244
245     OCStackResult result = OCPlatform::registerResource(childHandle, resource);
246
247     cout << "\tresource registed!" << endl;
248
249     if(result == OC_STACK_OK)
250     {
251         OCPlatform::bindResource(collectionHandle, childHandle);
252     }
253     else
254     {
255         cout << "\tresource Error!" << endl;
256     }
257
258     return result;
259  }
260
261
262
263 /*
264  Presence Check
265  */
266
267 std::map< std::string, CollectionPresenceCallback > presenceCallbacks;
268
269 // Callback to presence
270 void GroupManager::collectionPresenceHandler(OCStackResult result, const unsigned int nonce,
271         const std::string& hostAddress, std::string host, std::string uri)
272 {
273     std::cout << "uri : " << uri << std::endl;
274     std::cout << "host : " << host << std::endl;
275     std::cout << "result : " << result << std::endl;
276     switch (result)
277     {
278         case OC_STACK_OK:
279             std::cout << "Nonce# " << nonce << std::endl;
280             break;
281         case OC_STACK_PRESENCE_STOPPED:
282             std::cout << "Presence Stopped\n";
283             break;
284         case OC_STACK_PRESENCE_DO_NOT_HANDLE:
285             std::cout << "Presence do not handle\n";
286             break;
287         case OC_STACK_PRESENCE_TIMEOUT:
288             std::cout << "Presence TIMEOUT\n";
289             break;
290         default:
291             std::cout << "Error\n";
292             break;
293     }
294
295     if (presenceCallbacks.find(uri) != presenceCallbacks.end())
296     {
297         (presenceCallbacks.find(uri)->second)(uri, result);
298     }
299 }
300
301 void GroupManager::checkCollectionRepresentation(const OCRepresentation& rep,
302         CollectionPresenceCallback callback)
303 {
304     std::cout << "\tResource URI: " << rep.getUri() << std::endl;
305
306     /* //bug not found
307      if(rep.hasAttribute("name"))
308      {
309      std::cout << "\tRoom name: " << rep.getValue<std::string>("name") << std::endl;
310      }
311      */
312     std::vector< OCRepresentation > children = rep.getChildren();
313     
314     if(children.size() == 0 )
315     {
316         callback("", OC_STACK_ERROR);
317         return;
318     }
319
320     for (auto oit = children.begin(); oit != children.end(); ++oit)
321     {
322         std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
323         std::vector< std::string > hostAddressVector = str_split(oit->getUri(), '/');
324         std::string hostAddress = "";
325         for (unsigned int i = 0; i < hostAddressVector.size(); ++i)
326         {
327             if (i < 3)
328             {
329                 hostAddress.append(hostAddressVector.at(i));
330                 if (i != 2)
331                 {
332                     hostAddress.append("/");
333                 }
334             }
335         }
336
337         std::vector< std::string > resourceTypes = oit->getResourceTypes();
338         for (unsigned int i = 0; i < resourceTypes.size(); ++i)
339         {
340             std::cout << "\t\t\tresourcetype :" << resourceTypes.at(i) << std::endl;
341         }
342
343         std::string resourceType = "core.";
344         resourceType.append(str_split(oit->getUri(), '/').at(4));
345         std::cout << "\t\tconvertRT : " << resourceType << std::endl;
346         std::cout << "\t\thost : " << hostAddress << std::endl;
347         OCPlatform::OCPresenceHandle presenceHandle;
348         OCStackResult result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
349                 resourceType,
350                 std::function<
351                         void(OCStackResult result, const unsigned int nonce,
352                                 const std::string& hostAddress) >(
353                         std::bind(&GroupManager::collectionPresenceHandler, this,
354                                 std::placeholders::_1, std::placeholders::_2,
355                                 std::placeholders::_3, hostAddress, oit->getUri())));
356
357         if (result == OC_STACK_OK)
358         {
359             std::cout << "\t\tOK!" << std::endl;
360             presenceCallbacks.insert(std::make_pair(oit->getUri(), callback));
361         }
362         else
363         {
364             callback("", OC_STACK_ERROR);
365         }
366
367     }
368 }
369
370 void GroupManager::onGetForPresence(const HeaderOptions& headerOptions,
371         const OCRepresentation& rep, const int eCode, CollectionPresenceCallback callback)
372 {
373     if (eCode == OC_STACK_OK)
374     {
375         std::cout << "GET request was successful" << std::endl;
376         std::cout << "Resource URI: " << rep.getUri() << std::endl;
377
378         checkCollectionRepresentation(rep, callback);
379
380     }
381     else
382     {
383         std::cout << "onGET Response error: " << eCode << std::endl;
384         callback("", OC_STACK_ERROR);
385         std::exit(-1);
386     }
387 }
388
389 OCStackResult GroupManager::subscribeCollectionPresence(
390         std::shared_ptr< OCResource > collectionResource, CollectionPresenceCallback callback)
391 {
392     if(callback == NULL || collectionResource == NULL)
393     {
394         return OC_STACK_ERROR;
395     }
396     
397     OCStackResult result = OC_STACK_OK;
398     //callback("core.room",OC_STACK_OK);
399
400     QueryParamsMap queryParam;
401
402     //parameter 1 = resourceType
403     collectionResource->get("", DEFAULT_INTERFACE, queryParam,
404             std::function<
405                     void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
406                             const int eCode) >(
407                     std::bind(&GroupManager::onGetForPresence, this, std::placeholders::_1,
408                             std::placeholders::_2, std::placeholders::_3, callback)));
409
410     return result;
411 }
412
413 /*
414  Group Action
415  */
416
417 std::string GroupManager::getStringFromActionSet(const ActionSet *newActionSet)
418 {
419     std::string message = "";
420
421     message = newActionSet->actionsetName;
422     message.append("*");
423     for (auto iterAction = newActionSet->listOfAction.begin();
424             iterAction != newActionSet->listOfAction.end(); iterAction++)
425     {
426         message.append("uri=");
427         message.append((*iterAction)->target);
428         message.append("|");
429
430         for (auto iterCapa = (*iterAction)->listOfCapability.begin();
431                 iterCapa != (*iterAction)->listOfCapability.end(); iterCapa++)
432         {
433             message.append((*iterCapa)->capability);
434             message.append("=");
435             message.append((*iterCapa)->status);
436
437             if (iterCapa + 1 != (*iterAction)->listOfCapability.end())
438                 message.append("|");
439         }
440
441         if (iterAction + 1 != newActionSet->listOfAction.end())
442         {
443             message.append("*");
444         }
445     }
446
447     return message;
448 }
449
450 ActionSet* GroupManager::getActionSetfromString(std::string desc)
451 {
452
453     char *token = NULL;
454     char *plainText = NULL;
455     char *plainPtr = NULL;
456
457     ActionSet *actionset = new ActionSet();
458     plainText = new char[(desc.length() + 1)];
459     strcpy(plainText, desc.c_str());
460
461     token = strtok_r(plainText, ACTION_DELIMITER, &plainPtr);
462
463     if (token != NULL)
464     {
465         actionset->actionsetName = std::string(token);
466         token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
467     }
468     else
469     {
470         delete actionset;
471         delete[] plainText;
472         return NULL;
473     }
474
475     while (token)
476     {
477         char *descPtr = NULL;
478         char *desc = new char[(strlen(token) + 1)];
479
480         if (desc != NULL)
481         {
482             Action *action = NULL;
483             strcpy(desc, token);
484             token = strtok_r(desc, DESC_DELIMITER, &descPtr);
485
486             // cout << "desc :: " << token << endl;
487             while (token != NULL)
488             {
489                 char *attrPtr = NULL;
490                 char *attr = new char[(strlen(token) + 1)];
491
492                 strcpy(attr, token);
493
494                 // cout << "attr :: " << attr << endl;
495
496                 token = strtok_r(attr, ATTR_DELIMITER, &attrPtr);
497                 while (token != NULL)
498                 {
499                     if (strcmp(token, "uri") == 0)
500                     {
501                         token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
502                         action = new Action();
503
504                         if (action != NULL)
505                         {
506                             action->target = std::string(token);
507                         }
508                         else
509                         {
510                             delete actionset;
511                             delete[] attr;
512                             delete desc;
513                             delete[] plainText;
514                             return NULL;
515                         }
516                     }
517                     else
518                     {
519                         Capability *capa = new Capability();
520                         capa->capability = std::string(token);
521                         token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
522                         capa->status = std::string(token);
523
524                         if (action != NULL)
525                         {
526                             action->listOfCapability.push_back(capa);
527                         }
528                         else
529                         {
530                             delete capa;
531                             delete actionset;
532                             delete[] attr;
533                             delete[] plainText;
534                             delete desc;
535                             return NULL;
536                         }
537                     }
538
539                     token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
540                 }
541
542                 delete[] attr;
543                 token = strtok_r(NULL, DESC_DELIMITER, &descPtr);
544             }
545
546             actionset->listOfAction.push_back(action);
547             //delete action;
548         }
549         else
550         {
551             delete actionset;
552             delete[] plainText;
553             return NULL;
554         }
555
556         delete[] desc;
557
558         token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
559     }
560
561     delete plainText;
562     return actionset;
563 }
564
565 OCStackResult GroupManager::addActionSet(std::shared_ptr< OCResource > resource,
566         const ActionSet* newActionSet, PutCallback cb)
567 {
568     // BUILD message of ActionSet which it is included delimiter.
569     if ((resource != NULL) && (newActionSet != NULL))
570     {
571         std::string message = getStringFromActionSet(newActionSet);
572         OCRepresentation rep;
573
574         rep.setValue("ActionSet", message);
575
576         return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
577                 QueryParamsMap(), cb);
578     }
579     else
580     {
581         return OC_STACK_ERROR;
582     }
583 }
584
585 OCStackResult GroupManager::executeActionSet(std::shared_ptr< OCResource > resource,
586         std::string actionsetName, PostCallback cb)
587 {
588     if (resource != NULL)
589     {
590         OCRepresentation rep;
591
592         rep.setValue("DoAction", actionsetName);
593         return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
594                 QueryParamsMap(), cb);
595     }
596     else
597     {
598         return OC_STACK_ERROR;
599     }
600 }
601
602 OCStackResult GroupManager::getActionSet(std::shared_ptr< OCResource > resource,
603         std::string actionsetName, PostCallback cb)
604 {
605     if (resource != NULL)
606     {
607         OCRepresentation rep;
608
609         rep.setValue("GetActionSet", actionsetName);
610
611         return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
612                 QueryParamsMap(), cb);
613     }
614     else
615     {
616         return OC_STACK_ERROR;
617     }
618 }
619
620 OCStackResult GroupManager::deleteActionSet(std::shared_ptr< OCResource > resource,
621         std::string actionsetName, PutCallback cb)
622 {
623     if (resource != NULL)
624     {
625         OCRepresentation rep;
626
627         rep.setValue("DelActionSet", actionsetName);
628
629         return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
630                 QueryParamsMap(), cb);
631     }
632     else
633     {
634         return OC_STACK_ERROR;
635     }
636 }
637 }