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;
128 std::for_each(it, oc.representations().end(),
129 [&root](const OCRepresentation& repItr)
130 {root.addChild(repItr);});
135 OCStackApplicationResult listenCallback(void* ctx, OCDoHandle handle,
136 OCClientResponse* clientResponse)
138 ClientCallbackContext::ListenContext* context =
139 static_cast<ClientCallbackContext::ListenContext*>(ctx);
141 if(clientResponse->result != OC_STACK_OK)
143 oclog() << "listenCallback(): failed to create resource. clientResponse: "
144 << clientResponse->result
147 return OC_STACK_KEEP_TRANSACTION;
150 if(!clientResponse->payload || clientResponse->payload->type != PAYLOAD_TYPE_DISCOVERY)
152 oclog() << "listenCallback(): clientResponse payload was null or the wrong type"
154 return OC_STACK_KEEP_TRANSACTION;
157 auto clientWrapper = context->clientWrapper.lock();
161 oclog() << "listenCallback(): failed to get a shared_ptr to the client wrapper"
163 return OC_STACK_KEEP_TRANSACTION;
166 ListenOCContainer container(clientWrapper, clientResponse->devAddr,
167 reinterpret_cast<OCDiscoveryPayload*>(clientResponse->payload));
168 // loop to ensure valid construction of all resources
169 for(auto resource : container.Resources())
171 std::thread exec(context->callback, resource);
176 return OC_STACK_KEEP_TRANSACTION;
179 OCStackResult InProcClientWrapper::ListenForResource(
180 const std::string& serviceUrl,
181 const std::string& resourceType,
182 OCConnectivityType connectivityType,
183 FindCallback& callback, QualityOfService QoS)
187 return OC_STACK_INVALID_PARAM;
190 OCStackResult result;
191 ostringstream resourceUri;
192 resourceUri << serviceUrl << resourceType;
194 ClientCallbackContext::ListenContext* context =
195 new ClientCallbackContext::ListenContext(callback, shared_from_this());
196 OCCallbackData cbdata(
197 static_cast<void*>(context),
199 [](void* c){delete static_cast<ClientCallbackContext::ListenContext*>(c);}
202 auto cLock = m_csdkLock.lock();
205 std::lock_guard<std::recursive_mutex> lock(*cLock);
206 result = OCDoResource(nullptr, OC_REST_DISCOVER,
207 resourceUri.str().c_str(),
208 nullptr, nullptr, connectivityType,
209 static_cast<OCQualityOfService>(QoS),
216 result = OC_STACK_ERROR;
221 OCStackApplicationResult listenDeviceCallback(void* ctx, OCDoHandle handle,
222 OCClientResponse* clientResponse)
224 ClientCallbackContext::DeviceListenContext* context =
225 static_cast<ClientCallbackContext::DeviceListenContext*>(ctx);
229 OCRepresentation rep = parseGetSetCallback(clientResponse);
230 std::thread exec(context->callback, rep);
233 catch(OC::OCException& e)
235 oclog() <<"Exception in listenDeviceCallback, ignoring response: "
236 <<e.what() <<std::flush;
239 return OC_STACK_KEEP_TRANSACTION;
242 OCStackResult InProcClientWrapper::ListenForDevice(
243 const std::string& serviceUrl,
244 const std::string& deviceURI,
245 OCConnectivityType connectivityType,
246 FindDeviceCallback& callback,
247 QualityOfService QoS)
251 return OC_STACK_INVALID_PARAM;
253 OCStackResult result;
254 ostringstream deviceUri;
255 deviceUri << serviceUrl << deviceURI;
257 ClientCallbackContext::DeviceListenContext* context =
258 new ClientCallbackContext::DeviceListenContext(callback, shared_from_this());
259 OCCallbackData cbdata(
260 static_cast<void*>(context),
261 listenDeviceCallback,
262 [](void* c){delete static_cast<ClientCallbackContext::DeviceListenContext*>(c);}
265 auto cLock = m_csdkLock.lock();
268 std::lock_guard<std::recursive_mutex> lock(*cLock);
269 result = OCDoResource(nullptr, OC_REST_DISCOVER,
270 deviceUri.str().c_str(),
271 nullptr, nullptr, connectivityType,
272 static_cast<OCQualityOfService>(QoS),
279 result = OC_STACK_ERROR;
284 void parseServerHeaderOptions(OCClientResponse* clientResponse,
285 HeaderOptions& serverHeaderOptions)
289 // Parse header options from server
291 std::string optionData;
293 for(int i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
295 optionID = clientResponse->rcvdVendorSpecificHeaderOptions[i].optionID;
296 optionData = reinterpret_cast<const char*>
297 (clientResponse->rcvdVendorSpecificHeaderOptions[i].optionData);
298 HeaderOption::OCHeaderOption headerOption(optionID, optionData);
299 serverHeaderOptions.push_back(headerOption);
304 // clientResponse is invalid
305 // TODO check proper logging
306 std::cout << " Invalid response " << std::endl;
310 OCStackApplicationResult getResourceCallback(void* ctx, OCDoHandle handle,
311 OCClientResponse* clientResponse)
313 ClientCallbackContext::GetContext* context =
314 static_cast<ClientCallbackContext::GetContext*>(ctx);
316 OCRepresentation rep;
317 HeaderOptions serverHeaderOptions;
318 OCStackResult result = clientResponse->result;
319 if(result == OC_STACK_OK)
321 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
324 rep = parseGetSetCallback(clientResponse);
326 catch(OC::OCException& e)
332 std::thread exec(context->callback, serverHeaderOptions, rep, result);
334 return OC_STACK_DELETE_TRANSACTION;
337 OCStackResult InProcClientWrapper::GetResourceRepresentation(
338 const OCDevAddr& devAddr,
339 const std::string& resourceUri,
340 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
341 GetCallback& callback, QualityOfService QoS)
345 return OC_STACK_INVALID_PARAM;
347 OCStackResult result;
348 ClientCallbackContext::GetContext* ctx =
349 new ClientCallbackContext::GetContext(callback);
350 OCCallbackData cbdata(
351 static_cast<void*>(ctx),
353 [](void* c){delete static_cast<ClientCallbackContext::GetContext*>(c);}
356 std::string uri = assembleSetResourceUri(resourceUri, queryParams);
358 auto cLock = m_csdkLock.lock();
362 std::lock_guard<std::recursive_mutex> lock(*cLock);
363 OCHeaderOption options[MAX_HEADER_OPTIONS];
365 result = OCDoResource(
366 nullptr, OC_REST_GET,
370 static_cast<OCQualityOfService>(QoS),
372 assembleHeaderOptions(options, headerOptions),
373 headerOptions.size());
378 result = OC_STACK_ERROR;
384 OCStackApplicationResult setResourceCallback(void* ctx, OCDoHandle handle,
385 OCClientResponse* clientResponse)
387 ClientCallbackContext::SetContext* context =
388 static_cast<ClientCallbackContext::SetContext*>(ctx);
389 OCRepresentation attrs;
390 HeaderOptions serverHeaderOptions;
392 OCStackResult result = clientResponse->result;
393 if (OC_STACK_OK == result ||
394 OC_STACK_RESOURCE_CREATED == result ||
395 OC_STACK_RESOURCE_DELETED == result)
397 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
400 attrs = parseGetSetCallback(clientResponse);
402 catch(OC::OCException& e)
408 std::thread exec(context->callback, serverHeaderOptions, attrs, result);
410 return OC_STACK_DELETE_TRANSACTION;
413 std::string InProcClientWrapper::assembleSetResourceUri(std::string uri,
414 const QueryParamsMap& queryParams)
416 if(uri.back() == '/')
418 uri.resize(uri.size()-1);
421 ostringstream paramsList;
422 if(queryParams.size() > 0)
427 for(auto& param : queryParams)
429 paramsList << param.first <<'='<<param.second<<';';
432 std::string queryString = paramsList.str();
433 if(queryString.back() == ';')
435 queryString.resize(queryString.size() - 1);
438 std::string ret = uri + queryString;
442 OCPayload* InProcClientWrapper::assembleSetResourcePayload(const OCRepresentation& rep)
444 MessageContainer ocInfo;
445 ocInfo.addRepresentation(rep);
446 return reinterpret_cast<OCPayload*>(ocInfo.getPayload());
449 OCStackResult InProcClientWrapper::PostResourceRepresentation(
450 const OCDevAddr& devAddr,
451 const std::string& uri,
452 const OCRepresentation& rep,
453 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
454 PostCallback& callback, QualityOfService QoS)
458 return OC_STACK_INVALID_PARAM;
460 OCStackResult result;
461 ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(callback);
462 OCCallbackData cbdata(
463 static_cast<void*>(ctx),
465 [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
468 std::string url = assembleSetResourceUri(uri, queryParams);
470 auto cLock = m_csdkLock.lock();
474 std::lock_guard<std::recursive_mutex> lock(*cLock);
475 OCHeaderOption options[MAX_HEADER_OPTIONS];
477 result = OCDoResource(nullptr, OC_REST_POST,
478 url.c_str(), &devAddr,
479 assembleSetResourcePayload(rep),
481 static_cast<OCQualityOfService>(QoS),
483 assembleHeaderOptions(options, headerOptions),
484 headerOptions.size());
489 result = OC_STACK_ERROR;
495 OCStackResult InProcClientWrapper::PutResourceRepresentation(
496 const OCDevAddr& devAddr,
497 const std::string& uri,
498 const OCRepresentation& rep,
499 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
500 PutCallback& callback, QualityOfService QoS)
504 return OC_STACK_INVALID_PARAM;
506 OCStackResult result;
507 ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(callback);
508 OCCallbackData cbdata(
509 static_cast<void*>(ctx),
511 [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
514 std::string url = assembleSetResourceUri(uri, queryParams).c_str();
516 auto cLock = m_csdkLock.lock();
520 std::lock_guard<std::recursive_mutex> lock(*cLock);
522 OCHeaderOption options[MAX_HEADER_OPTIONS];
524 result = OCDoResource(&handle, OC_REST_PUT,
525 url.c_str(), &devAddr,
526 assembleSetResourcePayload(rep),
528 static_cast<OCQualityOfService>(QoS),
530 assembleHeaderOptions(options, headerOptions),
531 headerOptions.size());
536 result = OC_STACK_ERROR;
542 OCStackApplicationResult deleteResourceCallback(void* ctx, OCDoHandle handle,
543 OCClientResponse* clientResponse)
545 ClientCallbackContext::DeleteContext* context =
546 static_cast<ClientCallbackContext::DeleteContext*>(ctx);
547 HeaderOptions serverHeaderOptions;
549 if(clientResponse->result == OC_STACK_OK)
551 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
553 std::thread exec(context->callback, serverHeaderOptions, clientResponse->result);
555 return OC_STACK_DELETE_TRANSACTION;
558 OCStackResult InProcClientWrapper::DeleteResource(
559 const OCDevAddr& devAddr,
560 const std::string& uri,
561 const HeaderOptions& headerOptions, DeleteCallback& callback, QualityOfService QoS)
565 return OC_STACK_INVALID_PARAM;
567 OCStackResult result;
568 ClientCallbackContext::DeleteContext* ctx =
569 new ClientCallbackContext::DeleteContext(callback);
570 OCCallbackData cbdata(
571 static_cast<void*>(ctx),
572 deleteResourceCallback,
573 [](void* c){delete static_cast<ClientCallbackContext::DeleteContext*>(c);}
576 auto cLock = m_csdkLock.lock();
580 OCHeaderOption options[MAX_HEADER_OPTIONS];
582 std::lock_guard<std::recursive_mutex> lock(*cLock);
584 result = OCDoResource(nullptr, OC_REST_DELETE,
585 uri.c_str(), &devAddr,
588 static_cast<OCQualityOfService>(m_cfg.QoS),
590 assembleHeaderOptions(options, headerOptions),
591 headerOptions.size());
596 result = OC_STACK_ERROR;
602 OCStackApplicationResult observeResourceCallback(void* ctx, OCDoHandle handle,
603 OCClientResponse* clientResponse)
605 ClientCallbackContext::ObserveContext* context =
606 static_cast<ClientCallbackContext::ObserveContext*>(ctx);
607 OCRepresentation attrs;
608 HeaderOptions serverHeaderOptions;
609 uint32_t sequenceNumber = clientResponse->sequenceNumber;
610 OCStackResult result = clientResponse->result;
611 if(clientResponse->result == OC_STACK_OK)
613 parseServerHeaderOptions(clientResponse, serverHeaderOptions);
616 attrs = parseGetSetCallback(clientResponse);
618 catch(OC::OCException& e)
623 std::thread exec(context->callback, serverHeaderOptions, attrs,
624 result, sequenceNumber);
626 if(sequenceNumber == OC_OBSERVE_DEREGISTER)
628 return OC_STACK_DELETE_TRANSACTION;
630 return OC_STACK_KEEP_TRANSACTION;
633 OCStackResult InProcClientWrapper::ObserveResource(ObserveType observeType, OCDoHandle* handle,
634 const OCDevAddr& devAddr,
635 const std::string& uri,
636 const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
637 ObserveCallback& callback, QualityOfService QoS)
641 return OC_STACK_INVALID_PARAM;
643 OCStackResult result;
645 ClientCallbackContext::ObserveContext* ctx =
646 new ClientCallbackContext::ObserveContext(callback);
647 OCCallbackData cbdata(
648 static_cast<void*>(ctx),
649 observeResourceCallback,
650 [](void* c){delete static_cast<ClientCallbackContext::ObserveContext*>(c);}
654 if (observeType == ObserveType::Observe)
656 method = OC_REST_OBSERVE;
658 else if (observeType == ObserveType::ObserveAll)
660 method = OC_REST_OBSERVE_ALL;
664 method = OC_REST_OBSERVE_ALL;
667 std::string url = assembleSetResourceUri(uri, queryParams).c_str();
669 auto cLock = m_csdkLock.lock();
673 std::lock_guard<std::recursive_mutex> lock(*cLock);
674 OCHeaderOption options[MAX_HEADER_OPTIONS];
676 result = OCDoResource(handle, method,
677 url.c_str(), &devAddr,
680 static_cast<OCQualityOfService>(QoS),
682 assembleHeaderOptions(options, headerOptions),
683 headerOptions.size());
688 return OC_STACK_ERROR;
694 OCStackResult InProcClientWrapper::CancelObserveResource(
696 const std::string& host, // unused
697 const std::string& uri, // unused
698 const HeaderOptions& headerOptions,
699 QualityOfService QoS)
701 OCStackResult result;
702 auto cLock = m_csdkLock.lock();
706 std::lock_guard<std::recursive_mutex> lock(*cLock);
707 OCHeaderOption options[MAX_HEADER_OPTIONS];
709 result = OCCancel(handle,
710 static_cast<OCQualityOfService>(QoS),
711 assembleHeaderOptions(options, headerOptions),
712 headerOptions.size());
716 result = OC_STACK_ERROR;
722 OCStackApplicationResult subscribePresenceCallback(void* ctx, OCDoHandle handle,
723 OCClientResponse* clientResponse)
725 ClientCallbackContext::SubscribePresenceContext* context =
726 static_cast<ClientCallbackContext::SubscribePresenceContext*>(ctx);
729 * This a hack while we rethink presence subscription.
731 std::string url = clientResponse->devAddr.addr;
733 std::thread exec(context->callback, clientResponse->result,
734 clientResponse->sequenceNumber, url);
738 return OC_STACK_KEEP_TRANSACTION;
741 OCStackResult InProcClientWrapper::SubscribePresence(OCDoHandle* handle,
742 const std::string& host, const std::string& resourceType,
743 OCConnectivityType connectivityType, SubscribeCallback& presenceHandler)
747 return OC_STACK_INVALID_PARAM;
750 ClientCallbackContext::SubscribePresenceContext* ctx =
751 new ClientCallbackContext::SubscribePresenceContext(presenceHandler);
752 OCCallbackData cbdata(
753 static_cast<void*>(ctx),
754 subscribePresenceCallback,
756 {delete static_cast<ClientCallbackContext::SubscribePresenceContext*>(c);}
759 auto cLock = m_csdkLock.lock();
761 std::ostringstream os;
762 os << host << OC_RSRVD_PRESENCE_URI;
764 if(!resourceType.empty())
766 os << "?rt=" << resourceType;
772 return OC_STACK_ERROR;
775 return OCDoResource(handle, OC_REST_PRESENCE,
776 os.str().c_str(), nullptr,
777 nullptr, connectivityType,
778 OC_LOW_QOS, &cbdata, NULL, 0);
781 OCStackResult InProcClientWrapper::UnsubscribePresence(OCDoHandle handle)
783 OCStackResult result;
784 auto cLock = m_csdkLock.lock();
788 std::lock_guard<std::recursive_mutex> lock(*cLock);
789 result = OCCancel(handle, OC_LOW_QOS, NULL, 0);
793 result = OC_STACK_ERROR;
799 OCStackResult InProcClientWrapper::GetDefaultQos(QualityOfService& qos)
805 OCHeaderOption* InProcClientWrapper::assembleHeaderOptions(OCHeaderOption options[],
806 const HeaderOptions& headerOptions)
810 if( headerOptions.size() == 0)
815 for (auto it=headerOptions.begin(); it != headerOptions.end(); ++it)
817 options[i] = OCHeaderOption(OC_COAP_ID,
819 it->getOptionData().length() + 1,
820 reinterpret_cast<const uint8_t*>(it->getOptionData().c_str()));