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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 #include "InProcClientWrapper.h"
24 #include "OCPlatform.h"
25 #include "OCResource.h"
26 #include <OCSerialization.h>
31 InProcClientWrapper::InProcClientWrapper(
32 std::weak_ptr<std::recursive_mutex> csdkLock, PlatformConfig cfg)
33 : m_threadRun(false), m_csdkLock(csdkLock),
36 // if the config type is server, we ought to never get called. If the config type
37 // is both, we count on the server to run the thread and do the initialize
39 if(m_cfg.mode == ModeType::Client)
41 OCStackResult result = OCInit(m_cfg.ipAddress.c_str(), m_cfg.port, OC_CLIENT);
43 if(OC_STACK_OK != result)
45 throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
49 m_listeningThread = std::thread(&InProcClientWrapper::listeningFunc, this);
53 InProcClientWrapper::~InProcClientWrapper()
55 if(m_threadRun && m_listeningThread.joinable())
58 m_listeningThread.join();
61 // only stop if we are the ones who actually called 'init'. We are counting
62 // on the server to do the stop.
63 if(m_cfg.mode == ModeType::Client)
69 void InProcClientWrapper::listeningFunc()
74 auto cLock = m_csdkLock.lock();
77 std::lock_guard<std::recursive_mutex> lock(*cLock);
82 result = OC_STACK_ERROR;
85 if(result != OC_STACK_OK)
87 // TODO: do something with result if failed?
90 // To minimize CPU utilization we may wish to do this with sleep
91 std::this_thread::sleep_for(std::chrono::milliseconds(10));
95 OCRepresentation parseGetSetCallback(OCClientResponse* clientResponse)
97 if(clientResponse->resJSONPayload == nullptr || clientResponse->resJSONPayload[0] == '\0')
99 return OCRepresentation();
105 oc.setJSONRepresentation(clientResponse->resJSONPayload);
107 catch (cereal::RapidJSONException& ex)
109 oclog() <<"RapidJSON Exception in parseGetSetCallback: "<<ex.what() <<std::endl<<
110 "Data was:"<< clientResponse->resJSONPayload<< ":" << std::flush;
111 throw OCException(OC::Exception::INVALID_REPRESENTATION, OC_STACK_INVALID_JSON);
113 catch (cereal::Exception& ex)
115 oclog() <<"Cereal Exception in parseGetSetCallback: "<<ex.what() <<std::endl<<
116 "Data was:"<< clientResponse->resJSONPayload<< ":" << std::flush;
117 throw OCException(OC::Exception::INVALID_REPRESENTATION, OC_STACK_INVALID_JSON);
120 std::vector<OCRepresentation>::const_iterator it = oc.representations().begin();
121 if(it == oc.representations().end())
123 return OCRepresentation();
126 // first one is considered the root, everything else is considered a child of this one.
127 OCRepresentation root = *it;
130 std::for_each(it, oc.representations().end(),
131 [&root](const OCRepresentation& repItr)
132 {root.addChild(repItr);});
137 OCStackApplicationResult listenCallback(void* ctx, OCDoHandle handle,
138 OCClientResponse* clientResponse)
140 ClientCallbackContext::ListenContext* context =
141 static_cast<ClientCallbackContext::ListenContext*>(ctx);
143 if(clientResponse->result != OC_STACK_OK)
145 oclog() << "listenCallback(): failed to create resource. clientResponse: "
146 << clientResponse->result
149 return OC_STACK_KEEP_TRANSACTION;
152 auto clientWrapper = context->clientWrapper.lock();
156 oclog() << "listenCallback(): failed to get a shared_ptr to the client wrapper"
158 return OC_STACK_KEEP_TRANSACTION;
161 std::stringstream requestStream;
162 requestStream << clientResponse->resJSONPayload;
167 ListenOCContainer container(clientWrapper, *clientResponse->addr,
168 clientResponse->connType, requestStream);
169 // loop to ensure valid construction of all resources
170 for(auto resource : container.Resources())
172 std::thread exec(context->callback, resource);
177 catch(const std::exception& e)
179 oclog() << "listenCallback failed to parse a malformed message: "
182 << clientResponse->resJSONPayload
184 << clientResponse->result
186 return OC_STACK_KEEP_TRANSACTION;
189 return OC_STACK_KEEP_TRANSACTION;
192 OCStackResult InProcClientWrapper::ListenForResource(const std::string& serviceUrl,
193 const std::string& resourceType, OCConnectivityType connectivityType,
194 FindCallback& callback, QualityOfService QoS)
196 OCStackResult result;
198 OCCallbackData cbdata = {0};
200 ClientCallbackContext::ListenContext* context = new ClientCallbackContext::ListenContext();
201 context->callback = callback;
202 context->clientWrapper = shared_from_this();
204 cbdata.context = static_cast<void*>(context);
205 cbdata.cb = listenCallback;
206 cbdata.cd = [](void* c){delete static_cast<ClientCallbackContext::ListenContext*>(c);};
208 auto cLock = m_csdkLock.lock();
211 std::lock_guard<std::recursive_mutex> lock(*cLock);
212 result = OCDoResource(nullptr, OC_REST_GET,
213 resourceType.c_str(),
214 nullptr, nullptr, connectivityType,
215 static_cast<OCQualityOfService>(QoS),
222 result = OC_STACK_ERROR;
227 OCStackApplicationResult listenDeviceCallback(void* ctx, OCDoHandle handle,
228 OCClientResponse* clientResponse)
230 ClientCallbackContext::DeviceListenContext* context =
231 static_cast<ClientCallbackContext::DeviceListenContext*>(ctx);
235 OCRepresentation rep = parseGetSetCallback(clientResponse);
236 std::thread exec(context->callback, rep);
239 catch(OC::OCException& e)
241 oclog() <<"Exception in listenDeviceCallback, ignoring response: "
242 <<e.what() <<std::flush;
245 return OC_STACK_KEEP_TRANSACTION;
248 OCStackResult InProcClientWrapper::ListenForDevice(const std::string& serviceUrl,
249 const std::string& deviceURI, OCConnectivityType connectivityType,
250 FindDeviceCallback& callback, QualityOfService QoS)
252 OCStackResult result;
254 OCCallbackData cbdata = {0};
255 ClientCallbackContext::DeviceListenContext* context =
256 new ClientCallbackContext::DeviceListenContext();
257 context->callback = callback;
258 context->clientWrapper = shared_from_this();
259 cbdata.context = static_cast<void*>(context);
260 cbdata.cb = listenDeviceCallback;
261 cbdata.cd = [](void* c){delete static_cast<ClientCallbackContext::DeviceListenContext*>(c);};
263 auto cLock = m_csdkLock.lock();
266 std::lock_guard<std::recursive_mutex> lock(*cLock);
267 result = OCDoResource(nullptr, OC_REST_GET,
269 nullptr, nullptr, connectivityType,
270 static_cast<OCQualityOfService>(QoS),
277 result = OC_STACK_ERROR;
282 void parseServerHeaderOptions(OCClientResponse* clientResponse,
283 HeaderOptions& serverHeaderOptions)
287 // Parse header options from server
289 std::string optionData;
291 for(int i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
293 optionID = clientResponse->rcvdVendorSpecificHeaderOptions[i].optionID;
294 optionData = reinterpret_cast<const char*>
295 (clientResponse->rcvdVendorSpecificHeaderOptions[i].optionData);
296 HeaderOption::OCHeaderOption headerOption(optionID, optionData);
297 serverHeaderOptions.push_back(headerOption);
302 // clientResponse is invalid
303 // TODO check proper logging
304 std::cout << " Invalid response " << std::endl;
308 OCStackApplicationResult getResourceCallback(void* ctx, OCDoHandle handle,
309 OCClientResponse* clientResponse)
311 ClientCallbackContext::GetContext* context =
312 static_cast<ClientCallbackContext::GetContext*>(ctx);
314 OCRepresentation rep;
315 HeaderOptions serverHeaderOptions;
316 OCStackResult result = clientResponse->result;
317 if(result == OC_STACK_OK)
319 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
322 rep = parseGetSetCallback(clientResponse);
324 catch(OC::OCException& e)
330 std::thread exec(context->callback, serverHeaderOptions, rep, result);
332 return OC_STACK_DELETE_TRANSACTION;
335 OCStackResult InProcClientWrapper::GetResourceRepresentation(const std::string& host,
336 const std::string& uri, OCConnectivityType connectivityType,
337 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
338 GetCallback& callback, QualityOfService QoS)
340 OCStackResult result;
341 OCCallbackData cbdata = {0};
343 ClientCallbackContext::GetContext* ctx = new ClientCallbackContext::GetContext();
344 ctx->callback = callback;
345 cbdata.context = static_cast<void*>(ctx);
346 cbdata.cb = &getResourceCallback;
347 cbdata.cd = [](void* c){delete static_cast<ClientCallbackContext::GetContext*>(c);};
349 auto cLock = m_csdkLock.lock();
353 std::ostringstream os;
354 os << host << assembleSetResourceUri(uri, queryParams).c_str();
356 std::lock_guard<std::recursive_mutex> lock(*cLock);
357 OCHeaderOption options[MAX_HEADER_OPTIONS];
359 assembleHeaderOptions(options, headerOptions);
361 result = OCDoResource(nullptr, OC_REST_GET, os.str().c_str(),
362 nullptr, nullptr, connectivityType,
363 static_cast<OCQualityOfService>(QoS),
365 options, headerOptions.size());
370 result = OC_STACK_ERROR;
376 OCStackApplicationResult setResourceCallback(void* ctx, OCDoHandle handle,
377 OCClientResponse* clientResponse)
379 ClientCallbackContext::SetContext* context =
380 static_cast<ClientCallbackContext::SetContext*>(ctx);
381 OCRepresentation attrs;
382 HeaderOptions serverHeaderOptions;
384 OCStackResult result = clientResponse->result;
385 if (OC_STACK_OK == result ||
386 OC_STACK_RESOURCE_CREATED == result ||
387 OC_STACK_RESOURCE_DELETED == result)
389 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
392 attrs = parseGetSetCallback(clientResponse);
394 catch(OC::OCException& e)
400 std::thread exec(context->callback, serverHeaderOptions, attrs, result);
402 return OC_STACK_DELETE_TRANSACTION;
405 std::string InProcClientWrapper::assembleSetResourceUri(std::string uri,
406 const QueryParamsMap& queryParams)
408 if(uri.back() == '/')
410 uri.resize(uri.size()-1);
413 ostringstream paramsList;
414 if(queryParams.size() > 0)
419 for(auto& param : queryParams)
421 paramsList << param.first <<'='<<param.second<<'&';
424 std::string queryString = paramsList.str();
425 if(queryString.back() == '&')
427 queryString.resize(queryString.size() - 1);
430 std::string ret = uri + queryString;
434 std::string InProcClientWrapper::assembleSetResourcePayload(const OCRepresentation& rep)
436 MessageContainer ocInfo;
437 ocInfo.addRepresentation(rep);
438 return ocInfo.getJSONRepresentation(OCInfoFormat::IncludeOC);
441 OCStackResult InProcClientWrapper::PostResourceRepresentation(const std::string& host,
442 const std::string& uri, OCConnectivityType connectivityType, const OCRepresentation& rep,
443 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
444 PostCallback& callback, QualityOfService QoS)
446 OCStackResult result;
447 OCCallbackData cbdata = {0};
449 ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext();
450 ctx->callback = callback;
451 cbdata.cb = &setResourceCallback;
452 cbdata.cd = [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);};
453 cbdata.context = static_cast<void*>(ctx);
455 // TODO: in the future the cstack should be combining these two strings!
457 os << host << assembleSetResourceUri(uri, queryParams).c_str();
458 // TODO: end of above
460 auto cLock = m_csdkLock.lock();
464 std::lock_guard<std::recursive_mutex> lock(*cLock);
465 OCHeaderOption options[MAX_HEADER_OPTIONS];
467 assembleHeaderOptions(options, headerOptions);
468 result = OCDoResource(nullptr, OC_REST_POST,
469 os.str().c_str(), nullptr,
470 assembleSetResourcePayload(rep).c_str(), connectivityType,
471 static_cast<OCQualityOfService>(QoS),
472 &cbdata, options, headerOptions.size());
477 result = OC_STACK_ERROR;
483 OCStackResult InProcClientWrapper::PutResourceRepresentation(const std::string& host,
484 const std::string& uri, OCConnectivityType connectivityType, const OCRepresentation& rep,
485 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
486 PutCallback& callback, QualityOfService QoS)
488 OCStackResult result;
489 OCCallbackData cbdata = {0};
491 ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext();
492 ctx->callback = callback;
493 cbdata.cb = &setResourceCallback;
494 cbdata.cd = [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);};
495 cbdata.context = static_cast<void*>(ctx);
497 // TODO: in the future the cstack should be combining these two strings!
499 os << host << assembleSetResourceUri(uri, queryParams).c_str();
500 // TODO: end of above
502 auto cLock = m_csdkLock.lock();
506 std::lock_guard<std::recursive_mutex> lock(*cLock);
508 OCHeaderOption options[MAX_HEADER_OPTIONS];
510 assembleHeaderOptions(options, headerOptions);
511 result = OCDoResource(&handle, OC_REST_PUT,
512 os.str().c_str(), nullptr,
513 assembleSetResourcePayload(rep).c_str(), connectivityType,
514 static_cast<OCQualityOfService>(QoS),
516 options, headerOptions.size());
521 result = OC_STACK_ERROR;
527 OCStackApplicationResult deleteResourceCallback(void* ctx, OCDoHandle handle,
528 OCClientResponse* clientResponse)
530 ClientCallbackContext::DeleteContext* context =
531 static_cast<ClientCallbackContext::DeleteContext*>(ctx);
532 HeaderOptions serverHeaderOptions;
534 if(clientResponse->result == OC_STACK_OK)
536 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
538 std::thread exec(context->callback, serverHeaderOptions, clientResponse->result);
540 return OC_STACK_DELETE_TRANSACTION;
543 OCStackResult InProcClientWrapper::DeleteResource(const std::string& host,
544 const std::string& uri, OCConnectivityType connectivityType,
545 const HeaderOptions& headerOptions, DeleteCallback& callback, QualityOfService QoS)
547 OCStackResult result;
548 OCCallbackData cbdata = {0};
550 ClientCallbackContext::DeleteContext* ctx = new ClientCallbackContext::DeleteContext();
551 ctx->callback = callback;
552 cbdata.cb = &deleteResourceCallback;
553 cbdata.cd = [](void* c){delete static_cast<ClientCallbackContext::DeleteContext*>(c);};
554 cbdata.context = static_cast<void*>(ctx);
559 auto cLock = m_csdkLock.lock();
563 OCHeaderOption options[MAX_HEADER_OPTIONS];
565 assembleHeaderOptions(options, headerOptions);
567 std::lock_guard<std::recursive_mutex> lock(*cLock);
569 result = OCDoResource(nullptr, OC_REST_DELETE,
570 os.str().c_str(), nullptr,
571 nullptr, connectivityType,
572 static_cast<OCQualityOfService>(m_cfg.QoS),
573 &cbdata, options, headerOptions.size());
578 result = OC_STACK_ERROR;
584 OCStackApplicationResult observeResourceCallback(void* ctx, OCDoHandle handle,
585 OCClientResponse* clientResponse)
587 ClientCallbackContext::ObserveContext* context =
588 static_cast<ClientCallbackContext::ObserveContext*>(ctx);
589 OCRepresentation attrs;
590 HeaderOptions serverHeaderOptions;
591 uint32_t sequenceNumber = clientResponse->sequenceNumber;
592 OCStackResult result = clientResponse->result;
593 if(clientResponse->result == OC_STACK_OK)
595 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
598 attrs = parseGetSetCallback(clientResponse);
600 catch(OC::OCException& e)
605 std::thread exec(context->callback, serverHeaderOptions, attrs,
606 result, sequenceNumber);
608 if(sequenceNumber == OC_OBSERVE_DEREGISTER)
610 return OC_STACK_DELETE_TRANSACTION;
612 return OC_STACK_KEEP_TRANSACTION;
615 OCStackResult InProcClientWrapper::ObserveResource(ObserveType observeType, OCDoHandle* handle,
616 const std::string& host, const std::string& uri, OCConnectivityType connectivityType,
617 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
618 ObserveCallback& callback, QualityOfService QoS)
620 OCStackResult result;
621 OCCallbackData cbdata = {0};
623 ClientCallbackContext::ObserveContext* ctx = new ClientCallbackContext::ObserveContext();
624 ctx->callback = callback;
625 cbdata.context = static_cast<void*>(ctx);
626 cbdata.cb = &observeResourceCallback;
627 cbdata.cd = [](void* c){delete static_cast<ClientCallbackContext::ObserveContext*>(c);};
630 if (observeType == ObserveType::Observe)
632 method = OC_REST_OBSERVE;
634 else if (observeType == ObserveType::ObserveAll)
636 method = OC_REST_OBSERVE_ALL;
640 method = OC_REST_OBSERVE_ALL;
643 auto cLock = m_csdkLock.lock();
647 std::ostringstream os;
648 os << host << assembleSetResourceUri(uri, queryParams).c_str();
650 std::lock_guard<std::recursive_mutex> lock(*cLock);
651 OCHeaderOption options[MAX_HEADER_OPTIONS];
653 assembleHeaderOptions(options, headerOptions);
654 result = OCDoResource(handle, method,
655 os.str().c_str(), nullptr,
656 nullptr, connectivityType,
657 static_cast<OCQualityOfService>(QoS),
659 options, headerOptions.size());
664 return OC_STACK_ERROR;
670 OCStackResult InProcClientWrapper::CancelObserveResource(OCDoHandle handle,
671 const std::string& host, const std::string& uri, const HeaderOptions& headerOptions,
672 QualityOfService QoS)
674 OCStackResult result;
675 auto cLock = m_csdkLock.lock();
679 std::lock_guard<std::recursive_mutex> lock(*cLock);
680 OCHeaderOption options[MAX_HEADER_OPTIONS];
682 assembleHeaderOptions(options, headerOptions);
683 result = OCCancel(handle, static_cast<OCQualityOfService>(QoS), options,
684 headerOptions.size());
688 result = OC_STACK_ERROR;
694 OCStackApplicationResult subscribePresenceCallback(void* ctx, OCDoHandle handle,
695 OCClientResponse* clientResponse)
704 if(OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) == 0 &&
705 OCDevAddrToPort(clientResponse->addr, &port) == 0)
707 os<<static_cast<int>(a)<<"."<<static_cast<int>(b)<<"."<<static_cast<int>(c)
708 <<"."<<static_cast<int>(d)<<":"<<static_cast<int>(port);
710 ClientCallbackContext::SubscribePresenceContext* context =
711 static_cast<ClientCallbackContext::SubscribePresenceContext*>(ctx);
713 std::thread exec(context->callback, clientResponse->result,
714 clientResponse->sequenceNumber, os.str());
720 oclog() << "subscribePresenceCallback(): OCDevAddrToIPv4Addr() or OCDevAddrToPort() "
721 <<"failed"<< std::flush;
723 return OC_STACK_KEEP_TRANSACTION;
726 OCStackResult InProcClientWrapper::SubscribePresence(OCDoHandle* handle,
727 const std::string& host, const std::string& resourceType,
728 OCConnectivityType connectivityType, SubscribeCallback& presenceHandler)
730 OCCallbackData cbdata = {0};
732 ClientCallbackContext::SubscribePresenceContext* ctx =
733 new ClientCallbackContext::SubscribePresenceContext();
734 ctx->callback = presenceHandler;
735 cbdata.cb = &subscribePresenceCallback;
736 cbdata.context = static_cast<void*>(ctx);
737 cbdata.cd = [](void* c)
738 {delete static_cast<ClientCallbackContext::SubscribePresenceContext*>(c);};
739 auto cLock = m_csdkLock.lock();
741 std::ostringstream os;
742 os << host << "/oc/presence";
744 if(!resourceType.empty())
746 os << "?rt=" << resourceType;
752 return OC_STACK_ERROR;
755 return OCDoResource(handle, OC_REST_PRESENCE, os.str().c_str(), nullptr, nullptr,
756 connectivityType, OC_LOW_QOS, &cbdata, NULL, 0);
759 OCStackResult InProcClientWrapper::UnsubscribePresence(OCDoHandle handle)
761 OCStackResult result;
762 auto cLock = m_csdkLock.lock();
766 std::lock_guard<std::recursive_mutex> lock(*cLock);
767 result = OCCancel(handle, OC_LOW_QOS, NULL, 0);
771 result = OC_STACK_ERROR;
777 OCStackResult InProcClientWrapper::GetDefaultQos(QualityOfService& qos)
783 void InProcClientWrapper::assembleHeaderOptions(OCHeaderOption options[],
784 const HeaderOptions& headerOptions)
788 for (auto it=headerOptions.begin(); it != headerOptions.end(); ++it)
790 options[i].protocolID = OC_COAP_ID;
791 options[i].optionID = static_cast<uint16_t>(it->getOptionID());
792 options[i].optionLength = (it->getOptionData()).length() + 1;
793 memcpy(options[i].optionData, (it->getOptionData()).c_str(),
794 (it->getOptionData()).length() + 1);