216ac0ba9e53f4795fefbcbf8873b24c1c1b8774
[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  Presence Check
243  */
244
245 std::map< std::string, CollectionPresenceCallback > presenceCallbacks;
246
247 // Callback to presence
248 void GroupManager::collectionPresenceHandler(OCStackResult result, const unsigned int nonce,
249         const std::string& hostAddress, std::string host, std::string uri)
250 {
251     std::cout << "uri : " << uri << std::endl;
252     std::cout << "host : " << host << std::endl;
253     std::cout << "result : " << result << std::endl;
254     switch (result)
255     {
256         case OC_STACK_OK:
257             std::cout << "Nonce# " << nonce << std::endl;
258             break;
259         case OC_STACK_PRESENCE_STOPPED:
260             std::cout << "Presence Stopped\n";
261             break;
262         case OC_STACK_PRESENCE_DO_NOT_HANDLE:
263             std::cout << "Presence do not handle\n";
264             break;
265         case OC_STACK_PRESENCE_TIMEOUT:
266             std::cout << "Presence TIMEOUT\n";
267             break;
268         default:
269             std::cout << "Error\n";
270             break;
271     }
272
273     if (presenceCallbacks.find(uri) != presenceCallbacks.end())
274     {
275         (presenceCallbacks.find(uri)->second)(uri, result);
276     }
277 }
278
279 void GroupManager::checkCollectionRepresentation(const OCRepresentation& rep,
280         CollectionPresenceCallback callback)
281 {
282     std::cout << "\tResource URI: " << rep.getUri() << std::endl;
283
284     /* //bug not found
285      if(rep.hasAttribute("name"))
286      {
287      std::cout << "\tRoom name: " << rep.getValue<std::string>("name") << std::endl;
288      }
289      */
290     std::vector< OCRepresentation > children = rep.getChildren();
291     
292     if(children.size() == 0 )
293     {
294         callback("", OC_STACK_ERROR);
295         return;
296     }
297
298     for (auto oit = children.begin(); oit != children.end(); ++oit)
299     {
300         std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
301         std::vector< std::string > hostAddressVector = str_split(oit->getUri(), '/');
302         std::string hostAddress = "";
303         for (unsigned int i = 0; i < hostAddressVector.size(); ++i)
304         {
305             if (i < 3)
306             {
307                 hostAddress.append(hostAddressVector.at(i));
308                 if (i != 2)
309                 {
310                     hostAddress.append("/");
311                 }
312             }
313         }
314
315         std::vector< std::string > resourceTypes = oit->getResourceTypes();
316         for (unsigned int i = 0; i < resourceTypes.size(); ++i)
317         {
318             std::cout << "\t\t\tresourcetype :" << resourceTypes.at(i) << std::endl;
319         }
320
321         std::string resourceType = "core.";
322         resourceType.append(str_split(oit->getUri(), '/').at(4));
323         std::cout << "\t\tconvertRT : " << resourceType << std::endl;
324         std::cout << "\t\thost : " << hostAddress << std::endl;
325         OCPlatform::OCPresenceHandle presenceHandle;
326         OCStackResult result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
327                 resourceType,
328                 std::function<
329                         void(OCStackResult result, const unsigned int nonce,
330                                 const std::string& hostAddress) >(
331                         std::bind(&GroupManager::collectionPresenceHandler, this,
332                                 std::placeholders::_1, std::placeholders::_2,
333                                 std::placeholders::_3, hostAddress, oit->getUri())));
334
335         if (result == OC_STACK_OK)
336         {
337             std::cout << "\t\tOK!" << std::endl;
338             presenceCallbacks.insert(std::make_pair(oit->getUri(), callback));
339         }
340         else
341         {
342             callback("", OC_STACK_ERROR);
343         }
344
345     }
346 }
347
348 void GroupManager::onGetForPresence(const HeaderOptions& headerOptions,
349         const OCRepresentation& rep, const int eCode, CollectionPresenceCallback callback)
350 {
351     if (eCode == OC_STACK_OK)
352     {
353         std::cout << "GET request was successful" << std::endl;
354         std::cout << "Resource URI: " << rep.getUri() << std::endl;
355
356         checkCollectionRepresentation(rep, callback);
357
358     }
359     else
360     {
361         std::cout << "onGET Response error: " << eCode << std::endl;
362         callback("", OC_STACK_ERROR);
363         std::exit(-1);
364     }
365 }
366
367 OCStackResult GroupManager::subscribeCollectionPresence(
368         std::shared_ptr< OCResource > collectionResource, CollectionPresenceCallback callback)
369 {
370     if(callback == NULL || collectionResource == NULL)
371     {
372         return OC_STACK_ERROR;
373     }
374     
375     OCStackResult result = OC_STACK_OK;
376     //callback("core.room",OC_STACK_OK);
377
378     QueryParamsMap queryParam;
379
380     //parameter 1 = resourceType
381     collectionResource->get("", DEFAULT_INTERFACE, queryParam,
382             std::function<
383                     void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
384                             const int eCode) >(
385                     std::bind(&GroupManager::onGetForPresence, this, std::placeholders::_1,
386                             std::placeholders::_2, std::placeholders::_3, callback)));
387
388     return result;
389 }
390
391 /*
392  Group Action
393  */
394
395 std::string GroupManager::getStringFromActionSet(const ActionSet *newActionSet)
396 {
397     std::string message = "";
398
399     message = newActionSet->actionsetName;
400     message.append("*");
401     for (auto iterAction = newActionSet->listOfAction.begin();
402             iterAction != newActionSet->listOfAction.end(); iterAction++)
403     {
404         message.append("uri=");
405         message.append((*iterAction)->target);
406         message.append("|");
407
408         for (auto iterCapa = (*iterAction)->listOfCapability.begin();
409                 iterCapa != (*iterAction)->listOfCapability.end(); iterCapa++)
410         {
411             message.append((*iterCapa)->capability);
412             message.append("=");
413             message.append((*iterCapa)->status);
414
415             if (iterCapa + 1 != (*iterAction)->listOfCapability.end())
416                 message.append("|");
417         }
418
419         if (iterAction + 1 != newActionSet->listOfAction.end())
420         {
421             message.append("*");
422         }
423     }
424
425     return message;
426 }
427
428 ActionSet* GroupManager::getActionSetfromString(std::string desc)
429 {
430
431     char *token = NULL;
432     char *plainText = NULL;
433     char *plainPtr = NULL;
434
435     ActionSet *actionset = new ActionSet();
436     plainText = new char[(desc.length() + 1)];
437     strcpy(plainText, desc.c_str());
438
439     token = strtok_r(plainText, ACTION_DELIMITER, &plainPtr);
440
441     if (token != NULL)
442     {
443         actionset->actionsetName = std::string(token);
444         token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
445     }
446     else
447     {
448         delete actionset;
449         delete[] plainText;
450         return NULL;
451     }
452
453     while (token)
454     {
455         char *descPtr = NULL;
456         char *desc = new char[(strlen(token) + 1)];
457
458         if (desc != NULL)
459         {
460             Action *action = NULL;
461             strcpy(desc, token);
462             token = strtok_r(desc, DESC_DELIMITER, &descPtr);
463
464             // cout << "desc :: " << token << endl;
465             while (token != NULL)
466             {
467                 char *attrPtr = NULL;
468                 char *attr = new char[(strlen(token) + 1)];
469
470                 strcpy(attr, token);
471
472                 // cout << "attr :: " << attr << endl;
473
474                 token = strtok_r(attr, ATTR_DELIMITER, &attrPtr);
475                 while (token != NULL)
476                 {
477                     if (strcmp(token, "uri") == 0)
478                     {
479                         token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
480                         action = new Action();
481
482                         if (action != NULL)
483                         {
484                             action->target = std::string(token);
485                         }
486                         else
487                         {
488                             delete actionset;
489                             delete[] attr;
490                             delete desc;
491                             delete[] plainText;
492                             return NULL;
493                         }
494                     }
495                     else
496                     {
497                         Capability *capa = new Capability();
498                         capa->capability = std::string(token);
499                         token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
500                         capa->status = std::string(token);
501
502                         if (action != NULL)
503                         {
504                             action->listOfCapability.push_back(capa);
505                         }
506                         else
507                         {
508                             delete capa;
509                             delete actionset;
510                             delete[] attr;
511                             delete[] plainText;
512                             delete desc;
513                             return NULL;
514                         }
515                     }
516
517                     token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
518                 }
519
520                 delete[] attr;
521                 token = strtok_r(NULL, DESC_DELIMITER, &descPtr);
522             }
523
524             actionset->listOfAction.push_back(action);
525             //delete action;
526         }
527         else
528         {
529             delete actionset;
530             delete[] plainText;
531             return NULL;
532         }
533
534         delete[] desc;
535
536         token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
537     }
538
539     delete plainText;
540     return actionset;
541 }
542
543 OCStackResult GroupManager::addActionSet(std::shared_ptr< OCResource > resource,
544         const ActionSet* newActionSet, PutCallback cb)
545 {
546     // BUILD message of ActionSet which it is included delimiter.
547     if ((resource != NULL) && (newActionSet != NULL))
548     {
549         std::string message = getStringFromActionSet(newActionSet);
550         OCRepresentation rep;
551
552         rep.setValue("ActionSet", message);
553
554         return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
555                 QueryParamsMap(), cb);
556     }
557     else
558     {
559         return OC_STACK_ERROR;
560     }
561 }
562
563 OCStackResult GroupManager::executeActionSet(std::shared_ptr< OCResource > resource,
564         std::string actionsetName, PostCallback cb)
565 {
566     if (resource != NULL)
567     {
568         OCRepresentation rep;
569
570         rep.setValue("DoAction", actionsetName);
571         return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
572                 QueryParamsMap(), cb);
573     }
574     else
575     {
576         return OC_STACK_ERROR;
577     }
578 }
579
580 OCStackResult GroupManager::getActionSet(std::shared_ptr< OCResource > resource,
581         std::string actionsetName, PostCallback cb)
582 {
583     if (resource != NULL)
584     {
585         OCRepresentation rep;
586
587         rep.setValue("GetActionSet", actionsetName);
588
589         return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
590                 QueryParamsMap(), cb);
591     }
592     else
593     {
594         return OC_STACK_ERROR;
595     }
596 }
597
598 OCStackResult GroupManager::deleteActionSet(std::shared_ptr< OCResource > resource,
599         std::string actionsetName, PutCallback cb)
600 {
601     if (resource != NULL)
602     {
603         OCRepresentation rep;
604
605         rep.setValue("DelActionSet", actionsetName);
606
607         return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
608                 QueryParamsMap(), cb);
609     }
610     else
611     {
612         return OC_STACK_ERROR;
613     }
614 }
615 }