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 <OCPlatform.h>
37 #include <OCUtilities.h>
42 std::map <OCResourceHandle, OC::EntityHandler> entityHandlerMap;
43 std::map <OCResourceHandle, std::string> resourceUriMap;
44 EntityHandler defaultDeviceEntityHandler = 0;
46 void formResourceRequest(OCEntityHandlerFlag flag,
47 OCEntityHandlerRequest * entityHandlerRequest,
48 std::shared_ptr<OCResourceRequest> pRequest)
50 pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
51 pRequest->setResourceHandle(entityHandlerRequest->resource);
53 if(flag & OC_INIT_FLAG)
55 pRequest->setRequestHandlerFlag(OC::RequestHandlerFlag::InitFlag);
58 if(flag & OC_REQUEST_FLAG)
60 pRequest->setRequestHandlerFlag(OC::RequestHandlerFlag::RequestFlag);
62 if(entityHandlerRequest)
64 if(entityHandlerRequest->query)
66 std::string querystr(reinterpret_cast<char*>(entityHandlerRequest->query));
68 OC::Utilities::QueryParamsKeyVal qp = OC::Utilities::getQueryParams(querystr);
72 pRequest->setQueryParams(qp);
75 if(entityHandlerRequest->numRcvdVendorSpecificHeaderOptions != 0)
77 //Set the header options here.
79 std::string optionData;
80 HeaderOptions headerOptions;
83 i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions;
86 optionID = entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionID;
87 optionData = reinterpret_cast<const char*>
88 (entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionData);
89 HeaderOption::OCHeaderOption headerOption(optionID, optionData);
90 headerOptions.push_back(headerOption);
92 pRequest->setHeaderOptions(headerOptions);
95 if(OC_REST_GET == entityHandlerRequest->method)
97 pRequest->setRequestType(OC::PlatformCommands::GET);
99 else if(OC_REST_PUT == entityHandlerRequest->method)
101 pRequest->setRequestType(OC::PlatformCommands::PUT);
102 pRequest->setPayload(std::string(reinterpret_cast<const char*>
103 (entityHandlerRequest->reqJSONPayload)));
105 else if(OC_REST_POST == entityHandlerRequest->method)
107 pRequest->setRequestType(OC::PlatformCommands::POST);
108 pRequest->setPayload(std::string(reinterpret_cast<const char*>
109 (entityHandlerRequest->reqJSONPayload)));
111 else if(OC_REST_DELETE == entityHandlerRequest->method)
113 pRequest->setRequestType(OC::PlatformCommands::DELETE);
118 if(flag & OC_OBSERVE_FLAG)
120 pRequest->setRequestHandlerFlag(
121 OC::RequestHandlerFlag::RequestFlag | OC::RequestHandlerFlag::ObserverFlag);
123 if(entityHandlerRequest)
125 OC::ObservationInfo observationInfo;
126 observationInfo.action = (OC::ObserveAction) entityHandlerRequest->obsInfo.action;
127 observationInfo.obsId = entityHandlerRequest->obsInfo.obsId;
128 pRequest->setObservationInfo(observationInfo);
133 OCEntityHandlerResult DefaultEntityHandlerWrapper(OCEntityHandlerFlag flag,
134 OCEntityHandlerRequest * entityHandlerRequest,
137 OCEntityHandlerResult result = OC_EH_ERROR;
139 OC::oclog() << "In Default device entity handler wrapper";
141 if(NULL == entityHandlerRequest)
143 oclog() << "Entity handler request is NULL.";
147 auto pRequest = std::make_shared<OC::OCResourceRequest>();
149 formResourceRequest(flag, entityHandlerRequest, pRequest);
151 pRequest->setResourceUri(std::string(uri));
153 if(defaultDeviceEntityHandler)
155 result = defaultDeviceEntityHandler(pRequest);
159 oclog() << "Default device entity handler was not set.";
167 OCEntityHandlerResult EntityHandlerWrapper(OCEntityHandlerFlag flag,
168 OCEntityHandlerRequest * entityHandlerRequest)
170 OCEntityHandlerResult result = OC_EH_ERROR;
172 oclog() << "\nIn entity handler wrapper: " << endl;
174 if(NULL == entityHandlerRequest)
176 oclog() << "Entity handler request is NULL." << endl;
180 auto pRequest = std::make_shared<OC::OCResourceRequest>();
182 formResourceRequest(flag, entityHandlerRequest, pRequest);
184 // Finding the corresponding URI for a resource handle and set the URI in the request
185 auto resourceUriEntry = resourceUriMap.find(entityHandlerRequest->resource);
186 if(resourceUriEntry != resourceUriMap.end())
188 pRequest->setResourceUri(resourceUriEntry->second);
192 oclog() << "Resource handle not found; Resource URI not set in request";
196 // Finding the corresponding CPP Application entityHandler for a given resource
197 auto entityHandlerEntry = entityHandlerMap.find(entityHandlerRequest->resource);
199 if(entityHandlerEntry != entityHandlerMap.end())
201 // Call CPP Application Entity Handler
202 if(entityHandlerEntry->second)
204 result = entityHandlerEntry->second(pRequest);
208 oclog() << "C stack should not call again for parent resource\n";
214 oclog() << "No entity handler found." << endl;
223 InProcServerWrapper::InProcServerWrapper(
224 std::weak_ptr<std::recursive_mutex> csdkLock, PlatformConfig cfg)
225 : m_csdkLock(csdkLock)
229 if(cfg.mode == ModeType::Server)
231 initType = OC_SERVER;
233 else if (cfg.mode == ModeType::Both)
235 initType = OC_CLIENT_SERVER;
239 throw InitializeException(OC::InitException::NOT_CONFIGURED_AS_SERVER,
240 OC_STACK_INVALID_PARAM);
243 OCStackResult result = OCInit(cfg.ipAddress.c_str(), cfg.port, initType);
245 if(OC_STACK_OK != result)
247 throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
251 m_processThread = std::thread(&InProcServerWrapper::processFunc, this);
254 void InProcServerWrapper::processFunc()
256 auto cLock = m_csdkLock.lock();
257 while(cLock && m_threadRun)
259 OCStackResult result;
262 std::lock_guard<std::recursive_mutex> lock(*cLock);
263 result = OCProcess();
266 // ...the value of variable result is simply ignored for now.
267 if(OC_STACK_ERROR == result)
270 std::this_thread::sleep_for(std::chrono::milliseconds(10));
274 OCStackResult InProcServerWrapper::registerResource(
275 OCResourceHandle& resourceHandle,
276 std::string& resourceURI,
277 const std::string& resourceTypeName,
278 const std::string& resourceInterface,
279 EntityHandler& eHandler,
280 uint8_t resourceProperties)
283 OCStackResult result = OC_STACK_ERROR;
285 auto cLock = m_csdkLock.lock();
289 std::lock_guard<std::recursive_mutex> lock(*cLock);
293 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
294 resourceTypeName.c_str(), // const char * resourceTypeName
295 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
296 resourceURI.c_str(), // const char * uri
297 EntityHandlerWrapper, // OCEntityHandler entityHandler
298 resourceProperties // uint8_t resourceProperties
303 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
304 resourceTypeName.c_str(), // const char * resourceTypeName
305 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
306 resourceURI.c_str(), // const char * uri
307 NULL, // OCEntityHandler entityHandler
308 resourceProperties // uint8_t resourceProperties
312 if(result != OC_STACK_OK)
314 resourceHandle = (OCResourceHandle) 0;
318 entityHandlerMap[resourceHandle] = eHandler;
319 resourceUriMap[resourceHandle] = resourceURI;
324 result = OC_STACK_ERROR;
330 OCStackResult InProcServerWrapper::registerResourceWithHost(
331 OCResourceHandle& resourceHandle,
332 std::string& resourceHOST,
333 std::string& resourceURI,
334 const std::string& resourceTypeName,
335 const std::string& resourceInterface,
336 EntityHandler& eHandler,
337 uint8_t resourceProperties)
340 OCStackResult result = OC_STACK_ERROR;
342 auto cLock = m_csdkLock.lock();
346 std::lock_guard < std::recursive_mutex > lock(*cLock);
348 if (NULL != eHandler)
350 result = OCCreateResourceWithHost(&resourceHandle, // OCResourceHandle *handle
351 resourceTypeName.c_str(), // const char * resourceTypeName
352 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix
353 resourceHOST.c_str(), // const char * host
354 (resourceHOST + resourceURI).c_str(), // const char * uri
355 EntityHandlerWrapper, // OCEntityHandler entityHandler
356 resourceProperties // uint8_t resourceProperties
361 result = OCCreateResourceWithHost(&resourceHandle, // OCResourceHandle *handle
362 resourceTypeName.c_str(), // const char * resourceTypeName
363 resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix
364 resourceHOST.c_str(), // const char * host
365 (resourceHOST + resourceURI).c_str(), // const char * uri
366 nullptr, // OCEntityHandler entityHandler
367 resourceProperties // uint8_t resourceProperties
371 if (result != OC_STACK_OK)
373 resourceHandle = nullptr;
377 entityHandlerMap[resourceHandle] = eHandler;
378 resourceUriMap[resourceHandle] = resourceURI;
383 result = OC_STACK_ERROR;
389 OCStackResult InProcServerWrapper::setDefaultDeviceEntityHandler
390 (EntityHandler entityHandler)
392 OCStackResult result = OC_STACK_ERROR;
394 defaultDeviceEntityHandler = entityHandler;
398 result = OCSetDefaultDeviceEntityHandler(DefaultEntityHandlerWrapper);
402 // If Null passed we unset
403 result = OCSetDefaultDeviceEntityHandler(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 resourceUriMap.erase(resourceHandle);
425 throw OCException(OC::Exception::RESOURCE_UNREG_FAILED, result);
430 result = OC_STACK_ERROR;
436 OCStackResult InProcServerWrapper::bindTypeToResource(const OCResourceHandle& resourceHandle,
437 const std::string& resourceTypeName)
439 auto cLock = m_csdkLock.lock();
440 OCStackResult result;
443 std::lock_guard<std::recursive_mutex> lock(*cLock);
444 result = OCBindResourceTypeToResource(resourceHandle, resourceTypeName.c_str());
448 result = OC_STACK_ERROR;
451 if (result != OC_STACK_OK)
453 throw OCException(OC::Exception::BIND_TYPE_FAILED, result);
458 OCStackResult InProcServerWrapper::bindInterfaceToResource(
459 const OCResourceHandle& resourceHandle,
460 const std::string& resourceInterfaceName)
462 auto cLock = m_csdkLock.lock();
463 OCStackResult result;
466 std::lock_guard<std::recursive_mutex> lock(*cLock);
467 result = OCBindResourceInterfaceToResource(resourceHandle,
468 resourceInterfaceName.c_str());
472 result = OC_STACK_ERROR;
475 if (result != OC_STACK_OK)
477 throw OCException(OC::Exception::BIND_INTERFACE_FAILED, result);
482 OCStackResult InProcServerWrapper::startPresence(const unsigned int seconds)
484 auto cLock = m_csdkLock.lock();
485 OCStackResult result = OC_STACK_ERROR;
488 std::lock_guard<std::recursive_mutex> lock(*cLock);
489 result = OCStartPresence(seconds);
492 if(result != OC_STACK_OK)
494 throw OCException(OC::Exception::START_PRESENCE_FAILED, result);
499 OCStackResult InProcServerWrapper::stopPresence()
501 auto cLock = m_csdkLock.lock();
502 OCStackResult result = OC_STACK_ERROR;
505 std::lock_guard<std::recursive_mutex> lock(*cLock);
506 result = OCStopPresence();
509 if(result != OC_STACK_OK)
511 throw OCException(OC::Exception::END_PRESENCE_FAILED, result);
516 OCStackResult InProcServerWrapper::sendResponse(
517 const std::shared_ptr<OCResourceResponse> pResponse)
519 auto cLock = m_csdkLock.lock();
520 OCStackResult result = OC_STACK_ERROR;
524 result = OC_STACK_MALFORMED_RESPONSE;
525 throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_MALFORMED_RESPONSE);
529 OCEntityHandlerResponse response;
531 HeaderOptions serverHeaderOptions;
533 payLoad = pResponse->getPayload();
534 serverHeaderOptions = pResponse->getHeaderOptions();
536 response.requestHandle = pResponse->getRequestHandle();
537 response.resourceHandle = pResponse->getResourceHandle();
538 response.ehResult = pResponse->getResponseResult();
539 response.payload = (unsigned char*) payLoad.c_str();
540 response.payloadSize = payLoad.length() + 1;
541 response.persistentBufferFlag = 0;
543 response.numSendVendorSpecificHeaderOptions = serverHeaderOptions.size();
545 for (auto it=serverHeaderOptions.begin(); it != serverHeaderOptions.end(); ++it)
547 response.sendVendorSpecificHeaderOptions[i].protocolID = OC_COAP_ID;
548 response.sendVendorSpecificHeaderOptions[i].optionID =
549 static_cast<uint16_t>(it->getOptionID());
550 response.sendVendorSpecificHeaderOptions[i].optionLength =
551 (it->getOptionData()).length() + 1;
552 memcpy(response.sendVendorSpecificHeaderOptions[i].optionData,
553 (it->getOptionData()).c_str(),
554 (it->getOptionData()).length() + 1);
558 if(OC_EH_RESOURCE_CREATED == response.ehResult)
560 std::string createdUri = pResponse->getNewResourceUri();
561 strncpy(reinterpret_cast<char*>(response.resourceUri),
563 createdUri.length() + 1);
568 std::lock_guard<std::recursive_mutex> lock(*cLock);
569 result = OCDoResponse(&response);
573 result = OC_STACK_ERROR;
576 if(result != OC_STACK_OK)
578 oclog() << "Error sending response\n";
584 InProcServerWrapper::~InProcServerWrapper()
586 if(m_processThread.joinable())
589 m_processThread.join();