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>
36 #include <oic_malloc.h>
37 #include <OCPlatform.h>
38 #include <OCUtilities.h>
47 std::mutex serverWrapperLock;
48 std::map <OCResourceHandle, OC::EntityHandler> entityHandlerMap;
49 std::map <OCResourceHandle, std::string> resourceUriMap;
50 EntityHandler defaultDeviceEntityHandler = 0;
54 void formResourceRequest(OCEntityHandlerFlag flag,
55 OCEntityHandlerRequest * entityHandlerRequest,
56 std::shared_ptr<OCResourceRequest> pRequest)
58 if(pRequest && entityHandlerRequest)
60 pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
61 pRequest->setResourceHandle(entityHandlerRequest->resource);
64 if(flag & OC_REQUEST_FLAG)
66 pRequest->setRequestHandlerFlag(OC::RequestHandlerFlag::RequestFlag);
68 if(entityHandlerRequest)
70 if(entityHandlerRequest->query)
72 OC::Utilities::QueryParamsKeyVal qp = OC::Utilities::getQueryParams(
73 entityHandlerRequest->query);
77 pRequest->setQueryParams(qp);
80 if(entityHandlerRequest->numRcvdVendorSpecificHeaderOptions != 0)
82 //Set the header options here.
84 std::string optionData;
85 HeaderOptions headerOptions;
88 i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions;
91 optionID = entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionID;
92 optionData = reinterpret_cast<const char*>
93 (entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionData);
94 HeaderOption::OCHeaderOption headerOption(optionID, optionData);
95 headerOptions.push_back(headerOption);
97 pRequest->setHeaderOptions(headerOptions);
100 if(OC_REST_GET == entityHandlerRequest->method)
102 pRequest->setRequestType(OC::PlatformCommands::GET);
104 else if(OC_REST_PUT == entityHandlerRequest->method)
106 pRequest->setRequestType(OC::PlatformCommands::PUT);
107 pRequest->setPayload(entityHandlerRequest->payload);
109 else if(OC_REST_POST == entityHandlerRequest->method)
111 pRequest->setRequestType(OC::PlatformCommands::POST);
112 pRequest->setPayload(entityHandlerRequest->payload);
114 else if(OC_REST_DELETE == entityHandlerRequest->method)
116 pRequest->setRequestType(OC::PlatformCommands::DELETE);
121 if(flag & OC_OBSERVE_FLAG)
123 pRequest->setRequestHandlerFlag(
124 OC::RequestHandlerFlag::RequestFlag | OC::RequestHandlerFlag::ObserverFlag);
126 if(entityHandlerRequest)
128 OC::ObservationInfo observationInfo;
129 observationInfo.action = (OC::ObserveAction) entityHandlerRequest->obsInfo.action;
130 observationInfo.obsId = entityHandlerRequest->obsInfo.obsId;
131 pRequest->setObservationInfo(observationInfo);
136 OCEntityHandlerResult DefaultEntityHandlerWrapper(OCEntityHandlerFlag flag,
137 OCEntityHandlerRequest * entityHandlerRequest,
139 void * /*callbackParam*/)
141 OCEntityHandlerResult result = OC_EH_ERROR;
143 OC::oclog() << "In Default device entity handler wrapper";
145 if(NULL == entityHandlerRequest)
147 oclog() << "Entity handler request is NULL.";
151 auto pRequest = std::make_shared<OC::OCResourceRequest>();
153 formResourceRequest(flag, entityHandlerRequest, pRequest);
155 pRequest->setResourceUri(std::string(uri));
157 EntityHandler defHandler;
159 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
160 defHandler = OC::details::defaultDeviceEntityHandler;
165 result = defHandler(pRequest);
169 oclog() << "Default device entity handler was not set.";
177 OCEntityHandlerResult EntityHandlerWrapper(OCEntityHandlerFlag flag,
178 OCEntityHandlerRequest * entityHandlerRequest,
179 void* /*callbackParam*/)
181 OCEntityHandlerResult result = OC_EH_ERROR;
183 oclog() << "\nIn entity handler wrapper: " << endl;
185 if(NULL == entityHandlerRequest)
187 oclog() << "Entity handler request is NULL." << endl;
191 auto pRequest = std::make_shared<OC::OCResourceRequest>();
193 formResourceRequest(flag, entityHandlerRequest, pRequest);
195 std::map <OCResourceHandle, std::string>::iterator resourceUriEntry;
196 std::map <OCResourceHandle, std::string>::iterator resourceUriEnd;
198 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
199 resourceUriEntry = OC::details::resourceUriMap.find(entityHandlerRequest->resource);
200 resourceUriEnd = OC::details::resourceUriMap.end();
202 // Finding the corresponding URI for a resource handle and set the URI in the request
203 if(resourceUriEntry != resourceUriEnd)
205 pRequest->setResourceUri(resourceUriEntry->second);
209 oclog() << "Resource handle not found; Resource URI not set in request";
213 std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEntry;
214 std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEnd;
216 // Finding the corresponding CPP Application entityHandler for a given resource
217 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
218 entityHandlerEntry = OC::details::entityHandlerMap.find(entityHandlerRequest->resource);
219 entityHandlerEnd = OC::details::entityHandlerMap.end();
222 if(entityHandlerEntry != entityHandlerEnd)
224 // Call CPP Application Entity Handler
225 if(entityHandlerEntry->second)
227 result = entityHandlerEntry->second(pRequest);
231 oclog() << "C stack should not call again for parent resource\n";
237 oclog() << "No entity handler found." << endl;
246 InProcServerWrapper::InProcServerWrapper(
247 std::weak_ptr<std::recursive_mutex> csdkLock, PlatformConfig cfg)
248 : m_csdkLock(csdkLock)
252 if(cfg.mode == ModeType::Server)
254 initType = OC_SERVER;
256 else if (cfg.mode == ModeType::Both)
258 initType = OC_CLIENT_SERVER;
262 throw InitializeException(OC::InitException::NOT_CONFIGURED_AS_SERVER,
263 OC_STACK_INVALID_PARAM);
266 OCTransportFlags serverFlags =
267 static_cast<OCTransportFlags>(cfg.serverConnectivity & CT_MASK_FLAGS);
268 OCTransportFlags clientFlags =
269 static_cast<OCTransportFlags>(cfg.clientConnectivity & CT_MASK_FLAGS);
270 OCStackResult result = OCInit1(initType, serverFlags, clientFlags);
272 if(OC_STACK_OK != result)
274 throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
278 m_processThread = std::thread(&InProcServerWrapper::processFunc, this);
281 void InProcServerWrapper::processFunc()
283 auto cLock = m_csdkLock.lock();
284 while(cLock && m_threadRun)
286 OCStackResult result;
289 std::lock_guard<std::recursive_mutex> lock(*cLock);
290 result = OCProcess();
293 if(OC_STACK_ERROR == result)
295 oclog() << "OCProcess failed with result " << result <<std::flush;
296 // ...the value of variable result is simply ignored for now.
299 std::this_thread::sleep_for(std::chrono::milliseconds(10));
303 OCStackResult InProcServerWrapper::registerDeviceInfo(const OCDeviceInfo deviceInfo)
305 auto cLock = m_csdkLock.lock();
306 OCStackResult result = OC_STACK_ERROR;
309 std::lock_guard<std::recursive_mutex> lock(*cLock);
310 result = OCSetDeviceInfo(deviceInfo);
315 OCStackResult InProcServerWrapper::registerPlatformInfo(const OCPlatformInfo platformInfo)
317 auto cLock = m_csdkLock.lock();
318 OCStackResult result = OC_STACK_ERROR;
321 std::lock_guard<std::recursive_mutex> lock(*cLock);
322 result = OCSetPlatformInfo(platformInfo);
327 OCStackResult InProcServerWrapper::registerResource(
328 OCResourceHandle& resourceHandle,
329 std::string& resourceURI,
330 const std::string& resourceTypeName,
331 const std::string& resourceInterface,
332 EntityHandler& eHandler,
333 uint8_t resourceProperties)
336 OCStackResult result = OC_STACK_ERROR;
338 auto cLock = m_csdkLock.lock();
342 std::lock_guard<std::recursive_mutex> lock(*cLock);
346 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
347 resourceTypeName.c_str(), // const char * resourceTypeName
348 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
349 resourceURI.c_str(), // const char * uri
350 EntityHandlerWrapper, // OCEntityHandler entityHandler
352 resourceProperties // uint8_t resourceProperties
357 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
358 resourceTypeName.c_str(), // const char * resourceTypeName
359 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
360 resourceURI.c_str(), // const char * uri
361 NULL, // OCEntityHandler entityHandler
363 resourceProperties // uint8_t resourceProperties
367 if(result != OC_STACK_OK)
369 resourceHandle = (OCResourceHandle) 0;
373 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
374 OC::details::entityHandlerMap[resourceHandle] = eHandler;
375 OC::details::resourceUriMap[resourceHandle] = resourceURI;
380 result = OC_STACK_ERROR;
388 OCStackResult InProcServerWrapper::setDefaultDeviceEntityHandler
389 (EntityHandler entityHandler)
391 OCStackResult result = OC_STACK_ERROR;
394 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
395 OC::details::defaultDeviceEntityHandler = entityHandler;
400 result = OCSetDefaultDeviceEntityHandler(DefaultEntityHandlerWrapper, NULL);
404 // If Null passed we unset
405 result = OCSetDefaultDeviceEntityHandler(NULL, NULL);
411 OCStackResult InProcServerWrapper::unregisterResource(const OCResourceHandle& resourceHandle)
413 auto cLock = m_csdkLock.lock();
414 OCStackResult result = OC_STACK_ERROR;
418 std::lock_guard<std::recursive_mutex> lock(*cLock);
419 result = OCDeleteResource(resourceHandle);
421 if(result == OC_STACK_OK)
423 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
424 OC::details::resourceUriMap.erase(resourceHandle);
428 throw OCException(OC::Exception::RESOURCE_UNREG_FAILED, result);
433 result = OC_STACK_ERROR;
439 OCStackResult InProcServerWrapper::bindTypeToResource(const OCResourceHandle& resourceHandle,
440 const std::string& resourceTypeName)
442 auto cLock = m_csdkLock.lock();
443 OCStackResult result;
446 std::lock_guard<std::recursive_mutex> lock(*cLock);
447 result = OCBindResourceTypeToResource(resourceHandle, resourceTypeName.c_str());
451 result = OC_STACK_ERROR;
454 if (result != OC_STACK_OK)
456 throw OCException(OC::Exception::BIND_TYPE_FAILED, result);
461 OCStackResult InProcServerWrapper::bindInterfaceToResource(
462 const OCResourceHandle& resourceHandle,
463 const std::string& resourceInterfaceName)
465 auto cLock = m_csdkLock.lock();
466 OCStackResult result;
469 std::lock_guard<std::recursive_mutex> lock(*cLock);
470 result = OCBindResourceInterfaceToResource(resourceHandle,
471 resourceInterfaceName.c_str());
475 result = OC_STACK_ERROR;
478 if (result != OC_STACK_OK)
480 throw OCException(OC::Exception::BIND_INTERFACE_FAILED, result);
485 OCStackResult InProcServerWrapper::startPresence(const unsigned int seconds)
487 auto cLock = m_csdkLock.lock();
488 OCStackResult result = OC_STACK_ERROR;
491 std::lock_guard<std::recursive_mutex> lock(*cLock);
492 result = OCStartPresence(seconds);
495 if(result != OC_STACK_OK)
497 throw OCException(OC::Exception::START_PRESENCE_FAILED, result);
502 OCStackResult InProcServerWrapper::stopPresence()
504 auto cLock = m_csdkLock.lock();
505 OCStackResult result = OC_STACK_ERROR;
508 std::lock_guard<std::recursive_mutex> lock(*cLock);
509 result = OCStopPresence();
512 if(result != OC_STACK_OK)
514 throw OCException(OC::Exception::END_PRESENCE_FAILED, result);
519 OCStackResult InProcServerWrapper::sendResponse(
520 const std::shared_ptr<OCResourceResponse> pResponse)
522 auto cLock = m_csdkLock.lock();
523 OCStackResult result = OC_STACK_ERROR;
527 result = OC_STACK_MALFORMED_RESPONSE;
528 throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_MALFORMED_RESPONSE);
532 OCEntityHandlerResponse response;
533 // OCRepPayload* payLoad = pResponse->getPayload();
534 HeaderOptions serverHeaderOptions = pResponse->getHeaderOptions();
536 response.requestHandle = pResponse->getRequestHandle();
537 response.resourceHandle = pResponse->getResourceHandle();
538 response.ehResult = pResponse->getResponseResult();
540 response.payload = reinterpret_cast<OCPayload*>(pResponse->getPayload());
542 response.persistentBufferFlag = 0;
544 response.numSendVendorSpecificHeaderOptions = serverHeaderOptions.size();
546 for (auto it=serverHeaderOptions.begin(); it != serverHeaderOptions.end(); ++it)
548 response.sendVendorSpecificHeaderOptions[i].protocolID = OC_COAP_ID;
549 response.sendVendorSpecificHeaderOptions[i].optionID =
550 static_cast<uint16_t>(it->getOptionID());
551 response.sendVendorSpecificHeaderOptions[i].optionLength =
552 (it->getOptionData()).length() + 1;
553 std::string optionData = it->getOptionData();
554 std::copy(optionData.begin(),
556 response.sendVendorSpecificHeaderOptions[i].optionData);
557 response.sendVendorSpecificHeaderOptions[i].optionData[it->getOptionData().length()]
562 if(OC_EH_RESOURCE_CREATED == response.ehResult)
564 pResponse->getNewResourceUri().copy(response.resourceUri,
565 sizeof (response.resourceUri) - 1);
566 response.resourceUri[pResponse->getNewResourceUri().length()] = '\0';
571 std::lock_guard<std::recursive_mutex> lock(*cLock);
572 result = OCDoResponse(&response);
576 OICFree(response.payload);
577 result = OC_STACK_ERROR;
580 if(result != OC_STACK_OK)
582 oclog() << "Error sending response\n";
588 InProcServerWrapper::~InProcServerWrapper()
590 if(m_processThread.joinable())
593 m_processThread.join();