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(std::string(reinterpret_cast<const char*>
108 (entityHandlerRequest->reqJSONPayload)));
110 else if(OC_REST_POST == entityHandlerRequest->method)
112 pRequest->setRequestType(OC::PlatformCommands::POST);
113 pRequest->setPayload(std::string(reinterpret_cast<const char*>
114 (entityHandlerRequest->reqJSONPayload)));
116 else if(OC_REST_DELETE == entityHandlerRequest->method)
118 pRequest->setRequestType(OC::PlatformCommands::DELETE);
123 if(flag & OC_OBSERVE_FLAG)
125 pRequest->setRequestHandlerFlag(
126 OC::RequestHandlerFlag::RequestFlag | OC::RequestHandlerFlag::ObserverFlag);
128 if(entityHandlerRequest)
130 OC::ObservationInfo observationInfo;
131 observationInfo.action = (OC::ObserveAction) entityHandlerRequest->obsInfo.action;
132 observationInfo.obsId = entityHandlerRequest->obsInfo.obsId;
133 pRequest->setObservationInfo(observationInfo);
138 OCEntityHandlerResult DefaultEntityHandlerWrapper(OCEntityHandlerFlag flag,
139 OCEntityHandlerRequest * entityHandlerRequest,
141 void * callbackParam)
143 OCEntityHandlerResult result = OC_EH_ERROR;
145 OC::oclog() << "In Default device entity handler wrapper";
147 if(NULL == entityHandlerRequest)
149 oclog() << "Entity handler request is NULL.";
153 auto pRequest = std::make_shared<OC::OCResourceRequest>();
155 formResourceRequest(flag, entityHandlerRequest, pRequest);
157 pRequest->setResourceUri(std::string(uri));
159 EntityHandler defHandler;
161 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
162 defHandler = OC::details::defaultDeviceEntityHandler;
167 result = defHandler(pRequest);
171 oclog() << "Default device entity handler was not set.";
179 OCEntityHandlerResult EntityHandlerWrapper(OCEntityHandlerFlag flag,
180 OCEntityHandlerRequest * entityHandlerRequest,
183 OCEntityHandlerResult result = OC_EH_ERROR;
185 oclog() << "\nIn entity handler wrapper: " << endl;
187 if(NULL == entityHandlerRequest)
189 oclog() << "Entity handler request is NULL." << endl;
193 auto pRequest = std::make_shared<OC::OCResourceRequest>();
195 formResourceRequest(flag, entityHandlerRequest, pRequest);
197 std::map <OCResourceHandle, std::string>::iterator resourceUriEntry;
198 std::map <OCResourceHandle, std::string>::iterator resourceUriEnd;
200 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
201 resourceUriEntry = OC::details::resourceUriMap.find(entityHandlerRequest->resource);
202 resourceUriEnd = OC::details::resourceUriMap.end();
204 // Finding the corresponding URI for a resource handle and set the URI in the request
205 if(resourceUriEntry != resourceUriEnd)
207 pRequest->setResourceUri(resourceUriEntry->second);
211 oclog() << "Resource handle not found; Resource URI not set in request";
215 std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEntry;
216 std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEnd;
218 // Finding the corresponding CPP Application entityHandler for a given resource
219 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
220 entityHandlerEntry = OC::details::entityHandlerMap.find(entityHandlerRequest->resource);
221 entityHandlerEnd = OC::details::entityHandlerMap.end();
224 if(entityHandlerEntry != entityHandlerEnd)
226 // Call CPP Application Entity Handler
227 if(entityHandlerEntry->second)
229 result = entityHandlerEntry->second(pRequest);
233 oclog() << "C stack should not call again for parent resource\n";
239 oclog() << "No entity handler found." << endl;
248 InProcServerWrapper::InProcServerWrapper(
249 std::weak_ptr<std::recursive_mutex> csdkLock, PlatformConfig cfg)
250 : m_csdkLock(csdkLock)
254 if(cfg.mode == ModeType::Server)
256 initType = OC_SERVER;
258 else if (cfg.mode == ModeType::Both)
260 initType = OC_CLIENT_SERVER;
264 throw InitializeException(OC::InitException::NOT_CONFIGURED_AS_SERVER,
265 OC_STACK_INVALID_PARAM);
268 OCTransportFlags serverFlags =
269 static_cast<OCTransportFlags>(cfg.serverConnectivity & CT_MASK_FLAGS);
270 OCTransportFlags clientFlags =
271 static_cast<OCTransportFlags>(cfg.clientConnectivity & CT_MASK_FLAGS);
272 OCStackResult result = OCInit1(initType, serverFlags, clientFlags);
274 if(OC_STACK_OK != result)
276 throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
280 m_processThread = std::thread(&InProcServerWrapper::processFunc, this);
283 void InProcServerWrapper::processFunc()
285 auto cLock = m_csdkLock.lock();
286 while(cLock && m_threadRun)
288 OCStackResult result;
291 std::lock_guard<std::recursive_mutex> lock(*cLock);
292 result = OCProcess();
295 if(OC_STACK_ERROR == result)
297 oclog() << "OCProcess failed with result " << result <<std::flush;
298 // ...the value of variable result is simply ignored for now.
301 std::this_thread::sleep_for(std::chrono::milliseconds(10));
305 OCStackResult InProcServerWrapper::registerDeviceInfo(const OCDeviceInfo deviceInfo)
307 auto cLock = m_csdkLock.lock();
308 OCStackResult result = OC_STACK_ERROR;
311 std::lock_guard<std::recursive_mutex> lock(*cLock);
312 result = OCSetDeviceInfo(deviceInfo);
317 OCStackResult InProcServerWrapper::registerPlatformInfo(const OCPlatformInfo platformInfo)
319 auto cLock = m_csdkLock.lock();
320 OCStackResult result = OC_STACK_ERROR;
323 std::lock_guard<std::recursive_mutex> lock(*cLock);
324 result = OCSetPlatformInfo(platformInfo);
329 OCStackResult InProcServerWrapper::registerResource(
330 OCResourceHandle& resourceHandle,
331 std::string& resourceURI,
332 const std::string& resourceTypeName,
333 const std::string& resourceInterface,
334 EntityHandler& eHandler,
335 uint8_t resourceProperties)
338 OCStackResult result = OC_STACK_ERROR;
340 auto cLock = m_csdkLock.lock();
344 std::lock_guard<std::recursive_mutex> lock(*cLock);
348 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
349 resourceTypeName.c_str(), // const char * resourceTypeName
350 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
351 resourceURI.c_str(), // const char * uri
352 EntityHandlerWrapper, // OCEntityHandler entityHandler
354 resourceProperties // uint8_t resourceProperties
359 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
360 resourceTypeName.c_str(), // const char * resourceTypeName
361 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
362 resourceURI.c_str(), // const char * uri
363 NULL, // OCEntityHandler entityHandler
365 resourceProperties // uint8_t resourceProperties
369 if(result != OC_STACK_OK)
371 resourceHandle = (OCResourceHandle) 0;
375 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
376 OC::details::entityHandlerMap[resourceHandle] = eHandler;
377 OC::details::resourceUriMap[resourceHandle] = resourceURI;
382 result = OC_STACK_ERROR;
390 OCStackResult InProcServerWrapper::setDefaultDeviceEntityHandler
391 (EntityHandler entityHandler)
393 OCStackResult result = OC_STACK_ERROR;
396 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
397 OC::details::defaultDeviceEntityHandler = entityHandler;
402 result = OCSetDefaultDeviceEntityHandler(DefaultEntityHandlerWrapper, NULL);
406 // If Null passed we unset
407 result = OCSetDefaultDeviceEntityHandler(NULL, NULL);
413 OCStackResult InProcServerWrapper::unregisterResource(const OCResourceHandle& resourceHandle)
415 auto cLock = m_csdkLock.lock();
416 OCStackResult result = OC_STACK_ERROR;
420 std::lock_guard<std::recursive_mutex> lock(*cLock);
421 result = OCDeleteResource(resourceHandle);
423 if(result == OC_STACK_OK)
425 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
426 OC::details::resourceUriMap.erase(resourceHandle);
430 throw OCException(OC::Exception::RESOURCE_UNREG_FAILED, result);
435 result = OC_STACK_ERROR;
441 OCStackResult InProcServerWrapper::bindTypeToResource(const OCResourceHandle& resourceHandle,
442 const std::string& resourceTypeName)
444 auto cLock = m_csdkLock.lock();
445 OCStackResult result;
448 std::lock_guard<std::recursive_mutex> lock(*cLock);
449 result = OCBindResourceTypeToResource(resourceHandle, resourceTypeName.c_str());
453 result = OC_STACK_ERROR;
456 if (result != OC_STACK_OK)
458 throw OCException(OC::Exception::BIND_TYPE_FAILED, result);
463 OCStackResult InProcServerWrapper::bindInterfaceToResource(
464 const OCResourceHandle& resourceHandle,
465 const std::string& resourceInterfaceName)
467 auto cLock = m_csdkLock.lock();
468 OCStackResult result;
471 std::lock_guard<std::recursive_mutex> lock(*cLock);
472 result = OCBindResourceInterfaceToResource(resourceHandle,
473 resourceInterfaceName.c_str());
477 result = OC_STACK_ERROR;
480 if (result != OC_STACK_OK)
482 throw OCException(OC::Exception::BIND_INTERFACE_FAILED, result);
487 OCStackResult InProcServerWrapper::startPresence(const unsigned int seconds)
489 auto cLock = m_csdkLock.lock();
490 OCStackResult result = OC_STACK_ERROR;
493 std::lock_guard<std::recursive_mutex> lock(*cLock);
494 result = OCStartPresence(seconds);
497 if(result != OC_STACK_OK)
499 throw OCException(OC::Exception::START_PRESENCE_FAILED, result);
504 OCStackResult InProcServerWrapper::stopPresence()
506 auto cLock = m_csdkLock.lock();
507 OCStackResult result = OC_STACK_ERROR;
510 std::lock_guard<std::recursive_mutex> lock(*cLock);
511 result = OCStopPresence();
514 if(result != OC_STACK_OK)
516 throw OCException(OC::Exception::END_PRESENCE_FAILED, result);
521 OCStackResult InProcServerWrapper::sendResponse(
522 const std::shared_ptr<OCResourceResponse> pResponse)
524 auto cLock = m_csdkLock.lock();
525 OCStackResult result = OC_STACK_ERROR;
529 result = OC_STACK_MALFORMED_RESPONSE;
530 throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_MALFORMED_RESPONSE);
534 OCEntityHandlerResponse response;
535 std::string payLoad = pResponse->getPayload();
536 HeaderOptions serverHeaderOptions = pResponse->getHeaderOptions();
538 response.requestHandle = pResponse->getRequestHandle();
539 response.resourceHandle = pResponse->getResourceHandle();
540 response.ehResult = pResponse->getResponseResult();
542 response.payload = static_cast<char*>(OICMalloc(payLoad.length() + 1));
543 if(!response.payload)
545 result = OC_STACK_NO_MEMORY;
546 throw OCException(OC::Exception::NO_MEMORY, OC_STACK_NO_MEMORY);
549 payLoad.copy(response.payload, payLoad.length());
550 response.payload[payLoad.length()] = '\0';
551 response.payloadSize = payLoad.length() + 1;
552 response.persistentBufferFlag = 0;
554 response.numSendVendorSpecificHeaderOptions = serverHeaderOptions.size();
556 for (auto it=serverHeaderOptions.begin(); it != serverHeaderOptions.end(); ++it)
558 response.sendVendorSpecificHeaderOptions[i].protocolID = OC_COAP_ID;
559 response.sendVendorSpecificHeaderOptions[i].optionID =
560 static_cast<uint16_t>(it->getOptionID());
561 response.sendVendorSpecificHeaderOptions[i].optionLength =
562 (it->getOptionData()).length() + 1;
563 std::string optionData = it->getOptionData();
564 std::copy(optionData.begin(),
566 response.sendVendorSpecificHeaderOptions[i].optionData);
567 response.sendVendorSpecificHeaderOptions[i].optionData[it->getOptionData().length()]
572 if(OC_EH_RESOURCE_CREATED == response.ehResult)
574 pResponse->getNewResourceUri().copy(response.resourceUri,
575 sizeof (response.resourceUri) - 1);
576 response.resourceUri[pResponse->getNewResourceUri().length()] = '\0';
581 std::lock_guard<std::recursive_mutex> lock(*cLock);
582 result = OCDoResponse(&response);
586 OICFree(response.payload);
587 result = OC_STACK_ERROR;
590 if(result != OC_STACK_OK)
592 oclog() << "Error sending response\n";
598 InProcServerWrapper::~InProcServerWrapper()
600 if(m_processThread.joinable())
603 m_processThread.join();