1 //******************************************************************
3 // Copyright 2014 Samsung Electronics All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
26 #include "GroupManager.h"
33 #define PLAIN_DELIMITER "\""
34 #define ACTION_DELIMITER "*"
35 #define DESC_DELIMITER "|"
36 #define ATTR_DELIMITER "="
41 std::map< std::vector< std::string >, CandidateCallback > candidateRequest;
42 std::map< std::vector< std::string >, CandidateCallback > candidateRequestForTimer;
43 std::map< std::string, std::map< std::string, std::shared_ptr< OCResource > > > rtForResourceList;
44 std::vector< std::string > allFoundResourceTypes;
45 std::mutex callbackLock;
48 template< typename T >
49 bool IsSubset(std::vector< T > full, std::vector< T > sub)
51 std::sort(full.begin(), full.end());
52 std::sort(sub.begin(), sub.end());
53 return std::includes(full.begin(), full.end(), sub.begin(), sub.end());
55 std::vector< std::string > &str_split(const std::string &s, char delim,
56 std::vector< std::string > &elems)
58 std::stringstream ss(s);
60 while (std::getline(ss, item, delim))
62 elems.push_back(item);
67 std::vector< std::string > str_split(const std::string &s, char delim)
69 std::vector< std::string > elems;
70 str_split(s, delim, elems);
74 void GroupManager::onFoundResource(std::shared_ptr< OCResource > resource, int waitsec)
77 std::string resourceURI;
78 std::string hostAddress;
81 // Do some operations with resource object.
85 std::cout << "DISCOVERED Resource:" << std::endl;
86 // Get the resource URI
87 resourceURI = resource->uri();
88 std::cout << "\tURI of the resource: " << resourceURI << std::endl;
90 // Get the resource host address
91 hostAddress = resource->host();
92 std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
94 // Get the resource types
95 std::cout << "\tList of resource types: " << std::endl;
97 hostAddress.append(resourceURI);
99 for (auto &resourceTypes : resource->getResourceTypes())
101 std::cout << "\t\t" << resourceTypes << std::endl;
103 if (std::find(allFoundResourceTypes.begin(), allFoundResourceTypes.end(),
104 resourceTypes) == allFoundResourceTypes.end())
106 allFoundResourceTypes.push_back(resourceTypes);
109 rtForResourceList[resourceTypes][hostAddress] = resource;
112 // Get the resource interfaces
113 std::cout << "\tList of resource interfaces: " << std::endl;
114 for (auto &resourceInterfaces : resource->getResourceInterfaces())
116 std::cout << "\t\t" << resourceInterfaces << std::endl;
121 findPreparedRequest(candidateRequest);
126 // Resource is invalid
127 std::cout << "Resource is invalid" << std::endl;
131 catch (std::exception& e)
137 GroupManager::GroupManager(void)
145 GroupManager::~GroupManager(void)
147 candidateRequest.clear();
148 candidateRequestForTimer.clear();
149 rtForResourceList.clear();
150 allFoundResourceTypes.clear();
153 void GroupManager::findPreparedRequest(
154 std::map< std::vector< std::string >, CandidateCallback > &request)
156 std::lock_guard<std::mutex> lock(callbackLock);
157 std::vector< std::shared_ptr< OCResource > > resources;
159 for (auto it = request.begin(); it != request.end();)
162 if (IsSubset(allFoundResourceTypes, it->first))
164 for (unsigned int i = 0; i < it->first.size(); ++i)
167 for (auto secondIt = rtForResourceList[it->first.at(i)].begin();
168 secondIt != rtForResourceList[it->first.at(i)].end(); ++secondIt)
170 //insert resource related to request
171 resources.push_back(secondIt->second);
175 it->second(resources);
177 //TODO : decide policy - callback only once
189 void GroupManager::lazyCallback(int second)
192 findPreparedRequest(candidateRequestForTimer);
196 OCStackResult GroupManager::findCandidateResources(
197 std::vector< std::string > resourceTypes,
198 CandidateCallback callback, int waitsec)
200 if (resourceTypes.size() < 1)
202 return OC_STACK_ERROR;
206 return OC_STACK_ERROR;
209 std::sort(resourceTypes.begin(), resourceTypes.end());
210 resourceTypes.erase(std::unique(resourceTypes.begin(), resourceTypes.end()),
211 resourceTypes.end());
215 candidateRequestForTimer.insert(std::make_pair(resourceTypes, callback));
219 candidateRequest.insert(std::make_pair(resourceTypes, callback));
222 for (unsigned int i = 0; i < resourceTypes.size(); ++i)
224 // std::cout << "resourceTypes : " << resourceTypes.at(i) << std::endl;
226 std::string query = OC_WELL_KNOWN_QUERY;
227 query.append("?rt=");
228 query.append(resourceTypes.at(i));
230 OCPlatform::findResource("",
233 std::function < void(std::shared_ptr < OCResource > resource)
234 > (std::bind(&GroupManager::onFoundResource, this, std::placeholders::_1,
237 // OCPlatform::findResource("",
240 // std::function < void(std::shared_ptr < OCResource > resource)
241 // > (std::bind(&GroupManager::onFoundResource, this, std::placeholders::_1,
248 std::function< void(int second) >(
249 std::bind(&GroupManager::lazyCallback, this, std::placeholders::_1)),
258 OCStackResult GroupManager::bindResourceToGroup(OCResourceHandle& childHandle, std::shared_ptr< OCResource > resource, OCResourceHandle& collectionHandle)
261 OCStackResult result = OCPlatform::registerResource(childHandle, resource);
263 cout << "\tresource registed!" << endl;
265 if(result == OC_STACK_OK)
267 OCPlatform::bindResource(collectionHandle, childHandle);
271 cout << "\tresource Error!" << endl;
283 std::map< std::string, CollectionPresenceCallback > presenceCallbacks;
285 // Callback to presence
286 void GroupManager::collectionPresenceHandler(OCStackResult result, const unsigned int nonce,
287 const std::string& hostAddress, std::string host, std::string uri)
289 std::cout << "uri : " << uri << std::endl;
290 std::cout << "host : " << host << std::endl;
291 std::cout << "result : " << result << std::endl;
295 std::cout << "Nonce# " << nonce << std::endl;
297 case OC_STACK_PRESENCE_STOPPED:
298 std::cout << "Presence Stopped\n";
300 case OC_STACK_PRESENCE_DO_NOT_HANDLE:
301 std::cout << "Presence do not handle\n";
303 case OC_STACK_PRESENCE_TIMEOUT:
304 std::cout << "Presence TIMEOUT\n";
307 std::cout << "Error\n";
311 if (presenceCallbacks.find(uri) != presenceCallbacks.end())
313 (presenceCallbacks.find(uri)->second)(uri, result);
317 void GroupManager::checkCollectionRepresentation(const OCRepresentation& rep,
318 CollectionPresenceCallback callback)
320 std::cout << "\tResource URI: " << rep.getUri() << std::endl;
323 if(rep.hasAttribute("name"))
325 std::cout << "\tRoom name: " << rep.getValue<std::string>("name") << std::endl;
328 std::vector< OCRepresentation > children = rep.getChildren();
329 if(children.size() == 0 )
331 callback("", OC_STACK_ERROR);
335 for (auto oit = children.begin(); oit != children.end(); ++oit)
337 // std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
338 std::vector< std::string > hostAddressVector = str_split(oit->getUri(), '/');
339 std::string hostAddress = "";
340 for (unsigned int i = 0; i < hostAddressVector.size(); ++i)
344 hostAddress.append(hostAddressVector.at(i));
347 hostAddress.append("/");
352 std::vector< std::string > resourceTypes = oit->getResourceTypes();
353 // for (unsigned int i = 0; i < resourceTypes.size(); ++i)
355 // std::cout << "\t\t\tresourcetype :" << resourceTypes.at(i) << std::endl;
358 // std::string resourceType = "core.";
359 // resourceType.append(str_split(oit->getUri(), '/').at(4));
360 // std::cout << "\t\tconvertRT : " << resourceType << std::endl;
361 // std::cout << "\t\tresource type front : " << resourceTypes.front() << endl;
362 // std::cout << "\t\thost : " << hostAddress << std::endl;
363 OCPlatform::OCPresenceHandle presenceHandle;
364 OCStackResult result = OC_STACK_ERROR;
366 result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
368 resourceTypes.front(),
371 void(OCStackResult result, const unsigned int nonce,
372 const std::string& hostAddress) >(
373 std::bind(&GroupManager::collectionPresenceHandler, this,
374 std::placeholders::_1, std::placeholders::_2,
375 std::placeholders::_3, hostAddress, oit->getUri())));
377 if (result == OC_STACK_OK)
379 presenceCallbacks.insert(std::make_pair(oit->getUri(), callback));
383 callback("", OC_STACK_ERROR);
388 void GroupManager::onGetForPresence(const HeaderOptions& headerOptions,
389 const OCRepresentation& rep, const int eCode, CollectionPresenceCallback callback)
391 if (eCode == OC_STACK_OK)
393 std::cout << "GET request was successful" << std::endl;
394 std::cout << "Resource URI: " << rep.getUri() << std::endl;
396 checkCollectionRepresentation(rep, callback);
401 std::cout << "onGET Response error: " << eCode << std::endl;
402 callback("", OC_STACK_ERROR);
406 OCStackResult GroupManager::subscribeCollectionPresence(
407 std::shared_ptr< OCResource > collectionResource, CollectionPresenceCallback callback)
409 if(callback == NULL || collectionResource == NULL)
411 return OC_STACK_ERROR;
414 OCStackResult result = OC_STACK_OK;
415 //callback("core.room",OC_STACK_OK);
417 QueryParamsMap queryParam;
419 //parameter 1 = resourceType
420 collectionResource->get("", DEFAULT_INTERFACE, queryParam,
422 void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
424 std::bind(&GroupManager::onGetForPresence, this, std::placeholders::_1,
425 std::placeholders::_2, std::placeholders::_3, callback)));
434 std::string GroupManager::getStringFromActionSet(const ActionSet *newActionSet)
436 std::string message = "";
438 if(newActionSet == NULL)
441 message = newActionSet->actionsetName;
443 message.append(newActionSet->toString());
445 for (auto iterAction = newActionSet->listOfAction.begin();
446 iterAction != newActionSet->listOfAction.end(); iterAction++)
448 message.append("uri=");
449 message.append((*iterAction)->target);
452 for (auto iterCapa = (*iterAction)->listOfCapability.begin();
453 iterCapa != (*iterAction)->listOfCapability.end(); iterCapa++)
455 message.append((*iterCapa)->capability);
457 message.append((*iterCapa)->status);
459 if (iterCapa + 1 != (*iterAction)->listOfCapability.end())
463 if (iterAction + 1 != newActionSet->listOfAction.end())
472 #define DELETE(p) { \
477 #define DELETEARRAY(p) { \
482 ActionSet* GroupManager::getActionSetfromString(std::string description)
485 char *plainText = NULL;
486 char *plainPtr = NULL;
487 char *attr = NULL, *desc = NULL;
489 Capability *capa = NULL;
490 ActionSet *actionset = new ActionSet();
492 if(description.empty())
496 else if(description.at(0) == '*')
501 plainText = new char[(description.length() + 1)];
502 strcpy(plainText, description.c_str());
504 token = strtok_r(plainText, ACTION_DELIMITER, &plainPtr);
508 actionset->actionsetName = std::string(token);
510 if((actionset->actionsetName).empty())
513 token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
522 sscanf(token, "%ld %d", &actionset->mDelay, (int*)&actionset->type);
524 token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
533 char *descPtr = NULL;
534 desc = new char[(strlen(token) + 1)];
538 Action *action = NULL;
540 token = strtok_r(desc, DESC_DELIMITER, &descPtr);
542 while (token != NULL)
544 char *attrPtr = NULL;
545 attr = new char[(strlen(token) + 1)];
549 token = strtok_r(attr, ATTR_DELIMITER, &attrPtr);
550 while (token != NULL)
552 if (strcmp(token, "uri") == 0)
554 token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
560 action = new Action();
563 action->target = std::string(token);
572 capa = new Capability();
573 capa->capability = std::string(token);
574 token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
579 capa->status = std::string(token);
582 action->listOfCapability.push_back(capa);
587 token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
590 token = strtok_r(NULL, DESC_DELIMITER, &descPtr);
593 if( actionset != NULL )
594 actionset->listOfAction.push_back(action);
607 token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
617 DELETEARRAY(plainText);
622 OCStackResult GroupManager::addActionSet(std::shared_ptr< OCResource > resource,
623 const ActionSet* newActionSet, PutCallback cb)
625 // BUILD message of ActionSet which it is included delimiter.
626 if ((resource != NULL) && (newActionSet != NULL))
628 if(newActionSet->mDelay < 0)
630 return OC_STACK_INVALID_PARAM;
633 std::string message = getStringFromActionSet(newActionSet);
635 OCRepresentation rep;
636 rep.setValue("ActionSet", message);
637 return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
638 QueryParamsMap(), cb);
642 return OC_STACK_ERROR;
646 OCStackResult GroupManager::executeActionSet(std::shared_ptr< OCResource > resource,
647 std::string actionsetName, PostCallback cb)
649 if (resource != NULL)
651 OCRepresentation rep;
653 rep.setValue("DoAction", actionsetName);
654 return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
655 QueryParamsMap(), cb);
659 return OC_STACK_ERROR;
663 OCStackResult GroupManager::executeActionSet(std::shared_ptr< OCResource > resource,
664 std::string actionsetName, long int delay, PostCallback cb)
668 return OC_STACK_INVALID_PARAM;
670 if (resource != NULL)
672 std::string value = actionsetName;
674 value.append(std::to_string(delay));
676 OCRepresentation rep;
677 rep.setValue("DoScheduledAction", value);
678 return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
679 QueryParamsMap(), cb);
683 return OC_STACK_ERROR;
687 OCStackResult GroupManager::cancelActionSet(std::shared_ptr< OCResource > resource,
688 std::string actionsetName, PostCallback cb)
690 if (resource != NULL)
692 OCRepresentation rep;
694 rep.setValue("CancelAction", actionsetName);
695 return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
696 QueryParamsMap(), cb);
700 return OC_STACK_ERROR;
704 OCStackResult GroupManager::getActionSet(std::shared_ptr< OCResource > resource,
705 std::string actionsetName, PostCallback cb)
707 if (resource != NULL)
709 OCRepresentation rep;
711 rep.setValue("GetActionSet", actionsetName);
713 return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
714 QueryParamsMap(), cb);
718 return OC_STACK_ERROR;
722 OCStackResult GroupManager::deleteActionSet(std::shared_ptr< OCResource > resource,
723 std::string actionsetName, PutCallback cb)
725 if (resource != NULL)
727 OCRepresentation rep;
729 rep.setValue("DelActionSet", actionsetName);
731 return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
732 QueryParamsMap(), cb);
736 return OC_STACK_ERROR;