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;
132 observationInfo.connectivityType = static_cast<OCConnectivityType>(
133 (entityHandlerRequest->devAddr.adapter << CT_ADAPTER_SHIFT) |
134 (entityHandlerRequest->devAddr.flags & CT_MASK_FLAGS));
135 observationInfo.address = entityHandlerRequest->devAddr.addr;
136 observationInfo.port = entityHandlerRequest->devAddr.port;
137 pRequest->setObservationInfo(observationInfo);
142 OCEntityHandlerResult DefaultEntityHandlerWrapper(OCEntityHandlerFlag flag,
143 OCEntityHandlerRequest * entityHandlerRequest,
145 void * /*callbackParam*/)
147 OCEntityHandlerResult result = OC_EH_ERROR;
149 OC::oclog() << "In Default device entity handler wrapper";
151 if(NULL == entityHandlerRequest)
153 oclog() << "Entity handler request is NULL.";
157 auto pRequest = std::make_shared<OC::OCResourceRequest>();
159 formResourceRequest(flag, entityHandlerRequest, pRequest);
161 pRequest->setResourceUri(std::string(uri));
163 EntityHandler defHandler;
165 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
166 defHandler = OC::details::defaultDeviceEntityHandler;
171 result = defHandler(pRequest);
175 oclog() << "Default device entity handler was not set.";
183 OCEntityHandlerResult EntityHandlerWrapper(OCEntityHandlerFlag flag,
184 OCEntityHandlerRequest * entityHandlerRequest,
185 void* /*callbackParam*/)
187 OCEntityHandlerResult result = OC_EH_ERROR;
189 oclog() << "\nIn entity handler wrapper: " << endl;
191 if(NULL == entityHandlerRequest)
193 oclog() << "Entity handler request is NULL." << endl;
197 auto pRequest = std::make_shared<OC::OCResourceRequest>();
199 formResourceRequest(flag, entityHandlerRequest, pRequest);
201 std::map <OCResourceHandle, std::string>::iterator resourceUriEntry;
202 std::map <OCResourceHandle, std::string>::iterator resourceUriEnd;
204 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
205 resourceUriEntry = OC::details::resourceUriMap.find(entityHandlerRequest->resource);
206 resourceUriEnd = OC::details::resourceUriMap.end();
208 // Finding the corresponding URI for a resource handle and set the URI in the request
209 if(resourceUriEntry != resourceUriEnd)
211 pRequest->setResourceUri(resourceUriEntry->second);
215 oclog() << "Resource handle not found; Resource URI not set in request";
219 std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEntry;
220 std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEnd;
222 // Finding the corresponding CPP Application entityHandler for a given resource
223 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
224 entityHandlerEntry = OC::details::entityHandlerMap.find(entityHandlerRequest->resource);
225 entityHandlerEnd = OC::details::entityHandlerMap.end();
228 if(entityHandlerEntry != entityHandlerEnd)
230 // Call CPP Application Entity Handler
231 if(entityHandlerEntry->second)
233 result = entityHandlerEntry->second(pRequest);
237 oclog() << "C stack should not call again for parent resource\n";
243 oclog() << "No entity handler found." << endl;
252 InProcServerWrapper::InProcServerWrapper(
253 std::weak_ptr<std::recursive_mutex> csdkLock, PlatformConfig cfg)
254 : m_csdkLock(csdkLock)
258 if(cfg.mode == ModeType::Server)
260 initType = OC_SERVER;
262 else if (cfg.mode == ModeType::Both)
264 initType = OC_CLIENT_SERVER;
268 throw InitializeException(OC::InitException::NOT_CONFIGURED_AS_SERVER,
269 OC_STACK_INVALID_PARAM);
272 OCTransportFlags serverFlags =
273 static_cast<OCTransportFlags>(cfg.serverConnectivity & CT_MASK_FLAGS);
274 OCTransportFlags clientFlags =
275 static_cast<OCTransportFlags>(cfg.clientConnectivity & CT_MASK_FLAGS);
276 OCStackResult result = OCInit1(initType, serverFlags, clientFlags);
278 if(OC_STACK_OK != result)
280 throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
284 m_processThread = std::thread(&InProcServerWrapper::processFunc, this);
287 void InProcServerWrapper::processFunc()
289 auto cLock = m_csdkLock.lock();
290 while(cLock && m_threadRun)
292 OCStackResult result;
295 std::lock_guard<std::recursive_mutex> lock(*cLock);
296 result = OCProcess();
299 if(OC_STACK_ERROR == result)
301 oclog() << "OCProcess failed with result " << result <<std::flush;
302 // ...the value of variable result is simply ignored for now.
305 std::this_thread::sleep_for(std::chrono::milliseconds(10));
309 OCStackResult InProcServerWrapper::registerDeviceInfo(const OCDeviceInfo deviceInfo)
311 auto cLock = m_csdkLock.lock();
312 OCStackResult result = OC_STACK_ERROR;
315 std::lock_guard<std::recursive_mutex> lock(*cLock);
316 result = OCSetDeviceInfo(deviceInfo);
321 OCStackResult InProcServerWrapper::registerPlatformInfo(const OCPlatformInfo platformInfo)
323 auto cLock = m_csdkLock.lock();
324 OCStackResult result = OC_STACK_ERROR;
327 std::lock_guard<std::recursive_mutex> lock(*cLock);
328 result = OCSetPlatformInfo(platformInfo);
333 OCStackResult InProcServerWrapper::registerResource(
334 OCResourceHandle& resourceHandle,
335 std::string& resourceURI,
336 const std::string& resourceTypeName,
337 const std::string& resourceInterface,
338 EntityHandler& eHandler,
339 uint8_t resourceProperties)
342 OCStackResult result = OC_STACK_ERROR;
344 auto cLock = m_csdkLock.lock();
348 std::lock_guard<std::recursive_mutex> lock(*cLock);
352 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
353 resourceTypeName.c_str(), // const char * resourceTypeName
354 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
355 resourceURI.c_str(), // const char * uri
356 EntityHandlerWrapper, // OCEntityHandler entityHandler
358 resourceProperties // uint8_t resourceProperties
363 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
364 resourceTypeName.c_str(), // const char * resourceTypeName
365 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
366 resourceURI.c_str(), // const char * uri
367 NULL, // OCEntityHandler entityHandler
369 resourceProperties // uint8_t resourceProperties
373 if(result != OC_STACK_OK)
375 resourceHandle = (OCResourceHandle) 0;
379 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
380 OC::details::entityHandlerMap[resourceHandle] = eHandler;
381 OC::details::resourceUriMap[resourceHandle] = resourceURI;
386 result = OC_STACK_ERROR;
394 OCStackResult InProcServerWrapper::setDefaultDeviceEntityHandler
395 (EntityHandler entityHandler)
397 OCStackResult result = OC_STACK_ERROR;
400 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
401 OC::details::defaultDeviceEntityHandler = entityHandler;
406 result = OCSetDefaultDeviceEntityHandler(DefaultEntityHandlerWrapper, NULL);
410 // If Null passed we unset
411 result = OCSetDefaultDeviceEntityHandler(NULL, NULL);
417 OCStackResult InProcServerWrapper::unregisterResource(const OCResourceHandle& resourceHandle)
419 auto cLock = m_csdkLock.lock();
420 OCStackResult result = OC_STACK_ERROR;
424 std::lock_guard<std::recursive_mutex> lock(*cLock);
425 result = OCDeleteResource(resourceHandle);
427 if(result == OC_STACK_OK)
429 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
430 OC::details::resourceUriMap.erase(resourceHandle);
434 throw OCException(OC::Exception::RESOURCE_UNREG_FAILED, result);
439 result = OC_STACK_ERROR;
445 OCStackResult InProcServerWrapper::bindTypeToResource(const OCResourceHandle& resourceHandle,
446 const std::string& resourceTypeName)
448 auto cLock = m_csdkLock.lock();
449 OCStackResult result;
452 std::lock_guard<std::recursive_mutex> lock(*cLock);
453 result = OCBindResourceTypeToResource(resourceHandle, resourceTypeName.c_str());
457 result = OC_STACK_ERROR;
460 if (result != OC_STACK_OK)
462 throw OCException(OC::Exception::BIND_TYPE_FAILED, result);
467 OCStackResult InProcServerWrapper::bindInterfaceToResource(
468 const OCResourceHandle& resourceHandle,
469 const std::string& resourceInterfaceName)
471 auto cLock = m_csdkLock.lock();
472 OCStackResult result;
475 std::lock_guard<std::recursive_mutex> lock(*cLock);
476 result = OCBindResourceInterfaceToResource(resourceHandle,
477 resourceInterfaceName.c_str());
481 result = OC_STACK_ERROR;
484 if (result != OC_STACK_OK)
486 throw OCException(OC::Exception::BIND_INTERFACE_FAILED, result);
491 OCStackResult InProcServerWrapper::startPresence(const unsigned int seconds)
493 auto cLock = m_csdkLock.lock();
494 OCStackResult result = OC_STACK_ERROR;
497 std::lock_guard<std::recursive_mutex> lock(*cLock);
498 result = OCStartPresence(seconds);
501 if(result != OC_STACK_OK)
503 throw OCException(OC::Exception::START_PRESENCE_FAILED, result);
508 OCStackResult InProcServerWrapper::stopPresence()
510 auto cLock = m_csdkLock.lock();
511 OCStackResult result = OC_STACK_ERROR;
514 std::lock_guard<std::recursive_mutex> lock(*cLock);
515 result = OCStopPresence();
518 if(result != OC_STACK_OK)
520 throw OCException(OC::Exception::END_PRESENCE_FAILED, result);
525 OCStackResult InProcServerWrapper::sendResponse(
526 const std::shared_ptr<OCResourceResponse> pResponse)
528 auto cLock = m_csdkLock.lock();
529 OCStackResult result = OC_STACK_ERROR;
533 result = OC_STACK_MALFORMED_RESPONSE;
534 throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_MALFORMED_RESPONSE);
538 OCEntityHandlerResponse response;
539 // OCRepPayload* payLoad = pResponse->getPayload();
540 HeaderOptions serverHeaderOptions = pResponse->getHeaderOptions();
542 response.requestHandle = pResponse->getRequestHandle();
543 response.resourceHandle = pResponse->getResourceHandle();
544 response.ehResult = pResponse->getResponseResult();
546 response.payload = reinterpret_cast<OCPayload*>(pResponse->getPayload());
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::string optionData = it->getOptionData();
560 std::copy(optionData.begin(),
562 response.sendVendorSpecificHeaderOptions[i].optionData);
563 response.sendVendorSpecificHeaderOptions[i].optionData[it->getOptionData().length()]
568 if(OC_EH_RESOURCE_CREATED == response.ehResult)
570 pResponse->getNewResourceUri().copy(response.resourceUri,
571 sizeof (response.resourceUri) - 1);
572 response.resourceUri[pResponse->getNewResourceUri().length()] = '\0';
577 std::lock_guard<std::recursive_mutex> lock(*cLock);
578 result = OCDoResponse(&response);
582 OICFree(response.payload);
583 result = OC_STACK_ERROR;
586 if(result != OC_STACK_OK)
588 oclog() << "Error sending response\n";
594 InProcServerWrapper::~InProcServerWrapper()
596 if(m_processThread.joinable())
599 m_processThread.join();