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 OCStackResult result = OCInit(cfg.ipAddress.c_str(), cfg.port, initType);
270 if(OC_STACK_OK != result)
272 throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
276 m_processThread = std::thread(&InProcServerWrapper::processFunc, this);
279 void InProcServerWrapper::processFunc()
281 auto cLock = m_csdkLock.lock();
282 while(cLock && m_threadRun)
284 OCStackResult result;
287 std::lock_guard<std::recursive_mutex> lock(*cLock);
288 result = OCProcess();
291 if(OC_STACK_ERROR == result)
293 oclog() << "OCProcess failed with result " << result <<std::flush;
294 // ...the value of variable result is simply ignored for now.
297 std::this_thread::sleep_for(std::chrono::milliseconds(10));
301 OCStackResult InProcServerWrapper::registerDeviceInfo(const OCDeviceInfo deviceInfo)
303 auto cLock = m_csdkLock.lock();
304 OCStackResult result = OC_STACK_ERROR;
307 std::lock_guard<std::recursive_mutex> lock(*cLock);
308 result = OCSetDeviceInfo(deviceInfo);
313 OCStackResult InProcServerWrapper::registerPlatformInfo(const OCPlatformInfo platformInfo)
315 auto cLock = m_csdkLock.lock();
316 OCStackResult result = OC_STACK_ERROR;
319 std::lock_guard<std::recursive_mutex> lock(*cLock);
320 result = OCSetPlatformInfo(platformInfo);
325 OCStackResult InProcServerWrapper::registerResource(
326 OCResourceHandle& resourceHandle,
327 std::string& resourceURI,
328 const std::string& resourceTypeName,
329 const std::string& resourceInterface,
330 EntityHandler& eHandler,
331 uint8_t resourceProperties)
334 OCStackResult result = OC_STACK_ERROR;
336 auto cLock = m_csdkLock.lock();
340 std::lock_guard<std::recursive_mutex> lock(*cLock);
344 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
345 resourceTypeName.c_str(), // const char * resourceTypeName
346 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
347 resourceURI.c_str(), // const char * uri
348 EntityHandlerWrapper, // OCEntityHandler entityHandler
350 resourceProperties // uint8_t resourceProperties
355 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
356 resourceTypeName.c_str(), // const char * resourceTypeName
357 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
358 resourceURI.c_str(), // const char * uri
359 NULL, // OCEntityHandler entityHandler
361 resourceProperties // uint8_t resourceProperties
365 if(result != OC_STACK_OK)
367 resourceHandle = (OCResourceHandle) 0;
371 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
372 OC::details::entityHandlerMap[resourceHandle] = eHandler;
373 OC::details::resourceUriMap[resourceHandle] = resourceURI;
378 result = OC_STACK_ERROR;
386 OCStackResult InProcServerWrapper::setDefaultDeviceEntityHandler
387 (EntityHandler entityHandler)
389 OCStackResult result = OC_STACK_ERROR;
392 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
393 OC::details::defaultDeviceEntityHandler = entityHandler;
398 result = OCSetDefaultDeviceEntityHandler(DefaultEntityHandlerWrapper, NULL);
402 // If Null passed we unset
403 result = OCSetDefaultDeviceEntityHandler(NULL, NULL);
409 OCStackResult InProcServerWrapper::unregisterResource(const OCResourceHandle& resourceHandle)
411 auto cLock = m_csdkLock.lock();
412 OCStackResult result = OC_STACK_ERROR;
416 std::lock_guard<std::recursive_mutex> lock(*cLock);
417 result = OCDeleteResource(resourceHandle);
419 if(result == OC_STACK_OK)
421 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
422 OC::details::resourceUriMap.erase(resourceHandle);
426 throw OCException(OC::Exception::RESOURCE_UNREG_FAILED, result);
431 result = OC_STACK_ERROR;
437 OCStackResult InProcServerWrapper::bindTypeToResource(const OCResourceHandle& resourceHandle,
438 const std::string& resourceTypeName)
440 auto cLock = m_csdkLock.lock();
441 OCStackResult result;
444 std::lock_guard<std::recursive_mutex> lock(*cLock);
445 result = OCBindResourceTypeToResource(resourceHandle, resourceTypeName.c_str());
449 result = OC_STACK_ERROR;
452 if (result != OC_STACK_OK)
454 throw OCException(OC::Exception::BIND_TYPE_FAILED, result);
459 OCStackResult InProcServerWrapper::bindInterfaceToResource(
460 const OCResourceHandle& resourceHandle,
461 const std::string& resourceInterfaceName)
463 auto cLock = m_csdkLock.lock();
464 OCStackResult result;
467 std::lock_guard<std::recursive_mutex> lock(*cLock);
468 result = OCBindResourceInterfaceToResource(resourceHandle,
469 resourceInterfaceName.c_str());
473 result = OC_STACK_ERROR;
476 if (result != OC_STACK_OK)
478 throw OCException(OC::Exception::BIND_INTERFACE_FAILED, result);
483 OCStackResult InProcServerWrapper::startPresence(const unsigned int seconds)
485 auto cLock = m_csdkLock.lock();
486 OCStackResult result = OC_STACK_ERROR;
489 std::lock_guard<std::recursive_mutex> lock(*cLock);
490 result = OCStartPresence(seconds);
493 if(result != OC_STACK_OK)
495 throw OCException(OC::Exception::START_PRESENCE_FAILED, result);
500 OCStackResult InProcServerWrapper::stopPresence()
502 auto cLock = m_csdkLock.lock();
503 OCStackResult result = OC_STACK_ERROR;
506 std::lock_guard<std::recursive_mutex> lock(*cLock);
507 result = OCStopPresence();
510 if(result != OC_STACK_OK)
512 throw OCException(OC::Exception::END_PRESENCE_FAILED, result);
517 OCStackResult InProcServerWrapper::sendResponse(
518 const std::shared_ptr<OCResourceResponse> pResponse)
520 auto cLock = m_csdkLock.lock();
521 OCStackResult result = OC_STACK_ERROR;
525 result = OC_STACK_MALFORMED_RESPONSE;
526 throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_MALFORMED_RESPONSE);
530 OCEntityHandlerResponse response;
531 std::string payLoad = pResponse->getPayload();
532 HeaderOptions serverHeaderOptions = pResponse->getHeaderOptions();
534 response.requestHandle = pResponse->getRequestHandle();
535 response.resourceHandle = pResponse->getResourceHandle();
536 response.ehResult = pResponse->getResponseResult();
538 response.payload = static_cast<char*>(OICMalloc(payLoad.length() + 1));
539 if(!response.payload)
541 result = OC_STACK_NO_MEMORY;
542 throw OCException(OC::Exception::NO_MEMORY, OC_STACK_NO_MEMORY);
545 payLoad.copy(response.payload, payLoad.length());
546 response.payload[payLoad.length()] = '\0';
547 response.payloadSize = payLoad.length() + 1;
548 response.persistentBufferFlag = 0;
550 response.numSendVendorSpecificHeaderOptions = serverHeaderOptions.size();
552 for (auto it=serverHeaderOptions.begin(); it != serverHeaderOptions.end(); ++it)
554 response.sendVendorSpecificHeaderOptions[i].protocolID = OC_COAP_ID;
555 response.sendVendorSpecificHeaderOptions[i].optionID =
556 static_cast<uint16_t>(it->getOptionID());
557 response.sendVendorSpecificHeaderOptions[i].optionLength =
558 (it->getOptionData()).length() + 1;
559 std::copy(it->getOptionData().begin(),
560 it->getOptionData().end(),
561 response.sendVendorSpecificHeaderOptions[i].optionData);
562 response.sendVendorSpecificHeaderOptions[i].optionData[it->getOptionData().length()]
567 if(OC_EH_RESOURCE_CREATED == response.ehResult)
569 pResponse->getNewResourceUri().copy(response.resourceUri,
570 sizeof (response.resourceUri) - 1);
571 response.resourceUri[pResponse->getNewResourceUri().length()] = '\0';
576 std::lock_guard<std::recursive_mutex> lock(*cLock);
577 result = OCDoResponse(&response);
581 OICFree(response.payload);
582 result = OC_STACK_ERROR;
585 if(result != OC_STACK_OK)
587 oclog() << "Error sending response\n";
593 InProcServerWrapper::~InProcServerWrapper()
595 if(m_processThread.joinable())
598 m_processThread.join();