1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH 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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
30 #include <InProcServerWrapper.h>
31 #include <InitializeException.h>
32 #include <OCResourceRequest.h>
33 #include <OCResourceResponse.h>
35 #include <ocpayload.h>
38 #include <oic_malloc.h>
39 #include <OCPlatform.h>
40 #include <OCUtilities.h>
43 #define TAG "OIC_SERVER_WRAPPER"
52 std::mutex serverWrapperLock;
53 std::map <OCResourceHandle, OC::EntityHandler> entityHandlerMap;
54 std::map <OCResourceHandle, std::string> resourceUriMap;
55 EntityHandler defaultDeviceEntityHandler;
59 void formResourceRequest(OCEntityHandlerFlag flag,
60 OCEntityHandlerRequest * entityHandlerRequest,
61 std::shared_ptr<OCResourceRequest> pRequest)
63 if(pRequest && entityHandlerRequest)
65 pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
66 pRequest->setResourceHandle(entityHandlerRequest->resource);
67 pRequest->setMessageID(entityHandlerRequest->messageID);
70 if(flag & OC_REQUEST_FLAG)
72 pRequest->setRequestHandlerFlag(OC::RequestHandlerFlag::RequestFlag);
74 if(entityHandlerRequest)
76 if(entityHandlerRequest->query)
78 OC::Utilities::QueryParamsKeyVal qp = OC::Utilities::getQueryParams(
79 entityHandlerRequest->query);
83 pRequest->setQueryParams(qp);
86 if(entityHandlerRequest->numRcvdVendorSpecificHeaderOptions != 0)
88 //Set the header options here.
90 char optionData[MAX_HEADER_OPTION_DATA_LENGTH + 1];
91 HeaderOptions headerOptions;
93 optionData[MAX_HEADER_OPTION_DATA_LENGTH] = '\0';
95 i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions;
98 optionID = entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionID;
99 memcpy(optionData, entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionData,
100 MAX_HEADER_OPTION_DATA_LENGTH);
101 HeaderOption::OCHeaderOption headerOption(optionID, optionData);
102 headerOptions.push_back(headerOption);
104 pRequest->setHeaderOptions(headerOptions);
107 if(OC_REST_GET == entityHandlerRequest->method)
109 pRequest->setRequestType(OC::PlatformCommands::GET);
111 else if(OC_REST_PUT == entityHandlerRequest->method)
113 pRequest->setRequestType(OC::PlatformCommands::PUT);
114 pRequest->setPayload(entityHandlerRequest->payload);
116 else if(OC_REST_POST == entityHandlerRequest->method)
118 pRequest->setRequestType(OC::PlatformCommands::POST);
119 pRequest->setPayload(entityHandlerRequest->payload);
121 else if(OC_REST_DELETE == entityHandlerRequest->method)
123 pRequest->setRequestType(OC::PlatformCommands::DELETE);
128 if(flag & OC_OBSERVE_FLAG)
130 pRequest->setRequestHandlerFlag(
131 OC::RequestHandlerFlag::RequestFlag | OC::RequestHandlerFlag::ObserverFlag);
133 if(entityHandlerRequest)
135 OC::ObservationInfo observationInfo;
136 observationInfo.action = (OC::ObserveAction) entityHandlerRequest->obsInfo.action;
137 observationInfo.obsId = entityHandlerRequest->obsInfo.obsId;
139 observationInfo.connectivityType = static_cast<OCConnectivityType>(
140 (entityHandlerRequest->devAddr.adapter << CT_ADAPTER_SHIFT) |
141 (entityHandlerRequest->devAddr.flags & CT_MASK_FLAGS));
142 observationInfo.address = entityHandlerRequest->devAddr.addr;
143 observationInfo.port = entityHandlerRequest->devAddr.port;
144 pRequest->setObservationInfo(observationInfo);
149 OCEntityHandlerResult DefaultEntityHandlerWrapper(OCEntityHandlerFlag flag,
150 OCEntityHandlerRequest * entityHandlerRequest,
152 void * /*callbackParam*/)
154 OCEntityHandlerResult result = OC_EH_ERROR;
156 OC::oclog() << "In Default device entity handler wrapper";
158 if(NULL == entityHandlerRequest)
160 oclog() << "Entity handler request is NULL.";
164 auto pRequest = std::make_shared<OC::OCResourceRequest>();
166 formResourceRequest(flag, entityHandlerRequest, pRequest);
168 pRequest->setResourceUri(std::string(uri));
170 EntityHandler defHandler;
172 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
173 defHandler = OC::details::defaultDeviceEntityHandler;
178 result = defHandler(pRequest);
182 oclog() << "Default device entity handler was not set.";
190 OCEntityHandlerResult EntityHandlerWrapper(OCEntityHandlerFlag flag,
191 OCEntityHandlerRequest * entityHandlerRequest,
192 void* /*callbackParam*/)
194 OCEntityHandlerResult result = OC_EH_ERROR;
196 oclog() << "\nIn entity handler wrapper: " << endl;
198 if(NULL == entityHandlerRequest)
200 oclog() << "Entity handler request is NULL." << endl;
204 auto pRequest = std::make_shared<OC::OCResourceRequest>();
206 formResourceRequest(flag, entityHandlerRequest, pRequest);
208 std::map <OCResourceHandle, std::string>::iterator resourceUriEntry;
209 std::map <OCResourceHandle, std::string>::iterator resourceUriEnd;
211 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
212 resourceUriEntry = OC::details::resourceUriMap.find(entityHandlerRequest->resource);
213 resourceUriEnd = OC::details::resourceUriMap.end();
215 // Finding the corresponding URI for a resource handle and set the URI in the request
216 if(resourceUriEntry != resourceUriEnd)
218 pRequest->setResourceUri(resourceUriEntry->second);
222 oclog() << "Resource handle not found; Resource URI not set in request";
226 std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEntry;
227 std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEnd;
229 // Finding the corresponding CPP Application entityHandler for a given resource
230 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
231 entityHandlerEntry = OC::details::entityHandlerMap.find(entityHandlerRequest->resource);
232 entityHandlerEnd = OC::details::entityHandlerMap.end();
235 if(entityHandlerEntry != entityHandlerEnd)
237 // Call CPP Application Entity Handler
238 if(entityHandlerEntry->second)
240 result = entityHandlerEntry->second(pRequest);
244 oclog() << "C stack should not call again for parent resource\n";
250 oclog() << "No entity handler found." << endl;
259 InProcServerWrapper::InProcServerWrapper(
260 std::weak_ptr<std::recursive_mutex> csdkLock, PlatformConfig cfg)
261 : m_threadRun(false),
262 m_csdkLock(csdkLock),
268 OCStackResult InProcServerWrapper::start()
270 OIC_LOG_V(INFO, TAG, "start ocplatform for server : %d", m_cfg.transportType);
273 if(m_cfg.mode == ModeType::Server)
275 initType = OC_SERVER;
277 else if (m_cfg.mode == ModeType::Both)
279 initType = OC_CLIENT_SERVER;
281 else if (m_cfg.mode == ModeType::Gateway)
283 initType = OC_GATEWAY;
287 throw InitializeException(OC::InitException::NOT_CONFIGURED_AS_SERVER,
288 OC_STACK_INVALID_PARAM);
291 OCTransportFlags serverFlags =
292 static_cast<OCTransportFlags>(m_cfg.serverConnectivity & CT_MASK_FLAGS);
293 OCTransportFlags clientFlags =
294 static_cast<OCTransportFlags>(m_cfg.clientConnectivity & CT_MASK_FLAGS);
295 OCStackResult result = OCInit2(initType, serverFlags, clientFlags,
296 m_cfg.transportType);
298 if(OC_STACK_OK != result)
300 throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
303 if (false == m_threadRun)
306 m_processThread = std::thread(&InProcServerWrapper::processFunc, this);
311 OCStackResult InProcServerWrapper::stop()
313 OIC_LOG(INFO, TAG, "stop");
315 if(m_processThread.joinable())
318 m_processThread.join();
321 OCStackResult res = OCStop();
323 if (OC_STACK_OK != res)
325 throw InitializeException(OC::InitException::STACK_TERMINATE_ERROR, res);
331 void InProcServerWrapper::processFunc()
333 auto cLock = m_csdkLock.lock();
334 while(cLock && m_threadRun)
336 OCStackResult result;
339 std::lock_guard<std::recursive_mutex> lock(*cLock);
340 result = OCProcess();
343 if(OC_STACK_ERROR == result)
345 oclog() << "OCProcess failed with result " << result <<std::flush;
346 // ...the value of variable result is simply ignored for now.
349 std::this_thread::sleep_for(std::chrono::milliseconds(10));
353 OCStackResult InProcServerWrapper::registerDeviceInfo(const OCDeviceInfo deviceInfo)
355 auto cLock = m_csdkLock.lock();
356 OCStackResult result = OC_STACK_ERROR;
359 std::lock_guard<std::recursive_mutex> lock(*cLock);
360 result = OCSetDeviceInfo(deviceInfo);
365 OCStackResult InProcServerWrapper::registerPlatformInfo(const OCPlatformInfo platformInfo)
367 auto cLock = m_csdkLock.lock();
368 OCStackResult result = OC_STACK_ERROR;
371 std::lock_guard<std::recursive_mutex> lock(*cLock);
372 result = OCSetPlatformInfo(platformInfo);
377 OCStackResult InProcServerWrapper::setPropertyValue(OCPayloadType type, const std::string& propName,
378 const std::string& propValue)
380 auto cLock = m_csdkLock.lock();
381 OCStackResult result = OC_STACK_ERROR;
384 std::lock_guard<std::recursive_mutex> lock(*cLock);
385 result = OCSetPropertyValue(type, propName.c_str(), (void *)propValue.c_str());
390 OCStackResult InProcServerWrapper::getPropertyValue(OCPayloadType type, const std::string& propName,
391 std::string& propValue)
393 auto cLock = m_csdkLock.lock();
394 OCStackResult result = OC_STACK_ERROR;
397 std::lock_guard<std::recursive_mutex> lock(*cLock);
398 result = OCGetPropertyValue(type, propName.c_str(), (void **)propValue.c_str());
403 OCStackResult InProcServerWrapper::registerResource(
404 OCResourceHandle& resourceHandle,
405 std::string& resourceURI,
406 const std::string& resourceTypeName,
407 const std::string& resourceInterface,
408 EntityHandler& eHandler,
409 uint8_t resourceProperties)
412 OCStackResult result = OC_STACK_ERROR;
414 auto cLock = m_csdkLock.lock();
418 std::lock_guard<std::recursive_mutex> lock(*cLock);
422 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
423 resourceTypeName.c_str(), // const char * resourceTypeName
424 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
425 resourceURI.c_str(), // const char * uri
426 EntityHandlerWrapper, // OCEntityHandler entityHandler
428 resourceProperties // uint8_t resourceProperties
433 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
434 resourceTypeName.c_str(), // const char * resourceTypeName
435 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
436 resourceURI.c_str(), // const char * uri
437 NULL, // OCEntityHandler entityHandler
439 resourceProperties // uint8_t resourceProperties
443 if(result != OC_STACK_OK)
445 resourceHandle = (OCResourceHandle) 0;
449 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
450 OC::details::entityHandlerMap[resourceHandle] = eHandler;
451 OC::details::resourceUriMap[resourceHandle] = resourceURI;
456 result = OC_STACK_ERROR;
464 OCStackResult InProcServerWrapper::setDefaultDeviceEntityHandler
465 (EntityHandler entityHandler)
467 OCStackResult result = OC_STACK_ERROR;
470 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
471 OC::details::defaultDeviceEntityHandler = entityHandler;
476 result = OCSetDefaultDeviceEntityHandler(DefaultEntityHandlerWrapper, NULL);
480 // If Null passed we unset
481 result = OCSetDefaultDeviceEntityHandler(NULL, NULL);
487 OCStackResult InProcServerWrapper::unregisterResource(const OCResourceHandle& resourceHandle)
489 auto cLock = m_csdkLock.lock();
490 OCStackResult result = OC_STACK_ERROR;
494 std::lock_guard<std::recursive_mutex> lock(*cLock);
495 result = OCDeleteResource(resourceHandle);
497 if(result == OC_STACK_OK)
499 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
500 OC::details::resourceUriMap.erase(resourceHandle);
504 throw OCException(OC::Exception::RESOURCE_UNREG_FAILED, result);
509 result = OC_STACK_ERROR;
515 OCStackResult InProcServerWrapper::bindTypeToResource(const OCResourceHandle& resourceHandle,
516 const std::string& resourceTypeName)
518 auto cLock = m_csdkLock.lock();
519 OCStackResult result;
522 std::lock_guard<std::recursive_mutex> lock(*cLock);
523 result = OCBindResourceTypeToResource(resourceHandle, resourceTypeName.c_str());
527 result = OC_STACK_ERROR;
530 if (result != OC_STACK_OK)
532 throw OCException(OC::Exception::BIND_TYPE_FAILED, result);
537 OCStackResult InProcServerWrapper::resetResourceTypes(const OCResourceHandle& resourceHandle,
538 const std::string& newResourceType)
540 auto cLock = m_csdkLock.lock();
541 OCStackResult result;
544 std::lock_guard<std::recursive_mutex> lock(*cLock);
545 result = OCResetResourceTypes(resourceHandle, newResourceType.c_str());
549 result = OC_STACK_ERROR;
552 if (result != OC_STACK_OK)
554 throw OCException(OC::Exception::BIND_TYPE_FAILED, result);
559 OCStackResult InProcServerWrapper::bindInterfaceToResource(
560 const OCResourceHandle& resourceHandle,
561 const std::string& resourceInterfaceName)
563 auto cLock = m_csdkLock.lock();
564 OCStackResult result;
567 std::lock_guard<std::recursive_mutex> lock(*cLock);
568 result = OCBindResourceInterfaceToResource(resourceHandle,
569 resourceInterfaceName.c_str());
573 result = OC_STACK_ERROR;
576 if (result != OC_STACK_OK)
578 throw OCException(OC::Exception::BIND_INTERFACE_FAILED, result);
583 OCStackResult InProcServerWrapper::resetResourceInterfaces(
584 const OCResourceHandle& resourceHandle,
585 const std::string& newResourceInterface)
587 auto cLock = m_csdkLock.lock();
588 OCStackResult result;
591 std::lock_guard<std::recursive_mutex> lock(*cLock);
592 result = OCResetResourceInterfaces(resourceHandle,
593 newResourceInterface.c_str());
597 result = OC_STACK_ERROR;
600 if (result != OC_STACK_OK)
602 throw OCException(OC::Exception::BIND_INTERFACE_FAILED, result);
607 OCStackResult InProcServerWrapper::startPresence(const unsigned int seconds)
609 auto cLock = m_csdkLock.lock();
610 OCStackResult result = OC_STACK_ERROR;
613 std::lock_guard<std::recursive_mutex> lock(*cLock);
614 result = OCStartPresence(seconds);
617 if(result != OC_STACK_OK)
619 throw OCException(OC::Exception::START_PRESENCE_FAILED, result);
624 OCStackResult InProcServerWrapper::stopPresence()
626 auto cLock = m_csdkLock.lock();
627 OCStackResult result = OC_STACK_ERROR;
630 std::lock_guard<std::recursive_mutex> lock(*cLock);
631 result = OCStopPresence();
634 if(result != OC_STACK_OK)
636 throw OCException(OC::Exception::END_PRESENCE_FAILED, result);
641 OCStackResult InProcServerWrapper::sendResponse(
642 const std::shared_ptr<OCResourceResponse> pResponse)
644 auto cLock = m_csdkLock.lock();
645 OCStackResult result = OC_STACK_ERROR;
649 result = OC_STACK_MALFORMED_RESPONSE;
650 throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_MALFORMED_RESPONSE);
654 OCEntityHandlerResponse response;
655 // OCRepPayload* payLoad = pResponse->getPayload();
656 HeaderOptions serverHeaderOptions = pResponse->getHeaderOptions();
658 response.requestHandle = pResponse->getRequestHandle();
659 response.resourceHandle = pResponse->getResourceHandle();
660 response.ehResult = pResponse->getResponseResult();
662 response.payload = reinterpret_cast<OCPayload*>(pResponse->getPayload());
664 response.persistentBufferFlag = 0;
666 response.numSendVendorSpecificHeaderOptions = serverHeaderOptions.size();
668 for (auto it=serverHeaderOptions.begin(); it != serverHeaderOptions.end(); ++it)
670 response.sendVendorSpecificHeaderOptions[i].protocolID = OC_COAP_ID;
671 response.sendVendorSpecificHeaderOptions[i].optionID =
672 static_cast<uint16_t>(it->getOptionID());
673 response.sendVendorSpecificHeaderOptions[i].optionLength =
674 (it->getOptionData()).length() + 1;
675 std::string optionData = it->getOptionData();
676 std::copy(optionData.begin(),
678 response.sendVendorSpecificHeaderOptions[i].optionData);
679 response.sendVendorSpecificHeaderOptions[i].optionData[it->getOptionData().length()]
684 if(OC_EH_RESOURCE_CREATED == response.ehResult)
686 pResponse->getNewResourceUri().copy(response.resourceUri,
687 sizeof (response.resourceUri) - 1);
688 response.resourceUri[pResponse->getNewResourceUri().length()] = '\0';
693 std::lock_guard<std::recursive_mutex> lock(*cLock);
694 result = OCDoResponse(&response);
698 result = OC_STACK_ERROR;
701 if(result != OC_STACK_OK)
703 oclog() << "Error sending response\n";
706 OCPayloadDestroy(response.payload);
711 OCStackResult InProcServerWrapper::notifyAllObservers(OCResourceHandle resourceHandle,
712 QualityOfService QoS)
714 auto cLock = m_csdkLock.lock();
715 OCStackResult result = OC_STACK_ERROR;
718 std::lock_guard<std::recursive_mutex> lock(*cLock);
719 result = OCNotifyAllObservers(resourceHandle, static_cast<OCQualityOfService>(QoS));
725 OCStackResult InProcServerWrapper::notifyListOfObservers(OCResourceHandle resourceHandle,
726 ObservationIds& observationIds,
727 const std::shared_ptr<OCResourceResponse> pResponse,
728 QualityOfService QoS)
732 return OC_STACK_ERROR;
735 auto cLock = m_csdkLock.lock();
736 OCStackResult result = OC_STACK_ERROR;
739 std::lock_guard<std::recursive_mutex> lock(*cLock);
741 OCRepPayload* pl = pResponse->getResourceRepresentation().getPayload();
742 result = OCNotifyListOfObservers(resourceHandle,
744 observationIds.size(),
746 static_cast<OCQualityOfService>(QoS));
747 OCRepPayloadDestroy(pl);
750 if (result != OC_STACK_OK)
752 throw OCException(OC::Exception::NOTIFY_LIST_OBSERVERS_FAILED, result);
757 InProcServerWrapper::~InProcServerWrapper()
763 catch (InitializeException &e)
765 oclog() << "Exception in stop"<< e.what() << std::flush;