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 "ocpayload.h"
27 #include <OCSerialization.h>
32 InProcClientWrapper::InProcClientWrapper(
33 std::weak_ptr<std::recursive_mutex> csdkLock, PlatformConfig cfg)
34 : m_threadRun(false), m_csdkLock(csdkLock),
37 // if the config type is server, we ought to never get called. If the config type
38 // is both, we count on the server to run the thread and do the initialize
40 if(m_cfg.mode == ModeType::Client)
42 OCTransportFlags serverFlags =
43 static_cast<OCTransportFlags>(m_cfg.serverConnectivity & CT_MASK_FLAGS);
44 OCTransportFlags clientFlags =
45 static_cast<OCTransportFlags>(m_cfg.clientConnectivity & CT_MASK_FLAGS);
46 OCStackResult result = OCInit1(OC_CLIENT, serverFlags, clientFlags);
48 if(OC_STACK_OK != result)
50 throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
54 m_listeningThread = std::thread(&InProcClientWrapper::listeningFunc, this);
58 InProcClientWrapper::~InProcClientWrapper()
60 if(m_threadRun && m_listeningThread.joinable())
63 m_listeningThread.join();
66 // only stop if we are the ones who actually called 'init'. We are counting
67 // on the server to do the stop.
68 if(m_cfg.mode == ModeType::Client)
74 void InProcClientWrapper::listeningFunc()
79 auto cLock = m_csdkLock.lock();
82 std::lock_guard<std::recursive_mutex> lock(*cLock);
87 result = OC_STACK_ERROR;
90 if(result != OC_STACK_OK)
92 // TODO: do something with result if failed?
95 // To minimize CPU utilization we may wish to do this with sleep
96 std::this_thread::sleep_for(std::chrono::milliseconds(10));
100 OCRepresentation parseGetSetCallback(OCClientResponse* clientResponse)
102 if(clientResponse->payload == nullptr ||
104 clientResponse->payload->type != PAYLOAD_TYPE_DEVICE &&
105 clientResponse->payload->type != PAYLOAD_TYPE_PLATFORM &&
106 clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION
110 //OCPayloadDestroy(clientResponse->payload);
111 return OCRepresentation();
115 oc.setPayload(clientResponse->payload);
116 //OCPayloadDestroy(clientResponse->payload);
118 std::vector<OCRepresentation>::const_iterator it = oc.representations().begin();
119 if(it == oc.representations().end())
121 return OCRepresentation();
124 // first one is considered the root, everything else is considered a child of this one.
125 OCRepresentation root = *it;
126 root.setDevAddr(clientResponse->devAddr);
127 root.setUri(clientResponse->resourceUri);
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 if(!clientResponse->payload || clientResponse->payload->type != PAYLOAD_TYPE_DISCOVERY)
154 oclog() << "listenCallback(): clientResponse payload was null or the wrong type"
156 return OC_STACK_KEEP_TRANSACTION;
159 auto clientWrapper = context->clientWrapper.lock();
163 oclog() << "listenCallback(): failed to get a shared_ptr to the client wrapper"
165 return OC_STACK_KEEP_TRANSACTION;
169 ListenOCContainer container(clientWrapper, clientResponse->devAddr,
170 reinterpret_cast<OCDiscoveryPayload*>(clientResponse->payload));
171 // loop to ensure valid construction of all resources
172 for(auto resource : container.Resources())
174 std::thread exec(context->callback, resource);
178 catch (std::exception &e){
179 oclog() << "Exception in listCallback, ignoring response: "
180 << e.what() << std::flush;
184 return OC_STACK_KEEP_TRANSACTION;
187 OCStackResult InProcClientWrapper::ListenForResource(
188 const std::string& serviceUrl,
189 const std::string& resourceType,
190 OCConnectivityType connectivityType,
191 FindCallback& callback, QualityOfService QoS)
195 return OC_STACK_INVALID_PARAM;
198 OCStackResult result;
199 ostringstream resourceUri;
200 resourceUri << serviceUrl << resourceType;
202 ClientCallbackContext::ListenContext* context =
203 new ClientCallbackContext::ListenContext(callback, shared_from_this());
204 OCCallbackData cbdata(
205 static_cast<void*>(context),
207 [](void* c){delete static_cast<ClientCallbackContext::ListenContext*>(c);}
210 auto cLock = m_csdkLock.lock();
213 std::lock_guard<std::recursive_mutex> lock(*cLock);
214 result = OCDoResource(nullptr, OC_REST_DISCOVER,
215 resourceUri.str().c_str(),
216 nullptr, nullptr, connectivityType,
217 static_cast<OCQualityOfService>(QoS),
224 result = OC_STACK_ERROR;
229 OCStackApplicationResult listenDeviceCallback(void* ctx,
230 OCDoHandle /*handle*/,
231 OCClientResponse* clientResponse)
233 ClientCallbackContext::DeviceListenContext* context =
234 static_cast<ClientCallbackContext::DeviceListenContext*>(ctx);
238 OCRepresentation rep = parseGetSetCallback(clientResponse);
239 std::thread exec(context->callback, rep);
242 catch(OC::OCException& e)
244 oclog() <<"Exception in listenDeviceCallback, ignoring response: "
245 <<e.what() <<std::flush;
248 return OC_STACK_KEEP_TRANSACTION;
251 OCStackResult InProcClientWrapper::ListenForDevice(
252 const std::string& serviceUrl,
253 const std::string& deviceURI,
254 OCConnectivityType connectivityType,
255 FindDeviceCallback& callback,
256 QualityOfService QoS)
260 return OC_STACK_INVALID_PARAM;
262 OCStackResult result;
263 ostringstream deviceUri;
264 deviceUri << serviceUrl << deviceURI;
266 ClientCallbackContext::DeviceListenContext* context =
267 new ClientCallbackContext::DeviceListenContext(callback, shared_from_this());
268 OCCallbackData cbdata(
269 static_cast<void*>(context),
270 listenDeviceCallback,
271 [](void* c){delete static_cast<ClientCallbackContext::DeviceListenContext*>(c);}
274 auto cLock = m_csdkLock.lock();
277 std::lock_guard<std::recursive_mutex> lock(*cLock);
278 result = OCDoResource(nullptr, OC_REST_DISCOVER,
279 deviceUri.str().c_str(),
280 nullptr, nullptr, connectivityType,
281 static_cast<OCQualityOfService>(QoS),
288 result = OC_STACK_ERROR;
293 void parseServerHeaderOptions(OCClientResponse* clientResponse,
294 HeaderOptions& serverHeaderOptions)
298 // Parse header options from server
300 std::string optionData;
302 for(int i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
304 optionID = clientResponse->rcvdVendorSpecificHeaderOptions[i].optionID;
305 optionData = reinterpret_cast<const char*>
306 (clientResponse->rcvdVendorSpecificHeaderOptions[i].optionData);
307 HeaderOption::OCHeaderOption headerOption(optionID, optionData);
308 serverHeaderOptions.push_back(headerOption);
313 // clientResponse is invalid
314 // TODO check proper logging
315 std::cout << " Invalid response " << std::endl;
319 OCStackApplicationResult getResourceCallback(void* ctx,
320 OCDoHandle /*handle*/,
321 OCClientResponse* clientResponse)
323 ClientCallbackContext::GetContext* context =
324 static_cast<ClientCallbackContext::GetContext*>(ctx);
326 OCRepresentation rep;
327 HeaderOptions serverHeaderOptions;
328 OCStackResult result = clientResponse->result;
329 if(result == OC_STACK_OK)
331 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
334 rep = parseGetSetCallback(clientResponse);
336 catch(OC::OCException& e)
342 std::thread exec(context->callback, serverHeaderOptions, rep, result);
344 return OC_STACK_DELETE_TRANSACTION;
347 OCStackResult InProcClientWrapper::GetResourceRepresentation(
348 const OCDevAddr& devAddr,
349 const std::string& resourceUri,
350 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
351 GetCallback& callback, QualityOfService QoS)
355 return OC_STACK_INVALID_PARAM;
357 OCStackResult result;
358 ClientCallbackContext::GetContext* ctx =
359 new ClientCallbackContext::GetContext(callback);
360 OCCallbackData cbdata(
361 static_cast<void*>(ctx),
363 [](void* c){delete static_cast<ClientCallbackContext::GetContext*>(c);}
366 std::string uri = assembleSetResourceUri(resourceUri, queryParams);
368 auto cLock = m_csdkLock.lock();
372 std::lock_guard<std::recursive_mutex> lock(*cLock);
373 OCHeaderOption options[MAX_HEADER_OPTIONS];
375 result = OCDoResource(
376 nullptr, OC_REST_GET,
380 static_cast<OCQualityOfService>(QoS),
382 assembleHeaderOptions(options, headerOptions),
383 headerOptions.size());
388 result = OC_STACK_ERROR;
394 OCStackApplicationResult setResourceCallback(void* ctx,
395 OCDoHandle /*handle*/,
396 OCClientResponse* clientResponse)
398 ClientCallbackContext::SetContext* context =
399 static_cast<ClientCallbackContext::SetContext*>(ctx);
400 OCRepresentation attrs;
401 HeaderOptions serverHeaderOptions;
403 OCStackResult result = clientResponse->result;
404 if (OC_STACK_OK == result ||
405 OC_STACK_RESOURCE_CREATED == result ||
406 OC_STACK_RESOURCE_DELETED == result)
408 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
411 attrs = parseGetSetCallback(clientResponse);
413 catch(OC::OCException& e)
419 std::thread exec(context->callback, serverHeaderOptions, attrs, result);
421 return OC_STACK_DELETE_TRANSACTION;
424 std::string InProcClientWrapper::assembleSetResourceUri(std::string uri,
425 const QueryParamsMap& queryParams)
427 if(uri.back() == '/')
429 uri.resize(uri.size()-1);
432 ostringstream paramsList;
433 if(queryParams.size() > 0)
438 for(auto& param : queryParams)
440 paramsList << param.first <<'='<<param.second<<';';
443 std::string queryString = paramsList.str();
444 if(queryString.back() == ';')
446 queryString.resize(queryString.size() - 1);
449 std::string ret = uri + queryString;
453 OCPayload* InProcClientWrapper::assembleSetResourcePayload(const OCRepresentation& rep)
455 MessageContainer ocInfo;
456 ocInfo.addRepresentation(rep);
457 for(const OCRepresentation& r : rep.getChildren())
459 ocInfo.addRepresentation(r);
462 return reinterpret_cast<OCPayload*>(ocInfo.getPayload());
465 OCStackResult InProcClientWrapper::PostResourceRepresentation(
466 const OCDevAddr& devAddr,
467 const std::string& uri,
468 const OCRepresentation& rep,
469 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
470 PostCallback& callback, QualityOfService QoS)
474 return OC_STACK_INVALID_PARAM;
476 OCStackResult result;
477 ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(callback);
478 OCCallbackData cbdata(
479 static_cast<void*>(ctx),
481 [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
484 std::string url = assembleSetResourceUri(uri, queryParams);
486 auto cLock = m_csdkLock.lock();
490 std::lock_guard<std::recursive_mutex> lock(*cLock);
491 OCHeaderOption options[MAX_HEADER_OPTIONS];
493 result = OCDoResource(nullptr, OC_REST_POST,
494 url.c_str(), &devAddr,
495 assembleSetResourcePayload(rep),
497 static_cast<OCQualityOfService>(QoS),
499 assembleHeaderOptions(options, headerOptions),
500 headerOptions.size());
505 result = OC_STACK_ERROR;
511 OCStackResult InProcClientWrapper::PutResourceRepresentation(
512 const OCDevAddr& devAddr,
513 const std::string& uri,
514 const OCRepresentation& rep,
515 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
516 PutCallback& callback, QualityOfService QoS)
520 return OC_STACK_INVALID_PARAM;
522 OCStackResult result;
523 ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(callback);
524 OCCallbackData cbdata(
525 static_cast<void*>(ctx),
527 [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
530 std::string url = assembleSetResourceUri(uri, queryParams).c_str();
532 auto cLock = m_csdkLock.lock();
536 std::lock_guard<std::recursive_mutex> lock(*cLock);
538 OCHeaderOption options[MAX_HEADER_OPTIONS];
540 result = OCDoResource(&handle, OC_REST_PUT,
541 url.c_str(), &devAddr,
542 assembleSetResourcePayload(rep),
544 static_cast<OCQualityOfService>(QoS),
546 assembleHeaderOptions(options, headerOptions),
547 headerOptions.size());
552 result = OC_STACK_ERROR;
558 OCStackApplicationResult deleteResourceCallback(void* ctx,
559 OCDoHandle /*handle*/,
560 OCClientResponse* clientResponse)
562 ClientCallbackContext::DeleteContext* context =
563 static_cast<ClientCallbackContext::DeleteContext*>(ctx);
564 HeaderOptions serverHeaderOptions;
566 if(clientResponse->result == OC_STACK_OK)
568 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
570 std::thread exec(context->callback, serverHeaderOptions, clientResponse->result);
572 return OC_STACK_DELETE_TRANSACTION;
575 OCStackResult InProcClientWrapper::DeleteResource(
576 const OCDevAddr& devAddr,
577 const std::string& uri,
578 const HeaderOptions& headerOptions,
579 DeleteCallback& callback,
580 QualityOfService /*QoS*/)
584 return OC_STACK_INVALID_PARAM;
586 OCStackResult result;
587 ClientCallbackContext::DeleteContext* ctx =
588 new ClientCallbackContext::DeleteContext(callback);
589 OCCallbackData cbdata(
590 static_cast<void*>(ctx),
591 deleteResourceCallback,
592 [](void* c){delete static_cast<ClientCallbackContext::DeleteContext*>(c);}
595 auto cLock = m_csdkLock.lock();
599 OCHeaderOption options[MAX_HEADER_OPTIONS];
601 std::lock_guard<std::recursive_mutex> lock(*cLock);
603 result = OCDoResource(nullptr, OC_REST_DELETE,
604 uri.c_str(), &devAddr,
607 static_cast<OCQualityOfService>(m_cfg.QoS),
609 assembleHeaderOptions(options, headerOptions),
610 headerOptions.size());
615 result = OC_STACK_ERROR;
621 OCStackApplicationResult observeResourceCallback(void* ctx,
622 OCDoHandle /*handle*/,
623 OCClientResponse* clientResponse)
625 ClientCallbackContext::ObserveContext* context =
626 static_cast<ClientCallbackContext::ObserveContext*>(ctx);
627 OCRepresentation attrs;
628 HeaderOptions serverHeaderOptions;
629 uint32_t sequenceNumber = clientResponse->sequenceNumber;
630 OCStackResult result = clientResponse->result;
631 if(clientResponse->result == OC_STACK_OK)
633 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
636 attrs = parseGetSetCallback(clientResponse);
638 catch(OC::OCException& e)
643 std::thread exec(context->callback, serverHeaderOptions, attrs,
644 result, sequenceNumber);
646 if(sequenceNumber == OC_OBSERVE_DEREGISTER)
648 return OC_STACK_DELETE_TRANSACTION;
650 return OC_STACK_KEEP_TRANSACTION;
653 OCStackResult InProcClientWrapper::ObserveResource(ObserveType observeType, OCDoHandle* handle,
654 const OCDevAddr& devAddr,
655 const std::string& uri,
656 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
657 ObserveCallback& callback, QualityOfService QoS)
661 return OC_STACK_INVALID_PARAM;
663 OCStackResult result;
665 ClientCallbackContext::ObserveContext* ctx =
666 new ClientCallbackContext::ObserveContext(callback);
667 OCCallbackData cbdata(
668 static_cast<void*>(ctx),
669 observeResourceCallback,
670 [](void* c){delete static_cast<ClientCallbackContext::ObserveContext*>(c);}
674 if (observeType == ObserveType::Observe)
676 method = OC_REST_OBSERVE;
678 else if (observeType == ObserveType::ObserveAll)
680 method = OC_REST_OBSERVE_ALL;
684 method = OC_REST_OBSERVE_ALL;
687 std::string url = assembleSetResourceUri(uri, queryParams).c_str();
689 auto cLock = m_csdkLock.lock();
693 std::lock_guard<std::recursive_mutex> lock(*cLock);
694 OCHeaderOption options[MAX_HEADER_OPTIONS];
696 result = OCDoResource(handle, method,
697 url.c_str(), &devAddr,
700 static_cast<OCQualityOfService>(QoS),
702 assembleHeaderOptions(options, headerOptions),
703 headerOptions.size());
708 return OC_STACK_ERROR;
714 OCStackResult InProcClientWrapper::CancelObserveResource(
716 const std::string& /*host*/,
717 const std::string& /*uri*/,
718 const HeaderOptions& headerOptions,
719 QualityOfService QoS)
721 OCStackResult result;
722 auto cLock = m_csdkLock.lock();
726 std::lock_guard<std::recursive_mutex> lock(*cLock);
727 OCHeaderOption options[MAX_HEADER_OPTIONS];
729 result = OCCancel(handle,
730 static_cast<OCQualityOfService>(QoS),
731 assembleHeaderOptions(options, headerOptions),
732 headerOptions.size());
736 result = OC_STACK_ERROR;
742 OCStackApplicationResult subscribePresenceCallback(void* ctx,
743 OCDoHandle /*handle*/,
744 OCClientResponse* clientResponse)
746 ClientCallbackContext::SubscribePresenceContext* context =
747 static_cast<ClientCallbackContext::SubscribePresenceContext*>(ctx);
750 * This a hack while we rethink presence subscription.
752 std::string url = clientResponse->devAddr.addr;
754 std::thread exec(context->callback, clientResponse->result,
755 clientResponse->sequenceNumber, url);
759 return OC_STACK_KEEP_TRANSACTION;
762 OCStackResult InProcClientWrapper::SubscribePresence(OCDoHandle* handle,
763 const std::string& host, const std::string& resourceType,
764 OCConnectivityType connectivityType, SubscribeCallback& presenceHandler)
768 return OC_STACK_INVALID_PARAM;
771 ClientCallbackContext::SubscribePresenceContext* ctx =
772 new ClientCallbackContext::SubscribePresenceContext(presenceHandler);
773 OCCallbackData cbdata(
774 static_cast<void*>(ctx),
775 subscribePresenceCallback,
777 {delete static_cast<ClientCallbackContext::SubscribePresenceContext*>(c);}
780 auto cLock = m_csdkLock.lock();
782 std::ostringstream os;
783 os << host << OC_RSRVD_PRESENCE_URI;
785 if(!resourceType.empty())
787 os << "?rt=" << resourceType;
793 return OC_STACK_ERROR;
796 return OCDoResource(handle, OC_REST_PRESENCE,
797 os.str().c_str(), nullptr,
798 nullptr, connectivityType,
799 OC_LOW_QOS, &cbdata, NULL, 0);
802 OCStackResult InProcClientWrapper::UnsubscribePresence(OCDoHandle handle)
804 OCStackResult result;
805 auto cLock = m_csdkLock.lock();
809 std::lock_guard<std::recursive_mutex> lock(*cLock);
810 result = OCCancel(handle, OC_LOW_QOS, NULL, 0);
814 result = OC_STACK_ERROR;
820 OCStackResult InProcClientWrapper::GetDefaultQos(QualityOfService& qos)
826 OCHeaderOption* InProcClientWrapper::assembleHeaderOptions(OCHeaderOption options[],
827 const HeaderOptions& headerOptions)
831 if( headerOptions.size() == 0)
836 for (auto it=headerOptions.begin(); it != headerOptions.end(); ++it)
838 options[i] = OCHeaderOption(OC_COAP_ID,
840 it->getOptionData().length() + 1,
841 reinterpret_cast<const uint8_t*>(it->getOptionData().c_str()));