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